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