xref: /sqlite-3.40.0/src/pragma.c (revision ef480d37)
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 the names of the first N columns to the values in azCol[]
167 */
168 static void setAllColumnNames(
169   Vdbe *v,               /* The query under construction */
170   int N,                 /* Number of columns */
171   const char **azCol     /* Names of columns */
172 ){
173   int i;
174   sqlite3VdbeSetNumCols(v, N);
175   for(i=0; i<N; i++){
176     sqlite3VdbeSetColName(v, i, COLNAME_NAME, azCol[i], SQLITE_STATIC);
177   }
178 }
179 static void setOneColumnName(Vdbe *v, const char *z){
180   setAllColumnNames(v, 1, &z);
181 }
182 
183 /*
184 ** Generate code to return a single integer value.
185 */
186 static void returnSingleInt(Vdbe *v, const char *zLabel, i64 value){
187   sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
188   setOneColumnName(v, zLabel);
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 *zLabel,     /* Name of the result column */
198   const char *zValue      /* Value to be returned */
199 ){
200   if( zValue ){
201     sqlite3VdbeLoadString(v, 1, (const char*)zValue);
202     setOneColumnName(v, zLabel);
203     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
204   }
205 }
206 
207 
208 /*
209 ** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
210 ** set these values for all pagers.
211 */
212 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
213 static void setAllPagerFlags(sqlite3 *db){
214   if( db->autoCommit ){
215     Db *pDb = db->aDb;
216     int n = db->nDb;
217     assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
218     assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
219     assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
220     assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
221              ==  PAGER_FLAGS_MASK );
222     assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
223     while( (n--) > 0 ){
224       if( pDb->pBt ){
225         sqlite3BtreeSetPagerFlags(pDb->pBt,
226                  pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
227       }
228       pDb++;
229     }
230   }
231 }
232 #else
233 # define setAllPagerFlags(X)  /* no-op */
234 #endif
235 
236 
237 /*
238 ** Return a human-readable name for a constraint resolution action.
239 */
240 #ifndef SQLITE_OMIT_FOREIGN_KEY
241 static const char *actionName(u8 action){
242   const char *zName;
243   switch( action ){
244     case OE_SetNull:  zName = "SET NULL";        break;
245     case OE_SetDflt:  zName = "SET DEFAULT";     break;
246     case OE_Cascade:  zName = "CASCADE";         break;
247     case OE_Restrict: zName = "RESTRICT";        break;
248     default:          zName = "NO ACTION";
249                       assert( action==OE_None ); break;
250   }
251   return zName;
252 }
253 #endif
254 
255 
256 /*
257 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
258 ** defined in pager.h. This function returns the associated lowercase
259 ** journal-mode name.
260 */
261 const char *sqlite3JournalModename(int eMode){
262   static char * const azModeName[] = {
263     "delete", "persist", "off", "truncate", "memory"
264 #ifndef SQLITE_OMIT_WAL
265      , "wal"
266 #endif
267   };
268   assert( PAGER_JOURNALMODE_DELETE==0 );
269   assert( PAGER_JOURNALMODE_PERSIST==1 );
270   assert( PAGER_JOURNALMODE_OFF==2 );
271   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
272   assert( PAGER_JOURNALMODE_MEMORY==4 );
273   assert( PAGER_JOURNALMODE_WAL==5 );
274   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
275 
276   if( eMode==ArraySize(azModeName) ) return 0;
277   return azModeName[eMode];
278 }
279 
280 /*
281 ** Process a pragma statement.
282 **
283 ** Pragmas are of this form:
284 **
285 **      PRAGMA [schema.]id [= value]
286 **
287 ** The identifier might also be a string.  The value is a string, and
288 ** identifier, or a number.  If minusFlag is true, then the value is
289 ** a number that was preceded by a minus sign.
290 **
291 ** If the left side is "database.id" then pId1 is the database name
292 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
293 ** id and pId2 is any empty string.
294 */
295 void sqlite3Pragma(
296   Parse *pParse,
297   Token *pId1,        /* First part of [schema.]id field */
298   Token *pId2,        /* Second part of [schema.]id field, or NULL */
299   Token *pValue,      /* Token for <value>, or NULL */
300   int minusFlag       /* True if a '-' sign preceded <value> */
301 ){
302   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
303   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
304   const char *zDb = 0;   /* The database name */
305   Token *pId;            /* Pointer to <id> token */
306   char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
307   int iDb;               /* Database index for <database> */
308   int lwr, upr, mid = 0;       /* Binary search bounds */
309   int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
310   sqlite3 *db = pParse->db;    /* The database connection */
311   Db *pDb;                     /* The specific database being pragmaed */
312   Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
313   const struct sPragmaNames *pPragma;
314 
315   if( v==0 ) return;
316   sqlite3VdbeRunOnlyOnce(v);
317   pParse->nMem = 2;
318 
319   /* Interpret the [schema.] part of the pragma statement. iDb is the
320   ** index of the database this pragma is being applied to in db.aDb[]. */
321   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
322   if( iDb<0 ) return;
323   pDb = &db->aDb[iDb];
324 
325   /* If the temp database has been explicitly named as part of the
326   ** pragma, make sure it is open.
327   */
328   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
329     return;
330   }
331 
332   zLeft = sqlite3NameFromToken(db, pId);
333   if( !zLeft ) return;
334   if( minusFlag ){
335     zRight = sqlite3MPrintf(db, "-%T", pValue);
336   }else{
337     zRight = sqlite3NameFromToken(db, pValue);
338   }
339 
340   assert( pId2 );
341   zDb = pId2->n>0 ? pDb->zName : 0;
342   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
343     goto pragma_out;
344   }
345 
346   /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
347   ** connection.  If it returns SQLITE_OK, then assume that the VFS
348   ** handled the pragma and generate a no-op prepared statement.
349   **
350   ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
351   ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
352   ** object corresponding to the database file to which the pragma
353   ** statement refers.
354   **
355   ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
356   ** file control is an array of pointers to strings (char**) in which the
357   ** second element of the array is the name of the pragma and the third
358   ** element is the argument to the pragma or NULL if the pragma has no
359   ** argument.
360   */
361   aFcntl[0] = 0;
362   aFcntl[1] = zLeft;
363   aFcntl[2] = zRight;
364   aFcntl[3] = 0;
365   db->busyHandler.nBusy = 0;
366   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
367   if( rc==SQLITE_OK ){
368     returnSingleText(v, "result", aFcntl[0]);
369     sqlite3_free(aFcntl[0]);
370     goto pragma_out;
371   }
372   if( rc!=SQLITE_NOTFOUND ){
373     if( aFcntl[0] ){
374       sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
375       sqlite3_free(aFcntl[0]);
376     }
377     pParse->nErr++;
378     pParse->rc = rc;
379     goto pragma_out;
380   }
381 
382   /* Locate the pragma in the lookup table */
383   lwr = 0;
384   upr = ArraySize(aPragmaNames)-1;
385   while( lwr<=upr ){
386     mid = (lwr+upr)/2;
387     rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
388     if( rc==0 ) break;
389     if( rc<0 ){
390       upr = mid - 1;
391     }else{
392       lwr = mid + 1;
393     }
394   }
395   if( lwr>upr ) goto pragma_out;
396   pPragma = &aPragmaNames[mid];
397 
398   /* Make sure the database schema is loaded if the pragma requires that */
399   if( (pPragma->mPragFlag & PragFlag_NeedSchema)!=0 ){
400     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
401   }
402 
403   /* Jump to the appropriate pragma handler */
404   switch( pPragma->ePragTyp ){
405 
406 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
407   /*
408   **  PRAGMA [schema.]default_cache_size
409   **  PRAGMA [schema.]default_cache_size=N
410   **
411   ** The first form reports the current persistent setting for the
412   ** page cache size.  The value returned is the maximum number of
413   ** pages in the page cache.  The second form sets both the current
414   ** page cache size value and the persistent page cache size value
415   ** stored in the database file.
416   **
417   ** Older versions of SQLite would set the default cache size to a
418   ** negative number to indicate synchronous=OFF.  These days, synchronous
419   ** is always on by default regardless of the sign of the default cache
420   ** size.  But continue to take the absolute value of the default cache
421   ** size of historical compatibility.
422   */
423   case PragTyp_DEFAULT_CACHE_SIZE: {
424     static const int iLn = VDBE_OFFSET_LINENO(2);
425     static const VdbeOpList getCacheSize[] = {
426       { OP_Transaction, 0, 0,        0},                         /* 0 */
427       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
428       { OP_IfPos,       1, 8,        0},
429       { OP_Integer,     0, 2,        0},
430       { OP_Subtract,    1, 2,        1},
431       { OP_IfPos,       1, 8,        0},
432       { OP_Integer,     0, 1,        0},                         /* 6 */
433       { OP_Noop,        0, 0,        0},
434       { OP_ResultRow,   1, 1,        0},
435     };
436     VdbeOp *aOp;
437     sqlite3VdbeUsesBtree(v, iDb);
438     if( !zRight ){
439       setOneColumnName(v, "cache_size");
440       pParse->nMem += 2;
441       sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
442       aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
443       if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
444       aOp[0].p1 = iDb;
445       aOp[1].p1 = iDb;
446       aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
447     }else{
448       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
449       sqlite3BeginWriteOperation(pParse, 0, iDb);
450       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
451       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
452       pDb->pSchema->cache_size = size;
453       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
454     }
455     break;
456   }
457 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
458 
459 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
460   /*
461   **  PRAGMA [schema.]page_size
462   **  PRAGMA [schema.]page_size=N
463   **
464   ** The first form reports the current setting for the
465   ** database page size in bytes.  The second form sets the
466   ** database page size value.  The value can only be set if
467   ** the database has not yet been created.
468   */
469   case PragTyp_PAGE_SIZE: {
470     Btree *pBt = pDb->pBt;
471     assert( pBt!=0 );
472     if( !zRight ){
473       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
474       returnSingleInt(v, "page_size", size);
475     }else{
476       /* Malloc may fail when setting the page-size, as there is an internal
477       ** buffer that the pager module resizes using sqlite3_realloc().
478       */
479       db->nextPagesize = sqlite3Atoi(zRight);
480       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
481         sqlite3OomFault(db);
482       }
483     }
484     break;
485   }
486 
487   /*
488   **  PRAGMA [schema.]secure_delete
489   **  PRAGMA [schema.]secure_delete=ON/OFF
490   **
491   ** The first form reports the current setting for the
492   ** secure_delete flag.  The second form changes the secure_delete
493   ** flag setting and reports thenew value.
494   */
495   case PragTyp_SECURE_DELETE: {
496     Btree *pBt = pDb->pBt;
497     int b = -1;
498     assert( pBt!=0 );
499     if( zRight ){
500       b = sqlite3GetBoolean(zRight, 0);
501     }
502     if( pId2->n==0 && b>=0 ){
503       int ii;
504       for(ii=0; ii<db->nDb; ii++){
505         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
506       }
507     }
508     b = sqlite3BtreeSecureDelete(pBt, b);
509     returnSingleInt(v, "secure_delete", b);
510     break;
511   }
512 
513   /*
514   **  PRAGMA [schema.]max_page_count
515   **  PRAGMA [schema.]max_page_count=N
516   **
517   ** The first form reports the current setting for the
518   ** maximum number of pages in the database file.  The
519   ** second form attempts to change this setting.  Both
520   ** forms return the current setting.
521   **
522   ** The absolute value of N is used.  This is undocumented and might
523   ** change.  The only purpose is to provide an easy way to test
524   ** the sqlite3AbsInt32() function.
525   **
526   **  PRAGMA [schema.]page_count
527   **
528   ** Return the number of pages in the specified database.
529   */
530   case PragTyp_PAGE_COUNT: {
531     int iReg;
532     sqlite3CodeVerifySchema(pParse, iDb);
533     iReg = ++pParse->nMem;
534     if( sqlite3Tolower(zLeft[0])=='p' ){
535       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
536     }else{
537       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
538                         sqlite3AbsInt32(sqlite3Atoi(zRight)));
539     }
540     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
541     sqlite3VdbeSetNumCols(v, 1);
542     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
543     break;
544   }
545 
546   /*
547   **  PRAGMA [schema.]locking_mode
548   **  PRAGMA [schema.]locking_mode = (normal|exclusive)
549   */
550   case PragTyp_LOCKING_MODE: {
551     const char *zRet = "normal";
552     int eMode = getLockingMode(zRight);
553 
554     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
555       /* Simple "PRAGMA locking_mode;" statement. This is a query for
556       ** the current default locking mode (which may be different to
557       ** the locking-mode of the main database).
558       */
559       eMode = db->dfltLockMode;
560     }else{
561       Pager *pPager;
562       if( pId2->n==0 ){
563         /* This indicates that no database name was specified as part
564         ** of the PRAGMA command. In this case the locking-mode must be
565         ** set on all attached databases, as well as the main db file.
566         **
567         ** Also, the sqlite3.dfltLockMode variable is set so that
568         ** any subsequently attached databases also use the specified
569         ** locking mode.
570         */
571         int ii;
572         assert(pDb==&db->aDb[0]);
573         for(ii=2; ii<db->nDb; ii++){
574           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
575           sqlite3PagerLockingMode(pPager, eMode);
576         }
577         db->dfltLockMode = (u8)eMode;
578       }
579       pPager = sqlite3BtreePager(pDb->pBt);
580       eMode = sqlite3PagerLockingMode(pPager, eMode);
581     }
582 
583     assert( eMode==PAGER_LOCKINGMODE_NORMAL
584             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
585     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
586       zRet = "exclusive";
587     }
588     returnSingleText(v, "locking_mode", zRet);
589     break;
590   }
591 
592   /*
593   **  PRAGMA [schema.]journal_mode
594   **  PRAGMA [schema.]journal_mode =
595   **                      (delete|persist|off|truncate|memory|wal|off)
596   */
597   case PragTyp_JOURNAL_MODE: {
598     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
599     int ii;           /* Loop counter */
600 
601     setOneColumnName(v, "journal_mode");
602     if( zRight==0 ){
603       /* If there is no "=MODE" part of the pragma, do a query for the
604       ** current mode */
605       eMode = PAGER_JOURNALMODE_QUERY;
606     }else{
607       const char *zMode;
608       int n = sqlite3Strlen30(zRight);
609       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
610         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
611       }
612       if( !zMode ){
613         /* If the "=MODE" part does not match any known journal mode,
614         ** then do a query */
615         eMode = PAGER_JOURNALMODE_QUERY;
616       }
617     }
618     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
619       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
620       iDb = 0;
621       pId2->n = 1;
622     }
623     for(ii=db->nDb-1; ii>=0; ii--){
624       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
625         sqlite3VdbeUsesBtree(v, ii);
626         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
627       }
628     }
629     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
630     break;
631   }
632 
633   /*
634   **  PRAGMA [schema.]journal_size_limit
635   **  PRAGMA [schema.]journal_size_limit=N
636   **
637   ** Get or set the size limit on rollback journal files.
638   */
639   case PragTyp_JOURNAL_SIZE_LIMIT: {
640     Pager *pPager = sqlite3BtreePager(pDb->pBt);
641     i64 iLimit = -2;
642     if( zRight ){
643       sqlite3DecOrHexToI64(zRight, &iLimit);
644       if( iLimit<-1 ) iLimit = -1;
645     }
646     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
647     returnSingleInt(v, "journal_size_limit", iLimit);
648     break;
649   }
650 
651 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
652 
653   /*
654   **  PRAGMA [schema.]auto_vacuum
655   **  PRAGMA [schema.]auto_vacuum=N
656   **
657   ** Get or set the value of the database 'auto-vacuum' parameter.
658   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
659   */
660 #ifndef SQLITE_OMIT_AUTOVACUUM
661   case PragTyp_AUTO_VACUUM: {
662     Btree *pBt = pDb->pBt;
663     assert( pBt!=0 );
664     if( !zRight ){
665       returnSingleInt(v, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
666     }else{
667       int eAuto = getAutoVacuum(zRight);
668       assert( eAuto>=0 && eAuto<=2 );
669       db->nextAutovac = (u8)eAuto;
670       /* Call SetAutoVacuum() to set initialize the internal auto and
671       ** incr-vacuum flags. This is required in case this connection
672       ** creates the database file. It is important that it is created
673       ** as an auto-vacuum capable db.
674       */
675       rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
676       if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
677         /* When setting the auto_vacuum mode to either "full" or
678         ** "incremental", write the value of meta[6] in the database
679         ** file. Before writing to meta[6], check that meta[3] indicates
680         ** that this really is an auto-vacuum capable database.
681         */
682         static const int iLn = VDBE_OFFSET_LINENO(2);
683         static const VdbeOpList setMeta6[] = {
684           { OP_Transaction,    0,         1,                 0},    /* 0 */
685           { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
686           { OP_If,             1,         0,                 0},    /* 2 */
687           { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
688           { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 0},    /* 4 */
689         };
690         VdbeOp *aOp;
691         int iAddr = sqlite3VdbeCurrentAddr(v);
692         sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
693         aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
694         if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
695         aOp[0].p1 = iDb;
696         aOp[1].p1 = iDb;
697         aOp[2].p2 = iAddr+4;
698         aOp[4].p1 = iDb;
699         aOp[4].p3 = eAuto - 1;
700         sqlite3VdbeUsesBtree(v, iDb);
701       }
702     }
703     break;
704   }
705 #endif
706 
707   /*
708   **  PRAGMA [schema.]incremental_vacuum(N)
709   **
710   ** Do N steps of incremental vacuuming on a database.
711   */
712 #ifndef SQLITE_OMIT_AUTOVACUUM
713   case PragTyp_INCREMENTAL_VACUUM: {
714     int iLimit, addr;
715     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
716       iLimit = 0x7fffffff;
717     }
718     sqlite3BeginWriteOperation(pParse, 0, iDb);
719     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
720     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
721     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
722     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
723     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
724     sqlite3VdbeJumpHere(v, addr);
725     break;
726   }
727 #endif
728 
729 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
730   /*
731   **  PRAGMA [schema.]cache_size
732   **  PRAGMA [schema.]cache_size=N
733   **
734   ** The first form reports the current local setting for the
735   ** page cache size. The second form sets the local
736   ** page cache size value.  If N is positive then that is the
737   ** number of pages in the cache.  If N is negative, then the
738   ** number of pages is adjusted so that the cache uses -N kibibytes
739   ** of memory.
740   */
741   case PragTyp_CACHE_SIZE: {
742     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
743     if( !zRight ){
744       returnSingleInt(v, "cache_size", pDb->pSchema->cache_size);
745     }else{
746       int size = sqlite3Atoi(zRight);
747       pDb->pSchema->cache_size = size;
748       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
749     }
750     break;
751   }
752 
753   /*
754   **  PRAGMA [schema.]cache_spill
755   **  PRAGMA cache_spill=BOOLEAN
756   **  PRAGMA [schema.]cache_spill=N
757   **
758   ** The first form reports the current local setting for the
759   ** page cache spill size. The second form turns cache spill on
760   ** or off.  When turnning cache spill on, the size is set to the
761   ** current cache_size.  The third form sets a spill size that
762   ** may be different form the cache size.
763   ** If N is positive then that is the
764   ** number of pages in the cache.  If N is negative, then the
765   ** number of pages is adjusted so that the cache uses -N kibibytes
766   ** of memory.
767   **
768   ** If the number of cache_spill pages is less then the number of
769   ** cache_size pages, no spilling occurs until the page count exceeds
770   ** the number of cache_size pages.
771   **
772   ** The cache_spill=BOOLEAN setting applies to all attached schemas,
773   ** not just the schema specified.
774   */
775   case PragTyp_CACHE_SPILL: {
776     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
777     if( !zRight ){
778       returnSingleInt(v, "cache_spill",
779          (db->flags & SQLITE_CacheSpill)==0 ? 0 :
780             sqlite3BtreeSetSpillSize(pDb->pBt,0));
781     }else{
782       int size = 1;
783       if( sqlite3GetInt32(zRight, &size) ){
784         sqlite3BtreeSetSpillSize(pDb->pBt, size);
785       }
786       if( sqlite3GetBoolean(zRight, size!=0) ){
787         db->flags |= SQLITE_CacheSpill;
788       }else{
789         db->flags &= ~SQLITE_CacheSpill;
790       }
791       setAllPagerFlags(db);
792     }
793     break;
794   }
795 
796   /*
797   **  PRAGMA [schema.]mmap_size(N)
798   **
799   ** Used to set mapping size limit. The mapping size limit is
800   ** used to limit the aggregate size of all memory mapped regions of the
801   ** database file. If this parameter is set to zero, then memory mapping
802   ** is not used at all.  If N is negative, then the default memory map
803   ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
804   ** The parameter N is measured in bytes.
805   **
806   ** This value is advisory.  The underlying VFS is free to memory map
807   ** as little or as much as it wants.  Except, if N is set to 0 then the
808   ** upper layers will never invoke the xFetch interfaces to the VFS.
809   */
810   case PragTyp_MMAP_SIZE: {
811     sqlite3_int64 sz;
812 #if SQLITE_MAX_MMAP_SIZE>0
813     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
814     if( zRight ){
815       int ii;
816       sqlite3DecOrHexToI64(zRight, &sz);
817       if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
818       if( pId2->n==0 ) db->szMmap = sz;
819       for(ii=db->nDb-1; ii>=0; ii--){
820         if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
821           sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
822         }
823       }
824     }
825     sz = -1;
826     rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
827 #else
828     sz = 0;
829     rc = SQLITE_OK;
830 #endif
831     if( rc==SQLITE_OK ){
832       returnSingleInt(v, "mmap_size", sz);
833     }else if( rc!=SQLITE_NOTFOUND ){
834       pParse->nErr++;
835       pParse->rc = rc;
836     }
837     break;
838   }
839 
840   /*
841   **   PRAGMA temp_store
842   **   PRAGMA temp_store = "default"|"memory"|"file"
843   **
844   ** Return or set the local value of the temp_store flag.  Changing
845   ** the local value does not make changes to the disk file and the default
846   ** value will be restored the next time the database is opened.
847   **
848   ** Note that it is possible for the library compile-time options to
849   ** override this setting
850   */
851   case PragTyp_TEMP_STORE: {
852     if( !zRight ){
853       returnSingleInt(v, "temp_store", db->temp_store);
854     }else{
855       changeTempStorage(pParse, zRight);
856     }
857     break;
858   }
859 
860   /*
861   **   PRAGMA temp_store_directory
862   **   PRAGMA temp_store_directory = ""|"directory_name"
863   **
864   ** Return or set the local value of the temp_store_directory flag.  Changing
865   ** the value sets a specific directory to be used for temporary files.
866   ** Setting to a null string reverts to the default temporary directory search.
867   ** If temporary directory is changed, then invalidateTempStorage.
868   **
869   */
870   case PragTyp_TEMP_STORE_DIRECTORY: {
871     if( !zRight ){
872       returnSingleText(v, "temp_store_directory", sqlite3_temp_directory);
873     }else{
874 #ifndef SQLITE_OMIT_WSD
875       if( zRight[0] ){
876         int res;
877         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
878         if( rc!=SQLITE_OK || res==0 ){
879           sqlite3ErrorMsg(pParse, "not a writable directory");
880           goto pragma_out;
881         }
882       }
883       if( SQLITE_TEMP_STORE==0
884        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
885        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
886       ){
887         invalidateTempStorage(pParse);
888       }
889       sqlite3_free(sqlite3_temp_directory);
890       if( zRight[0] ){
891         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
892       }else{
893         sqlite3_temp_directory = 0;
894       }
895 #endif /* SQLITE_OMIT_WSD */
896     }
897     break;
898   }
899 
900 #if SQLITE_OS_WIN
901   /*
902   **   PRAGMA data_store_directory
903   **   PRAGMA data_store_directory = ""|"directory_name"
904   **
905   ** Return or set the local value of the data_store_directory flag.  Changing
906   ** the value sets a specific directory to be used for database files that
907   ** were specified with a relative pathname.  Setting to a null string reverts
908   ** to the default database directory, which for database files specified with
909   ** a relative path will probably be based on the current directory for the
910   ** process.  Database file specified with an absolute path are not impacted
911   ** by this setting, regardless of its value.
912   **
913   */
914   case PragTyp_DATA_STORE_DIRECTORY: {
915     if( !zRight ){
916       returnSingleText(v, "data_store_directory", sqlite3_data_directory);
917     }else{
918 #ifndef SQLITE_OMIT_WSD
919       if( zRight[0] ){
920         int res;
921         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
922         if( rc!=SQLITE_OK || res==0 ){
923           sqlite3ErrorMsg(pParse, "not a writable directory");
924           goto pragma_out;
925         }
926       }
927       sqlite3_free(sqlite3_data_directory);
928       if( zRight[0] ){
929         sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
930       }else{
931         sqlite3_data_directory = 0;
932       }
933 #endif /* SQLITE_OMIT_WSD */
934     }
935     break;
936   }
937 #endif
938 
939 #if SQLITE_ENABLE_LOCKING_STYLE
940   /*
941   **   PRAGMA [schema.]lock_proxy_file
942   **   PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
943   **
944   ** Return or set the value of the lock_proxy_file flag.  Changing
945   ** the value sets a specific file to be used for database access locks.
946   **
947   */
948   case PragTyp_LOCK_PROXY_FILE: {
949     if( !zRight ){
950       Pager *pPager = sqlite3BtreePager(pDb->pBt);
951       char *proxy_file_path = NULL;
952       sqlite3_file *pFile = sqlite3PagerFile(pPager);
953       sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
954                            &proxy_file_path);
955       returnSingleText(v, "lock_proxy_file", proxy_file_path);
956     }else{
957       Pager *pPager = sqlite3BtreePager(pDb->pBt);
958       sqlite3_file *pFile = sqlite3PagerFile(pPager);
959       int res;
960       if( zRight[0] ){
961         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
962                                      zRight);
963       } else {
964         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
965                                      NULL);
966       }
967       if( res!=SQLITE_OK ){
968         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
969         goto pragma_out;
970       }
971     }
972     break;
973   }
974 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
975 
976   /*
977   **   PRAGMA [schema.]synchronous
978   **   PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
979   **
980   ** Return or set the local value of the synchronous flag.  Changing
981   ** the local value does not make changes to the disk file and the
982   ** default value will be restored the next time the database is
983   ** opened.
984   */
985   case PragTyp_SYNCHRONOUS: {
986     if( !zRight ){
987       returnSingleInt(v, "synchronous", pDb->safety_level-1);
988     }else{
989       if( !db->autoCommit ){
990         sqlite3ErrorMsg(pParse,
991             "Safety level may not be changed inside a transaction");
992       }else{
993         int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
994         if( iLevel==0 ) iLevel = 1;
995         pDb->safety_level = iLevel;
996         pDb->bSyncSet = 1;
997         setAllPagerFlags(db);
998       }
999     }
1000     break;
1001   }
1002 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
1003 
1004 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
1005   case PragTyp_FLAG: {
1006     if( zRight==0 ){
1007       returnSingleInt(v, pPragma->zName, (db->flags & pPragma->iArg)!=0 );
1008     }else{
1009       int mask = pPragma->iArg;    /* Mask of bits to set or clear. */
1010       if( db->autoCommit==0 ){
1011         /* Foreign key support may not be enabled or disabled while not
1012         ** in auto-commit mode.  */
1013         mask &= ~(SQLITE_ForeignKeys);
1014       }
1015 #if SQLITE_USER_AUTHENTICATION
1016       if( db->auth.authLevel==UAUTH_User ){
1017         /* Do not allow non-admin users to modify the schema arbitrarily */
1018         mask &= ~(SQLITE_WriteSchema);
1019       }
1020 #endif
1021 
1022       if( sqlite3GetBoolean(zRight, 0) ){
1023         db->flags |= mask;
1024       }else{
1025         db->flags &= ~mask;
1026         if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
1027       }
1028 
1029       /* Many of the flag-pragmas modify the code generated by the SQL
1030       ** compiler (eg. count_changes). So add an opcode to expire all
1031       ** compiled SQL statements after modifying a pragma value.
1032       */
1033       sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
1034       setAllPagerFlags(db);
1035     }
1036     break;
1037   }
1038 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
1039 
1040 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
1041   /*
1042   **   PRAGMA table_info(<table>)
1043   **
1044   ** Return a single row for each column of the named table. The columns of
1045   ** the returned data set are:
1046   **
1047   ** cid:        Column id (numbered from left to right, starting at 0)
1048   ** name:       Column name
1049   ** type:       Column declaration type.
1050   ** notnull:    True if 'NOT NULL' is part of column declaration
1051   ** dflt_value: The default value for the column, if any.
1052   */
1053   case PragTyp_TABLE_INFO: if( zRight ){
1054     Table *pTab;
1055     pTab = sqlite3FindTable(db, zRight, zDb);
1056     if( pTab ){
1057       static const char *azCol[] = {
1058          "cid", "name", "type", "notnull", "dflt_value", "pk"
1059       };
1060       int i, k;
1061       int nHidden = 0;
1062       Column *pCol;
1063       Index *pPk = sqlite3PrimaryKeyIndex(pTab);
1064       pParse->nMem = 6;
1065       sqlite3CodeVerifySchema(pParse, iDb);
1066       setAllColumnNames(v, 6, azCol); assert( 6==ArraySize(azCol) );
1067       sqlite3ViewGetColumnNames(pParse, pTab);
1068       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
1069         const char *zName;
1070         if( IsHiddenColumn(pCol) ){
1071           nHidden++;
1072           continue;
1073         }
1074         if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
1075           k = 0;
1076         }else if( pPk==0 ){
1077           k = 1;
1078         }else{
1079           for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
1080         }
1081         assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
1082         zName = pCol->zName;
1083         sqlite3VdbeMultiLoad(v, 1, "issisi",
1084                i-nHidden,
1085                zName,
1086                sqlite3StrNext(zName),
1087                pCol->notNull ? 1 : 0,
1088                pCol->pDflt ? pCol->pDflt->u.zToken : 0,
1089                k);
1090         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
1091       }
1092     }
1093   }
1094   break;
1095 
1096   case PragTyp_STATS: {
1097     static const char *azCol[] = { "table", "index", "width", "height" };
1098     Index *pIdx;
1099     HashElem *i;
1100     v = sqlite3GetVdbe(pParse);
1101     pParse->nMem = 4;
1102     sqlite3CodeVerifySchema(pParse, iDb);
1103     setAllColumnNames(v, 4, azCol);  assert( 4==ArraySize(azCol) );
1104     for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
1105       Table *pTab = sqliteHashData(i);
1106       sqlite3VdbeMultiLoad(v, 1, "ssii",
1107            pTab->zName,
1108            0,
1109            pTab->szTabRow,
1110            pTab->nRowLogEst);
1111       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
1112       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1113         sqlite3VdbeMultiLoad(v, 2, "sii",
1114            pIdx->zName,
1115            pIdx->szIdxRow,
1116            pIdx->aiRowLogEst[0]);
1117         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
1118       }
1119     }
1120   }
1121   break;
1122 
1123   case PragTyp_INDEX_INFO: if( zRight ){
1124     Index *pIdx;
1125     Table *pTab;
1126     pIdx = sqlite3FindIndex(db, zRight, zDb);
1127     if( pIdx ){
1128       static const char *azCol[] = {
1129          "seqno", "cid", "name", "desc", "coll", "key"
1130       };
1131       int i;
1132       int mx;
1133       if( pPragma->iArg ){
1134         /* PRAGMA index_xinfo (newer version with more rows and columns) */
1135         mx = pIdx->nColumn;
1136         pParse->nMem = 6;
1137       }else{
1138         /* PRAGMA index_info (legacy version) */
1139         mx = pIdx->nKeyCol;
1140         pParse->nMem = 3;
1141       }
1142       pTab = pIdx->pTable;
1143       sqlite3CodeVerifySchema(pParse, iDb);
1144       assert( pParse->nMem<=ArraySize(azCol) );
1145       setAllColumnNames(v, pParse->nMem, azCol);
1146       for(i=0; i<mx; i++){
1147         i16 cnum = pIdx->aiColumn[i];
1148         sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum,
1149                              cnum<0 ? 0 : pTab->aCol[cnum].zName);
1150         if( pPragma->iArg ){
1151           sqlite3VdbeMultiLoad(v, 4, "isi",
1152             pIdx->aSortOrder[i],
1153             pIdx->azColl[i],
1154             i<pIdx->nKeyCol);
1155         }
1156         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
1157       }
1158     }
1159   }
1160   break;
1161 
1162   case PragTyp_INDEX_LIST: if( zRight ){
1163     Index *pIdx;
1164     Table *pTab;
1165     int i;
1166     pTab = sqlite3FindTable(db, zRight, zDb);
1167     if( pTab ){
1168       static const char *azCol[] = {
1169         "seq", "name", "unique", "origin", "partial"
1170       };
1171       v = sqlite3GetVdbe(pParse);
1172       pParse->nMem = 5;
1173       sqlite3CodeVerifySchema(pParse, iDb);
1174       setAllColumnNames(v, 5, azCol);  assert( 5==ArraySize(azCol) );
1175       for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
1176         const char *azOrigin[] = { "c", "u", "pk" };
1177         sqlite3VdbeMultiLoad(v, 1, "isisi",
1178            i,
1179            pIdx->zName,
1180            IsUniqueIndex(pIdx),
1181            azOrigin[pIdx->idxType],
1182            pIdx->pPartIdxWhere!=0);
1183         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
1184       }
1185     }
1186   }
1187   break;
1188 
1189   case PragTyp_DATABASE_LIST: {
1190     static const char *azCol[] = { "seq", "name", "file" };
1191     int i;
1192     pParse->nMem = 3;
1193     setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
1194     for(i=0; i<db->nDb; i++){
1195       if( db->aDb[i].pBt==0 ) continue;
1196       assert( db->aDb[i].zName!=0 );
1197       sqlite3VdbeMultiLoad(v, 1, "iss",
1198          i,
1199          db->aDb[i].zName,
1200          sqlite3BtreeGetFilename(db->aDb[i].pBt));
1201       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
1202     }
1203   }
1204   break;
1205 
1206   case PragTyp_COLLATION_LIST: {
1207     static const char *azCol[] = { "seq", "name" };
1208     int i = 0;
1209     HashElem *p;
1210     pParse->nMem = 2;
1211     setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
1212     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
1213       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
1214       sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
1215       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
1216     }
1217   }
1218   break;
1219 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
1220 
1221 #ifndef SQLITE_OMIT_FOREIGN_KEY
1222   case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
1223     FKey *pFK;
1224     Table *pTab;
1225     pTab = sqlite3FindTable(db, zRight, zDb);
1226     if( pTab ){
1227       v = sqlite3GetVdbe(pParse);
1228       pFK = pTab->pFKey;
1229       if( pFK ){
1230         static const char *azCol[] = {
1231            "id", "seq", "table", "from", "to", "on_update", "on_delete",
1232            "match"
1233         };
1234         int i = 0;
1235         pParse->nMem = 8;
1236         sqlite3CodeVerifySchema(pParse, iDb);
1237         setAllColumnNames(v, 8, azCol); assert( 8==ArraySize(azCol) );
1238         while(pFK){
1239           int j;
1240           for(j=0; j<pFK->nCol; j++){
1241             sqlite3VdbeMultiLoad(v, 1, "iissssss",
1242                    i,
1243                    j,
1244                    pFK->zTo,
1245                    pTab->aCol[pFK->aCol[j].iFrom].zName,
1246                    pFK->aCol[j].zCol,
1247                    actionName(pFK->aAction[1]),  /* ON UPDATE */
1248                    actionName(pFK->aAction[0]),  /* ON DELETE */
1249                    "NONE");
1250             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
1251           }
1252           ++i;
1253           pFK = pFK->pNextFrom;
1254         }
1255       }
1256     }
1257   }
1258   break;
1259 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1260 
1261 #ifndef SQLITE_OMIT_FOREIGN_KEY
1262 #ifndef SQLITE_OMIT_TRIGGER
1263   case PragTyp_FOREIGN_KEY_CHECK: {
1264     FKey *pFK;             /* A foreign key constraint */
1265     Table *pTab;           /* Child table contain "REFERENCES" keyword */
1266     Table *pParent;        /* Parent table that child points to */
1267     Index *pIdx;           /* Index in the parent table */
1268     int i;                 /* Loop counter:  Foreign key number for pTab */
1269     int j;                 /* Loop counter:  Field of the foreign key */
1270     HashElem *k;           /* Loop counter:  Next table in schema */
1271     int x;                 /* result variable */
1272     int regResult;         /* 3 registers to hold a result row */
1273     int regKey;            /* Register to hold key for checking the FK */
1274     int regRow;            /* Registers to hold a row from pTab */
1275     int addrTop;           /* Top of a loop checking foreign keys */
1276     int addrOk;            /* Jump here if the key is OK */
1277     int *aiCols;           /* child to parent column mapping */
1278     static const char *azCol[] = { "table", "rowid", "parent", "fkid" };
1279 
1280     regResult = pParse->nMem+1;
1281     pParse->nMem += 4;
1282     regKey = ++pParse->nMem;
1283     regRow = ++pParse->nMem;
1284     v = sqlite3GetVdbe(pParse);
1285     setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) );
1286     sqlite3CodeVerifySchema(pParse, iDb);
1287     k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
1288     while( k ){
1289       if( zRight ){
1290         pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
1291         k = 0;
1292       }else{
1293         pTab = (Table*)sqliteHashData(k);
1294         k = sqliteHashNext(k);
1295       }
1296       if( pTab==0 || pTab->pFKey==0 ) continue;
1297       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
1298       if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
1299       sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
1300       sqlite3VdbeLoadString(v, regResult, pTab->zName);
1301       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
1302         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
1303         if( pParent==0 ) continue;
1304         pIdx = 0;
1305         sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
1306         x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
1307         if( x==0 ){
1308           if( pIdx==0 ){
1309             sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
1310           }else{
1311             sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
1312             sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1313           }
1314         }else{
1315           k = 0;
1316           break;
1317         }
1318       }
1319       assert( pParse->nErr>0 || pFK==0 );
1320       if( pFK ) break;
1321       if( pParse->nTab<i ) pParse->nTab = i;
1322       addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
1323       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
1324         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
1325         pIdx = 0;
1326         aiCols = 0;
1327         if( pParent ){
1328           x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
1329           assert( x==0 );
1330         }
1331         addrOk = sqlite3VdbeMakeLabel(v);
1332         if( pParent && pIdx==0 ){
1333           int iKey = pFK->aCol[0].iFrom;
1334           assert( iKey>=0 && iKey<pTab->nCol );
1335           if( iKey!=pTab->iPKey ){
1336             sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
1337             sqlite3ColumnDefault(v, pTab, iKey, regRow);
1338             sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
1339             sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
1340                sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
1341           }else{
1342             sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
1343           }
1344           sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
1345           sqlite3VdbeGoto(v, addrOk);
1346           sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1347         }else{
1348           for(j=0; j<pFK->nCol; j++){
1349             sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
1350                             aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
1351             sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
1352           }
1353           if( pParent ){
1354             sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
1355                               sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
1356             sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
1357             VdbeCoverage(v);
1358           }
1359         }
1360         sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
1361         sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1);
1362         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
1363         sqlite3VdbeResolveLabel(v, addrOk);
1364         sqlite3DbFree(db, aiCols);
1365       }
1366       sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
1367       sqlite3VdbeJumpHere(v, addrTop);
1368     }
1369   }
1370   break;
1371 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
1372 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1373 
1374 #ifndef NDEBUG
1375   case PragTyp_PARSER_TRACE: {
1376     if( zRight ){
1377       if( sqlite3GetBoolean(zRight, 0) ){
1378         sqlite3ParserTrace(stdout, "parser: ");
1379       }else{
1380         sqlite3ParserTrace(0, 0);
1381       }
1382     }
1383   }
1384   break;
1385 #endif
1386 
1387   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
1388   ** used will be case sensitive or not depending on the RHS.
1389   */
1390   case PragTyp_CASE_SENSITIVE_LIKE: {
1391     if( zRight ){
1392       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
1393     }
1394   }
1395   break;
1396 
1397 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
1398 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
1399 #endif
1400 
1401 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
1402   /* Pragma "quick_check" is reduced version of
1403   ** integrity_check designed to detect most database corruption
1404   ** without most of the overhead of a full integrity-check.
1405   */
1406   case PragTyp_INTEGRITY_CHECK: {
1407     int i, j, addr, mxErr;
1408 
1409     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
1410 
1411     /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
1412     ** then iDb is set to the index of the database identified by <db>.
1413     ** In this case, the integrity of database iDb only is verified by
1414     ** the VDBE created below.
1415     **
1416     ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
1417     ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
1418     ** to -1 here, to indicate that the VDBE should verify the integrity
1419     ** of all attached databases.  */
1420     assert( iDb>=0 );
1421     assert( iDb==0 || pId2->z );
1422     if( pId2->z==0 ) iDb = -1;
1423 
1424     /* Initialize the VDBE program */
1425     pParse->nMem = 6;
1426     setOneColumnName(v, "integrity_check");
1427 
1428     /* Set the maximum error count */
1429     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
1430     if( zRight ){
1431       sqlite3GetInt32(zRight, &mxErr);
1432       if( mxErr<=0 ){
1433         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
1434       }
1435     }
1436     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
1437 
1438     /* Do an integrity check on each database file */
1439     for(i=0; i<db->nDb; i++){
1440       HashElem *x;
1441       Hash *pTbls;
1442       int *aRoot;
1443       int cnt = 0;
1444       int mxIdx = 0;
1445       int nIdx;
1446 
1447       if( OMIT_TEMPDB && i==1 ) continue;
1448       if( iDb>=0 && i!=iDb ) continue;
1449 
1450       sqlite3CodeVerifySchema(pParse, i);
1451       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
1452       VdbeCoverage(v);
1453       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
1454       sqlite3VdbeJumpHere(v, addr);
1455 
1456       /* Do an integrity check of the B-Tree
1457       **
1458       ** Begin by finding the root pages numbers
1459       ** for all tables and indices in the database.
1460       */
1461       assert( sqlite3SchemaMutexHeld(db, i, 0) );
1462       pTbls = &db->aDb[i].pSchema->tblHash;
1463       for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
1464         Table *pTab = sqliteHashData(x);
1465         Index *pIdx;
1466         if( HasRowid(pTab) ) cnt++;
1467         for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
1468         if( nIdx>mxIdx ) mxIdx = nIdx;
1469       }
1470       aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
1471       if( aRoot==0 ) break;
1472       for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
1473         Table *pTab = sqliteHashData(x);
1474         Index *pIdx;
1475         if( HasRowid(pTab) ) aRoot[cnt++] = pTab->tnum;
1476         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1477           aRoot[cnt++] = pIdx->tnum;
1478         }
1479       }
1480       aRoot[cnt] = 0;
1481 
1482       /* Make sure sufficient number of registers have been allocated */
1483       pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
1484 
1485       /* Do the b-tree integrity checks */
1486       sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
1487       sqlite3VdbeChangeP5(v, (u8)i);
1488       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
1489       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
1490          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
1491          P4_DYNAMIC);
1492       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
1493       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
1494       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
1495       sqlite3VdbeJumpHere(v, addr);
1496 
1497       /* Make sure all the indices are constructed correctly.
1498       */
1499       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
1500         Table *pTab = sqliteHashData(x);
1501         Index *pIdx, *pPk;
1502         Index *pPrior = 0;
1503         int loopTop;
1504         int iDataCur, iIdxCur;
1505         int r1 = -1;
1506 
1507         if( pTab->pIndex==0 ) continue;
1508         pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
1509         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
1510         VdbeCoverage(v);
1511         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
1512         sqlite3VdbeJumpHere(v, addr);
1513         sqlite3ExprCacheClear(pParse);
1514         sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
1515                                    1, 0, &iDataCur, &iIdxCur);
1516         sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
1517         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
1518           sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
1519         }
1520         assert( pParse->nMem>=8+j );
1521         assert( sqlite3NoTempsInRange(pParse,1,7+j) );
1522         sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
1523         loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
1524         /* Verify that all NOT NULL columns really are NOT NULL */
1525         for(j=0; j<pTab->nCol; j++){
1526           char *zErr;
1527           int jmp2, jmp3;
1528           if( j==pTab->iPKey ) continue;
1529           if( pTab->aCol[j].notNull==0 ) continue;
1530           sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
1531           sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
1532           jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
1533           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
1534           zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
1535                               pTab->aCol[j].zName);
1536           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1537           sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
1538           jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
1539           sqlite3VdbeAddOp0(v, OP_Halt);
1540           sqlite3VdbeJumpHere(v, jmp2);
1541           sqlite3VdbeJumpHere(v, jmp3);
1542         }
1543         /* Validate index entries for the current row */
1544         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
1545           int jmp2, jmp3, jmp4, jmp5;
1546           int ckUniq = sqlite3VdbeMakeLabel(v);
1547           if( pPk==pIdx ) continue;
1548           r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
1549                                        pPrior, r1);
1550           pPrior = pIdx;
1551           sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);  /* increment entry count */
1552           /* Verify that an index entry exists for the current table row */
1553           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
1554                                       pIdx->nColumn); VdbeCoverage(v);
1555           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
1556           sqlite3VdbeLoadString(v, 3, "row ");
1557           sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
1558           sqlite3VdbeLoadString(v, 4, " missing from index ");
1559           sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
1560           jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
1561           sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
1562           sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
1563           jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
1564           sqlite3VdbeAddOp0(v, OP_Halt);
1565           sqlite3VdbeJumpHere(v, jmp2);
1566           /* For UNIQUE indexes, verify that only one entry exists with the
1567           ** current key.  The entry is unique if (1) any column is NULL
1568           ** or (2) the next entry has a different key */
1569           if( IsUniqueIndex(pIdx) ){
1570             int uniqOk = sqlite3VdbeMakeLabel(v);
1571             int jmp6;
1572             int kk;
1573             for(kk=0; kk<pIdx->nKeyCol; kk++){
1574               int iCol = pIdx->aiColumn[kk];
1575               assert( iCol!=XN_ROWID && iCol<pTab->nCol );
1576               if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
1577               sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
1578               VdbeCoverage(v);
1579             }
1580             jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
1581             sqlite3VdbeGoto(v, uniqOk);
1582             sqlite3VdbeJumpHere(v, jmp6);
1583             sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
1584                                  pIdx->nKeyCol); VdbeCoverage(v);
1585             sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
1586             sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
1587             sqlite3VdbeGoto(v, jmp5);
1588             sqlite3VdbeResolveLabel(v, uniqOk);
1589           }
1590           sqlite3VdbeJumpHere(v, jmp4);
1591           sqlite3ResolvePartIdxLabel(pParse, jmp3);
1592         }
1593         sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
1594         sqlite3VdbeJumpHere(v, loopTop-1);
1595 #ifndef SQLITE_OMIT_BTREECOUNT
1596         sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
1597         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
1598           if( pPk==pIdx ) continue;
1599           addr = sqlite3VdbeCurrentAddr(v);
1600           sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
1601           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
1602           sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
1603           sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
1604           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
1605           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
1606           sqlite3VdbeLoadString(v, 3, pIdx->zName);
1607           sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
1608           sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
1609         }
1610 #endif /* SQLITE_OMIT_BTREECOUNT */
1611       }
1612     }
1613     {
1614       static const int iLn = VDBE_OFFSET_LINENO(2);
1615       static const VdbeOpList endCode[] = {
1616         { OP_AddImm,      1, 0,        0},    /* 0 */
1617         { OP_If,          1, 4,        0},    /* 1 */
1618         { OP_String8,     0, 3,        0},    /* 2 */
1619         { OP_ResultRow,   3, 1,        0},    /* 3 */
1620       };
1621       VdbeOp *aOp;
1622 
1623       aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
1624       if( aOp ){
1625         aOp[0].p2 = -mxErr;
1626         aOp[2].p4type = P4_STATIC;
1627         aOp[2].p4.z = "ok";
1628       }
1629     }
1630   }
1631   break;
1632 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
1633 
1634 #ifndef SQLITE_OMIT_UTF16
1635   /*
1636   **   PRAGMA encoding
1637   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
1638   **
1639   ** In its first form, this pragma returns the encoding of the main
1640   ** database. If the database is not initialized, it is initialized now.
1641   **
1642   ** The second form of this pragma is a no-op if the main database file
1643   ** has not already been initialized. In this case it sets the default
1644   ** encoding that will be used for the main database file if a new file
1645   ** is created. If an existing main database file is opened, then the
1646   ** default text encoding for the existing database is used.
1647   **
1648   ** In all cases new databases created using the ATTACH command are
1649   ** created to use the same default text encoding as the main database. If
1650   ** the main database has not been initialized and/or created when ATTACH
1651   ** is executed, this is done before the ATTACH operation.
1652   **
1653   ** In the second form this pragma sets the text encoding to be used in
1654   ** new database files created using this database handle. It is only
1655   ** useful if invoked immediately after the main database i
1656   */
1657   case PragTyp_ENCODING: {
1658     static const struct EncName {
1659       char *zName;
1660       u8 enc;
1661     } encnames[] = {
1662       { "UTF8",     SQLITE_UTF8        },
1663       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
1664       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
1665       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
1666       { "UTF16le",  SQLITE_UTF16LE     },
1667       { "UTF16be",  SQLITE_UTF16BE     },
1668       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
1669       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
1670       { 0, 0 }
1671     };
1672     const struct EncName *pEnc;
1673     if( !zRight ){    /* "PRAGMA encoding" */
1674       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
1675       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
1676       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
1677       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
1678       returnSingleText(v, "encoding", encnames[ENC(pParse->db)].zName);
1679     }else{                        /* "PRAGMA encoding = XXX" */
1680       /* Only change the value of sqlite.enc if the database handle is not
1681       ** initialized. If the main database exists, the new sqlite.enc value
1682       ** will be overwritten when the schema is next loaded. If it does not
1683       ** already exists, it will be created to use the new encoding value.
1684       */
1685       if(
1686         !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
1687         DbHasProperty(db, 0, DB_Empty)
1688       ){
1689         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
1690           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
1691             SCHEMA_ENC(db) = ENC(db) =
1692                 pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
1693             break;
1694           }
1695         }
1696         if( !pEnc->zName ){
1697           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
1698         }
1699       }
1700     }
1701   }
1702   break;
1703 #endif /* SQLITE_OMIT_UTF16 */
1704 
1705 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
1706   /*
1707   **   PRAGMA [schema.]schema_version
1708   **   PRAGMA [schema.]schema_version = <integer>
1709   **
1710   **   PRAGMA [schema.]user_version
1711   **   PRAGMA [schema.]user_version = <integer>
1712   **
1713   **   PRAGMA [schema.]freelist_count
1714   **
1715   **   PRAGMA [schema.]data_version
1716   **
1717   **   PRAGMA [schema.]application_id
1718   **   PRAGMA [schema.]application_id = <integer>
1719   **
1720   ** The pragma's schema_version and user_version are used to set or get
1721   ** the value of the schema-version and user-version, respectively. Both
1722   ** the schema-version and the user-version are 32-bit signed integers
1723   ** stored in the database header.
1724   **
1725   ** The schema-cookie is usually only manipulated internally by SQLite. It
1726   ** is incremented by SQLite whenever the database schema is modified (by
1727   ** creating or dropping a table or index). The schema version is used by
1728   ** SQLite each time a query is executed to ensure that the internal cache
1729   ** of the schema used when compiling the SQL query matches the schema of
1730   ** the database against which the compiled query is actually executed.
1731   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
1732   ** the schema-version is potentially dangerous and may lead to program
1733   ** crashes or database corruption. Use with caution!
1734   **
1735   ** The user-version is not used internally by SQLite. It may be used by
1736   ** applications for any purpose.
1737   */
1738   case PragTyp_HEADER_VALUE: {
1739     int iCookie = pPragma->iArg;  /* Which cookie to read or write */
1740     sqlite3VdbeUsesBtree(v, iDb);
1741     if( zRight && (pPragma->mPragFlag & PragFlag_ReadOnly)==0 ){
1742       /* Write the specified cookie value */
1743       static const VdbeOpList setCookie[] = {
1744         { OP_Transaction,    0,  1,  0},    /* 0 */
1745         { OP_SetCookie,      0,  0,  0},    /* 1 */
1746       };
1747       VdbeOp *aOp;
1748       sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
1749       aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
1750       if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
1751       aOp[0].p1 = iDb;
1752       aOp[1].p1 = iDb;
1753       aOp[1].p2 = iCookie;
1754       aOp[1].p3 = sqlite3Atoi(zRight);
1755     }else{
1756       /* Read the specified cookie value */
1757       static const VdbeOpList readCookie[] = {
1758         { OP_Transaction,     0,  0,  0},    /* 0 */
1759         { OP_ReadCookie,      0,  1,  0},    /* 1 */
1760         { OP_ResultRow,       1,  1,  0}
1761       };
1762       VdbeOp *aOp;
1763       sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
1764       aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
1765       if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
1766       aOp[0].p1 = iDb;
1767       aOp[1].p1 = iDb;
1768       aOp[1].p3 = iCookie;
1769       sqlite3VdbeSetNumCols(v, 1);
1770       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
1771       sqlite3VdbeReusable(v);
1772     }
1773   }
1774   break;
1775 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
1776 
1777 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
1778   /*
1779   **   PRAGMA compile_options
1780   **
1781   ** Return the names of all compile-time options used in this build,
1782   ** one option per row.
1783   */
1784   case PragTyp_COMPILE_OPTIONS: {
1785     int i = 0;
1786     const char *zOpt;
1787     pParse->nMem = 1;
1788     setOneColumnName(v, "compile_option");
1789     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
1790       sqlite3VdbeLoadString(v, 1, zOpt);
1791       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
1792     }
1793     sqlite3VdbeReusable(v);
1794   }
1795   break;
1796 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
1797 
1798 #ifndef SQLITE_OMIT_WAL
1799   /*
1800   **   PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
1801   **
1802   ** Checkpoint the database.
1803   */
1804   case PragTyp_WAL_CHECKPOINT: {
1805     static const char *azCol[] = { "busy", "log", "checkpointed" };
1806     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
1807     int eMode = SQLITE_CHECKPOINT_PASSIVE;
1808     if( zRight ){
1809       if( sqlite3StrICmp(zRight, "full")==0 ){
1810         eMode = SQLITE_CHECKPOINT_FULL;
1811       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
1812         eMode = SQLITE_CHECKPOINT_RESTART;
1813       }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
1814         eMode = SQLITE_CHECKPOINT_TRUNCATE;
1815       }
1816     }
1817     setAllColumnNames(v, 3, azCol);  assert( 3==ArraySize(azCol) );
1818     pParse->nMem = 3;
1819     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
1820     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
1821   }
1822   break;
1823 
1824   /*
1825   **   PRAGMA wal_autocheckpoint
1826   **   PRAGMA wal_autocheckpoint = N
1827   **
1828   ** Configure a database connection to automatically checkpoint a database
1829   ** after accumulating N frames in the log. Or query for the current value
1830   ** of N.
1831   */
1832   case PragTyp_WAL_AUTOCHECKPOINT: {
1833     if( zRight ){
1834       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
1835     }
1836     returnSingleInt(v, "wal_autocheckpoint",
1837        db->xWalCallback==sqlite3WalDefaultHook ?
1838            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
1839   }
1840   break;
1841 #endif
1842 
1843   /*
1844   **  PRAGMA shrink_memory
1845   **
1846   ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
1847   ** connection on which it is invoked to free up as much memory as it
1848   ** can, by calling sqlite3_db_release_memory().
1849   */
1850   case PragTyp_SHRINK_MEMORY: {
1851     sqlite3_db_release_memory(db);
1852     break;
1853   }
1854 
1855   /*
1856   **   PRAGMA busy_timeout
1857   **   PRAGMA busy_timeout = N
1858   **
1859   ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
1860   ** if one is set.  If no busy handler or a different busy handler is set
1861   ** then 0 is returned.  Setting the busy_timeout to 0 or negative
1862   ** disables the timeout.
1863   */
1864   /*case PragTyp_BUSY_TIMEOUT*/ default: {
1865     assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
1866     if( zRight ){
1867       sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
1868     }
1869     returnSingleInt(v, "timeout",  db->busyTimeout);
1870     break;
1871   }
1872 
1873   /*
1874   **   PRAGMA soft_heap_limit
1875   **   PRAGMA soft_heap_limit = N
1876   **
1877   ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
1878   ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
1879   ** specified and is a non-negative integer.
1880   ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
1881   ** returns the same integer that would be returned by the
1882   ** sqlite3_soft_heap_limit64(-1) C-language function.
1883   */
1884   case PragTyp_SOFT_HEAP_LIMIT: {
1885     sqlite3_int64 N;
1886     if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
1887       sqlite3_soft_heap_limit64(N);
1888     }
1889     returnSingleInt(v, "soft_heap_limit",  sqlite3_soft_heap_limit64(-1));
1890     break;
1891   }
1892 
1893   /*
1894   **   PRAGMA threads
1895   **   PRAGMA threads = N
1896   **
1897   ** Configure the maximum number of worker threads.  Return the new
1898   ** maximum, which might be less than requested.
1899   */
1900   case PragTyp_THREADS: {
1901     sqlite3_int64 N;
1902     if( zRight
1903      && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
1904      && N>=0
1905     ){
1906       sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
1907     }
1908     returnSingleInt(v, "threads",
1909                     sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
1910     break;
1911   }
1912 
1913 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
1914   /*
1915   ** Report the current state of file logs for all databases
1916   */
1917   case PragTyp_LOCK_STATUS: {
1918     static const char *const azLockName[] = {
1919       "unlocked", "shared", "reserved", "pending", "exclusive"
1920     };
1921     static const char *azCol[] = { "database", "status" };
1922     int i;
1923     setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
1924     pParse->nMem = 2;
1925     for(i=0; i<db->nDb; i++){
1926       Btree *pBt;
1927       const char *zState = "unknown";
1928       int j;
1929       if( db->aDb[i].zName==0 ) continue;
1930       pBt = db->aDb[i].pBt;
1931       if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
1932         zState = "closed";
1933       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
1934                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
1935          zState = azLockName[j];
1936       }
1937       sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zName, zState);
1938       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
1939     }
1940     break;
1941   }
1942 #endif
1943 
1944 #ifdef SQLITE_HAS_CODEC
1945   case PragTyp_KEY: {
1946     if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
1947     break;
1948   }
1949   case PragTyp_REKEY: {
1950     if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
1951     break;
1952   }
1953   case PragTyp_HEXKEY: {
1954     if( zRight ){
1955       u8 iByte;
1956       int i;
1957       char zKey[40];
1958       for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
1959         iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
1960         if( (i&1)!=0 ) zKey[i/2] = iByte;
1961       }
1962       if( (zLeft[3] & 0xf)==0xb ){
1963         sqlite3_key_v2(db, zDb, zKey, i/2);
1964       }else{
1965         sqlite3_rekey_v2(db, zDb, zKey, i/2);
1966       }
1967     }
1968     break;
1969   }
1970 #endif
1971 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
1972   case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
1973 #ifdef SQLITE_HAS_CODEC
1974     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
1975       sqlite3_activate_see(&zRight[4]);
1976     }
1977 #endif
1978 #ifdef SQLITE_ENABLE_CEROD
1979     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
1980       sqlite3_activate_cerod(&zRight[6]);
1981     }
1982 #endif
1983   }
1984   break;
1985 #endif
1986 
1987   } /* End of the PRAGMA switch */
1988 
1989 pragma_out:
1990   sqlite3DbFree(db, zLeft);
1991   sqlite3DbFree(db, zRight);
1992 }
1993 
1994 #endif /* SQLITE_OMIT_PRAGMA */
1995