SQLite

Artifact Content
Login

Artifact 67bb05b1077e0cdaccb2e36bfcbe7a5df9ed31e8:


     1  /*
     2  ** 2001 September 15
     3  **
     4  ** The author disclaims copyright to this source code.  In place of
     5  ** a legal notice, here is a blessing:
     6  **
     7  **    May you do good and not evil.
     8  **    May you find forgiveness for yourself and forgive others.
     9  **    May you share freely, never taking more than you give.
    10  **
    11  *************************************************************************
    12  ** This file contains C code routines that are called by the SQLite parser
    13  ** when syntax rules are reduced.  The routines in this file handle the
    14  ** following kinds of SQL syntax:
    15  **
    16  **     CREATE TABLE
    17  **     DROP TABLE
    18  **     CREATE INDEX
    19  **     DROP INDEX
    20  **     creating ID lists
    21  **     BEGIN TRANSACTION
    22  **     COMMIT
    23  **     ROLLBACK
    24  */
    25  #include "sqliteInt.h"
    26  
    27  /*
    28  ** This routine is called when a new SQL statement is beginning to
    29  ** be parsed.  Initialize the pParse structure as needed.
    30  */
    31  void sqlite3BeginParse(Parse *pParse, int explainFlag){
    32    pParse->explain = (u8)explainFlag;
    33    pParse->nVar = 0;
    34  }
    35  
    36  #ifndef SQLITE_OMIT_SHARED_CACHE
    37  /*
    38  ** The TableLock structure is only used by the sqlite3TableLock() and
    39  ** codeTableLocks() functions.
    40  */
    41  struct TableLock {
    42    int iDb;             /* The database containing the table to be locked */
    43    int iTab;            /* The root page of the table to be locked */
    44    u8 isWriteLock;      /* True for write lock.  False for a read lock */
    45    const char *zName;   /* Name of the table */
    46  };
    47  
    48  /*
    49  ** Record the fact that we want to lock a table at run-time.  
    50  **
    51  ** The table to be locked has root page iTab and is found in database iDb.
    52  ** A read or a write lock can be taken depending on isWritelock.
    53  **
    54  ** This routine just records the fact that the lock is desired.  The
    55  ** code to make the lock occur is generated by a later call to
    56  ** codeTableLocks() which occurs during sqlite3FinishCoding().
    57  */
    58  void sqlite3TableLock(
    59    Parse *pParse,     /* Parsing context */
    60    int iDb,           /* Index of the database containing the table to lock */
    61    int iTab,          /* Root page number of the table to be locked */
    62    u8 isWriteLock,    /* True for a write lock */
    63    const char *zName  /* Name of the table to be locked */
    64  ){
    65    Parse *pToplevel = sqlite3ParseToplevel(pParse);
    66    int i;
    67    int nBytes;
    68    TableLock *p;
    69    assert( iDb>=0 );
    70  
    71    for(i=0; i<pToplevel->nTableLock; i++){
    72      p = &pToplevel->aTableLock[i];
    73      if( p->iDb==iDb && p->iTab==iTab ){
    74        p->isWriteLock = (p->isWriteLock || isWriteLock);
    75        return;
    76      }
    77    }
    78  
    79    nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
    80    pToplevel->aTableLock =
    81        sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
    82    if( pToplevel->aTableLock ){
    83      p = &pToplevel->aTableLock[pToplevel->nTableLock++];
    84      p->iDb = iDb;
    85      p->iTab = iTab;
    86      p->isWriteLock = isWriteLock;
    87      p->zName = zName;
    88    }else{
    89      pToplevel->nTableLock = 0;
    90      pToplevel->db->mallocFailed = 1;
    91    }
    92  }
    93  
    94  /*
    95  ** Code an OP_TableLock instruction for each table locked by the
    96  ** statement (configured by calls to sqlite3TableLock()).
    97  */
    98  static void codeTableLocks(Parse *pParse){
    99    int i;
   100    Vdbe *pVdbe; 
   101  
   102    pVdbe = sqlite3GetVdbe(pParse);
   103    assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
   104  
   105    for(i=0; i<pParse->nTableLock; i++){
   106      TableLock *p = &pParse->aTableLock[i];
   107      int p1 = p->iDb;
   108      sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
   109                        p->zName, P4_STATIC);
   110    }
   111  }
   112  #else
   113    #define codeTableLocks(x)
   114  #endif
   115  
   116  /*
   117  ** Return TRUE if the given yDbMask object is empty - if it contains no
   118  ** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
   119  ** macros when SQLITE_MAX_ATTACHED is greater than 30.
   120  */
   121  #if SQLITE_MAX_ATTACHED>30
   122  int sqlite3DbMaskAllZero(yDbMask m){
   123    int i;
   124    for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
   125    return 1;
   126  }
   127  #endif
   128  
   129  /*
   130  ** This routine is called after a single SQL statement has been
   131  ** parsed and a VDBE program to execute that statement has been
   132  ** prepared.  This routine puts the finishing touches on the
   133  ** VDBE program and resets the pParse structure for the next
   134  ** parse.
   135  **
   136  ** Note that if an error occurred, it might be the case that
   137  ** no VDBE code was generated.
   138  */
   139  void sqlite3FinishCoding(Parse *pParse){
   140    sqlite3 *db;
   141    Vdbe *v;
   142  
   143    assert( pParse->pToplevel==0 );
   144    db = pParse->db;
   145    if( db->mallocFailed ) return;
   146    if( pParse->nested ) return;
   147    if( pParse->nErr ) return;
   148  
   149    /* Begin by generating some termination code at the end of the
   150    ** vdbe program
   151    */
   152    v = sqlite3GetVdbe(pParse);
   153    assert( !pParse->isMultiWrite 
   154         || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
   155    if( v ){
   156      while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
   157      sqlite3VdbeAddOp0(v, OP_Halt);
   158  
   159  #if SQLITE_USER_AUTHENTICATION
   160      if( pParse->nTableLock>0 && db->init.busy==0 ){
   161        sqlite3UserAuthInit(db);
   162        if( db->auth.authLevel<UAUTH_User ){
   163          pParse->rc = SQLITE_AUTH_USER;
   164          sqlite3ErrorMsg(pParse, "user not authenticated");
   165          return;
   166        }
   167      }
   168  #endif
   169  
   170      /* The cookie mask contains one bit for each database file open.
   171      ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
   172      ** set for each database that is used.  Generate code to start a
   173      ** transaction on each used database and to verify the schema cookie
   174      ** on each used database.
   175      */
   176      if( db->mallocFailed==0 
   177       && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
   178      ){
   179        int iDb, i;
   180        assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
   181        sqlite3VdbeJumpHere(v, 0);
   182        for(iDb=0; iDb<db->nDb; iDb++){
   183          if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
   184          sqlite3VdbeUsesBtree(v, iDb);
   185          sqlite3VdbeAddOp4Int(v,
   186            OP_Transaction,                    /* Opcode */
   187            iDb,                               /* P1 */
   188            DbMaskTest(pParse->writeMask,iDb), /* P2 */
   189            pParse->cookieValue[iDb],          /* P3 */
   190            db->aDb[iDb].pSchema->iGeneration  /* P4 */
   191          );
   192          if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
   193        }
   194  #ifndef SQLITE_OMIT_VIRTUALTABLE
   195        for(i=0; i<pParse->nVtabLock; i++){
   196          char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
   197          sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
   198        }
   199        pParse->nVtabLock = 0;
   200  #endif
   201  
   202        /* Once all the cookies have been verified and transactions opened, 
   203        ** obtain the required table-locks. This is a no-op unless the 
   204        ** shared-cache feature is enabled.
   205        */
   206        codeTableLocks(pParse);
   207  
   208        /* Initialize any AUTOINCREMENT data structures required.
   209        */
   210        sqlite3AutoincrementBegin(pParse);
   211  
   212        /* Code constant expressions that where factored out of inner loops */
   213        if( pParse->pConstExpr ){
   214          ExprList *pEL = pParse->pConstExpr;
   215          pParse->okConstFactor = 0;
   216          for(i=0; i<pEL->nExpr; i++){
   217            sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
   218          }
   219        }
   220  
   221        /* Finally, jump back to the beginning of the executable code. */
   222        sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
   223      }
   224    }
   225  
   226  
   227    /* Get the VDBE program ready for execution
   228    */
   229    if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
   230      assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
   231      /* A minimum of one cursor is required if autoincrement is used
   232      *  See ticket [a696379c1f08866] */
   233      if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
   234      sqlite3VdbeMakeReady(v, pParse);
   235      pParse->rc = SQLITE_DONE;
   236      pParse->colNamesSet = 0;
   237    }else{
   238      pParse->rc = SQLITE_ERROR;
   239    }
   240    pParse->nTab = 0;
   241    pParse->nMem = 0;
   242    pParse->nSet = 0;
   243    pParse->nVar = 0;
   244    DbMaskZero(pParse->cookieMask);
   245  }
   246  
   247  /*
   248  ** Run the parser and code generator recursively in order to generate
   249  ** code for the SQL statement given onto the end of the pParse context
   250  ** currently under construction.  When the parser is run recursively
   251  ** this way, the final OP_Halt is not appended and other initialization
   252  ** and finalization steps are omitted because those are handling by the
   253  ** outermost parser.
   254  **
   255  ** Not everything is nestable.  This facility is designed to permit
   256  ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
   257  ** care if you decide to try to use this routine for some other purposes.
   258  */
   259  void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
   260    va_list ap;
   261    char *zSql;
   262    char *zErrMsg = 0;
   263    sqlite3 *db = pParse->db;
   264  # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
   265    char saveBuf[SAVE_SZ];
   266  
   267    if( pParse->nErr ) return;
   268    assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
   269    va_start(ap, zFormat);
   270    zSql = sqlite3VMPrintf(db, zFormat, ap);
   271    va_end(ap);
   272    if( zSql==0 ){
   273      return;   /* A malloc must have failed */
   274    }
   275    pParse->nested++;
   276    memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
   277    memset(&pParse->nVar, 0, SAVE_SZ);
   278    sqlite3RunParser(pParse, zSql, &zErrMsg);
   279    sqlite3DbFree(db, zErrMsg);
   280    sqlite3DbFree(db, zSql);
   281    memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
   282    pParse->nested--;
   283  }
   284  
   285  #if SQLITE_USER_AUTHENTICATION
   286  /*
   287  ** Return TRUE if zTable is the name of the system table that stores the
   288  ** list of users and their access credentials.
   289  */
   290  int sqlite3UserAuthTable(const char *zTable){
   291    return sqlite3_stricmp(zTable, "sqlite_user")==0;
   292  }
   293  #endif
   294  
   295  /*
   296  ** Locate the in-memory structure that describes a particular database
   297  ** table given the name of that table and (optionally) the name of the
   298  ** database containing the table.  Return NULL if not found.
   299  **
   300  ** If zDatabase is 0, all databases are searched for the table and the
   301  ** first matching table is returned.  (No checking for duplicate table
   302  ** names is done.)  The search order is TEMP first, then MAIN, then any
   303  ** auxiliary databases added using the ATTACH command.
   304  **
   305  ** See also sqlite3LocateTable().
   306  */
   307  Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
   308    Table *p = 0;
   309    int i;
   310  
   311  #ifdef SQLITE_ENABLE_API_ARMOR
   312    if( !sqlite3SafetyCheckOk(db) || zName==0 ) return 0;
   313  #endif
   314  
   315    /* All mutexes are required for schema access.  Make sure we hold them. */
   316    assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   317  #if SQLITE_USER_AUTHENTICATION
   318    /* Only the admin user is allowed to know that the sqlite_user table
   319    ** exists */
   320    if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
   321      return 0;
   322    }
   323  #endif
   324    for(i=OMIT_TEMPDB; i<db->nDb; i++){
   325      int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
   326      if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
   327      assert( sqlite3SchemaMutexHeld(db, j, 0) );
   328      p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
   329      if( p ) break;
   330    }
   331    return p;
   332  }
   333  
   334  /*
   335  ** Locate the in-memory structure that describes a particular database
   336  ** table given the name of that table and (optionally) the name of the
   337  ** database containing the table.  Return NULL if not found.  Also leave an
   338  ** error message in pParse->zErrMsg.
   339  **
   340  ** The difference between this routine and sqlite3FindTable() is that this
   341  ** routine leaves an error message in pParse->zErrMsg where
   342  ** sqlite3FindTable() does not.
   343  */
   344  Table *sqlite3LocateTable(
   345    Parse *pParse,         /* context in which to report errors */
   346    int isView,            /* True if looking for a VIEW rather than a TABLE */
   347    const char *zName,     /* Name of the table we are looking for */
   348    const char *zDbase     /* Name of the database.  Might be NULL */
   349  ){
   350    Table *p;
   351  
   352    /* Read the database schema. If an error occurs, leave an error message
   353    ** and code in pParse and return NULL. */
   354    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   355      return 0;
   356    }
   357  
   358    p = sqlite3FindTable(pParse->db, zName, zDbase);
   359    if( p==0 ){
   360      const char *zMsg = isView ? "no such view" : "no such table";
   361      if( zDbase ){
   362        sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
   363      }else{
   364        sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
   365      }
   366      pParse->checkSchema = 1;
   367    }
   368  #if SQLITE_USER_AUTHENICATION
   369    else if( pParse->db->auth.authLevel<UAUTH_User ){
   370      sqlite3ErrorMsg(pParse, "user not authenticated");
   371      p = 0;
   372    }
   373  #endif
   374    return p;
   375  }
   376  
   377  /*
   378  ** Locate the table identified by *p.
   379  **
   380  ** This is a wrapper around sqlite3LocateTable(). The difference between
   381  ** sqlite3LocateTable() and this function is that this function restricts
   382  ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
   383  ** non-NULL if it is part of a view or trigger program definition. See
   384  ** sqlite3FixSrcList() for details.
   385  */
   386  Table *sqlite3LocateTableItem(
   387    Parse *pParse, 
   388    int isView, 
   389    struct SrcList_item *p
   390  ){
   391    const char *zDb;
   392    assert( p->pSchema==0 || p->zDatabase==0 );
   393    if( p->pSchema ){
   394      int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
   395      zDb = pParse->db->aDb[iDb].zName;
   396    }else{
   397      zDb = p->zDatabase;
   398    }
   399    return sqlite3LocateTable(pParse, isView, p->zName, zDb);
   400  }
   401  
   402  /*
   403  ** Locate the in-memory structure that describes 
   404  ** a particular index given the name of that index
   405  ** and the name of the database that contains the index.
   406  ** Return NULL if not found.
   407  **
   408  ** If zDatabase is 0, all databases are searched for the
   409  ** table and the first matching index is returned.  (No checking
   410  ** for duplicate index names is done.)  The search order is
   411  ** TEMP first, then MAIN, then any auxiliary databases added
   412  ** using the ATTACH command.
   413  */
   414  Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
   415    Index *p = 0;
   416    int i;
   417    /* All mutexes are required for schema access.  Make sure we hold them. */
   418    assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   419    for(i=OMIT_TEMPDB; i<db->nDb; i++){
   420      int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
   421      Schema *pSchema = db->aDb[j].pSchema;
   422      assert( pSchema );
   423      if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
   424      assert( sqlite3SchemaMutexHeld(db, j, 0) );
   425      p = sqlite3HashFind(&pSchema->idxHash, zName);
   426      if( p ) break;
   427    }
   428    return p;
   429  }
   430  
   431  /*
   432  ** Reclaim the memory used by an index
   433  */
   434  static void freeIndex(sqlite3 *db, Index *p){
   435  #ifndef SQLITE_OMIT_ANALYZE
   436    sqlite3DeleteIndexSamples(db, p);
   437  #endif
   438    if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo);
   439    sqlite3ExprDelete(db, p->pPartIdxWhere);
   440    sqlite3DbFree(db, p->zColAff);
   441    if( p->isResized ) sqlite3DbFree(db, p->azColl);
   442  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   443    sqlite3_free(p->aiRowEst);
   444  #endif
   445    sqlite3DbFree(db, p);
   446  }
   447  
   448  /*
   449  ** For the index called zIdxName which is found in the database iDb,
   450  ** unlike that index from its Table then remove the index from
   451  ** the index hash table and free all memory structures associated
   452  ** with the index.
   453  */
   454  void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
   455    Index *pIndex;
   456    Hash *pHash;
   457  
   458    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   459    pHash = &db->aDb[iDb].pSchema->idxHash;
   460    pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
   461    if( ALWAYS(pIndex) ){
   462      if( pIndex->pTable->pIndex==pIndex ){
   463        pIndex->pTable->pIndex = pIndex->pNext;
   464      }else{
   465        Index *p;
   466        /* Justification of ALWAYS();  The index must be on the list of
   467        ** indices. */
   468        p = pIndex->pTable->pIndex;
   469        while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
   470        if( ALWAYS(p && p->pNext==pIndex) ){
   471          p->pNext = pIndex->pNext;
   472        }
   473      }
   474      freeIndex(db, pIndex);
   475    }
   476    db->flags |= SQLITE_InternChanges;
   477  }
   478  
   479  /*
   480  ** Look through the list of open database files in db->aDb[] and if
   481  ** any have been closed, remove them from the list.  Reallocate the
   482  ** db->aDb[] structure to a smaller size, if possible.
   483  **
   484  ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
   485  ** are never candidates for being collapsed.
   486  */
   487  void sqlite3CollapseDatabaseArray(sqlite3 *db){
   488    int i, j;
   489    for(i=j=2; i<db->nDb; i++){
   490      struct Db *pDb = &db->aDb[i];
   491      if( pDb->pBt==0 ){
   492        sqlite3DbFree(db, pDb->zName);
   493        pDb->zName = 0;
   494        continue;
   495      }
   496      if( j<i ){
   497        db->aDb[j] = db->aDb[i];
   498      }
   499      j++;
   500    }
   501    memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
   502    db->nDb = j;
   503    if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
   504      memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
   505      sqlite3DbFree(db, db->aDb);
   506      db->aDb = db->aDbStatic;
   507    }
   508  }
   509  
   510  /*
   511  ** Reset the schema for the database at index iDb.  Also reset the
   512  ** TEMP schema.
   513  */
   514  void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
   515    Db *pDb;
   516    assert( iDb<db->nDb );
   517  
   518    /* Case 1:  Reset the single schema identified by iDb */
   519    pDb = &db->aDb[iDb];
   520    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   521    assert( pDb->pSchema!=0 );
   522    sqlite3SchemaClear(pDb->pSchema);
   523  
   524    /* If any database other than TEMP is reset, then also reset TEMP
   525    ** since TEMP might be holding triggers that reference tables in the
   526    ** other database.
   527    */
   528    if( iDb!=1 ){
   529      pDb = &db->aDb[1];
   530      assert( pDb->pSchema!=0 );
   531      sqlite3SchemaClear(pDb->pSchema);
   532    }
   533    return;
   534  }
   535  
   536  /*
   537  ** Erase all schema information from all attached databases (including
   538  ** "main" and "temp") for a single database connection.
   539  */
   540  void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
   541    int i;
   542    sqlite3BtreeEnterAll(db);
   543    for(i=0; i<db->nDb; i++){
   544      Db *pDb = &db->aDb[i];
   545      if( pDb->pSchema ){
   546        sqlite3SchemaClear(pDb->pSchema);
   547      }
   548    }
   549    db->flags &= ~SQLITE_InternChanges;
   550    sqlite3VtabUnlockList(db);
   551    sqlite3BtreeLeaveAll(db);
   552    sqlite3CollapseDatabaseArray(db);
   553  }
   554  
   555  /*
   556  ** This routine is called when a commit occurs.
   557  */
   558  void sqlite3CommitInternalChanges(sqlite3 *db){
   559    db->flags &= ~SQLITE_InternChanges;
   560  }
   561  
   562  /*
   563  ** Delete memory allocated for the column names of a table or view (the
   564  ** Table.aCol[] array).
   565  */
   566  static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
   567    int i;
   568    Column *pCol;
   569    assert( pTable!=0 );
   570    if( (pCol = pTable->aCol)!=0 ){
   571      for(i=0; i<pTable->nCol; i++, pCol++){
   572        sqlite3DbFree(db, pCol->zName);
   573        sqlite3ExprDelete(db, pCol->pDflt);
   574        sqlite3DbFree(db, pCol->zDflt);
   575        sqlite3DbFree(db, pCol->zType);
   576        sqlite3DbFree(db, pCol->zColl);
   577      }
   578      sqlite3DbFree(db, pTable->aCol);
   579    }
   580  }
   581  
   582  /*
   583  ** Remove the memory data structures associated with the given
   584  ** Table.  No changes are made to disk by this routine.
   585  **
   586  ** This routine just deletes the data structure.  It does not unlink
   587  ** the table data structure from the hash table.  But it does destroy
   588  ** memory structures of the indices and foreign keys associated with 
   589  ** the table.
   590  **
   591  ** The db parameter is optional.  It is needed if the Table object 
   592  ** contains lookaside memory.  (Table objects in the schema do not use
   593  ** lookaside memory, but some ephemeral Table objects do.)  Or the
   594  ** db parameter can be used with db->pnBytesFreed to measure the memory
   595  ** used by the Table object.
   596  */
   597  void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
   598    Index *pIndex, *pNext;
   599    TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
   600  
   601    assert( !pTable || pTable->nRef>0 );
   602  
   603    /* Do not delete the table until the reference count reaches zero. */
   604    if( !pTable ) return;
   605    if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
   606  
   607    /* Record the number of outstanding lookaside allocations in schema Tables
   608    ** prior to doing any free() operations.  Since schema Tables do not use
   609    ** lookaside, this number should not change. */
   610    TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
   611                           db->lookaside.nOut : 0 );
   612  
   613    /* Delete all indices associated with this table. */
   614    for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
   615      pNext = pIndex->pNext;
   616      assert( pIndex->pSchema==pTable->pSchema );
   617      if( !db || db->pnBytesFreed==0 ){
   618        char *zName = pIndex->zName; 
   619        TESTONLY ( Index *pOld = ) sqlite3HashInsert(
   620           &pIndex->pSchema->idxHash, zName, 0
   621        );
   622        assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
   623        assert( pOld==pIndex || pOld==0 );
   624      }
   625      freeIndex(db, pIndex);
   626    }
   627  
   628    /* Delete any foreign keys attached to this table. */
   629    sqlite3FkDelete(db, pTable);
   630  
   631    /* Delete the Table structure itself.
   632    */
   633    sqliteDeleteColumnNames(db, pTable);
   634    sqlite3DbFree(db, pTable->zName);
   635    sqlite3DbFree(db, pTable->zColAff);
   636    sqlite3SelectDelete(db, pTable->pSelect);
   637  #ifndef SQLITE_OMIT_CHECK
   638    sqlite3ExprListDelete(db, pTable->pCheck);
   639  #endif
   640  #ifndef SQLITE_OMIT_VIRTUALTABLE
   641    sqlite3VtabClear(db, pTable);
   642  #endif
   643    sqlite3DbFree(db, pTable);
   644  
   645    /* Verify that no lookaside memory was used by schema tables */
   646    assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
   647  }
   648  
   649  /*
   650  ** Unlink the given table from the hash tables and the delete the
   651  ** table structure with all its indices and foreign keys.
   652  */
   653  void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
   654    Table *p;
   655    Db *pDb;
   656  
   657    assert( db!=0 );
   658    assert( iDb>=0 && iDb<db->nDb );
   659    assert( zTabName );
   660    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   661    testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
   662    pDb = &db->aDb[iDb];
   663    p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
   664    sqlite3DeleteTable(db, p);
   665    db->flags |= SQLITE_InternChanges;
   666  }
   667  
   668  /*
   669  ** Given a token, return a string that consists of the text of that
   670  ** token.  Space to hold the returned string
   671  ** is obtained from sqliteMalloc() and must be freed by the calling
   672  ** function.
   673  **
   674  ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
   675  ** surround the body of the token are removed.
   676  **
   677  ** Tokens are often just pointers into the original SQL text and so
   678  ** are not \000 terminated and are not persistent.  The returned string
   679  ** is \000 terminated and is persistent.
   680  */
   681  char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
   682    char *zName;
   683    if( pName ){
   684      zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
   685      sqlite3Dequote(zName);
   686    }else{
   687      zName = 0;
   688    }
   689    return zName;
   690  }
   691  
   692  /*
   693  ** Open the sqlite_master table stored in database number iDb for
   694  ** writing. The table is opened using cursor 0.
   695  */
   696  void sqlite3OpenMasterTable(Parse *p, int iDb){
   697    Vdbe *v = sqlite3GetVdbe(p);
   698    sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
   699    sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
   700    if( p->nTab==0 ){
   701      p->nTab = 1;
   702    }
   703  }
   704  
   705  /*
   706  ** Parameter zName points to a nul-terminated buffer containing the name
   707  ** of a database ("main", "temp" or the name of an attached db). This
   708  ** function returns the index of the named database in db->aDb[], or
   709  ** -1 if the named db cannot be found.
   710  */
   711  int sqlite3FindDbName(sqlite3 *db, const char *zName){
   712    int i = -1;         /* Database number */
   713    if( zName ){
   714      Db *pDb;
   715      int n = sqlite3Strlen30(zName);
   716      for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
   717        if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
   718            0==sqlite3StrICmp(pDb->zName, zName) ){
   719          break;
   720        }
   721      }
   722    }
   723    return i;
   724  }
   725  
   726  /*
   727  ** The token *pName contains the name of a database (either "main" or
   728  ** "temp" or the name of an attached db). This routine returns the
   729  ** index of the named database in db->aDb[], or -1 if the named db 
   730  ** does not exist.
   731  */
   732  int sqlite3FindDb(sqlite3 *db, Token *pName){
   733    int i;                               /* Database number */
   734    char *zName;                         /* Name we are searching for */
   735    zName = sqlite3NameFromToken(db, pName);
   736    i = sqlite3FindDbName(db, zName);
   737    sqlite3DbFree(db, zName);
   738    return i;
   739  }
   740  
   741  /* The table or view or trigger name is passed to this routine via tokens
   742  ** pName1 and pName2. If the table name was fully qualified, for example:
   743  **
   744  ** CREATE TABLE xxx.yyy (...);
   745  ** 
   746  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
   747  ** the table name is not fully qualified, i.e.:
   748  **
   749  ** CREATE TABLE yyy(...);
   750  **
   751  ** Then pName1 is set to "yyy" and pName2 is "".
   752  **
   753  ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
   754  ** pName2) that stores the unqualified table name.  The index of the
   755  ** database "xxx" is returned.
   756  */
   757  int sqlite3TwoPartName(
   758    Parse *pParse,      /* Parsing and code generating context */
   759    Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
   760    Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
   761    Token **pUnqual     /* Write the unqualified object name here */
   762  ){
   763    int iDb;                    /* Database holding the object */
   764    sqlite3 *db = pParse->db;
   765  
   766    if( ALWAYS(pName2!=0) && pName2->n>0 ){
   767      if( db->init.busy ) {
   768        sqlite3ErrorMsg(pParse, "corrupt database");
   769        pParse->nErr++;
   770        return -1;
   771      }
   772      *pUnqual = pName2;
   773      iDb = sqlite3FindDb(db, pName1);
   774      if( iDb<0 ){
   775        sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
   776        pParse->nErr++;
   777        return -1;
   778      }
   779    }else{
   780      assert( db->init.iDb==0 || db->init.busy );
   781      iDb = db->init.iDb;
   782      *pUnqual = pName1;
   783    }
   784    return iDb;
   785  }
   786  
   787  /*
   788  ** This routine is used to check if the UTF-8 string zName is a legal
   789  ** unqualified name for a new schema object (table, index, view or
   790  ** trigger). All names are legal except those that begin with the string
   791  ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
   792  ** is reserved for internal use.
   793  */
   794  int sqlite3CheckObjectName(Parse *pParse, const char *zName){
   795    if( !pParse->db->init.busy && pParse->nested==0 
   796            && (pParse->db->flags & SQLITE_WriteSchema)==0
   797            && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
   798      sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
   799      return SQLITE_ERROR;
   800    }
   801    return SQLITE_OK;
   802  }
   803  
   804  /*
   805  ** Return the PRIMARY KEY index of a table
   806  */
   807  Index *sqlite3PrimaryKeyIndex(Table *pTab){
   808    Index *p;
   809    for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
   810    return p;
   811  }
   812  
   813  /*
   814  ** Return the column of index pIdx that corresponds to table
   815  ** column iCol.  Return -1 if not found.
   816  */
   817  i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
   818    int i;
   819    for(i=0; i<pIdx->nColumn; i++){
   820      if( iCol==pIdx->aiColumn[i] ) return i;
   821    }
   822    return -1;
   823  }
   824  
   825  /*
   826  ** Begin constructing a new table representation in memory.  This is
   827  ** the first of several action routines that get called in response
   828  ** to a CREATE TABLE statement.  In particular, this routine is called
   829  ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
   830  ** flag is true if the table should be stored in the auxiliary database
   831  ** file instead of in the main database file.  This is normally the case
   832  ** when the "TEMP" or "TEMPORARY" keyword occurs in between
   833  ** CREATE and TABLE.
   834  **
   835  ** The new table record is initialized and put in pParse->pNewTable.
   836  ** As more of the CREATE TABLE statement is parsed, additional action
   837  ** routines will be called to add more information to this record.
   838  ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
   839  ** is called to complete the construction of the new table record.
   840  */
   841  void sqlite3StartTable(
   842    Parse *pParse,   /* Parser context */
   843    Token *pName1,   /* First part of the name of the table or view */
   844    Token *pName2,   /* Second part of the name of the table or view */
   845    int isTemp,      /* True if this is a TEMP table */
   846    int isView,      /* True if this is a VIEW */
   847    int isVirtual,   /* True if this is a VIRTUAL table */
   848    int noErr        /* Do nothing if table already exists */
   849  ){
   850    Table *pTable;
   851    char *zName = 0; /* The name of the new table */
   852    sqlite3 *db = pParse->db;
   853    Vdbe *v;
   854    int iDb;         /* Database number to create the table in */
   855    Token *pName;    /* Unqualified name of the table to create */
   856  
   857    /* The table or view name to create is passed to this routine via tokens
   858    ** pName1 and pName2. If the table name was fully qualified, for example:
   859    **
   860    ** CREATE TABLE xxx.yyy (...);
   861    ** 
   862    ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
   863    ** the table name is not fully qualified, i.e.:
   864    **
   865    ** CREATE TABLE yyy(...);
   866    **
   867    ** Then pName1 is set to "yyy" and pName2 is "".
   868    **
   869    ** The call below sets the pName pointer to point at the token (pName1 or
   870    ** pName2) that stores the unqualified table name. The variable iDb is
   871    ** set to the index of the database that the table or view is to be
   872    ** created in.
   873    */
   874    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   875    if( iDb<0 ) return;
   876    if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
   877      /* If creating a temp table, the name may not be qualified. Unless 
   878      ** the database name is "temp" anyway.  */
   879      sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
   880      return;
   881    }
   882    if( !OMIT_TEMPDB && isTemp ) iDb = 1;
   883  
   884    pParse->sNameToken = *pName;
   885    zName = sqlite3NameFromToken(db, pName);
   886    if( zName==0 ) return;
   887    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   888      goto begin_table_error;
   889    }
   890    if( db->init.iDb==1 ) isTemp = 1;
   891  #ifndef SQLITE_OMIT_AUTHORIZATION
   892    assert( (isTemp & 1)==isTemp );
   893    {
   894      int code;
   895      char *zDb = db->aDb[iDb].zName;
   896      if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
   897        goto begin_table_error;
   898      }
   899      if( isView ){
   900        if( !OMIT_TEMPDB && isTemp ){
   901          code = SQLITE_CREATE_TEMP_VIEW;
   902        }else{
   903          code = SQLITE_CREATE_VIEW;
   904        }
   905      }else{
   906        if( !OMIT_TEMPDB && isTemp ){
   907          code = SQLITE_CREATE_TEMP_TABLE;
   908        }else{
   909          code = SQLITE_CREATE_TABLE;
   910        }
   911      }
   912      if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
   913        goto begin_table_error;
   914      }
   915    }
   916  #endif
   917  
   918    /* Make sure the new table name does not collide with an existing
   919    ** index or table name in the same database.  Issue an error message if
   920    ** it does. The exception is if the statement being parsed was passed
   921    ** to an sqlite3_declare_vtab() call. In that case only the column names
   922    ** and types will be used, so there is no need to test for namespace
   923    ** collisions.
   924    */
   925    if( !IN_DECLARE_VTAB ){
   926      char *zDb = db->aDb[iDb].zName;
   927      if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   928        goto begin_table_error;
   929      }
   930      pTable = sqlite3FindTable(db, zName, zDb);
   931      if( pTable ){
   932        if( !noErr ){
   933          sqlite3ErrorMsg(pParse, "table %T already exists", pName);
   934        }else{
   935          assert( !db->init.busy );
   936          sqlite3CodeVerifySchema(pParse, iDb);
   937        }
   938        goto begin_table_error;
   939      }
   940      if( sqlite3FindIndex(db, zName, zDb)!=0 ){
   941        sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
   942        goto begin_table_error;
   943      }
   944    }
   945  
   946    pTable = sqlite3DbMallocZero(db, sizeof(Table));
   947    if( pTable==0 ){
   948      db->mallocFailed = 1;
   949      pParse->rc = SQLITE_NOMEM;
   950      pParse->nErr++;
   951      goto begin_table_error;
   952    }
   953    pTable->zName = zName;
   954    pTable->iPKey = -1;
   955    pTable->pSchema = db->aDb[iDb].pSchema;
   956    pTable->nRef = 1;
   957    pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
   958    assert( pParse->pNewTable==0 );
   959    pParse->pNewTable = pTable;
   960  
   961    /* If this is the magic sqlite_sequence table used by autoincrement,
   962    ** then record a pointer to this table in the main database structure
   963    ** so that INSERT can find the table easily.
   964    */
   965  #ifndef SQLITE_OMIT_AUTOINCREMENT
   966    if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
   967      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   968      pTable->pSchema->pSeqTab = pTable;
   969    }
   970  #endif
   971  
   972    /* Begin generating the code that will insert the table record into
   973    ** the SQLITE_MASTER table.  Note in particular that we must go ahead
   974    ** and allocate the record number for the table entry now.  Before any
   975    ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
   976    ** indices to be created and the table record must come before the 
   977    ** indices.  Hence, the record number for the table must be allocated
   978    ** now.
   979    */
   980    if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
   981      int j1;
   982      int fileFormat;
   983      int reg1, reg2, reg3;
   984      sqlite3BeginWriteOperation(pParse, 0, iDb);
   985  
   986  #ifndef SQLITE_OMIT_VIRTUALTABLE
   987      if( isVirtual ){
   988        sqlite3VdbeAddOp0(v, OP_VBegin);
   989      }
   990  #endif
   991  
   992      /* If the file format and encoding in the database have not been set, 
   993      ** set them now.
   994      */
   995      reg1 = pParse->regRowid = ++pParse->nMem;
   996      reg2 = pParse->regRoot = ++pParse->nMem;
   997      reg3 = ++pParse->nMem;
   998      sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
   999      sqlite3VdbeUsesBtree(v, iDb);
  1000      j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
  1001      fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  1002                    1 : SQLITE_MAX_FILE_FORMAT;
  1003      sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
  1004      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
  1005      sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
  1006      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
  1007      sqlite3VdbeJumpHere(v, j1);
  1008  
  1009      /* This just creates a place-holder record in the sqlite_master table.
  1010      ** The record created does not contain anything yet.  It will be replaced
  1011      ** by the real entry in code generated at sqlite3EndTable().
  1012      **
  1013      ** The rowid for the new entry is left in register pParse->regRowid.
  1014      ** The root page number of the new table is left in reg pParse->regRoot.
  1015      ** The rowid and root page number values are needed by the code that
  1016      ** sqlite3EndTable will generate.
  1017      */
  1018  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  1019      if( isView || isVirtual ){
  1020        sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  1021      }else
  1022  #endif
  1023      {
  1024        pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  1025      }
  1026      sqlite3OpenMasterTable(pParse, iDb);
  1027      sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  1028      sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
  1029      sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  1030      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  1031      sqlite3VdbeAddOp0(v, OP_Close);
  1032    }
  1033  
  1034    /* Normal (non-error) return. */
  1035    return;
  1036  
  1037    /* If an error occurs, we jump here */
  1038  begin_table_error:
  1039    sqlite3DbFree(db, zName);
  1040    return;
  1041  }
  1042  
  1043  /*
  1044  ** This macro is used to compare two strings in a case-insensitive manner.
  1045  ** It is slightly faster than calling sqlite3StrICmp() directly, but
  1046  ** produces larger code.
  1047  **
  1048  ** WARNING: This macro is not compatible with the strcmp() family. It
  1049  ** returns true if the two strings are equal, otherwise false.
  1050  */
  1051  #define STRICMP(x, y) (\
  1052  sqlite3UpperToLower[*(unsigned char *)(x)]==   \
  1053  sqlite3UpperToLower[*(unsigned char *)(y)]     \
  1054  && sqlite3StrICmp((x)+1,(y)+1)==0 )
  1055  
  1056  /*
  1057  ** Add a new column to the table currently being constructed.
  1058  **
  1059  ** The parser calls this routine once for each column declaration
  1060  ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
  1061  ** first to get things going.  Then this routine is called for each
  1062  ** column.
  1063  */
  1064  void sqlite3AddColumn(Parse *pParse, Token *pName){
  1065    Table *p;
  1066    int i;
  1067    char *z;
  1068    Column *pCol;
  1069    sqlite3 *db = pParse->db;
  1070    if( (p = pParse->pNewTable)==0 ) return;
  1071  #if SQLITE_MAX_COLUMN
  1072    if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  1073      sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  1074      return;
  1075    }
  1076  #endif
  1077    z = sqlite3NameFromToken(db, pName);
  1078    if( z==0 ) return;
  1079    for(i=0; i<p->nCol; i++){
  1080      if( STRICMP(z, p->aCol[i].zName) ){
  1081        sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  1082        sqlite3DbFree(db, z);
  1083        return;
  1084      }
  1085    }
  1086    if( (p->nCol & 0x7)==0 ){
  1087      Column *aNew;
  1088      aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  1089      if( aNew==0 ){
  1090        sqlite3DbFree(db, z);
  1091        return;
  1092      }
  1093      p->aCol = aNew;
  1094    }
  1095    pCol = &p->aCol[p->nCol];
  1096    memset(pCol, 0, sizeof(p->aCol[0]));
  1097    pCol->zName = z;
  1098   
  1099    /* If there is no type specified, columns have the default affinity
  1100    ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
  1101    ** be called next to set pCol->affinity correctly.
  1102    */
  1103    pCol->affinity = SQLITE_AFF_NONE;
  1104    pCol->szEst = 1;
  1105    p->nCol++;
  1106  }
  1107  
  1108  /*
  1109  ** This routine is called by the parser while in the middle of
  1110  ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
  1111  ** been seen on a column.  This routine sets the notNull flag on
  1112  ** the column currently under construction.
  1113  */
  1114  void sqlite3AddNotNull(Parse *pParse, int onError){
  1115    Table *p;
  1116    p = pParse->pNewTable;
  1117    if( p==0 || NEVER(p->nCol<1) ) return;
  1118    p->aCol[p->nCol-1].notNull = (u8)onError;
  1119  }
  1120  
  1121  /*
  1122  ** Scan the column type name zType (length nType) and return the
  1123  ** associated affinity type.
  1124  **
  1125  ** This routine does a case-independent search of zType for the 
  1126  ** substrings in the following table. If one of the substrings is
  1127  ** found, the corresponding affinity is returned. If zType contains
  1128  ** more than one of the substrings, entries toward the top of 
  1129  ** the table take priority. For example, if zType is 'BLOBINT', 
  1130  ** SQLITE_AFF_INTEGER is returned.
  1131  **
  1132  ** Substring     | Affinity
  1133  ** --------------------------------
  1134  ** 'INT'         | SQLITE_AFF_INTEGER
  1135  ** 'CHAR'        | SQLITE_AFF_TEXT
  1136  ** 'CLOB'        | SQLITE_AFF_TEXT
  1137  ** 'TEXT'        | SQLITE_AFF_TEXT
  1138  ** 'BLOB'        | SQLITE_AFF_NONE
  1139  ** 'REAL'        | SQLITE_AFF_REAL
  1140  ** 'FLOA'        | SQLITE_AFF_REAL
  1141  ** 'DOUB'        | SQLITE_AFF_REAL
  1142  **
  1143  ** If none of the substrings in the above table are found,
  1144  ** SQLITE_AFF_NUMERIC is returned.
  1145  */
  1146  char sqlite3AffinityType(const char *zIn, u8 *pszEst){
  1147    u32 h = 0;
  1148    char aff = SQLITE_AFF_NUMERIC;
  1149    const char *zChar = 0;
  1150  
  1151    if( zIn==0 ) return aff;
  1152    while( zIn[0] ){
  1153      h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  1154      zIn++;
  1155      if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
  1156        aff = SQLITE_AFF_TEXT;
  1157        zChar = zIn;
  1158      }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
  1159        aff = SQLITE_AFF_TEXT;
  1160      }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
  1161        aff = SQLITE_AFF_TEXT;
  1162      }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
  1163          && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  1164        aff = SQLITE_AFF_NONE;
  1165        if( zIn[0]=='(' ) zChar = zIn;
  1166  #ifndef SQLITE_OMIT_FLOATING_POINT
  1167      }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
  1168          && aff==SQLITE_AFF_NUMERIC ){
  1169        aff = SQLITE_AFF_REAL;
  1170      }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
  1171          && aff==SQLITE_AFF_NUMERIC ){
  1172        aff = SQLITE_AFF_REAL;
  1173      }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
  1174          && aff==SQLITE_AFF_NUMERIC ){
  1175        aff = SQLITE_AFF_REAL;
  1176  #endif
  1177      }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
  1178        aff = SQLITE_AFF_INTEGER;
  1179        break;
  1180      }
  1181    }
  1182  
  1183    /* If pszEst is not NULL, store an estimate of the field size.  The
  1184    ** estimate is scaled so that the size of an integer is 1.  */
  1185    if( pszEst ){
  1186      *pszEst = 1;   /* default size is approx 4 bytes */
  1187      if( aff<SQLITE_AFF_NUMERIC ){
  1188        if( zChar ){
  1189          while( zChar[0] ){
  1190            if( sqlite3Isdigit(zChar[0]) ){
  1191              int v = 0;
  1192              sqlite3GetInt32(zChar, &v);
  1193              v = v/4 + 1;
  1194              if( v>255 ) v = 255;
  1195              *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  1196              break;
  1197            }
  1198            zChar++;
  1199          }
  1200        }else{
  1201          *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
  1202        }
  1203      }
  1204    }
  1205    return aff;
  1206  }
  1207  
  1208  /*
  1209  ** This routine is called by the parser while in the middle of
  1210  ** parsing a CREATE TABLE statement.  The pFirst token is the first
  1211  ** token in the sequence of tokens that describe the type of the
  1212  ** column currently under construction.   pLast is the last token
  1213  ** in the sequence.  Use this information to construct a string
  1214  ** that contains the typename of the column and store that string
  1215  ** in zType.
  1216  */ 
  1217  void sqlite3AddColumnType(Parse *pParse, Token *pType){
  1218    Table *p;
  1219    Column *pCol;
  1220  
  1221    p = pParse->pNewTable;
  1222    if( p==0 || NEVER(p->nCol<1) ) return;
  1223    pCol = &p->aCol[p->nCol-1];
  1224    assert( pCol->zType==0 );
  1225    pCol->zType = sqlite3NameFromToken(pParse->db, pType);
  1226    pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
  1227  }
  1228  
  1229  /*
  1230  ** The expression is the default value for the most recently added column
  1231  ** of the table currently under construction.
  1232  **
  1233  ** Default value expressions must be constant.  Raise an exception if this
  1234  ** is not the case.
  1235  **
  1236  ** This routine is called by the parser while in the middle of
  1237  ** parsing a CREATE TABLE statement.
  1238  */
  1239  void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  1240    Table *p;
  1241    Column *pCol;
  1242    sqlite3 *db = pParse->db;
  1243    p = pParse->pNewTable;
  1244    if( p!=0 ){
  1245      pCol = &(p->aCol[p->nCol-1]);
  1246      if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
  1247        sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  1248            pCol->zName);
  1249      }else{
  1250        /* A copy of pExpr is used instead of the original, as pExpr contains
  1251        ** tokens that point to volatile memory. The 'span' of the expression
  1252        ** is required by pragma table_info.
  1253        */
  1254        sqlite3ExprDelete(db, pCol->pDflt);
  1255        pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
  1256        sqlite3DbFree(db, pCol->zDflt);
  1257        pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  1258                                       (int)(pSpan->zEnd - pSpan->zStart));
  1259      }
  1260    }
  1261    sqlite3ExprDelete(db, pSpan->pExpr);
  1262  }
  1263  
  1264  /*
  1265  ** Designate the PRIMARY KEY for the table.  pList is a list of names 
  1266  ** of columns that form the primary key.  If pList is NULL, then the
  1267  ** most recently added column of the table is the primary key.
  1268  **
  1269  ** A table can have at most one primary key.  If the table already has
  1270  ** a primary key (and this is the second primary key) then create an
  1271  ** error.
  1272  **
  1273  ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  1274  ** then we will try to use that column as the rowid.  Set the Table.iPKey
  1275  ** field of the table under construction to be the index of the
  1276  ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
  1277  ** no INTEGER PRIMARY KEY.
  1278  **
  1279  ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  1280  ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
  1281  */
  1282  void sqlite3AddPrimaryKey(
  1283    Parse *pParse,    /* Parsing context */
  1284    ExprList *pList,  /* List of field names to be indexed */
  1285    int onError,      /* What to do with a uniqueness conflict */
  1286    int autoInc,      /* True if the AUTOINCREMENT keyword is present */
  1287    int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  1288  ){
  1289    Table *pTab = pParse->pNewTable;
  1290    char *zType = 0;
  1291    int iCol = -1, i;
  1292    int nTerm;
  1293    if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  1294    if( pTab->tabFlags & TF_HasPrimaryKey ){
  1295      sqlite3ErrorMsg(pParse, 
  1296        "table \"%s\" has more than one primary key", pTab->zName);
  1297      goto primary_key_exit;
  1298    }
  1299    pTab->tabFlags |= TF_HasPrimaryKey;
  1300    if( pList==0 ){
  1301      iCol = pTab->nCol - 1;
  1302      pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  1303      zType = pTab->aCol[iCol].zType;
  1304      nTerm = 1;
  1305    }else{
  1306      nTerm = pList->nExpr;
  1307      for(i=0; i<nTerm; i++){
  1308        for(iCol=0; iCol<pTab->nCol; iCol++){
  1309          if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
  1310            pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  1311            zType = pTab->aCol[iCol].zType;
  1312            break;
  1313          }
  1314        }
  1315      }
  1316    }
  1317    if( nTerm==1
  1318     && zType && sqlite3StrICmp(zType, "INTEGER")==0
  1319     && sortOrder==SQLITE_SO_ASC
  1320    ){
  1321      pTab->iPKey = iCol;
  1322      pTab->keyConf = (u8)onError;
  1323      assert( autoInc==0 || autoInc==1 );
  1324      pTab->tabFlags |= autoInc*TF_Autoincrement;
  1325      if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
  1326    }else if( autoInc ){
  1327  #ifndef SQLITE_OMIT_AUTOINCREMENT
  1328      sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  1329         "INTEGER PRIMARY KEY");
  1330  #endif
  1331    }else{
  1332      Vdbe *v = pParse->pVdbe;
  1333      Index *p;
  1334      if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
  1335      p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  1336                             0, sortOrder, 0);
  1337      if( p ){
  1338        p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
  1339        if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
  1340      }
  1341      pList = 0;
  1342    }
  1343  
  1344  primary_key_exit:
  1345    sqlite3ExprListDelete(pParse->db, pList);
  1346    return;
  1347  }
  1348  
  1349  /*
  1350  ** Add a new CHECK constraint to the table currently under construction.
  1351  */
  1352  void sqlite3AddCheckConstraint(
  1353    Parse *pParse,    /* Parsing context */
  1354    Expr *pCheckExpr  /* The check expression */
  1355  ){
  1356  #ifndef SQLITE_OMIT_CHECK
  1357    Table *pTab = pParse->pNewTable;
  1358    sqlite3 *db = pParse->db;
  1359    if( pTab && !IN_DECLARE_VTAB
  1360     && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
  1361    ){
  1362      pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  1363      if( pParse->constraintName.n ){
  1364        sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  1365      }
  1366    }else
  1367  #endif
  1368    {
  1369      sqlite3ExprDelete(pParse->db, pCheckExpr);
  1370    }
  1371  }
  1372  
  1373  /*
  1374  ** Set the collation function of the most recently parsed table column
  1375  ** to the CollSeq given.
  1376  */
  1377  void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  1378    Table *p;
  1379    int i;
  1380    char *zColl;              /* Dequoted name of collation sequence */
  1381    sqlite3 *db;
  1382  
  1383    if( (p = pParse->pNewTable)==0 ) return;
  1384    i = p->nCol-1;
  1385    db = pParse->db;
  1386    zColl = sqlite3NameFromToken(db, pToken);
  1387    if( !zColl ) return;
  1388  
  1389    if( sqlite3LocateCollSeq(pParse, zColl) ){
  1390      Index *pIdx;
  1391      sqlite3DbFree(db, p->aCol[i].zColl);
  1392      p->aCol[i].zColl = zColl;
  1393    
  1394      /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  1395      ** then an index may have been created on this column before the
  1396      ** collation type was added. Correct this if it is the case.
  1397      */
  1398      for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  1399        assert( pIdx->nKeyCol==1 );
  1400        if( pIdx->aiColumn[0]==i ){
  1401          pIdx->azColl[0] = p->aCol[i].zColl;
  1402        }
  1403      }
  1404    }else{
  1405      sqlite3DbFree(db, zColl);
  1406    }
  1407  }
  1408  
  1409  /*
  1410  ** This function returns the collation sequence for database native text
  1411  ** encoding identified by the string zName, length nName.
  1412  **
  1413  ** If the requested collation sequence is not available, or not available
  1414  ** in the database native encoding, the collation factory is invoked to
  1415  ** request it. If the collation factory does not supply such a sequence,
  1416  ** and the sequence is available in another text encoding, then that is
  1417  ** returned instead.
  1418  **
  1419  ** If no versions of the requested collations sequence are available, or
  1420  ** another error occurs, NULL is returned and an error message written into
  1421  ** pParse.
  1422  **
  1423  ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
  1424  ** invokes the collation factory if the named collation cannot be found
  1425  ** and generates an error message.
  1426  **
  1427  ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  1428  */
  1429  CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  1430    sqlite3 *db = pParse->db;
  1431    u8 enc = ENC(db);
  1432    u8 initbusy = db->init.busy;
  1433    CollSeq *pColl;
  1434  
  1435    pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  1436    if( !initbusy && (!pColl || !pColl->xCmp) ){
  1437      pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  1438    }
  1439  
  1440    return pColl;
  1441  }
  1442  
  1443  
  1444  /*
  1445  ** Generate code that will increment the schema cookie.
  1446  **
  1447  ** The schema cookie is used to determine when the schema for the
  1448  ** database changes.  After each schema change, the cookie value
  1449  ** changes.  When a process first reads the schema it records the
  1450  ** cookie.  Thereafter, whenever it goes to access the database,
  1451  ** it checks the cookie to make sure the schema has not changed
  1452  ** since it was last read.
  1453  **
  1454  ** This plan is not completely bullet-proof.  It is possible for
  1455  ** the schema to change multiple times and for the cookie to be
  1456  ** set back to prior value.  But schema changes are infrequent
  1457  ** and the probability of hitting the same cookie value is only
  1458  ** 1 chance in 2^32.  So we're safe enough.
  1459  */
  1460  void sqlite3ChangeCookie(Parse *pParse, int iDb){
  1461    int r1 = sqlite3GetTempReg(pParse);
  1462    sqlite3 *db = pParse->db;
  1463    Vdbe *v = pParse->pVdbe;
  1464    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  1465    sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  1466    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
  1467    sqlite3ReleaseTempReg(pParse, r1);
  1468  }
  1469  
  1470  /*
  1471  ** Measure the number of characters needed to output the given
  1472  ** identifier.  The number returned includes any quotes used
  1473  ** but does not include the null terminator.
  1474  **
  1475  ** The estimate is conservative.  It might be larger that what is
  1476  ** really needed.
  1477  */
  1478  static int identLength(const char *z){
  1479    int n;
  1480    for(n=0; *z; n++, z++){
  1481      if( *z=='"' ){ n++; }
  1482    }
  1483    return n + 2;
  1484  }
  1485  
  1486  /*
  1487  ** The first parameter is a pointer to an output buffer. The second 
  1488  ** parameter is a pointer to an integer that contains the offset at
  1489  ** which to write into the output buffer. This function copies the
  1490  ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  1491  ** to the specified offset in the buffer and updates *pIdx to refer
  1492  ** to the first byte after the last byte written before returning.
  1493  ** 
  1494  ** If the string zSignedIdent consists entirely of alpha-numeric
  1495  ** characters, does not begin with a digit and is not an SQL keyword,
  1496  ** then it is copied to the output buffer exactly as it is. Otherwise,
  1497  ** it is quoted using double-quotes.
  1498  */
  1499  static void identPut(char *z, int *pIdx, char *zSignedIdent){
  1500    unsigned char *zIdent = (unsigned char*)zSignedIdent;
  1501    int i, j, needQuote;
  1502    i = *pIdx;
  1503  
  1504    for(j=0; zIdent[j]; j++){
  1505      if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  1506    }
  1507    needQuote = sqlite3Isdigit(zIdent[0])
  1508              || sqlite3KeywordCode(zIdent, j)!=TK_ID
  1509              || zIdent[j]!=0
  1510              || j==0;
  1511  
  1512    if( needQuote ) z[i++] = '"';
  1513    for(j=0; zIdent[j]; j++){
  1514      z[i++] = zIdent[j];
  1515      if( zIdent[j]=='"' ) z[i++] = '"';
  1516    }
  1517    if( needQuote ) z[i++] = '"';
  1518    z[i] = 0;
  1519    *pIdx = i;
  1520  }
  1521  
  1522  /*
  1523  ** Generate a CREATE TABLE statement appropriate for the given
  1524  ** table.  Memory to hold the text of the statement is obtained
  1525  ** from sqliteMalloc() and must be freed by the calling function.
  1526  */
  1527  static char *createTableStmt(sqlite3 *db, Table *p){
  1528    int i, k, n;
  1529    char *zStmt;
  1530    char *zSep, *zSep2, *zEnd;
  1531    Column *pCol;
  1532    n = 0;
  1533    for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  1534      n += identLength(pCol->zName) + 5;
  1535    }
  1536    n += identLength(p->zName);
  1537    if( n<50 ){ 
  1538      zSep = "";
  1539      zSep2 = ",";
  1540      zEnd = ")";
  1541    }else{
  1542      zSep = "\n  ";
  1543      zSep2 = ",\n  ";
  1544      zEnd = "\n)";
  1545    }
  1546    n += 35 + 6*p->nCol;
  1547    zStmt = sqlite3DbMallocRaw(0, n);
  1548    if( zStmt==0 ){
  1549      db->mallocFailed = 1;
  1550      return 0;
  1551    }
  1552    sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  1553    k = sqlite3Strlen30(zStmt);
  1554    identPut(zStmt, &k, p->zName);
  1555    zStmt[k++] = '(';
  1556    for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  1557      static const char * const azType[] = {
  1558          /* SQLITE_AFF_NONE    */ "",
  1559          /* SQLITE_AFF_TEXT    */ " TEXT",
  1560          /* SQLITE_AFF_NUMERIC */ " NUM",
  1561          /* SQLITE_AFF_INTEGER */ " INT",
  1562          /* SQLITE_AFF_REAL    */ " REAL"
  1563      };
  1564      int len;
  1565      const char *zType;
  1566  
  1567      sqlite3_snprintf(n-k, &zStmt[k], zSep);
  1568      k += sqlite3Strlen30(&zStmt[k]);
  1569      zSep = zSep2;
  1570      identPut(zStmt, &k, pCol->zName);
  1571      assert( pCol->affinity-SQLITE_AFF_NONE >= 0 );
  1572      assert( pCol->affinity-SQLITE_AFF_NONE < ArraySize(azType) );
  1573      testcase( pCol->affinity==SQLITE_AFF_NONE );
  1574      testcase( pCol->affinity==SQLITE_AFF_TEXT );
  1575      testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  1576      testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  1577      testcase( pCol->affinity==SQLITE_AFF_REAL );
  1578      
  1579      zType = azType[pCol->affinity - SQLITE_AFF_NONE];
  1580      len = sqlite3Strlen30(zType);
  1581      assert( pCol->affinity==SQLITE_AFF_NONE 
  1582              || pCol->affinity==sqlite3AffinityType(zType, 0) );
  1583      memcpy(&zStmt[k], zType, len);
  1584      k += len;
  1585      assert( k<=n );
  1586    }
  1587    sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  1588    return zStmt;
  1589  }
  1590  
  1591  /*
  1592  ** Resize an Index object to hold N columns total.  Return SQLITE_OK
  1593  ** on success and SQLITE_NOMEM on an OOM error.
  1594  */
  1595  static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
  1596    char *zExtra;
  1597    int nByte;
  1598    if( pIdx->nColumn>=N ) return SQLITE_OK;
  1599    assert( pIdx->isResized==0 );
  1600    nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
  1601    zExtra = sqlite3DbMallocZero(db, nByte);
  1602    if( zExtra==0 ) return SQLITE_NOMEM;
  1603    memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
  1604    pIdx->azColl = (char**)zExtra;
  1605    zExtra += sizeof(char*)*N;
  1606    memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
  1607    pIdx->aiColumn = (i16*)zExtra;
  1608    zExtra += sizeof(i16)*N;
  1609    memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
  1610    pIdx->aSortOrder = (u8*)zExtra;
  1611    pIdx->nColumn = N;
  1612    pIdx->isResized = 1;
  1613    return SQLITE_OK;
  1614  }
  1615  
  1616  /*
  1617  ** Estimate the total row width for a table.
  1618  */
  1619  static void estimateTableWidth(Table *pTab){
  1620    unsigned wTable = 0;
  1621    const Column *pTabCol;
  1622    int i;
  1623    for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  1624      wTable += pTabCol->szEst;
  1625    }
  1626    if( pTab->iPKey<0 ) wTable++;
  1627    pTab->szTabRow = sqlite3LogEst(wTable*4);
  1628  }
  1629  
  1630  /*
  1631  ** Estimate the average size of a row for an index.
  1632  */
  1633  static void estimateIndexWidth(Index *pIdx){
  1634    unsigned wIndex = 0;
  1635    int i;
  1636    const Column *aCol = pIdx->pTable->aCol;
  1637    for(i=0; i<pIdx->nColumn; i++){
  1638      i16 x = pIdx->aiColumn[i];
  1639      assert( x<pIdx->pTable->nCol );
  1640      wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
  1641    }
  1642    pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  1643  }
  1644  
  1645  /* Return true if value x is found any of the first nCol entries of aiCol[]
  1646  */
  1647  static int hasColumn(const i16 *aiCol, int nCol, int x){
  1648    while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
  1649    return 0;
  1650  }
  1651  
  1652  /*
  1653  ** This routine runs at the end of parsing a CREATE TABLE statement that
  1654  ** has a WITHOUT ROWID clause.  The job of this routine is to convert both
  1655  ** internal schema data structures and the generated VDBE code so that they
  1656  ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
  1657  ** Changes include:
  1658  **
  1659  **     (1)  Convert the OP_CreateTable into an OP_CreateIndex.  There is
  1660  **          no rowid btree for a WITHOUT ROWID.  Instead, the canonical
  1661  **          data storage is a covering index btree.
  1662  **     (2)  Bypass the creation of the sqlite_master table entry
  1663  **          for the PRIMARY KEY as the primary key index is now
  1664  **          identified by the sqlite_master table entry of the table itself.
  1665  **     (3)  Set the Index.tnum of the PRIMARY KEY Index object in the
  1666  **          schema to the rootpage from the main table.
  1667  **     (4)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
  1668  **     (5)  Add all table columns to the PRIMARY KEY Index object
  1669  **          so that the PRIMARY KEY is a covering index.  The surplus
  1670  **          columns are part of KeyInfo.nXField and are not used for
  1671  **          sorting or lookup or uniqueness checks.
  1672  **     (6)  Replace the rowid tail on all automatically generated UNIQUE
  1673  **          indices with the PRIMARY KEY columns.
  1674  */
  1675  static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
  1676    Index *pIdx;
  1677    Index *pPk;
  1678    int nPk;
  1679    int i, j;
  1680    sqlite3 *db = pParse->db;
  1681    Vdbe *v = pParse->pVdbe;
  1682  
  1683    /* Convert the OP_CreateTable opcode that would normally create the
  1684    ** root-page for the table into an OP_CreateIndex opcode.  The index
  1685    ** created will become the PRIMARY KEY index.
  1686    */
  1687    if( pParse->addrCrTab ){
  1688      assert( v );
  1689      sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
  1690    }
  1691  
  1692    /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
  1693    ** table entry.
  1694    */
  1695    if( pParse->addrSkipPK ){
  1696      assert( v );
  1697      sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
  1698    }
  1699  
  1700    /* Locate the PRIMARY KEY index.  Or, if this table was originally
  1701    ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. 
  1702    */
  1703    if( pTab->iPKey>=0 ){
  1704      ExprList *pList;
  1705      pList = sqlite3ExprListAppend(pParse, 0, 0);
  1706      if( pList==0 ) return;
  1707      pList->a[0].zName = sqlite3DbStrDup(pParse->db,
  1708                                          pTab->aCol[pTab->iPKey].zName);
  1709      pList->a[0].sortOrder = pParse->iPkSortOrder;
  1710      assert( pParse->pNewTable==pTab );
  1711      pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
  1712      if( pPk==0 ) return;
  1713      pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
  1714      pTab->iPKey = -1;
  1715    }else{
  1716      pPk = sqlite3PrimaryKeyIndex(pTab);
  1717    }
  1718    pPk->isCovering = 1;
  1719    assert( pPk!=0 );
  1720    nPk = pPk->nKeyCol;
  1721  
  1722    /* Make sure every column of the PRIMARY KEY is NOT NULL */
  1723    for(i=0; i<nPk; i++){
  1724      pTab->aCol[pPk->aiColumn[i]].notNull = 1;
  1725    }
  1726    pPk->uniqNotNull = 1;
  1727  
  1728    /* The root page of the PRIMARY KEY is the table root page */
  1729    pPk->tnum = pTab->tnum;
  1730  
  1731    /* Update the in-memory representation of all UNIQUE indices by converting
  1732    ** the final rowid column into one or more columns of the PRIMARY KEY.
  1733    */
  1734    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  1735      int n;
  1736      if( IsPrimaryKeyIndex(pIdx) ) continue;
  1737      for(i=n=0; i<nPk; i++){
  1738        if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
  1739      }
  1740      if( n==0 ){
  1741        /* This index is a superset of the primary key */
  1742        pIdx->nColumn = pIdx->nKeyCol;
  1743        continue;
  1744      }
  1745      if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
  1746      for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
  1747        if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
  1748          pIdx->aiColumn[j] = pPk->aiColumn[i];
  1749          pIdx->azColl[j] = pPk->azColl[i];
  1750          j++;
  1751        }
  1752      }
  1753      assert( pIdx->nColumn>=pIdx->nKeyCol+n );
  1754      assert( pIdx->nColumn>=j );
  1755    }
  1756  
  1757    /* Add all table columns to the PRIMARY KEY index
  1758    */
  1759    if( nPk<pTab->nCol ){
  1760      if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
  1761      for(i=0, j=nPk; i<pTab->nCol; i++){
  1762        if( !hasColumn(pPk->aiColumn, j, i) ){
  1763          assert( j<pPk->nColumn );
  1764          pPk->aiColumn[j] = i;
  1765          pPk->azColl[j] = "BINARY";
  1766          j++;
  1767        }
  1768      }
  1769      assert( pPk->nColumn==j );
  1770      assert( pTab->nCol==j );
  1771    }else{
  1772      pPk->nColumn = pTab->nCol;
  1773    }
  1774  }
  1775  
  1776  /*
  1777  ** This routine is called to report the final ")" that terminates
  1778  ** a CREATE TABLE statement.
  1779  **
  1780  ** The table structure that other action routines have been building
  1781  ** is added to the internal hash tables, assuming no errors have
  1782  ** occurred.
  1783  **
  1784  ** An entry for the table is made in the master table on disk, unless
  1785  ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
  1786  ** it means we are reading the sqlite_master table because we just
  1787  ** connected to the database or because the sqlite_master table has
  1788  ** recently changed, so the entry for this table already exists in
  1789  ** the sqlite_master table.  We do not want to create it again.
  1790  **
  1791  ** If the pSelect argument is not NULL, it means that this routine
  1792  ** was called to create a table generated from a 
  1793  ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
  1794  ** the new table will match the result set of the SELECT.
  1795  */
  1796  void sqlite3EndTable(
  1797    Parse *pParse,          /* Parse context */
  1798    Token *pCons,           /* The ',' token after the last column defn. */
  1799    Token *pEnd,            /* The ')' before options in the CREATE TABLE */
  1800    u8 tabOpts,             /* Extra table options. Usually 0. */
  1801    Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
  1802  ){
  1803    Table *p;                 /* The new table */
  1804    sqlite3 *db = pParse->db; /* The database connection */
  1805    int iDb;                  /* Database in which the table lives */
  1806    Index *pIdx;              /* An implied index of the table */
  1807  
  1808    if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
  1809      return;
  1810    }
  1811    p = pParse->pNewTable;
  1812    if( p==0 ) return;
  1813  
  1814    assert( !db->init.busy || !pSelect );
  1815  
  1816    /* If the db->init.busy is 1 it means we are reading the SQL off the
  1817    ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  1818    ** So do not write to the disk again.  Extract the root page number
  1819    ** for the table from the db->init.newTnum field.  (The page number
  1820    ** should have been put there by the sqliteOpenCb routine.)
  1821    */
  1822    if( db->init.busy ){
  1823      p->tnum = db->init.newTnum;
  1824    }
  1825  
  1826    /* Special processing for WITHOUT ROWID Tables */
  1827    if( tabOpts & TF_WithoutRowid ){
  1828      if( (p->tabFlags & TF_Autoincrement) ){
  1829        sqlite3ErrorMsg(pParse,
  1830            "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
  1831        return;
  1832      }
  1833      if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
  1834        sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
  1835      }else{
  1836        p->tabFlags |= TF_WithoutRowid;
  1837        convertToWithoutRowidTable(pParse, p);
  1838      }
  1839    }
  1840  
  1841    iDb = sqlite3SchemaToIndex(db, p->pSchema);
  1842  
  1843  #ifndef SQLITE_OMIT_CHECK
  1844    /* Resolve names in all CHECK constraint expressions.
  1845    */
  1846    if( p->pCheck ){
  1847      sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  1848    }
  1849  #endif /* !defined(SQLITE_OMIT_CHECK) */
  1850  
  1851    /* Estimate the average row size for the table and for all implied indices */
  1852    estimateTableWidth(p);
  1853    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  1854      estimateIndexWidth(pIdx);
  1855    }
  1856  
  1857    /* If not initializing, then create a record for the new table
  1858    ** in the SQLITE_MASTER table of the database.
  1859    **
  1860    ** If this is a TEMPORARY table, write the entry into the auxiliary
  1861    ** file instead of into the main database file.
  1862    */
  1863    if( !db->init.busy ){
  1864      int n;
  1865      Vdbe *v;
  1866      char *zType;    /* "view" or "table" */
  1867      char *zType2;   /* "VIEW" or "TABLE" */
  1868      char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
  1869  
  1870      v = sqlite3GetVdbe(pParse);
  1871      if( NEVER(v==0) ) return;
  1872  
  1873      sqlite3VdbeAddOp1(v, OP_Close, 0);
  1874  
  1875      /* 
  1876      ** Initialize zType for the new view or table.
  1877      */
  1878      if( p->pSelect==0 ){
  1879        /* A regular table */
  1880        zType = "table";
  1881        zType2 = "TABLE";
  1882  #ifndef SQLITE_OMIT_VIEW
  1883      }else{
  1884        /* A view */
  1885        zType = "view";
  1886        zType2 = "VIEW";
  1887  #endif
  1888      }
  1889  
  1890      /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  1891      ** statement to populate the new table. The root-page number for the
  1892      ** new table is in register pParse->regRoot.
  1893      **
  1894      ** Once the SELECT has been coded by sqlite3Select(), it is in a
  1895      ** suitable state to query for the column names and types to be used
  1896      ** by the new table.
  1897      **
  1898      ** A shared-cache write-lock is not required to write to the new table,
  1899      ** as a schema-lock must have already been obtained to create it. Since
  1900      ** a schema-lock excludes all other database users, the write-lock would
  1901      ** be redundant.
  1902      */
  1903      if( pSelect ){
  1904        SelectDest dest;
  1905        Table *pSelTab;
  1906  
  1907        assert(pParse->nTab==1);
  1908        sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  1909        sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  1910        pParse->nTab = 2;
  1911        sqlite3SelectDestInit(&dest, SRT_Table, 1);
  1912        sqlite3Select(pParse, pSelect, &dest);
  1913        sqlite3VdbeAddOp1(v, OP_Close, 1);
  1914        if( pParse->nErr==0 ){
  1915          pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  1916          if( pSelTab==0 ) return;
  1917          assert( p->aCol==0 );
  1918          p->nCol = pSelTab->nCol;
  1919          p->aCol = pSelTab->aCol;
  1920          pSelTab->nCol = 0;
  1921          pSelTab->aCol = 0;
  1922          sqlite3DeleteTable(db, pSelTab);
  1923        }
  1924      }
  1925  
  1926      /* Compute the complete text of the CREATE statement */
  1927      if( pSelect ){
  1928        zStmt = createTableStmt(db, p);
  1929      }else{
  1930        Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
  1931        n = (int)(pEnd2->z - pParse->sNameToken.z);
  1932        if( pEnd2->z[0]!=';' ) n += pEnd2->n;
  1933        zStmt = sqlite3MPrintf(db, 
  1934            "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  1935        );
  1936      }
  1937  
  1938      /* A slot for the record has already been allocated in the 
  1939      ** SQLITE_MASTER table.  We just need to update that slot with all
  1940      ** the information we've collected.
  1941      */
  1942      sqlite3NestedParse(pParse,
  1943        "UPDATE %Q.%s "
  1944           "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  1945         "WHERE rowid=#%d",
  1946        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  1947        zType,
  1948        p->zName,
  1949        p->zName,
  1950        pParse->regRoot,
  1951        zStmt,
  1952        pParse->regRowid
  1953      );
  1954      sqlite3DbFree(db, zStmt);
  1955      sqlite3ChangeCookie(pParse, iDb);
  1956  
  1957  #ifndef SQLITE_OMIT_AUTOINCREMENT
  1958      /* Check to see if we need to create an sqlite_sequence table for
  1959      ** keeping track of autoincrement keys.
  1960      */
  1961      if( p->tabFlags & TF_Autoincrement ){
  1962        Db *pDb = &db->aDb[iDb];
  1963        assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  1964        if( pDb->pSchema->pSeqTab==0 ){
  1965          sqlite3NestedParse(pParse,
  1966            "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  1967            pDb->zName
  1968          );
  1969        }
  1970      }
  1971  #endif
  1972  
  1973      /* Reparse everything to update our internal data structures */
  1974      sqlite3VdbeAddParseSchemaOp(v, iDb,
  1975             sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
  1976    }
  1977  
  1978  
  1979    /* Add the table to the in-memory representation of the database.
  1980    */
  1981    if( db->init.busy ){
  1982      Table *pOld;
  1983      Schema *pSchema = p->pSchema;
  1984      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  1985      pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
  1986      if( pOld ){
  1987        assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
  1988        db->mallocFailed = 1;
  1989        return;
  1990      }
  1991      pParse->pNewTable = 0;
  1992      db->flags |= SQLITE_InternChanges;
  1993  
  1994  #ifndef SQLITE_OMIT_ALTERTABLE
  1995      if( !p->pSelect ){
  1996        const char *zName = (const char *)pParse->sNameToken.z;
  1997        int nName;
  1998        assert( !pSelect && pCons && pEnd );
  1999        if( pCons->z==0 ){
  2000          pCons = pEnd;
  2001        }
  2002        nName = (int)((const char *)pCons->z - zName);
  2003        p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  2004      }
  2005  #endif
  2006    }
  2007  }
  2008  
  2009  #ifndef SQLITE_OMIT_VIEW
  2010  /*
  2011  ** The parser calls this routine in order to create a new VIEW
  2012  */
  2013  void sqlite3CreateView(
  2014    Parse *pParse,     /* The parsing context */
  2015    Token *pBegin,     /* The CREATE token that begins the statement */
  2016    Token *pName1,     /* The token that holds the name of the view */
  2017    Token *pName2,     /* The token that holds the name of the view */
  2018    Select *pSelect,   /* A SELECT statement that will become the new view */
  2019    int isTemp,        /* TRUE for a TEMPORARY view */
  2020    int noErr          /* Suppress error messages if VIEW already exists */
  2021  ){
  2022    Table *p;
  2023    int n;
  2024    const char *z;
  2025    Token sEnd;
  2026    DbFixer sFix;
  2027    Token *pName = 0;
  2028    int iDb;
  2029    sqlite3 *db = pParse->db;
  2030  
  2031    if( pParse->nVar>0 ){
  2032      sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  2033      sqlite3SelectDelete(db, pSelect);
  2034      return;
  2035    }
  2036    sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  2037    p = pParse->pNewTable;
  2038    if( p==0 || pParse->nErr ){
  2039      sqlite3SelectDelete(db, pSelect);
  2040      return;
  2041    }
  2042    sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  2043    iDb = sqlite3SchemaToIndex(db, p->pSchema);
  2044    sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  2045    if( sqlite3FixSelect(&sFix, pSelect) ){
  2046      sqlite3SelectDelete(db, pSelect);
  2047      return;
  2048    }
  2049  
  2050    /* Make a copy of the entire SELECT statement that defines the view.
  2051    ** This will force all the Expr.token.z values to be dynamically
  2052    ** allocated rather than point to the input string - which means that
  2053    ** they will persist after the current sqlite3_exec() call returns.
  2054    */
  2055    p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  2056    sqlite3SelectDelete(db, pSelect);
  2057    if( db->mallocFailed ){
  2058      return;
  2059    }
  2060    if( !db->init.busy ){
  2061      sqlite3ViewGetColumnNames(pParse, p);
  2062    }
  2063  
  2064    /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
  2065    ** the end.
  2066    */
  2067    sEnd = pParse->sLastToken;
  2068    if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
  2069      sEnd.z += sEnd.n;
  2070    }
  2071    sEnd.n = 0;
  2072    n = (int)(sEnd.z - pBegin->z);
  2073    z = pBegin->z;
  2074    while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
  2075    sEnd.z = &z[n-1];
  2076    sEnd.n = 1;
  2077  
  2078    /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  2079    sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
  2080    return;
  2081  }
  2082  #endif /* SQLITE_OMIT_VIEW */
  2083  
  2084  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  2085  /*
  2086  ** The Table structure pTable is really a VIEW.  Fill in the names of
  2087  ** the columns of the view in the pTable structure.  Return the number
  2088  ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
  2089  */
  2090  int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  2091    Table *pSelTab;   /* A fake table from which we get the result set */
  2092    Select *pSel;     /* Copy of the SELECT that implements the view */
  2093    int nErr = 0;     /* Number of errors encountered */
  2094    int n;            /* Temporarily holds the number of cursors assigned */
  2095    sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
  2096    sqlite3_xauth xAuth;       /* Saved xAuth pointer */
  2097  
  2098    assert( pTable );
  2099  
  2100  #ifndef SQLITE_OMIT_VIRTUALTABLE
  2101    if( sqlite3VtabCallConnect(pParse, pTable) ){
  2102      return SQLITE_ERROR;
  2103    }
  2104    if( IsVirtual(pTable) ) return 0;
  2105  #endif
  2106  
  2107  #ifndef SQLITE_OMIT_VIEW
  2108    /* A positive nCol means the columns names for this view are
  2109    ** already known.
  2110    */
  2111    if( pTable->nCol>0 ) return 0;
  2112  
  2113    /* A negative nCol is a special marker meaning that we are currently
  2114    ** trying to compute the column names.  If we enter this routine with
  2115    ** a negative nCol, it means two or more views form a loop, like this:
  2116    **
  2117    **     CREATE VIEW one AS SELECT * FROM two;
  2118    **     CREATE VIEW two AS SELECT * FROM one;
  2119    **
  2120    ** Actually, the error above is now caught prior to reaching this point.
  2121    ** But the following test is still important as it does come up
  2122    ** in the following:
  2123    ** 
  2124    **     CREATE TABLE main.ex1(a);
  2125    **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  2126    **     SELECT * FROM temp.ex1;
  2127    */
  2128    if( pTable->nCol<0 ){
  2129      sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  2130      return 1;
  2131    }
  2132    assert( pTable->nCol>=0 );
  2133  
  2134    /* If we get this far, it means we need to compute the table names.
  2135    ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  2136    ** "*" elements in the results set of the view and will assign cursors
  2137    ** to the elements of the FROM clause.  But we do not want these changes
  2138    ** to be permanent.  So the computation is done on a copy of the SELECT
  2139    ** statement that defines the view.
  2140    */
  2141    assert( pTable->pSelect );
  2142    pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  2143    if( pSel ){
  2144      u8 enableLookaside = db->lookaside.bEnabled;
  2145      n = pParse->nTab;
  2146      sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  2147      pTable->nCol = -1;
  2148      db->lookaside.bEnabled = 0;
  2149  #ifndef SQLITE_OMIT_AUTHORIZATION
  2150      xAuth = db->xAuth;
  2151      db->xAuth = 0;
  2152      pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  2153      db->xAuth = xAuth;
  2154  #else
  2155      pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  2156  #endif
  2157      db->lookaside.bEnabled = enableLookaside;
  2158      pParse->nTab = n;
  2159      if( pSelTab ){
  2160        assert( pTable->aCol==0 );
  2161        pTable->nCol = pSelTab->nCol;
  2162        pTable->aCol = pSelTab->aCol;
  2163        pSelTab->nCol = 0;
  2164        pSelTab->aCol = 0;
  2165        sqlite3DeleteTable(db, pSelTab);
  2166        assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  2167        pTable->pSchema->schemaFlags |= DB_UnresetViews;
  2168      }else{
  2169        pTable->nCol = 0;
  2170        nErr++;
  2171      }
  2172      sqlite3SelectDelete(db, pSel);
  2173    } else {
  2174      nErr++;
  2175    }
  2176  #endif /* SQLITE_OMIT_VIEW */
  2177    return nErr;  
  2178  }
  2179  #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  2180  
  2181  #ifndef SQLITE_OMIT_VIEW
  2182  /*
  2183  ** Clear the column names from every VIEW in database idx.
  2184  */
  2185  static void sqliteViewResetAll(sqlite3 *db, int idx){
  2186    HashElem *i;
  2187    assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  2188    if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  2189    for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  2190      Table *pTab = sqliteHashData(i);
  2191      if( pTab->pSelect ){
  2192        sqliteDeleteColumnNames(db, pTab);
  2193        pTab->aCol = 0;
  2194        pTab->nCol = 0;
  2195      }
  2196    }
  2197    DbClearProperty(db, idx, DB_UnresetViews);
  2198  }
  2199  #else
  2200  # define sqliteViewResetAll(A,B)
  2201  #endif /* SQLITE_OMIT_VIEW */
  2202  
  2203  /*
  2204  ** This function is called by the VDBE to adjust the internal schema
  2205  ** used by SQLite when the btree layer moves a table root page. The
  2206  ** root-page of a table or index in database iDb has changed from iFrom
  2207  ** to iTo.
  2208  **
  2209  ** Ticket #1728:  The symbol table might still contain information
  2210  ** on tables and/or indices that are the process of being deleted.
  2211  ** If you are unlucky, one of those deleted indices or tables might
  2212  ** have the same rootpage number as the real table or index that is
  2213  ** being moved.  So we cannot stop searching after the first match 
  2214  ** because the first match might be for one of the deleted indices
  2215  ** or tables and not the table/index that is actually being moved.
  2216  ** We must continue looping until all tables and indices with
  2217  ** rootpage==iFrom have been converted to have a rootpage of iTo
  2218  ** in order to be certain that we got the right one.
  2219  */
  2220  #ifndef SQLITE_OMIT_AUTOVACUUM
  2221  void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  2222    HashElem *pElem;
  2223    Hash *pHash;
  2224    Db *pDb;
  2225  
  2226    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  2227    pDb = &db->aDb[iDb];
  2228    pHash = &pDb->pSchema->tblHash;
  2229    for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  2230      Table *pTab = sqliteHashData(pElem);
  2231      if( pTab->tnum==iFrom ){
  2232        pTab->tnum = iTo;
  2233      }
  2234    }
  2235    pHash = &pDb->pSchema->idxHash;
  2236    for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  2237      Index *pIdx = sqliteHashData(pElem);
  2238      if( pIdx->tnum==iFrom ){
  2239        pIdx->tnum = iTo;
  2240      }
  2241    }
  2242  }
  2243  #endif
  2244  
  2245  /*
  2246  ** Write code to erase the table with root-page iTable from database iDb.
  2247  ** Also write code to modify the sqlite_master table and internal schema
  2248  ** if a root-page of another table is moved by the btree-layer whilst
  2249  ** erasing iTable (this can happen with an auto-vacuum database).
  2250  */ 
  2251  static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  2252    Vdbe *v = sqlite3GetVdbe(pParse);
  2253    int r1 = sqlite3GetTempReg(pParse);
  2254    sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  2255    sqlite3MayAbort(pParse);
  2256  #ifndef SQLITE_OMIT_AUTOVACUUM
  2257    /* OP_Destroy stores an in integer r1. If this integer
  2258    ** is non-zero, then it is the root page number of a table moved to
  2259    ** location iTable. The following code modifies the sqlite_master table to
  2260    ** reflect this.
  2261    **
  2262    ** The "#NNN" in the SQL is a special constant that means whatever value
  2263    ** is in register NNN.  See grammar rules associated with the TK_REGISTER
  2264    ** token for additional information.
  2265    */
  2266    sqlite3NestedParse(pParse, 
  2267       "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  2268       pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  2269  #endif
  2270    sqlite3ReleaseTempReg(pParse, r1);
  2271  }
  2272  
  2273  /*
  2274  ** Write VDBE code to erase table pTab and all associated indices on disk.
  2275  ** Code to update the sqlite_master tables and internal schema definitions
  2276  ** in case a root-page belonging to another table is moved by the btree layer
  2277  ** is also added (this can happen with an auto-vacuum database).
  2278  */
  2279  static void destroyTable(Parse *pParse, Table *pTab){
  2280  #ifdef SQLITE_OMIT_AUTOVACUUM
  2281    Index *pIdx;
  2282    int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  2283    destroyRootPage(pParse, pTab->tnum, iDb);
  2284    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  2285      destroyRootPage(pParse, pIdx->tnum, iDb);
  2286    }
  2287  #else
  2288    /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  2289    ** is not defined), then it is important to call OP_Destroy on the
  2290    ** table and index root-pages in order, starting with the numerically 
  2291    ** largest root-page number. This guarantees that none of the root-pages
  2292    ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  2293    ** following were coded:
  2294    **
  2295    ** OP_Destroy 4 0
  2296    ** ...
  2297    ** OP_Destroy 5 0
  2298    **
  2299    ** and root page 5 happened to be the largest root-page number in the
  2300    ** database, then root page 5 would be moved to page 4 by the 
  2301    ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  2302    ** a free-list page.
  2303    */
  2304    int iTab = pTab->tnum;
  2305    int iDestroyed = 0;
  2306  
  2307    while( 1 ){
  2308      Index *pIdx;
  2309      int iLargest = 0;
  2310  
  2311      if( iDestroyed==0 || iTab<iDestroyed ){
  2312        iLargest = iTab;
  2313      }
  2314      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  2315        int iIdx = pIdx->tnum;
  2316        assert( pIdx->pSchema==pTab->pSchema );
  2317        if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  2318          iLargest = iIdx;
  2319        }
  2320      }
  2321      if( iLargest==0 ){
  2322        return;
  2323      }else{
  2324        int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  2325        assert( iDb>=0 && iDb<pParse->db->nDb );
  2326        destroyRootPage(pParse, iLargest, iDb);
  2327        iDestroyed = iLargest;
  2328      }
  2329    }
  2330  #endif
  2331  }
  2332  
  2333  /*
  2334  ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  2335  ** after a DROP INDEX or DROP TABLE command.
  2336  */
  2337  static void sqlite3ClearStatTables(
  2338    Parse *pParse,         /* The parsing context */
  2339    int iDb,               /* The database number */
  2340    const char *zType,     /* "idx" or "tbl" */
  2341    const char *zName      /* Name of index or table */
  2342  ){
  2343    int i;
  2344    const char *zDbName = pParse->db->aDb[iDb].zName;
  2345    for(i=1; i<=4; i++){
  2346      char zTab[24];
  2347      sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  2348      if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  2349        sqlite3NestedParse(pParse,
  2350          "DELETE FROM %Q.%s WHERE %s=%Q",
  2351          zDbName, zTab, zType, zName
  2352        );
  2353      }
  2354    }
  2355  }
  2356  
  2357  /*
  2358  ** Generate code to drop a table.
  2359  */
  2360  void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  2361    Vdbe *v;
  2362    sqlite3 *db = pParse->db;
  2363    Trigger *pTrigger;
  2364    Db *pDb = &db->aDb[iDb];
  2365  
  2366    v = sqlite3GetVdbe(pParse);
  2367    assert( v!=0 );
  2368    sqlite3BeginWriteOperation(pParse, 1, iDb);
  2369  
  2370  #ifndef SQLITE_OMIT_VIRTUALTABLE
  2371    if( IsVirtual(pTab) ){
  2372      sqlite3VdbeAddOp0(v, OP_VBegin);
  2373    }
  2374  #endif
  2375  
  2376    /* Drop all triggers associated with the table being dropped. Code
  2377    ** is generated to remove entries from sqlite_master and/or
  2378    ** sqlite_temp_master if required.
  2379    */
  2380    pTrigger = sqlite3TriggerList(pParse, pTab);
  2381    while( pTrigger ){
  2382      assert( pTrigger->pSchema==pTab->pSchema || 
  2383          pTrigger->pSchema==db->aDb[1].pSchema );
  2384      sqlite3DropTriggerPtr(pParse, pTrigger);
  2385      pTrigger = pTrigger->pNext;
  2386    }
  2387  
  2388  #ifndef SQLITE_OMIT_AUTOINCREMENT
  2389    /* Remove any entries of the sqlite_sequence table associated with
  2390    ** the table being dropped. This is done before the table is dropped
  2391    ** at the btree level, in case the sqlite_sequence table needs to
  2392    ** move as a result of the drop (can happen in auto-vacuum mode).
  2393    */
  2394    if( pTab->tabFlags & TF_Autoincrement ){
  2395      sqlite3NestedParse(pParse,
  2396        "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  2397        pDb->zName, pTab->zName
  2398      );
  2399    }
  2400  #endif
  2401  
  2402    /* Drop all SQLITE_MASTER table and index entries that refer to the
  2403    ** table. The program name loops through the master table and deletes
  2404    ** every row that refers to a table of the same name as the one being
  2405    ** dropped. Triggers are handled separately because a trigger can be
  2406    ** created in the temp database that refers to a table in another
  2407    ** database.
  2408    */
  2409    sqlite3NestedParse(pParse, 
  2410        "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  2411        pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  2412    if( !isView && !IsVirtual(pTab) ){
  2413      destroyTable(pParse, pTab);
  2414    }
  2415  
  2416    /* Remove the table entry from SQLite's internal schema and modify
  2417    ** the schema cookie.
  2418    */
  2419    if( IsVirtual(pTab) ){
  2420      sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  2421    }
  2422    sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  2423    sqlite3ChangeCookie(pParse, iDb);
  2424    sqliteViewResetAll(db, iDb);
  2425  }
  2426  
  2427  /*
  2428  ** This routine is called to do the work of a DROP TABLE statement.
  2429  ** pName is the name of the table to be dropped.
  2430  */
  2431  void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  2432    Table *pTab;
  2433    Vdbe *v;
  2434    sqlite3 *db = pParse->db;
  2435    int iDb;
  2436  
  2437    if( db->mallocFailed ){
  2438      goto exit_drop_table;
  2439    }
  2440    assert( pParse->nErr==0 );
  2441    assert( pName->nSrc==1 );
  2442    if( noErr ) db->suppressErr++;
  2443    pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  2444    if( noErr ) db->suppressErr--;
  2445  
  2446    if( pTab==0 ){
  2447      if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  2448      goto exit_drop_table;
  2449    }
  2450    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  2451    assert( iDb>=0 && iDb<db->nDb );
  2452  
  2453    /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  2454    ** it is initialized.
  2455    */
  2456    if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  2457      goto exit_drop_table;
  2458    }
  2459  #ifndef SQLITE_OMIT_AUTHORIZATION
  2460    {
  2461      int code;
  2462      const char *zTab = SCHEMA_TABLE(iDb);
  2463      const char *zDb = db->aDb[iDb].zName;
  2464      const char *zArg2 = 0;
  2465      if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  2466        goto exit_drop_table;
  2467      }
  2468      if( isView ){
  2469        if( !OMIT_TEMPDB && iDb==1 ){
  2470          code = SQLITE_DROP_TEMP_VIEW;
  2471        }else{
  2472          code = SQLITE_DROP_VIEW;
  2473        }
  2474  #ifndef SQLITE_OMIT_VIRTUALTABLE
  2475      }else if( IsVirtual(pTab) ){
  2476        code = SQLITE_DROP_VTABLE;
  2477        zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  2478  #endif
  2479      }else{
  2480        if( !OMIT_TEMPDB && iDb==1 ){
  2481          code = SQLITE_DROP_TEMP_TABLE;
  2482        }else{
  2483          code = SQLITE_DROP_TABLE;
  2484        }
  2485      }
  2486      if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  2487        goto exit_drop_table;
  2488      }
  2489      if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  2490        goto exit_drop_table;
  2491      }
  2492    }
  2493  #endif
  2494    if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
  2495      && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  2496      sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  2497      goto exit_drop_table;
  2498    }
  2499  
  2500  #ifndef SQLITE_OMIT_VIEW
  2501    /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  2502    ** on a table.
  2503    */
  2504    if( isView && pTab->pSelect==0 ){
  2505      sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  2506      goto exit_drop_table;
  2507    }
  2508    if( !isView && pTab->pSelect ){
  2509      sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  2510      goto exit_drop_table;
  2511    }
  2512  #endif
  2513  
  2514    /* Generate code to remove the table from the master table
  2515    ** on disk.
  2516    */
  2517    v = sqlite3GetVdbe(pParse);
  2518    if( v ){
  2519      sqlite3BeginWriteOperation(pParse, 1, iDb);
  2520      sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  2521      sqlite3FkDropTable(pParse, pName, pTab);
  2522      sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  2523    }
  2524  
  2525  exit_drop_table:
  2526    sqlite3SrcListDelete(db, pName);
  2527  }
  2528  
  2529  /*
  2530  ** This routine is called to create a new foreign key on the table
  2531  ** currently under construction.  pFromCol determines which columns
  2532  ** in the current table point to the foreign key.  If pFromCol==0 then
  2533  ** connect the key to the last column inserted.  pTo is the name of
  2534  ** the table referred to (a.k.a the "parent" table).  pToCol is a list
  2535  ** of tables in the parent pTo table.  flags contains all
  2536  ** information about the conflict resolution algorithms specified
  2537  ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  2538  **
  2539  ** An FKey structure is created and added to the table currently
  2540  ** under construction in the pParse->pNewTable field.
  2541  **
  2542  ** The foreign key is set for IMMEDIATE processing.  A subsequent call
  2543  ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  2544  */
  2545  void sqlite3CreateForeignKey(
  2546    Parse *pParse,       /* Parsing context */
  2547    ExprList *pFromCol,  /* Columns in this table that point to other table */
  2548    Token *pTo,          /* Name of the other table */
  2549    ExprList *pToCol,    /* Columns in the other table */
  2550    int flags            /* Conflict resolution algorithms. */
  2551  ){
  2552    sqlite3 *db = pParse->db;
  2553  #ifndef SQLITE_OMIT_FOREIGN_KEY
  2554    FKey *pFKey = 0;
  2555    FKey *pNextTo;
  2556    Table *p = pParse->pNewTable;
  2557    int nByte;
  2558    int i;
  2559    int nCol;
  2560    char *z;
  2561  
  2562    assert( pTo!=0 );
  2563    if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  2564    if( pFromCol==0 ){
  2565      int iCol = p->nCol-1;
  2566      if( NEVER(iCol<0) ) goto fk_end;
  2567      if( pToCol && pToCol->nExpr!=1 ){
  2568        sqlite3ErrorMsg(pParse, "foreign key on %s"
  2569           " should reference only one column of table %T",
  2570           p->aCol[iCol].zName, pTo);
  2571        goto fk_end;
  2572      }
  2573      nCol = 1;
  2574    }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  2575      sqlite3ErrorMsg(pParse,
  2576          "number of columns in foreign key does not match the number of "
  2577          "columns in the referenced table");
  2578      goto fk_end;
  2579    }else{
  2580      nCol = pFromCol->nExpr;
  2581    }
  2582    nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  2583    if( pToCol ){
  2584      for(i=0; i<pToCol->nExpr; i++){
  2585        nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  2586      }
  2587    }
  2588    pFKey = sqlite3DbMallocZero(db, nByte );
  2589    if( pFKey==0 ){
  2590      goto fk_end;
  2591    }
  2592    pFKey->pFrom = p;
  2593    pFKey->pNextFrom = p->pFKey;
  2594    z = (char*)&pFKey->aCol[nCol];
  2595    pFKey->zTo = z;
  2596    memcpy(z, pTo->z, pTo->n);
  2597    z[pTo->n] = 0;
  2598    sqlite3Dequote(z);
  2599    z += pTo->n+1;
  2600    pFKey->nCol = nCol;
  2601    if( pFromCol==0 ){
  2602      pFKey->aCol[0].iFrom = p->nCol-1;
  2603    }else{
  2604      for(i=0; i<nCol; i++){
  2605        int j;
  2606        for(j=0; j<p->nCol; j++){
  2607          if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  2608            pFKey->aCol[i].iFrom = j;
  2609            break;
  2610          }
  2611        }
  2612        if( j>=p->nCol ){
  2613          sqlite3ErrorMsg(pParse, 
  2614            "unknown column \"%s\" in foreign key definition", 
  2615            pFromCol->a[i].zName);
  2616          goto fk_end;
  2617        }
  2618      }
  2619    }
  2620    if( pToCol ){
  2621      for(i=0; i<nCol; i++){
  2622        int n = sqlite3Strlen30(pToCol->a[i].zName);
  2623        pFKey->aCol[i].zCol = z;
  2624        memcpy(z, pToCol->a[i].zName, n);
  2625        z[n] = 0;
  2626        z += n+1;
  2627      }
  2628    }
  2629    pFKey->isDeferred = 0;
  2630    pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
  2631    pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
  2632  
  2633    assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  2634    pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
  2635        pFKey->zTo, (void *)pFKey
  2636    );
  2637    if( pNextTo==pFKey ){
  2638      db->mallocFailed = 1;
  2639      goto fk_end;
  2640    }
  2641    if( pNextTo ){
  2642      assert( pNextTo->pPrevTo==0 );
  2643      pFKey->pNextTo = pNextTo;
  2644      pNextTo->pPrevTo = pFKey;
  2645    }
  2646  
  2647    /* Link the foreign key to the table as the last step.
  2648    */
  2649    p->pFKey = pFKey;
  2650    pFKey = 0;
  2651  
  2652  fk_end:
  2653    sqlite3DbFree(db, pFKey);
  2654  #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  2655    sqlite3ExprListDelete(db, pFromCol);
  2656    sqlite3ExprListDelete(db, pToCol);
  2657  }
  2658  
  2659  /*
  2660  ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  2661  ** clause is seen as part of a foreign key definition.  The isDeferred
  2662  ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  2663  ** The behavior of the most recently created foreign key is adjusted
  2664  ** accordingly.
  2665  */
  2666  void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  2667  #ifndef SQLITE_OMIT_FOREIGN_KEY
  2668    Table *pTab;
  2669    FKey *pFKey;
  2670    if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  2671    assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  2672    pFKey->isDeferred = (u8)isDeferred;
  2673  #endif
  2674  }
  2675  
  2676  /*
  2677  ** Generate code that will erase and refill index *pIdx.  This is
  2678  ** used to initialize a newly created index or to recompute the
  2679  ** content of an index in response to a REINDEX command.
  2680  **
  2681  ** if memRootPage is not negative, it means that the index is newly
  2682  ** created.  The register specified by memRootPage contains the
  2683  ** root page number of the index.  If memRootPage is negative, then
  2684  ** the index already exists and must be cleared before being refilled and
  2685  ** the root page number of the index is taken from pIndex->tnum.
  2686  */
  2687  static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  2688    Table *pTab = pIndex->pTable;  /* The table that is indexed */
  2689    int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
  2690    int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
  2691    int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
  2692    int addr1;                     /* Address of top of loop */
  2693    int addr2;                     /* Address to jump to for next iteration */
  2694    int tnum;                      /* Root page of index */
  2695    int iPartIdxLabel;             /* Jump to this label to skip a row */
  2696    Vdbe *v;                       /* Generate code into this virtual machine */
  2697    KeyInfo *pKey;                 /* KeyInfo for index */
  2698    int regRecord;                 /* Register holding assembled index record */
  2699    sqlite3 *db = pParse->db;      /* The database connection */
  2700    int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  2701  
  2702  #ifndef SQLITE_OMIT_AUTHORIZATION
  2703    if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  2704        db->aDb[iDb].zName ) ){
  2705      return;
  2706    }
  2707  #endif
  2708  
  2709    /* Require a write-lock on the table to perform this operation */
  2710    sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  2711  
  2712    v = sqlite3GetVdbe(pParse);
  2713    if( v==0 ) return;
  2714    if( memRootPage>=0 ){
  2715      tnum = memRootPage;
  2716    }else{
  2717      tnum = pIndex->tnum;
  2718    }
  2719    pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
  2720  
  2721    /* Open the sorter cursor if we are to use one. */
  2722    iSorter = pParse->nTab++;
  2723    sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
  2724                      sqlite3KeyInfoRef(pKey), P4_KEYINFO);
  2725  
  2726    /* Open the table. Loop through all rows of the table, inserting index
  2727    ** records into the sorter. */
  2728    sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  2729    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
  2730    regRecord = sqlite3GetTempReg(pParse);
  2731  
  2732    sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
  2733    sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  2734    sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  2735    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
  2736    sqlite3VdbeJumpHere(v, addr1);
  2737    if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  2738    sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
  2739                      (char *)pKey, P4_KEYINFO);
  2740    sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  2741  
  2742    addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
  2743    assert( pKey!=0 || db->mallocFailed || pParse->nErr );
  2744    if( IsUniqueIndex(pIndex) && pKey!=0 ){
  2745      int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  2746      sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
  2747      addr2 = sqlite3VdbeCurrentAddr(v);
  2748      sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
  2749                           pIndex->nKeyCol); VdbeCoverage(v);
  2750      sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
  2751    }else{
  2752      addr2 = sqlite3VdbeCurrentAddr(v);
  2753    }
  2754    sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
  2755    sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
  2756    sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  2757    sqlite3ReleaseTempReg(pParse, regRecord);
  2758    sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
  2759    sqlite3VdbeJumpHere(v, addr1);
  2760  
  2761    sqlite3VdbeAddOp1(v, OP_Close, iTab);
  2762    sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  2763    sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  2764  }
  2765  
  2766  /*
  2767  ** Allocate heap space to hold an Index object with nCol columns.
  2768  **
  2769  ** Increase the allocation size to provide an extra nExtra bytes
  2770  ** of 8-byte aligned space after the Index object and return a
  2771  ** pointer to this extra space in *ppExtra.
  2772  */
  2773  Index *sqlite3AllocateIndexObject(
  2774    sqlite3 *db,         /* Database connection */
  2775    i16 nCol,            /* Total number of columns in the index */
  2776    int nExtra,          /* Number of bytes of extra space to alloc */
  2777    char **ppExtra       /* Pointer to the "extra" space */
  2778  ){
  2779    Index *p;            /* Allocated index object */
  2780    int nByte;           /* Bytes of space for Index object + arrays */
  2781  
  2782    nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
  2783            ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
  2784            ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
  2785                   sizeof(i16)*nCol +            /* Index.aiColumn   */
  2786                   sizeof(u8)*nCol);             /* Index.aSortOrder */
  2787    p = sqlite3DbMallocZero(db, nByte + nExtra);
  2788    if( p ){
  2789      char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
  2790      p->azColl = (char**)pExtra;       pExtra += ROUND8(sizeof(char*)*nCol);
  2791      p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
  2792      p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
  2793      p->aSortOrder = (u8*)pExtra;
  2794      p->nColumn = nCol;
  2795      p->nKeyCol = nCol - 1;
  2796      *ppExtra = ((char*)p) + nByte;
  2797    }
  2798    return p;
  2799  }
  2800  
  2801  /*
  2802  ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
  2803  ** and pTblList is the name of the table that is to be indexed.  Both will 
  2804  ** be NULL for a primary key or an index that is created to satisfy a
  2805  ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
  2806  ** as the table to be indexed.  pParse->pNewTable is a table that is
  2807  ** currently being constructed by a CREATE TABLE statement.
  2808  **
  2809  ** pList is a list of columns to be indexed.  pList will be NULL if this
  2810  ** is a primary key or unique-constraint on the most recent column added
  2811  ** to the table currently under construction.  
  2812  **
  2813  ** If the index is created successfully, return a pointer to the new Index
  2814  ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
  2815  ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  2816  */
  2817  Index *sqlite3CreateIndex(
  2818    Parse *pParse,     /* All information about this parse */
  2819    Token *pName1,     /* First part of index name. May be NULL */
  2820    Token *pName2,     /* Second part of index name. May be NULL */
  2821    SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  2822    ExprList *pList,   /* A list of columns to be indexed */
  2823    int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  2824    Token *pStart,     /* The CREATE token that begins this statement */
  2825    Expr *pPIWhere,    /* WHERE clause for partial indices */
  2826    int sortOrder,     /* Sort order of primary key when pList==NULL */
  2827    int ifNotExist     /* Omit error if index already exists */
  2828  ){
  2829    Index *pRet = 0;     /* Pointer to return */
  2830    Table *pTab = 0;     /* Table to be indexed */
  2831    Index *pIndex = 0;   /* The index to be created */
  2832    char *zName = 0;     /* Name of the index */
  2833    int nName;           /* Number of characters in zName */
  2834    int i, j;
  2835    DbFixer sFix;        /* For assigning database names to pTable */
  2836    int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
  2837    sqlite3 *db = pParse->db;
  2838    Db *pDb;             /* The specific table containing the indexed database */
  2839    int iDb;             /* Index of the database that is being written */
  2840    Token *pName = 0;    /* Unqualified name of the index to create */
  2841    struct ExprList_item *pListItem; /* For looping over pList */
  2842    const Column *pTabCol;           /* A column in the table */
  2843    int nExtra = 0;                  /* Space allocated for zExtra[] */
  2844    int nExtraCol;                   /* Number of extra columns needed */
  2845    char *zExtra = 0;                /* Extra space after the Index object */
  2846    Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
  2847  
  2848    assert( pParse->nErr==0 );      /* Never called with prior errors */
  2849    if( db->mallocFailed || IN_DECLARE_VTAB ){
  2850      goto exit_create_index;
  2851    }
  2852    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  2853      goto exit_create_index;
  2854    }
  2855  
  2856    /*
  2857    ** Find the table that is to be indexed.  Return early if not found.
  2858    */
  2859    if( pTblName!=0 ){
  2860  
  2861      /* Use the two-part index name to determine the database 
  2862      ** to search for the table. 'Fix' the table name to this db
  2863      ** before looking up the table.
  2864      */
  2865      assert( pName1 && pName2 );
  2866      iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  2867      if( iDb<0 ) goto exit_create_index;
  2868      assert( pName && pName->z );
  2869  
  2870  #ifndef SQLITE_OMIT_TEMPDB
  2871      /* If the index name was unqualified, check if the table
  2872      ** is a temp table. If so, set the database to 1. Do not do this
  2873      ** if initialising a database schema.
  2874      */
  2875      if( !db->init.busy ){
  2876        pTab = sqlite3SrcListLookup(pParse, pTblName);
  2877        if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  2878          iDb = 1;
  2879        }
  2880      }
  2881  #endif
  2882  
  2883      sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  2884      if( sqlite3FixSrcList(&sFix, pTblName) ){
  2885        /* Because the parser constructs pTblName from a single identifier,
  2886        ** sqlite3FixSrcList can never fail. */
  2887        assert(0);
  2888      }
  2889      pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  2890      assert( db->mallocFailed==0 || pTab==0 );
  2891      if( pTab==0 ) goto exit_create_index;
  2892      if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  2893        sqlite3ErrorMsg(pParse, 
  2894             "cannot create a TEMP index on non-TEMP table \"%s\"",
  2895             pTab->zName);
  2896        goto exit_create_index;
  2897      }
  2898      if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
  2899    }else{
  2900      assert( pName==0 );
  2901      assert( pStart==0 );
  2902      pTab = pParse->pNewTable;
  2903      if( !pTab ) goto exit_create_index;
  2904      iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  2905    }
  2906    pDb = &db->aDb[iDb];
  2907  
  2908    assert( pTab!=0 );
  2909    assert( pParse->nErr==0 );
  2910    if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
  2911         && db->init.busy==0
  2912  #if SQLITE_USER_AUTHENTICATION
  2913         && sqlite3UserAuthTable(pTab->zName)==0
  2914  #endif
  2915         && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  2916      sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  2917      goto exit_create_index;
  2918    }
  2919  #ifndef SQLITE_OMIT_VIEW
  2920    if( pTab->pSelect ){
  2921      sqlite3ErrorMsg(pParse, "views may not be indexed");
  2922      goto exit_create_index;
  2923    }
  2924  #endif
  2925  #ifndef SQLITE_OMIT_VIRTUALTABLE
  2926    if( IsVirtual(pTab) ){
  2927      sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  2928      goto exit_create_index;
  2929    }
  2930  #endif
  2931  
  2932    /*
  2933    ** Find the name of the index.  Make sure there is not already another
  2934    ** index or table with the same name.  
  2935    **
  2936    ** Exception:  If we are reading the names of permanent indices from the
  2937    ** sqlite_master table (because some other process changed the schema) and
  2938    ** one of the index names collides with the name of a temporary table or
  2939    ** index, then we will continue to process this index.
  2940    **
  2941    ** If pName==0 it means that we are
  2942    ** dealing with a primary key or UNIQUE constraint.  We have to invent our
  2943    ** own name.
  2944    */
  2945    if( pName ){
  2946      zName = sqlite3NameFromToken(db, pName);
  2947      if( zName==0 ) goto exit_create_index;
  2948      assert( pName->z!=0 );
  2949      if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  2950        goto exit_create_index;
  2951      }
  2952      if( !db->init.busy ){
  2953        if( sqlite3FindTable(db, zName, 0)!=0 ){
  2954          sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  2955          goto exit_create_index;
  2956        }
  2957      }
  2958      if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  2959        if( !ifNotExist ){
  2960          sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  2961        }else{
  2962          assert( !db->init.busy );
  2963          sqlite3CodeVerifySchema(pParse, iDb);
  2964        }
  2965        goto exit_create_index;
  2966      }
  2967    }else{
  2968      int n;
  2969      Index *pLoop;
  2970      for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  2971      zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  2972      if( zName==0 ){
  2973        goto exit_create_index;
  2974      }
  2975    }
  2976  
  2977    /* Check for authorization to create an index.
  2978    */
  2979  #ifndef SQLITE_OMIT_AUTHORIZATION
  2980    {
  2981      const char *zDb = pDb->zName;
  2982      if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  2983        goto exit_create_index;
  2984      }
  2985      i = SQLITE_CREATE_INDEX;
  2986      if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  2987      if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  2988        goto exit_create_index;
  2989      }
  2990    }
  2991  #endif
  2992  
  2993    /* If pList==0, it means this routine was called to make a primary
  2994    ** key out of the last column added to the table under construction.
  2995    ** So create a fake list to simulate this.
  2996    */
  2997    if( pList==0 ){
  2998      pList = sqlite3ExprListAppend(pParse, 0, 0);
  2999      if( pList==0 ) goto exit_create_index;
  3000      pList->a[0].zName = sqlite3DbStrDup(pParse->db,
  3001                                          pTab->aCol[pTab->nCol-1].zName);
  3002      pList->a[0].sortOrder = (u8)sortOrder;
  3003    }
  3004  
  3005    /* Figure out how many bytes of space are required to store explicitly
  3006    ** specified collation sequence names.
  3007    */
  3008    for(i=0; i<pList->nExpr; i++){
  3009      Expr *pExpr = pList->a[i].pExpr;
  3010      if( pExpr ){
  3011        assert( pExpr->op==TK_COLLATE );
  3012        nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  3013      }
  3014    }
  3015  
  3016    /* 
  3017    ** Allocate the index structure. 
  3018    */
  3019    nName = sqlite3Strlen30(zName);
  3020    nExtraCol = pPk ? pPk->nKeyCol : 1;
  3021    pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
  3022                                        nName + nExtra + 1, &zExtra);
  3023    if( db->mallocFailed ){
  3024      goto exit_create_index;
  3025    }
  3026    assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
  3027    assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  3028    pIndex->zName = zExtra;
  3029    zExtra += nName + 1;
  3030    memcpy(pIndex->zName, zName, nName+1);
  3031    pIndex->pTable = pTab;
  3032    pIndex->onError = (u8)onError;
  3033    pIndex->uniqNotNull = onError!=OE_None;
  3034    pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
  3035    pIndex->pSchema = db->aDb[iDb].pSchema;
  3036    pIndex->nKeyCol = pList->nExpr;
  3037    if( pPIWhere ){
  3038      sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  3039      pIndex->pPartIdxWhere = pPIWhere;
  3040      pPIWhere = 0;
  3041    }
  3042    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  3043  
  3044    /* Check to see if we should honor DESC requests on index columns
  3045    */
  3046    if( pDb->pSchema->file_format>=4 ){
  3047      sortOrderMask = -1;   /* Honor DESC */
  3048    }else{
  3049      sortOrderMask = 0;    /* Ignore DESC */
  3050    }
  3051  
  3052    /* Scan the names of the columns of the table to be indexed and
  3053    ** load the column indices into the Index structure.  Report an error
  3054    ** if any column is not found.
  3055    **
  3056    ** TODO:  Add a test to make sure that the same column is not named
  3057    ** more than once within the same index.  Only the first instance of
  3058    ** the column will ever be used by the optimizer.  Note that using the
  3059    ** same column more than once cannot be an error because that would 
  3060    ** break backwards compatibility - it needs to be a warning.
  3061    */
  3062    for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  3063      const char *zColName = pListItem->zName;
  3064      int requestedSortOrder;
  3065      char *zColl;                   /* Collation sequence name */
  3066  
  3067      for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
  3068        if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
  3069      }
  3070      if( j>=pTab->nCol ){
  3071        sqlite3ErrorMsg(pParse, "table %s has no column named %s",
  3072          pTab->zName, zColName);
  3073        pParse->checkSchema = 1;
  3074        goto exit_create_index;
  3075      }
  3076      assert( j<=0x7fff );
  3077      pIndex->aiColumn[i] = (i16)j;
  3078      if( pListItem->pExpr ){
  3079        int nColl;
  3080        assert( pListItem->pExpr->op==TK_COLLATE );
  3081        zColl = pListItem->pExpr->u.zToken;
  3082        nColl = sqlite3Strlen30(zColl) + 1;
  3083        assert( nExtra>=nColl );
  3084        memcpy(zExtra, zColl, nColl);
  3085        zColl = zExtra;
  3086        zExtra += nColl;
  3087        nExtra -= nColl;
  3088      }else{
  3089        zColl = pTab->aCol[j].zColl;
  3090        if( !zColl ) zColl = "BINARY";
  3091      }
  3092      if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  3093        goto exit_create_index;
  3094      }
  3095      pIndex->azColl[i] = zColl;
  3096      requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  3097      pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  3098      if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
  3099    }
  3100    if( pPk ){
  3101      for(j=0; j<pPk->nKeyCol; j++){
  3102        int x = pPk->aiColumn[j];
  3103        if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
  3104          pIndex->nColumn--; 
  3105        }else{
  3106          pIndex->aiColumn[i] = x;
  3107          pIndex->azColl[i] = pPk->azColl[j];
  3108          pIndex->aSortOrder[i] = pPk->aSortOrder[j];
  3109          i++;
  3110        }
  3111      }
  3112      assert( i==pIndex->nColumn );
  3113    }else{
  3114      pIndex->aiColumn[i] = -1;
  3115      pIndex->azColl[i] = "BINARY";
  3116    }
  3117    sqlite3DefaultRowEst(pIndex);
  3118    if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  3119  
  3120    if( pTab==pParse->pNewTable ){
  3121      /* This routine has been called to create an automatic index as a
  3122      ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  3123      ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  3124      ** i.e. one of:
  3125      **
  3126      ** CREATE TABLE t(x PRIMARY KEY, y);
  3127      ** CREATE TABLE t(x, y, UNIQUE(x, y));
  3128      **
  3129      ** Either way, check to see if the table already has such an index. If
  3130      ** so, don't bother creating this one. This only applies to
  3131      ** automatically created indices. Users can do as they wish with
  3132      ** explicit indices.
  3133      **
  3134      ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  3135      ** (and thus suppressing the second one) even if they have different
  3136      ** sort orders.
  3137      **
  3138      ** If there are different collating sequences or if the columns of
  3139      ** the constraint occur in different orders, then the constraints are
  3140      ** considered distinct and both result in separate indices.
  3141      */
  3142      Index *pIdx;
  3143      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  3144        int k;
  3145        assert( IsUniqueIndex(pIdx) );
  3146        assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
  3147        assert( IsUniqueIndex(pIndex) );
  3148  
  3149        if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
  3150        for(k=0; k<pIdx->nKeyCol; k++){
  3151          const char *z1;
  3152          const char *z2;
  3153          if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  3154          z1 = pIdx->azColl[k];
  3155          z2 = pIndex->azColl[k];
  3156          if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  3157        }
  3158        if( k==pIdx->nKeyCol ){
  3159          if( pIdx->onError!=pIndex->onError ){
  3160            /* This constraint creates the same index as a previous
  3161            ** constraint specified somewhere in the CREATE TABLE statement.
  3162            ** However the ON CONFLICT clauses are different. If both this 
  3163            ** constraint and the previous equivalent constraint have explicit
  3164            ** ON CONFLICT clauses this is an error. Otherwise, use the
  3165            ** explicitly specified behavior for the index.
  3166            */
  3167            if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  3168              sqlite3ErrorMsg(pParse, 
  3169                  "conflicting ON CONFLICT clauses specified", 0);
  3170            }
  3171            if( pIdx->onError==OE_Default ){
  3172              pIdx->onError = pIndex->onError;
  3173            }
  3174          }
  3175          goto exit_create_index;
  3176        }
  3177      }
  3178    }
  3179  
  3180    /* Link the new Index structure to its table and to the other
  3181    ** in-memory database structures. 
  3182    */
  3183    if( db->init.busy ){
  3184      Index *p;
  3185      assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  3186      p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
  3187                            pIndex->zName, pIndex);
  3188      if( p ){
  3189        assert( p==pIndex );  /* Malloc must have failed */
  3190        db->mallocFailed = 1;
  3191        goto exit_create_index;
  3192      }
  3193      db->flags |= SQLITE_InternChanges;
  3194      if( pTblName!=0 ){
  3195        pIndex->tnum = db->init.newTnum;
  3196      }
  3197    }
  3198  
  3199    /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
  3200    ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
  3201    ** emit code to allocate the index rootpage on disk and make an entry for
  3202    ** the index in the sqlite_master table and populate the index with
  3203    ** content.  But, do not do this if we are simply reading the sqlite_master
  3204    ** table to parse the schema, or if this index is the PRIMARY KEY index
  3205    ** of a WITHOUT ROWID table.
  3206    **
  3207    ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
  3208    ** or UNIQUE index in a CREATE TABLE statement.  Since the table
  3209    ** has just been created, it contains no data and the index initialization
  3210    ** step can be skipped.
  3211    */
  3212    else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
  3213      Vdbe *v;
  3214      char *zStmt;
  3215      int iMem = ++pParse->nMem;
  3216  
  3217      v = sqlite3GetVdbe(pParse);
  3218      if( v==0 ) goto exit_create_index;
  3219  
  3220  
  3221      /* Create the rootpage for the index
  3222      */
  3223      sqlite3BeginWriteOperation(pParse, 1, iDb);
  3224      sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  3225  
  3226      /* Gather the complete text of the CREATE INDEX statement into
  3227      ** the zStmt variable
  3228      */
  3229      if( pStart ){
  3230        int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  3231        if( pName->z[n-1]==';' ) n--;
  3232        /* A named index with an explicit CREATE INDEX statement */
  3233        zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  3234          onError==OE_None ? "" : " UNIQUE", n, pName->z);
  3235      }else{
  3236        /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  3237        /* zStmt = sqlite3MPrintf(""); */
  3238        zStmt = 0;
  3239      }
  3240  
  3241      /* Add an entry in sqlite_master for this index
  3242      */
  3243      sqlite3NestedParse(pParse, 
  3244          "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  3245          db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  3246          pIndex->zName,
  3247          pTab->zName,
  3248          iMem,
  3249          zStmt
  3250      );
  3251      sqlite3DbFree(db, zStmt);
  3252  
  3253      /* Fill the index with data and reparse the schema. Code an OP_Expire
  3254      ** to invalidate all pre-compiled statements.
  3255      */
  3256      if( pTblName ){
  3257        sqlite3RefillIndex(pParse, pIndex, iMem);
  3258        sqlite3ChangeCookie(pParse, iDb);
  3259        sqlite3VdbeAddParseSchemaOp(v, iDb,
  3260           sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  3261        sqlite3VdbeAddOp1(v, OP_Expire, 0);
  3262      }
  3263    }
  3264  
  3265    /* When adding an index to the list of indices for a table, make
  3266    ** sure all indices labeled OE_Replace come after all those labeled
  3267    ** OE_Ignore.  This is necessary for the correct constraint check
  3268    ** processing (in sqlite3GenerateConstraintChecks()) as part of
  3269    ** UPDATE and INSERT statements.  
  3270    */
  3271    if( db->init.busy || pTblName==0 ){
  3272      if( onError!=OE_Replace || pTab->pIndex==0
  3273           || pTab->pIndex->onError==OE_Replace){
  3274        pIndex->pNext = pTab->pIndex;
  3275        pTab->pIndex = pIndex;
  3276      }else{
  3277        Index *pOther = pTab->pIndex;
  3278        while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  3279          pOther = pOther->pNext;
  3280        }
  3281        pIndex->pNext = pOther->pNext;
  3282        pOther->pNext = pIndex;
  3283      }
  3284      pRet = pIndex;
  3285      pIndex = 0;
  3286    }
  3287  
  3288    /* Clean up before exiting */
  3289  exit_create_index:
  3290    if( pIndex ) freeIndex(db, pIndex);
  3291    sqlite3ExprDelete(db, pPIWhere);
  3292    sqlite3ExprListDelete(db, pList);
  3293    sqlite3SrcListDelete(db, pTblName);
  3294    sqlite3DbFree(db, zName);
  3295    return pRet;
  3296  }
  3297  
  3298  /*
  3299  ** Fill the Index.aiRowEst[] array with default information - information
  3300  ** to be used when we have not run the ANALYZE command.
  3301  **
  3302  ** aiRowEst[0] is supposed to contain the number of elements in the index.
  3303  ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
  3304  ** number of rows in the table that match any particular value of the
  3305  ** first column of the index.  aiRowEst[2] is an estimate of the number
  3306  ** of rows that match any particular combination of the first 2 columns
  3307  ** of the index.  And so forth.  It must always be the case that
  3308  *
  3309  **           aiRowEst[N]<=aiRowEst[N-1]
  3310  **           aiRowEst[N]>=1
  3311  **
  3312  ** Apart from that, we have little to go on besides intuition as to
  3313  ** how aiRowEst[] should be initialized.  The numbers generated here
  3314  ** are based on typical values found in actual indices.
  3315  */
  3316  void sqlite3DefaultRowEst(Index *pIdx){
  3317    /*                10,  9,  8,  7,  6 */
  3318    LogEst aVal[] = { 33, 32, 30, 28, 26 };
  3319    LogEst *a = pIdx->aiRowLogEst;
  3320    int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
  3321    int i;
  3322  
  3323    /* Set the first entry (number of rows in the index) to the estimated 
  3324    ** number of rows in the table. Or 10, if the estimated number of rows 
  3325    ** in the table is less than that.  */
  3326    a[0] = pIdx->pTable->nRowLogEst;
  3327    if( a[0]<33 ) a[0] = 33;        assert( 33==sqlite3LogEst(10) );
  3328  
  3329    /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
  3330    ** 6 and each subsequent value (if any) is 5.  */
  3331    memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
  3332    for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
  3333      a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
  3334    }
  3335  
  3336    assert( 0==sqlite3LogEst(1) );
  3337    if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
  3338  }
  3339  
  3340  /*
  3341  ** This routine will drop an existing named index.  This routine
  3342  ** implements the DROP INDEX statement.
  3343  */
  3344  void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  3345    Index *pIndex;
  3346    Vdbe *v;
  3347    sqlite3 *db = pParse->db;
  3348    int iDb;
  3349  
  3350    assert( pParse->nErr==0 );   /* Never called with prior errors */
  3351    if( db->mallocFailed ){
  3352      goto exit_drop_index;
  3353    }
  3354    assert( pName->nSrc==1 );
  3355    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  3356      goto exit_drop_index;
  3357    }
  3358    pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  3359    if( pIndex==0 ){
  3360      if( !ifExists ){
  3361        sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  3362      }else{
  3363        sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  3364      }
  3365      pParse->checkSchema = 1;
  3366      goto exit_drop_index;
  3367    }
  3368    if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
  3369      sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  3370        "or PRIMARY KEY constraint cannot be dropped", 0);
  3371      goto exit_drop_index;
  3372    }
  3373    iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  3374  #ifndef SQLITE_OMIT_AUTHORIZATION
  3375    {
  3376      int code = SQLITE_DROP_INDEX;
  3377      Table *pTab = pIndex->pTable;
  3378      const char *zDb = db->aDb[iDb].zName;
  3379      const char *zTab = SCHEMA_TABLE(iDb);
  3380      if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  3381        goto exit_drop_index;
  3382      }
  3383      if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  3384      if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  3385        goto exit_drop_index;
  3386      }
  3387    }
  3388  #endif
  3389  
  3390    /* Generate code to remove the index and from the master table */
  3391    v = sqlite3GetVdbe(pParse);
  3392    if( v ){
  3393      sqlite3BeginWriteOperation(pParse, 1, iDb);
  3394      sqlite3NestedParse(pParse,
  3395         "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  3396         db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
  3397      );
  3398      sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  3399      sqlite3ChangeCookie(pParse, iDb);
  3400      destroyRootPage(pParse, pIndex->tnum, iDb);
  3401      sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  3402    }
  3403  
  3404  exit_drop_index:
  3405    sqlite3SrcListDelete(db, pName);
  3406  }
  3407  
  3408  /*
  3409  ** pArray is a pointer to an array of objects. Each object in the
  3410  ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  3411  ** to extend the array so that there is space for a new object at the end.
  3412  **
  3413  ** When this function is called, *pnEntry contains the current size of
  3414  ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  3415  ** in total).
  3416  **
  3417  ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  3418  ** space allocated for the new object is zeroed, *pnEntry updated to
  3419  ** reflect the new size of the array and a pointer to the new allocation
  3420  ** returned. *pIdx is set to the index of the new array entry in this case.
  3421  **
  3422  ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  3423  ** unchanged and a copy of pArray returned.
  3424  */
  3425  void *sqlite3ArrayAllocate(
  3426    sqlite3 *db,      /* Connection to notify of malloc failures */
  3427    void *pArray,     /* Array of objects.  Might be reallocated */
  3428    int szEntry,      /* Size of each object in the array */
  3429    int *pnEntry,     /* Number of objects currently in use */
  3430    int *pIdx         /* Write the index of a new slot here */
  3431  ){
  3432    char *z;
  3433    int n = *pnEntry;
  3434    if( (n & (n-1))==0 ){
  3435      int sz = (n==0) ? 1 : 2*n;
  3436      void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  3437      if( pNew==0 ){
  3438        *pIdx = -1;
  3439        return pArray;
  3440      }
  3441      pArray = pNew;
  3442    }
  3443    z = (char*)pArray;
  3444    memset(&z[n * szEntry], 0, szEntry);
  3445    *pIdx = n;
  3446    ++*pnEntry;
  3447    return pArray;
  3448  }
  3449  
  3450  /*
  3451  ** Append a new element to the given IdList.  Create a new IdList if
  3452  ** need be.
  3453  **
  3454  ** A new IdList is returned, or NULL if malloc() fails.
  3455  */
  3456  IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  3457    int i;
  3458    if( pList==0 ){
  3459      pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  3460      if( pList==0 ) return 0;
  3461    }
  3462    pList->a = sqlite3ArrayAllocate(
  3463        db,
  3464        pList->a,
  3465        sizeof(pList->a[0]),
  3466        &pList->nId,
  3467        &i
  3468    );
  3469    if( i<0 ){
  3470      sqlite3IdListDelete(db, pList);
  3471      return 0;
  3472    }
  3473    pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  3474    return pList;
  3475  }
  3476  
  3477  /*
  3478  ** Delete an IdList.
  3479  */
  3480  void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  3481    int i;
  3482    if( pList==0 ) return;
  3483    for(i=0; i<pList->nId; i++){
  3484      sqlite3DbFree(db, pList->a[i].zName);
  3485    }
  3486    sqlite3DbFree(db, pList->a);
  3487    sqlite3DbFree(db, pList);
  3488  }
  3489  
  3490  /*
  3491  ** Return the index in pList of the identifier named zId.  Return -1
  3492  ** if not found.
  3493  */
  3494  int sqlite3IdListIndex(IdList *pList, const char *zName){
  3495    int i;
  3496    if( pList==0 ) return -1;
  3497    for(i=0; i<pList->nId; i++){
  3498      if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  3499    }
  3500    return -1;
  3501  }
  3502  
  3503  /*
  3504  ** Expand the space allocated for the given SrcList object by
  3505  ** creating nExtra new slots beginning at iStart.  iStart is zero based.
  3506  ** New slots are zeroed.
  3507  **
  3508  ** For example, suppose a SrcList initially contains two entries: A,B.
  3509  ** To append 3 new entries onto the end, do this:
  3510  **
  3511  **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  3512  **
  3513  ** After the call above it would contain:  A, B, nil, nil, nil.
  3514  ** If the iStart argument had been 1 instead of 2, then the result
  3515  ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
  3516  ** the iStart value would be 0.  The result then would
  3517  ** be: nil, nil, nil, A, B.
  3518  **
  3519  ** If a memory allocation fails the SrcList is unchanged.  The
  3520  ** db->mallocFailed flag will be set to true.
  3521  */
  3522  SrcList *sqlite3SrcListEnlarge(
  3523    sqlite3 *db,       /* Database connection to notify of OOM errors */
  3524    SrcList *pSrc,     /* The SrcList to be enlarged */
  3525    int nExtra,        /* Number of new slots to add to pSrc->a[] */
  3526    int iStart         /* Index in pSrc->a[] of first new slot */
  3527  ){
  3528    int i;
  3529  
  3530    /* Sanity checking on calling parameters */
  3531    assert( iStart>=0 );
  3532    assert( nExtra>=1 );
  3533    assert( pSrc!=0 );
  3534    assert( iStart<=pSrc->nSrc );
  3535  
  3536    /* Allocate additional space if needed */
  3537    if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
  3538      SrcList *pNew;
  3539      int nAlloc = pSrc->nSrc+nExtra;
  3540      int nGot;
  3541      pNew = sqlite3DbRealloc(db, pSrc,
  3542                 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  3543      if( pNew==0 ){
  3544        assert( db->mallocFailed );
  3545        return pSrc;
  3546      }
  3547      pSrc = pNew;
  3548      nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  3549      pSrc->nAlloc = nGot;
  3550    }
  3551  
  3552    /* Move existing slots that come after the newly inserted slots
  3553    ** out of the way */
  3554    for(i=pSrc->nSrc-1; i>=iStart; i--){
  3555      pSrc->a[i+nExtra] = pSrc->a[i];
  3556    }
  3557    pSrc->nSrc += nExtra;
  3558  
  3559    /* Zero the newly allocated slots */
  3560    memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  3561    for(i=iStart; i<iStart+nExtra; i++){
  3562      pSrc->a[i].iCursor = -1;
  3563    }
  3564  
  3565    /* Return a pointer to the enlarged SrcList */
  3566    return pSrc;
  3567  }
  3568  
  3569  
  3570  /*
  3571  ** Append a new table name to the given SrcList.  Create a new SrcList if
  3572  ** need be.  A new entry is created in the SrcList even if pTable is NULL.
  3573  **
  3574  ** A SrcList is returned, or NULL if there is an OOM error.  The returned
  3575  ** SrcList might be the same as the SrcList that was input or it might be
  3576  ** a new one.  If an OOM error does occurs, then the prior value of pList
  3577  ** that is input to this routine is automatically freed.
  3578  **
  3579  ** If pDatabase is not null, it means that the table has an optional
  3580  ** database name prefix.  Like this:  "database.table".  The pDatabase
  3581  ** points to the table name and the pTable points to the database name.
  3582  ** The SrcList.a[].zName field is filled with the table name which might
  3583  ** come from pTable (if pDatabase is NULL) or from pDatabase.  
  3584  ** SrcList.a[].zDatabase is filled with the database name from pTable,
  3585  ** or with NULL if no database is specified.
  3586  **
  3587  ** In other words, if call like this:
  3588  **
  3589  **         sqlite3SrcListAppend(D,A,B,0);
  3590  **
  3591  ** Then B is a table name and the database name is unspecified.  If called
  3592  ** like this:
  3593  **
  3594  **         sqlite3SrcListAppend(D,A,B,C);
  3595  **
  3596  ** Then C is the table name and B is the database name.  If C is defined
  3597  ** then so is B.  In other words, we never have a case where:
  3598  **
  3599  **         sqlite3SrcListAppend(D,A,0,C);
  3600  **
  3601  ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
  3602  ** before being added to the SrcList.
  3603  */
  3604  SrcList *sqlite3SrcListAppend(
  3605    sqlite3 *db,        /* Connection to notify of malloc failures */
  3606    SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
  3607    Token *pTable,      /* Table to append */
  3608    Token *pDatabase    /* Database of the table */
  3609  ){
  3610    struct SrcList_item *pItem;
  3611    assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
  3612    if( pList==0 ){
  3613      pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  3614      if( pList==0 ) return 0;
  3615      pList->nAlloc = 1;
  3616    }
  3617    pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  3618    if( db->mallocFailed ){
  3619      sqlite3SrcListDelete(db, pList);
  3620      return 0;
  3621    }
  3622    pItem = &pList->a[pList->nSrc-1];
  3623    if( pDatabase && pDatabase->z==0 ){
  3624      pDatabase = 0;
  3625    }
  3626    if( pDatabase ){
  3627      Token *pTemp = pDatabase;
  3628      pDatabase = pTable;
  3629      pTable = pTemp;
  3630    }
  3631    pItem->zName = sqlite3NameFromToken(db, pTable);
  3632    pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  3633    return pList;
  3634  }
  3635  
  3636  /*
  3637  ** Assign VdbeCursor index numbers to all tables in a SrcList
  3638  */
  3639  void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  3640    int i;
  3641    struct SrcList_item *pItem;
  3642    assert(pList || pParse->db->mallocFailed );
  3643    if( pList ){
  3644      for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  3645        if( pItem->iCursor>=0 ) break;
  3646        pItem->iCursor = pParse->nTab++;
  3647        if( pItem->pSelect ){
  3648          sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  3649        }
  3650      }
  3651    }
  3652  }
  3653  
  3654  /*
  3655  ** Delete an entire SrcList including all its substructure.
  3656  */
  3657  void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  3658    int i;
  3659    struct SrcList_item *pItem;
  3660    if( pList==0 ) return;
  3661    for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  3662      sqlite3DbFree(db, pItem->zDatabase);
  3663      sqlite3DbFree(db, pItem->zName);
  3664      sqlite3DbFree(db, pItem->zAlias);
  3665      sqlite3DbFree(db, pItem->zIndex);
  3666      sqlite3DeleteTable(db, pItem->pTab);
  3667      sqlite3SelectDelete(db, pItem->pSelect);
  3668      sqlite3ExprDelete(db, pItem->pOn);
  3669      sqlite3IdListDelete(db, pItem->pUsing);
  3670    }
  3671    sqlite3DbFree(db, pList);
  3672  }
  3673  
  3674  /*
  3675  ** This routine is called by the parser to add a new term to the
  3676  ** end of a growing FROM clause.  The "p" parameter is the part of
  3677  ** the FROM clause that has already been constructed.  "p" is NULL
  3678  ** if this is the first term of the FROM clause.  pTable and pDatabase
  3679  ** are the name of the table and database named in the FROM clause term.
  3680  ** pDatabase is NULL if the database name qualifier is missing - the
  3681  ** usual case.  If the term has an alias, then pAlias points to the
  3682  ** alias token.  If the term is a subquery, then pSubquery is the
  3683  ** SELECT statement that the subquery encodes.  The pTable and
  3684  ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
  3685  ** parameters are the content of the ON and USING clauses.
  3686  **
  3687  ** Return a new SrcList which encodes is the FROM with the new
  3688  ** term added.
  3689  */
  3690  SrcList *sqlite3SrcListAppendFromTerm(
  3691    Parse *pParse,          /* Parsing context */
  3692    SrcList *p,             /* The left part of the FROM clause already seen */
  3693    Token *pTable,          /* Name of the table to add to the FROM clause */
  3694    Token *pDatabase,       /* Name of the database containing pTable */
  3695    Token *pAlias,          /* The right-hand side of the AS subexpression */
  3696    Select *pSubquery,      /* A subquery used in place of a table name */
  3697    Expr *pOn,              /* The ON clause of a join */
  3698    IdList *pUsing          /* The USING clause of a join */
  3699  ){
  3700    struct SrcList_item *pItem;
  3701    sqlite3 *db = pParse->db;
  3702    if( !p && (pOn || pUsing) ){
  3703      sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
  3704        (pOn ? "ON" : "USING")
  3705      );
  3706      goto append_from_error;
  3707    }
  3708    p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  3709    if( p==0 || NEVER(p->nSrc==0) ){
  3710      goto append_from_error;
  3711    }
  3712    pItem = &p->a[p->nSrc-1];
  3713    assert( pAlias!=0 );
  3714    if( pAlias->n ){
  3715      pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  3716    }
  3717    pItem->pSelect = pSubquery;
  3718    pItem->pOn = pOn;
  3719    pItem->pUsing = pUsing;
  3720    return p;
  3721  
  3722   append_from_error:
  3723    assert( p==0 );
  3724    sqlite3ExprDelete(db, pOn);
  3725    sqlite3IdListDelete(db, pUsing);
  3726    sqlite3SelectDelete(db, pSubquery);
  3727    return 0;
  3728  }
  3729  
  3730  /*
  3731  ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
  3732  ** element of the source-list passed as the second argument.
  3733  */
  3734  void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  3735    assert( pIndexedBy!=0 );
  3736    if( p && ALWAYS(p->nSrc>0) ){
  3737      struct SrcList_item *pItem = &p->a[p->nSrc-1];
  3738      assert( pItem->notIndexed==0 && pItem->zIndex==0 );
  3739      if( pIndexedBy->n==1 && !pIndexedBy->z ){
  3740        /* A "NOT INDEXED" clause was supplied. See parse.y 
  3741        ** construct "indexed_opt" for details. */
  3742        pItem->notIndexed = 1;
  3743      }else{
  3744        pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
  3745      }
  3746    }
  3747  }
  3748  
  3749  /*
  3750  ** When building up a FROM clause in the parser, the join operator
  3751  ** is initially attached to the left operand.  But the code generator
  3752  ** expects the join operator to be on the right operand.  This routine
  3753  ** Shifts all join operators from left to right for an entire FROM
  3754  ** clause.
  3755  **
  3756  ** Example: Suppose the join is like this:
  3757  **
  3758  **           A natural cross join B
  3759  **
  3760  ** The operator is "natural cross join".  The A and B operands are stored
  3761  ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
  3762  ** operator with A.  This routine shifts that operator over to B.
  3763  */
  3764  void sqlite3SrcListShiftJoinType(SrcList *p){
  3765    if( p ){
  3766      int i;
  3767      assert( p->a || p->nSrc==0 );
  3768      for(i=p->nSrc-1; i>0; i--){
  3769        p->a[i].jointype = p->a[i-1].jointype;
  3770      }
  3771      p->a[0].jointype = 0;
  3772    }
  3773  }
  3774  
  3775  /*
  3776  ** Begin a transaction
  3777  */
  3778  void sqlite3BeginTransaction(Parse *pParse, int type){
  3779    sqlite3 *db;
  3780    Vdbe *v;
  3781    int i;
  3782  
  3783    assert( pParse!=0 );
  3784    db = pParse->db;
  3785    assert( db!=0 );
  3786  /*  if( db->aDb[0].pBt==0 ) return; */
  3787    if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  3788      return;
  3789    }
  3790    v = sqlite3GetVdbe(pParse);
  3791    if( !v ) return;
  3792    if( type!=TK_DEFERRED ){
  3793      for(i=0; i<db->nDb; i++){
  3794        sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  3795        sqlite3VdbeUsesBtree(v, i);
  3796      }
  3797    }
  3798    sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  3799  }
  3800  
  3801  /*
  3802  ** Commit a transaction
  3803  */
  3804  void sqlite3CommitTransaction(Parse *pParse){
  3805    Vdbe *v;
  3806  
  3807    assert( pParse!=0 );
  3808    assert( pParse->db!=0 );
  3809    if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  3810      return;
  3811    }
  3812    v = sqlite3GetVdbe(pParse);
  3813    if( v ){
  3814      sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  3815    }
  3816  }
  3817  
  3818  /*
  3819  ** Rollback a transaction
  3820  */
  3821  void sqlite3RollbackTransaction(Parse *pParse){
  3822    Vdbe *v;
  3823  
  3824    assert( pParse!=0 );
  3825    assert( pParse->db!=0 );
  3826    if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  3827      return;
  3828    }
  3829    v = sqlite3GetVdbe(pParse);
  3830    if( v ){
  3831      sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  3832    }
  3833  }
  3834  
  3835  /*
  3836  ** This function is called by the parser when it parses a command to create,
  3837  ** release or rollback an SQL savepoint. 
  3838  */
  3839  void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  3840    char *zName = sqlite3NameFromToken(pParse->db, pName);
  3841    if( zName ){
  3842      Vdbe *v = sqlite3GetVdbe(pParse);
  3843  #ifndef SQLITE_OMIT_AUTHORIZATION
  3844      static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  3845      assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  3846  #endif
  3847      if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  3848        sqlite3DbFree(pParse->db, zName);
  3849        return;
  3850      }
  3851      sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  3852    }
  3853  }
  3854  
  3855  /*
  3856  ** Make sure the TEMP database is open and available for use.  Return
  3857  ** the number of errors.  Leave any error messages in the pParse structure.
  3858  */
  3859  int sqlite3OpenTempDatabase(Parse *pParse){
  3860    sqlite3 *db = pParse->db;
  3861    if( db->aDb[1].pBt==0 && !pParse->explain ){
  3862      int rc;
  3863      Btree *pBt;
  3864      static const int flags = 
  3865            SQLITE_OPEN_READWRITE |
  3866            SQLITE_OPEN_CREATE |
  3867            SQLITE_OPEN_EXCLUSIVE |
  3868            SQLITE_OPEN_DELETEONCLOSE |
  3869            SQLITE_OPEN_TEMP_DB;
  3870  
  3871      rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  3872      if( rc!=SQLITE_OK ){
  3873        sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  3874          "file for storing temporary tables");
  3875        pParse->rc = rc;
  3876        return 1;
  3877      }
  3878      db->aDb[1].pBt = pBt;
  3879      assert( db->aDb[1].pSchema );
  3880      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  3881        db->mallocFailed = 1;
  3882        return 1;
  3883      }
  3884    }
  3885    return 0;
  3886  }
  3887  
  3888  /*
  3889  ** Record the fact that the schema cookie will need to be verified
  3890  ** for database iDb.  The code to actually verify the schema cookie
  3891  ** will occur at the end of the top-level VDBE and will be generated
  3892  ** later, by sqlite3FinishCoding().
  3893  */
  3894  void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  3895    Parse *pToplevel = sqlite3ParseToplevel(pParse);
  3896    sqlite3 *db = pToplevel->db;
  3897  
  3898    assert( iDb>=0 && iDb<db->nDb );
  3899    assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  3900    assert( iDb<SQLITE_MAX_ATTACHED+2 );
  3901    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  3902    if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
  3903      DbMaskSet(pToplevel->cookieMask, iDb);
  3904      pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  3905      if( !OMIT_TEMPDB && iDb==1 ){
  3906        sqlite3OpenTempDatabase(pToplevel);
  3907      }
  3908    }
  3909  }
  3910  
  3911  /*
  3912  ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 
  3913  ** attached database. Otherwise, invoke it for the database named zDb only.
  3914  */
  3915  void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  3916    sqlite3 *db = pParse->db;
  3917    int i;
  3918    for(i=0; i<db->nDb; i++){
  3919      Db *pDb = &db->aDb[i];
  3920      if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
  3921        sqlite3CodeVerifySchema(pParse, i);
  3922      }
  3923    }
  3924  }
  3925  
  3926  /*
  3927  ** Generate VDBE code that prepares for doing an operation that
  3928  ** might change the database.
  3929  **
  3930  ** This routine starts a new transaction if we are not already within
  3931  ** a transaction.  If we are already within a transaction, then a checkpoint
  3932  ** is set if the setStatement parameter is true.  A checkpoint should
  3933  ** be set for operations that might fail (due to a constraint) part of
  3934  ** the way through and which will need to undo some writes without having to
  3935  ** rollback the whole transaction.  For operations where all constraints
  3936  ** can be checked before any changes are made to the database, it is never
  3937  ** necessary to undo a write and the checkpoint should not be set.
  3938  */
  3939  void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  3940    Parse *pToplevel = sqlite3ParseToplevel(pParse);
  3941    sqlite3CodeVerifySchema(pParse, iDb);
  3942    DbMaskSet(pToplevel->writeMask, iDb);
  3943    pToplevel->isMultiWrite |= setStatement;
  3944  }
  3945  
  3946  /*
  3947  ** Indicate that the statement currently under construction might write
  3948  ** more than one entry (example: deleting one row then inserting another,
  3949  ** inserting multiple rows in a table, or inserting a row and index entries.)
  3950  ** If an abort occurs after some of these writes have completed, then it will
  3951  ** be necessary to undo the completed writes.
  3952  */
  3953  void sqlite3MultiWrite(Parse *pParse){
  3954    Parse *pToplevel = sqlite3ParseToplevel(pParse);
  3955    pToplevel->isMultiWrite = 1;
  3956  }
  3957  
  3958  /* 
  3959  ** The code generator calls this routine if is discovers that it is
  3960  ** possible to abort a statement prior to completion.  In order to 
  3961  ** perform this abort without corrupting the database, we need to make
  3962  ** sure that the statement is protected by a statement transaction.
  3963  **
  3964  ** Technically, we only need to set the mayAbort flag if the
  3965  ** isMultiWrite flag was previously set.  There is a time dependency
  3966  ** such that the abort must occur after the multiwrite.  This makes
  3967  ** some statements involving the REPLACE conflict resolution algorithm
  3968  ** go a little faster.  But taking advantage of this time dependency
  3969  ** makes it more difficult to prove that the code is correct (in 
  3970  ** particular, it prevents us from writing an effective
  3971  ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  3972  ** to take the safe route and skip the optimization.
  3973  */
  3974  void sqlite3MayAbort(Parse *pParse){
  3975    Parse *pToplevel = sqlite3ParseToplevel(pParse);
  3976    pToplevel->mayAbort = 1;
  3977  }
  3978  
  3979  /*
  3980  ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  3981  ** error. The onError parameter determines which (if any) of the statement
  3982  ** and/or current transaction is rolled back.
  3983  */
  3984  void sqlite3HaltConstraint(
  3985    Parse *pParse,    /* Parsing context */
  3986    int errCode,      /* extended error code */
  3987    int onError,      /* Constraint type */
  3988    char *p4,         /* Error message */
  3989    i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
  3990    u8 p5Errmsg       /* P5_ErrMsg type */
  3991  ){
  3992    Vdbe *v = sqlite3GetVdbe(pParse);
  3993    assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  3994    if( onError==OE_Abort ){
  3995      sqlite3MayAbort(pParse);
  3996    }
  3997    sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  3998    if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
  3999  }
  4000  
  4001  /*
  4002  ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
  4003  */
  4004  void sqlite3UniqueConstraint(
  4005    Parse *pParse,    /* Parsing context */
  4006    int onError,      /* Constraint type */
  4007    Index *pIdx       /* The index that triggers the constraint */
  4008  ){
  4009    char *zErr;
  4010    int j;
  4011    StrAccum errMsg;
  4012    Table *pTab = pIdx->pTable;
  4013  
  4014    sqlite3StrAccumInit(&errMsg, 0, 0, 200);
  4015    errMsg.db = pParse->db;
  4016    for(j=0; j<pIdx->nKeyCol; j++){
  4017      char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  4018      if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
  4019      sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
  4020      sqlite3StrAccumAppend(&errMsg, ".", 1);
  4021      sqlite3StrAccumAppendAll(&errMsg, zCol);
  4022    }
  4023    zErr = sqlite3StrAccumFinish(&errMsg);
  4024    sqlite3HaltConstraint(pParse, 
  4025      IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY 
  4026                              : SQLITE_CONSTRAINT_UNIQUE,
  4027      onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
  4028  }
  4029  
  4030  
  4031  /*
  4032  ** Code an OP_Halt due to non-unique rowid.
  4033  */
  4034  void sqlite3RowidConstraint(
  4035    Parse *pParse,    /* Parsing context */
  4036    int onError,      /* Conflict resolution algorithm */
  4037    Table *pTab       /* The table with the non-unique rowid */ 
  4038  ){
  4039    char *zMsg;
  4040    int rc;
  4041    if( pTab->iPKey>=0 ){
  4042      zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
  4043                            pTab->aCol[pTab->iPKey].zName);
  4044      rc = SQLITE_CONSTRAINT_PRIMARYKEY;
  4045    }else{
  4046      zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
  4047      rc = SQLITE_CONSTRAINT_ROWID;
  4048    }
  4049    sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
  4050                          P5_ConstraintUnique);
  4051  }
  4052  
  4053  /*
  4054  ** Check to see if pIndex uses the collating sequence pColl.  Return
  4055  ** true if it does and false if it does not.
  4056  */
  4057  #ifndef SQLITE_OMIT_REINDEX
  4058  static int collationMatch(const char *zColl, Index *pIndex){
  4059    int i;
  4060    assert( zColl!=0 );
  4061    for(i=0; i<pIndex->nColumn; i++){
  4062      const char *z = pIndex->azColl[i];
  4063      assert( z!=0 || pIndex->aiColumn[i]<0 );
  4064      if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
  4065        return 1;
  4066      }
  4067    }
  4068    return 0;
  4069  }
  4070  #endif
  4071  
  4072  /*
  4073  ** Recompute all indices of pTab that use the collating sequence pColl.
  4074  ** If pColl==0 then recompute all indices of pTab.
  4075  */
  4076  #ifndef SQLITE_OMIT_REINDEX
  4077  static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  4078    Index *pIndex;              /* An index associated with pTab */
  4079  
  4080    for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  4081      if( zColl==0 || collationMatch(zColl, pIndex) ){
  4082        int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  4083        sqlite3BeginWriteOperation(pParse, 0, iDb);
  4084        sqlite3RefillIndex(pParse, pIndex, -1);
  4085      }
  4086    }
  4087  }
  4088  #endif
  4089  
  4090  /*
  4091  ** Recompute all indices of all tables in all databases where the
  4092  ** indices use the collating sequence pColl.  If pColl==0 then recompute
  4093  ** all indices everywhere.
  4094  */
  4095  #ifndef SQLITE_OMIT_REINDEX
  4096  static void reindexDatabases(Parse *pParse, char const *zColl){
  4097    Db *pDb;                    /* A single database */
  4098    int iDb;                    /* The database index number */
  4099    sqlite3 *db = pParse->db;   /* The database connection */
  4100    HashElem *k;                /* For looping over tables in pDb */
  4101    Table *pTab;                /* A table in the database */
  4102  
  4103    assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
  4104    for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  4105      assert( pDb!=0 );
  4106      for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
  4107        pTab = (Table*)sqliteHashData(k);
  4108        reindexTable(pParse, pTab, zColl);
  4109      }
  4110    }
  4111  }
  4112  #endif
  4113  
  4114  /*
  4115  ** Generate code for the REINDEX command.
  4116  **
  4117  **        REINDEX                            -- 1
  4118  **        REINDEX  <collation>               -- 2
  4119  **        REINDEX  ?<database>.?<tablename>  -- 3
  4120  **        REINDEX  ?<database>.?<indexname>  -- 4
  4121  **
  4122  ** Form 1 causes all indices in all attached databases to be rebuilt.
  4123  ** Form 2 rebuilds all indices in all databases that use the named
  4124  ** collating function.  Forms 3 and 4 rebuild the named index or all
  4125  ** indices associated with the named table.
  4126  */
  4127  #ifndef SQLITE_OMIT_REINDEX
  4128  void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  4129    CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
  4130    char *z;                    /* Name of a table or index */
  4131    const char *zDb;            /* Name of the database */
  4132    Table *pTab;                /* A table in the database */
  4133    Index *pIndex;              /* An index associated with pTab */
  4134    int iDb;                    /* The database index number */
  4135    sqlite3 *db = pParse->db;   /* The database connection */
  4136    Token *pObjName;            /* Name of the table or index to be reindexed */
  4137  
  4138    /* Read the database schema. If an error occurs, leave an error message
  4139    ** and code in pParse and return NULL. */
  4140    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  4141      return;
  4142    }
  4143  
  4144    if( pName1==0 ){
  4145      reindexDatabases(pParse, 0);
  4146      return;
  4147    }else if( NEVER(pName2==0) || pName2->z==0 ){
  4148      char *zColl;
  4149      assert( pName1->z );
  4150      zColl = sqlite3NameFromToken(pParse->db, pName1);
  4151      if( !zColl ) return;
  4152      pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  4153      if( pColl ){
  4154        reindexDatabases(pParse, zColl);
  4155        sqlite3DbFree(db, zColl);
  4156        return;
  4157      }
  4158      sqlite3DbFree(db, zColl);
  4159    }
  4160    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  4161    if( iDb<0 ) return;
  4162    z = sqlite3NameFromToken(db, pObjName);
  4163    if( z==0 ) return;
  4164    zDb = db->aDb[iDb].zName;
  4165    pTab = sqlite3FindTable(db, z, zDb);
  4166    if( pTab ){
  4167      reindexTable(pParse, pTab, 0);
  4168      sqlite3DbFree(db, z);
  4169      return;
  4170    }
  4171    pIndex = sqlite3FindIndex(db, z, zDb);
  4172    sqlite3DbFree(db, z);
  4173    if( pIndex ){
  4174      sqlite3BeginWriteOperation(pParse, 0, iDb);
  4175      sqlite3RefillIndex(pParse, pIndex, -1);
  4176      return;
  4177    }
  4178    sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  4179  }
  4180  #endif
  4181  
  4182  /*
  4183  ** Return a KeyInfo structure that is appropriate for the given Index.
  4184  **
  4185  ** The KeyInfo structure for an index is cached in the Index object.
  4186  ** So there might be multiple references to the returned pointer.  The
  4187  ** caller should not try to modify the KeyInfo object.
  4188  **
  4189  ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
  4190  ** when it has finished using it.
  4191  */
