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