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