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