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