xref: /sqlite-3.40.0/src/pragma.c (revision 554cb87d)
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     if( !zRight ){
969       returnSingleText(v, sqlite3_temp_directory);
970     }else{
971 #ifndef SQLITE_OMIT_WSD
972       if( zRight[0] ){
973         int res;
974         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
975         if( rc!=SQLITE_OK || res==0 ){
976           sqlite3ErrorMsg(pParse, "not a writable directory");
977           goto pragma_out;
978         }
979       }
980       if( SQLITE_TEMP_STORE==0
981        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
982        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
983       ){
984         invalidateTempStorage(pParse);
985       }
986       sqlite3_free(sqlite3_temp_directory);
987       if( zRight[0] ){
988         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
989       }else{
990         sqlite3_temp_directory = 0;
991       }
992 #endif /* SQLITE_OMIT_WSD */
993     }
994     break;
995   }
996 
997 #if SQLITE_OS_WIN
998   /*
999   **   PRAGMA data_store_directory
1000   **   PRAGMA data_store_directory = ""|"directory_name"
1001   **
1002   ** Return or set the local value of the data_store_directory flag.  Changing
1003   ** the value sets a specific directory to be used for database files that
1004   ** were specified with a relative pathname.  Setting to a null string reverts
1005   ** to the default database directory, which for database files specified with
1006   ** a relative path will probably be based on the current directory for the
1007   ** process.  Database file specified with an absolute path are not impacted
1008   ** by this setting, regardless of its value.
1009   **
1010   */
1011   case PragTyp_DATA_STORE_DIRECTORY: {
1012     if( !zRight ){
1013       returnSingleText(v, sqlite3_data_directory);
1014     }else{
1015 #ifndef SQLITE_OMIT_WSD
1016       if( zRight[0] ){
1017         int res;
1018         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
1019         if( rc!=SQLITE_OK || res==0 ){
1020           sqlite3ErrorMsg(pParse, "not a writable directory");
1021           goto pragma_out;
1022         }
1023       }
1024       sqlite3_free(sqlite3_data_directory);
1025       if( zRight[0] ){
1026         sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
1027       }else{
1028         sqlite3_data_directory = 0;
1029       }
1030 #endif /* SQLITE_OMIT_WSD */
1031     }
1032     break;
1033   }
1034 #endif
1035 
1036 #if SQLITE_ENABLE_LOCKING_STYLE
1037   /*
1038   **   PRAGMA [schema.]lock_proxy_file
1039   **   PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
1040   **
1041   ** Return or set the value of the lock_proxy_file flag.  Changing
1042   ** the value sets a specific file to be used for database access locks.
1043   **
1044   */
1045   case PragTyp_LOCK_PROXY_FILE: {
1046     if( !zRight ){
1047       Pager *pPager = sqlite3BtreePager(pDb->pBt);
1048       char *proxy_file_path = NULL;
1049       sqlite3_file *pFile = sqlite3PagerFile(pPager);
1050       sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
1051                            &proxy_file_path);
1052       returnSingleText(v, proxy_file_path);
1053     }else{
1054       Pager *pPager = sqlite3BtreePager(pDb->pBt);
1055       sqlite3_file *pFile = sqlite3PagerFile(pPager);
1056       int res;
1057       if( zRight[0] ){
1058         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
1059                                      zRight);
1060       } else {
1061         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
1062                                      NULL);
1063       }
1064       if( res!=SQLITE_OK ){
1065         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
1066         goto pragma_out;
1067       }
1068     }
1069     break;
1070   }
1071 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
1072 
1073   /*
1074   **   PRAGMA [schema.]synchronous
1075   **   PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
1076   **
1077   ** Return or set the local value of the synchronous flag.  Changing
1078   ** the local value does not make changes to the disk file and the
1079   ** default value will be restored the next time the database is
1080   ** opened.
1081   */
1082   case PragTyp_SYNCHRONOUS: {
1083     if( !zRight ){
1084       returnSingleInt(v, pDb->safety_level-1);
1085     }else{
1086       if( !db->autoCommit ){
1087         sqlite3ErrorMsg(pParse,
1088             "Safety level may not be changed inside a transaction");
1089       }else if( iDb!=1 ){
1090         int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
1091         if( iLevel==0 ) iLevel = 1;
1092         pDb->safety_level = iLevel;
1093         pDb->bSyncSet = 1;
1094         setAllPagerFlags(db);
1095       }
1096     }
1097     break;
1098   }
1099 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
1100 
1101 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
1102   case PragTyp_FLAG: {
1103     if( zRight==0 ){
1104       setPragmaResultColumnNames(v, pPragma);
1105       returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
1106     }else{
1107       u64 mask = pPragma->iArg;    /* Mask of bits to set or clear. */
1108       if( db->autoCommit==0 ){
1109         /* Foreign key support may not be enabled or disabled while not
1110         ** in auto-commit mode.  */
1111         mask &= ~(SQLITE_ForeignKeys);
1112       }
1113 #if SQLITE_USER_AUTHENTICATION
1114       if( db->auth.authLevel==UAUTH_User ){
1115         /* Do not allow non-admin users to modify the schema arbitrarily */
1116         mask &= ~(SQLITE_WriteSchema);
1117       }
1118 #endif
1119 
1120       if( sqlite3GetBoolean(zRight, 0) ){
1121         db->flags |= mask;
1122       }else{
1123         db->flags &= ~mask;
1124         if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
1125         if( (mask & SQLITE_WriteSchema)!=0
1126          && sqlite3_stricmp(zRight, "reset")==0
1127         ){
1128           /* IMP: R-60817-01178 If the argument is "RESET" then schema
1129           ** writing is disabled (as with "PRAGMA writable_schema=OFF") and,
1130           ** in addition, the schema is reloaded. */
1131           sqlite3ResetAllSchemasOfConnection(db);
1132         }
1133       }
1134 
1135       /* Many of the flag-pragmas modify the code generated by the SQL
1136       ** compiler (eg. count_changes). So add an opcode to expire all
1137       ** compiled SQL statements after modifying a pragma value.
1138       */
1139       sqlite3VdbeAddOp0(v, OP_Expire);
1140       setAllPagerFlags(db);
1141     }
1142     break;
1143   }
1144 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
1145 
1146 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
1147   /*
1148   **   PRAGMA table_info(<table>)
1149   **
1150   ** Return a single row for each column of the named table. The columns of
1151   ** the returned data set are:
1152   **
1153   ** cid:        Column id (numbered from left to right, starting at 0)
1154   ** name:       Column name
1155   ** type:       Column declaration type.
1156   ** notnull:    True if 'NOT NULL' is part of column declaration
1157   ** dflt_value: The default value for the column, if any.
1158   ** pk:         Non-zero for PK fields.
1159   */
1160   case PragTyp_TABLE_INFO: if( zRight ){
1161     Table *pTab;
1162     sqlite3CodeVerifyNamedSchema(pParse, zDb);
1163     pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
1164     if( pTab ){
1165       int i, k;
1166       int nHidden = 0;
1167       Column *pCol;
1168       Index *pPk = sqlite3PrimaryKeyIndex(pTab);
1169       pParse->nMem = 7;
1170       sqlite3ViewGetColumnNames(pParse, pTab);
1171       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
1172         int isHidden = 0;
1173         const Expr *pColExpr;
1174         if( pCol->colFlags & COLFLAG_NOINSERT ){
1175           if( pPragma->iArg==0 ){
1176             nHidden++;
1177             continue;
1178           }
1179           if( pCol->colFlags & COLFLAG_VIRTUAL ){
1180             isHidden = 2;  /* GENERATED ALWAYS AS ... VIRTUAL */
1181           }else if( pCol->colFlags & COLFLAG_STORED ){
1182             isHidden = 3;  /* GENERATED ALWAYS AS ... STORED */
1183           }else{ assert( pCol->colFlags & COLFLAG_HIDDEN );
1184             isHidden = 1;  /* HIDDEN */
1185           }
1186         }
1187         if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
1188           k = 0;
1189         }else if( pPk==0 ){
1190           k = 1;
1191         }else{
1192           for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
1193         }
1194         pColExpr = sqlite3ColumnExpr(pTab,pCol);
1195         assert( pColExpr==0 || pColExpr->op==TK_SPAN || isHidden>=2 );
1196         assert( pColExpr==0 || !ExprHasProperty(pColExpr, EP_IntValue)
1197                   || isHidden>=2 );
1198         sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
1199                i-nHidden,
1200                pCol->zCnName,
1201                sqlite3ColumnType(pCol,""),
1202                pCol->notNull ? 1 : 0,
1203                (isHidden>=2 || pColExpr==0) ? 0 : pColExpr->u.zToken,
1204                k,
1205                isHidden);
1206       }
1207     }
1208   }
1209   break;
1210 
1211   /*
1212   **   PRAGMA table_list
1213   **
1214   ** Return a single row for each table, virtual table, or view in the
1215   ** entire schema.
1216   **
1217   ** schema:     Name of attached database hold this table
1218   ** name:       Name of the table itself
1219   ** type:       "table", "view", "virtual", "shadow"
1220   ** ncol:       Number of columns
1221   ** wr:         True for a WITHOUT ROWID table
1222   ** strict:     True for a STRICT table
1223   */
1224   case PragTyp_TABLE_LIST: {
1225     int ii;
1226     pParse->nMem = 6;
1227     sqlite3CodeVerifyNamedSchema(pParse, zDb);
1228     for(ii=0; ii<db->nDb; ii++){
1229       HashElem *k;
1230       Hash *pHash;
1231       int initNCol;
1232       if( zDb && sqlite3_stricmp(zDb, db->aDb[ii].zDbSName)!=0 ) continue;
1233 
1234       /* Ensure that the Table.nCol field is initialized for all views
1235       ** and virtual tables.  Each time we initialize a Table.nCol value
1236       ** for a table, that can potentially disrupt the hash table, so restart
1237       ** the initialization scan.
1238       */
1239       pHash = &db->aDb[ii].pSchema->tblHash;
1240       initNCol = sqliteHashCount(pHash);
1241       while( initNCol-- ){
1242         for(k=sqliteHashFirst(pHash); 1; k=sqliteHashNext(k) ){
1243           Table *pTab;
1244           if( k==0 ){ initNCol = 0; break; }
1245           pTab = sqliteHashData(k);
1246           if( pTab->nCol==0 ){
1247             char *zSql = sqlite3MPrintf(db, "SELECT*FROM\"%w\"", pTab->zName);
1248             if( zSql ){
1249               sqlite3_stmt *pDummy = 0;
1250               (void)sqlite3_prepare(db, zSql, -1, &pDummy, 0);
1251               (void)sqlite3_finalize(pDummy);
1252               sqlite3DbFree(db, zSql);
1253             }
1254             if( db->mallocFailed ){
1255               sqlite3ErrorMsg(db->pParse, "out of memory");
1256               db->pParse->rc = SQLITE_NOMEM_BKPT;
1257             }
1258             pHash = &db->aDb[ii].pSchema->tblHash;
1259             break;
1260           }
1261         }
1262       }
1263 
1264       for(k=sqliteHashFirst(pHash); k; k=sqliteHashNext(k) ){
1265         Table *pTab = sqliteHashData(k);
1266         const char *zType;
1267         if( zRight && sqlite3_stricmp(zRight, pTab->zName)!=0 ) continue;
1268         if( IsView(pTab) ){
1269           zType = "view";
1270         }else if( IsVirtual(pTab) ){
1271           zType = "virtual";
1272         }else if( pTab->tabFlags & TF_Shadow ){
1273           zType = "shadow";
1274         }else{
1275           zType = "table";
1276         }
1277         sqlite3VdbeMultiLoad(v, 1, "sssiii",
1278            db->aDb[ii].zDbSName,
1279            sqlite3PreferredTableName(pTab->zName),
1280            zType,
1281            pTab->nCol,
1282            (pTab->tabFlags & TF_WithoutRowid)!=0,
1283            (pTab->tabFlags & TF_Strict)!=0
1284         );
1285       }
1286     }
1287   }
1288   break;
1289 
1290 #ifdef SQLITE_DEBUG
1291   case PragTyp_STATS: {
1292     Index *pIdx;
1293     HashElem *i;
1294     pParse->nMem = 5;
1295     sqlite3CodeVerifySchema(pParse, iDb);
1296     for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
1297       Table *pTab = sqliteHashData(i);
1298       sqlite3VdbeMultiLoad(v, 1, "ssiii",
1299            sqlite3PreferredTableName(pTab->zName),
1300            0,
1301            pTab->szTabRow,
1302            pTab->nRowLogEst,
1303            pTab->tabFlags);
1304       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1305         sqlite3VdbeMultiLoad(v, 2, "siiiX",
1306            pIdx->zName,
1307            pIdx->szIdxRow,
1308            pIdx->aiRowLogEst[0],
1309            pIdx->hasStat1);
1310         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
1311       }
1312     }
1313   }
1314   break;
1315 #endif
1316 
1317   case PragTyp_INDEX_INFO: if( zRight ){
1318     Index *pIdx;
1319     Table *pTab;
1320     pIdx = sqlite3FindIndex(db, zRight, zDb);
1321     if( pIdx==0 ){
1322       /* If there is no index named zRight, check to see if there is a
1323       ** WITHOUT ROWID table named zRight, and if there is, show the
1324       ** structure of the PRIMARY KEY index for that table. */
1325       pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
1326       if( pTab && !HasRowid(pTab) ){
1327         pIdx = sqlite3PrimaryKeyIndex(pTab);
1328       }
1329     }
1330     if( pIdx ){
1331       int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
1332       int i;
1333       int mx;
1334       if( pPragma->iArg ){
1335         /* PRAGMA index_xinfo (newer version with more rows and columns) */
1336         mx = pIdx->nColumn;
1337         pParse->nMem = 6;
1338       }else{
1339         /* PRAGMA index_info (legacy version) */
1340         mx = pIdx->nKeyCol;
1341         pParse->nMem = 3;
1342       }
1343       pTab = pIdx->pTable;
1344       sqlite3CodeVerifySchema(pParse, iIdxDb);
1345       assert( pParse->nMem<=pPragma->nPragCName );
1346       for(i=0; i<mx; i++){
1347         i16 cnum = pIdx->aiColumn[i];
1348         sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
1349                              cnum<0 ? 0 : pTab->aCol[cnum].zCnName);
1350         if( pPragma->iArg ){
1351           sqlite3VdbeMultiLoad(v, 4, "isiX",
1352             pIdx->aSortOrder[i],
1353             pIdx->azColl[i],
1354             i<pIdx->nKeyCol);
1355         }
1356         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
1357       }
1358     }
1359   }
1360   break;
1361 
1362   case PragTyp_INDEX_LIST: if( zRight ){
1363     Index *pIdx;
1364     Table *pTab;
1365     int i;
1366     pTab = sqlite3FindTable(db, zRight, zDb);
1367     if( pTab ){
1368       int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1369       pParse->nMem = 5;
1370       sqlite3CodeVerifySchema(pParse, iTabDb);
1371       for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
1372         const char *azOrigin[] = { "c", "u", "pk" };
1373         sqlite3VdbeMultiLoad(v, 1, "isisi",
1374            i,
1375            pIdx->zName,
1376            IsUniqueIndex(pIdx),
1377            azOrigin[pIdx->idxType],
1378            pIdx->pPartIdxWhere!=0);
1379       }
1380     }
1381   }
1382   break;
1383 
1384   case PragTyp_DATABASE_LIST: {
1385     int i;
1386     pParse->nMem = 3;
1387     for(i=0; i<db->nDb; i++){
1388       if( db->aDb[i].pBt==0 ) continue;
1389       assert( db->aDb[i].zDbSName!=0 );
1390       sqlite3VdbeMultiLoad(v, 1, "iss",
1391          i,
1392          db->aDb[i].zDbSName,
1393          sqlite3BtreeGetFilename(db->aDb[i].pBt));
1394     }
1395   }
1396   break;
1397 
1398   case PragTyp_COLLATION_LIST: {
1399     int i = 0;
1400     HashElem *p;
1401     pParse->nMem = 2;
1402     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
1403       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
1404       sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
1405     }
1406   }
1407   break;
1408 
1409 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
1410   case PragTyp_FUNCTION_LIST: {
1411     int i;
1412     HashElem *j;
1413     FuncDef *p;
1414     int showInternFunc = (db->mDbFlags & DBFLAG_InternalFunc)!=0;
1415     pParse->nMem = 6;
1416     for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
1417       for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
1418         assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
1419         pragmaFunclistLine(v, p, 1, showInternFunc);
1420       }
1421     }
1422     for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
1423       p = (FuncDef*)sqliteHashData(j);
1424       assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
1425       pragmaFunclistLine(v, p, 0, showInternFunc);
1426     }
1427   }
1428   break;
1429 
1430 #ifndef SQLITE_OMIT_VIRTUALTABLE
1431   case PragTyp_MODULE_LIST: {
1432     HashElem *j;
1433     pParse->nMem = 1;
1434     for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
1435       Module *pMod = (Module*)sqliteHashData(j);
1436       sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
1437     }
1438   }
1439   break;
1440 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1441 
1442   case PragTyp_PRAGMA_LIST: {
1443     int i;
1444     for(i=0; i<ArraySize(aPragmaName); i++){
1445       sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
1446     }
1447   }
1448   break;
1449 #endif /* SQLITE_INTROSPECTION_PRAGMAS */
1450 
1451 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
1452 
1453 #ifndef SQLITE_OMIT_FOREIGN_KEY
1454   case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
1455     FKey *pFK;
1456     Table *pTab;
1457     pTab = sqlite3FindTable(db, zRight, zDb);
1458     if( pTab && IsOrdinaryTable(pTab) ){
1459       pFK = pTab->u.tab.pFKey;
1460       if( pFK ){
1461         int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1462         int i = 0;
1463         pParse->nMem = 8;
1464         sqlite3CodeVerifySchema(pParse, iTabDb);
1465         while(pFK){
1466           int j;
1467           for(j=0; j<pFK->nCol; j++){
1468             sqlite3VdbeMultiLoad(v, 1, "iissssss",
1469                    i,
1470                    j,
1471                    pFK->zTo,
1472                    pTab->aCol[pFK->aCol[j].iFrom].zCnName,
1473                    pFK->aCol[j].zCol,
1474                    actionName(pFK->aAction[1]),  /* ON UPDATE */
1475                    actionName(pFK->aAction[0]),  /* ON DELETE */
1476                    "NONE");
1477           }
1478           ++i;
1479           pFK = pFK->pNextFrom;
1480         }
1481       }
1482     }
1483   }
1484   break;
1485 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1486 
1487 #ifndef SQLITE_OMIT_FOREIGN_KEY
1488 #ifndef SQLITE_OMIT_TRIGGER
1489   case PragTyp_FOREIGN_KEY_CHECK: {
1490     FKey *pFK;             /* A foreign key constraint */
1491     Table *pTab;           /* Child table contain "REFERENCES" keyword */
1492     Table *pParent;        /* Parent table that child points to */
1493     Index *pIdx;           /* Index in the parent table */
1494     int i;                 /* Loop counter:  Foreign key number for pTab */
1495     int j;                 /* Loop counter:  Field of the foreign key */
1496     HashElem *k;           /* Loop counter:  Next table in schema */
1497     int x;                 /* result variable */
1498     int regResult;         /* 3 registers to hold a result row */
1499     int regRow;            /* Registers to hold a row from pTab */
1500     int addrTop;           /* Top of a loop checking foreign keys */
1501     int addrOk;            /* Jump here if the key is OK */
1502     int *aiCols;           /* child to parent column mapping */
1503 
1504     regResult = pParse->nMem+1;
1505     pParse->nMem += 4;
1506     regRow = ++pParse->nMem;
1507     k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
1508     while( k ){
1509       if( zRight ){
1510         pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
1511         k = 0;
1512       }else{
1513         pTab = (Table*)sqliteHashData(k);
1514         k = sqliteHashNext(k);
1515       }
1516       if( pTab==0 || !IsOrdinaryTable(pTab) || pTab->u.tab.pFKey==0 ) continue;
1517       iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1518       zDb = db->aDb[iDb].zDbSName;
1519       sqlite3CodeVerifySchema(pParse, iDb);
1520       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
1521       if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
1522       sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
1523       sqlite3VdbeLoadString(v, regResult, pTab->zName);
1524       assert( IsOrdinaryTable(pTab) );
1525       for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
1526         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
1527         if( pParent==0 ) continue;
1528         pIdx = 0;
1529         sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
1530         x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
1531         if( x==0 ){
1532           if( pIdx==0 ){
1533             sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
1534           }else{
1535             sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
1536             sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1537           }
1538         }else{
1539           k = 0;
1540           break;
1541         }
1542       }
1543       assert( pParse->nErr>0 || pFK==0 );
1544       if( pFK ) break;
1545       if( pParse->nTab<i ) pParse->nTab = i;
1546       addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
1547       assert( IsOrdinaryTable(pTab) );
1548       for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
1549         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
1550         pIdx = 0;
1551         aiCols = 0;
1552         if( pParent ){
1553           x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
1554           assert( x==0 || db->mallocFailed );
1555         }
1556         addrOk = sqlite3VdbeMakeLabel(pParse);
1557 
1558         /* Generate code to read the child key values into registers
1559         ** regRow..regRow+n. If any of the child key values are NULL, this
1560         ** row cannot cause an FK violation. Jump directly to addrOk in
1561         ** this case. */
1562         if( regRow+pFK->nCol>pParse->nMem ) pParse->nMem = regRow+pFK->nCol;
1563         for(j=0; j<pFK->nCol; j++){
1564           int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
1565           sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
1566           sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
1567         }
1568 
1569         /* Generate code to query the parent index for a matching parent
1570         ** key. If a match is found, jump to addrOk. */
1571         if( pIdx ){
1572           sqlite3VdbeAddOp4(v, OP_Affinity, regRow, pFK->nCol, 0,
1573               sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
1574           sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regRow, pFK->nCol);
1575           VdbeCoverage(v);
1576         }else if( pParent ){
1577           int jmp = sqlite3VdbeCurrentAddr(v)+2;
1578           sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
1579           sqlite3VdbeGoto(v, addrOk);
1580           assert( pFK->nCol==1 || db->mallocFailed );
1581         }
1582 
1583         /* Generate code to report an FK violation to the caller. */
1584         if( HasRowid(pTab) ){
1585           sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
1586         }else{
1587           sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
1588         }
1589         sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
1590         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
1591         sqlite3VdbeResolveLabel(v, addrOk);
1592         sqlite3DbFree(db, aiCols);
1593       }
1594       sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
1595       sqlite3VdbeJumpHere(v, addrTop);
1596     }
1597   }
1598   break;
1599 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
1600 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1601 
1602 #ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA
1603   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
1604   ** used will be case sensitive or not depending on the RHS.
1605   */
1606   case PragTyp_CASE_SENSITIVE_LIKE: {
1607     if( zRight ){
1608       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
1609     }
1610   }
1611   break;
1612 #endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */
1613 
1614 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
1615 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
1616 #endif
1617 
1618 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
1619   /*    PRAGMA integrity_check
1620   **    PRAGMA integrity_check(N)
1621   **    PRAGMA quick_check
1622   **    PRAGMA quick_check(N)
1623   **
1624   ** Verify the integrity of the database.
1625   **
1626   ** The "quick_check" is reduced version of
1627   ** integrity_check designed to detect most database corruption
1628   ** without the overhead of cross-checking indexes.  Quick_check
1629   ** is linear time wherease integrity_check is O(NlogN).
1630   **
1631   ** The maximum nubmer of errors is 100 by default.  A different default
1632   ** can be specified using a numeric parameter N.
1633   **
1634   ** Or, the parameter N can be the name of a table.  In that case, only
1635   ** the one table named is verified.  The freelist is only verified if
1636   ** the named table is "sqlite_schema" (or one of its aliases).
1637   **
1638   ** All schemas are checked by default.  To check just a single
1639   ** schema, use the form:
1640   **
1641   **      PRAGMA schema.integrity_check;
1642   */
1643   case PragTyp_INTEGRITY_CHECK: {
1644     int i, j, addr, mxErr;
1645     Table *pObjTab = 0;     /* Check only this one table, if not NULL */
1646 
1647     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
1648 
1649     /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
1650     ** then iDb is set to the index of the database identified by <db>.
1651     ** In this case, the integrity of database iDb only is verified by
1652     ** the VDBE created below.
1653     **
1654     ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
1655     ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
1656     ** to -1 here, to indicate that the VDBE should verify the integrity
1657     ** of all attached databases.  */
1658     assert( iDb>=0 );
1659     assert( iDb==0 || pId2->z );
1660     if( pId2->z==0 ) iDb = -1;
1661 
1662     /* Initialize the VDBE program */
1663     pParse->nMem = 6;
1664 
1665     /* Set the maximum error count */
1666     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
1667     if( zRight ){
1668       if( sqlite3GetInt32(zRight, &mxErr) ){
1669         if( mxErr<=0 ){
1670           mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
1671         }
1672       }else{
1673         pObjTab = sqlite3LocateTable(pParse, 0, zRight,
1674                       iDb>=0 ? db->aDb[iDb].zDbSName : 0);
1675       }
1676     }
1677     sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
1678 
1679     /* Do an integrity check on each database file */
1680     for(i=0; i<db->nDb; i++){
1681       HashElem *x;     /* For looping over tables in the schema */
1682       Hash *pTbls;     /* Set of all tables in the schema */
1683       int *aRoot;      /* Array of root page numbers of all btrees */
1684       int cnt = 0;     /* Number of entries in aRoot[] */
1685       int mxIdx = 0;   /* Maximum number of indexes for any table */
1686 
1687       if( OMIT_TEMPDB && i==1 ) continue;
1688       if( iDb>=0 && i!=iDb ) continue;
1689 
1690       sqlite3CodeVerifySchema(pParse, i);
1691 
1692       /* Do an integrity check of the B-Tree
1693       **
1694       ** Begin by finding the root pages numbers
1695       ** for all tables and indices in the database.
1696       */
1697       assert( sqlite3SchemaMutexHeld(db, i, 0) );
1698       pTbls = &db->aDb[i].pSchema->tblHash;
1699       for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
1700         Table *pTab = sqliteHashData(x);  /* Current table */
1701         Index *pIdx;                      /* An index on pTab */
1702         int nIdx;                         /* Number of indexes on pTab */
1703         if( pObjTab && pObjTab!=pTab ) continue;
1704         if( HasRowid(pTab) ) cnt++;
1705         for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
1706         if( nIdx>mxIdx ) mxIdx = nIdx;
1707       }
1708       if( cnt==0 ) continue;
1709       if( pObjTab ) cnt++;
1710       aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
1711       if( aRoot==0 ) break;
1712       cnt = 0;
1713       if( pObjTab ) aRoot[++cnt] = 0;
1714       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
1715         Table *pTab = sqliteHashData(x);
1716         Index *pIdx;
1717         if( pObjTab && pObjTab!=pTab ) continue;
1718         if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
1719         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1720           aRoot[++cnt] = pIdx->tnum;
1721         }
1722       }
1723       aRoot[0] = cnt;
1724 
1725       /* Make sure sufficient number of registers have been allocated */
1726       pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
1727       sqlite3ClearTempRegCache(pParse);
1728 
1729       /* Do the b-tree integrity checks */
1730       sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
1731       sqlite3VdbeChangeP5(v, (u8)i);
1732       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
1733       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
1734          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
1735          P4_DYNAMIC);
1736       sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
1737       integrityCheckResultRow(v);
1738       sqlite3VdbeJumpHere(v, addr);
1739 
1740       /* Make sure all the indices are constructed correctly.
1741       */
1742       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
1743         Table *pTab = sqliteHashData(x);
1744         Index *pIdx, *pPk;
1745         Index *pPrior = 0;
1746         int loopTop;
1747         int iDataCur, iIdxCur;
1748         int r1 = -1;
1749         int bStrict;
1750 
1751         if( !IsOrdinaryTable(pTab) ) continue;
1752         if( pObjTab && pObjTab!=pTab ) continue;
1753         pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
1754         sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
1755                                    1, 0, &iDataCur, &iIdxCur);
1756         /* reg[7] counts the number of entries in the table.
1757         ** reg[8+i] counts the number of entries in the i-th index
1758         */
1759         sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
1760         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
1761           sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
1762         }
1763         assert( pParse->nMem>=8+j );
1764         assert( sqlite3NoTempsInRange(pParse,1,7+j) );
1765         sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
1766         loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
1767         if( !isQuick ){
1768           /* Sanity check on record header decoding */
1769           sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nNVCol-1,3);
1770           sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
1771           VdbeComment((v, "(right-most column)"));
1772         }
1773         /* Verify that all NOT NULL columns really are NOT NULL.  At the
1774         ** same time verify the type of the content of STRICT tables */
1775         bStrict = (pTab->tabFlags & TF_Strict)!=0;
1776         for(j=0; j<pTab->nCol; j++){
1777           char *zErr;
1778           Column *pCol = pTab->aCol + j;
1779           int doError, jmp2;
1780           if( j==pTab->iPKey ) continue;
1781           if( pCol->notNull==0 && !bStrict ) continue;
1782           doError = bStrict ? sqlite3VdbeMakeLabel(pParse) : 0;
1783           sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
1784           if( sqlite3VdbeGetOp(v,-1)->opcode==OP_Column ){
1785             sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
1786           }
1787           if( pCol->notNull ){
1788             jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
1789             zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
1790                                 pCol->zCnName);
1791             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1792             if( bStrict && pCol->eCType!=COLTYPE_ANY ){
1793               sqlite3VdbeGoto(v, doError);
1794             }else{
1795               integrityCheckResultRow(v);
1796             }
1797             sqlite3VdbeJumpHere(v, jmp2);
1798           }
1799           if( (pTab->tabFlags & TF_Strict)!=0
1800            && pCol->eCType!=COLTYPE_ANY
1801           ){
1802             jmp2 = sqlite3VdbeAddOp3(v, OP_IsNullOrType, 3, 0,
1803                                      sqlite3StdTypeMap[pCol->eCType-1]);
1804             VdbeCoverage(v);
1805             zErr = sqlite3MPrintf(db, "non-%s value in %s.%s",
1806                                   sqlite3StdType[pCol->eCType-1],
1807                                   pTab->zName, pTab->aCol[j].zCnName);
1808             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1809             sqlite3VdbeResolveLabel(v, doError);
1810             integrityCheckResultRow(v);
1811             sqlite3VdbeJumpHere(v, jmp2);
1812           }
1813         }
1814         /* Verify CHECK constraints */
1815         if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
1816           ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
1817           if( db->mallocFailed==0 ){
1818             int addrCkFault = sqlite3VdbeMakeLabel(pParse);
1819             int addrCkOk = sqlite3VdbeMakeLabel(pParse);
1820             char *zErr;
1821             int k;
1822             pParse->iSelfTab = iDataCur + 1;
1823             for(k=pCheck->nExpr-1; k>0; k--){
1824               sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
1825             }
1826             sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
1827                 SQLITE_JUMPIFNULL);
1828             sqlite3VdbeResolveLabel(v, addrCkFault);
1829             pParse->iSelfTab = 0;
1830             zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
1831                 pTab->zName);
1832             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1833             integrityCheckResultRow(v);
1834             sqlite3VdbeResolveLabel(v, addrCkOk);
1835           }
1836           sqlite3ExprListDelete(db, pCheck);
1837         }
1838         if( !isQuick ){ /* Omit the remaining tests for quick_check */
1839           /* Validate index entries for the current row */
1840           for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
1841             int jmp2, jmp3, jmp4, jmp5;
1842             int ckUniq = sqlite3VdbeMakeLabel(pParse);
1843             if( pPk==pIdx ) continue;
1844             r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
1845                                          pPrior, r1);
1846             pPrior = pIdx;
1847             sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
1848             /* Verify that an index entry exists for the current table row */
1849             jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
1850                                         pIdx->nColumn); VdbeCoverage(v);
1851             sqlite3VdbeLoadString(v, 3, "row ");
1852             sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
1853             sqlite3VdbeLoadString(v, 4, " missing from index ");
1854             sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
1855             jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
1856             sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
1857             jmp4 = integrityCheckResultRow(v);
1858             sqlite3VdbeJumpHere(v, jmp2);
1859             /* For UNIQUE indexes, verify that only one entry exists with the
1860             ** current key.  The entry is unique if (1) any column is NULL
1861             ** or (2) the next entry has a different key */
1862             if( IsUniqueIndex(pIdx) ){
1863               int uniqOk = sqlite3VdbeMakeLabel(pParse);
1864               int jmp6;
1865               int kk;
1866               for(kk=0; kk<pIdx->nKeyCol; kk++){
1867                 int iCol = pIdx->aiColumn[kk];
1868                 assert( iCol!=XN_ROWID && iCol<pTab->nCol );
1869                 if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
1870                 sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
1871                 VdbeCoverage(v);
1872               }
1873               jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
1874               sqlite3VdbeGoto(v, uniqOk);
1875               sqlite3VdbeJumpHere(v, jmp6);
1876               sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
1877                                    pIdx->nKeyCol); VdbeCoverage(v);
1878               sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
1879               sqlite3VdbeGoto(v, jmp5);
1880               sqlite3VdbeResolveLabel(v, uniqOk);
1881             }
1882             sqlite3VdbeJumpHere(v, jmp4);
1883             sqlite3ResolvePartIdxLabel(pParse, jmp3);
1884           }
1885         }
1886         sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
1887         sqlite3VdbeJumpHere(v, loopTop-1);
1888         if( !isQuick ){
1889           sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
1890           for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
1891             if( pPk==pIdx ) continue;
1892             sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
1893             addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
1894             sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
1895             sqlite3VdbeLoadString(v, 4, pIdx->zName);
1896             sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
1897             integrityCheckResultRow(v);
1898             sqlite3VdbeJumpHere(v, addr);
1899           }
1900         }
1901       }
1902     }
1903     {
1904       static const int iLn = VDBE_OFFSET_LINENO(2);
1905       static const VdbeOpList endCode[] = {
1906         { OP_AddImm,      1, 0,        0},    /* 0 */
1907         { OP_IfNotZero,   1, 4,        0},    /* 1 */
1908         { OP_String8,     0, 3,        0},    /* 2 */
1909         { OP_ResultRow,   3, 1,        0},    /* 3 */
1910         { OP_Halt,        0, 0,        0},    /* 4 */
1911         { OP_String8,     0, 3,        0},    /* 5 */
1912         { OP_Goto,        0, 3,        0},    /* 6 */
1913       };
1914       VdbeOp *aOp;
1915 
1916       aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
1917       if( aOp ){
1918         aOp[0].p2 = 1-mxErr;
1919         aOp[2].p4type = P4_STATIC;
1920         aOp[2].p4.z = "ok";
1921         aOp[5].p4type = P4_STATIC;
1922         aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
1923       }
1924       sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
1925     }
1926   }
1927   break;
1928 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
1929 
1930 #ifndef SQLITE_OMIT_UTF16
1931   /*
1932   **   PRAGMA encoding
1933   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
1934   **
1935   ** In its first form, this pragma returns the encoding of the main
1936   ** database. If the database is not initialized, it is initialized now.
1937   **
1938   ** The second form of this pragma is a no-op if the main database file
1939   ** has not already been initialized. In this case it sets the default
1940   ** encoding that will be used for the main database file if a new file
1941   ** is created. If an existing main database file is opened, then the
1942   ** default text encoding for the existing database is used.
1943   **
1944   ** In all cases new databases created using the ATTACH command are
1945   ** created to use the same default text encoding as the main database. If
1946   ** the main database has not been initialized and/or created when ATTACH
1947   ** is executed, this is done before the ATTACH operation.
1948   **
1949   ** In the second form this pragma sets the text encoding to be used in
1950   ** new database files created using this database handle. It is only
1951   ** useful if invoked immediately after the main database i
1952   */
1953   case PragTyp_ENCODING: {
1954     static const struct EncName {
1955       char *zName;
1956       u8 enc;
1957     } encnames[] = {
1958       { "UTF8",     SQLITE_UTF8        },
1959       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
1960       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
1961       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
1962       { "UTF16le",  SQLITE_UTF16LE     },
1963       { "UTF16be",  SQLITE_UTF16BE     },
1964       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
1965       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
1966       { 0, 0 }
1967     };
1968     const struct EncName *pEnc;
1969     if( !zRight ){    /* "PRAGMA encoding" */
1970       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
1971       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
1972       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
1973       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
1974       returnSingleText(v, encnames[ENC(pParse->db)].zName);
1975     }else{                        /* "PRAGMA encoding = XXX" */
1976       /* Only change the value of sqlite.enc if the database handle is not
1977       ** initialized. If the main database exists, the new sqlite.enc value
1978       ** will be overwritten when the schema is next loaded. If it does not
1979       ** already exists, it will be created to use the new encoding value.
1980       */
1981       if( (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
1982         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
1983           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
1984             u8 enc = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
1985             SCHEMA_ENC(db) = enc;
1986             sqlite3SetTextEncoding(db, enc);
1987             break;
1988           }
1989         }
1990         if( !pEnc->zName ){
1991           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
1992         }
1993       }
1994     }
1995   }
1996   break;
1997 #endif /* SQLITE_OMIT_UTF16 */
1998 
1999 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
2000   /*
2001   **   PRAGMA [schema.]schema_version
2002   **   PRAGMA [schema.]schema_version = <integer>
2003   **
2004   **   PRAGMA [schema.]user_version
2005   **   PRAGMA [schema.]user_version = <integer>
2006   **
2007   **   PRAGMA [schema.]freelist_count
2008   **
2009   **   PRAGMA [schema.]data_version
2010   **
2011   **   PRAGMA [schema.]application_id
2012   **   PRAGMA [schema.]application_id = <integer>
2013   **
2014   ** The pragma's schema_version and user_version are used to set or get
2015   ** the value of the schema-version and user-version, respectively. Both
2016   ** the schema-version and the user-version are 32-bit signed integers
2017   ** stored in the database header.
2018   **
2019   ** The schema-cookie is usually only manipulated internally by SQLite. It
2020   ** is incremented by SQLite whenever the database schema is modified (by
2021   ** creating or dropping a table or index). The schema version is used by
2022   ** SQLite each time a query is executed to ensure that the internal cache
2023   ** of the schema used when compiling the SQL query matches the schema of
2024   ** the database against which the compiled query is actually executed.
2025   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
2026   ** the schema-version is potentially dangerous and may lead to program
2027   ** crashes or database corruption. Use with caution!
2028   **
2029   ** The user-version is not used internally by SQLite. It may be used by
2030   ** applications for any purpose.
2031   */
2032   case PragTyp_HEADER_VALUE: {
2033     int iCookie = pPragma->iArg;  /* Which cookie to read or write */
2034     sqlite3VdbeUsesBtree(v, iDb);
2035     if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
2036       /* Write the specified cookie value */
2037       static const VdbeOpList setCookie[] = {
2038         { OP_Transaction,    0,  1,  0},    /* 0 */
2039         { OP_SetCookie,      0,  0,  0},    /* 1 */
2040       };
2041       VdbeOp *aOp;
2042       sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
2043       aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
2044       if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
2045       aOp[0].p1 = iDb;
2046       aOp[1].p1 = iDb;
2047       aOp[1].p2 = iCookie;
2048       aOp[1].p3 = sqlite3Atoi(zRight);
2049       aOp[1].p5 = 1;
2050     }else{
2051       /* Read the specified cookie value */
2052       static const VdbeOpList readCookie[] = {
2053         { OP_Transaction,     0,  0,  0},    /* 0 */
2054         { OP_ReadCookie,      0,  1,  0},    /* 1 */
2055         { OP_ResultRow,       1,  1,  0}
2056       };
2057       VdbeOp *aOp;
2058       sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
2059       aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
2060       if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
2061       aOp[0].p1 = iDb;
2062       aOp[1].p1 = iDb;
2063       aOp[1].p3 = iCookie;
2064       sqlite3VdbeReusable(v);
2065     }
2066   }
2067   break;
2068 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
2069 
2070 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
2071   /*
2072   **   PRAGMA compile_options
2073   **
2074   ** Return the names of all compile-time options used in this build,
2075   ** one option per row.
2076   */
2077   case PragTyp_COMPILE_OPTIONS: {
2078     int i = 0;
2079     const char *zOpt;
2080     pParse->nMem = 1;
2081     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
2082       sqlite3VdbeLoadString(v, 1, zOpt);
2083       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
2084     }
2085     sqlite3VdbeReusable(v);
2086   }
2087   break;
2088 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
2089 
2090 #ifndef SQLITE_OMIT_WAL
2091   /*
2092   **   PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
2093   **
2094   ** Checkpoint the database.
2095   */
2096   case PragTyp_WAL_CHECKPOINT: {
2097     int iBt = (pId2->z?iDb:SQLITE_MAX_DB);
2098     int eMode = SQLITE_CHECKPOINT_PASSIVE;
2099     if( zRight ){
2100       if( sqlite3StrICmp(zRight, "full")==0 ){
2101         eMode = SQLITE_CHECKPOINT_FULL;
2102       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
2103         eMode = SQLITE_CHECKPOINT_RESTART;
2104       }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
2105         eMode = SQLITE_CHECKPOINT_TRUNCATE;
2106       }
2107     }
2108     pParse->nMem = 3;
2109     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
2110     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
2111   }
2112   break;
2113 
2114   /*
2115   **   PRAGMA wal_autocheckpoint
2116   **   PRAGMA wal_autocheckpoint = N
2117   **
2118   ** Configure a database connection to automatically checkpoint a database
2119   ** after accumulating N frames in the log. Or query for the current value
2120   ** of N.
2121   */
2122   case PragTyp_WAL_AUTOCHECKPOINT: {
2123     if( zRight ){
2124       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
2125     }
2126     returnSingleInt(v,
2127        db->xWalCallback==sqlite3WalDefaultHook ?
2128            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
2129   }
2130   break;
2131 #endif
2132 
2133   /*
2134   **  PRAGMA shrink_memory
2135   **
2136   ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
2137   ** connection on which it is invoked to free up as much memory as it
2138   ** can, by calling sqlite3_db_release_memory().
2139   */
2140   case PragTyp_SHRINK_MEMORY: {
2141     sqlite3_db_release_memory(db);
2142     break;
2143   }
2144 
2145   /*
2146   **  PRAGMA optimize
2147   **  PRAGMA optimize(MASK)
2148   **  PRAGMA schema.optimize
2149   **  PRAGMA schema.optimize(MASK)
2150   **
2151   ** Attempt to optimize the database.  All schemas are optimized in the first
2152   ** two forms, and only the specified schema is optimized in the latter two.
2153   **
2154   ** The details of optimizations performed by this pragma are expected
2155   ** to change and improve over time.  Applications should anticipate that
2156   ** this pragma will perform new optimizations in future releases.
2157   **
2158   ** The optional argument is a bitmask of optimizations to perform:
2159   **
2160   **    0x0001    Debugging mode.  Do not actually perform any optimizations
2161   **              but instead return one line of text for each optimization
2162   **              that would have been done.  Off by default.
2163   **
2164   **    0x0002    Run ANALYZE on tables that might benefit.  On by default.
2165   **              See below for additional information.
2166   **
2167   **    0x0004    (Not yet implemented) Record usage and performance
2168   **              information from the current session in the
2169   **              database file so that it will be available to "optimize"
2170   **              pragmas run by future database connections.
2171   **
2172   **    0x0008    (Not yet implemented) Create indexes that might have
2173   **              been helpful to recent queries
2174   **
2175   ** The default MASK is and always shall be 0xfffe.  0xfffe means perform all
2176   ** of the optimizations listed above except Debug Mode, including new
2177   ** optimizations that have not yet been invented.  If new optimizations are
2178   ** ever added that should be off by default, those off-by-default
2179   ** optimizations will have bitmasks of 0x10000 or larger.
2180   **
2181   ** DETERMINATION OF WHEN TO RUN ANALYZE
2182   **
2183   ** In the current implementation, a table is analyzed if only if all of
2184   ** the following are true:
2185   **
2186   ** (1) MASK bit 0x02 is set.
2187   **
2188   ** (2) The query planner used sqlite_stat1-style statistics for one or
2189   **     more indexes of the table at some point during the lifetime of
2190   **     the current connection.
2191   **
2192   ** (3) One or more indexes of the table are currently unanalyzed OR
2193   **     the number of rows in the table has increased by 25 times or more
2194   **     since the last time ANALYZE was run.
2195   **
2196   ** The rules for when tables are analyzed are likely to change in
2197   ** future releases.
2198   */
2199   case PragTyp_OPTIMIZE: {
2200     int iDbLast;           /* Loop termination point for the schema loop */
2201     int iTabCur;           /* Cursor for a table whose size needs checking */
2202     HashElem *k;           /* Loop over tables of a schema */
2203     Schema *pSchema;       /* The current schema */
2204     Table *pTab;           /* A table in the schema */
2205     Index *pIdx;           /* An index of the table */
2206     LogEst szThreshold;    /* Size threshold above which reanalysis is needd */
2207     char *zSubSql;         /* SQL statement for the OP_SqlExec opcode */
2208     u32 opMask;            /* Mask of operations to perform */
2209 
2210     if( zRight ){
2211       opMask = (u32)sqlite3Atoi(zRight);
2212       if( (opMask & 0x02)==0 ) break;
2213     }else{
2214       opMask = 0xfffe;
2215     }
2216     iTabCur = pParse->nTab++;
2217     for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
2218       if( iDb==1 ) continue;
2219       sqlite3CodeVerifySchema(pParse, iDb);
2220       pSchema = db->aDb[iDb].pSchema;
2221       for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
2222         pTab = (Table*)sqliteHashData(k);
2223 
2224         /* If table pTab has not been used in a way that would benefit from
2225         ** having analysis statistics during the current session, then skip it.
2226         ** This also has the effect of skipping virtual tables and views */
2227         if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
2228 
2229         /* Reanalyze if the table is 25 times larger than the last analysis */
2230         szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
2231         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2232           if( !pIdx->hasStat1 ){
2233             szThreshold = 0; /* Always analyze if any index lacks statistics */
2234             break;
2235           }
2236         }
2237         if( szThreshold ){
2238           sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
2239           sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
2240                          sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
2241           VdbeCoverage(v);
2242         }
2243         zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
2244                                  db->aDb[iDb].zDbSName, pTab->zName);
2245         if( opMask & 0x01 ){
2246           int r1 = sqlite3GetTempReg(pParse);
2247           sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
2248           sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
2249         }else{
2250           sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
2251         }
2252       }
2253     }
2254     sqlite3VdbeAddOp0(v, OP_Expire);
2255     break;
2256   }
2257 
2258   /*
2259   **   PRAGMA busy_timeout
2260   **   PRAGMA busy_timeout = N
2261   **
2262   ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
2263   ** if one is set.  If no busy handler or a different busy handler is set
2264   ** then 0 is returned.  Setting the busy_timeout to 0 or negative
2265   ** disables the timeout.
2266   */
2267   /*case PragTyp_BUSY_TIMEOUT*/ default: {
2268     assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
2269     if( zRight ){
2270       sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
2271     }
2272     returnSingleInt(v, db->busyTimeout);
2273     break;
2274   }
2275 
2276   /*
2277   **   PRAGMA soft_heap_limit
2278   **   PRAGMA soft_heap_limit = N
2279   **
2280   ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
2281   ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
2282   ** specified and is a non-negative integer.
2283   ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
2284   ** returns the same integer that would be returned by the
2285   ** sqlite3_soft_heap_limit64(-1) C-language function.
2286   */
2287   case PragTyp_SOFT_HEAP_LIMIT: {
2288     sqlite3_int64 N;
2289     if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
2290       sqlite3_soft_heap_limit64(N);
2291     }
2292     returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
2293     break;
2294   }
2295 
2296   /*
2297   **   PRAGMA hard_heap_limit
2298   **   PRAGMA hard_heap_limit = N
2299   **
2300   ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap
2301   ** limit.  The hard heap limit can be activated or lowered by this
2302   ** pragma, but not raised or deactivated.  Only the
2303   ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate
2304   ** the hard heap limit.  This allows an application to set a heap limit
2305   ** constraint that cannot be relaxed by an untrusted SQL script.
2306   */
2307   case PragTyp_HARD_HEAP_LIMIT: {
2308     sqlite3_int64 N;
2309     if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
2310       sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1);
2311       if( N>0 && (iPrior==0 || iPrior>N) ) sqlite3_hard_heap_limit64(N);
2312     }
2313     returnSingleInt(v, sqlite3_hard_heap_limit64(-1));
2314     break;
2315   }
2316 
2317   /*
2318   **   PRAGMA threads
2319   **   PRAGMA threads = N
2320   **
2321   ** Configure the maximum number of worker threads.  Return the new
2322   ** maximum, which might be less than requested.
2323   */
2324   case PragTyp_THREADS: {
2325     sqlite3_int64 N;
2326     if( zRight
2327      && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
2328      && N>=0
2329     ){
2330       sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
2331     }
2332     returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
2333     break;
2334   }
2335 
2336   /*
2337   **   PRAGMA analysis_limit
2338   **   PRAGMA analysis_limit = N
2339   **
2340   ** Configure the maximum number of rows that ANALYZE will examine
2341   ** in each index that it looks at.  Return the new limit.
2342   */
2343   case PragTyp_ANALYSIS_LIMIT: {
2344     sqlite3_int64 N;
2345     if( zRight
2346      && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK /* IMP: R-40975-20399 */
2347      && N>=0
2348     ){
2349       db->nAnalysisLimit = (int)(N&0x7fffffff);
2350     }
2351     returnSingleInt(v, db->nAnalysisLimit); /* IMP: R-57594-65522 */
2352     break;
2353   }
2354 
2355 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
2356   /*
2357   ** Report the current state of file logs for all databases
2358   */
2359   case PragTyp_LOCK_STATUS: {
2360     static const char *const azLockName[] = {
2361       "unlocked", "shared", "reserved", "pending", "exclusive"
2362     };
2363     int i;
2364     pParse->nMem = 2;
2365     for(i=0; i<db->nDb; i++){
2366       Btree *pBt;
2367       const char *zState = "unknown";
2368       int j;
2369       if( db->aDb[i].zDbSName==0 ) continue;
2370       pBt = db->aDb[i].pBt;
2371       if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
2372         zState = "closed";
2373       }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
2374                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
2375          zState = azLockName[j];
2376       }
2377       sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
2378     }
2379     break;
2380   }
2381 #endif
2382 
2383 #if defined(SQLITE_ENABLE_CEROD)
2384   case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
2385     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
2386       sqlite3_activate_cerod(&zRight[6]);
2387     }
2388   }
2389   break;
2390 #endif
2391 
2392   } /* End of the PRAGMA switch */
2393 
2394   /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
2395   ** purpose is to execute assert() statements to verify that if the
2396   ** PragFlg_NoColumns1 flag is set and the caller specified an argument
2397   ** to the PRAGMA, the implementation has not added any OP_ResultRow
2398   ** instructions to the VM.  */
2399   if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
2400     sqlite3VdbeVerifyNoResultRow(v);
2401   }
2402 
2403 pragma_out:
2404   sqlite3DbFree(db, zLeft);
2405   sqlite3DbFree(db, zRight);
2406 }
2407 #ifndef SQLITE_OMIT_VIRTUALTABLE
2408 /*****************************************************************************
2409 ** Implementation of an eponymous virtual table that runs a pragma.
2410 **
2411 */
2412 typedef struct PragmaVtab PragmaVtab;
2413 typedef struct PragmaVtabCursor PragmaVtabCursor;
2414 struct PragmaVtab {
2415   sqlite3_vtab base;        /* Base class.  Must be first */
2416   sqlite3 *db;              /* The database connection to which it belongs */
2417   const PragmaName *pName;  /* Name of the pragma */
2418   u8 nHidden;               /* Number of hidden columns */
2419   u8 iHidden;               /* Index of the first hidden column */
2420 };
2421 struct PragmaVtabCursor {
2422   sqlite3_vtab_cursor base; /* Base class.  Must be first */
2423   sqlite3_stmt *pPragma;    /* The pragma statement to run */
2424   sqlite_int64 iRowid;      /* Current rowid */
2425   char *azArg[2];           /* Value of the argument and schema */
2426 };
2427 
2428 /*
2429 ** Pragma virtual table module xConnect method.
2430 */
2431 static int pragmaVtabConnect(
2432   sqlite3 *db,
2433   void *pAux,
2434   int argc, const char *const*argv,
2435   sqlite3_vtab **ppVtab,
2436   char **pzErr
2437 ){
2438   const PragmaName *pPragma = (const PragmaName*)pAux;
2439   PragmaVtab *pTab = 0;
2440   int rc;
2441   int i, j;
2442   char cSep = '(';
2443   StrAccum acc;
2444   char zBuf[200];
2445 
2446   UNUSED_PARAMETER(argc);
2447   UNUSED_PARAMETER(argv);
2448   sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
2449   sqlite3_str_appendall(&acc, "CREATE TABLE x");
2450   for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
2451     sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]);
2452     cSep = ',';
2453   }
2454   if( i==0 ){
2455     sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
2456     i++;
2457   }
2458   j = 0;
2459   if( pPragma->mPragFlg & PragFlg_Result1 ){
2460     sqlite3_str_appendall(&acc, ",arg HIDDEN");
2461     j++;
2462   }
2463   if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
2464     sqlite3_str_appendall(&acc, ",schema HIDDEN");
2465     j++;
2466   }
2467   sqlite3_str_append(&acc, ")", 1);
2468   sqlite3StrAccumFinish(&acc);
2469   assert( strlen(zBuf) < sizeof(zBuf)-1 );
2470   rc = sqlite3_declare_vtab(db, zBuf);
2471   if( rc==SQLITE_OK ){
2472     pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
2473     if( pTab==0 ){
2474       rc = SQLITE_NOMEM;
2475     }else{
2476       memset(pTab, 0, sizeof(PragmaVtab));
2477       pTab->pName = pPragma;
2478       pTab->db = db;
2479       pTab->iHidden = i;
2480       pTab->nHidden = j;
2481     }
2482   }else{
2483     *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
2484   }
2485 
2486   *ppVtab = (sqlite3_vtab*)pTab;
2487   return rc;
2488 }
2489 
2490 /*
2491 ** Pragma virtual table module xDisconnect method.
2492 */
2493 static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
2494   PragmaVtab *pTab = (PragmaVtab*)pVtab;
2495   sqlite3_free(pTab);
2496   return SQLITE_OK;
2497 }
2498 
2499 /* Figure out the best index to use to search a pragma virtual table.
2500 **
2501 ** There are not really any index choices.  But we want to encourage the
2502 ** query planner to give == constraints on as many hidden parameters as
2503 ** possible, and especially on the first hidden parameter.  So return a
2504 ** high cost if hidden parameters are unconstrained.
2505 */
2506 static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
2507   PragmaVtab *pTab = (PragmaVtab*)tab;
2508   const struct sqlite3_index_constraint *pConstraint;
2509   int i, j;
2510   int seen[2];
2511 
2512   pIdxInfo->estimatedCost = (double)1;
2513   if( pTab->nHidden==0 ){ return SQLITE_OK; }
2514   pConstraint = pIdxInfo->aConstraint;
2515   seen[0] = 0;
2516   seen[1] = 0;
2517   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
2518     if( pConstraint->usable==0 ) continue;
2519     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
2520     if( pConstraint->iColumn < pTab->iHidden ) continue;
2521     j = pConstraint->iColumn - pTab->iHidden;
2522     assert( j < 2 );
2523     seen[j] = i+1;
2524   }
2525   if( seen[0]==0 ){
2526     pIdxInfo->estimatedCost = (double)2147483647;
2527     pIdxInfo->estimatedRows = 2147483647;
2528     return SQLITE_OK;
2529   }
2530   j = seen[0]-1;
2531   pIdxInfo->aConstraintUsage[j].argvIndex = 1;
2532   pIdxInfo->aConstraintUsage[j].omit = 1;
2533   if( seen[1]==0 ) return SQLITE_OK;
2534   pIdxInfo->estimatedCost = (double)20;
2535   pIdxInfo->estimatedRows = 20;
2536   j = seen[1]-1;
2537   pIdxInfo->aConstraintUsage[j].argvIndex = 2;
2538   pIdxInfo->aConstraintUsage[j].omit = 1;
2539   return SQLITE_OK;
2540 }
2541 
2542 /* Create a new cursor for the pragma virtual table */
2543 static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
2544   PragmaVtabCursor *pCsr;
2545   pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
2546   if( pCsr==0 ) return SQLITE_NOMEM;
2547   memset(pCsr, 0, sizeof(PragmaVtabCursor));
2548   pCsr->base.pVtab = pVtab;
2549   *ppCursor = &pCsr->base;
2550   return SQLITE_OK;
2551 }
2552 
2553 /* Clear all content from pragma virtual table cursor. */
2554 static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
2555   int i;
2556   sqlite3_finalize(pCsr->pPragma);
2557   pCsr->pPragma = 0;
2558   for(i=0; i<ArraySize(pCsr->azArg); i++){
2559     sqlite3_free(pCsr->azArg[i]);
2560     pCsr->azArg[i] = 0;
2561   }
2562 }
2563 
2564 /* Close a pragma virtual table cursor */
2565 static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
2566   PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
2567   pragmaVtabCursorClear(pCsr);
2568   sqlite3_free(pCsr);
2569   return SQLITE_OK;
2570 }
2571 
2572 /* Advance the pragma virtual table cursor to the next row */
2573 static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
2574   PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2575   int rc = SQLITE_OK;
2576 
2577   /* Increment the xRowid value */
2578   pCsr->iRowid++;
2579   assert( pCsr->pPragma );
2580   if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
2581     rc = sqlite3_finalize(pCsr->pPragma);
2582     pCsr->pPragma = 0;
2583     pragmaVtabCursorClear(pCsr);
2584   }
2585   return rc;
2586 }
2587 
2588 /*
2589 ** Pragma virtual table module xFilter method.
2590 */
2591 static int pragmaVtabFilter(
2592   sqlite3_vtab_cursor *pVtabCursor,
2593   int idxNum, const char *idxStr,
2594   int argc, sqlite3_value **argv
2595 ){
2596   PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2597   PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
2598   int rc;
2599   int i, j;
2600   StrAccum acc;
2601   char *zSql;
2602 
2603   UNUSED_PARAMETER(idxNum);
2604   UNUSED_PARAMETER(idxStr);
2605   pragmaVtabCursorClear(pCsr);
2606   j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
2607   for(i=0; i<argc; i++, j++){
2608     const char *zText = (const char*)sqlite3_value_text(argv[i]);
2609     assert( j<ArraySize(pCsr->azArg) );
2610     assert( pCsr->azArg[j]==0 );
2611     if( zText ){
2612       pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
2613       if( pCsr->azArg[j]==0 ){
2614         return SQLITE_NOMEM;
2615       }
2616     }
2617   }
2618   sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
2619   sqlite3_str_appendall(&acc, "PRAGMA ");
2620   if( pCsr->azArg[1] ){
2621     sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
2622   }
2623   sqlite3_str_appendall(&acc, pTab->pName->zName);
2624   if( pCsr->azArg[0] ){
2625     sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
2626   }
2627   zSql = sqlite3StrAccumFinish(&acc);
2628   if( zSql==0 ) return SQLITE_NOMEM;
2629   rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
2630   sqlite3_free(zSql);
2631   if( rc!=SQLITE_OK ){
2632     pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
2633     return rc;
2634   }
2635   return pragmaVtabNext(pVtabCursor);
2636 }
2637 
2638 /*
2639 ** Pragma virtual table module xEof method.
2640 */
2641 static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
2642   PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2643   return (pCsr->pPragma==0);
2644 }
2645 
2646 /* The xColumn method simply returns the corresponding column from
2647 ** the PRAGMA.
2648 */
2649 static int pragmaVtabColumn(
2650   sqlite3_vtab_cursor *pVtabCursor,
2651   sqlite3_context *ctx,
2652   int i
2653 ){
2654   PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2655   PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
2656   if( i<pTab->iHidden ){
2657     sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
2658   }else{
2659     sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
2660   }
2661   return SQLITE_OK;
2662 }
2663 
2664 /*
2665 ** Pragma virtual table module xRowid method.
2666 */
2667 static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
2668   PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2669   *p = pCsr->iRowid;
2670   return SQLITE_OK;
2671 }
2672 
2673 /* The pragma virtual table object */
2674 static const sqlite3_module pragmaVtabModule = {
2675   0,                           /* iVersion */
2676   0,                           /* xCreate - create a table */
2677   pragmaVtabConnect,           /* xConnect - connect to an existing table */
2678   pragmaVtabBestIndex,         /* xBestIndex - Determine search strategy */
2679   pragmaVtabDisconnect,        /* xDisconnect - Disconnect from a table */
2680   0,                           /* xDestroy - Drop a table */
2681   pragmaVtabOpen,              /* xOpen - open a cursor */
2682   pragmaVtabClose,             /* xClose - close a cursor */
2683   pragmaVtabFilter,            /* xFilter - configure scan constraints */
2684   pragmaVtabNext,              /* xNext - advance a cursor */
2685   pragmaVtabEof,               /* xEof */
2686   pragmaVtabColumn,            /* xColumn - read data */
2687   pragmaVtabRowid,             /* xRowid - read data */
2688   0,                           /* xUpdate - write data */
2689   0,                           /* xBegin - begin transaction */
2690   0,                           /* xSync - sync transaction */
2691   0,                           /* xCommit - commit transaction */
2692   0,                           /* xRollback - rollback transaction */
2693   0,                           /* xFindFunction - function overloading */
2694   0,                           /* xRename - rename the table */
2695   0,                           /* xSavepoint */
2696   0,                           /* xRelease */
2697   0,                           /* xRollbackTo */
2698   0                            /* xShadowName */
2699 };
2700 
2701 /*
2702 ** Check to see if zTabName is really the name of a pragma.  If it is,
2703 ** then register an eponymous virtual table for that pragma and return
2704 ** a pointer to the Module object for the new virtual table.
2705 */
2706 Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
2707   const PragmaName *pName;
2708   assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
2709   pName = pragmaLocate(zName+7);
2710   if( pName==0 ) return 0;
2711   if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
2712   assert( sqlite3HashFind(&db->aModule, zName)==0 );
2713   return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
2714 }
2715 
2716 #endif /* SQLITE_OMIT_VIRTUALTABLE */
2717 
2718 #endif /* SQLITE_OMIT_PRAGMA */
2719