1 /* 2 ** 2003 April 6 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** May you do good and not evil. 8 ** May you find forgiveness for yourself and forgive others. 9 ** May you share freely, never taking more than you give. 10 ** 11 ************************************************************************* 12 ** This file contains code used to implement the PRAGMA command. 13 */ 14 #include "sqliteInt.h" 15 16 #if !defined(SQLITE_ENABLE_LOCKING_STYLE) 17 # if defined(__APPLE__) 18 # define SQLITE_ENABLE_LOCKING_STYLE 1 19 # else 20 # define SQLITE_ENABLE_LOCKING_STYLE 0 21 # endif 22 #endif 23 24 /*************************************************************************** 25 ** The "pragma.h" include file is an automatically generated file that 26 ** that includes the PragType_XXXX macro definitions and the aPragmaName[] 27 ** object. This ensures that the aPragmaName[] table is arranged in 28 ** lexicographical order to facility a binary search of the pragma name. 29 ** Do not edit pragma.h directly. Edit and rerun the script in at 30 ** ../tool/mkpragmatab.tcl. */ 31 #include "pragma.h" 32 33 /* 34 ** Interpret the given string as a safety level. Return 0 for OFF, 35 ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or 36 ** unrecognized string argument. The FULL and EXTRA option is disallowed 37 ** if the omitFull parameter it 1. 38 ** 39 ** Note that the values returned are one less that the values that 40 ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done 41 ** to support legacy SQL code. The safety level used to be boolean 42 ** and older scripts may have used numbers 0 for OFF and 1 for ON. 43 */ 44 static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){ 45 /* 123456789 123456789 123 */ 46 static const char zText[] = "onoffalseyestruextrafull"; 47 static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20}; 48 static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4}; 49 static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2}; 50 /* on no off false yes true extra full */ 51 int i, n; 52 if( sqlite3Isdigit(*z) ){ 53 return (u8)sqlite3Atoi(z); 54 } 55 n = sqlite3Strlen30(z); 56 for(i=0; i<ArraySize(iLength); i++){ 57 if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 58 && (!omitFull || iValue[i]<=1) 59 ){ 60 return iValue[i]; 61 } 62 } 63 return dflt; 64 } 65 66 /* 67 ** Interpret the given string as a boolean value. 68 */ 69 u8 sqlite3GetBoolean(const char *z, u8 dflt){ 70 return getSafetyLevel(z,1,dflt)!=0; 71 } 72 73 /* The sqlite3GetBoolean() function is used by other modules but the 74 ** remainder of this file is specific to PRAGMA processing. So omit 75 ** the rest of the file if PRAGMAs are omitted from the build. 76 */ 77 #if !defined(SQLITE_OMIT_PRAGMA) 78 79 /* 80 ** Interpret the given string as a locking mode value. 81 */ 82 static int getLockingMode(const char *z){ 83 if( z ){ 84 if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE; 85 if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL; 86 } 87 return PAGER_LOCKINGMODE_QUERY; 88 } 89 90 #ifndef SQLITE_OMIT_AUTOVACUUM 91 /* 92 ** Interpret the given string as an auto-vacuum mode value. 93 ** 94 ** The following strings, "none", "full" and "incremental" are 95 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively. 96 */ 97 static int getAutoVacuum(const char *z){ 98 int i; 99 if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE; 100 if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL; 101 if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR; 102 i = sqlite3Atoi(z); 103 return (u8)((i>=0&&i<=2)?i:0); 104 } 105 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */ 106 107 #ifndef SQLITE_OMIT_PAGER_PRAGMAS 108 /* 109 ** Interpret the given string as a temp db location. Return 1 for file 110 ** backed temporary databases, 2 for the Red-Black tree in memory database 111 ** and 0 to use the compile-time default. 112 */ 113 static int getTempStore(const char *z){ 114 if( z[0]>='0' && z[0]<='2' ){ 115 return z[0] - '0'; 116 }else if( sqlite3StrICmp(z, "file")==0 ){ 117 return 1; 118 }else if( sqlite3StrICmp(z, "memory")==0 ){ 119 return 2; 120 }else{ 121 return 0; 122 } 123 } 124 #endif /* SQLITE_PAGER_PRAGMAS */ 125 126 #ifndef SQLITE_OMIT_PAGER_PRAGMAS 127 /* 128 ** Invalidate temp storage, either when the temp storage is changed 129 ** from default, or when 'file' and the temp_store_directory has changed 130 */ 131 static int invalidateTempStorage(Parse *pParse){ 132 sqlite3 *db = pParse->db; 133 if( db->aDb[1].pBt!=0 ){ 134 if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){ 135 sqlite3ErrorMsg(pParse, "temporary storage cannot be changed " 136 "from within a transaction"); 137 return SQLITE_ERROR; 138 } 139 sqlite3BtreeClose(db->aDb[1].pBt); 140 db->aDb[1].pBt = 0; 141 sqlite3ResetAllSchemasOfConnection(db); 142 } 143 return SQLITE_OK; 144 } 145 #endif /* SQLITE_PAGER_PRAGMAS */ 146 147 #ifndef SQLITE_OMIT_PAGER_PRAGMAS 148 /* 149 ** If the TEMP database is open, close it and mark the database schema 150 ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE 151 ** or DEFAULT_TEMP_STORE pragmas. 152 */ 153 static int changeTempStorage(Parse *pParse, const char *zStorageType){ 154 int ts = getTempStore(zStorageType); 155 sqlite3 *db = pParse->db; 156 if( db->temp_store==ts ) return SQLITE_OK; 157 if( invalidateTempStorage( pParse ) != SQLITE_OK ){ 158 return SQLITE_ERROR; 159 } 160 db->temp_store = (u8)ts; 161 return SQLITE_OK; 162 } 163 #endif /* SQLITE_PAGER_PRAGMAS */ 164 165 /* 166 ** Set result column names for a pragma. 167 */ 168 static void setPragmaResultColumnNames( 169 Vdbe *v, /* The query under construction */ 170 const PragmaName *pPragma /* The pragma */ 171 ){ 172 u8 n = pPragma->nPragCName; 173 sqlite3VdbeSetNumCols(v, n==0 ? 1 : n); 174 if( n==0 ){ 175 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC); 176 }else{ 177 int i, j; 178 for(i=0, j=pPragma->iPragCName; i<n; i++, j++){ 179 sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC); 180 } 181 } 182 } 183 184 /* 185 ** Generate code to return a single integer value. 186 */ 187 static void returnSingleInt(Vdbe *v, i64 value){ 188 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64); 189 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); 190 } 191 192 /* 193 ** Generate code to return a single text value. 194 */ 195 static void returnSingleText( 196 Vdbe *v, /* Prepared statement under construction */ 197 const char *zValue /* Value to be returned */ 198 ){ 199 if( zValue ){ 200 sqlite3VdbeLoadString(v, 1, (const char*)zValue); 201 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); 202 } 203 } 204 205 206 /* 207 ** Set the safety_level and pager flags for pager iDb. Or if iDb<0 208 ** set these values for all pagers. 209 */ 210 #ifndef SQLITE_OMIT_PAGER_PRAGMAS 211 static void setAllPagerFlags(sqlite3 *db){ 212 if( db->autoCommit ){ 213 Db *pDb = db->aDb; 214 int n = db->nDb; 215 assert( SQLITE_FullFSync==PAGER_FULLFSYNC ); 216 assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC ); 217 assert( SQLITE_CacheSpill==PAGER_CACHESPILL ); 218 assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL) 219 == PAGER_FLAGS_MASK ); 220 assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level ); 221 while( (n--) > 0 ){ 222 if( pDb->pBt ){ 223 sqlite3BtreeSetPagerFlags(pDb->pBt, 224 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) ); 225 } 226 pDb++; 227 } 228 } 229 } 230 #else 231 # define setAllPagerFlags(X) /* no-op */ 232 #endif 233 234 235 /* 236 ** Return a human-readable name for a constraint resolution action. 237 */ 238 #ifndef SQLITE_OMIT_FOREIGN_KEY 239 static const char *actionName(u8 action){ 240 const char *zName; 241 switch( action ){ 242 case OE_SetNull: zName = "SET NULL"; break; 243 case OE_SetDflt: zName = "SET DEFAULT"; break; 244 case OE_Cascade: zName = "CASCADE"; break; 245 case OE_Restrict: zName = "RESTRICT"; break; 246 default: zName = "NO ACTION"; 247 assert( action==OE_None ); break; 248 } 249 return zName; 250 } 251 #endif 252 253 254 /* 255 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants 256 ** defined in pager.h. This function returns the associated lowercase 257 ** journal-mode name. 258 */ 259 const char *sqlite3JournalModename(int eMode){ 260 static char * const azModeName[] = { 261 "delete", "persist", "off", "truncate", "memory" 262 #ifndef SQLITE_OMIT_WAL 263 , "wal" 264 #endif 265 }; 266 assert( PAGER_JOURNALMODE_DELETE==0 ); 267 assert( PAGER_JOURNALMODE_PERSIST==1 ); 268 assert( PAGER_JOURNALMODE_OFF==2 ); 269 assert( PAGER_JOURNALMODE_TRUNCATE==3 ); 270 assert( PAGER_JOURNALMODE_MEMORY==4 ); 271 assert( PAGER_JOURNALMODE_WAL==5 ); 272 assert( eMode>=0 && eMode<=ArraySize(azModeName) ); 273 274 if( eMode==ArraySize(azModeName) ) return 0; 275 return azModeName[eMode]; 276 } 277 278 /* 279 ** Locate a pragma in the aPragmaName[] array. 280 */ 281 static const PragmaName *pragmaLocate(const char *zName){ 282 int upr, lwr, mid = 0, rc; 283 lwr = 0; 284 upr = ArraySize(aPragmaName)-1; 285 while( lwr<=upr ){ 286 mid = (lwr+upr)/2; 287 rc = sqlite3_stricmp(zName, aPragmaName[mid].zName); 288 if( rc==0 ) break; 289 if( rc<0 ){ 290 upr = mid - 1; 291 }else{ 292 lwr = mid + 1; 293 } 294 } 295 return lwr>upr ? 0 : &aPragmaName[mid]; 296 } 297 298 /* 299 ** Helper subroutine for PRAGMA integrity_check: 300 ** 301 ** Generate code to output a single-column result row with a value of the 302 ** string held in register 3. Decrement the result count in register 1 303 ** and halt if the maximum number of result rows have been issued. 304 */ 305 static int integrityCheckResultRow(Vdbe *v){ 306 int addr; 307 sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1); 308 addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1); 309 VdbeCoverage(v); 310 sqlite3VdbeAddOp0(v, OP_Halt); 311 return addr; 312 } 313 314 /* 315 ** Process a pragma statement. 316 ** 317 ** Pragmas are of this form: 318 ** 319 ** PRAGMA [schema.]id [= value] 320 ** 321 ** The identifier might also be a string. The value is a string, and 322 ** identifier, or a number. If minusFlag is true, then the value is 323 ** a number that was preceded by a minus sign. 324 ** 325 ** If the left side is "database.id" then pId1 is the database name 326 ** and pId2 is the id. If the left side is just "id" then pId1 is the 327 ** id and pId2 is any empty string. 328 */ 329 void sqlite3Pragma( 330 Parse *pParse, 331 Token *pId1, /* First part of [schema.]id field */ 332 Token *pId2, /* Second part of [schema.]id field, or NULL */ 333 Token *pValue, /* Token for <value>, or NULL */ 334 int minusFlag /* True if a '-' sign preceded <value> */ 335 ){ 336 char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */ 337 char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */ 338 const char *zDb = 0; /* The database name */ 339 Token *pId; /* Pointer to <id> token */ 340 char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */ 341 int iDb; /* Database index for <database> */ 342 int rc; /* return value form SQLITE_FCNTL_PRAGMA */ 343 sqlite3 *db = pParse->db; /* The database connection */ 344 Db *pDb; /* The specific database being pragmaed */ 345 Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */ 346 const PragmaName *pPragma; /* The pragma */ 347 348 if( v==0 ) return; 349 sqlite3VdbeRunOnlyOnce(v); 350 pParse->nMem = 2; 351 352 /* Interpret the [schema.] part of the pragma statement. iDb is the 353 ** index of the database this pragma is being applied to in db.aDb[]. */ 354 iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId); 355 if( iDb<0 ) return; 356 pDb = &db->aDb[iDb]; 357 358 /* If the temp database has been explicitly named as part of the 359 ** pragma, make sure it is open. 360 */ 361 if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){ 362 return; 363 } 364 365 zLeft = sqlite3NameFromToken(db, pId); 366 if( !zLeft ) return; 367 if( minusFlag ){ 368 zRight = sqlite3MPrintf(db, "-%T", pValue); 369 }else{ 370 zRight = sqlite3NameFromToken(db, pValue); 371 } 372 373 assert( pId2 ); 374 zDb = pId2->n>0 ? pDb->zDbSName : 0; 375 if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){ 376 goto pragma_out; 377 } 378 379 /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS 380 ** connection. If it returns SQLITE_OK, then assume that the VFS 381 ** handled the pragma and generate a no-op prepared statement. 382 ** 383 ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed, 384 ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file 385 ** object corresponding to the database file to which the pragma 386 ** statement refers. 387 ** 388 ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA 389 ** file control is an array of pointers to strings (char**) in which the 390 ** second element of the array is the name of the pragma and the third 391 ** element is the argument to the pragma or NULL if the pragma has no 392 ** argument. 393 */ 394 aFcntl[0] = 0; 395 aFcntl[1] = zLeft; 396 aFcntl[2] = zRight; 397 aFcntl[3] = 0; 398 db->busyHandler.nBusy = 0; 399 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl); 400 if( rc==SQLITE_OK ){ 401 sqlite3VdbeSetNumCols(v, 1); 402 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT); 403 returnSingleText(v, aFcntl[0]); 404 sqlite3_free(aFcntl[0]); 405 goto pragma_out; 406 } 407 if( rc!=SQLITE_NOTFOUND ){ 408 if( aFcntl[0] ){ 409 sqlite3ErrorMsg(pParse, "%s", aFcntl[0]); 410 sqlite3_free(aFcntl[0]); 411 } 412 pParse->nErr++; 413 pParse->rc = rc; 414 goto pragma_out; 415 } 416 417 /* Locate the pragma in the lookup table */ 418 pPragma = pragmaLocate(zLeft); 419 if( pPragma==0 ) goto pragma_out; 420 421 /* Make sure the database schema is loaded if the pragma requires that */ 422 if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){ 423 if( sqlite3ReadSchema(pParse) ) goto pragma_out; 424 } 425 426 /* Register the result column names for pragmas that return results */ 427 if( (pPragma->mPragFlg & PragFlg_NoColumns)==0 428 && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0) 429 ){ 430 setPragmaResultColumnNames(v, pPragma); 431 } 432 433 /* Jump to the appropriate pragma handler */ 434 switch( pPragma->ePragTyp ){ 435 436 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED) 437 /* 438 ** PRAGMA [schema.]default_cache_size 439 ** PRAGMA [schema.]default_cache_size=N 440 ** 441 ** The first form reports the current persistent setting for the 442 ** page cache size. The value returned is the maximum number of 443 ** pages in the page cache. The second form sets both the current 444 ** page cache size value and the persistent page cache size value 445 ** stored in the database file. 446 ** 447 ** Older versions of SQLite would set the default cache size to a 448 ** negative number to indicate synchronous=OFF. These days, synchronous 449 ** is always on by default regardless of the sign of the default cache 450 ** size. But continue to take the absolute value of the default cache 451 ** size of historical compatibility. 452 */ 453 case PragTyp_DEFAULT_CACHE_SIZE: { 454 static const int iLn = VDBE_OFFSET_LINENO(2); 455 static const VdbeOpList getCacheSize[] = { 456 { OP_Transaction, 0, 0, 0}, /* 0 */ 457 { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */ 458 { OP_IfPos, 1, 8, 0}, 459 { OP_Integer, 0, 2, 0}, 460 { OP_Subtract, 1, 2, 1}, 461 { OP_IfPos, 1, 8, 0}, 462 { OP_Integer, 0, 1, 0}, /* 6 */ 463 { OP_Noop, 0, 0, 0}, 464 { OP_ResultRow, 1, 1, 0}, 465 }; 466 VdbeOp *aOp; 467 sqlite3VdbeUsesBtree(v, iDb); 468 if( !zRight ){ 469 pParse->nMem += 2; 470 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize)); 471 aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn); 472 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; 473 aOp[0].p1 = iDb; 474 aOp[1].p1 = iDb; 475 aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE; 476 }else{ 477 int size = sqlite3AbsInt32(sqlite3Atoi(zRight)); 478 sqlite3BeginWriteOperation(pParse, 0, iDb); 479 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size); 480 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 481 pDb->pSchema->cache_size = size; 482 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); 483 } 484 break; 485 } 486 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */ 487 488 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) 489 /* 490 ** PRAGMA [schema.]page_size 491 ** PRAGMA [schema.]page_size=N 492 ** 493 ** The first form reports the current setting for the 494 ** database page size in bytes. The second form sets the 495 ** database page size value. The value can only be set if 496 ** the database has not yet been created. 497 */ 498 case PragTyp_PAGE_SIZE: { 499 Btree *pBt = pDb->pBt; 500 assert( pBt!=0 ); 501 if( !zRight ){ 502 int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0; 503 returnSingleInt(v, size); 504 }else{ 505 /* Malloc may fail when setting the page-size, as there is an internal 506 ** buffer that the pager module resizes using sqlite3_realloc(). 507 */ 508 db->nextPagesize = sqlite3Atoi(zRight); 509 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){ 510 sqlite3OomFault(db); 511 } 512 } 513 break; 514 } 515 516 /* 517 ** PRAGMA [schema.]secure_delete 518 ** PRAGMA [schema.]secure_delete=ON/OFF/FAST 519 ** 520 ** The first form reports the current setting for the 521 ** secure_delete flag. The second form changes the secure_delete 522 ** flag setting and reports the new value. 523 */ 524 case PragTyp_SECURE_DELETE: { 525 Btree *pBt = pDb->pBt; 526 int b = -1; 527 assert( pBt!=0 ); 528 if( zRight ){ 529 if( sqlite3_stricmp(zRight, "fast")==0 ){ 530 b = 2; 531 }else{ 532 b = sqlite3GetBoolean(zRight, 0); 533 } 534 } 535 if( pId2->n==0 && b>=0 ){ 536 int ii; 537 for(ii=0; ii<db->nDb; ii++){ 538 sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b); 539 } 540 } 541 b = sqlite3BtreeSecureDelete(pBt, b); 542 returnSingleInt(v, b); 543 break; 544 } 545 546 /* 547 ** PRAGMA [schema.]max_page_count 548 ** PRAGMA [schema.]max_page_count=N 549 ** 550 ** The first form reports the current setting for the 551 ** maximum number of pages in the database file. The 552 ** second form attempts to change this setting. Both 553 ** forms return the current setting. 554 ** 555 ** The absolute value of N is used. This is undocumented and might 556 ** change. The only purpose is to provide an easy way to test 557 ** the sqlite3AbsInt32() function. 558 ** 559 ** PRAGMA [schema.]page_count 560 ** 561 ** Return the number of pages in the specified database. 562 */ 563 case PragTyp_PAGE_COUNT: { 564 int iReg; 565 sqlite3CodeVerifySchema(pParse, iDb); 566 iReg = ++pParse->nMem; 567 if( sqlite3Tolower(zLeft[0])=='p' ){ 568 sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg); 569 }else{ 570 sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, 571 sqlite3AbsInt32(sqlite3Atoi(zRight))); 572 } 573 sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1); 574 break; 575 } 576 577 /* 578 ** PRAGMA [schema.]locking_mode 579 ** PRAGMA [schema.]locking_mode = (normal|exclusive) 580 */ 581 case PragTyp_LOCKING_MODE: { 582 const char *zRet = "normal"; 583 int eMode = getLockingMode(zRight); 584 585 if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){ 586 /* Simple "PRAGMA locking_mode;" statement. This is a query for 587 ** the current default locking mode (which may be different to 588 ** the locking-mode of the main database). 589 */ 590 eMode = db->dfltLockMode; 591 }else{ 592 Pager *pPager; 593 if( pId2->n==0 ){ 594 /* This indicates that no database name was specified as part 595 ** of the PRAGMA command. In this case the locking-mode must be 596 ** set on all attached databases, as well as the main db file. 597 ** 598 ** Also, the sqlite3.dfltLockMode variable is set so that 599 ** any subsequently attached databases also use the specified 600 ** locking mode. 601 */ 602 int ii; 603 assert(pDb==&db->aDb[0]); 604 for(ii=2; ii<db->nDb; ii++){ 605 pPager = sqlite3BtreePager(db->aDb[ii].pBt); 606 sqlite3PagerLockingMode(pPager, eMode); 607 } 608 db->dfltLockMode = (u8)eMode; 609 } 610 pPager = sqlite3BtreePager(pDb->pBt); 611 eMode = sqlite3PagerLockingMode(pPager, eMode); 612 } 613 614 assert( eMode==PAGER_LOCKINGMODE_NORMAL 615 || eMode==PAGER_LOCKINGMODE_EXCLUSIVE ); 616 if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){ 617 zRet = "exclusive"; 618 } 619 returnSingleText(v, zRet); 620 break; 621 } 622 623 /* 624 ** PRAGMA [schema.]journal_mode 625 ** PRAGMA [schema.]journal_mode = 626 ** (delete|persist|off|truncate|memory|wal|off) 627 */ 628 case PragTyp_JOURNAL_MODE: { 629 int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */ 630 int ii; /* Loop counter */ 631 632 if( zRight==0 ){ 633 /* If there is no "=MODE" part of the pragma, do a query for the 634 ** current mode */ 635 eMode = PAGER_JOURNALMODE_QUERY; 636 }else{ 637 const char *zMode; 638 int n = sqlite3Strlen30(zRight); 639 for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){ 640 if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break; 641 } 642 if( !zMode ){ 643 /* If the "=MODE" part does not match any known journal mode, 644 ** then do a query */ 645 eMode = PAGER_JOURNALMODE_QUERY; 646 } 647 if( eMode==PAGER_JOURNALMODE_OFF && (db->flags & SQLITE_Defensive)!=0 ){ 648 /* Do not allow journal-mode "OFF" in defensive since the database 649 ** can become corrupted using ordinary SQL when the journal is off */ 650 eMode = PAGER_JOURNALMODE_QUERY; 651 } 652 } 653 if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){ 654 /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */ 655 iDb = 0; 656 pId2->n = 1; 657 } 658 for(ii=db->nDb-1; ii>=0; ii--){ 659 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ 660 sqlite3VdbeUsesBtree(v, ii); 661 sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode); 662 } 663 } 664 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); 665 break; 666 } 667 668 /* 669 ** PRAGMA [schema.]journal_size_limit 670 ** PRAGMA [schema.]journal_size_limit=N 671 ** 672 ** Get or set the size limit on rollback journal files. 673 */ 674 case PragTyp_JOURNAL_SIZE_LIMIT: { 675 Pager *pPager = sqlite3BtreePager(pDb->pBt); 676 i64 iLimit = -2; 677 if( zRight ){ 678 sqlite3DecOrHexToI64(zRight, &iLimit); 679 if( iLimit<-1 ) iLimit = -1; 680 } 681 iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit); 682 returnSingleInt(v, iLimit); 683 break; 684 } 685 686 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */ 687 688 /* 689 ** PRAGMA [schema.]auto_vacuum 690 ** PRAGMA [schema.]auto_vacuum=N 691 ** 692 ** Get or set the value of the database 'auto-vacuum' parameter. 693 ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL 694 */ 695 #ifndef SQLITE_OMIT_AUTOVACUUM 696 case PragTyp_AUTO_VACUUM: { 697 Btree *pBt = pDb->pBt; 698 assert( pBt!=0 ); 699 if( !zRight ){ 700 returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt)); 701 }else{ 702 int eAuto = getAutoVacuum(zRight); 703 assert( eAuto>=0 && eAuto<=2 ); 704 db->nextAutovac = (u8)eAuto; 705 /* Call SetAutoVacuum() to set initialize the internal auto and 706 ** incr-vacuum flags. This is required in case this connection 707 ** creates the database file. It is important that it is created 708 ** as an auto-vacuum capable db. 709 */ 710 rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto); 711 if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){ 712 /* When setting the auto_vacuum mode to either "full" or 713 ** "incremental", write the value of meta[6] in the database 714 ** file. Before writing to meta[6], check that meta[3] indicates 715 ** that this really is an auto-vacuum capable database. 716 */ 717 static const int iLn = VDBE_OFFSET_LINENO(2); 718 static const VdbeOpList setMeta6[] = { 719 { OP_Transaction, 0, 1, 0}, /* 0 */ 720 { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE}, 721 { OP_If, 1, 0, 0}, /* 2 */ 722 { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */ 723 { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */ 724 }; 725 VdbeOp *aOp; 726 int iAddr = sqlite3VdbeCurrentAddr(v); 727 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6)); 728 aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn); 729 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; 730 aOp[0].p1 = iDb; 731 aOp[1].p1 = iDb; 732 aOp[2].p2 = iAddr+4; 733 aOp[4].p1 = iDb; 734 aOp[4].p3 = eAuto - 1; 735 sqlite3VdbeUsesBtree(v, iDb); 736 } 737 } 738 break; 739 } 740 #endif 741 742 /* 743 ** PRAGMA [schema.]incremental_vacuum(N) 744 ** 745 ** Do N steps of incremental vacuuming on a database. 746 */ 747 #ifndef SQLITE_OMIT_AUTOVACUUM 748 case PragTyp_INCREMENTAL_VACUUM: { 749 int iLimit, addr; 750 if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){ 751 iLimit = 0x7fffffff; 752 } 753 sqlite3BeginWriteOperation(pParse, 0, iDb); 754 sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1); 755 addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v); 756 sqlite3VdbeAddOp1(v, OP_ResultRow, 1); 757 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); 758 sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v); 759 sqlite3VdbeJumpHere(v, addr); 760 break; 761 } 762 #endif 763 764 #ifndef SQLITE_OMIT_PAGER_PRAGMAS 765 /* 766 ** PRAGMA [schema.]cache_size 767 ** PRAGMA [schema.]cache_size=N 768 ** 769 ** The first form reports the current local setting for the 770 ** page cache size. The second form sets the local 771 ** page cache size value. If N is positive then that is the 772 ** number of pages in the cache. If N is negative, then the 773 ** number of pages is adjusted so that the cache uses -N kibibytes 774 ** of memory. 775 */ 776 case PragTyp_CACHE_SIZE: { 777 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 778 if( !zRight ){ 779 returnSingleInt(v, pDb->pSchema->cache_size); 780 }else{ 781 int size = sqlite3Atoi(zRight); 782 pDb->pSchema->cache_size = size; 783 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); 784 } 785 break; 786 } 787 788 /* 789 ** PRAGMA [schema.]cache_spill 790 ** PRAGMA cache_spill=BOOLEAN 791 ** PRAGMA [schema.]cache_spill=N 792 ** 793 ** The first form reports the current local setting for the 794 ** page cache spill size. The second form turns cache spill on 795 ** or off. When turnning cache spill on, the size is set to the 796 ** current cache_size. The third form sets a spill size that 797 ** may be different form the cache size. 798 ** If N is positive then that is the 799 ** number of pages in the cache. If N is negative, then the 800 ** number of pages is adjusted so that the cache uses -N kibibytes 801 ** of memory. 802 ** 803 ** If the number of cache_spill pages is less then the number of 804 ** cache_size pages, no spilling occurs until the page count exceeds 805 ** the number of cache_size pages. 806 ** 807 ** The cache_spill=BOOLEAN setting applies to all attached schemas, 808 ** not just the schema specified. 809 */ 810 case PragTyp_CACHE_SPILL: { 811 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 812 if( !zRight ){ 813 returnSingleInt(v, 814 (db->flags & SQLITE_CacheSpill)==0 ? 0 : 815 sqlite3BtreeSetSpillSize(pDb->pBt,0)); 816 }else{ 817 int size = 1; 818 if( sqlite3GetInt32(zRight, &size) ){ 819 sqlite3BtreeSetSpillSize(pDb->pBt, size); 820 } 821 if( sqlite3GetBoolean(zRight, size!=0) ){ 822 db->flags |= SQLITE_CacheSpill; 823 }else{ 824 db->flags &= ~(u64)SQLITE_CacheSpill; 825 } 826 setAllPagerFlags(db); 827 } 828 break; 829 } 830 831 /* 832 ** PRAGMA [schema.]mmap_size(N) 833 ** 834 ** Used to set mapping size limit. The mapping size limit is 835 ** used to limit the aggregate size of all memory mapped regions of the 836 ** database file. If this parameter is set to zero, then memory mapping 837 ** is not used at all. If N is negative, then the default memory map 838 ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set. 839 ** The parameter N is measured in bytes. 840 ** 841 ** This value is advisory. The underlying VFS is free to memory map 842 ** as little or as much as it wants. Except, if N is set to 0 then the 843 ** upper layers will never invoke the xFetch interfaces to the VFS. 844 */ 845 case PragTyp_MMAP_SIZE: { 846 sqlite3_int64 sz; 847 #if SQLITE_MAX_MMAP_SIZE>0 848 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 849 if( zRight ){ 850 int ii; 851 sqlite3DecOrHexToI64(zRight, &sz); 852 if( sz<0 ) sz = sqlite3GlobalConfig.szMmap; 853 if( pId2->n==0 ) db->szMmap = sz; 854 for(ii=db->nDb-1; ii>=0; ii--){ 855 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ 856 sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz); 857 } 858 } 859 } 860 sz = -1; 861 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz); 862 #else 863 sz = 0; 864 rc = SQLITE_OK; 865 #endif 866 if( rc==SQLITE_OK ){ 867 returnSingleInt(v, sz); 868 }else if( rc!=SQLITE_NOTFOUND ){ 869 pParse->nErr++; 870 pParse->rc = rc; 871 } 872 break; 873 } 874 875 /* 876 ** PRAGMA temp_store 877 ** PRAGMA temp_store = "default"|"memory"|"file" 878 ** 879 ** Return or set the local value of the temp_store flag. Changing 880 ** the local value does not make changes to the disk file and the default 881 ** value will be restored the next time the database is opened. 882 ** 883 ** Note that it is possible for the library compile-time options to 884 ** override this setting 885 */ 886 case PragTyp_TEMP_STORE: { 887 if( !zRight ){ 888 returnSingleInt(v, db->temp_store); 889 }else{ 890 changeTempStorage(pParse, zRight); 891 } 892 break; 893 } 894 895 /* 896 ** PRAGMA temp_store_directory 897 ** PRAGMA temp_store_directory = ""|"directory_name" 898 ** 899 ** Return or set the local value of the temp_store_directory flag. Changing 900 ** the value sets a specific directory to be used for temporary files. 901 ** Setting to a null string reverts to the default temporary directory search. 902 ** If temporary directory is changed, then invalidateTempStorage. 903 ** 904 */ 905 case PragTyp_TEMP_STORE_DIRECTORY: { 906 if( !zRight ){ 907 returnSingleText(v, sqlite3_temp_directory); 908 }else{ 909 #ifndef SQLITE_OMIT_WSD 910 if( zRight[0] ){ 911 int res; 912 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); 913 if( rc!=SQLITE_OK || res==0 ){ 914 sqlite3ErrorMsg(pParse, "not a writable directory"); 915 goto pragma_out; 916 } 917 } 918 if( SQLITE_TEMP_STORE==0 919 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1) 920 || (SQLITE_TEMP_STORE==2 && db->temp_store==1) 921 ){ 922 invalidateTempStorage(pParse); 923 } 924 sqlite3_free(sqlite3_temp_directory); 925 if( zRight[0] ){ 926 sqlite3_temp_directory = sqlite3_mprintf("%s", zRight); 927 }else{ 928 sqlite3_temp_directory = 0; 929 } 930 #endif /* SQLITE_OMIT_WSD */ 931 } 932 break; 933 } 934 935 #if SQLITE_OS_WIN 936 /* 937 ** PRAGMA data_store_directory 938 ** PRAGMA data_store_directory = ""|"directory_name" 939 ** 940 ** Return or set the local value of the data_store_directory flag. Changing 941 ** the value sets a specific directory to be used for database files that 942 ** were specified with a relative pathname. Setting to a null string reverts 943 ** to the default database directory, which for database files specified with 944 ** a relative path will probably be based on the current directory for the 945 ** process. Database file specified with an absolute path are not impacted 946 ** by this setting, regardless of its value. 947 ** 948 */ 949 case PragTyp_DATA_STORE_DIRECTORY: { 950 if( !zRight ){ 951 returnSingleText(v, sqlite3_data_directory); 952 }else{ 953 #ifndef SQLITE_OMIT_WSD 954 if( zRight[0] ){ 955 int res; 956 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); 957 if( rc!=SQLITE_OK || res==0 ){ 958 sqlite3ErrorMsg(pParse, "not a writable directory"); 959 goto pragma_out; 960 } 961 } 962 sqlite3_free(sqlite3_data_directory); 963 if( zRight[0] ){ 964 sqlite3_data_directory = sqlite3_mprintf("%s", zRight); 965 }else{ 966 sqlite3_data_directory = 0; 967 } 968 #endif /* SQLITE_OMIT_WSD */ 969 } 970 break; 971 } 972 #endif 973 974 #if SQLITE_ENABLE_LOCKING_STYLE 975 /* 976 ** PRAGMA [schema.]lock_proxy_file 977 ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path" 978 ** 979 ** Return or set the value of the lock_proxy_file flag. Changing 980 ** the value sets a specific file to be used for database access locks. 981 ** 982 */ 983 case PragTyp_LOCK_PROXY_FILE: { 984 if( !zRight ){ 985 Pager *pPager = sqlite3BtreePager(pDb->pBt); 986 char *proxy_file_path = NULL; 987 sqlite3_file *pFile = sqlite3PagerFile(pPager); 988 sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, 989 &proxy_file_path); 990 returnSingleText(v, proxy_file_path); 991 }else{ 992 Pager *pPager = sqlite3BtreePager(pDb->pBt); 993 sqlite3_file *pFile = sqlite3PagerFile(pPager); 994 int res; 995 if( zRight[0] ){ 996 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 997 zRight); 998 } else { 999 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 1000 NULL); 1001 } 1002 if( res!=SQLITE_OK ){ 1003 sqlite3ErrorMsg(pParse, "failed to set lock proxy file"); 1004 goto pragma_out; 1005 } 1006 } 1007 break; 1008 } 1009 #endif /* SQLITE_ENABLE_LOCKING_STYLE */ 1010 1011 /* 1012 ** PRAGMA [schema.]synchronous 1013 ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA 1014 ** 1015 ** Return or set the local value of the synchronous flag. Changing 1016 ** the local value does not make changes to the disk file and the 1017 ** default value will be restored the next time the database is 1018 ** opened. 1019 */ 1020 case PragTyp_SYNCHRONOUS: { 1021 if( !zRight ){ 1022 returnSingleInt(v, pDb->safety_level-1); 1023 }else{ 1024 if( !db->autoCommit ){ 1025 sqlite3ErrorMsg(pParse, 1026 "Safety level may not be changed inside a transaction"); 1027 }else if( iDb!=1 ){ 1028 int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK; 1029 if( iLevel==0 ) iLevel = 1; 1030 pDb->safety_level = iLevel; 1031 pDb->bSyncSet = 1; 1032 setAllPagerFlags(db); 1033 } 1034 } 1035 break; 1036 } 1037 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */ 1038 1039 #ifndef SQLITE_OMIT_FLAG_PRAGMAS 1040 case PragTyp_FLAG: { 1041 if( zRight==0 ){ 1042 setPragmaResultColumnNames(v, pPragma); 1043 returnSingleInt(v, (db->flags & pPragma->iArg)!=0 ); 1044 }else{ 1045 u64 mask = pPragma->iArg; /* Mask of bits to set or clear. */ 1046 if( db->autoCommit==0 ){ 1047 /* Foreign key support may not be enabled or disabled while not 1048 ** in auto-commit mode. */ 1049 mask &= ~(SQLITE_ForeignKeys); 1050 } 1051 #if SQLITE_USER_AUTHENTICATION 1052 if( db->auth.authLevel==UAUTH_User ){ 1053 /* Do not allow non-admin users to modify the schema arbitrarily */ 1054 mask &= ~(SQLITE_WriteSchema); 1055 } 1056 #endif 1057 1058 if( sqlite3GetBoolean(zRight, 0) ){ 1059 db->flags |= mask; 1060 }else{ 1061 db->flags &= ~mask; 1062 if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0; 1063 } 1064 1065 /* Many of the flag-pragmas modify the code generated by the SQL 1066 ** compiler (eg. count_changes). So add an opcode to expire all 1067 ** compiled SQL statements after modifying a pragma value. 1068 */ 1069 sqlite3VdbeAddOp0(v, OP_Expire); 1070 setAllPagerFlags(db); 1071 } 1072 break; 1073 } 1074 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */ 1075 1076 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS 1077 /* 1078 ** PRAGMA table_info(<table>) 1079 ** 1080 ** Return a single row for each column of the named table. The columns of 1081 ** the returned data set are: 1082 ** 1083 ** cid: Column id (numbered from left to right, starting at 0) 1084 ** name: Column name 1085 ** type: Column declaration type. 1086 ** notnull: True if 'NOT NULL' is part of column declaration 1087 ** dflt_value: The default value for the column, if any. 1088 ** pk: Non-zero for PK fields. 1089 */ 1090 case PragTyp_TABLE_INFO: if( zRight ){ 1091 Table *pTab; 1092 pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb); 1093 if( pTab ){ 1094 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); 1095 int i, k; 1096 int nHidden = 0; 1097 Column *pCol; 1098 Index *pPk = sqlite3PrimaryKeyIndex(pTab); 1099 pParse->nMem = 7; 1100 sqlite3CodeVerifySchema(pParse, iTabDb); 1101 sqlite3ViewGetColumnNames(pParse, pTab); 1102 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){ 1103 int isHidden = 0; 1104 if( pCol->colFlags & COLFLAG_NOINSERT ){ 1105 if( pPragma->iArg==0 ){ 1106 nHidden++; 1107 continue; 1108 } 1109 if( pCol->colFlags & COLFLAG_VIRTUAL ){ 1110 isHidden = 2; /* GENERATED ALWAYS AS ... VIRTUAL */ 1111 }else if( pCol->colFlags & COLFLAG_STORED ){ 1112 isHidden = 3; /* GENERATED ALWAYS AS ... STORED */ 1113 }else{ assert( pCol->colFlags & COLFLAG_HIDDEN ); 1114 isHidden = 1; /* HIDDEN */ 1115 } 1116 } 1117 if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){ 1118 k = 0; 1119 }else if( pPk==0 ){ 1120 k = 1; 1121 }else{ 1122 for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){} 1123 } 1124 assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN || isHidden>=2 ); 1125 sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi", 1126 i-nHidden, 1127 pCol->zName, 1128 sqlite3ColumnType(pCol,""), 1129 pCol->notNull ? 1 : 0, 1130 pCol->pDflt && isHidden<2 ? pCol->pDflt->u.zToken : 0, 1131 k, 1132 isHidden); 1133 } 1134 } 1135 } 1136 break; 1137 1138 #ifdef SQLITE_DEBUG 1139 case PragTyp_STATS: { 1140 Index *pIdx; 1141 HashElem *i; 1142 pParse->nMem = 5; 1143 sqlite3CodeVerifySchema(pParse, iDb); 1144 for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){ 1145 Table *pTab = sqliteHashData(i); 1146 sqlite3VdbeMultiLoad(v, 1, "ssiii", 1147 pTab->zName, 1148 0, 1149 pTab->szTabRow, 1150 pTab->nRowLogEst, 1151 pTab->tabFlags); 1152 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 1153 sqlite3VdbeMultiLoad(v, 2, "siiiX", 1154 pIdx->zName, 1155 pIdx->szIdxRow, 1156 pIdx->aiRowLogEst[0], 1157 pIdx->hasStat1); 1158 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5); 1159 } 1160 } 1161 } 1162 break; 1163 #endif 1164 1165 case PragTyp_INDEX_INFO: if( zRight ){ 1166 Index *pIdx; 1167 Table *pTab; 1168 pIdx = sqlite3FindIndex(db, zRight, zDb); 1169 if( pIdx==0 ){ 1170 /* If there is no index named zRight, check to see if there is a 1171 ** WITHOUT ROWID table named zRight, and if there is, show the 1172 ** structure of the PRIMARY KEY index for that table. */ 1173 pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb); 1174 if( pTab && !HasRowid(pTab) ){ 1175 pIdx = sqlite3PrimaryKeyIndex(pTab); 1176 } 1177 } 1178 if( pIdx ){ 1179 int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema); 1180 int i; 1181 int mx; 1182 if( pPragma->iArg ){ 1183 /* PRAGMA index_xinfo (newer version with more rows and columns) */ 1184 mx = pIdx->nColumn; 1185 pParse->nMem = 6; 1186 }else{ 1187 /* PRAGMA index_info (legacy version) */ 1188 mx = pIdx->nKeyCol; 1189 pParse->nMem = 3; 1190 } 1191 pTab = pIdx->pTable; 1192 sqlite3CodeVerifySchema(pParse, iIdxDb); 1193 assert( pParse->nMem<=pPragma->nPragCName ); 1194 for(i=0; i<mx; i++){ 1195 i16 cnum = pIdx->aiColumn[i]; 1196 sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum, 1197 cnum<0 ? 0 : pTab->aCol[cnum].zName); 1198 if( pPragma->iArg ){ 1199 sqlite3VdbeMultiLoad(v, 4, "isiX", 1200 pIdx->aSortOrder[i], 1201 pIdx->azColl[i], 1202 i<pIdx->nKeyCol); 1203 } 1204 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem); 1205 } 1206 } 1207 } 1208 break; 1209 1210 case PragTyp_INDEX_LIST: if( zRight ){ 1211 Index *pIdx; 1212 Table *pTab; 1213 int i; 1214 pTab = sqlite3FindTable(db, zRight, zDb); 1215 if( pTab ){ 1216 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); 1217 pParse->nMem = 5; 1218 sqlite3CodeVerifySchema(pParse, iTabDb); 1219 for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){ 1220 const char *azOrigin[] = { "c", "u", "pk" }; 1221 sqlite3VdbeMultiLoad(v, 1, "isisi", 1222 i, 1223 pIdx->zName, 1224 IsUniqueIndex(pIdx), 1225 azOrigin[pIdx->idxType], 1226 pIdx->pPartIdxWhere!=0); 1227 } 1228 } 1229 } 1230 break; 1231 1232 case PragTyp_DATABASE_LIST: { 1233 int i; 1234 pParse->nMem = 3; 1235 for(i=0; i<db->nDb; i++){ 1236 if( db->aDb[i].pBt==0 ) continue; 1237 assert( db->aDb[i].zDbSName!=0 ); 1238 sqlite3VdbeMultiLoad(v, 1, "iss", 1239 i, 1240 db->aDb[i].zDbSName, 1241 sqlite3BtreeGetFilename(db->aDb[i].pBt)); 1242 } 1243 } 1244 break; 1245 1246 case PragTyp_COLLATION_LIST: { 1247 int i = 0; 1248 HashElem *p; 1249 pParse->nMem = 2; 1250 for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){ 1251 CollSeq *pColl = (CollSeq *)sqliteHashData(p); 1252 sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName); 1253 } 1254 } 1255 break; 1256 1257 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS 1258 case PragTyp_FUNCTION_LIST: { 1259 int i; 1260 HashElem *j; 1261 FuncDef *p; 1262 pParse->nMem = 2; 1263 for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){ 1264 for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){ 1265 if( p->funcFlags & SQLITE_FUNC_INTERNAL ) continue; 1266 sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 1); 1267 } 1268 } 1269 for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){ 1270 p = (FuncDef*)sqliteHashData(j); 1271 sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 0); 1272 } 1273 } 1274 break; 1275 1276 #ifndef SQLITE_OMIT_VIRTUALTABLE 1277 case PragTyp_MODULE_LIST: { 1278 HashElem *j; 1279 pParse->nMem = 1; 1280 for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){ 1281 Module *pMod = (Module*)sqliteHashData(j); 1282 sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName); 1283 } 1284 } 1285 break; 1286 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 1287 1288 case PragTyp_PRAGMA_LIST: { 1289 int i; 1290 for(i=0; i<ArraySize(aPragmaName); i++){ 1291 sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName); 1292 } 1293 } 1294 break; 1295 #endif /* SQLITE_INTROSPECTION_PRAGMAS */ 1296 1297 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */ 1298 1299 #ifndef SQLITE_OMIT_FOREIGN_KEY 1300 case PragTyp_FOREIGN_KEY_LIST: if( zRight ){ 1301 FKey *pFK; 1302 Table *pTab; 1303 pTab = sqlite3FindTable(db, zRight, zDb); 1304 if( pTab ){ 1305 pFK = pTab->pFKey; 1306 if( pFK ){ 1307 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); 1308 int i = 0; 1309 pParse->nMem = 8; 1310 sqlite3CodeVerifySchema(pParse, iTabDb); 1311 while(pFK){ 1312 int j; 1313 for(j=0; j<pFK->nCol; j++){ 1314 sqlite3VdbeMultiLoad(v, 1, "iissssss", 1315 i, 1316 j, 1317 pFK->zTo, 1318 pTab->aCol[pFK->aCol[j].iFrom].zName, 1319 pFK->aCol[j].zCol, 1320 actionName(pFK->aAction[1]), /* ON UPDATE */ 1321 actionName(pFK->aAction[0]), /* ON DELETE */ 1322 "NONE"); 1323 } 1324 ++i; 1325 pFK = pFK->pNextFrom; 1326 } 1327 } 1328 } 1329 } 1330 break; 1331 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ 1332 1333 #ifndef SQLITE_OMIT_FOREIGN_KEY 1334 #ifndef SQLITE_OMIT_TRIGGER 1335 case PragTyp_FOREIGN_KEY_CHECK: { 1336 FKey *pFK; /* A foreign key constraint */ 1337 Table *pTab; /* Child table contain "REFERENCES" keyword */ 1338 Table *pParent; /* Parent table that child points to */ 1339 Index *pIdx; /* Index in the parent table */ 1340 int i; /* Loop counter: Foreign key number for pTab */ 1341 int j; /* Loop counter: Field of the foreign key */ 1342 HashElem *k; /* Loop counter: Next table in schema */ 1343 int x; /* result variable */ 1344 int regResult; /* 3 registers to hold a result row */ 1345 int regKey; /* Register to hold key for checking the FK */ 1346 int regRow; /* Registers to hold a row from pTab */ 1347 int addrTop; /* Top of a loop checking foreign keys */ 1348 int addrOk; /* Jump here if the key is OK */ 1349 int *aiCols; /* child to parent column mapping */ 1350 1351 regResult = pParse->nMem+1; 1352 pParse->nMem += 4; 1353 regKey = ++pParse->nMem; 1354 regRow = ++pParse->nMem; 1355 k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash); 1356 while( k ){ 1357 int iTabDb; 1358 if( zRight ){ 1359 pTab = sqlite3LocateTable(pParse, 0, zRight, zDb); 1360 k = 0; 1361 }else{ 1362 pTab = (Table*)sqliteHashData(k); 1363 k = sqliteHashNext(k); 1364 } 1365 if( pTab==0 || pTab->pFKey==0 ) continue; 1366 iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); 1367 sqlite3CodeVerifySchema(pParse, iTabDb); 1368 sqlite3TableLock(pParse, iTabDb, pTab->tnum, 0, pTab->zName); 1369 if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow; 1370 sqlite3OpenTable(pParse, 0, iTabDb, pTab, OP_OpenRead); 1371 sqlite3VdbeLoadString(v, regResult, pTab->zName); 1372 for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ 1373 pParent = sqlite3FindTable(db, pFK->zTo, zDb); 1374 if( pParent==0 ) continue; 1375 pIdx = 0; 1376 sqlite3TableLock(pParse, iTabDb, pParent->tnum, 0, pParent->zName); 1377 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0); 1378 if( x==0 ){ 1379 if( pIdx==0 ){ 1380 sqlite3OpenTable(pParse, i, iTabDb, pParent, OP_OpenRead); 1381 }else{ 1382 sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iTabDb); 1383 sqlite3VdbeSetP4KeyInfo(pParse, pIdx); 1384 } 1385 }else{ 1386 k = 0; 1387 break; 1388 } 1389 } 1390 assert( pParse->nErr>0 || pFK==0 ); 1391 if( pFK ) break; 1392 if( pParse->nTab<i ) pParse->nTab = i; 1393 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v); 1394 for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ 1395 pParent = sqlite3FindTable(db, pFK->zTo, zDb); 1396 pIdx = 0; 1397 aiCols = 0; 1398 if( pParent ){ 1399 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols); 1400 assert( x==0 ); 1401 } 1402 addrOk = sqlite3VdbeMakeLabel(pParse); 1403 1404 /* Generate code to read the child key values into registers 1405 ** regRow..regRow+n. If any of the child key values are NULL, this 1406 ** row cannot cause an FK violation. Jump directly to addrOk in 1407 ** this case. */ 1408 for(j=0; j<pFK->nCol; j++){ 1409 int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom; 1410 sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j); 1411 sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v); 1412 } 1413 1414 /* Generate code to query the parent index for a matching parent 1415 ** key. If a match is found, jump to addrOk. */ 1416 if( pIdx ){ 1417 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey, 1418 sqlite3IndexAffinityStr(db,pIdx), pFK->nCol); 1419 sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0); 1420 VdbeCoverage(v); 1421 }else if( pParent ){ 1422 int jmp = sqlite3VdbeCurrentAddr(v)+2; 1423 sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v); 1424 sqlite3VdbeGoto(v, addrOk); 1425 assert( pFK->nCol==1 ); 1426 } 1427 1428 /* Generate code to report an FK violation to the caller. */ 1429 if( HasRowid(pTab) ){ 1430 sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1); 1431 }else{ 1432 sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1); 1433 } 1434 sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1); 1435 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4); 1436 sqlite3VdbeResolveLabel(v, addrOk); 1437 sqlite3DbFree(db, aiCols); 1438 } 1439 sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v); 1440 sqlite3VdbeJumpHere(v, addrTop); 1441 } 1442 } 1443 break; 1444 #endif /* !defined(SQLITE_OMIT_TRIGGER) */ 1445 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ 1446 1447 #ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA 1448 /* Reinstall the LIKE and GLOB functions. The variant of LIKE 1449 ** used will be case sensitive or not depending on the RHS. 1450 */ 1451 case PragTyp_CASE_SENSITIVE_LIKE: { 1452 if( zRight ){ 1453 sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0)); 1454 } 1455 } 1456 break; 1457 #endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */ 1458 1459 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX 1460 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100 1461 #endif 1462 1463 #ifndef SQLITE_OMIT_INTEGRITY_CHECK 1464 /* PRAGMA integrity_check 1465 ** PRAGMA integrity_check(N) 1466 ** PRAGMA quick_check 1467 ** PRAGMA quick_check(N) 1468 ** 1469 ** Verify the integrity of the database. 1470 ** 1471 ** The "quick_check" is reduced version of 1472 ** integrity_check designed to detect most database corruption 1473 ** without the overhead of cross-checking indexes. Quick_check 1474 ** is linear time wherease integrity_check is O(NlogN). 1475 */ 1476 case PragTyp_INTEGRITY_CHECK: { 1477 int i, j, addr, mxErr; 1478 1479 int isQuick = (sqlite3Tolower(zLeft[0])=='q'); 1480 1481 /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check", 1482 ** then iDb is set to the index of the database identified by <db>. 1483 ** In this case, the integrity of database iDb only is verified by 1484 ** the VDBE created below. 1485 ** 1486 ** Otherwise, if the command was simply "PRAGMA integrity_check" (or 1487 ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb 1488 ** to -1 here, to indicate that the VDBE should verify the integrity 1489 ** of all attached databases. */ 1490 assert( iDb>=0 ); 1491 assert( iDb==0 || pId2->z ); 1492 if( pId2->z==0 ) iDb = -1; 1493 1494 /* Initialize the VDBE program */ 1495 pParse->nMem = 6; 1496 1497 /* Set the maximum error count */ 1498 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; 1499 if( zRight ){ 1500 sqlite3GetInt32(zRight, &mxErr); 1501 if( mxErr<=0 ){ 1502 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; 1503 } 1504 } 1505 sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */ 1506 1507 /* Do an integrity check on each database file */ 1508 for(i=0; i<db->nDb; i++){ 1509 HashElem *x; /* For looping over tables in the schema */ 1510 Hash *pTbls; /* Set of all tables in the schema */ 1511 int *aRoot; /* Array of root page numbers of all btrees */ 1512 int cnt = 0; /* Number of entries in aRoot[] */ 1513 int mxIdx = 0; /* Maximum number of indexes for any table */ 1514 1515 if( OMIT_TEMPDB && i==1 ) continue; 1516 if( iDb>=0 && i!=iDb ) continue; 1517 1518 sqlite3CodeVerifySchema(pParse, i); 1519 1520 /* Do an integrity check of the B-Tree 1521 ** 1522 ** Begin by finding the root pages numbers 1523 ** for all tables and indices in the database. 1524 */ 1525 assert( sqlite3SchemaMutexHeld(db, i, 0) ); 1526 pTbls = &db->aDb[i].pSchema->tblHash; 1527 for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ 1528 Table *pTab = sqliteHashData(x); /* Current table */ 1529 Index *pIdx; /* An index on pTab */ 1530 int nIdx; /* Number of indexes on pTab */ 1531 if( HasRowid(pTab) ) cnt++; 1532 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; } 1533 if( nIdx>mxIdx ) mxIdx = nIdx; 1534 } 1535 aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1)); 1536 if( aRoot==0 ) break; 1537 for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ 1538 Table *pTab = sqliteHashData(x); 1539 Index *pIdx; 1540 if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum; 1541 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 1542 aRoot[++cnt] = pIdx->tnum; 1543 } 1544 } 1545 aRoot[0] = cnt; 1546 1547 /* Make sure sufficient number of registers have been allocated */ 1548 pParse->nMem = MAX( pParse->nMem, 8+mxIdx ); 1549 sqlite3ClearTempRegCache(pParse); 1550 1551 /* Do the b-tree integrity checks */ 1552 sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY); 1553 sqlite3VdbeChangeP5(v, (u8)i); 1554 addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v); 1555 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, 1556 sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName), 1557 P4_DYNAMIC); 1558 sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3); 1559 integrityCheckResultRow(v); 1560 sqlite3VdbeJumpHere(v, addr); 1561 1562 /* Make sure all the indices are constructed correctly. 1563 */ 1564 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ 1565 Table *pTab = sqliteHashData(x); 1566 Index *pIdx, *pPk; 1567 Index *pPrior = 0; 1568 int loopTop; 1569 int iDataCur, iIdxCur; 1570 int r1 = -1; 1571 1572 if( pTab->tnum<1 ) continue; /* Skip VIEWs or VIRTUAL TABLEs */ 1573 pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); 1574 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0, 1575 1, 0, &iDataCur, &iIdxCur); 1576 /* reg[7] counts the number of entries in the table. 1577 ** reg[8+i] counts the number of entries in the i-th index 1578 */ 1579 sqlite3VdbeAddOp2(v, OP_Integer, 0, 7); 1580 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ 1581 sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */ 1582 } 1583 assert( pParse->nMem>=8+j ); 1584 assert( sqlite3NoTempsInRange(pParse,1,7+j) ); 1585 sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v); 1586 loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1); 1587 if( !isQuick ){ 1588 /* Sanity check on record header decoding */ 1589 sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nNVCol-1,3); 1590 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); 1591 } 1592 /* Verify that all NOT NULL columns really are NOT NULL */ 1593 for(j=0; j<pTab->nCol; j++){ 1594 char *zErr; 1595 int jmp2; 1596 if( j==pTab->iPKey ) continue; 1597 if( pTab->aCol[j].notNull==0 ) continue; 1598 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3); 1599 if( sqlite3VdbeGetOp(v,-1)->opcode==OP_Column ){ 1600 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); 1601 } 1602 jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v); 1603 zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName, 1604 pTab->aCol[j].zName); 1605 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC); 1606 integrityCheckResultRow(v); 1607 sqlite3VdbeJumpHere(v, jmp2); 1608 } 1609 /* Verify CHECK constraints */ 1610 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ 1611 ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0); 1612 if( db->mallocFailed==0 ){ 1613 int addrCkFault = sqlite3VdbeMakeLabel(pParse); 1614 int addrCkOk = sqlite3VdbeMakeLabel(pParse); 1615 char *zErr; 1616 int k; 1617 pParse->iSelfTab = iDataCur + 1; 1618 for(k=pCheck->nExpr-1; k>0; k--){ 1619 sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0); 1620 } 1621 sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk, 1622 SQLITE_JUMPIFNULL); 1623 sqlite3VdbeResolveLabel(v, addrCkFault); 1624 pParse->iSelfTab = 0; 1625 zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s", 1626 pTab->zName); 1627 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC); 1628 integrityCheckResultRow(v); 1629 sqlite3VdbeResolveLabel(v, addrCkOk); 1630 } 1631 sqlite3ExprListDelete(db, pCheck); 1632 } 1633 if( !isQuick ){ /* Omit the remaining tests for quick_check */ 1634 /* Validate index entries for the current row */ 1635 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ 1636 int jmp2, jmp3, jmp4, jmp5; 1637 int ckUniq = sqlite3VdbeMakeLabel(pParse); 1638 if( pPk==pIdx ) continue; 1639 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3, 1640 pPrior, r1); 1641 pPrior = pIdx; 1642 sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */ 1643 /* Verify that an index entry exists for the current table row */ 1644 jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1, 1645 pIdx->nColumn); VdbeCoverage(v); 1646 sqlite3VdbeLoadString(v, 3, "row "); 1647 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3); 1648 sqlite3VdbeLoadString(v, 4, " missing from index "); 1649 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); 1650 jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName); 1651 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); 1652 jmp4 = integrityCheckResultRow(v); 1653 sqlite3VdbeJumpHere(v, jmp2); 1654 /* For UNIQUE indexes, verify that only one entry exists with the 1655 ** current key. The entry is unique if (1) any column is NULL 1656 ** or (2) the next entry has a different key */ 1657 if( IsUniqueIndex(pIdx) ){ 1658 int uniqOk = sqlite3VdbeMakeLabel(pParse); 1659 int jmp6; 1660 int kk; 1661 for(kk=0; kk<pIdx->nKeyCol; kk++){ 1662 int iCol = pIdx->aiColumn[kk]; 1663 assert( iCol!=XN_ROWID && iCol<pTab->nCol ); 1664 if( iCol>=0 && pTab->aCol[iCol].notNull ) continue; 1665 sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk); 1666 VdbeCoverage(v); 1667 } 1668 jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v); 1669 sqlite3VdbeGoto(v, uniqOk); 1670 sqlite3VdbeJumpHere(v, jmp6); 1671 sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1, 1672 pIdx->nKeyCol); VdbeCoverage(v); 1673 sqlite3VdbeLoadString(v, 3, "non-unique entry in index "); 1674 sqlite3VdbeGoto(v, jmp5); 1675 sqlite3VdbeResolveLabel(v, uniqOk); 1676 } 1677 sqlite3VdbeJumpHere(v, jmp4); 1678 sqlite3ResolvePartIdxLabel(pParse, jmp3); 1679 } 1680 } 1681 sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v); 1682 sqlite3VdbeJumpHere(v, loopTop-1); 1683 #ifndef SQLITE_OMIT_BTREECOUNT 1684 if( !isQuick ){ 1685 sqlite3VdbeLoadString(v, 2, "wrong # of entries in index "); 1686 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ 1687 if( pPk==pIdx ) continue; 1688 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3); 1689 addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v); 1690 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1691 sqlite3VdbeLoadString(v, 4, pIdx->zName); 1692 sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3); 1693 integrityCheckResultRow(v); 1694 sqlite3VdbeJumpHere(v, addr); 1695 } 1696 } 1697 #endif /* SQLITE_OMIT_BTREECOUNT */ 1698 } 1699 } 1700 { 1701 static const int iLn = VDBE_OFFSET_LINENO(2); 1702 static const VdbeOpList endCode[] = { 1703 { OP_AddImm, 1, 0, 0}, /* 0 */ 1704 { OP_IfNotZero, 1, 4, 0}, /* 1 */ 1705 { OP_String8, 0, 3, 0}, /* 2 */ 1706 { OP_ResultRow, 3, 1, 0}, /* 3 */ 1707 { OP_Halt, 0, 0, 0}, /* 4 */ 1708 { OP_String8, 0, 3, 0}, /* 5 */ 1709 { OP_Goto, 0, 3, 0}, /* 6 */ 1710 }; 1711 VdbeOp *aOp; 1712 1713 aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn); 1714 if( aOp ){ 1715 aOp[0].p2 = 1-mxErr; 1716 aOp[2].p4type = P4_STATIC; 1717 aOp[2].p4.z = "ok"; 1718 aOp[5].p4type = P4_STATIC; 1719 aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT); 1720 } 1721 sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2); 1722 } 1723 } 1724 break; 1725 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ 1726 1727 #ifndef SQLITE_OMIT_UTF16 1728 /* 1729 ** PRAGMA encoding 1730 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be" 1731 ** 1732 ** In its first form, this pragma returns the encoding of the main 1733 ** database. If the database is not initialized, it is initialized now. 1734 ** 1735 ** The second form of this pragma is a no-op if the main database file 1736 ** has not already been initialized. In this case it sets the default 1737 ** encoding that will be used for the main database file if a new file 1738 ** is created. If an existing main database file is opened, then the 1739 ** default text encoding for the existing database is used. 1740 ** 1741 ** In all cases new databases created using the ATTACH command are 1742 ** created to use the same default text encoding as the main database. If 1743 ** the main database has not been initialized and/or created when ATTACH 1744 ** is executed, this is done before the ATTACH operation. 1745 ** 1746 ** In the second form this pragma sets the text encoding to be used in 1747 ** new database files created using this database handle. It is only 1748 ** useful if invoked immediately after the main database i 1749 */ 1750 case PragTyp_ENCODING: { 1751 static const struct EncName { 1752 char *zName; 1753 u8 enc; 1754 } encnames[] = { 1755 { "UTF8", SQLITE_UTF8 }, 1756 { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */ 1757 { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */ 1758 { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */ 1759 { "UTF16le", SQLITE_UTF16LE }, 1760 { "UTF16be", SQLITE_UTF16BE }, 1761 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */ 1762 { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */ 1763 { 0, 0 } 1764 }; 1765 const struct EncName *pEnc; 1766 if( !zRight ){ /* "PRAGMA encoding" */ 1767 if( sqlite3ReadSchema(pParse) ) goto pragma_out; 1768 assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 ); 1769 assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE ); 1770 assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE ); 1771 returnSingleText(v, encnames[ENC(pParse->db)].zName); 1772 }else{ /* "PRAGMA encoding = XXX" */ 1773 /* Only change the value of sqlite.enc if the database handle is not 1774 ** initialized. If the main database exists, the new sqlite.enc value 1775 ** will be overwritten when the schema is next loaded. If it does not 1776 ** already exists, it will be created to use the new encoding value. 1777 */ 1778 if( 1779 !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 1780 DbHasProperty(db, 0, DB_Empty) 1781 ){ 1782 for(pEnc=&encnames[0]; pEnc->zName; pEnc++){ 1783 if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){ 1784 SCHEMA_ENC(db) = ENC(db) = 1785 pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE; 1786 break; 1787 } 1788 } 1789 if( !pEnc->zName ){ 1790 sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight); 1791 } 1792 } 1793 } 1794 } 1795 break; 1796 #endif /* SQLITE_OMIT_UTF16 */ 1797 1798 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS 1799 /* 1800 ** PRAGMA [schema.]schema_version 1801 ** PRAGMA [schema.]schema_version = <integer> 1802 ** 1803 ** PRAGMA [schema.]user_version 1804 ** PRAGMA [schema.]user_version = <integer> 1805 ** 1806 ** PRAGMA [schema.]freelist_count 1807 ** 1808 ** PRAGMA [schema.]data_version 1809 ** 1810 ** PRAGMA [schema.]application_id 1811 ** PRAGMA [schema.]application_id = <integer> 1812 ** 1813 ** The pragma's schema_version and user_version are used to set or get 1814 ** the value of the schema-version and user-version, respectively. Both 1815 ** the schema-version and the user-version are 32-bit signed integers 1816 ** stored in the database header. 1817 ** 1818 ** The schema-cookie is usually only manipulated internally by SQLite. It 1819 ** is incremented by SQLite whenever the database schema is modified (by 1820 ** creating or dropping a table or index). The schema version is used by 1821 ** SQLite each time a query is executed to ensure that the internal cache 1822 ** of the schema used when compiling the SQL query matches the schema of 1823 ** the database against which the compiled query is actually executed. 1824 ** Subverting this mechanism by using "PRAGMA schema_version" to modify 1825 ** the schema-version is potentially dangerous and may lead to program 1826 ** crashes or database corruption. Use with caution! 1827 ** 1828 ** The user-version is not used internally by SQLite. It may be used by 1829 ** applications for any purpose. 1830 */ 1831 case PragTyp_HEADER_VALUE: { 1832 int iCookie = pPragma->iArg; /* Which cookie to read or write */ 1833 sqlite3VdbeUsesBtree(v, iDb); 1834 if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){ 1835 /* Write the specified cookie value */ 1836 static const VdbeOpList setCookie[] = { 1837 { OP_Transaction, 0, 1, 0}, /* 0 */ 1838 { OP_SetCookie, 0, 0, 0}, /* 1 */ 1839 }; 1840 VdbeOp *aOp; 1841 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie)); 1842 aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0); 1843 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; 1844 aOp[0].p1 = iDb; 1845 aOp[1].p1 = iDb; 1846 aOp[1].p2 = iCookie; 1847 aOp[1].p3 = sqlite3Atoi(zRight); 1848 }else{ 1849 /* Read the specified cookie value */ 1850 static const VdbeOpList readCookie[] = { 1851 { OP_Transaction, 0, 0, 0}, /* 0 */ 1852 { OP_ReadCookie, 0, 1, 0}, /* 1 */ 1853 { OP_ResultRow, 1, 1, 0} 1854 }; 1855 VdbeOp *aOp; 1856 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie)); 1857 aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0); 1858 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; 1859 aOp[0].p1 = iDb; 1860 aOp[1].p1 = iDb; 1861 aOp[1].p3 = iCookie; 1862 sqlite3VdbeReusable(v); 1863 } 1864 } 1865 break; 1866 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */ 1867 1868 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS 1869 /* 1870 ** PRAGMA compile_options 1871 ** 1872 ** Return the names of all compile-time options used in this build, 1873 ** one option per row. 1874 */ 1875 case PragTyp_COMPILE_OPTIONS: { 1876 int i = 0; 1877 const char *zOpt; 1878 pParse->nMem = 1; 1879 while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){ 1880 sqlite3VdbeLoadString(v, 1, zOpt); 1881 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); 1882 } 1883 sqlite3VdbeReusable(v); 1884 } 1885 break; 1886 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ 1887 1888 #ifndef SQLITE_OMIT_WAL 1889 /* 1890 ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate 1891 ** 1892 ** Checkpoint the database. 1893 */ 1894 case PragTyp_WAL_CHECKPOINT: { 1895 int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED); 1896 int eMode = SQLITE_CHECKPOINT_PASSIVE; 1897 if( zRight ){ 1898 if( sqlite3StrICmp(zRight, "full")==0 ){ 1899 eMode = SQLITE_CHECKPOINT_FULL; 1900 }else if( sqlite3StrICmp(zRight, "restart")==0 ){ 1901 eMode = SQLITE_CHECKPOINT_RESTART; 1902 }else if( sqlite3StrICmp(zRight, "truncate")==0 ){ 1903 eMode = SQLITE_CHECKPOINT_TRUNCATE; 1904 } 1905 } 1906 pParse->nMem = 3; 1907 sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1); 1908 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); 1909 } 1910 break; 1911 1912 /* 1913 ** PRAGMA wal_autocheckpoint 1914 ** PRAGMA wal_autocheckpoint = N 1915 ** 1916 ** Configure a database connection to automatically checkpoint a database 1917 ** after accumulating N frames in the log. Or query for the current value 1918 ** of N. 1919 */ 1920 case PragTyp_WAL_AUTOCHECKPOINT: { 1921 if( zRight ){ 1922 sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight)); 1923 } 1924 returnSingleInt(v, 1925 db->xWalCallback==sqlite3WalDefaultHook ? 1926 SQLITE_PTR_TO_INT(db->pWalArg) : 0); 1927 } 1928 break; 1929 #endif 1930 1931 /* 1932 ** PRAGMA shrink_memory 1933 ** 1934 ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database 1935 ** connection on which it is invoked to free up as much memory as it 1936 ** can, by calling sqlite3_db_release_memory(). 1937 */ 1938 case PragTyp_SHRINK_MEMORY: { 1939 sqlite3_db_release_memory(db); 1940 break; 1941 } 1942 1943 /* 1944 ** PRAGMA optimize 1945 ** PRAGMA optimize(MASK) 1946 ** PRAGMA schema.optimize 1947 ** PRAGMA schema.optimize(MASK) 1948 ** 1949 ** Attempt to optimize the database. All schemas are optimized in the first 1950 ** two forms, and only the specified schema is optimized in the latter two. 1951 ** 1952 ** The details of optimizations performed by this pragma are expected 1953 ** to change and improve over time. Applications should anticipate that 1954 ** this pragma will perform new optimizations in future releases. 1955 ** 1956 ** The optional argument is a bitmask of optimizations to perform: 1957 ** 1958 ** 0x0001 Debugging mode. Do not actually perform any optimizations 1959 ** but instead return one line of text for each optimization 1960 ** that would have been done. Off by default. 1961 ** 1962 ** 0x0002 Run ANALYZE on tables that might benefit. On by default. 1963 ** See below for additional information. 1964 ** 1965 ** 0x0004 (Not yet implemented) Record usage and performance 1966 ** information from the current session in the 1967 ** database file so that it will be available to "optimize" 1968 ** pragmas run by future database connections. 1969 ** 1970 ** 0x0008 (Not yet implemented) Create indexes that might have 1971 ** been helpful to recent queries 1972 ** 1973 ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all 1974 ** of the optimizations listed above except Debug Mode, including new 1975 ** optimizations that have not yet been invented. If new optimizations are 1976 ** ever added that should be off by default, those off-by-default 1977 ** optimizations will have bitmasks of 0x10000 or larger. 1978 ** 1979 ** DETERMINATION OF WHEN TO RUN ANALYZE 1980 ** 1981 ** In the current implementation, a table is analyzed if only if all of 1982 ** the following are true: 1983 ** 1984 ** (1) MASK bit 0x02 is set. 1985 ** 1986 ** (2) The query planner used sqlite_stat1-style statistics for one or 1987 ** more indexes of the table at some point during the lifetime of 1988 ** the current connection. 1989 ** 1990 ** (3) One or more indexes of the table are currently unanalyzed OR 1991 ** the number of rows in the table has increased by 25 times or more 1992 ** since the last time ANALYZE was run. 1993 ** 1994 ** The rules for when tables are analyzed are likely to change in 1995 ** future releases. 1996 */ 1997 case PragTyp_OPTIMIZE: { 1998 int iDbLast; /* Loop termination point for the schema loop */ 1999 int iTabCur; /* Cursor for a table whose size needs checking */ 2000 HashElem *k; /* Loop over tables of a schema */ 2001 Schema *pSchema; /* The current schema */ 2002 Table *pTab; /* A table in the schema */ 2003 Index *pIdx; /* An index of the table */ 2004 LogEst szThreshold; /* Size threshold above which reanalysis is needd */ 2005 char *zSubSql; /* SQL statement for the OP_SqlExec opcode */ 2006 u32 opMask; /* Mask of operations to perform */ 2007 2008 if( zRight ){ 2009 opMask = (u32)sqlite3Atoi(zRight); 2010 if( (opMask & 0x02)==0 ) break; 2011 }else{ 2012 opMask = 0xfffe; 2013 } 2014 iTabCur = pParse->nTab++; 2015 for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){ 2016 if( iDb==1 ) continue; 2017 sqlite3CodeVerifySchema(pParse, iDb); 2018 pSchema = db->aDb[iDb].pSchema; 2019 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){ 2020 pTab = (Table*)sqliteHashData(k); 2021 2022 /* If table pTab has not been used in a way that would benefit from 2023 ** having analysis statistics during the current session, then skip it. 2024 ** This also has the effect of skipping virtual tables and views */ 2025 if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue; 2026 2027 /* Reanalyze if the table is 25 times larger than the last analysis */ 2028 szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 ); 2029 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 2030 if( !pIdx->hasStat1 ){ 2031 szThreshold = 0; /* Always analyze if any index lacks statistics */ 2032 break; 2033 } 2034 } 2035 if( szThreshold ){ 2036 sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead); 2037 sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur, 2038 sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold); 2039 VdbeCoverage(v); 2040 } 2041 zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"", 2042 db->aDb[iDb].zDbSName, pTab->zName); 2043 if( opMask & 0x01 ){ 2044 int r1 = sqlite3GetTempReg(pParse); 2045 sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC); 2046 sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1); 2047 }else{ 2048 sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC); 2049 } 2050 } 2051 } 2052 sqlite3VdbeAddOp0(v, OP_Expire); 2053 break; 2054 } 2055 2056 /* 2057 ** PRAGMA busy_timeout 2058 ** PRAGMA busy_timeout = N 2059 ** 2060 ** Call sqlite3_busy_timeout(db, N). Return the current timeout value 2061 ** if one is set. If no busy handler or a different busy handler is set 2062 ** then 0 is returned. Setting the busy_timeout to 0 or negative 2063 ** disables the timeout. 2064 */ 2065 /*case PragTyp_BUSY_TIMEOUT*/ default: { 2066 assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT ); 2067 if( zRight ){ 2068 sqlite3_busy_timeout(db, sqlite3Atoi(zRight)); 2069 } 2070 returnSingleInt(v, db->busyTimeout); 2071 break; 2072 } 2073 2074 /* 2075 ** PRAGMA soft_heap_limit 2076 ** PRAGMA soft_heap_limit = N 2077 ** 2078 ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the 2079 ** sqlite3_soft_heap_limit64() interface with the argument N, if N is 2080 ** specified and is a non-negative integer. 2081 ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always 2082 ** returns the same integer that would be returned by the 2083 ** sqlite3_soft_heap_limit64(-1) C-language function. 2084 */ 2085 case PragTyp_SOFT_HEAP_LIMIT: { 2086 sqlite3_int64 N; 2087 if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){ 2088 sqlite3_soft_heap_limit64(N); 2089 } 2090 returnSingleInt(v, sqlite3_soft_heap_limit64(-1)); 2091 break; 2092 } 2093 2094 /* 2095 ** PRAGMA hard_heap_limit 2096 ** PRAGMA hard_heap_limit = N 2097 ** 2098 ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap 2099 ** limit. The hard heap limit can be activated or lowered by this 2100 ** pragma, but not raised or deactivated. Only the 2101 ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate 2102 ** the hard heap limit. This allows an application to set a heap limit 2103 ** constraint that cannot be relaxed by an untrusted SQL script. 2104 */ 2105 case PragTyp_HARD_HEAP_LIMIT: { 2106 sqlite3_int64 N; 2107 if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){ 2108 sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1); 2109 if( N>0 && (iPrior==0 || iPrior>N) ) sqlite3_hard_heap_limit64(N); 2110 } 2111 returnSingleInt(v, sqlite3_hard_heap_limit64(-1)); 2112 break; 2113 } 2114 2115 /* 2116 ** PRAGMA threads 2117 ** PRAGMA threads = N 2118 ** 2119 ** Configure the maximum number of worker threads. Return the new 2120 ** maximum, which might be less than requested. 2121 */ 2122 case PragTyp_THREADS: { 2123 sqlite3_int64 N; 2124 if( zRight 2125 && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK 2126 && N>=0 2127 ){ 2128 sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff)); 2129 } 2130 returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1)); 2131 break; 2132 } 2133 2134 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) 2135 /* 2136 ** Report the current state of file logs for all databases 2137 */ 2138 case PragTyp_LOCK_STATUS: { 2139 static const char *const azLockName[] = { 2140 "unlocked", "shared", "reserved", "pending", "exclusive" 2141 }; 2142 int i; 2143 pParse->nMem = 2; 2144 for(i=0; i<db->nDb; i++){ 2145 Btree *pBt; 2146 const char *zState = "unknown"; 2147 int j; 2148 if( db->aDb[i].zDbSName==0 ) continue; 2149 pBt = db->aDb[i].pBt; 2150 if( pBt==0 || sqlite3BtreePager(pBt)==0 ){ 2151 zState = "closed"; 2152 }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0, 2153 SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){ 2154 zState = azLockName[j]; 2155 } 2156 sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState); 2157 } 2158 break; 2159 } 2160 #endif 2161 2162 #ifdef SQLITE_HAS_CODEC 2163 /* Pragma iArg 2164 ** ---------- ------ 2165 ** key 0 2166 ** rekey 1 2167 ** hexkey 2 2168 ** hexrekey 3 2169 ** textkey 4 2170 ** textrekey 5 2171 */ 2172 case PragTyp_KEY: { 2173 if( zRight ){ 2174 char zBuf[40]; 2175 const char *zKey = zRight; 2176 int n; 2177 if( pPragma->iArg==2 || pPragma->iArg==3 ){ 2178 u8 iByte; 2179 int i; 2180 for(i=0, iByte=0; i<sizeof(zBuf)*2 && sqlite3Isxdigit(zRight[i]); i++){ 2181 iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]); 2182 if( (i&1)!=0 ) zBuf[i/2] = iByte; 2183 } 2184 zKey = zBuf; 2185 n = i/2; 2186 }else{ 2187 n = pPragma->iArg<4 ? sqlite3Strlen30(zRight) : -1; 2188 } 2189 if( (pPragma->iArg & 1)==0 ){ 2190 rc = sqlite3_key_v2(db, zDb, zKey, n); 2191 }else{ 2192 rc = sqlite3_rekey_v2(db, zDb, zKey, n); 2193 } 2194 if( rc==SQLITE_OK && n!=0 ){ 2195 sqlite3VdbeSetNumCols(v, 1); 2196 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "ok", SQLITE_STATIC); 2197 returnSingleText(v, "ok"); 2198 } 2199 } 2200 break; 2201 } 2202 #endif 2203 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD) 2204 case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){ 2205 #ifdef SQLITE_HAS_CODEC 2206 if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){ 2207 sqlite3_activate_see(&zRight[4]); 2208 } 2209 #endif 2210 #ifdef SQLITE_ENABLE_CEROD 2211 if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){ 2212 sqlite3_activate_cerod(&zRight[6]); 2213 } 2214 #endif 2215 } 2216 break; 2217 #endif 2218 2219 } /* End of the PRAGMA switch */ 2220 2221 /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only 2222 ** purpose is to execute assert() statements to verify that if the 2223 ** PragFlg_NoColumns1 flag is set and the caller specified an argument 2224 ** to the PRAGMA, the implementation has not added any OP_ResultRow 2225 ** instructions to the VM. */ 2226 if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){ 2227 sqlite3VdbeVerifyNoResultRow(v); 2228 } 2229 2230 pragma_out: 2231 sqlite3DbFree(db, zLeft); 2232 sqlite3DbFree(db, zRight); 2233 } 2234 #ifndef SQLITE_OMIT_VIRTUALTABLE 2235 /***************************************************************************** 2236 ** Implementation of an eponymous virtual table that runs a pragma. 2237 ** 2238 */ 2239 typedef struct PragmaVtab PragmaVtab; 2240 typedef struct PragmaVtabCursor PragmaVtabCursor; 2241 struct PragmaVtab { 2242 sqlite3_vtab base; /* Base class. Must be first */ 2243 sqlite3 *db; /* The database connection to which it belongs */ 2244 const PragmaName *pName; /* Name of the pragma */ 2245 u8 nHidden; /* Number of hidden columns */ 2246 u8 iHidden; /* Index of the first hidden column */ 2247 }; 2248 struct PragmaVtabCursor { 2249 sqlite3_vtab_cursor base; /* Base class. Must be first */ 2250 sqlite3_stmt *pPragma; /* The pragma statement to run */ 2251 sqlite_int64 iRowid; /* Current rowid */ 2252 char *azArg[2]; /* Value of the argument and schema */ 2253 }; 2254 2255 /* 2256 ** Pragma virtual table module xConnect method. 2257 */ 2258 static int pragmaVtabConnect( 2259 sqlite3 *db, 2260 void *pAux, 2261 int argc, const char *const*argv, 2262 sqlite3_vtab **ppVtab, 2263 char **pzErr 2264 ){ 2265 const PragmaName *pPragma = (const PragmaName*)pAux; 2266 PragmaVtab *pTab = 0; 2267 int rc; 2268 int i, j; 2269 char cSep = '('; 2270 StrAccum acc; 2271 char zBuf[200]; 2272 2273 UNUSED_PARAMETER(argc); 2274 UNUSED_PARAMETER(argv); 2275 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); 2276 sqlite3_str_appendall(&acc, "CREATE TABLE x"); 2277 for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){ 2278 sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]); 2279 cSep = ','; 2280 } 2281 if( i==0 ){ 2282 sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName); 2283 i++; 2284 } 2285 j = 0; 2286 if( pPragma->mPragFlg & PragFlg_Result1 ){ 2287 sqlite3_str_appendall(&acc, ",arg HIDDEN"); 2288 j++; 2289 } 2290 if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){ 2291 sqlite3_str_appendall(&acc, ",schema HIDDEN"); 2292 j++; 2293 } 2294 sqlite3_str_append(&acc, ")", 1); 2295 sqlite3StrAccumFinish(&acc); 2296 assert( strlen(zBuf) < sizeof(zBuf)-1 ); 2297 rc = sqlite3_declare_vtab(db, zBuf); 2298 if( rc==SQLITE_OK ){ 2299 pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab)); 2300 if( pTab==0 ){ 2301 rc = SQLITE_NOMEM; 2302 }else{ 2303 memset(pTab, 0, sizeof(PragmaVtab)); 2304 pTab->pName = pPragma; 2305 pTab->db = db; 2306 pTab->iHidden = i; 2307 pTab->nHidden = j; 2308 } 2309 }else{ 2310 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); 2311 } 2312 2313 *ppVtab = (sqlite3_vtab*)pTab; 2314 return rc; 2315 } 2316 2317 /* 2318 ** Pragma virtual table module xDisconnect method. 2319 */ 2320 static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){ 2321 PragmaVtab *pTab = (PragmaVtab*)pVtab; 2322 sqlite3_free(pTab); 2323 return SQLITE_OK; 2324 } 2325 2326 /* Figure out the best index to use to search a pragma virtual table. 2327 ** 2328 ** There are not really any index choices. But we want to encourage the 2329 ** query planner to give == constraints on as many hidden parameters as 2330 ** possible, and especially on the first hidden parameter. So return a 2331 ** high cost if hidden parameters are unconstrained. 2332 */ 2333 static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ 2334 PragmaVtab *pTab = (PragmaVtab*)tab; 2335 const struct sqlite3_index_constraint *pConstraint; 2336 int i, j; 2337 int seen[2]; 2338 2339 pIdxInfo->estimatedCost = (double)1; 2340 if( pTab->nHidden==0 ){ return SQLITE_OK; } 2341 pConstraint = pIdxInfo->aConstraint; 2342 seen[0] = 0; 2343 seen[1] = 0; 2344 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ 2345 if( pConstraint->usable==0 ) continue; 2346 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; 2347 if( pConstraint->iColumn < pTab->iHidden ) continue; 2348 j = pConstraint->iColumn - pTab->iHidden; 2349 assert( j < 2 ); 2350 seen[j] = i+1; 2351 } 2352 if( seen[0]==0 ){ 2353 pIdxInfo->estimatedCost = (double)2147483647; 2354 pIdxInfo->estimatedRows = 2147483647; 2355 return SQLITE_OK; 2356 } 2357 j = seen[0]-1; 2358 pIdxInfo->aConstraintUsage[j].argvIndex = 1; 2359 pIdxInfo->aConstraintUsage[j].omit = 1; 2360 if( seen[1]==0 ) return SQLITE_OK; 2361 pIdxInfo->estimatedCost = (double)20; 2362 pIdxInfo->estimatedRows = 20; 2363 j = seen[1]-1; 2364 pIdxInfo->aConstraintUsage[j].argvIndex = 2; 2365 pIdxInfo->aConstraintUsage[j].omit = 1; 2366 return SQLITE_OK; 2367 } 2368 2369 /* Create a new cursor for the pragma virtual table */ 2370 static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){ 2371 PragmaVtabCursor *pCsr; 2372 pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr)); 2373 if( pCsr==0 ) return SQLITE_NOMEM; 2374 memset(pCsr, 0, sizeof(PragmaVtabCursor)); 2375 pCsr->base.pVtab = pVtab; 2376 *ppCursor = &pCsr->base; 2377 return SQLITE_OK; 2378 } 2379 2380 /* Clear all content from pragma virtual table cursor. */ 2381 static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){ 2382 int i; 2383 sqlite3_finalize(pCsr->pPragma); 2384 pCsr->pPragma = 0; 2385 for(i=0; i<ArraySize(pCsr->azArg); i++){ 2386 sqlite3_free(pCsr->azArg[i]); 2387 pCsr->azArg[i] = 0; 2388 } 2389 } 2390 2391 /* Close a pragma virtual table cursor */ 2392 static int pragmaVtabClose(sqlite3_vtab_cursor *cur){ 2393 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur; 2394 pragmaVtabCursorClear(pCsr); 2395 sqlite3_free(pCsr); 2396 return SQLITE_OK; 2397 } 2398 2399 /* Advance the pragma virtual table cursor to the next row */ 2400 static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){ 2401 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; 2402 int rc = SQLITE_OK; 2403 2404 /* Increment the xRowid value */ 2405 pCsr->iRowid++; 2406 assert( pCsr->pPragma ); 2407 if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){ 2408 rc = sqlite3_finalize(pCsr->pPragma); 2409 pCsr->pPragma = 0; 2410 pragmaVtabCursorClear(pCsr); 2411 } 2412 return rc; 2413 } 2414 2415 /* 2416 ** Pragma virtual table module xFilter method. 2417 */ 2418 static int pragmaVtabFilter( 2419 sqlite3_vtab_cursor *pVtabCursor, 2420 int idxNum, const char *idxStr, 2421 int argc, sqlite3_value **argv 2422 ){ 2423 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; 2424 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab); 2425 int rc; 2426 int i, j; 2427 StrAccum acc; 2428 char *zSql; 2429 2430 UNUSED_PARAMETER(idxNum); 2431 UNUSED_PARAMETER(idxStr); 2432 pragmaVtabCursorClear(pCsr); 2433 j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1; 2434 for(i=0; i<argc; i++, j++){ 2435 const char *zText = (const char*)sqlite3_value_text(argv[i]); 2436 assert( j<ArraySize(pCsr->azArg) ); 2437 assert( pCsr->azArg[j]==0 ); 2438 if( zText ){ 2439 pCsr->azArg[j] = sqlite3_mprintf("%s", zText); 2440 if( pCsr->azArg[j]==0 ){ 2441 return SQLITE_NOMEM; 2442 } 2443 } 2444 } 2445 sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]); 2446 sqlite3_str_appendall(&acc, "PRAGMA "); 2447 if( pCsr->azArg[1] ){ 2448 sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]); 2449 } 2450 sqlite3_str_appendall(&acc, pTab->pName->zName); 2451 if( pCsr->azArg[0] ){ 2452 sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]); 2453 } 2454 zSql = sqlite3StrAccumFinish(&acc); 2455 if( zSql==0 ) return SQLITE_NOMEM; 2456 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0); 2457 sqlite3_free(zSql); 2458 if( rc!=SQLITE_OK ){ 2459 pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db)); 2460 return rc; 2461 } 2462 return pragmaVtabNext(pVtabCursor); 2463 } 2464 2465 /* 2466 ** Pragma virtual table module xEof method. 2467 */ 2468 static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){ 2469 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; 2470 return (pCsr->pPragma==0); 2471 } 2472 2473 /* The xColumn method simply returns the corresponding column from 2474 ** the PRAGMA. 2475 */ 2476 static int pragmaVtabColumn( 2477 sqlite3_vtab_cursor *pVtabCursor, 2478 sqlite3_context *ctx, 2479 int i 2480 ){ 2481 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; 2482 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab); 2483 if( i<pTab->iHidden ){ 2484 sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i)); 2485 }else{ 2486 sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT); 2487 } 2488 return SQLITE_OK; 2489 } 2490 2491 /* 2492 ** Pragma virtual table module xRowid method. 2493 */ 2494 static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){ 2495 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; 2496 *p = pCsr->iRowid; 2497 return SQLITE_OK; 2498 } 2499 2500 /* The pragma virtual table object */ 2501 static const sqlite3_module pragmaVtabModule = { 2502 0, /* iVersion */ 2503 0, /* xCreate - create a table */ 2504 pragmaVtabConnect, /* xConnect - connect to an existing table */ 2505 pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */ 2506 pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */ 2507 0, /* xDestroy - Drop a table */ 2508 pragmaVtabOpen, /* xOpen - open a cursor */ 2509 pragmaVtabClose, /* xClose - close a cursor */ 2510 pragmaVtabFilter, /* xFilter - configure scan constraints */ 2511 pragmaVtabNext, /* xNext - advance a cursor */ 2512 pragmaVtabEof, /* xEof */ 2513 pragmaVtabColumn, /* xColumn - read data */ 2514 pragmaVtabRowid, /* xRowid - read data */ 2515 0, /* xUpdate - write data */ 2516 0, /* xBegin - begin transaction */ 2517 0, /* xSync - sync transaction */ 2518 0, /* xCommit - commit transaction */ 2519 0, /* xRollback - rollback transaction */ 2520 0, /* xFindFunction - function overloading */ 2521 0, /* xRename - rename the table */ 2522 0, /* xSavepoint */ 2523 0, /* xRelease */ 2524 0, /* xRollbackTo */ 2525 0 /* xShadowName */ 2526 }; 2527 2528 /* 2529 ** Check to see if zTabName is really the name of a pragma. If it is, 2530 ** then register an eponymous virtual table for that pragma and return 2531 ** a pointer to the Module object for the new virtual table. 2532 */ 2533 Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){ 2534 const PragmaName *pName; 2535 assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 ); 2536 pName = pragmaLocate(zName+7); 2537 if( pName==0 ) return 0; 2538 if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0; 2539 assert( sqlite3HashFind(&db->aModule, zName)==0 ); 2540 return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0); 2541 } 2542 2543 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 2544 2545 #endif /* SQLITE_OMIT_PRAGMA */ 2546