4192 KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){ 4193 if( pParse->nErr ) return 0; 4194 #ifndef SQLITE_OMIT_SHARED_CACHE 4195 if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){ 4196 sqlite3KeyInfoUnref(pIdx->pKeyInfo); 4197 pIdx->pKeyInfo = 0; 4198 } 4199 #endif
4200 if( pIdx->pKeyInfo==0 ){ 4201 int i; 4202 int nCol = pIdx->nColumn; 4203 int nKey = pIdx->nKeyCol; 4204 KeyInfo *pKey; 4205 if( pIdx->uniqNotNull ){ 4206 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey); 4207 }else{ 4208 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0); 4209 } 4210 if( pKey ){ 4211 assert( sqlite3KeyInfoIsWriteable(pKey) ); 4212 for(i=0; i<nCol; i++){ 4213 char *zColl = pIdx->azColl[i]; 4214 assert( zColl!=0 ); 4215 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 : 4216 sqlite3LocateCollSeq(pParse, zColl); 4217 pKey->aSortOrder[i] = pIdx->aSortOrder[i]; 4218 } 4219 if( pParse->nErr ){ 4220 sqlite3KeyInfoUnref(pKey); 4221 }else{ 4222 pIdx->pKeyInfo = pKey; 4223 } 4224 } 4225 } 4226 return sqlite3KeyInfoRef(pIdx->pKeyInfo); 4227 } 4228 4229 #ifndef SQLITE_OMIT_CTE 4230 /* 4231 ** This routine is invoked once per CTE by the parser while parsing a 4232 ** WITH clause. 4233 */ 4234 With *sqlite3WithAdd( 4235 Parse *pParse, /* Parsing context */ 4236 With *pWith, /* Existing WITH clause, or NULL */ 4237 Token *pName, /* Name of the common-table */ 4238 ExprList *pArglist, /* Optional column name list for the table */ 4239 Select *pQuery /* Query used to initialize the table */ 4240 ){ 4241 sqlite3 *db = pParse->db; 4242 With *pNew; 4243 char *zName; 4244 4245 /* Check that the CTE name is unique within this WITH clause. If 4246 ** not, store an error in the Parse structure. */ 4247 zName = sqlite3NameFromToken(pParse->db, pName); 4248 if( zName && pWith ){ 4249 int i; 4250 for(i=0; i<pWith->nCte; i++){ 4251 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){ 4252 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName); 4253 } 4254 } 4255 } 4256 4257 if( pWith ){ 4258 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte); 4259 pNew = sqlite3DbRealloc(db, pWith, nByte); 4260 }else{ 4261 pNew = sqlite3DbMallocZero(db, sizeof(*pWith)); 4262 } 4263 assert( zName!=0 || pNew==0 ); 4264 assert( db->mallocFailed==0 || pNew==0 ); 4265 4266 if( pNew==0 ){ 4267 sqlite3ExprListDelete(db, pArglist); 4268 sqlite3SelectDelete(db, pQuery); 4269 sqlite3DbFree(db, zName); 4270 pNew = pWith; 4271 }else{ 4272 pNew->a[pNew->nCte].pSelect = pQuery; 4273 pNew->a[pNew->nCte].pCols = pArglist; 4274 pNew->a[pNew->nCte].zName = zName; 4275 pNew->a[pNew->nCte].zErr = 0; 4276 pNew->nCte++; 4277 } 4278 4279 return pNew; 4280 } 4281 4282 /* 4283 ** Free the contents of the With object passed as the second argument. 4284 */ 4285 void sqlite3WithDelete(sqlite3 *db, With *pWith){ 4286 if( pWith ){ 4287 int i; 4288 for(i=0; i<pWith->nCte; i++){ 4289 struct Cte *pCte = &pWith->a[i]; 4290 sqlite3ExprListDelete(db, pCte->pCols); 4291 sqlite3SelectDelete(db, pCte->pSelect); 4292 sqlite3DbFree(db, pCte->zName); 4293 } 4294 sqlite3DbFree(db, pWith); 4295 } 4296 } 4297 #endif /* !defined(SQLITE_OMIT_CTE) */