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