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