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, 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  ** Process a pragma statement.  
000300  **
000301  ** Pragmas are of this form:
000302  **
000303  **      PRAGMA [schema.]id [= value]
000304  **
000305  ** The identifier might also be a string.  The value is a string, and
000306  ** identifier, or a number.  If minusFlag is true, then the value is
000307  ** a number that was preceded by a minus sign.
000308  **
000309  ** If the left side is "database.id" then pId1 is the database name
000310  ** and pId2 is the id.  If the left side is just "id" then pId1 is the
000311  ** id and pId2 is any empty string.
000312  */
000313  void sqlite3Pragma(
000314    Parse *pParse, 
000315    Token *pId1,        /* First part of [schema.]id field */
000316    Token *pId2,        /* Second part of [schema.]id field, or NULL */
000317    Token *pValue,      /* Token for <value>, or NULL */
000318    int minusFlag       /* True if a '-' sign preceded <value> */
000319  ){
000320    char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
000321    char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
000322    const char *zDb = 0;   /* The database name */
000323    Token *pId;            /* Pointer to <id> token */
000324    char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
000325    int iDb;               /* Database index for <database> */
000326    int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
000327    sqlite3 *db = pParse->db;    /* The database connection */
000328    Db *pDb;                     /* The specific database being pragmaed */
000329    Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
000330    const PragmaName *pPragma;   /* The pragma */
000331  
000332    if( v==0 ) return;
000333    sqlite3VdbeRunOnlyOnce(v);
000334    pParse->nMem = 2;
000335  
000336    /* Interpret the [schema.] part of the pragma statement. iDb is the
000337    ** index of the database this pragma is being applied to in db.aDb[]. */
000338    iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
000339    if( iDb<0 ) return;
000340    pDb = &db->aDb[iDb];
000341  
000342    /* If the temp database has been explicitly named as part of the 
000343    ** pragma, make sure it is open. 
000344    */
000345    if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
000346      return;
000347    }
000348  
000349    zLeft = sqlite3NameFromToken(db, pId);
000350    if( !zLeft ) return;
000351    if( minusFlag ){
000352      zRight = sqlite3MPrintf(db, "-%T", pValue);
000353    }else{
000354      zRight = sqlite3NameFromToken(db, pValue);
000355    }
000356  
000357    assert( pId2 );
000358    zDb = pId2->n>0 ? pDb->zDbSName : 0;
000359    if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
000360      goto pragma_out;
000361    }
000362  
000363    /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
000364    ** connection.  If it returns SQLITE_OK, then assume that the VFS
000365    ** handled the pragma and generate a no-op prepared statement.
000366    **
000367    ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
000368    ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
000369    ** object corresponding to the database file to which the pragma
000370    ** statement refers.
000371    **
000372    ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
000373    ** file control is an array of pointers to strings (char**) in which the
000374    ** second element of the array is the name of the pragma and the third
000375    ** element is the argument to the pragma or NULL if the pragma has no
000376    ** argument.
000377    */
000378    aFcntl[0] = 0;
000379    aFcntl[1] = zLeft;
000380    aFcntl[2] = zRight;
000381    aFcntl[3] = 0;
000382    db->busyHandler.nBusy = 0;
000383    rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
000384    if( rc==SQLITE_OK ){
000385      sqlite3VdbeSetNumCols(v, 1);
000386      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
000387      returnSingleText(v, aFcntl[0]);
000388      sqlite3_free(aFcntl[0]);
000389      goto pragma_out;
000390    }
000391    if( rc!=SQLITE_NOTFOUND ){
000392      if( aFcntl[0] ){
000393        sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
000394        sqlite3_free(aFcntl[0]);
000395      }
000396      pParse->nErr++;
000397      pParse->rc = rc;
000398      goto pragma_out;
000399    }
000400  
000401    /* Locate the pragma in the lookup table */
000402    pPragma = pragmaLocate(zLeft);
000403    if( pPragma==0 ) goto pragma_out;
000404  
000405    /* Make sure the database schema is loaded if the pragma requires that */
000406    if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
000407      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
000408    }
000409  
000410    /* Register the result column names for pragmas that return results */
000411    if( (pPragma->mPragFlg & PragFlg_NoColumns)==0 ){
000412      setPragmaResultColumnNames(v, pPragma);
000413    }
000414  
000415    /* Jump to the appropriate pragma handler */
000416    switch( pPragma->ePragTyp ){
000417    
000418  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
000419    /*
000420    **  PRAGMA [schema.]default_cache_size
000421    **  PRAGMA [schema.]default_cache_size=N
000422    **
000423    ** The first form reports the current persistent setting for the
000424    ** page cache size.  The value returned is the maximum number of
000425    ** pages in the page cache.  The second form sets both the current
000426    ** page cache size value and the persistent page cache size value
000427    ** stored in the database file.
000428    **
000429    ** Older versions of SQLite would set the default cache size to a
000430    ** negative number to indicate synchronous=OFF.  These days, synchronous
000431    ** is always on by default regardless of the sign of the default cache
000432    ** size.  But continue to take the absolute value of the default cache
000433    ** size of historical compatibility.
000434    */
000435    case PragTyp_DEFAULT_CACHE_SIZE: {
000436      static const int iLn = VDBE_OFFSET_LINENO(2);
000437      static const VdbeOpList getCacheSize[] = {
000438        { OP_Transaction, 0, 0,        0},                         /* 0 */
000439        { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
000440        { OP_IfPos,       1, 8,        0},
000441        { OP_Integer,     0, 2,        0},
000442        { OP_Subtract,    1, 2,        1},
000443        { OP_IfPos,       1, 8,        0},
000444        { OP_Integer,     0, 1,        0},                         /* 6 */
000445        { OP_Noop,        0, 0,        0},
000446        { OP_ResultRow,   1, 1,        0},
000447      };
000448      VdbeOp *aOp;
000449      sqlite3VdbeUsesBtree(v, iDb);
000450      if( !zRight ){
000451        pParse->nMem += 2;
000452        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
000453        aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
000454        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
000455        aOp[0].p1 = iDb;
000456        aOp[1].p1 = iDb;
000457        aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
000458      }else{
000459        int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
000460        sqlite3BeginWriteOperation(pParse, 0, iDb);
000461        sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
000462        assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000463        pDb->pSchema->cache_size = size;
000464        sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
000465      }
000466      break;
000467    }
000468  #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
000469  
000470  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
000471    /*
000472    **  PRAGMA [schema.]page_size
000473    **  PRAGMA [schema.]page_size=N
000474    **
000475    ** The first form reports the current setting for the
000476    ** database page size in bytes.  The second form sets the
000477    ** database page size value.  The value can only be set if
000478    ** the database has not yet been created.
000479    */
000480    case PragTyp_PAGE_SIZE: {
000481      Btree *pBt = pDb->pBt;
000482      assert( pBt!=0 );
000483      if( !zRight ){
000484        int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
000485        returnSingleInt(v, size);
000486      }else{
000487        /* Malloc may fail when setting the page-size, as there is an internal
000488        ** buffer that the pager module resizes using sqlite3_realloc().
000489        */
000490        db->nextPagesize = sqlite3Atoi(zRight);
000491        if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
000492          sqlite3OomFault(db);
000493        }
000494      }
000495      break;
000496    }
000497  
000498    /*
000499    **  PRAGMA [schema.]secure_delete
000500    **  PRAGMA [schema.]secure_delete=ON/OFF
000501    **
000502    ** The first form reports the current setting for the
000503    ** secure_delete flag.  The second form changes the secure_delete
000504    ** flag setting and reports thenew value.
000505    */
000506    case PragTyp_SECURE_DELETE: {
000507      Btree *pBt = pDb->pBt;
000508      int b = -1;
000509      assert( pBt!=0 );
000510      if( zRight ){
000511        b = sqlite3GetBoolean(zRight, 0);
000512      }
000513      if( pId2->n==0 && b>=0 ){
000514        int ii;
000515        for(ii=0; ii<db->nDb; ii++){
000516          sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
000517        }
000518      }
000519      b = sqlite3BtreeSecureDelete(pBt, b);
000520      returnSingleInt(v, b);
000521      break;
000522    }
000523  
000524    /*
000525    **  PRAGMA [schema.]max_page_count
000526    **  PRAGMA [schema.]max_page_count=N
000527    **
000528    ** The first form reports the current setting for the
000529    ** maximum number of pages in the database file.  The 
000530    ** second form attempts to change this setting.  Both
000531    ** forms return the current setting.
000532    **
000533    ** The absolute value of N is used.  This is undocumented and might
000534    ** change.  The only purpose is to provide an easy way to test
000535    ** the sqlite3AbsInt32() function.
000536    **
000537    **  PRAGMA [schema.]page_count
000538    **
000539    ** Return the number of pages in the specified database.
000540    */
000541    case PragTyp_PAGE_COUNT: {
000542      int iReg;
000543      sqlite3CodeVerifySchema(pParse, iDb);
000544      iReg = ++pParse->nMem;
000545      if( sqlite3Tolower(zLeft[0])=='p' ){
000546        sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
000547      }else{
000548        sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, 
000549                          sqlite3AbsInt32(sqlite3Atoi(zRight)));
000550      }
000551      sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
000552      break;
000553    }
000554  
000555    /*
000556    **  PRAGMA [schema.]locking_mode
000557    **  PRAGMA [schema.]locking_mode = (normal|exclusive)
000558    */
000559    case PragTyp_LOCKING_MODE: {
000560      const char *zRet = "normal";
000561      int eMode = getLockingMode(zRight);
000562  
000563      if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
000564        /* Simple "PRAGMA locking_mode;" statement. This is a query for
000565        ** the current default locking mode (which may be different to
000566        ** the locking-mode of the main database).
000567        */
000568        eMode = db->dfltLockMode;
000569      }else{
000570        Pager *pPager;
000571        if( pId2->n==0 ){
000572          /* This indicates that no database name was specified as part
000573          ** of the PRAGMA command. In this case the locking-mode must be
000574          ** set on all attached databases, as well as the main db file.
000575          **
000576          ** Also, the sqlite3.dfltLockMode variable is set so that
000577          ** any subsequently attached databases also use the specified
000578          ** locking mode.
000579          */
000580          int ii;
000581          assert(pDb==&db->aDb[0]);
000582          for(ii=2; ii<db->nDb; ii++){
000583            pPager = sqlite3BtreePager(db->aDb[ii].pBt);
000584            sqlite3PagerLockingMode(pPager, eMode);
000585          }
000586          db->dfltLockMode = (u8)eMode;
000587        }
000588        pPager = sqlite3BtreePager(pDb->pBt);
000589        eMode = sqlite3PagerLockingMode(pPager, eMode);
000590      }
000591  
000592      assert( eMode==PAGER_LOCKINGMODE_NORMAL
000593              || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
000594      if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
000595        zRet = "exclusive";
000596      }
000597      returnSingleText(v, zRet);
000598      break;
000599    }
000600  
000601    /*
000602    **  PRAGMA [schema.]journal_mode
000603    **  PRAGMA [schema.]journal_mode =
000604    **                      (delete|persist|off|truncate|memory|wal|off)
000605    */
000606    case PragTyp_JOURNAL_MODE: {
000607      int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
000608      int ii;           /* Loop counter */
000609  
000610      if( zRight==0 ){
000611        /* If there is no "=MODE" part of the pragma, do a query for the
000612        ** current mode */
000613        eMode = PAGER_JOURNALMODE_QUERY;
000614      }else{
000615        const char *zMode;
000616        int n = sqlite3Strlen30(zRight);
000617        for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
000618          if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
000619        }
000620        if( !zMode ){
000621          /* If the "=MODE" part does not match any known journal mode,
000622          ** then do a query */
000623          eMode = PAGER_JOURNALMODE_QUERY;
000624        }
000625      }
000626      if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
000627        /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
000628        iDb = 0;
000629        pId2->n = 1;
000630      }
000631      for(ii=db->nDb-1; ii>=0; ii--){
000632        if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
000633          sqlite3VdbeUsesBtree(v, ii);
000634          sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
000635        }
000636      }
000637      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
000638      break;
000639    }
000640  
000641    /*
000642    **  PRAGMA [schema.]journal_size_limit
000643    **  PRAGMA [schema.]journal_size_limit=N
000644    **
000645    ** Get or set the size limit on rollback journal files.
000646    */
000647    case PragTyp_JOURNAL_SIZE_LIMIT: {
000648      Pager *pPager = sqlite3BtreePager(pDb->pBt);
000649      i64 iLimit = -2;
000650      if( zRight ){
000651        sqlite3DecOrHexToI64(zRight, &iLimit);
000652        if( iLimit<-1 ) iLimit = -1;
000653      }
000654      iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
000655      returnSingleInt(v, iLimit);
000656      break;
000657    }
000658  
000659  #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
000660  
000661    /*
000662    **  PRAGMA [schema.]auto_vacuum
000663    **  PRAGMA [schema.]auto_vacuum=N
000664    **
000665    ** Get or set the value of the database 'auto-vacuum' parameter.
000666    ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
000667    */
000668  #ifndef SQLITE_OMIT_AUTOVACUUM
000669    case PragTyp_AUTO_VACUUM: {
000670      Btree *pBt = pDb->pBt;
000671      assert( pBt!=0 );
000672      if( !zRight ){
000673        returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
000674      }else{
000675        int eAuto = getAutoVacuum(zRight);
000676        assert( eAuto>=0 && eAuto<=2 );
000677        db->nextAutovac = (u8)eAuto;
000678        /* Call SetAutoVacuum() to set initialize the internal auto and
000679        ** incr-vacuum flags. This is required in case this connection
000680        ** creates the database file. It is important that it is created
000681        ** as an auto-vacuum capable db.
000682        */
000683        rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
000684        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
000685          /* When setting the auto_vacuum mode to either "full" or 
000686          ** "incremental", write the value of meta[6] in the database
000687          ** file. Before writing to meta[6], check that meta[3] indicates
000688          ** that this really is an auto-vacuum capable database.
000689          */
000690          static const int iLn = VDBE_OFFSET_LINENO(2);
000691          static const VdbeOpList setMeta6[] = {
000692            { OP_Transaction,    0,         1,                 0},    /* 0 */
000693            { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
000694            { OP_If,             1,         0,                 0},    /* 2 */
000695            { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
000696            { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 0},    /* 4 */
000697          };
000698          VdbeOp *aOp;
000699          int iAddr = sqlite3VdbeCurrentAddr(v);
000700          sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
000701          aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
000702          if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
000703          aOp[0].p1 = iDb;
000704          aOp[1].p1 = iDb;
000705          aOp[2].p2 = iAddr+4;
000706          aOp[4].p1 = iDb;
000707          aOp[4].p3 = eAuto - 1;
000708          sqlite3VdbeUsesBtree(v, iDb);
000709        }
000710      }
000711      break;
000712    }
000713  #endif
000714  
000715    /*
000716    **  PRAGMA [schema.]incremental_vacuum(N)
000717    **
000718    ** Do N steps of incremental vacuuming on a database.
000719    */
000720  #ifndef SQLITE_OMIT_AUTOVACUUM
000721    case PragTyp_INCREMENTAL_VACUUM: {
000722      int iLimit, addr;
000723      if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
000724        iLimit = 0x7fffffff;
000725      }
000726      sqlite3BeginWriteOperation(pParse, 0, iDb);
000727      sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
000728      addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
000729      sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
000730      sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
000731      sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
000732      sqlite3VdbeJumpHere(v, addr);
000733      break;
000734    }
000735  #endif
000736  
000737  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
000738    /*
000739    **  PRAGMA [schema.]cache_size
000740    **  PRAGMA [schema.]cache_size=N
000741    **
000742    ** The first form reports the current local setting for the
000743    ** page cache size. The second form sets the local
000744    ** page cache size value.  If N is positive then that is the
000745    ** number of pages in the cache.  If N is negative, then the
000746    ** number of pages is adjusted so that the cache uses -N kibibytes
000747    ** of memory.
000748    */
000749    case PragTyp_CACHE_SIZE: {
000750      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000751      if( !zRight ){
000752        returnSingleInt(v, pDb->pSchema->cache_size);
000753      }else{
000754        int size = sqlite3Atoi(zRight);
000755        pDb->pSchema->cache_size = size;
000756        sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
000757      }
000758      break;
000759    }
000760  
000761    /*
000762    **  PRAGMA [schema.]cache_spill
000763    **  PRAGMA cache_spill=BOOLEAN
000764    **  PRAGMA [schema.]cache_spill=N
000765    **
000766    ** The first form reports the current local setting for the
000767    ** page cache spill size. The second form turns cache spill on
000768    ** or off.  When turnning cache spill on, the size is set to the
000769    ** current cache_size.  The third form sets a spill size that
000770    ** may be different form the cache size.
000771    ** If N is positive then that is the
000772    ** number of pages in the cache.  If N is negative, then the
000773    ** number of pages is adjusted so that the cache uses -N kibibytes
000774    ** of memory.
000775    **
000776    ** If the number of cache_spill pages is less then the number of
000777    ** cache_size pages, no spilling occurs until the page count exceeds
000778    ** the number of cache_size pages.
000779    **
000780    ** The cache_spill=BOOLEAN setting applies to all attached schemas,
000781    ** not just the schema specified.
000782    */
000783    case PragTyp_CACHE_SPILL: {
000784      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000785      if( !zRight ){
000786        returnSingleInt(v,
000787           (db->flags & SQLITE_CacheSpill)==0 ? 0 : 
000788              sqlite3BtreeSetSpillSize(pDb->pBt,0));
000789      }else{
000790        int size = 1;
000791        if( sqlite3GetInt32(zRight, &size) ){
000792          sqlite3BtreeSetSpillSize(pDb->pBt, size);
000793        }
000794        if( sqlite3GetBoolean(zRight, size!=0) ){
000795          db->flags |= SQLITE_CacheSpill;
000796        }else{
000797          db->flags &= ~SQLITE_CacheSpill;
000798        }
000799        setAllPagerFlags(db);
000800      }
000801      break;
000802    }
000803  
000804    /*
000805    **  PRAGMA [schema.]mmap_size(N)
000806    **
000807    ** Used to set mapping size limit. The mapping size limit is
000808    ** used to limit the aggregate size of all memory mapped regions of the
000809    ** database file. If this parameter is set to zero, then memory mapping
000810    ** is not used at all.  If N is negative, then the default memory map
000811    ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
000812    ** The parameter N is measured in bytes.
000813    **
000814    ** This value is advisory.  The underlying VFS is free to memory map
000815    ** as little or as much as it wants.  Except, if N is set to 0 then the
000816    ** upper layers will never invoke the xFetch interfaces to the VFS.
000817    */
000818    case PragTyp_MMAP_SIZE: {
000819      sqlite3_int64 sz;
000820  #if SQLITE_MAX_MMAP_SIZE>0
000821      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000822      if( zRight ){
000823        int ii;
000824        sqlite3DecOrHexToI64(zRight, &sz);
000825        if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
000826        if( pId2->n==0 ) db->szMmap = sz;
000827        for(ii=db->nDb-1; ii>=0; ii--){
000828          if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
000829            sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
000830          }
000831        }
000832      }
000833      sz = -1;
000834      rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
000835  #else
000836      sz = 0;
000837      rc = SQLITE_OK;
000838  #endif
000839      if( rc==SQLITE_OK ){
000840        returnSingleInt(v, sz);
000841      }else if( rc!=SQLITE_NOTFOUND ){
000842        pParse->nErr++;
000843        pParse->rc = rc;
000844      }
000845      break;
000846    }
000847  
000848    /*
000849    **   PRAGMA temp_store
000850    **   PRAGMA temp_store = "default"|"memory"|"file"
000851    **
000852    ** Return or set the local value of the temp_store flag.  Changing
000853    ** the local value does not make changes to the disk file and the default
000854    ** value will be restored the next time the database is opened.
000855    **
000856    ** Note that it is possible for the library compile-time options to
000857    ** override this setting
000858    */
000859    case PragTyp_TEMP_STORE: {
000860      if( !zRight ){
000861        returnSingleInt(v, db->temp_store);
000862      }else{
000863        changeTempStorage(pParse, zRight);
000864      }
000865      break;
000866    }
000867  
000868    /*
000869    **   PRAGMA temp_store_directory
000870    **   PRAGMA temp_store_directory = ""|"directory_name"
000871    **
000872    ** Return or set the local value of the temp_store_directory flag.  Changing
000873    ** the value sets a specific directory to be used for temporary files.
000874    ** Setting to a null string reverts to the default temporary directory search.
000875    ** If temporary directory is changed, then invalidateTempStorage.
000876    **
000877    */
000878    case PragTyp_TEMP_STORE_DIRECTORY: {
000879      if( !zRight ){
000880        returnSingleText(v, sqlite3_temp_directory);
000881      }else{
000882  #ifndef SQLITE_OMIT_WSD
000883        if( zRight[0] ){
000884          int res;
000885          rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
000886          if( rc!=SQLITE_OK || res==0 ){
000887            sqlite3ErrorMsg(pParse, "not a writable directory");
000888            goto pragma_out;
000889          }
000890        }
000891        if( SQLITE_TEMP_STORE==0
000892         || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
000893         || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
000894        ){
000895          invalidateTempStorage(pParse);
000896        }
000897        sqlite3_free(sqlite3_temp_directory);
000898        if( zRight[0] ){
000899          sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
000900        }else{
000901          sqlite3_temp_directory = 0;
000902        }
000903  #endif /* SQLITE_OMIT_WSD */
000904      }
000905      break;
000906    }
000907  
000908  #if SQLITE_OS_WIN
000909    /*
000910    **   PRAGMA data_store_directory
000911    **   PRAGMA data_store_directory = ""|"directory_name"
000912    **
000913    ** Return or set the local value of the data_store_directory flag.  Changing
000914    ** the value sets a specific directory to be used for database files that
000915    ** were specified with a relative pathname.  Setting to a null string reverts
000916    ** to the default database directory, which for database files specified with
000917    ** a relative path will probably be based on the current directory for the
000918    ** process.  Database file specified with an absolute path are not impacted
000919    ** by this setting, regardless of its value.
000920    **
000921    */
000922    case PragTyp_DATA_STORE_DIRECTORY: {
000923      if( !zRight ){
000924        returnSingleText(v, sqlite3_data_directory);
000925      }else{
000926  #ifndef SQLITE_OMIT_WSD
000927        if( zRight[0] ){
000928          int res;
000929          rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
000930          if( rc!=SQLITE_OK || res==0 ){
000931            sqlite3ErrorMsg(pParse, "not a writable directory");
000932            goto pragma_out;
000933          }
000934        }
000935        sqlite3_free(sqlite3_data_directory);
000936        if( zRight[0] ){
000937          sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
000938        }else{
000939          sqlite3_data_directory = 0;
000940        }
000941  #endif /* SQLITE_OMIT_WSD */
000942      }
000943      break;
000944    }
000945  #endif
000946  
000947  #if SQLITE_ENABLE_LOCKING_STYLE
000948    /*
000949    **   PRAGMA [schema.]lock_proxy_file
000950    **   PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
000951    **
000952    ** Return or set the value of the lock_proxy_file flag.  Changing
000953    ** the value sets a specific file to be used for database access locks.
000954    **
000955    */
000956    case PragTyp_LOCK_PROXY_FILE: {
000957      if( !zRight ){
000958        Pager *pPager = sqlite3BtreePager(pDb->pBt);
000959        char *proxy_file_path = NULL;
000960        sqlite3_file *pFile = sqlite3PagerFile(pPager);
000961        sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, 
000962                             &proxy_file_path);
000963        returnSingleText(v, proxy_file_path);
000964      }else{
000965        Pager *pPager = sqlite3BtreePager(pDb->pBt);
000966        sqlite3_file *pFile = sqlite3PagerFile(pPager);
000967        int res;
000968        if( zRight[0] ){
000969          res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
000970                                       zRight);
000971        } else {
000972          res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
000973                                       NULL);
000974        }
000975        if( res!=SQLITE_OK ){
000976          sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
000977          goto pragma_out;
000978        }
000979      }
000980      break;
000981    }
000982  #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
000983      
000984    /*
000985    **   PRAGMA [schema.]synchronous
000986    **   PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
000987    **
000988    ** Return or set the local value of the synchronous flag.  Changing
000989    ** the local value does not make changes to the disk file and the
000990    ** default value will be restored the next time the database is
000991    ** opened.
000992    */
000993    case PragTyp_SYNCHRONOUS: {
000994      if( !zRight ){
000995        returnSingleInt(v, pDb->safety_level-1);
000996      }else{
000997        if( !db->autoCommit ){
000998          sqlite3ErrorMsg(pParse, 
000999              "Safety level may not be changed inside a transaction");
001000        }else{
001001          int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
001002          if( iLevel==0 ) iLevel = 1;
001003          pDb->safety_level = iLevel;
001004          pDb->bSyncSet = 1;
001005          setAllPagerFlags(db);
001006        }
001007      }
001008      break;
001009    }
001010  #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
001011  
001012  #ifndef SQLITE_OMIT_FLAG_PRAGMAS
001013    case PragTyp_FLAG: {
001014      if( zRight==0 ){
001015        setPragmaResultColumnNames(v, pPragma);
001016        returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
001017      }else{
001018        int mask = pPragma->iArg;    /* Mask of bits to set or clear. */
001019        if( db->autoCommit==0 ){
001020          /* Foreign key support may not be enabled or disabled while not
001021          ** in auto-commit mode.  */
001022          mask &= ~(SQLITE_ForeignKeys);
001023        }
001024  #if SQLITE_USER_AUTHENTICATION
001025        if( db->auth.authLevel==UAUTH_User ){
001026          /* Do not allow non-admin users to modify the schema arbitrarily */
001027          mask &= ~(SQLITE_WriteSchema);
001028        }
001029  #endif
001030  
001031        if( sqlite3GetBoolean(zRight, 0) ){
001032          db->flags |= mask;
001033        }else{
001034          db->flags &= ~mask;
001035          if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
001036        }
001037  
001038        /* Many of the flag-pragmas modify the code generated by the SQL 
001039        ** compiler (eg. count_changes). So add an opcode to expire all
001040        ** compiled SQL statements after modifying a pragma value.
001041        */
001042        sqlite3VdbeAddOp0(v, OP_Expire);
001043        setAllPagerFlags(db);
001044      }
001045      break;
001046    }
001047  #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
001048  
001049  #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
001050    /*
001051    **   PRAGMA table_info(<table>)
001052    **
001053    ** Return a single row for each column of the named table. The columns of
001054    ** the returned data set are:
001055    **
001056    ** cid:        Column id (numbered from left to right, starting at 0)
001057    ** name:       Column name
001058    ** type:       Column declaration type.
001059    ** notnull:    True if 'NOT NULL' is part of column declaration
001060    ** dflt_value: The default value for the column, if any.
001061    */
001062    case PragTyp_TABLE_INFO: if( zRight ){
001063      Table *pTab;
001064      pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
001065      if( pTab ){
001066        int i, k;
001067        int nHidden = 0;
001068        Column *pCol;
001069        Index *pPk = sqlite3PrimaryKeyIndex(pTab);
001070        pParse->nMem = 6;
001071        sqlite3CodeVerifySchema(pParse, iDb);
001072        sqlite3ViewGetColumnNames(pParse, pTab);
001073        for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
001074          if( IsHiddenColumn(pCol) ){
001075            nHidden++;
001076            continue;
001077          }
001078          if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
001079            k = 0;
001080          }else if( pPk==0 ){
001081            k = 1;
001082          }else{
001083            for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
001084          }
001085          assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
001086          sqlite3VdbeMultiLoad(v, 1, "issisi",
001087                 i-nHidden,
001088                 pCol->zName,
001089                 sqlite3ColumnType(pCol,""),
001090                 pCol->notNull ? 1 : 0,
001091                 pCol->pDflt ? pCol->pDflt->u.zToken : 0,
001092                 k);
001093          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
001094        }
001095      }
001096    }
001097    break;
001098  
001099    case PragTyp_STATS: {
001100      Index *pIdx;
001101      HashElem *i;
001102      pParse->nMem = 4;
001103      sqlite3CodeVerifySchema(pParse, iDb);
001104      for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
001105        Table *pTab = sqliteHashData(i);
001106        sqlite3VdbeMultiLoad(v, 1, "ssii",
001107             pTab->zName,
001108             0,
001109             pTab->szTabRow,
001110             pTab->nRowLogEst);
001111        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
001112        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
001113          sqlite3VdbeMultiLoad(v, 2, "sii",
001114             pIdx->zName,
001115             pIdx->szIdxRow,
001116             pIdx->aiRowLogEst[0]);
001117          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
001118        }
001119      }
001120    }
001121    break;
001122  
001123    case PragTyp_INDEX_INFO: if( zRight ){
001124      Index *pIdx;
001125      Table *pTab;
001126      pIdx = sqlite3FindIndex(db, zRight, zDb);
001127      if( pIdx ){
001128        int i;
001129        int mx;
001130        if( pPragma->iArg ){
001131          /* PRAGMA index_xinfo (newer version with more rows and columns) */
001132          mx = pIdx->nColumn;
001133          pParse->nMem = 6;
001134        }else{
001135          /* PRAGMA index_info (legacy version) */
001136          mx = pIdx->nKeyCol;
001137          pParse->nMem = 3;
001138        }
001139        pTab = pIdx->pTable;
001140        sqlite3CodeVerifySchema(pParse, iDb);
001141        assert( pParse->nMem<=pPragma->nPragCName );
001142        for(i=0; i<mx; i++){
001143          i16 cnum = pIdx->aiColumn[i];
001144          sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum,
001145                               cnum<0 ? 0 : pTab->aCol[cnum].zName);
001146          if( pPragma->iArg ){
001147            sqlite3VdbeMultiLoad(v, 4, "isi",
001148              pIdx->aSortOrder[i],
001149              pIdx->azColl[i],
001150              i<pIdx->nKeyCol);
001151          }
001152          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
001153        }
001154      }
001155    }
001156    break;
001157  
001158    case PragTyp_INDEX_LIST: if( zRight ){
001159      Index *pIdx;
001160      Table *pTab;
001161      int i;
001162      pTab = sqlite3FindTable(db, zRight, zDb);
001163      if( pTab ){
001164        pParse->nMem = 5;
001165        sqlite3CodeVerifySchema(pParse, iDb);
001166        for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
001167          const char *azOrigin[] = { "c", "u", "pk" };
001168          sqlite3VdbeMultiLoad(v, 1, "isisi",
001169             i,
001170             pIdx->zName,
001171             IsUniqueIndex(pIdx),
001172             azOrigin[pIdx->idxType],
001173             pIdx->pPartIdxWhere!=0);
001174          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
001175        }
001176      }
001177    }
001178    break;
001179  
001180    case PragTyp_DATABASE_LIST: {
001181      int i;
001182      pParse->nMem = 3;
001183      for(i=0; i<db->nDb; i++){
001184        if( db->aDb[i].pBt==0 ) continue;
001185        assert( db->aDb[i].zDbSName!=0 );
001186        sqlite3VdbeMultiLoad(v, 1, "iss",
001187           i,
001188           db->aDb[i].zDbSName,
001189           sqlite3BtreeGetFilename(db->aDb[i].pBt));
001190        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
001191      }
001192    }
001193    break;
001194  
001195    case PragTyp_COLLATION_LIST: {
001196      int i = 0;
001197      HashElem *p;
001198      pParse->nMem = 2;
001199      for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
001200        CollSeq *pColl = (CollSeq *)sqliteHashData(p);
001201        sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
001202        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
001203      }
001204    }
001205    break;
001206  #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
001207  
001208  #ifndef SQLITE_OMIT_FOREIGN_KEY
001209    case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
001210      FKey *pFK;
001211      Table *pTab;
001212      pTab = sqlite3FindTable(db, zRight, zDb);
001213      if( pTab ){
001214        pFK = pTab->pFKey;
001215        if( pFK ){
001216          int i = 0; 
001217          pParse->nMem = 8;
001218          sqlite3CodeVerifySchema(pParse, iDb);
001219          while(pFK){
001220            int j;
001221            for(j=0; j<pFK->nCol; j++){
001222              sqlite3VdbeMultiLoad(v, 1, "iissssss",
001223                     i,
001224                     j,
001225                     pFK->zTo,
001226                     pTab->aCol[pFK->aCol[j].iFrom].zName,
001227                     pFK->aCol[j].zCol,
001228                     actionName(pFK->aAction[1]),  /* ON UPDATE */
001229                     actionName(pFK->aAction[0]),  /* ON DELETE */
001230                     "NONE");
001231              sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
001232            }
001233            ++i;
001234            pFK = pFK->pNextFrom;
001235          }
001236        }
001237      }
001238    }
001239    break;
001240  #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
001241  
001242  #ifndef SQLITE_OMIT_FOREIGN_KEY
001243  #ifndef SQLITE_OMIT_TRIGGER
001244    case PragTyp_FOREIGN_KEY_CHECK: {
001245      FKey *pFK;             /* A foreign key constraint */
001246      Table *pTab;           /* Child table contain "REFERENCES" keyword */
001247      Table *pParent;        /* Parent table that child points to */
001248      Index *pIdx;           /* Index in the parent table */
001249      int i;                 /* Loop counter:  Foreign key number for pTab */
001250      int j;                 /* Loop counter:  Field of the foreign key */
001251      HashElem *k;           /* Loop counter:  Next table in schema */
001252      int x;                 /* result variable */
001253      int regResult;         /* 3 registers to hold a result row */
001254      int regKey;            /* Register to hold key for checking the FK */
001255      int regRow;            /* Registers to hold a row from pTab */
001256      int addrTop;           /* Top of a loop checking foreign keys */
001257      int addrOk;            /* Jump here if the key is OK */
001258      int *aiCols;           /* child to parent column mapping */
001259  
001260      regResult = pParse->nMem+1;
001261      pParse->nMem += 4;
001262      regKey = ++pParse->nMem;
001263      regRow = ++pParse->nMem;
001264      sqlite3CodeVerifySchema(pParse, iDb);
001265      k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
001266      while( k ){
001267        if( zRight ){
001268          pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
001269          k = 0;
001270        }else{
001271          pTab = (Table*)sqliteHashData(k);
001272          k = sqliteHashNext(k);
001273        }
001274        if( pTab==0 || pTab->pFKey==0 ) continue;
001275        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
001276        if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
001277        sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
001278        sqlite3VdbeLoadString(v, regResult, pTab->zName);
001279        for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
001280          pParent = sqlite3FindTable(db, pFK->zTo, zDb);
001281          if( pParent==0 ) continue;
001282          pIdx = 0;
001283          sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
001284          x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
001285          if( x==0 ){
001286            if( pIdx==0 ){
001287              sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
001288            }else{
001289              sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
001290              sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
001291            }
001292          }else{
001293            k = 0;
001294            break;
001295          }
001296        }
001297        assert( pParse->nErr>0 || pFK==0 );
001298        if( pFK ) break;
001299        if( pParse->nTab<i ) pParse->nTab = i;
001300        addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
001301        for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
001302          pParent = sqlite3FindTable(db, pFK->zTo, zDb);
001303          pIdx = 0;
001304          aiCols = 0;
001305          if( pParent ){
001306            x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
001307            assert( x==0 );
001308          }
001309          addrOk = sqlite3VdbeMakeLabel(v);
001310          if( pParent && pIdx==0 ){
001311            int iKey = pFK->aCol[0].iFrom;
001312            assert( iKey>=0 && iKey<pTab->nCol );
001313            if( iKey!=pTab->iPKey ){
001314              sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
001315              sqlite3ColumnDefault(v, pTab, iKey, regRow);
001316              sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
001317            }else{
001318              sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
001319            }
001320            sqlite3VdbeAddOp3(v, OP_SeekRowid, i, 0, regRow); VdbeCoverage(v);
001321            sqlite3VdbeGoto(v, addrOk);
001322            sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
001323          }else{
001324            for(j=0; j<pFK->nCol; j++){
001325              sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
001326                              aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
001327              sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
001328            }
001329            if( pParent ){
001330              sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
001331                                sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
001332              sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
001333              VdbeCoverage(v);
001334            }
001335          }
001336          sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
001337          sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1);
001338          sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
001339          sqlite3VdbeResolveLabel(v, addrOk);
001340          sqlite3DbFree(db, aiCols);
001341        }
001342        sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
001343        sqlite3VdbeJumpHere(v, addrTop);
001344      }
001345    }
001346    break;
001347  #endif /* !defined(SQLITE_OMIT_TRIGGER) */
001348  #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
001349  
001350  #ifndef NDEBUG
001351    case PragTyp_PARSER_TRACE: {
001352      if( zRight ){
001353        if( sqlite3GetBoolean(zRight, 0) ){
001354          sqlite3ParserTrace(stdout, "parser: ");
001355        }else{
001356          sqlite3ParserTrace(0, 0);
001357        }
001358      }
001359    }
001360    break;
001361  #endif
001362  
001363    /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
001364    ** used will be case sensitive or not depending on the RHS.
001365    */
001366    case PragTyp_CASE_SENSITIVE_LIKE: {
001367      if( zRight ){
001368        sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
001369      }
001370    }
001371    break;
001372  
001373  #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
001374  # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
001375  #endif
001376  
001377  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
001378    /* Pragma "quick_check" is reduced version of 
001379    ** integrity_check designed to detect most database corruption
001380    ** without most of the overhead of a full integrity-check.
001381    */
001382    case PragTyp_INTEGRITY_CHECK: {
001383      int i, j, addr, mxErr;
001384  
001385      int isQuick = (sqlite3Tolower(zLeft[0])=='q');
001386  
001387      /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
001388      ** then iDb is set to the index of the database identified by <db>.
001389      ** In this case, the integrity of database iDb only is verified by
001390      ** the VDBE created below.
001391      **
001392      ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
001393      ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
001394      ** to -1 here, to indicate that the VDBE should verify the integrity
001395      ** of all attached databases.  */
001396      assert( iDb>=0 );
001397      assert( iDb==0 || pId2->z );
001398      if( pId2->z==0 ) iDb = -1;
001399  
001400      /* Initialize the VDBE program */
001401      pParse->nMem = 6;
001402  
001403      /* Set the maximum error count */
001404      mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
001405      if( zRight ){
001406        sqlite3GetInt32(zRight, &mxErr);
001407        if( mxErr<=0 ){
001408          mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
001409        }
001410      }
001411      sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
001412  
001413      /* Do an integrity check on each database file */
001414      for(i=0; i<db->nDb; i++){
001415        HashElem *x;
001416        Hash *pTbls;
001417        int *aRoot;
001418        int cnt = 0;
001419        int mxIdx = 0;
001420        int nIdx;
001421  
001422        if( OMIT_TEMPDB && i==1 ) continue;
001423        if( iDb>=0 && i!=iDb ) continue;
001424  
001425        sqlite3CodeVerifySchema(pParse, i);
001426        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
001427        VdbeCoverage(v);
001428        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
001429        sqlite3VdbeJumpHere(v, addr);
001430  
001431        /* Do an integrity check of the B-Tree
001432        **
001433        ** Begin by finding the root pages numbers
001434        ** for all tables and indices in the database.
001435        */
001436        assert( sqlite3SchemaMutexHeld(db, i, 0) );
001437        pTbls = &db->aDb[i].pSchema->tblHash;
001438        for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
001439          Table *pTab = sqliteHashData(x);
001440          Index *pIdx;
001441          if( HasRowid(pTab) ) cnt++;
001442          for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
001443          if( nIdx>mxIdx ) mxIdx = nIdx;
001444        }
001445        aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
001446        if( aRoot==0 ) break;
001447        for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
001448          Table *pTab = sqliteHashData(x);
001449          Index *pIdx;
001450          if( HasRowid(pTab) ) aRoot[cnt++] = pTab->tnum;
001451          for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
001452            aRoot[cnt++] = pIdx->tnum;
001453          }
001454        }
001455        aRoot[cnt] = 0;
001456  
001457        /* Make sure sufficient number of registers have been allocated */
001458        pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
001459  
001460        /* Do the b-tree integrity checks */
001461        sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
001462        sqlite3VdbeChangeP5(v, (u8)i);
001463        addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
001464        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
001465           sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
001466           P4_DYNAMIC);
001467        sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
001468        sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
001469        sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
001470        sqlite3VdbeJumpHere(v, addr);
001471  
001472        /* Make sure all the indices are constructed correctly.
001473        */
001474        for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
001475          Table *pTab = sqliteHashData(x);
001476          Index *pIdx, *pPk;
001477          Index *pPrior = 0;
001478          int loopTop;
001479          int iDataCur, iIdxCur;
001480          int r1 = -1;
001481  
001482          if( pTab->pIndex==0 ) continue;
001483          pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
001484          addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
001485          VdbeCoverage(v);
001486          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
001487          sqlite3VdbeJumpHere(v, addr);
001488          sqlite3ExprCacheClear(pParse);
001489          sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
001490                                     1, 0, &iDataCur, &iIdxCur);
001491          sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
001492          for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
001493            sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
001494          }
001495          assert( pParse->nMem>=8+j );
001496          assert( sqlite3NoTempsInRange(pParse,1,7+j) );
001497          sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
001498          loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
001499          /* Verify that all NOT NULL columns really are NOT NULL */
001500          for(j=0; j<pTab->nCol; j++){
001501            char *zErr;
001502            int jmp2, jmp3;
001503            if( j==pTab->iPKey ) continue;
001504            if( pTab->aCol[j].notNull==0 ) continue;
001505            sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
001506            sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
001507            jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
001508            sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
001509            zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
001510                                pTab->aCol[j].zName);
001511            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
001512            sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
001513            jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
001514            sqlite3VdbeAddOp0(v, OP_Halt);
001515            sqlite3VdbeJumpHere(v, jmp2);
001516            sqlite3VdbeJumpHere(v, jmp3);
001517          }
001518          /* Validate index entries for the current row */
001519          for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
001520            int jmp2, jmp3, jmp4, jmp5;
001521            int ckUniq = sqlite3VdbeMakeLabel(v);
001522            if( pPk==pIdx ) continue;
001523            r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
001524                                         pPrior, r1);
001525            pPrior = pIdx;
001526            sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);  /* increment entry count */
001527            /* Verify that an index entry exists for the current table row */
001528            jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
001529                                        pIdx->nColumn); VdbeCoverage(v);
001530            sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
001531            sqlite3VdbeLoadString(v, 3, "row ");
001532            sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
001533            sqlite3VdbeLoadString(v, 4, " missing from index ");
001534            sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
001535            jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
001536            sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
001537            sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
001538            jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
001539            sqlite3VdbeAddOp0(v, OP_Halt);
001540            sqlite3VdbeJumpHere(v, jmp2);
001541            /* For UNIQUE indexes, verify that only one entry exists with the
001542            ** current key.  The entry is unique if (1) any column is NULL
001543            ** or (2) the next entry has a different key */
001544            if( IsUniqueIndex(pIdx) ){
001545              int uniqOk = sqlite3VdbeMakeLabel(v);
001546              int jmp6;
001547              int kk;
001548              for(kk=0; kk<pIdx->nKeyCol; kk++){
001549                int iCol = pIdx->aiColumn[kk];
001550                assert( iCol!=XN_ROWID && iCol<pTab->nCol );
001551                if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
001552                sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
001553                VdbeCoverage(v);
001554              }
001555              jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
001556              sqlite3VdbeGoto(v, uniqOk);
001557              sqlite3VdbeJumpHere(v, jmp6);
001558              sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
001559                                   pIdx->nKeyCol); VdbeCoverage(v);
001560              sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
001561              sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
001562              sqlite3VdbeGoto(v, jmp5);
001563              sqlite3VdbeResolveLabel(v, uniqOk);
001564            }
001565            sqlite3VdbeJumpHere(v, jmp4);
001566            sqlite3ResolvePartIdxLabel(pParse, jmp3);
001567          }
001568          sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
001569          sqlite3VdbeJumpHere(v, loopTop-1);
001570  #ifndef SQLITE_OMIT_BTREECOUNT
001571          sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
001572          for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
001573            if( pPk==pIdx ) continue;
001574            addr = sqlite3VdbeCurrentAddr(v);
001575            sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
001576            sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
001577            sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
001578            sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
001579            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
001580            sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
001581            sqlite3VdbeLoadString(v, 3, pIdx->zName);
001582            sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
001583            sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
001584          }
001585  #endif /* SQLITE_OMIT_BTREECOUNT */
001586        } 
001587      }
001588      {
001589        static const int iLn = VDBE_OFFSET_LINENO(2);
001590        static const VdbeOpList endCode[] = {
001591          { OP_AddImm,      1, 0,        0},    /* 0 */
001592          { OP_If,          1, 4,        0},    /* 1 */
001593          { OP_String8,     0, 3,        0},    /* 2 */
001594          { OP_ResultRow,   3, 1,        0},    /* 3 */
001595        };
001596        VdbeOp *aOp;
001597  
001598        aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
001599        if( aOp ){
001600          aOp[0].p2 = -mxErr;
001601          aOp[2].p4type = P4_STATIC;
001602          aOp[2].p4.z = "ok";
001603        }
001604      }
001605    }
001606    break;
001607  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
001608  
001609  #ifndef SQLITE_OMIT_UTF16
001610    /*
001611    **   PRAGMA encoding
001612    **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
001613    **
001614    ** In its first form, this pragma returns the encoding of the main
001615    ** database. If the database is not initialized, it is initialized now.
001616    **
001617    ** The second form of this pragma is a no-op if the main database file
001618    ** has not already been initialized. In this case it sets the default
001619    ** encoding that will be used for the main database file if a new file
001620    ** is created. If an existing main database file is opened, then the
001621    ** default text encoding for the existing database is used.
001622    ** 
001623    ** In all cases new databases created using the ATTACH command are
001624    ** created to use the same default text encoding as the main database. If
001625    ** the main database has not been initialized and/or created when ATTACH
001626    ** is executed, this is done before the ATTACH operation.
001627    **
001628    ** In the second form this pragma sets the text encoding to be used in
001629    ** new database files created using this database handle. It is only
001630    ** useful if invoked immediately after the main database i
001631    */
001632    case PragTyp_ENCODING: {
001633      static const struct EncName {
001634        char *zName;
001635        u8 enc;
001636      } encnames[] = {
001637        { "UTF8",     SQLITE_UTF8        },
001638        { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
001639        { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
001640        { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
001641        { "UTF16le",  SQLITE_UTF16LE     },
001642        { "UTF16be",  SQLITE_UTF16BE     },
001643        { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
001644        { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
001645        { 0, 0 }
001646      };
001647      const struct EncName *pEnc;
001648      if( !zRight ){    /* "PRAGMA encoding" */
001649        if( sqlite3ReadSchema(pParse) ) goto pragma_out;
001650        assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
001651        assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
001652        assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
001653        returnSingleText(v, encnames[ENC(pParse->db)].zName);
001654      }else{                        /* "PRAGMA encoding = XXX" */
001655        /* Only change the value of sqlite.enc if the database handle is not
001656        ** initialized. If the main database exists, the new sqlite.enc value
001657        ** will be overwritten when the schema is next loaded. If it does not
001658        ** already exists, it will be created to use the new encoding value.
001659        */
001660        if( 
001661          !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
001662          DbHasProperty(db, 0, DB_Empty) 
001663        ){
001664          for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
001665            if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
001666              SCHEMA_ENC(db) = ENC(db) =
001667                  pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
001668              break;
001669            }
001670          }
001671          if( !pEnc->zName ){
001672            sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
001673          }
001674        }
001675      }
001676    }
001677    break;
001678  #endif /* SQLITE_OMIT_UTF16 */
001679  
001680  #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
001681    /*
001682    **   PRAGMA [schema.]schema_version
001683    **   PRAGMA [schema.]schema_version = <integer>
001684    **
001685    **   PRAGMA [schema.]user_version
001686    **   PRAGMA [schema.]user_version = <integer>
001687    **
001688    **   PRAGMA [schema.]freelist_count
001689    **
001690    **   PRAGMA [schema.]data_version
001691    **
001692    **   PRAGMA [schema.]application_id
001693    **   PRAGMA [schema.]application_id = <integer>
001694    **
001695    ** The pragma's schema_version and user_version are used to set or get
001696    ** the value of the schema-version and user-version, respectively. Both
001697    ** the schema-version and the user-version are 32-bit signed integers
001698    ** stored in the database header.
001699    **
001700    ** The schema-cookie is usually only manipulated internally by SQLite. It
001701    ** is incremented by SQLite whenever the database schema is modified (by
001702    ** creating or dropping a table or index). The schema version is used by
001703    ** SQLite each time a query is executed to ensure that the internal cache
001704    ** of the schema used when compiling the SQL query matches the schema of
001705    ** the database against which the compiled query is actually executed.
001706    ** Subverting this mechanism by using "PRAGMA schema_version" to modify
001707    ** the schema-version is potentially dangerous and may lead to program
001708    ** crashes or database corruption. Use with caution!
001709    **
001710    ** The user-version is not used internally by SQLite. It may be used by
001711    ** applications for any purpose.
001712    */
001713    case PragTyp_HEADER_VALUE: {
001714      int iCookie = pPragma->iArg;  /* Which cookie to read or write */
001715      sqlite3VdbeUsesBtree(v, iDb);
001716      if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
001717        /* Write the specified cookie value */
001718        static const VdbeOpList setCookie[] = {
001719          { OP_Transaction,    0,  1,  0},    /* 0 */
001720          { OP_SetCookie,      0,  0,  0},    /* 1 */
001721        };
001722        VdbeOp *aOp;
001723        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
001724        aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
001725        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
001726        aOp[0].p1 = iDb;
001727        aOp[1].p1 = iDb;
001728        aOp[1].p2 = iCookie;
001729        aOp[1].p3 = sqlite3Atoi(zRight);
001730      }else{
001731        /* Read the specified cookie value */
001732        static const VdbeOpList readCookie[] = {
001733          { OP_Transaction,     0,  0,  0},    /* 0 */
001734          { OP_ReadCookie,      0,  1,  0},    /* 1 */
001735          { OP_ResultRow,       1,  1,  0}
001736        };
001737        VdbeOp *aOp;
001738        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
001739        aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
001740        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
001741        aOp[0].p1 = iDb;
001742        aOp[1].p1 = iDb;
001743        aOp[1].p3 = iCookie;
001744        sqlite3VdbeReusable(v);
001745      }
001746    }
001747    break;
001748  #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
001749  
001750  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
001751    /*
001752    **   PRAGMA compile_options
001753    **
001754    ** Return the names of all compile-time options used in this build,
001755    ** one option per row.
001756    */
001757    case PragTyp_COMPILE_OPTIONS: {
001758      int i = 0;
001759      const char *zOpt;
001760      pParse->nMem = 1;
001761      while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
001762        sqlite3VdbeLoadString(v, 1, zOpt);
001763        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
001764      }
001765      sqlite3VdbeReusable(v);
001766    }
001767    break;
001768  #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
001769  
001770  #ifndef SQLITE_OMIT_WAL
001771    /*
001772    **   PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
001773    **
001774    ** Checkpoint the database.
001775    */
001776    case PragTyp_WAL_CHECKPOINT: {
001777      int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
001778      int eMode = SQLITE_CHECKPOINT_PASSIVE;
001779      if( zRight ){
001780        if( sqlite3StrICmp(zRight, "full")==0 ){
001781          eMode = SQLITE_CHECKPOINT_FULL;
001782        }else if( sqlite3StrICmp(zRight, "restart")==0 ){
001783          eMode = SQLITE_CHECKPOINT_RESTART;
001784        }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
001785          eMode = SQLITE_CHECKPOINT_TRUNCATE;
001786        }
001787      }
001788      pParse->nMem = 3;
001789      sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
001790      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
001791    }
001792    break;
001793  
001794    /*
001795    **   PRAGMA wal_autocheckpoint
001796    **   PRAGMA wal_autocheckpoint = N
001797    **
001798    ** Configure a database connection to automatically checkpoint a database
001799    ** after accumulating N frames in the log. Or query for the current value
001800    ** of N.
001801    */
001802    case PragTyp_WAL_AUTOCHECKPOINT: {
001803      if( zRight ){
001804        sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
001805      }
001806      returnSingleInt(v, 
001807         db->xWalCallback==sqlite3WalDefaultHook ? 
001808             SQLITE_PTR_TO_INT(db->pWalArg) : 0);
001809    }
001810    break;
001811  #endif
001812  
001813    /*
001814    **  PRAGMA shrink_memory
001815    **
001816    ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
001817    ** connection on which it is invoked to free up as much memory as it
001818    ** can, by calling sqlite3_db_release_memory().
001819    */
001820    case PragTyp_SHRINK_MEMORY: {
001821      sqlite3_db_release_memory(db);
001822      break;
001823    }
001824  
001825    /*
001826    **   PRAGMA busy_timeout
001827    **   PRAGMA busy_timeout = N
001828    **
001829    ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
001830    ** if one is set.  If no busy handler or a different busy handler is set
001831    ** then 0 is returned.  Setting the busy_timeout to 0 or negative
001832    ** disables the timeout.
001833    */
001834    /*case PragTyp_BUSY_TIMEOUT*/ default: {
001835      assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
001836      if( zRight ){
001837        sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
001838      }
001839      returnSingleInt(v, db->busyTimeout);
001840      break;
001841    }
001842  
001843    /*
001844    **   PRAGMA soft_heap_limit
001845    **   PRAGMA soft_heap_limit = N
001846    **
001847    ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
001848    ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
001849    ** specified and is a non-negative integer.
001850    ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
001851    ** returns the same integer that would be returned by the
001852    ** sqlite3_soft_heap_limit64(-1) C-language function.
001853    */
001854    case PragTyp_SOFT_HEAP_LIMIT: {
001855      sqlite3_int64 N;
001856      if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
001857        sqlite3_soft_heap_limit64(N);
001858      }
001859      returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
001860      break;
001861    }
001862  
001863    /*
001864    **   PRAGMA threads
001865    **   PRAGMA threads = N
001866    **
001867    ** Configure the maximum number of worker threads.  Return the new
001868    ** maximum, which might be less than requested.
001869    */
001870    case PragTyp_THREADS: {
001871      sqlite3_int64 N;
001872      if( zRight
001873       && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
001874       && N>=0
001875      ){
001876        sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
001877      }
001878      returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
001879      break;
001880    }
001881  
001882  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
001883    /*
001884    ** Report the current state of file logs for all databases
001885    */
001886    case PragTyp_LOCK_STATUS: {
001887      static const char *const azLockName[] = {
001888        "unlocked", "shared", "reserved", "pending", "exclusive"
001889      };
001890      int i;
001891      pParse->nMem = 2;
001892      for(i=0; i<db->nDb; i++){
001893        Btree *pBt;
001894        const char *zState = "unknown";
001895        int j;
001896        if( db->aDb[i].zDbSName==0 ) continue;
001897        pBt = db->aDb[i].pBt;
001898        if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
001899          zState = "closed";
001900        }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0, 
001901                                       SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
001902           zState = azLockName[j];
001903        }
001904        sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
001905        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
001906      }
001907      break;
001908    }
001909  #endif
001910  
001911  #ifdef SQLITE_HAS_CODEC
001912    case PragTyp_KEY: {
001913      if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
001914      break;
001915    }
001916    case PragTyp_REKEY: {
001917      if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
001918      break;
001919    }
001920    case PragTyp_HEXKEY: {
001921      if( zRight ){
001922        u8 iByte;
001923        int i;
001924        char zKey[40];
001925        for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
001926          iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
001927          if( (i&1)!=0 ) zKey[i/2] = iByte;
001928        }
001929        if( (zLeft[3] & 0xf)==0xb ){
001930          sqlite3_key_v2(db, zDb, zKey, i/2);
001931        }else{
001932          sqlite3_rekey_v2(db, zDb, zKey, i/2);
001933        }
001934      }
001935      break;
001936    }
001937  #endif
001938  #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
001939    case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
001940  #ifdef SQLITE_HAS_CODEC
001941      if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
001942        sqlite3_activate_see(&zRight[4]);
001943      }
001944  #endif
001945  #ifdef SQLITE_ENABLE_CEROD
001946      if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
001947        sqlite3_activate_cerod(&zRight[6]);
001948      }
001949  #endif
001950    }
001951    break;
001952  #endif
001953  
001954    } /* End of the PRAGMA switch */
001955  
001956  pragma_out:
001957    sqlite3DbFree(db, zLeft);
001958    sqlite3DbFree(db, zRight);
001959  }
001960  #ifndef SQLITE_OMIT_VIRTUALTABLE
001961  /*****************************************************************************
001962  ** Implementation of an eponymous virtual table that runs a pragma.
001963  **
001964  */
001965  typedef struct PragmaVtab PragmaVtab;
001966  typedef struct PragmaVtabCursor PragmaVtabCursor;
001967  struct PragmaVtab {
001968    sqlite3_vtab base;        /* Base class.  Must be first */
001969    sqlite3 *db;              /* The database connection to which it belongs */
001970    const PragmaName *pName;  /* Name of the pragma */
001971    u8 nHidden;               /* Number of hidden columns */
001972    u8 iHidden;               /* Index of the first hidden column */
001973  };
001974  struct PragmaVtabCursor {
001975    sqlite3_vtab_cursor base; /* Base class.  Must be first */
001976    sqlite3_stmt *pPragma;    /* The pragma statement to run */
001977    sqlite_int64 iRowid;      /* Current rowid */
001978    char *azArg[2];           /* Value of the argument and schema */
001979  };
001980  
001981  /* 
001982  ** Pragma virtual table module xConnect method.
001983  */
001984  static int pragmaVtabConnect(
001985    sqlite3 *db,
001986    void *pAux,
001987    int argc, const char *const*argv,
001988    sqlite3_vtab **ppVtab,
001989    char **pzErr
001990  ){
001991    const PragmaName *pPragma = (const PragmaName*)pAux;
001992    PragmaVtab *pTab = 0;
001993    int rc;
001994    int i, j;
001995    char cSep = '(';
001996    StrAccum acc;
001997    char zBuf[200];
001998  
001999    UNUSED_PARAMETER(argc);
002000    UNUSED_PARAMETER(argv);
002001    sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
002002    sqlite3StrAccumAppendAll(&acc, "CREATE TABLE x");
002003    for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
002004      sqlite3XPrintf(&acc, "%c\"%s\"", cSep, pragCName[j]);
002005      cSep = ',';
002006    }
002007    if( i==0 ){
002008      sqlite3XPrintf(&acc, "(\"%s\"", pPragma->zName);
002009      cSep = ',';
002010      i++;
002011    }
002012    j = 0;
002013    if( pPragma->mPragFlg & PragFlg_Result1 ){
002014      sqlite3StrAccumAppendAll(&acc, ",arg HIDDEN");
002015      j++;
002016    }
002017    if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
002018      sqlite3StrAccumAppendAll(&acc, ",schema HIDDEN");
002019      j++;
002020    }
002021    sqlite3StrAccumAppend(&acc, ")", 1);
002022    sqlite3StrAccumFinish(&acc);
002023    assert( strlen(zBuf) < sizeof(zBuf)-1 );
002024    rc = sqlite3_declare_vtab(db, zBuf);
002025    if( rc==SQLITE_OK ){
002026      pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
002027      if( pTab==0 ){
002028        rc = SQLITE_NOMEM;
002029      }else{
002030        memset(pTab, 0, sizeof(PragmaVtab));
002031        pTab->pName = pPragma;
002032        pTab->db = db;
002033        pTab->iHidden = i;
002034        pTab->nHidden = j;
002035      }
002036    }else{
002037      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
002038    }
002039  
002040    *ppVtab = (sqlite3_vtab*)pTab;
002041    return rc;
002042  }
002043  
002044  /* 
002045  ** Pragma virtual table module xDisconnect method.
002046  */
002047  static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
002048    PragmaVtab *pTab = (PragmaVtab*)pVtab;
002049    sqlite3_free(pTab);
002050    return SQLITE_OK;
002051  }
002052  
002053  /* Figure out the best index to use to search a pragma virtual table.
002054  **
002055  ** There are not really any index choices.  But we want to encourage the
002056  ** query planner to give == constraints on as many hidden parameters as
002057  ** possible, and especially on the first hidden parameter.  So return a
002058  ** high cost if hidden parameters are unconstrained.
002059  */
002060  static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
002061    PragmaVtab *pTab = (PragmaVtab*)tab;
002062    const struct sqlite3_index_constraint *pConstraint;
002063    int i, j;
002064    int seen[2];
002065  
002066    pIdxInfo->estimatedCost = (double)1;
002067    if( pTab->nHidden==0 ){ return SQLITE_OK; }
002068    pConstraint = pIdxInfo->aConstraint;
002069    seen[0] = 0;
002070    seen[1] = 0;
002071    for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
002072      if( pConstraint->usable==0 ) continue;
002073      if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
002074      if( pConstraint->iColumn < pTab->iHidden ) continue;
002075      j = pConstraint->iColumn - pTab->iHidden;
002076      assert( j < 2 );
002077      seen[j] = i+1;
002078    }
002079    if( seen[0]==0 ){
002080      pIdxInfo->estimatedCost = (double)2147483647;
002081      pIdxInfo->estimatedRows = 2147483647;
002082      return SQLITE_OK;
002083    }
002084    j = seen[0]-1;
002085    pIdxInfo->aConstraintUsage[j].argvIndex = 1;
002086    pIdxInfo->aConstraintUsage[j].omit = 1;
002087    if( seen[1]==0 ) return SQLITE_OK;
002088    pIdxInfo->estimatedCost = (double)20;
002089    pIdxInfo->estimatedRows = 20;
002090    j = seen[1]-1;
002091    pIdxInfo->aConstraintUsage[j].argvIndex = 2;
002092    pIdxInfo->aConstraintUsage[j].omit = 1;
002093    return SQLITE_OK;
002094  }
002095  
002096  /* Create a new cursor for the pragma virtual table */
002097  static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
002098    PragmaVtabCursor *pCsr;
002099    pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
002100    if( pCsr==0 ) return SQLITE_NOMEM;
002101    memset(pCsr, 0, sizeof(PragmaVtabCursor));
002102    pCsr->base.pVtab = pVtab;
002103    *ppCursor = &pCsr->base;
002104    return SQLITE_OK;
002105  }
002106  
002107  /* Clear all content from pragma virtual table cursor. */
002108  static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
002109    int i;
002110    sqlite3_finalize(pCsr->pPragma);
002111    pCsr->pPragma = 0;
002112    for(i=0; i<ArraySize(pCsr->azArg); i++){
002113      sqlite3_free(pCsr->azArg[i]);
002114      pCsr->azArg[i] = 0;
002115    }
002116  }
002117  
002118  /* Close a pragma virtual table cursor */
002119  static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
002120    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
002121    pragmaVtabCursorClear(pCsr);
002122    sqlite3_free(pCsr);
002123    return SQLITE_OK;
002124  }
002125  
002126  /* Advance the pragma virtual table cursor to the next row */
002127  static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
002128    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
002129    int rc = SQLITE_OK;
002130  
002131    /* Increment the xRowid value */
002132    pCsr->iRowid++;
002133    assert( pCsr->pPragma );
002134    if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
002135      rc = sqlite3_finalize(pCsr->pPragma);
002136      pCsr->pPragma = 0;
002137      pragmaVtabCursorClear(pCsr);
002138    }
002139    return rc;
002140  }
002141  
002142  /* 
002143  ** Pragma virtual table module xFilter method.
002144  */
002145  static int pragmaVtabFilter(
002146    sqlite3_vtab_cursor *pVtabCursor, 
002147    int idxNum, const char *idxStr,
002148    int argc, sqlite3_value **argv
002149  ){
002150    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
002151    PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
002152    int rc;
002153    int i, j;
002154    StrAccum acc;
002155    char *zSql;
002156  
002157    UNUSED_PARAMETER(idxNum);
002158    UNUSED_PARAMETER(idxStr);
002159    pragmaVtabCursorClear(pCsr);
002160    j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
002161    for(i=0; i<argc; i++, j++){
002162      assert( j<ArraySize(pCsr->azArg) );
002163      pCsr->azArg[j] = sqlite3_mprintf("%s", sqlite3_value_text(argv[i]));
002164      if( pCsr->azArg[j]==0 ){
002165        return SQLITE_NOMEM;
002166      }
002167    }
002168    sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
002169    sqlite3StrAccumAppendAll(&acc, "PRAGMA ");
002170    if( pCsr->azArg[1] ){
002171      sqlite3XPrintf(&acc, "%Q.", pCsr->azArg[1]);
002172    }
002173    sqlite3StrAccumAppendAll(&acc, pTab->pName->zName);
002174    if( pCsr->azArg[0] ){
002175      sqlite3XPrintf(&acc, "=%Q", pCsr->azArg[0]);
002176    }
002177    zSql = sqlite3StrAccumFinish(&acc);
002178    if( zSql==0 ) return SQLITE_NOMEM;
002179    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
002180    sqlite3_free(zSql);
002181    if( rc!=SQLITE_OK ){
002182      pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
002183      return rc;
002184    }
002185    return pragmaVtabNext(pVtabCursor);
002186  }
002187  
002188  /*
002189  ** Pragma virtual table module xEof method.
002190  */
002191  static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
002192    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
002193    return (pCsr->pPragma==0);
002194  }
002195  
002196  /* The xColumn method simply returns the corresponding column from
002197  ** the PRAGMA.  
002198  */
002199  static int pragmaVtabColumn(
002200    sqlite3_vtab_cursor *pVtabCursor, 
002201    sqlite3_context *ctx, 
002202    int i
002203  ){
002204    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
002205    PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
002206    if( i<pTab->iHidden ){
002207      sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
002208    }else{
002209      sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
002210    }
002211    return SQLITE_OK;
002212  }
002213  
002214  /* 
002215  ** Pragma virtual table module xRowid method.
002216  */
002217  static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
002218    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
002219    *p = pCsr->iRowid;
002220    return SQLITE_OK;
002221  }
002222  
002223  /* The pragma virtual table object */
002224  static const sqlite3_module pragmaVtabModule = {
002225    0,                           /* iVersion */
002226    0,                           /* xCreate - create a table */
002227    pragmaVtabConnect,           /* xConnect - connect to an existing table */
002228    pragmaVtabBestIndex,         /* xBestIndex - Determine search strategy */
002229    pragmaVtabDisconnect,        /* xDisconnect - Disconnect from a table */
002230    0,                           /* xDestroy - Drop a table */
002231    pragmaVtabOpen,              /* xOpen - open a cursor */
002232    pragmaVtabClose,             /* xClose - close a cursor */
002233    pragmaVtabFilter,            /* xFilter - configure scan constraints */
002234    pragmaVtabNext,              /* xNext - advance a cursor */
002235    pragmaVtabEof,               /* xEof */
002236    pragmaVtabColumn,            /* xColumn - read data */
002237    pragmaVtabRowid,             /* xRowid - read data */
002238    0,                           /* xUpdate - write data */
002239    0,                           /* xBegin - begin transaction */
002240    0,                           /* xSync - sync transaction */
002241    0,                           /* xCommit - commit transaction */
002242    0,                           /* xRollback - rollback transaction */
002243    0,                           /* xFindFunction - function overloading */
002244    0,                           /* xRename - rename the table */
002245    0,                           /* xSavepoint */
002246    0,                           /* xRelease */
002247    0                            /* xRollbackTo */
002248  };
002249  
002250  /*
002251  ** Check to see if zTabName is really the name of a pragma.  If it is,
002252  ** then register an eponymous virtual table for that pragma and return
002253  ** a pointer to the Module object for the new virtual table.
002254  */
002255  Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
002256    const PragmaName *pName;
002257    assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
002258    pName = pragmaLocate(zName+7);
002259    if( pName==0 ) return 0;
002260    if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
002261    assert( sqlite3HashFind(&db->aModule, zName)==0 );
002262    return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
002263  }
002264  
002265  #endif /* SQLITE_OMIT_VIRTUALTABLE */
002266  
002267  #endif /* SQLITE_OMIT_PRAGMA */