000001  /*
000002  ** 2001 September 15
000003  **
000004  ** The author disclaims copyright to this source code.  In place of
000005  ** a legal notice, here is a blessing:
000006  **
000007  **    May you do good and not evil.
000008  **    May you find forgiveness for yourself and forgive others.
000009  **    May you share freely, never taking more than you give.
000010  **
000011  *************************************************************************
000012  ** This file contains C code routines that are called by the SQLite parser
000013  ** when syntax rules are reduced.  The routines in this file handle the
000014  ** following kinds of SQL syntax:
000015  **
000016  **     CREATE TABLE
000017  **     DROP TABLE
000018  **     CREATE INDEX
000019  **     DROP INDEX
000020  **     creating ID lists
000021  **     BEGIN TRANSACTION
000022  **     COMMIT
000023  **     ROLLBACK
000024  */
000025  #include "sqliteInt.h"
000026  
000027  #ifndef SQLITE_OMIT_SHARED_CACHE
000028  /*
000029  ** The TableLock structure is only used by the sqlite3TableLock() and
000030  ** codeTableLocks() functions.
000031  */
000032  struct TableLock {
000033    int iDb;               /* The database containing the table to be locked */
000034    int iTab;              /* The root page of the table to be locked */
000035    u8 isWriteLock;        /* True for write lock.  False for a read lock */
000036    const char *zLockName; /* Name of the table */
000037  };
000038  
000039  /*
000040  ** Record the fact that we want to lock a table at run-time.  
000041  **
000042  ** The table to be locked has root page iTab and is found in database iDb.
000043  ** A read or a write lock can be taken depending on isWritelock.
000044  **
000045  ** This routine just records the fact that the lock is desired.  The
000046  ** code to make the lock occur is generated by a later call to
000047  ** codeTableLocks() which occurs during sqlite3FinishCoding().
000048  */
000049  void sqlite3TableLock(
000050    Parse *pParse,     /* Parsing context */
000051    int iDb,           /* Index of the database containing the table to lock */
000052    int iTab,          /* Root page number of the table to be locked */
000053    u8 isWriteLock,    /* True for a write lock */
000054    const char *zName  /* Name of the table to be locked */
000055  ){
000056    Parse *pToplevel = sqlite3ParseToplevel(pParse);
000057    int i;
000058    int nBytes;
000059    TableLock *p;
000060    assert( iDb>=0 );
000061  
000062    if( iDb==1 ) return;
000063    if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
000064    for(i=0; i<pToplevel->nTableLock; i++){
000065      p = &pToplevel->aTableLock[i];
000066      if( p->iDb==iDb && p->iTab==iTab ){
000067        p->isWriteLock = (p->isWriteLock || isWriteLock);
000068        return;
000069      }
000070    }
000071  
000072    nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
000073    pToplevel->aTableLock =
000074        sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
000075    if( pToplevel->aTableLock ){
000076      p = &pToplevel->aTableLock[pToplevel->nTableLock++];
000077      p->iDb = iDb;
000078      p->iTab = iTab;
000079      p->isWriteLock = isWriteLock;
000080      p->zLockName = zName;
000081    }else{
000082      pToplevel->nTableLock = 0;
000083      sqlite3OomFault(pToplevel->db);
000084    }
000085  }
000086  
000087  /*
000088  ** Code an OP_TableLock instruction for each table locked by the
000089  ** statement (configured by calls to sqlite3TableLock()).
000090  */
000091  static void codeTableLocks(Parse *pParse){
000092    int i;
000093    Vdbe *pVdbe; 
000094  
000095    pVdbe = sqlite3GetVdbe(pParse);
000096    assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
000097  
000098    for(i=0; i<pParse->nTableLock; i++){
000099      TableLock *p = &pParse->aTableLock[i];
000100      int p1 = p->iDb;
000101      sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
000102                        p->zLockName, P4_STATIC);
000103    }
000104  }
000105  #else
000106    #define codeTableLocks(x)
000107  #endif
000108  
000109  /*
000110  ** Return TRUE if the given yDbMask object is empty - if it contains no
000111  ** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
000112  ** macros when SQLITE_MAX_ATTACHED is greater than 30.
000113  */
000114  #if SQLITE_MAX_ATTACHED>30
000115  int sqlite3DbMaskAllZero(yDbMask m){
000116    int i;
000117    for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
000118    return 1;
000119  }
000120  #endif
000121  
000122  /*
000123  ** This routine is called after a single SQL statement has been
000124  ** parsed and a VDBE program to execute that statement has been
000125  ** prepared.  This routine puts the finishing touches on the
000126  ** VDBE program and resets the pParse structure for the next
000127  ** parse.
000128  **
000129  ** Note that if an error occurred, it might be the case that
000130  ** no VDBE code was generated.
000131  */
000132  void sqlite3FinishCoding(Parse *pParse){
000133    sqlite3 *db;
000134    Vdbe *v;
000135  
000136    assert( pParse->pToplevel==0 );
000137    db = pParse->db;
000138    if( pParse->nested ) return;
000139    if( db->mallocFailed || pParse->nErr ){
000140      if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
000141      return;
000142    }
000143  
000144    /* Begin by generating some termination code at the end of the
000145    ** vdbe program
000146    */
000147    v = sqlite3GetVdbe(pParse);
000148    assert( !pParse->isMultiWrite 
000149         || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
000150    if( v ){
000151      sqlite3VdbeAddOp0(v, OP_Halt);
000152  
000153  #if SQLITE_USER_AUTHENTICATION
000154      if( pParse->nTableLock>0 && db->init.busy==0 ){
000155        sqlite3UserAuthInit(db);
000156        if( db->auth.authLevel<UAUTH_User ){
000157          sqlite3ErrorMsg(pParse, "user not authenticated");
000158          pParse->rc = SQLITE_AUTH_USER;
000159          return;
000160        }
000161      }
000162  #endif
000163  
000164      /* The cookie mask contains one bit for each database file open.
000165      ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
000166      ** set for each database that is used.  Generate code to start a
000167      ** transaction on each used database and to verify the schema cookie
000168      ** on each used database.
000169      */
000170      if( db->mallocFailed==0 
000171       && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
000172      ){
000173        int iDb, i;
000174        assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
000175        sqlite3VdbeJumpHere(v, 0);
000176        for(iDb=0; iDb<db->nDb; iDb++){
000177          Schema *pSchema;
000178          if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
000179          sqlite3VdbeUsesBtree(v, iDb);
000180          pSchema = db->aDb[iDb].pSchema;
000181          sqlite3VdbeAddOp4Int(v,
000182            OP_Transaction,                    /* Opcode */
000183            iDb,                               /* P1 */
000184            DbMaskTest(pParse->writeMask,iDb), /* P2 */
000185            pSchema->schema_cookie,            /* P3 */
000186            pSchema->iGeneration               /* P4 */
000187          );
000188          if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
000189          VdbeComment((v,
000190                "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
000191        }
000192  #ifndef SQLITE_OMIT_VIRTUALTABLE
000193        for(i=0; i<pParse->nVtabLock; i++){
000194          char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
000195          sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
000196        }
000197        pParse->nVtabLock = 0;
000198  #endif
000199  
000200        /* Once all the cookies have been verified and transactions opened, 
000201        ** obtain the required table-locks. This is a no-op unless the 
000202        ** shared-cache feature is enabled.
000203        */
000204        codeTableLocks(pParse);
000205  
000206        /* Initialize any AUTOINCREMENT data structures required.
000207        */
000208        sqlite3AutoincrementBegin(pParse);
000209  
000210        /* Code constant expressions that where factored out of inner loops */
000211        if( pParse->pConstExpr ){
000212          ExprList *pEL = pParse->pConstExpr;
000213          pParse->okConstFactor = 0;
000214          for(i=0; i<pEL->nExpr; i++){
000215            sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
000216          }
000217        }
000218  
000219        /* Finally, jump back to the beginning of the executable code. */
000220        sqlite3VdbeGoto(v, 1);
000221      }
000222    }
000223  
000224  
000225    /* Get the VDBE program ready for execution
000226    */
000227    if( v && pParse->nErr==0 && !db->mallocFailed ){
000228      assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
000229      /* A minimum of one cursor is required if autoincrement is used
000230      *  See ticket [a696379c1f08866] */
000231      if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
000232      sqlite3VdbeMakeReady(v, pParse);
000233      pParse->rc = SQLITE_DONE;
000234    }else{
000235      pParse->rc = SQLITE_ERROR;
000236    }
000237  }
000238  
000239  /*
000240  ** Run the parser and code generator recursively in order to generate
000241  ** code for the SQL statement given onto the end of the pParse context
000242  ** currently under construction.  When the parser is run recursively
000243  ** this way, the final OP_Halt is not appended and other initialization
000244  ** and finalization steps are omitted because those are handling by the
000245  ** outermost parser.
000246  **
000247  ** Not everything is nestable.  This facility is designed to permit
000248  ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
000249  ** care if you decide to try to use this routine for some other purposes.
000250  */
000251  void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
000252    va_list ap;
000253    char *zSql;
000254    char *zErrMsg = 0;
000255    sqlite3 *db = pParse->db;
000256    char saveBuf[PARSE_TAIL_SZ];
000257  
000258    if( pParse->nErr ) return;
000259    assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
000260    va_start(ap, zFormat);
000261    zSql = sqlite3VMPrintf(db, zFormat, ap);
000262    va_end(ap);
000263    if( zSql==0 ){
000264      return;   /* A malloc must have failed */
000265    }
000266    pParse->nested++;
000267    memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
000268    memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
000269    sqlite3RunParser(pParse, zSql, &zErrMsg);
000270    sqlite3DbFree(db, zErrMsg);
000271    sqlite3DbFree(db, zSql);
000272    memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
000273    pParse->nested--;
000274  }
000275  
000276  #if SQLITE_USER_AUTHENTICATION
000277  /*
000278  ** Return TRUE if zTable is the name of the system table that stores the
000279  ** list of users and their access credentials.
000280  */
000281  int sqlite3UserAuthTable(const char *zTable){
000282    return sqlite3_stricmp(zTable, "sqlite_user")==0;
000283  }
000284  #endif
000285  
000286  /*
000287  ** Locate the in-memory structure that describes a particular database
000288  ** table given the name of that table and (optionally) the name of the
000289  ** database containing the table.  Return NULL if not found.
000290  **
000291  ** If zDatabase is 0, all databases are searched for the table and the
000292  ** first matching table is returned.  (No checking for duplicate table
000293  ** names is done.)  The search order is TEMP first, then MAIN, then any
000294  ** auxiliary databases added using the ATTACH command.
000295  **
000296  ** See also sqlite3LocateTable().
000297  */
000298  Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
000299    Table *p = 0;
000300    int i;
000301  
000302    /* All mutexes are required for schema access.  Make sure we hold them. */
000303    assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
000304  #if SQLITE_USER_AUTHENTICATION
000305    /* Only the admin user is allowed to know that the sqlite_user table
000306    ** exists */
000307    if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
000308      return 0;
000309    }
000310  #endif
000311    while(1){
000312      for(i=OMIT_TEMPDB; i<db->nDb; i++){
000313        int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
000314        if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
000315          assert( sqlite3SchemaMutexHeld(db, j, 0) );
000316          p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
000317          if( p ) return p;
000318        }
000319      }
000320      /* Not found.  If the name we were looking for was temp.sqlite_master
000321      ** then change the name to sqlite_temp_master and try again. */
000322      if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
000323      if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
000324      zName = TEMP_MASTER_NAME;
000325    }
000326    return 0;
000327  }
000328  
000329  /*
000330  ** Locate the in-memory structure that describes a particular database
000331  ** table given the name of that table and (optionally) the name of the
000332  ** database containing the table.  Return NULL if not found.  Also leave an
000333  ** error message in pParse->zErrMsg.
000334  **
000335  ** The difference between this routine and sqlite3FindTable() is that this
000336  ** routine leaves an error message in pParse->zErrMsg where
000337  ** sqlite3FindTable() does not.
000338  */
000339  Table *sqlite3LocateTable(
000340    Parse *pParse,         /* context in which to report errors */
000341    u32 flags,             /* LOCATE_VIEW or LOCATE_NOERR */
000342    const char *zName,     /* Name of the table we are looking for */
000343    const char *zDbase     /* Name of the database.  Might be NULL */
000344  ){
000345    Table *p;
000346    sqlite3 *db = pParse->db;
000347  
000348    /* Read the database schema. If an error occurs, leave an error message
000349    ** and code in pParse and return NULL. */
000350    if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 
000351     && SQLITE_OK!=sqlite3ReadSchema(pParse)
000352    ){
000353      return 0;
000354    }
000355  
000356    p = sqlite3FindTable(db, zName, zDbase);
000357    if( p==0 ){
000358      const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
000359  #ifndef SQLITE_OMIT_VIRTUALTABLE
000360      if( sqlite3FindDbName(db, zDbase)<1 ){
000361        /* If zName is the not the name of a table in the schema created using
000362        ** CREATE, then check to see if it is the name of an virtual table that
000363        ** can be an eponymous virtual table. */
000364        Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
000365        if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
000366          pMod = sqlite3PragmaVtabRegister(db, zName);
000367        }
000368        if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
000369          return pMod->pEpoTab;
000370        }
000371      }
000372  #endif
000373      if( (flags & LOCATE_NOERR)==0 ){
000374        if( zDbase ){
000375          sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
000376        }else{
000377          sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
000378        }
000379        pParse->checkSchema = 1;
000380      }
000381    }
000382  
000383    return p;
000384  }
000385  
000386  /*
000387  ** Locate the table identified by *p.
000388  **
000389  ** This is a wrapper around sqlite3LocateTable(). The difference between
000390  ** sqlite3LocateTable() and this function is that this function restricts
000391  ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
000392  ** non-NULL if it is part of a view or trigger program definition. See
000393  ** sqlite3FixSrcList() for details.
000394  */
000395  Table *sqlite3LocateTableItem(
000396    Parse *pParse, 
000397    u32 flags,
000398    struct SrcList_item *p
000399  ){
000400    const char *zDb;
000401    assert( p->pSchema==0 || p->zDatabase==0 );
000402    if( p->pSchema ){
000403      int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
000404      zDb = pParse->db->aDb[iDb].zDbSName;
000405    }else{
000406      zDb = p->zDatabase;
000407    }
000408    return sqlite3LocateTable(pParse, flags, p->zName, zDb);
000409  }
000410  
000411  /*
000412  ** Locate the in-memory structure that describes 
000413  ** a particular index given the name of that index
000414  ** and the name of the database that contains the index.
000415  ** Return NULL if not found.
000416  **
000417  ** If zDatabase is 0, all databases are searched for the
000418  ** table and the first matching index is returned.  (No checking
000419  ** for duplicate index names is done.)  The search order is
000420  ** TEMP first, then MAIN, then any auxiliary databases added
000421  ** using the ATTACH command.
000422  */
000423  Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
000424    Index *p = 0;
000425    int i;
000426    /* All mutexes are required for schema access.  Make sure we hold them. */
000427    assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
000428    for(i=OMIT_TEMPDB; i<db->nDb; i++){
000429      int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
000430      Schema *pSchema = db->aDb[j].pSchema;
000431      assert( pSchema );
000432      if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
000433      assert( sqlite3SchemaMutexHeld(db, j, 0) );
000434      p = sqlite3HashFind(&pSchema->idxHash, zName);
000435      if( p ) break;
000436    }
000437    return p;
000438  }
000439  
000440  /*
000441  ** Reclaim the memory used by an index
000442  */
000443  static void freeIndex(sqlite3 *db, Index *p){
000444  #ifndef SQLITE_OMIT_ANALYZE
000445    sqlite3DeleteIndexSamples(db, p);
000446  #endif
000447    sqlite3ExprDelete(db, p->pPartIdxWhere);
000448    sqlite3ExprListDelete(db, p->aColExpr);
000449    sqlite3DbFree(db, p->zColAff);
000450    if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
000451  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
000452    sqlite3_free(p->aiRowEst);
000453  #endif
000454    sqlite3DbFree(db, p);
000455  }
000456  
000457  /*
000458  ** For the index called zIdxName which is found in the database iDb,
000459  ** unlike that index from its Table then remove the index from
000460  ** the index hash table and free all memory structures associated
000461  ** with the index.
000462  */
000463  void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
000464    Index *pIndex;
000465    Hash *pHash;
000466  
000467    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000468    pHash = &db->aDb[iDb].pSchema->idxHash;
000469    pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
000470    if( ALWAYS(pIndex) ){
000471      if( pIndex->pTable->pIndex==pIndex ){
000472        pIndex->pTable->pIndex = pIndex->pNext;
000473      }else{
000474        Index *p;
000475        /* Justification of ALWAYS();  The index must be on the list of
000476        ** indices. */
000477        p = pIndex->pTable->pIndex;
000478        while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
000479        if( ALWAYS(p && p->pNext==pIndex) ){
000480          p->pNext = pIndex->pNext;
000481        }
000482      }
000483      freeIndex(db, pIndex);
000484    }
000485    db->mDbFlags |= DBFLAG_SchemaChange;
000486  }
000487  
000488  /*
000489  ** Look through the list of open database files in db->aDb[] and if
000490  ** any have been closed, remove them from the list.  Reallocate the
000491  ** db->aDb[] structure to a smaller size, if possible.
000492  **
000493  ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
000494  ** are never candidates for being collapsed.
000495  */
000496  void sqlite3CollapseDatabaseArray(sqlite3 *db){
000497    int i, j;
000498    for(i=j=2; i<db->nDb; i++){
000499      struct Db *pDb = &db->aDb[i];
000500      if( pDb->pBt==0 ){
000501        sqlite3DbFree(db, pDb->zDbSName);
000502        pDb->zDbSName = 0;
000503        continue;
000504      }
000505      if( j<i ){
000506        db->aDb[j] = db->aDb[i];
000507      }
000508      j++;
000509    }
000510    db->nDb = j;
000511    if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
000512      memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
000513      sqlite3DbFree(db, db->aDb);
000514      db->aDb = db->aDbStatic;
000515    }
000516  }
000517  
000518  /*
000519  ** Reset the schema for the database at index iDb.  Also reset the
000520  ** TEMP schema.  The reset is deferred if db->nSchemaLock is not zero.
000521  ** Deferred resets may be run by calling with iDb<0.
000522  */
000523  void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
000524    int i;
000525    assert( iDb<db->nDb );
000526  
000527    if( iDb>=0 ){
000528      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000529      DbSetProperty(db, iDb, DB_ResetWanted);
000530      DbSetProperty(db, 1, DB_ResetWanted);
000531      db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
000532    }
000533  
000534    if( db->nSchemaLock==0 ){
000535      for(i=0; i<db->nDb; i++){
000536        if( DbHasProperty(db, i, DB_ResetWanted) ){
000537          sqlite3SchemaClear(db->aDb[i].pSchema);
000538        }
000539      }
000540    }
000541  }
000542  
000543  /*
000544  ** Erase all schema information from all attached databases (including
000545  ** "main" and "temp") for a single database connection.
000546  */
000547  void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
000548    int i;
000549    sqlite3BtreeEnterAll(db);
000550    assert( db->nSchemaLock==0 );
000551    for(i=0; i<db->nDb; i++){
000552      Db *pDb = &db->aDb[i];
000553      if( pDb->pSchema ){
000554        sqlite3SchemaClear(pDb->pSchema);
000555      }
000556    }
000557    db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
000558    sqlite3VtabUnlockList(db);
000559    sqlite3BtreeLeaveAll(db);
000560    sqlite3CollapseDatabaseArray(db);
000561  }
000562  
000563  /*
000564  ** This routine is called when a commit occurs.
000565  */
000566  void sqlite3CommitInternalChanges(sqlite3 *db){
000567    db->mDbFlags &= ~DBFLAG_SchemaChange;
000568  }
000569  
000570  /*
000571  ** Delete memory allocated for the column names of a table or view (the
000572  ** Table.aCol[] array).
000573  */
000574  void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
000575    int i;
000576    Column *pCol;
000577    assert( pTable!=0 );
000578    if( (pCol = pTable->aCol)!=0 ){
000579      for(i=0; i<pTable->nCol; i++, pCol++){
000580        sqlite3DbFree(db, pCol->zName);
000581        sqlite3ExprDelete(db, pCol->pDflt);
000582        sqlite3DbFree(db, pCol->zColl);
000583      }
000584      sqlite3DbFree(db, pTable->aCol);
000585    }
000586  }
000587  
000588  /*
000589  ** Remove the memory data structures associated with the given
000590  ** Table.  No changes are made to disk by this routine.
000591  **
000592  ** This routine just deletes the data structure.  It does not unlink
000593  ** the table data structure from the hash table.  But it does destroy
000594  ** memory structures of the indices and foreign keys associated with 
000595  ** the table.
000596  **
000597  ** The db parameter is optional.  It is needed if the Table object 
000598  ** contains lookaside memory.  (Table objects in the schema do not use
000599  ** lookaside memory, but some ephemeral Table objects do.)  Or the
000600  ** db parameter can be used with db->pnBytesFreed to measure the memory
000601  ** used by the Table object.
000602  */
000603  static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
000604    Index *pIndex, *pNext;
000605  
000606  #ifdef SQLITE_DEBUG
000607    /* Record the number of outstanding lookaside allocations in schema Tables
000608    ** prior to doing any free() operations.  Since schema Tables do not use
000609    ** lookaside, this number should not change. */
000610    int nLookaside = 0;
000611    if( db && (pTable->tabFlags & TF_Ephemeral)==0 ){
000612      nLookaside = sqlite3LookasideUsed(db, 0);
000613    }
000614  #endif
000615  
000616    /* Delete all indices associated with this table. */
000617    for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
000618      pNext = pIndex->pNext;
000619      assert( pIndex->pSchema==pTable->pSchema
000620           || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
000621      if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
000622        char *zName = pIndex->zName; 
000623        TESTONLY ( Index *pOld = ) sqlite3HashInsert(
000624           &pIndex->pSchema->idxHash, zName, 0
000625        );
000626        assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
000627        assert( pOld==pIndex || pOld==0 );
000628      }
000629      freeIndex(db, pIndex);
000630    }
000631  
000632    /* Delete any foreign keys attached to this table. */
000633    sqlite3FkDelete(db, pTable);
000634  
000635    /* Delete the Table structure itself.
000636    */
000637    sqlite3DeleteColumnNames(db, pTable);
000638    sqlite3DbFree(db, pTable->zName);
000639    sqlite3DbFree(db, pTable->zColAff);
000640    sqlite3SelectDelete(db, pTable->pSelect);
000641    sqlite3ExprListDelete(db, pTable->pCheck);
000642  #ifndef SQLITE_OMIT_VIRTUALTABLE
000643    sqlite3VtabClear(db, pTable);
000644  #endif
000645    sqlite3DbFree(db, pTable);
000646  
000647    /* Verify that no lookaside memory was used by schema tables */
000648    assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
000649  }
000650  void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
000651    /* Do not delete the table until the reference count reaches zero. */
000652    if( !pTable ) return;
000653    if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
000654    deleteTable(db, pTable);
000655  }
000656  
000657  
000658  /*
000659  ** Unlink the given table from the hash tables and the delete the
000660  ** table structure with all its indices and foreign keys.
000661  */
000662  void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
000663    Table *p;
000664    Db *pDb;
000665  
000666    assert( db!=0 );
000667    assert( iDb>=0 && iDb<db->nDb );
000668    assert( zTabName );
000669    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000670    testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
000671    pDb = &db->aDb[iDb];
000672    p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
000673    sqlite3DeleteTable(db, p);
000674    db->mDbFlags |= DBFLAG_SchemaChange;
000675  }
000676  
000677  /*
000678  ** Given a token, return a string that consists of the text of that
000679  ** token.  Space to hold the returned string
000680  ** is obtained from sqliteMalloc() and must be freed by the calling
000681  ** function.
000682  **
000683  ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
000684  ** surround the body of the token are removed.
000685  **
000686  ** Tokens are often just pointers into the original SQL text and so
000687  ** are not \000 terminated and are not persistent.  The returned string
000688  ** is \000 terminated and is persistent.
000689  */
000690  char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
000691    char *zName;
000692    if( pName ){
000693      zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
000694      sqlite3Dequote(zName);
000695    }else{
000696      zName = 0;
000697    }
000698    return zName;
000699  }
000700  
000701  /*
000702  ** Open the sqlite_master table stored in database number iDb for
000703  ** writing. The table is opened using cursor 0.
000704  */
000705  void sqlite3OpenMasterTable(Parse *p, int iDb){
000706    Vdbe *v = sqlite3GetVdbe(p);
000707    sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
000708    sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
000709    if( p->nTab==0 ){
000710      p->nTab = 1;
000711    }
000712  }
000713  
000714  /*
000715  ** Parameter zName points to a nul-terminated buffer containing the name
000716  ** of a database ("main", "temp" or the name of an attached db). This
000717  ** function returns the index of the named database in db->aDb[], or
000718  ** -1 if the named db cannot be found.
000719  */
000720  int sqlite3FindDbName(sqlite3 *db, const char *zName){
000721    int i = -1;         /* Database number */
000722    if( zName ){
000723      Db *pDb;
000724      for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
000725        if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
000726        /* "main" is always an acceptable alias for the primary database
000727        ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
000728        if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
000729      }
000730    }
000731    return i;
000732  }
000733  
000734  /*
000735  ** The token *pName contains the name of a database (either "main" or
000736  ** "temp" or the name of an attached db). This routine returns the
000737  ** index of the named database in db->aDb[], or -1 if the named db 
000738  ** does not exist.
000739  */
000740  int sqlite3FindDb(sqlite3 *db, Token *pName){
000741    int i;                               /* Database number */
000742    char *zName;                         /* Name we are searching for */
000743    zName = sqlite3NameFromToken(db, pName);
000744    i = sqlite3FindDbName(db, zName);
000745    sqlite3DbFree(db, zName);
000746    return i;
000747  }
000748  
000749  /* The table or view or trigger name is passed to this routine via tokens
000750  ** pName1 and pName2. If the table name was fully qualified, for example:
000751  **
000752  ** CREATE TABLE xxx.yyy (...);
000753  ** 
000754  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
000755  ** the table name is not fully qualified, i.e.:
000756  **
000757  ** CREATE TABLE yyy(...);
000758  **
000759  ** Then pName1 is set to "yyy" and pName2 is "".
000760  **
000761  ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
000762  ** pName2) that stores the unqualified table name.  The index of the
000763  ** database "xxx" is returned.
000764  */
000765  int sqlite3TwoPartName(
000766    Parse *pParse,      /* Parsing and code generating context */
000767    Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
000768    Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
000769    Token **pUnqual     /* Write the unqualified object name here */
000770  ){
000771    int iDb;                    /* Database holding the object */
000772    sqlite3 *db = pParse->db;
000773  
000774    assert( pName2!=0 );
000775    if( pName2->n>0 ){
000776      if( db->init.busy ) {
000777        sqlite3ErrorMsg(pParse, "corrupt database");
000778        return -1;
000779      }
000780      *pUnqual = pName2;
000781      iDb = sqlite3FindDb(db, pName1);
000782      if( iDb<0 ){
000783        sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
000784        return -1;
000785      }
000786    }else{
000787      assert( db->init.iDb==0 || db->init.busy
000788               || (db->mDbFlags & DBFLAG_Vacuum)!=0);
000789      iDb = db->init.iDb;
000790      *pUnqual = pName1;
000791    }
000792    return iDb;
000793  }
000794  
000795  /*
000796  ** This routine is used to check if the UTF-8 string zName is a legal
000797  ** unqualified name for a new schema object (table, index, view or
000798  ** trigger). All names are legal except those that begin with the string
000799  ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
000800  ** is reserved for internal use.
000801  */
000802  int sqlite3CheckObjectName(Parse *pParse, const char *zName){
000803    if( !pParse->db->init.busy && pParse->nested==0 
000804            && (pParse->db->flags & SQLITE_WriteSchema)==0
000805            && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
000806      sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
000807      return SQLITE_ERROR;
000808    }
000809    return SQLITE_OK;
000810  }
000811  
000812  /*
000813  ** Return the PRIMARY KEY index of a table
000814  */
000815  Index *sqlite3PrimaryKeyIndex(Table *pTab){
000816    Index *p;
000817    for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
000818    return p;
000819  }
000820  
000821  /*
000822  ** Return the column of index pIdx that corresponds to table
000823  ** column iCol.  Return -1 if not found.
000824  */
000825  i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
000826    int i;
000827    for(i=0; i<pIdx->nColumn; i++){
000828      if( iCol==pIdx->aiColumn[i] ) return i;
000829    }
000830    return -1;
000831  }
000832  
000833  /*
000834  ** Begin constructing a new table representation in memory.  This is
000835  ** the first of several action routines that get called in response
000836  ** to a CREATE TABLE statement.  In particular, this routine is called
000837  ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
000838  ** flag is true if the table should be stored in the auxiliary database
000839  ** file instead of in the main database file.  This is normally the case
000840  ** when the "TEMP" or "TEMPORARY" keyword occurs in between
000841  ** CREATE and TABLE.
000842  **
000843  ** The new table record is initialized and put in pParse->pNewTable.
000844  ** As more of the CREATE TABLE statement is parsed, additional action
000845  ** routines will be called to add more information to this record.
000846  ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
000847  ** is called to complete the construction of the new table record.
000848  */
000849  void sqlite3StartTable(
000850    Parse *pParse,   /* Parser context */
000851    Token *pName1,   /* First part of the name of the table or view */
000852    Token *pName2,   /* Second part of the name of the table or view */
000853    int isTemp,      /* True if this is a TEMP table */
000854    int isView,      /* True if this is a VIEW */
000855    int isVirtual,   /* True if this is a VIRTUAL table */
000856    int noErr        /* Do nothing if table already exists */
000857  ){
000858    Table *pTable;
000859    char *zName = 0; /* The name of the new table */
000860    sqlite3 *db = pParse->db;
000861    Vdbe *v;
000862    int iDb;         /* Database number to create the table in */
000863    Token *pName;    /* Unqualified name of the table to create */
000864  
000865    if( db->init.busy && db->init.newTnum==1 ){
000866      /* Special case:  Parsing the sqlite_master or sqlite_temp_master schema */
000867      iDb = db->init.iDb;
000868      zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
000869      pName = pName1;
000870    }else{
000871      /* The common case */
000872      iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
000873      if( iDb<0 ) return;
000874      if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
000875        /* If creating a temp table, the name may not be qualified. Unless 
000876        ** the database name is "temp" anyway.  */
000877        sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
000878        return;
000879      }
000880      if( !OMIT_TEMPDB && isTemp ) iDb = 1;
000881      zName = sqlite3NameFromToken(db, pName);
000882    }
000883    pParse->sNameToken = *pName;
000884    if( zName==0 ) return;
000885    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
000886      goto begin_table_error;
000887    }
000888    if( db->init.iDb==1 ) isTemp = 1;
000889  #ifndef SQLITE_OMIT_AUTHORIZATION
000890    assert( isTemp==0 || isTemp==1 );
000891    assert( isView==0 || isView==1 );
000892    {
000893      static const u8 aCode[] = {
000894         SQLITE_CREATE_TABLE,
000895         SQLITE_CREATE_TEMP_TABLE,
000896         SQLITE_CREATE_VIEW,
000897         SQLITE_CREATE_TEMP_VIEW
000898      };
000899      char *zDb = db->aDb[iDb].zDbSName;
000900      if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
000901        goto begin_table_error;
000902      }
000903      if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
000904                                         zName, 0, zDb) ){
000905        goto begin_table_error;
000906      }
000907    }
000908  #endif
000909  
000910    /* Make sure the new table name does not collide with an existing
000911    ** index or table name in the same database.  Issue an error message if
000912    ** it does. The exception is if the statement being parsed was passed
000913    ** to an sqlite3_declare_vtab() call. In that case only the column names
000914    ** and types will be used, so there is no need to test for namespace
000915    ** collisions.
000916    */
000917    if( !IN_DECLARE_VTAB ){
000918      char *zDb = db->aDb[iDb].zDbSName;
000919      if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
000920        goto begin_table_error;
000921      }
000922      pTable = sqlite3FindTable(db, zName, zDb);
000923      if( pTable ){
000924        if( !noErr ){
000925          sqlite3ErrorMsg(pParse, "table %T already exists", pName);
000926        }else{
000927          assert( !db->init.busy || CORRUPT_DB );
000928          sqlite3CodeVerifySchema(pParse, iDb);
000929        }
000930        goto begin_table_error;
000931      }
000932      if( sqlite3FindIndex(db, zName, zDb)!=0 ){
000933        sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
000934        goto begin_table_error;
000935      }
000936    }
000937  
000938    pTable = sqlite3DbMallocZero(db, sizeof(Table));
000939    if( pTable==0 ){
000940      assert( db->mallocFailed );
000941      pParse->rc = SQLITE_NOMEM_BKPT;
000942      pParse->nErr++;
000943      goto begin_table_error;
000944    }
000945    pTable->zName = zName;
000946    pTable->iPKey = -1;
000947    pTable->pSchema = db->aDb[iDb].pSchema;
000948    pTable->nTabRef = 1;
000949  #ifdef SQLITE_DEFAULT_ROWEST
000950    pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
000951  #else
000952    pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
000953  #endif
000954    assert( pParse->pNewTable==0 );
000955    pParse->pNewTable = pTable;
000956  
000957    /* If this is the magic sqlite_sequence table used by autoincrement,
000958    ** then record a pointer to this table in the main database structure
000959    ** so that INSERT can find the table easily.
000960    */
000961  #ifndef SQLITE_OMIT_AUTOINCREMENT
000962    if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
000963      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000964      pTable->pSchema->pSeqTab = pTable;
000965    }
000966  #endif
000967  
000968    /* Begin generating the code that will insert the table record into
000969    ** the SQLITE_MASTER table.  Note in particular that we must go ahead
000970    ** and allocate the record number for the table entry now.  Before any
000971    ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
000972    ** indices to be created and the table record must come before the 
000973    ** indices.  Hence, the record number for the table must be allocated
000974    ** now.
000975    */
000976    if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
000977      int addr1;
000978      int fileFormat;
000979      int reg1, reg2, reg3;
000980      /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
000981      static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
000982      sqlite3BeginWriteOperation(pParse, 1, iDb);
000983  
000984  #ifndef SQLITE_OMIT_VIRTUALTABLE
000985      if( isVirtual ){
000986        sqlite3VdbeAddOp0(v, OP_VBegin);
000987      }
000988  #endif
000989  
000990      /* If the file format and encoding in the database have not been set, 
000991      ** set them now.
000992      */
000993      reg1 = pParse->regRowid = ++pParse->nMem;
000994      reg2 = pParse->regRoot = ++pParse->nMem;
000995      reg3 = ++pParse->nMem;
000996      sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
000997      sqlite3VdbeUsesBtree(v, iDb);
000998      addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
000999      fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
001000                    1 : SQLITE_MAX_FILE_FORMAT;
001001      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
001002      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
001003      sqlite3VdbeJumpHere(v, addr1);
001004  
001005      /* This just creates a place-holder record in the sqlite_master table.
001006      ** The record created does not contain anything yet.  It will be replaced
001007      ** by the real entry in code generated at sqlite3EndTable().
001008      **
001009      ** The rowid for the new entry is left in register pParse->regRowid.
001010      ** The root page number of the new table is left in reg pParse->regRoot.
001011      ** The rowid and root page number values are needed by the code that
001012      ** sqlite3EndTable will generate.
001013      */
001014  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
001015      if( isView || isVirtual ){
001016        sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
001017      }else
001018  #endif
001019      {
001020        pParse->addrCrTab =
001021           sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
001022      }
001023      sqlite3OpenMasterTable(pParse, iDb);
001024      sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
001025      sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
001026      sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
001027      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
001028      sqlite3VdbeAddOp0(v, OP_Close);
001029    }
001030  
001031    /* Normal (non-error) return. */
001032    return;
001033  
001034    /* If an error occurs, we jump here */
001035  begin_table_error:
001036    sqlite3DbFree(db, zName);
001037    return;
001038  }
001039  
001040  /* Set properties of a table column based on the (magical)
001041  ** name of the column.
001042  */
001043  #if SQLITE_ENABLE_HIDDEN_COLUMNS
001044  void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
001045    if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
001046      pCol->colFlags |= COLFLAG_HIDDEN;
001047    }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
001048      pTab->tabFlags |= TF_OOOHidden;
001049    }
001050  }
001051  #endif
001052  
001053  
001054  /*
001055  ** Add a new column to the table currently being constructed.
001056  **
001057  ** The parser calls this routine once for each column declaration
001058  ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
001059  ** first to get things going.  Then this routine is called for each
001060  ** column.
001061  */
001062  void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
001063    Table *p;
001064    int i;
001065    char *z;
001066    char *zType;
001067    Column *pCol;
001068    sqlite3 *db = pParse->db;
001069    if( (p = pParse->pNewTable)==0 ) return;
001070    if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
001071      sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
001072      return;
001073    }
001074    z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
001075    if( z==0 ) return;
001076    memcpy(z, pName->z, pName->n);
001077    z[pName->n] = 0;
001078    sqlite3Dequote(z);
001079    for(i=0; i<p->nCol; i++){
001080      if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
001081        sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
001082        sqlite3DbFree(db, z);
001083        return;
001084      }
001085    }
001086    if( (p->nCol & 0x7)==0 ){
001087      Column *aNew;
001088      aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
001089      if( aNew==0 ){
001090        sqlite3DbFree(db, z);
001091        return;
001092      }
001093      p->aCol = aNew;
001094    }
001095    pCol = &p->aCol[p->nCol];
001096    memset(pCol, 0, sizeof(p->aCol[0]));
001097    pCol->zName = z;
001098    sqlite3ColumnPropertiesFromName(p, pCol);
001099   
001100    if( pType->n==0 ){
001101      /* If there is no type specified, columns have the default affinity
001102      ** 'BLOB' with a default size of 4 bytes. */
001103      pCol->affinity = SQLITE_AFF_BLOB;
001104      pCol->szEst = 1;
001105  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
001106      if( 4>=sqlite3GlobalConfig.szSorterRef ){
001107        pCol->colFlags |= COLFLAG_SORTERREF;
001108      }
001109  #endif
001110    }else{
001111      zType = z + sqlite3Strlen30(z) + 1;
001112      memcpy(zType, pType->z, pType->n);
001113      zType[pType->n] = 0;
001114      sqlite3Dequote(zType);
001115      pCol->affinity = sqlite3AffinityType(zType, pCol);
001116      pCol->colFlags |= COLFLAG_HASTYPE;
001117    }
001118    p->nCol++;
001119    pParse->constraintName.n = 0;
001120  }
001121  
001122  /*
001123  ** This routine is called by the parser while in the middle of
001124  ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
001125  ** been seen on a column.  This routine sets the notNull flag on
001126  ** the column currently under construction.
001127  */
001128  void sqlite3AddNotNull(Parse *pParse, int onError){
001129    Table *p;
001130    Column *pCol;
001131    p = pParse->pNewTable;
001132    if( p==0 || NEVER(p->nCol<1) ) return;
001133    pCol = &p->aCol[p->nCol-1];
001134    pCol->notNull = (u8)onError;
001135    p->tabFlags |= TF_HasNotNull;
001136  
001137    /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
001138    ** on this column.  */
001139    if( pCol->colFlags & COLFLAG_UNIQUE ){
001140      Index *pIdx;
001141      for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
001142        assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
001143        if( pIdx->aiColumn[0]==p->nCol-1 ){
001144          pIdx->uniqNotNull = 1;
001145        }
001146      }
001147    }
001148  }
001149  
001150  /*
001151  ** Scan the column type name zType (length nType) and return the
001152  ** associated affinity type.
001153  **
001154  ** This routine does a case-independent search of zType for the 
001155  ** substrings in the following table. If one of the substrings is
001156  ** found, the corresponding affinity is returned. If zType contains
001157  ** more than one of the substrings, entries toward the top of 
001158  ** the table take priority. For example, if zType is 'BLOBINT', 
001159  ** SQLITE_AFF_INTEGER is returned.
001160  **
001161  ** Substring     | Affinity
001162  ** --------------------------------
001163  ** 'INT'         | SQLITE_AFF_INTEGER
001164  ** 'CHAR'        | SQLITE_AFF_TEXT
001165  ** 'CLOB'        | SQLITE_AFF_TEXT
001166  ** 'TEXT'        | SQLITE_AFF_TEXT
001167  ** 'BLOB'        | SQLITE_AFF_BLOB
001168  ** 'REAL'        | SQLITE_AFF_REAL
001169  ** 'FLOA'        | SQLITE_AFF_REAL
001170  ** 'DOUB'        | SQLITE_AFF_REAL
001171  **
001172  ** If none of the substrings in the above table are found,
001173  ** SQLITE_AFF_NUMERIC is returned.
001174  */
001175  char sqlite3AffinityType(const char *zIn, Column *pCol){
001176    u32 h = 0;
001177    char aff = SQLITE_AFF_NUMERIC;
001178    const char *zChar = 0;
001179  
001180    assert( zIn!=0 );
001181    while( zIn[0] ){
001182      h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
001183      zIn++;
001184      if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
001185        aff = SQLITE_AFF_TEXT;
001186        zChar = zIn;
001187      }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
001188        aff = SQLITE_AFF_TEXT;
001189      }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
001190        aff = SQLITE_AFF_TEXT;
001191      }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
001192          && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
001193        aff = SQLITE_AFF_BLOB;
001194        if( zIn[0]=='(' ) zChar = zIn;
001195  #ifndef SQLITE_OMIT_FLOATING_POINT
001196      }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
001197          && aff==SQLITE_AFF_NUMERIC ){
001198        aff = SQLITE_AFF_REAL;
001199      }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
001200          && aff==SQLITE_AFF_NUMERIC ){
001201        aff = SQLITE_AFF_REAL;
001202      }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
001203          && aff==SQLITE_AFF_NUMERIC ){
001204        aff = SQLITE_AFF_REAL;
001205  #endif
001206      }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
001207        aff = SQLITE_AFF_INTEGER;
001208        break;
001209      }
001210    }
001211  
001212    /* If pCol is not NULL, store an estimate of the field size.  The
001213    ** estimate is scaled so that the size of an integer is 1.  */
001214    if( pCol ){
001215      int v = 0;   /* default size is approx 4 bytes */
001216      if( aff<SQLITE_AFF_NUMERIC ){
001217        if( zChar ){
001218          while( zChar[0] ){
001219            if( sqlite3Isdigit(zChar[0]) ){
001220              /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
001221              sqlite3GetInt32(zChar, &v);
001222              break;
001223            }
001224            zChar++;
001225          }
001226        }else{
001227          v = 16;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
001228        }
001229      }
001230  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
001231      if( v>=sqlite3GlobalConfig.szSorterRef ){
001232        pCol->colFlags |= COLFLAG_SORTERREF;
001233      }
001234  #endif
001235      v = v/4 + 1;
001236      if( v>255 ) v = 255;
001237      pCol->szEst = v;
001238    }
001239    return aff;
001240  }
001241  
001242  /*
001243  ** The expression is the default value for the most recently added column
001244  ** of the table currently under construction.
001245  **
001246  ** Default value expressions must be constant.  Raise an exception if this
001247  ** is not the case.
001248  **
001249  ** This routine is called by the parser while in the middle of
001250  ** parsing a CREATE TABLE statement.
001251  */
001252  void sqlite3AddDefaultValue(
001253    Parse *pParse,           /* Parsing context */
001254    Expr *pExpr,             /* The parsed expression of the default value */
001255    const char *zStart,      /* Start of the default value text */
001256    const char *zEnd         /* First character past end of defaut value text */
001257  ){
001258    Table *p;
001259    Column *pCol;
001260    sqlite3 *db = pParse->db;
001261    p = pParse->pNewTable;
001262    if( p!=0 ){
001263      pCol = &(p->aCol[p->nCol-1]);
001264      if( !sqlite3ExprIsConstantOrFunction(pExpr, db->init.busy) ){
001265        sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
001266            pCol->zName);
001267      }else{
001268        /* A copy of pExpr is used instead of the original, as pExpr contains
001269        ** tokens that point to volatile memory.
001270        */
001271        Expr x;
001272        sqlite3ExprDelete(db, pCol->pDflt);
001273        memset(&x, 0, sizeof(x));
001274        x.op = TK_SPAN;
001275        x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
001276        x.pLeft = pExpr;
001277        x.flags = EP_Skip;
001278        pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
001279        sqlite3DbFree(db, x.u.zToken);
001280      }
001281    }
001282    sqlite3ExprDelete(db, pExpr);
001283  }
001284  
001285  /*
001286  ** Backwards Compatibility Hack:
001287  ** 
001288  ** Historical versions of SQLite accepted strings as column names in
001289  ** indexes and PRIMARY KEY constraints and in UNIQUE constraints.  Example:
001290  **
001291  **     CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
001292  **     CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
001293  **
001294  ** This is goofy.  But to preserve backwards compatibility we continue to
001295  ** accept it.  This routine does the necessary conversion.  It converts
001296  ** the expression given in its argument from a TK_STRING into a TK_ID
001297  ** if the expression is just a TK_STRING with an optional COLLATE clause.
001298  ** If the epxression is anything other than TK_STRING, the expression is
001299  ** unchanged.
001300  */
001301  static void sqlite3StringToId(Expr *p){
001302    if( p->op==TK_STRING ){
001303      p->op = TK_ID;
001304    }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
001305      p->pLeft->op = TK_ID;
001306    }
001307  }
001308  
001309  /*
001310  ** Designate the PRIMARY KEY for the table.  pList is a list of names 
001311  ** of columns that form the primary key.  If pList is NULL, then the
001312  ** most recently added column of the table is the primary key.
001313  **
001314  ** A table can have at most one primary key.  If the table already has
001315  ** a primary key (and this is the second primary key) then create an
001316  ** error.
001317  **
001318  ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
001319  ** then we will try to use that column as the rowid.  Set the Table.iPKey
001320  ** field of the table under construction to be the index of the
001321  ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
001322  ** no INTEGER PRIMARY KEY.
001323  **
001324  ** If the key is not an INTEGER PRIMARY KEY, then create a unique
001325  ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
001326  */
001327  void sqlite3AddPrimaryKey(
001328    Parse *pParse,    /* Parsing context */
001329    ExprList *pList,  /* List of field names to be indexed */
001330    int onError,      /* What to do with a uniqueness conflict */
001331    int autoInc,      /* True if the AUTOINCREMENT keyword is present */
001332    int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
001333  ){
001334    Table *pTab = pParse->pNewTable;
001335    Column *pCol = 0;
001336    int iCol = -1, i;
001337    int nTerm;
001338    if( pTab==0 ) goto primary_key_exit;
001339    if( pTab->tabFlags & TF_HasPrimaryKey ){
001340      sqlite3ErrorMsg(pParse, 
001341        "table \"%s\" has more than one primary key", pTab->zName);
001342      goto primary_key_exit;
001343    }
001344    pTab->tabFlags |= TF_HasPrimaryKey;
001345    if( pList==0 ){
001346      iCol = pTab->nCol - 1;
001347      pCol = &pTab->aCol[iCol];
001348      pCol->colFlags |= COLFLAG_PRIMKEY;
001349      nTerm = 1;
001350    }else{
001351      nTerm = pList->nExpr;
001352      for(i=0; i<nTerm; i++){
001353        Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
001354        assert( pCExpr!=0 );
001355        sqlite3StringToId(pCExpr);
001356        if( pCExpr->op==TK_ID ){
001357          const char *zCName = pCExpr->u.zToken;
001358          for(iCol=0; iCol<pTab->nCol; iCol++){
001359            if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
001360              pCol = &pTab->aCol[iCol];
001361              pCol->colFlags |= COLFLAG_PRIMKEY;
001362              break;
001363            }
001364          }
001365        }
001366      }
001367    }
001368    if( nTerm==1
001369     && pCol
001370     && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
001371     && sortOrder!=SQLITE_SO_DESC
001372    ){
001373      pTab->iPKey = iCol;
001374      pTab->keyConf = (u8)onError;
001375      assert( autoInc==0 || autoInc==1 );
001376      pTab->tabFlags |= autoInc*TF_Autoincrement;
001377      if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
001378    }else if( autoInc ){
001379  #ifndef SQLITE_OMIT_AUTOINCREMENT
001380      sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
001381         "INTEGER PRIMARY KEY");
001382  #endif
001383    }else{
001384      sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
001385                             0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
001386      pList = 0;
001387    }
001388  
001389  primary_key_exit:
001390    sqlite3ExprListDelete(pParse->db, pList);
001391    return;
001392  }
001393  
001394  /*
001395  ** Add a new CHECK constraint to the table currently under construction.
001396  */
001397  void sqlite3AddCheckConstraint(
001398    Parse *pParse,    /* Parsing context */
001399    Expr *pCheckExpr  /* The check expression */
001400  ){
001401  #ifndef SQLITE_OMIT_CHECK
001402    Table *pTab = pParse->pNewTable;
001403    sqlite3 *db = pParse->db;
001404    if( pTab && !IN_DECLARE_VTAB
001405     && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
001406    ){
001407      pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
001408      if( pParse->constraintName.n ){
001409        sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
001410      }
001411    }else
001412  #endif
001413    {
001414      sqlite3ExprDelete(pParse->db, pCheckExpr);
001415    }
001416  }
001417  
001418  /*
001419  ** Set the collation function of the most recently parsed table column
001420  ** to the CollSeq given.
001421  */
001422  void sqlite3AddCollateType(Parse *pParse, Token *pToken){
001423    Table *p;
001424    int i;
001425    char *zColl;              /* Dequoted name of collation sequence */
001426    sqlite3 *db;
001427  
001428    if( (p = pParse->pNewTable)==0 ) return;
001429    i = p->nCol-1;
001430    db = pParse->db;
001431    zColl = sqlite3NameFromToken(db, pToken);
001432    if( !zColl ) return;
001433  
001434    if( sqlite3LocateCollSeq(pParse, zColl) ){
001435      Index *pIdx;
001436      sqlite3DbFree(db, p->aCol[i].zColl);
001437      p->aCol[i].zColl = zColl;
001438    
001439      /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
001440      ** then an index may have been created on this column before the
001441      ** collation type was added. Correct this if it is the case.
001442      */
001443      for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
001444        assert( pIdx->nKeyCol==1 );
001445        if( pIdx->aiColumn[0]==i ){
001446          pIdx->azColl[0] = p->aCol[i].zColl;
001447        }
001448      }
001449    }else{
001450      sqlite3DbFree(db, zColl);
001451    }
001452  }
001453  
001454  /*
001455  ** This function returns the collation sequence for database native text
001456  ** encoding identified by the string zName, length nName.
001457  **
001458  ** If the requested collation sequence is not available, or not available
001459  ** in the database native encoding, the collation factory is invoked to
001460  ** request it. If the collation factory does not supply such a sequence,
001461  ** and the sequence is available in another text encoding, then that is
001462  ** returned instead.
001463  **
001464  ** If no versions of the requested collations sequence are available, or
001465  ** another error occurs, NULL is returned and an error message written into
001466  ** pParse.
001467  **
001468  ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
001469  ** invokes the collation factory if the named collation cannot be found
001470  ** and generates an error message.
001471  **
001472  ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
001473  */
001474  CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
001475    sqlite3 *db = pParse->db;
001476    u8 enc = ENC(db);
001477    u8 initbusy = db->init.busy;
001478    CollSeq *pColl;
001479  
001480    pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
001481    if( !initbusy && (!pColl || !pColl->xCmp) ){
001482      pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
001483    }
001484  
001485    return pColl;
001486  }
001487  
001488  
001489  /*
001490  ** Generate code that will increment the schema cookie.
001491  **
001492  ** The schema cookie is used to determine when the schema for the
001493  ** database changes.  After each schema change, the cookie value
001494  ** changes.  When a process first reads the schema it records the
001495  ** cookie.  Thereafter, whenever it goes to access the database,
001496  ** it checks the cookie to make sure the schema has not changed
001497  ** since it was last read.
001498  **
001499  ** This plan is not completely bullet-proof.  It is possible for
001500  ** the schema to change multiple times and for the cookie to be
001501  ** set back to prior value.  But schema changes are infrequent
001502  ** and the probability of hitting the same cookie value is only
001503  ** 1 chance in 2^32.  So we're safe enough.
001504  **
001505  ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
001506  ** the schema-version whenever the schema changes.
001507  */
001508  void sqlite3ChangeCookie(Parse *pParse, int iDb){
001509    sqlite3 *db = pParse->db;
001510    Vdbe *v = pParse->pVdbe;
001511    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
001512    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, 
001513                     (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
001514  }
001515  
001516  /*
001517  ** Measure the number of characters needed to output the given
001518  ** identifier.  The number returned includes any quotes used
001519  ** but does not include the null terminator.
001520  **
001521  ** The estimate is conservative.  It might be larger that what is
001522  ** really needed.
001523  */
001524  static int identLength(const char *z){
001525    int n;
001526    for(n=0; *z; n++, z++){
001527      if( *z=='"' ){ n++; }
001528    }
001529    return n + 2;
001530  }
001531  
001532  /*
001533  ** The first parameter is a pointer to an output buffer. The second 
001534  ** parameter is a pointer to an integer that contains the offset at
001535  ** which to write into the output buffer. This function copies the
001536  ** nul-terminated string pointed to by the third parameter, zSignedIdent,
001537  ** to the specified offset in the buffer and updates *pIdx to refer
001538  ** to the first byte after the last byte written before returning.
001539  ** 
001540  ** If the string zSignedIdent consists entirely of alpha-numeric
001541  ** characters, does not begin with a digit and is not an SQL keyword,
001542  ** then it is copied to the output buffer exactly as it is. Otherwise,
001543  ** it is quoted using double-quotes.
001544  */
001545  static void identPut(char *z, int *pIdx, char *zSignedIdent){
001546    unsigned char *zIdent = (unsigned char*)zSignedIdent;
001547    int i, j, needQuote;
001548    i = *pIdx;
001549  
001550    for(j=0; zIdent[j]; j++){
001551      if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
001552    }
001553    needQuote = sqlite3Isdigit(zIdent[0])
001554              || sqlite3KeywordCode(zIdent, j)!=TK_ID
001555              || zIdent[j]!=0
001556              || j==0;
001557  
001558    if( needQuote ) z[i++] = '"';
001559    for(j=0; zIdent[j]; j++){
001560      z[i++] = zIdent[j];
001561      if( zIdent[j]=='"' ) z[i++] = '"';
001562    }
001563    if( needQuote ) z[i++] = '"';
001564    z[i] = 0;
001565    *pIdx = i;
001566  }
001567  
001568  /*
001569  ** Generate a CREATE TABLE statement appropriate for the given
001570  ** table.  Memory to hold the text of the statement is obtained
001571  ** from sqliteMalloc() and must be freed by the calling function.
001572  */
001573  static char *createTableStmt(sqlite3 *db, Table *p){
001574    int i, k, n;
001575    char *zStmt;
001576    char *zSep, *zSep2, *zEnd;
001577    Column *pCol;
001578    n = 0;
001579    for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
001580      n += identLength(pCol->zName) + 5;
001581    }
001582    n += identLength(p->zName);
001583    if( n<50 ){ 
001584      zSep = "";
001585      zSep2 = ",";
001586      zEnd = ")";
001587    }else{
001588      zSep = "\n  ";
001589      zSep2 = ",\n  ";
001590      zEnd = "\n)";
001591    }
001592    n += 35 + 6*p->nCol;
001593    zStmt = sqlite3DbMallocRaw(0, n);
001594    if( zStmt==0 ){
001595      sqlite3OomFault(db);
001596      return 0;
001597    }
001598    sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
001599    k = sqlite3Strlen30(zStmt);
001600    identPut(zStmt, &k, p->zName);
001601    zStmt[k++] = '(';
001602    for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
001603      static const char * const azType[] = {
001604          /* SQLITE_AFF_BLOB    */ "",
001605          /* SQLITE_AFF_TEXT    */ " TEXT",
001606          /* SQLITE_AFF_NUMERIC */ " NUM",
001607          /* SQLITE_AFF_INTEGER */ " INT",
001608          /* SQLITE_AFF_REAL    */ " REAL"
001609      };
001610      int len;
001611      const char *zType;
001612  
001613      sqlite3_snprintf(n-k, &zStmt[k], zSep);
001614      k += sqlite3Strlen30(&zStmt[k]);
001615      zSep = zSep2;
001616      identPut(zStmt, &k, pCol->zName);
001617      assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
001618      assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
001619      testcase( pCol->affinity==SQLITE_AFF_BLOB );
001620      testcase( pCol->affinity==SQLITE_AFF_TEXT );
001621      testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
001622      testcase( pCol->affinity==SQLITE_AFF_INTEGER );
001623      testcase( pCol->affinity==SQLITE_AFF_REAL );
001624      
001625      zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
001626      len = sqlite3Strlen30(zType);
001627      assert( pCol->affinity==SQLITE_AFF_BLOB 
001628              || pCol->affinity==sqlite3AffinityType(zType, 0) );
001629      memcpy(&zStmt[k], zType, len);
001630      k += len;
001631      assert( k<=n );
001632    }
001633    sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
001634    return zStmt;
001635  }
001636  
001637  /*
001638  ** Resize an Index object to hold N columns total.  Return SQLITE_OK
001639  ** on success and SQLITE_NOMEM on an OOM error.
001640  */
001641  static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
001642    char *zExtra;
001643    int nByte;
001644    if( pIdx->nColumn>=N ) return SQLITE_OK;
001645    assert( pIdx->isResized==0 );
001646    nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
001647    zExtra = sqlite3DbMallocZero(db, nByte);
001648    if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
001649    memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
001650    pIdx->azColl = (const char**)zExtra;
001651    zExtra += sizeof(char*)*N;
001652    memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
001653    pIdx->aiColumn = (i16*)zExtra;
001654    zExtra += sizeof(i16)*N;
001655    memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
001656    pIdx->aSortOrder = (u8*)zExtra;
001657    pIdx->nColumn = N;
001658    pIdx->isResized = 1;
001659    return SQLITE_OK;
001660  }
001661  
001662  /*
001663  ** Estimate the total row width for a table.
001664  */
001665  static void estimateTableWidth(Table *pTab){
001666    unsigned wTable = 0;
001667    const Column *pTabCol;
001668    int i;
001669    for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
001670      wTable += pTabCol->szEst;
001671    }
001672    if( pTab->iPKey<0 ) wTable++;
001673    pTab->szTabRow = sqlite3LogEst(wTable*4);
001674  }
001675  
001676  /*
001677  ** Estimate the average size of a row for an index.
001678  */
001679  static void estimateIndexWidth(Index *pIdx){
001680    unsigned wIndex = 0;
001681    int i;
001682    const Column *aCol = pIdx->pTable->aCol;
001683    for(i=0; i<pIdx->nColumn; i++){
001684      i16 x = pIdx->aiColumn[i];
001685      assert( x<pIdx->pTable->nCol );
001686      wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
001687    }
001688    pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
001689  }
001690  
001691  /* Return true if value x is found any of the first nCol entries of aiCol[]
001692  */
001693  static int hasColumn(const i16 *aiCol, int nCol, int x){
001694    while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
001695    return 0;
001696  }
001697  
001698  /*
001699  ** This routine runs at the end of parsing a CREATE TABLE statement that
001700  ** has a WITHOUT ROWID clause.  The job of this routine is to convert both
001701  ** internal schema data structures and the generated VDBE code so that they
001702  ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
001703  ** Changes include:
001704  **
001705  **     (1)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
001706  **     (2)  Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY 
001707  **          into BTREE_BLOBKEY.
001708  **     (3)  Bypass the creation of the sqlite_master table entry
001709  **          for the PRIMARY KEY as the primary key index is now
001710  **          identified by the sqlite_master table entry of the table itself.
001711  **     (4)  Set the Index.tnum of the PRIMARY KEY Index object in the
001712  **          schema to the rootpage from the main table.
001713  **     (5)  Add all table columns to the PRIMARY KEY Index object
001714  **          so that the PRIMARY KEY is a covering index.  The surplus
001715  **          columns are part of KeyInfo.nAllField and are not used for
001716  **          sorting or lookup or uniqueness checks.
001717  **     (6)  Replace the rowid tail on all automatically generated UNIQUE
001718  **          indices with the PRIMARY KEY columns.
001719  **
001720  ** For virtual tables, only (1) is performed.
001721  */
001722  static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
001723    Index *pIdx;
001724    Index *pPk;
001725    int nPk;
001726    int i, j;
001727    sqlite3 *db = pParse->db;
001728    Vdbe *v = pParse->pVdbe;
001729  
001730    /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
001731    */
001732    if( !db->init.imposterTable ){
001733      for(i=0; i<pTab->nCol; i++){
001734        if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
001735          pTab->aCol[i].notNull = OE_Abort;
001736        }
001737      }
001738    }
001739  
001740    /* The remaining transformations only apply to b-tree tables, not to
001741    ** virtual tables */
001742    if( IN_DECLARE_VTAB ) return;
001743  
001744    /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
001745    ** into BTREE_BLOBKEY.
001746    */
001747    if( pParse->addrCrTab ){
001748      assert( v );
001749      sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
001750    }
001751  
001752    /* Locate the PRIMARY KEY index.  Or, if this table was originally
001753    ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. 
001754    */
001755    if( pTab->iPKey>=0 ){
001756      ExprList *pList;
001757      Token ipkToken;
001758      sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
001759      pList = sqlite3ExprListAppend(pParse, 0, 
001760                    sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
001761      if( pList==0 ) return;
001762      pList->a[0].sortOrder = pParse->iPkSortOrder;
001763      assert( pParse->pNewTable==pTab );
001764      sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
001765                         SQLITE_IDXTYPE_PRIMARYKEY);
001766      if( db->mallocFailed ) return;
001767      pPk = sqlite3PrimaryKeyIndex(pTab);
001768      pTab->iPKey = -1;
001769    }else{
001770      pPk = sqlite3PrimaryKeyIndex(pTab);
001771  
001772      /*
001773      ** Remove all redundant columns from the PRIMARY KEY.  For example, change
001774      ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)".  Later
001775      ** code assumes the PRIMARY KEY contains no repeated columns.
001776      */
001777      for(i=j=1; i<pPk->nKeyCol; i++){
001778        if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
001779          pPk->nColumn--;
001780        }else{
001781          pPk->aiColumn[j++] = pPk->aiColumn[i];
001782        }
001783      }
001784      pPk->nKeyCol = j;
001785    }
001786    assert( pPk!=0 );
001787    pPk->isCovering = 1;
001788    if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
001789    nPk = pPk->nKeyCol;
001790  
001791    /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
001792    ** table entry. This is only required if currently generating VDBE
001793    ** code for a CREATE TABLE (not when parsing one as part of reading
001794    ** a database schema).  */
001795    if( v && pPk->tnum>0 ){
001796      assert( db->init.busy==0 );
001797      sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
001798    }
001799  
001800    /* The root page of the PRIMARY KEY is the table root page */
001801    pPk->tnum = pTab->tnum;
001802  
001803    /* Update the in-memory representation of all UNIQUE indices by converting
001804    ** the final rowid column into one or more columns of the PRIMARY KEY.
001805    */
001806    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
001807      int n;
001808      if( IsPrimaryKeyIndex(pIdx) ) continue;
001809      for(i=n=0; i<nPk; i++){
001810        if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
001811      }
001812      if( n==0 ){
001813        /* This index is a superset of the primary key */
001814        pIdx->nColumn = pIdx->nKeyCol;
001815        continue;
001816      }
001817      if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
001818      for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
001819        if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
001820          pIdx->aiColumn[j] = pPk->aiColumn[i];
001821          pIdx->azColl[j] = pPk->azColl[i];
001822          j++;
001823        }
001824      }
001825      assert( pIdx->nColumn>=pIdx->nKeyCol+n );
001826      assert( pIdx->nColumn>=j );
001827    }
001828  
001829    /* Add all table columns to the PRIMARY KEY index
001830    */
001831    if( nPk<pTab->nCol ){
001832      if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
001833      for(i=0, j=nPk; i<pTab->nCol; i++){
001834        if( !hasColumn(pPk->aiColumn, j, i) ){
001835          assert( j<pPk->nColumn );
001836          pPk->aiColumn[j] = i;
001837          pPk->azColl[j] = sqlite3StrBINARY;
001838          j++;
001839        }
001840      }
001841      assert( pPk->nColumn==j );
001842      assert( pTab->nCol==j );
001843    }else{
001844      pPk->nColumn = pTab->nCol;
001845    }
001846  }
001847  
001848  /*
001849  ** This routine is called to report the final ")" that terminates
001850  ** a CREATE TABLE statement.
001851  **
001852  ** The table structure that other action routines have been building
001853  ** is added to the internal hash tables, assuming no errors have
001854  ** occurred.
001855  **
001856  ** An entry for the table is made in the master table on disk, unless
001857  ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
001858  ** it means we are reading the sqlite_master table because we just
001859  ** connected to the database or because the sqlite_master table has
001860  ** recently changed, so the entry for this table already exists in
001861  ** the sqlite_master table.  We do not want to create it again.
001862  **
001863  ** If the pSelect argument is not NULL, it means that this routine
001864  ** was called to create a table generated from a 
001865  ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
001866  ** the new table will match the result set of the SELECT.
001867  */
001868  void sqlite3EndTable(
001869    Parse *pParse,          /* Parse context */
001870    Token *pCons,           /* The ',' token after the last column defn. */
001871    Token *pEnd,            /* The ')' before options in the CREATE TABLE */
001872    u8 tabOpts,             /* Extra table options. Usually 0. */
001873    Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
001874  ){
001875    Table *p;                 /* The new table */
001876    sqlite3 *db = pParse->db; /* The database connection */
001877    int iDb;                  /* Database in which the table lives */
001878    Index *pIdx;              /* An implied index of the table */
001879  
001880    if( pEnd==0 && pSelect==0 ){
001881      return;
001882    }
001883    assert( !db->mallocFailed );
001884    p = pParse->pNewTable;
001885    if( p==0 ) return;
001886  
001887    /* If the db->init.busy is 1 it means we are reading the SQL off the
001888    ** "sqlite_master" or "sqlite_temp_master" table on the disk.
001889    ** So do not write to the disk again.  Extract the root page number
001890    ** for the table from the db->init.newTnum field.  (The page number
001891    ** should have been put there by the sqliteOpenCb routine.)
001892    **
001893    ** If the root page number is 1, that means this is the sqlite_master
001894    ** table itself.  So mark it read-only.
001895    */
001896    if( db->init.busy ){
001897      if( pSelect ){
001898        sqlite3ErrorMsg(pParse, "");
001899        return;
001900      }
001901      p->tnum = db->init.newTnum;
001902      if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
001903    }
001904  
001905    /* Special processing for WITHOUT ROWID Tables */
001906    if( tabOpts & TF_WithoutRowid ){
001907      if( (p->tabFlags & TF_Autoincrement) ){
001908        sqlite3ErrorMsg(pParse,
001909            "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
001910        return;
001911      }
001912      if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
001913        sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
001914      }else{
001915        p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
001916        convertToWithoutRowidTable(pParse, p);
001917      }
001918    }
001919  
001920    iDb = sqlite3SchemaToIndex(db, p->pSchema);
001921  
001922  #ifndef SQLITE_OMIT_CHECK
001923    /* Resolve names in all CHECK constraint expressions.
001924    */
001925    if( p->pCheck ){
001926      sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
001927    }
001928  #endif /* !defined(SQLITE_OMIT_CHECK) */
001929  
001930    /* Estimate the average row size for the table and for all implied indices */
001931    estimateTableWidth(p);
001932    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
001933      estimateIndexWidth(pIdx);
001934    }
001935  
001936    /* If not initializing, then create a record for the new table
001937    ** in the SQLITE_MASTER table of the database.
001938    **
001939    ** If this is a TEMPORARY table, write the entry into the auxiliary
001940    ** file instead of into the main database file.
001941    */
001942    if( !db->init.busy ){
001943      int n;
001944      Vdbe *v;
001945      char *zType;    /* "view" or "table" */
001946      char *zType2;   /* "VIEW" or "TABLE" */
001947      char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
001948  
001949      v = sqlite3GetVdbe(pParse);
001950      if( NEVER(v==0) ) return;
001951  
001952      sqlite3VdbeAddOp1(v, OP_Close, 0);
001953  
001954      /* 
001955      ** Initialize zType for the new view or table.
001956      */
001957      if( p->pSelect==0 ){
001958        /* A regular table */
001959        zType = "table";
001960        zType2 = "TABLE";
001961  #ifndef SQLITE_OMIT_VIEW
001962      }else{
001963        /* A view */
001964        zType = "view";
001965        zType2 = "VIEW";
001966  #endif
001967      }
001968  
001969      /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
001970      ** statement to populate the new table. The root-page number for the
001971      ** new table is in register pParse->regRoot.
001972      **
001973      ** Once the SELECT has been coded by sqlite3Select(), it is in a
001974      ** suitable state to query for the column names and types to be used
001975      ** by the new table.
001976      **
001977      ** A shared-cache write-lock is not required to write to the new table,
001978      ** as a schema-lock must have already been obtained to create it. Since
001979      ** a schema-lock excludes all other database users, the write-lock would
001980      ** be redundant.
001981      */
001982      if( pSelect ){
001983        SelectDest dest;    /* Where the SELECT should store results */
001984        int regYield;       /* Register holding co-routine entry-point */
001985        int addrTop;        /* Top of the co-routine */
001986        int regRec;         /* A record to be insert into the new table */
001987        int regRowid;       /* Rowid of the next row to insert */
001988        int addrInsLoop;    /* Top of the loop for inserting rows */
001989        Table *pSelTab;     /* A table that describes the SELECT results */
001990  
001991        regYield = ++pParse->nMem;
001992        regRec = ++pParse->nMem;
001993        regRowid = ++pParse->nMem;
001994        assert(pParse->nTab==1);
001995        sqlite3MayAbort(pParse);
001996        sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
001997        sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
001998        pParse->nTab = 2;
001999        addrTop = sqlite3VdbeCurrentAddr(v) + 1;
002000        sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
002001        if( pParse->nErr ) return;
002002        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
002003        if( pSelTab==0 ) return;
002004        assert( p->aCol==0 );
002005        p->nCol = pSelTab->nCol;
002006        p->aCol = pSelTab->aCol;
002007        pSelTab->nCol = 0;
002008        pSelTab->aCol = 0;
002009        sqlite3DeleteTable(db, pSelTab);
002010        sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
002011        sqlite3Select(pParse, pSelect, &dest);
002012        if( pParse->nErr ) return;
002013        sqlite3VdbeEndCoroutine(v, regYield);
002014        sqlite3VdbeJumpHere(v, addrTop - 1);
002015        addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
002016        VdbeCoverage(v);
002017        sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
002018        sqlite3TableAffinity(v, p, 0);
002019        sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
002020        sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
002021        sqlite3VdbeGoto(v, addrInsLoop);
002022        sqlite3VdbeJumpHere(v, addrInsLoop);
002023        sqlite3VdbeAddOp1(v, OP_Close, 1);
002024      }
002025  
002026      /* Compute the complete text of the CREATE statement */
002027      if( pSelect ){
002028        zStmt = createTableStmt(db, p);
002029      }else{
002030        Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
002031        n = (int)(pEnd2->z - pParse->sNameToken.z);
002032        if( pEnd2->z[0]!=';' ) n += pEnd2->n;
002033        zStmt = sqlite3MPrintf(db, 
002034            "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
002035        );
002036      }
002037  
002038      /* A slot for the record has already been allocated in the 
002039      ** SQLITE_MASTER table.  We just need to update that slot with all
002040      ** the information we've collected.
002041      */
002042      sqlite3NestedParse(pParse,
002043        "UPDATE %Q.%s "
002044           "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
002045         "WHERE rowid=#%d",
002046        db->aDb[iDb].zDbSName, MASTER_NAME,
002047        zType,
002048        p->zName,
002049        p->zName,
002050        pParse->regRoot,
002051        zStmt,
002052        pParse->regRowid
002053      );
002054      sqlite3DbFree(db, zStmt);
002055      sqlite3ChangeCookie(pParse, iDb);
002056  
002057  #ifndef SQLITE_OMIT_AUTOINCREMENT
002058      /* Check to see if we need to create an sqlite_sequence table for
002059      ** keeping track of autoincrement keys.
002060      */
002061      if( (p->tabFlags & TF_Autoincrement)!=0 ){
002062        Db *pDb = &db->aDb[iDb];
002063        assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
002064        if( pDb->pSchema->pSeqTab==0 ){
002065          sqlite3NestedParse(pParse,
002066            "CREATE TABLE %Q.sqlite_sequence(name,seq)",
002067            pDb->zDbSName
002068          );
002069        }
002070      }
002071  #endif
002072  
002073      /* Reparse everything to update our internal data structures */
002074      sqlite3VdbeAddParseSchemaOp(v, iDb,
002075             sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
002076    }
002077  
002078  
002079    /* Add the table to the in-memory representation of the database.
002080    */
002081    if( db->init.busy ){
002082      Table *pOld;
002083      Schema *pSchema = p->pSchema;
002084      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
002085      pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
002086      if( pOld ){
002087        assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
002088        sqlite3OomFault(db);
002089        return;
002090      }
002091      pParse->pNewTable = 0;
002092      db->mDbFlags |= DBFLAG_SchemaChange;
002093  
002094  #ifndef SQLITE_OMIT_ALTERTABLE
002095      if( !p->pSelect ){
002096        const char *zName = (const char *)pParse->sNameToken.z;
002097        int nName;
002098        assert( !pSelect && pCons && pEnd );
002099        if( pCons->z==0 ){
002100          pCons = pEnd;
002101        }
002102        nName = (int)((const char *)pCons->z - zName);
002103        p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
002104      }
002105  #endif
002106    }
002107  }
002108  
002109  #ifndef SQLITE_OMIT_VIEW
002110  /*
002111  ** The parser calls this routine in order to create a new VIEW
002112  */
002113  void sqlite3CreateView(
002114    Parse *pParse,     /* The parsing context */
002115    Token *pBegin,     /* The CREATE token that begins the statement */
002116    Token *pName1,     /* The token that holds the name of the view */
002117    Token *pName2,     /* The token that holds the name of the view */
002118    ExprList *pCNames, /* Optional list of view column names */
002119    Select *pSelect,   /* A SELECT statement that will become the new view */
002120    int isTemp,        /* TRUE for a TEMPORARY view */
002121    int noErr          /* Suppress error messages if VIEW already exists */
002122  ){
002123    Table *p;
002124    int n;
002125    const char *z;
002126    Token sEnd;
002127    DbFixer sFix;
002128    Token *pName = 0;
002129    int iDb;
002130    sqlite3 *db = pParse->db;
002131  
002132    if( pParse->nVar>0 ){
002133      sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
002134      goto create_view_fail;
002135    }
002136    sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
002137    p = pParse->pNewTable;
002138    if( p==0 || pParse->nErr ) goto create_view_fail;
002139    sqlite3TwoPartName(pParse, pName1, pName2, &pName);
002140    iDb = sqlite3SchemaToIndex(db, p->pSchema);
002141    sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
002142    if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
002143  
002144    /* Make a copy of the entire SELECT statement that defines the view.
002145    ** This will force all the Expr.token.z values to be dynamically
002146    ** allocated rather than point to the input string - which means that
002147    ** they will persist after the current sqlite3_exec() call returns.
002148    */
002149    p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
002150    p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
002151    if( db->mallocFailed ) goto create_view_fail;
002152  
002153    /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
002154    ** the end.
002155    */
002156    sEnd = pParse->sLastToken;
002157    assert( sEnd.z[0]!=0 || sEnd.n==0 );
002158    if( sEnd.z[0]!=';' ){
002159      sEnd.z += sEnd.n;
002160    }
002161    sEnd.n = 0;
002162    n = (int)(sEnd.z - pBegin->z);
002163    assert( n>0 );
002164    z = pBegin->z;
002165    while( sqlite3Isspace(z[n-1]) ){ n--; }
002166    sEnd.z = &z[n-1];
002167    sEnd.n = 1;
002168  
002169    /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
002170    sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
002171  
002172  create_view_fail:
002173    sqlite3SelectDelete(db, pSelect);
002174    sqlite3ExprListDelete(db, pCNames);
002175    return;
002176  }
002177  #endif /* SQLITE_OMIT_VIEW */
002178  
002179  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
002180  /*
002181  ** The Table structure pTable is really a VIEW.  Fill in the names of
002182  ** the columns of the view in the pTable structure.  Return the number
002183  ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
002184  */
002185  int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
002186    Table *pSelTab;   /* A fake table from which we get the result set */
002187    Select *pSel;     /* Copy of the SELECT that implements the view */
002188    int nErr = 0;     /* Number of errors encountered */
002189    int n;            /* Temporarily holds the number of cursors assigned */
002190    sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
002191  #ifndef SQLITE_OMIT_VIRTUALTABLE
002192    int rc;
002193  #endif
002194  #ifndef SQLITE_OMIT_AUTHORIZATION
002195    sqlite3_xauth xAuth;       /* Saved xAuth pointer */
002196  #endif
002197  
002198    assert( pTable );
002199  
002200  #ifndef SQLITE_OMIT_VIRTUALTABLE
002201    db->nSchemaLock++;
002202    rc = sqlite3VtabCallConnect(pParse, pTable);
002203    db->nSchemaLock--;
002204    if( rc ){
002205      return 1;
002206    }
002207    if( IsVirtual(pTable) ) return 0;
002208  #endif
002209  
002210  #ifndef SQLITE_OMIT_VIEW
002211    /* A positive nCol means the columns names for this view are
002212    ** already known.
002213    */
002214    if( pTable->nCol>0 ) return 0;
002215  
002216    /* A negative nCol is a special marker meaning that we are currently
002217    ** trying to compute the column names.  If we enter this routine with
002218    ** a negative nCol, it means two or more views form a loop, like this:
002219    **
002220    **     CREATE VIEW one AS SELECT * FROM two;
002221    **     CREATE VIEW two AS SELECT * FROM one;
002222    **
002223    ** Actually, the error above is now caught prior to reaching this point.
002224    ** But the following test is still important as it does come up
002225    ** in the following:
002226    ** 
002227    **     CREATE TABLE main.ex1(a);
002228    **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
002229    **     SELECT * FROM temp.ex1;
002230    */
002231    if( pTable->nCol<0 ){
002232      sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
002233      return 1;
002234    }
002235    assert( pTable->nCol>=0 );
002236  
002237    /* If we get this far, it means we need to compute the table names.
002238    ** Note that the call to sqlite3ResultSetOfSelect() will expand any
002239    ** "*" elements in the results set of the view and will assign cursors
002240    ** to the elements of the FROM clause.  But we do not want these changes
002241    ** to be permanent.  So the computation is done on a copy of the SELECT
002242    ** statement that defines the view.
002243    */
002244    assert( pTable->pSelect );
002245    pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
002246    if( pSel ){
002247      n = pParse->nTab;
002248      sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
002249      pTable->nCol = -1;
002250      db->lookaside.bDisable++;
002251  #ifndef SQLITE_OMIT_AUTHORIZATION
002252      xAuth = db->xAuth;
002253      db->xAuth = 0;
002254      pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
002255      db->xAuth = xAuth;
002256  #else
002257      pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
002258  #endif
002259      pParse->nTab = n;
002260      if( pTable->pCheck ){
002261        /* CREATE VIEW name(arglist) AS ...
002262        ** The names of the columns in the table are taken from
002263        ** arglist which is stored in pTable->pCheck.  The pCheck field
002264        ** normally holds CHECK constraints on an ordinary table, but for
002265        ** a VIEW it holds the list of column names.
002266        */
002267        sqlite3ColumnsFromExprList(pParse, pTable->pCheck, 
002268                                   &pTable->nCol, &pTable->aCol);
002269        if( db->mallocFailed==0 
002270         && pParse->nErr==0
002271         && pTable->nCol==pSel->pEList->nExpr
002272        ){
002273          sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
002274        }
002275      }else if( pSelTab ){
002276        /* CREATE VIEW name AS...  without an argument list.  Construct
002277        ** the column names from the SELECT statement that defines the view.
002278        */
002279        assert( pTable->aCol==0 );
002280        pTable->nCol = pSelTab->nCol;
002281        pTable->aCol = pSelTab->aCol;
002282        pSelTab->nCol = 0;
002283        pSelTab->aCol = 0;
002284        assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
002285      }else{
002286        pTable->nCol = 0;
002287        nErr++;
002288      }
002289      sqlite3DeleteTable(db, pSelTab);
002290      sqlite3SelectDelete(db, pSel);
002291      db->lookaside.bDisable--;
002292    } else {
002293      nErr++;
002294    }
002295    pTable->pSchema->schemaFlags |= DB_UnresetViews;
002296  #endif /* SQLITE_OMIT_VIEW */
002297    return nErr;  
002298  }
002299  #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
002300  
002301  #ifndef SQLITE_OMIT_VIEW
002302  /*
002303  ** Clear the column names from every VIEW in database idx.
002304  */
002305  static void sqliteViewResetAll(sqlite3 *db, int idx){
002306    HashElem *i;
002307    assert( sqlite3SchemaMutexHeld(db, idx, 0) );
002308    if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
002309    for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
002310      Table *pTab = sqliteHashData(i);
002311      if( pTab->pSelect ){
002312        sqlite3DeleteColumnNames(db, pTab);
002313        pTab->aCol = 0;
002314        pTab->nCol = 0;
002315      }
002316    }
002317    DbClearProperty(db, idx, DB_UnresetViews);
002318  }
002319  #else
002320  # define sqliteViewResetAll(A,B)
002321  #endif /* SQLITE_OMIT_VIEW */
002322  
002323  /*
002324  ** This function is called by the VDBE to adjust the internal schema
002325  ** used by SQLite when the btree layer moves a table root page. The
002326  ** root-page of a table or index in database iDb has changed from iFrom
002327  ** to iTo.
002328  **
002329  ** Ticket #1728:  The symbol table might still contain information
002330  ** on tables and/or indices that are the process of being deleted.
002331  ** If you are unlucky, one of those deleted indices or tables might
002332  ** have the same rootpage number as the real table or index that is
002333  ** being moved.  So we cannot stop searching after the first match 
002334  ** because the first match might be for one of the deleted indices
002335  ** or tables and not the table/index that is actually being moved.
002336  ** We must continue looping until all tables and indices with
002337  ** rootpage==iFrom have been converted to have a rootpage of iTo
002338  ** in order to be certain that we got the right one.
002339  */
002340  #ifndef SQLITE_OMIT_AUTOVACUUM
002341  void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
002342    HashElem *pElem;
002343    Hash *pHash;
002344    Db *pDb;
002345  
002346    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
002347    pDb = &db->aDb[iDb];
002348    pHash = &pDb->pSchema->tblHash;
002349    for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
002350      Table *pTab = sqliteHashData(pElem);
002351      if( pTab->tnum==iFrom ){
002352        pTab->tnum = iTo;
002353      }
002354    }
002355    pHash = &pDb->pSchema->idxHash;
002356    for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
002357      Index *pIdx = sqliteHashData(pElem);
002358      if( pIdx->tnum==iFrom ){
002359        pIdx->tnum = iTo;
002360      }
002361    }
002362  }
002363  #endif
002364  
002365  /*
002366  ** Write code to erase the table with root-page iTable from database iDb.
002367  ** Also write code to modify the sqlite_master table and internal schema
002368  ** if a root-page of another table is moved by the btree-layer whilst
002369  ** erasing iTable (this can happen with an auto-vacuum database).
002370  */ 
002371  static void destroyRootPage(Parse *pParse, int iTable, int iDb){
002372    Vdbe *v = sqlite3GetVdbe(pParse);
002373    int r1 = sqlite3GetTempReg(pParse);
002374    assert( iTable>1 );
002375    sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
002376    sqlite3MayAbort(pParse);
002377  #ifndef SQLITE_OMIT_AUTOVACUUM
002378    /* OP_Destroy stores an in integer r1. If this integer
002379    ** is non-zero, then it is the root page number of a table moved to
002380    ** location iTable. The following code modifies the sqlite_master table to
002381    ** reflect this.
002382    **
002383    ** The "#NNN" in the SQL is a special constant that means whatever value
002384    ** is in register NNN.  See grammar rules associated with the TK_REGISTER
002385    ** token for additional information.
002386    */
002387    sqlite3NestedParse(pParse, 
002388       "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
002389       pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
002390  #endif
002391    sqlite3ReleaseTempReg(pParse, r1);
002392  }
002393  
002394  /*
002395  ** Write VDBE code to erase table pTab and all associated indices on disk.
002396  ** Code to update the sqlite_master tables and internal schema definitions
002397  ** in case a root-page belonging to another table is moved by the btree layer
002398  ** is also added (this can happen with an auto-vacuum database).
002399  */
002400  static void destroyTable(Parse *pParse, Table *pTab){
002401    /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
002402    ** is not defined), then it is important to call OP_Destroy on the
002403    ** table and index root-pages in order, starting with the numerically 
002404    ** largest root-page number. This guarantees that none of the root-pages
002405    ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
002406    ** following were coded:
002407    **
002408    ** OP_Destroy 4 0
002409    ** ...
002410    ** OP_Destroy 5 0
002411    **
002412    ** and root page 5 happened to be the largest root-page number in the
002413    ** database, then root page 5 would be moved to page 4 by the 
002414    ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
002415    ** a free-list page.
002416    */
002417    int iTab = pTab->tnum;
002418    int iDestroyed = 0;
002419  
002420    while( 1 ){
002421      Index *pIdx;
002422      int iLargest = 0;
002423  
002424      if( iDestroyed==0 || iTab<iDestroyed ){
002425        iLargest = iTab;
002426      }
002427      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
002428        int iIdx = pIdx->tnum;
002429        assert( pIdx->pSchema==pTab->pSchema );
002430        if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
002431          iLargest = iIdx;
002432        }
002433      }
002434      if( iLargest==0 ){
002435        return;
002436      }else{
002437        int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
002438        assert( iDb>=0 && iDb<pParse->db->nDb );
002439        destroyRootPage(pParse, iLargest, iDb);
002440        iDestroyed = iLargest;
002441      }
002442    }
002443  }
002444  
002445  /*
002446  ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
002447  ** after a DROP INDEX or DROP TABLE command.
002448  */
002449  static void sqlite3ClearStatTables(
002450    Parse *pParse,         /* The parsing context */
002451    int iDb,               /* The database number */
002452    const char *zType,     /* "idx" or "tbl" */
002453    const char *zName      /* Name of index or table */
002454  ){
002455    int i;
002456    const char *zDbName = pParse->db->aDb[iDb].zDbSName;
002457    for(i=1; i<=4; i++){
002458      char zTab[24];
002459      sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
002460      if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
002461        sqlite3NestedParse(pParse,
002462          "DELETE FROM %Q.%s WHERE %s=%Q",
002463          zDbName, zTab, zType, zName
002464        );
002465      }
002466    }
002467  }
002468  
002469  /*
002470  ** Generate code to drop a table.
002471  */
002472  void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
002473    Vdbe *v;
002474    sqlite3 *db = pParse->db;
002475    Trigger *pTrigger;
002476    Db *pDb = &db->aDb[iDb];
002477  
002478    v = sqlite3GetVdbe(pParse);
002479    assert( v!=0 );
002480    sqlite3BeginWriteOperation(pParse, 1, iDb);
002481  
002482  #ifndef SQLITE_OMIT_VIRTUALTABLE
002483    if( IsVirtual(pTab) ){
002484      sqlite3VdbeAddOp0(v, OP_VBegin);
002485    }
002486  #endif
002487  
002488    /* Drop all triggers associated with the table being dropped. Code
002489    ** is generated to remove entries from sqlite_master and/or
002490    ** sqlite_temp_master if required.
002491    */
002492    pTrigger = sqlite3TriggerList(pParse, pTab);
002493    while( pTrigger ){
002494      assert( pTrigger->pSchema==pTab->pSchema || 
002495          pTrigger->pSchema==db->aDb[1].pSchema );
002496      sqlite3DropTriggerPtr(pParse, pTrigger);
002497      pTrigger = pTrigger->pNext;
002498    }
002499  
002500  #ifndef SQLITE_OMIT_AUTOINCREMENT
002501    /* Remove any entries of the sqlite_sequence table associated with
002502    ** the table being dropped. This is done before the table is dropped
002503    ** at the btree level, in case the sqlite_sequence table needs to
002504    ** move as a result of the drop (can happen in auto-vacuum mode).
002505    */
002506    if( pTab->tabFlags & TF_Autoincrement ){
002507      sqlite3NestedParse(pParse,
002508        "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
002509        pDb->zDbSName, pTab->zName
002510      );
002511    }
002512  #endif
002513  
002514    /* Drop all SQLITE_MASTER table and index entries that refer to the
002515    ** table. The program name loops through the master table and deletes
002516    ** every row that refers to a table of the same name as the one being
002517    ** dropped. Triggers are handled separately because a trigger can be
002518    ** created in the temp database that refers to a table in another
002519    ** database.
002520    */
002521    sqlite3NestedParse(pParse, 
002522        "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
002523        pDb->zDbSName, MASTER_NAME, pTab->zName);
002524    if( !isView && !IsVirtual(pTab) ){
002525      destroyTable(pParse, pTab);
002526    }
002527  
002528    /* Remove the table entry from SQLite's internal schema and modify
002529    ** the schema cookie.
002530    */
002531    if( IsVirtual(pTab) ){
002532      sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
002533    }
002534    sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
002535    sqlite3ChangeCookie(pParse, iDb);
002536    sqliteViewResetAll(db, iDb);
002537  }
002538  
002539  /*
002540  ** This routine is called to do the work of a DROP TABLE statement.
002541  ** pName is the name of the table to be dropped.
002542  */
002543  void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
002544    Table *pTab;
002545    Vdbe *v;
002546    sqlite3 *db = pParse->db;
002547    int iDb;
002548  
002549    if( db->mallocFailed ){
002550      goto exit_drop_table;
002551    }
002552    assert( pParse->nErr==0 );
002553    assert( pName->nSrc==1 );
002554    if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
002555    if( noErr ) db->suppressErr++;
002556    assert( isView==0 || isView==LOCATE_VIEW );
002557    pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
002558    if( noErr ) db->suppressErr--;
002559  
002560    if( pTab==0 ){
002561      if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
002562      goto exit_drop_table;
002563    }
002564    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
002565    assert( iDb>=0 && iDb<db->nDb );
002566  
002567    /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
002568    ** it is initialized.
002569    */
002570    if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
002571      goto exit_drop_table;
002572    }
002573  #ifndef SQLITE_OMIT_AUTHORIZATION
002574    {
002575      int code;
002576      const char *zTab = SCHEMA_TABLE(iDb);
002577      const char *zDb = db->aDb[iDb].zDbSName;
002578      const char *zArg2 = 0;
002579      if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
002580        goto exit_drop_table;
002581      }
002582      if( isView ){
002583        if( !OMIT_TEMPDB && iDb==1 ){
002584          code = SQLITE_DROP_TEMP_VIEW;
002585        }else{
002586          code = SQLITE_DROP_VIEW;
002587        }
002588  #ifndef SQLITE_OMIT_VIRTUALTABLE
002589      }else if( IsVirtual(pTab) ){
002590        code = SQLITE_DROP_VTABLE;
002591        zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
002592  #endif
002593      }else{
002594        if( !OMIT_TEMPDB && iDb==1 ){
002595          code = SQLITE_DROP_TEMP_TABLE;
002596        }else{
002597          code = SQLITE_DROP_TABLE;
002598        }
002599      }
002600      if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
002601        goto exit_drop_table;
002602      }
002603      if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
002604        goto exit_drop_table;
002605      }
002606    }
002607  #endif
002608    if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
002609      && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
002610      sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
002611      goto exit_drop_table;
002612    }
002613  
002614  #ifndef SQLITE_OMIT_VIEW
002615    /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
002616    ** on a table.
002617    */
002618    if( isView && pTab->pSelect==0 ){
002619      sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
002620      goto exit_drop_table;
002621    }
002622    if( !isView && pTab->pSelect ){
002623      sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
002624      goto exit_drop_table;
002625    }
002626  #endif
002627  
002628    /* Generate code to remove the table from the master table
002629    ** on disk.
002630    */
002631    v = sqlite3GetVdbe(pParse);
002632    if( v ){
002633      sqlite3BeginWriteOperation(pParse, 1, iDb);
002634      sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
002635      sqlite3FkDropTable(pParse, pName, pTab);
002636      sqlite3CodeDropTable(pParse, pTab, iDb, isView);
002637    }
002638  
002639  exit_drop_table:
002640    sqlite3SrcListDelete(db, pName);
002641  }
002642  
002643  /*
002644  ** This routine is called to create a new foreign key on the table
002645  ** currently under construction.  pFromCol determines which columns
002646  ** in the current table point to the foreign key.  If pFromCol==0 then
002647  ** connect the key to the last column inserted.  pTo is the name of
002648  ** the table referred to (a.k.a the "parent" table).  pToCol is a list
002649  ** of tables in the parent pTo table.  flags contains all
002650  ** information about the conflict resolution algorithms specified
002651  ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
002652  **
002653  ** An FKey structure is created and added to the table currently
002654  ** under construction in the pParse->pNewTable field.
002655  **
002656  ** The foreign key is set for IMMEDIATE processing.  A subsequent call
002657  ** to sqlite3DeferForeignKey() might change this to DEFERRED.
002658  */
002659  void sqlite3CreateForeignKey(
002660    Parse *pParse,       /* Parsing context */
002661    ExprList *pFromCol,  /* Columns in this table that point to other table */
002662    Token *pTo,          /* Name of the other table */
002663    ExprList *pToCol,    /* Columns in the other table */
002664    int flags            /* Conflict resolution algorithms. */
002665  ){
002666    sqlite3 *db = pParse->db;
002667  #ifndef SQLITE_OMIT_FOREIGN_KEY
002668    FKey *pFKey = 0;
002669    FKey *pNextTo;
002670    Table *p = pParse->pNewTable;
002671    int nByte;
002672    int i;
002673    int nCol;
002674    char *z;
002675  
002676    assert( pTo!=0 );
002677    if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
002678    if( pFromCol==0 ){
002679      int iCol = p->nCol-1;
002680      if( NEVER(iCol<0) ) goto fk_end;
002681      if( pToCol && pToCol->nExpr!=1 ){
002682        sqlite3ErrorMsg(pParse, "foreign key on %s"
002683           " should reference only one column of table %T",
002684           p->aCol[iCol].zName, pTo);
002685        goto fk_end;
002686      }
002687      nCol = 1;
002688    }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
002689      sqlite3ErrorMsg(pParse,
002690          "number of columns in foreign key does not match the number of "
002691          "columns in the referenced table");
002692      goto fk_end;
002693    }else{
002694      nCol = pFromCol->nExpr;
002695    }
002696    nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
002697    if( pToCol ){
002698      for(i=0; i<pToCol->nExpr; i++){
002699        nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
002700      }
002701    }
002702    pFKey = sqlite3DbMallocZero(db, nByte );
002703    if( pFKey==0 ){
002704      goto fk_end;
002705    }
002706    pFKey->pFrom = p;
002707    pFKey->pNextFrom = p->pFKey;
002708    z = (char*)&pFKey->aCol[nCol];
002709    pFKey->zTo = z;
002710    memcpy(z, pTo->z, pTo->n);
002711    z[pTo->n] = 0;
002712    sqlite3Dequote(z);
002713    z += pTo->n+1;
002714    pFKey->nCol = nCol;
002715    if( pFromCol==0 ){
002716      pFKey->aCol[0].iFrom = p->nCol-1;
002717    }else{
002718      for(i=0; i<nCol; i++){
002719        int j;
002720        for(j=0; j<p->nCol; j++){
002721          if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
002722            pFKey->aCol[i].iFrom = j;
002723            break;
002724          }
002725        }
002726        if( j>=p->nCol ){
002727          sqlite3ErrorMsg(pParse, 
002728            "unknown column \"%s\" in foreign key definition", 
002729            pFromCol->a[i].zName);
002730          goto fk_end;
002731        }
002732      }
002733    }
002734    if( pToCol ){
002735      for(i=0; i<nCol; i++){
002736        int n = sqlite3Strlen30(pToCol->a[i].zName);
002737        pFKey->aCol[i].zCol = z;
002738        memcpy(z, pToCol->a[i].zName, n);
002739        z[n] = 0;
002740        z += n+1;
002741      }
002742    }
002743    pFKey->isDeferred = 0;
002744    pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
002745    pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
002746  
002747    assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
002748    pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
002749        pFKey->zTo, (void *)pFKey
002750    );
002751    if( pNextTo==pFKey ){
002752      sqlite3OomFault(db);
002753      goto fk_end;
002754    }
002755    if( pNextTo ){
002756      assert( pNextTo->pPrevTo==0 );
002757      pFKey->pNextTo = pNextTo;
002758      pNextTo->pPrevTo = pFKey;
002759    }
002760  
002761    /* Link the foreign key to the table as the last step.
002762    */
002763    p->pFKey = pFKey;
002764    pFKey = 0;
002765  
002766  fk_end:
002767    sqlite3DbFree(db, pFKey);
002768  #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
002769    sqlite3ExprListDelete(db, pFromCol);
002770    sqlite3ExprListDelete(db, pToCol);
002771  }
002772  
002773  /*
002774  ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
002775  ** clause is seen as part of a foreign key definition.  The isDeferred
002776  ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
002777  ** The behavior of the most recently created foreign key is adjusted
002778  ** accordingly.
002779  */
002780  void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
002781  #ifndef SQLITE_OMIT_FOREIGN_KEY
002782    Table *pTab;
002783    FKey *pFKey;
002784    if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
002785    assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
002786    pFKey->isDeferred = (u8)isDeferred;
002787  #endif
002788  }
002789  
002790  /*
002791  ** Generate code that will erase and refill index *pIdx.  This is
002792  ** used to initialize a newly created index or to recompute the
002793  ** content of an index in response to a REINDEX command.
002794  **
002795  ** if memRootPage is not negative, it means that the index is newly
002796  ** created.  The register specified by memRootPage contains the
002797  ** root page number of the index.  If memRootPage is negative, then
002798  ** the index already exists and must be cleared before being refilled and
002799  ** the root page number of the index is taken from pIndex->tnum.
002800  */
002801  static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
002802    Table *pTab = pIndex->pTable;  /* The table that is indexed */
002803    int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
002804    int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
002805    int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
002806    int addr1;                     /* Address of top of loop */
002807    int addr2;                     /* Address to jump to for next iteration */
002808    int tnum;                      /* Root page of index */
002809    int iPartIdxLabel;             /* Jump to this label to skip a row */
002810    Vdbe *v;                       /* Generate code into this virtual machine */
002811    KeyInfo *pKey;                 /* KeyInfo for index */
002812    int regRecord;                 /* Register holding assembled index record */
002813    sqlite3 *db = pParse->db;      /* The database connection */
002814    int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
002815  
002816  #ifndef SQLITE_OMIT_AUTHORIZATION
002817    if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
002818        db->aDb[iDb].zDbSName ) ){
002819      return;
002820    }
002821  #endif
002822  
002823    /* Require a write-lock on the table to perform this operation */
002824    sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
002825  
002826    v = sqlite3GetVdbe(pParse);
002827    if( v==0 ) return;
002828    if( memRootPage>=0 ){
002829      tnum = memRootPage;
002830    }else{
002831      tnum = pIndex->tnum;
002832    }
002833    pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
002834    assert( pKey!=0 || db->mallocFailed || pParse->nErr );
002835  
002836    /* Open the sorter cursor if we are to use one. */
002837    iSorter = pParse->nTab++;
002838    sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
002839                      sqlite3KeyInfoRef(pKey), P4_KEYINFO);
002840  
002841    /* Open the table. Loop through all rows of the table, inserting index
002842    ** records into the sorter. */
002843    sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
002844    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
002845    regRecord = sqlite3GetTempReg(pParse);
002846    sqlite3MultiWrite(pParse);
002847  
002848    sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
002849    sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
002850    sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
002851    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
002852    sqlite3VdbeJumpHere(v, addr1);
002853    if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
002854    sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
002855                      (char *)pKey, P4_KEYINFO);
002856    sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
002857  
002858    addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
002859    if( IsUniqueIndex(pIndex) ){
002860      int j2 = sqlite3VdbeGoto(v, 1);
002861      addr2 = sqlite3VdbeCurrentAddr(v);
002862      sqlite3VdbeVerifyAbortable(v, OE_Abort);
002863      sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
002864                           pIndex->nKeyCol); VdbeCoverage(v);
002865      sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
002866      sqlite3VdbeJumpHere(v, j2);
002867    }else{
002868      addr2 = sqlite3VdbeCurrentAddr(v);
002869    }
002870    sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
002871    sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
002872    sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
002873    sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
002874    sqlite3ReleaseTempReg(pParse, regRecord);
002875    sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
002876    sqlite3VdbeJumpHere(v, addr1);
002877  
002878    sqlite3VdbeAddOp1(v, OP_Close, iTab);
002879    sqlite3VdbeAddOp1(v, OP_Close, iIdx);
002880    sqlite3VdbeAddOp1(v, OP_Close, iSorter);
002881  }
002882  
002883  /*
002884  ** Allocate heap space to hold an Index object with nCol columns.
002885  **
002886  ** Increase the allocation size to provide an extra nExtra bytes
002887  ** of 8-byte aligned space after the Index object and return a
002888  ** pointer to this extra space in *ppExtra.
002889  */
002890  Index *sqlite3AllocateIndexObject(
002891    sqlite3 *db,         /* Database connection */
002892    i16 nCol,            /* Total number of columns in the index */
002893    int nExtra,          /* Number of bytes of extra space to alloc */
002894    char **ppExtra       /* Pointer to the "extra" space */
002895  ){
002896    Index *p;            /* Allocated index object */
002897    int nByte;           /* Bytes of space for Index object + arrays */
002898  
002899    nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
002900            ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
002901            ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
002902                   sizeof(i16)*nCol +            /* Index.aiColumn   */
002903                   sizeof(u8)*nCol);             /* Index.aSortOrder */
002904    p = sqlite3DbMallocZero(db, nByte + nExtra);
002905    if( p ){
002906      char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
002907      p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
002908      p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
002909      p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
002910      p->aSortOrder = (u8*)pExtra;
002911      p->nColumn = nCol;
002912      p->nKeyCol = nCol - 1;
002913      *ppExtra = ((char*)p) + nByte;
002914    }
002915    return p;
002916  }
002917  
002918  /*
002919  ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
002920  ** and pTblList is the name of the table that is to be indexed.  Both will 
002921  ** be NULL for a primary key or an index that is created to satisfy a
002922  ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
002923  ** as the table to be indexed.  pParse->pNewTable is a table that is
002924  ** currently being constructed by a CREATE TABLE statement.
002925  **
002926  ** pList is a list of columns to be indexed.  pList will be NULL if this
002927  ** is a primary key or unique-constraint on the most recent column added
002928  ** to the table currently under construction.  
002929  */
002930  void sqlite3CreateIndex(
002931    Parse *pParse,     /* All information about this parse */
002932    Token *pName1,     /* First part of index name. May be NULL */
002933    Token *pName2,     /* Second part of index name. May be NULL */
002934    SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
002935    ExprList *pList,   /* A list of columns to be indexed */
002936    int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
002937    Token *pStart,     /* The CREATE token that begins this statement */
002938    Expr *pPIWhere,    /* WHERE clause for partial indices */
002939    int sortOrder,     /* Sort order of primary key when pList==NULL */
002940    int ifNotExist,    /* Omit error if index already exists */
002941    u8 idxType         /* The index type */
002942  ){
002943    Table *pTab = 0;     /* Table to be indexed */
002944    Index *pIndex = 0;   /* The index to be created */
002945    char *zName = 0;     /* Name of the index */
002946    int nName;           /* Number of characters in zName */
002947    int i, j;
002948    DbFixer sFix;        /* For assigning database names to pTable */
002949    int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
002950    sqlite3 *db = pParse->db;
002951    Db *pDb;             /* The specific table containing the indexed database */
002952    int iDb;             /* Index of the database that is being written */
002953    Token *pName = 0;    /* Unqualified name of the index to create */
002954    struct ExprList_item *pListItem; /* For looping over pList */
002955    int nExtra = 0;                  /* Space allocated for zExtra[] */
002956    int nExtraCol;                   /* Number of extra columns needed */
002957    char *zExtra = 0;                /* Extra space after the Index object */
002958    Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
002959  
002960    if( db->mallocFailed || pParse->nErr>0 ){
002961      goto exit_create_index;
002962    }
002963    if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
002964      goto exit_create_index;
002965    }
002966    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
002967      goto exit_create_index;
002968    }
002969  
002970    /*
002971    ** Find the table that is to be indexed.  Return early if not found.
002972    */
002973    if( pTblName!=0 ){
002974  
002975      /* Use the two-part index name to determine the database 
002976      ** to search for the table. 'Fix' the table name to this db
002977      ** before looking up the table.
002978      */
002979      assert( pName1 && pName2 );
002980      iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
002981      if( iDb<0 ) goto exit_create_index;
002982      assert( pName && pName->z );
002983  
002984  #ifndef SQLITE_OMIT_TEMPDB
002985      /* If the index name was unqualified, check if the table
002986      ** is a temp table. If so, set the database to 1. Do not do this
002987      ** if initialising a database schema.
002988      */
002989      if( !db->init.busy ){
002990        pTab = sqlite3SrcListLookup(pParse, pTblName);
002991        if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
002992          iDb = 1;
002993        }
002994      }
002995  #endif
002996  
002997      sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
002998      if( sqlite3FixSrcList(&sFix, pTblName) ){
002999        /* Because the parser constructs pTblName from a single identifier,
003000        ** sqlite3FixSrcList can never fail. */
003001        assert(0);
003002      }
003003      pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
003004      assert( db->mallocFailed==0 || pTab==0 );
003005      if( pTab==0 ) goto exit_create_index;
003006      if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
003007        sqlite3ErrorMsg(pParse, 
003008             "cannot create a TEMP index on non-TEMP table \"%s\"",
003009             pTab->zName);
003010        goto exit_create_index;
003011      }
003012      if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
003013    }else{
003014      assert( pName==0 );
003015      assert( pStart==0 );
003016      pTab = pParse->pNewTable;
003017      if( !pTab ) goto exit_create_index;
003018      iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
003019    }
003020    pDb = &db->aDb[iDb];
003021  
003022    assert( pTab!=0 );
003023    assert( pParse->nErr==0 );
003024    if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
003025         && db->init.busy==0
003026  #if SQLITE_USER_AUTHENTICATION
003027         && sqlite3UserAuthTable(pTab->zName)==0
003028  #endif
003029  #ifdef SQLITE_ALLOW_SQLITE_MASTER_INDEX
003030         && sqlite3StrICmp(&pTab->zName[7],"master")!=0
003031  #endif
003032         && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0
003033   ){
003034      sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
003035      goto exit_create_index;
003036    }
003037  #ifndef SQLITE_OMIT_VIEW
003038    if( pTab->pSelect ){
003039      sqlite3ErrorMsg(pParse, "views may not be indexed");
003040      goto exit_create_index;
003041    }
003042  #endif
003043  #ifndef SQLITE_OMIT_VIRTUALTABLE
003044    if( IsVirtual(pTab) ){
003045      sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
003046      goto exit_create_index;
003047    }
003048  #endif
003049  
003050    /*
003051    ** Find the name of the index.  Make sure there is not already another
003052    ** index or table with the same name.  
003053    **
003054    ** Exception:  If we are reading the names of permanent indices from the
003055    ** sqlite_master table (because some other process changed the schema) and
003056    ** one of the index names collides with the name of a temporary table or
003057    ** index, then we will continue to process this index.
003058    **
003059    ** If pName==0 it means that we are
003060    ** dealing with a primary key or UNIQUE constraint.  We have to invent our
003061    ** own name.
003062    */
003063    if( pName ){
003064      zName = sqlite3NameFromToken(db, pName);
003065      if( zName==0 ) goto exit_create_index;
003066      assert( pName->z!=0 );
003067      if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
003068        goto exit_create_index;
003069      }
003070      if( !db->init.busy ){
003071        if( sqlite3FindTable(db, zName, 0)!=0 ){
003072          sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
003073          goto exit_create_index;
003074        }
003075      }
003076      if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
003077        if( !ifNotExist ){
003078          sqlite3ErrorMsg(pParse, "index %s already exists", zName);
003079        }else{
003080          assert( !db->init.busy );
003081          sqlite3CodeVerifySchema(pParse, iDb);
003082        }
003083        goto exit_create_index;
003084      }
003085    }else{
003086      int n;
003087      Index *pLoop;
003088      for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
003089      zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
003090      if( zName==0 ){
003091        goto exit_create_index;
003092      }
003093  
003094      /* Automatic index names generated from within sqlite3_declare_vtab()
003095      ** must have names that are distinct from normal automatic index names.
003096      ** The following statement converts "sqlite3_autoindex..." into
003097      ** "sqlite3_butoindex..." in order to make the names distinct.
003098      ** The "vtab_err.test" test demonstrates the need of this statement. */
003099      if( IN_DECLARE_VTAB ) zName[7]++;
003100    }
003101  
003102    /* Check for authorization to create an index.
003103    */
003104  #ifndef SQLITE_OMIT_AUTHORIZATION
003105    {
003106      const char *zDb = pDb->zDbSName;
003107      if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
003108        goto exit_create_index;
003109      }
003110      i = SQLITE_CREATE_INDEX;
003111      if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
003112      if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
003113        goto exit_create_index;
003114      }
003115    }
003116  #endif
003117  
003118    /* If pList==0, it means this routine was called to make a primary
003119    ** key out of the last column added to the table under construction.
003120    ** So create a fake list to simulate this.
003121    */
003122    if( pList==0 ){
003123      Token prevCol;
003124      Column *pCol = &pTab->aCol[pTab->nCol-1];
003125      pCol->colFlags |= COLFLAG_UNIQUE;
003126      sqlite3TokenInit(&prevCol, pCol->zName);
003127      pList = sqlite3ExprListAppend(pParse, 0,
003128                sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
003129      if( pList==0 ) goto exit_create_index;
003130      assert( pList->nExpr==1 );
003131      sqlite3ExprListSetSortOrder(pList, sortOrder);
003132    }else{
003133      sqlite3ExprListCheckLength(pParse, pList, "index");
003134    }
003135  
003136    /* Figure out how many bytes of space are required to store explicitly
003137    ** specified collation sequence names.
003138    */
003139    for(i=0; i<pList->nExpr; i++){
003140      Expr *pExpr = pList->a[i].pExpr;
003141      assert( pExpr!=0 );
003142      if( pExpr->op==TK_COLLATE ){
003143        nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
003144      }
003145    }
003146  
003147    /* 
003148    ** Allocate the index structure. 
003149    */
003150    nName = sqlite3Strlen30(zName);
003151    nExtraCol = pPk ? pPk->nKeyCol : 1;
003152    pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
003153                                        nName + nExtra + 1, &zExtra);
003154    if( db->mallocFailed ){
003155      goto exit_create_index;
003156    }
003157    assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
003158    assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
003159    pIndex->zName = zExtra;
003160    zExtra += nName + 1;
003161    memcpy(pIndex->zName, zName, nName+1);
003162    pIndex->pTable = pTab;
003163    pIndex->onError = (u8)onError;
003164    pIndex->uniqNotNull = onError!=OE_None;
003165    pIndex->idxType = idxType;
003166    pIndex->pSchema = db->aDb[iDb].pSchema;
003167    pIndex->nKeyCol = pList->nExpr;
003168    if( pPIWhere ){
003169      sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
003170      pIndex->pPartIdxWhere = pPIWhere;
003171      pPIWhere = 0;
003172    }
003173    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
003174  
003175    /* Check to see if we should honor DESC requests on index columns
003176    */
003177    if( pDb->pSchema->file_format>=4 ){
003178      sortOrderMask = -1;   /* Honor DESC */
003179    }else{
003180      sortOrderMask = 0;    /* Ignore DESC */
003181    }
003182  
003183    /* Analyze the list of expressions that form the terms of the index and
003184    ** report any errors.  In the common case where the expression is exactly
003185    ** a table column, store that column in aiColumn[].  For general expressions,
003186    ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
003187    **
003188    ** TODO: Issue a warning if two or more columns of the index are identical.
003189    ** TODO: Issue a warning if the table primary key is used as part of the
003190    ** index key.
003191    */
003192    for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
003193      Expr *pCExpr;                  /* The i-th index expression */
003194      int requestedSortOrder;        /* ASC or DESC on the i-th expression */
003195      const char *zColl;             /* Collation sequence name */
003196  
003197      sqlite3StringToId(pListItem->pExpr);
003198      sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
003199      if( pParse->nErr ) goto exit_create_index;
003200      pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
003201      if( pCExpr->op!=TK_COLUMN ){
003202        if( pTab==pParse->pNewTable ){
003203          sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
003204                                  "UNIQUE constraints");
003205          goto exit_create_index;
003206        }
003207        if( pIndex->aColExpr==0 ){
003208          ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
003209          pIndex->aColExpr = pCopy;
003210          if( !db->mallocFailed ){
003211            assert( pCopy!=0 );
003212            pListItem = &pCopy->a[i];
003213          }
003214        }
003215        j = XN_EXPR;
003216        pIndex->aiColumn[i] = XN_EXPR;
003217        pIndex->uniqNotNull = 0;
003218      }else{
003219        j = pCExpr->iColumn;
003220        assert( j<=0x7fff );
003221        if( j<0 ){
003222          j = pTab->iPKey;
003223        }else if( pTab->aCol[j].notNull==0 ){
003224          pIndex->uniqNotNull = 0;
003225        }
003226        pIndex->aiColumn[i] = (i16)j;
003227      }
003228      zColl = 0;
003229      if( pListItem->pExpr->op==TK_COLLATE ){
003230        int nColl;
003231        zColl = pListItem->pExpr->u.zToken;
003232        nColl = sqlite3Strlen30(zColl) + 1;
003233        assert( nExtra>=nColl );
003234        memcpy(zExtra, zColl, nColl);
003235        zColl = zExtra;
003236        zExtra += nColl;
003237        nExtra -= nColl;
003238      }else if( j>=0 ){
003239        zColl = pTab->aCol[j].zColl;
003240      }
003241      if( !zColl ) zColl = sqlite3StrBINARY;
003242      if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
003243        goto exit_create_index;
003244      }
003245      pIndex->azColl[i] = zColl;
003246      requestedSortOrder = pListItem->sortOrder & sortOrderMask;
003247      pIndex->aSortOrder[i] = (u8)requestedSortOrder;
003248    }
003249  
003250    /* Append the table key to the end of the index.  For WITHOUT ROWID
003251    ** tables (when pPk!=0) this will be the declared PRIMARY KEY.  For
003252    ** normal tables (when pPk==0) this will be the rowid.
003253    */
003254    if( pPk ){
003255      for(j=0; j<pPk->nKeyCol; j++){
003256        int x = pPk->aiColumn[j];
003257        assert( x>=0 );
003258        if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
003259          pIndex->nColumn--; 
003260        }else{
003261          pIndex->aiColumn[i] = x;
003262          pIndex->azColl[i] = pPk->azColl[j];
003263          pIndex->aSortOrder[i] = pPk->aSortOrder[j];
003264          i++;
003265        }
003266      }
003267      assert( i==pIndex->nColumn );
003268    }else{
003269      pIndex->aiColumn[i] = XN_ROWID;
003270      pIndex->azColl[i] = sqlite3StrBINARY;
003271    }
003272    sqlite3DefaultRowEst(pIndex);
003273    if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
003274  
003275    /* If this index contains every column of its table, then mark
003276    ** it as a covering index */
003277    assert( HasRowid(pTab) 
003278        || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
003279    if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
003280      pIndex->isCovering = 1;
003281      for(j=0; j<pTab->nCol; j++){
003282        if( j==pTab->iPKey ) continue;
003283        if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
003284        pIndex->isCovering = 0;
003285        break;
003286      }
003287    }
003288  
003289    if( pTab==pParse->pNewTable ){
003290      /* This routine has been called to create an automatic index as a
003291      ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
003292      ** a PRIMARY KEY or UNIQUE clause following the column definitions.
003293      ** i.e. one of:
003294      **
003295      ** CREATE TABLE t(x PRIMARY KEY, y);
003296      ** CREATE TABLE t(x, y, UNIQUE(x, y));
003297      **
003298      ** Either way, check to see if the table already has such an index. If
003299      ** so, don't bother creating this one. This only applies to
003300      ** automatically created indices. Users can do as they wish with
003301      ** explicit indices.
003302      **
003303      ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
003304      ** (and thus suppressing the second one) even if they have different
003305      ** sort orders.
003306      **
003307      ** If there are different collating sequences or if the columns of
003308      ** the constraint occur in different orders, then the constraints are
003309      ** considered distinct and both result in separate indices.
003310      */
003311      Index *pIdx;
003312      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
003313        int k;
003314        assert( IsUniqueIndex(pIdx) );
003315        assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
003316        assert( IsUniqueIndex(pIndex) );
003317  
003318        if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
003319        for(k=0; k<pIdx->nKeyCol; k++){
003320          const char *z1;
003321          const char *z2;
003322          assert( pIdx->aiColumn[k]>=0 );
003323          if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
003324          z1 = pIdx->azColl[k];
003325          z2 = pIndex->azColl[k];
003326          if( sqlite3StrICmp(z1, z2) ) break;
003327        }
003328        if( k==pIdx->nKeyCol ){
003329          if( pIdx->onError!=pIndex->onError ){
003330            /* This constraint creates the same index as a previous
003331            ** constraint specified somewhere in the CREATE TABLE statement.
003332            ** However the ON CONFLICT clauses are different. If both this 
003333            ** constraint and the previous equivalent constraint have explicit
003334            ** ON CONFLICT clauses this is an error. Otherwise, use the
003335            ** explicitly specified behavior for the index.
003336            */
003337            if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
003338              sqlite3ErrorMsg(pParse, 
003339                  "conflicting ON CONFLICT clauses specified", 0);
003340            }
003341            if( pIdx->onError==OE_Default ){
003342              pIdx->onError = pIndex->onError;
003343            }
003344          }
003345          if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
003346          goto exit_create_index;
003347        }
003348      }
003349    }
003350  
003351    /* Link the new Index structure to its table and to the other
003352    ** in-memory database structures. 
003353    */
003354    assert( pParse->nErr==0 );
003355    if( db->init.busy ){
003356      Index *p;
003357      assert( !IN_DECLARE_VTAB );
003358      assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
003359      p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
003360                            pIndex->zName, pIndex);
003361      if( p ){
003362        assert( p==pIndex );  /* Malloc must have failed */
003363        sqlite3OomFault(db);
003364        goto exit_create_index;
003365      }
003366      db->mDbFlags |= DBFLAG_SchemaChange;
003367      if( pTblName!=0 ){
003368        pIndex->tnum = db->init.newTnum;
003369      }
003370    }
003371  
003372    /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
003373    ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
003374    ** emit code to allocate the index rootpage on disk and make an entry for
003375    ** the index in the sqlite_master table and populate the index with
003376    ** content.  But, do not do this if we are simply reading the sqlite_master
003377    ** table to parse the schema, or if this index is the PRIMARY KEY index
003378    ** of a WITHOUT ROWID table.
003379    **
003380    ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
003381    ** or UNIQUE index in a CREATE TABLE statement.  Since the table
003382    ** has just been created, it contains no data and the index initialization
003383    ** step can be skipped.
003384    */
003385    else if( HasRowid(pTab) || pTblName!=0 ){
003386      Vdbe *v;
003387      char *zStmt;
003388      int iMem = ++pParse->nMem;
003389  
003390      v = sqlite3GetVdbe(pParse);
003391      if( v==0 ) goto exit_create_index;
003392  
003393      sqlite3BeginWriteOperation(pParse, 1, iDb);
003394  
003395      /* Create the rootpage for the index using CreateIndex. But before
003396      ** doing so, code a Noop instruction and store its address in 
003397      ** Index.tnum. This is required in case this index is actually a 
003398      ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In 
003399      ** that case the convertToWithoutRowidTable() routine will replace
003400      ** the Noop with a Goto to jump over the VDBE code generated below. */
003401      pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
003402      sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
003403  
003404      /* Gather the complete text of the CREATE INDEX statement into
003405      ** the zStmt variable
003406      */
003407      if( pStart ){
003408        int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
003409        if( pName->z[n-1]==';' ) n--;
003410        /* A named index with an explicit CREATE INDEX statement */
003411        zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
003412          onError==OE_None ? "" : " UNIQUE", n, pName->z);
003413      }else{
003414        /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
003415        /* zStmt = sqlite3MPrintf(""); */
003416        zStmt = 0;
003417      }
003418  
003419      /* Add an entry in sqlite_master for this index
003420      */
003421      sqlite3NestedParse(pParse, 
003422          "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
003423          db->aDb[iDb].zDbSName, MASTER_NAME,
003424          pIndex->zName,
003425          pTab->zName,
003426          iMem,
003427          zStmt
003428      );
003429      sqlite3DbFree(db, zStmt);
003430  
003431      /* Fill the index with data and reparse the schema. Code an OP_Expire
003432      ** to invalidate all pre-compiled statements.
003433      */
003434      if( pTblName ){
003435        sqlite3RefillIndex(pParse, pIndex, iMem);
003436        sqlite3ChangeCookie(pParse, iDb);
003437        sqlite3VdbeAddParseSchemaOp(v, iDb,
003438           sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
003439        sqlite3VdbeAddOp0(v, OP_Expire);
003440      }
003441  
003442      sqlite3VdbeJumpHere(v, pIndex->tnum);
003443    }
003444  
003445    /* When adding an index to the list of indices for a table, make
003446    ** sure all indices labeled OE_Replace come after all those labeled
003447    ** OE_Ignore.  This is necessary for the correct constraint check
003448    ** processing (in sqlite3GenerateConstraintChecks()) as part of
003449    ** UPDATE and INSERT statements.  
003450    */
003451    if( db->init.busy || pTblName==0 ){
003452      if( onError!=OE_Replace || pTab->pIndex==0
003453           || pTab->pIndex->onError==OE_Replace){
003454        pIndex->pNext = pTab->pIndex;
003455        pTab->pIndex = pIndex;
003456      }else{
003457        Index *pOther = pTab->pIndex;
003458        while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
003459          pOther = pOther->pNext;
003460        }
003461        pIndex->pNext = pOther->pNext;
003462        pOther->pNext = pIndex;
003463      }
003464      pIndex = 0;
003465    }
003466  
003467    /* Clean up before exiting */
003468  exit_create_index:
003469    if( pIndex ) freeIndex(db, pIndex);
003470    sqlite3ExprDelete(db, pPIWhere);
003471    sqlite3ExprListDelete(db, pList);
003472    sqlite3SrcListDelete(db, pTblName);
003473    sqlite3DbFree(db, zName);
003474  }
003475  
003476  /*
003477  ** Fill the Index.aiRowEst[] array with default information - information
003478  ** to be used when we have not run the ANALYZE command.
003479  **
003480  ** aiRowEst[0] is supposed to contain the number of elements in the index.
003481  ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
003482  ** number of rows in the table that match any particular value of the
003483  ** first column of the index.  aiRowEst[2] is an estimate of the number
003484  ** of rows that match any particular combination of the first 2 columns
003485  ** of the index.  And so forth.  It must always be the case that
003486  *
003487  **           aiRowEst[N]<=aiRowEst[N-1]
003488  **           aiRowEst[N]>=1
003489  **
003490  ** Apart from that, we have little to go on besides intuition as to
003491  ** how aiRowEst[] should be initialized.  The numbers generated here
003492  ** are based on typical values found in actual indices.
003493  */
003494  void sqlite3DefaultRowEst(Index *pIdx){
003495    /*                10,  9,  8,  7,  6 */
003496    LogEst aVal[] = { 33, 32, 30, 28, 26 };
003497    LogEst *a = pIdx->aiRowLogEst;
003498    int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
003499    int i;
003500  
003501    /* Indexes with default row estimates should not have stat1 data */
003502    assert( !pIdx->hasStat1 );
003503  
003504    /* Set the first entry (number of rows in the index) to the estimated 
003505    ** number of rows in the table, or half the number of rows in the table
003506    ** for a partial index.   But do not let the estimate drop below 10. */
003507    a[0] = pIdx->pTable->nRowLogEst;
003508    if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10;  assert( 10==sqlite3LogEst(2) );
003509    if( a[0]<33 ) a[0] = 33;                  assert( 33==sqlite3LogEst(10) );
003510  
003511    /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
003512    ** 6 and each subsequent value (if any) is 5.  */
003513    memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
003514    for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
003515      a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
003516    }
003517  
003518    assert( 0==sqlite3LogEst(1) );
003519    if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
003520  }
003521  
003522  /*
003523  ** This routine will drop an existing named index.  This routine
003524  ** implements the DROP INDEX statement.
003525  */
003526  void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
003527    Index *pIndex;
003528    Vdbe *v;
003529    sqlite3 *db = pParse->db;
003530    int iDb;
003531  
003532    assert( pParse->nErr==0 );   /* Never called with prior errors */
003533    if( db->mallocFailed ){
003534      goto exit_drop_index;
003535    }
003536    assert( pName->nSrc==1 );
003537    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
003538      goto exit_drop_index;
003539    }
003540    pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
003541    if( pIndex==0 ){
003542      if( !ifExists ){
003543        sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
003544      }else{
003545        sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
003546      }
003547      pParse->checkSchema = 1;
003548      goto exit_drop_index;
003549    }
003550    if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
003551      sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
003552        "or PRIMARY KEY constraint cannot be dropped", 0);
003553      goto exit_drop_index;
003554    }
003555    iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
003556  #ifndef SQLITE_OMIT_AUTHORIZATION
003557    {
003558      int code = SQLITE_DROP_INDEX;
003559      Table *pTab = pIndex->pTable;
003560      const char *zDb = db->aDb[iDb].zDbSName;
003561      const char *zTab = SCHEMA_TABLE(iDb);
003562      if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
003563        goto exit_drop_index;
003564      }
003565      if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
003566      if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
003567        goto exit_drop_index;
003568      }
003569    }
003570  #endif
003571  
003572    /* Generate code to remove the index and from the master table */
003573    v = sqlite3GetVdbe(pParse);
003574    if( v ){
003575      sqlite3BeginWriteOperation(pParse, 1, iDb);
003576      sqlite3NestedParse(pParse,
003577         "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
003578         db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
003579      );
003580      sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
003581      sqlite3ChangeCookie(pParse, iDb);
003582      destroyRootPage(pParse, pIndex->tnum, iDb);
003583      sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
003584    }
003585  
003586  exit_drop_index:
003587    sqlite3SrcListDelete(db, pName);
003588  }
003589  
003590  /*
003591  ** pArray is a pointer to an array of objects. Each object in the
003592  ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
003593  ** to extend the array so that there is space for a new object at the end.
003594  **
003595  ** When this function is called, *pnEntry contains the current size of
003596  ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
003597  ** in total).
003598  **
003599  ** If the realloc() is successful (i.e. if no OOM condition occurs), the
003600  ** space allocated for the new object is zeroed, *pnEntry updated to
003601  ** reflect the new size of the array and a pointer to the new allocation
003602  ** returned. *pIdx is set to the index of the new array entry in this case.
003603  **
003604  ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
003605  ** unchanged and a copy of pArray returned.
003606  */
003607  void *sqlite3ArrayAllocate(
003608    sqlite3 *db,      /* Connection to notify of malloc failures */
003609    void *pArray,     /* Array of objects.  Might be reallocated */
003610    int szEntry,      /* Size of each object in the array */
003611    int *pnEntry,     /* Number of objects currently in use */
003612    int *pIdx         /* Write the index of a new slot here */
003613  ){
003614    char *z;
003615    int n = *pnEntry;
003616    if( (n & (n-1))==0 ){
003617      int sz = (n==0) ? 1 : 2*n;
003618      void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
003619      if( pNew==0 ){
003620        *pIdx = -1;
003621        return pArray;
003622      }
003623      pArray = pNew;
003624    }
003625    z = (char*)pArray;
003626    memset(&z[n * szEntry], 0, szEntry);
003627    *pIdx = n;
003628    ++*pnEntry;
003629    return pArray;
003630  }
003631  
003632  /*
003633  ** Append a new element to the given IdList.  Create a new IdList if
003634  ** need be.
003635  **
003636  ** A new IdList is returned, or NULL if malloc() fails.
003637  */
003638  IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
003639    int i;
003640    if( pList==0 ){
003641      pList = sqlite3DbMallocZero(db, sizeof(IdList) );
003642      if( pList==0 ) return 0;
003643    }
003644    pList->a = sqlite3ArrayAllocate(
003645        db,
003646        pList->a,
003647        sizeof(pList->a[0]),
003648        &pList->nId,
003649        &i
003650    );
003651    if( i<0 ){
003652      sqlite3IdListDelete(db, pList);
003653      return 0;
003654    }
003655    pList->a[i].zName = sqlite3NameFromToken(db, pToken);
003656    return pList;
003657  }
003658  
003659  /*
003660  ** Delete an IdList.
003661  */
003662  void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
003663    int i;
003664    if( pList==0 ) return;
003665    for(i=0; i<pList->nId; i++){
003666      sqlite3DbFree(db, pList->a[i].zName);
003667    }
003668    sqlite3DbFree(db, pList->a);
003669    sqlite3DbFreeNN(db, pList);
003670  }
003671  
003672  /*
003673  ** Return the index in pList of the identifier named zId.  Return -1
003674  ** if not found.
003675  */
003676  int sqlite3IdListIndex(IdList *pList, const char *zName){
003677    int i;
003678    if( pList==0 ) return -1;
003679    for(i=0; i<pList->nId; i++){
003680      if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
003681    }
003682    return -1;
003683  }
003684  
003685  /*
003686  ** Expand the space allocated for the given SrcList object by
003687  ** creating nExtra new slots beginning at iStart.  iStart is zero based.
003688  ** New slots are zeroed.
003689  **
003690  ** For example, suppose a SrcList initially contains two entries: A,B.
003691  ** To append 3 new entries onto the end, do this:
003692  **
003693  **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
003694  **
003695  ** After the call above it would contain:  A, B, nil, nil, nil.
003696  ** If the iStart argument had been 1 instead of 2, then the result
003697  ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
003698  ** the iStart value would be 0.  The result then would
003699  ** be: nil, nil, nil, A, B.
003700  **
003701  ** If a memory allocation fails the SrcList is unchanged.  The
003702  ** db->mallocFailed flag will be set to true.
003703  */
003704  SrcList *sqlite3SrcListEnlarge(
003705    sqlite3 *db,       /* Database connection to notify of OOM errors */
003706    SrcList *pSrc,     /* The SrcList to be enlarged */
003707    int nExtra,        /* Number of new slots to add to pSrc->a[] */
003708    int iStart         /* Index in pSrc->a[] of first new slot */
003709  ){
003710    int i;
003711  
003712    /* Sanity checking on calling parameters */
003713    assert( iStart>=0 );
003714    assert( nExtra>=1 );
003715    assert( pSrc!=0 );
003716    assert( iStart<=pSrc->nSrc );
003717  
003718    /* Allocate additional space if needed */
003719    if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
003720      SrcList *pNew;
003721      int nAlloc = pSrc->nSrc*2+nExtra;
003722      int nGot;
003723      pNew = sqlite3DbRealloc(db, pSrc,
003724                 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
003725      if( pNew==0 ){
003726        assert( db->mallocFailed );
003727        return pSrc;
003728      }
003729      pSrc = pNew;
003730      nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
003731      pSrc->nAlloc = nGot;
003732    }
003733  
003734    /* Move existing slots that come after the newly inserted slots
003735    ** out of the way */
003736    for(i=pSrc->nSrc-1; i>=iStart; i--){
003737      pSrc->a[i+nExtra] = pSrc->a[i];
003738    }
003739    pSrc->nSrc += nExtra;
003740  
003741    /* Zero the newly allocated slots */
003742    memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
003743    for(i=iStart; i<iStart+nExtra; i++){
003744      pSrc->a[i].iCursor = -1;
003745    }
003746  
003747    /* Return a pointer to the enlarged SrcList */
003748    return pSrc;
003749  }
003750  
003751  
003752  /*
003753  ** Append a new table name to the given SrcList.  Create a new SrcList if
003754  ** need be.  A new entry is created in the SrcList even if pTable is NULL.
003755  **
003756  ** A SrcList is returned, or NULL if there is an OOM error.  The returned
003757  ** SrcList might be the same as the SrcList that was input or it might be
003758  ** a new one.  If an OOM error does occurs, then the prior value of pList
003759  ** that is input to this routine is automatically freed.
003760  **
003761  ** If pDatabase is not null, it means that the table has an optional
003762  ** database name prefix.  Like this:  "database.table".  The pDatabase
003763  ** points to the table name and the pTable points to the database name.
003764  ** The SrcList.a[].zName field is filled with the table name which might
003765  ** come from pTable (if pDatabase is NULL) or from pDatabase.  
003766  ** SrcList.a[].zDatabase is filled with the database name from pTable,
003767  ** or with NULL if no database is specified.
003768  **
003769  ** In other words, if call like this:
003770  **
003771  **         sqlite3SrcListAppend(D,A,B,0);
003772  **
003773  ** Then B is a table name and the database name is unspecified.  If called
003774  ** like this:
003775  **
003776  **         sqlite3SrcListAppend(D,A,B,C);
003777  **
003778  ** Then C is the table name and B is the database name.  If C is defined
003779  ** then so is B.  In other words, we never have a case where:
003780  **
003781  **         sqlite3SrcListAppend(D,A,0,C);
003782  **
003783  ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
003784  ** before being added to the SrcList.
003785  */
003786  SrcList *sqlite3SrcListAppend(
003787    sqlite3 *db,        /* Connection to notify of malloc failures */
003788    SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
003789    Token *pTable,      /* Table to append */
003790    Token *pDatabase    /* Database of the table */
003791  ){
003792    struct SrcList_item *pItem;
003793    assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
003794    assert( db!=0 );
003795    if( pList==0 ){
003796      pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
003797      if( pList==0 ) return 0;
003798      pList->nAlloc = 1;
003799      pList->nSrc = 1;
003800      memset(&pList->a[0], 0, sizeof(pList->a[0]));
003801      pList->a[0].iCursor = -1;
003802    }else{
003803      pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
003804    }
003805    if( db->mallocFailed ){
003806      sqlite3SrcListDelete(db, pList);
003807      return 0;
003808    }
003809    pItem = &pList->a[pList->nSrc-1];
003810    if( pDatabase && pDatabase->z==0 ){
003811      pDatabase = 0;
003812    }
003813    if( pDatabase ){
003814      pItem->zName = sqlite3NameFromToken(db, pDatabase);
003815      pItem->zDatabase = sqlite3NameFromToken(db, pTable);
003816    }else{
003817      pItem->zName = sqlite3NameFromToken(db, pTable);
003818      pItem->zDatabase = 0;
003819    }
003820    return pList;
003821  }
003822  
003823  /*
003824  ** Assign VdbeCursor index numbers to all tables in a SrcList
003825  */
003826  void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
003827    int i;
003828    struct SrcList_item *pItem;
003829    assert(pList || pParse->db->mallocFailed );
003830    if( pList ){
003831      for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
003832        if( pItem->iCursor>=0 ) break;
003833        pItem->iCursor = pParse->nTab++;
003834        if( pItem->pSelect ){
003835          sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
003836        }
003837      }
003838    }
003839  }
003840  
003841  /*
003842  ** Delete an entire SrcList including all its substructure.
003843  */
003844  void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
003845    int i;
003846    struct SrcList_item *pItem;
003847    if( pList==0 ) return;
003848    for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
003849      sqlite3DbFree(db, pItem->zDatabase);
003850      sqlite3DbFree(db, pItem->zName);
003851      sqlite3DbFree(db, pItem->zAlias);
003852      if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
003853      if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
003854      sqlite3DeleteTable(db, pItem->pTab);
003855      sqlite3SelectDelete(db, pItem->pSelect);
003856      sqlite3ExprDelete(db, pItem->pOn);
003857      sqlite3IdListDelete(db, pItem->pUsing);
003858    }
003859    sqlite3DbFreeNN(db, pList);
003860  }
003861  
003862  /*
003863  ** This routine is called by the parser to add a new term to the
003864  ** end of a growing FROM clause.  The "p" parameter is the part of
003865  ** the FROM clause that has already been constructed.  "p" is NULL
003866  ** if this is the first term of the FROM clause.  pTable and pDatabase
003867  ** are the name of the table and database named in the FROM clause term.
003868  ** pDatabase is NULL if the database name qualifier is missing - the
003869  ** usual case.  If the term has an alias, then pAlias points to the
003870  ** alias token.  If the term is a subquery, then pSubquery is the
003871  ** SELECT statement that the subquery encodes.  The pTable and
003872  ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
003873  ** parameters are the content of the ON and USING clauses.
003874  **
003875  ** Return a new SrcList which encodes is the FROM with the new
003876  ** term added.
003877  */
003878  SrcList *sqlite3SrcListAppendFromTerm(
003879    Parse *pParse,          /* Parsing context */
003880    SrcList *p,             /* The left part of the FROM clause already seen */
003881    Token *pTable,          /* Name of the table to add to the FROM clause */
003882    Token *pDatabase,       /* Name of the database containing pTable */
003883    Token *pAlias,          /* The right-hand side of the AS subexpression */
003884    Select *pSubquery,      /* A subquery used in place of a table name */
003885    Expr *pOn,              /* The ON clause of a join */
003886    IdList *pUsing          /* The USING clause of a join */
003887  ){
003888    struct SrcList_item *pItem;
003889    sqlite3 *db = pParse->db;
003890    if( !p && (pOn || pUsing) ){
003891      sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
003892        (pOn ? "ON" : "USING")
003893      );
003894      goto append_from_error;
003895    }
003896    p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
003897    if( p==0 ){
003898      goto append_from_error;
003899    }
003900    assert( p->nSrc>0 );
003901    pItem = &p->a[p->nSrc-1];
003902    assert( pAlias!=0 );
003903    if( pAlias->n ){
003904      pItem->zAlias = sqlite3NameFromToken(db, pAlias);
003905    }
003906    pItem->pSelect = pSubquery;
003907    pItem->pOn = pOn;
003908    pItem->pUsing = pUsing;
003909    return p;
003910  
003911   append_from_error:
003912    assert( p==0 );
003913    sqlite3ExprDelete(db, pOn);
003914    sqlite3IdListDelete(db, pUsing);
003915    sqlite3SelectDelete(db, pSubquery);
003916    return 0;
003917  }
003918  
003919  /*
003920  ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
003921  ** element of the source-list passed as the second argument.
003922  */
003923  void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
003924    assert( pIndexedBy!=0 );
003925    if( p && pIndexedBy->n>0 ){
003926      struct SrcList_item *pItem;
003927      assert( p->nSrc>0 );
003928      pItem = &p->a[p->nSrc-1];
003929      assert( pItem->fg.notIndexed==0 );
003930      assert( pItem->fg.isIndexedBy==0 );
003931      assert( pItem->fg.isTabFunc==0 );
003932      if( pIndexedBy->n==1 && !pIndexedBy->z ){
003933        /* A "NOT INDEXED" clause was supplied. See parse.y 
003934        ** construct "indexed_opt" for details. */
003935        pItem->fg.notIndexed = 1;
003936      }else{
003937        pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
003938        pItem->fg.isIndexedBy = 1;
003939      }
003940    }
003941  }
003942  
003943  /*
003944  ** Add the list of function arguments to the SrcList entry for a
003945  ** table-valued-function.
003946  */
003947  void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
003948    if( p ){
003949      struct SrcList_item *pItem = &p->a[p->nSrc-1];
003950      assert( pItem->fg.notIndexed==0 );
003951      assert( pItem->fg.isIndexedBy==0 );
003952      assert( pItem->fg.isTabFunc==0 );
003953      pItem->u1.pFuncArg = pList;
003954      pItem->fg.isTabFunc = 1;
003955    }else{
003956      sqlite3ExprListDelete(pParse->db, pList);
003957    }
003958  }
003959  
003960  /*
003961  ** When building up a FROM clause in the parser, the join operator
003962  ** is initially attached to the left operand.  But the code generator
003963  ** expects the join operator to be on the right operand.  This routine
003964  ** Shifts all join operators from left to right for an entire FROM
003965  ** clause.
003966  **
003967  ** Example: Suppose the join is like this:
003968  **
003969  **           A natural cross join B
003970  **
003971  ** The operator is "natural cross join".  The A and B operands are stored
003972  ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
003973  ** operator with A.  This routine shifts that operator over to B.
003974  */
003975  void sqlite3SrcListShiftJoinType(SrcList *p){
003976    if( p ){
003977      int i;
003978      for(i=p->nSrc-1; i>0; i--){
003979        p->a[i].fg.jointype = p->a[i-1].fg.jointype;
003980      }
003981      p->a[0].fg.jointype = 0;
003982    }
003983  }
003984  
003985  /*
003986  ** Generate VDBE code for a BEGIN statement.
003987  */
003988  void sqlite3BeginTransaction(Parse *pParse, int type){
003989    sqlite3 *db;
003990    Vdbe *v;
003991    int i;
003992  
003993    assert( pParse!=0 );
003994    db = pParse->db;
003995    assert( db!=0 );
003996    if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
003997      return;
003998    }
003999    v = sqlite3GetVdbe(pParse);
004000    if( !v ) return;
004001    if( type!=TK_DEFERRED ){
004002      for(i=0; i<db->nDb; i++){
004003        sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
004004        sqlite3VdbeUsesBtree(v, i);
004005      }
004006    }
004007    sqlite3VdbeAddOp0(v, OP_AutoCommit);
004008  }
004009  
004010  /*
004011  ** Generate VDBE code for a COMMIT or ROLLBACK statement.
004012  ** Code for ROLLBACK is generated if eType==TK_ROLLBACK.  Otherwise
004013  ** code is generated for a COMMIT.
004014  */
004015  void sqlite3EndTransaction(Parse *pParse, int eType){
004016    Vdbe *v;
004017    int isRollback;
004018  
004019    assert( pParse!=0 );
004020    assert( pParse->db!=0 );
004021    assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
004022    isRollback = eType==TK_ROLLBACK;
004023    if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, 
004024         isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
004025      return;
004026    }
004027    v = sqlite3GetVdbe(pParse);
004028    if( v ){
004029      sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
004030    }
004031  }
004032  
004033  /*
004034  ** This function is called by the parser when it parses a command to create,
004035  ** release or rollback an SQL savepoint. 
004036  */
004037  void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
004038    char *zName = sqlite3NameFromToken(pParse->db, pName);
004039    if( zName ){
004040      Vdbe *v = sqlite3GetVdbe(pParse);
004041  #ifndef SQLITE_OMIT_AUTHORIZATION
004042      static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
004043      assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
004044  #endif
004045      if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
004046        sqlite3DbFree(pParse->db, zName);
004047        return;
004048      }
004049      sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
004050    }
004051  }
004052  
004053  /*
004054  ** Make sure the TEMP database is open and available for use.  Return
004055  ** the number of errors.  Leave any error messages in the pParse structure.
004056  */
004057  int sqlite3OpenTempDatabase(Parse *pParse){
004058    sqlite3 *db = pParse->db;
004059    if( db->aDb[1].pBt==0 && !pParse->explain ){
004060      int rc;
004061      Btree *pBt;
004062      static const int flags = 
004063            SQLITE_OPEN_READWRITE |
004064            SQLITE_OPEN_CREATE |
004065            SQLITE_OPEN_EXCLUSIVE |
004066            SQLITE_OPEN_DELETEONCLOSE |
004067            SQLITE_OPEN_TEMP_DB;
004068  
004069      rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
004070      if( rc!=SQLITE_OK ){
004071        sqlite3ErrorMsg(pParse, "unable to open a temporary database "
004072          "file for storing temporary tables");
004073        pParse->rc = rc;
004074        return 1;
004075      }
004076      db->aDb[1].pBt = pBt;
004077      assert( db->aDb[1].pSchema );
004078      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
004079        sqlite3OomFault(db);
004080        return 1;
004081      }
004082    }
004083    return 0;
004084  }
004085  
004086  /*
004087  ** Record the fact that the schema cookie will need to be verified
004088  ** for database iDb.  The code to actually verify the schema cookie
004089  ** will occur at the end of the top-level VDBE and will be generated
004090  ** later, by sqlite3FinishCoding().
004091  */
004092  void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
004093    Parse *pToplevel = sqlite3ParseToplevel(pParse);
004094  
004095    assert( iDb>=0 && iDb<pParse->db->nDb );
004096    assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
004097    assert( iDb<SQLITE_MAX_ATTACHED+2 );
004098    assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
004099    if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
004100      DbMaskSet(pToplevel->cookieMask, iDb);
004101      if( !OMIT_TEMPDB && iDb==1 ){
004102        sqlite3OpenTempDatabase(pToplevel);
004103      }
004104    }
004105  }
004106  
004107  /*
004108  ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 
004109  ** attached database. Otherwise, invoke it for the database named zDb only.
004110  */
004111  void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
004112    sqlite3 *db = pParse->db;
004113    int i;
004114    for(i=0; i<db->nDb; i++){
004115      Db *pDb = &db->aDb[i];
004116      if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
004117        sqlite3CodeVerifySchema(pParse, i);
004118      }
004119    }
004120  }
004121  
004122  /*
004123  ** Generate VDBE code that prepares for doing an operation that
004124  ** might change the database.
004125  **
004126  ** This routine starts a new transaction if we are not already within
004127  ** a transaction.  If we are already within a transaction, then a checkpoint
004128  ** is set if the setStatement parameter is true.  A checkpoint should
004129  ** be set for operations that might fail (due to a constraint) part of
004130  ** the way through and which will need to undo some writes without having to
004131  ** rollback the whole transaction.  For operations where all constraints
004132  ** can be checked before any changes are made to the database, it is never
004133  ** necessary to undo a write and the checkpoint should not be set.
004134  */
004135  void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
004136    Parse *pToplevel = sqlite3ParseToplevel(pParse);
004137    sqlite3CodeVerifySchema(pParse, iDb);
004138    DbMaskSet(pToplevel->writeMask, iDb);
004139    pToplevel->isMultiWrite |= setStatement;
004140  }
004141  
004142  /*
004143  ** Indicate that the statement currently under construction might write
004144  ** more than one entry (example: deleting one row then inserting another,
004145  ** inserting multiple rows in a table, or inserting a row and index entries.)
004146  ** If an abort occurs after some of these writes have completed, then it will
004147  ** be necessary to undo the completed writes.
004148  */
004149  void sqlite3MultiWrite(Parse *pParse){
004150    Parse *pToplevel = sqlite3ParseToplevel(pParse);
004151    pToplevel->isMultiWrite = 1;
004152  }
004153  
004154  /* 
004155  ** The code generator calls this routine if is discovers that it is
004156  ** possible to abort a statement prior to completion.  In order to 
004157  ** perform this abort without corrupting the database, we need to make
004158  ** sure that the statement is protected by a statement transaction.
004159  **
004160  ** Technically, we only need to set the mayAbort flag if the
004161  ** isMultiWrite flag was previously set.  There is a time dependency
004162  ** such that the abort must occur after the multiwrite.  This makes
004163  ** some statements involving the REPLACE conflict resolution algorithm
004164  ** go a little faster.  But taking advantage of this time dependency
004165  ** makes it more difficult to prove that the code is correct (in 
004166  ** particular, it prevents us from writing an effective
004167  ** implementation of sqlite3AssertMayAbort()) and so we have chosen
004168  ** to take the safe route and skip the optimization.
004169  */
004170  void sqlite3MayAbort(Parse *pParse){
004171    Parse *pToplevel = sqlite3ParseToplevel(pParse);
004172    pToplevel->mayAbort = 1;
004173  }
004174  
004175  /*
004176  ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
004177  ** error. The onError parameter determines which (if any) of the statement
004178  ** and/or current transaction is rolled back.
004179  */
004180  void sqlite3HaltConstraint(
004181    Parse *pParse,    /* Parsing context */
004182    int errCode,      /* extended error code */
004183    int onError,      /* Constraint type */
004184    char *p4,         /* Error message */
004185    i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
004186    u8 p5Errmsg       /* P5_ErrMsg type */
004187  ){
004188    Vdbe *v = sqlite3GetVdbe(pParse);
004189    assert( (errCode&0xff)==SQLITE_CONSTRAINT );
004190    if( onError==OE_Abort ){
004191      sqlite3MayAbort(pParse);
004192    }
004193    sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
004194    sqlite3VdbeChangeP5(v, p5Errmsg);
004195  }
004196  
004197  /*
004198  ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
004199  */
004200  void sqlite3UniqueConstraint(
004201    Parse *pParse,    /* Parsing context */
004202    int onError,      /* Constraint type */
004203    Index *pIdx       /* The index that triggers the constraint */
004204  ){
004205    char *zErr;
004206    int j;
004207    StrAccum errMsg;
004208    Table *pTab = pIdx->pTable;
004209  
004210    sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
004211    if( pIdx->aColExpr ){
004212      sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
004213    }else{
004214      for(j=0; j<pIdx->nKeyCol; j++){
004215        char *zCol;
004216        assert( pIdx->aiColumn[j]>=0 );
004217        zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
004218        if( j ) sqlite3_str_append(&errMsg, ", ", 2);
004219        sqlite3_str_appendall(&errMsg, pTab->zName);
004220        sqlite3_str_append(&errMsg, ".", 1);
004221        sqlite3_str_appendall(&errMsg, zCol);
004222      }
004223    }
004224    zErr = sqlite3StrAccumFinish(&errMsg);
004225    sqlite3HaltConstraint(pParse, 
004226      IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY 
004227                              : SQLITE_CONSTRAINT_UNIQUE,
004228      onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
004229  }
004230  
004231  
004232  /*
004233  ** Code an OP_Halt due to non-unique rowid.
004234  */
004235  void sqlite3RowidConstraint(
004236    Parse *pParse,    /* Parsing context */
004237    int onError,      /* Conflict resolution algorithm */
004238    Table *pTab       /* The table with the non-unique rowid */ 
004239  ){
004240    char *zMsg;
004241    int rc;
004242    if( pTab->iPKey>=0 ){
004243      zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
004244                            pTab->aCol[pTab->iPKey].zName);
004245      rc = SQLITE_CONSTRAINT_PRIMARYKEY;
004246    }else{
004247      zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
004248      rc = SQLITE_CONSTRAINT_ROWID;
004249    }
004250    sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
004251                          P5_ConstraintUnique);
004252  }
004253  
004254  /*
004255  ** Check to see if pIndex uses the collating sequence pColl.  Return
004256  ** true if it does and false if it does not.
004257  */
004258  #ifndef SQLITE_OMIT_REINDEX
004259  static int collationMatch(const char *zColl, Index *pIndex){
004260    int i;
004261    assert( zColl!=0 );
004262    for(i=0; i<pIndex->nColumn; i++){
004263      const char *z = pIndex->azColl[i];
004264      assert( z!=0 || pIndex->aiColumn[i]<0 );
004265      if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
004266        return 1;
004267      }
004268    }
004269    return 0;
004270  }
004271  #endif
004272  
004273  /*
004274  ** Recompute all indices of pTab that use the collating sequence pColl.
004275  ** If pColl==0 then recompute all indices of pTab.
004276  */
004277  #ifndef SQLITE_OMIT_REINDEX
004278  static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
004279    Index *pIndex;              /* An index associated with pTab */
004280  
004281    for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
004282      if( zColl==0 || collationMatch(zColl, pIndex) ){
004283        int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
004284        sqlite3BeginWriteOperation(pParse, 0, iDb);
004285        sqlite3RefillIndex(pParse, pIndex, -1);
004286      }
004287    }
004288  }
004289  #endif
004290  
004291  /*
004292  ** Recompute all indices of all tables in all databases where the
004293  ** indices use the collating sequence pColl.  If pColl==0 then recompute
004294  ** all indices everywhere.
004295  */
004296  #ifndef SQLITE_OMIT_REINDEX
004297  static void reindexDatabases(Parse *pParse, char const *zColl){
004298    Db *pDb;                    /* A single database */
004299    int iDb;                    /* The database index number */
004300    sqlite3 *db = pParse->db;   /* The database connection */
004301    HashElem *k;                /* For looping over tables in pDb */
004302    Table *pTab;                /* A table in the database */
004303  
004304    assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
004305    for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
004306      assert( pDb!=0 );
004307      for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
004308        pTab = (Table*)sqliteHashData(k);
004309        reindexTable(pParse, pTab, zColl);
004310      }
004311    }
004312  }
004313  #endif
004314  
004315  /*
004316  ** Generate code for the REINDEX command.
004317  **
004318  **        REINDEX                            -- 1
004319  **        REINDEX  <collation>               -- 2
004320  **        REINDEX  ?<database>.?<tablename>  -- 3
004321  **        REINDEX  ?<database>.?<indexname>  -- 4
004322  **
004323  ** Form 1 causes all indices in all attached databases to be rebuilt.
004324  ** Form 2 rebuilds all indices in all databases that use the named
004325  ** collating function.  Forms 3 and 4 rebuild the named index or all
004326  ** indices associated with the named table.
004327  */
004328  #ifndef SQLITE_OMIT_REINDEX
004329  void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
004330    CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
004331    char *z;                    /* Name of a table or index */
004332    const char *zDb;            /* Name of the database */
004333    Table *pTab;                /* A table in the database */
004334    Index *pIndex;              /* An index associated with pTab */
004335    int iDb;                    /* The database index number */
004336    sqlite3 *db = pParse->db;   /* The database connection */
004337    Token *pObjName;            /* Name of the table or index to be reindexed */
004338  
004339    /* Read the database schema. If an error occurs, leave an error message
004340    ** and code in pParse and return NULL. */
004341    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
004342      return;
004343    }
004344  
004345    if( pName1==0 ){
004346      reindexDatabases(pParse, 0);
004347      return;
004348    }else if( NEVER(pName2==0) || pName2->z==0 ){
004349      char *zColl;
004350      assert( pName1->z );
004351      zColl = sqlite3NameFromToken(pParse->db, pName1);
004352      if( !zColl ) return;
004353      pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
004354      if( pColl ){
004355        reindexDatabases(pParse, zColl);
004356        sqlite3DbFree(db, zColl);
004357        return;
004358      }
004359      sqlite3DbFree(db, zColl);
004360    }
004361    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
004362    if( iDb<0 ) return;
004363    z = sqlite3NameFromToken(db, pObjName);
004364    if( z==0 ) return;
004365    zDb = db->aDb[iDb].zDbSName;
004366    pTab = sqlite3FindTable(db, z, zDb);
004367    if( pTab ){
004368      reindexTable(pParse, pTab, 0);
004369      sqlite3DbFree(db, z);
004370      return;
004371    }
004372    pIndex = sqlite3FindIndex(db, z, zDb);
004373    sqlite3DbFree(db, z);
004374    if( pIndex ){
004375      sqlite3BeginWriteOperation(pParse, 0, iDb);
004376      sqlite3RefillIndex(pParse, pIndex, -1);
004377      return;
004378    }
004379    sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
004380  }
004381  #endif
004382  
004383  /*
004384  ** Return a KeyInfo structure that is appropriate for the given Index.
004385  **
004386  ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
004387  ** when it has finished using it.
004388  */
004389  KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
004390    int i;
004391    int nCol = pIdx->nColumn;
004392    int nKey = pIdx->nKeyCol;
004393    KeyInfo *pKey;
004394    if( pParse->nErr ) return 0;
004395    if( pIdx->uniqNotNull ){
004396      pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
004397    }else{
004398      pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
004399    }
004400    if( pKey ){
004401      assert( sqlite3KeyInfoIsWriteable(pKey) );
004402      for(i=0; i<nCol; i++){
004403        const char *zColl = pIdx->azColl[i];
004404        pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
004405                          sqlite3LocateCollSeq(pParse, zColl);
004406        pKey->aSortOrder[i] = pIdx->aSortOrder[i];
004407      }
004408      if( pParse->nErr ){
004409        assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
004410        if( pIdx->bNoQuery==0 ){
004411          /* Deactivate the index because it contains an unknown collating
004412          ** sequence.  The only way to reactive the index is to reload the
004413          ** schema.  Adding the missing collating sequence later does not
004414          ** reactive the index.  The application had the chance to register
004415          ** the missing index using the collation-needed callback.  For
004416          ** simplicity, SQLite will not give the application a second chance.
004417          */
004418          pIdx->bNoQuery = 1;
004419          pParse->rc = SQLITE_ERROR_RETRY;
004420        }
004421        sqlite3KeyInfoUnref(pKey);
004422        pKey = 0;
004423      }
004424    }
004425    return pKey;
004426  }
004427  
004428  #ifndef SQLITE_OMIT_CTE
004429  /* 
004430  ** This routine is invoked once per CTE by the parser while parsing a 
004431  ** WITH clause. 
004432  */
004433  With *sqlite3WithAdd(
004434    Parse *pParse,          /* Parsing context */
004435    With *pWith,            /* Existing WITH clause, or NULL */
004436    Token *pName,           /* Name of the common-table */
004437    ExprList *pArglist,     /* Optional column name list for the table */
004438    Select *pQuery          /* Query used to initialize the table */
004439  ){
004440    sqlite3 *db = pParse->db;
004441    With *pNew;
004442    char *zName;
004443  
004444    /* Check that the CTE name is unique within this WITH clause. If
004445    ** not, store an error in the Parse structure. */
004446    zName = sqlite3NameFromToken(pParse->db, pName);
004447    if( zName && pWith ){
004448      int i;
004449      for(i=0; i<pWith->nCte; i++){
004450        if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
004451          sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
004452        }
004453      }
004454    }
004455  
004456    if( pWith ){
004457      int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
004458      pNew = sqlite3DbRealloc(db, pWith, nByte);
004459    }else{
004460      pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
004461    }
004462    assert( (pNew!=0 && zName!=0) || db->mallocFailed );
004463  
004464    if( db->mallocFailed ){
004465      sqlite3ExprListDelete(db, pArglist);
004466      sqlite3SelectDelete(db, pQuery);
004467      sqlite3DbFree(db, zName);
004468      pNew = pWith;
004469    }else{
004470      pNew->a[pNew->nCte].pSelect = pQuery;
004471      pNew->a[pNew->nCte].pCols = pArglist;
004472      pNew->a[pNew->nCte].zName = zName;
004473      pNew->a[pNew->nCte].zCteErr = 0;
004474      pNew->nCte++;
004475    }
004476  
004477    return pNew;
004478  }
004479  
004480  /*
004481  ** Free the contents of the With object passed as the second argument.
004482  */
004483  void sqlite3WithDelete(sqlite3 *db, With *pWith){
004484    if( pWith ){
004485      int i;
004486      for(i=0; i<pWith->nCte; i++){
004487        struct Cte *pCte = &pWith->a[i];
004488        sqlite3ExprListDelete(db, pCte->pCols);
004489        sqlite3SelectDelete(db, pCte->pSelect);
004490        sqlite3DbFree(db, pCte->zName);
004491      }
004492      sqlite3DbFree(db, pWith);
004493    }
004494  }
004495  #endif /* !defined(SQLITE_OMIT_CTE) */