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
001148 if( sqlite3GetBoolean(zRight, 0) ){
001149 if( (mask & SQLITE_WriteSchema)==0
001150 || (db->flags & SQLITE_Defensive)==0
001151 ){
001152 db->flags |= mask;
001153 }
001154 }else{
001155 db->flags &= ~mask;
001156 if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
001157 if( (mask & SQLITE_WriteSchema)!=0
001158 && sqlite3_stricmp(zRight, "reset")==0
001159 ){
001160 /* IMP: R-60817-01178 If the argument is "RESET" then schema
001161 ** writing is disabled (as with "PRAGMA writable_schema=OFF") and,
001162 ** in addition, the schema is reloaded. */
001163 sqlite3ResetAllSchemasOfConnection(db);
001164 }
001165 }
001166
001167 /* Many of the flag-pragmas modify the code generated by the SQL
001168 ** compiler (eg. count_changes). So add an opcode to expire all
001169 ** compiled SQL statements after modifying a pragma value.
001170 */
001171 sqlite3VdbeAddOp0(v, OP_Expire);
001172 setAllPagerFlags(db);
001173 }
001174 break;
001175 }
001176 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
001177
001178 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
001179 /*
001180 ** PRAGMA table_info(<table>)
001181 **
001182 ** Return a single row for each column of the named table. The columns of
001183 ** the returned data set are:
001184 **
001185 ** cid: Column id (numbered from left to right, starting at 0)
001186 ** name: Column name
001187 ** type: Column declaration type.
001188 ** notnull: True if 'NOT NULL' is part of column declaration
001189 ** dflt_value: The default value for the column, if any.
001190 ** pk: Non-zero for PK fields.
001191 */
001192 case PragTyp_TABLE_INFO: if( zRight ){
001193 Table *pTab;
001194 sqlite3CodeVerifyNamedSchema(pParse, zDb);
001195 pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
001196 if( pTab ){
001197 int i, k;
001198 int nHidden = 0;
001199 Column *pCol;
001200 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
001201 pParse->nMem = 7;
001202 sqlite3ViewGetColumnNames(pParse, pTab);
001203 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
001204 int isHidden = 0;
001205 const Expr *pColExpr;
001206 if( pCol->colFlags & COLFLAG_NOINSERT ){
001207 if( pPragma->iArg==0 ){
001208 nHidden++;
001209 continue;
001210 }
001211 if( pCol->colFlags & COLFLAG_VIRTUAL ){
001212 isHidden = 2; /* GENERATED ALWAYS AS ... VIRTUAL */
001213 }else if( pCol->colFlags & COLFLAG_STORED ){
001214 isHidden = 3; /* GENERATED ALWAYS AS ... STORED */
001215 }else{ assert( pCol->colFlags & COLFLAG_HIDDEN );
001216 isHidden = 1; /* HIDDEN */
001217 }
001218 }
001219 if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
001220 k = 0;
001221 }else if( pPk==0 ){
001222 k = 1;
001223 }else{
001224 for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
001225 }
001226 pColExpr = sqlite3ColumnExpr(pTab,pCol);
001227 assert( pColExpr==0 || pColExpr->op==TK_SPAN || isHidden>=2 );
001228 assert( pColExpr==0 || !ExprHasProperty(pColExpr, EP_IntValue)
001229 || isHidden>=2 );
001230 sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
001231 i-nHidden,
001232 pCol->zCnName,
001233 sqlite3ColumnType(pCol,""),
001234 pCol->notNull ? 1 : 0,
001235 (isHidden>=2 || pColExpr==0) ? 0 : pColExpr->u.zToken,
001236 k,
001237 isHidden);
001238 }
001239 }
001240 }
001241 break;
001242
001243 /*
001244 ** PRAGMA table_list
001245 **
001246 ** Return a single row for each table, virtual table, or view in the
001247 ** entire schema.
001248 **
001249 ** schema: Name of attached database hold this table
001250 ** name: Name of the table itself
001251 ** type: "table", "view", "virtual", "shadow"
001252 ** ncol: Number of columns
001253 ** wr: True for a WITHOUT ROWID table
001254 ** strict: True for a STRICT table
001255 */
001256 case PragTyp_TABLE_LIST: {
001257 int ii;
001258 pParse->nMem = 6;
001259 sqlite3CodeVerifyNamedSchema(pParse, zDb);
001260 for(ii=0; ii<db->nDb; ii++){
001261 HashElem *k;
001262 Hash *pHash;
001263 int initNCol;
001264 if( zDb && sqlite3_stricmp(zDb, db->aDb[ii].zDbSName)!=0 ) continue;
001265
001266 /* Ensure that the Table.nCol field is initialized for all views
001267 ** and virtual tables. Each time we initialize a Table.nCol value
001268 ** for a table, that can potentially disrupt the hash table, so restart
001269 ** the initialization scan.
001270 */
001271 pHash = &db->aDb[ii].pSchema->tblHash;
001272 initNCol = sqliteHashCount(pHash);
001273 while( initNCol-- ){
001274 for(k=sqliteHashFirst(pHash); 1; k=sqliteHashNext(k) ){
001275 Table *pTab;
001276 if( k==0 ){ initNCol = 0; break; }
001277 pTab = sqliteHashData(k);
001278 if( pTab->nCol==0 ){
001279 char *zSql = sqlite3MPrintf(db, "SELECT*FROM\"%w\"", pTab->zName);
001280 if( zSql ){
001281 sqlite3_stmt *pDummy = 0;
001282 (void)sqlite3_prepare_v3(db, zSql, -1, SQLITE_PREPARE_DONT_LOG,
001283 &pDummy, 0);
001284 (void)sqlite3_finalize(pDummy);
001285 sqlite3DbFree(db, zSql);
001286 }
001287 if( db->mallocFailed ){
001288 sqlite3ErrorMsg(db->pParse, "out of memory");
001289 db->pParse->rc = SQLITE_NOMEM_BKPT;
001290 }
001291 pHash = &db->aDb[ii].pSchema->tblHash;
001292 break;
001293 }
001294 }
001295 }
001296
001297 for(k=sqliteHashFirst(pHash); k; k=sqliteHashNext(k) ){
001298 Table *pTab = sqliteHashData(k);
001299 const char *zType;
001300 if( zRight && sqlite3_stricmp(zRight, pTab->zName)!=0 ) continue;
001301 if( IsView(pTab) ){
001302 zType = "view";
001303 }else if( IsVirtual(pTab) ){
001304 zType = "virtual";
001305 }else if( pTab->tabFlags & TF_Shadow ){
001306 zType = "shadow";
001307 }else{
001308 zType = "table";
001309 }
001310 sqlite3VdbeMultiLoad(v, 1, "sssiii",
001311 db->aDb[ii].zDbSName,
001312 sqlite3PreferredTableName(pTab->zName),
001313 zType,
001314 pTab->nCol,
001315 (pTab->tabFlags & TF_WithoutRowid)!=0,
001316 (pTab->tabFlags & TF_Strict)!=0
001317 );
001318 }
001319 }
001320 }
001321 break;
001322
001323 #ifdef SQLITE_DEBUG
001324 case PragTyp_STATS: {
001325 Index *pIdx;
001326 HashElem *i;
001327 pParse->nMem = 5;
001328 sqlite3CodeVerifySchema(pParse, iDb);
001329 for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
001330 Table *pTab = sqliteHashData(i);
001331 sqlite3VdbeMultiLoad(v, 1, "ssiii",
001332 sqlite3PreferredTableName(pTab->zName),
001333 0,
001334 pTab->szTabRow,
001335 pTab->nRowLogEst,
001336 pTab->tabFlags);
001337 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
001338 sqlite3VdbeMultiLoad(v, 2, "siiiX",
001339 pIdx->zName,
001340 pIdx->szIdxRow,
001341 pIdx->aiRowLogEst[0],
001342 pIdx->hasStat1);
001343 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
001344 }
001345 }
001346 }
001347 break;
001348 #endif
001349
001350 case PragTyp_INDEX_INFO: if( zRight ){
001351 Index *pIdx;
001352 Table *pTab;
001353 pIdx = sqlite3FindIndex(db, zRight, zDb);
001354 if( pIdx==0 ){
001355 /* If there is no index named zRight, check to see if there is a
001356 ** WITHOUT ROWID table named zRight, and if there is, show the
001357 ** structure of the PRIMARY KEY index for that table. */
001358 pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
001359 if( pTab && !HasRowid(pTab) ){
001360 pIdx = sqlite3PrimaryKeyIndex(pTab);
001361 }
001362 }
001363 if( pIdx ){
001364 int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
001365 int i;
001366 int mx;
001367 if( pPragma->iArg ){
001368 /* PRAGMA index_xinfo (newer version with more rows and columns) */
001369 mx = pIdx->nColumn;
001370 pParse->nMem = 6;
001371 }else{
001372 /* PRAGMA index_info (legacy version) */
001373 mx = pIdx->nKeyCol;
001374 pParse->nMem = 3;
001375 }
001376 pTab = pIdx->pTable;
001377 sqlite3CodeVerifySchema(pParse, iIdxDb);
001378 assert( pParse->nMem<=pPragma->nPragCName );
001379 for(i=0; i<mx; i++){
001380 i16 cnum = pIdx->aiColumn[i];
001381 sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
001382 cnum<0 ? 0 : pTab->aCol[cnum].zCnName);
001383 if( pPragma->iArg ){
001384 sqlite3VdbeMultiLoad(v, 4, "isiX",
001385 pIdx->aSortOrder[i],
001386 pIdx->azColl[i],
001387 i<pIdx->nKeyCol);
001388 }
001389 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
001390 }
001391 }
001392 }
001393 break;
001394
001395 case PragTyp_INDEX_LIST: if( zRight ){
001396 Index *pIdx;
001397 Table *pTab;
001398 int i;
001399 pTab = sqlite3FindTable(db, zRight, zDb);
001400 if( pTab ){
001401 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
001402 pParse->nMem = 5;
001403 sqlite3CodeVerifySchema(pParse, iTabDb);
001404 for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
001405 const char *azOrigin[] = { "c", "u", "pk" };
001406 sqlite3VdbeMultiLoad(v, 1, "isisi",
001407 i,
001408 pIdx->zName,
001409 IsUniqueIndex(pIdx),
001410 azOrigin[pIdx->idxType],
001411 pIdx->pPartIdxWhere!=0);
001412 }
001413 }
001414 }
001415 break;
001416
001417 case PragTyp_DATABASE_LIST: {
001418 int i;
001419 pParse->nMem = 3;
001420 for(i=0; i<db->nDb; i++){
001421 if( db->aDb[i].pBt==0 ) continue;
001422 assert( db->aDb[i].zDbSName!=0 );
001423 sqlite3VdbeMultiLoad(v, 1, "iss",
001424 i,
001425 db->aDb[i].zDbSName,
001426 sqlite3BtreeGetFilename(db->aDb[i].pBt));
001427 }
001428 }
001429 break;
001430
001431 case PragTyp_COLLATION_LIST: {
001432 int i = 0;
001433 HashElem *p;
001434 pParse->nMem = 2;
001435 for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
001436 CollSeq *pColl = (CollSeq *)sqliteHashData(p);
001437 sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
001438 }
001439 }
001440 break;
001441
001442 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
001443 case PragTyp_FUNCTION_LIST: {
001444 int i;
001445 HashElem *j;
001446 FuncDef *p;
001447 int showInternFunc = (db->mDbFlags & DBFLAG_InternalFunc)!=0;
001448 pParse->nMem = 6;
001449 for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
001450 for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
001451 assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
001452 pragmaFunclistLine(v, p, 1, showInternFunc);
001453 }
001454 }
001455 for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
001456 p = (FuncDef*)sqliteHashData(j);
001457 assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
001458 pragmaFunclistLine(v, p, 0, showInternFunc);
001459 }
001460 }
001461 break;
001462
001463 #ifndef SQLITE_OMIT_VIRTUALTABLE
001464 case PragTyp_MODULE_LIST: {
001465 HashElem *j;
001466 pParse->nMem = 1;
001467 for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
001468 Module *pMod = (Module*)sqliteHashData(j);
001469 sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
001470 }
001471 }
001472 break;
001473 #endif /* SQLITE_OMIT_VIRTUALTABLE */
001474
001475 case PragTyp_PRAGMA_LIST: {
001476 int i;
001477 for(i=0; i<ArraySize(aPragmaName); i++){
001478 sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
001479 }
001480 }
001481 break;
001482 #endif /* SQLITE_INTROSPECTION_PRAGMAS */
001483
001484 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
001485
001486 #ifndef SQLITE_OMIT_FOREIGN_KEY
001487 case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
001488 FKey *pFK;
001489 Table *pTab;
001490 pTab = sqlite3FindTable(db, zRight, zDb);
001491 if( pTab && IsOrdinaryTable(pTab) ){
001492 pFK = pTab->u.tab.pFKey;
001493 if( pFK ){
001494 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
001495 int i = 0;
001496 pParse->nMem = 8;
001497 sqlite3CodeVerifySchema(pParse, iTabDb);
001498 while(pFK){
001499 int j;
001500 for(j=0; j<pFK->nCol; j++){
001501 sqlite3VdbeMultiLoad(v, 1, "iissssss",
001502 i,
001503 j,
001504 pFK->zTo,
001505 pTab->aCol[pFK->aCol[j].iFrom].zCnName,
001506 pFK->aCol[j].zCol,
001507 actionName(pFK->aAction[1]), /* ON UPDATE */
001508 actionName(pFK->aAction[0]), /* ON DELETE */
001509 "NONE");
001510 }
001511 ++i;
001512 pFK = pFK->pNextFrom;
001513 }
001514 }
001515 }
001516 }
001517 break;
001518 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
001519
001520 #ifndef SQLITE_OMIT_FOREIGN_KEY
001521 #ifndef SQLITE_OMIT_TRIGGER
001522 case PragTyp_FOREIGN_KEY_CHECK: {
001523 FKey *pFK; /* A foreign key constraint */
001524 Table *pTab; /* Child table contain "REFERENCES" keyword */
001525 Table *pParent; /* Parent table that child points to */
001526 Index *pIdx; /* Index in the parent table */
001527 int i; /* Loop counter: Foreign key number for pTab */
001528 int j; /* Loop counter: Field of the foreign key */
001529 HashElem *k; /* Loop counter: Next table in schema */
001530 int x; /* result variable */
001531 int regResult; /* 3 registers to hold a result row */
001532 int regRow; /* Registers to hold a row from pTab */
001533 int addrTop; /* Top of a loop checking foreign keys */
001534 int addrOk; /* Jump here if the key is OK */
001535 int *aiCols; /* child to parent column mapping */
001536
001537 regResult = pParse->nMem+1;
001538 pParse->nMem += 4;
001539 regRow = ++pParse->nMem;
001540 k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
001541 while( k ){
001542 if( zRight ){
001543 pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
001544 k = 0;
001545 }else{
001546 pTab = (Table*)sqliteHashData(k);
001547 k = sqliteHashNext(k);
001548 }
001549 if( pTab==0 || !IsOrdinaryTable(pTab) || pTab->u.tab.pFKey==0 ) continue;
001550 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
001551 zDb = db->aDb[iDb].zDbSName;
001552 sqlite3CodeVerifySchema(pParse, iDb);
001553 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
001554 sqlite3TouchRegister(pParse, pTab->nCol+regRow);
001555 sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
001556 sqlite3VdbeLoadString(v, regResult, pTab->zName);
001557 assert( IsOrdinaryTable(pTab) );
001558 for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
001559 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
001560 if( pParent==0 ) continue;
001561 pIdx = 0;
001562 sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
001563 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
001564 if( x==0 ){
001565 if( pIdx==0 ){
001566 sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
001567 }else{
001568 sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
001569 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
001570 }
001571 }else{
001572 k = 0;
001573 break;
001574 }
001575 }
001576 assert( pParse->nErr>0 || pFK==0 );
001577 if( pFK ) break;
001578 if( pParse->nTab<i ) pParse->nTab = i;
001579 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
001580 assert( IsOrdinaryTable(pTab) );
001581 for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
001582 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
001583 pIdx = 0;
001584 aiCols = 0;
001585 if( pParent ){
001586 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
001587 assert( x==0 || db->mallocFailed );
001588 }
001589 addrOk = sqlite3VdbeMakeLabel(pParse);
001590
001591 /* Generate code to read the child key values into registers
001592 ** regRow..regRow+n. If any of the child key values are NULL, this
001593 ** row cannot cause an FK violation. Jump directly to addrOk in
001594 ** this case. */
001595 sqlite3TouchRegister(pParse, regRow + pFK->nCol);
001596 for(j=0; j<pFK->nCol; j++){
001597 int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
001598 sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
001599 sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
001600 }
001601
001602 /* Generate code to query the parent index for a matching parent
001603 ** key. If a match is found, jump to addrOk. */
001604 if( pIdx ){
001605 sqlite3VdbeAddOp4(v, OP_Affinity, regRow, pFK->nCol, 0,
001606 sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
001607 sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regRow, pFK->nCol);
001608 VdbeCoverage(v);
001609 }else if( pParent ){
001610 int jmp = sqlite3VdbeCurrentAddr(v)+2;
001611 sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
001612 sqlite3VdbeGoto(v, addrOk);
001613 assert( pFK->nCol==1 || db->mallocFailed );
001614 }
001615
001616 /* Generate code to report an FK violation to the caller. */
001617 if( HasRowid(pTab) ){
001618 sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
001619 }else{
001620 sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
001621 }
001622 sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
001623 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
001624 sqlite3VdbeResolveLabel(v, addrOk);
001625 sqlite3DbFree(db, aiCols);
001626 }
001627 sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
001628 sqlite3VdbeJumpHere(v, addrTop);
001629 }
001630 }
001631 break;
001632 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
001633 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
001634
001635 #ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA
001636 /* Reinstall the LIKE and GLOB functions. The variant of LIKE
001637 ** used will be case sensitive or not depending on the RHS.
001638 */
001639 case PragTyp_CASE_SENSITIVE_LIKE: {
001640 if( zRight ){
001641 sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
001642 }
001643 }
001644 break;
001645 #endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */
001646
001647 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
001648 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
001649 #endif
001650
001651 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
001652 /* PRAGMA integrity_check
001653 ** PRAGMA integrity_check(N)
001654 ** PRAGMA quick_check
001655 ** PRAGMA quick_check(N)
001656 **
001657 ** Verify the integrity of the database.
001658 **
001659 ** The "quick_check" is reduced version of
001660 ** integrity_check designed to detect most database corruption
001661 ** without the overhead of cross-checking indexes. Quick_check
001662 ** is linear time whereas integrity_check is O(NlogN).
001663 **
001664 ** The maximum number of errors is 100 by default. A different default
001665 ** can be specified using a numeric parameter N.
001666 **
001667 ** Or, the parameter N can be the name of a table. In that case, only
001668 ** the one table named is verified. The freelist is only verified if
001669 ** the named table is "sqlite_schema" (or one of its aliases).
001670 **
001671 ** All schemas are checked by default. To check just a single
001672 ** schema, use the form:
001673 **
001674 ** PRAGMA schema.integrity_check;
001675 */
001676 case PragTyp_INTEGRITY_CHECK: {
001677 int i, j, addr, mxErr;
001678 Table *pObjTab = 0; /* Check only this one table, if not NULL */
001679
001680 int isQuick = (sqlite3Tolower(zLeft[0])=='q');
001681
001682 /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
001683 ** then iDb is set to the index of the database identified by <db>.
001684 ** In this case, the integrity of database iDb only is verified by
001685 ** the VDBE created below.
001686 **
001687 ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
001688 ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
001689 ** to -1 here, to indicate that the VDBE should verify the integrity
001690 ** of all attached databases. */
001691 assert( iDb>=0 );
001692 assert( iDb==0 || pId2->z );
001693 if( pId2->z==0 ) iDb = -1;
001694
001695 /* Initialize the VDBE program */
001696 pParse->nMem = 6;
001697
001698 /* Set the maximum error count */
001699 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
001700 if( zRight ){
001701 if( sqlite3GetInt32(pValue->z, &mxErr) ){
001702 if( mxErr<=0 ){
001703 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
001704 }
001705 }else{
001706 pObjTab = sqlite3LocateTable(pParse, 0, zRight,
001707 iDb>=0 ? db->aDb[iDb].zDbSName : 0);
001708 }
001709 }
001710 sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
001711
001712 /* Do an integrity check on each database file */
001713 for(i=0; i<db->nDb; i++){
001714 HashElem *x; /* For looping over tables in the schema */
001715 Hash *pTbls; /* Set of all tables in the schema */
001716 int *aRoot; /* Array of root page numbers of all btrees */
001717 int cnt = 0; /* Number of entries in aRoot[] */
001718
001719 if( OMIT_TEMPDB && i==1 ) continue;
001720 if( iDb>=0 && i!=iDb ) continue;
001721
001722 sqlite3CodeVerifySchema(pParse, i);
001723 pParse->okConstFactor = 0; /* tag-20230327-1 */
001724
001725 /* Do an integrity check of the B-Tree
001726 **
001727 ** Begin by finding the root pages numbers
001728 ** for all tables and indices in the database.
001729 */
001730 assert( sqlite3SchemaMutexHeld(db, i, 0) );
001731 pTbls = &db->aDb[i].pSchema->tblHash;
001732 for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
001733 Table *pTab = sqliteHashData(x); /* Current table */
001734 Index *pIdx; /* An index on pTab */
001735 int nIdx; /* Number of indexes on pTab */
001736 if( pObjTab && pObjTab!=pTab ) continue;
001737 if( HasRowid(pTab) ) cnt++;
001738 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
001739 }
001740 if( cnt==0 ) continue;
001741 if( pObjTab ) cnt++;
001742 aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
001743 if( aRoot==0 ) break;
001744 cnt = 0;
001745 if( pObjTab ) aRoot[++cnt] = 0;
001746 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
001747 Table *pTab = sqliteHashData(x);
001748 Index *pIdx;
001749 if( pObjTab && pObjTab!=pTab ) continue;
001750 if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
001751 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
001752 aRoot[++cnt] = pIdx->tnum;
001753 }
001754 }
001755 aRoot[0] = cnt;
001756
001757 /* Make sure sufficient number of registers have been allocated */
001758 sqlite3TouchRegister(pParse, 8+cnt);
001759 sqlite3VdbeAddOp3(v, OP_Null, 0, 8, 8+cnt);
001760 sqlite3ClearTempRegCache(pParse);
001761
001762 /* Do the b-tree integrity checks */
001763 sqlite3VdbeAddOp4(v, OP_IntegrityCk, 1, cnt, 8, (char*)aRoot,P4_INTARRAY);
001764 sqlite3VdbeChangeP5(v, (u16)i);
001765 addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
001766 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
001767 sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
001768 P4_DYNAMIC);
001769 sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
001770 integrityCheckResultRow(v);
001771 sqlite3VdbeJumpHere(v, addr);
001772
001773 /* Check that the indexes all have the right number of rows */
001774 cnt = pObjTab ? 1 : 0;
001775 sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
001776 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
001777 int iTab = 0;
001778 Table *pTab = sqliteHashData(x);
001779 Index *pIdx;
001780 if( pObjTab && pObjTab!=pTab ) continue;
001781 if( HasRowid(pTab) ){
001782 iTab = cnt++;
001783 }else{
001784 iTab = cnt;
001785 for(pIdx=pTab->pIndex; ALWAYS(pIdx); pIdx=pIdx->pNext){
001786 if( IsPrimaryKeyIndex(pIdx) ) break;
001787 iTab++;
001788 }
001789 }
001790 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
001791 if( pIdx->pPartIdxWhere==0 ){
001792 addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+cnt, 0, 8+iTab);
001793 VdbeCoverageNeverNull(v);
001794 sqlite3VdbeLoadString(v, 4, pIdx->zName);
001795 sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
001796 integrityCheckResultRow(v);
001797 sqlite3VdbeJumpHere(v, addr);
001798 }
001799 cnt++;
001800 }
001801 }
001802
001803 /* Make sure all the indices are constructed correctly.
001804 */
001805 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
001806 Table *pTab = sqliteHashData(x);
001807 Index *pIdx, *pPk;
001808 Index *pPrior = 0; /* Previous index */
001809 int loopTop;
001810 int iDataCur, iIdxCur;
001811 int r1 = -1;
001812 int bStrict; /* True for a STRICT table */
001813 int r2; /* Previous key for WITHOUT ROWID tables */
001814 int mxCol; /* Maximum non-virtual column number */
001815
001816 if( pObjTab && pObjTab!=pTab ) continue;
001817 if( !IsOrdinaryTable(pTab) ) continue;
001818 if( isQuick || HasRowid(pTab) ){
001819 pPk = 0;
001820 r2 = 0;
001821 }else{
001822 pPk = sqlite3PrimaryKeyIndex(pTab);
001823 r2 = sqlite3GetTempRange(pParse, pPk->nKeyCol);
001824 sqlite3VdbeAddOp3(v, OP_Null, 1, r2, r2+pPk->nKeyCol-1);
001825 }
001826 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
001827 1, 0, &iDataCur, &iIdxCur);
001828 /* reg[7] counts the number of entries in the table.
001829 ** reg[8+i] counts the number of entries in the i-th index
001830 */
001831 sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
001832 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
001833 sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
001834 }
001835 assert( pParse->nMem>=8+j );
001836 assert( sqlite3NoTempsInRange(pParse,1,7+j) );
001837 sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
001838 loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
001839
001840 /* Fetch the right-most column from the table. This will cause
001841 ** the entire record header to be parsed and sanity checked. It
001842 ** will also prepopulate the cursor column cache that is used
001843 ** by the OP_IsType code, so it is a required step.
001844 */
001845 assert( !IsVirtual(pTab) );
001846 if( HasRowid(pTab) ){
001847 mxCol = -1;
001848 for(j=0; j<pTab->nCol; j++){
001849 if( (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)==0 ) mxCol++;
001850 }
001851 if( mxCol==pTab->iPKey ) mxCol--;
001852 }else{
001853 /* COLFLAG_VIRTUAL columns are not included in the WITHOUT ROWID
001854 ** PK index column-count, so there is no need to account for them
001855 ** in this case. */
001856 mxCol = sqlite3PrimaryKeyIndex(pTab)->nColumn-1;
001857 }
001858 if( mxCol>=0 ){
001859 sqlite3VdbeAddOp3(v, OP_Column, iDataCur, mxCol, 3);
001860 sqlite3VdbeTypeofColumn(v, 3);
001861 }
001862
001863 if( !isQuick ){
001864 if( pPk ){
001865 /* Verify WITHOUT ROWID keys are in ascending order */
001866 int a1;
001867 char *zErr;
001868 a1 = sqlite3VdbeAddOp4Int(v, OP_IdxGT, iDataCur, 0,r2,pPk->nKeyCol);
001869 VdbeCoverage(v);
001870 sqlite3VdbeAddOp1(v, OP_IsNull, r2); VdbeCoverage(v);
001871 zErr = sqlite3MPrintf(db,
001872 "row not in PRIMARY KEY order for %s",
001873 pTab->zName);
001874 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
001875 integrityCheckResultRow(v);
001876 sqlite3VdbeJumpHere(v, a1);
001877 sqlite3VdbeJumpHere(v, a1+1);
001878 for(j=0; j<pPk->nKeyCol; j++){
001879 sqlite3ExprCodeLoadIndexColumn(pParse, pPk, iDataCur, j, r2+j);
001880 }
001881 }
001882 }
001883 /* Verify datatypes for all columns:
001884 **
001885 ** (1) NOT NULL columns may not contain a NULL
001886 ** (2) Datatype must be exact for non-ANY columns in STRICT tables
001887 ** (3) Datatype for TEXT columns in non-STRICT tables must be
001888 ** NULL, TEXT, or BLOB.
001889 ** (4) Datatype for numeric columns in non-STRICT tables must not
001890 ** be a TEXT value that can be losslessly converted to numeric.
001891 */
001892 bStrict = (pTab->tabFlags & TF_Strict)!=0;
001893 for(j=0; j<pTab->nCol; j++){
001894 char *zErr;
001895 Column *pCol = pTab->aCol + j; /* The column to be checked */
001896 int labelError; /* Jump here to report an error */
001897 int labelOk; /* Jump here if all looks ok */
001898 int p1, p3, p4; /* Operands to the OP_IsType opcode */
001899 int doTypeCheck; /* Check datatypes (besides NOT NULL) */
001900
001901 if( j==pTab->iPKey ) continue;
001902 if( bStrict ){
001903 doTypeCheck = pCol->eCType>COLTYPE_ANY;
001904 }else{
001905 doTypeCheck = pCol->affinity>SQLITE_AFF_BLOB;
001906 }
001907 if( pCol->notNull==0 && !doTypeCheck ) continue;
001908
001909 /* Compute the operands that will be needed for OP_IsType */
001910 p4 = SQLITE_NULL;
001911 if( pCol->colFlags & COLFLAG_VIRTUAL ){
001912 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
001913 p1 = -1;
001914 p3 = 3;
001915 }else{
001916 if( pCol->iDflt ){
001917 sqlite3_value *pDfltValue = 0;
001918 sqlite3ValueFromExpr(db, sqlite3ColumnExpr(pTab,pCol), ENC(db),
001919 pCol->affinity, &pDfltValue);
001920 if( pDfltValue ){
001921 p4 = sqlite3_value_type(pDfltValue);
001922 sqlite3ValueFree(pDfltValue);
001923 }
001924 }
001925 p1 = iDataCur;
001926 if( !HasRowid(pTab) ){
001927 testcase( j!=sqlite3TableColumnToStorage(pTab, j) );
001928 p3 = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), j);
001929 }else{
001930 p3 = sqlite3TableColumnToStorage(pTab,j);
001931 testcase( p3!=j);
001932 }
001933 }
001934
001935 labelError = sqlite3VdbeMakeLabel(pParse);
001936 labelOk = sqlite3VdbeMakeLabel(pParse);
001937 if( pCol->notNull ){
001938 /* (1) NOT NULL columns may not contain a NULL */
001939 int jmp3;
001940 int jmp2 = sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
001941 VdbeCoverage(v);
001942 if( p1<0 ){
001943 sqlite3VdbeChangeP5(v, 0x0f); /* INT, REAL, TEXT, or BLOB */
001944 jmp3 = jmp2;
001945 }else{
001946 sqlite3VdbeChangeP5(v, 0x0d); /* INT, TEXT, or BLOB */
001947 /* OP_IsType does not detect NaN values in the database file
001948 ** which should be treated as a NULL. So if the header type
001949 ** is REAL, we have to load the actual data using OP_Column
001950 ** to reliably determine if the value is a NULL. */
001951 sqlite3VdbeAddOp3(v, OP_Column, p1, p3, 3);
001952 sqlite3ColumnDefault(v, pTab, j, 3);
001953 jmp3 = sqlite3VdbeAddOp2(v, OP_NotNull, 3, labelOk);
001954 VdbeCoverage(v);
001955 }
001956 zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
001957 pCol->zCnName);
001958 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
001959 if( doTypeCheck ){
001960 sqlite3VdbeGoto(v, labelError);
001961 sqlite3VdbeJumpHere(v, jmp2);
001962 sqlite3VdbeJumpHere(v, jmp3);
001963 }else{
001964 /* VDBE byte code will fall thru */
001965 }
001966 }
001967 if( bStrict && doTypeCheck ){
001968 /* (2) Datatype must be exact for non-ANY columns in STRICT tables*/
001969 static unsigned char aStdTypeMask[] = {
001970 0x1f, /* ANY */
001971 0x18, /* BLOB */
001972 0x11, /* INT */
001973 0x11, /* INTEGER */
001974 0x13, /* REAL */
001975 0x14 /* TEXT */
001976 };
001977 sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
001978 assert( pCol->eCType>=1 && pCol->eCType<=sizeof(aStdTypeMask) );
001979 sqlite3VdbeChangeP5(v, aStdTypeMask[pCol->eCType-1]);
001980 VdbeCoverage(v);
001981 zErr = sqlite3MPrintf(db, "non-%s value in %s.%s",
001982 sqlite3StdType[pCol->eCType-1],
001983 pTab->zName, pTab->aCol[j].zCnName);
001984 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
001985 }else if( !bStrict && pCol->affinity==SQLITE_AFF_TEXT ){
001986 /* (3) Datatype for TEXT columns in non-STRICT tables must be
001987 ** NULL, TEXT, or BLOB. */
001988 sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
001989 sqlite3VdbeChangeP5(v, 0x1c); /* NULL, TEXT, or BLOB */
001990 VdbeCoverage(v);
001991 zErr = sqlite3MPrintf(db, "NUMERIC value in %s.%s",
001992 pTab->zName, pTab->aCol[j].zCnName);
001993 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
001994 }else if( !bStrict && pCol->affinity>=SQLITE_AFF_NUMERIC ){
001995 /* (4) Datatype for numeric columns in non-STRICT tables must not
001996 ** be a TEXT value that can be converted to numeric. */
001997 sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
001998 sqlite3VdbeChangeP5(v, 0x1b); /* NULL, INT, FLOAT, or BLOB */
001999 VdbeCoverage(v);
002000 if( p1>=0 ){
002001 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
002002 }
002003 sqlite3VdbeAddOp4(v, OP_Affinity, 3, 1, 0, "C", P4_STATIC);
002004 sqlite3VdbeAddOp4Int(v, OP_IsType, -1, labelOk, 3, p4);
002005 sqlite3VdbeChangeP5(v, 0x1c); /* NULL, TEXT, or BLOB */
002006 VdbeCoverage(v);
002007 zErr = sqlite3MPrintf(db, "TEXT value in %s.%s",
002008 pTab->zName, pTab->aCol[j].zCnName);
002009 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
002010 }
002011 sqlite3VdbeResolveLabel(v, labelError);
002012 integrityCheckResultRow(v);
002013 sqlite3VdbeResolveLabel(v, labelOk);
002014 }
002015 /* Verify CHECK constraints */
002016 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
002017 ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
002018 if( db->mallocFailed==0 ){
002019 int addrCkFault = sqlite3VdbeMakeLabel(pParse);
002020 int addrCkOk = sqlite3VdbeMakeLabel(pParse);
002021 char *zErr;
002022 int k;
002023 pParse->iSelfTab = iDataCur + 1;
002024 for(k=pCheck->nExpr-1; k>0; k--){
002025 sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
002026 }
002027 sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
002028 SQLITE_JUMPIFNULL);
002029 sqlite3VdbeResolveLabel(v, addrCkFault);
002030 pParse->iSelfTab = 0;
002031 zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
002032 pTab->zName);
002033 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
002034 integrityCheckResultRow(v);
002035 sqlite3VdbeResolveLabel(v, addrCkOk);
002036 }
002037 sqlite3ExprListDelete(db, pCheck);
002038 }
002039 if( !isQuick ){ /* Omit the remaining tests for quick_check */
002040 /* Validate index entries for the current row */
002041 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
002042 int jmp2, jmp3, jmp4, jmp5, label6;
002043 int kk;
002044 int ckUniq = sqlite3VdbeMakeLabel(pParse);
002045 if( pPk==pIdx ) continue;
002046 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
002047 pPrior, r1);
002048 pPrior = pIdx;
002049 sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
002050 /* Verify that an index entry exists for the current table row */
002051 jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
002052 pIdx->nColumn); VdbeCoverage(v);
002053 sqlite3VdbeLoadString(v, 3, "row ");
002054 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
002055 sqlite3VdbeLoadString(v, 4, " missing from index ");
002056 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
002057 jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
002058 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
002059 jmp4 = integrityCheckResultRow(v);
002060 sqlite3VdbeJumpHere(v, jmp2);
002061
002062 /* The OP_IdxRowid opcode is an optimized version of OP_Column
002063 ** that extracts the rowid off the end of the index record.
002064 ** But it only works correctly if index record does not have
002065 ** any extra bytes at the end. Verify that this is the case. */
002066 if( HasRowid(pTab) ){
002067 int jmp7;
002068 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur+j, 3);
002069 jmp7 = sqlite3VdbeAddOp3(v, OP_Eq, 3, 0, r1+pIdx->nColumn-1);
002070 VdbeCoverageNeverNull(v);
002071 sqlite3VdbeLoadString(v, 3,
002072 "rowid not at end-of-record for row ");
002073 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
002074 sqlite3VdbeLoadString(v, 4, " of index ");
002075 sqlite3VdbeGoto(v, jmp5-1);
002076 sqlite3VdbeJumpHere(v, jmp7);
002077 }
002078
002079 /* Any indexed columns with non-BINARY collations must still hold
002080 ** the exact same text value as the table. */
002081 label6 = 0;
002082 for(kk=0; kk<pIdx->nKeyCol; kk++){
002083 if( pIdx->azColl[kk]==sqlite3StrBINARY ) continue;
002084 if( label6==0 ) label6 = sqlite3VdbeMakeLabel(pParse);
002085 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur+j, kk, 3);
002086 sqlite3VdbeAddOp3(v, OP_Ne, 3, label6, r1+kk); VdbeCoverage(v);
002087 }
002088 if( label6 ){
002089 int jmp6 = sqlite3VdbeAddOp0(v, OP_Goto);
002090 sqlite3VdbeResolveLabel(v, label6);
002091 sqlite3VdbeLoadString(v, 3, "row ");
002092 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
002093 sqlite3VdbeLoadString(v, 4, " values differ from index ");
002094 sqlite3VdbeGoto(v, jmp5-1);
002095 sqlite3VdbeJumpHere(v, jmp6);
002096 }
002097
002098 /* For UNIQUE indexes, verify that only one entry exists with the
002099 ** current key. The entry is unique if (1) any column is NULL
002100 ** or (2) the next entry has a different key */
002101 if( IsUniqueIndex(pIdx) ){
002102 int uniqOk = sqlite3VdbeMakeLabel(pParse);
002103 int jmp6;
002104 for(kk=0; kk<pIdx->nKeyCol; kk++){
002105 int iCol = pIdx->aiColumn[kk];
002106 assert( iCol!=XN_ROWID && iCol<pTab->nCol );
002107 if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
002108 sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
002109 VdbeCoverage(v);
002110 }
002111 jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
002112 sqlite3VdbeGoto(v, uniqOk);
002113 sqlite3VdbeJumpHere(v, jmp6);
002114 sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
002115 pIdx->nKeyCol); VdbeCoverage(v);
002116 sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
002117 sqlite3VdbeGoto(v, jmp5);
002118 sqlite3VdbeResolveLabel(v, uniqOk);
002119 }
002120 sqlite3VdbeJumpHere(v, jmp4);
002121 sqlite3ResolvePartIdxLabel(pParse, jmp3);
002122 }
002123 }
002124 sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
002125 sqlite3VdbeJumpHere(v, loopTop-1);
002126 if( pPk ){
002127 assert( !isQuick );
002128 sqlite3ReleaseTempRange(pParse, r2, pPk->nKeyCol);
002129 }
002130 }
002131
002132 #ifndef SQLITE_OMIT_VIRTUALTABLE
002133 /* Second pass to invoke the xIntegrity method on all virtual
002134 ** tables.
002135 */
002136 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
002137 Table *pTab = sqliteHashData(x);
002138 sqlite3_vtab *pVTab;
002139 int a1;
002140 if( pObjTab && pObjTab!=pTab ) continue;
002141 if( IsOrdinaryTable(pTab) ) continue;
002142 if( !IsVirtual(pTab) ) continue;
002143 if( pTab->nCol<=0 ){
002144 const char *zMod = pTab->u.vtab.azArg[0];
002145 if( sqlite3HashFind(&db->aModule, zMod)==0 ) continue;
002146 }
002147 sqlite3ViewGetColumnNames(pParse, pTab);
002148 if( pTab->u.vtab.p==0 ) continue;
002149 pVTab = pTab->u.vtab.p->pVtab;
002150 if( NEVER(pVTab==0) ) continue;
002151 if( NEVER(pVTab->pModule==0) ) continue;
002152 if( pVTab->pModule->iVersion<4 ) continue;
002153 if( pVTab->pModule->xIntegrity==0 ) continue;
002154 sqlite3VdbeAddOp3(v, OP_VCheck, i, 3, isQuick);
002155 pTab->nTabRef++;
002156 sqlite3VdbeAppendP4(v, pTab, P4_TABLEREF);
002157 a1 = sqlite3VdbeAddOp1(v, OP_IsNull, 3); VdbeCoverage(v);
002158 integrityCheckResultRow(v);
002159 sqlite3VdbeJumpHere(v, a1);
002160 continue;
002161 }
002162 #endif
002163 }
002164 {
002165 static const int iLn = VDBE_OFFSET_LINENO(2);
002166 static const VdbeOpList endCode[] = {
002167 { OP_AddImm, 1, 0, 0}, /* 0 */
002168 { OP_IfNotZero, 1, 4, 0}, /* 1 */
002169 { OP_String8, 0, 3, 0}, /* 2 */
002170 { OP_ResultRow, 3, 1, 0}, /* 3 */
002171 { OP_Halt, 0, 0, 0}, /* 4 */
002172 { OP_String8, 0, 3, 0}, /* 5 */
002173 { OP_Goto, 0, 3, 0}, /* 6 */
002174 };
002175 VdbeOp *aOp;
002176
002177 aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
002178 if( aOp ){
002179 aOp[0].p2 = 1-mxErr;
002180 aOp[2].p4type = P4_STATIC;
002181 aOp[2].p4.z = "ok";
002182 aOp[5].p4type = P4_STATIC;
002183 aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
002184 }
002185 sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
002186 }
002187 }
002188 break;
002189 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
002190
002191 #ifndef SQLITE_OMIT_UTF16
002192 /*
002193 ** PRAGMA encoding
002194 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
002195 **
002196 ** In its first form, this pragma returns the encoding of the main
002197 ** database. If the database is not initialized, it is initialized now.
002198 **
002199 ** The second form of this pragma is a no-op if the main database file
002200 ** has not already been initialized. In this case it sets the default
002201 ** encoding that will be used for the main database file if a new file
002202 ** is created. If an existing main database file is opened, then the
002203 ** default text encoding for the existing database is used.
002204 **
002205 ** In all cases new databases created using the ATTACH command are
002206 ** created to use the same default text encoding as the main database. If
002207 ** the main database has not been initialized and/or created when ATTACH
002208 ** is executed, this is done before the ATTACH operation.
002209 **
002210 ** In the second form this pragma sets the text encoding to be used in
002211 ** new database files created using this database handle. It is only
002212 ** useful if invoked immediately after the main database i
002213 */
002214 case PragTyp_ENCODING: {
002215 static const struct EncName {
002216 char *zName;
002217 u8 enc;
002218 } encnames[] = {
002219 { "UTF8", SQLITE_UTF8 },
002220 { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
002221 { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
002222 { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
002223 { "UTF16le", SQLITE_UTF16LE },
002224 { "UTF16be", SQLITE_UTF16BE },
002225 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
002226 { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
002227 { 0, 0 }
002228 };
002229 const struct EncName *pEnc;
002230 if( !zRight ){ /* "PRAGMA encoding" */
002231 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
002232 assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
002233 assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
002234 assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
002235 returnSingleText(v, encnames[ENC(pParse->db)].zName);
002236 }else{ /* "PRAGMA encoding = XXX" */
002237 /* Only change the value of sqlite.enc if the database handle is not
002238 ** initialized. If the main database exists, the new sqlite.enc value
002239 ** will be overwritten when the schema is next loaded. If it does not
002240 ** already exists, it will be created to use the new encoding value.
002241 */
002242 if( (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
002243 for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
002244 if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
002245 u8 enc = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
002246 SCHEMA_ENC(db) = enc;
002247 sqlite3SetTextEncoding(db, enc);
002248 break;
002249 }
002250 }
002251 if( !pEnc->zName ){
002252 sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
002253 }
002254 }
002255 }
002256 }
002257 break;
002258 #endif /* SQLITE_OMIT_UTF16 */
002259
002260 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
002261 /*
002262 ** PRAGMA [schema.]schema_version
002263 ** PRAGMA [schema.]schema_version = <integer>
002264 **
002265 ** PRAGMA [schema.]user_version
002266 ** PRAGMA [schema.]user_version = <integer>
002267 **
002268 ** PRAGMA [schema.]freelist_count
002269 **
002270 ** PRAGMA [schema.]data_version
002271 **
002272 ** PRAGMA [schema.]application_id
002273 ** PRAGMA [schema.]application_id = <integer>
002274 **
002275 ** The pragma's schema_version and user_version are used to set or get
002276 ** the value of the schema-version and user-version, respectively. Both
002277 ** the schema-version and the user-version are 32-bit signed integers
002278 ** stored in the database header.
002279 **
002280 ** The schema-cookie is usually only manipulated internally by SQLite. It
002281 ** is incremented by SQLite whenever the database schema is modified (by
002282 ** creating or dropping a table or index). The schema version is used by
002283 ** SQLite each time a query is executed to ensure that the internal cache
002284 ** of the schema used when compiling the SQL query matches the schema of
002285 ** the database against which the compiled query is actually executed.
002286 ** Subverting this mechanism by using "PRAGMA schema_version" to modify
002287 ** the schema-version is potentially dangerous and may lead to program
002288 ** crashes or database corruption. Use with caution!
002289 **
002290 ** The user-version is not used internally by SQLite. It may be used by
002291 ** applications for any purpose.
002292 */
002293 case PragTyp_HEADER_VALUE: {
002294 int iCookie = pPragma->iArg; /* Which cookie to read or write */
002295 sqlite3VdbeUsesBtree(v, iDb);
002296 if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
002297 /* Write the specified cookie value */
002298 static const VdbeOpList setCookie[] = {
002299 { OP_Transaction, 0, 1, 0}, /* 0 */
002300 { OP_SetCookie, 0, 0, 0}, /* 1 */
002301 };
002302 VdbeOp *aOp;
002303 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
002304 aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
002305 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
002306 aOp[0].p1 = iDb;
002307 aOp[1].p1 = iDb;
002308 aOp[1].p2 = iCookie;
002309 aOp[1].p3 = sqlite3Atoi(zRight);
002310 aOp[1].p5 = 1;
002311 if( iCookie==BTREE_SCHEMA_VERSION && (db->flags & SQLITE_Defensive)!=0 ){
002312 /* Do not allow the use of PRAGMA schema_version=VALUE in defensive
002313 ** mode. Change the OP_SetCookie opcode into a no-op. */
002314 aOp[1].opcode = OP_Noop;
002315 }
002316 }else{
002317 /* Read the specified cookie value */
002318 static const VdbeOpList readCookie[] = {
002319 { OP_Transaction, 0, 0, 0}, /* 0 */
002320 { OP_ReadCookie, 0, 1, 0}, /* 1 */
002321 { OP_ResultRow, 1, 1, 0}
002322 };
002323 VdbeOp *aOp;
002324 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
002325 aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
002326 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
002327 aOp[0].p1 = iDb;
002328 aOp[1].p1 = iDb;
002329 aOp[1].p3 = iCookie;
002330 sqlite3VdbeReusable(v);
002331 }
002332 }
002333 break;
002334 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
002335
002336 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
002337 /*
002338 ** PRAGMA compile_options
002339 **
002340 ** Return the names of all compile-time options used in this build,
002341 ** one option per row.
002342 */
002343 case PragTyp_COMPILE_OPTIONS: {
002344 int i = 0;
002345 const char *zOpt;
002346 pParse->nMem = 1;
002347 while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
002348 sqlite3VdbeLoadString(v, 1, zOpt);
002349 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
002350 }
002351 sqlite3VdbeReusable(v);
002352 }
002353 break;
002354 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
002355
002356 #ifndef SQLITE_OMIT_WAL
002357 /*
002358 ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
002359 **
002360 ** Checkpoint the database.
002361 */
002362 case PragTyp_WAL_CHECKPOINT: {
002363 int iBt = (pId2->z?iDb:SQLITE_MAX_DB);
002364 int eMode = SQLITE_CHECKPOINT_PASSIVE;
002365 if( zRight ){
002366 if( sqlite3StrICmp(zRight, "full")==0 ){
002367 eMode = SQLITE_CHECKPOINT_FULL;
002368 }else if( sqlite3StrICmp(zRight, "restart")==0 ){
002369 eMode = SQLITE_CHECKPOINT_RESTART;
002370 }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
002371 eMode = SQLITE_CHECKPOINT_TRUNCATE;
002372 }
002373 }
002374 pParse->nMem = 3;
002375 sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
002376 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
002377 }
002378 break;
002379
002380 /*
002381 ** PRAGMA wal_autocheckpoint
002382 ** PRAGMA wal_autocheckpoint = N
002383 **
002384 ** Configure a database connection to automatically checkpoint a database
002385 ** after accumulating N frames in the log. Or query for the current value
002386 ** of N.
002387 */
002388 case PragTyp_WAL_AUTOCHECKPOINT: {
002389 if( zRight ){
002390 sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
002391 }
002392 returnSingleInt(v,
002393 db->xWalCallback==sqlite3WalDefaultHook ?
002394 SQLITE_PTR_TO_INT(db->pWalArg) : 0);
002395 }
002396 break;
002397 #endif
002398
002399 /*
002400 ** PRAGMA shrink_memory
002401 **
002402 ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
002403 ** connection on which it is invoked to free up as much memory as it
002404 ** can, by calling sqlite3_db_release_memory().
002405 */
002406 case PragTyp_SHRINK_MEMORY: {
002407 sqlite3_db_release_memory(db);
002408 break;
002409 }
002410
002411 /*
002412 ** PRAGMA optimize
002413 ** PRAGMA optimize(MASK)
002414 ** PRAGMA schema.optimize
002415 ** PRAGMA schema.optimize(MASK)
002416 **
002417 ** Attempt to optimize the database. All schemas are optimized in the first
002418 ** two forms, and only the specified schema is optimized in the latter two.
002419 **
002420 ** The details of optimizations performed by this pragma are expected
002421 ** to change and improve over time. Applications should anticipate that
002422 ** this pragma will perform new optimizations in future releases.
002423 **
002424 ** The optional argument is a bitmask of optimizations to perform:
002425 **
002426 ** 0x00001 Debugging mode. Do not actually perform any optimizations
002427 ** but instead return one line of text for each optimization
002428 ** that would have been done. Off by default.
002429 **
002430 ** 0x00002 Run ANALYZE on tables that might benefit. On by default.
002431 ** See below for additional information.
002432 **
002433 ** 0x00010 Run all ANALYZE operations using an analysis_limit that
002434 ** is the lessor of the current analysis_limit and the
002435 ** SQLITE_DEFAULT_OPTIMIZE_LIMIT compile-time option.
002436 ** The default value of SQLITE_DEFAULT_OPTIMIZE_LIMIT is
002437 ** currently (2024-02-19) set to 2000, which is such that
002438 ** the worst case run-time for PRAGMA optimize on a 100MB
002439 ** database will usually be less than 100 milliseconds on
002440 ** a RaspberryPI-4 class machine. On by default.
002441 **
002442 ** 0x10000 Look at tables to see if they need to be reanalyzed
002443 ** due to growth or shrinkage even if they have not been
002444 ** queried during the current connection. Off by default.
002445 **
002446 ** The default MASK is and always shall be 0x0fffe. In the current
002447 ** implementation, the default mask only covers the 0x00002 optimization,
002448 ** though additional optimizations that are covered by 0x0fffe might be
002449 ** added in the future. Optimizations that are off by default and must
002450 ** be explicitly requested have masks of 0x10000 or greater.
002451 **
002452 ** DETERMINATION OF WHEN TO RUN ANALYZE
002453 **
002454 ** In the current implementation, a table is analyzed if only if all of
002455 ** the following are true:
002456 **
002457 ** (1) MASK bit 0x00002 is set.
002458 **
002459 ** (2) The table is an ordinary table, not a virtual table or view.
002460 **
002461 ** (3) The table name does not begin with "sqlite_".
002462 **
002463 ** (4) One or more of the following is true:
002464 ** (4a) The 0x10000 MASK bit is set.
002465 ** (4b) One or more indexes on the table lacks an entry
002466 ** in the sqlite_stat1 table.
002467 ** (4c) The query planner used sqlite_stat1-style statistics for one
002468 ** or more indexes of the table at some point during the lifetime
002469 ** of the current connection.
002470 **
002471 ** (5) One or more of the following is true:
002472 ** (5a) One or more indexes on the table lacks an entry
002473 ** in the sqlite_stat1 table. (Same as 4a)
002474 ** (5b) The number of rows in the table has increased or decreased by
002475 ** 10-fold. In other words, the current size of the table is
002476 ** 10 times larger than the size in sqlite_stat1 or else the
002477 ** current size is less than 1/10th the size in sqlite_stat1.
002478 **
002479 ** The rules for when tables are analyzed are likely to change in
002480 ** future releases. Future versions of SQLite might accept a string
002481 ** literal argument to this pragma that contains a mnemonic description
002482 ** of the options rather than a bitmap.
002483 */
002484 case PragTyp_OPTIMIZE: {
002485 int iDbLast; /* Loop termination point for the schema loop */
002486 int iTabCur; /* Cursor for a table whose size needs checking */
002487 HashElem *k; /* Loop over tables of a schema */
002488 Schema *pSchema; /* The current schema */
002489 Table *pTab; /* A table in the schema */
002490 Index *pIdx; /* An index of the table */
002491 LogEst szThreshold; /* Size threshold above which reanalysis needed */
002492 char *zSubSql; /* SQL statement for the OP_SqlExec opcode */
002493 u32 opMask; /* Mask of operations to perform */
002494 int nLimit; /* Analysis limit to use */
002495 int nCheck = 0; /* Number of tables to be optimized */
002496 int nBtree = 0; /* Number of btrees to scan */
002497 int nIndex; /* Number of indexes on the current table */
002498
002499 if( zRight ){
002500 opMask = (u32)sqlite3Atoi(zRight);
002501 if( (opMask & 0x02)==0 ) break;
002502 }else{
002503 opMask = 0xfffe;
002504 }
002505 if( (opMask & 0x10)==0 ){
002506 nLimit = 0;
002507 }else if( db->nAnalysisLimit>0
002508 && db->nAnalysisLimit<SQLITE_DEFAULT_OPTIMIZE_LIMIT ){
002509 nLimit = 0;
002510 }else{
002511 nLimit = SQLITE_DEFAULT_OPTIMIZE_LIMIT;
002512 }
002513 iTabCur = pParse->nTab++;
002514 for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
002515 if( iDb==1 ) continue;
002516 sqlite3CodeVerifySchema(pParse, iDb);
002517 pSchema = db->aDb[iDb].pSchema;
002518 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
002519 pTab = (Table*)sqliteHashData(k);
002520
002521 /* This only works for ordinary tables */
002522 if( !IsOrdinaryTable(pTab) ) continue;
002523
002524 /* Do not scan system tables */
002525 if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) ) continue;
002526
002527 /* Find the size of the table as last recorded in sqlite_stat1.
002528 ** If any index is unanalyzed, then the threshold is -1 to
002529 ** indicate a new, unanalyzed index
002530 */
002531 szThreshold = pTab->nRowLogEst;
002532 nIndex = 0;
002533 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
002534 nIndex++;
002535 if( !pIdx->hasStat1 ){
002536 szThreshold = -1; /* Always analyze if any index lacks statistics */
002537 }
002538 }
002539
002540 /* If table pTab has not been used in a way that would benefit from
002541 ** having analysis statistics during the current session, then skip it,
002542 ** unless the 0x10000 MASK bit is set. */
002543 if( (pTab->tabFlags & TF_MaybeReanalyze)!=0 ){
002544 /* Check for size change if stat1 has been used for a query */
002545 }else if( opMask & 0x10000 ){
002546 /* Check for size change if 0x10000 is set */
002547 }else if( pTab->pIndex!=0 && szThreshold<0 ){
002548 /* Do analysis if unanalyzed indexes exists */
002549 }else{
002550 /* Otherwise, we can skip this table */
002551 continue;
002552 }
002553
002554 nCheck++;
002555 if( nCheck==2 ){
002556 /* If ANALYZE might be invoked two or more times, hold a write
002557 ** transaction for efficiency */
002558 sqlite3BeginWriteOperation(pParse, 0, iDb);
002559 }
002560 nBtree += nIndex+1;
002561
002562 /* Reanalyze if the table is 10 times larger or smaller than
002563 ** the last analysis. Unconditional reanalysis if there are
002564 ** unanalyzed indexes. */
002565 sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
002566 if( szThreshold>=0 ){
002567 const LogEst iRange = 33; /* 10x size change */
002568 sqlite3VdbeAddOp4Int(v, OP_IfSizeBetween, iTabCur,
002569 sqlite3VdbeCurrentAddr(v)+2+(opMask&1),
002570 szThreshold>=iRange ? szThreshold-iRange : -1,
002571 szThreshold+iRange);
002572 VdbeCoverage(v);
002573 }else{
002574 sqlite3VdbeAddOp2(v, OP_Rewind, iTabCur,
002575 sqlite3VdbeCurrentAddr(v)+2+(opMask&1));
002576 VdbeCoverage(v);
002577 }
002578 zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
002579 db->aDb[iDb].zDbSName, pTab->zName);
002580 if( opMask & 0x01 ){
002581 int r1 = sqlite3GetTempReg(pParse);
002582 sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
002583 sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
002584 }else{
002585 sqlite3VdbeAddOp4(v, OP_SqlExec, nLimit ? 0x02 : 00, nLimit, 0,
002586 zSubSql, P4_DYNAMIC);
002587 }
002588 }
002589 }
002590 sqlite3VdbeAddOp0(v, OP_Expire);
002591
002592 /* In a schema with a large number of tables and indexes, scale back
002593 ** the analysis_limit to avoid excess run-time in the worst case.
002594 */
002595 if( !db->mallocFailed && nLimit>0 && nBtree>100 ){
002596 int iAddr, iEnd;
002597 VdbeOp *aOp;
002598 nLimit = 100*nLimit/nBtree;
002599 if( nLimit<100 ) nLimit = 100;
002600 aOp = sqlite3VdbeGetOp(v, 0);
002601 iEnd = sqlite3VdbeCurrentAddr(v);
002602 for(iAddr=0; iAddr<iEnd; iAddr++){
002603 if( aOp[iAddr].opcode==OP_SqlExec ) aOp[iAddr].p2 = nLimit;
002604 }
002605 }
002606 break;
002607 }
002608
002609 /*
002610 ** PRAGMA busy_timeout
002611 ** PRAGMA busy_timeout = N
002612 **
002613 ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
002614 ** if one is set. If no busy handler or a different busy handler is set
002615 ** then 0 is returned. Setting the busy_timeout to 0 or negative
002616 ** disables the timeout.
002617 */
002618 /*case PragTyp_BUSY_TIMEOUT*/ default: {
002619 assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
002620 if( zRight ){
002621 sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
002622 }
002623 returnSingleInt(v, db->busyTimeout);
002624 break;
002625 }
002626
002627 /*
002628 ** PRAGMA soft_heap_limit
002629 ** PRAGMA soft_heap_limit = N
002630 **
002631 ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
002632 ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
002633 ** specified and is a non-negative integer.
002634 ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
002635 ** returns the same integer that would be returned by the
002636 ** sqlite3_soft_heap_limit64(-1) C-language function.
002637 */
002638 case PragTyp_SOFT_HEAP_LIMIT: {
002639 sqlite3_int64 N;
002640 if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
002641 sqlite3_soft_heap_limit64(N);
002642 }
002643 returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
002644 break;
002645 }
002646
002647 /*
002648 ** PRAGMA hard_heap_limit
002649 ** PRAGMA hard_heap_limit = N
002650 **
002651 ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap
002652 ** limit. The hard heap limit can be activated or lowered by this
002653 ** pragma, but not raised or deactivated. Only the
002654 ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate
002655 ** the hard heap limit. This allows an application to set a heap limit
002656 ** constraint that cannot be relaxed by an untrusted SQL script.
002657 */
002658 case PragTyp_HARD_HEAP_LIMIT: {
002659 sqlite3_int64 N;
002660 if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
002661 sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1);
002662 if( N>0 && (iPrior==0 || iPrior>N) ) sqlite3_hard_heap_limit64(N);
002663 }
002664 returnSingleInt(v, sqlite3_hard_heap_limit64(-1));
002665 break;
002666 }
002667
002668 /*
002669 ** PRAGMA threads
002670 ** PRAGMA threads = N
002671 **
002672 ** Configure the maximum number of worker threads. Return the new
002673 ** maximum, which might be less than requested.
002674 */
002675 case PragTyp_THREADS: {
002676 sqlite3_int64 N;
002677 if( zRight
002678 && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
002679 && N>=0
002680 ){
002681 sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
002682 }
002683 returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
002684 break;
002685 }
002686
002687 /*
002688 ** PRAGMA analysis_limit
002689 ** PRAGMA analysis_limit = N
002690 **
002691 ** Configure the maximum number of rows that ANALYZE will examine
002692 ** in each index that it looks at. Return the new limit.
002693 */
002694 case PragTyp_ANALYSIS_LIMIT: {
002695 sqlite3_int64 N;
002696 if( zRight
002697 && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK /* IMP: R-40975-20399 */
002698 && N>=0
002699 ){
002700 db->nAnalysisLimit = (int)(N&0x7fffffff);
002701 }
002702 returnSingleInt(v, db->nAnalysisLimit); /* IMP: R-57594-65522 */
002703 break;
002704 }
002705
002706 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
002707 /*
002708 ** Report the current state of file logs for all databases
002709 */
002710 case PragTyp_LOCK_STATUS: {
002711 static const char *const azLockName[] = {
002712 "unlocked", "shared", "reserved", "pending", "exclusive"
002713 };
002714 int i;
002715 pParse->nMem = 2;
002716 for(i=0; i<db->nDb; i++){
002717 Btree *pBt;
002718 const char *zState = "unknown";
002719 int j;
002720 if( db->aDb[i].zDbSName==0 ) continue;
002721 pBt = db->aDb[i].pBt;
002722 if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
002723 zState = "closed";
002724 }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
002725 SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
002726 zState = azLockName[j];
002727 }
002728 sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
002729 }
002730 break;
002731 }
002732 #endif
002733
002734 #if defined(SQLITE_ENABLE_CEROD)
002735 case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
002736 if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
002737 sqlite3_activate_cerod(&zRight[6]);
002738 }
002739 }
002740 break;
002741 #endif
002742
002743 } /* End of the PRAGMA switch */
002744
002745 /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
002746 ** purpose is to execute assert() statements to verify that if the
002747 ** PragFlg_NoColumns1 flag is set and the caller specified an argument
002748 ** to the PRAGMA, the implementation has not added any OP_ResultRow
002749 ** instructions to the VM. */
002750 if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
002751 sqlite3VdbeVerifyNoResultRow(v);
002752 }
002753
002754 pragma_out:
002755 sqlite3DbFree(db, zLeft);
002756 sqlite3DbFree(db, zRight);
002757 }
002758 #ifndef SQLITE_OMIT_VIRTUALTABLE
002759 /*****************************************************************************
002760 ** Implementation of an eponymous virtual table that runs a pragma.
002761 **
002762 */
002763 typedef struct PragmaVtab PragmaVtab;
002764 typedef struct PragmaVtabCursor PragmaVtabCursor;
002765 struct PragmaVtab {
002766 sqlite3_vtab base; /* Base class. Must be first */
002767 sqlite3 *db; /* The database connection to which it belongs */
002768 const PragmaName *pName; /* Name of the pragma */
002769 u8 nHidden; /* Number of hidden columns */
002770 u8 iHidden; /* Index of the first hidden column */
002771 };
002772 struct PragmaVtabCursor {
002773 sqlite3_vtab_cursor base; /* Base class. Must be first */
002774 sqlite3_stmt *pPragma; /* The pragma statement to run */
002775 sqlite_int64 iRowid; /* Current rowid */
002776 char *azArg[2]; /* Value of the argument and schema */
002777 };
002778
002779 /*
002780 ** Pragma virtual table module xConnect method.
002781 */
002782 static int pragmaVtabConnect(
002783 sqlite3 *db,
002784 void *pAux,
002785 int argc, const char *const*argv,
002786 sqlite3_vtab **ppVtab,
002787 char **pzErr
002788 ){
002789 const PragmaName *pPragma = (const PragmaName*)pAux;
002790 PragmaVtab *pTab = 0;
002791 int rc;
002792 int i, j;
002793 char cSep = '(';
002794 StrAccum acc;
002795 char zBuf[200];
002796
002797 UNUSED_PARAMETER(argc);
002798 UNUSED_PARAMETER(argv);
002799 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
002800 sqlite3_str_appendall(&acc, "CREATE TABLE x");
002801 for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
002802 sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]);
002803 cSep = ',';
002804 }
002805 if( i==0 ){
002806 sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
002807 i++;
002808 }
002809 j = 0;
002810 if( pPragma->mPragFlg & PragFlg_Result1 ){
002811 sqlite3_str_appendall(&acc, ",arg HIDDEN");
002812 j++;
002813 }
002814 if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
002815 sqlite3_str_appendall(&acc, ",schema HIDDEN");
002816 j++;
002817 }
002818 sqlite3_str_append(&acc, ")", 1);
002819 sqlite3StrAccumFinish(&acc);
002820 assert( strlen(zBuf) < sizeof(zBuf)-1 );
002821 rc = sqlite3_declare_vtab(db, zBuf);
002822 if( rc==SQLITE_OK ){
002823 pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
002824 if( pTab==0 ){
002825 rc = SQLITE_NOMEM;
002826 }else{
002827 memset(pTab, 0, sizeof(PragmaVtab));
002828 pTab->pName = pPragma;
002829 pTab->db = db;
002830 pTab->iHidden = i;
002831 pTab->nHidden = j;
002832 }
002833 }else{
002834 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
002835 }
002836
002837 *ppVtab = (sqlite3_vtab*)pTab;
002838 return rc;
002839 }
002840
002841 /*
002842 ** Pragma virtual table module xDisconnect method.
002843 */
002844 static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
002845 PragmaVtab *pTab = (PragmaVtab*)pVtab;
002846 sqlite3_free(pTab);
002847 return SQLITE_OK;
002848 }
002849
002850 /* Figure out the best index to use to search a pragma virtual table.
002851 **
002852 ** There are not really any index choices. But we want to encourage the
002853 ** query planner to give == constraints on as many hidden parameters as
002854 ** possible, and especially on the first hidden parameter. So return a
002855 ** high cost if hidden parameters are unconstrained.
002856 */
002857 static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
002858 PragmaVtab *pTab = (PragmaVtab*)tab;
002859 const struct sqlite3_index_constraint *pConstraint;
002860 int i, j;
002861 int seen[2];
002862
002863 pIdxInfo->estimatedCost = (double)1;
002864 if( pTab->nHidden==0 ){ return SQLITE_OK; }
002865 pConstraint = pIdxInfo->aConstraint;
002866 seen[0] = 0;
002867 seen[1] = 0;
002868 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
002869 if( pConstraint->iColumn < pTab->iHidden ) continue;
002870 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
002871 if( pConstraint->usable==0 ) return SQLITE_CONSTRAINT;
002872 j = pConstraint->iColumn - pTab->iHidden;
002873 assert( j < 2 );
002874 seen[j] = i+1;
002875 }
002876 if( seen[0]==0 ){
002877 pIdxInfo->estimatedCost = (double)2147483647;
002878 pIdxInfo->estimatedRows = 2147483647;
002879 return SQLITE_OK;
002880 }
002881 j = seen[0]-1;
002882 pIdxInfo->aConstraintUsage[j].argvIndex = 1;
002883 pIdxInfo->aConstraintUsage[j].omit = 1;
002884 pIdxInfo->estimatedCost = (double)20;
002885 pIdxInfo->estimatedRows = 20;
002886 if( seen[1] ){
002887 j = seen[1]-1;
002888 pIdxInfo->aConstraintUsage[j].argvIndex = 2;
002889 pIdxInfo->aConstraintUsage[j].omit = 1;
002890 }
002891 return SQLITE_OK;
002892 }
002893
002894 /* Create a new cursor for the pragma virtual table */
002895 static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
002896 PragmaVtabCursor *pCsr;
002897 pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
002898 if( pCsr==0 ) return SQLITE_NOMEM;
002899 memset(pCsr, 0, sizeof(PragmaVtabCursor));
002900 pCsr->base.pVtab = pVtab;
002901 *ppCursor = &pCsr->base;
002902 return SQLITE_OK;
002903 }
002904
002905 /* Clear all content from pragma virtual table cursor. */
002906 static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
002907 int i;
002908 sqlite3_finalize(pCsr->pPragma);
002909 pCsr->pPragma = 0;
002910 pCsr->iRowid = 0;
002911 for(i=0; i<ArraySize(pCsr->azArg); i++){
002912 sqlite3_free(pCsr->azArg[i]);
002913 pCsr->azArg[i] = 0;
002914 }
002915 }
002916
002917 /* Close a pragma virtual table cursor */
002918 static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
002919 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
002920 pragmaVtabCursorClear(pCsr);
002921 sqlite3_free(pCsr);
002922 return SQLITE_OK;
002923 }
002924
002925 /* Advance the pragma virtual table cursor to the next row */
002926 static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
002927 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
002928 int rc = SQLITE_OK;
002929
002930 /* Increment the xRowid value */
002931 pCsr->iRowid++;
002932 assert( pCsr->pPragma );
002933 if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
002934 rc = sqlite3_finalize(pCsr->pPragma);
002935 pCsr->pPragma = 0;
002936 pragmaVtabCursorClear(pCsr);
002937 }
002938 return rc;
002939 }
002940
002941 /*
002942 ** Pragma virtual table module xFilter method.
002943 */
002944 static int pragmaVtabFilter(
002945 sqlite3_vtab_cursor *pVtabCursor,
002946 int idxNum, const char *idxStr,
002947 int argc, sqlite3_value **argv
002948 ){
002949 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
002950 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
002951 int rc;
002952 int i, j;
002953 StrAccum acc;
002954 char *zSql;
002955
002956 UNUSED_PARAMETER(idxNum);
002957 UNUSED_PARAMETER(idxStr);
002958 pragmaVtabCursorClear(pCsr);
002959 j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
002960 for(i=0; i<argc; i++, j++){
002961 const char *zText = (const char*)sqlite3_value_text(argv[i]);
002962 assert( j<ArraySize(pCsr->azArg) );
002963 assert( pCsr->azArg[j]==0 );
002964 if( zText ){
002965 pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
002966 if( pCsr->azArg[j]==0 ){
002967 return SQLITE_NOMEM;
002968 }
002969 }
002970 }
002971 sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
002972 sqlite3_str_appendall(&acc, "PRAGMA ");
002973 if( pCsr->azArg[1] ){
002974 sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
002975 }
002976 sqlite3_str_appendall(&acc, pTab->pName->zName);
002977 if( pCsr->azArg[0] ){
002978 sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
002979 }
002980 zSql = sqlite3StrAccumFinish(&acc);
002981 if( zSql==0 ) return SQLITE_NOMEM;
002982 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
002983 sqlite3_free(zSql);
002984 if( rc!=SQLITE_OK ){
002985 pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
002986 return rc;
002987 }
002988 return pragmaVtabNext(pVtabCursor);
002989 }
002990
002991 /*
002992 ** Pragma virtual table module xEof method.
002993 */
002994 static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
002995 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
002996 return (pCsr->pPragma==0);
002997 }
002998
002999 /* The xColumn method simply returns the corresponding column from
003000 ** the PRAGMA.
003001 */
003002 static int pragmaVtabColumn(
003003 sqlite3_vtab_cursor *pVtabCursor,
003004 sqlite3_context *ctx,
003005 int i
003006 ){
003007 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
003008 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
003009 if( i<pTab->iHidden ){
003010 sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
003011 }else{
003012 sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
003013 }
003014 return SQLITE_OK;
003015 }
003016
003017 /*
003018 ** Pragma virtual table module xRowid method.
003019 */
003020 static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
003021 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
003022 *p = pCsr->iRowid;
003023 return SQLITE_OK;
003024 }
003025
003026 /* The pragma virtual table object */
003027 static const sqlite3_module pragmaVtabModule = {
003028 0, /* iVersion */
003029 0, /* xCreate - create a table */
003030 pragmaVtabConnect, /* xConnect - connect to an existing table */
003031 pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */
003032 pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */
003033 0, /* xDestroy - Drop a table */
003034 pragmaVtabOpen, /* xOpen - open a cursor */
003035 pragmaVtabClose, /* xClose - close a cursor */
003036 pragmaVtabFilter, /* xFilter - configure scan constraints */
003037 pragmaVtabNext, /* xNext - advance a cursor */
003038 pragmaVtabEof, /* xEof */
003039 pragmaVtabColumn, /* xColumn - read data */
003040 pragmaVtabRowid, /* xRowid - read data */
003041 0, /* xUpdate - write data */
003042 0, /* xBegin - begin transaction */
003043 0, /* xSync - sync transaction */
003044 0, /* xCommit - commit transaction */
003045 0, /* xRollback - rollback transaction */
003046 0, /* xFindFunction - function overloading */
003047 0, /* xRename - rename the table */
003048 0, /* xSavepoint */
003049 0, /* xRelease */
003050 0, /* xRollbackTo */
003051 0, /* xShadowName */
003052 0 /* xIntegrity */
003053 };
003054
003055 /*
003056 ** Check to see if zTabName is really the name of a pragma. If it is,
003057 ** then register an eponymous virtual table for that pragma and return
003058 ** a pointer to the Module object for the new virtual table.
003059 */
003060 Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
003061 const PragmaName *pName;
003062 assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
003063 pName = pragmaLocate(zName+7);
003064 if( pName==0 ) return 0;
003065 if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
003066 assert( sqlite3HashFind(&db->aModule, zName)==0 );
003067 return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
003068 }
003069
003070 #endif /* SQLITE_OMIT_VIRTUALTABLE */
003071
003072 #endif /* SQLITE_OMIT_PRAGMA */