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