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