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      }
000648      if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
000649        /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
000650        iDb = 0;
000651        pId2->n = 1;
000652      }
000653      for(ii=db->nDb-1; ii>=0; ii--){
000654        if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
000655          sqlite3VdbeUsesBtree(v, ii);
000656          sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
000657        }
000658      }
000659      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
000660      break;
000661    }
000662  
000663    /*
000664    **  PRAGMA [schema.]journal_size_limit
000665    **  PRAGMA [schema.]journal_size_limit=N
000666    **
000667    ** Get or set the size limit on rollback journal files.
000668    */
000669    case PragTyp_JOURNAL_SIZE_LIMIT: {
000670      Pager *pPager = sqlite3BtreePager(pDb->pBt);
000671      i64 iLimit = -2;
000672      if( zRight ){
000673        sqlite3DecOrHexToI64(zRight, &iLimit);
000674        if( iLimit<-1 ) iLimit = -1;
000675      }
000676      iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
000677      returnSingleInt(v, iLimit);
000678      break;
000679    }
000680  
000681  #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
000682  
000683    /*
000684    **  PRAGMA [schema.]auto_vacuum
000685    **  PRAGMA [schema.]auto_vacuum=N
000686    **
000687    ** Get or set the value of the database 'auto-vacuum' parameter.
000688    ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
000689    */
000690  #ifndef SQLITE_OMIT_AUTOVACUUM
000691    case PragTyp_AUTO_VACUUM: {
000692      Btree *pBt = pDb->pBt;
000693      assert( pBt!=0 );
000694      if( !zRight ){
000695        returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
000696      }else{
000697        int eAuto = getAutoVacuum(zRight);
000698        assert( eAuto>=0 && eAuto<=2 );
000699        db->nextAutovac = (u8)eAuto;
000700        /* Call SetAutoVacuum() to set initialize the internal auto and
000701        ** incr-vacuum flags. This is required in case this connection
000702        ** creates the database file. It is important that it is created
000703        ** as an auto-vacuum capable db.
000704        */
000705        rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
000706        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
000707          /* When setting the auto_vacuum mode to either "full" or 
000708          ** "incremental", write the value of meta[6] in the database
000709          ** file. Before writing to meta[6], check that meta[3] indicates
000710          ** that this really is an auto-vacuum capable database.
000711          */
000712          static const int iLn = VDBE_OFFSET_LINENO(2);
000713          static const VdbeOpList setMeta6[] = {
000714            { OP_Transaction,    0,         1,                 0},    /* 0 */
000715            { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
000716            { OP_If,             1,         0,                 0},    /* 2 */
000717            { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
000718            { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 0},    /* 4 */
000719          };
000720          VdbeOp *aOp;
000721          int iAddr = sqlite3VdbeCurrentAddr(v);
000722          sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
000723          aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
000724          if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
000725          aOp[0].p1 = iDb;
000726          aOp[1].p1 = iDb;
000727          aOp[2].p2 = iAddr+4;
000728          aOp[4].p1 = iDb;
000729          aOp[4].p3 = eAuto - 1;
000730          sqlite3VdbeUsesBtree(v, iDb);
000731        }
000732      }
000733      break;
000734    }
000735  #endif
000736  
000737    /*
000738    **  PRAGMA [schema.]incremental_vacuum(N)
000739    **
000740    ** Do N steps of incremental vacuuming on a database.
000741    */
000742  #ifndef SQLITE_OMIT_AUTOVACUUM
000743    case PragTyp_INCREMENTAL_VACUUM: {
000744      int iLimit, addr;
000745      if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
000746        iLimit = 0x7fffffff;
000747      }
000748      sqlite3BeginWriteOperation(pParse, 0, iDb);
000749      sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
000750      addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
000751      sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
000752      sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
000753      sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
000754      sqlite3VdbeJumpHere(v, addr);
000755      break;
000756    }
000757  #endif
000758  
000759  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
000760    /*
000761    **  PRAGMA [schema.]cache_size
000762    **  PRAGMA [schema.]cache_size=N
000763    **
000764    ** The first form reports the current local setting for the
000765    ** page cache size. The second form sets the local
000766    ** page cache size value.  If N is positive then that is the
000767    ** number of pages in the cache.  If N is negative, then the
000768    ** number of pages is adjusted so that the cache uses -N kibibytes
000769    ** of memory.
000770    */
000771    case PragTyp_CACHE_SIZE: {
000772      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000773      if( !zRight ){
000774        returnSingleInt(v, pDb->pSchema->cache_size);
000775      }else{
000776        int size = sqlite3Atoi(zRight);
000777        pDb->pSchema->cache_size = size;
000778        sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
000779      }
000780      break;
000781    }
000782  
000783    /*
000784    **  PRAGMA [schema.]cache_spill
000785    **  PRAGMA cache_spill=BOOLEAN
000786    **  PRAGMA [schema.]cache_spill=N
000787    **
000788    ** The first form reports the current local setting for the
000789    ** page cache spill size. The second form turns cache spill on
000790    ** or off.  When turnning cache spill on, the size is set to the
000791    ** current cache_size.  The third form sets a spill size that
000792    ** may be different form the cache size.
000793    ** If N is positive then that is the
000794    ** number of pages in the cache.  If N is negative, then the
000795    ** number of pages is adjusted so that the cache uses -N kibibytes
000796    ** of memory.
000797    **
000798    ** If the number of cache_spill pages is less then the number of
000799    ** cache_size pages, no spilling occurs until the page count exceeds
000800    ** the number of cache_size pages.
000801    **
000802    ** The cache_spill=BOOLEAN setting applies to all attached schemas,
000803    ** not just the schema specified.
000804    */
000805    case PragTyp_CACHE_SPILL: {
000806      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000807      if( !zRight ){
000808        returnSingleInt(v,
000809           (db->flags & SQLITE_CacheSpill)==0 ? 0 : 
000810              sqlite3BtreeSetSpillSize(pDb->pBt,0));
000811      }else{
000812        int size = 1;
000813        if( sqlite3GetInt32(zRight, &size) ){
000814          sqlite3BtreeSetSpillSize(pDb->pBt, size);
000815        }
000816        if( sqlite3GetBoolean(zRight, size!=0) ){
000817          db->flags |= SQLITE_CacheSpill;
000818        }else{
000819          db->flags &= ~SQLITE_CacheSpill;
000820        }
000821        setAllPagerFlags(db);
000822      }
000823      break;
000824    }
000825  
000826    /*
000827    **  PRAGMA [schema.]mmap_size(N)
000828    **
000829    ** Used to set mapping size limit. The mapping size limit is
000830    ** used to limit the aggregate size of all memory mapped regions of the
000831    ** database file. If this parameter is set to zero, then memory mapping
000832    ** is not used at all.  If N is negative, then the default memory map
000833    ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
000834    ** The parameter N is measured in bytes.
000835    **
000836    ** This value is advisory.  The underlying VFS is free to memory map
000837    ** as little or as much as it wants.  Except, if N is set to 0 then the
000838    ** upper layers will never invoke the xFetch interfaces to the VFS.
000839    */
000840    case PragTyp_MMAP_SIZE: {
000841      sqlite3_int64 sz;
000842  #if SQLITE_MAX_MMAP_SIZE>0
000843      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000844      if( zRight ){
000845        int ii;
000846        sqlite3DecOrHexToI64(zRight, &sz);
000847        if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
000848        if( pId2->n==0 ) db->szMmap = sz;
000849        for(ii=db->nDb-1; ii>=0; ii--){
000850          if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
000851            sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
000852          }
000853        }
000854      }
000855      sz = -1;
000856      rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
000857  #else
000858      sz = 0;
000859      rc = SQLITE_OK;
000860  #endif
000861      if( rc==SQLITE_OK ){
000862        returnSingleInt(v, sz);
000863      }else if( rc!=SQLITE_NOTFOUND ){
000864        pParse->nErr++;
000865        pParse->rc = rc;
000866      }
000867      break;
000868    }
000869  
000870    /*
000871    **   PRAGMA temp_store
000872    **   PRAGMA temp_store = "default"|"memory"|"file"
000873    **
000874    ** Return or set the local value of the temp_store flag.  Changing
000875    ** the local value does not make changes to the disk file and the default
000876    ** value will be restored the next time the database is opened.
000877    **
000878    ** Note that it is possible for the library compile-time options to
000879    ** override this setting
000880    */
000881    case PragTyp_TEMP_STORE: {
000882      if( !zRight ){
000883        returnSingleInt(v, db->temp_store);
000884      }else{
000885        changeTempStorage(pParse, zRight);
000886      }
000887      break;
000888    }
000889  
000890    /*
000891    **   PRAGMA temp_store_directory
000892    **   PRAGMA temp_store_directory = ""|"directory_name"
000893    **
000894    ** Return or set the local value of the temp_store_directory flag.  Changing
000895    ** the value sets a specific directory to be used for temporary files.
000896    ** Setting to a null string reverts to the default temporary directory search.
000897    ** If temporary directory is changed, then invalidateTempStorage.
000898    **
000899    */
000900    case PragTyp_TEMP_STORE_DIRECTORY: {
000901      if( !zRight ){
000902        returnSingleText(v, sqlite3_temp_directory);
000903      }else{
000904  #ifndef SQLITE_OMIT_WSD
000905        if( zRight[0] ){
000906          int res;
000907          rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
000908          if( rc!=SQLITE_OK || res==0 ){
000909            sqlite3ErrorMsg(pParse, "not a writable directory");
000910            goto pragma_out;
000911          }
000912        }
000913        if( SQLITE_TEMP_STORE==0
000914         || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
000915         || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
000916        ){
000917          invalidateTempStorage(pParse);
000918        }
000919        sqlite3_free(sqlite3_temp_directory);
000920        if( zRight[0] ){
000921          sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
000922        }else{
000923          sqlite3_temp_directory = 0;
000924        }
000925  #endif /* SQLITE_OMIT_WSD */
000926      }
000927      break;
000928    }
000929  
000930  #if SQLITE_OS_WIN
000931    /*
000932    **   PRAGMA data_store_directory
000933    **   PRAGMA data_store_directory = ""|"directory_name"
000934    **
000935    ** Return or set the local value of the data_store_directory flag.  Changing
000936    ** the value sets a specific directory to be used for database files that
000937    ** were specified with a relative pathname.  Setting to a null string reverts
000938    ** to the default database directory, which for database files specified with
000939    ** a relative path will probably be based on the current directory for the
000940    ** process.  Database file specified with an absolute path are not impacted
000941    ** by this setting, regardless of its value.
000942    **
000943    */
000944    case PragTyp_DATA_STORE_DIRECTORY: {
000945      if( !zRight ){
000946        returnSingleText(v, sqlite3_data_directory);
000947      }else{
000948  #ifndef SQLITE_OMIT_WSD
000949        if( zRight[0] ){
000950          int res;
000951          rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
000952          if( rc!=SQLITE_OK || res==0 ){
000953            sqlite3ErrorMsg(pParse, "not a writable directory");
000954            goto pragma_out;
000955          }
000956        }
000957        sqlite3_free(sqlite3_data_directory);
000958        if( zRight[0] ){
000959          sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
000960        }else{
000961          sqlite3_data_directory = 0;
000962        }
000963  #endif /* SQLITE_OMIT_WSD */
000964      }
000965      break;
000966    }
000967  #endif
000968  
000969  #if SQLITE_ENABLE_LOCKING_STYLE
000970    /*
000971    **   PRAGMA [schema.]lock_proxy_file
000972    **   PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
000973    **
000974    ** Return or set the value of the lock_proxy_file flag.  Changing
000975    ** the value sets a specific file to be used for database access locks.
000976    **
000977    */
000978    case PragTyp_LOCK_PROXY_FILE: {
000979      if( !zRight ){
000980        Pager *pPager = sqlite3BtreePager(pDb->pBt);
000981        char *proxy_file_path = NULL;
000982        sqlite3_file *pFile = sqlite3PagerFile(pPager);
000983        sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, 
000984                             &proxy_file_path);
000985        returnSingleText(v, proxy_file_path);
000986      }else{
000987        Pager *pPager = sqlite3BtreePager(pDb->pBt);
000988        sqlite3_file *pFile = sqlite3PagerFile(pPager);
000989        int res;
000990        if( zRight[0] ){
000991          res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
000992                                       zRight);
000993        } else {
000994          res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
000995                                       NULL);
000996        }
000997        if( res!=SQLITE_OK ){
000998          sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
000999          goto pragma_out;
001000        }
001001      }
001002      break;
001003    }
001004  #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
001005      
001006    /*
001007    **   PRAGMA [schema.]synchronous
001008    **   PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
001009    **
001010    ** Return or set the local value of the synchronous flag.  Changing
001011    ** the local value does not make changes to the disk file and the
001012    ** default value will be restored the next time the database is
001013    ** opened.
001014    */
001015    case PragTyp_SYNCHRONOUS: {
001016      if( !zRight ){
001017        returnSingleInt(v, pDb->safety_level-1);
001018      }else{
001019        if( !db->autoCommit ){
001020          sqlite3ErrorMsg(pParse, 
001021              "Safety level may not be changed inside a transaction");
001022        }else if( iDb!=1 ){
001023          int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
001024          if( iLevel==0 ) iLevel = 1;
001025          pDb->safety_level = iLevel;
001026          pDb->bSyncSet = 1;
001027          setAllPagerFlags(db);
001028        }
001029      }
001030      break;
001031    }
001032  #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
001033  
001034  #ifndef SQLITE_OMIT_FLAG_PRAGMAS
001035    case PragTyp_FLAG: {
001036      if( zRight==0 ){
001037        setPragmaResultColumnNames(v, pPragma);
001038        returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
001039      }else{
001040        int mask = pPragma->iArg;    /* Mask of bits to set or clear. */
001041        if( db->autoCommit==0 ){
001042          /* Foreign key support may not be enabled or disabled while not
001043          ** in auto-commit mode.  */
001044          mask &= ~(SQLITE_ForeignKeys);
001045        }
001046  #if SQLITE_USER_AUTHENTICATION
001047        if( db->auth.authLevel==UAUTH_User ){
001048          /* Do not allow non-admin users to modify the schema arbitrarily */
001049          mask &= ~(SQLITE_WriteSchema);
001050        }
001051  #endif
001052  
001053        if( sqlite3GetBoolean(zRight, 0) ){
001054          db->flags |= mask;
001055        }else{
001056          db->flags &= ~mask;
001057          if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
001058        }
001059  
001060        /* Many of the flag-pragmas modify the code generated by the SQL 
001061        ** compiler (eg. count_changes). So add an opcode to expire all
001062        ** compiled SQL statements after modifying a pragma value.
001063        */
001064        sqlite3VdbeAddOp0(v, OP_Expire);
001065        setAllPagerFlags(db);
001066      }
001067      break;
001068    }
001069  #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
001070  
001071  #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
001072    /*
001073    **   PRAGMA table_info(<table>)
001074    **
001075    ** Return a single row for each column of the named table. The columns of
001076    ** the returned data set are:
001077    **
001078    ** cid:        Column id (numbered from left to right, starting at 0)
001079    ** name:       Column name
001080    ** type:       Column declaration type.
001081    ** notnull:    True if 'NOT NULL' is part of column declaration
001082    ** dflt_value: The default value for the column, if any.
001083    ** pk:         Non-zero for PK fields.
001084    */
001085    case PragTyp_TABLE_INFO: if( zRight ){
001086      Table *pTab;
001087      pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
001088      if( pTab ){
001089        int i, k;
001090        int nHidden = 0;
001091        Column *pCol;
001092        Index *pPk = sqlite3PrimaryKeyIndex(pTab);
001093        pParse->nMem = 6;
001094        sqlite3CodeVerifySchema(pParse, iDb);
001095        sqlite3ViewGetColumnNames(pParse, pTab);
001096        for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
001097          if( IsHiddenColumn(pCol) ){
001098            nHidden++;
001099            continue;
001100          }
001101          if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
001102            k = 0;
001103          }else if( pPk==0 ){
001104            k = 1;
001105          }else{
001106            for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
001107          }
001108          assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
001109          sqlite3VdbeMultiLoad(v, 1, "issisi",
001110                 i-nHidden,
001111                 pCol->zName,
001112                 sqlite3ColumnType(pCol,""),
001113                 pCol->notNull ? 1 : 0,
001114                 pCol->pDflt ? pCol->pDflt->u.zToken : 0,
001115                 k);
001116        }
001117      }
001118    }
001119    break;
001120  
001121  #ifdef SQLITE_DEBUG
001122    case PragTyp_STATS: {
001123      Index *pIdx;
001124      HashElem *i;
001125      pParse->nMem = 5;
001126      sqlite3CodeVerifySchema(pParse, iDb);
001127      for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
001128        Table *pTab = sqliteHashData(i);
001129        sqlite3VdbeMultiLoad(v, 1, "ssiii",
001130             pTab->zName,
001131             0,
001132             pTab->szTabRow,
001133             pTab->nRowLogEst,
001134             pTab->tabFlags);
001135        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
001136          sqlite3VdbeMultiLoad(v, 2, "siiiX",
001137             pIdx->zName,
001138             pIdx->szIdxRow,
001139             pIdx->aiRowLogEst[0],
001140             pIdx->hasStat1);
001141          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
001142        }
001143      }
001144    }
001145    break;
001146  #endif
001147  
001148    case PragTyp_INDEX_INFO: if( zRight ){
001149      Index *pIdx;
001150      Table *pTab;
001151      pIdx = sqlite3FindIndex(db, zRight, zDb);
001152      if( pIdx ){
001153        int i;
001154        int mx;
001155        if( pPragma->iArg ){
001156          /* PRAGMA index_xinfo (newer version with more rows and columns) */
001157          mx = pIdx->nColumn;
001158          pParse->nMem = 6;
001159        }else{
001160          /* PRAGMA index_info (legacy version) */
001161          mx = pIdx->nKeyCol;
001162          pParse->nMem = 3;
001163        }
001164        pTab = pIdx->pTable;
001165        sqlite3CodeVerifySchema(pParse, iDb);
001166        assert( pParse->nMem<=pPragma->nPragCName );
001167        for(i=0; i<mx; i++){
001168          i16 cnum = pIdx->aiColumn[i];
001169          sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
001170                               cnum<0 ? 0 : pTab->aCol[cnum].zName);
001171          if( pPragma->iArg ){
001172            sqlite3VdbeMultiLoad(v, 4, "isiX",
001173              pIdx->aSortOrder[i],
001174              pIdx->azColl[i],
001175              i<pIdx->nKeyCol);
001176          }
001177          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
001178        }
001179      }
001180    }
001181    break;
001182  
001183    case PragTyp_INDEX_LIST: if( zRight ){
001184      Index *pIdx;
001185      Table *pTab;
001186      int i;
001187      pTab = sqlite3FindTable(db, zRight, zDb);
001188      if( pTab ){
001189        pParse->nMem = 5;
001190        sqlite3CodeVerifySchema(pParse, iDb);
001191        for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
001192          const char *azOrigin[] = { "c", "u", "pk" };
001193          sqlite3VdbeMultiLoad(v, 1, "isisi",
001194             i,
001195             pIdx->zName,
001196             IsUniqueIndex(pIdx),
001197             azOrigin[pIdx->idxType],
001198             pIdx->pPartIdxWhere!=0);
001199        }
001200      }
001201    }
001202    break;
001203  
001204    case PragTyp_DATABASE_LIST: {
001205      int i;
001206      pParse->nMem = 3;
001207      for(i=0; i<db->nDb; i++){
001208        if( db->aDb[i].pBt==0 ) continue;
001209        assert( db->aDb[i].zDbSName!=0 );
001210        sqlite3VdbeMultiLoad(v, 1, "iss",
001211           i,
001212           db->aDb[i].zDbSName,
001213           sqlite3BtreeGetFilename(db->aDb[i].pBt));
001214      }
001215    }
001216    break;
001217  
001218    case PragTyp_COLLATION_LIST: {
001219      int i = 0;
001220      HashElem *p;
001221      pParse->nMem = 2;
001222      for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
001223        CollSeq *pColl = (CollSeq *)sqliteHashData(p);
001224        sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
001225      }
001226    }
001227    break;
001228  
001229  #ifdef SQLITE_INTROSPECTION_PRAGMAS
001230    case PragTyp_FUNCTION_LIST: {
001231      int i;
001232      HashElem *j;
001233      FuncDef *p;
001234      pParse->nMem = 2;
001235      for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
001236        for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
001237          sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 1);
001238        }
001239      }
001240      for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
001241        p = (FuncDef*)sqliteHashData(j);
001242        sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 0);
001243      }
001244    }
001245    break;
001246  
001247  #ifndef SQLITE_OMIT_VIRTUALTABLE
001248    case PragTyp_MODULE_LIST: {
001249      HashElem *j;
001250      pParse->nMem = 1;
001251      for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
001252        Module *pMod = (Module*)sqliteHashData(j);
001253        sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
001254      }
001255    }
001256    break;
001257  #endif /* SQLITE_OMIT_VIRTUALTABLE */
001258  
001259    case PragTyp_PRAGMA_LIST: {
001260      int i;
001261      for(i=0; i<ArraySize(aPragmaName); i++){
001262        sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
001263      }
001264    }
001265    break;
001266  #endif /* SQLITE_INTROSPECTION_PRAGMAS */
001267  
001268  #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
001269  
001270  #ifndef SQLITE_OMIT_FOREIGN_KEY
001271    case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
001272      FKey *pFK;
001273      Table *pTab;
001274      pTab = sqlite3FindTable(db, zRight, zDb);
001275      if( pTab ){
001276        pFK = pTab->pFKey;
001277        if( pFK ){
001278          int i = 0; 
001279          pParse->nMem = 8;
001280          sqlite3CodeVerifySchema(pParse, iDb);
001281          while(pFK){
001282            int j;
001283            for(j=0; j<pFK->nCol; j++){
001284              sqlite3VdbeMultiLoad(v, 1, "iissssss",
001285                     i,
001286                     j,
001287                     pFK->zTo,
001288                     pTab->aCol[pFK->aCol[j].iFrom].zName,
001289                     pFK->aCol[j].zCol,
001290                     actionName(pFK->aAction[1]),  /* ON UPDATE */
001291                     actionName(pFK->aAction[0]),  /* ON DELETE */
001292                     "NONE");
001293            }
001294            ++i;
001295            pFK = pFK->pNextFrom;
001296          }
001297        }
001298      }
001299    }
001300    break;
001301  #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
001302  
001303  #ifndef SQLITE_OMIT_FOREIGN_KEY
001304  #ifndef SQLITE_OMIT_TRIGGER
001305    case PragTyp_FOREIGN_KEY_CHECK: {
001306      FKey *pFK;             /* A foreign key constraint */
001307      Table *pTab;           /* Child table contain "REFERENCES" keyword */
001308      Table *pParent;        /* Parent table that child points to */
001309      Index *pIdx;           /* Index in the parent table */
001310      int i;                 /* Loop counter:  Foreign key number for pTab */
001311      int j;                 /* Loop counter:  Field of the foreign key */
001312      HashElem *k;           /* Loop counter:  Next table in schema */
001313      int x;                 /* result variable */
001314      int regResult;         /* 3 registers to hold a result row */
001315      int regKey;            /* Register to hold key for checking the FK */
001316      int regRow;            /* Registers to hold a row from pTab */
001317      int addrTop;           /* Top of a loop checking foreign keys */
001318      int addrOk;            /* Jump here if the key is OK */
001319      int *aiCols;           /* child to parent column mapping */
001320  
001321      regResult = pParse->nMem+1;
001322      pParse->nMem += 4;
001323      regKey = ++pParse->nMem;
001324      regRow = ++pParse->nMem;
001325      sqlite3CodeVerifySchema(pParse, iDb);
001326      k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
001327      while( k ){
001328        if( zRight ){
001329          pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
001330          k = 0;
001331        }else{
001332          pTab = (Table*)sqliteHashData(k);
001333          k = sqliteHashNext(k);
001334        }
001335        if( pTab==0 || pTab->pFKey==0 ) continue;
001336        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
001337        if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
001338        sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
001339        sqlite3VdbeLoadString(v, regResult, pTab->zName);
001340        for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
001341          pParent = sqlite3FindTable(db, pFK->zTo, zDb);
001342          if( pParent==0 ) continue;
001343          pIdx = 0;
001344          sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
001345          x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
001346          if( x==0 ){
001347            if( pIdx==0 ){
001348              sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
001349            }else{
001350              sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
001351              sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
001352            }
001353          }else{
001354            k = 0;
001355            break;
001356          }
001357        }
001358        assert( pParse->nErr>0 || pFK==0 );
001359        if( pFK ) break;
001360        if( pParse->nTab<i ) pParse->nTab = i;
001361        addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
001362        for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
001363          pParent = sqlite3FindTable(db, pFK->zTo, zDb);
001364          pIdx = 0;
001365          aiCols = 0;
001366          if( pParent ){
001367            x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
001368            assert( x==0 );
001369          }
001370          addrOk = sqlite3VdbeMakeLabel(v);
001371  
001372          /* Generate code to read the child key values into registers
001373          ** regRow..regRow+n. If any of the child key values are NULL, this 
001374          ** row cannot cause an FK violation. Jump directly to addrOk in 
001375          ** this case. */
001376          for(j=0; j<pFK->nCol; j++){
001377            int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
001378            sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
001379            sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
001380          }
001381  
001382          /* Generate code to query the parent index for a matching parent
001383          ** key. If a match is found, jump to addrOk. */
001384          if( pIdx ){
001385            sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
001386                sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
001387            sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
001388            VdbeCoverage(v);
001389          }else if( pParent ){
001390            int jmp = sqlite3VdbeCurrentAddr(v)+2;
001391            sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
001392            sqlite3VdbeGoto(v, addrOk);
001393            assert( pFK->nCol==1 );
001394          }
001395  
001396          /* Generate code to report an FK violation to the caller. */
001397          if( HasRowid(pTab) ){
001398            sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
001399          }else{
001400            sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
001401          }
001402          sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
001403          sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
001404          sqlite3VdbeResolveLabel(v, addrOk);
001405          sqlite3DbFree(db, aiCols);
001406        }
001407        sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
001408        sqlite3VdbeJumpHere(v, addrTop);
001409      }
001410    }
001411    break;
001412  #endif /* !defined(SQLITE_OMIT_TRIGGER) */
001413  #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
001414  
001415  #ifndef NDEBUG
001416    case PragTyp_PARSER_TRACE: {
001417      if( zRight ){
001418        if( sqlite3GetBoolean(zRight, 0) ){
001419          sqlite3ParserTrace(stdout, "parser: ");
001420        }else{
001421          sqlite3ParserTrace(0, 0);
001422        }
001423      }
001424    }
001425    break;
001426  #endif
001427  
001428    /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
001429    ** used will be case sensitive or not depending on the RHS.
001430    */
001431    case PragTyp_CASE_SENSITIVE_LIKE: {
001432      if( zRight ){
001433        sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
001434      }
001435    }
001436    break;
001437  
001438  #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
001439  # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
001440  #endif
001441  
001442  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
001443    /*    PRAGMA integrity_check
001444    **    PRAGMA integrity_check(N)
001445    **    PRAGMA quick_check
001446    **    PRAGMA quick_check(N)
001447    **
001448    ** Verify the integrity of the database.
001449    **
001450    ** The "quick_check" is reduced version of 
001451    ** integrity_check designed to detect most database corruption
001452    ** without the overhead of cross-checking indexes.  Quick_check
001453    ** is linear time wherease integrity_check is O(NlogN).
001454    */
001455    case PragTyp_INTEGRITY_CHECK: {
001456      int i, j, addr, mxErr;
001457  
001458      int isQuick = (sqlite3Tolower(zLeft[0])=='q');
001459  
001460      /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
001461      ** then iDb is set to the index of the database identified by <db>.
001462      ** In this case, the integrity of database iDb only is verified by
001463      ** the VDBE created below.
001464      **
001465      ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
001466      ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
001467      ** to -1 here, to indicate that the VDBE should verify the integrity
001468      ** of all attached databases.  */
001469      assert( iDb>=0 );
001470      assert( iDb==0 || pId2->z );
001471      if( pId2->z==0 ) iDb = -1;
001472  
001473      /* Initialize the VDBE program */
001474      pParse->nMem = 6;
001475  
001476      /* Set the maximum error count */
001477      mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
001478      if( zRight ){
001479        sqlite3GetInt32(zRight, &mxErr);
001480        if( mxErr<=0 ){
001481          mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
001482        }
001483      }
001484      sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
001485  
001486      /* Do an integrity check on each database file */
001487      for(i=0; i<db->nDb; i++){
001488        HashElem *x;     /* For looping over tables in the schema */
001489        Hash *pTbls;     /* Set of all tables in the schema */
001490        int *aRoot;      /* Array of root page numbers of all btrees */
001491        int cnt = 0;     /* Number of entries in aRoot[] */
001492        int mxIdx = 0;   /* Maximum number of indexes for any table */
001493  
001494        if( OMIT_TEMPDB && i==1 ) continue;
001495        if( iDb>=0 && i!=iDb ) continue;
001496  
001497        sqlite3CodeVerifySchema(pParse, i);
001498  
001499        /* Do an integrity check of the B-Tree
001500        **
001501        ** Begin by finding the root pages numbers
001502        ** for all tables and indices in the database.
001503        */
001504        assert( sqlite3SchemaMutexHeld(db, i, 0) );
001505        pTbls = &db->aDb[i].pSchema->tblHash;
001506        for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
001507          Table *pTab = sqliteHashData(x);  /* Current table */
001508          Index *pIdx;                      /* An index on pTab */
001509          int nIdx;                         /* Number of indexes on pTab */
001510          if( HasRowid(pTab) ) cnt++;
001511          for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
001512          if( nIdx>mxIdx ) mxIdx = nIdx;
001513        }
001514        aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
001515        if( aRoot==0 ) break;
001516        for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
001517          Table *pTab = sqliteHashData(x);
001518          Index *pIdx;
001519          if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
001520          for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
001521            aRoot[++cnt] = pIdx->tnum;
001522          }
001523        }
001524        aRoot[0] = cnt;
001525  
001526        /* Make sure sufficient number of registers have been allocated */
001527        pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
001528        sqlite3ClearTempRegCache(pParse);
001529  
001530        /* Do the b-tree integrity checks */
001531        sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
001532        sqlite3VdbeChangeP5(v, (u8)i);
001533        addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
001534        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
001535           sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
001536           P4_DYNAMIC);
001537        sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
001538        integrityCheckResultRow(v);
001539        sqlite3VdbeJumpHere(v, addr);
001540  
001541        /* Make sure all the indices are constructed correctly.
001542        */
001543        for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
001544          Table *pTab = sqliteHashData(x);
001545          Index *pIdx, *pPk;
001546          Index *pPrior = 0;
001547          int loopTop;
001548          int iDataCur, iIdxCur;
001549          int r1 = -1;
001550  
001551          if( pTab->tnum<1 ) continue;  /* Skip VIEWs or VIRTUAL TABLEs */
001552          pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
001553          sqlite3ExprCacheClear(pParse);
001554          sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
001555                                     1, 0, &iDataCur, &iIdxCur);
001556          /* reg[7] counts the number of entries in the table.
001557          ** reg[8+i] counts the number of entries in the i-th index 
001558          */
001559          sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
001560          for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
001561            sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
001562          }
001563          assert( pParse->nMem>=8+j );
001564          assert( sqlite3NoTempsInRange(pParse,1,7+j) );
001565          sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
001566          loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
001567          /* Verify that all NOT NULL columns really are NOT NULL */
001568          for(j=0; j<pTab->nCol; j++){
001569            char *zErr;
001570            int jmp2;
001571            if( j==pTab->iPKey ) continue;
001572            if( pTab->aCol[j].notNull==0 ) continue;
001573            sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
001574            sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
001575            jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
001576            zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
001577                                pTab->aCol[j].zName);
001578            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
001579            integrityCheckResultRow(v);
001580            sqlite3VdbeJumpHere(v, jmp2);
001581          }
001582          /* Verify CHECK constraints */
001583          if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
001584            ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
001585            if( db->mallocFailed==0 ){
001586              int addrCkFault = sqlite3VdbeMakeLabel(v);
001587              int addrCkOk = sqlite3VdbeMakeLabel(v);
001588              char *zErr;
001589              int k;
001590              pParse->iSelfTab = iDataCur + 1;
001591              sqlite3ExprCachePush(pParse);
001592              for(k=pCheck->nExpr-1; k>0; k--){
001593                sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
001594              }
001595              sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk, 
001596                  SQLITE_JUMPIFNULL);
001597              sqlite3VdbeResolveLabel(v, addrCkFault);
001598              pParse->iSelfTab = 0;
001599              zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
001600                  pTab->zName);
001601              sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
001602              integrityCheckResultRow(v);
001603              sqlite3VdbeResolveLabel(v, addrCkOk);
001604              sqlite3ExprCachePop(pParse);
001605            }
001606            sqlite3ExprListDelete(db, pCheck);
001607          }
001608          if( !isQuick ){ /* Omit the remaining tests for quick_check */
001609            /* Sanity check on record header decoding */
001610            sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nCol-1, 3);
001611            sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
001612            /* Validate index entries for the current row */
001613            for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
001614              int jmp2, jmp3, jmp4, jmp5;
001615              int ckUniq = sqlite3VdbeMakeLabel(v);
001616              if( pPk==pIdx ) continue;
001617              r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
001618                                           pPrior, r1);
001619              pPrior = pIdx;
001620              sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
001621              /* Verify that an index entry exists for the current table row */
001622              jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
001623                                          pIdx->nColumn); VdbeCoverage(v);
001624              sqlite3VdbeLoadString(v, 3, "row ");
001625              sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
001626              sqlite3VdbeLoadString(v, 4, " missing from index ");
001627              sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
001628              jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
001629              sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
001630              jmp4 = integrityCheckResultRow(v);
001631              sqlite3VdbeJumpHere(v, jmp2);
001632              /* For UNIQUE indexes, verify that only one entry exists with the
001633              ** current key.  The entry is unique if (1) any column is NULL
001634              ** or (2) the next entry has a different key */
001635              if( IsUniqueIndex(pIdx) ){
001636                int uniqOk = sqlite3VdbeMakeLabel(v);
001637                int jmp6;
001638                int kk;
001639                for(kk=0; kk<pIdx->nKeyCol; kk++){
001640                  int iCol = pIdx->aiColumn[kk];
001641                  assert( iCol!=XN_ROWID && iCol<pTab->nCol );
001642                  if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
001643                  sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
001644                  VdbeCoverage(v);
001645                }
001646                jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
001647                sqlite3VdbeGoto(v, uniqOk);
001648                sqlite3VdbeJumpHere(v, jmp6);
001649                sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
001650                                     pIdx->nKeyCol); VdbeCoverage(v);
001651                sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
001652                sqlite3VdbeGoto(v, jmp5);
001653                sqlite3VdbeResolveLabel(v, uniqOk);
001654              }
001655              sqlite3VdbeJumpHere(v, jmp4);
001656              sqlite3ResolvePartIdxLabel(pParse, jmp3);
001657            }
001658          }
001659          sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
001660          sqlite3VdbeJumpHere(v, loopTop-1);
001661  #ifndef SQLITE_OMIT_BTREECOUNT
001662          if( !isQuick ){
001663            sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
001664            for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
001665              if( pPk==pIdx ) continue;
001666              sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
001667              addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
001668              sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
001669              sqlite3VdbeLoadString(v, 4, pIdx->zName);
001670              sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
001671              integrityCheckResultRow(v);
001672              sqlite3VdbeJumpHere(v, addr);
001673            }
001674          }
001675  #endif /* SQLITE_OMIT_BTREECOUNT */
001676        } 
001677      }
001678      {
001679        static const int iLn = VDBE_OFFSET_LINENO(2);
001680        static const VdbeOpList endCode[] = {
001681          { OP_AddImm,      1, 0,        0},    /* 0 */
001682          { OP_IfNotZero,   1, 4,        0},    /* 1 */
001683          { OP_String8,     0, 3,        0},    /* 2 */
001684          { OP_ResultRow,   3, 1,        0},    /* 3 */
001685          { OP_Halt,        0, 0,        0},    /* 4 */
001686          { OP_String8,     0, 3,        0},    /* 5 */
001687          { OP_Goto,        0, 3,        0},    /* 6 */
001688        };
001689        VdbeOp *aOp;
001690  
001691        aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
001692        if( aOp ){
001693          aOp[0].p2 = 1-mxErr;
001694          aOp[2].p4type = P4_STATIC;
001695          aOp[2].p4.z = "ok";
001696          aOp[5].p4type = P4_STATIC;
001697          aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
001698        }
001699        sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
001700      }
001701    }
001702    break;
001703  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
001704  
001705  #ifndef SQLITE_OMIT_UTF16
001706    /*
001707    **   PRAGMA encoding
001708    **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
001709    **
001710    ** In its first form, this pragma returns the encoding of the main
001711    ** database. If the database is not initialized, it is initialized now.
001712    **
001713    ** The second form of this pragma is a no-op if the main database file
001714    ** has not already been initialized. In this case it sets the default
001715    ** encoding that will be used for the main database file if a new file
001716    ** is created. If an existing main database file is opened, then the
001717    ** default text encoding for the existing database is used.
001718    ** 
001719    ** In all cases new databases created using the ATTACH command are
001720    ** created to use the same default text encoding as the main database. If
001721    ** the main database has not been initialized and/or created when ATTACH
001722    ** is executed, this is done before the ATTACH operation.
001723    **
001724    ** In the second form this pragma sets the text encoding to be used in
001725    ** new database files created using this database handle. It is only
001726    ** useful if invoked immediately after the main database i
001727    */
001728    case PragTyp_ENCODING: {
001729      static const struct EncName {
001730        char *zName;
001731        u8 enc;
001732      } encnames[] = {
001733        { "UTF8",     SQLITE_UTF8        },
001734        { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
001735        { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
001736        { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
001737        { "UTF16le",  SQLITE_UTF16LE     },
001738        { "UTF16be",  SQLITE_UTF16BE     },
001739        { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
001740        { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
001741        { 0, 0 }
001742      };
001743      const struct EncName *pEnc;
001744      if( !zRight ){    /* "PRAGMA encoding" */
001745        if( sqlite3ReadSchema(pParse) ) goto pragma_out;
001746        assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
001747        assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
001748        assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
001749        returnSingleText(v, encnames[ENC(pParse->db)].zName);
001750      }else{                        /* "PRAGMA encoding = XXX" */
001751        /* Only change the value of sqlite.enc if the database handle is not
001752        ** initialized. If the main database exists, the new sqlite.enc value
001753        ** will be overwritten when the schema is next loaded. If it does not
001754        ** already exists, it will be created to use the new encoding value.
001755        */
001756        if( 
001757          !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
001758          DbHasProperty(db, 0, DB_Empty) 
001759        ){
001760          for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
001761            if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
001762              SCHEMA_ENC(db) = ENC(db) =
001763                  pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
001764              break;
001765            }
001766          }
001767          if( !pEnc->zName ){
001768            sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
001769          }
001770        }
001771      }
001772    }
001773    break;
001774  #endif /* SQLITE_OMIT_UTF16 */
001775  
001776  #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
001777    /*
001778    **   PRAGMA [schema.]schema_version
001779    **   PRAGMA [schema.]schema_version = <integer>
001780    **
001781    **   PRAGMA [schema.]user_version
001782    **   PRAGMA [schema.]user_version = <integer>
001783    **
001784    **   PRAGMA [schema.]freelist_count
001785    **
001786    **   PRAGMA [schema.]data_version
001787    **
001788    **   PRAGMA [schema.]application_id
001789    **   PRAGMA [schema.]application_id = <integer>
001790    **
001791    ** The pragma's schema_version and user_version are used to set or get
001792    ** the value of the schema-version and user-version, respectively. Both
001793    ** the schema-version and the user-version are 32-bit signed integers
001794    ** stored in the database header.
001795    **
001796    ** The schema-cookie is usually only manipulated internally by SQLite. It
001797    ** is incremented by SQLite whenever the database schema is modified (by
001798    ** creating or dropping a table or index). The schema version is used by
001799    ** SQLite each time a query is executed to ensure that the internal cache
001800    ** of the schema used when compiling the SQL query matches the schema of
001801    ** the database against which the compiled query is actually executed.
001802    ** Subverting this mechanism by using "PRAGMA schema_version" to modify
001803    ** the schema-version is potentially dangerous and may lead to program
001804    ** crashes or database corruption. Use with caution!
001805    **
001806    ** The user-version is not used internally by SQLite. It may be used by
001807    ** applications for any purpose.
001808    */
001809    case PragTyp_HEADER_VALUE: {
001810      int iCookie = pPragma->iArg;  /* Which cookie to read or write */
001811      sqlite3VdbeUsesBtree(v, iDb);
001812      if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
001813        /* Write the specified cookie value */
001814        static const VdbeOpList setCookie[] = {
001815          { OP_Transaction,    0,  1,  0},    /* 0 */
001816          { OP_SetCookie,      0,  0,  0},    /* 1 */
001817        };
001818        VdbeOp *aOp;
001819        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
001820        aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
001821        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
001822        aOp[0].p1 = iDb;
001823        aOp[1].p1 = iDb;
001824        aOp[1].p2 = iCookie;
001825        aOp[1].p3 = sqlite3Atoi(zRight);
001826      }else{
001827        /* Read the specified cookie value */
001828        static const VdbeOpList readCookie[] = {
001829          { OP_Transaction,     0,  0,  0},    /* 0 */
001830          { OP_ReadCookie,      0,  1,  0},    /* 1 */
001831          { OP_ResultRow,       1,  1,  0}
001832        };
001833        VdbeOp *aOp;
001834        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
001835        aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
001836        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
001837        aOp[0].p1 = iDb;
001838        aOp[1].p1 = iDb;
001839        aOp[1].p3 = iCookie;
001840        sqlite3VdbeReusable(v);
001841      }
001842    }
001843    break;
001844  #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
001845  
001846  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
001847    /*
001848    **   PRAGMA compile_options
001849    **
001850    ** Return the names of all compile-time options used in this build,
001851    ** one option per row.
001852    */
001853    case PragTyp_COMPILE_OPTIONS: {
001854      int i = 0;
001855      const char *zOpt;
001856      pParse->nMem = 1;
001857      while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
001858        sqlite3VdbeLoadString(v, 1, zOpt);
001859        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
001860      }
001861      sqlite3VdbeReusable(v);
001862    }
001863    break;
001864  #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
001865  
001866  #ifndef SQLITE_OMIT_WAL
001867    /*
001868    **   PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
001869    **
001870    ** Checkpoint the database.
001871    */
001872    case PragTyp_WAL_CHECKPOINT: {
001873      int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
001874      int eMode = SQLITE_CHECKPOINT_PASSIVE;
001875      if( zRight ){
001876        if( sqlite3StrICmp(zRight, "full")==0 ){
001877          eMode = SQLITE_CHECKPOINT_FULL;
001878        }else if( sqlite3StrICmp(zRight, "restart")==0 ){
001879          eMode = SQLITE_CHECKPOINT_RESTART;
001880        }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
001881          eMode = SQLITE_CHECKPOINT_TRUNCATE;
001882        }
001883      }
001884      pParse->nMem = 3;
001885      sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
001886      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
001887    }
001888    break;
001889  
001890    /*
001891    **   PRAGMA wal_autocheckpoint
001892    **   PRAGMA wal_autocheckpoint = N
001893    **
001894    ** Configure a database connection to automatically checkpoint a database
001895    ** after accumulating N frames in the log. Or query for the current value
001896    ** of N.
001897    */
001898    case PragTyp_WAL_AUTOCHECKPOINT: {
001899      if( zRight ){
001900        sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
001901      }
001902      returnSingleInt(v, 
001903         db->xWalCallback==sqlite3WalDefaultHook ? 
001904             SQLITE_PTR_TO_INT(db->pWalArg) : 0);
001905    }
001906    break;
001907  #endif
001908  
001909    /*
001910    **  PRAGMA shrink_memory
001911    **
001912    ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
001913    ** connection on which it is invoked to free up as much memory as it
001914    ** can, by calling sqlite3_db_release_memory().
001915    */
001916    case PragTyp_SHRINK_MEMORY: {
001917      sqlite3_db_release_memory(db);
001918      break;
001919    }
001920  
001921    /*
001922    **  PRAGMA optimize
001923    **  PRAGMA optimize(MASK)
001924    **  PRAGMA schema.optimize
001925    **  PRAGMA schema.optimize(MASK)
001926    **
001927    ** Attempt to optimize the database.  All schemas are optimized in the first
001928    ** two forms, and only the specified schema is optimized in the latter two.
001929    **
001930    ** The details of optimizations performed by this pragma are expected
001931    ** to change and improve over time.  Applications should anticipate that
001932    ** this pragma will perform new optimizations in future releases.
001933    **
001934    ** The optional argument is a bitmask of optimizations to perform:
001935    **
001936    **    0x0001    Debugging mode.  Do not actually perform any optimizations
001937    **              but instead return one line of text for each optimization
001938    **              that would have been done.  Off by default.
001939    **
001940    **    0x0002    Run ANALYZE on tables that might benefit.  On by default.
001941    **              See below for additional information.
001942    **
001943    **    0x0004    (Not yet implemented) Record usage and performance 
001944    **              information from the current session in the
001945    **              database file so that it will be available to "optimize"
001946    **              pragmas run by future database connections.
001947    **
001948    **    0x0008    (Not yet implemented) Create indexes that might have
001949    **              been helpful to recent queries
001950    **
001951    ** The default MASK is and always shall be 0xfffe.  0xfffe means perform all
001952    ** of the optimizations listed above except Debug Mode, including new
001953    ** optimizations that have not yet been invented.  If new optimizations are
001954    ** ever added that should be off by default, those off-by-default 
001955    ** optimizations will have bitmasks of 0x10000 or larger.
001956    **
001957    ** DETERMINATION OF WHEN TO RUN ANALYZE
001958    **
001959    ** In the current implementation, a table is analyzed if only if all of
001960    ** the following are true:
001961    **
001962    ** (1) MASK bit 0x02 is set.
001963    **
001964    ** (2) The query planner used sqlite_stat1-style statistics for one or
001965    **     more indexes of the table at some point during the lifetime of
001966    **     the current connection.
001967    **
001968    ** (3) One or more indexes of the table are currently unanalyzed OR
001969    **     the number of rows in the table has increased by 25 times or more
001970    **     since the last time ANALYZE was run.
001971    **
001972    ** The rules for when tables are analyzed are likely to change in
001973    ** future releases.
001974    */
001975    case PragTyp_OPTIMIZE: {
001976      int iDbLast;           /* Loop termination point for the schema loop */
001977      int iTabCur;           /* Cursor for a table whose size needs checking */
001978      HashElem *k;           /* Loop over tables of a schema */
001979      Schema *pSchema;       /* The current schema */
001980      Table *pTab;           /* A table in the schema */
001981      Index *pIdx;           /* An index of the table */
001982      LogEst szThreshold;    /* Size threshold above which reanalysis is needd */
001983      char *zSubSql;         /* SQL statement for the OP_SqlExec opcode */
001984      u32 opMask;            /* Mask of operations to perform */
001985  
001986      if( zRight ){
001987        opMask = (u32)sqlite3Atoi(zRight);
001988        if( (opMask & 0x02)==0 ) break;
001989      }else{
001990        opMask = 0xfffe;
001991      }
001992      iTabCur = pParse->nTab++;
001993      for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
001994        if( iDb==1 ) continue;
001995        sqlite3CodeVerifySchema(pParse, iDb);
001996        pSchema = db->aDb[iDb].pSchema;
001997        for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
001998          pTab = (Table*)sqliteHashData(k);
001999  
002000          /* If table pTab has not been used in a way that would benefit from
002001          ** having analysis statistics during the current session, then skip it.
002002          ** This also has the effect of skipping virtual tables and views */
002003          if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
002004  
002005          /* Reanalyze if the table is 25 times larger than the last analysis */
002006          szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
002007          for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
002008            if( !pIdx->hasStat1 ){
002009              szThreshold = 0; /* Always analyze if any index lacks statistics */
002010              break;
002011            }
002012          }
002013          if( szThreshold ){
002014            sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
002015            sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur, 
002016                           sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
002017            VdbeCoverage(v);
002018          }
002019          zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
002020                                   db->aDb[iDb].zDbSName, pTab->zName);
002021          if( opMask & 0x01 ){
002022            int r1 = sqlite3GetTempReg(pParse);
002023            sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
002024            sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
002025          }else{
002026            sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
002027          }
002028        }
002029      }
002030      sqlite3VdbeAddOp0(v, OP_Expire);
002031      break;
002032    }
002033  
002034    /*
002035    **   PRAGMA busy_timeout
002036    **   PRAGMA busy_timeout = N
002037    **
002038    ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
002039    ** if one is set.  If no busy handler or a different busy handler is set
002040    ** then 0 is returned.  Setting the busy_timeout to 0 or negative
002041    ** disables the timeout.
002042    */
002043    /*case PragTyp_BUSY_TIMEOUT*/ default: {
002044      assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
002045      if( zRight ){
002046        sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
002047      }
002048      returnSingleInt(v, db->busyTimeout);
002049      break;
002050    }
002051  
002052    /*
002053    **   PRAGMA soft_heap_limit
002054    **   PRAGMA soft_heap_limit = N
002055    **
002056    ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
002057    ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
002058    ** specified and is a non-negative integer.
002059    ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
002060    ** returns the same integer that would be returned by the
002061    ** sqlite3_soft_heap_limit64(-1) C-language function.
002062    */
002063    case PragTyp_SOFT_HEAP_LIMIT: {
002064      sqlite3_int64 N;
002065      if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
002066        sqlite3_soft_heap_limit64(N);
002067      }
002068      returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
002069      break;
002070    }
002071  
002072    /*
002073    **   PRAGMA threads
002074    **   PRAGMA threads = N
002075    **
002076    ** Configure the maximum number of worker threads.  Return the new
002077    ** maximum, which might be less than requested.
002078    */
002079    case PragTyp_THREADS: {
002080      sqlite3_int64 N;
002081      if( zRight
002082       && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
002083       && N>=0
002084      ){
002085        sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
002086      }
002087      returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
002088      break;
002089    }
002090  
002091  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
002092    /*
002093    ** Report the current state of file logs for all databases
002094    */
002095    case PragTyp_LOCK_STATUS: {
002096      static const char *const azLockName[] = {
002097        "unlocked", "shared", "reserved", "pending", "exclusive"
002098      };
002099      int i;
002100      pParse->nMem = 2;
002101      for(i=0; i<db->nDb; i++){
002102        Btree *pBt;
002103        const char *zState = "unknown";
002104        int j;
002105        if( db->aDb[i].zDbSName==0 ) continue;
002106        pBt = db->aDb[i].pBt;
002107        if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
002108          zState = "closed";
002109        }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0, 
002110                                       SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
002111           zState = azLockName[j];
002112        }
002113        sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
002114      }
002115      break;
002116    }
002117  #endif
002118  
002119  #ifdef SQLITE_HAS_CODEC
002120    case PragTyp_KEY: {
002121      if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
002122      break;
002123    }
002124    case PragTyp_REKEY: {
002125      if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
002126      break;
002127    }
002128    case PragTyp_HEXKEY: {
002129      if( zRight ){
002130        u8 iByte;
002131        int i;
002132        char zKey[40];
002133        for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
002134          iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
002135          if( (i&1)!=0 ) zKey[i/2] = iByte;
002136        }
002137        if( (zLeft[3] & 0xf)==0xb ){
002138          sqlite3_key_v2(db, zDb, zKey, i/2);
002139        }else{
002140          sqlite3_rekey_v2(db, zDb, zKey, i/2);
002141        }
002142      }
002143      break;
002144    }
002145  #endif
002146  #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
002147    case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
002148  #ifdef SQLITE_HAS_CODEC
002149      if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
002150        sqlite3_activate_see(&zRight[4]);
002151      }
002152  #endif
002153  #ifdef SQLITE_ENABLE_CEROD
002154      if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
002155        sqlite3_activate_cerod(&zRight[6]);
002156      }
002157  #endif
002158    }
002159    break;
002160  #endif
002161  
002162    } /* End of the PRAGMA switch */
002163  
002164    /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
002165    ** purpose is to execute assert() statements to verify that if the
002166    ** PragFlg_NoColumns1 flag is set and the caller specified an argument
002167    ** to the PRAGMA, the implementation has not added any OP_ResultRow 
002168    ** instructions to the VM.  */
002169    if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
002170      sqlite3VdbeVerifyNoResultRow(v);
002171    }
002172  
002173  pragma_out:
002174    sqlite3DbFree(db, zLeft);
002175    sqlite3DbFree(db, zRight);
002176  }
002177  #ifndef SQLITE_OMIT_VIRTUALTABLE
002178  /*****************************************************************************
002179  ** Implementation of an eponymous virtual table that runs a pragma.
002180  **
002181  */
002182  typedef struct PragmaVtab PragmaVtab;
002183  typedef struct PragmaVtabCursor PragmaVtabCursor;
002184  struct PragmaVtab {
002185    sqlite3_vtab base;        /* Base class.  Must be first */
002186    sqlite3 *db;              /* The database connection to which it belongs */
002187    const PragmaName *pName;  /* Name of the pragma */
002188    u8 nHidden;               /* Number of hidden columns */
002189    u8 iHidden;               /* Index of the first hidden column */
002190  };
002191  struct PragmaVtabCursor {
002192    sqlite3_vtab_cursor base; /* Base class.  Must be first */
002193    sqlite3_stmt *pPragma;    /* The pragma statement to run */
002194    sqlite_int64 iRowid;      /* Current rowid */
002195    char *azArg[2];           /* Value of the argument and schema */
002196  };
002197  
002198  /* 
002199  ** Pragma virtual table module xConnect method.
002200  */
002201  static int pragmaVtabConnect(
002202    sqlite3 *db,
002203    void *pAux,
002204    int argc, const char *const*argv,
002205    sqlite3_vtab **ppVtab,
002206    char **pzErr
002207  ){
002208    const PragmaName *pPragma = (const PragmaName*)pAux;
002209    PragmaVtab *pTab = 0;
002210    int rc;
002211    int i, j;
002212    char cSep = '(';
002213    StrAccum acc;
002214    char zBuf[200];
002215  
002216    UNUSED_PARAMETER(argc);
002217    UNUSED_PARAMETER(argv);
002218    sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
002219    sqlite3_str_appendall(&acc, "CREATE TABLE x");
002220    for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
002221      sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]);
002222      cSep = ',';
002223    }
002224    if( i==0 ){
002225      sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
002226      cSep = ',';
002227      i++;
002228    }
002229    j = 0;
002230    if( pPragma->mPragFlg & PragFlg_Result1 ){
002231      sqlite3_str_appendall(&acc, ",arg HIDDEN");
002232      j++;
002233    }
002234    if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
002235      sqlite3_str_appendall(&acc, ",schema HIDDEN");
002236      j++;
002237    }
002238    sqlite3_str_append(&acc, ")", 1);
002239    sqlite3StrAccumFinish(&acc);
002240    assert( strlen(zBuf) < sizeof(zBuf)-1 );
002241    rc = sqlite3_declare_vtab(db, zBuf);
002242    if( rc==SQLITE_OK ){
002243      pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
002244      if( pTab==0 ){
002245        rc = SQLITE_NOMEM;
002246      }else{
002247        memset(pTab, 0, sizeof(PragmaVtab));
002248        pTab->pName = pPragma;
002249        pTab->db = db;
002250        pTab->iHidden = i;
002251        pTab->nHidden = j;
002252      }
002253    }else{
002254      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
002255    }
002256  
002257    *ppVtab = (sqlite3_vtab*)pTab;
002258    return rc;
002259  }
002260  
002261  /* 
002262  ** Pragma virtual table module xDisconnect method.
002263  */
002264  static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
002265    PragmaVtab *pTab = (PragmaVtab*)pVtab;
002266    sqlite3_free(pTab);
002267    return SQLITE_OK;
002268  }
002269  
002270  /* Figure out the best index to use to search a pragma virtual table.
002271  **
002272  ** There are not really any index choices.  But we want to encourage the
002273  ** query planner to give == constraints on as many hidden parameters as
002274  ** possible, and especially on the first hidden parameter.  So return a
002275  ** high cost if hidden parameters are unconstrained.
002276  */
002277  static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
002278    PragmaVtab *pTab = (PragmaVtab*)tab;
002279    const struct sqlite3_index_constraint *pConstraint;
002280    int i, j;
002281    int seen[2];
002282  
002283    pIdxInfo->estimatedCost = (double)1;
002284    if( pTab->nHidden==0 ){ return SQLITE_OK; }
002285    pConstraint = pIdxInfo->aConstraint;
002286    seen[0] = 0;
002287    seen[1] = 0;
002288    for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
002289      if( pConstraint->usable==0 ) continue;
002290      if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
002291      if( pConstraint->iColumn < pTab->iHidden ) continue;
002292      j = pConstraint->iColumn - pTab->iHidden;
002293      assert( j < 2 );
002294      seen[j] = i+1;
002295    }
002296    if( seen[0]==0 ){
002297      pIdxInfo->estimatedCost = (double)2147483647;
002298      pIdxInfo->estimatedRows = 2147483647;
002299      return SQLITE_OK;
002300    }
002301    j = seen[0]-1;
002302    pIdxInfo->aConstraintUsage[j].argvIndex = 1;
002303    pIdxInfo->aConstraintUsage[j].omit = 1;
002304    if( seen[1]==0 ) return SQLITE_OK;
002305    pIdxInfo->estimatedCost = (double)20;
002306    pIdxInfo->estimatedRows = 20;
002307    j = seen[1]-1;
002308    pIdxInfo->aConstraintUsage[j].argvIndex = 2;
002309    pIdxInfo->aConstraintUsage[j].omit = 1;
002310    return SQLITE_OK;
002311  }
002312  
002313  /* Create a new cursor for the pragma virtual table */
002314  static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
002315    PragmaVtabCursor *pCsr;
002316    pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
002317    if( pCsr==0 ) return SQLITE_NOMEM;
002318    memset(pCsr, 0, sizeof(PragmaVtabCursor));
002319    pCsr->base.pVtab = pVtab;
002320    *ppCursor = &pCsr->base;
002321    return SQLITE_OK;
002322  }
002323  
002324  /* Clear all content from pragma virtual table cursor. */
002325  static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
002326    int i;
002327    sqlite3_finalize(pCsr->pPragma);
002328    pCsr->pPragma = 0;
002329    for(i=0; i<ArraySize(pCsr->azArg); i++){
002330      sqlite3_free(pCsr->azArg[i]);
002331      pCsr->azArg[i] = 0;
002332    }
002333  }
002334  
002335  /* Close a pragma virtual table cursor */
002336  static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
002337    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
002338    pragmaVtabCursorClear(pCsr);
002339    sqlite3_free(pCsr);
002340    return SQLITE_OK;
002341  }
002342  
002343  /* Advance the pragma virtual table cursor to the next row */
002344  static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
002345    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
002346    int rc = SQLITE_OK;
002347  
002348    /* Increment the xRowid value */
002349    pCsr->iRowid++;
002350    assert( pCsr->pPragma );
002351    if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
002352      rc = sqlite3_finalize(pCsr->pPragma);
002353      pCsr->pPragma = 0;
002354      pragmaVtabCursorClear(pCsr);
002355    }
002356    return rc;
002357  }
002358  
002359  /* 
002360  ** Pragma virtual table module xFilter method.
002361  */
002362  static int pragmaVtabFilter(
002363    sqlite3_vtab_cursor *pVtabCursor, 
002364    int idxNum, const char *idxStr,
002365    int argc, sqlite3_value **argv
002366  ){
002367    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
002368    PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
002369    int rc;
002370    int i, j;
002371    StrAccum acc;
002372    char *zSql;
002373  
002374    UNUSED_PARAMETER(idxNum);
002375    UNUSED_PARAMETER(idxStr);
002376    pragmaVtabCursorClear(pCsr);
002377    j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
002378    for(i=0; i<argc; i++, j++){
002379      const char *zText = (const char*)sqlite3_value_text(argv[i]);
002380      assert( j<ArraySize(pCsr->azArg) );
002381      assert( pCsr->azArg[j]==0 );
002382      if( zText ){
002383        pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
002384        if( pCsr->azArg[j]==0 ){
002385          return SQLITE_NOMEM;
002386        }
002387      }
002388    }
002389    sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
002390    sqlite3_str_appendall(&acc, "PRAGMA ");
002391    if( pCsr->azArg[1] ){
002392      sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
002393    }
002394    sqlite3_str_appendall(&acc, pTab->pName->zName);
002395    if( pCsr->azArg[0] ){
002396      sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
002397    }
002398    zSql = sqlite3StrAccumFinish(&acc);
002399    if( zSql==0 ) return SQLITE_NOMEM;
002400    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
002401    sqlite3_free(zSql);
002402    if( rc!=SQLITE_OK ){
002403      pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
002404      return rc;
002405    }
002406    return pragmaVtabNext(pVtabCursor);
002407  }
002408  
002409  /*
002410  ** Pragma virtual table module xEof method.
002411  */
002412  static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
002413    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
002414    return (pCsr->pPragma==0);
002415  }
002416  
002417  /* The xColumn method simply returns the corresponding column from
002418  ** the PRAGMA.  
002419  */
002420  static int pragmaVtabColumn(
002421    sqlite3_vtab_cursor *pVtabCursor, 
002422    sqlite3_context *ctx, 
002423    int i
002424  ){
002425    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
002426    PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
002427    if( i<pTab->iHidden ){
002428      sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
002429    }else{
002430      sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
002431    }
002432    return SQLITE_OK;
002433  }
002434  
002435  /* 
002436  ** Pragma virtual table module xRowid method.
002437  */
002438  static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
002439    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
002440    *p = pCsr->iRowid;
002441    return SQLITE_OK;
002442  }
002443  
002444  /* The pragma virtual table object */
002445  static const sqlite3_module pragmaVtabModule = {
002446    0,                           /* iVersion */
002447    0,                           /* xCreate - create a table */
002448    pragmaVtabConnect,           /* xConnect - connect to an existing table */
002449    pragmaVtabBestIndex,         /* xBestIndex - Determine search strategy */
002450    pragmaVtabDisconnect,        /* xDisconnect - Disconnect from a table */
002451    0,                           /* xDestroy - Drop a table */
002452    pragmaVtabOpen,              /* xOpen - open a cursor */
002453    pragmaVtabClose,             /* xClose - close a cursor */
002454    pragmaVtabFilter,            /* xFilter - configure scan constraints */
002455    pragmaVtabNext,              /* xNext - advance a cursor */
002456    pragmaVtabEof,               /* xEof */
002457    pragmaVtabColumn,            /* xColumn - read data */
002458    pragmaVtabRowid,             /* xRowid - read data */
002459    0,                           /* xUpdate - write data */
002460    0,                           /* xBegin - begin transaction */
002461    0,                           /* xSync - sync transaction */
002462    0,                           /* xCommit - commit transaction */
002463    0,                           /* xRollback - rollback transaction */
002464    0,                           /* xFindFunction - function overloading */
002465    0,                           /* xRename - rename the table */
002466    0,                           /* xSavepoint */
002467    0,                           /* xRelease */
002468    0                            /* xRollbackTo */
002469  };
002470  
002471  /*
002472  ** Check to see if zTabName is really the name of a pragma.  If it is,
002473  ** then register an eponymous virtual table for that pragma and return
002474  ** a pointer to the Module object for the new virtual table.
002475  */
002476  Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
002477    const PragmaName *pName;
002478    assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
002479    pName = pragmaLocate(zName+7);
002480    if( pName==0 ) return 0;
002481    if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
002482    assert( sqlite3HashFind(&db->aModule, zName)==0 );
002483    return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
002484  }
002485  
002486  #endif /* SQLITE_OMIT_VIRTUALTABLE */
002487  
002488  #endif /* SQLITE_OMIT_PRAGMA */