000001  /*
000002  ** 2003 April 6
000003  **
000004  ** The author disclaims copyright to this source code.  In place of
000005  ** a legal notice, here is a blessing:
000006  **
000007  **    May you do good and not evil.
000008  **    May you find forgiveness for yourself and forgive others.
000009  **    May you share freely, never taking more than you give.
000010  **
000011  *************************************************************************
000012  ** This file contains code used to implement the PRAGMA command.
000013  */
000014  #include "sqliteInt.h"
000015  
000016  #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
000017  #  if defined(__APPLE__)
000018  #    define SQLITE_ENABLE_LOCKING_STYLE 1
000019  #  else
000020  #    define SQLITE_ENABLE_LOCKING_STYLE 0
000021  #  endif
000022  #endif
000023  
000024  /***************************************************************************
000025  ** The "pragma.h" include file is an automatically generated file that
000026  ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
000027  ** object.  This ensures that the aPragmaName[] table is arranged in
000028  ** lexicographical order to facility a binary search of the pragma name.
000029  ** Do not edit pragma.h directly.  Edit and rerun the script in at 
000030  ** ../tool/mkpragmatab.tcl. */
000031  #include "pragma.h"
000032  
000033  /*
000034  ** Interpret the given string as a safety level.  Return 0 for OFF,
000035  ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA.  Return 1 for an empty or 
000036  ** unrecognized string argument.  The FULL and EXTRA option is disallowed
000037  ** if the omitFull parameter it 1.
000038  **
000039  ** Note that the values returned are one less that the values that
000040  ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
000041  ** to support legacy SQL code.  The safety level used to be boolean
000042  ** and older scripts may have used numbers 0 for OFF and 1 for ON.
000043  */
000044  static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
000045                               /* 123456789 123456789 123 */
000046    static const char zText[] = "onoffalseyestruextrafull";
000047    static const u8 iOffset[] = {0, 1, 2,  4,    9,  12,  15,   20};
000048    static const u8 iLength[] = {2, 2, 3,  5,    3,   4,   5,    4};
000049    static const u8 iValue[] =  {1, 0, 0,  0,    1,   1,   3,    2};
000050                              /* on no off false yes true extra full */
000051    int i, n;
000052    if( sqlite3Isdigit(*z) ){
000053      return (u8)sqlite3Atoi(z);
000054    }
000055    n = sqlite3Strlen30(z);
000056    for(i=0; i<ArraySize(iLength); i++){
000057      if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
000058       && (!omitFull || iValue[i]<=1)
000059      ){
000060        return iValue[i];
000061      }
000062    }
000063    return dflt;
000064  }
000065  
000066  /*
000067  ** Interpret the given string as a boolean value.
000068  */
000069  u8 sqlite3GetBoolean(const char *z, u8 dflt){
000070    return getSafetyLevel(z,1,dflt)!=0;
000071  }
000072  
000073  /* The sqlite3GetBoolean() function is used by other modules but the
000074  ** remainder of this file is specific to PRAGMA processing.  So omit
000075  ** the rest of the file if PRAGMAs are omitted from the build.
000076  */
000077  #if !defined(SQLITE_OMIT_PRAGMA)
000078  
000079  /*
000080  ** Interpret the given string as a locking mode value.
000081  */
000082  static int getLockingMode(const char *z){
000083    if( z ){
000084      if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
000085      if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
000086    }
000087    return PAGER_LOCKINGMODE_QUERY;
000088  }
000089  
000090  #ifndef SQLITE_OMIT_AUTOVACUUM
000091  /*
000092  ** Interpret the given string as an auto-vacuum mode value.
000093  **
000094  ** The following strings, "none", "full" and "incremental" are 
000095  ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
000096  */
000097  static int getAutoVacuum(const char *z){
000098    int i;
000099    if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
000100    if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
000101    if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
000102    i = sqlite3Atoi(z);
000103    return (u8)((i>=0&&i<=2)?i:0);
000104  }
000105  #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
000106  
000107  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
000108  /*
000109  ** Interpret the given string as a temp db location. Return 1 for file
000110  ** backed temporary databases, 2 for the Red-Black tree in memory database
000111  ** and 0 to use the compile-time default.
000112  */
000113  static int getTempStore(const char *z){
000114    if( z[0]>='0' && z[0]<='2' ){
000115      return z[0] - '0';
000116    }else if( sqlite3StrICmp(z, "file")==0 ){
000117      return 1;
000118    }else if( sqlite3StrICmp(z, "memory")==0 ){
000119      return 2;
000120    }else{
000121      return 0;
000122    }
000123  }
000124  #endif /* SQLITE_PAGER_PRAGMAS */
000125  
000126  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
000127  /*
000128  ** Invalidate temp storage, either when the temp storage is changed
000129  ** from default, or when 'file' and the temp_store_directory has changed
000130  */
000131  static int invalidateTempStorage(Parse *pParse){
000132    sqlite3 *db = pParse->db;
000133    if( db->aDb[1].pBt!=0 ){
000134      if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
000135        sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
000136          "from within a transaction");
000137        return SQLITE_ERROR;
000138      }
000139      sqlite3BtreeClose(db->aDb[1].pBt);
000140      db->aDb[1].pBt = 0;
000141      sqlite3ResetAllSchemasOfConnection(db);
000142    }
000143    return SQLITE_OK;
000144  }
000145  #endif /* SQLITE_PAGER_PRAGMAS */
000146  
000147  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
000148  /*
000149  ** If the TEMP database is open, close it and mark the database schema
000150  ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
000151  ** or DEFAULT_TEMP_STORE pragmas.
000152  */
000153  static int changeTempStorage(Parse *pParse, const char *zStorageType){
000154    int ts = getTempStore(zStorageType);
000155    sqlite3 *db = pParse->db;
000156    if( db->temp_store==ts ) return SQLITE_OK;
000157    if( invalidateTempStorage( pParse ) != SQLITE_OK ){
000158      return SQLITE_ERROR;
000159    }
000160    db->temp_store = (u8)ts;
000161    return SQLITE_OK;
000162  }
000163  #endif /* SQLITE_PAGER_PRAGMAS */
000164  
000165  /*
000166  ** Set result column names for a pragma.
000167  */
000168  static void setPragmaResultColumnNames(
000169    Vdbe *v,                     /* The query under construction */
000170    const PragmaName *pPragma    /* The pragma */
000171  ){
000172    u8 n = pPragma->nPragCName;
000173    sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
000174    if( n==0 ){
000175      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
000176    }else{
000177      int i, j;
000178      for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
000179        sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
000180      }
000181    }
000182  }
000183  
000184  /*
000185  ** Generate code to return a single integer value.
000186  */
000187  static void returnSingleInt(Vdbe *v, i64 value){
000188    sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
000189    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
000190  }
000191  
000192  /*
000193  ** Generate code to return a single text value.
000194  */
000195  static void returnSingleText(
000196    Vdbe *v,                /* Prepared statement under construction */
000197    const char *zValue      /* Value to be returned */
000198  ){
000199    if( zValue ){
000200      sqlite3VdbeLoadString(v, 1, (const char*)zValue);
000201      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
000202    }
000203  }
000204  
000205  
000206  /*
000207  ** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
000208  ** set these values for all pagers.
000209  */
000210  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
000211  static void setAllPagerFlags(sqlite3 *db){
000212    if( db->autoCommit ){
000213      Db *pDb = db->aDb;
000214      int n = db->nDb;
000215      assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
000216      assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
000217      assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
000218      assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
000219               ==  PAGER_FLAGS_MASK );
000220      assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
000221      while( (n--) > 0 ){
000222        if( pDb->pBt ){
000223          sqlite3BtreeSetPagerFlags(pDb->pBt,
000224                   pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
000225        }
000226        pDb++;
000227      }
000228    }
000229  }
000230  #else
000231  # define setAllPagerFlags(X)  /* no-op */
000232  #endif
000233  
000234  
000235  /*
000236  ** Return a human-readable name for a constraint resolution action.
000237  */
000238  #ifndef SQLITE_OMIT_FOREIGN_KEY
000239  static const char *actionName(u8 action){
000240    const char *zName;
000241    switch( action ){
000242      case OE_SetNull:  zName = "SET NULL";        break;
000243      case OE_SetDflt:  zName = "SET DEFAULT";     break;
000244      case OE_Cascade:  zName = "CASCADE";         break;
000245      case OE_Restrict: zName = "RESTRICT";        break;
000246      default:          zName = "NO ACTION";  
000247                        assert( action==OE_None ); break;
000248    }
000249    return zName;
000250  }
000251  #endif
000252  
000253  
000254  /*
000255  ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
000256  ** defined in pager.h. This function returns the associated lowercase
000257  ** journal-mode name.
000258  */
000259  const char *sqlite3JournalModename(int eMode){
000260    static char * const azModeName[] = {
000261      "delete", "persist", "off", "truncate", "memory"
000262  #ifndef SQLITE_OMIT_WAL
000263       , "wal"
000264  #endif
000265    };
000266    assert( PAGER_JOURNALMODE_DELETE==0 );
000267    assert( PAGER_JOURNALMODE_PERSIST==1 );
000268    assert( PAGER_JOURNALMODE_OFF==2 );
000269    assert( PAGER_JOURNALMODE_TRUNCATE==3 );
000270    assert( PAGER_JOURNALMODE_MEMORY==4 );
000271    assert( PAGER_JOURNALMODE_WAL==5 );
000272    assert( eMode>=0 && eMode<=ArraySize(azModeName) );
000273  
000274    if( eMode==ArraySize(azModeName) ) return 0;
000275    return azModeName[eMode];
000276  }
000277  
000278  /*
000279  ** Locate a pragma in the aPragmaName[] array.
000280  */
000281  static const PragmaName *pragmaLocate(const char *zName){
000282    int upr, lwr, mid = 0, rc;
000283    lwr = 0;
000284    upr = ArraySize(aPragmaName)-1;
000285    while( lwr<=upr ){
000286      mid = (lwr+upr)/2;
000287      rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
000288      if( rc==0 ) break;
000289      if( rc<0 ){
000290        upr = mid - 1;
000291      }else{
000292        lwr = mid + 1;
000293      }
000294    }
000295    return lwr>upr ? 0 : &aPragmaName[mid];
000296  }
000297  
000298  /*
000299  ** Helper subroutine for PRAGMA integrity_check:
000300  **
000301  ** Generate code to output a single-column result row with a value of the
000302  ** string held in register 3.  Decrement the result count in register 1
000303  ** and halt if the maximum number of result rows have been issued.
000304  */
000305  static int integrityCheckResultRow(Vdbe *v){
000306    int addr;
000307    sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
000308    addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
000309    VdbeCoverage(v);
000310    sqlite3VdbeAddOp0(v, OP_Halt);
000311    return addr;
000312  }
000313  
000314  /*
000315  ** Process a pragma statement.  
000316  **
000317  ** Pragmas are of this form:
000318  **
000319  **      PRAGMA [schema.]id [= value]
000320  **
000321  ** The identifier might also be a string.  The value is a string, and
000322  ** identifier, or a number.  If minusFlag is true, then the value is
000323  ** a number that was preceded by a minus sign.
000324  **
000325  ** If the left side is "database.id" then pId1 is the database name
000326  ** and pId2 is the id.  If the left side is just "id" then pId1 is the
000327  ** id and pId2 is any empty string.
000328  */
000329  void sqlite3Pragma(
000330    Parse *pParse, 
000331    Token *pId1,        /* First part of [schema.]id field */
000332    Token *pId2,        /* Second part of [schema.]id field, or NULL */
000333    Token *pValue,      /* Token for <value>, or NULL */
000334    int minusFlag       /* True if a '-' sign preceded <value> */
000335  ){
000336    char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
000337    char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
000338    const char *zDb = 0;   /* The database name */
000339    Token *pId;            /* Pointer to <id> token */
000340    char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
000341    int iDb;               /* Database index for <database> */
000342    int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
000343    sqlite3 *db = pParse->db;    /* The database connection */
000344    Db *pDb;                     /* The specific database being pragmaed */
000345    Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
000346    const PragmaName *pPragma;   /* The pragma */
000347  
000348    if( v==0 ) return;
000349    sqlite3VdbeRunOnlyOnce(v);
000350    pParse->nMem = 2;
000351  
000352    /* Interpret the [schema.] part of the pragma statement. iDb is the
000353    ** index of the database this pragma is being applied to in db.aDb[]. */
000354    iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
000355    if( iDb<0 ) return;
000356    pDb = &db->aDb[iDb];
000357  
000358    /* If the temp database has been explicitly named as part of the 
000359    ** pragma, make sure it is open. 
000360    */
000361    if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
000362      return;
000363    }
000364  
000365    zLeft = sqlite3NameFromToken(db, pId);
000366    if( !zLeft ) return;
000367    if( minusFlag ){
000368      zRight = sqlite3MPrintf(db, "-%T", pValue);
000369    }else{
000370      zRight = sqlite3NameFromToken(db, pValue);
000371    }
000372  
000373    assert( pId2 );
000374    zDb = pId2->n>0 ? pDb->zDbSName : 0;
000375    if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
000376      goto pragma_out;
000377    }
000378  
000379    /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
000380    ** connection.  If it returns SQLITE_OK, then assume that the VFS
000381    ** handled the pragma and generate a no-op prepared statement.
000382    **
000383    ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
000384    ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
000385    ** object corresponding to the database file to which the pragma
000386    ** statement refers.
000387    **
000388    ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
000389    ** file control is an array of pointers to strings (char**) in which the
000390    ** second element of the array is the name of the pragma and the third
000391    ** element is the argument to the pragma or NULL if the pragma has no
000392    ** argument.
000393    */
000394    aFcntl[0] = 0;
000395    aFcntl[1] = zLeft;
000396    aFcntl[2] = zRight;
000397    aFcntl[3] = 0;
000398    db->busyHandler.nBusy = 0;
000399    rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
000400    if( rc==SQLITE_OK ){
000401      sqlite3VdbeSetNumCols(v, 1);
000402      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
000403      returnSingleText(v, aFcntl[0]);
000404      sqlite3_free(aFcntl[0]);
000405      goto pragma_out;
000406    }
000407    if( rc!=SQLITE_NOTFOUND ){
000408      if( aFcntl[0] ){
000409        sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
000410        sqlite3_free(aFcntl[0]);
000411      }
000412      pParse->nErr++;
000413      pParse->rc = rc;
000414      goto pragma_out;
000415    }
000416  
000417    /* Locate the pragma in the lookup table */
000418    pPragma = pragmaLocate(zLeft);
000419    if( pPragma==0 ) goto pragma_out;
000420  
000421    /* Make sure the database schema is loaded if the pragma requires that */
000422    if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
000423      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
000424    }
000425  
000426    /* Register the result column names for pragmas that return results */
000427    if( (pPragma->mPragFlg & PragFlg_NoColumns)==0 
000428     && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
000429    ){
000430      setPragmaResultColumnNames(v, pPragma);
000431    }
000432  
000433    /* Jump to the appropriate pragma handler */
000434    switch( pPragma->ePragTyp ){
000435    
000436  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
000437    /*
000438    **  PRAGMA [schema.]default_cache_size
000439    **  PRAGMA [schema.]default_cache_size=N
000440    **
000441    ** The first form reports the current persistent setting for the
000442    ** page cache size.  The value returned is the maximum number of
000443    ** pages in the page cache.  The second form sets both the current
000444    ** page cache size value and the persistent page cache size value
000445    ** stored in the database file.
000446    **
000447    ** Older versions of SQLite would set the default cache size to a
000448    ** negative number to indicate synchronous=OFF.  These days, synchronous
000449    ** is always on by default regardless of the sign of the default cache
000450    ** size.  But continue to take the absolute value of the default cache
000451    ** size of historical compatibility.
000452    */
000453    case PragTyp_DEFAULT_CACHE_SIZE: {
000454      static const int iLn = VDBE_OFFSET_LINENO(2);
000455      static const VdbeOpList getCacheSize[] = {
000456        { OP_Transaction, 0, 0,        0},                         /* 0 */
000457        { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
000458        { OP_IfPos,       1, 8,        0},
000459        { OP_Integer,     0, 2,        0},
000460        { OP_Subtract,    1, 2,        1},
000461        { OP_IfPos,       1, 8,        0},
000462        { OP_Integer,     0, 1,        0},                         /* 6 */
000463        { OP_Noop,        0, 0,        0},
000464        { OP_ResultRow,   1, 1,        0},
000465      };
000466      VdbeOp *aOp;
000467      sqlite3VdbeUsesBtree(v, iDb);
000468      if( !zRight ){
000469        pParse->nMem += 2;
000470        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
000471        aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
000472        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
000473        aOp[0].p1 = iDb;
000474        aOp[1].p1 = iDb;
000475        aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
000476      }else{
000477        int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
000478        sqlite3BeginWriteOperation(pParse, 0, iDb);
000479        sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
000480        assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000481        pDb->pSchema->cache_size = size;
000482        sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
000483      }
000484      break;
000485    }
000486  #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
000487  
000488  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
000489    /*
000490    **  PRAGMA [schema.]page_size
000491    **  PRAGMA [schema.]page_size=N
000492    **
000493    ** The first form reports the current setting for the
000494    ** database page size in bytes.  The second form sets the
000495    ** database page size value.  The value can only be set if
000496    ** the database has not yet been created.
000497    */
000498    case PragTyp_PAGE_SIZE: {
000499      Btree *pBt = pDb->pBt;
000500      assert( pBt!=0 );
000501      if( !zRight ){
000502        int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
000503        returnSingleInt(v, size);
000504      }else{
000505        /* Malloc may fail when setting the page-size, as there is an internal
000506        ** buffer that the pager module resizes using sqlite3_realloc().
000507        */
000508        db->nextPagesize = sqlite3Atoi(zRight);
000509        if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
000510          sqlite3OomFault(db);
000511        }
000512      }
000513      break;
000514    }
000515  
000516    /*
000517    **  PRAGMA [schema.]secure_delete
000518    **  PRAGMA [schema.]secure_delete=ON/OFF/FAST
000519    **
000520    ** The first form reports the current setting for the
000521    ** secure_delete flag.  The second form changes the secure_delete
000522    ** flag setting and reports the new value.
000523    */
000524    case PragTyp_SECURE_DELETE: {
000525      Btree *pBt = pDb->pBt;
000526      int b = -1;
000527      assert( pBt!=0 );
000528      if( zRight ){
000529        if( sqlite3_stricmp(zRight, "fast")==0 ){
000530          b = 2;
000531        }else{
000532          b = sqlite3GetBoolean(zRight, 0);
000533        }
000534      }
000535      if( pId2->n==0 && b>=0 ){
000536        int ii;
000537        for(ii=0; ii<db->nDb; ii++){
000538          sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
000539        }
000540      }
000541      b = sqlite3BtreeSecureDelete(pBt, b);
000542      returnSingleInt(v, b);
000543      break;
000544    }
000545  
000546    /*
000547    **  PRAGMA [schema.]max_page_count
000548    **  PRAGMA [schema.]max_page_count=N
000549    **
000550    ** The first form reports the current setting for the
000551    ** maximum number of pages in the database file.  The 
000552    ** second form attempts to change this setting.  Both
000553    ** forms return the current setting.
000554    **
000555    ** The absolute value of N is used.  This is undocumented and might
000556    ** change.  The only purpose is to provide an easy way to test
000557    ** the sqlite3AbsInt32() function.
000558    **
000559    **  PRAGMA [schema.]page_count
000560    **
000561    ** Return the number of pages in the specified database.
000562    */
000563    case PragTyp_PAGE_COUNT: {
000564      int iReg;
000565      sqlite3CodeVerifySchema(pParse, iDb);
000566      iReg = ++pParse->nMem;
000567      if( sqlite3Tolower(zLeft[0])=='p' ){
000568        sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
000569      }else{
000570        sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, 
000571                          sqlite3AbsInt32(sqlite3Atoi(zRight)));
000572      }
000573      sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
000574      break;
000575    }
000576  
000577    /*
000578    **  PRAGMA [schema.]locking_mode
000579    **  PRAGMA [schema.]locking_mode = (normal|exclusive)
000580    */
000581    case PragTyp_LOCKING_MODE: {
000582      const char *zRet = "normal";
000583      int eMode = getLockingMode(zRight);
000584  
000585      if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
000586        /* Simple "PRAGMA locking_mode;" statement. This is a query for
000587        ** the current default locking mode (which may be different to
000588        ** the locking-mode of the main database).
000589        */
000590        eMode = db->dfltLockMode;
000591      }else{
000592        Pager *pPager;
000593        if( pId2->n==0 ){
000594          /* This indicates that no database name was specified as part
000595          ** of the PRAGMA command. In this case the locking-mode must be
000596          ** set on all attached databases, as well as the main db file.
000597          **
000598          ** Also, the sqlite3.dfltLockMode variable is set so that
000599          ** any subsequently attached databases also use the specified
000600          ** locking mode.
000601          */
000602          int ii;
000603          assert(pDb==&db->aDb[0]);
000604          for(ii=2; ii<db->nDb; ii++){
000605            pPager = sqlite3BtreePager(db->aDb[ii].pBt);
000606            sqlite3PagerLockingMode(pPager, eMode);
000607          }
000608          db->dfltLockMode = (u8)eMode;
000609        }
000610        pPager = sqlite3BtreePager(pDb->pBt);
000611        eMode = sqlite3PagerLockingMode(pPager, eMode);
000612      }
000613  
000614      assert( eMode==PAGER_LOCKINGMODE_NORMAL
000615              || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
000616      if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
000617        zRet = "exclusive";
000618      }
000619      returnSingleText(v, zRet);
000620      break;
000621    }
000622  
000623    /*
000624    **  PRAGMA [schema.]journal_mode
000625    **  PRAGMA [schema.]journal_mode =
000626    **                      (delete|persist|off|truncate|memory|wal|off)
000627    */
000628    case PragTyp_JOURNAL_MODE: {
000629      int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
000630      int ii;           /* Loop counter */
000631  
000632      if( zRight==0 ){
000633        /* If there is no "=MODE" part of the pragma, do a query for the
000634        ** current mode */
000635        eMode = PAGER_JOURNALMODE_QUERY;
000636      }else{
000637        const char *zMode;
000638        int n = sqlite3Strlen30(zRight);
000639        for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
000640          if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
000641        }
000642        if( !zMode ){
000643          /* If the "=MODE" part does not match any known journal mode,
000644          ** then do a query */
000645          eMode = PAGER_JOURNALMODE_QUERY;
000646        }
000647        if( eMode==PAGER_JOURNALMODE_OFF && (db->flags & SQLITE_Defensive)!=0 ){
000648          /* Do not allow journal-mode "OFF" in defensive since the database
000649          ** can become corrupted using ordinary SQL when the journal is off */
000650          eMode = PAGER_JOURNALMODE_QUERY;
000651        }
000652      }
000653      if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
000654        /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
000655        iDb = 0;
000656        pId2->n = 1;
000657      }
000658      for(ii=db->nDb-1; ii>=0; ii--){
000659        if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
000660          sqlite3VdbeUsesBtree(v, ii);
000661          sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
000662        }
000663      }
000664      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
000665      break;
000666    }
000667  
000668    /*
000669    **  PRAGMA [schema.]journal_size_limit
000670    **  PRAGMA [schema.]journal_size_limit=N
000671    **
000672    ** Get or set the size limit on rollback journal files.
000673    */
000674    case PragTyp_JOURNAL_SIZE_LIMIT: {
000675      Pager *pPager = sqlite3BtreePager(pDb->pBt);
000676      i64 iLimit = -2;
000677      if( zRight ){
000678        sqlite3DecOrHexToI64(zRight, &iLimit);
000679        if( iLimit<-1 ) iLimit = -1;
000680      }
000681      iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
000682      returnSingleInt(v, iLimit);
000683      break;
000684    }
000685  
000686  #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
000687  
000688    /*
000689    **  PRAGMA [schema.]auto_vacuum
000690    **  PRAGMA [schema.]auto_vacuum=N
000691    **
000692    ** Get or set the value of the database 'auto-vacuum' parameter.
000693    ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
000694    */
000695  #ifndef SQLITE_OMIT_AUTOVACUUM
000696    case PragTyp_AUTO_VACUUM: {
000697      Btree *pBt = pDb->pBt;
000698      assert( pBt!=0 );
000699      if( !zRight ){
000700        returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
000701      }else{
000702        int eAuto = getAutoVacuum(zRight);
000703        assert( eAuto>=0 && eAuto<=2 );
000704        db->nextAutovac = (u8)eAuto;
000705        /* Call SetAutoVacuum() to set initialize the internal auto and
000706        ** incr-vacuum flags. This is required in case this connection
000707        ** creates the database file. It is important that it is created
000708        ** as an auto-vacuum capable db.
000709        */
000710        rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
000711        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
000712          /* When setting the auto_vacuum mode to either "full" or 
000713          ** "incremental", write the value of meta[6] in the database
000714          ** file. Before writing to meta[6], check that meta[3] indicates
000715          ** that this really is an auto-vacuum capable database.
000716          */
000717          static const int iLn = VDBE_OFFSET_LINENO(2);
000718          static const VdbeOpList setMeta6[] = {
000719            { OP_Transaction,    0,         1,                 0},    /* 0 */
000720            { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
000721            { OP_If,             1,         0,                 0},    /* 2 */
000722            { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
000723            { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 0},    /* 4 */
000724          };
000725          VdbeOp *aOp;
000726          int iAddr = sqlite3VdbeCurrentAddr(v);
000727          sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
000728          aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
000729          if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
000730          aOp[0].p1 = iDb;
000731          aOp[1].p1 = iDb;
000732          aOp[2].p2 = iAddr+4;
000733          aOp[4].p1 = iDb;
000734          aOp[4].p3 = eAuto - 1;
000735          sqlite3VdbeUsesBtree(v, iDb);
000736        }
000737      }
000738      break;
000739    }
000740  #endif
000741  
000742    /*
000743    **  PRAGMA [schema.]incremental_vacuum(N)
000744    **
000745    ** Do N steps of incremental vacuuming on a database.
000746    */
000747  #ifndef SQLITE_OMIT_AUTOVACUUM
000748    case PragTyp_INCREMENTAL_VACUUM: {
000749      int iLimit, addr;
000750      if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
000751        iLimit = 0x7fffffff;
000752      }
000753      sqlite3BeginWriteOperation(pParse, 0, iDb);
000754      sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
000755      addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
000756      sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
000757      sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
000758      sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
000759      sqlite3VdbeJumpHere(v, addr);
000760      break;
000761    }
000762  #endif
000763  
000764  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
000765    /*
000766    **  PRAGMA [schema.]cache_size
000767    **  PRAGMA [schema.]cache_size=N
000768    **
000769    ** The first form reports the current local setting for the
000770    ** page cache size. The second form sets the local
000771    ** page cache size value.  If N is positive then that is the
000772    ** number of pages in the cache.  If N is negative, then the
000773    ** number of pages is adjusted so that the cache uses -N kibibytes
000774    ** of memory.
000775    */
000776    case PragTyp_CACHE_SIZE: {
000777      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000778      if( !zRight ){
000779        returnSingleInt(v, pDb->pSchema->cache_size);
000780      }else{
000781        int size = sqlite3Atoi(zRight);
000782        pDb->pSchema->cache_size = size;
000783        sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
000784      }
000785      break;
000786    }
000787  
000788    /*
000789    **  PRAGMA [schema.]cache_spill
000790    **  PRAGMA cache_spill=BOOLEAN
000791    **  PRAGMA [schema.]cache_spill=N
000792    **
000793    ** The first form reports the current local setting for the
000794    ** page cache spill size. The second form turns cache spill on
000795    ** or off.  When turnning cache spill on, the size is set to the
000796    ** current cache_size.  The third form sets a spill size that
000797    ** may be different form the cache size.
000798    ** If N is positive then that is the
000799    ** number of pages in the cache.  If N is negative, then the
000800    ** number of pages is adjusted so that the cache uses -N kibibytes
000801    ** of memory.
000802    **
000803    ** If the number of cache_spill pages is less then the number of
000804    ** cache_size pages, no spilling occurs until the page count exceeds
000805    ** the number of cache_size pages.
000806    **
000807    ** The cache_spill=BOOLEAN setting applies to all attached schemas,
000808    ** not just the schema specified.
000809    */
000810    case PragTyp_CACHE_SPILL: {
000811      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000812      if( !zRight ){
000813        returnSingleInt(v,
000814           (db->flags & SQLITE_CacheSpill)==0 ? 0 : 
000815              sqlite3BtreeSetSpillSize(pDb->pBt,0));
000816      }else{
000817        int size = 1;
000818        if( sqlite3GetInt32(zRight, &size) ){
000819          sqlite3BtreeSetSpillSize(pDb->pBt, size);
000820        }
000821        if( sqlite3GetBoolean(zRight, size!=0) ){
000822          db->flags |= SQLITE_CacheSpill;
000823        }else{
000824          db->flags &= ~(u64)SQLITE_CacheSpill;
000825        }
000826        setAllPagerFlags(db);
000827      }
000828      break;
000829    }
000830  
000831    /*
000832    **  PRAGMA [schema.]mmap_size(N)
000833    **
000834    ** Used to set mapping size limit. The mapping size limit is
000835    ** used to limit the aggregate size of all memory mapped regions of the
000836    ** database file. If this parameter is set to zero, then memory mapping
000837    ** is not used at all.  If N is negative, then the default memory map
000838    ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
000839    ** The parameter N is measured in bytes.
000840    **
000841    ** This value is advisory.  The underlying VFS is free to memory map
000842    ** as little or as much as it wants.  Except, if N is set to 0 then the
000843    ** upper layers will never invoke the xFetch interfaces to the VFS.
000844    */
000845    case PragTyp_MMAP_SIZE: {
000846      sqlite3_int64 sz;
000847  #if SQLITE_MAX_MMAP_SIZE>0
000848      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000849      if( zRight ){
000850        int ii;
000851        sqlite3DecOrHexToI64(zRight, &sz);
000852        if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
000853        if( pId2->n==0 ) db->szMmap = sz;
000854        for(ii=db->nDb-1; ii>=0; ii--){
000855          if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
000856            sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
000857          }
000858        }
000859      }
000860      sz = -1;
000861      rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
000862  #else
000863      sz = 0;
000864      rc = SQLITE_OK;
000865  #endif
000866      if( rc==SQLITE_OK ){
000867        returnSingleInt(v, sz);
000868      }else if( rc!=SQLITE_NOTFOUND ){
000869        pParse->nErr++;
000870        pParse->rc = rc;
000871      }
000872      break;
000873    }
000874  
000875    /*
000876    **   PRAGMA temp_store
000877    **   PRAGMA temp_store = "default"|"memory"|"file"
000878    **
000879    ** Return or set the local value of the temp_store flag.  Changing
000880    ** the local value does not make changes to the disk file and the default
000881    ** value will be restored the next time the database is opened.
000882    **
000883    ** Note that it is possible for the library compile-time options to
000884    ** override this setting
000885    */
000886    case PragTyp_TEMP_STORE: {
000887      if( !zRight ){
000888        returnSingleInt(v, db->temp_store);
000889      }else{
000890        changeTempStorage(pParse, zRight);
000891      }
000892      break;
000893    }
000894  
000895    /*
000896    **   PRAGMA temp_store_directory
000897    **   PRAGMA temp_store_directory = ""|"directory_name"
000898    **
000899    ** Return or set the local value of the temp_store_directory flag.  Changing
000900    ** the value sets a specific directory to be used for temporary files.
000901    ** Setting to a null string reverts to the default temporary directory search.
000902    ** If temporary directory is changed, then invalidateTempStorage.
000903    **
000904    */
000905    case PragTyp_TEMP_STORE_DIRECTORY: {
000906      if( !zRight ){
000907        returnSingleText(v, sqlite3_temp_directory);
000908      }else{
000909  #ifndef SQLITE_OMIT_WSD
000910        if( zRight[0] ){
000911          int res;
000912          rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
000913          if( rc!=SQLITE_OK || res==0 ){
000914            sqlite3ErrorMsg(pParse, "not a writable directory");
000915            goto pragma_out;
000916          }
000917        }
000918        if( SQLITE_TEMP_STORE==0
000919         || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
000920         || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
000921        ){
000922          invalidateTempStorage(pParse);
000923        }
000924        sqlite3_free(sqlite3_temp_directory);
000925        if( zRight[0] ){
000926          sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
000927        }else{
000928          sqlite3_temp_directory = 0;
000929        }
000930  #endif /* SQLITE_OMIT_WSD */
000931      }
000932      break;
000933    }
000934  
000935  #if SQLITE_OS_WIN
000936    /*
000937    **   PRAGMA data_store_directory
000938    **   PRAGMA data_store_directory = ""|"directory_name"
000939    **
000940    ** Return or set the local value of the data_store_directory flag.  Changing
000941    ** the value sets a specific directory to be used for database files that
000942    ** were specified with a relative pathname.  Setting to a null string reverts
000943    ** to the default database directory, which for database files specified with
000944    ** a relative path will probably be based on the current directory for the
000945    ** process.  Database file specified with an absolute path are not impacted
000946    ** by this setting, regardless of its value.
000947    **
000948    */
000949    case PragTyp_DATA_STORE_DIRECTORY: {
000950      if( !zRight ){
000951        returnSingleText(v, sqlite3_data_directory);
000952      }else{
000953  #ifndef SQLITE_OMIT_WSD
000954        if( zRight[0] ){
000955          int res;
000956          rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
000957          if( rc!=SQLITE_OK || res==0 ){
000958            sqlite3ErrorMsg(pParse, "not a writable directory");
000959            goto pragma_out;
000960          }
000961        }
000962        sqlite3_free(sqlite3_data_directory);
000963        if( zRight[0] ){
000964          sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
000965        }else{
000966          sqlite3_data_directory = 0;
000967        }
000968  #endif /* SQLITE_OMIT_WSD */
000969      }
000970      break;
000971    }
000972  #endif
000973  
000974  #if SQLITE_ENABLE_LOCKING_STYLE
000975    /*
000976    **   PRAGMA [schema.]lock_proxy_file
000977    **   PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
000978    **
000979    ** Return or set the value of the lock_proxy_file flag.  Changing
000980    ** the value sets a specific file to be used for database access locks.
000981    **
000982    */
000983    case PragTyp_LOCK_PROXY_FILE: {
000984      if( !zRight ){
000985        Pager *pPager = sqlite3BtreePager(pDb->pBt);
000986        char *proxy_file_path = NULL;
000987        sqlite3_file *pFile = sqlite3PagerFile(pPager);
000988        sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, 
000989                             &proxy_file_path);
000990        returnSingleText(v, proxy_file_path);
000991      }else{
000992        Pager *pPager = sqlite3BtreePager(pDb->pBt);
000993        sqlite3_file *pFile = sqlite3PagerFile(pPager);
000994        int res;
000995        if( zRight[0] ){
000996          res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
000997                                       zRight);
000998        } else {
000999          res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
001000                                       NULL);
001001        }
001002        if( res!=SQLITE_OK ){
001003          sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
001004          goto pragma_out;
001005        }
001006      }
001007      break;
001008    }
001009  #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
001010      
001011    /*
001012    **   PRAGMA [schema.]synchronous
001013    **   PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
001014    **
001015    ** Return or set the local value of the synchronous flag.  Changing
001016    ** the local value does not make changes to the disk file and the
001017    ** default value will be restored the next time the database is
001018    ** opened.
001019    */
001020    case PragTyp_SYNCHRONOUS: {
001021      if( !zRight ){
001022        returnSingleInt(v, pDb->safety_level-1);
001023      }else{
001024        if( !db->autoCommit ){
001025          sqlite3ErrorMsg(pParse, 
001026              "Safety level may not be changed inside a transaction");
001027        }else if( iDb!=1 ){
001028          int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
001029          if( iLevel==0 ) iLevel = 1;
001030          pDb->safety_level = iLevel;
001031          pDb->bSyncSet = 1;
001032          setAllPagerFlags(db);
001033        }
001034      }
001035      break;
001036    }
001037  #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
001038  
001039  #ifndef SQLITE_OMIT_FLAG_PRAGMAS
001040    case PragTyp_FLAG: {
001041      if( zRight==0 ){
001042        setPragmaResultColumnNames(v, pPragma);
001043        returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
001044      }else{
001045        u64 mask = pPragma->iArg;    /* Mask of bits to set or clear. */
001046        if( db->autoCommit==0 ){
001047          /* Foreign key support may not be enabled or disabled while not
001048          ** in auto-commit mode.  */
001049          mask &= ~(SQLITE_ForeignKeys);
001050        }
001051  #if SQLITE_USER_AUTHENTICATION
001052        if( db->auth.authLevel==UAUTH_User ){
001053          /* Do not allow non-admin users to modify the schema arbitrarily */
001054          mask &= ~(SQLITE_WriteSchema);
001055        }
001056  #endif
001057  
001058        if( sqlite3GetBoolean(zRight, 0) ){
001059          db->flags |= mask;
001060        }else{
001061          db->flags &= ~mask;
001062          if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
001063        }
001064  
001065        /* Many of the flag-pragmas modify the code generated by the SQL 
001066        ** compiler (eg. count_changes). So add an opcode to expire all
001067        ** compiled SQL statements after modifying a pragma value.
001068        */
001069        sqlite3VdbeAddOp0(v, OP_Expire);
001070        setAllPagerFlags(db);
001071      }
001072      break;
001073    }
001074  #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
001075  
001076  #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
001077    /*
001078    **   PRAGMA table_info(<table>)
001079    **
001080    ** Return a single row for each column of the named table. The columns of
001081    ** the returned data set are:
001082    **
001083    ** cid:        Column id (numbered from left to right, starting at 0)
001084    ** name:       Column name
001085    ** type:       Column declaration type.
001086    ** notnull:    True if 'NOT NULL' is part of column declaration
001087    ** dflt_value: The default value for the column, if any.
001088    ** pk:         Non-zero for PK fields.
001089    */
001090    case PragTyp_TABLE_INFO: if( zRight ){
001091      Table *pTab;
001092      pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
001093      if( pTab ){
001094        int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
001095        int i, k;
001096        int nHidden = 0;
001097        Column *pCol;
001098        Index *pPk = sqlite3PrimaryKeyIndex(pTab);
001099        pParse->nMem = 7;
001100        sqlite3CodeVerifySchema(pParse, iTabDb);
001101        sqlite3ViewGetColumnNames(pParse, pTab);
001102        for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
001103          int isHidden = 0;
001104          if( pCol->colFlags & COLFLAG_NOINSERT ){
001105            if( pPragma->iArg==0 ){
001106              nHidden++;
001107              continue;
001108            }
001109            if( pCol->colFlags & COLFLAG_VIRTUAL ){
001110              isHidden = 2;  /* GENERATED ALWAYS AS ... VIRTUAL */
001111            }else if( pCol->colFlags & COLFLAG_STORED ){
001112              isHidden = 3;  /* GENERATED ALWAYS AS ... STORED */
001113            }else{ assert( pCol->colFlags & COLFLAG_HIDDEN );
001114              isHidden = 1;  /* HIDDEN */
001115            }
001116          }
001117          if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
001118            k = 0;
001119          }else if( pPk==0 ){
001120            k = 1;
001121          }else{
001122            for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
001123          }
001124          assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN || isHidden>=2 );
001125          sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
001126                 i-nHidden,
001127                 pCol->zName,
001128                 sqlite3ColumnType(pCol,""),
001129                 pCol->notNull ? 1 : 0,
001130                 pCol->pDflt && isHidden<2 ? pCol->pDflt->u.zToken : 0,
001131                 k,
001132                 isHidden);
001133        }
001134      }
001135    }
001136    break;
001137  
001138  #ifdef SQLITE_DEBUG
001139    case PragTyp_STATS: {
001140      Index *pIdx;
001141      HashElem *i;
001142      pParse->nMem = 5;
001143      sqlite3CodeVerifySchema(pParse, iDb);
001144      for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
001145        Table *pTab = sqliteHashData(i);
001146        sqlite3VdbeMultiLoad(v, 1, "ssiii",
001147             pTab->zName,
001148             0,
001149             pTab->szTabRow,
001150             pTab->nRowLogEst,
001151             pTab->tabFlags);
001152        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
001153          sqlite3VdbeMultiLoad(v, 2, "siiiX",
001154             pIdx->zName,
001155             pIdx->szIdxRow,
001156             pIdx->aiRowLogEst[0],
001157             pIdx->hasStat1);
001158          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
001159        }
001160      }
001161    }
001162    break;
001163  #endif
001164  
001165    case PragTyp_INDEX_INFO: if( zRight ){
001166      Index *pIdx;
001167      Table *pTab;
001168      pIdx = sqlite3FindIndex(db, zRight, zDb);
001169      if( pIdx==0 ){
001170        /* If there is no index named zRight, check to see if there is a
001171        ** WITHOUT ROWID table named zRight, and if there is, show the
001172        ** structure of the PRIMARY KEY index for that table. */
001173        pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
001174        if( pTab && !HasRowid(pTab) ){
001175          pIdx = sqlite3PrimaryKeyIndex(pTab);
001176        }
001177      }
001178      if( pIdx ){
001179        int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
001180        int i;
001181        int mx;
001182        if( pPragma->iArg ){
001183          /* PRAGMA index_xinfo (newer version with more rows and columns) */
001184          mx = pIdx->nColumn;
001185          pParse->nMem = 6;
001186        }else{
001187          /* PRAGMA index_info (legacy version) */
001188          mx = pIdx->nKeyCol;
001189          pParse->nMem = 3;
001190        }
001191        pTab = pIdx->pTable;
001192        sqlite3CodeVerifySchema(pParse, iIdxDb);
001193        assert( pParse->nMem<=pPragma->nPragCName );
001194        for(i=0; i<mx; i++){
001195          i16 cnum = pIdx->aiColumn[i];
001196          sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
001197                               cnum<0 ? 0 : pTab->aCol[cnum].zName);
001198          if( pPragma->iArg ){
001199            sqlite3VdbeMultiLoad(v, 4, "isiX",
001200              pIdx->aSortOrder[i],
001201              pIdx->azColl[i],
001202              i<pIdx->nKeyCol);
001203          }
001204          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
001205        }
001206      }
001207    }
001208    break;
001209  
001210    case PragTyp_INDEX_LIST: if( zRight ){
001211      Index *pIdx;
001212      Table *pTab;
001213      int i;
001214      pTab = sqlite3FindTable(db, zRight, zDb);
001215      if( pTab ){
001216        int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
001217        pParse->nMem = 5;
001218        sqlite3CodeVerifySchema(pParse, iTabDb);
001219        for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
001220          const char *azOrigin[] = { "c", "u", "pk" };
001221          sqlite3VdbeMultiLoad(v, 1, "isisi",
001222             i,
001223             pIdx->zName,
001224             IsUniqueIndex(pIdx),
001225             azOrigin[pIdx->idxType],
001226             pIdx->pPartIdxWhere!=0);
001227        }
001228      }
001229    }
001230    break;
001231  
001232    case PragTyp_DATABASE_LIST: {
001233      int i;
001234      pParse->nMem = 3;
001235      for(i=0; i<db->nDb; i++){
001236        if( db->aDb[i].pBt==0 ) continue;
001237        assert( db->aDb[i].zDbSName!=0 );
001238        sqlite3VdbeMultiLoad(v, 1, "iss",
001239           i,
001240           db->aDb[i].zDbSName,
001241           sqlite3BtreeGetFilename(db->aDb[i].pBt));
001242      }
001243    }
001244    break;
001245  
001246    case PragTyp_COLLATION_LIST: {
001247      int i = 0;
001248      HashElem *p;
001249      pParse->nMem = 2;
001250      for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
001251        CollSeq *pColl = (CollSeq *)sqliteHashData(p);
001252        sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
001253      }
001254    }
001255    break;
001256  
001257  #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
001258    case PragTyp_FUNCTION_LIST: {
001259      int i;
001260      HashElem *j;
001261      FuncDef *p;
001262      pParse->nMem = 2;
001263      for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
001264        for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
001265          if( p->funcFlags & SQLITE_FUNC_INTERNAL ) continue;
001266          sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 1);
001267        }
001268      }
001269      for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
001270        p = (FuncDef*)sqliteHashData(j);
001271        sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 0);
001272      }
001273    }
001274    break;
001275  
001276  #ifndef SQLITE_OMIT_VIRTUALTABLE
001277    case PragTyp_MODULE_LIST: {
001278      HashElem *j;
001279      pParse->nMem = 1;
001280      for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
001281        Module *pMod = (Module*)sqliteHashData(j);
001282        sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
001283      }
001284    }
001285    break;
001286  #endif /* SQLITE_OMIT_VIRTUALTABLE */
001287  
001288    case PragTyp_PRAGMA_LIST: {
001289      int i;
001290      for(i=0; i<ArraySize(aPragmaName); i++){
001291        sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
001292      }
001293    }
001294    break;
001295  #endif /* SQLITE_INTROSPECTION_PRAGMAS */
001296  
001297  #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
001298  
001299  #ifndef SQLITE_OMIT_FOREIGN_KEY
001300    case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
001301      FKey *pFK;
001302      Table *pTab;
001303      pTab = sqlite3FindTable(db, zRight, zDb);
001304      if( pTab ){
001305        pFK = pTab->pFKey;
001306        if( pFK ){
001307          int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
001308          int i = 0; 
001309          pParse->nMem = 8;
001310          sqlite3CodeVerifySchema(pParse, iTabDb);
001311          while(pFK){
001312            int j;
001313            for(j=0; j<pFK->nCol; j++){
001314              sqlite3VdbeMultiLoad(v, 1, "iissssss",
001315                     i,
001316                     j,
001317                     pFK->zTo,
001318                     pTab->aCol[pFK->aCol[j].iFrom].zName,
001319                     pFK->aCol[j].zCol,
001320                     actionName(pFK->aAction[1]),  /* ON UPDATE */
001321                     actionName(pFK->aAction[0]),  /* ON DELETE */
001322                     "NONE");
001323            }
001324            ++i;
001325            pFK = pFK->pNextFrom;
001326          }
001327        }
001328      }
001329    }
001330    break;
001331  #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
001332  
001333  #ifndef SQLITE_OMIT_FOREIGN_KEY
001334  #ifndef SQLITE_OMIT_TRIGGER
001335    case PragTyp_FOREIGN_KEY_CHECK: {
001336      FKey *pFK;             /* A foreign key constraint */
001337      Table *pTab;           /* Child table contain "REFERENCES" keyword */
001338      Table *pParent;        /* Parent table that child points to */
001339      Index *pIdx;           /* Index in the parent table */
001340      int i;                 /* Loop counter:  Foreign key number for pTab */
001341      int j;                 /* Loop counter:  Field of the foreign key */
001342      HashElem *k;           /* Loop counter:  Next table in schema */
001343      int x;                 /* result variable */
001344      int regResult;         /* 3 registers to hold a result row */
001345      int regKey;            /* Register to hold key for checking the FK */
001346      int regRow;            /* Registers to hold a row from pTab */
001347      int addrTop;           /* Top of a loop checking foreign keys */
001348      int addrOk;            /* Jump here if the key is OK */
001349      int *aiCols;           /* child to parent column mapping */
001350  
001351      regResult = pParse->nMem+1;
001352      pParse->nMem += 4;
001353      regKey = ++pParse->nMem;
001354      regRow = ++pParse->nMem;
001355      k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
001356      while( k ){
001357        int iTabDb;
001358        if( zRight ){
001359          pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
001360          k = 0;
001361        }else{
001362          pTab = (Table*)sqliteHashData(k);
001363          k = sqliteHashNext(k);
001364        }
001365        if( pTab==0 || pTab->pFKey==0 ) continue;
001366        iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
001367        sqlite3CodeVerifySchema(pParse, iTabDb);
001368        sqlite3TableLock(pParse, iTabDb, pTab->tnum, 0, pTab->zName);
001369        if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
001370        sqlite3OpenTable(pParse, 0, iTabDb, pTab, OP_OpenRead);
001371        sqlite3VdbeLoadString(v, regResult, pTab->zName);
001372        for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
001373          pParent = sqlite3FindTable(db, pFK->zTo, zDb);
001374          if( pParent==0 ) continue;
001375          pIdx = 0;
001376          sqlite3TableLock(pParse, iTabDb, pParent->tnum, 0, pParent->zName);
001377          x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
001378          if( x==0 ){
001379            if( pIdx==0 ){
001380              sqlite3OpenTable(pParse, i, iTabDb, pParent, OP_OpenRead);
001381            }else{
001382              sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iTabDb);
001383              sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
001384            }
001385          }else{
001386            k = 0;
001387            break;
001388          }
001389        }
001390        assert( pParse->nErr>0 || pFK==0 );
001391        if( pFK ) break;
001392        if( pParse->nTab<i ) pParse->nTab = i;
001393        addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
001394        for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
001395          pParent = sqlite3FindTable(db, pFK->zTo, zDb);
001396          pIdx = 0;
001397          aiCols = 0;
001398          if( pParent ){
001399            x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
001400            assert( x==0 );
001401          }
001402          addrOk = sqlite3VdbeMakeLabel(pParse);
001403  
001404          /* Generate code to read the child key values into registers
001405          ** regRow..regRow+n. If any of the child key values are NULL, this 
001406          ** row cannot cause an FK violation. Jump directly to addrOk in 
001407          ** this case. */
001408          for(j=0; j<pFK->nCol; j++){
001409            int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
001410            sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
001411            sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
001412          }
001413  
001414          /* Generate code to query the parent index for a matching parent
001415          ** key. If a match is found, jump to addrOk. */
001416          if( pIdx ){
001417            sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
001418                sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
001419            sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
001420            VdbeCoverage(v);
001421          }else if( pParent ){
001422            int jmp = sqlite3VdbeCurrentAddr(v)+2;
001423            sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
001424            sqlite3VdbeGoto(v, addrOk);
001425            assert( pFK->nCol==1 );
001426          }
001427  
001428          /* Generate code to report an FK violation to the caller. */
001429          if( HasRowid(pTab) ){
001430            sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
001431          }else{
001432            sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
001433          }
001434          sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
001435          sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
001436          sqlite3VdbeResolveLabel(v, addrOk);
001437          sqlite3DbFree(db, aiCols);
001438        }
001439        sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
001440        sqlite3VdbeJumpHere(v, addrTop);
001441      }
001442    }
001443    break;
001444  #endif /* !defined(SQLITE_OMIT_TRIGGER) */
001445  #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
001446  
001447  #ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA
001448    /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
001449    ** used will be case sensitive or not depending on the RHS.
001450    */
001451    case PragTyp_CASE_SENSITIVE_LIKE: {
001452      if( zRight ){
001453        sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
001454      }
001455    }
001456    break;
001457  #endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */
001458  
001459  #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
001460  # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
001461  #endif
001462  
001463  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
001464    /*    PRAGMA integrity_check
001465    **    PRAGMA integrity_check(N)
001466    **    PRAGMA quick_check
001467    **    PRAGMA quick_check(N)
001468    **
001469    ** Verify the integrity of the database.
001470    **
001471    ** The "quick_check" is reduced version of 
001472    ** integrity_check designed to detect most database corruption
001473    ** without the overhead of cross-checking indexes.  Quick_check
001474    ** is linear time wherease integrity_check is O(NlogN).
001475    */
001476    case PragTyp_INTEGRITY_CHECK: {
001477      int i, j, addr, mxErr;
001478  
001479      int isQuick = (sqlite3Tolower(zLeft[0])=='q');
001480  
001481      /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
001482      ** then iDb is set to the index of the database identified by <db>.
001483      ** In this case, the integrity of database iDb only is verified by
001484      ** the VDBE created below.
001485      **
001486      ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
001487      ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
001488      ** to -1 here, to indicate that the VDBE should verify the integrity
001489      ** of all attached databases.  */
001490      assert( iDb>=0 );
001491      assert( iDb==0 || pId2->z );
001492      if( pId2->z==0 ) iDb = -1;
001493  
001494      /* Initialize the VDBE program */
001495      pParse->nMem = 6;
001496  
001497      /* Set the maximum error count */
001498      mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
001499      if( zRight ){
001500        sqlite3GetInt32(zRight, &mxErr);
001501        if( mxErr<=0 ){
001502          mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
001503        }
001504      }
001505      sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
001506  
001507      /* Do an integrity check on each database file */
001508      for(i=0; i<db->nDb; i++){
001509        HashElem *x;     /* For looping over tables in the schema */
001510        Hash *pTbls;     /* Set of all tables in the schema */
001511        int *aRoot;      /* Array of root page numbers of all btrees */
001512        int cnt = 0;     /* Number of entries in aRoot[] */
001513        int mxIdx = 0;   /* Maximum number of indexes for any table */
001514  
001515        if( OMIT_TEMPDB && i==1 ) continue;
001516        if( iDb>=0 && i!=iDb ) continue;
001517  
001518        sqlite3CodeVerifySchema(pParse, i);
001519  
001520        /* Do an integrity check of the B-Tree
001521        **
001522        ** Begin by finding the root pages numbers
001523        ** for all tables and indices in the database.
001524        */
001525        assert( sqlite3SchemaMutexHeld(db, i, 0) );
001526        pTbls = &db->aDb[i].pSchema->tblHash;
001527        for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
001528          Table *pTab = sqliteHashData(x);  /* Current table */
001529          Index *pIdx;                      /* An index on pTab */
001530          int nIdx;                         /* Number of indexes on pTab */
001531          if( HasRowid(pTab) ) cnt++;
001532          for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
001533          if( nIdx>mxIdx ) mxIdx = nIdx;
001534        }
001535        aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
001536        if( aRoot==0 ) break;
001537        for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
001538          Table *pTab = sqliteHashData(x);
001539          Index *pIdx;
001540          if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
001541          for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
001542            aRoot[++cnt] = pIdx->tnum;
001543          }
001544        }
001545        aRoot[0] = cnt;
001546  
001547        /* Make sure sufficient number of registers have been allocated */
001548        pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
001549        sqlite3ClearTempRegCache(pParse);
001550  
001551        /* Do the b-tree integrity checks */
001552        sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
001553        sqlite3VdbeChangeP5(v, (u8)i);
001554        addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
001555        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
001556           sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
001557           P4_DYNAMIC);
001558        sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
001559        integrityCheckResultRow(v);
001560        sqlite3VdbeJumpHere(v, addr);
001561  
001562        /* Make sure all the indices are constructed correctly.
001563        */
001564        for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
001565          Table *pTab = sqliteHashData(x);
001566          Index *pIdx, *pPk;
001567          Index *pPrior = 0;
001568          int loopTop;
001569          int iDataCur, iIdxCur;
001570          int r1 = -1;
001571  
001572          if( pTab->tnum<1 ) continue;  /* Skip VIEWs or VIRTUAL TABLEs */
001573          pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
001574          sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
001575                                     1, 0, &iDataCur, &iIdxCur);
001576          /* reg[7] counts the number of entries in the table.
001577          ** reg[8+i] counts the number of entries in the i-th index 
001578          */
001579          sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
001580          for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
001581            sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
001582          }
001583          assert( pParse->nMem>=8+j );
001584          assert( sqlite3NoTempsInRange(pParse,1,7+j) );
001585          sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
001586          loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
001587          if( !isQuick ){
001588            /* Sanity check on record header decoding */
001589            sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nNVCol-1,3);
001590            sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
001591          }
001592          /* Verify that all NOT NULL columns really are NOT NULL */
001593          for(j=0; j<pTab->nCol; j++){
001594            char *zErr;
001595            int jmp2;
001596            if( j==pTab->iPKey ) continue;
001597            if( pTab->aCol[j].notNull==0 ) continue;
001598            sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
001599            if( sqlite3VdbeGetOp(v,-1)->opcode==OP_Column ){
001600              sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
001601            }
001602            jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
001603            zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
001604                                pTab->aCol[j].zName);
001605            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
001606            integrityCheckResultRow(v);
001607            sqlite3VdbeJumpHere(v, jmp2);
001608          }
001609          /* Verify CHECK constraints */
001610          if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
001611            ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
001612            if( db->mallocFailed==0 ){
001613              int addrCkFault = sqlite3VdbeMakeLabel(pParse);
001614              int addrCkOk = sqlite3VdbeMakeLabel(pParse);
001615              char *zErr;
001616              int k;
001617              pParse->iSelfTab = iDataCur + 1;
001618              for(k=pCheck->nExpr-1; k>0; k--){
001619                sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
001620              }
001621              sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk, 
001622                  SQLITE_JUMPIFNULL);
001623              sqlite3VdbeResolveLabel(v, addrCkFault);
001624              pParse->iSelfTab = 0;
001625              zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
001626                  pTab->zName);
001627              sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
001628              integrityCheckResultRow(v);
001629              sqlite3VdbeResolveLabel(v, addrCkOk);
001630            }
001631            sqlite3ExprListDelete(db, pCheck);
001632          }
001633          if( !isQuick ){ /* Omit the remaining tests for quick_check */
001634            /* Validate index entries for the current row */
001635            for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
001636              int jmp2, jmp3, jmp4, jmp5;
001637              int ckUniq = sqlite3VdbeMakeLabel(pParse);
001638              if( pPk==pIdx ) continue;
001639              r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
001640                                           pPrior, r1);
001641              pPrior = pIdx;
001642              sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
001643              /* Verify that an index entry exists for the current table row */
001644              jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
001645                                          pIdx->nColumn); VdbeCoverage(v);
001646              sqlite3VdbeLoadString(v, 3, "row ");
001647              sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
001648              sqlite3VdbeLoadString(v, 4, " missing from index ");
001649              sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
001650              jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
001651              sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
001652              jmp4 = integrityCheckResultRow(v);
001653              sqlite3VdbeJumpHere(v, jmp2);
001654              /* For UNIQUE indexes, verify that only one entry exists with the
001655              ** current key.  The entry is unique if (1) any column is NULL
001656              ** or (2) the next entry has a different key */
001657              if( IsUniqueIndex(pIdx) ){
001658                int uniqOk = sqlite3VdbeMakeLabel(pParse);
001659                int jmp6;
001660                int kk;
001661                for(kk=0; kk<pIdx->nKeyCol; kk++){
001662                  int iCol = pIdx->aiColumn[kk];
001663                  assert( iCol!=XN_ROWID && iCol<pTab->nCol );
001664                  if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
001665                  sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
001666                  VdbeCoverage(v);
001667                }
001668                jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
001669                sqlite3VdbeGoto(v, uniqOk);
001670                sqlite3VdbeJumpHere(v, jmp6);
001671                sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
001672                                     pIdx->nKeyCol); VdbeCoverage(v);
001673                sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
001674                sqlite3VdbeGoto(v, jmp5);
001675                sqlite3VdbeResolveLabel(v, uniqOk);
001676              }
001677              sqlite3VdbeJumpHere(v, jmp4);
001678              sqlite3ResolvePartIdxLabel(pParse, jmp3);
001679            }
001680          }
001681          sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
001682          sqlite3VdbeJumpHere(v, loopTop-1);
001683  #ifndef SQLITE_OMIT_BTREECOUNT
001684          if( !isQuick ){
001685            sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
001686            for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
001687              if( pPk==pIdx ) continue;
001688              sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
001689              addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
001690              sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
001691              sqlite3VdbeLoadString(v, 4, pIdx->zName);
001692              sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
001693              integrityCheckResultRow(v);
001694              sqlite3VdbeJumpHere(v, addr);
001695            }
001696          }
001697  #endif /* SQLITE_OMIT_BTREECOUNT */
001698        } 
001699      }
001700      {
001701        static const int iLn = VDBE_OFFSET_LINENO(2);
001702        static const VdbeOpList endCode[] = {
001703          { OP_AddImm,      1, 0,        0},    /* 0 */
001704          { OP_IfNotZero,   1, 4,        0},    /* 1 */
001705          { OP_String8,     0, 3,        0},    /* 2 */
001706          { OP_ResultRow,   3, 1,        0},    /* 3 */
001707          { OP_Halt,        0, 0,        0},    /* 4 */
001708          { OP_String8,     0, 3,        0},    /* 5 */
001709          { OP_Goto,        0, 3,        0},    /* 6 */
001710        };
001711        VdbeOp *aOp;
001712  
001713        aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
001714        if( aOp ){
001715          aOp[0].p2 = 1-mxErr;
001716          aOp[2].p4type = P4_STATIC;
001717          aOp[2].p4.z = "ok";
001718          aOp[5].p4type = P4_STATIC;
001719          aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
001720        }
001721        sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
001722      }
001723    }
001724    break;
001725  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
001726  
001727  #ifndef SQLITE_OMIT_UTF16
001728    /*
001729    **   PRAGMA encoding
001730    **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
001731    **
001732    ** In its first form, this pragma returns the encoding of the main
001733    ** database. If the database is not initialized, it is initialized now.
001734    **
001735    ** The second form of this pragma is a no-op if the main database file
001736    ** has not already been initialized. In this case it sets the default
001737    ** encoding that will be used for the main database file if a new file
001738    ** is created. If an existing main database file is opened, then the
001739    ** default text encoding for the existing database is used.
001740    ** 
001741    ** In all cases new databases created using the ATTACH command are
001742    ** created to use the same default text encoding as the main database. If
001743    ** the main database has not been initialized and/or created when ATTACH
001744    ** is executed, this is done before the ATTACH operation.
001745    **
001746    ** In the second form this pragma sets the text encoding to be used in
001747    ** new database files created using this database handle. It is only
001748    ** useful if invoked immediately after the main database i
001749    */
001750    case PragTyp_ENCODING: {
001751      static const struct EncName {
001752        char *zName;
001753        u8 enc;
001754      } encnames[] = {
001755        { "UTF8",     SQLITE_UTF8        },
001756        { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
001757        { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
001758        { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
001759        { "UTF16le",  SQLITE_UTF16LE     },
001760        { "UTF16be",  SQLITE_UTF16BE     },
001761        { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
001762        { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
001763        { 0, 0 }
001764      };
001765      const struct EncName *pEnc;
001766      if( !zRight ){    /* "PRAGMA encoding" */
001767        if( sqlite3ReadSchema(pParse) ) goto pragma_out;
001768        assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
001769        assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
001770        assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
001771        returnSingleText(v, encnames[ENC(pParse->db)].zName);
001772      }else{                        /* "PRAGMA encoding = XXX" */
001773        /* Only change the value of sqlite.enc if the database handle is not
001774        ** initialized. If the main database exists, the new sqlite.enc value
001775        ** will be overwritten when the schema is next loaded. If it does not
001776        ** already exists, it will be created to use the new encoding value.
001777        */
001778        if( 
001779          !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
001780          DbHasProperty(db, 0, DB_Empty) 
001781        ){
001782          for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
001783            if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
001784              SCHEMA_ENC(db) = ENC(db) =
001785                  pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
001786              break;
001787            }
001788          }
001789          if( !pEnc->zName ){
001790            sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
001791          }
001792        }
001793      }
001794    }
001795    break;
001796  #endif /* SQLITE_OMIT_UTF16 */
001797  
001798  #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
001799    /*
001800    **   PRAGMA [schema.]schema_version
001801    **   PRAGMA [schema.]schema_version = <integer>
001802    **
001803    **   PRAGMA [schema.]user_version
001804    **   PRAGMA [schema.]user_version = <integer>
001805    **
001806    **   PRAGMA [schema.]freelist_count
001807    **
001808    **   PRAGMA [schema.]data_version
001809    **
001810    **   PRAGMA [schema.]application_id
001811    **   PRAGMA [schema.]application_id = <integer>
001812    **
001813    ** The pragma's schema_version and user_version are used to set or get
001814    ** the value of the schema-version and user-version, respectively. Both
001815    ** the schema-version and the user-version are 32-bit signed integers
001816    ** stored in the database header.
001817    **
001818    ** The schema-cookie is usually only manipulated internally by SQLite. It
001819    ** is incremented by SQLite whenever the database schema is modified (by
001820    ** creating or dropping a table or index). The schema version is used by
001821    ** SQLite each time a query is executed to ensure that the internal cache
001822    ** of the schema used when compiling the SQL query matches the schema of
001823    ** the database against which the compiled query is actually executed.
001824    ** Subverting this mechanism by using "PRAGMA schema_version" to modify
001825    ** the schema-version is potentially dangerous and may lead to program
001826    ** crashes or database corruption. Use with caution!
001827    **
001828    ** The user-version is not used internally by SQLite. It may be used by
001829    ** applications for any purpose.
001830    */
001831    case PragTyp_HEADER_VALUE: {
001832      int iCookie = pPragma->iArg;  /* Which cookie to read or write */
001833      sqlite3VdbeUsesBtree(v, iDb);
001834      if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
001835        /* Write the specified cookie value */
001836        static const VdbeOpList setCookie[] = {
001837          { OP_Transaction,    0,  1,  0},    /* 0 */
001838          { OP_SetCookie,      0,  0,  0},    /* 1 */
001839        };
001840        VdbeOp *aOp;
001841        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
001842        aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
001843        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
001844        aOp[0].p1 = iDb;
001845        aOp[1].p1 = iDb;
001846        aOp[1].p2 = iCookie;
001847        aOp[1].p3 = sqlite3Atoi(zRight);
001848      }else{
001849        /* Read the specified cookie value */
001850        static const VdbeOpList readCookie[] = {
001851          { OP_Transaction,     0,  0,  0},    /* 0 */
001852          { OP_ReadCookie,      0,  1,  0},    /* 1 */
001853          { OP_ResultRow,       1,  1,  0}
001854        };
001855        VdbeOp *aOp;
001856        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
001857        aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
001858        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
001859        aOp[0].p1 = iDb;
001860        aOp[1].p1 = iDb;
001861        aOp[1].p3 = iCookie;
001862        sqlite3VdbeReusable(v);
001863      }
001864    }
001865    break;
001866  #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
001867  
001868  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
001869    /*
001870    **   PRAGMA compile_options
001871    **
001872    ** Return the names of all compile-time options used in this build,
001873    ** one option per row.
001874    */
001875    case PragTyp_COMPILE_OPTIONS: {
001876      int i = 0;
001877      const char *zOpt;
001878      pParse->nMem = 1;
001879      while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
001880        sqlite3VdbeLoadString(v, 1, zOpt);
001881        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
001882      }
001883      sqlite3VdbeReusable(v);
001884    }
001885    break;
001886  #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
001887  
001888  #ifndef SQLITE_OMIT_WAL
001889    /*
001890    **   PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
001891    **
001892    ** Checkpoint the database.
001893    */
001894    case PragTyp_WAL_CHECKPOINT: {
001895      int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
001896      int eMode = SQLITE_CHECKPOINT_PASSIVE;
001897      if( zRight ){
001898        if( sqlite3StrICmp(zRight, "full")==0 ){
001899          eMode = SQLITE_CHECKPOINT_FULL;
001900        }else if( sqlite3StrICmp(zRight, "restart")==0 ){
001901          eMode = SQLITE_CHECKPOINT_RESTART;
001902        }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
001903          eMode = SQLITE_CHECKPOINT_TRUNCATE;
001904        }
001905      }
001906      pParse->nMem = 3;
001907      sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
001908      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
001909    }
001910    break;
001911  
001912    /*
001913    **   PRAGMA wal_autocheckpoint
001914    **   PRAGMA wal_autocheckpoint = N
001915    **
001916    ** Configure a database connection to automatically checkpoint a database
001917    ** after accumulating N frames in the log. Or query for the current value
001918    ** of N.
001919    */
001920    case PragTyp_WAL_AUTOCHECKPOINT: {
001921      if( zRight ){
001922        sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
001923      }
001924      returnSingleInt(v, 
001925         db->xWalCallback==sqlite3WalDefaultHook ? 
001926             SQLITE_PTR_TO_INT(db->pWalArg) : 0);
001927    }
001928    break;
001929  #endif
001930  
001931    /*
001932    **  PRAGMA shrink_memory
001933    **
001934    ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
001935    ** connection on which it is invoked to free up as much memory as it
001936    ** can, by calling sqlite3_db_release_memory().
001937    */
001938    case PragTyp_SHRINK_MEMORY: {
001939      sqlite3_db_release_memory(db);
001940      break;
001941    }
001942  
001943    /*
001944    **  PRAGMA optimize
001945    **  PRAGMA optimize(MASK)
001946    **  PRAGMA schema.optimize
001947    **  PRAGMA schema.optimize(MASK)
001948    **
001949    ** Attempt to optimize the database.  All schemas are optimized in the first
001950    ** two forms, and only the specified schema is optimized in the latter two.
001951    **
001952    ** The details of optimizations performed by this pragma are expected
001953    ** to change and improve over time.  Applications should anticipate that
001954    ** this pragma will perform new optimizations in future releases.
001955    **
001956    ** The optional argument is a bitmask of optimizations to perform:
001957    **
001958    **    0x0001    Debugging mode.  Do not actually perform any optimizations
001959    **              but instead return one line of text for each optimization
001960    **              that would have been done.  Off by default.
001961    **
001962    **    0x0002    Run ANALYZE on tables that might benefit.  On by default.
001963    **              See below for additional information.
001964    **
001965    **    0x0004    (Not yet implemented) Record usage and performance 
001966    **              information from the current session in the
001967    **              database file so that it will be available to "optimize"
001968    **              pragmas run by future database connections.
001969    **
001970    **    0x0008    (Not yet implemented) Create indexes that might have
001971    **              been helpful to recent queries
001972    **
001973    ** The default MASK is and always shall be 0xfffe.  0xfffe means perform all
001974    ** of the optimizations listed above except Debug Mode, including new
001975    ** optimizations that have not yet been invented.  If new optimizations are
001976    ** ever added that should be off by default, those off-by-default 
001977    ** optimizations will have bitmasks of 0x10000 or larger.
001978    **
001979    ** DETERMINATION OF WHEN TO RUN ANALYZE
001980    **
001981    ** In the current implementation, a table is analyzed if only if all of
001982    ** the following are true:
001983    **
001984    ** (1) MASK bit 0x02 is set.
001985    **
001986    ** (2) The query planner used sqlite_stat1-style statistics for one or
001987    **     more indexes of the table at some point during the lifetime of
001988    **     the current connection.
001989    **
001990    ** (3) One or more indexes of the table are currently unanalyzed OR
001991    **     the number of rows in the table has increased by 25 times or more
001992    **     since the last time ANALYZE was run.
001993    **
001994    ** The rules for when tables are analyzed are likely to change in
001995    ** future releases.
001996    */
001997    case PragTyp_OPTIMIZE: {
001998      int iDbLast;           /* Loop termination point for the schema loop */
001999      int iTabCur;           /* Cursor for a table whose size needs checking */
002000      HashElem *k;           /* Loop over tables of a schema */
002001      Schema *pSchema;       /* The current schema */
002002      Table *pTab;           /* A table in the schema */
002003      Index *pIdx;           /* An index of the table */
002004      LogEst szThreshold;    /* Size threshold above which reanalysis is needd */
002005      char *zSubSql;         /* SQL statement for the OP_SqlExec opcode */
002006      u32 opMask;            /* Mask of operations to perform */
002007  
002008      if( zRight ){
002009        opMask = (u32)sqlite3Atoi(zRight);
002010        if( (opMask & 0x02)==0 ) break;
002011      }else{
002012        opMask = 0xfffe;
002013      }
002014      iTabCur = pParse->nTab++;
002015      for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
002016        if( iDb==1 ) continue;
002017        sqlite3CodeVerifySchema(pParse, iDb);
002018        pSchema = db->aDb[iDb].pSchema;
002019        for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
002020          pTab = (Table*)sqliteHashData(k);
002021  
002022          /* If table pTab has not been used in a way that would benefit from
002023          ** having analysis statistics during the current session, then skip it.
002024          ** This also has the effect of skipping virtual tables and views */
002025          if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
002026  
002027          /* Reanalyze if the table is 25 times larger than the last analysis */
002028          szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
002029          for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
002030            if( !pIdx->hasStat1 ){
002031              szThreshold = 0; /* Always analyze if any index lacks statistics */
002032              break;
002033            }
002034          }
002035          if( szThreshold ){
002036            sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
002037            sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur, 
002038                           sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
002039            VdbeCoverage(v);
002040          }
002041          zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
002042                                   db->aDb[iDb].zDbSName, pTab->zName);
002043          if( opMask & 0x01 ){
002044            int r1 = sqlite3GetTempReg(pParse);
002045            sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
002046            sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
002047          }else{
002048            sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
002049          }
002050        }
002051      }
002052      sqlite3VdbeAddOp0(v, OP_Expire);
002053      break;
002054    }
002055  
002056    /*
002057    **   PRAGMA busy_timeout
002058    **   PRAGMA busy_timeout = N
002059    **
002060    ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
002061    ** if one is set.  If no busy handler or a different busy handler is set
002062    ** then 0 is returned.  Setting the busy_timeout to 0 or negative
002063    ** disables the timeout.
002064    */
002065    /*case PragTyp_BUSY_TIMEOUT*/ default: {
002066      assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
002067      if( zRight ){
002068        sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
002069      }
002070      returnSingleInt(v, db->busyTimeout);
002071      break;
002072    }
002073  
002074    /*
002075    **   PRAGMA soft_heap_limit
002076    **   PRAGMA soft_heap_limit = N
002077    **
002078    ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
002079    ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
002080    ** specified and is a non-negative integer.
002081    ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
002082    ** returns the same integer that would be returned by the
002083    ** sqlite3_soft_heap_limit64(-1) C-language function.
002084    */
002085    case PragTyp_SOFT_HEAP_LIMIT: {
002086      sqlite3_int64 N;
002087      if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
002088        sqlite3_soft_heap_limit64(N);
002089      }
002090      returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
002091      break;
002092    }
002093  
002094    /*
002095    **   PRAGMA hard_heap_limit
002096    **   PRAGMA hard_heap_limit = N
002097    **
002098    ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap
002099    ** limit.  The hard heap limit can be activated or lowered by this
002100    ** pragma, but not raised or deactivated.  Only the
002101    ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate
002102    ** the hard heap limit.  This allows an application to set a heap limit
002103    ** constraint that cannot be relaxed by an untrusted SQL script.
002104    */
002105    case PragTyp_HARD_HEAP_LIMIT: {
002106      sqlite3_int64 N;
002107      if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
002108        sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1);
002109        if( N>0 && (iPrior==0 || iPrior>N) ) sqlite3_hard_heap_limit64(N);
002110      }
002111      returnSingleInt(v, sqlite3_hard_heap_limit64(-1));
002112      break;
002113    }
002114  
002115    /*
002116    **   PRAGMA threads
002117    **   PRAGMA threads = N
002118    **
002119    ** Configure the maximum number of worker threads.  Return the new
002120    ** maximum, which might be less than requested.
002121    */
002122    case PragTyp_THREADS: {
002123      sqlite3_int64 N;
002124      if( zRight
002125       && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
002126       && N>=0
002127      ){
002128        sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
002129      }
002130      returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
002131      break;
002132    }
002133  
002134  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
002135    /*
002136    ** Report the current state of file logs for all databases
002137    */
002138    case PragTyp_LOCK_STATUS: {
002139      static const char *const azLockName[] = {
002140        "unlocked", "shared", "reserved", "pending", "exclusive"
002141      };
002142      int i;
002143      pParse->nMem = 2;
002144      for(i=0; i<db->nDb; i++){
002145        Btree *pBt;
002146        const char *zState = "unknown";
002147        int j;
002148        if( db->aDb[i].zDbSName==0 ) continue;
002149        pBt = db->aDb[i].pBt;
002150        if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
002151          zState = "closed";
002152        }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0, 
002153                                       SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
002154           zState = azLockName[j];
002155        }
002156        sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
002157      }
002158      break;
002159    }
002160  #endif
002161  
002162  #ifdef SQLITE_HAS_CODEC
002163    /* Pragma        iArg
002164    ** ----------   ------
002165    **  key           0
002166    **  rekey         1
002167    **  hexkey        2
002168    **  hexrekey      3
002169    **  textkey       4
002170    **  textrekey     5
002171    */
002172    case PragTyp_KEY: {
002173      if( zRight ){
002174        char zBuf[40];
002175        const char *zKey = zRight;
002176        int n;
002177        if( pPragma->iArg==2 || pPragma->iArg==3 ){
002178          u8 iByte;
002179          int i;
002180          for(i=0, iByte=0; i<sizeof(zBuf)*2 && sqlite3Isxdigit(zRight[i]); i++){
002181            iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
002182            if( (i&1)!=0 ) zBuf[i/2] = iByte;
002183          }
002184          zKey = zBuf;
002185          n = i/2;
002186        }else{
002187          n = pPragma->iArg<4 ? sqlite3Strlen30(zRight) : -1;
002188        }
002189        if( (pPragma->iArg & 1)==0 ){
002190          rc = sqlite3_key_v2(db, zDb, zKey, n);
002191        }else{
002192          rc = sqlite3_rekey_v2(db, zDb, zKey, n);
002193        }
002194        if( rc==SQLITE_OK && n!=0 ){
002195          sqlite3VdbeSetNumCols(v, 1);
002196          sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "ok", SQLITE_STATIC);
002197          returnSingleText(v, "ok");
002198        }
002199      }
002200      break;
002201    }
002202  #endif
002203  #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
002204    case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
002205  #ifdef SQLITE_HAS_CODEC
002206      if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
002207        sqlite3_activate_see(&zRight[4]);
002208      }
002209  #endif
002210  #ifdef SQLITE_ENABLE_CEROD
002211      if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
002212        sqlite3_activate_cerod(&zRight[6]);
002213      }
002214  #endif
002215    }
002216    break;
002217  #endif
002218  
002219    } /* End of the PRAGMA switch */
002220  
002221    /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
002222    ** purpose is to execute assert() statements to verify that if the
002223    ** PragFlg_NoColumns1 flag is set and the caller specified an argument
002224    ** to the PRAGMA, the implementation has not added any OP_ResultRow 
002225    ** instructions to the VM.  */
002226    if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
002227      sqlite3VdbeVerifyNoResultRow(v);
002228    }
002229  
002230  pragma_out:
002231    sqlite3DbFree(db, zLeft);
002232    sqlite3DbFree(db, zRight);
002233  }
002234  #ifndef SQLITE_OMIT_VIRTUALTABLE
002235  /*****************************************************************************
002236  ** Implementation of an eponymous virtual table that runs a pragma.
002237  **
002238  */
002239  typedef struct PragmaVtab PragmaVtab;
002240  typedef struct PragmaVtabCursor PragmaVtabCursor;
002241  struct PragmaVtab {
002242    sqlite3_vtab base;        /* Base class.  Must be first */
002243    sqlite3 *db;              /* The database connection to which it belongs */
002244    const PragmaName *pName;  /* Name of the pragma */
002245    u8 nHidden;               /* Number of hidden columns */
002246    u8 iHidden;               /* Index of the first hidden column */
002247  };
002248  struct PragmaVtabCursor {
002249    sqlite3_vtab_cursor base; /* Base class.  Must be first */
002250    sqlite3_stmt *pPragma;    /* The pragma statement to run */
002251    sqlite_int64 iRowid;      /* Current rowid */
002252    char *azArg[2];           /* Value of the argument and schema */
002253  };
002254  
002255  /* 
002256  ** Pragma virtual table module xConnect method.
002257  */
002258  static int pragmaVtabConnect(
002259    sqlite3 *db,
002260    void *pAux,
002261    int argc, const char *const*argv,
002262    sqlite3_vtab **ppVtab,
002263    char **pzErr
002264  ){
002265    const PragmaName *pPragma = (const PragmaName*)pAux;
002266    PragmaVtab *pTab = 0;
002267    int rc;
002268    int i, j;
002269    char cSep = '(';
002270    StrAccum acc;
002271    char zBuf[200];
002272  
002273    UNUSED_PARAMETER(argc);
002274    UNUSED_PARAMETER(argv);
002275    sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
002276    sqlite3_str_appendall(&acc, "CREATE TABLE x");
002277    for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
002278      sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]);
002279      cSep = ',';
002280    }
002281    if( i==0 ){
002282      sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
002283      i++;
002284    }
002285    j = 0;
002286    if( pPragma->mPragFlg & PragFlg_Result1 ){
002287      sqlite3_str_appendall(&acc, ",arg HIDDEN");
002288      j++;
002289    }
002290    if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
002291      sqlite3_str_appendall(&acc, ",schema HIDDEN");
002292      j++;
002293    }
002294    sqlite3_str_append(&acc, ")", 1);
002295    sqlite3StrAccumFinish(&acc);
002296    assert( strlen(zBuf) < sizeof(zBuf)-1 );
002297    rc = sqlite3_declare_vtab(db, zBuf);
002298    if( rc==SQLITE_OK ){
002299      pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
002300      if( pTab==0 ){
002301        rc = SQLITE_NOMEM;
002302      }else{
002303        memset(pTab, 0, sizeof(PragmaVtab));
002304        pTab->pName = pPragma;
002305        pTab->db = db;
002306        pTab->iHidden = i;
002307        pTab->nHidden = j;
002308      }
002309    }else{
002310      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
002311    }
002312  
002313    *ppVtab = (sqlite3_vtab*)pTab;
002314    return rc;
002315  }
002316  
002317  /* 
002318  ** Pragma virtual table module xDisconnect method.
002319  */
002320  static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
002321    PragmaVtab *pTab = (PragmaVtab*)pVtab;
002322    sqlite3_free(pTab);
002323    return SQLITE_OK;
002324  }
002325  
002326  /* Figure out the best index to use to search a pragma virtual table.
002327  **
002328  ** There are not really any index choices.  But we want to encourage the
002329  ** query planner to give == constraints on as many hidden parameters as
002330  ** possible, and especially on the first hidden parameter.  So return a
002331  ** high cost if hidden parameters are unconstrained.
002332  */
002333  static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
002334    PragmaVtab *pTab = (PragmaVtab*)tab;
002335    const struct sqlite3_index_constraint *pConstraint;
002336    int i, j;
002337    int seen[2];
002338  
002339    pIdxInfo->estimatedCost = (double)1;
002340    if( pTab->nHidden==0 ){ return SQLITE_OK; }
002341    pConstraint = pIdxInfo->aConstraint;
002342    seen[0] = 0;
002343    seen[1] = 0;
002344    for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
002345      if( pConstraint->usable==0 ) continue;
002346      if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
002347      if( pConstraint->iColumn < pTab->iHidden ) continue;
002348      j = pConstraint->iColumn - pTab->iHidden;
002349      assert( j < 2 );
002350      seen[j] = i+1;
002351    }
002352    if( seen[0]==0 ){
002353      pIdxInfo->estimatedCost = (double)2147483647;
002354      pIdxInfo->estimatedRows = 2147483647;
002355      return SQLITE_OK;
002356    }
002357    j = seen[0]-1;
002358    pIdxInfo->aConstraintUsage[j].argvIndex = 1;
002359    pIdxInfo->aConstraintUsage[j].omit = 1;
002360    if( seen[1]==0 ) return SQLITE_OK;
002361    pIdxInfo->estimatedCost = (double)20;
002362    pIdxInfo->estimatedRows = 20;
002363    j = seen[1]-1;
002364    pIdxInfo->aConstraintUsage[j].argvIndex = 2;
002365    pIdxInfo->aConstraintUsage[j].omit = 1;
002366    return SQLITE_OK;
002367  }
002368  
002369  /* Create a new cursor for the pragma virtual table */
002370  static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
002371    PragmaVtabCursor *pCsr;
002372    pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
002373    if( pCsr==0 ) return SQLITE_NOMEM;
002374    memset(pCsr, 0, sizeof(PragmaVtabCursor));
002375    pCsr->base.pVtab = pVtab;
002376    *ppCursor = &pCsr->base;
002377    return SQLITE_OK;
002378  }
002379  
002380  /* Clear all content from pragma virtual table cursor. */
002381  static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
002382    int i;
002383    sqlite3_finalize(pCsr->pPragma);
002384    pCsr->pPragma = 0;
002385    for(i=0; i<ArraySize(pCsr->azArg); i++){
002386      sqlite3_free(pCsr->azArg[i]);
002387      pCsr->azArg[i] = 0;
002388    }
002389  }
002390  
002391  /* Close a pragma virtual table cursor */
002392  static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
002393    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
002394    pragmaVtabCursorClear(pCsr);
002395    sqlite3_free(pCsr);
002396    return SQLITE_OK;
002397  }
002398  
002399  /* Advance the pragma virtual table cursor to the next row */
002400  static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
002401    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
002402    int rc = SQLITE_OK;
002403  
002404    /* Increment the xRowid value */
002405    pCsr->iRowid++;
002406    assert( pCsr->pPragma );
002407    if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
002408      rc = sqlite3_finalize(pCsr->pPragma);
002409      pCsr->pPragma = 0;
002410      pragmaVtabCursorClear(pCsr);
002411    }
002412    return rc;
002413  }
002414  
002415  /* 
002416  ** Pragma virtual table module xFilter method.
002417  */
002418  static int pragmaVtabFilter(
002419    sqlite3_vtab_cursor *pVtabCursor, 
002420    int idxNum, const char *idxStr,
002421    int argc, sqlite3_value **argv
002422  ){
002423    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
002424    PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
002425    int rc;
002426    int i, j;
002427    StrAccum acc;
002428    char *zSql;
002429  
002430    UNUSED_PARAMETER(idxNum);
002431    UNUSED_PARAMETER(idxStr);
002432    pragmaVtabCursorClear(pCsr);
002433    j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
002434    for(i=0; i<argc; i++, j++){
002435      const char *zText = (const char*)sqlite3_value_text(argv[i]);
002436      assert( j<ArraySize(pCsr->azArg) );
002437      assert( pCsr->azArg[j]==0 );
002438      if( zText ){
002439        pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
002440        if( pCsr->azArg[j]==0 ){
002441          return SQLITE_NOMEM;
002442        }
002443      }
002444    }
002445    sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
002446    sqlite3_str_appendall(&acc, "PRAGMA ");
002447    if( pCsr->azArg[1] ){
002448      sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
002449    }
002450    sqlite3_str_appendall(&acc, pTab->pName->zName);
002451    if( pCsr->azArg[0] ){
002452      sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
002453    }
002454    zSql = sqlite3StrAccumFinish(&acc);
002455    if( zSql==0 ) return SQLITE_NOMEM;
002456    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
002457    sqlite3_free(zSql);
002458    if( rc!=SQLITE_OK ){
002459      pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
002460      return rc;
002461    }
002462    return pragmaVtabNext(pVtabCursor);
002463  }
002464  
002465  /*
002466  ** Pragma virtual table module xEof method.
002467  */
002468  static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
002469    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
002470    return (pCsr->pPragma==0);
002471  }
002472  
002473  /* The xColumn method simply returns the corresponding column from
002474  ** the PRAGMA.  
002475  */
002476  static int pragmaVtabColumn(
002477    sqlite3_vtab_cursor *pVtabCursor, 
002478    sqlite3_context *ctx, 
002479    int i
002480  ){
002481    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
002482    PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
002483    if( i<pTab->iHidden ){
002484      sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
002485    }else{
002486      sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
002487    }
002488    return SQLITE_OK;
002489  }
002490  
002491  /* 
002492  ** Pragma virtual table module xRowid method.
002493  */
002494  static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
002495    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
002496    *p = pCsr->iRowid;
002497    return SQLITE_OK;
002498  }
002499  
002500  /* The pragma virtual table object */
002501  static const sqlite3_module pragmaVtabModule = {
002502    0,                           /* iVersion */
002503    0,                           /* xCreate - create a table */
002504    pragmaVtabConnect,           /* xConnect - connect to an existing table */
002505    pragmaVtabBestIndex,         /* xBestIndex - Determine search strategy */
002506    pragmaVtabDisconnect,        /* xDisconnect - Disconnect from a table */
002507    0,                           /* xDestroy - Drop a table */
002508    pragmaVtabOpen,              /* xOpen - open a cursor */
002509    pragmaVtabClose,             /* xClose - close a cursor */
002510    pragmaVtabFilter,            /* xFilter - configure scan constraints */
002511    pragmaVtabNext,              /* xNext - advance a cursor */
002512    pragmaVtabEof,               /* xEof */
002513    pragmaVtabColumn,            /* xColumn - read data */
002514    pragmaVtabRowid,             /* xRowid - read data */
002515    0,                           /* xUpdate - write data */
002516    0,                           /* xBegin - begin transaction */
002517    0,                           /* xSync - sync transaction */
002518    0,                           /* xCommit - commit transaction */
002519    0,                           /* xRollback - rollback transaction */
002520    0,                           /* xFindFunction - function overloading */
002521    0,                           /* xRename - rename the table */
002522    0,                           /* xSavepoint */
002523    0,                           /* xRelease */
002524    0,                           /* xRollbackTo */
002525    0                            /* xShadowName */
002526  };
002527  
002528  /*
002529  ** Check to see if zTabName is really the name of a pragma.  If it is,
002530  ** then register an eponymous virtual table for that pragma and return
002531  ** a pointer to the Module object for the new virtual table.
002532  */
002533  Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
002534    const PragmaName *pName;
002535    assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
002536    pName = pragmaLocate(zName+7);
002537    if( pName==0 ) return 0;
002538    if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
002539    assert( sqlite3HashFind(&db->aModule, zName)==0 );
002540    return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
002541  }
002542  
002543  #endif /* SQLITE_OMIT_VIRTUALTABLE */
002544  
002545  #endif /* SQLITE_OMIT_PRAGMA */