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