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    Pgno 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  static SQLITE_NOINLINE void lockTable(
000050    Parse *pParse,     /* Parsing context */
000051    int iDb,           /* Index of the database containing the table to lock */
000052    Pgno 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;
000057    int i;
000058    int nBytes;
000059    TableLock *p;
000060    assert( iDb>=0 );
000061  
000062    pToplevel = sqlite3ParseToplevel(pParse);
000063    for(i=0; i<pToplevel->nTableLock; i++){
000064      p = &pToplevel->aTableLock[i];
000065      if( p->iDb==iDb && p->iTab==iTab ){
000066        p->isWriteLock = (p->isWriteLock || isWriteLock);
000067        return;
000068      }
000069    }
000070  
000071    assert( pToplevel->nTableLock < 0x7fff0000 );
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  void sqlite3TableLock(
000087    Parse *pParse,     /* Parsing context */
000088    int iDb,           /* Index of the database containing the table to lock */
000089    Pgno iTab,         /* Root page number of the table to be locked */
000090    u8 isWriteLock,    /* True for a write lock */
000091    const char *zName  /* Name of the table to be locked */
000092  ){
000093    if( iDb==1 ) return;
000094    if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
000095    lockTable(pParse, iDb, iTab, isWriteLock, zName);
000096  }
000097  
000098  /*
000099  ** Code an OP_TableLock instruction for each table locked by the
000100  ** statement (configured by calls to sqlite3TableLock()).
000101  */
000102  static void codeTableLocks(Parse *pParse){
000103    int i;
000104    Vdbe *pVdbe = pParse->pVdbe;
000105    assert( pVdbe!=0 );
000106  
000107    for(i=0; i<pParse->nTableLock; i++){
000108      TableLock *p = &pParse->aTableLock[i];
000109      int p1 = p->iDb;
000110      sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
000111                        p->zLockName, P4_STATIC);
000112    }
000113  }
000114  #else
000115    #define codeTableLocks(x)
000116  #endif
000117  
000118  /*
000119  ** Return TRUE if the given yDbMask object is empty - if it contains no
000120  ** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
000121  ** macros when SQLITE_MAX_ATTACHED is greater than 30.
000122  */
000123  #if SQLITE_MAX_ATTACHED>30
000124  int sqlite3DbMaskAllZero(yDbMask m){
000125    int i;
000126    for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
000127    return 1;
000128  }
000129  #endif
000130  
000131  /*
000132  ** This routine is called after a single SQL statement has been
000133  ** parsed and a VDBE program to execute that statement has been
000134  ** prepared.  This routine puts the finishing touches on the
000135  ** VDBE program and resets the pParse structure for the next
000136  ** parse.
000137  **
000138  ** Note that if an error occurred, it might be the case that
000139  ** no VDBE code was generated.
000140  */
000141  void sqlite3FinishCoding(Parse *pParse){
000142    sqlite3 *db;
000143    Vdbe *v;
000144    int iDb, i;
000145  
000146    assert( pParse->pToplevel==0 );
000147    db = pParse->db;
000148    assert( db->pParse==pParse );
000149    if( pParse->nested ) return;
000150    if( pParse->nErr ){
000151      if( db->mallocFailed ) pParse->rc = SQLITE_NOMEM;
000152      return;
000153    }
000154    assert( db->mallocFailed==0 );
000155  
000156    /* Begin by generating some termination code at the end of the
000157    ** vdbe program
000158    */
000159    v = pParse->pVdbe;
000160    if( v==0 ){
000161      if( db->init.busy ){
000162        pParse->rc = SQLITE_DONE;
000163        return;
000164      }
000165      v = sqlite3GetVdbe(pParse);
000166      if( v==0 ) pParse->rc = SQLITE_ERROR;
000167    }
000168    assert( !pParse->isMultiWrite
000169         || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
000170    if( v ){
000171      if( pParse->bReturning ){
000172        Returning *pReturning;
000173        int addrRewind;
000174        int reg;
000175  
000176        assert( !pParse->isCreate );
000177        pReturning = pParse->u1.d.pReturning;
000178        if( pReturning->nRetCol ){
000179          sqlite3VdbeAddOp0(v, OP_FkCheck);
000180          addrRewind =
000181             sqlite3VdbeAddOp1(v, OP_Rewind, pReturning->iRetCur);
000182          VdbeCoverage(v);
000183          reg = pReturning->iRetReg;
000184          for(i=0; i<pReturning->nRetCol; i++){
000185            sqlite3VdbeAddOp3(v, OP_Column, pReturning->iRetCur, i, reg+i);
000186          }
000187          sqlite3VdbeAddOp2(v, OP_ResultRow, reg, i);
000188          sqlite3VdbeAddOp2(v, OP_Next, pReturning->iRetCur, addrRewind+1);
000189          VdbeCoverage(v);
000190          sqlite3VdbeJumpHere(v, addrRewind);
000191        }
000192      }
000193      sqlite3VdbeAddOp0(v, OP_Halt);
000194  
000195      /* The cookie mask contains one bit for each database file open.
000196      ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
000197      ** set for each database that is used.  Generate code to start a
000198      ** transaction on each used database and to verify the schema cookie
000199      ** on each used database.
000200      */
000201      assert( pParse->nErr>0 || sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
000202      sqlite3VdbeJumpHere(v, 0);
000203      assert( db->nDb>0 );
000204      iDb = 0;
000205      do{
000206        Schema *pSchema;
000207        if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
000208        sqlite3VdbeUsesBtree(v, iDb);
000209        pSchema = db->aDb[iDb].pSchema;
000210        sqlite3VdbeAddOp4Int(v,
000211          OP_Transaction,                    /* Opcode */
000212          iDb,                               /* P1 */
000213          DbMaskTest(pParse->writeMask,iDb), /* P2 */
000214          pSchema->schema_cookie,            /* P3 */
000215          pSchema->iGeneration               /* P4 */
000216        );
000217        if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
000218        VdbeComment((v,
000219              "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
000220      }while( ++iDb<db->nDb );
000221  #ifndef SQLITE_OMIT_VIRTUALTABLE
000222      for(i=0; i<pParse->nVtabLock; i++){
000223        char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
000224        sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
000225      }
000226      pParse->nVtabLock = 0;
000227  #endif
000228  
000229  #ifndef SQLITE_OMIT_SHARED_CACHE
000230      /* Once all the cookies have been verified and transactions opened,
000231      ** obtain the required table-locks. This is a no-op unless the
000232      ** shared-cache feature is enabled.
000233      */
000234      if( pParse->nTableLock ) codeTableLocks(pParse);
000235  #endif
000236  
000237      /* Initialize any AUTOINCREMENT data structures required.
000238      */
000239      if( pParse->pAinc ) sqlite3AutoincrementBegin(pParse);
000240  
000241      /* Code constant expressions that were factored out of inner loops. 
000242      */
000243      if( pParse->pConstExpr ){
000244        ExprList *pEL = pParse->pConstExpr;
000245        pParse->okConstFactor = 0;
000246        for(i=0; i<pEL->nExpr; i++){
000247          assert( pEL->a[i].u.iConstExprReg>0 );
000248          sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
000249        }
000250      }
000251  
000252      if( pParse->bReturning ){
000253        Returning *pRet;
000254        assert( !pParse->isCreate );
000255        pRet = pParse->u1.d.pReturning;
000256        if( pRet->nRetCol ){
000257          sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRet->iRetCur, pRet->nRetCol);
000258        }
000259      }
000260  
000261      /* Finally, jump back to the beginning of the executable code. */
000262      sqlite3VdbeGoto(v, 1);
000263    }
000264  
000265    /* Get the VDBE program ready for execution
000266    */
000267    assert( v!=0 || pParse->nErr );
000268    assert( db->mallocFailed==0 || pParse->nErr );
000269    if( pParse->nErr==0 ){
000270      /* A minimum of one cursor is required if autoincrement is used
000271      *  See ticket [a696379c1f08866] */
000272      assert( pParse->pAinc==0 || pParse->nTab>0 );
000273      sqlite3VdbeMakeReady(v, pParse);
000274      pParse->rc = SQLITE_DONE;
000275    }else{
000276      pParse->rc = SQLITE_ERROR;
000277    }
000278  }
000279  
000280  /*
000281  ** Run the parser and code generator recursively in order to generate
000282  ** code for the SQL statement given onto the end of the pParse context
000283  ** currently under construction.  Notes:
000284  **
000285  **   *  The final OP_Halt is not appended and other initialization
000286  **      and finalization steps are omitted because those are handling by the
000287  **      outermost parser.
000288  **
000289  **   *  Built-in SQL functions always take precedence over application-defined
000290  **      SQL functions.  In other words, it is not possible to override a
000291  **      built-in function.
000292  */
000293  void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
000294    va_list ap;
000295    char *zSql;
000296    sqlite3 *db = pParse->db;
000297    u32 savedDbFlags = db->mDbFlags;
000298    char saveBuf[PARSE_TAIL_SZ];
000299  
000300    if( pParse->nErr ) return;
000301    if( pParse->eParseMode ) return;
000302    assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
000303    va_start(ap, zFormat);
000304    zSql = sqlite3VMPrintf(db, zFormat, ap);
000305    va_end(ap);
000306    if( zSql==0 ){
000307      /* This can result either from an OOM or because the formatted string
000308      ** exceeds SQLITE_LIMIT_LENGTH.  In the latter case, we need to set
000309      ** an error */
000310      if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;
000311      pParse->nErr++;
000312      return;
000313    }
000314    pParse->nested++;
000315    memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
000316    memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
000317    db->mDbFlags |= DBFLAG_PreferBuiltin;
000318    sqlite3RunParser(pParse, zSql);
000319    db->mDbFlags = savedDbFlags;
000320    sqlite3DbFree(db, zSql);
000321    memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
000322    pParse->nested--;
000323  }
000324  
000325  /*
000326  ** Locate the in-memory structure that describes a particular database
000327  ** table given the name of that table and (optionally) the name of the
000328  ** database containing the table.  Return NULL if not found.
000329  **
000330  ** If zDatabase is 0, all databases are searched for the table and the
000331  ** first matching table is returned.  (No checking for duplicate table
000332  ** names is done.)  The search order is TEMP first, then MAIN, then any
000333  ** auxiliary databases added using the ATTACH command.
000334  **
000335  ** See also sqlite3LocateTable().
000336  */
000337  Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
000338    Table *p = 0;
000339    int i;
000340  
000341    /* All mutexes are required for schema access.  Make sure we hold them. */
000342    assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
000343    if( zDatabase ){
000344      for(i=0; i<db->nDb; i++){
000345        if( sqlite3StrICmp(zDatabase, db->aDb[i].zDbSName)==0 ) break;
000346      }
000347      if( i>=db->nDb ){
000348        /* No match against the official names.  But always match "main"
000349        ** to schema 0 as a legacy fallback. */
000350        if( sqlite3StrICmp(zDatabase,"main")==0 ){
000351          i = 0;
000352        }else{
000353          return 0;
000354        }
000355      }
000356      p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
000357      if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
000358        if( i==1 ){
000359          if( sqlite3StrICmp(zName+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0
000360           || sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0
000361           || sqlite3StrICmp(zName+7, &LEGACY_SCHEMA_TABLE[7])==0
000362          ){
000363            p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
000364                                LEGACY_TEMP_SCHEMA_TABLE);
000365          }
000366        }else{
000367          if( sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0 ){
000368            p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash,
000369                                LEGACY_SCHEMA_TABLE);
000370          }
000371        }
000372      }
000373    }else{
000374      /* Match against TEMP first */
000375      p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, zName);
000376      if( p ) return p;
000377      /* The main database is second */
000378      p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, zName);
000379      if( p ) return p;
000380      /* Attached databases are in order of attachment */
000381      for(i=2; i<db->nDb; i++){
000382        assert( sqlite3SchemaMutexHeld(db, i, 0) );
000383        p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
000384        if( p ) break;
000385      }
000386      if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
000387        if( sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0 ){
000388          p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, LEGACY_SCHEMA_TABLE);
000389        }else if( sqlite3StrICmp(zName+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0 ){
000390          p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
000391                              LEGACY_TEMP_SCHEMA_TABLE);
000392        }
000393      }
000394    }
000395    return p;
000396  }
000397  
000398  /*
000399  ** Locate the in-memory structure that describes a particular database
000400  ** table given the name of that table and (optionally) the name of the
000401  ** database containing the table.  Return NULL if not found.  Also leave an
000402  ** error message in pParse->zErrMsg.
000403  **
000404  ** The difference between this routine and sqlite3FindTable() is that this
000405  ** routine leaves an error message in pParse->zErrMsg where
000406  ** sqlite3FindTable() does not.
000407  */
000408  Table *sqlite3LocateTable(
000409    Parse *pParse,         /* context in which to report errors */
000410    u32 flags,             /* LOCATE_VIEW or LOCATE_NOERR */
000411    const char *zName,     /* Name of the table we are looking for */
000412    const char *zDbase     /* Name of the database.  Might be NULL */
000413  ){
000414    Table *p;
000415    sqlite3 *db = pParse->db;
000416  
000417    /* Read the database schema. If an error occurs, leave an error message
000418    ** and code in pParse and return NULL. */
000419    if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
000420     && SQLITE_OK!=sqlite3ReadSchema(pParse)
000421    ){
000422      return 0;
000423    }
000424  
000425    p = sqlite3FindTable(db, zName, zDbase);
000426    if( p==0 ){
000427  #ifndef SQLITE_OMIT_VIRTUALTABLE
000428      /* If zName is the not the name of a table in the schema created using
000429      ** CREATE, then check to see if it is the name of an virtual table that
000430      ** can be an eponymous virtual table. */
000431      if( (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)==0 && db->init.busy==0 ){
000432        Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
000433        if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
000434          pMod = sqlite3PragmaVtabRegister(db, zName);
000435        }
000436  #ifndef SQLITE_OMIT_JSON
000437        if( pMod==0 && sqlite3_strnicmp(zName, "json", 4)==0 ){
000438          pMod = sqlite3JsonVtabRegister(db, zName);
000439        }
000440  #endif
000441  #ifdef SQLITE_ENABLE_CARRAY
000442        if( pMod==0 && sqlite3_stricmp(zName, "carray")==0 ){
000443          pMod = sqlite3CarrayRegister(db);
000444        }
000445  #endif
000446        if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
000447          testcase( pMod->pEpoTab==0 );
000448          return pMod->pEpoTab;
000449        }
000450      }
000451  #endif
000452      if( flags & LOCATE_NOERR ) return 0;
000453      pParse->checkSchema = 1;
000454    }else if( IsVirtual(p) && (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)!=0 ){
000455      p = 0;
000456    }
000457  
000458    if( p==0 ){
000459      const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
000460      if( zDbase ){
000461        sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
000462      }else{
000463        sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
000464      }
000465    }else{
000466      assert( HasRowid(p) || p->iPKey<0 );
000467    }
000468  
000469    return p;
000470  }
000471  
000472  /*
000473  ** Locate the table identified by *p.
000474  **
000475  ** This is a wrapper around sqlite3LocateTable(). The difference between
000476  ** sqlite3LocateTable() and this function is that this function restricts
000477  ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
000478  ** non-NULL if it is part of a view or trigger program definition. See
000479  ** sqlite3FixSrcList() for details.
000480  */
000481  Table *sqlite3LocateTableItem(
000482    Parse *pParse,
000483    u32 flags,
000484    SrcItem *p
000485  ){
000486    const char *zDb;
000487    if( p->fg.fixedSchema ){
000488      int iDb = sqlite3SchemaToIndex(pParse->db, p->u4.pSchema);
000489      zDb = pParse->db->aDb[iDb].zDbSName;
000490    }else{
000491      assert( !p->fg.isSubquery );
000492      zDb = p->u4.zDatabase;
000493    }
000494    return sqlite3LocateTable(pParse, flags, p->zName, zDb);
000495  }
000496  
000497  /*
000498  ** Return the preferred table name for system tables.  Translate legacy
000499  ** names into the new preferred names, as appropriate.
000500  */
000501  const char *sqlite3PreferredTableName(const char *zName){
000502    if( sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
000503      if( sqlite3StrICmp(zName+7, &LEGACY_SCHEMA_TABLE[7])==0 ){
000504        return PREFERRED_SCHEMA_TABLE;
000505      }
000506      if( sqlite3StrICmp(zName+7, &LEGACY_TEMP_SCHEMA_TABLE[7])==0 ){
000507        return PREFERRED_TEMP_SCHEMA_TABLE;
000508      }
000509    }
000510    return zName;
000511  }
000512  
000513  /*
000514  ** Locate the in-memory structure that describes
000515  ** a particular index given the name of that index
000516  ** and the name of the database that contains the index.
000517  ** Return NULL if not found.
000518  **
000519  ** If zDatabase is 0, all databases are searched for the
000520  ** table and the first matching index is returned.  (No checking
000521  ** for duplicate index names is done.)  The search order is
000522  ** TEMP first, then MAIN, then any auxiliary databases added
000523  ** using the ATTACH command.
000524  */
000525  Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
000526    Index *p = 0;
000527    int i;
000528    /* All mutexes are required for schema access.  Make sure we hold them. */
000529    assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
000530    for(i=OMIT_TEMPDB; i<db->nDb; i++){
000531      int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
000532      Schema *pSchema = db->aDb[j].pSchema;
000533      assert( pSchema );
000534      if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;
000535      assert( sqlite3SchemaMutexHeld(db, j, 0) );
000536      p = sqlite3HashFind(&pSchema->idxHash, zName);
000537      if( p ) break;
000538    }
000539    return p;
000540  }
000541  
000542  /*
000543  ** Reclaim the memory used by an index
000544  */
000545  void sqlite3FreeIndex(sqlite3 *db, Index *p){
000546  #ifndef SQLITE_OMIT_ANALYZE
000547    sqlite3DeleteIndexSamples(db, p);
000548  #endif
000549    sqlite3ExprDelete(db, p->pPartIdxWhere);
000550    sqlite3ExprListDelete(db, p->aColExpr);
000551    sqlite3DbFree(db, p->zColAff);
000552    if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
000553  #ifdef SQLITE_ENABLE_STAT4
000554    sqlite3_free(p->aiRowEst);
000555  #endif
000556    sqlite3DbFree(db, p);
000557  }
000558  
000559  /*
000560  ** For the index called zIdxName which is found in the database iDb,
000561  ** unlike that index from its Table then remove the index from
000562  ** the index hash table and free all memory structures associated
000563  ** with the index.
000564  */
000565  void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
000566    Index *pIndex;
000567    Hash *pHash;
000568  
000569    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000570    pHash = &db->aDb[iDb].pSchema->idxHash;
000571    pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
000572    if( ALWAYS(pIndex) ){
000573      if( pIndex->pTable->pIndex==pIndex ){
000574        pIndex->pTable->pIndex = pIndex->pNext;
000575      }else{
000576        Index *p;
000577        /* Justification of ALWAYS();  The index must be on the list of
000578        ** indices. */
000579        p = pIndex->pTable->pIndex;
000580        while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
000581        if( ALWAYS(p && p->pNext==pIndex) ){
000582          p->pNext = pIndex->pNext;
000583        }
000584      }
000585      sqlite3FreeIndex(db, pIndex);
000586    }
000587    db->mDbFlags |= DBFLAG_SchemaChange;
000588  }
000589  
000590  /*
000591  ** Look through the list of open database files in db->aDb[] and if
000592  ** any have been closed, remove them from the list.  Reallocate the
000593  ** db->aDb[] structure to a smaller size, if possible.
000594  **
000595  ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
000596  ** are never candidates for being collapsed.
000597  */
000598  void sqlite3CollapseDatabaseArray(sqlite3 *db){
000599    int i, j;
000600    for(i=j=2; i<db->nDb; i++){
000601      struct Db *pDb = &db->aDb[i];
000602      if( pDb->pBt==0 ){
000603        sqlite3DbFree(db, pDb->zDbSName);
000604        pDb->zDbSName = 0;
000605        continue;
000606      }
000607      if( j<i ){
000608        db->aDb[j] = db->aDb[i];
000609      }
000610      j++;
000611    }
000612    db->nDb = j;
000613    if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
000614      memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
000615      sqlite3DbFree(db, db->aDb);
000616      db->aDb = db->aDbStatic;
000617    }
000618  }
000619  
000620  /*
000621  ** Reset the schema for the database at index iDb.  Also reset the
000622  ** TEMP schema.  The reset is deferred if db->nSchemaLock is not zero.
000623  ** Deferred resets may be run by calling with iDb<0.
000624  */
000625  void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
000626    int i;
000627    assert( iDb<db->nDb );
000628  
000629    if( iDb>=0 ){
000630      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000631      DbSetProperty(db, iDb, DB_ResetWanted);
000632      DbSetProperty(db, 1, DB_ResetWanted);
000633      db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
000634    }
000635  
000636    if( db->nSchemaLock==0 ){
000637      for(i=0; i<db->nDb; i++){
000638        if( DbHasProperty(db, i, DB_ResetWanted) ){
000639          sqlite3SchemaClear(db->aDb[i].pSchema);
000640        }
000641      }
000642    }
000643  }
000644  
000645  /*
000646  ** Erase all schema information from all attached databases (including
000647  ** "main" and "temp") for a single database connection.
000648  */
000649  void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
000650    int i;
000651    sqlite3BtreeEnterAll(db);
000652    for(i=0; i<db->nDb; i++){
000653      Db *pDb = &db->aDb[i];
000654      if( pDb->pSchema ){
000655        if( db->nSchemaLock==0 ){
000656          sqlite3SchemaClear(pDb->pSchema);
000657        }else{
000658          DbSetProperty(db, i, DB_ResetWanted);
000659        }
000660      }
000661    }
000662    db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
000663    sqlite3VtabUnlockList(db);
000664    sqlite3BtreeLeaveAll(db);
000665    if( db->nSchemaLock==0 ){
000666      sqlite3CollapseDatabaseArray(db);
000667    }
000668  }
000669  
000670  /*
000671  ** This routine is called when a commit occurs.
000672  */
000673  void sqlite3CommitInternalChanges(sqlite3 *db){
000674    db->mDbFlags &= ~DBFLAG_SchemaChange;
000675  }
000676  
000677  /*
000678  ** Set the expression associated with a column.  This is usually
000679  ** the DEFAULT value, but might also be the expression that computes
000680  ** the value for a generated column.
000681  */
000682  void sqlite3ColumnSetExpr(
000683    Parse *pParse,    /* Parsing context */
000684    Table *pTab,      /* The table containing the column */
000685    Column *pCol,     /* The column to receive the new DEFAULT expression */
000686    Expr *pExpr       /* The new default expression */
000687  ){
000688    ExprList *pList;
000689    assert( IsOrdinaryTable(pTab) );
000690    pList = pTab->u.tab.pDfltList;
000691    if( pCol->iDflt==0
000692     || NEVER(pList==0)
000693     || NEVER(pList->nExpr<pCol->iDflt)
000694    ){
000695      pCol->iDflt = pList==0 ? 1 : pList->nExpr+1;
000696      pTab->u.tab.pDfltList = sqlite3ExprListAppend(pParse, pList, pExpr);
000697    }else{
000698      sqlite3ExprDelete(pParse->db, pList->a[pCol->iDflt-1].pExpr);
000699      pList->a[pCol->iDflt-1].pExpr = pExpr;
000700    }
000701  }
000702  
000703  /*
000704  ** Return the expression associated with a column.  The expression might be
000705  ** the DEFAULT clause or the AS clause of a generated column.
000706  ** Return NULL if the column has no associated expression.
000707  */
000708  Expr *sqlite3ColumnExpr(Table *pTab, Column *pCol){
000709    if( pCol->iDflt==0 ) return 0;
000710    if( !IsOrdinaryTable(pTab) ) return 0;
000711    if( NEVER(pTab->u.tab.pDfltList==0) ) return 0;
000712    if( NEVER(pTab->u.tab.pDfltList->nExpr<pCol->iDflt) ) return 0;
000713    return pTab->u.tab.pDfltList->a[pCol->iDflt-1].pExpr;
000714  }
000715  
000716  /*
000717  ** Set the collating sequence name for a column.
000718  */
000719  void sqlite3ColumnSetColl(
000720    sqlite3 *db,
000721    Column *pCol,
000722    const char *zColl
000723  ){
000724    i64 nColl;
000725    i64 n;
000726    char *zNew;
000727    assert( zColl!=0 );
000728    n = sqlite3Strlen30(pCol->zCnName) + 1;
000729    if( pCol->colFlags & COLFLAG_HASTYPE ){
000730      n += sqlite3Strlen30(pCol->zCnName+n) + 1;
000731    }
000732    nColl = sqlite3Strlen30(zColl) + 1;
000733    zNew = sqlite3DbRealloc(db, pCol->zCnName, nColl+n);
000734    if( zNew ){
000735      pCol->zCnName = zNew;
000736      memcpy(pCol->zCnName + n, zColl, nColl);
000737      pCol->colFlags |= COLFLAG_HASCOLL;
000738    }
000739  }
000740  
000741  /*
000742  ** Return the collating sequence name for a column
000743  */
000744  const char *sqlite3ColumnColl(Column *pCol){
000745    const char *z;
000746    if( (pCol->colFlags & COLFLAG_HASCOLL)==0 ) return 0;
000747    z = pCol->zCnName;
000748    while( *z ){ z++; }
000749    if( pCol->colFlags & COLFLAG_HASTYPE ){
000750      do{ z++; }while( *z );
000751    }
000752    return z+1;
000753  }
000754  
000755  /*
000756  ** Delete memory allocated for the column names of a table or view (the
000757  ** Table.aCol[] array).
000758  */
000759  void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
000760    int i;
000761    Column *pCol;
000762    assert( pTable!=0 );
000763    assert( db!=0 );
000764    if( (pCol = pTable->aCol)!=0 ){
000765      for(i=0; i<pTable->nCol; i++, pCol++){
000766        assert( pCol->zCnName==0 || pCol->hName==sqlite3StrIHash(pCol->zCnName) );
000767        sqlite3DbFree(db, pCol->zCnName);
000768      }
000769      sqlite3DbNNFreeNN(db, pTable->aCol);
000770      if( IsOrdinaryTable(pTable) ){
000771        sqlite3ExprListDelete(db, pTable->u.tab.pDfltList);
000772      }
000773      if( db->pnBytesFreed==0 ){
000774        pTable->aCol = 0;
000775        pTable->nCol = 0;
000776        if( IsOrdinaryTable(pTable) ){
000777          pTable->u.tab.pDfltList = 0;
000778        }
000779      }
000780    }
000781  }
000782  
000783  /*
000784  ** Remove the memory data structures associated with the given
000785  ** Table.  No changes are made to disk by this routine.
000786  **
000787  ** This routine just deletes the data structure.  It does not unlink
000788  ** the table data structure from the hash table.  But it does destroy
000789  ** memory structures of the indices and foreign keys associated with
000790  ** the table.
000791  **
000792  ** The db parameter is optional.  It is needed if the Table object
000793  ** contains lookaside memory.  (Table objects in the schema do not use
000794  ** lookaside memory, but some ephemeral Table objects do.)  Or the
000795  ** db parameter can be used with db->pnBytesFreed to measure the memory
000796  ** used by the Table object.
000797  */
000798  static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
000799    Index *pIndex, *pNext;
000800  
000801  #ifdef SQLITE_DEBUG
000802    /* Record the number of outstanding lookaside allocations in schema Tables
000803    ** prior to doing any free() operations. Since schema Tables do not use
000804    ** lookaside, this number should not change.
000805    **
000806    ** If malloc has already failed, it may be that it failed while allocating
000807    ** a Table object that was going to be marked ephemeral. So do not check
000808    ** that no lookaside memory is used in this case either. */
000809    int nLookaside = 0;
000810    assert( db!=0 );
000811    if( !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){
000812      nLookaside = sqlite3LookasideUsed(db, 0);
000813    }
000814  #endif
000815  
000816    /* Delete all indices associated with this table. */
000817    for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
000818      pNext = pIndex->pNext;
000819      assert( pIndex->pSchema==pTable->pSchema
000820           || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
000821      if( db->pnBytesFreed==0 && !IsVirtual(pTable) ){
000822        char *zName = pIndex->zName;
000823        TESTONLY ( Index *pOld = ) sqlite3HashInsert(
000824           &pIndex->pSchema->idxHash, zName, 0
000825        );
000826        assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
000827        assert( pOld==pIndex || pOld==0 );
000828      }
000829      sqlite3FreeIndex(db, pIndex);
000830    }
000831  
000832    if( IsOrdinaryTable(pTable) ){
000833      sqlite3FkDelete(db, pTable);
000834    }
000835  #ifndef SQLITE_OMIT_VIRTUALTABLE
000836    else if( IsVirtual(pTable) ){
000837      sqlite3VtabClear(db, pTable);
000838    }
000839  #endif
000840    else{
000841      assert( IsView(pTable) );
000842      sqlite3SelectDelete(db, pTable->u.view.pSelect);
000843    }
000844  
000845    /* Delete the Table structure itself.
000846    */
000847    sqlite3DeleteColumnNames(db, pTable);
000848    sqlite3DbFree(db, pTable->zName);
000849    sqlite3DbFree(db, pTable->zColAff);
000850    sqlite3ExprListDelete(db, pTable->pCheck);
000851    sqlite3DbFree(db, pTable);
000852  
000853    /* Verify that no lookaside memory was used by schema tables */
000854    assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
000855  }
000856  void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
000857    /* Do not delete the table until the reference count reaches zero. */
000858    assert( db!=0 );
000859    if( !pTable ) return;
000860    if( db->pnBytesFreed==0 && (--pTable->nTabRef)>0 ) return;
000861    deleteTable(db, pTable);
000862  }
000863  void sqlite3DeleteTableGeneric(sqlite3 *db, void *pTable){
000864    sqlite3DeleteTable(db, (Table*)pTable);
000865  }
000866  
000867  
000868  /*
000869  ** Unlink the given table from the hash tables and the delete the
000870  ** table structure with all its indices and foreign keys.
000871  */
000872  void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
000873    Table *p;
000874    Db *pDb;
000875  
000876    assert( db!=0 );
000877    assert( iDb>=0 && iDb<db->nDb );
000878    assert( zTabName );
000879    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000880    testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
000881    pDb = &db->aDb[iDb];
000882    p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
000883    sqlite3DeleteTable(db, p);
000884    db->mDbFlags |= DBFLAG_SchemaChange;
000885  }
000886  
000887  /*
000888  ** Given a token, return a string that consists of the text of that
000889  ** token.  Space to hold the returned string
000890  ** is obtained from sqliteMalloc() and must be freed by the calling
000891  ** function.
000892  **
000893  ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
000894  ** surround the body of the token are removed.
000895  **
000896  ** Tokens are often just pointers into the original SQL text and so
000897  ** are not \000 terminated and are not persistent.  The returned string
000898  ** is \000 terminated and is persistent.
000899  */
000900  char *sqlite3NameFromToken(sqlite3 *db, const Token *pName){
000901    char *zName;
000902    if( pName ){
000903      zName = sqlite3DbStrNDup(db, (const char*)pName->z, pName->n);
000904      sqlite3Dequote(zName);
000905    }else{
000906      zName = 0;
000907    }
000908    return zName;
000909  }
000910  
000911  /*
000912  ** Open the sqlite_schema table stored in database number iDb for
000913  ** writing. The table is opened using cursor 0.
000914  */
000915  void sqlite3OpenSchemaTable(Parse *p, int iDb){
000916    Vdbe *v = sqlite3GetVdbe(p);
000917    sqlite3TableLock(p, iDb, SCHEMA_ROOT, 1, LEGACY_SCHEMA_TABLE);
000918    sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, SCHEMA_ROOT, iDb, 5);
000919    if( p->nTab==0 ){
000920      p->nTab = 1;
000921    }
000922  }
000923  
000924  /*
000925  ** Parameter zName points to a nul-terminated buffer containing the name
000926  ** of a database ("main", "temp" or the name of an attached db). This
000927  ** function returns the index of the named database in db->aDb[], or
000928  ** -1 if the named db cannot be found.
000929  */
000930  int sqlite3FindDbName(sqlite3 *db, const char *zName){
000931    int i = -1;         /* Database number */
000932    if( zName ){
000933      Db *pDb;
000934      for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
000935        if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
000936        /* "main" is always an acceptable alias for the primary database
000937        ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
000938        if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
000939      }
000940    }
000941    return i;
000942  }
000943  
000944  /*
000945  ** The token *pName contains the name of a database (either "main" or
000946  ** "temp" or the name of an attached db). This routine returns the
000947  ** index of the named database in db->aDb[], or -1 if the named db
000948  ** does not exist.
000949  */
000950  int sqlite3FindDb(sqlite3 *db, Token *pName){
000951    int i;                               /* Database number */
000952    char *zName;                         /* Name we are searching for */
000953    zName = sqlite3NameFromToken(db, pName);
000954    i = sqlite3FindDbName(db, zName);
000955    sqlite3DbFree(db, zName);
000956    return i;
000957  }
000958  
000959  /* The table or view or trigger name is passed to this routine via tokens
000960  ** pName1 and pName2. If the table name was fully qualified, for example:
000961  **
000962  ** CREATE TABLE xxx.yyy (...);
000963  **
000964  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
000965  ** the table name is not fully qualified, i.e.:
000966  **
000967  ** CREATE TABLE yyy(...);
000968  **
000969  ** Then pName1 is set to "yyy" and pName2 is "".
000970  **
000971  ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
000972  ** pName2) that stores the unqualified table name.  The index of the
000973  ** database "xxx" is returned.
000974  */
000975  int sqlite3TwoPartName(
000976    Parse *pParse,      /* Parsing and code generating context */
000977    Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
000978    Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
000979    Token **pUnqual     /* Write the unqualified object name here */
000980  ){
000981    int iDb;                    /* Database holding the object */
000982    sqlite3 *db = pParse->db;
000983  
000984    assert( pName2!=0 );
000985    if( pName2->n>0 ){
000986      if( db->init.busy ) {
000987        sqlite3ErrorMsg(pParse, "corrupt database");
000988        return -1;
000989      }
000990      *pUnqual = pName2;
000991      iDb = sqlite3FindDb(db, pName1);
000992      if( iDb<0 ){
000993        sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
000994        return -1;
000995      }
000996    }else{
000997      assert( db->init.iDb==0 || db->init.busy || IN_SPECIAL_PARSE
000998               || (db->mDbFlags & DBFLAG_Vacuum)!=0);
000999      iDb = db->init.iDb;
001000      *pUnqual = pName1;
001001    }
001002    return iDb;
001003  }
001004  
001005  /*
001006  ** True if PRAGMA writable_schema is ON
001007  */
001008  int sqlite3WritableSchema(sqlite3 *db){
001009    testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
001010    testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
001011                 SQLITE_WriteSchema );
001012    testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
001013                 SQLITE_Defensive );
001014    testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
001015                 (SQLITE_WriteSchema|SQLITE_Defensive) );
001016    return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
001017  }
001018  
001019  /*
001020  ** This routine is used to check if the UTF-8 string zName is a legal
001021  ** unqualified name for a new schema object (table, index, view or
001022  ** trigger). All names are legal except those that begin with the string
001023  ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
001024  ** is reserved for internal use.
001025  **
001026  ** When parsing the sqlite_schema table, this routine also checks to
001027  ** make sure the "type", "name", and "tbl_name" columns are consistent
001028  ** with the SQL.
001029  */
001030  int sqlite3CheckObjectName(
001031    Parse *pParse,            /* Parsing context */
001032    const char *zName,        /* Name of the object to check */
001033    const char *zType,        /* Type of this object */
001034    const char *zTblName      /* Parent table name for triggers and indexes */
001035  ){
001036    sqlite3 *db = pParse->db;
001037    if( sqlite3WritableSchema(db)
001038     || db->init.imposterTable
001039     || !sqlite3Config.bExtraSchemaChecks
001040    ){
001041      /* Skip these error checks for writable_schema=ON */
001042      return SQLITE_OK;
001043    }
001044    if( db->init.busy ){
001045      if( sqlite3_stricmp(zType, db->init.azInit[0])
001046       || sqlite3_stricmp(zName, db->init.azInit[1])
001047       || sqlite3_stricmp(zTblName, db->init.azInit[2])
001048      ){
001049        sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */
001050        return SQLITE_ERROR;
001051      }
001052    }else{
001053      if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
001054       || (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName))
001055      ){
001056        sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s",
001057                        zName);
001058        return SQLITE_ERROR;
001059      }
001060  
001061    }
001062    return SQLITE_OK;
001063  }
001064  
001065  /*
001066  ** Return the PRIMARY KEY index of a table
001067  */
001068  Index *sqlite3PrimaryKeyIndex(Table *pTab){
001069    Index *p;
001070    for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
001071    return p;
001072  }
001073  
001074  /*
001075  ** Convert an table column number into a index column number.  That is,
001076  ** for the column iCol in the table (as defined by the CREATE TABLE statement)
001077  ** find the (first) offset of that column in index pIdx.  Or return -1
001078  ** if column iCol is not used in index pIdx.
001079  */
001080  int sqlite3TableColumnToIndex(Index *pIdx, int iCol){
001081    int i;
001082    i16 iCol16;
001083    assert( iCol>=(-1) && iCol<=SQLITE_MAX_COLUMN );
001084    assert( pIdx->nColumn<=SQLITE_MAX_COLUMN*2 );
001085    iCol16 = iCol;
001086    for(i=0; i<pIdx->nColumn; i++){
001087      if( iCol16==pIdx->aiColumn[i] ){
001088        return i;
001089      }
001090    }
001091    return -1;
001092  }
001093  
001094  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
001095  /* Convert a storage column number into a table column number.
001096  **
001097  ** The storage column number (0,1,2,....) is the index of the value
001098  ** as it appears in the record on disk.  The true column number
001099  ** is the index (0,1,2,...) of the column in the CREATE TABLE statement.
001100  **
001101  ** The storage column number is less than the table column number if
001102  ** and only there are VIRTUAL columns to the left.
001103  **
001104  ** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro.
001105  */
001106  i16 sqlite3StorageColumnToTable(Table *pTab, i16 iCol){
001107    if( pTab->tabFlags & TF_HasVirtual ){
001108      int i;
001109      for(i=0; i<=iCol; i++){
001110        if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++;
001111      }
001112    }
001113    return iCol;
001114  }
001115  #endif
001116  
001117  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
001118  /* Convert a table column number into a storage column number.
001119  **
001120  ** The storage column number (0,1,2,....) is the index of the value
001121  ** as it appears in the record on disk.  Or, if the input column is
001122  ** the N-th virtual column (zero-based) then the storage number is
001123  ** the number of non-virtual columns in the table plus N. 
001124  **
001125  ** The true column number is the index (0,1,2,...) of the column in
001126  ** the CREATE TABLE statement.
001127  **
001128  ** If the input column is a VIRTUAL column, then it should not appear
001129  ** in storage.  But the value sometimes is cached in registers that
001130  ** follow the range of registers used to construct storage.  This
001131  ** avoids computing the same VIRTUAL column multiple times, and provides
001132  ** values for use by OP_Param opcodes in triggers.  Hence, if the
001133  ** input column is a VIRTUAL table, put it after all the other columns.
001134  **
001135  ** In the following, N means "normal column", S means STORED, and
001136  ** V means VIRTUAL.  Suppose the CREATE TABLE has columns like this:
001137  **
001138  **        CREATE TABLE ex(N,S,V,N,S,V,N,S,V);
001139  **                     -- 0 1 2 3 4 5 6 7 8
001140  **
001141  ** Then the mapping from this function is as follows:
001142  **
001143  **    INPUTS:     0 1 2 3 4 5 6 7 8
001144  **    OUTPUTS:    0 1 6 2 3 7 4 5 8
001145  **
001146  ** So, in other words, this routine shifts all the virtual columns to
001147  ** the end.
001148  **
001149  ** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and
001150  ** this routine is a no-op macro.  If the pTab does not have any virtual
001151  ** columns, then this routine is no-op that always return iCol.  If iCol
001152  ** is negative (indicating the ROWID column) then this routine return iCol.
001153  */
001154  i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){
001155    int i;
001156    i16 n;
001157    assert( iCol<pTab->nCol );
001158    if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol;
001159    for(i=0, n=0; i<iCol; i++){
001160      if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++;
001161    }
001162    if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){
001163      /* iCol is a virtual column itself */
001164      return pTab->nNVCol + i - n;
001165    }else{
001166      /* iCol is a normal or stored column */
001167      return n;
001168    }
001169  }
001170  #endif
001171  
001172  /*
001173  ** Insert a single OP_JournalMode query opcode in order to force the
001174  ** prepared statement to return false for sqlite3_stmt_readonly().  This
001175  ** is used by CREATE TABLE IF NOT EXISTS and similar if the table already
001176  ** exists, so that the prepared statement for CREATE TABLE IF NOT EXISTS
001177  ** will return false for sqlite3_stmt_readonly() even if that statement
001178  ** is a read-only no-op.
001179  */
001180  static void sqlite3ForceNotReadOnly(Parse *pParse){
001181    int iReg = ++pParse->nMem;
001182    Vdbe *v = sqlite3GetVdbe(pParse);
001183    if( v ){
001184      sqlite3VdbeAddOp3(v, OP_JournalMode, 0, iReg, PAGER_JOURNALMODE_QUERY);
001185      sqlite3VdbeUsesBtree(v, 0);
001186    }
001187  }
001188  
001189  /*
001190  ** Begin constructing a new table representation in memory.  This is
001191  ** the first of several action routines that get called in response
001192  ** to a CREATE TABLE statement.  In particular, this routine is called
001193  ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
001194  ** flag is true if the table should be stored in the auxiliary database
001195  ** file instead of in the main database file.  This is normally the case
001196  ** when the "TEMP" or "TEMPORARY" keyword occurs in between
001197  ** CREATE and TABLE.
001198  **
001199  ** The new table record is initialized and put in pParse->pNewTable.
001200  ** As more of the CREATE TABLE statement is parsed, additional action
001201  ** routines will be called to add more information to this record.
001202  ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
001203  ** is called to complete the construction of the new table record.
001204  */
001205  void sqlite3StartTable(
001206    Parse *pParse,   /* Parser context */
001207    Token *pName1,   /* First part of the name of the table or view */
001208    Token *pName2,   /* Second part of the name of the table or view */
001209    int isTemp,      /* True if this is a TEMP table */
001210    int isView,      /* True if this is a VIEW */
001211    int isVirtual,   /* True if this is a VIRTUAL table */
001212    int noErr        /* Do nothing if table already exists */
001213  ){
001214    Table *pTable;
001215    char *zName = 0; /* The name of the new table */
001216    sqlite3 *db = pParse->db;
001217    Vdbe *v;
001218    int iDb;         /* Database number to create the table in */
001219    Token *pName;    /* Unqualified name of the table to create */
001220  
001221    if( db->init.busy && db->init.newTnum==1 ){
001222      /* Special case:  Parsing the sqlite_schema or sqlite_temp_schema schema */
001223      iDb = db->init.iDb;
001224      zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
001225      pName = pName1;
001226    }else{
001227      /* The common case */
001228      iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
001229      if( iDb<0 ) return;
001230      if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
001231        /* If creating a temp table, the name may not be qualified. Unless
001232        ** the database name is "temp" anyway.  */
001233        sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
001234        return;
001235      }
001236      if( !OMIT_TEMPDB && isTemp ) iDb = 1;
001237      zName = sqlite3NameFromToken(db, pName);
001238      if( IN_RENAME_OBJECT ){
001239        sqlite3RenameTokenMap(pParse, (void*)zName, pName);
001240      }
001241    }
001242    pParse->sNameToken = *pName;
001243    if( zName==0 ) return;
001244    if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName) ){
001245      goto begin_table_error;
001246    }
001247    if( db->init.iDb==1 ) isTemp = 1;
001248  #ifndef SQLITE_OMIT_AUTHORIZATION
001249    assert( isTemp==0 || isTemp==1 );
001250    assert( isView==0 || isView==1 );
001251    {
001252      static const u8 aCode[] = {
001253         SQLITE_CREATE_TABLE,
001254         SQLITE_CREATE_TEMP_TABLE,
001255         SQLITE_CREATE_VIEW,
001256         SQLITE_CREATE_TEMP_VIEW
001257      };
001258      char *zDb = db->aDb[iDb].zDbSName;
001259      if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
001260        goto begin_table_error;
001261      }
001262      if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
001263                                         zName, 0, zDb) ){
001264        goto begin_table_error;
001265      }
001266    }
001267  #endif
001268  
001269    /* Make sure the new table name does not collide with an existing
001270    ** index or table name in the same database.  Issue an error message if
001271    ** it does. The exception is if the statement being parsed was passed
001272    ** to an sqlite3_declare_vtab() call. In that case only the column names
001273    ** and types will be used, so there is no need to test for namespace
001274    ** collisions.
001275    */
001276    if( !IN_SPECIAL_PARSE ){
001277      char *zDb = db->aDb[iDb].zDbSName;
001278      if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
001279        goto begin_table_error;
001280      }
001281      pTable = sqlite3FindTable(db, zName, zDb);
001282      if( pTable ){
001283        if( !noErr ){
001284          sqlite3ErrorMsg(pParse, "%s %T already exists",
001285                          (IsView(pTable)? "view" : "table"), pName);
001286        }else{
001287          assert( !db->init.busy || CORRUPT_DB );
001288          sqlite3CodeVerifySchema(pParse, iDb);
001289          sqlite3ForceNotReadOnly(pParse);
001290        }
001291        goto begin_table_error;
001292      }
001293      if( sqlite3FindIndex(db, zName, zDb)!=0 ){
001294        sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
001295        goto begin_table_error;
001296      }
001297    }
001298  
001299    pTable = sqlite3DbMallocZero(db, sizeof(Table));
001300    if( pTable==0 ){
001301      assert( db->mallocFailed );
001302      pParse->rc = SQLITE_NOMEM_BKPT;
001303      pParse->nErr++;
001304      goto begin_table_error;
001305    }
001306    pTable->zName = zName;
001307    pTable->iPKey = -1;
001308    pTable->pSchema = db->aDb[iDb].pSchema;
001309    pTable->nTabRef = 1;
001310  #ifdef SQLITE_DEFAULT_ROWEST
001311    pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
001312  #else
001313    pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
001314  #endif
001315    assert( pParse->pNewTable==0 );
001316    pParse->pNewTable = pTable;
001317  
001318    /* Begin generating the code that will insert the table record into
001319    ** the schema table.  Note in particular that we must go ahead
001320    ** and allocate the record number for the table entry now.  Before any
001321    ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
001322    ** indices to be created and the table record must come before the
001323    ** indices.  Hence, the record number for the table must be allocated
001324    ** now.
001325    */
001326    if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
001327      int addr1;
001328      int fileFormat;
001329      int reg1, reg2, reg3;
001330      /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
001331      static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
001332      sqlite3BeginWriteOperation(pParse, 1, iDb);
001333  
001334  #ifndef SQLITE_OMIT_VIRTUALTABLE
001335      if( isVirtual ){
001336        sqlite3VdbeAddOp0(v, OP_VBegin);
001337      }
001338  #endif
001339  
001340      /* If the file format and encoding in the database have not been set,
001341      ** set them now.
001342      */
001343      assert( pParse->isCreate );
001344      reg1 = pParse->u1.cr.regRowid = ++pParse->nMem;
001345      reg2 = pParse->u1.cr.regRoot = ++pParse->nMem;
001346      reg3 = ++pParse->nMem;
001347      sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
001348      sqlite3VdbeUsesBtree(v, iDb);
001349      addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
001350      fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
001351                    1 : SQLITE_MAX_FILE_FORMAT;
001352      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
001353      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
001354      sqlite3VdbeJumpHere(v, addr1);
001355  
001356      /* This just creates a place-holder record in the sqlite_schema table.
001357      ** The record created does not contain anything yet.  It will be replaced
001358      ** by the real entry in code generated at sqlite3EndTable().
001359      **
001360      ** The rowid for the new entry is left in register pParse->u1.cr.regRowid.
001361      ** The root page of the new table is left in reg pParse->u1.cr.regRoot.
001362      ** The rowid and root page number values are needed by the code that
001363      ** sqlite3EndTable will generate.
001364      */
001365  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
001366      if( isView || isVirtual ){
001367        sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
001368      }else
001369  #endif
001370      {
001371        assert( !pParse->bReturning );
001372        pParse->u1.cr.addrCrTab =
001373           sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
001374      }
001375      sqlite3OpenSchemaTable(pParse, iDb);
001376      sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
001377      sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
001378      sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
001379      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
001380      sqlite3VdbeAddOp0(v, OP_Close);
001381    }else if( db->init.imposterTable ){
001382      pTable->tabFlags |= TF_Imposter;
001383      if( db->init.imposterTable>=2 ) pTable->tabFlags |= TF_Readonly;
001384    }
001385  
001386    /* Normal (non-error) return. */
001387    return;
001388  
001389    /* If an error occurs, we jump here */
001390  begin_table_error:
001391    pParse->checkSchema = 1;
001392    sqlite3DbFree(db, zName);
001393    return;
001394  }
001395  
001396  /* Set properties of a table column based on the (magical)
001397  ** name of the column.
001398  */
001399  #if SQLITE_ENABLE_HIDDEN_COLUMNS
001400  void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
001401    if( sqlite3_strnicmp(pCol->zCnName, "__hidden__", 10)==0 ){
001402      pCol->colFlags |= COLFLAG_HIDDEN;
001403      if( pTab ) pTab->tabFlags |= TF_HasHidden;
001404    }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
001405      pTab->tabFlags |= TF_OOOHidden;
001406    }
001407  }
001408  #endif
001409  
001410  /*
001411  ** Clean up the data structures associated with the RETURNING clause.
001412  */
001413  static void sqlite3DeleteReturning(sqlite3 *db, void *pArg){
001414    Returning *pRet = (Returning*)pArg;
001415    Hash *pHash;
001416    pHash = &(db->aDb[1].pSchema->trigHash);
001417    sqlite3HashInsert(pHash, pRet->zName, 0);
001418    sqlite3ExprListDelete(db, pRet->pReturnEL);
001419    sqlite3DbFree(db, pRet);
001420  }
001421  
001422  /*
001423  ** Add the RETURNING clause to the parse currently underway.
001424  **
001425  ** This routine creates a special TEMP trigger that will fire for each row
001426  ** of the DML statement.  That TEMP trigger contains a single SELECT
001427  ** statement with a result set that is the argument of the RETURNING clause.
001428  ** The trigger has the Trigger.bReturning flag and an opcode of
001429  ** TK_RETURNING instead of TK_SELECT, so that the trigger code generator
001430  ** knows to handle it specially.  The TEMP trigger is automatically
001431  ** removed at the end of the parse.
001432  **
001433  ** When this routine is called, we do not yet know if the RETURNING clause
001434  ** is attached to a DELETE, INSERT, or UPDATE, so construct it as a
001435  ** RETURNING trigger instead.  It will then be converted into the appropriate
001436  ** type on the first call to sqlite3TriggersExist().
001437  */
001438  void sqlite3AddReturning(Parse *pParse, ExprList *pList){
001439    Returning *pRet;
001440    Hash *pHash;
001441    sqlite3 *db = pParse->db;
001442    if( pParse->pNewTrigger ){
001443      sqlite3ErrorMsg(pParse, "cannot use RETURNING in a trigger");
001444    }else{
001445      assert( pParse->bReturning==0 || pParse->ifNotExists );
001446    }
001447    pParse->bReturning = 1;
001448    pRet = sqlite3DbMallocZero(db, sizeof(*pRet));
001449    if( pRet==0 ){
001450      sqlite3ExprListDelete(db, pList);
001451      return;
001452    }
001453    assert( !pParse->isCreate );
001454    pParse->u1.d.pReturning = pRet;
001455    pRet->pParse = pParse;
001456    pRet->pReturnEL = pList;
001457    sqlite3ParserAddCleanup(pParse, sqlite3DeleteReturning, pRet);
001458    testcase( pParse->earlyCleanup );
001459    if( db->mallocFailed ) return;
001460    sqlite3_snprintf(sizeof(pRet->zName), pRet->zName,
001461                     "sqlite_returning_%p", pParse);
001462    pRet->retTrig.zName = pRet->zName;
001463    pRet->retTrig.op = TK_RETURNING;
001464    pRet->retTrig.tr_tm = TRIGGER_AFTER;
001465    pRet->retTrig.bReturning = 1;
001466    pRet->retTrig.pSchema = db->aDb[1].pSchema;
001467    pRet->retTrig.pTabSchema = db->aDb[1].pSchema;
001468    pRet->retTrig.step_list = &pRet->retTStep;
001469    pRet->retTStep.op = TK_RETURNING;
001470    pRet->retTStep.pTrig = &pRet->retTrig;
001471    pRet->retTStep.pExprList = pList;
001472    pHash = &(db->aDb[1].pSchema->trigHash);
001473    assert( sqlite3HashFind(pHash, pRet->zName)==0
001474            || pParse->nErr  || pParse->ifNotExists );
001475    if( sqlite3HashInsert(pHash, pRet->zName, &pRet->retTrig)
001476            ==&pRet->retTrig ){
001477      sqlite3OomFault(db);
001478    }
001479  }
001480  
001481  /*
001482  ** Add a new column to the table currently being constructed.
001483  **
001484  ** The parser calls this routine once for each column declaration
001485  ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
001486  ** first to get things going.  Then this routine is called for each
001487  ** column.
001488  */
001489  void sqlite3AddColumn(Parse *pParse, Token sName, Token sType){
001490    Table *p;
001491    int i;
001492    char *z;
001493    char *zType;
001494    Column *pCol;
001495    sqlite3 *db = pParse->db;
001496    Column *aNew;
001497    u8 eType = COLTYPE_CUSTOM;
001498    u8 szEst = 1;
001499    char affinity = SQLITE_AFF_BLOB;
001500  
001501    if( (p = pParse->pNewTable)==0 ) return;
001502    if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
001503      sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
001504      return;
001505    }
001506    if( !IN_RENAME_OBJECT ) sqlite3DequoteToken(&sName);
001507  
001508    /* Because keywords GENERATE ALWAYS can be converted into identifiers
001509    ** by the parser, we can sometimes end up with a typename that ends
001510    ** with "generated always".  Check for this case and omit the surplus
001511    ** text. */
001512    if( sType.n>=16
001513     && sqlite3_strnicmp(sType.z+(sType.n-6),"always",6)==0
001514    ){
001515      sType.n -= 6;
001516      while( ALWAYS(sType.n>0) && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
001517      if( sType.n>=9
001518       && sqlite3_strnicmp(sType.z+(sType.n-9),"generated",9)==0
001519      ){
001520        sType.n -= 9;
001521        while( sType.n>0 && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
001522      }
001523    }
001524  
001525    /* Check for standard typenames.  For standard typenames we will
001526    ** set the Column.eType field rather than storing the typename after
001527    ** the column name, in order to save space. */
001528    if( sType.n>=3 ){
001529      sqlite3DequoteToken(&sType);
001530      for(i=0; i<SQLITE_N_STDTYPE; i++){
001531         if( sType.n==sqlite3StdTypeLen[i]
001532          && sqlite3_strnicmp(sType.z, sqlite3StdType[i], sType.n)==0
001533         ){
001534           sType.n = 0;
001535           eType = i+1;
001536           affinity = sqlite3StdTypeAffinity[i];
001537           if( affinity<=SQLITE_AFF_TEXT ) szEst = 5;
001538           break;
001539         }
001540      }
001541    }
001542  
001543    z = sqlite3DbMallocRaw(db, (i64)sName.n + 1 + (i64)sType.n + (sType.n>0) );
001544    if( z==0 ) return;
001545    if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, &sName);
001546    memcpy(z, sName.z, sName.n);
001547    z[sName.n] = 0;
001548    sqlite3Dequote(z);
001549    if( p->nCol && sqlite3ColumnIndex(p, z)>=0 ){
001550      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
001551      sqlite3DbFree(db, z);
001552      return;
001553    }
001554    aNew = sqlite3DbRealloc(db,p->aCol,((i64)p->nCol+1)*sizeof(p->aCol[0]));
001555    if( aNew==0 ){
001556      sqlite3DbFree(db, z);
001557      return;
001558    }
001559    p->aCol = aNew;
001560    pCol = &p->aCol[p->nCol];
001561    memset(pCol, 0, sizeof(p->aCol[0]));
001562    pCol->zCnName = z;
001563    pCol->hName = sqlite3StrIHash(z);
001564    sqlite3ColumnPropertiesFromName(p, pCol);
001565  
001566    if( sType.n==0 ){
001567      /* If there is no type specified, columns have the default affinity
001568      ** 'BLOB' with a default size of 4 bytes. */
001569      pCol->affinity = affinity;
001570      pCol->eCType = eType;
001571      pCol->szEst = szEst;
001572  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
001573      if( affinity==SQLITE_AFF_BLOB ){
001574        if( 4>=sqlite3GlobalConfig.szSorterRef ){
001575          pCol->colFlags |= COLFLAG_SORTERREF;
001576        }
001577      }
001578  #endif
001579    }else{
001580      zType = z + sqlite3Strlen30(z) + 1;
001581      memcpy(zType, sType.z, sType.n);
001582      zType[sType.n] = 0;
001583      sqlite3Dequote(zType);
001584      pCol->affinity = sqlite3AffinityType(zType, pCol);
001585      pCol->colFlags |= COLFLAG_HASTYPE;
001586    }
001587    if( p->nCol<=0xff ){
001588      u8 h = pCol->hName % sizeof(p->aHx);
001589      p->aHx[h] = p->nCol;
001590    }
001591    p->nCol++;
001592    p->nNVCol++;
001593    assert( pParse->isCreate );
001594    pParse->u1.cr.constraintName.n = 0;
001595  }
001596  
001597  /*
001598  ** This routine is called by the parser while in the middle of
001599  ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
001600  ** been seen on a column.  This routine sets the notNull flag on
001601  ** the column currently under construction.
001602  */
001603  void sqlite3AddNotNull(Parse *pParse, int onError){
001604    Table *p;
001605    Column *pCol;
001606    p = pParse->pNewTable;
001607    if( p==0 || NEVER(p->nCol<1) ) return;
001608    pCol = &p->aCol[p->nCol-1];
001609    pCol->notNull = (u8)onError;
001610    p->tabFlags |= TF_HasNotNull;
001611  
001612    /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
001613    ** on this column.  */
001614    if( pCol->colFlags & COLFLAG_UNIQUE ){
001615      Index *pIdx;
001616      for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
001617        assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
001618        if( pIdx->aiColumn[0]==p->nCol-1 ){
001619          pIdx->uniqNotNull = 1;
001620        }
001621      }
001622    }
001623  }
001624  
001625  /*
001626  ** Scan the column type name zType (length nType) and return the
001627  ** associated affinity type.
001628  **
001629  ** This routine does a case-independent search of zType for the
001630  ** substrings in the following table. If one of the substrings is
001631  ** found, the corresponding affinity is returned. If zType contains
001632  ** more than one of the substrings, entries toward the top of
001633  ** the table take priority. For example, if zType is 'BLOBINT',
001634  ** SQLITE_AFF_INTEGER is returned.
001635  **
001636  ** Substring     | Affinity
001637  ** --------------------------------
001638  ** 'INT'         | SQLITE_AFF_INTEGER
001639  ** 'CHAR'        | SQLITE_AFF_TEXT
001640  ** 'CLOB'        | SQLITE_AFF_TEXT
001641  ** 'TEXT'        | SQLITE_AFF_TEXT
001642  ** 'BLOB'        | SQLITE_AFF_BLOB
001643  ** 'REAL'        | SQLITE_AFF_REAL
001644  ** 'FLOA'        | SQLITE_AFF_REAL
001645  ** 'DOUB'        | SQLITE_AFF_REAL
001646  **
001647  ** If none of the substrings in the above table are found,
001648  ** SQLITE_AFF_NUMERIC is returned.
001649  */
001650  char sqlite3AffinityType(const char *zIn, Column *pCol){
001651    u32 h = 0;
001652    char aff = SQLITE_AFF_NUMERIC;
001653    const char *zChar = 0;
001654  
001655    assert( zIn!=0 );
001656    while( zIn[0] ){
001657      u8 x = *(u8*)zIn;
001658      h = (h<<8) + sqlite3UpperToLower[x];
001659      zIn++;
001660      if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
001661        aff = SQLITE_AFF_TEXT;
001662        zChar = zIn;
001663      }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
001664        aff = SQLITE_AFF_TEXT;
001665      }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
001666        aff = SQLITE_AFF_TEXT;
001667      }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
001668          && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
001669        aff = SQLITE_AFF_BLOB;
001670        if( zIn[0]=='(' ) zChar = zIn;
001671  #ifndef SQLITE_OMIT_FLOATING_POINT
001672      }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
001673          && aff==SQLITE_AFF_NUMERIC ){
001674        aff = SQLITE_AFF_REAL;
001675      }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
001676          && aff==SQLITE_AFF_NUMERIC ){
001677        aff = SQLITE_AFF_REAL;
001678      }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
001679          && aff==SQLITE_AFF_NUMERIC ){
001680        aff = SQLITE_AFF_REAL;
001681  #endif
001682      }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
001683        aff = SQLITE_AFF_INTEGER;
001684        break;
001685      }
001686    }
001687  
001688    /* If pCol is not NULL, store an estimate of the field size.  The
001689    ** estimate is scaled so that the size of an integer is 1.  */
001690    if( pCol ){
001691      int v = 0;   /* default size is approx 4 bytes */
001692      if( aff<SQLITE_AFF_NUMERIC ){
001693        if( zChar ){
001694          while( zChar[0] ){
001695            if( sqlite3Isdigit(zChar[0]) ){
001696              /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
001697              sqlite3GetInt32(zChar, &v);
001698              break;
001699            }
001700            zChar++;
001701          }
001702        }else{
001703          v = 16;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
001704        }
001705      }
001706  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
001707      if( v>=sqlite3GlobalConfig.szSorterRef ){
001708        pCol->colFlags |= COLFLAG_SORTERREF;
001709      }
001710  #endif
001711      v = v/4 + 1;
001712      if( v>255 ) v = 255;
001713      pCol->szEst = v;
001714    }
001715    return aff;
001716  }
001717  
001718  /*
001719  ** The expression is the default value for the most recently added column
001720  ** of the table currently under construction.
001721  **
001722  ** Default value expressions must be constant.  Raise an exception if this
001723  ** is not the case.
001724  **
001725  ** This routine is called by the parser while in the middle of
001726  ** parsing a CREATE TABLE statement.
001727  */
001728  void sqlite3AddDefaultValue(
001729    Parse *pParse,           /* Parsing context */
001730    Expr *pExpr,             /* The parsed expression of the default value */
001731    const char *zStart,      /* Start of the default value text */
001732    const char *zEnd         /* First character past end of default value text */
001733  ){
001734    Table *p;
001735    Column *pCol;
001736    sqlite3 *db = pParse->db;
001737    p = pParse->pNewTable;
001738    if( p!=0 ){
001739      int isInit = db->init.busy && db->init.iDb!=1;
001740      pCol = &(p->aCol[p->nCol-1]);
001741      if( !sqlite3ExprIsConstantOrFunction(pExpr, isInit) ){
001742        sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
001743            pCol->zCnName);
001744  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
001745      }else if( pCol->colFlags & COLFLAG_GENERATED ){
001746        testcase( pCol->colFlags & COLFLAG_VIRTUAL );
001747        testcase( pCol->colFlags & COLFLAG_STORED );
001748        sqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column");
001749  #endif
001750      }else{
001751        /* A copy of pExpr is used instead of the original, as pExpr contains
001752        ** tokens that point to volatile memory.
001753        */
001754        Expr x, *pDfltExpr;
001755        memset(&x, 0, sizeof(x));
001756        x.op = TK_SPAN;
001757        x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
001758        x.pLeft = pExpr;
001759        x.flags = EP_Skip;
001760        pDfltExpr = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
001761        sqlite3DbFree(db, x.u.zToken);
001762        sqlite3ColumnSetExpr(pParse, p, pCol, pDfltExpr);
001763      }
001764    }
001765    if( IN_RENAME_OBJECT ){
001766      sqlite3RenameExprUnmap(pParse, pExpr);
001767    }
001768    sqlite3ExprDelete(db, pExpr);
001769  }
001770  
001771  /*
001772  ** Backwards Compatibility Hack:
001773  **
001774  ** Historical versions of SQLite accepted strings as column names in
001775  ** indexes and PRIMARY KEY constraints and in UNIQUE constraints.  Example:
001776  **
001777  **     CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
001778  **     CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
001779  **
001780  ** This is goofy.  But to preserve backwards compatibility we continue to
001781  ** accept it.  This routine does the necessary conversion.  It converts
001782  ** the expression given in its argument from a TK_STRING into a TK_ID
001783  ** if the expression is just a TK_STRING with an optional COLLATE clause.
001784  ** If the expression is anything other than TK_STRING, the expression is
001785  ** unchanged.
001786  */
001787  static void sqlite3StringToId(Expr *p){
001788    if( p->op==TK_STRING ){
001789      p->op = TK_ID;
001790    }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
001791      p->pLeft->op = TK_ID;
001792    }
001793  }
001794  
001795  /*
001796  ** Tag the given column as being part of the PRIMARY KEY
001797  */
001798  static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){
001799    pCol->colFlags |= COLFLAG_PRIMKEY;
001800  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
001801    if( pCol->colFlags & COLFLAG_GENERATED ){
001802      testcase( pCol->colFlags & COLFLAG_VIRTUAL );
001803      testcase( pCol->colFlags & COLFLAG_STORED );
001804      sqlite3ErrorMsg(pParse,
001805        "generated columns cannot be part of the PRIMARY KEY");
001806    }
001807  #endif         
001808  }
001809  
001810  /*
001811  ** Designate the PRIMARY KEY for the table.  pList is a list of names
001812  ** of columns that form the primary key.  If pList is NULL, then the
001813  ** most recently added column of the table is the primary key.
001814  **
001815  ** A table can have at most one primary key.  If the table already has
001816  ** a primary key (and this is the second primary key) then create an
001817  ** error.
001818  **
001819  ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
001820  ** then we will try to use that column as the rowid.  Set the Table.iPKey
001821  ** field of the table under construction to be the index of the
001822  ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
001823  ** no INTEGER PRIMARY KEY.
001824  **
001825  ** If the key is not an INTEGER PRIMARY KEY, then create a unique
001826  ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
001827  */
001828  void sqlite3AddPrimaryKey(
001829    Parse *pParse,    /* Parsing context */
001830    ExprList *pList,  /* List of field names to be indexed */
001831    int onError,      /* What to do with a uniqueness conflict */
001832    int autoInc,      /* True if the AUTOINCREMENT keyword is present */
001833    int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
001834  ){
001835    Table *pTab = pParse->pNewTable;
001836    Column *pCol = 0;
001837    int iCol = -1, i;
001838    int nTerm;
001839    if( pTab==0 ) goto primary_key_exit;
001840    if( pTab->tabFlags & TF_HasPrimaryKey ){
001841      sqlite3ErrorMsg(pParse,
001842        "table \"%s\" has more than one primary key", pTab->zName);
001843      goto primary_key_exit;
001844    }
001845    pTab->tabFlags |= TF_HasPrimaryKey;
001846    if( pList==0 ){
001847      iCol = pTab->nCol - 1;
001848      pCol = &pTab->aCol[iCol];
001849      makeColumnPartOfPrimaryKey(pParse, pCol);
001850      nTerm = 1;
001851    }else{
001852      nTerm = pList->nExpr;
001853      for(i=0; i<nTerm; i++){
001854        Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
001855        assert( pCExpr!=0 );
001856        sqlite3StringToId(pCExpr);
001857        if( pCExpr->op==TK_ID ){
001858          assert( !ExprHasProperty(pCExpr, EP_IntValue) );
001859          iCol = sqlite3ColumnIndex(pTab, pCExpr->u.zToken);
001860          if( iCol>=0 ){
001861            pCol = &pTab->aCol[iCol];
001862            makeColumnPartOfPrimaryKey(pParse, pCol);
001863          }
001864        }
001865      }
001866    }
001867    if( nTerm==1
001868     && pCol
001869     && pCol->eCType==COLTYPE_INTEGER
001870     && sortOrder!=SQLITE_SO_DESC
001871    ){
001872      if( IN_RENAME_OBJECT && pList ){
001873        Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
001874        sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
001875      }
001876      pTab->iPKey = iCol;
001877      pTab->keyConf = (u8)onError;
001878      assert( autoInc==0 || autoInc==1 );
001879      pTab->tabFlags |= autoInc*TF_Autoincrement;
001880      if( pList ) pParse->iPkSortOrder = pList->a[0].fg.sortFlags;
001881      (void)sqlite3HasExplicitNulls(pParse, pList);
001882    }else if( autoInc ){
001883  #ifndef SQLITE_OMIT_AUTOINCREMENT
001884      sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
001885         "INTEGER PRIMARY KEY");
001886  #endif
001887    }else{
001888      sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
001889                             0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
001890      pList = 0;
001891    }
001892  
001893  primary_key_exit:
001894    sqlite3ExprListDelete(pParse->db, pList);
001895    return;
001896  }
001897  
001898  /*
001899  ** Add a new CHECK constraint to the table currently under construction.
001900  */
001901  void sqlite3AddCheckConstraint(
001902    Parse *pParse,      /* Parsing context */
001903    Expr *pCheckExpr,   /* The check expression */
001904    const char *zStart, /* Opening "(" */
001905    const char *zEnd    /* Closing ")" */
001906  ){
001907  #ifndef SQLITE_OMIT_CHECK
001908    Table *pTab = pParse->pNewTable;
001909    sqlite3 *db = pParse->db;
001910    if( pTab && !IN_DECLARE_VTAB
001911     && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
001912    ){
001913      pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
001914      assert( pParse->isCreate );
001915      if( pParse->u1.cr.constraintName.n ){
001916        sqlite3ExprListSetName(pParse, pTab->pCheck,
001917                               &pParse->u1.cr.constraintName, 1);
001918      }else{
001919        Token t;
001920        for(zStart++; sqlite3Isspace(zStart[0]); zStart++){}
001921        while( sqlite3Isspace(zEnd[-1]) ){ zEnd--; }
001922        t.z = zStart;
001923        t.n = (int)(zEnd - t.z);
001924        sqlite3ExprListSetName(pParse, pTab->pCheck, &t, 1);   
001925      }
001926    }else
001927  #endif
001928    {
001929      sqlite3ExprDelete(pParse->db, pCheckExpr);
001930    }
001931  }
001932  
001933  /*
001934  ** Set the collation function of the most recently parsed table column
001935  ** to the CollSeq given.
001936  */
001937  void sqlite3AddCollateType(Parse *pParse, Token *pToken){
001938    Table *p;
001939    int i;
001940    char *zColl;              /* Dequoted name of collation sequence */
001941    sqlite3 *db;
001942  
001943    if( (p = pParse->pNewTable)==0 || IN_RENAME_OBJECT ) return;
001944    i = p->nCol-1;
001945    db = pParse->db;
001946    zColl = sqlite3NameFromToken(db, pToken);
001947    if( !zColl ) return;
001948  
001949    if( sqlite3LocateCollSeq(pParse, zColl) ){
001950      Index *pIdx;
001951      sqlite3ColumnSetColl(db, &p->aCol[i], zColl);
001952   
001953      /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
001954      ** then an index may have been created on this column before the
001955      ** collation type was added. Correct this if it is the case.
001956      */
001957      for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
001958        assert( pIdx->nKeyCol==1 );
001959        if( pIdx->aiColumn[0]==i ){
001960          pIdx->azColl[0] = sqlite3ColumnColl(&p->aCol[i]);
001961        }
001962      }
001963    }
001964    sqlite3DbFree(db, zColl);
001965  }
001966  
001967  /* Change the most recently parsed column to be a GENERATED ALWAYS AS
001968  ** column.
001969  */
001970  void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){
001971  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
001972    u8 eType = COLFLAG_VIRTUAL;
001973    Table *pTab = pParse->pNewTable;
001974    Column *pCol;
001975    if( pTab==0 ){
001976      /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */
001977      goto generated_done;
001978    }
001979    pCol = &(pTab->aCol[pTab->nCol-1]);
001980    if( IN_DECLARE_VTAB ){
001981      sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns");
001982      goto generated_done;
001983    }
001984    if( pCol->iDflt>0 ) goto generated_error;
001985    if( pType ){
001986      if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){
001987        /* no-op */
001988      }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){
001989        eType = COLFLAG_STORED;
001990      }else{
001991        goto generated_error;
001992      }
001993    }
001994    if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--;
001995    pCol->colFlags |= eType;
001996    assert( TF_HasVirtual==COLFLAG_VIRTUAL );
001997    assert( TF_HasStored==COLFLAG_STORED );
001998    pTab->tabFlags |= eType;
001999    if( pCol->colFlags & COLFLAG_PRIMKEY ){
002000      makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */
002001    }
002002    if( ALWAYS(pExpr) && pExpr->op==TK_ID ){
002003      /* The value of a generated column needs to be a real expression, not
002004      ** just a reference to another column, in order for covering index
002005      ** optimizations to work correctly.  So if the value is not an expression,
002006      ** turn it into one by adding a unary "+" operator. */
002007      pExpr = sqlite3PExpr(pParse, TK_UPLUS, pExpr, 0);
002008    }
002009    if( pExpr && pExpr->op!=TK_RAISE ) pExpr->affExpr = pCol->affinity;
002010    sqlite3ColumnSetExpr(pParse, pTab, pCol, pExpr);
002011    pExpr = 0;
002012    goto generated_done;
002013  
002014  generated_error:
002015    sqlite3ErrorMsg(pParse, "error in generated column \"%s\"",
002016                    pCol->zCnName);
002017  generated_done:
002018    sqlite3ExprDelete(pParse->db, pExpr);
002019  #else
002020    /* Throw and error for the GENERATED ALWAYS AS clause if the
002021    ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
002022    sqlite3ErrorMsg(pParse, "generated columns not supported");
002023    sqlite3ExprDelete(pParse->db, pExpr);
002024  #endif
002025  }
002026  
002027  /*
002028  ** Generate code that will increment the schema cookie.
002029  **
002030  ** The schema cookie is used to determine when the schema for the
002031  ** database changes.  After each schema change, the cookie value
002032  ** changes.  When a process first reads the schema it records the
002033  ** cookie.  Thereafter, whenever it goes to access the database,
002034  ** it checks the cookie to make sure the schema has not changed
002035  ** since it was last read.
002036  **
002037  ** This plan is not completely bullet-proof.  It is possible for
002038  ** the schema to change multiple times and for the cookie to be
002039  ** set back to prior value.  But schema changes are infrequent
002040  ** and the probability of hitting the same cookie value is only
002041  ** 1 chance in 2^32.  So we're safe enough.
002042  **
002043  ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
002044  ** the schema-version whenever the schema changes.
002045  */
002046  void sqlite3ChangeCookie(Parse *pParse, int iDb){
002047    sqlite3 *db = pParse->db;
002048    Vdbe *v = pParse->pVdbe;
002049    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
002050    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
002051                     (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
002052  }
002053  
002054  /*
002055  ** Measure the number of characters needed to output the given
002056  ** identifier.  The number returned includes any quotes used
002057  ** but does not include the null terminator.
002058  **
002059  ** The estimate is conservative.  It might be larger that what is
002060  ** really needed.
002061  */
002062  static int identLength(const char *z){
002063    int n;
002064    for(n=0; *z; n++, z++){
002065      if( *z=='"' ){ n++; }
002066    }
002067    return n + 2;
002068  }
002069  
002070  /*
002071  ** The first parameter is a pointer to an output buffer. The second
002072  ** parameter is a pointer to an integer that contains the offset at
002073  ** which to write into the output buffer. This function copies the
002074  ** nul-terminated string pointed to by the third parameter, zSignedIdent,
002075  ** to the specified offset in the buffer and updates *pIdx to refer
002076  ** to the first byte after the last byte written before returning.
002077  **
002078  ** If the string zSignedIdent consists entirely of alphanumeric
002079  ** characters, does not begin with a digit and is not an SQL keyword,
002080  ** then it is copied to the output buffer exactly as it is. Otherwise,
002081  ** it is quoted using double-quotes.
002082  */
002083  static void identPut(char *z, int *pIdx, char *zSignedIdent){
002084    unsigned char *zIdent = (unsigned char*)zSignedIdent;
002085    int i, j, needQuote;
002086    i = *pIdx;
002087  
002088    for(j=0; zIdent[j]; j++){
002089      if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
002090    }
002091    needQuote = sqlite3Isdigit(zIdent[0])
002092              || sqlite3KeywordCode(zIdent, j)!=TK_ID
002093              || zIdent[j]!=0
002094              || j==0;
002095  
002096    if( needQuote ) z[i++] = '"';
002097    for(j=0; zIdent[j]; j++){
002098      z[i++] = zIdent[j];
002099      if( zIdent[j]=='"' ) z[i++] = '"';
002100    }
002101    if( needQuote ) z[i++] = '"';
002102    z[i] = 0;
002103    *pIdx = i;
002104  }
002105  
002106  /*
002107  ** Generate a CREATE TABLE statement appropriate for the given
002108  ** table.  Memory to hold the text of the statement is obtained
002109  ** from sqliteMalloc() and must be freed by the calling function.
002110  */
002111  static char *createTableStmt(sqlite3 *db, Table *p){
002112    int i, k, len;
002113    i64 n;
002114    char *zStmt;
002115    char *zSep, *zSep2, *zEnd;
002116    Column *pCol;
002117    n = 0;
002118    for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
002119      n += identLength(pCol->zCnName) + 5;
002120    }
002121    n += identLength(p->zName);
002122    if( n<50 ){
002123      zSep = "";
002124      zSep2 = ",";
002125      zEnd = ")";
002126    }else{
002127      zSep = "\n  ";
002128      zSep2 = ",\n  ";
002129      zEnd = "\n)";
002130    }
002131    n += 35 + 6*p->nCol;
002132    zStmt = sqlite3DbMallocRaw(0, n);
002133    if( zStmt==0 ){
002134      sqlite3OomFault(db);
002135      return 0;
002136    }
002137    assert( n>14 && n<=0x7fffffff );
002138    memcpy(zStmt, "CREATE TABLE ", 13);
002139    k = 13;
002140    identPut(zStmt, &k, p->zName);
002141    zStmt[k++] = '(';
002142    for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
002143      static const char * const azType[] = {
002144          /* SQLITE_AFF_BLOB    */ "",
002145          /* SQLITE_AFF_TEXT    */ " TEXT",
002146          /* SQLITE_AFF_NUMERIC */ " NUM",
002147          /* SQLITE_AFF_INTEGER */ " INT",
002148          /* SQLITE_AFF_REAL    */ " REAL",
002149          /* SQLITE_AFF_FLEXNUM */ " NUM",
002150      };
002151      const char *zType;
002152  
002153      len = sqlite3Strlen30(zSep);
002154      assert( k+len<n );
002155      memcpy(&zStmt[k], zSep, len);
002156      k += len;
002157      zSep = zSep2;
002158      identPut(zStmt, &k, pCol->zCnName);
002159      assert( k<n );
002160      assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
002161      assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
002162      testcase( pCol->affinity==SQLITE_AFF_BLOB );
002163      testcase( pCol->affinity==SQLITE_AFF_TEXT );
002164      testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
002165      testcase( pCol->affinity==SQLITE_AFF_INTEGER );
002166      testcase( pCol->affinity==SQLITE_AFF_REAL );
002167      testcase( pCol->affinity==SQLITE_AFF_FLEXNUM );
002168     
002169      zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
002170      len = sqlite3Strlen30(zType);
002171      assert( pCol->affinity==SQLITE_AFF_BLOB
002172              || pCol->affinity==SQLITE_AFF_FLEXNUM
002173              || pCol->affinity==sqlite3AffinityType(zType, 0) );
002174      assert( k+len<n );
002175      memcpy(&zStmt[k], zType, len);
002176      k += len;
002177      assert( k<=n );
002178    }
002179    len = sqlite3Strlen30(zEnd);
002180    assert( k+len<n );
002181    memcpy(&zStmt[k], zEnd, len+1);
002182    return zStmt;
002183  }
002184  
002185  /*
002186  ** Resize an Index object to hold N columns total.  Return SQLITE_OK
002187  ** on success and SQLITE_NOMEM on an OOM error.
002188  */
002189  static int resizeIndexObject(Parse *pParse, Index *pIdx, int N){
002190    char *zExtra;
002191    u64 nByte;
002192    sqlite3 *db;
002193    if( pIdx->nColumn>=N ) return SQLITE_OK;
002194    db = pParse->db;
002195    assert( N>0 );
002196    assert( N <= SQLITE_MAX_COLUMN*2 /* tag-20250221-1 */ );
002197    testcase( N==2*pParse->db->aLimit[SQLITE_LIMIT_COLUMN] );
002198    assert( pIdx->isResized==0 );
002199    nByte = (sizeof(char*) + sizeof(LogEst) + sizeof(i16) + 1)*(u64)N;
002200    zExtra = sqlite3DbMallocZero(db, nByte);
002201    if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
002202    memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
002203    pIdx->azColl = (const char**)zExtra;
002204    zExtra += sizeof(char*)*N;
002205    memcpy(zExtra, pIdx->aiRowLogEst, sizeof(LogEst)*(pIdx->nKeyCol+1));
002206    pIdx->aiRowLogEst = (LogEst*)zExtra;
002207    zExtra += sizeof(LogEst)*N;
002208    memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
002209    pIdx->aiColumn = (i16*)zExtra;
002210    zExtra += sizeof(i16)*N;
002211    memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
002212    pIdx->aSortOrder = (u8*)zExtra;
002213    pIdx->nColumn = (u16)N;  /* See tag-20250221-1 above for proof of safety */
002214    pIdx->isResized = 1;
002215    return SQLITE_OK;
002216  }
002217  
002218  /*
002219  ** Estimate the total row width for a table.
002220  */
002221  static void estimateTableWidth(Table *pTab){
002222    unsigned wTable = 0;
002223    const Column *pTabCol;
002224    int i;
002225    for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
002226      wTable += pTabCol->szEst;
002227    }
002228    if( pTab->iPKey<0 ) wTable++;
002229    pTab->szTabRow = sqlite3LogEst(wTable*4);
002230  }
002231  
002232  /*
002233  ** Estimate the average size of a row for an index.
002234  */
002235  static void estimateIndexWidth(Index *pIdx){
002236    unsigned wIndex = 0;
002237    int i;
002238    const Column *aCol = pIdx->pTable->aCol;
002239    for(i=0; i<pIdx->nColumn; i++){
002240      i16 x = pIdx->aiColumn[i];
002241      assert( x<pIdx->pTable->nCol );
002242      wIndex += x<0 ? 1 : aCol[x].szEst;
002243    }
002244    pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
002245  }
002246  
002247  /* Return true if column number x is any of the first nCol entries of aiCol[].
002248  ** This is used to determine if the column number x appears in any of the
002249  ** first nCol entries of an index.
002250  */
002251  static int hasColumn(const i16 *aiCol, int nCol, int x){
002252    while( nCol-- > 0 ){
002253      if( x==*(aiCol++) ){
002254        return 1;
002255      }
002256    }
002257    return 0;
002258  }
002259  
002260  /*
002261  ** Return true if any of the first nKey entries of index pIdx exactly
002262  ** match the iCol-th entry of pPk.  pPk is always a WITHOUT ROWID
002263  ** PRIMARY KEY index.  pIdx is an index on the same table.  pIdx may
002264  ** or may not be the same index as pPk.
002265  **
002266  ** The first nKey entries of pIdx are guaranteed to be ordinary columns,
002267  ** not a rowid or expression.
002268  **
002269  ** This routine differs from hasColumn() in that both the column and the
002270  ** collating sequence must match for this routine, but for hasColumn() only
002271  ** the column name must match.
002272  */
002273  static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){
002274    int i, j;
002275    assert( nKey<=pIdx->nColumn );
002276    assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );
002277    assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );
002278    assert( pPk->pTable->tabFlags & TF_WithoutRowid );
002279    assert( pPk->pTable==pIdx->pTable );
002280    testcase( pPk==pIdx );
002281    j = pPk->aiColumn[iCol];
002282    assert( j!=XN_ROWID && j!=XN_EXPR );
002283    for(i=0; i<nKey; i++){
002284      assert( pIdx->aiColumn[i]>=0 || j>=0 );
002285      if( pIdx->aiColumn[i]==j
002286       && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
002287      ){
002288        return 1;
002289      }
002290    }
002291    return 0;
002292  }
002293  
002294  /* Recompute the colNotIdxed field of the Index.
002295  **
002296  ** colNotIdxed is a bitmask that has a 0 bit representing each indexed
002297  ** columns that are within the first 63 columns of the table and a 1 for
002298  ** all other bits (all columns that are not in the index).  The
002299  ** high-order bit of colNotIdxed is always 1.  All unindexed columns
002300  ** of the table have a 1.
002301  **
002302  ** 2019-10-24:  For the purpose of this computation, virtual columns are
002303  ** not considered to be covered by the index, even if they are in the
002304  ** index, because we do not trust the logic in whereIndexExprTrans() to be
002305  ** able to find all instances of a reference to the indexed table column
002306  ** and convert them into references to the index.  Hence we always want
002307  ** the actual table at hand in order to recompute the virtual column, if
002308  ** necessary.
002309  **
002310  ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
002311  ** to determine if the index is covering index.
002312  */
002313  static void recomputeColumnsNotIndexed(Index *pIdx){
002314    Bitmask m = 0;
002315    int j;
002316    Table *pTab = pIdx->pTable;
002317    for(j=pIdx->nColumn-1; j>=0; j--){
002318      int x = pIdx->aiColumn[j];
002319      if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){
002320        testcase( x==BMS-1 );
002321        testcase( x==BMS-2 );
002322        if( x<BMS-1 ) m |= MASKBIT(x);
002323      }
002324    }
002325    pIdx->colNotIdxed = ~m;
002326    assert( (pIdx->colNotIdxed>>63)==1 );  /* See note-20221022-a */
002327  }
002328  
002329  /*
002330  ** This routine runs at the end of parsing a CREATE TABLE statement that
002331  ** has a WITHOUT ROWID clause.  The job of this routine is to convert both
002332  ** internal schema data structures and the generated VDBE code so that they
002333  ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
002334  ** Changes include:
002335  **
002336  **     (1)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
002337  **     (2)  Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
002338  **          into BTREE_BLOBKEY.
002339  **     (3)  Bypass the creation of the sqlite_schema table entry
002340  **          for the PRIMARY KEY as the primary key index is now
002341  **          identified by the sqlite_schema table entry of the table itself.
002342  **     (4)  Set the Index.tnum of the PRIMARY KEY Index object in the
002343  **          schema to the rootpage from the main table.
002344  **     (5)  Add all table columns to the PRIMARY KEY Index object
002345  **          so that the PRIMARY KEY is a covering index.  The surplus
002346  **          columns are part of KeyInfo.nAllField and are not used for
002347  **          sorting or lookup or uniqueness checks.
002348  **     (6)  Replace the rowid tail on all automatically generated UNIQUE
002349  **          indices with the PRIMARY KEY columns.
002350  **
002351  ** For virtual tables, only (1) is performed.
002352  */
002353  static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
002354    Index *pIdx;
002355    Index *pPk;
002356    int nPk;
002357    int nExtra;
002358    int i, j;
002359    sqlite3 *db = pParse->db;
002360    Vdbe *v = pParse->pVdbe;
002361  
002362    /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
002363    */
002364    if( !db->init.imposterTable ){
002365      for(i=0; i<pTab->nCol; i++){
002366        if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
002367         && (pTab->aCol[i].notNull==OE_None)
002368        ){
002369          pTab->aCol[i].notNull = OE_Abort;
002370        }
002371      }
002372      pTab->tabFlags |= TF_HasNotNull;
002373    }
002374  
002375    /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
002376    ** into BTREE_BLOBKEY.
002377    */
002378    assert( !pParse->bReturning );
002379    if( pParse->u1.cr.addrCrTab ){
002380      assert( v );
002381      sqlite3VdbeChangeP3(v, pParse->u1.cr.addrCrTab, BTREE_BLOBKEY);
002382    }
002383  
002384    /* Locate the PRIMARY KEY index.  Or, if this table was originally
002385    ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
002386    */
002387    if( pTab->iPKey>=0 ){
002388      ExprList *pList;
002389      Token ipkToken;
002390      sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zCnName);
002391      pList = sqlite3ExprListAppend(pParse, 0,
002392                    sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
002393      if( pList==0 ){
002394        pTab->tabFlags &= ~TF_WithoutRowid;
002395        return;
002396      }
002397      if( IN_RENAME_OBJECT ){
002398        sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
002399      }
002400      pList->a[0].fg.sortFlags = pParse->iPkSortOrder;
002401      assert( pParse->pNewTable==pTab );
002402      pTab->iPKey = -1;
002403      sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
002404                         SQLITE_IDXTYPE_PRIMARYKEY);
002405      if( pParse->nErr ){
002406        pTab->tabFlags &= ~TF_WithoutRowid;
002407        return;
002408      }
002409      assert( db->mallocFailed==0 );
002410      pPk = sqlite3PrimaryKeyIndex(pTab);
002411      assert( pPk->nKeyCol==1 );
002412    }else{
002413      pPk = sqlite3PrimaryKeyIndex(pTab);
002414      assert( pPk!=0 );
002415  
002416      /*
002417      ** Remove all redundant columns from the PRIMARY KEY.  For example, change
002418      ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)".  Later
002419      ** code assumes the PRIMARY KEY contains no repeated columns.
002420      */
002421      for(i=j=1; i<pPk->nKeyCol; i++){
002422        if( isDupColumn(pPk, j, pPk, i) ){
002423          pPk->nColumn--;
002424        }else{
002425          testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );
002426          pPk->azColl[j] = pPk->azColl[i];
002427          pPk->aSortOrder[j] = pPk->aSortOrder[i];
002428          pPk->aiColumn[j++] = pPk->aiColumn[i];
002429        }
002430      }
002431      pPk->nKeyCol = j;
002432    }
002433    assert( pPk!=0 );
002434    pPk->isCovering = 1;
002435    if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
002436    nPk = pPk->nColumn = pPk->nKeyCol;
002437  
002438    /* Bypass the creation of the PRIMARY KEY btree and the sqlite_schema
002439    ** table entry. This is only required if currently generating VDBE
002440    ** code for a CREATE TABLE (not when parsing one as part of reading
002441    ** a database schema).  */
002442    if( v && pPk->tnum>0 ){
002443      assert( db->init.busy==0 );
002444      sqlite3VdbeChangeOpcode(v, (int)pPk->tnum, OP_Goto);
002445    }
002446  
002447    /* The root page of the PRIMARY KEY is the table root page */
002448    pPk->tnum = pTab->tnum;
002449  
002450    /* Update the in-memory representation of all UNIQUE indices by converting
002451    ** the final rowid column into one or more columns of the PRIMARY KEY.
002452    */
002453    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
002454      int n;
002455      if( IsPrimaryKeyIndex(pIdx) ) continue;
002456      for(i=n=0; i<nPk; i++){
002457        if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
002458          testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
002459          n++;
002460        }
002461      }
002462      if( n==0 ){
002463        /* This index is a superset of the primary key */
002464        pIdx->nColumn = pIdx->nKeyCol;
002465        continue;
002466      }
002467      if( resizeIndexObject(pParse, pIdx, pIdx->nKeyCol+n) ) return;
002468      for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
002469        if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
002470          testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
002471          pIdx->aiColumn[j] = pPk->aiColumn[i];
002472          pIdx->azColl[j] = pPk->azColl[i];
002473          if( pPk->aSortOrder[i] ){
002474            /* See ticket https://sqlite.org/src/info/bba7b69f9849b5bf */
002475            pIdx->bAscKeyBug = 1;
002476          }
002477          j++;
002478        }
002479      }
002480      assert( pIdx->nColumn>=pIdx->nKeyCol+n );
002481      assert( pIdx->nColumn>=j );
002482    }
002483  
002484    /* Add all table columns to the PRIMARY KEY index
002485    */
002486    nExtra = 0;
002487    for(i=0; i<pTab->nCol; i++){
002488      if( !hasColumn(pPk->aiColumn, nPk, i)
002489       && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;
002490    }
002491    if( resizeIndexObject(pParse, pPk, nPk+nExtra) ) return;
002492    for(i=0, j=nPk; i<pTab->nCol; i++){
002493      if( !hasColumn(pPk->aiColumn, j, i)
002494       && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0
002495      ){
002496        assert( j<pPk->nColumn );
002497        pPk->aiColumn[j] = i;
002498        pPk->azColl[j] = sqlite3StrBINARY;
002499        j++;
002500      }
002501    }
002502    assert( pPk->nColumn==j );
002503    assert( pTab->nNVCol<=j );
002504    recomputeColumnsNotIndexed(pPk);
002505  }
002506  
002507  
002508  #ifndef SQLITE_OMIT_VIRTUALTABLE
002509  /*
002510  ** Return true if pTab is a virtual table and zName is a shadow table name
002511  ** for that virtual table.
002512  */
002513  int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *zName){
002514    int nName;                    /* Length of zName */
002515    Module *pMod;                 /* Module for the virtual table */
002516  
002517    if( !IsVirtual(pTab) ) return 0;
002518    nName = sqlite3Strlen30(pTab->zName);
002519    if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0;
002520    if( zName[nName]!='_' ) return 0;
002521    pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
002522    if( pMod==0 ) return 0;
002523    if( pMod->pModule->iVersion<3 ) return 0;
002524    if( pMod->pModule->xShadowName==0 ) return 0;
002525    return pMod->pModule->xShadowName(zName+nName+1);
002526  }
002527  #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
002528  
002529  #ifndef SQLITE_OMIT_VIRTUALTABLE
002530  /*
002531  ** Table pTab is a virtual table.  If it the virtual table implementation
002532  ** exists and has an xShadowName method, then loop over all other ordinary
002533  ** tables within the same schema looking for shadow tables of pTab, and mark
002534  ** any shadow tables seen using the TF_Shadow flag.
002535  */
002536  void sqlite3MarkAllShadowTablesOf(sqlite3 *db, Table *pTab){
002537    int nName;                    /* Length of pTab->zName */
002538    Module *pMod;                 /* Module for the virtual table */
002539    HashElem *k;                  /* For looping through the symbol table */
002540  
002541    assert( IsVirtual(pTab) );
002542    pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
002543    if( pMod==0 ) return;
002544    if( NEVER(pMod->pModule==0) ) return;
002545    if( pMod->pModule->iVersion<3 ) return;
002546    if( pMod->pModule->xShadowName==0 ) return;
002547    assert( pTab->zName!=0 );
002548    nName = sqlite3Strlen30(pTab->zName);
002549    for(k=sqliteHashFirst(&pTab->pSchema->tblHash); k; k=sqliteHashNext(k)){
002550      Table *pOther = sqliteHashData(k);
002551      assert( pOther->zName!=0 );
002552      if( !IsOrdinaryTable(pOther) ) continue;
002553      if( pOther->tabFlags & TF_Shadow ) continue;
002554      if( sqlite3StrNICmp(pOther->zName, pTab->zName, nName)==0
002555       && pOther->zName[nName]=='_'
002556       && pMod->pModule->xShadowName(pOther->zName+nName+1)
002557      ){
002558        pOther->tabFlags |= TF_Shadow;
002559      }
002560    }
002561  }
002562  #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
002563  
002564  #ifndef SQLITE_OMIT_VIRTUALTABLE
002565  /*
002566  ** Return true if zName is a shadow table name in the current database
002567  ** connection.
002568  **
002569  ** zName is temporarily modified while this routine is running, but is
002570  ** restored to its original value prior to this routine returning.
002571  */
002572  int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
002573    char *zTail;                  /* Pointer to the last "_" in zName */
002574    Table *pTab;                  /* Table that zName is a shadow of */
002575    zTail = strrchr(zName, '_');
002576    if( zTail==0 ) return 0;
002577    *zTail = 0;
002578    pTab = sqlite3FindTable(db, zName, 0);
002579    *zTail = '_';
002580    if( pTab==0 ) return 0;
002581    if( !IsVirtual(pTab) ) return 0;
002582    return sqlite3IsShadowTableOf(db, pTab, zName);
002583  }
002584  #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
002585  
002586  
002587  #ifdef SQLITE_DEBUG
002588  /*
002589  ** Mark all nodes of an expression as EP_Immutable, indicating that
002590  ** they should not be changed.  Expressions attached to a table or
002591  ** index definition are tagged this way to help ensure that we do
002592  ** not pass them into code generator routines by mistake.
002593  */
002594  static int markImmutableExprStep(Walker *pWalker, Expr *pExpr){
002595    (void)pWalker;
002596    ExprSetVVAProperty(pExpr, EP_Immutable);
002597    return WRC_Continue;
002598  }
002599  static void markExprListImmutable(ExprList *pList){
002600    if( pList ){
002601      Walker w;
002602      memset(&w, 0, sizeof(w));
002603      w.xExprCallback = markImmutableExprStep;
002604      w.xSelectCallback = sqlite3SelectWalkNoop;
002605      w.xSelectCallback2 = 0;
002606      sqlite3WalkExprList(&w, pList);
002607    }
002608  }
002609  #else
002610  #define markExprListImmutable(X)  /* no-op */
002611  #endif /* SQLITE_DEBUG */
002612  
002613  
002614  /*
002615  ** This routine is called to report the final ")" that terminates
002616  ** a CREATE TABLE statement.
002617  **
002618  ** The table structure that other action routines have been building
002619  ** is added to the internal hash tables, assuming no errors have
002620  ** occurred.
002621  **
002622  ** An entry for the table is made in the schema table on disk, unless
002623  ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
002624  ** it means we are reading the sqlite_schema table because we just
002625  ** connected to the database or because the sqlite_schema table has
002626  ** recently changed, so the entry for this table already exists in
002627  ** the sqlite_schema table.  We do not want to create it again.
002628  **
002629  ** If the pSelect argument is not NULL, it means that this routine
002630  ** was called to create a table generated from a
002631  ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
002632  ** the new table will match the result set of the SELECT.
002633  */
002634  void sqlite3EndTable(
002635    Parse *pParse,          /* Parse context */
002636    Token *pCons,           /* The ',' token after the last column defn. */
002637    Token *pEnd,            /* The ')' before options in the CREATE TABLE */
002638    u32 tabOpts,            /* Extra table options. Usually 0. */
002639    Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
002640  ){
002641    Table *p;                 /* The new table */
002642    sqlite3 *db = pParse->db; /* The database connection */
002643    int iDb;                  /* Database in which the table lives */
002644    Index *pIdx;              /* An implied index of the table */
002645  
002646    if( pEnd==0 && pSelect==0 ){
002647      return;
002648    }
002649    p = pParse->pNewTable;
002650    if( p==0 ) return;
002651  
002652    if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){
002653      p->tabFlags |= TF_Shadow;
002654    }
002655  
002656    /* If the db->init.busy is 1 it means we are reading the SQL off the
002657    ** "sqlite_schema" or "sqlite_temp_schema" table on the disk.
002658    ** So do not write to the disk again.  Extract the root page number
002659    ** for the table from the db->init.newTnum field.  (The page number
002660    ** should have been put there by the sqliteOpenCb routine.)
002661    **
002662    ** If the root page number is 1, that means this is the sqlite_schema
002663    ** table itself.  So mark it read-only.
002664    */
002665    if( db->init.busy ){
002666      if( pSelect || (!IsOrdinaryTable(p) && db->init.newTnum) ){
002667        sqlite3ErrorMsg(pParse, "");
002668        return;
002669      }
002670      p->tnum = db->init.newTnum;
002671      if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
002672    }
002673  
002674    /* Special processing for tables that include the STRICT keyword:
002675    **
002676    **   *  Do not allow custom column datatypes.  Every column must have
002677    **      a datatype that is one of INT, INTEGER, REAL, TEXT, or BLOB.
002678    **
002679    **   *  If a PRIMARY KEY is defined, other than the INTEGER PRIMARY KEY,
002680    **      then all columns of the PRIMARY KEY must have a NOT NULL
002681    **      constraint.
002682    */
002683    if( tabOpts & TF_Strict ){
002684      int ii;
002685      p->tabFlags |= TF_Strict;
002686      for(ii=0; ii<p->nCol; ii++){
002687        Column *pCol = &p->aCol[ii];
002688        if( pCol->eCType==COLTYPE_CUSTOM ){
002689          if( pCol->colFlags & COLFLAG_HASTYPE ){
002690            sqlite3ErrorMsg(pParse,
002691              "unknown datatype for %s.%s: \"%s\"",
002692              p->zName, pCol->zCnName, sqlite3ColumnType(pCol, "")
002693            );
002694          }else{
002695            sqlite3ErrorMsg(pParse, "missing datatype for %s.%s",
002696                            p->zName, pCol->zCnName);
002697          }
002698          return;
002699        }else if( pCol->eCType==COLTYPE_ANY ){
002700          pCol->affinity = SQLITE_AFF_BLOB;
002701        }
002702        if( (pCol->colFlags & COLFLAG_PRIMKEY)!=0
002703         && p->iPKey!=ii
002704         && pCol->notNull == OE_None
002705        ){
002706          pCol->notNull = OE_Abort;
002707          p->tabFlags |= TF_HasNotNull;
002708        }
002709      }   
002710    }
002711  
002712    assert( (p->tabFlags & TF_HasPrimaryKey)==0
002713         || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
002714    assert( (p->tabFlags & TF_HasPrimaryKey)!=0
002715         || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
002716  
002717    /* Special processing for WITHOUT ROWID Tables */
002718    if( tabOpts & TF_WithoutRowid ){
002719      if( (p->tabFlags & TF_Autoincrement) ){
002720        sqlite3ErrorMsg(pParse,
002721            "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
002722        return;
002723      }
002724      if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
002725        sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
002726        return;
002727      }
002728      p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
002729      convertToWithoutRowidTable(pParse, p);
002730    }
002731    iDb = sqlite3SchemaToIndex(db, p->pSchema);
002732  
002733  #ifndef SQLITE_OMIT_CHECK
002734    /* Resolve names in all CHECK constraint expressions.
002735    */
002736    if( p->pCheck ){
002737      sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
002738      if( pParse->nErr ){
002739        /* If errors are seen, delete the CHECK constraints now, else they might
002740        ** actually be used if PRAGMA writable_schema=ON is set. */
002741        sqlite3ExprListDelete(db, p->pCheck);
002742        p->pCheck = 0;
002743      }else{
002744        markExprListImmutable(p->pCheck);
002745      }
002746    }
002747  #endif /* !defined(SQLITE_OMIT_CHECK) */
002748  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
002749    if( p->tabFlags & TF_HasGenerated ){
002750      int ii, nNG = 0;
002751      testcase( p->tabFlags & TF_HasVirtual );
002752      testcase( p->tabFlags & TF_HasStored );
002753      for(ii=0; ii<p->nCol; ii++){
002754        u32 colFlags = p->aCol[ii].colFlags;
002755        if( (colFlags & COLFLAG_GENERATED)!=0 ){
002756          Expr *pX = sqlite3ColumnExpr(p, &p->aCol[ii]);
002757          testcase( colFlags & COLFLAG_VIRTUAL );
002758          testcase( colFlags & COLFLAG_STORED );
002759          if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){
002760            /* If there are errors in resolving the expression, change the
002761            ** expression to a NULL.  This prevents code generators that operate
002762            ** on the expression from inserting extra parts into the expression
002763            ** tree that have been allocated from lookaside memory, which is
002764            ** illegal in a schema and will lead to errors or heap corruption
002765            ** when the database connection closes. */
002766            sqlite3ColumnSetExpr(pParse, p, &p->aCol[ii],
002767                 sqlite3ExprAlloc(db, TK_NULL, 0, 0));
002768          }
002769        }else{
002770          nNG++;
002771        }
002772      }
002773      if( nNG==0 ){
002774        sqlite3ErrorMsg(pParse, "must have at least one non-generated column");
002775        return;
002776      }
002777    }
002778  #endif
002779  
002780    /* Estimate the average row size for the table and for all implied indices */
002781    estimateTableWidth(p);
002782    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
002783      estimateIndexWidth(pIdx);
002784    }
002785  
002786    /* If not initializing, then create a record for the new table
002787    ** in the schema table of the database.
002788    **
002789    ** If this is a TEMPORARY table, write the entry into the auxiliary
002790    ** file instead of into the main database file.
002791    */
002792    if( !db->init.busy ){
002793      int n;
002794      Vdbe *v;
002795      char *zType;    /* "view" or "table" */
002796      char *zType2;   /* "VIEW" or "TABLE" */
002797      char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
002798  
002799      v = sqlite3GetVdbe(pParse);
002800      if( NEVER(v==0) ) return;
002801  
002802      sqlite3VdbeAddOp1(v, OP_Close, 0);
002803  
002804      /*
002805      ** Initialize zType for the new view or table.
002806      */
002807      if( IsOrdinaryTable(p) ){
002808        /* A regular table */
002809        zType = "table";
002810        zType2 = "TABLE";
002811  #ifndef SQLITE_OMIT_VIEW
002812      }else{
002813        /* A view */
002814        zType = "view";
002815        zType2 = "VIEW";
002816  #endif
002817      }
002818  
002819      /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
002820      ** statement to populate the new table. The root-page number for the
002821      ** new table is in register pParse->u1.cr.regRoot.
002822      **
002823      ** Once the SELECT has been coded by sqlite3Select(), it is in a
002824      ** suitable state to query for the column names and types to be used
002825      ** by the new table.
002826      **
002827      ** A shared-cache write-lock is not required to write to the new table,
002828      ** as a schema-lock must have already been obtained to create it. Since
002829      ** a schema-lock excludes all other database users, the write-lock would
002830      ** be redundant.
002831      */
002832      if( pSelect ){
002833        SelectDest dest;    /* Where the SELECT should store results */
002834        int regYield;       /* Register holding co-routine entry-point */
002835        int addrTop;        /* Top of the co-routine */
002836        int regRec;         /* A record to be insert into the new table */
002837        int regRowid;       /* Rowid of the next row to insert */
002838        int addrInsLoop;    /* Top of the loop for inserting rows */
002839        Table *pSelTab;     /* A table that describes the SELECT results */
002840        int iCsr;           /* Write cursor on the new table */
002841  
002842        if( IN_SPECIAL_PARSE ){
002843          pParse->rc = SQLITE_ERROR;
002844          pParse->nErr++;
002845          return;
002846        }
002847        iCsr = pParse->nTab++;
002848        regYield = ++pParse->nMem;
002849        regRec = ++pParse->nMem;
002850        regRowid = ++pParse->nMem;
002851        sqlite3MayAbort(pParse);
002852        assert( pParse->isCreate );
002853        sqlite3VdbeAddOp3(v, OP_OpenWrite, iCsr, pParse->u1.cr.regRoot, iDb);
002854        sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
002855        addrTop = sqlite3VdbeCurrentAddr(v) + 1;
002856        sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
002857        if( pParse->nErr ) return;
002858        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB);
002859        if( pSelTab==0 ) return;
002860        assert( p->aCol==0 );
002861        p->nCol = p->nNVCol = pSelTab->nCol;
002862        p->aCol = pSelTab->aCol;
002863        pSelTab->nCol = 0;
002864        pSelTab->aCol = 0;
002865        sqlite3DeleteTable(db, pSelTab);
002866        sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
002867        sqlite3Select(pParse, pSelect, &dest);
002868        if( pParse->nErr ) return;
002869        sqlite3VdbeEndCoroutine(v, regYield);
002870        sqlite3VdbeJumpHere(v, addrTop - 1);
002871        addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
002872        VdbeCoverage(v);
002873        sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
002874        sqlite3TableAffinity(v, p, 0);
002875        sqlite3VdbeAddOp2(v, OP_NewRowid, iCsr, regRowid);
002876        sqlite3VdbeAddOp3(v, OP_Insert, iCsr, regRec, regRowid);
002877        sqlite3VdbeGoto(v, addrInsLoop);
002878        sqlite3VdbeJumpHere(v, addrInsLoop);
002879        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
002880      }
002881  
002882      /* Compute the complete text of the CREATE statement */
002883      if( pSelect ){
002884        zStmt = createTableStmt(db, p);
002885      }else{
002886        Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
002887        n = (int)(pEnd2->z - pParse->sNameToken.z);
002888        if( pEnd2->z[0]!=';' ) n += pEnd2->n;
002889        zStmt = sqlite3MPrintf(db,
002890            "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
002891        );
002892      }
002893  
002894      /* A slot for the record has already been allocated in the
002895      ** schema table.  We just need to update that slot with all
002896      ** the information we've collected.
002897      */
002898      assert( pParse->isCreate );
002899      sqlite3NestedParse(pParse,
002900        "UPDATE %Q." LEGACY_SCHEMA_TABLE
002901        " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q"
002902        " WHERE rowid=#%d",
002903        db->aDb[iDb].zDbSName,
002904        zType,
002905        p->zName,
002906        p->zName,
002907        pParse->u1.cr.regRoot,
002908        zStmt,
002909        pParse->u1.cr.regRowid
002910      );
002911      sqlite3DbFree(db, zStmt);
002912      sqlite3ChangeCookie(pParse, iDb);
002913  
002914  #ifndef SQLITE_OMIT_AUTOINCREMENT
002915      /* Check to see if we need to create an sqlite_sequence table for
002916      ** keeping track of autoincrement keys.
002917      */
002918      if( (p->tabFlags & TF_Autoincrement)!=0 && !IN_SPECIAL_PARSE ){
002919        Db *pDb = &db->aDb[iDb];
002920        assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
002921        if( pDb->pSchema->pSeqTab==0 ){
002922          sqlite3NestedParse(pParse,
002923            "CREATE TABLE %Q.sqlite_sequence(name,seq)",
002924            pDb->zDbSName
002925          );
002926        }
002927      }
002928  #endif
002929  
002930      /* Reparse everything to update our internal data structures */
002931      sqlite3VdbeAddParseSchemaOp(v, iDb,
002932             sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName),0);
002933  
002934      /* Test for cycles in generated columns and illegal expressions
002935      ** in CHECK constraints and in DEFAULT clauses. */
002936      if( p->tabFlags & TF_HasGenerated ){
002937        sqlite3VdbeAddOp4(v, OP_SqlExec, 0x0001, 0, 0,
002938               sqlite3MPrintf(db, "SELECT*FROM\"%w\".\"%w\"",
002939                     db->aDb[iDb].zDbSName, p->zName), P4_DYNAMIC);
002940      }
002941    }
002942  
002943    /* Add the table to the in-memory representation of the database.
002944    */
002945    if( db->init.busy ){
002946      Table *pOld;
002947      Schema *pSchema = p->pSchema;
002948      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
002949      assert( HasRowid(p) || p->iPKey<0 );
002950      pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
002951      if( pOld ){
002952        assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
002953        sqlite3OomFault(db);
002954        return;
002955      }
002956      pParse->pNewTable = 0;
002957      db->mDbFlags |= DBFLAG_SchemaChange;
002958  
002959      /* If this is the magic sqlite_sequence table used by autoincrement,
002960      ** then record a pointer to this table in the main database structure
002961      ** so that INSERT can find the table easily.  */
002962      assert( !pParse->nested );
002963  #ifndef SQLITE_OMIT_AUTOINCREMENT
002964      if( strcmp(p->zName, "sqlite_sequence")==0 ){
002965        assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
002966        p->pSchema->pSeqTab = p;
002967      }
002968  #endif
002969    }
002970  
002971  #ifndef SQLITE_OMIT_ALTERTABLE
002972    if( !pSelect && IsOrdinaryTable(p) ){
002973      assert( pCons && pEnd );
002974      if( pCons->z==0 ){
002975        pCons = pEnd;
002976      }
002977      p->u.tab.addColOffset = 13 + (int)(pCons->z - pParse->sNameToken.z);
002978    }
002979  #endif
002980  }
002981  
002982  #ifndef SQLITE_OMIT_VIEW
002983  /*
002984  ** The parser calls this routine in order to create a new VIEW
002985  */
002986  void sqlite3CreateView(
002987    Parse *pParse,     /* The parsing context */
002988    Token *pBegin,     /* The CREATE token that begins the statement */
002989    Token *pName1,     /* The token that holds the name of the view */
002990    Token *pName2,     /* The token that holds the name of the view */
002991    ExprList *pCNames, /* Optional list of view column names */
002992    Select *pSelect,   /* A SELECT statement that will become the new view */
002993    int isTemp,        /* TRUE for a TEMPORARY view */
002994    int noErr          /* Suppress error messages if VIEW already exists */
002995  ){
002996    Table *p;
002997    int n;
002998    const char *z;
002999    Token sEnd;
003000    DbFixer sFix;
003001    Token *pName = 0;
003002    int iDb;
003003    sqlite3 *db = pParse->db;
003004  
003005    if( pParse->nVar>0 ){
003006      sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
003007      goto create_view_fail;
003008    }
003009    sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
003010    p = pParse->pNewTable;
003011    if( p==0 || pParse->nErr ) goto create_view_fail;
003012  
003013    /* Legacy versions of SQLite allowed the use of the magic "rowid" column
003014    ** on a view, even though views do not have rowids.  The following flag
003015    ** setting fixes this problem.  But the fix can be disabled by compiling
003016    ** with -DSQLITE_ALLOW_ROWID_IN_VIEW in case there are legacy apps that
003017    ** depend upon the old buggy behavior.  The ability can also be toggled
003018    ** using sqlite3_config(SQLITE_CONFIG_ROWID_IN_VIEW,...) */
003019  #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
003020    p->tabFlags |= sqlite3Config.mNoVisibleRowid; /* Optional. Allow by default */
003021  #else
003022    p->tabFlags |= TF_NoVisibleRowid;             /* Never allow rowid in view */
003023  #endif
003024  
003025    sqlite3TwoPartName(pParse, pName1, pName2, &pName);
003026    iDb = sqlite3SchemaToIndex(db, p->pSchema);
003027    sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
003028    if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
003029  
003030    /* Make a copy of the entire SELECT statement that defines the view.
003031    ** This will force all the Expr.token.z values to be dynamically
003032    ** allocated rather than point to the input string - which means that
003033    ** they will persist after the current sqlite3_exec() call returns.
003034    */
003035    pSelect->selFlags |= SF_View;
003036    if( IN_RENAME_OBJECT ){
003037      p->u.view.pSelect = pSelect;
003038      pSelect = 0;
003039    }else{
003040      p->u.view.pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
003041    }
003042    p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
003043    p->eTabType = TABTYP_VIEW;
003044    if( db->mallocFailed ) goto create_view_fail;
003045  
003046    /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
003047    ** the end.
003048    */
003049    sEnd = pParse->sLastToken;
003050    assert( sEnd.z[0]!=0 || sEnd.n==0 );
003051    if( sEnd.z[0]!=';' ){
003052      sEnd.z += sEnd.n;
003053    }
003054    sEnd.n = 0;
003055    n = (int)(sEnd.z - pBegin->z);
003056    assert( n>0 );
003057    z = pBegin->z;
003058    while( sqlite3Isspace(z[n-1]) ){ n--; }
003059    sEnd.z = &z[n-1];
003060    sEnd.n = 1;
003061  
003062    /* Use sqlite3EndTable() to add the view to the schema table */
003063    sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
003064  
003065  create_view_fail:
003066    sqlite3SelectDelete(db, pSelect);
003067    if( IN_RENAME_OBJECT ){
003068      sqlite3RenameExprlistUnmap(pParse, pCNames);
003069    }
003070    sqlite3ExprListDelete(db, pCNames);
003071    return;
003072  }
003073  #endif /* SQLITE_OMIT_VIEW */
003074  
003075  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
003076  /*
003077  ** The Table structure pTable is really a VIEW.  Fill in the names of
003078  ** the columns of the view in the pTable structure.  Return non-zero if
003079  ** there are errors.  If an error is seen an error message is left
003080  ** in pParse->zErrMsg.
003081  */
003082  static SQLITE_NOINLINE int viewGetColumnNames(Parse *pParse, Table *pTable){
003083    Table *pSelTab;   /* A fake table from which we get the result set */
003084    Select *pSel;     /* Copy of the SELECT that implements the view */
003085    int nErr = 0;     /* Number of errors encountered */
003086    sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
003087  #ifndef SQLITE_OMIT_VIRTUALTABLE
003088    int rc;
003089  #endif
003090  #ifndef SQLITE_OMIT_AUTHORIZATION
003091    sqlite3_xauth xAuth;       /* Saved xAuth pointer */
003092  #endif
003093  
003094    assert( pTable );
003095  
003096  #ifndef SQLITE_OMIT_VIRTUALTABLE
003097    if( IsVirtual(pTable) ){
003098      db->nSchemaLock++;
003099      rc = sqlite3VtabCallConnect(pParse, pTable);
003100      db->nSchemaLock--;
003101      return rc;
003102    }
003103  #endif
003104  
003105  #ifndef SQLITE_OMIT_VIEW
003106    /* A positive nCol means the columns names for this view are
003107    ** already known.  This routine is not called unless either the
003108    ** table is virtual or nCol is zero.
003109    */
003110    assert( pTable->nCol<=0 );
003111  
003112    /* A negative nCol is a special marker meaning that we are currently
003113    ** trying to compute the column names.  If we enter this routine with
003114    ** a negative nCol, it means two or more views form a loop, like this:
003115    **
003116    **     CREATE VIEW one AS SELECT * FROM two;
003117    **     CREATE VIEW two AS SELECT * FROM one;
003118    **
003119    ** Actually, the error above is now caught prior to reaching this point.
003120    ** But the following test is still important as it does come up
003121    ** in the following:
003122    **
003123    **     CREATE TABLE main.ex1(a);
003124    **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
003125    **     SELECT * FROM temp.ex1;
003126    */
003127    if( pTable->nCol<0 ){
003128      sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
003129      return 1;
003130    }
003131    assert( pTable->nCol>=0 );
003132  
003133    /* If we get this far, it means we need to compute the table names.
003134    ** Note that the call to sqlite3ResultSetOfSelect() will expand any
003135    ** "*" elements in the results set of the view and will assign cursors
003136    ** to the elements of the FROM clause.  But we do not want these changes
003137    ** to be permanent.  So the computation is done on a copy of the SELECT
003138    ** statement that defines the view.
003139    */
003140    assert( IsView(pTable) );
003141    pSel = sqlite3SelectDup(db, pTable->u.view.pSelect, 0);
003142    if( pSel ){
003143      u8 eParseMode = pParse->eParseMode;
003144      int nTab = pParse->nTab;
003145      int nSelect = pParse->nSelect;
003146      pParse->eParseMode = PARSE_MODE_NORMAL;
003147      sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
003148      pTable->nCol = -1;
003149      DisableLookaside;
003150  #ifndef SQLITE_OMIT_AUTHORIZATION
003151      xAuth = db->xAuth;
003152      db->xAuth = 0;
003153      pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
003154      db->xAuth = xAuth;
003155  #else
003156      pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
003157  #endif
003158      pParse->nTab = nTab;
003159      pParse->nSelect = nSelect;
003160      if( pSelTab==0 ){
003161        pTable->nCol = 0;
003162        nErr++;
003163      }else if( pTable->pCheck ){
003164        /* CREATE VIEW name(arglist) AS ...
003165        ** The names of the columns in the table are taken from
003166        ** arglist which is stored in pTable->pCheck.  The pCheck field
003167        ** normally holds CHECK constraints on an ordinary table, but for
003168        ** a VIEW it holds the list of column names.
003169        */
003170        sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
003171                                   &pTable->nCol, &pTable->aCol);
003172        if( pParse->nErr==0
003173         && pTable->nCol==pSel->pEList->nExpr
003174        ){
003175          assert( db->mallocFailed==0 );
003176          sqlite3SubqueryColumnTypes(pParse, pTable, pSel, SQLITE_AFF_NONE);
003177        }
003178      }else{
003179        /* CREATE VIEW name AS...  without an argument list.  Construct
003180        ** the column names from the SELECT statement that defines the view.
003181        */
003182        assert( pTable->aCol==0 );
003183        pTable->nCol = pSelTab->nCol;
003184        pTable->aCol = pSelTab->aCol;
003185        pTable->tabFlags |= (pSelTab->tabFlags & COLFLAG_NOINSERT);
003186        pSelTab->nCol = 0;
003187        pSelTab->aCol = 0;
003188        assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
003189      }
003190      pTable->nNVCol = pTable->nCol;
003191      sqlite3DeleteTable(db, pSelTab);
003192      sqlite3SelectDelete(db, pSel);
003193      EnableLookaside;
003194      pParse->eParseMode = eParseMode;
003195    } else {
003196      nErr++;
003197    }
003198    pTable->pSchema->schemaFlags |= DB_UnresetViews;
003199    if( db->mallocFailed ){
003200      sqlite3DeleteColumnNames(db, pTable);
003201    }
003202  #endif /* SQLITE_OMIT_VIEW */
003203    return nErr + pParse->nErr; 
003204  }
003205  int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
003206    assert( pTable!=0 );
003207    if( !IsVirtual(pTable) && pTable->nCol>0 ) return 0;
003208    return viewGetColumnNames(pParse, pTable);
003209  }
003210  #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
003211  
003212  #ifndef SQLITE_OMIT_VIEW
003213  /*
003214  ** Clear the column names from every VIEW in database idx.
003215  */
003216  static void sqliteViewResetAll(sqlite3 *db, int idx){
003217    HashElem *i;
003218    assert( sqlite3SchemaMutexHeld(db, idx, 0) );
003219    if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
003220    for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
003221      Table *pTab = sqliteHashData(i);
003222      if( IsView(pTab) ){
003223        sqlite3DeleteColumnNames(db, pTab);
003224      }
003225    }
003226    DbClearProperty(db, idx, DB_UnresetViews);
003227  }
003228  #else
003229  # define sqliteViewResetAll(A,B)
003230  #endif /* SQLITE_OMIT_VIEW */
003231  
003232  /*
003233  ** This function is called by the VDBE to adjust the internal schema
003234  ** used by SQLite when the btree layer moves a table root page. The
003235  ** root-page of a table or index in database iDb has changed from iFrom
003236  ** to iTo.
003237  **
003238  ** Ticket #1728:  The symbol table might still contain information
003239  ** on tables and/or indices that are the process of being deleted.
003240  ** If you are unlucky, one of those deleted indices or tables might
003241  ** have the same rootpage number as the real table or index that is
003242  ** being moved.  So we cannot stop searching after the first match
003243  ** because the first match might be for one of the deleted indices
003244  ** or tables and not the table/index that is actually being moved.
003245  ** We must continue looping until all tables and indices with
003246  ** rootpage==iFrom have been converted to have a rootpage of iTo
003247  ** in order to be certain that we got the right one.
003248  */
003249  #ifndef SQLITE_OMIT_AUTOVACUUM
003250  void sqlite3RootPageMoved(sqlite3 *db, int iDb, Pgno iFrom, Pgno iTo){
003251    HashElem *pElem;
003252    Hash *pHash;
003253    Db *pDb;
003254  
003255    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
003256    pDb = &db->aDb[iDb];
003257    pHash = &pDb->pSchema->tblHash;
003258    for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
003259      Table *pTab = sqliteHashData(pElem);
003260      if( pTab->tnum==iFrom ){
003261        pTab->tnum = iTo;
003262      }
003263    }
003264    pHash = &pDb->pSchema->idxHash;
003265    for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
003266      Index *pIdx = sqliteHashData(pElem);
003267      if( pIdx->tnum==iFrom ){
003268        pIdx->tnum = iTo;
003269      }
003270    }
003271  }
003272  #endif
003273  
003274  /*
003275  ** Write code to erase the table with root-page iTable from database iDb.
003276  ** Also write code to modify the sqlite_schema table and internal schema
003277  ** if a root-page of another table is moved by the btree-layer whilst
003278  ** erasing iTable (this can happen with an auto-vacuum database).
003279  */
003280  static void destroyRootPage(Parse *pParse, int iTable, int iDb){
003281    Vdbe *v = sqlite3GetVdbe(pParse);
003282    int r1 = sqlite3GetTempReg(pParse);
003283    if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
003284    sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
003285    sqlite3MayAbort(pParse);
003286  #ifndef SQLITE_OMIT_AUTOVACUUM
003287    /* OP_Destroy stores an in integer r1. If this integer
003288    ** is non-zero, then it is the root page number of a table moved to
003289    ** location iTable. The following code modifies the sqlite_schema table to
003290    ** reflect this.
003291    **
003292    ** The "#NNN" in the SQL is a special constant that means whatever value
003293    ** is in register NNN.  See grammar rules associated with the TK_REGISTER
003294    ** token for additional information.
003295    */
003296    sqlite3NestedParse(pParse,
003297       "UPDATE %Q." LEGACY_SCHEMA_TABLE
003298       " SET rootpage=%d WHERE #%d AND rootpage=#%d",
003299       pParse->db->aDb[iDb].zDbSName, iTable, r1, r1);
003300  #endif
003301    sqlite3ReleaseTempReg(pParse, r1);
003302  }
003303  
003304  /*
003305  ** Write VDBE code to erase table pTab and all associated indices on disk.
003306  ** Code to update the sqlite_schema tables and internal schema definitions
003307  ** in case a root-page belonging to another table is moved by the btree layer
003308  ** is also added (this can happen with an auto-vacuum database).
003309  */
003310  static void destroyTable(Parse *pParse, Table *pTab){
003311    /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
003312    ** is not defined), then it is important to call OP_Destroy on the
003313    ** table and index root-pages in order, starting with the numerically
003314    ** largest root-page number. This guarantees that none of the root-pages
003315    ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
003316    ** following were coded:
003317    **
003318    ** OP_Destroy 4 0
003319    ** ...
003320    ** OP_Destroy 5 0
003321    **
003322    ** and root page 5 happened to be the largest root-page number in the
003323    ** database, then root page 5 would be moved to page 4 by the
003324    ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
003325    ** a free-list page.
003326    */
003327    Pgno iTab = pTab->tnum;
003328    Pgno iDestroyed = 0;
003329  
003330    while( 1 ){
003331      Index *pIdx;
003332      Pgno iLargest = 0;
003333  
003334      if( iDestroyed==0 || iTab<iDestroyed ){
003335        iLargest = iTab;
003336      }
003337      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
003338        Pgno iIdx = pIdx->tnum;
003339        assert( pIdx->pSchema==pTab->pSchema );
003340        if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
003341          iLargest = iIdx;
003342        }
003343      }
003344      if( iLargest==0 ){
003345        return;
003346      }else{
003347        int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
003348        assert( iDb>=0 && iDb<pParse->db->nDb );
003349        destroyRootPage(pParse, iLargest, iDb);
003350        iDestroyed = iLargest;
003351      }
003352    }
003353  }
003354  
003355  /*
003356  ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
003357  ** after a DROP INDEX or DROP TABLE command.
003358  */
003359  static void sqlite3ClearStatTables(
003360    Parse *pParse,         /* The parsing context */
003361    int iDb,               /* The database number */
003362    const char *zType,     /* "idx" or "tbl" */
003363    const char *zName      /* Name of index or table */
003364  ){
003365    int i;
003366    const char *zDbName = pParse->db->aDb[iDb].zDbSName;
003367    for(i=1; i<=4; i++){
003368      char zTab[24];
003369      sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
003370      if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
003371        sqlite3NestedParse(pParse,
003372          "DELETE FROM %Q.%s WHERE %s=%Q",
003373          zDbName, zTab, zType, zName
003374        );
003375      }
003376    }
003377  }
003378  
003379  /*
003380  ** Generate code to drop a table.
003381  */
003382  void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
003383    Vdbe *v;
003384    sqlite3 *db = pParse->db;
003385    Trigger *pTrigger;
003386    Db *pDb = &db->aDb[iDb];
003387  
003388    v = sqlite3GetVdbe(pParse);
003389    assert( v!=0 );
003390    sqlite3BeginWriteOperation(pParse, 1, iDb);
003391  
003392  #ifndef SQLITE_OMIT_VIRTUALTABLE
003393    if( IsVirtual(pTab) ){
003394      sqlite3VdbeAddOp0(v, OP_VBegin);
003395    }
003396  #endif
003397  
003398    /* Drop all triggers associated with the table being dropped. Code
003399    ** is generated to remove entries from sqlite_schema and/or
003400    ** sqlite_temp_schema if required.
003401    */
003402    pTrigger = sqlite3TriggerList(pParse, pTab);
003403    while( pTrigger ){
003404      assert( pTrigger->pSchema==pTab->pSchema ||
003405          pTrigger->pSchema==db->aDb[1].pSchema );
003406      sqlite3DropTriggerPtr(pParse, pTrigger);
003407      pTrigger = pTrigger->pNext;
003408    }
003409  
003410  #ifndef SQLITE_OMIT_AUTOINCREMENT
003411    /* Remove any entries of the sqlite_sequence table associated with
003412    ** the table being dropped. This is done before the table is dropped
003413    ** at the btree level, in case the sqlite_sequence table needs to
003414    ** move as a result of the drop (can happen in auto-vacuum mode).
003415    */
003416    if( pTab->tabFlags & TF_Autoincrement ){
003417      sqlite3NestedParse(pParse,
003418        "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
003419        pDb->zDbSName, pTab->zName
003420      );
003421    }
003422  #endif
003423  
003424    /* Drop all entries in the schema table that refer to the
003425    ** table. The program name loops through the schema table and deletes
003426    ** every row that refers to a table of the same name as the one being
003427    ** dropped. Triggers are handled separately because a trigger can be
003428    ** created in the temp database that refers to a table in another
003429    ** database.
003430    */
003431    sqlite3NestedParse(pParse,
003432        "DELETE FROM %Q." LEGACY_SCHEMA_TABLE
003433        " WHERE tbl_name=%Q and type!='trigger'",
003434        pDb->zDbSName, pTab->zName);
003435    if( !isView && !IsVirtual(pTab) ){
003436      destroyTable(pParse, pTab);
003437    }
003438  
003439    /* Remove the table entry from SQLite's internal schema and modify
003440    ** the schema cookie.
003441    */
003442    if( IsVirtual(pTab) ){
003443      sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
003444      sqlite3MayAbort(pParse);
003445    }
003446    sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
003447    sqlite3ChangeCookie(pParse, iDb);
003448    sqliteViewResetAll(db, iDb);
003449  }
003450  
003451  /*
003452  ** Return TRUE if shadow tables should be read-only in the current
003453  ** context.
003454  */
003455  int sqlite3ReadOnlyShadowTables(sqlite3 *db){
003456  #ifndef SQLITE_OMIT_VIRTUALTABLE
003457    if( (db->flags & SQLITE_Defensive)!=0
003458     && db->pVtabCtx==0
003459     && db->nVdbeExec==0
003460     && !sqlite3VtabInSync(db)
003461    ){
003462      return 1;
003463    }
003464  #endif
003465    return 0;
003466  }
003467  
003468  /*
003469  ** Return true if it is not allowed to drop the given table
003470  */
003471  static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){
003472    if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
003473      if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0;
003474      if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0;
003475      return 1;
003476    }
003477    if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
003478      return 1;
003479    }
003480    if( pTab->tabFlags & TF_Eponymous ){
003481      return 1;
003482    }
003483    return 0;
003484  }
003485  
003486  /*
003487  ** This routine is called to do the work of a DROP TABLE statement.
003488  ** pName is the name of the table to be dropped.
003489  */
003490  void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
003491    Table *pTab;
003492    Vdbe *v;
003493    sqlite3 *db = pParse->db;
003494    int iDb;
003495  
003496    if( db->mallocFailed ){
003497      goto exit_drop_table;
003498    }
003499    assert( pParse->nErr==0 );
003500    assert( pName->nSrc==1 );
003501    assert( pName->a[0].fg.fixedSchema==0 );
003502    assert( pName->a[0].fg.isSubquery==0 );
003503    if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
003504    if( noErr ) db->suppressErr++;
003505    assert( isView==0 || isView==LOCATE_VIEW );
003506    pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
003507    if( noErr ) db->suppressErr--;
003508  
003509    if( pTab==0 ){
003510      if( noErr ){
003511        sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].u4.zDatabase);
003512        sqlite3ForceNotReadOnly(pParse);
003513      }
003514      goto exit_drop_table;
003515    }
003516    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
003517    assert( iDb>=0 && iDb<db->nDb );
003518  
003519    /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
003520    ** it is initialized.
003521    */
003522    if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
003523      goto exit_drop_table;
003524    }
003525  #ifndef SQLITE_OMIT_AUTHORIZATION
003526    {
003527      int code;
003528      const char *zTab = SCHEMA_TABLE(iDb);
003529      const char *zDb = db->aDb[iDb].zDbSName;
003530      const char *zArg2 = 0;
003531      if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
003532        goto exit_drop_table;
003533      }
003534      if( isView ){
003535        if( !OMIT_TEMPDB && iDb==1 ){
003536          code = SQLITE_DROP_TEMP_VIEW;
003537        }else{
003538          code = SQLITE_DROP_VIEW;
003539        }
003540  #ifndef SQLITE_OMIT_VIRTUALTABLE
003541      }else if( IsVirtual(pTab) ){
003542        code = SQLITE_DROP_VTABLE;
003543        zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
003544  #endif
003545      }else{
003546        if( !OMIT_TEMPDB && iDb==1 ){
003547          code = SQLITE_DROP_TEMP_TABLE;
003548        }else{
003549          code = SQLITE_DROP_TABLE;
003550        }
003551      }
003552      if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
003553        goto exit_drop_table;
003554      }
003555      if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
003556        goto exit_drop_table;
003557      }
003558    }
003559  #endif
003560    if( tableMayNotBeDropped(db, pTab) ){
003561      sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
003562      goto exit_drop_table;
003563    }
003564  
003565  #ifndef SQLITE_OMIT_VIEW
003566    /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
003567    ** on a table.
003568    */
003569    if( isView && !IsView(pTab) ){
003570      sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
003571      goto exit_drop_table;
003572    }
003573    if( !isView && IsView(pTab) ){
003574      sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
003575      goto exit_drop_table;
003576    }
003577  #endif
003578  
003579    /* Generate code to remove the table from the schema table
003580    ** on disk.
003581    */
003582    v = sqlite3GetVdbe(pParse);
003583    if( v ){
003584      sqlite3BeginWriteOperation(pParse, 1, iDb);
003585      if( !isView ){
003586        sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
003587        sqlite3FkDropTable(pParse, pName, pTab);
003588      }
003589      sqlite3CodeDropTable(pParse, pTab, iDb, isView);
003590    }
003591  
003592  exit_drop_table:
003593    sqlite3SrcListDelete(db, pName);
003594  }
003595  
003596  /*
003597  ** This routine is called to create a new foreign key on the table
003598  ** currently under construction.  pFromCol determines which columns
003599  ** in the current table point to the foreign key.  If pFromCol==0 then
003600  ** connect the key to the last column inserted.  pTo is the name of
003601  ** the table referred to (a.k.a the "parent" table).  pToCol is a list
003602  ** of tables in the parent pTo table.  flags contains all
003603  ** information about the conflict resolution algorithms specified
003604  ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
003605  **
003606  ** An FKey structure is created and added to the table currently
003607  ** under construction in the pParse->pNewTable field.
003608  **
003609  ** The foreign key is set for IMMEDIATE processing.  A subsequent call
003610  ** to sqlite3DeferForeignKey() might change this to DEFERRED.
003611  */
003612  void sqlite3CreateForeignKey(
003613    Parse *pParse,       /* Parsing context */
003614    ExprList *pFromCol,  /* Columns in this table that point to other table */
003615    Token *pTo,          /* Name of the other table */
003616    ExprList *pToCol,    /* Columns in the other table */
003617    int flags            /* Conflict resolution algorithms. */
003618  ){
003619    sqlite3 *db = pParse->db;
003620  #ifndef SQLITE_OMIT_FOREIGN_KEY
003621    FKey *pFKey = 0;
003622    FKey *pNextTo;
003623    Table *p = pParse->pNewTable;
003624    i64 nByte;
003625    int i;
003626    int nCol;
003627    char *z;
003628  
003629    assert( pTo!=0 );
003630    if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
003631    if( pFromCol==0 ){
003632      int iCol = p->nCol-1;
003633      if( NEVER(iCol<0) ) goto fk_end;
003634      if( pToCol && pToCol->nExpr!=1 ){
003635        sqlite3ErrorMsg(pParse, "foreign key on %s"
003636           " should reference only one column of table %T",
003637           p->aCol[iCol].zCnName, pTo);
003638        goto fk_end;
003639      }
003640      nCol = 1;
003641    }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
003642      sqlite3ErrorMsg(pParse,
003643          "number of columns in foreign key does not match the number of "
003644          "columns in the referenced table");
003645      goto fk_end;
003646    }else{
003647      nCol = pFromCol->nExpr;
003648    }
003649    nByte = SZ_FKEY(nCol) + pTo->n + 1;
003650    if( pToCol ){
003651      for(i=0; i<pToCol->nExpr; i++){
003652        nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1;
003653      }
003654    }
003655    pFKey = sqlite3DbMallocZero(db, nByte );
003656    if( pFKey==0 ){
003657      goto fk_end;
003658    }
003659    pFKey->pFrom = p;
003660    assert( IsOrdinaryTable(p) );
003661    pFKey->pNextFrom = p->u.tab.pFKey;
003662    z = (char*)&pFKey->aCol[nCol];
003663    pFKey->zTo = z;
003664    if( IN_RENAME_OBJECT ){
003665      sqlite3RenameTokenMap(pParse, (void*)z, pTo);
003666    }
003667    memcpy(z, pTo->z, pTo->n);
003668    z[pTo->n] = 0;
003669    sqlite3Dequote(z);
003670    z += pTo->n+1;
003671    pFKey->nCol = nCol;
003672    if( pFromCol==0 ){
003673      pFKey->aCol[0].iFrom = p->nCol-1;
003674    }else{
003675      for(i=0; i<nCol; i++){
003676        int j;
003677        for(j=0; j<p->nCol; j++){
003678          if( sqlite3StrICmp(p->aCol[j].zCnName, pFromCol->a[i].zEName)==0 ){
003679            pFKey->aCol[i].iFrom = j;
003680            break;
003681          }
003682        }
003683        if( j>=p->nCol ){
003684          sqlite3ErrorMsg(pParse,
003685            "unknown column \"%s\" in foreign key definition",
003686            pFromCol->a[i].zEName);
003687          goto fk_end;
003688        }
003689        if( IN_RENAME_OBJECT ){
003690          sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName);
003691        }
003692      }
003693    }
003694    if( pToCol ){
003695      for(i=0; i<nCol; i++){
003696        int n = sqlite3Strlen30(pToCol->a[i].zEName);
003697        pFKey->aCol[i].zCol = z;
003698        if( IN_RENAME_OBJECT ){
003699          sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName);
003700        }
003701        memcpy(z, pToCol->a[i].zEName, n);
003702        z[n] = 0;
003703        z += n+1;
003704      }
003705    }
003706    pFKey->isDeferred = 0;
003707    pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
003708    pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
003709  
003710    assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
003711    pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
003712        pFKey->zTo, (void *)pFKey
003713    );
003714    if( pNextTo==pFKey ){
003715      sqlite3OomFault(db);
003716      goto fk_end;
003717    }
003718    if( pNextTo ){
003719      assert( pNextTo->pPrevTo==0 );
003720      pFKey->pNextTo = pNextTo;
003721      pNextTo->pPrevTo = pFKey;
003722    }
003723  
003724    /* Link the foreign key to the table as the last step.
003725    */
003726    assert( IsOrdinaryTable(p) );
003727    p->u.tab.pFKey = pFKey;
003728    pFKey = 0;
003729  
003730  fk_end:
003731    sqlite3DbFree(db, pFKey);
003732  #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
003733    sqlite3ExprListDelete(db, pFromCol);
003734    sqlite3ExprListDelete(db, pToCol);
003735  }
003736  
003737  /*
003738  ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
003739  ** clause is seen as part of a foreign key definition.  The isDeferred
003740  ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
003741  ** The behavior of the most recently created foreign key is adjusted
003742  ** accordingly.
003743  */
003744  void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
003745  #ifndef SQLITE_OMIT_FOREIGN_KEY
003746    Table *pTab;
003747    FKey *pFKey;
003748    if( (pTab = pParse->pNewTable)==0 ) return;
003749    if( NEVER(!IsOrdinaryTable(pTab)) ) return;
003750    if( (pFKey = pTab->u.tab.pFKey)==0 ) return;
003751    assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
003752    pFKey->isDeferred = (u8)isDeferred;
003753  #endif
003754  }
003755  
003756  /*
003757  ** Generate code that will erase and refill index *pIdx.  This is
003758  ** used to initialize a newly created index or to recompute the
003759  ** content of an index in response to a REINDEX command.
003760  **
003761  ** if memRootPage is not negative, it means that the index is newly
003762  ** created.  The register specified by memRootPage contains the
003763  ** root page number of the index.  If memRootPage is negative, then
003764  ** the index already exists and must be cleared before being refilled and
003765  ** the root page number of the index is taken from pIndex->tnum.
003766  */
003767  static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
003768    Table *pTab = pIndex->pTable;  /* The table that is indexed */
003769    int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
003770    int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
003771    int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
003772    int addr1;                     /* Address of top of loop */
003773    int addr2;                     /* Address to jump to for next iteration */
003774    Pgno tnum;                     /* Root page of index */
003775    int iPartIdxLabel;             /* Jump to this label to skip a row */
003776    Vdbe *v;                       /* Generate code into this virtual machine */
003777    KeyInfo *pKey;                 /* KeyInfo for index */
003778    int regRecord;                 /* Register holding assembled index record */
003779    sqlite3 *db = pParse->db;      /* The database connection */
003780    int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
003781  
003782  #ifndef SQLITE_OMIT_AUTHORIZATION
003783    if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
003784        db->aDb[iDb].zDbSName ) ){
003785      return;
003786    }
003787  #endif
003788  
003789    /* Require a write-lock on the table to perform this operation */
003790    sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
003791  
003792    v = sqlite3GetVdbe(pParse);
003793    if( v==0 ) return;
003794    if( memRootPage>=0 ){
003795      tnum = (Pgno)memRootPage;
003796    }else{
003797      tnum = pIndex->tnum;
003798    }
003799    pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
003800    assert( pKey!=0 || pParse->nErr );
003801  
003802    /* Open the sorter cursor if we are to use one. */
003803    iSorter = pParse->nTab++;
003804    sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
003805                      sqlite3KeyInfoRef(pKey), P4_KEYINFO);
003806  
003807    /* Open the table. Loop through all rows of the table, inserting index
003808    ** records into the sorter. */
003809    sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
003810    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
003811    regRecord = sqlite3GetTempReg(pParse);
003812    sqlite3MultiWrite(pParse);
003813  
003814    sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
003815    sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
003816    sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
003817    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
003818    sqlite3VdbeJumpHere(v, addr1);
003819    if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
003820    sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, (int)tnum, iDb,
003821                      (char *)pKey, P4_KEYINFO);
003822    sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
003823  
003824    addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
003825    if( IsUniqueIndex(pIndex) ){
003826      int j2 = sqlite3VdbeGoto(v, 1);
003827      addr2 = sqlite3VdbeCurrentAddr(v);
003828      sqlite3VdbeVerifyAbortable(v, OE_Abort);
003829      sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
003830                           pIndex->nKeyCol); VdbeCoverage(v);
003831      sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
003832      sqlite3VdbeJumpHere(v, j2);
003833    }else{
003834      /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
003835      ** abort. The exception is if one of the indexed expressions contains a
003836      ** user function that throws an exception when it is evaluated. But the
003837      ** overhead of adding a statement journal to a CREATE INDEX statement is
003838      ** very small (since most of the pages written do not contain content that
003839      ** needs to be restored if the statement aborts), so we call
003840      ** sqlite3MayAbort() for all CREATE INDEX statements.  */
003841      sqlite3MayAbort(pParse);
003842      addr2 = sqlite3VdbeCurrentAddr(v);
003843    }
003844    sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
003845    if( !pIndex->bAscKeyBug ){
003846      /* This OP_SeekEnd opcode makes index insert for a REINDEX go much
003847      ** faster by avoiding unnecessary seeks.  But the optimization does
003848      ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
003849      ** with DESC primary keys, since those indexes have there keys in
003850      ** a different order from the main table.
003851      ** See ticket: https://sqlite.org/src/info/bba7b69f9849b5bf
003852      */
003853      sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
003854    }
003855    sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
003856    sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
003857    sqlite3ReleaseTempReg(pParse, regRecord);
003858    sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
003859    sqlite3VdbeJumpHere(v, addr1);
003860  
003861    sqlite3VdbeAddOp1(v, OP_Close, iTab);
003862    sqlite3VdbeAddOp1(v, OP_Close, iIdx);
003863    sqlite3VdbeAddOp1(v, OP_Close, iSorter);
003864  }
003865  
003866  /*
003867  ** Allocate heap space to hold an Index object with nCol columns.
003868  **
003869  ** Increase the allocation size to provide an extra nExtra bytes
003870  ** of 8-byte aligned space after the Index object and return a
003871  ** pointer to this extra space in *ppExtra.
003872  */
003873  Index *sqlite3AllocateIndexObject(
003874    sqlite3 *db,         /* Database connection */
003875    int nCol,            /* Total number of columns in the index */
003876    int nExtra,          /* Number of bytes of extra space to alloc */
003877    char **ppExtra       /* Pointer to the "extra" space */
003878  ){
003879    Index *p;            /* Allocated index object */
003880    i64 nByte;           /* Bytes of space for Index object + arrays */
003881  
003882    assert( nCol <= 2*db->aLimit[SQLITE_LIMIT_COLUMN] );
003883    nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
003884            ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
003885            ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
003886                   sizeof(i16)*nCol +            /* Index.aiColumn   */
003887                   sizeof(u8)*nCol);             /* Index.aSortOrder */
003888    p = sqlite3DbMallocZero(db, nByte + nExtra);
003889    if( p ){
003890      char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
003891      p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
003892      p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
003893      p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
003894      p->aSortOrder = (u8*)pExtra;
003895      assert( nCol>0 );
003896      p->nColumn = (u16)nCol;
003897      p->nKeyCol = (u16)(nCol - 1);
003898      *ppExtra = ((char*)p) + nByte;
003899    }
003900    return p;
003901  }
003902  
003903  /*
003904  ** If expression list pList contains an expression that was parsed with
003905  ** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in
003906  ** pParse and return non-zero. Otherwise, return zero.
003907  */
003908  int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){
003909    if( pList ){
003910      int i;
003911      for(i=0; i<pList->nExpr; i++){
003912        if( pList->a[i].fg.bNulls ){
003913          u8 sf = pList->a[i].fg.sortFlags;
003914          sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s",
003915              (sf==0 || sf==3) ? "FIRST" : "LAST"
003916          );
003917          return 1;
003918        }
003919      }
003920    }
003921    return 0;
003922  }
003923  
003924  /*
003925  ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
003926  ** and pTblList is the name of the table that is to be indexed.  Both will
003927  ** be NULL for a primary key or an index that is created to satisfy a
003928  ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
003929  ** as the table to be indexed.  pParse->pNewTable is a table that is
003930  ** currently being constructed by a CREATE TABLE statement.
003931  **
003932  ** pList is a list of columns to be indexed.  pList will be NULL if this
003933  ** is a primary key or unique-constraint on the most recent column added
003934  ** to the table currently under construction. 
003935  */
003936  void sqlite3CreateIndex(
003937    Parse *pParse,     /* All information about this parse */
003938    Token *pName1,     /* First part of index name. May be NULL */
003939    Token *pName2,     /* Second part of index name. May be NULL */
003940    SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
003941    ExprList *pList,   /* A list of columns to be indexed */
003942    int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
003943    Token *pStart,     /* The CREATE token that begins this statement */
003944    Expr *pPIWhere,    /* WHERE clause for partial indices */
003945    int sortOrder,     /* Sort order of primary key when pList==NULL */
003946    int ifNotExist,    /* Omit error if index already exists */
003947    u8 idxType         /* The index type */
003948  ){
003949    Table *pTab = 0;     /* Table to be indexed */
003950    Index *pIndex = 0;   /* The index to be created */
003951    char *zName = 0;     /* Name of the index */
003952    int nName;           /* Number of characters in zName */
003953    int i, j;
003954    DbFixer sFix;        /* For assigning database names to pTable */
003955    int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
003956    sqlite3 *db = pParse->db;
003957    Db *pDb;             /* The specific table containing the indexed database */
003958    int iDb;             /* Index of the database that is being written */
003959    Token *pName = 0;    /* Unqualified name of the index to create */
003960    struct ExprList_item *pListItem; /* For looping over pList */
003961    int nExtra = 0;                  /* Space allocated for zExtra[] */
003962    int nExtraCol;                   /* Number of extra columns needed */
003963    char *zExtra = 0;                /* Extra space after the Index object */
003964    Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
003965  
003966    assert( db->pParse==pParse );
003967    if( pParse->nErr ){
003968      goto exit_create_index;
003969    }
003970    assert( db->mallocFailed==0 );
003971    if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
003972      goto exit_create_index;
003973    }
003974    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
003975      goto exit_create_index;
003976    }
003977    if( sqlite3HasExplicitNulls(pParse, pList) ){
003978      goto exit_create_index;
003979    }
003980  
003981    /*
003982    ** Find the table that is to be indexed.  Return early if not found.
003983    */
003984    if( pTblName!=0 ){
003985  
003986      /* Use the two-part index name to determine the database
003987      ** to search for the table. 'Fix' the table name to this db
003988      ** before looking up the table.
003989      */
003990      assert( pName1 && pName2 );
003991      iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
003992      if( iDb<0 ) goto exit_create_index;
003993      assert( pName && pName->z );
003994  
003995  #ifndef SQLITE_OMIT_TEMPDB
003996      /* If the index name was unqualified, check if the table
003997      ** is a temp table. If so, set the database to 1. Do not do this
003998      ** if initializing a database schema.
003999      */
004000      if( !db->init.busy ){
004001        pTab = sqlite3SrcListLookup(pParse, pTblName);
004002        if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
004003          iDb = 1;
004004        }
004005      }
004006  #endif
004007  
004008      sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
004009      if( sqlite3FixSrcList(&sFix, pTblName) ){
004010        /* Because the parser constructs pTblName from a single identifier,
004011        ** sqlite3FixSrcList can never fail. */
004012        assert(0);
004013      }
004014      pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
004015      assert( db->mallocFailed==0 || pTab==0 );
004016      if( pTab==0 ) goto exit_create_index;
004017      if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
004018        sqlite3ErrorMsg(pParse,
004019             "cannot create a TEMP index on non-TEMP table \"%s\"",
004020             pTab->zName);
004021        goto exit_create_index;
004022      }
004023      if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
004024    }else{
004025      assert( pName==0 );
004026      assert( pStart==0 );
004027      pTab = pParse->pNewTable;
004028      if( !pTab ) goto exit_create_index;
004029      iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
004030    }
004031    pDb = &db->aDb[iDb];
004032  
004033    assert( pTab!=0 );
004034    if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
004035         && db->init.busy==0
004036         && pTblName!=0
004037    ){
004038      sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
004039      goto exit_create_index;
004040    }
004041  #ifndef SQLITE_OMIT_VIEW
004042    if( IsView(pTab) ){
004043      sqlite3ErrorMsg(pParse, "views may not be indexed");
004044      goto exit_create_index;
004045    }
004046  #endif
004047  #ifndef SQLITE_OMIT_VIRTUALTABLE
004048    if( IsVirtual(pTab) ){
004049      sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
004050      goto exit_create_index;
004051    }
004052  #endif
004053  
004054    /*
004055    ** Find the name of the index.  Make sure there is not already another
004056    ** index or table with the same name. 
004057    **
004058    ** Exception:  If we are reading the names of permanent indices from the
004059    ** sqlite_schema table (because some other process changed the schema) and
004060    ** one of the index names collides with the name of a temporary table or
004061    ** index, then we will continue to process this index.
004062    **
004063    ** If pName==0 it means that we are
004064    ** dealing with a primary key or UNIQUE constraint.  We have to invent our
004065    ** own name.
004066    */
004067    if( pName ){
004068      zName = sqlite3NameFromToken(db, pName);
004069      if( zName==0 ) goto exit_create_index;
004070      assert( pName->z!=0 );
004071      if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){
004072        goto exit_create_index;
004073      }
004074      if( !IN_RENAME_OBJECT ){
004075        if( !db->init.busy ){
004076          if( sqlite3FindTable(db, zName, pDb->zDbSName)!=0 ){
004077            sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
004078            goto exit_create_index;
004079          }
004080        }
004081        if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
004082          if( !ifNotExist ){
004083            sqlite3ErrorMsg(pParse, "index %s already exists", zName);
004084          }else{
004085            assert( !db->init.busy );
004086            sqlite3CodeVerifySchema(pParse, iDb);
004087            sqlite3ForceNotReadOnly(pParse);
004088          }
004089          goto exit_create_index;
004090        }
004091      }
004092    }else{
004093      int n;
004094      Index *pLoop;
004095      for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
004096      zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
004097      if( zName==0 ){
004098        goto exit_create_index;
004099      }
004100  
004101      /* Automatic index names generated from within sqlite3_declare_vtab()
004102      ** must have names that are distinct from normal automatic index names.
004103      ** The following statement converts "sqlite3_autoindex..." into
004104      ** "sqlite3_butoindex..." in order to make the names distinct.
004105      ** The "vtab_err.test" test demonstrates the need of this statement. */
004106      if( IN_SPECIAL_PARSE ) zName[7]++;
004107    }
004108  
004109    /* Check for authorization to create an index.
004110    */
004111  #ifndef SQLITE_OMIT_AUTHORIZATION
004112    if( !IN_RENAME_OBJECT ){
004113      const char *zDb = pDb->zDbSName;
004114      if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
004115        goto exit_create_index;
004116      }
004117      i = SQLITE_CREATE_INDEX;
004118      if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
004119      if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
004120        goto exit_create_index;
004121      }
004122    }
004123  #endif
004124  
004125    /* If pList==0, it means this routine was called to make a primary
004126    ** key out of the last column added to the table under construction.
004127    ** So create a fake list to simulate this.
004128    */
004129    if( pList==0 ){
004130      Token prevCol;
004131      Column *pCol = &pTab->aCol[pTab->nCol-1];
004132      pCol->colFlags |= COLFLAG_UNIQUE;
004133      sqlite3TokenInit(&prevCol, pCol->zCnName);
004134      pList = sqlite3ExprListAppend(pParse, 0,
004135                sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
004136      if( pList==0 ) goto exit_create_index;
004137      assert( pList->nExpr==1 );
004138      sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED);
004139    }else{
004140      sqlite3ExprListCheckLength(pParse, pList, "index");
004141      if( pParse->nErr ) goto exit_create_index;
004142    }
004143  
004144    /* Figure out how many bytes of space are required to store explicitly
004145    ** specified collation sequence names.
004146    */
004147    for(i=0; i<pList->nExpr; i++){
004148      Expr *pExpr = pList->a[i].pExpr;
004149      assert( pExpr!=0 );
004150      if( pExpr->op==TK_COLLATE ){
004151        assert( !ExprHasProperty(pExpr, EP_IntValue) );
004152        nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
004153      }
004154    }
004155  
004156    /*
004157    ** Allocate the index structure.
004158    */
004159    nName = sqlite3Strlen30(zName);
004160    nExtraCol = pPk ? pPk->nKeyCol : 1;
004161    assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
004162    pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
004163                                        nName + nExtra + 1, &zExtra);
004164    if( db->mallocFailed ){
004165      goto exit_create_index;
004166    }
004167    assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
004168    assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
004169    pIndex->zName = zExtra;
004170    zExtra += nName + 1;
004171    memcpy(pIndex->zName, zName, nName+1);
004172    pIndex->pTable = pTab;
004173    pIndex->onError = (u8)onError;
004174    pIndex->uniqNotNull = onError!=OE_None;
004175    pIndex->idxType = idxType;
004176    pIndex->pSchema = db->aDb[iDb].pSchema;
004177    pIndex->nKeyCol = pList->nExpr;
004178    if( pPIWhere ){
004179      sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
004180      pIndex->pPartIdxWhere = pPIWhere;
004181      pPIWhere = 0;
004182    }
004183    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
004184  
004185    /* Check to see if we should honor DESC requests on index columns
004186    */
004187    if( pDb->pSchema->file_format>=4 ){
004188      sortOrderMask = -1;   /* Honor DESC */
004189    }else{
004190      sortOrderMask = 0;    /* Ignore DESC */
004191    }
004192  
004193    /* Analyze the list of expressions that form the terms of the index and
004194    ** report any errors.  In the common case where the expression is exactly
004195    ** a table column, store that column in aiColumn[].  For general expressions,
004196    ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
004197    **
004198    ** TODO: Issue a warning if two or more columns of the index are identical.
004199    ** TODO: Issue a warning if the table primary key is used as part of the
004200    ** index key.
004201    */
004202    pListItem = pList->a;
004203    if( IN_RENAME_OBJECT ){
004204      pIndex->aColExpr = pList;
004205      pList = 0;
004206    }
004207    for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
004208      Expr *pCExpr;                  /* The i-th index expression */
004209      int requestedSortOrder;        /* ASC or DESC on the i-th expression */
004210      const char *zColl;             /* Collation sequence name */
004211  
004212      sqlite3StringToId(pListItem->pExpr);
004213      sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
004214      if( pParse->nErr ) goto exit_create_index;
004215      pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
004216      if( pCExpr->op!=TK_COLUMN ){
004217        if( pTab==pParse->pNewTable ){
004218          sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
004219                                  "UNIQUE constraints");
004220          goto exit_create_index;
004221        }
004222        if( pIndex->aColExpr==0 ){
004223          pIndex->aColExpr = pList;
004224          pList = 0;
004225        }
004226        j = XN_EXPR;
004227        pIndex->aiColumn[i] = XN_EXPR;
004228        pIndex->uniqNotNull = 0;
004229        pIndex->bHasExpr = 1;
004230      }else{
004231        j = pCExpr->iColumn;
004232        assert( j<=0x7fff );
004233        if( j<0 ){
004234          j = pTab->iPKey;
004235        }else{
004236          if( pTab->aCol[j].notNull==0 ){
004237            pIndex->uniqNotNull = 0;
004238          }
004239          if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){
004240            pIndex->bHasVCol = 1;
004241            pIndex->bHasExpr = 1;
004242          }
004243        }
004244        pIndex->aiColumn[i] = (i16)j;
004245      }
004246      zColl = 0;
004247      if( pListItem->pExpr->op==TK_COLLATE ){
004248        int nColl;
004249        assert( !ExprHasProperty(pListItem->pExpr, EP_IntValue) );
004250        zColl = pListItem->pExpr->u.zToken;
004251        nColl = sqlite3Strlen30(zColl) + 1;
004252        assert( nExtra>=nColl );
004253        memcpy(zExtra, zColl, nColl);
004254        zColl = zExtra;
004255        zExtra += nColl;
004256        nExtra -= nColl;
004257      }else if( j>=0 ){
004258        zColl = sqlite3ColumnColl(&pTab->aCol[j]);
004259      }
004260      if( !zColl ) zColl = sqlite3StrBINARY;
004261      if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
004262        goto exit_create_index;
004263      }
004264      pIndex->azColl[i] = zColl;
004265      requestedSortOrder = pListItem->fg.sortFlags & sortOrderMask;
004266      pIndex->aSortOrder[i] = (u8)requestedSortOrder;
004267    }
004268  
004269    /* Append the table key to the end of the index.  For WITHOUT ROWID
004270    ** tables (when pPk!=0) this will be the declared PRIMARY KEY.  For
004271    ** normal tables (when pPk==0) this will be the rowid.
004272    */
004273    if( pPk ){
004274      for(j=0; j<pPk->nKeyCol; j++){
004275        int x = pPk->aiColumn[j];
004276        assert( x>=0 );
004277        if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
004278          pIndex->nColumn--;
004279        }else{
004280          testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
004281          pIndex->aiColumn[i] = x;
004282          pIndex->azColl[i] = pPk->azColl[j];
004283          pIndex->aSortOrder[i] = pPk->aSortOrder[j];
004284          i++;
004285        }
004286      }
004287      assert( i==pIndex->nColumn );
004288    }else{
004289      pIndex->aiColumn[i] = XN_ROWID;
004290      pIndex->azColl[i] = sqlite3StrBINARY;
004291    }
004292    sqlite3DefaultRowEst(pIndex);
004293    if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
004294  
004295    /* If this index contains every column of its table, then mark
004296    ** it as a covering index */
004297    assert( HasRowid(pTab)
004298        || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 );
004299    recomputeColumnsNotIndexed(pIndex);
004300    if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
004301      pIndex->isCovering = 1;
004302      for(j=0; j<pTab->nCol; j++){
004303        if( j==pTab->iPKey ) continue;
004304        if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue;
004305        pIndex->isCovering = 0;
004306        break;
004307      }
004308    }
004309  
004310    if( pTab==pParse->pNewTable ){
004311      /* This routine has been called to create an automatic index as a
004312      ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
004313      ** a PRIMARY KEY or UNIQUE clause following the column definitions.
004314      ** i.e. one of:
004315      **
004316      ** CREATE TABLE t(x PRIMARY KEY, y);
004317      ** CREATE TABLE t(x, y, UNIQUE(x, y));
004318      **
004319      ** Either way, check to see if the table already has such an index. If
004320      ** so, don't bother creating this one. This only applies to
004321      ** automatically created indices. Users can do as they wish with
004322      ** explicit indices.
004323      **
004324      ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
004325      ** (and thus suppressing the second one) even if they have different
004326      ** sort orders.
004327      **
004328      ** If there are different collating sequences or if the columns of
004329      ** the constraint occur in different orders, then the constraints are
004330      ** considered distinct and both result in separate indices.
004331      */
004332      Index *pIdx;
004333      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
004334        int k;
004335        assert( IsUniqueIndex(pIdx) );
004336        assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
004337        assert( IsUniqueIndex(pIndex) );
004338  
004339        if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
004340        for(k=0; k<pIdx->nKeyCol; k++){
004341          const char *z1;
004342          const char *z2;
004343          assert( pIdx->aiColumn[k]>=0 );
004344          if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
004345          z1 = pIdx->azColl[k];
004346          z2 = pIndex->azColl[k];
004347          if( sqlite3StrICmp(z1, z2) ) break;
004348        }
004349        if( k==pIdx->nKeyCol ){
004350          if( pIdx->onError!=pIndex->onError ){
004351            /* This constraint creates the same index as a previous
004352            ** constraint specified somewhere in the CREATE TABLE statement.
004353            ** However the ON CONFLICT clauses are different. If both this
004354            ** constraint and the previous equivalent constraint have explicit
004355            ** ON CONFLICT clauses this is an error. Otherwise, use the
004356            ** explicitly specified behavior for the index.
004357            */
004358            if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
004359              sqlite3ErrorMsg(pParse,
004360                  "conflicting ON CONFLICT clauses specified", 0);
004361            }
004362            if( pIdx->onError==OE_Default ){
004363              pIdx->onError = pIndex->onError;
004364            }
004365          }
004366          if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
004367          if( IN_RENAME_OBJECT ){
004368            pIndex->pNext = pParse->pNewIndex;
004369            pParse->pNewIndex = pIndex;
004370            pIndex = 0;
004371          }
004372          goto exit_create_index;
004373        }
004374      }
004375    }
004376  
004377    if( !IN_RENAME_OBJECT ){
004378  
004379      /* Link the new Index structure to its table and to the other
004380      ** in-memory database structures.
004381      */
004382      assert( pParse->nErr==0 );
004383      if( db->init.busy ){
004384        Index *p;
004385        assert( !IN_SPECIAL_PARSE );
004386        assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
004387        if( pTblName!=0 ){
004388          pIndex->tnum = db->init.newTnum;
004389          if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
004390            sqlite3ErrorMsg(pParse, "invalid rootpage");
004391            pParse->rc = SQLITE_CORRUPT_BKPT;
004392            goto exit_create_index;
004393          }
004394        }
004395        p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
004396            pIndex->zName, pIndex);
004397        if( p ){
004398          assert( p==pIndex );  /* Malloc must have failed */
004399          sqlite3OomFault(db);
004400          goto exit_create_index;
004401        }
004402        db->mDbFlags |= DBFLAG_SchemaChange;
004403      }
004404  
004405      /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
004406      ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
004407      ** emit code to allocate the index rootpage on disk and make an entry for
004408      ** the index in the sqlite_schema table and populate the index with
004409      ** content.  But, do not do this if we are simply reading the sqlite_schema
004410      ** table to parse the schema, or if this index is the PRIMARY KEY index
004411      ** of a WITHOUT ROWID table.
004412      **
004413      ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
004414      ** or UNIQUE index in a CREATE TABLE statement.  Since the table
004415      ** has just been created, it contains no data and the index initialization
004416      ** step can be skipped.
004417      */
004418      else if( HasRowid(pTab) || pTblName!=0 ){
004419        Vdbe *v;
004420        char *zStmt;
004421        int iMem = ++pParse->nMem;
004422  
004423        v = sqlite3GetVdbe(pParse);
004424        if( v==0 ) goto exit_create_index;
004425  
004426        sqlite3BeginWriteOperation(pParse, 1, iDb);
004427  
004428        /* Create the rootpage for the index using CreateIndex. But before
004429        ** doing so, code a Noop instruction and store its address in
004430        ** Index.tnum. This is required in case this index is actually a
004431        ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
004432        ** that case the convertToWithoutRowidTable() routine will replace
004433        ** the Noop with a Goto to jump over the VDBE code generated below. */
004434        pIndex->tnum = (Pgno)sqlite3VdbeAddOp0(v, OP_Noop);
004435        sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
004436  
004437        /* Gather the complete text of the CREATE INDEX statement into
004438        ** the zStmt variable
004439        */
004440        assert( pName!=0 || pStart==0 );
004441        if( pStart ){
004442          int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
004443          if( pName->z[n-1]==';' ) n--;
004444          /* A named index with an explicit CREATE INDEX statement */
004445          zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
004446              onError==OE_None ? "" : " UNIQUE", n, pName->z);
004447        }else{
004448          /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
004449          /* zStmt = sqlite3MPrintf(""); */
004450          zStmt = 0;
004451        }
004452  
004453        /* Add an entry in sqlite_schema for this index
004454        */
004455        sqlite3NestedParse(pParse,
004456           "INSERT INTO %Q." LEGACY_SCHEMA_TABLE " VALUES('index',%Q,%Q,#%d,%Q);",
004457           db->aDb[iDb].zDbSName,
004458           pIndex->zName,
004459           pTab->zName,
004460           iMem,
004461           zStmt
004462        );
004463        sqlite3DbFree(db, zStmt);
004464  
004465        /* Fill the index with data and reparse the schema. Code an OP_Expire
004466        ** to invalidate all pre-compiled statements.
004467        */
004468        if( pTblName ){
004469          sqlite3RefillIndex(pParse, pIndex, iMem);
004470          sqlite3ChangeCookie(pParse, iDb);
004471          sqlite3VdbeAddParseSchemaOp(v, iDb,
004472              sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 0);
004473          sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
004474        }
004475  
004476        sqlite3VdbeJumpHere(v, (int)pIndex->tnum);
004477      }
004478    }
004479    if( db->init.busy || pTblName==0 ){
004480      pIndex->pNext = pTab->pIndex;
004481      pTab->pIndex = pIndex;
004482      pIndex = 0;
004483    }
004484    else if( IN_RENAME_OBJECT ){
004485      assert( pParse->pNewIndex==0 );
004486      pParse->pNewIndex = pIndex;
004487      pIndex = 0;
004488    }
004489  
004490    /* Clean up before exiting */
004491  exit_create_index:
004492    if( pIndex ) sqlite3FreeIndex(db, pIndex);
004493    if( pTab ){
004494      /* Ensure all REPLACE indexes on pTab are at the end of the pIndex list.
004495      ** The list was already ordered when this routine was entered, so at this
004496      ** point at most a single index (the newly added index) will be out of
004497      ** order.  So we have to reorder at most one index. */
004498      Index **ppFrom;
004499      Index *pThis;
004500      for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){
004501        Index *pNext;
004502        if( pThis->onError!=OE_Replace ) continue;
004503        while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){
004504          *ppFrom = pNext;
004505          pThis->pNext = pNext->pNext;
004506          pNext->pNext = pThis;
004507          ppFrom = &pNext->pNext;
004508        }
004509        break;
004510      }
004511  #ifdef SQLITE_DEBUG
004512      /* Verify that all REPLACE indexes really are now at the end
004513      ** of the index list.  In other words, no other index type ever
004514      ** comes after a REPLACE index on the list. */
004515      for(pThis = pTab->pIndex; pThis; pThis=pThis->pNext){
004516        assert( pThis->onError!=OE_Replace
004517             || pThis->pNext==0
004518             || pThis->pNext->onError==OE_Replace );
004519      }
004520  #endif
004521    }
004522    sqlite3ExprDelete(db, pPIWhere);
004523    sqlite3ExprListDelete(db, pList);
004524    sqlite3SrcListDelete(db, pTblName);
004525    sqlite3DbFree(db, zName);
004526  }
004527  
004528  /*
004529  ** Fill the Index.aiRowEst[] array with default information - information
004530  ** to be used when we have not run the ANALYZE command.
004531  **
004532  ** aiRowEst[0] is supposed to contain the number of elements in the index.
004533  ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
004534  ** number of rows in the table that match any particular value of the
004535  ** first column of the index.  aiRowEst[2] is an estimate of the number
004536  ** of rows that match any particular combination of the first 2 columns
004537  ** of the index.  And so forth.  It must always be the case that
004538  *
004539  **           aiRowEst[N]<=aiRowEst[N-1]
004540  **           aiRowEst[N]>=1
004541  **
004542  ** Apart from that, we have little to go on besides intuition as to
004543  ** how aiRowEst[] should be initialized.  The numbers generated here
004544  ** are based on typical values found in actual indices.
004545  */
004546  void sqlite3DefaultRowEst(Index *pIdx){
004547                 /*                10,  9,  8,  7,  6 */
004548    static const LogEst aVal[] = { 33, 32, 30, 28, 26 };
004549    LogEst *a = pIdx->aiRowLogEst;
004550    LogEst x;
004551    int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
004552    int i;
004553  
004554    /* Indexes with default row estimates should not have stat1 data */
004555    assert( !pIdx->hasStat1 );
004556  
004557    /* Set the first entry (number of rows in the index) to the estimated
004558    ** number of rows in the table, or half the number of rows in the table
004559    ** for a partial index.
004560    **
004561    ** 2020-05-27:  If some of the stat data is coming from the sqlite_stat1
004562    ** table but other parts we are having to guess at, then do not let the
004563    ** estimated number of rows in the table be less than 1000 (LogEst 99).
004564    ** Failure to do this can cause the indexes for which we do not have
004565    ** stat1 data to be ignored by the query planner.
004566    */
004567    x = pIdx->pTable->nRowLogEst;
004568    assert( 99==sqlite3LogEst(1000) );
004569    if( x<99 ){
004570      pIdx->pTable->nRowLogEst = x = 99;
004571    }
004572    if( pIdx->pPartIdxWhere!=0 ){ x -= 10;  assert( 10==sqlite3LogEst(2) ); }
004573    a[0] = x;
004574  
004575    /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
004576    ** 6 and each subsequent value (if any) is 5.  */
004577    memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
004578    for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
004579      a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
004580    }
004581  
004582    assert( 0==sqlite3LogEst(1) );
004583    if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
004584  }
004585  
004586  /*
004587  ** This routine will drop an existing named index.  This routine
004588  ** implements the DROP INDEX statement.
004589  */
004590  void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
004591    Index *pIndex;
004592    Vdbe *v;
004593    sqlite3 *db = pParse->db;
004594    int iDb;
004595  
004596    if( db->mallocFailed ){
004597      goto exit_drop_index;
004598    }
004599    assert( pParse->nErr==0 );   /* Never called with prior non-OOM errors */
004600    assert( pName->nSrc==1 );
004601    assert( pName->a[0].fg.fixedSchema==0 );
004602    assert( pName->a[0].fg.isSubquery==0 );
004603    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
004604      goto exit_drop_index;
004605    }
004606    pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].u4.zDatabase);
004607    if( pIndex==0 ){
004608      if( !ifExists ){
004609        sqlite3ErrorMsg(pParse, "no such index: %S", pName->a);
004610      }else{
004611        sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].u4.zDatabase);
004612        sqlite3ForceNotReadOnly(pParse);
004613      }
004614      pParse->checkSchema = 1;
004615      goto exit_drop_index;
004616    }
004617    if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
004618      sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
004619        "or PRIMARY KEY constraint cannot be dropped", 0);
004620      goto exit_drop_index;
004621    }
004622    iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
004623  #ifndef SQLITE_OMIT_AUTHORIZATION
004624    {
004625      int code = SQLITE_DROP_INDEX;
004626      Table *pTab = pIndex->pTable;
004627      const char *zDb = db->aDb[iDb].zDbSName;
004628      const char *zTab = SCHEMA_TABLE(iDb);
004629      if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
004630        goto exit_drop_index;
004631      }
004632      if( !OMIT_TEMPDB && iDb==1 ) code = SQLITE_DROP_TEMP_INDEX;
004633      if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
004634        goto exit_drop_index;
004635      }
004636    }
004637  #endif
004638  
004639    /* Generate code to remove the index and from the schema table */
004640    v = sqlite3GetVdbe(pParse);
004641    if( v ){
004642      sqlite3BeginWriteOperation(pParse, 1, iDb);
004643      sqlite3NestedParse(pParse,
004644         "DELETE FROM %Q." LEGACY_SCHEMA_TABLE " WHERE name=%Q AND type='index'",
004645         db->aDb[iDb].zDbSName, pIndex->zName
004646      );
004647      sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
004648      sqlite3ChangeCookie(pParse, iDb);
004649      destroyRootPage(pParse, pIndex->tnum, iDb);
004650      sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
004651    }
004652  
004653  exit_drop_index:
004654    sqlite3SrcListDelete(db, pName);
004655  }
004656  
004657  /*
004658  ** pArray is a pointer to an array of objects. Each object in the
004659  ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
004660  ** to extend the array so that there is space for a new object at the end.
004661  **
004662  ** When this function is called, *pnEntry contains the current size of
004663  ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
004664  ** in total).
004665  **
004666  ** If the realloc() is successful (i.e. if no OOM condition occurs), the
004667  ** space allocated for the new object is zeroed, *pnEntry updated to
004668  ** reflect the new size of the array and a pointer to the new allocation
004669  ** returned. *pIdx is set to the index of the new array entry in this case.
004670  **
004671  ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
004672  ** unchanged and a copy of pArray returned.
004673  */
004674  void *sqlite3ArrayAllocate(
004675    sqlite3 *db,      /* Connection to notify of malloc failures */
004676    void *pArray,     /* Array of objects.  Might be reallocated */
004677    int szEntry,      /* Size of each object in the array */
004678    int *pnEntry,     /* Number of objects currently in use */
004679    int *pIdx         /* Write the index of a new slot here */
004680  ){
004681    char *z;
004682    sqlite3_int64 n = *pIdx = *pnEntry;
004683    if( (n & (n-1))==0 ){
004684      sqlite3_int64 sz = (n==0) ? 1 : 2*n;
004685      void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
004686      if( pNew==0 ){
004687        *pIdx = -1;
004688        return pArray;
004689      }
004690      pArray = pNew;
004691    }
004692    z = (char*)pArray;
004693    memset(&z[n * szEntry], 0, szEntry);
004694    ++*pnEntry;
004695    return pArray;
004696  }
004697  
004698  /*
004699  ** Append a new element to the given IdList.  Create a new IdList if
004700  ** need be.
004701  **
004702  ** A new IdList is returned, or NULL if malloc() fails.
004703  */
004704  IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
004705    sqlite3 *db = pParse->db;
004706    int i;
004707    if( pList==0 ){
004708      pList = sqlite3DbMallocZero(db, SZ_IDLIST(1));
004709      if( pList==0 ) return 0;
004710    }else{
004711      IdList *pNew;
004712      pNew = sqlite3DbRealloc(db, pList, SZ_IDLIST(pList->nId+1));
004713      if( pNew==0 ){
004714        sqlite3IdListDelete(db, pList);
004715        return 0;
004716      }
004717      pList = pNew;
004718    }
004719    i = pList->nId++;
004720    pList->a[i].zName = sqlite3NameFromToken(db, pToken);
004721    if( IN_RENAME_OBJECT && pList->a[i].zName ){
004722      sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
004723    }
004724    return pList;
004725  }
004726  
004727  /*
004728  ** Delete an IdList.
004729  */
004730  void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
004731    int i;
004732    assert( db!=0 );
004733    if( pList==0 ) return;
004734    for(i=0; i<pList->nId; i++){
004735      sqlite3DbFree(db, pList->a[i].zName);
004736    }
004737    sqlite3DbNNFreeNN(db, pList);
004738  }
004739  
004740  /*
004741  ** Return the index in pList of the identifier named zId.  Return -1
004742  ** if not found.
004743  */
004744  int sqlite3IdListIndex(IdList *pList, const char *zName){
004745    int i;
004746    assert( pList!=0 );
004747    for(i=0; i<pList->nId; i++){
004748      if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
004749    }
004750    return -1;
004751  }
004752  
004753  /*
004754  ** Maximum size of a SrcList object.
004755  ** The SrcList object is used to represent the FROM clause of a
004756  ** SELECT statement, and the query planner cannot deal with more
004757  ** than 64 tables in a join.  So any value larger than 64 here
004758  ** is sufficient for most uses.  Smaller values, like say 10, are
004759  ** appropriate for small and memory-limited applications.
004760  */
004761  #ifndef SQLITE_MAX_SRCLIST
004762  # define SQLITE_MAX_SRCLIST 200
004763  #endif
004764  
004765  /*
004766  ** Expand the space allocated for the given SrcList object by
004767  ** creating nExtra new slots beginning at iStart.  iStart is zero based.
004768  ** New slots are zeroed.
004769  **
004770  ** For example, suppose a SrcList initially contains two entries: A,B.
004771  ** To append 3 new entries onto the end, do this:
004772  **
004773  **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
004774  **
004775  ** After the call above it would contain:  A, B, nil, nil, nil.
004776  ** If the iStart argument had been 1 instead of 2, then the result
004777  ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
004778  ** the iStart value would be 0.  The result then would
004779  ** be: nil, nil, nil, A, B.
004780  **
004781  ** If a memory allocation fails or the SrcList becomes too large, leave
004782  ** the original SrcList unchanged, return NULL, and leave an error message
004783  ** in pParse.
004784  */
004785  SrcList *sqlite3SrcListEnlarge(
004786    Parse *pParse,     /* Parsing context into which errors are reported */
004787    SrcList *pSrc,     /* The SrcList to be enlarged */
004788    int nExtra,        /* Number of new slots to add to pSrc->a[] */
004789    int iStart         /* Index in pSrc->a[] of first new slot */
004790  ){
004791    int i;
004792  
004793    /* Sanity checking on calling parameters */
004794    assert( iStart>=0 );
004795    assert( nExtra>=1 );
004796    assert( pSrc!=0 );
004797    assert( iStart<=pSrc->nSrc );
004798  
004799    /* Allocate additional space if needed */
004800    if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
004801      SrcList *pNew;
004802      sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
004803      sqlite3 *db = pParse->db;
004804  
004805      if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
004806        sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
004807                        SQLITE_MAX_SRCLIST);
004808        return 0;
004809      }
004810      if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
004811      pNew = sqlite3DbRealloc(db, pSrc, SZ_SRCLIST(nAlloc));
004812      if( pNew==0 ){
004813        assert( db->mallocFailed );
004814        return 0;
004815      }
004816      pSrc = pNew;
004817      pSrc->nAlloc = nAlloc;
004818    }
004819  
004820    /* Move existing slots that come after the newly inserted slots
004821    ** out of the way */
004822    for(i=pSrc->nSrc-1; i>=iStart; i--){
004823      pSrc->a[i+nExtra] = pSrc->a[i];
004824    }
004825    pSrc->nSrc += nExtra;
004826  
004827    /* Zero the newly allocated slots */
004828    memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
004829    for(i=iStart; i<iStart+nExtra; i++){
004830      pSrc->a[i].iCursor = -1;
004831    }
004832  
004833    /* Return a pointer to the enlarged SrcList */
004834    return pSrc;
004835  }
004836  
004837  
004838  /*
004839  ** Append a new table name to the given SrcList.  Create a new SrcList if
004840  ** need be.  A new entry is created in the SrcList even if pTable is NULL.
004841  **
004842  ** A SrcList is returned, or NULL if there is an OOM error or if the
004843  ** SrcList grows to large.  The returned
004844  ** SrcList might be the same as the SrcList that was input or it might be
004845  ** a new one.  If an OOM error does occurs, then the prior value of pList
004846  ** that is input to this routine is automatically freed.
004847  **
004848  ** If pDatabase is not null, it means that the table has an optional
004849  ** database name prefix.  Like this:  "database.table".  The pDatabase
004850  ** points to the table name and the pTable points to the database name.
004851  ** The SrcList.a[].zName field is filled with the table name which might
004852  ** come from pTable (if pDatabase is NULL) or from pDatabase. 
004853  ** SrcList.a[].zDatabase is filled with the database name from pTable,
004854  ** or with NULL if no database is specified.
004855  **
004856  ** In other words, if call like this:
004857  **
004858  **         sqlite3SrcListAppend(D,A,B,0);
004859  **
004860  ** Then B is a table name and the database name is unspecified.  If called
004861  ** like this:
004862  **
004863  **         sqlite3SrcListAppend(D,A,B,C);
004864  **
004865  ** Then C is the table name and B is the database name.  If C is defined
004866  ** then so is B.  In other words, we never have a case where:
004867  **
004868  **         sqlite3SrcListAppend(D,A,0,C);
004869  **
004870  ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
004871  ** before being added to the SrcList.
004872  */
004873  SrcList *sqlite3SrcListAppend(
004874    Parse *pParse,      /* Parsing context, in which errors are reported */
004875    SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
004876    Token *pTable,      /* Table to append */
004877    Token *pDatabase    /* Database of the table */
004878  ){
004879    SrcItem *pItem;
004880    sqlite3 *db;
004881    assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
004882    assert( pParse!=0 );
004883    assert( pParse->db!=0 );
004884    db = pParse->db;
004885    if( pList==0 ){
004886      pList = sqlite3DbMallocRawNN(pParse->db, SZ_SRCLIST(1));
004887      if( pList==0 ) return 0;
004888      pList->nAlloc = 1;
004889      pList->nSrc = 1;
004890      memset(&pList->a[0], 0, sizeof(pList->a[0]));
004891      pList->a[0].iCursor = -1;
004892    }else{
004893      SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
004894      if( pNew==0 ){
004895        sqlite3SrcListDelete(db, pList);
004896        return 0;
004897      }else{
004898        pList = pNew;
004899      }
004900    }
004901    pItem = &pList->a[pList->nSrc-1];
004902    if( pDatabase && pDatabase->z==0 ){
004903      pDatabase = 0;
004904    }
004905    assert( pItem->fg.fixedSchema==0 );
004906    assert( pItem->fg.isSubquery==0 );
004907    if( pDatabase ){
004908      pItem->zName = sqlite3NameFromToken(db, pDatabase);
004909      pItem->u4.zDatabase = sqlite3NameFromToken(db, pTable);
004910    }else{
004911      pItem->zName = sqlite3NameFromToken(db, pTable);
004912      pItem->u4.zDatabase = 0;
004913    }
004914    return pList;
004915  }
004916  
004917  /*
004918  ** Assign VdbeCursor index numbers to all tables in a SrcList
004919  */
004920  void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
004921    int i;
004922    SrcItem *pItem;
004923    assert( pList || pParse->db->mallocFailed );
004924    if( ALWAYS(pList) ){
004925      for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
004926        if( pItem->iCursor>=0 ) continue;
004927        pItem->iCursor = pParse->nTab++;
004928        if( pItem->fg.isSubquery ){
004929          assert( pItem->u4.pSubq!=0 );
004930          assert( pItem->u4.pSubq->pSelect!=0 );
004931          assert( pItem->u4.pSubq->pSelect->pSrc!=0 );
004932          sqlite3SrcListAssignCursors(pParse, pItem->u4.pSubq->pSelect->pSrc);
004933        }
004934      }
004935    }
004936  }
004937  
004938  /*
004939  ** Delete a Subquery object and its substructure.
004940  */
004941  void sqlite3SubqueryDelete(sqlite3 *db, Subquery *pSubq){
004942    assert( pSubq!=0 && pSubq->pSelect!=0 );
004943    sqlite3SelectDelete(db, pSubq->pSelect);
004944    sqlite3DbFree(db, pSubq);
004945  }
004946  
004947  /*
004948  ** Remove a Subquery from a SrcItem.  Return the associated Select object.
004949  ** The returned Select becomes the responsibility of the caller.
004950  */
004951  Select *sqlite3SubqueryDetach(sqlite3 *db, SrcItem *pItem){
004952    Select *pSel;
004953    assert( pItem!=0 );
004954    assert( pItem->fg.isSubquery );
004955    pSel = pItem->u4.pSubq->pSelect;
004956    sqlite3DbFree(db, pItem->u4.pSubq);
004957    pItem->u4.pSubq = 0;
004958    pItem->fg.isSubquery = 0;
004959    return pSel;
004960  }
004961  
004962  /*
004963  ** Delete an entire SrcList including all its substructure.
004964  */
004965  void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
004966    int i;
004967    SrcItem *pItem;
004968    assert( db!=0 );
004969    if( pList==0 ) return;
004970    for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
004971   
004972      /* Check invariants on SrcItem */
004973      assert( !pItem->fg.isIndexedBy || !pItem->fg.isTabFunc );
004974      assert( !pItem->fg.isCte || !pItem->fg.isIndexedBy );
004975      assert( !pItem->fg.fixedSchema || !pItem->fg.isSubquery );
004976      assert( !pItem->fg.isSubquery || (pItem->u4.pSubq!=0 && 
004977                                        pItem->u4.pSubq->pSelect!=0) );
004978  
004979      if( pItem->zName ) sqlite3DbNNFreeNN(db, pItem->zName);
004980      if( pItem->zAlias ) sqlite3DbNNFreeNN(db, pItem->zAlias);
004981      if( pItem->fg.isSubquery ){
004982        sqlite3SubqueryDelete(db, pItem->u4.pSubq);
004983      }else if( pItem->fg.fixedSchema==0 && pItem->u4.zDatabase!=0 ){
004984        sqlite3DbNNFreeNN(db, pItem->u4.zDatabase);
004985      }
004986      if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
004987      if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
004988      sqlite3DeleteTable(db, pItem->pSTab);
004989      if( pItem->fg.isUsing ){
004990        sqlite3IdListDelete(db, pItem->u3.pUsing);
004991      }else if( pItem->u3.pOn ){
004992        sqlite3ExprDelete(db, pItem->u3.pOn);
004993      }
004994    }
004995    sqlite3DbNNFreeNN(db, pList);
004996  }
004997  
004998  /*
004999  ** Attach a Subquery object to pItem->uv.pSubq.  Set the
005000  ** pSelect value but leave all the other values initialized
005001  ** to zero.
005002  **
005003  ** A copy of the Select object is made if dupSelect is true, and the
005004  ** SrcItem takes responsibility for deleting the copy.  If dupSelect is
005005  ** false, ownership of the Select passes to the SrcItem.  Either way,
005006  ** the SrcItem will take responsibility for deleting the Select.
005007  **
005008  ** When dupSelect is zero, that means the Select might get deleted right
005009  ** away if there is an OOM error.  Beware.
005010  **
005011  ** Return non-zero on success.  Return zero on an OOM error.
005012  */
005013  int sqlite3SrcItemAttachSubquery(
005014    Parse *pParse,     /* Parsing context */
005015    SrcItem *pItem,    /* Item to which the subquery is to be attached */
005016    Select *pSelect,   /* The subquery SELECT.  Must be non-NULL */
005017    int dupSelect      /* If true, attach a copy of pSelect, not pSelect itself.*/
005018  ){
005019    Subquery *p;
005020    assert( pSelect!=0 );
005021    assert( pItem->fg.isSubquery==0 );
005022    if( pItem->fg.fixedSchema ){
005023      pItem->u4.pSchema = 0;
005024      pItem->fg.fixedSchema = 0;
005025    }else if( pItem->u4.zDatabase!=0 ){
005026      sqlite3DbFree(pParse->db, pItem->u4.zDatabase);
005027      pItem->u4.zDatabase = 0;
005028    }
005029    if( dupSelect ){
005030      pSelect = sqlite3SelectDup(pParse->db, pSelect, 0);
005031      if( pSelect==0 ) return 0;
005032    }
005033    p = pItem->u4.pSubq = sqlite3DbMallocRawNN(pParse->db, sizeof(Subquery));
005034    if( p==0 ){
005035      sqlite3SelectDelete(pParse->db, pSelect);
005036      return 0;
005037    }
005038    pItem->fg.isSubquery = 1;
005039    p->pSelect = pSelect;
005040    assert( offsetof(Subquery, pSelect)==0 );
005041    memset(((char*)p)+sizeof(p->pSelect), 0, sizeof(*p)-sizeof(p->pSelect));
005042    return 1;
005043  }
005044  
005045  
005046  /*
005047  ** This routine is called by the parser to add a new term to the
005048  ** end of a growing FROM clause.  The "p" parameter is the part of
005049  ** the FROM clause that has already been constructed.  "p" is NULL
005050  ** if this is the first term of the FROM clause.  pTable and pDatabase
005051  ** are the name of the table and database named in the FROM clause term.
005052  ** pDatabase is NULL if the database name qualifier is missing - the
005053  ** usual case.  If the term has an alias, then pAlias points to the
005054  ** alias token.  If the term is a subquery, then pSubquery is the
005055  ** SELECT statement that the subquery encodes.  The pTable and
005056  ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
005057  ** parameters are the content of the ON and USING clauses.
005058  **
005059  ** Return a new SrcList which encodes is the FROM with the new
005060  ** term added.
005061  */
005062  SrcList *sqlite3SrcListAppendFromTerm(
005063    Parse *pParse,          /* Parsing context */
005064    SrcList *p,             /* The left part of the FROM clause already seen */
005065    Token *pTable,          /* Name of the table to add to the FROM clause */
005066    Token *pDatabase,       /* Name of the database containing pTable */
005067    Token *pAlias,          /* The right-hand side of the AS subexpression */
005068    Select *pSubquery,      /* A subquery used in place of a table name */
005069    OnOrUsing *pOnUsing     /* Either the ON clause or the USING clause */
005070  ){
005071    SrcItem *pItem;
005072    sqlite3 *db = pParse->db;
005073    if( !p && pOnUsing!=0 && (pOnUsing->pOn || pOnUsing->pUsing) ){
005074      sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
005075        (pOnUsing->pOn ? "ON" : "USING")
005076      );
005077      goto append_from_error;
005078    }
005079    p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
005080    if( p==0 ){
005081      goto append_from_error;
005082    }
005083    assert( p->nSrc>0 );
005084    pItem = &p->a[p->nSrc-1];
005085    assert( (pTable==0)==(pDatabase==0) );
005086    assert( pItem->zName==0 || pDatabase!=0 );
005087    if( IN_RENAME_OBJECT && pItem->zName ){
005088      Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
005089      sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
005090    }
005091    assert( pAlias!=0 );
005092    if( pAlias->n ){
005093      pItem->zAlias = sqlite3NameFromToken(db, pAlias);
005094    }
005095    assert( pSubquery==0 || pDatabase==0 );
005096    if( pSubquery ){
005097      if( sqlite3SrcItemAttachSubquery(pParse, pItem, pSubquery, 0) ){
005098        if( pSubquery->selFlags & SF_NestedFrom ){
005099          pItem->fg.isNestedFrom = 1;
005100        }
005101      }
005102    }
005103    assert( pOnUsing==0 || pOnUsing->pOn==0 || pOnUsing->pUsing==0 );
005104    assert( pItem->fg.isUsing==0 );
005105    if( pOnUsing==0 ){
005106      pItem->u3.pOn = 0;
005107    }else if( pOnUsing->pUsing ){
005108      pItem->fg.isUsing = 1;
005109      pItem->u3.pUsing = pOnUsing->pUsing;
005110    }else{
005111      pItem->u3.pOn = pOnUsing->pOn;
005112    }
005113    return p;
005114  
005115  append_from_error:
005116    assert( p==0 );
005117    sqlite3ClearOnOrUsing(db, pOnUsing);
005118    sqlite3SelectDelete(db, pSubquery);
005119    return 0;
005120  }
005121  
005122  /*
005123  ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
005124  ** element of the source-list passed as the second argument.
005125  */
005126  void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
005127    assert( pIndexedBy!=0 );
005128    if( p && pIndexedBy->n>0 ){
005129      SrcItem *pItem;
005130      assert( p->nSrc>0 );
005131      pItem = &p->a[p->nSrc-1];
005132      assert( pItem->fg.notIndexed==0 );
005133      assert( pItem->fg.isIndexedBy==0 );
005134      assert( pItem->fg.isTabFunc==0 );
005135      if( pIndexedBy->n==1 && !pIndexedBy->z ){
005136        /* A "NOT INDEXED" clause was supplied. See parse.y
005137        ** construct "indexed_opt" for details. */
005138        pItem->fg.notIndexed = 1;
005139      }else{
005140        pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
005141        pItem->fg.isIndexedBy = 1;
005142        assert( pItem->fg.isCte==0 );  /* No collision on union u2 */
005143      }
005144    }
005145  }
005146  
005147  /*
005148  ** Append the contents of SrcList p2 to SrcList p1 and return the resulting
005149  ** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2
005150  ** are deleted by this function.
005151  */
005152  SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){
005153    assert( p1 );
005154    assert( p2 || pParse->nErr );
005155    assert( p2==0 || p2->nSrc>=1 );
005156    testcase( p1->nSrc==0 );
005157    if( p2 ){
005158      int nOld = p1->nSrc;
005159      SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, nOld);
005160      if( pNew==0 ){
005161        sqlite3SrcListDelete(pParse->db, p2);
005162      }else{
005163        p1 = pNew;
005164        memcpy(&p1->a[nOld], p2->a, p2->nSrc*sizeof(SrcItem));
005165        assert( nOld==1 || (p2->a[0].fg.jointype & JT_LTORJ)==0 );
005166        assert( p1->nSrc>=1 );
005167        p1->a[0].fg.jointype |= (JT_LTORJ & p2->a[0].fg.jointype);
005168        sqlite3DbFree(pParse->db, p2);
005169      }
005170    }
005171    return p1;
005172  }
005173  
005174  /*
005175  ** Add the list of function arguments to the SrcList entry for a
005176  ** table-valued-function.
005177  */
005178  void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
005179    if( p ){
005180      SrcItem *pItem = &p->a[p->nSrc-1];
005181      assert( pItem->fg.notIndexed==0 );
005182      assert( pItem->fg.isIndexedBy==0 );
005183      assert( pItem->fg.isTabFunc==0 );
005184      pItem->u1.pFuncArg = pList;
005185      pItem->fg.isTabFunc = 1;
005186    }else{
005187      sqlite3ExprListDelete(pParse->db, pList);
005188    }
005189  }
005190  
005191  /*
005192  ** When building up a FROM clause in the parser, the join operator
005193  ** is initially attached to the left operand.  But the code generator
005194  ** expects the join operator to be on the right operand.  This routine
005195  ** Shifts all join operators from left to right for an entire FROM
005196  ** clause.
005197  **
005198  ** Example: Suppose the join is like this:
005199  **
005200  **           A natural cross join B
005201  **
005202  ** The operator is "natural cross join".  The A and B operands are stored
005203  ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
005204  ** operator with A.  This routine shifts that operator over to B.
005205  **
005206  ** Additional changes:
005207  **
005208  **   *   All tables to the left of the right-most RIGHT JOIN are tagged with
005209  **       JT_LTORJ (mnemonic: Left Table Of Right Join) so that the
005210  **       code generator can easily tell that the table is part of
005211  **       the left operand of at least one RIGHT JOIN.
005212  */
005213  void sqlite3SrcListShiftJoinType(Parse *pParse, SrcList *p){
005214    (void)pParse;
005215    if( p && p->nSrc>1 ){
005216      int i = p->nSrc-1;
005217      u8 allFlags = 0;
005218      do{
005219        allFlags |= p->a[i].fg.jointype = p->a[i-1].fg.jointype;
005220      }while( (--i)>0 );
005221      p->a[0].fg.jointype = 0;
005222  
005223      /* All terms to the left of a RIGHT JOIN should be tagged with the
005224      ** JT_LTORJ flags */
005225      if( allFlags & JT_RIGHT ){
005226        for(i=p->nSrc-1; ALWAYS(i>0) && (p->a[i].fg.jointype&JT_RIGHT)==0; i--){}
005227        i--;
005228        assert( i>=0 );
005229        do{
005230          p->a[i].fg.jointype |= JT_LTORJ;
005231        }while( (--i)>=0 );
005232      }
005233    }
005234  }
005235  
005236  /*
005237  ** Generate VDBE code for a BEGIN statement.
005238  */
005239  void sqlite3BeginTransaction(Parse *pParse, int type){
005240    sqlite3 *db;
005241    Vdbe *v;
005242    int i;
005243  
005244    assert( pParse!=0 );
005245    db = pParse->db;
005246    assert( db!=0 );
005247    if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
005248      return;
005249    }
005250    v = sqlite3GetVdbe(pParse);
005251    if( !v ) return;
005252    if( type!=TK_DEFERRED ){
005253      for(i=0; i<db->nDb; i++){
005254        int eTxnType;
005255        Btree *pBt = db->aDb[i].pBt;
005256        if( pBt && sqlite3BtreeIsReadonly(pBt) ){
005257          eTxnType = 0;  /* Read txn */
005258        }else if( type==TK_EXCLUSIVE ){
005259          eTxnType = 2;  /* Exclusive txn */
005260        }else{
005261          eTxnType = 1;  /* Write txn */
005262        }
005263        sqlite3VdbeAddOp2(v, OP_Transaction, i, eTxnType);
005264        sqlite3VdbeUsesBtree(v, i);
005265      }
005266    }
005267    sqlite3VdbeAddOp0(v, OP_AutoCommit);
005268  }
005269  
005270  /*
005271  ** Generate VDBE code for a COMMIT or ROLLBACK statement.
005272  ** Code for ROLLBACK is generated if eType==TK_ROLLBACK.  Otherwise
005273  ** code is generated for a COMMIT.
005274  */
005275  void sqlite3EndTransaction(Parse *pParse, int eType){
005276    Vdbe *v;
005277    int isRollback;
005278  
005279    assert( pParse!=0 );
005280    assert( pParse->db!=0 );
005281    assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
005282    isRollback = eType==TK_ROLLBACK;
005283    if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
005284         isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
005285      return;
005286    }
005287    v = sqlite3GetVdbe(pParse);
005288    if( v ){
005289      sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
005290    }
005291  }
005292  
005293  /*
005294  ** This function is called by the parser when it parses a command to create,
005295  ** release or rollback an SQL savepoint.
005296  */
005297  void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
005298    char *zName = sqlite3NameFromToken(pParse->db, pName);
005299    if( zName ){
005300      Vdbe *v = sqlite3GetVdbe(pParse);
005301  #ifndef SQLITE_OMIT_AUTHORIZATION
005302      static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
005303      assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
005304  #endif
005305      if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
005306        sqlite3DbFree(pParse->db, zName);
005307        return;
005308      }
005309      sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
005310    }
005311  }
005312  
005313  /*
005314  ** Make sure the TEMP database is open and available for use.  Return
005315  ** the number of errors.  Leave any error messages in the pParse structure.
005316  */
005317  int sqlite3OpenTempDatabase(Parse *pParse){
005318    sqlite3 *db = pParse->db;
005319    if( db->aDb[1].pBt==0 && !pParse->explain ){
005320      int rc;
005321      Btree *pBt;
005322      static const int flags =
005323            SQLITE_OPEN_READWRITE |
005324            SQLITE_OPEN_CREATE |
005325            SQLITE_OPEN_EXCLUSIVE |
005326            SQLITE_OPEN_DELETEONCLOSE |
005327            SQLITE_OPEN_TEMP_DB;
005328  
005329      rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
005330      if( rc!=SQLITE_OK ){
005331        sqlite3ErrorMsg(pParse, "unable to open a temporary database "
005332          "file for storing temporary tables");
005333        pParse->rc = rc;
005334        return 1;
005335      }
005336      db->aDb[1].pBt = pBt;
005337      assert( db->aDb[1].pSchema );
005338      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){
005339        sqlite3OomFault(db);
005340        return 1;
005341      }
005342    }
005343    return 0;
005344  }
005345  
005346  /*
005347  ** Record the fact that the schema cookie will need to be verified
005348  ** for database iDb.  The code to actually verify the schema cookie
005349  ** will occur at the end of the top-level VDBE and will be generated
005350  ** later, by sqlite3FinishCoding().
005351  */
005352  static void sqlite3CodeVerifySchemaAtToplevel(Parse *pToplevel, int iDb){
005353    assert( iDb>=0 && iDb<pToplevel->db->nDb );
005354    assert( pToplevel->db->aDb[iDb].pBt!=0 || iDb==1 );
005355    assert( iDb<SQLITE_MAX_DB );
005356    assert( sqlite3SchemaMutexHeld(pToplevel->db, iDb, 0) );
005357    if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
005358      DbMaskSet(pToplevel->cookieMask, iDb);
005359      if( !OMIT_TEMPDB && iDb==1 ){
005360        sqlite3OpenTempDatabase(pToplevel);
005361      }
005362    }
005363  }
005364  void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
005365    sqlite3CodeVerifySchemaAtToplevel(sqlite3ParseToplevel(pParse), iDb);
005366  }
005367  
005368  
005369  /*
005370  ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
005371  ** attached database. Otherwise, invoke it for the database named zDb only.
005372  */
005373  void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
005374    sqlite3 *db = pParse->db;
005375    int i;
005376    for(i=0; i<db->nDb; i++){
005377      Db *pDb = &db->aDb[i];
005378      if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
005379        sqlite3CodeVerifySchema(pParse, i);
005380      }
005381    }
005382  }
005383  
005384  /*
005385  ** Generate VDBE code that prepares for doing an operation that
005386  ** might change the database.
005387  **
005388  ** This routine starts a new transaction if we are not already within
005389  ** a transaction.  If we are already within a transaction, then a checkpoint
005390  ** is set if the setStatement parameter is true.  A checkpoint should
005391  ** be set for operations that might fail (due to a constraint) part of
005392  ** the way through and which will need to undo some writes without having to
005393  ** rollback the whole transaction.  For operations where all constraints
005394  ** can be checked before any changes are made to the database, it is never
005395  ** necessary to undo a write and the checkpoint should not be set.
005396  */
005397  void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
005398    Parse *pToplevel = sqlite3ParseToplevel(pParse);
005399    sqlite3CodeVerifySchemaAtToplevel(pToplevel, iDb);
005400    DbMaskSet(pToplevel->writeMask, iDb);
005401    pToplevel->isMultiWrite |= setStatement;
005402  }
005403  
005404  /*
005405  ** Indicate that the statement currently under construction might write
005406  ** more than one entry (example: deleting one row then inserting another,
005407  ** inserting multiple rows in a table, or inserting a row and index entries.)
005408  ** If an abort occurs after some of these writes have completed, then it will
005409  ** be necessary to undo the completed writes.
005410  */
005411  void sqlite3MultiWrite(Parse *pParse){
005412    Parse *pToplevel = sqlite3ParseToplevel(pParse);
005413    pToplevel->isMultiWrite = 1;
005414  }
005415  
005416  /*
005417  ** The code generator calls this routine if is discovers that it is
005418  ** possible to abort a statement prior to completion.  In order to
005419  ** perform this abort without corrupting the database, we need to make
005420  ** sure that the statement is protected by a statement transaction.
005421  **
005422  ** Technically, we only need to set the mayAbort flag if the
005423  ** isMultiWrite flag was previously set.  There is a time dependency
005424  ** such that the abort must occur after the multiwrite.  This makes
005425  ** some statements involving the REPLACE conflict resolution algorithm
005426  ** go a little faster.  But taking advantage of this time dependency
005427  ** makes it more difficult to prove that the code is correct (in
005428  ** particular, it prevents us from writing an effective
005429  ** implementation of sqlite3AssertMayAbort()) and so we have chosen
005430  ** to take the safe route and skip the optimization.
005431  */
005432  void sqlite3MayAbort(Parse *pParse){
005433    Parse *pToplevel = sqlite3ParseToplevel(pParse);
005434    pToplevel->mayAbort = 1;
005435  }
005436  
005437  /*
005438  ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
005439  ** error. The onError parameter determines which (if any) of the statement
005440  ** and/or current transaction is rolled back.
005441  */
005442  void sqlite3HaltConstraint(
005443    Parse *pParse,    /* Parsing context */
005444    int errCode,      /* extended error code */
005445    int onError,      /* Constraint type */
005446    char *p4,         /* Error message */
005447    i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
005448    u8 p5Errmsg       /* P5_ErrMsg type */
005449  ){
005450    Vdbe *v;
005451    assert( pParse->pVdbe!=0 );
005452    v = sqlite3GetVdbe(pParse);
005453    assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested );
005454    if( onError==OE_Abort ){
005455      sqlite3MayAbort(pParse);
005456    }
005457    sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
005458    sqlite3VdbeChangeP5(v, p5Errmsg);
005459  }
005460  
005461  /*
005462  ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
005463  */
005464  void sqlite3UniqueConstraint(
005465    Parse *pParse,    /* Parsing context */
005466    int onError,      /* Constraint type */
005467    Index *pIdx       /* The index that triggers the constraint */
005468  ){
005469    char *zErr;
005470    int j;
005471    StrAccum errMsg;
005472    Table *pTab = pIdx->pTable;
005473  
005474    sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
005475                        pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
005476    if( pIdx->aColExpr ){
005477      sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
005478    }else{
005479      for(j=0; j<pIdx->nKeyCol; j++){
005480        char *zCol;
005481        assert( pIdx->aiColumn[j]>=0 );
005482        zCol = pTab->aCol[pIdx->aiColumn[j]].zCnName;
005483        if( j ) sqlite3_str_append(&errMsg, ", ", 2);
005484        sqlite3_str_appendall(&errMsg, pTab->zName);
005485        sqlite3_str_append(&errMsg, ".", 1);
005486        sqlite3_str_appendall(&errMsg, zCol);
005487      }
005488    }
005489    zErr = sqlite3StrAccumFinish(&errMsg);
005490    sqlite3HaltConstraint(pParse,
005491      IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
005492                              : SQLITE_CONSTRAINT_UNIQUE,
005493      onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
005494  }
005495  
005496  
005497  /*
005498  ** Code an OP_Halt due to non-unique rowid.
005499  */
005500  void sqlite3RowidConstraint(
005501    Parse *pParse,    /* Parsing context */
005502    int onError,      /* Conflict resolution algorithm */
005503    Table *pTab       /* The table with the non-unique rowid */
005504  ){
005505    char *zMsg;
005506    int rc;
005507    if( pTab->iPKey>=0 ){
005508      zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
005509                            pTab->aCol[pTab->iPKey].zCnName);
005510      rc = SQLITE_CONSTRAINT_PRIMARYKEY;
005511    }else{
005512      zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
005513      rc = SQLITE_CONSTRAINT_ROWID;
005514    }
005515    sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
005516                          P5_ConstraintUnique);
005517  }
005518  
005519  /*
005520  ** Check to see if pIndex uses the collating sequence pColl.  Return
005521  ** true if it does and false if it does not.
005522  */
005523  #ifndef SQLITE_OMIT_REINDEX
005524  static int collationMatch(const char *zColl, Index *pIndex){
005525    int i;
005526    assert( zColl!=0 );
005527    for(i=0; i<pIndex->nColumn; i++){
005528      const char *z = pIndex->azColl[i];
005529      assert( z!=0 || pIndex->aiColumn[i]<0 );
005530      if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
005531        return 1;
005532      }
005533    }
005534    return 0;
005535  }
005536  #endif
005537  
005538  /*
005539  ** Recompute all indices of pTab that use the collating sequence pColl.
005540  ** If pColl==0 then recompute all indices of pTab.
005541  */
005542  #ifndef SQLITE_OMIT_REINDEX
005543  static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
005544    if( !IsVirtual(pTab) ){
005545      Index *pIndex;              /* An index associated with pTab */
005546  
005547      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
005548        if( zColl==0 || collationMatch(zColl, pIndex) ){
005549          int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
005550          sqlite3BeginWriteOperation(pParse, 0, iDb);
005551          sqlite3RefillIndex(pParse, pIndex, -1);
005552        }
005553      }
005554    }
005555  }
005556  #endif
005557  
005558  /*
005559  ** Recompute all indices of all tables in all databases where the
005560  ** indices use the collating sequence pColl.  If pColl==0 then recompute
005561  ** all indices everywhere.
005562  */
005563  #ifndef SQLITE_OMIT_REINDEX
005564  static void reindexDatabases(Parse *pParse, char const *zColl){
005565    Db *pDb;                    /* A single database */
005566    int iDb;                    /* The database index number */
005567    sqlite3 *db = pParse->db;   /* The database connection */
005568    HashElem *k;                /* For looping over tables in pDb */
005569    Table *pTab;                /* A table in the database */
005570  
005571    assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
005572    for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
005573      assert( pDb!=0 );
005574      for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
005575        pTab = (Table*)sqliteHashData(k);
005576        reindexTable(pParse, pTab, zColl);
005577      }
005578    }
005579  }
005580  #endif
005581  
005582  /*
005583  ** Generate code for the REINDEX command.
005584  **
005585  **        REINDEX                            -- 1
005586  **        REINDEX  <collation>               -- 2
005587  **        REINDEX  ?<database>.?<tablename>  -- 3
005588  **        REINDEX  ?<database>.?<indexname>  -- 4
005589  **
005590  ** Form 1 causes all indices in all attached databases to be rebuilt.
005591  ** Form 2 rebuilds all indices in all databases that use the named
005592  ** collating function.  Forms 3 and 4 rebuild the named index or all
005593  ** indices associated with the named table.
005594  */
005595  #ifndef SQLITE_OMIT_REINDEX
005596  void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
005597    CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
005598    char *z;                    /* Name of a table or index */
005599    const char *zDb;            /* Name of the database */
005600    Table *pTab;                /* A table in the database */
005601    Index *pIndex;              /* An index associated with pTab */
005602    int iDb;                    /* The database index number */
005603    sqlite3 *db = pParse->db;   /* The database connection */
005604    Token *pObjName;            /* Name of the table or index to be reindexed */
005605  
005606    /* Read the database schema. If an error occurs, leave an error message
005607    ** and code in pParse and return NULL. */
005608    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
005609      return;
005610    }
005611  
005612    if( pName1==0 ){
005613      reindexDatabases(pParse, 0);
005614      return;
005615    }else if( NEVER(pName2==0) || pName2->z==0 ){
005616      char *zColl;
005617      assert( pName1->z );
005618      zColl = sqlite3NameFromToken(pParse->db, pName1);
005619      if( !zColl ) return;
005620      pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
005621      if( pColl ){
005622        reindexDatabases(pParse, zColl);
005623        sqlite3DbFree(db, zColl);
005624        return;
005625      }
005626      sqlite3DbFree(db, zColl);
005627    }
005628    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
005629    if( iDb<0 ) return;
005630    z = sqlite3NameFromToken(db, pObjName);
005631    if( z==0 ) return;
005632    zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
005633    pTab = sqlite3FindTable(db, z, zDb);
005634    if( pTab ){
005635      reindexTable(pParse, pTab, 0);
005636      sqlite3DbFree(db, z);
005637      return;
005638    }
005639    pIndex = sqlite3FindIndex(db, z, zDb);
005640    sqlite3DbFree(db, z);
005641    if( pIndex ){
005642      iDb = sqlite3SchemaToIndex(db, pIndex->pTable->pSchema);
005643      sqlite3BeginWriteOperation(pParse, 0, iDb);
005644      sqlite3RefillIndex(pParse, pIndex, -1);
005645      return;
005646    }
005647    sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
005648  }
005649  #endif
005650  
005651  /*
005652  ** Return a KeyInfo structure that is appropriate for the given Index.
005653  **
005654  ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
005655  ** when it has finished using it.
005656  */
005657  KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
005658    int i;
005659    int nCol = pIdx->nColumn;
005660    int nKey = pIdx->nKeyCol;
005661    KeyInfo *pKey;
005662    if( pParse->nErr ) return 0;
005663    if( pIdx->uniqNotNull ){
005664      pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
005665    }else{
005666      pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
005667    }
005668    if( pKey ){
005669      assert( sqlite3KeyInfoIsWriteable(pKey) );
005670      for(i=0; i<nCol; i++){
005671        const char *zColl = pIdx->azColl[i];
005672        pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
005673                          sqlite3LocateCollSeq(pParse, zColl);
005674        pKey->aSortFlags[i] = pIdx->aSortOrder[i];
005675        assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) );
005676      }
005677      if( pParse->nErr ){
005678        assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
005679        if( pIdx->bNoQuery==0 
005680         && sqlite3HashFind(&pIdx->pSchema->idxHash, pIdx->zName)
005681        ){
005682          /* Deactivate the index because it contains an unknown collating
005683          ** sequence.  The only way to reactive the index is to reload the
005684          ** schema.  Adding the missing collating sequence later does not
005685          ** reactive the index.  The application had the chance to register
005686          ** the missing index using the collation-needed callback.  For
005687          ** simplicity, SQLite will not give the application a second chance.
005688          **
005689          ** Except, do not do this if the index is not in the schema hash
005690          ** table. In this case the index is currently being constructed
005691          ** by a CREATE INDEX statement, and retrying will not help.  */
005692          pIdx->bNoQuery = 1;
005693          pParse->rc = SQLITE_ERROR_RETRY;
005694        }
005695        sqlite3KeyInfoUnref(pKey);
005696        pKey = 0;
005697      }
005698    }
005699    return pKey;
005700  }
005701  
005702  #ifndef SQLITE_OMIT_CTE
005703  /*
005704  ** Create a new CTE object
005705  */
005706  Cte *sqlite3CteNew(
005707    Parse *pParse,          /* Parsing context */
005708    Token *pName,           /* Name of the common-table */
005709    ExprList *pArglist,     /* Optional column name list for the table */
005710    Select *pQuery,         /* Query used to initialize the table */
005711    u8 eM10d                /* The MATERIALIZED flag */
005712  ){
005713    Cte *pNew;
005714    sqlite3 *db = pParse->db;
005715  
005716    pNew = sqlite3DbMallocZero(db, sizeof(*pNew));
005717    assert( pNew!=0 || db->mallocFailed );
005718  
005719    if( db->mallocFailed ){
005720      sqlite3ExprListDelete(db, pArglist);
005721      sqlite3SelectDelete(db, pQuery);
005722    }else{
005723      pNew->pSelect = pQuery;
005724      pNew->pCols = pArglist;
005725      pNew->zName = sqlite3NameFromToken(pParse->db, pName);
005726      pNew->eM10d = eM10d;
005727    }
005728    return pNew;
005729  }
005730  
005731  /*
005732  ** Clear information from a Cte object, but do not deallocate storage
005733  ** for the object itself.
005734  */
005735  static void cteClear(sqlite3 *db, Cte *pCte){
005736    assert( pCte!=0 );
005737    sqlite3ExprListDelete(db, pCte->pCols);
005738    sqlite3SelectDelete(db, pCte->pSelect);
005739    sqlite3DbFree(db, pCte->zName);
005740  }
005741  
005742  /*
005743  ** Free the contents of the CTE object passed as the second argument.
005744  */
005745  void sqlite3CteDelete(sqlite3 *db, Cte *pCte){
005746    assert( pCte!=0 );
005747    cteClear(db, pCte);
005748    sqlite3DbFree(db, pCte);
005749  }
005750  
005751  /*
005752  ** This routine is invoked once per CTE by the parser while parsing a
005753  ** WITH clause.  The CTE described by the third argument is added to
005754  ** the WITH clause of the second argument.  If the second argument is
005755  ** NULL, then a new WITH argument is created.
005756  */
005757  With *sqlite3WithAdd(
005758    Parse *pParse,          /* Parsing context */
005759    With *pWith,            /* Existing WITH clause, or NULL */
005760    Cte *pCte               /* CTE to add to the WITH clause */
005761  ){
005762    sqlite3 *db = pParse->db;
005763    With *pNew;
005764    char *zName;
005765  
005766    if( pCte==0 ){
005767      return pWith;
005768    }
005769  
005770    /* Check that the CTE name is unique within this WITH clause. If
005771    ** not, store an error in the Parse structure. */
005772    zName = pCte->zName;
005773    if( zName && pWith ){
005774      int i;
005775      for(i=0; i<pWith->nCte; i++){
005776        if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
005777          sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
005778        }
005779      }
005780    }
005781  
005782    if( pWith ){
005783      pNew = sqlite3DbRealloc(db, pWith, SZ_WITH(pWith->nCte+1));
005784    }else{
005785      pNew = sqlite3DbMallocZero(db, SZ_WITH(1));
005786    }
005787    assert( (pNew!=0 && zName!=0) || db->mallocFailed );
005788  
005789    if( db->mallocFailed ){
005790      sqlite3CteDelete(db, pCte);
005791      pNew = pWith;
005792    }else{
005793      pNew->a[pNew->nCte++] = *pCte;
005794      sqlite3DbFree(db, pCte);
005795    }
005796  
005797    return pNew;
005798  }
005799  
005800  /*
005801  ** Free the contents of the With object passed as the second argument.
005802  */
005803  void sqlite3WithDelete(sqlite3 *db, With *pWith){
005804    if( pWith ){
005805      int i;
005806      for(i=0; i<pWith->nCte; i++){
005807        cteClear(db, &pWith->a[i]);
005808      }
005809      sqlite3DbFree(db, pWith);
005810    }
005811  }
005812  void sqlite3WithDeleteGeneric(sqlite3 *db, void *pWith){
005813    sqlite3WithDelete(db, (With*)pWith);
005814  }
005815  #endif /* !defined(SQLITE_OMIT_CTE) */