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