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