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