4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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
20 # define SQLITE_ENABLE_LOCKING_STYLE 0
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. */
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 */
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)
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
){
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
){
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
;
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' ){
116 }else if( sqlite3StrICmp(z
, "file")==0 ){
118 }else if( sqlite3StrICmp(z
, "memory")==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
|| sqlite3BtreeIsInReadTrans(db
->aDb
[1].pBt
) ){
135 sqlite3ErrorMsg(pParse
, "temporary storage cannot be changed "
136 "from within a transaction");
139 sqlite3BtreeClose(db
->aDb
[1].pBt
);
141 sqlite3ResetAllSchemasOfConnection(db
);
145 #endif /* SQLITE_PAGER_PRAGMAS */
147 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
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.
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
){
160 db
->temp_store
= (u8
)ts
;
163 #endif /* SQLITE_PAGER_PRAGMAS */
166 ** Set result column names for a pragma.
168 static void setPragmaResultColumnNames(
169 Vdbe
*v
, /* The query under construction */
170 const PragmaName
*pPragma
/* The pragma */
172 u8 n
= pPragma
->nPragCName
;
173 sqlite3VdbeSetNumCols(v
, n
==0 ? 1 : n
);
175 sqlite3VdbeSetColName(v
, 0, COLNAME_NAME
, pPragma
->zName
, SQLITE_STATIC
);
178 for(i
=0, j
=pPragma
->iPragCName
; i
<n
; i
++, j
++){
179 sqlite3VdbeSetColName(v
, i
, COLNAME_NAME
, pragCName
[j
], SQLITE_STATIC
);
185 ** Generate code to return a single integer value.
187 static void returnSingleInt(Vdbe
*v
, i64 value
){
188 sqlite3VdbeAddOp4Dup8(v
, OP_Int64
, 0, 1, 0, (const u8
*)&value
, P4_INT64
);
189 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, 1);
193 ** Generate code to return a single text value.
195 static void returnSingleText(
196 Vdbe
*v
, /* Prepared statement under construction */
197 const char *zValue
/* Value to be returned */
200 sqlite3VdbeLoadString(v
, 1, (const char*)zValue
);
201 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, 1);
207 ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
208 ** set these values for all pagers.
210 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
211 static void setAllPagerFlags(sqlite3
*db
){
212 if( db
->autoCommit
){
215 assert( SQLITE_FullFSync
==PAGER_FULLFSYNC
);
216 assert( SQLITE_CkptFullFSync
==PAGER_CKPT_FULLFSYNC
);
217 assert( SQLITE_CacheSpill
==PAGER_CACHESPILL
);
218 assert( (PAGER_FULLFSYNC
| PAGER_CKPT_FULLFSYNC
| PAGER_CACHESPILL
)
219 == PAGER_FLAGS_MASK
);
220 assert( (pDb
->safety_level
& PAGER_SYNCHRONOUS_MASK
)==pDb
->safety_level
);
223 sqlite3BtreeSetPagerFlags(pDb
->pBt
,
224 pDb
->safety_level
| (db
->flags
& PAGER_FLAGS_MASK
) );
231 # define setAllPagerFlags(X) /* no-op */
236 ** Return a human-readable name for a constraint resolution action.
238 #ifndef SQLITE_OMIT_FOREIGN_KEY
239 static const char *actionName(u8 action
){
242 case OE_SetNull
: zName
= "SET NULL"; break;
243 case OE_SetDflt
: zName
= "SET DEFAULT"; break;
244 case OE_Cascade
: zName
= "CASCADE"; break;
245 case OE_Restrict
: zName
= "RESTRICT"; break;
246 default: zName
= "NO ACTION";
247 assert( action
==OE_None
); break;
255 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
256 ** defined in pager.h. This function returns the associated lowercase
257 ** journal-mode name.
259 const char *sqlite3JournalModename(int eMode
){
260 static char * const azModeName
[] = {
261 "delete", "persist", "off", "truncate", "memory"
262 #ifndef SQLITE_OMIT_WAL
266 assert( PAGER_JOURNALMODE_DELETE
==0 );
267 assert( PAGER_JOURNALMODE_PERSIST
==1 );
268 assert( PAGER_JOURNALMODE_OFF
==2 );
269 assert( PAGER_JOURNALMODE_TRUNCATE
==3 );
270 assert( PAGER_JOURNALMODE_MEMORY
==4 );
271 assert( PAGER_JOURNALMODE_WAL
==5 );
272 assert( eMode
>=0 && eMode
<=ArraySize(azModeName
) );
274 if( eMode
==ArraySize(azModeName
) ) return 0;
275 return azModeName
[eMode
];
279 ** Locate a pragma in the aPragmaName[] array.
281 static const PragmaName
*pragmaLocate(const char *zName
){
282 int upr
, lwr
, mid
= 0, rc
;
284 upr
= ArraySize(aPragmaName
)-1;
287 rc
= sqlite3_stricmp(zName
, aPragmaName
[mid
].zName
);
295 return lwr
>upr
? 0 : &aPragmaName
[mid
];
299 ** Create zero or more entries in the output for the SQL functions
300 ** defined by FuncDef p.
302 static void pragmaFunclistLine(
303 Vdbe
*v
, /* The prepared statement being created */
304 FuncDef
*p
, /* A particular function definition */
305 int isBuiltin
, /* True if this is a built-in function */
306 int showInternFuncs
/* True if showing internal functions */
308 for(; p
; p
=p
->pNext
){
310 static const u32 mask
=
311 SQLITE_DETERMINISTIC
|
317 static const char *azEnc
[] = { 0, "utf8", "utf16le", "utf16be" };
319 assert( SQLITE_FUNC_ENCMASK
==0x3 );
320 assert( strcmp(azEnc
[SQLITE_UTF8
],"utf8")==0 );
321 assert( strcmp(azEnc
[SQLITE_UTF16LE
],"utf16le")==0 );
322 assert( strcmp(azEnc
[SQLITE_UTF16BE
],"utf16be")==0 );
324 if( p
->xSFunc
==0 ) continue;
325 if( (p
->funcFlags
& SQLITE_FUNC_INTERNAL
)!=0
326 && showInternFuncs
==0
332 }else if( p
->xFinalize
!=0 ){
337 sqlite3VdbeMultiLoad(v
, 1, "sissii",
339 zType
, azEnc
[p
->funcFlags
&SQLITE_FUNC_ENCMASK
],
341 (p
->funcFlags
& mask
) ^ SQLITE_INNOCUOUS
348 ** Helper subroutine for PRAGMA integrity_check:
350 ** Generate code to output a single-column result row with a value of the
351 ** string held in register 3. Decrement the result count in register 1
352 ** and halt if the maximum number of result rows have been issued.
354 static int integrityCheckResultRow(Vdbe
*v
){
356 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 3, 1);
357 addr
= sqlite3VdbeAddOp3(v
, OP_IfPos
, 1, sqlite3VdbeCurrentAddr(v
)+2, 1);
359 sqlite3VdbeAddOp0(v
, OP_Halt
);
364 ** Process a pragma statement.
366 ** Pragmas are of this form:
368 ** PRAGMA [schema.]id [= value]
370 ** The identifier might also be a string. The value is a string, and
371 ** identifier, or a number. If minusFlag is true, then the value is
372 ** a number that was preceded by a minus sign.
374 ** If the left side is "database.id" then pId1 is the database name
375 ** and pId2 is the id. If the left side is just "id" then pId1 is the
376 ** id and pId2 is any empty string.
380 Token
*pId1
, /* First part of [schema.]id field */
381 Token
*pId2
, /* Second part of [schema.]id field, or NULL */
382 Token
*pValue
, /* Token for <value>, or NULL */
383 int minusFlag
/* True if a '-' sign preceded <value> */
385 char *zLeft
= 0; /* Nul-terminated UTF-8 string <id> */
386 char *zRight
= 0; /* Nul-terminated UTF-8 string <value>, or NULL */
387 const char *zDb
= 0; /* The database name */
388 Token
*pId
; /* Pointer to <id> token */
389 char *aFcntl
[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
390 int iDb
; /* Database index for <database> */
391 int rc
; /* return value form SQLITE_FCNTL_PRAGMA */
392 sqlite3
*db
= pParse
->db
; /* The database connection */
393 Db
*pDb
; /* The specific database being pragmaed */
394 Vdbe
*v
= sqlite3GetVdbe(pParse
); /* Prepared statement */
395 const PragmaName
*pPragma
; /* The pragma */
396 /* BEGIN SQLCIPHER */
397 #ifdef SQLITE_HAS_CODEC
398 extern int sqlcipher_codec_pragma(sqlite3
*, int, Parse
*, const char *, const char *);
403 sqlite3VdbeRunOnlyOnce(v
);
406 /* Interpret the [schema.] part of the pragma statement. iDb is the
407 ** index of the database this pragma is being applied to in db.aDb[]. */
408 iDb
= sqlite3TwoPartName(pParse
, pId1
, pId2
, &pId
);
412 /* If the temp database has been explicitly named as part of the
413 ** pragma, make sure it is open.
415 if( iDb
==1 && sqlite3OpenTempDatabase(pParse
) ){
419 zLeft
= sqlite3NameFromToken(db
, pId
);
422 zRight
= sqlite3MPrintf(db
, "-%T", pValue
);
424 zRight
= sqlite3NameFromToken(db
, pValue
);
428 zDb
= pId2
->n
>0 ? pDb
->zDbSName
: 0;
429 if( sqlite3AuthCheck(pParse
, SQLITE_PRAGMA
, zLeft
, zRight
, zDb
) ){
433 /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
434 ** connection. If it returns SQLITE_OK, then assume that the VFS
435 ** handled the pragma and generate a no-op prepared statement.
437 ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
438 ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
439 ** object corresponding to the database file to which the pragma
442 ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
443 ** file control is an array of pointers to strings (char**) in which the
444 ** second element of the array is the name of the pragma and the third
445 ** element is the argument to the pragma or NULL if the pragma has no
452 db
->busyHandler
.nBusy
= 0;
453 rc
= sqlite3_file_control(db
, zDb
, SQLITE_FCNTL_PRAGMA
, (void*)aFcntl
);
455 sqlite3VdbeSetNumCols(v
, 1);
456 sqlite3VdbeSetColName(v
, 0, COLNAME_NAME
, aFcntl
[0], SQLITE_TRANSIENT
);
457 returnSingleText(v
, aFcntl
[0]);
458 sqlite3_free(aFcntl
[0]);
461 if( rc
!=SQLITE_NOTFOUND
){
463 sqlite3ErrorMsg(pParse
, "%s", aFcntl
[0]);
464 sqlite3_free(aFcntl
[0]);
472 /* BEGIN SQLCIPHER */
473 #ifdef SQLITE_HAS_CODEC
474 if(sqlcipher_codec_pragma(db
, iDb
, pParse
, zLeft
, zRight
)) {
475 /* sqlcipher_codec_pragma executes internal */
481 /* Locate the pragma in the lookup table */
482 pPragma
= pragmaLocate(zLeft
);
483 if( pPragma
==0 ) goto pragma_out
;
485 /* Make sure the database schema is loaded if the pragma requires that */
486 if( (pPragma
->mPragFlg
& PragFlg_NeedSchema
)!=0 ){
487 if( sqlite3ReadSchema(pParse
) ) goto pragma_out
;
490 /* Register the result column names for pragmas that return results */
491 if( (pPragma
->mPragFlg
& PragFlg_NoColumns
)==0
492 && ((pPragma
->mPragFlg
& PragFlg_NoColumns1
)==0 || zRight
==0)
494 setPragmaResultColumnNames(v
, pPragma
);
497 /* Jump to the appropriate pragma handler */
498 switch( pPragma
->ePragTyp
){
500 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
502 ** PRAGMA [schema.]default_cache_size
503 ** PRAGMA [schema.]default_cache_size=N
505 ** The first form reports the current persistent setting for the
506 ** page cache size. The value returned is the maximum number of
507 ** pages in the page cache. The second form sets both the current
508 ** page cache size value and the persistent page cache size value
509 ** stored in the database file.
511 ** Older versions of SQLite would set the default cache size to a
512 ** negative number to indicate synchronous=OFF. These days, synchronous
513 ** is always on by default regardless of the sign of the default cache
514 ** size. But continue to take the absolute value of the default cache
515 ** size of historical compatibility.
517 case PragTyp_DEFAULT_CACHE_SIZE
: {
518 static const int iLn
= VDBE_OFFSET_LINENO(2);
519 static const VdbeOpList getCacheSize
[] = {
520 { OP_Transaction
, 0, 0, 0}, /* 0 */
521 { OP_ReadCookie
, 0, 1, BTREE_DEFAULT_CACHE_SIZE
}, /* 1 */
522 { OP_IfPos
, 1, 8, 0},
523 { OP_Integer
, 0, 2, 0},
524 { OP_Subtract
, 1, 2, 1},
525 { OP_IfPos
, 1, 8, 0},
526 { OP_Integer
, 0, 1, 0}, /* 6 */
528 { OP_ResultRow
, 1, 1, 0},
531 sqlite3VdbeUsesBtree(v
, iDb
);
534 sqlite3VdbeVerifyNoMallocRequired(v
, ArraySize(getCacheSize
));
535 aOp
= sqlite3VdbeAddOpList(v
, ArraySize(getCacheSize
), getCacheSize
, iLn
);
536 if( ONLY_IF_REALLOC_STRESS(aOp
==0) ) break;
539 aOp
[6].p1
= SQLITE_DEFAULT_CACHE_SIZE
;
541 int size
= sqlite3AbsInt32(sqlite3Atoi(zRight
));
542 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
543 sqlite3VdbeAddOp3(v
, OP_SetCookie
, iDb
, BTREE_DEFAULT_CACHE_SIZE
, size
);
544 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
545 pDb
->pSchema
->cache_size
= size
;
546 sqlite3BtreeSetCacheSize(pDb
->pBt
, pDb
->pSchema
->cache_size
);
550 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
552 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
554 ** PRAGMA [schema.]page_size
555 ** PRAGMA [schema.]page_size=N
557 ** The first form reports the current setting for the
558 ** database page size in bytes. The second form sets the
559 ** database page size value. The value can only be set if
560 ** the database has not yet been created.
562 case PragTyp_PAGE_SIZE
: {
563 Btree
*pBt
= pDb
->pBt
;
566 int size
= ALWAYS(pBt
) ? sqlite3BtreeGetPageSize(pBt
) : 0;
567 returnSingleInt(v
, size
);
569 /* Malloc may fail when setting the page-size, as there is an internal
570 ** buffer that the pager module resizes using sqlite3_realloc().
572 db
->nextPagesize
= sqlite3Atoi(zRight
);
573 if( SQLITE_NOMEM
==sqlite3BtreeSetPageSize(pBt
, db
->nextPagesize
,0,0) ){
581 ** PRAGMA [schema.]secure_delete
582 ** PRAGMA [schema.]secure_delete=ON/OFF/FAST
584 ** The first form reports the current setting for the
585 ** secure_delete flag. The second form changes the secure_delete
586 ** flag setting and reports the new value.
588 case PragTyp_SECURE_DELETE
: {
589 Btree
*pBt
= pDb
->pBt
;
593 if( sqlite3_stricmp(zRight
, "fast")==0 ){
596 b
= sqlite3GetBoolean(zRight
, 0);
599 if( pId2
->n
==0 && b
>=0 ){
601 for(ii
=0; ii
<db
->nDb
; ii
++){
602 sqlite3BtreeSecureDelete(db
->aDb
[ii
].pBt
, b
);
605 b
= sqlite3BtreeSecureDelete(pBt
, b
);
606 returnSingleInt(v
, b
);
611 ** PRAGMA [schema.]max_page_count
612 ** PRAGMA [schema.]max_page_count=N
614 ** The first form reports the current setting for the
615 ** maximum number of pages in the database file. The
616 ** second form attempts to change this setting. Both
617 ** forms return the current setting.
619 ** The absolute value of N is used. This is undocumented and might
620 ** change. The only purpose is to provide an easy way to test
621 ** the sqlite3AbsInt32() function.
623 ** PRAGMA [schema.]page_count
625 ** Return the number of pages in the specified database.
627 case PragTyp_PAGE_COUNT
: {
629 sqlite3CodeVerifySchema(pParse
, iDb
);
630 iReg
= ++pParse
->nMem
;
631 if( sqlite3Tolower(zLeft
[0])=='p' ){
632 sqlite3VdbeAddOp2(v
, OP_Pagecount
, iDb
, iReg
);
634 sqlite3VdbeAddOp3(v
, OP_MaxPgcnt
, iDb
, iReg
,
635 sqlite3AbsInt32(sqlite3Atoi(zRight
)));
637 sqlite3VdbeAddOp2(v
, OP_ResultRow
, iReg
, 1);
642 ** PRAGMA [schema.]locking_mode
643 ** PRAGMA [schema.]locking_mode = (normal|exclusive)
645 case PragTyp_LOCKING_MODE
: {
646 const char *zRet
= "normal";
647 int eMode
= getLockingMode(zRight
);
649 if( pId2
->n
==0 && eMode
==PAGER_LOCKINGMODE_QUERY
){
650 /* Simple "PRAGMA locking_mode;" statement. This is a query for
651 ** the current default locking mode (which may be different to
652 ** the locking-mode of the main database).
654 eMode
= db
->dfltLockMode
;
658 /* This indicates that no database name was specified as part
659 ** of the PRAGMA command. In this case the locking-mode must be
660 ** set on all attached databases, as well as the main db file.
662 ** Also, the sqlite3.dfltLockMode variable is set so that
663 ** any subsequently attached databases also use the specified
667 assert(pDb
==&db
->aDb
[0]);
668 for(ii
=2; ii
<db
->nDb
; ii
++){
669 pPager
= sqlite3BtreePager(db
->aDb
[ii
].pBt
);
670 sqlite3PagerLockingMode(pPager
, eMode
);
672 db
->dfltLockMode
= (u8
)eMode
;
674 pPager
= sqlite3BtreePager(pDb
->pBt
);
675 eMode
= sqlite3PagerLockingMode(pPager
, eMode
);
678 assert( eMode
==PAGER_LOCKINGMODE_NORMAL
679 || eMode
==PAGER_LOCKINGMODE_EXCLUSIVE
);
680 if( eMode
==PAGER_LOCKINGMODE_EXCLUSIVE
){
683 returnSingleText(v
, zRet
);
688 ** PRAGMA [schema.]journal_mode
689 ** PRAGMA [schema.]journal_mode =
690 ** (delete|persist|off|truncate|memory|wal|off)
692 case PragTyp_JOURNAL_MODE
: {
693 int eMode
; /* One of the PAGER_JOURNALMODE_XXX symbols */
694 int ii
; /* Loop counter */
697 /* If there is no "=MODE" part of the pragma, do a query for the
699 eMode
= PAGER_JOURNALMODE_QUERY
;
702 int n
= sqlite3Strlen30(zRight
);
703 for(eMode
=0; (zMode
= sqlite3JournalModename(eMode
))!=0; eMode
++){
704 if( sqlite3StrNICmp(zRight
, zMode
, n
)==0 ) break;
707 /* If the "=MODE" part does not match any known journal mode,
708 ** then do a query */
709 eMode
= PAGER_JOURNALMODE_QUERY
;
711 if( eMode
==PAGER_JOURNALMODE_OFF
&& (db
->flags
& SQLITE_Defensive
)!=0 ){
712 /* Do not allow journal-mode "OFF" in defensive since the database
713 ** can become corrupted using ordinary SQL when the journal is off */
714 eMode
= PAGER_JOURNALMODE_QUERY
;
717 if( eMode
==PAGER_JOURNALMODE_QUERY
&& pId2
->n
==0 ){
718 /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
722 for(ii
=db
->nDb
-1; ii
>=0; ii
--){
723 if( db
->aDb
[ii
].pBt
&& (ii
==iDb
|| pId2
->n
==0) ){
724 sqlite3VdbeUsesBtree(v
, ii
);
725 sqlite3VdbeAddOp3(v
, OP_JournalMode
, ii
, 1, eMode
);
728 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, 1);
733 ** PRAGMA [schema.]journal_size_limit
734 ** PRAGMA [schema.]journal_size_limit=N
736 ** Get or set the size limit on rollback journal files.
738 case PragTyp_JOURNAL_SIZE_LIMIT
: {
739 Pager
*pPager
= sqlite3BtreePager(pDb
->pBt
);
742 sqlite3DecOrHexToI64(zRight
, &iLimit
);
743 if( iLimit
<-1 ) iLimit
= -1;
745 iLimit
= sqlite3PagerJournalSizeLimit(pPager
, iLimit
);
746 returnSingleInt(v
, iLimit
);
750 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
753 ** PRAGMA [schema.]auto_vacuum
754 ** PRAGMA [schema.]auto_vacuum=N
756 ** Get or set the value of the database 'auto-vacuum' parameter.
757 ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
759 #ifndef SQLITE_OMIT_AUTOVACUUM
760 case PragTyp_AUTO_VACUUM
: {
761 Btree
*pBt
= pDb
->pBt
;
764 returnSingleInt(v
, sqlite3BtreeGetAutoVacuum(pBt
));
766 int eAuto
= getAutoVacuum(zRight
);
767 assert( eAuto
>=0 && eAuto
<=2 );
768 db
->nextAutovac
= (u8
)eAuto
;
769 /* Call SetAutoVacuum() to set initialize the internal auto and
770 ** incr-vacuum flags. This is required in case this connection
771 ** creates the database file. It is important that it is created
772 ** as an auto-vacuum capable db.
774 rc
= sqlite3BtreeSetAutoVacuum(pBt
, eAuto
);
775 if( rc
==SQLITE_OK
&& (eAuto
==1 || eAuto
==2) ){
776 /* When setting the auto_vacuum mode to either "full" or
777 ** "incremental", write the value of meta[6] in the database
778 ** file. Before writing to meta[6], check that meta[3] indicates
779 ** that this really is an auto-vacuum capable database.
781 static const int iLn
= VDBE_OFFSET_LINENO(2);
782 static const VdbeOpList setMeta6
[] = {
783 { OP_Transaction
, 0, 1, 0}, /* 0 */
784 { OP_ReadCookie
, 0, 1, BTREE_LARGEST_ROOT_PAGE
},
785 { OP_If
, 1, 0, 0}, /* 2 */
786 { OP_Halt
, SQLITE_OK
, OE_Abort
, 0}, /* 3 */
787 { OP_SetCookie
, 0, BTREE_INCR_VACUUM
, 0}, /* 4 */
790 int iAddr
= sqlite3VdbeCurrentAddr(v
);
791 sqlite3VdbeVerifyNoMallocRequired(v
, ArraySize(setMeta6
));
792 aOp
= sqlite3VdbeAddOpList(v
, ArraySize(setMeta6
), setMeta6
, iLn
);
793 if( ONLY_IF_REALLOC_STRESS(aOp
==0) ) break;
798 aOp
[4].p3
= eAuto
- 1;
799 sqlite3VdbeUsesBtree(v
, iDb
);
807 ** PRAGMA [schema.]incremental_vacuum(N)
809 ** Do N steps of incremental vacuuming on a database.
811 #ifndef SQLITE_OMIT_AUTOVACUUM
812 case PragTyp_INCREMENTAL_VACUUM
: {
814 if( zRight
==0 || !sqlite3GetInt32(zRight
, &iLimit
) || iLimit
<=0 ){
817 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
818 sqlite3VdbeAddOp2(v
, OP_Integer
, iLimit
, 1);
819 addr
= sqlite3VdbeAddOp1(v
, OP_IncrVacuum
, iDb
); VdbeCoverage(v
);
820 sqlite3VdbeAddOp1(v
, OP_ResultRow
, 1);
821 sqlite3VdbeAddOp2(v
, OP_AddImm
, 1, -1);
822 sqlite3VdbeAddOp2(v
, OP_IfPos
, 1, addr
); VdbeCoverage(v
);
823 sqlite3VdbeJumpHere(v
, addr
);
828 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
830 ** PRAGMA [schema.]cache_size
831 ** PRAGMA [schema.]cache_size=N
833 ** The first form reports the current local setting for the
834 ** page cache size. The second form sets the local
835 ** page cache size value. If N is positive then that is the
836 ** number of pages in the cache. If N is negative, then the
837 ** number of pages is adjusted so that the cache uses -N kibibytes
840 case PragTyp_CACHE_SIZE
: {
841 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
843 returnSingleInt(v
, pDb
->pSchema
->cache_size
);
845 int size
= sqlite3Atoi(zRight
);
846 pDb
->pSchema
->cache_size
= size
;
847 sqlite3BtreeSetCacheSize(pDb
->pBt
, pDb
->pSchema
->cache_size
);
853 ** PRAGMA [schema.]cache_spill
854 ** PRAGMA cache_spill=BOOLEAN
855 ** PRAGMA [schema.]cache_spill=N
857 ** The first form reports the current local setting for the
858 ** page cache spill size. The second form turns cache spill on
859 ** or off. When turnning cache spill on, the size is set to the
860 ** current cache_size. The third form sets a spill size that
861 ** may be different form the cache size.
862 ** If N is positive then that is the
863 ** number of pages in the cache. If N is negative, then the
864 ** number of pages is adjusted so that the cache uses -N kibibytes
867 ** If the number of cache_spill pages is less then the number of
868 ** cache_size pages, no spilling occurs until the page count exceeds
869 ** the number of cache_size pages.
871 ** The cache_spill=BOOLEAN setting applies to all attached schemas,
872 ** not just the schema specified.
874 case PragTyp_CACHE_SPILL
: {
875 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
878 (db
->flags
& SQLITE_CacheSpill
)==0 ? 0 :
879 sqlite3BtreeSetSpillSize(pDb
->pBt
,0));
882 if( sqlite3GetInt32(zRight
, &size
) ){
883 sqlite3BtreeSetSpillSize(pDb
->pBt
, size
);
885 if( sqlite3GetBoolean(zRight
, size
!=0) ){
886 db
->flags
|= SQLITE_CacheSpill
;
888 db
->flags
&= ~(u64
)SQLITE_CacheSpill
;
890 setAllPagerFlags(db
);
896 ** PRAGMA [schema.]mmap_size(N)
898 ** Used to set mapping size limit. The mapping size limit is
899 ** used to limit the aggregate size of all memory mapped regions of the
900 ** database file. If this parameter is set to zero, then memory mapping
901 ** is not used at all. If N is negative, then the default memory map
902 ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
903 ** The parameter N is measured in bytes.
905 ** This value is advisory. The underlying VFS is free to memory map
906 ** as little or as much as it wants. Except, if N is set to 0 then the
907 ** upper layers will never invoke the xFetch interfaces to the VFS.
909 case PragTyp_MMAP_SIZE
: {
911 #if SQLITE_MAX_MMAP_SIZE>0
912 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
915 sqlite3DecOrHexToI64(zRight
, &sz
);
916 if( sz
<0 ) sz
= sqlite3GlobalConfig
.szMmap
;
917 if( pId2
->n
==0 ) db
->szMmap
= sz
;
918 for(ii
=db
->nDb
-1; ii
>=0; ii
--){
919 if( db
->aDb
[ii
].pBt
&& (ii
==iDb
|| pId2
->n
==0) ){
920 sqlite3BtreeSetMmapLimit(db
->aDb
[ii
].pBt
, sz
);
925 rc
= sqlite3_file_control(db
, zDb
, SQLITE_FCNTL_MMAP_SIZE
, &sz
);
931 returnSingleInt(v
, sz
);
932 }else if( rc
!=SQLITE_NOTFOUND
){
941 ** PRAGMA temp_store = "default"|"memory"|"file"
943 ** Return or set the local value of the temp_store flag. Changing
944 ** the local value does not make changes to the disk file and the default
945 ** value will be restored the next time the database is opened.
947 ** Note that it is possible for the library compile-time options to
948 ** override this setting
950 case PragTyp_TEMP_STORE
: {
952 returnSingleInt(v
, db
->temp_store
);
954 changeTempStorage(pParse
, zRight
);
960 ** PRAGMA temp_store_directory
961 ** PRAGMA temp_store_directory = ""|"directory_name"
963 ** Return or set the local value of the temp_store_directory flag. Changing
964 ** the value sets a specific directory to be used for temporary files.
965 ** Setting to a null string reverts to the default temporary directory search.
966 ** If temporary directory is changed, then invalidateTempStorage.
969 case PragTyp_TEMP_STORE_DIRECTORY
: {
971 returnSingleText(v
, sqlite3_temp_directory
);
973 #ifndef SQLITE_OMIT_WSD
976 rc
= sqlite3OsAccess(db
->pVfs
, zRight
, SQLITE_ACCESS_READWRITE
, &res
);
977 if( rc
!=SQLITE_OK
|| res
==0 ){
978 sqlite3ErrorMsg(pParse
, "not a writable directory");
982 if( SQLITE_TEMP_STORE
==0
983 || (SQLITE_TEMP_STORE
==1 && db
->temp_store
<=1)
984 || (SQLITE_TEMP_STORE
==2 && db
->temp_store
==1)
986 invalidateTempStorage(pParse
);
988 sqlite3_free(sqlite3_temp_directory
);
990 sqlite3_temp_directory
= sqlite3_mprintf("%s", zRight
);
992 sqlite3_temp_directory
= 0;
994 #endif /* SQLITE_OMIT_WSD */
1001 ** PRAGMA data_store_directory
1002 ** PRAGMA data_store_directory = ""|"directory_name"
1004 ** Return or set the local value of the data_store_directory flag. Changing
1005 ** the value sets a specific directory to be used for database files that
1006 ** were specified with a relative pathname. Setting to a null string reverts
1007 ** to the default database directory, which for database files specified with
1008 ** a relative path will probably be based on the current directory for the
1009 ** process. Database file specified with an absolute path are not impacted
1010 ** by this setting, regardless of its value.
1013 case PragTyp_DATA_STORE_DIRECTORY
: {
1015 returnSingleText(v
, sqlite3_data_directory
);
1017 #ifndef SQLITE_OMIT_WSD
1020 rc
= sqlite3OsAccess(db
->pVfs
, zRight
, SQLITE_ACCESS_READWRITE
, &res
);
1021 if( rc
!=SQLITE_OK
|| res
==0 ){
1022 sqlite3ErrorMsg(pParse
, "not a writable directory");
1026 sqlite3_free(sqlite3_data_directory
);
1028 sqlite3_data_directory
= sqlite3_mprintf("%s", zRight
);
1030 sqlite3_data_directory
= 0;
1032 #endif /* SQLITE_OMIT_WSD */
1038 #if SQLITE_ENABLE_LOCKING_STYLE
1040 ** PRAGMA [schema.]lock_proxy_file
1041 ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
1043 ** Return or set the value of the lock_proxy_file flag. Changing
1044 ** the value sets a specific file to be used for database access locks.
1047 case PragTyp_LOCK_PROXY_FILE
: {
1049 Pager
*pPager
= sqlite3BtreePager(pDb
->pBt
);
1050 char *proxy_file_path
= NULL
;
1051 sqlite3_file
*pFile
= sqlite3PagerFile(pPager
);
1052 sqlite3OsFileControlHint(pFile
, SQLITE_GET_LOCKPROXYFILE
,
1054 returnSingleText(v
, proxy_file_path
);
1056 Pager
*pPager
= sqlite3BtreePager(pDb
->pBt
);
1057 sqlite3_file
*pFile
= sqlite3PagerFile(pPager
);
1060 res
=sqlite3OsFileControl(pFile
, SQLITE_SET_LOCKPROXYFILE
,
1063 res
=sqlite3OsFileControl(pFile
, SQLITE_SET_LOCKPROXYFILE
,
1066 if( res
!=SQLITE_OK
){
1067 sqlite3ErrorMsg(pParse
, "failed to set lock proxy file");
1073 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
1076 ** PRAGMA [schema.]synchronous
1077 ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
1079 ** Return or set the local value of the synchronous flag. Changing
1080 ** the local value does not make changes to the disk file and the
1081 ** default value will be restored the next time the database is
1084 case PragTyp_SYNCHRONOUS
: {
1086 returnSingleInt(v
, pDb
->safety_level
-1);
1088 if( !db
->autoCommit
){
1089 sqlite3ErrorMsg(pParse
,
1090 "Safety level may not be changed inside a transaction");
1092 int iLevel
= (getSafetyLevel(zRight
,0,1)+1) & PAGER_SYNCHRONOUS_MASK
;
1093 if( iLevel
==0 ) iLevel
= 1;
1094 pDb
->safety_level
= iLevel
;
1096 setAllPagerFlags(db
);
1101 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
1103 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
1104 case PragTyp_FLAG
: {
1106 setPragmaResultColumnNames(v
, pPragma
);
1107 returnSingleInt(v
, (db
->flags
& pPragma
->iArg
)!=0 );
1109 u64 mask
= pPragma
->iArg
; /* Mask of bits to set or clear. */
1110 if( db
->autoCommit
==0 ){
1111 /* Foreign key support may not be enabled or disabled while not
1112 ** in auto-commit mode. */
1113 mask
&= ~(SQLITE_ForeignKeys
);
1115 #if SQLITE_USER_AUTHENTICATION
1116 if( db
->auth
.authLevel
==UAUTH_User
){
1117 /* Do not allow non-admin users to modify the schema arbitrarily */
1118 mask
&= ~(SQLITE_WriteSchema
);
1122 if( sqlite3GetBoolean(zRight
, 0) ){
1126 if( mask
==SQLITE_DeferFKs
) db
->nDeferredImmCons
= 0;
1129 /* Many of the flag-pragmas modify the code generated by the SQL
1130 ** compiler (eg. count_changes). So add an opcode to expire all
1131 ** compiled SQL statements after modifying a pragma value.
1133 sqlite3VdbeAddOp0(v
, OP_Expire
);
1134 setAllPagerFlags(db
);
1138 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
1140 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
1142 ** PRAGMA table_info(<table>)
1144 ** Return a single row for each column of the named table. The columns of
1145 ** the returned data set are:
1147 ** cid: Column id (numbered from left to right, starting at 0)
1148 ** name: Column name
1149 ** type: Column declaration type.
1150 ** notnull: True if 'NOT NULL' is part of column declaration
1151 ** dflt_value: The default value for the column, if any.
1152 ** pk: Non-zero for PK fields.
1154 case PragTyp_TABLE_INFO
: if( zRight
){
1156 pTab
= sqlite3LocateTable(pParse
, LOCATE_NOERR
, zRight
, zDb
);
1158 int iTabDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
1162 Index
*pPk
= sqlite3PrimaryKeyIndex(pTab
);
1164 sqlite3CodeVerifySchema(pParse
, iTabDb
);
1165 sqlite3ViewGetColumnNames(pParse
, pTab
);
1166 for(i
=0, pCol
=pTab
->aCol
; i
<pTab
->nCol
; i
++, pCol
++){
1168 if( pCol
->colFlags
& COLFLAG_NOINSERT
){
1169 if( pPragma
->iArg
==0 ){
1173 if( pCol
->colFlags
& COLFLAG_VIRTUAL
){
1174 isHidden
= 2; /* GENERATED ALWAYS AS ... VIRTUAL */
1175 }else if( pCol
->colFlags
& COLFLAG_STORED
){
1176 isHidden
= 3; /* GENERATED ALWAYS AS ... STORED */
1177 }else{ assert( pCol
->colFlags
& COLFLAG_HIDDEN
);
1178 isHidden
= 1; /* HIDDEN */
1181 if( (pCol
->colFlags
& COLFLAG_PRIMKEY
)==0 ){
1186 for(k
=1; k
<=pTab
->nCol
&& pPk
->aiColumn
[k
-1]!=i
; k
++){}
1188 assert( pCol
->pDflt
==0 || pCol
->pDflt
->op
==TK_SPAN
|| isHidden
>=2 );
1189 sqlite3VdbeMultiLoad(v
, 1, pPragma
->iArg
? "issisii" : "issisi",
1192 sqlite3ColumnType(pCol
,""),
1193 pCol
->notNull
? 1 : 0,
1194 pCol
->pDflt
&& isHidden
<2 ? pCol
->pDflt
->u
.zToken
: 0,
1203 case PragTyp_STATS
: {
1207 sqlite3CodeVerifySchema(pParse
, iDb
);
1208 for(i
=sqliteHashFirst(&pDb
->pSchema
->tblHash
); i
; i
=sqliteHashNext(i
)){
1209 Table
*pTab
= sqliteHashData(i
);
1210 sqlite3VdbeMultiLoad(v
, 1, "ssiii",
1216 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1217 sqlite3VdbeMultiLoad(v
, 2, "siiiX",
1220 pIdx
->aiRowLogEst
[0],
1222 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, 5);
1229 case PragTyp_INDEX_INFO
: if( zRight
){
1232 pIdx
= sqlite3FindIndex(db
, zRight
, zDb
);
1234 /* If there is no index named zRight, check to see if there is a
1235 ** WITHOUT ROWID table named zRight, and if there is, show the
1236 ** structure of the PRIMARY KEY index for that table. */
1237 pTab
= sqlite3LocateTable(pParse
, LOCATE_NOERR
, zRight
, zDb
);
1238 if( pTab
&& !HasRowid(pTab
) ){
1239 pIdx
= sqlite3PrimaryKeyIndex(pTab
);
1243 int iIdxDb
= sqlite3SchemaToIndex(db
, pIdx
->pSchema
);
1246 if( pPragma
->iArg
){
1247 /* PRAGMA index_xinfo (newer version with more rows and columns) */
1251 /* PRAGMA index_info (legacy version) */
1255 pTab
= pIdx
->pTable
;
1256 sqlite3CodeVerifySchema(pParse
, iIdxDb
);
1257 assert( pParse
->nMem
<=pPragma
->nPragCName
);
1258 for(i
=0; i
<mx
; i
++){
1259 i16 cnum
= pIdx
->aiColumn
[i
];
1260 sqlite3VdbeMultiLoad(v
, 1, "iisX", i
, cnum
,
1261 cnum
<0 ? 0 : pTab
->aCol
[cnum
].zName
);
1262 if( pPragma
->iArg
){
1263 sqlite3VdbeMultiLoad(v
, 4, "isiX",
1264 pIdx
->aSortOrder
[i
],
1268 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, pParse
->nMem
);
1274 case PragTyp_INDEX_LIST
: if( zRight
){
1278 pTab
= sqlite3FindTable(db
, zRight
, zDb
);
1280 int iTabDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
1282 sqlite3CodeVerifySchema(pParse
, iTabDb
);
1283 for(pIdx
=pTab
->pIndex
, i
=0; pIdx
; pIdx
=pIdx
->pNext
, i
++){
1284 const char *azOrigin
[] = { "c", "u", "pk" };
1285 sqlite3VdbeMultiLoad(v
, 1, "isisi",
1288 IsUniqueIndex(pIdx
),
1289 azOrigin
[pIdx
->idxType
],
1290 pIdx
->pPartIdxWhere
!=0);
1296 case PragTyp_DATABASE_LIST
: {
1299 for(i
=0; i
<db
->nDb
; i
++){
1300 if( db
->aDb
[i
].pBt
==0 ) continue;
1301 assert( db
->aDb
[i
].zDbSName
!=0 );
1302 sqlite3VdbeMultiLoad(v
, 1, "iss",
1304 db
->aDb
[i
].zDbSName
,
1305 sqlite3BtreeGetFilename(db
->aDb
[i
].pBt
));
1310 case PragTyp_COLLATION_LIST
: {
1314 for(p
=sqliteHashFirst(&db
->aCollSeq
); p
; p
=sqliteHashNext(p
)){
1315 CollSeq
*pColl
= (CollSeq
*)sqliteHashData(p
);
1316 sqlite3VdbeMultiLoad(v
, 1, "is", i
++, pColl
->zName
);
1321 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
1322 case PragTyp_FUNCTION_LIST
: {
1326 int showInternFunc
= (db
->mDbFlags
& DBFLAG_InternalFunc
)!=0;
1328 for(i
=0; i
<SQLITE_FUNC_HASH_SZ
; i
++){
1329 for(p
=sqlite3BuiltinFunctions
.a
[i
]; p
; p
=p
->u
.pHash
){
1330 pragmaFunclistLine(v
, p
, 1, showInternFunc
);
1333 for(j
=sqliteHashFirst(&db
->aFunc
); j
; j
=sqliteHashNext(j
)){
1334 p
= (FuncDef
*)sqliteHashData(j
);
1335 pragmaFunclistLine(v
, p
, 0, showInternFunc
);
1340 #ifndef SQLITE_OMIT_VIRTUALTABLE
1341 case PragTyp_MODULE_LIST
: {
1344 for(j
=sqliteHashFirst(&db
->aModule
); j
; j
=sqliteHashNext(j
)){
1345 Module
*pMod
= (Module
*)sqliteHashData(j
);
1346 sqlite3VdbeMultiLoad(v
, 1, "s", pMod
->zName
);
1350 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1352 case PragTyp_PRAGMA_LIST
: {
1354 for(i
=0; i
<ArraySize(aPragmaName
); i
++){
1355 sqlite3VdbeMultiLoad(v
, 1, "s", aPragmaName
[i
].zName
);
1359 #endif /* SQLITE_INTROSPECTION_PRAGMAS */
1361 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
1363 #ifndef SQLITE_OMIT_FOREIGN_KEY
1364 case PragTyp_FOREIGN_KEY_LIST
: if( zRight
){
1367 pTab
= sqlite3FindTable(db
, zRight
, zDb
);
1371 int iTabDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
1374 sqlite3CodeVerifySchema(pParse
, iTabDb
);
1377 for(j
=0; j
<pFK
->nCol
; j
++){
1378 sqlite3VdbeMultiLoad(v
, 1, "iissssss",
1382 pTab
->aCol
[pFK
->aCol
[j
].iFrom
].zName
,
1384 actionName(pFK
->aAction
[1]), /* ON UPDATE */
1385 actionName(pFK
->aAction
[0]), /* ON DELETE */
1389 pFK
= pFK
->pNextFrom
;
1395 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1397 #ifndef SQLITE_OMIT_FOREIGN_KEY
1398 #ifndef SQLITE_OMIT_TRIGGER
1399 case PragTyp_FOREIGN_KEY_CHECK
: {
1400 FKey
*pFK
; /* A foreign key constraint */
1401 Table
*pTab
; /* Child table contain "REFERENCES" keyword */
1402 Table
*pParent
; /* Parent table that child points to */
1403 Index
*pIdx
; /* Index in the parent table */
1404 int i
; /* Loop counter: Foreign key number for pTab */
1405 int j
; /* Loop counter: Field of the foreign key */
1406 HashElem
*k
; /* Loop counter: Next table in schema */
1407 int x
; /* result variable */
1408 int regResult
; /* 3 registers to hold a result row */
1409 int regKey
; /* Register to hold key for checking the FK */
1410 int regRow
; /* Registers to hold a row from pTab */
1411 int addrTop
; /* Top of a loop checking foreign keys */
1412 int addrOk
; /* Jump here if the key is OK */
1413 int *aiCols
; /* child to parent column mapping */
1415 regResult
= pParse
->nMem
+1;
1417 regKey
= ++pParse
->nMem
;
1418 regRow
= ++pParse
->nMem
;
1419 k
= sqliteHashFirst(&db
->aDb
[iDb
].pSchema
->tblHash
);
1423 pTab
= sqlite3LocateTable(pParse
, 0, zRight
, zDb
);
1426 pTab
= (Table
*)sqliteHashData(k
);
1427 k
= sqliteHashNext(k
);
1429 if( pTab
==0 || pTab
->pFKey
==0 ) continue;
1430 iTabDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
1431 sqlite3CodeVerifySchema(pParse
, iTabDb
);
1432 sqlite3TableLock(pParse
, iTabDb
, pTab
->tnum
, 0, pTab
->zName
);
1433 if( pTab
->nCol
+regRow
>pParse
->nMem
) pParse
->nMem
= pTab
->nCol
+ regRow
;
1434 sqlite3OpenTable(pParse
, 0, iTabDb
, pTab
, OP_OpenRead
);
1435 sqlite3VdbeLoadString(v
, regResult
, pTab
->zName
);
1436 for(i
=1, pFK
=pTab
->pFKey
; pFK
; i
++, pFK
=pFK
->pNextFrom
){
1437 pParent
= sqlite3FindTable(db
, pFK
->zTo
, zDb
);
1438 if( pParent
==0 ) continue;
1440 sqlite3TableLock(pParse
, iTabDb
, pParent
->tnum
, 0, pParent
->zName
);
1441 x
= sqlite3FkLocateIndex(pParse
, pParent
, pFK
, &pIdx
, 0);
1444 sqlite3OpenTable(pParse
, i
, iTabDb
, pParent
, OP_OpenRead
);
1446 sqlite3VdbeAddOp3(v
, OP_OpenRead
, i
, pIdx
->tnum
, iTabDb
);
1447 sqlite3VdbeSetP4KeyInfo(pParse
, pIdx
);
1454 assert( pParse
->nErr
>0 || pFK
==0 );
1456 if( pParse
->nTab
<i
) pParse
->nTab
= i
;
1457 addrTop
= sqlite3VdbeAddOp1(v
, OP_Rewind
, 0); VdbeCoverage(v
);
1458 for(i
=1, pFK
=pTab
->pFKey
; pFK
; i
++, pFK
=pFK
->pNextFrom
){
1459 pParent
= sqlite3FindTable(db
, pFK
->zTo
, zDb
);
1463 x
= sqlite3FkLocateIndex(pParse
, pParent
, pFK
, &pIdx
, &aiCols
);
1466 addrOk
= sqlite3VdbeMakeLabel(pParse
);
1468 /* Generate code to read the child key values into registers
1469 ** regRow..regRow+n. If any of the child key values are NULL, this
1470 ** row cannot cause an FK violation. Jump directly to addrOk in
1472 for(j
=0; j
<pFK
->nCol
; j
++){
1473 int iCol
= aiCols
? aiCols
[j
] : pFK
->aCol
[j
].iFrom
;
1474 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, 0, iCol
, regRow
+j
);
1475 sqlite3VdbeAddOp2(v
, OP_IsNull
, regRow
+j
, addrOk
); VdbeCoverage(v
);
1478 /* Generate code to query the parent index for a matching parent
1479 ** key. If a match is found, jump to addrOk. */
1481 sqlite3VdbeAddOp4(v
, OP_MakeRecord
, regRow
, pFK
->nCol
, regKey
,
1482 sqlite3IndexAffinityStr(db
,pIdx
), pFK
->nCol
);
1483 sqlite3VdbeAddOp4Int(v
, OP_Found
, i
, addrOk
, regKey
, 0);
1485 }else if( pParent
){
1486 int jmp
= sqlite3VdbeCurrentAddr(v
)+2;
1487 sqlite3VdbeAddOp3(v
, OP_SeekRowid
, i
, jmp
, regRow
); VdbeCoverage(v
);
1488 sqlite3VdbeGoto(v
, addrOk
);
1489 assert( pFK
->nCol
==1 );
1492 /* Generate code to report an FK violation to the caller. */
1493 if( HasRowid(pTab
) ){
1494 sqlite3VdbeAddOp2(v
, OP_Rowid
, 0, regResult
+1);
1496 sqlite3VdbeAddOp2(v
, OP_Null
, 0, regResult
+1);
1498 sqlite3VdbeMultiLoad(v
, regResult
+2, "siX", pFK
->zTo
, i
-1);
1499 sqlite3VdbeAddOp2(v
, OP_ResultRow
, regResult
, 4);
1500 sqlite3VdbeResolveLabel(v
, addrOk
);
1501 sqlite3DbFree(db
, aiCols
);
1503 sqlite3VdbeAddOp2(v
, OP_Next
, 0, addrTop
+1); VdbeCoverage(v
);
1504 sqlite3VdbeJumpHere(v
, addrTop
);
1508 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
1509 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1511 #ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA
1512 /* Reinstall the LIKE and GLOB functions. The variant of LIKE
1513 ** used will be case sensitive or not depending on the RHS.
1515 case PragTyp_CASE_SENSITIVE_LIKE
: {
1517 sqlite3RegisterLikeFunctions(db
, sqlite3GetBoolean(zRight
, 0));
1521 #endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */
1523 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
1524 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
1527 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
1528 /* PRAGMA integrity_check
1529 ** PRAGMA integrity_check(N)
1530 ** PRAGMA quick_check
1531 ** PRAGMA quick_check(N)
1533 ** Verify the integrity of the database.
1535 ** The "quick_check" is reduced version of
1536 ** integrity_check designed to detect most database corruption
1537 ** without the overhead of cross-checking indexes. Quick_check
1538 ** is linear time wherease integrity_check is O(NlogN).
1540 case PragTyp_INTEGRITY_CHECK
: {
1541 int i
, j
, addr
, mxErr
;
1543 int isQuick
= (sqlite3Tolower(zLeft
[0])=='q');
1545 /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
1546 ** then iDb is set to the index of the database identified by <db>.
1547 ** In this case, the integrity of database iDb only is verified by
1548 ** the VDBE created below.
1550 ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
1551 ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
1552 ** to -1 here, to indicate that the VDBE should verify the integrity
1553 ** of all attached databases. */
1555 assert( iDb
==0 || pId2
->z
);
1556 if( pId2
->z
==0 ) iDb
= -1;
1558 /* Initialize the VDBE program */
1561 /* Set the maximum error count */
1562 mxErr
= SQLITE_INTEGRITY_CHECK_ERROR_MAX
;
1564 sqlite3GetInt32(zRight
, &mxErr
);
1566 mxErr
= SQLITE_INTEGRITY_CHECK_ERROR_MAX
;
1569 sqlite3VdbeAddOp2(v
, OP_Integer
, mxErr
-1, 1); /* reg[1] holds errors left */
1571 /* Do an integrity check on each database file */
1572 for(i
=0; i
<db
->nDb
; i
++){
1573 HashElem
*x
; /* For looping over tables in the schema */
1574 Hash
*pTbls
; /* Set of all tables in the schema */
1575 int *aRoot
; /* Array of root page numbers of all btrees */
1576 int cnt
= 0; /* Number of entries in aRoot[] */
1577 int mxIdx
= 0; /* Maximum number of indexes for any table */
1579 if( OMIT_TEMPDB
&& i
==1 ) continue;
1580 if( iDb
>=0 && i
!=iDb
) continue;
1582 sqlite3CodeVerifySchema(pParse
, i
);
1584 /* Do an integrity check of the B-Tree
1586 ** Begin by finding the root pages numbers
1587 ** for all tables and indices in the database.
1589 assert( sqlite3SchemaMutexHeld(db
, i
, 0) );
1590 pTbls
= &db
->aDb
[i
].pSchema
->tblHash
;
1591 for(cnt
=0, x
=sqliteHashFirst(pTbls
); x
; x
=sqliteHashNext(x
)){
1592 Table
*pTab
= sqliteHashData(x
); /* Current table */
1593 Index
*pIdx
; /* An index on pTab */
1594 int nIdx
; /* Number of indexes on pTab */
1595 if( HasRowid(pTab
) ) cnt
++;
1596 for(nIdx
=0, pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
, nIdx
++){ cnt
++; }
1597 if( nIdx
>mxIdx
) mxIdx
= nIdx
;
1599 aRoot
= sqlite3DbMallocRawNN(db
, sizeof(int)*(cnt
+1));
1600 if( aRoot
==0 ) break;
1601 for(cnt
=0, x
=sqliteHashFirst(pTbls
); x
; x
=sqliteHashNext(x
)){
1602 Table
*pTab
= sqliteHashData(x
);
1604 if( HasRowid(pTab
) ) aRoot
[++cnt
] = pTab
->tnum
;
1605 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1606 aRoot
[++cnt
] = pIdx
->tnum
;
1611 /* Make sure sufficient number of registers have been allocated */
1612 pParse
->nMem
= MAX( pParse
->nMem
, 8+mxIdx
);
1613 sqlite3ClearTempRegCache(pParse
);
1615 /* Do the b-tree integrity checks */
1616 sqlite3VdbeAddOp4(v
, OP_IntegrityCk
, 2, cnt
, 1, (char*)aRoot
,P4_INTARRAY
);
1617 sqlite3VdbeChangeP5(v
, (u8
)i
);
1618 addr
= sqlite3VdbeAddOp1(v
, OP_IsNull
, 2); VdbeCoverage(v
);
1619 sqlite3VdbeAddOp4(v
, OP_String8
, 0, 3, 0,
1620 sqlite3MPrintf(db
, "*** in database %s ***\n", db
->aDb
[i
].zDbSName
),
1622 sqlite3VdbeAddOp3(v
, OP_Concat
, 2, 3, 3);
1623 integrityCheckResultRow(v
);
1624 sqlite3VdbeJumpHere(v
, addr
);
1626 /* Make sure all the indices are constructed correctly.
1628 for(x
=sqliteHashFirst(pTbls
); x
; x
=sqliteHashNext(x
)){
1629 Table
*pTab
= sqliteHashData(x
);
1633 int iDataCur
, iIdxCur
;
1636 if( pTab
->tnum
<1 ) continue; /* Skip VIEWs or VIRTUAL TABLEs */
1637 pPk
= HasRowid(pTab
) ? 0 : sqlite3PrimaryKeyIndex(pTab
);
1638 sqlite3OpenTableAndIndices(pParse
, pTab
, OP_OpenRead
, 0,
1639 1, 0, &iDataCur
, &iIdxCur
);
1640 /* reg[7] counts the number of entries in the table.
1641 ** reg[8+i] counts the number of entries in the i-th index
1643 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, 7);
1644 for(j
=0, pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
, j
++){
1645 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, 8+j
); /* index entries counter */
1647 assert( pParse
->nMem
>=8+j
);
1648 assert( sqlite3NoTempsInRange(pParse
,1,7+j
) );
1649 sqlite3VdbeAddOp2(v
, OP_Rewind
, iDataCur
, 0); VdbeCoverage(v
);
1650 loopTop
= sqlite3VdbeAddOp2(v
, OP_AddImm
, 7, 1);
1652 /* Sanity check on record header decoding */
1653 sqlite3VdbeAddOp3(v
, OP_Column
, iDataCur
, pTab
->nNVCol
-1,3);
1654 sqlite3VdbeChangeP5(v
, OPFLAG_TYPEOFARG
);
1656 /* Verify that all NOT NULL columns really are NOT NULL */
1657 for(j
=0; j
<pTab
->nCol
; j
++){
1660 if( j
==pTab
->iPKey
) continue;
1661 if( pTab
->aCol
[j
].notNull
==0 ) continue;
1662 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iDataCur
, j
, 3);
1663 if( sqlite3VdbeGetOp(v
,-1)->opcode
==OP_Column
){
1664 sqlite3VdbeChangeP5(v
, OPFLAG_TYPEOFARG
);
1666 jmp2
= sqlite3VdbeAddOp1(v
, OP_NotNull
, 3); VdbeCoverage(v
);
1667 zErr
= sqlite3MPrintf(db
, "NULL value in %s.%s", pTab
->zName
,
1668 pTab
->aCol
[j
].zName
);
1669 sqlite3VdbeAddOp4(v
, OP_String8
, 0, 3, 0, zErr
, P4_DYNAMIC
);
1670 integrityCheckResultRow(v
);
1671 sqlite3VdbeJumpHere(v
, jmp2
);
1673 /* Verify CHECK constraints */
1674 if( pTab
->pCheck
&& (db
->flags
& SQLITE_IgnoreChecks
)==0 ){
1675 ExprList
*pCheck
= sqlite3ExprListDup(db
, pTab
->pCheck
, 0);
1676 if( db
->mallocFailed
==0 ){
1677 int addrCkFault
= sqlite3VdbeMakeLabel(pParse
);
1678 int addrCkOk
= sqlite3VdbeMakeLabel(pParse
);
1681 pParse
->iSelfTab
= iDataCur
+ 1;
1682 for(k
=pCheck
->nExpr
-1; k
>0; k
--){
1683 sqlite3ExprIfFalse(pParse
, pCheck
->a
[k
].pExpr
, addrCkFault
, 0);
1685 sqlite3ExprIfTrue(pParse
, pCheck
->a
[0].pExpr
, addrCkOk
,
1687 sqlite3VdbeResolveLabel(v
, addrCkFault
);
1688 pParse
->iSelfTab
= 0;
1689 zErr
= sqlite3MPrintf(db
, "CHECK constraint failed in %s",
1691 sqlite3VdbeAddOp4(v
, OP_String8
, 0, 3, 0, zErr
, P4_DYNAMIC
);
1692 integrityCheckResultRow(v
);
1693 sqlite3VdbeResolveLabel(v
, addrCkOk
);
1695 sqlite3ExprListDelete(db
, pCheck
);
1697 if( !isQuick
){ /* Omit the remaining tests for quick_check */
1698 /* Validate index entries for the current row */
1699 for(j
=0, pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
, j
++){
1700 int jmp2
, jmp3
, jmp4
, jmp5
;
1701 int ckUniq
= sqlite3VdbeMakeLabel(pParse
);
1702 if( pPk
==pIdx
) continue;
1703 r1
= sqlite3GenerateIndexKey(pParse
, pIdx
, iDataCur
, 0, 0, &jmp3
,
1706 sqlite3VdbeAddOp2(v
, OP_AddImm
, 8+j
, 1);/* increment entry count */
1707 /* Verify that an index entry exists for the current table row */
1708 jmp2
= sqlite3VdbeAddOp4Int(v
, OP_Found
, iIdxCur
+j
, ckUniq
, r1
,
1709 pIdx
->nColumn
); VdbeCoverage(v
);
1710 sqlite3VdbeLoadString(v
, 3, "row ");
1711 sqlite3VdbeAddOp3(v
, OP_Concat
, 7, 3, 3);
1712 sqlite3VdbeLoadString(v
, 4, " missing from index ");
1713 sqlite3VdbeAddOp3(v
, OP_Concat
, 4, 3, 3);
1714 jmp5
= sqlite3VdbeLoadString(v
, 4, pIdx
->zName
);
1715 sqlite3VdbeAddOp3(v
, OP_Concat
, 4, 3, 3);
1716 jmp4
= integrityCheckResultRow(v
);
1717 sqlite3VdbeJumpHere(v
, jmp2
);
1718 /* For UNIQUE indexes, verify that only one entry exists with the
1719 ** current key. The entry is unique if (1) any column is NULL
1720 ** or (2) the next entry has a different key */
1721 if( IsUniqueIndex(pIdx
) ){
1722 int uniqOk
= sqlite3VdbeMakeLabel(pParse
);
1725 for(kk
=0; kk
<pIdx
->nKeyCol
; kk
++){
1726 int iCol
= pIdx
->aiColumn
[kk
];
1727 assert( iCol
!=XN_ROWID
&& iCol
<pTab
->nCol
);
1728 if( iCol
>=0 && pTab
->aCol
[iCol
].notNull
) continue;
1729 sqlite3VdbeAddOp2(v
, OP_IsNull
, r1
+kk
, uniqOk
);
1732 jmp6
= sqlite3VdbeAddOp1(v
, OP_Next
, iIdxCur
+j
); VdbeCoverage(v
);
1733 sqlite3VdbeGoto(v
, uniqOk
);
1734 sqlite3VdbeJumpHere(v
, jmp6
);
1735 sqlite3VdbeAddOp4Int(v
, OP_IdxGT
, iIdxCur
+j
, uniqOk
, r1
,
1736 pIdx
->nKeyCol
); VdbeCoverage(v
);
1737 sqlite3VdbeLoadString(v
, 3, "non-unique entry in index ");
1738 sqlite3VdbeGoto(v
, jmp5
);
1739 sqlite3VdbeResolveLabel(v
, uniqOk
);
1741 sqlite3VdbeJumpHere(v
, jmp4
);
1742 sqlite3ResolvePartIdxLabel(pParse
, jmp3
);
1745 sqlite3VdbeAddOp2(v
, OP_Next
, iDataCur
, loopTop
); VdbeCoverage(v
);
1746 sqlite3VdbeJumpHere(v
, loopTop
-1);
1748 sqlite3VdbeLoadString(v
, 2, "wrong # of entries in index ");
1749 for(j
=0, pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
, j
++){
1750 if( pPk
==pIdx
) continue;
1751 sqlite3VdbeAddOp2(v
, OP_Count
, iIdxCur
+j
, 3);
1752 addr
= sqlite3VdbeAddOp3(v
, OP_Eq
, 8+j
, 0, 3); VdbeCoverage(v
);
1753 sqlite3VdbeChangeP5(v
, SQLITE_NOTNULL
);
1754 sqlite3VdbeLoadString(v
, 4, pIdx
->zName
);
1755 sqlite3VdbeAddOp3(v
, OP_Concat
, 4, 2, 3);
1756 integrityCheckResultRow(v
);
1757 sqlite3VdbeJumpHere(v
, addr
);
1763 static const int iLn
= VDBE_OFFSET_LINENO(2);
1764 static const VdbeOpList endCode
[] = {
1765 { OP_AddImm
, 1, 0, 0}, /* 0 */
1766 { OP_IfNotZero
, 1, 4, 0}, /* 1 */
1767 { OP_String8
, 0, 3, 0}, /* 2 */
1768 { OP_ResultRow
, 3, 1, 0}, /* 3 */
1769 { OP_Halt
, 0, 0, 0}, /* 4 */
1770 { OP_String8
, 0, 3, 0}, /* 5 */
1771 { OP_Goto
, 0, 3, 0}, /* 6 */
1775 aOp
= sqlite3VdbeAddOpList(v
, ArraySize(endCode
), endCode
, iLn
);
1777 aOp
[0].p2
= 1-mxErr
;
1778 aOp
[2].p4type
= P4_STATIC
;
1780 aOp
[5].p4type
= P4_STATIC
;
1781 aOp
[5].p4
.z
= (char*)sqlite3ErrStr(SQLITE_CORRUPT
);
1783 sqlite3VdbeChangeP3(v
, 0, sqlite3VdbeCurrentAddr(v
)-2);
1787 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
1789 #ifndef SQLITE_OMIT_UTF16
1792 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
1794 ** In its first form, this pragma returns the encoding of the main
1795 ** database. If the database is not initialized, it is initialized now.
1797 ** The second form of this pragma is a no-op if the main database file
1798 ** has not already been initialized. In this case it sets the default
1799 ** encoding that will be used for the main database file if a new file
1800 ** is created. If an existing main database file is opened, then the
1801 ** default text encoding for the existing database is used.
1803 ** In all cases new databases created using the ATTACH command are
1804 ** created to use the same default text encoding as the main database. If
1805 ** the main database has not been initialized and/or created when ATTACH
1806 ** is executed, this is done before the ATTACH operation.
1808 ** In the second form this pragma sets the text encoding to be used in
1809 ** new database files created using this database handle. It is only
1810 ** useful if invoked immediately after the main database i
1812 case PragTyp_ENCODING
: {
1813 static const struct EncName
{
1817 { "UTF8", SQLITE_UTF8
},
1818 { "UTF-8", SQLITE_UTF8
}, /* Must be element [1] */
1819 { "UTF-16le", SQLITE_UTF16LE
}, /* Must be element [2] */
1820 { "UTF-16be", SQLITE_UTF16BE
}, /* Must be element [3] */
1821 { "UTF16le", SQLITE_UTF16LE
},
1822 { "UTF16be", SQLITE_UTF16BE
},
1823 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
1824 { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
1827 const struct EncName
*pEnc
;
1828 if( !zRight
){ /* "PRAGMA encoding" */
1829 if( sqlite3ReadSchema(pParse
) ) goto pragma_out
;
1830 assert( encnames
[SQLITE_UTF8
].enc
==SQLITE_UTF8
);
1831 assert( encnames
[SQLITE_UTF16LE
].enc
==SQLITE_UTF16LE
);
1832 assert( encnames
[SQLITE_UTF16BE
].enc
==SQLITE_UTF16BE
);
1833 returnSingleText(v
, encnames
[ENC(pParse
->db
)].zName
);
1834 }else{ /* "PRAGMA encoding = XXX" */
1835 /* Only change the value of sqlite.enc if the database handle is not
1836 ** initialized. If the main database exists, the new sqlite.enc value
1837 ** will be overwritten when the schema is next loaded. If it does not
1838 ** already exists, it will be created to use the new encoding value.
1840 if( (db
->mDbFlags
& DBFLAG_EncodingFixed
)==0 ){
1841 for(pEnc
=&encnames
[0]; pEnc
->zName
; pEnc
++){
1842 if( 0==sqlite3StrICmp(zRight
, pEnc
->zName
) ){
1843 u8 enc
= pEnc
->enc
? pEnc
->enc
: SQLITE_UTF16NATIVE
;
1844 SCHEMA_ENC(db
) = enc
;
1845 sqlite3SetTextEncoding(db
, enc
);
1850 sqlite3ErrorMsg(pParse
, "unsupported encoding: %s", zRight
);
1856 #endif /* SQLITE_OMIT_UTF16 */
1858 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
1860 ** PRAGMA [schema.]schema_version
1861 ** PRAGMA [schema.]schema_version = <integer>
1863 ** PRAGMA [schema.]user_version
1864 ** PRAGMA [schema.]user_version = <integer>
1866 ** PRAGMA [schema.]freelist_count
1868 ** PRAGMA [schema.]data_version
1870 ** PRAGMA [schema.]application_id
1871 ** PRAGMA [schema.]application_id = <integer>
1873 ** The pragma's schema_version and user_version are used to set or get
1874 ** the value of the schema-version and user-version, respectively. Both
1875 ** the schema-version and the user-version are 32-bit signed integers
1876 ** stored in the database header.
1878 ** The schema-cookie is usually only manipulated internally by SQLite. It
1879 ** is incremented by SQLite whenever the database schema is modified (by
1880 ** creating or dropping a table or index). The schema version is used by
1881 ** SQLite each time a query is executed to ensure that the internal cache
1882 ** of the schema used when compiling the SQL query matches the schema of
1883 ** the database against which the compiled query is actually executed.
1884 ** Subverting this mechanism by using "PRAGMA schema_version" to modify
1885 ** the schema-version is potentially dangerous and may lead to program
1886 ** crashes or database corruption. Use with caution!
1888 ** The user-version is not used internally by SQLite. It may be used by
1889 ** applications for any purpose.
1891 case PragTyp_HEADER_VALUE
: {
1892 int iCookie
= pPragma
->iArg
; /* Which cookie to read or write */
1893 sqlite3VdbeUsesBtree(v
, iDb
);
1894 if( zRight
&& (pPragma
->mPragFlg
& PragFlg_ReadOnly
)==0 ){
1895 /* Write the specified cookie value */
1896 static const VdbeOpList setCookie
[] = {
1897 { OP_Transaction
, 0, 1, 0}, /* 0 */
1898 { OP_SetCookie
, 0, 0, 0}, /* 1 */
1901 sqlite3VdbeVerifyNoMallocRequired(v
, ArraySize(setCookie
));
1902 aOp
= sqlite3VdbeAddOpList(v
, ArraySize(setCookie
), setCookie
, 0);
1903 if( ONLY_IF_REALLOC_STRESS(aOp
==0) ) break;
1906 aOp
[1].p2
= iCookie
;
1907 aOp
[1].p3
= sqlite3Atoi(zRight
);
1909 /* Read the specified cookie value */
1910 static const VdbeOpList readCookie
[] = {
1911 { OP_Transaction
, 0, 0, 0}, /* 0 */
1912 { OP_ReadCookie
, 0, 1, 0}, /* 1 */
1913 { OP_ResultRow
, 1, 1, 0}
1916 sqlite3VdbeVerifyNoMallocRequired(v
, ArraySize(readCookie
));
1917 aOp
= sqlite3VdbeAddOpList(v
, ArraySize(readCookie
),readCookie
,0);
1918 if( ONLY_IF_REALLOC_STRESS(aOp
==0) ) break;
1921 aOp
[1].p3
= iCookie
;
1922 sqlite3VdbeReusable(v
);
1926 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
1928 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
1930 ** PRAGMA compile_options
1932 ** Return the names of all compile-time options used in this build,
1933 ** one option per row.
1935 case PragTyp_COMPILE_OPTIONS
: {
1939 while( (zOpt
= sqlite3_compileoption_get(i
++))!=0 ){
1940 sqlite3VdbeLoadString(v
, 1, zOpt
);
1941 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, 1);
1943 sqlite3VdbeReusable(v
);
1946 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
1948 #ifndef SQLITE_OMIT_WAL
1950 ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
1952 ** Checkpoint the database.
1954 case PragTyp_WAL_CHECKPOINT
: {
1955 int iBt
= (pId2
->z
?iDb
:SQLITE_MAX_ATTACHED
);
1956 int eMode
= SQLITE_CHECKPOINT_PASSIVE
;
1958 if( sqlite3StrICmp(zRight
, "full")==0 ){
1959 eMode
= SQLITE_CHECKPOINT_FULL
;
1960 }else if( sqlite3StrICmp(zRight
, "restart")==0 ){
1961 eMode
= SQLITE_CHECKPOINT_RESTART
;
1962 }else if( sqlite3StrICmp(zRight
, "truncate")==0 ){
1963 eMode
= SQLITE_CHECKPOINT_TRUNCATE
;
1967 sqlite3VdbeAddOp3(v
, OP_Checkpoint
, iBt
, eMode
, 1);
1968 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, 3);
1973 ** PRAGMA wal_autocheckpoint
1974 ** PRAGMA wal_autocheckpoint = N
1976 ** Configure a database connection to automatically checkpoint a database
1977 ** after accumulating N frames in the log. Or query for the current value
1980 case PragTyp_WAL_AUTOCHECKPOINT
: {
1982 sqlite3_wal_autocheckpoint(db
, sqlite3Atoi(zRight
));
1985 db
->xWalCallback
==sqlite3WalDefaultHook
?
1986 SQLITE_PTR_TO_INT(db
->pWalArg
) : 0);
1992 ** PRAGMA shrink_memory
1994 ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
1995 ** connection on which it is invoked to free up as much memory as it
1996 ** can, by calling sqlite3_db_release_memory().
1998 case PragTyp_SHRINK_MEMORY
: {
1999 sqlite3_db_release_memory(db
);
2005 ** PRAGMA optimize(MASK)
2006 ** PRAGMA schema.optimize
2007 ** PRAGMA schema.optimize(MASK)
2009 ** Attempt to optimize the database. All schemas are optimized in the first
2010 ** two forms, and only the specified schema is optimized in the latter two.
2012 ** The details of optimizations performed by this pragma are expected
2013 ** to change and improve over time. Applications should anticipate that
2014 ** this pragma will perform new optimizations in future releases.
2016 ** The optional argument is a bitmask of optimizations to perform:
2018 ** 0x0001 Debugging mode. Do not actually perform any optimizations
2019 ** but instead return one line of text for each optimization
2020 ** that would have been done. Off by default.
2022 ** 0x0002 Run ANALYZE on tables that might benefit. On by default.
2023 ** See below for additional information.
2025 ** 0x0004 (Not yet implemented) Record usage and performance
2026 ** information from the current session in the
2027 ** database file so that it will be available to "optimize"
2028 ** pragmas run by future database connections.
2030 ** 0x0008 (Not yet implemented) Create indexes that might have
2031 ** been helpful to recent queries
2033 ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all
2034 ** of the optimizations listed above except Debug Mode, including new
2035 ** optimizations that have not yet been invented. If new optimizations are
2036 ** ever added that should be off by default, those off-by-default
2037 ** optimizations will have bitmasks of 0x10000 or larger.
2039 ** DETERMINATION OF WHEN TO RUN ANALYZE
2041 ** In the current implementation, a table is analyzed if only if all of
2042 ** the following are true:
2044 ** (1) MASK bit 0x02 is set.
2046 ** (2) The query planner used sqlite_stat1-style statistics for one or
2047 ** more indexes of the table at some point during the lifetime of
2048 ** the current connection.
2050 ** (3) One or more indexes of the table are currently unanalyzed OR
2051 ** the number of rows in the table has increased by 25 times or more
2052 ** since the last time ANALYZE was run.
2054 ** The rules for when tables are analyzed are likely to change in
2057 case PragTyp_OPTIMIZE
: {
2058 int iDbLast
; /* Loop termination point for the schema loop */
2059 int iTabCur
; /* Cursor for a table whose size needs checking */
2060 HashElem
*k
; /* Loop over tables of a schema */
2061 Schema
*pSchema
; /* The current schema */
2062 Table
*pTab
; /* A table in the schema */
2063 Index
*pIdx
; /* An index of the table */
2064 LogEst szThreshold
; /* Size threshold above which reanalysis is needd */
2065 char *zSubSql
; /* SQL statement for the OP_SqlExec opcode */
2066 u32 opMask
; /* Mask of operations to perform */
2069 opMask
= (u32
)sqlite3Atoi(zRight
);
2070 if( (opMask
& 0x02)==0 ) break;
2074 iTabCur
= pParse
->nTab
++;
2075 for(iDbLast
= zDb
?iDb
:db
->nDb
-1; iDb
<=iDbLast
; iDb
++){
2076 if( iDb
==1 ) continue;
2077 sqlite3CodeVerifySchema(pParse
, iDb
);
2078 pSchema
= db
->aDb
[iDb
].pSchema
;
2079 for(k
=sqliteHashFirst(&pSchema
->tblHash
); k
; k
=sqliteHashNext(k
)){
2080 pTab
= (Table
*)sqliteHashData(k
);
2082 /* If table pTab has not been used in a way that would benefit from
2083 ** having analysis statistics during the current session, then skip it.
2084 ** This also has the effect of skipping virtual tables and views */
2085 if( (pTab
->tabFlags
& TF_StatsUsed
)==0 ) continue;
2087 /* Reanalyze if the table is 25 times larger than the last analysis */
2088 szThreshold
= pTab
->nRowLogEst
+ 46; assert( sqlite3LogEst(25)==46 );
2089 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
2090 if( !pIdx
->hasStat1
){
2091 szThreshold
= 0; /* Always analyze if any index lacks statistics */
2096 sqlite3OpenTable(pParse
, iTabCur
, iDb
, pTab
, OP_OpenRead
);
2097 sqlite3VdbeAddOp3(v
, OP_IfSmaller
, iTabCur
,
2098 sqlite3VdbeCurrentAddr(v
)+2+(opMask
&1), szThreshold
);
2101 zSubSql
= sqlite3MPrintf(db
, "ANALYZE \"%w\".\"%w\"",
2102 db
->aDb
[iDb
].zDbSName
, pTab
->zName
);
2103 if( opMask
& 0x01 ){
2104 int r1
= sqlite3GetTempReg(pParse
);
2105 sqlite3VdbeAddOp4(v
, OP_String8
, 0, r1
, 0, zSubSql
, P4_DYNAMIC
);
2106 sqlite3VdbeAddOp2(v
, OP_ResultRow
, r1
, 1);
2108 sqlite3VdbeAddOp4(v
, OP_SqlExec
, 0, 0, 0, zSubSql
, P4_DYNAMIC
);
2112 sqlite3VdbeAddOp0(v
, OP_Expire
);
2117 ** PRAGMA busy_timeout
2118 ** PRAGMA busy_timeout = N
2120 ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
2121 ** if one is set. If no busy handler or a different busy handler is set
2122 ** then 0 is returned. Setting the busy_timeout to 0 or negative
2123 ** disables the timeout.
2125 /*case PragTyp_BUSY_TIMEOUT*/ default: {
2126 assert( pPragma
->ePragTyp
==PragTyp_BUSY_TIMEOUT
);
2128 sqlite3_busy_timeout(db
, sqlite3Atoi(zRight
));
2130 returnSingleInt(v
, db
->busyTimeout
);
2135 ** PRAGMA soft_heap_limit
2136 ** PRAGMA soft_heap_limit = N
2138 ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
2139 ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
2140 ** specified and is a non-negative integer.
2141 ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
2142 ** returns the same integer that would be returned by the
2143 ** sqlite3_soft_heap_limit64(-1) C-language function.
2145 case PragTyp_SOFT_HEAP_LIMIT
: {
2147 if( zRight
&& sqlite3DecOrHexToI64(zRight
, &N
)==SQLITE_OK
){
2148 sqlite3_soft_heap_limit64(N
);
2150 returnSingleInt(v
, sqlite3_soft_heap_limit64(-1));
2155 ** PRAGMA hard_heap_limit
2156 ** PRAGMA hard_heap_limit = N
2158 ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap
2159 ** limit. The hard heap limit can be activated or lowered by this
2160 ** pragma, but not raised or deactivated. Only the
2161 ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate
2162 ** the hard heap limit. This allows an application to set a heap limit
2163 ** constraint that cannot be relaxed by an untrusted SQL script.
2165 case PragTyp_HARD_HEAP_LIMIT
: {
2167 if( zRight
&& sqlite3DecOrHexToI64(zRight
, &N
)==SQLITE_OK
){
2168 sqlite3_int64 iPrior
= sqlite3_hard_heap_limit64(-1);
2169 if( N
>0 && (iPrior
==0 || iPrior
>N
) ) sqlite3_hard_heap_limit64(N
);
2171 returnSingleInt(v
, sqlite3_hard_heap_limit64(-1));
2177 ** PRAGMA threads = N
2179 ** Configure the maximum number of worker threads. Return the new
2180 ** maximum, which might be less than requested.
2182 case PragTyp_THREADS
: {
2185 && sqlite3DecOrHexToI64(zRight
, &N
)==SQLITE_OK
2188 sqlite3_limit(db
, SQLITE_LIMIT_WORKER_THREADS
, (int)(N
&0x7fffffff));
2190 returnSingleInt(v
, sqlite3_limit(db
, SQLITE_LIMIT_WORKER_THREADS
, -1));
2195 ** PRAGMA analysis_limit
2196 ** PRAGMA analysis_limit = N
2198 ** Configure the maximum number of rows that ANALYZE will examine
2199 ** in each index that it looks at. Return the new limit.
2201 case PragTyp_ANALYSIS_LIMIT
: {
2204 && sqlite3DecOrHexToI64(zRight
, &N
)==SQLITE_OK
2207 db
->nAnalysisLimit
= (int)(N
&0x7fffffff);
2209 returnSingleInt(v
, db
->nAnalysisLimit
);
2213 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
2215 ** Report the current state of file logs for all databases
2217 case PragTyp_LOCK_STATUS
: {
2218 static const char *const azLockName
[] = {
2219 "unlocked", "shared", "reserved", "pending", "exclusive"
2223 for(i
=0; i
<db
->nDb
; i
++){
2225 const char *zState
= "unknown";
2227 if( db
->aDb
[i
].zDbSName
==0 ) continue;
2228 pBt
= db
->aDb
[i
].pBt
;
2229 if( pBt
==0 || sqlite3BtreePager(pBt
)==0 ){
2231 }else if( sqlite3_file_control(db
, i
? db
->aDb
[i
].zDbSName
: 0,
2232 SQLITE_FCNTL_LOCKSTATE
, &j
)==SQLITE_OK
){
2233 zState
= azLockName
[j
];
2235 sqlite3VdbeMultiLoad(v
, 1, "ss", db
->aDb
[i
].zDbSName
, zState
);
2241 /* BEGIN SQLCIPHER */
2242 #ifdef SQLITE_HAS_CODEC
2244 ** ---------- ------
2255 const char *zKey
= zRight
;
2257 if( pPragma
->iArg
==2 || pPragma
->iArg
==3 ){
2260 for(i
=0, iByte
=0; i
<sizeof(zBuf
)*2 && sqlite3Isxdigit(zRight
[i
]); i
++){
2261 iByte
= (iByte
<<4) + sqlite3HexToInt(zRight
[i
]);
2262 if( (i
&1)!=0 ) zBuf
[i
/2] = iByte
;
2267 n
= pPragma
->iArg
<4 ? sqlite3Strlen30(zRight
) : -1;
2269 if( (pPragma
->iArg
& 1)==0 ){
2270 rc
= sqlite3_key_v2(db
, zDb
, zKey
, n
);
2272 rc
= sqlite3_rekey_v2(db
, zDb
, zKey
, n
);
2274 if( rc
==SQLITE_OK
&& n
!=0 ){
2275 sqlite3VdbeSetNumCols(v
, 1);
2276 sqlite3VdbeSetColName(v
, 0, COLNAME_NAME
, "ok", SQLITE_STATIC
);
2277 returnSingleText(v
, "ok");
2284 #if defined(SQLITE_ENABLE_CEROD)
2285 case PragTyp_ACTIVATE_EXTENSIONS
: if( zRight
){
2286 if( sqlite3StrNICmp(zRight
, "cerod-", 6)==0 ){
2287 sqlite3_activate_cerod(&zRight
[6]);
2293 } /* End of the PRAGMA switch */
2295 /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
2296 ** purpose is to execute assert() statements to verify that if the
2297 ** PragFlg_NoColumns1 flag is set and the caller specified an argument
2298 ** to the PRAGMA, the implementation has not added any OP_ResultRow
2299 ** instructions to the VM. */
2300 if( (pPragma
->mPragFlg
& PragFlg_NoColumns1
) && zRight
){
2301 sqlite3VdbeVerifyNoResultRow(v
);
2305 sqlite3DbFree(db
, zLeft
);
2306 sqlite3DbFree(db
, zRight
);
2308 #ifndef SQLITE_OMIT_VIRTUALTABLE
2309 /*****************************************************************************
2310 ** Implementation of an eponymous virtual table that runs a pragma.
2313 typedef struct PragmaVtab PragmaVtab
;
2314 typedef struct PragmaVtabCursor PragmaVtabCursor
;
2316 sqlite3_vtab base
; /* Base class. Must be first */
2317 sqlite3
*db
; /* The database connection to which it belongs */
2318 const PragmaName
*pName
; /* Name of the pragma */
2319 u8 nHidden
; /* Number of hidden columns */
2320 u8 iHidden
; /* Index of the first hidden column */
2322 struct PragmaVtabCursor
{
2323 sqlite3_vtab_cursor base
; /* Base class. Must be first */
2324 sqlite3_stmt
*pPragma
; /* The pragma statement to run */
2325 sqlite_int64 iRowid
; /* Current rowid */
2326 char *azArg
[2]; /* Value of the argument and schema */
2330 ** Pragma virtual table module xConnect method.
2332 static int pragmaVtabConnect(
2335 int argc
, const char *const*argv
,
2336 sqlite3_vtab
**ppVtab
,
2339 const PragmaName
*pPragma
= (const PragmaName
*)pAux
;
2340 PragmaVtab
*pTab
= 0;
2347 UNUSED_PARAMETER(argc
);
2348 UNUSED_PARAMETER(argv
);
2349 sqlite3StrAccumInit(&acc
, 0, zBuf
, sizeof(zBuf
), 0);
2350 sqlite3_str_appendall(&acc
, "CREATE TABLE x");
2351 for(i
=0, j
=pPragma
->iPragCName
; i
<pPragma
->nPragCName
; i
++, j
++){
2352 sqlite3_str_appendf(&acc
, "%c\"%s\"", cSep
, pragCName
[j
]);
2356 sqlite3_str_appendf(&acc
, "(\"%s\"", pPragma
->zName
);
2360 if( pPragma
->mPragFlg
& PragFlg_Result1
){
2361 sqlite3_str_appendall(&acc
, ",arg HIDDEN");
2364 if( pPragma
->mPragFlg
& (PragFlg_SchemaOpt
|PragFlg_SchemaReq
) ){
2365 sqlite3_str_appendall(&acc
, ",schema HIDDEN");
2368 sqlite3_str_append(&acc
, ")", 1);
2369 sqlite3StrAccumFinish(&acc
);
2370 assert( strlen(zBuf
) < sizeof(zBuf
)-1 );
2371 rc
= sqlite3_declare_vtab(db
, zBuf
);
2372 if( rc
==SQLITE_OK
){
2373 pTab
= (PragmaVtab
*)sqlite3_malloc(sizeof(PragmaVtab
));
2377 memset(pTab
, 0, sizeof(PragmaVtab
));
2378 pTab
->pName
= pPragma
;
2384 *pzErr
= sqlite3_mprintf("%s", sqlite3_errmsg(db
));
2387 *ppVtab
= (sqlite3_vtab
*)pTab
;
2392 ** Pragma virtual table module xDisconnect method.
2394 static int pragmaVtabDisconnect(sqlite3_vtab
*pVtab
){
2395 PragmaVtab
*pTab
= (PragmaVtab
*)pVtab
;
2400 /* Figure out the best index to use to search a pragma virtual table.
2402 ** There are not really any index choices. But we want to encourage the
2403 ** query planner to give == constraints on as many hidden parameters as
2404 ** possible, and especially on the first hidden parameter. So return a
2405 ** high cost if hidden parameters are unconstrained.
2407 static int pragmaVtabBestIndex(sqlite3_vtab
*tab
, sqlite3_index_info
*pIdxInfo
){
2408 PragmaVtab
*pTab
= (PragmaVtab
*)tab
;
2409 const struct sqlite3_index_constraint
*pConstraint
;
2413 pIdxInfo
->estimatedCost
= (double)1;
2414 if( pTab
->nHidden
==0 ){ return SQLITE_OK
; }
2415 pConstraint
= pIdxInfo
->aConstraint
;
2418 for(i
=0; i
<pIdxInfo
->nConstraint
; i
++, pConstraint
++){
2419 if( pConstraint
->usable
==0 ) continue;
2420 if( pConstraint
->op
!=SQLITE_INDEX_CONSTRAINT_EQ
) continue;
2421 if( pConstraint
->iColumn
< pTab
->iHidden
) continue;
2422 j
= pConstraint
->iColumn
- pTab
->iHidden
;
2427 pIdxInfo
->estimatedCost
= (double)2147483647;
2428 pIdxInfo
->estimatedRows
= 2147483647;
2432 pIdxInfo
->aConstraintUsage
[j
].argvIndex
= 1;
2433 pIdxInfo
->aConstraintUsage
[j
].omit
= 1;
2434 if( seen
[1]==0 ) return SQLITE_OK
;
2435 pIdxInfo
->estimatedCost
= (double)20;
2436 pIdxInfo
->estimatedRows
= 20;
2438 pIdxInfo
->aConstraintUsage
[j
].argvIndex
= 2;
2439 pIdxInfo
->aConstraintUsage
[j
].omit
= 1;
2443 /* Create a new cursor for the pragma virtual table */
2444 static int pragmaVtabOpen(sqlite3_vtab
*pVtab
, sqlite3_vtab_cursor
**ppCursor
){
2445 PragmaVtabCursor
*pCsr
;
2446 pCsr
= (PragmaVtabCursor
*)sqlite3_malloc(sizeof(*pCsr
));
2447 if( pCsr
==0 ) return SQLITE_NOMEM
;
2448 memset(pCsr
, 0, sizeof(PragmaVtabCursor
));
2449 pCsr
->base
.pVtab
= pVtab
;
2450 *ppCursor
= &pCsr
->base
;
2454 /* Clear all content from pragma virtual table cursor. */
2455 static void pragmaVtabCursorClear(PragmaVtabCursor
*pCsr
){
2457 sqlite3_finalize(pCsr
->pPragma
);
2459 for(i
=0; i
<ArraySize(pCsr
->azArg
); i
++){
2460 sqlite3_free(pCsr
->azArg
[i
]);
2465 /* Close a pragma virtual table cursor */
2466 static int pragmaVtabClose(sqlite3_vtab_cursor
*cur
){
2467 PragmaVtabCursor
*pCsr
= (PragmaVtabCursor
*)cur
;
2468 pragmaVtabCursorClear(pCsr
);
2473 /* Advance the pragma virtual table cursor to the next row */
2474 static int pragmaVtabNext(sqlite3_vtab_cursor
*pVtabCursor
){
2475 PragmaVtabCursor
*pCsr
= (PragmaVtabCursor
*)pVtabCursor
;
2478 /* Increment the xRowid value */
2480 assert( pCsr
->pPragma
);
2481 if( SQLITE_ROW
!=sqlite3_step(pCsr
->pPragma
) ){
2482 rc
= sqlite3_finalize(pCsr
->pPragma
);
2484 pragmaVtabCursorClear(pCsr
);
2490 ** Pragma virtual table module xFilter method.
2492 static int pragmaVtabFilter(
2493 sqlite3_vtab_cursor
*pVtabCursor
,
2494 int idxNum
, const char *idxStr
,
2495 int argc
, sqlite3_value
**argv
2497 PragmaVtabCursor
*pCsr
= (PragmaVtabCursor
*)pVtabCursor
;
2498 PragmaVtab
*pTab
= (PragmaVtab
*)(pVtabCursor
->pVtab
);
2504 UNUSED_PARAMETER(idxNum
);
2505 UNUSED_PARAMETER(idxStr
);
2506 pragmaVtabCursorClear(pCsr
);
2507 j
= (pTab
->pName
->mPragFlg
& PragFlg_Result1
)!=0 ? 0 : 1;
2508 for(i
=0; i
<argc
; i
++, j
++){
2509 const char *zText
= (const char*)sqlite3_value_text(argv
[i
]);
2510 assert( j
<ArraySize(pCsr
->azArg
) );
2511 assert( pCsr
->azArg
[j
]==0 );
2513 pCsr
->azArg
[j
] = sqlite3_mprintf("%s", zText
);
2514 if( pCsr
->azArg
[j
]==0 ){
2515 return SQLITE_NOMEM
;
2519 sqlite3StrAccumInit(&acc
, 0, 0, 0, pTab
->db
->aLimit
[SQLITE_LIMIT_SQL_LENGTH
]);
2520 sqlite3_str_appendall(&acc
, "PRAGMA ");
2521 if( pCsr
->azArg
[1] ){
2522 sqlite3_str_appendf(&acc
, "%Q.", pCsr
->azArg
[1]);
2524 sqlite3_str_appendall(&acc
, pTab
->pName
->zName
);
2525 if( pCsr
->azArg
[0] ){
2526 sqlite3_str_appendf(&acc
, "=%Q", pCsr
->azArg
[0]);
2528 zSql
= sqlite3StrAccumFinish(&acc
);
2529 if( zSql
==0 ) return SQLITE_NOMEM
;
2530 rc
= sqlite3_prepare_v2(pTab
->db
, zSql
, -1, &pCsr
->pPragma
, 0);
2532 if( rc
!=SQLITE_OK
){
2533 pTab
->base
.zErrMsg
= sqlite3_mprintf("%s", sqlite3_errmsg(pTab
->db
));
2536 return pragmaVtabNext(pVtabCursor
);
2540 ** Pragma virtual table module xEof method.
2542 static int pragmaVtabEof(sqlite3_vtab_cursor
*pVtabCursor
){
2543 PragmaVtabCursor
*pCsr
= (PragmaVtabCursor
*)pVtabCursor
;
2544 return (pCsr
->pPragma
==0);
2547 /* The xColumn method simply returns the corresponding column from
2550 static int pragmaVtabColumn(
2551 sqlite3_vtab_cursor
*pVtabCursor
,
2552 sqlite3_context
*ctx
,
2555 PragmaVtabCursor
*pCsr
= (PragmaVtabCursor
*)pVtabCursor
;
2556 PragmaVtab
*pTab
= (PragmaVtab
*)(pVtabCursor
->pVtab
);
2557 if( i
<pTab
->iHidden
){
2558 sqlite3_result_value(ctx
, sqlite3_column_value(pCsr
->pPragma
, i
));
2560 sqlite3_result_text(ctx
, pCsr
->azArg
[i
-pTab
->iHidden
],-1,SQLITE_TRANSIENT
);
2566 ** Pragma virtual table module xRowid method.
2568 static int pragmaVtabRowid(sqlite3_vtab_cursor
*pVtabCursor
, sqlite_int64
*p
){
2569 PragmaVtabCursor
*pCsr
= (PragmaVtabCursor
*)pVtabCursor
;
2574 /* The pragma virtual table object */
2575 static const sqlite3_module pragmaVtabModule
= {
2577 0, /* xCreate - create a table */
2578 pragmaVtabConnect
, /* xConnect - connect to an existing table */
2579 pragmaVtabBestIndex
, /* xBestIndex - Determine search strategy */
2580 pragmaVtabDisconnect
, /* xDisconnect - Disconnect from a table */
2581 0, /* xDestroy - Drop a table */
2582 pragmaVtabOpen
, /* xOpen - open a cursor */
2583 pragmaVtabClose
, /* xClose - close a cursor */
2584 pragmaVtabFilter
, /* xFilter - configure scan constraints */
2585 pragmaVtabNext
, /* xNext - advance a cursor */
2586 pragmaVtabEof
, /* xEof */
2587 pragmaVtabColumn
, /* xColumn - read data */
2588 pragmaVtabRowid
, /* xRowid - read data */
2589 0, /* xUpdate - write data */
2590 0, /* xBegin - begin transaction */
2591 0, /* xSync - sync transaction */
2592 0, /* xCommit - commit transaction */
2593 0, /* xRollback - rollback transaction */
2594 0, /* xFindFunction - function overloading */
2595 0, /* xRename - rename the table */
2598 0, /* xRollbackTo */
2603 ** Check to see if zTabName is really the name of a pragma. If it is,
2604 ** then register an eponymous virtual table for that pragma and return
2605 ** a pointer to the Module object for the new virtual table.
2607 Module
*sqlite3PragmaVtabRegister(sqlite3
*db
, const char *zName
){
2608 const PragmaName
*pName
;
2609 assert( sqlite3_strnicmp(zName
, "pragma_", 7)==0 );
2610 pName
= pragmaLocate(zName
+7);
2611 if( pName
==0 ) return 0;
2612 if( (pName
->mPragFlg
& (PragFlg_Result0
|PragFlg_Result1
))==0 ) return 0;
2613 assert( sqlite3HashFind(&db
->aModule
, zName
)==0 );
2614 return sqlite3VtabCreateModule(db
, zName
, &pragmaVtabModule
, (void*)pName
, 0);
2617 #endif /* SQLITE_OMIT_VIRTUALTABLE */
2619 #endif /* SQLITE_OMIT_PRAGMA */