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