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