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 ){
135 || sqlite3BtreeTxnState(db
->aDb
[1].pBt
)!=SQLITE_TXN_NONE
137 sqlite3ErrorMsg(pParse
, "temporary storage cannot be changed "
138 "from within a transaction");
141 sqlite3BtreeClose(db
->aDb
[1].pBt
);
143 sqlite3ResetAllSchemasOfConnection(db
);
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
){
162 db
->temp_store
= (u8
)ts
;
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
);
177 sqlite3VdbeSetColName(v
, 0, COLNAME_NAME
, pPragma
->zName
, SQLITE_STATIC
);
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 */
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
){
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
);
225 sqlite3BtreeSetPagerFlags(pDb
->pBt
,
226 pDb
->safety_level
| (db
->flags
& PAGER_FLAGS_MASK
) );
233 # define setAllPagerFlags(X) /* no-op */
238 ** Return a human-readable name for a constraint resolution action.
240 #ifndef SQLITE_OMIT_FOREIGN_KEY
241 static const char *actionName(u8 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;
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
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
;
286 upr
= ArraySize(aPragmaName
)-1;
289 rc
= sqlite3_stricmp(zName
, aPragmaName
[mid
].zName
);
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 */
311 SQLITE_DETERMINISTIC
|
317 if( showInternFuncs
) mask
= 0xffffffff;
318 for(; p
; p
=p
->pNext
){
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
335 }else if( p
->xFinalize
!=0 ){
340 sqlite3VdbeMultiLoad(v
, 1, "sissii",
342 zType
, azEnc
[p
->funcFlags
&SQLITE_FUNC_ENCMASK
],
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
){
359 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 3, 1);
360 addr
= sqlite3VdbeAddOp3(v
, OP_IfPos
, 1, sqlite3VdbeCurrentAddr(v
)+2, 1);
362 sqlite3VdbeAddOp0(v
, OP_Halt
);
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.
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 */
401 sqlite3VdbeRunOnlyOnce(v
);
404 /* Interpret the [schema.] part of the pragma statement. iDb is the
405 ** index of the database this pragma is being applied to in db.aDb[]. */
406 iDb
= sqlite3TwoPartName(pParse
, pId1
, pId2
, &pId
);
410 /* If the temp database has been explicitly named as part of the
411 ** pragma, make sure it is open.
413 if( iDb
==1 && sqlite3OpenTempDatabase(pParse
) ){
417 zLeft
= sqlite3NameFromToken(db
, pId
);
420 zRight
= sqlite3MPrintf(db
, "-%T", pValue
);
422 zRight
= sqlite3NameFromToken(db
, pValue
);
426 zDb
= pId2
->n
>0 ? pDb
->zDbSName
: 0;
427 if( sqlite3AuthCheck(pParse
, SQLITE_PRAGMA
, zLeft
, zRight
, zDb
) ){
431 /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
432 ** connection. If it returns SQLITE_OK, then assume that the VFS
433 ** handled the pragma and generate a no-op prepared statement.
435 ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
436 ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
437 ** object corresponding to the database file to which the pragma
440 ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
441 ** file control is an array of pointers to strings (char**) in which the
442 ** second element of the array is the name of the pragma and the third
443 ** element is the argument to the pragma or NULL if the pragma has no
450 db
->busyHandler
.nBusy
= 0;
451 rc
= sqlite3_file_control(db
, zDb
, SQLITE_FCNTL_PRAGMA
, (void*)aFcntl
);
453 sqlite3VdbeSetNumCols(v
, 1);
454 sqlite3VdbeSetColName(v
, 0, COLNAME_NAME
, aFcntl
[0], SQLITE_TRANSIENT
);
455 returnSingleText(v
, aFcntl
[0]);
456 sqlite3_free(aFcntl
[0]);
459 if( rc
!=SQLITE_NOTFOUND
){
461 sqlite3ErrorMsg(pParse
, "%s", aFcntl
[0]);
462 sqlite3_free(aFcntl
[0]);
469 /* Locate the pragma in the lookup table */
470 pPragma
= pragmaLocate(zLeft
);
472 /* IMP: R-43042-22504 No error messages are generated if an
473 ** unknown pragma is issued. */
477 /* Make sure the database schema is loaded if the pragma requires that */
478 if( (pPragma
->mPragFlg
& PragFlg_NeedSchema
)!=0 ){
479 if( sqlite3ReadSchema(pParse
) ) goto pragma_out
;
482 /* Register the result column names for pragmas that return results */
483 if( (pPragma
->mPragFlg
& PragFlg_NoColumns
)==0
484 && ((pPragma
->mPragFlg
& PragFlg_NoColumns1
)==0 || zRight
==0)
486 setPragmaResultColumnNames(v
, pPragma
);
489 /* Jump to the appropriate pragma handler */
490 switch( pPragma
->ePragTyp
){
492 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
494 ** PRAGMA [schema.]default_cache_size
495 ** PRAGMA [schema.]default_cache_size=N
497 ** The first form reports the current persistent setting for the
498 ** page cache size. The value returned is the maximum number of
499 ** pages in the page cache. The second form sets both the current
500 ** page cache size value and the persistent page cache size value
501 ** stored in the database file.
503 ** Older versions of SQLite would set the default cache size to a
504 ** negative number to indicate synchronous=OFF. These days, synchronous
505 ** is always on by default regardless of the sign of the default cache
506 ** size. But continue to take the absolute value of the default cache
507 ** size of historical compatibility.
509 case PragTyp_DEFAULT_CACHE_SIZE
: {
510 static const int iLn
= VDBE_OFFSET_LINENO(2);
511 static const VdbeOpList getCacheSize
[] = {
512 { OP_Transaction
, 0, 0, 0}, /* 0 */
513 { OP_ReadCookie
, 0, 1, BTREE_DEFAULT_CACHE_SIZE
}, /* 1 */
514 { OP_IfPos
, 1, 8, 0},
515 { OP_Integer
, 0, 2, 0},
516 { OP_Subtract
, 1, 2, 1},
517 { OP_IfPos
, 1, 8, 0},
518 { OP_Integer
, 0, 1, 0}, /* 6 */
520 { OP_ResultRow
, 1, 1, 0},
523 sqlite3VdbeUsesBtree(v
, iDb
);
526 sqlite3VdbeVerifyNoMallocRequired(v
, ArraySize(getCacheSize
));
527 aOp
= sqlite3VdbeAddOpList(v
, ArraySize(getCacheSize
), getCacheSize
, iLn
);
528 if( ONLY_IF_REALLOC_STRESS(aOp
==0) ) break;
531 aOp
[6].p1
= SQLITE_DEFAULT_CACHE_SIZE
;
533 int size
= sqlite3AbsInt32(sqlite3Atoi(zRight
));
534 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
535 sqlite3VdbeAddOp3(v
, OP_SetCookie
, iDb
, BTREE_DEFAULT_CACHE_SIZE
, size
);
536 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
537 pDb
->pSchema
->cache_size
= size
;
538 sqlite3BtreeSetCacheSize(pDb
->pBt
, pDb
->pSchema
->cache_size
);
542 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
544 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
546 ** PRAGMA [schema.]page_size
547 ** PRAGMA [schema.]page_size=N
549 ** The first form reports the current setting for the
550 ** database page size in bytes. The second form sets the
551 ** database page size value. The value can only be set if
552 ** the database has not yet been created.
554 case PragTyp_PAGE_SIZE
: {
555 Btree
*pBt
= pDb
->pBt
;
558 int size
= ALWAYS(pBt
) ? sqlite3BtreeGetPageSize(pBt
) : 0;
559 returnSingleInt(v
, size
);
561 /* Malloc may fail when setting the page-size, as there is an internal
562 ** buffer that the pager module resizes using sqlite3_realloc().
564 db
->nextPagesize
= sqlite3Atoi(zRight
);
565 if( SQLITE_NOMEM
==sqlite3BtreeSetPageSize(pBt
, db
->nextPagesize
,0,0) ){
573 ** PRAGMA [schema.]secure_delete
574 ** PRAGMA [schema.]secure_delete=ON/OFF/FAST
576 ** The first form reports the current setting for the
577 ** secure_delete flag. The second form changes the secure_delete
578 ** flag setting and reports the new value.
580 case PragTyp_SECURE_DELETE
: {
581 Btree
*pBt
= pDb
->pBt
;
585 if( sqlite3_stricmp(zRight
, "fast")==0 ){
588 b
= sqlite3GetBoolean(zRight
, 0);
591 if( pId2
->n
==0 && b
>=0 ){
593 for(ii
=0; ii
<db
->nDb
; ii
++){
594 sqlite3BtreeSecureDelete(db
->aDb
[ii
].pBt
, b
);
597 b
= sqlite3BtreeSecureDelete(pBt
, b
);
598 returnSingleInt(v
, b
);
603 ** PRAGMA [schema.]max_page_count
604 ** PRAGMA [schema.]max_page_count=N
606 ** The first form reports the current setting for the
607 ** maximum number of pages in the database file. The
608 ** second form attempts to change this setting. Both
609 ** forms return the current setting.
611 ** The absolute value of N is used. This is undocumented and might
612 ** change. The only purpose is to provide an easy way to test
613 ** the sqlite3AbsInt32() function.
615 ** PRAGMA [schema.]page_count
617 ** Return the number of pages in the specified database.
619 case PragTyp_PAGE_COUNT
: {
622 sqlite3CodeVerifySchema(pParse
, iDb
);
623 iReg
= ++pParse
->nMem
;
624 if( sqlite3Tolower(zLeft
[0])=='p' ){
625 sqlite3VdbeAddOp2(v
, OP_Pagecount
, iDb
, iReg
);
627 if( zRight
&& sqlite3DecOrHexToI64(zRight
,&x
)==0 ){
629 else if( x
>0xfffffffe ) x
= 0xfffffffe;
633 sqlite3VdbeAddOp3(v
, OP_MaxPgcnt
, iDb
, iReg
, (int)x
);
635 sqlite3VdbeAddOp2(v
, OP_ResultRow
, iReg
, 1);
640 ** PRAGMA [schema.]locking_mode
641 ** PRAGMA [schema.]locking_mode = (normal|exclusive)
643 case PragTyp_LOCKING_MODE
: {
644 const char *zRet
= "normal";
645 int eMode
= getLockingMode(zRight
);
647 if( pId2
->n
==0 && eMode
==PAGER_LOCKINGMODE_QUERY
){
648 /* Simple "PRAGMA locking_mode;" statement. This is a query for
649 ** the current default locking mode (which may be different to
650 ** the locking-mode of the main database).
652 eMode
= db
->dfltLockMode
;
656 /* This indicates that no database name was specified as part
657 ** of the PRAGMA command. In this case the locking-mode must be
658 ** set on all attached databases, as well as the main db file.
660 ** Also, the sqlite3.dfltLockMode variable is set so that
661 ** any subsequently attached databases also use the specified
665 assert(pDb
==&db
->aDb
[0]);
666 for(ii
=2; ii
<db
->nDb
; ii
++){
667 pPager
= sqlite3BtreePager(db
->aDb
[ii
].pBt
);
668 sqlite3PagerLockingMode(pPager
, eMode
);
670 db
->dfltLockMode
= (u8
)eMode
;
672 pPager
= sqlite3BtreePager(pDb
->pBt
);
673 eMode
= sqlite3PagerLockingMode(pPager
, eMode
);
676 assert( eMode
==PAGER_LOCKINGMODE_NORMAL
677 || eMode
==PAGER_LOCKINGMODE_EXCLUSIVE
);
678 if( eMode
==PAGER_LOCKINGMODE_EXCLUSIVE
){
681 returnSingleText(v
, zRet
);
686 ** PRAGMA [schema.]journal_mode
687 ** PRAGMA [schema.]journal_mode =
688 ** (delete|persist|off|truncate|memory|wal|off)
690 case PragTyp_JOURNAL_MODE
: {
691 int eMode
; /* One of the PAGER_JOURNALMODE_XXX symbols */
692 int ii
; /* Loop counter */
695 /* If there is no "=MODE" part of the pragma, do a query for the
697 eMode
= PAGER_JOURNALMODE_QUERY
;
700 int n
= sqlite3Strlen30(zRight
);
701 for(eMode
=0; (zMode
= sqlite3JournalModename(eMode
))!=0; eMode
++){
702 if( sqlite3StrNICmp(zRight
, zMode
, n
)==0 ) break;
705 /* If the "=MODE" part does not match any known journal mode,
706 ** then do a query */
707 eMode
= PAGER_JOURNALMODE_QUERY
;
709 if( eMode
==PAGER_JOURNALMODE_OFF
&& (db
->flags
& SQLITE_Defensive
)!=0 ){
710 /* Do not allow journal-mode "OFF" in defensive since the database
711 ** can become corrupted using ordinary SQL when the journal is off */
712 eMode
= PAGER_JOURNALMODE_QUERY
;
715 if( eMode
==PAGER_JOURNALMODE_QUERY
&& pId2
->n
==0 ){
716 /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
720 for(ii
=db
->nDb
-1; ii
>=0; ii
--){
721 if( db
->aDb
[ii
].pBt
&& (ii
==iDb
|| pId2
->n
==0) ){
722 sqlite3VdbeUsesBtree(v
, ii
);
723 sqlite3VdbeAddOp3(v
, OP_JournalMode
, ii
, 1, eMode
);
726 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, 1);
731 ** PRAGMA [schema.]journal_size_limit
732 ** PRAGMA [schema.]journal_size_limit=N
734 ** Get or set the size limit on rollback journal files.
736 case PragTyp_JOURNAL_SIZE_LIMIT
: {
737 Pager
*pPager
= sqlite3BtreePager(pDb
->pBt
);
740 sqlite3DecOrHexToI64(zRight
, &iLimit
);
741 if( iLimit
<-1 ) iLimit
= -1;
743 iLimit
= sqlite3PagerJournalSizeLimit(pPager
, iLimit
);
744 returnSingleInt(v
, iLimit
);
748 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
751 ** PRAGMA [schema.]auto_vacuum
752 ** PRAGMA [schema.]auto_vacuum=N
754 ** Get or set the value of the database 'auto-vacuum' parameter.
755 ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
757 #ifndef SQLITE_OMIT_AUTOVACUUM
758 case PragTyp_AUTO_VACUUM
: {
759 Btree
*pBt
= pDb
->pBt
;
762 returnSingleInt(v
, sqlite3BtreeGetAutoVacuum(pBt
));
764 int eAuto
= getAutoVacuum(zRight
);
765 assert( eAuto
>=0 && eAuto
<=2 );
766 db
->nextAutovac
= (u8
)eAuto
;
767 /* Call SetAutoVacuum() to set initialize the internal auto and
768 ** incr-vacuum flags. This is required in case this connection
769 ** creates the database file. It is important that it is created
770 ** as an auto-vacuum capable db.
772 rc
= sqlite3BtreeSetAutoVacuum(pBt
, eAuto
);
773 if( rc
==SQLITE_OK
&& (eAuto
==1 || eAuto
==2) ){
774 /* When setting the auto_vacuum mode to either "full" or
775 ** "incremental", write the value of meta[6] in the database
776 ** file. Before writing to meta[6], check that meta[3] indicates
777 ** that this really is an auto-vacuum capable database.
779 static const int iLn
= VDBE_OFFSET_LINENO(2);
780 static const VdbeOpList setMeta6
[] = {
781 { OP_Transaction
, 0, 1, 0}, /* 0 */
782 { OP_ReadCookie
, 0, 1, BTREE_LARGEST_ROOT_PAGE
},
783 { OP_If
, 1, 0, 0}, /* 2 */
784 { OP_Halt
, SQLITE_OK
, OE_Abort
, 0}, /* 3 */
785 { OP_SetCookie
, 0, BTREE_INCR_VACUUM
, 0}, /* 4 */
788 int iAddr
= sqlite3VdbeCurrentAddr(v
);
789 sqlite3VdbeVerifyNoMallocRequired(v
, ArraySize(setMeta6
));
790 aOp
= sqlite3VdbeAddOpList(v
, ArraySize(setMeta6
), setMeta6
, iLn
);
791 if( ONLY_IF_REALLOC_STRESS(aOp
==0) ) break;
796 aOp
[4].p3
= eAuto
- 1;
797 sqlite3VdbeUsesBtree(v
, iDb
);
805 ** PRAGMA [schema.]incremental_vacuum(N)
807 ** Do N steps of incremental vacuuming on a database.
809 #ifndef SQLITE_OMIT_AUTOVACUUM
810 case PragTyp_INCREMENTAL_VACUUM
: {
811 int iLimit
= 0, addr
;
812 if( zRight
==0 || !sqlite3GetInt32(zRight
, &iLimit
) || iLimit
<=0 ){
815 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
816 sqlite3VdbeAddOp2(v
, OP_Integer
, iLimit
, 1);
817 addr
= sqlite3VdbeAddOp1(v
, OP_IncrVacuum
, iDb
); VdbeCoverage(v
);
818 sqlite3VdbeAddOp1(v
, OP_ResultRow
, 1);
819 sqlite3VdbeAddOp2(v
, OP_AddImm
, 1, -1);
820 sqlite3VdbeAddOp2(v
, OP_IfPos
, 1, addr
); VdbeCoverage(v
);
821 sqlite3VdbeJumpHere(v
, addr
);
826 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
828 ** PRAGMA [schema.]cache_size
829 ** PRAGMA [schema.]cache_size=N
831 ** The first form reports the current local setting for the
832 ** page cache size. The second form sets the local
833 ** page cache size value. If N is positive then that is the
834 ** number of pages in the cache. If N is negative, then the
835 ** number of pages is adjusted so that the cache uses -N kibibytes
838 case PragTyp_CACHE_SIZE
: {
839 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
841 returnSingleInt(v
, pDb
->pSchema
->cache_size
);
843 int size
= sqlite3Atoi(zRight
);
844 pDb
->pSchema
->cache_size
= size
;
845 sqlite3BtreeSetCacheSize(pDb
->pBt
, pDb
->pSchema
->cache_size
);
851 ** PRAGMA [schema.]cache_spill
852 ** PRAGMA cache_spill=BOOLEAN
853 ** PRAGMA [schema.]cache_spill=N
855 ** The first form reports the current local setting for the
856 ** page cache spill size. The second form turns cache spill on
857 ** or off. When turning cache spill on, the size is set to the
858 ** current cache_size. The third form sets a spill size that
859 ** may be different form the cache size.
860 ** If N is positive then that is the
861 ** number of pages in the cache. If N is negative, then the
862 ** number of pages is adjusted so that the cache uses -N kibibytes
865 ** If the number of cache_spill pages is less then the number of
866 ** cache_size pages, no spilling occurs until the page count exceeds
867 ** the number of cache_size pages.
869 ** The cache_spill=BOOLEAN setting applies to all attached schemas,
870 ** not just the schema specified.
872 case PragTyp_CACHE_SPILL
: {
873 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
876 (db
->flags
& SQLITE_CacheSpill
)==0 ? 0 :
877 sqlite3BtreeSetSpillSize(pDb
->pBt
,0));
880 if( sqlite3GetInt32(zRight
, &size
) ){
881 sqlite3BtreeSetSpillSize(pDb
->pBt
, size
);
883 if( sqlite3GetBoolean(zRight
, size
!=0) ){
884 db
->flags
|= SQLITE_CacheSpill
;
886 db
->flags
&= ~(u64
)SQLITE_CacheSpill
;
888 setAllPagerFlags(db
);
894 ** PRAGMA [schema.]mmap_size(N)
896 ** Used to set mapping size limit. The mapping size limit is
897 ** used to limit the aggregate size of all memory mapped regions of the
898 ** database file. If this parameter is set to zero, then memory mapping
899 ** is not used at all. If N is negative, then the default memory map
900 ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
901 ** The parameter N is measured in bytes.
903 ** This value is advisory. The underlying VFS is free to memory map
904 ** as little or as much as it wants. Except, if N is set to 0 then the
905 ** upper layers will never invoke the xFetch interfaces to the VFS.
907 case PragTyp_MMAP_SIZE
: {
909 #if SQLITE_MAX_MMAP_SIZE>0
910 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
913 sqlite3DecOrHexToI64(zRight
, &sz
);
914 if( sz
<0 ) sz
= sqlite3GlobalConfig
.szMmap
;
915 if( pId2
->n
==0 ) db
->szMmap
= sz
;
916 for(ii
=db
->nDb
-1; ii
>=0; ii
--){
917 if( db
->aDb
[ii
].pBt
&& (ii
==iDb
|| pId2
->n
==0) ){
918 sqlite3BtreeSetMmapLimit(db
->aDb
[ii
].pBt
, sz
);
923 rc
= sqlite3_file_control(db
, zDb
, SQLITE_FCNTL_MMAP_SIZE
, &sz
);
929 returnSingleInt(v
, sz
);
930 }else if( rc
!=SQLITE_NOTFOUND
){
939 ** PRAGMA temp_store = "default"|"memory"|"file"
941 ** Return or set the local value of the temp_store flag. Changing
942 ** the local value does not make changes to the disk file and the default
943 ** value will be restored the next time the database is opened.
945 ** Note that it is possible for the library compile-time options to
946 ** override this setting
948 case PragTyp_TEMP_STORE
: {
950 returnSingleInt(v
, db
->temp_store
);
952 changeTempStorage(pParse
, zRight
);
958 ** PRAGMA temp_store_directory
959 ** PRAGMA temp_store_directory = ""|"directory_name"
961 ** Return or set the local value of the temp_store_directory flag. Changing
962 ** the value sets a specific directory to be used for temporary files.
963 ** Setting to a null string reverts to the default temporary directory search.
964 ** If temporary directory is changed, then invalidateTempStorage.
967 case PragTyp_TEMP_STORE_DIRECTORY
: {
968 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR
));
970 returnSingleText(v
, sqlite3_temp_directory
);
972 #ifndef SQLITE_OMIT_WSD
975 rc
= sqlite3OsAccess(db
->pVfs
, zRight
, SQLITE_ACCESS_READWRITE
, &res
);
976 if( rc
!=SQLITE_OK
|| res
==0 ){
977 sqlite3ErrorMsg(pParse
, "not a writable directory");
978 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR
));
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 */
996 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR
));
1002 ** PRAGMA data_store_directory
1003 ** PRAGMA data_store_directory = ""|"directory_name"
1005 ** Return or set the local value of the data_store_directory flag. Changing
1006 ** the value sets a specific directory to be used for database files that
1007 ** were specified with a relative pathname. Setting to a null string reverts
1008 ** to the default database directory, which for database files specified with
1009 ** a relative path will probably be based on the current directory for the
1010 ** process. Database file specified with an absolute path are not impacted
1011 ** by this setting, regardless of its value.
1014 case PragTyp_DATA_STORE_DIRECTORY
: {
1015 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR
));
1017 returnSingleText(v
, sqlite3_data_directory
);
1019 #ifndef SQLITE_OMIT_WSD
1022 rc
= sqlite3OsAccess(db
->pVfs
, zRight
, SQLITE_ACCESS_READWRITE
, &res
);
1023 if( rc
!=SQLITE_OK
|| res
==0 ){
1024 sqlite3ErrorMsg(pParse
, "not a writable directory");
1025 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR
));
1029 sqlite3_free(sqlite3_data_directory
);
1031 sqlite3_data_directory
= sqlite3_mprintf("%s", zRight
);
1033 sqlite3_data_directory
= 0;
1035 #endif /* SQLITE_OMIT_WSD */
1037 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR
));
1042 #if SQLITE_ENABLE_LOCKING_STYLE
1044 ** PRAGMA [schema.]lock_proxy_file
1045 ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
1047 ** Return or set the value of the lock_proxy_file flag. Changing
1048 ** the value sets a specific file to be used for database access locks.
1051 case PragTyp_LOCK_PROXY_FILE
: {
1053 Pager
*pPager
= sqlite3BtreePager(pDb
->pBt
);
1054 char *proxy_file_path
= NULL
;
1055 sqlite3_file
*pFile
= sqlite3PagerFile(pPager
);
1056 sqlite3OsFileControlHint(pFile
, SQLITE_GET_LOCKPROXYFILE
,
1058 returnSingleText(v
, proxy_file_path
);
1060 Pager
*pPager
= sqlite3BtreePager(pDb
->pBt
);
1061 sqlite3_file
*pFile
= sqlite3PagerFile(pPager
);
1064 res
=sqlite3OsFileControl(pFile
, SQLITE_SET_LOCKPROXYFILE
,
1067 res
=sqlite3OsFileControl(pFile
, SQLITE_SET_LOCKPROXYFILE
,
1070 if( res
!=SQLITE_OK
){
1071 sqlite3ErrorMsg(pParse
, "failed to set lock proxy file");
1077 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
1080 ** PRAGMA [schema.]synchronous
1081 ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
1083 ** Return or set the local value of the synchronous flag. Changing
1084 ** the local value does not make changes to the disk file and the
1085 ** default value will be restored the next time the database is
1088 case PragTyp_SYNCHRONOUS
: {
1090 returnSingleInt(v
, pDb
->safety_level
-1);
1092 if( !db
->autoCommit
){
1093 sqlite3ErrorMsg(pParse
,
1094 "Safety level may not be changed inside a transaction");
1096 int iLevel
= (getSafetyLevel(zRight
,0,1)+1) & PAGER_SYNCHRONOUS_MASK
;
1097 if( iLevel
==0 ) iLevel
= 1;
1098 pDb
->safety_level
= iLevel
;
1100 setAllPagerFlags(db
);
1105 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
1107 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
1108 case PragTyp_FLAG
: {
1110 setPragmaResultColumnNames(v
, pPragma
);
1111 returnSingleInt(v
, (db
->flags
& pPragma
->iArg
)!=0 );
1113 u64 mask
= pPragma
->iArg
; /* Mask of bits to set or clear. */
1114 if( db
->autoCommit
==0 ){
1115 /* Foreign key support may not be enabled or disabled while not
1116 ** in auto-commit mode. */
1117 mask
&= ~(SQLITE_ForeignKeys
);
1119 #if SQLITE_USER_AUTHENTICATION
1120 if( db
->auth
.authLevel
==UAUTH_User
){
1121 /* Do not allow non-admin users to modify the schema arbitrarily */
1122 mask
&= ~(SQLITE_WriteSchema
);
1126 if( sqlite3GetBoolean(zRight
, 0) ){
1127 if( (mask
& SQLITE_WriteSchema
)==0
1128 || (db
->flags
& SQLITE_Defensive
)==0
1134 if( mask
==SQLITE_DeferFKs
) db
->nDeferredImmCons
= 0;
1135 if( (mask
& SQLITE_WriteSchema
)!=0
1136 && sqlite3_stricmp(zRight
, "reset")==0
1138 /* IMP: R-60817-01178 If the argument is "RESET" then schema
1139 ** writing is disabled (as with "PRAGMA writable_schema=OFF") and,
1140 ** in addition, the schema is reloaded. */
1141 sqlite3ResetAllSchemasOfConnection(db
);
1145 /* Many of the flag-pragmas modify the code generated by the SQL
1146 ** compiler (eg. count_changes). So add an opcode to expire all
1147 ** compiled SQL statements after modifying a pragma value.
1149 sqlite3VdbeAddOp0(v
, OP_Expire
);
1150 setAllPagerFlags(db
);
1154 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
1156 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
1158 ** PRAGMA table_info(<table>)
1160 ** Return a single row for each column of the named table. The columns of
1161 ** the returned data set are:
1163 ** cid: Column id (numbered from left to right, starting at 0)
1164 ** name: Column name
1165 ** type: Column declaration type.
1166 ** notnull: True if 'NOT NULL' is part of column declaration
1167 ** dflt_value: The default value for the column, if any.
1168 ** pk: Non-zero for PK fields.
1170 case PragTyp_TABLE_INFO
: if( zRight
){
1172 sqlite3CodeVerifyNamedSchema(pParse
, zDb
);
1173 pTab
= sqlite3LocateTable(pParse
, LOCATE_NOERR
, zRight
, zDb
);
1178 Index
*pPk
= sqlite3PrimaryKeyIndex(pTab
);
1180 sqlite3ViewGetColumnNames(pParse
, pTab
);
1181 for(i
=0, pCol
=pTab
->aCol
; i
<pTab
->nCol
; i
++, pCol
++){
1183 const Expr
*pColExpr
;
1184 if( pCol
->colFlags
& COLFLAG_NOINSERT
){
1185 if( pPragma
->iArg
==0 ){
1189 if( pCol
->colFlags
& COLFLAG_VIRTUAL
){
1190 isHidden
= 2; /* GENERATED ALWAYS AS ... VIRTUAL */
1191 }else if( pCol
->colFlags
& COLFLAG_STORED
){
1192 isHidden
= 3; /* GENERATED ALWAYS AS ... STORED */
1193 }else{ assert( pCol
->colFlags
& COLFLAG_HIDDEN
);
1194 isHidden
= 1; /* HIDDEN */
1197 if( (pCol
->colFlags
& COLFLAG_PRIMKEY
)==0 ){
1202 for(k
=1; k
<=pTab
->nCol
&& pPk
->aiColumn
[k
-1]!=i
; k
++){}
1204 pColExpr
= sqlite3ColumnExpr(pTab
,pCol
);
1205 assert( pColExpr
==0 || pColExpr
->op
==TK_SPAN
|| isHidden
>=2 );
1206 assert( pColExpr
==0 || !ExprHasProperty(pColExpr
, EP_IntValue
)
1208 sqlite3VdbeMultiLoad(v
, 1, pPragma
->iArg
? "issisii" : "issisi",
1211 sqlite3ColumnType(pCol
,""),
1212 pCol
->notNull
? 1 : 0,
1213 (isHidden
>=2 || pColExpr
==0) ? 0 : pColExpr
->u
.zToken
,
1222 ** PRAGMA table_list
1224 ** Return a single row for each table, virtual table, or view in the
1227 ** schema: Name of attached database hold this table
1228 ** name: Name of the table itself
1229 ** type: "table", "view", "virtual", "shadow"
1230 ** ncol: Number of columns
1231 ** wr: True for a WITHOUT ROWID table
1232 ** strict: True for a STRICT table
1234 case PragTyp_TABLE_LIST
: {
1237 sqlite3CodeVerifyNamedSchema(pParse
, zDb
);
1238 for(ii
=0; ii
<db
->nDb
; ii
++){
1242 if( zDb
&& sqlite3_stricmp(zDb
, db
->aDb
[ii
].zDbSName
)!=0 ) continue;
1244 /* Ensure that the Table.nCol field is initialized for all views
1245 ** and virtual tables. Each time we initialize a Table.nCol value
1246 ** for a table, that can potentially disrupt the hash table, so restart
1247 ** the initialization scan.
1249 pHash
= &db
->aDb
[ii
].pSchema
->tblHash
;
1250 initNCol
= sqliteHashCount(pHash
);
1251 while( initNCol
-- ){
1252 for(k
=sqliteHashFirst(pHash
); 1; k
=sqliteHashNext(k
) ){
1254 if( k
==0 ){ initNCol
= 0; break; }
1255 pTab
= sqliteHashData(k
);
1256 if( pTab
->nCol
==0 ){
1257 char *zSql
= sqlite3MPrintf(db
, "SELECT*FROM\"%w\"", pTab
->zName
);
1259 sqlite3_stmt
*pDummy
= 0;
1260 (void)sqlite3_prepare(db
, zSql
, -1, &pDummy
, 0);
1261 (void)sqlite3_finalize(pDummy
);
1262 sqlite3DbFree(db
, zSql
);
1264 if( db
->mallocFailed
){
1265 sqlite3ErrorMsg(db
->pParse
, "out of memory");
1266 db
->pParse
->rc
= SQLITE_NOMEM_BKPT
;
1268 pHash
= &db
->aDb
[ii
].pSchema
->tblHash
;
1274 for(k
=sqliteHashFirst(pHash
); k
; k
=sqliteHashNext(k
) ){
1275 Table
*pTab
= sqliteHashData(k
);
1277 if( zRight
&& sqlite3_stricmp(zRight
, pTab
->zName
)!=0 ) continue;
1280 }else if( IsVirtual(pTab
) ){
1282 }else if( pTab
->tabFlags
& TF_Shadow
){
1287 sqlite3VdbeMultiLoad(v
, 1, "sssiii",
1288 db
->aDb
[ii
].zDbSName
,
1289 sqlite3PreferredTableName(pTab
->zName
),
1292 (pTab
->tabFlags
& TF_WithoutRowid
)!=0,
1293 (pTab
->tabFlags
& TF_Strict
)!=0
1301 case PragTyp_STATS
: {
1305 sqlite3CodeVerifySchema(pParse
, iDb
);
1306 for(i
=sqliteHashFirst(&pDb
->pSchema
->tblHash
); i
; i
=sqliteHashNext(i
)){
1307 Table
*pTab
= sqliteHashData(i
);
1308 sqlite3VdbeMultiLoad(v
, 1, "ssiii",
1309 sqlite3PreferredTableName(pTab
->zName
),
1314 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1315 sqlite3VdbeMultiLoad(v
, 2, "siiiX",
1318 pIdx
->aiRowLogEst
[0],
1320 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, 5);
1327 case PragTyp_INDEX_INFO
: if( zRight
){
1330 pIdx
= sqlite3FindIndex(db
, zRight
, zDb
);
1332 /* If there is no index named zRight, check to see if there is a
1333 ** WITHOUT ROWID table named zRight, and if there is, show the
1334 ** structure of the PRIMARY KEY index for that table. */
1335 pTab
= sqlite3LocateTable(pParse
, LOCATE_NOERR
, zRight
, zDb
);
1336 if( pTab
&& !HasRowid(pTab
) ){
1337 pIdx
= sqlite3PrimaryKeyIndex(pTab
);
1341 int iIdxDb
= sqlite3SchemaToIndex(db
, pIdx
->pSchema
);
1344 if( pPragma
->iArg
){
1345 /* PRAGMA index_xinfo (newer version with more rows and columns) */
1349 /* PRAGMA index_info (legacy version) */
1353 pTab
= pIdx
->pTable
;
1354 sqlite3CodeVerifySchema(pParse
, iIdxDb
);
1355 assert( pParse
->nMem
<=pPragma
->nPragCName
);
1356 for(i
=0; i
<mx
; i
++){
1357 i16 cnum
= pIdx
->aiColumn
[i
];
1358 sqlite3VdbeMultiLoad(v
, 1, "iisX", i
, cnum
,
1359 cnum
<0 ? 0 : pTab
->aCol
[cnum
].zCnName
);
1360 if( pPragma
->iArg
){
1361 sqlite3VdbeMultiLoad(v
, 4, "isiX",
1362 pIdx
->aSortOrder
[i
],
1366 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, pParse
->nMem
);
1372 case PragTyp_INDEX_LIST
: if( zRight
){
1376 pTab
= sqlite3FindTable(db
, zRight
, zDb
);
1378 int iTabDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
1380 sqlite3CodeVerifySchema(pParse
, iTabDb
);
1381 for(pIdx
=pTab
->pIndex
, i
=0; pIdx
; pIdx
=pIdx
->pNext
, i
++){
1382 const char *azOrigin
[] = { "c", "u", "pk" };
1383 sqlite3VdbeMultiLoad(v
, 1, "isisi",
1386 IsUniqueIndex(pIdx
),
1387 azOrigin
[pIdx
->idxType
],
1388 pIdx
->pPartIdxWhere
!=0);
1394 case PragTyp_DATABASE_LIST
: {
1397 for(i
=0; i
<db
->nDb
; i
++){
1398 if( db
->aDb
[i
].pBt
==0 ) continue;
1399 assert( db
->aDb
[i
].zDbSName
!=0 );
1400 sqlite3VdbeMultiLoad(v
, 1, "iss",
1402 db
->aDb
[i
].zDbSName
,
1403 sqlite3BtreeGetFilename(db
->aDb
[i
].pBt
));
1408 case PragTyp_COLLATION_LIST
: {
1412 for(p
=sqliteHashFirst(&db
->aCollSeq
); p
; p
=sqliteHashNext(p
)){
1413 CollSeq
*pColl
= (CollSeq
*)sqliteHashData(p
);
1414 sqlite3VdbeMultiLoad(v
, 1, "is", i
++, pColl
->zName
);
1419 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
1420 case PragTyp_FUNCTION_LIST
: {
1424 int showInternFunc
= (db
->mDbFlags
& DBFLAG_InternalFunc
)!=0;
1426 for(i
=0; i
<SQLITE_FUNC_HASH_SZ
; i
++){
1427 for(p
=sqlite3BuiltinFunctions
.a
[i
]; p
; p
=p
->u
.pHash
){
1428 assert( p
->funcFlags
& SQLITE_FUNC_BUILTIN
);
1429 pragmaFunclistLine(v
, p
, 1, showInternFunc
);
1432 for(j
=sqliteHashFirst(&db
->aFunc
); j
; j
=sqliteHashNext(j
)){
1433 p
= (FuncDef
*)sqliteHashData(j
);
1434 assert( (p
->funcFlags
& SQLITE_FUNC_BUILTIN
)==0 );
1435 pragmaFunclistLine(v
, p
, 0, showInternFunc
);
1440 #ifndef SQLITE_OMIT_VIRTUALTABLE
1441 case PragTyp_MODULE_LIST
: {
1444 for(j
=sqliteHashFirst(&db
->aModule
); j
; j
=sqliteHashNext(j
)){
1445 Module
*pMod
= (Module
*)sqliteHashData(j
);
1446 sqlite3VdbeMultiLoad(v
, 1, "s", pMod
->zName
);
1450 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1452 case PragTyp_PRAGMA_LIST
: {
1454 for(i
=0; i
<ArraySize(aPragmaName
); i
++){
1455 sqlite3VdbeMultiLoad(v
, 1, "s", aPragmaName
[i
].zName
);
1459 #endif /* SQLITE_INTROSPECTION_PRAGMAS */
1461 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
1463 #ifndef SQLITE_OMIT_FOREIGN_KEY
1464 case PragTyp_FOREIGN_KEY_LIST
: if( zRight
){
1467 pTab
= sqlite3FindTable(db
, zRight
, zDb
);
1468 if( pTab
&& IsOrdinaryTable(pTab
) ){
1469 pFK
= pTab
->u
.tab
.pFKey
;
1471 int iTabDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
1474 sqlite3CodeVerifySchema(pParse
, iTabDb
);
1477 for(j
=0; j
<pFK
->nCol
; j
++){
1478 sqlite3VdbeMultiLoad(v
, 1, "iissssss",
1482 pTab
->aCol
[pFK
->aCol
[j
].iFrom
].zCnName
,
1484 actionName(pFK
->aAction
[1]), /* ON UPDATE */
1485 actionName(pFK
->aAction
[0]), /* ON DELETE */
1489 pFK
= pFK
->pNextFrom
;
1495 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1497 #ifndef SQLITE_OMIT_FOREIGN_KEY
1498 #ifndef SQLITE_OMIT_TRIGGER
1499 case PragTyp_FOREIGN_KEY_CHECK
: {
1500 FKey
*pFK
; /* A foreign key constraint */
1501 Table
*pTab
; /* Child table contain "REFERENCES" keyword */
1502 Table
*pParent
; /* Parent table that child points to */
1503 Index
*pIdx
; /* Index in the parent table */
1504 int i
; /* Loop counter: Foreign key number for pTab */
1505 int j
; /* Loop counter: Field of the foreign key */
1506 HashElem
*k
; /* Loop counter: Next table in schema */
1507 int x
; /* result variable */
1508 int regResult
; /* 3 registers to hold a result row */
1509 int regRow
; /* Registers to hold a row from pTab */
1510 int addrTop
; /* Top of a loop checking foreign keys */
1511 int addrOk
; /* Jump here if the key is OK */
1512 int *aiCols
; /* child to parent column mapping */
1514 regResult
= pParse
->nMem
+1;
1516 regRow
= ++pParse
->nMem
;
1517 k
= sqliteHashFirst(&db
->aDb
[iDb
].pSchema
->tblHash
);
1520 pTab
= sqlite3LocateTable(pParse
, 0, zRight
, zDb
);
1523 pTab
= (Table
*)sqliteHashData(k
);
1524 k
= sqliteHashNext(k
);
1526 if( pTab
==0 || !IsOrdinaryTable(pTab
) || pTab
->u
.tab
.pFKey
==0 ) continue;
1527 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
1528 zDb
= db
->aDb
[iDb
].zDbSName
;
1529 sqlite3CodeVerifySchema(pParse
, iDb
);
1530 sqlite3TableLock(pParse
, iDb
, pTab
->tnum
, 0, pTab
->zName
);
1531 sqlite3TouchRegister(pParse
, pTab
->nCol
+regRow
);
1532 sqlite3OpenTable(pParse
, 0, iDb
, pTab
, OP_OpenRead
);
1533 sqlite3VdbeLoadString(v
, regResult
, pTab
->zName
);
1534 assert( IsOrdinaryTable(pTab
) );
1535 for(i
=1, pFK
=pTab
->u
.tab
.pFKey
; pFK
; i
++, pFK
=pFK
->pNextFrom
){
1536 pParent
= sqlite3FindTable(db
, pFK
->zTo
, zDb
);
1537 if( pParent
==0 ) continue;
1539 sqlite3TableLock(pParse
, iDb
, pParent
->tnum
, 0, pParent
->zName
);
1540 x
= sqlite3FkLocateIndex(pParse
, pParent
, pFK
, &pIdx
, 0);
1543 sqlite3OpenTable(pParse
, i
, iDb
, pParent
, OP_OpenRead
);
1545 sqlite3VdbeAddOp3(v
, OP_OpenRead
, i
, pIdx
->tnum
, iDb
);
1546 sqlite3VdbeSetP4KeyInfo(pParse
, pIdx
);
1553 assert( pParse
->nErr
>0 || pFK
==0 );
1555 if( pParse
->nTab
<i
) pParse
->nTab
= i
;
1556 addrTop
= sqlite3VdbeAddOp1(v
, OP_Rewind
, 0); VdbeCoverage(v
);
1557 assert( IsOrdinaryTable(pTab
) );
1558 for(i
=1, pFK
=pTab
->u
.tab
.pFKey
; pFK
; i
++, pFK
=pFK
->pNextFrom
){
1559 pParent
= sqlite3FindTable(db
, pFK
->zTo
, zDb
);
1563 x
= sqlite3FkLocateIndex(pParse
, pParent
, pFK
, &pIdx
, &aiCols
);
1564 assert( x
==0 || db
->mallocFailed
);
1566 addrOk
= sqlite3VdbeMakeLabel(pParse
);
1568 /* Generate code to read the child key values into registers
1569 ** regRow..regRow+n. If any of the child key values are NULL, this
1570 ** row cannot cause an FK violation. Jump directly to addrOk in
1572 sqlite3TouchRegister(pParse
, regRow
+ pFK
->nCol
);
1573 for(j
=0; j
<pFK
->nCol
; j
++){
1574 int iCol
= aiCols
? aiCols
[j
] : pFK
->aCol
[j
].iFrom
;
1575 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, 0, iCol
, regRow
+j
);
1576 sqlite3VdbeAddOp2(v
, OP_IsNull
, regRow
+j
, addrOk
); VdbeCoverage(v
);
1579 /* Generate code to query the parent index for a matching parent
1580 ** key. If a match is found, jump to addrOk. */
1582 sqlite3VdbeAddOp4(v
, OP_Affinity
, regRow
, pFK
->nCol
, 0,
1583 sqlite3IndexAffinityStr(db
,pIdx
), pFK
->nCol
);
1584 sqlite3VdbeAddOp4Int(v
, OP_Found
, i
, addrOk
, regRow
, pFK
->nCol
);
1586 }else if( pParent
){
1587 int jmp
= sqlite3VdbeCurrentAddr(v
)+2;
1588 sqlite3VdbeAddOp3(v
, OP_SeekRowid
, i
, jmp
, regRow
); VdbeCoverage(v
);
1589 sqlite3VdbeGoto(v
, addrOk
);
1590 assert( pFK
->nCol
==1 || db
->mallocFailed
);
1593 /* Generate code to report an FK violation to the caller. */
1594 if( HasRowid(pTab
) ){
1595 sqlite3VdbeAddOp2(v
, OP_Rowid
, 0, regResult
+1);
1597 sqlite3VdbeAddOp2(v
, OP_Null
, 0, regResult
+1);
1599 sqlite3VdbeMultiLoad(v
, regResult
+2, "siX", pFK
->zTo
, i
-1);
1600 sqlite3VdbeAddOp2(v
, OP_ResultRow
, regResult
, 4);
1601 sqlite3VdbeResolveLabel(v
, addrOk
);
1602 sqlite3DbFree(db
, aiCols
);
1604 sqlite3VdbeAddOp2(v
, OP_Next
, 0, addrTop
+1); VdbeCoverage(v
);
1605 sqlite3VdbeJumpHere(v
, addrTop
);
1609 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
1610 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1612 #ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA
1613 /* Reinstall the LIKE and GLOB functions. The variant of LIKE
1614 ** used will be case sensitive or not depending on the RHS.
1616 case PragTyp_CASE_SENSITIVE_LIKE
: {
1618 sqlite3RegisterLikeFunctions(db
, sqlite3GetBoolean(zRight
, 0));
1622 #endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */
1624 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
1625 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
1628 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
1629 /* PRAGMA integrity_check
1630 ** PRAGMA integrity_check(N)
1631 ** PRAGMA quick_check
1632 ** PRAGMA quick_check(N)
1634 ** Verify the integrity of the database.
1636 ** The "quick_check" is reduced version of
1637 ** integrity_check designed to detect most database corruption
1638 ** without the overhead of cross-checking indexes. Quick_check
1639 ** is linear time whereas integrity_check is O(NlogN).
1641 ** The maximum number of errors is 100 by default. A different default
1642 ** can be specified using a numeric parameter N.
1644 ** Or, the parameter N can be the name of a table. In that case, only
1645 ** the one table named is verified. The freelist is only verified if
1646 ** the named table is "sqlite_schema" (or one of its aliases).
1648 ** All schemas are checked by default. To check just a single
1649 ** schema, use the form:
1651 ** PRAGMA schema.integrity_check;
1653 case PragTyp_INTEGRITY_CHECK
: {
1654 int i
, j
, addr
, mxErr
;
1655 Table
*pObjTab
= 0; /* Check only this one table, if not NULL */
1657 int isQuick
= (sqlite3Tolower(zLeft
[0])=='q');
1659 /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
1660 ** then iDb is set to the index of the database identified by <db>.
1661 ** In this case, the integrity of database iDb only is verified by
1662 ** the VDBE created below.
1664 ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
1665 ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
1666 ** to -1 here, to indicate that the VDBE should verify the integrity
1667 ** of all attached databases. */
1669 assert( iDb
==0 || pId2
->z
);
1670 if( pId2
->z
==0 ) iDb
= -1;
1672 /* Initialize the VDBE program */
1675 /* Set the maximum error count */
1676 mxErr
= SQLITE_INTEGRITY_CHECK_ERROR_MAX
;
1678 if( sqlite3GetInt32(zRight
, &mxErr
) ){
1680 mxErr
= SQLITE_INTEGRITY_CHECK_ERROR_MAX
;
1683 pObjTab
= sqlite3LocateTable(pParse
, 0, zRight
,
1684 iDb
>=0 ? db
->aDb
[iDb
].zDbSName
: 0);
1687 sqlite3VdbeAddOp2(v
, OP_Integer
, mxErr
-1, 1); /* reg[1] holds errors left */
1689 /* Do an integrity check on each database file */
1690 for(i
=0; i
<db
->nDb
; i
++){
1691 HashElem
*x
; /* For looping over tables in the schema */
1692 Hash
*pTbls
; /* Set of all tables in the schema */
1693 int *aRoot
; /* Array of root page numbers of all btrees */
1694 int cnt
= 0; /* Number of entries in aRoot[] */
1695 int mxIdx
= 0; /* Maximum number of indexes for any table */
1697 if( OMIT_TEMPDB
&& i
==1 ) continue;
1698 if( iDb
>=0 && i
!=iDb
) continue;
1700 sqlite3CodeVerifySchema(pParse
, i
);
1701 pParse
->okConstFactor
= 0; /* tag-20230327-1 */
1703 /* Do an integrity check of the B-Tree
1705 ** Begin by finding the root pages numbers
1706 ** for all tables and indices in the database.
1708 assert( sqlite3SchemaMutexHeld(db
, i
, 0) );
1709 pTbls
= &db
->aDb
[i
].pSchema
->tblHash
;
1710 for(cnt
=0, x
=sqliteHashFirst(pTbls
); x
; x
=sqliteHashNext(x
)){
1711 Table
*pTab
= sqliteHashData(x
); /* Current table */
1712 Index
*pIdx
; /* An index on pTab */
1713 int nIdx
; /* Number of indexes on pTab */
1714 if( pObjTab
&& pObjTab
!=pTab
) continue;
1715 if( HasRowid(pTab
) ) cnt
++;
1716 for(nIdx
=0, pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
, nIdx
++){ cnt
++; }
1717 if( nIdx
>mxIdx
) mxIdx
= nIdx
;
1719 if( cnt
==0 ) continue;
1720 if( pObjTab
) cnt
++;
1721 aRoot
= sqlite3DbMallocRawNN(db
, sizeof(int)*(cnt
+1));
1722 if( aRoot
==0 ) break;
1724 if( pObjTab
) aRoot
[++cnt
] = 0;
1725 for(x
=sqliteHashFirst(pTbls
); x
; x
=sqliteHashNext(x
)){
1726 Table
*pTab
= sqliteHashData(x
);
1728 if( pObjTab
&& pObjTab
!=pTab
) continue;
1729 if( HasRowid(pTab
) ) aRoot
[++cnt
] = pTab
->tnum
;
1730 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1731 aRoot
[++cnt
] = pIdx
->tnum
;
1736 /* Make sure sufficient number of registers have been allocated */
1737 sqlite3TouchRegister(pParse
, 8+mxIdx
);
1738 sqlite3ClearTempRegCache(pParse
);
1740 /* Do the b-tree integrity checks */
1741 sqlite3VdbeAddOp4(v
, OP_IntegrityCk
, 2, cnt
, 1, (char*)aRoot
,P4_INTARRAY
);
1742 sqlite3VdbeChangeP5(v
, (u8
)i
);
1743 addr
= sqlite3VdbeAddOp1(v
, OP_IsNull
, 2); VdbeCoverage(v
);
1744 sqlite3VdbeAddOp4(v
, OP_String8
, 0, 3, 0,
1745 sqlite3MPrintf(db
, "*** in database %s ***\n", db
->aDb
[i
].zDbSName
),
1747 sqlite3VdbeAddOp3(v
, OP_Concat
, 2, 3, 3);
1748 integrityCheckResultRow(v
);
1749 sqlite3VdbeJumpHere(v
, addr
);
1751 /* Make sure all the indices are constructed correctly.
1753 for(x
=sqliteHashFirst(pTbls
); x
; x
=sqliteHashNext(x
)){
1754 Table
*pTab
= sqliteHashData(x
);
1756 Index
*pPrior
= 0; /* Previous index */
1758 int iDataCur
, iIdxCur
;
1760 int bStrict
; /* True for a STRICT table */
1761 int r2
; /* Previous key for WITHOUT ROWID tables */
1762 int mxCol
; /* Maximum non-virtual column number */
1764 if( pObjTab
&& pObjTab
!=pTab
) continue;
1765 if( !IsOrdinaryTable(pTab
) ){
1766 #ifndef SQLITE_OMIT_VIRTUALTABLE
1767 sqlite3_vtab
*pVTab
;
1769 if( !IsVirtual(pTab
) ) continue;
1770 if( pTab
->nCol
<=0 ){
1771 const char *zMod
= pTab
->u
.vtab
.azArg
[0];
1772 if( sqlite3HashFind(&db
->aModule
, zMod
)==0 ) continue;
1774 sqlite3ViewGetColumnNames(pParse
, pTab
);
1775 if( pTab
->u
.vtab
.p
==0 ) continue;
1776 pVTab
= pTab
->u
.vtab
.p
->pVtab
;
1777 if( NEVER(pVTab
==0) ) continue;
1778 if( NEVER(pVTab
->pModule
==0) ) continue;
1779 if( pVTab
->pModule
->iVersion
<4 ) continue;
1780 if( pVTab
->pModule
->xIntegrity
==0 ) continue;
1781 sqlite3VdbeAddOp3(v
, OP_VCheck
, i
, 3, isQuick
);
1783 sqlite3VdbeAppendP4(v
, pTab
, P4_TABLEREF
);
1784 a1
= sqlite3VdbeAddOp1(v
, OP_IsNull
, 3); VdbeCoverage(v
);
1785 integrityCheckResultRow(v
);
1786 sqlite3VdbeJumpHere(v
, a1
);
1790 if( isQuick
|| HasRowid(pTab
) ){
1794 pPk
= sqlite3PrimaryKeyIndex(pTab
);
1795 r2
= sqlite3GetTempRange(pParse
, pPk
->nKeyCol
);
1796 sqlite3VdbeAddOp3(v
, OP_Null
, 1, r2
, r2
+pPk
->nKeyCol
-1);
1798 sqlite3OpenTableAndIndices(pParse
, pTab
, OP_OpenRead
, 0,
1799 1, 0, &iDataCur
, &iIdxCur
);
1800 /* reg[7] counts the number of entries in the table.
1801 ** reg[8+i] counts the number of entries in the i-th index
1803 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, 7);
1804 for(j
=0, pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
, j
++){
1805 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, 8+j
); /* index entries counter */
1807 assert( pParse
->nMem
>=8+j
);
1808 assert( sqlite3NoTempsInRange(pParse
,1,7+j
) );
1809 sqlite3VdbeAddOp2(v
, OP_Rewind
, iDataCur
, 0); VdbeCoverage(v
);
1810 loopTop
= sqlite3VdbeAddOp2(v
, OP_AddImm
, 7, 1);
1812 /* Fetch the right-most column from the table. This will cause
1813 ** the entire record header to be parsed and sanity checked. It
1814 ** will also prepopulate the cursor column cache that is used
1815 ** by the OP_IsType code, so it is a required step.
1817 assert( !IsVirtual(pTab
) );
1818 if( HasRowid(pTab
) ){
1820 for(j
=0; j
<pTab
->nCol
; j
++){
1821 if( (pTab
->aCol
[j
].colFlags
& COLFLAG_VIRTUAL
)==0 ) mxCol
++;
1823 if( mxCol
==pTab
->iPKey
) mxCol
--;
1825 /* COLFLAG_VIRTUAL columns are not included in the WITHOUT ROWID
1826 ** PK index column-count, so there is no need to account for them
1828 mxCol
= sqlite3PrimaryKeyIndex(pTab
)->nColumn
-1;
1831 sqlite3VdbeAddOp3(v
, OP_Column
, iDataCur
, mxCol
, 3);
1832 sqlite3VdbeTypeofColumn(v
, 3);
1837 /* Verify WITHOUT ROWID keys are in ascending order */
1840 a1
= sqlite3VdbeAddOp4Int(v
, OP_IdxGT
, iDataCur
, 0,r2
,pPk
->nKeyCol
);
1842 sqlite3VdbeAddOp1(v
, OP_IsNull
, r2
); VdbeCoverage(v
);
1843 zErr
= sqlite3MPrintf(db
,
1844 "row not in PRIMARY KEY order for %s",
1846 sqlite3VdbeAddOp4(v
, OP_String8
, 0, 3, 0, zErr
, P4_DYNAMIC
);
1847 integrityCheckResultRow(v
);
1848 sqlite3VdbeJumpHere(v
, a1
);
1849 sqlite3VdbeJumpHere(v
, a1
+1);
1850 for(j
=0; j
<pPk
->nKeyCol
; j
++){
1851 sqlite3ExprCodeLoadIndexColumn(pParse
, pPk
, iDataCur
, j
, r2
+j
);
1855 /* Verify datatypes for all columns:
1857 ** (1) NOT NULL columns may not contain a NULL
1858 ** (2) Datatype must be exact for non-ANY columns in STRICT tables
1859 ** (3) Datatype for TEXT columns in non-STRICT tables must be
1860 ** NULL, TEXT, or BLOB.
1861 ** (4) Datatype for numeric columns in non-STRICT tables must not
1862 ** be a TEXT value that can be losslessly converted to numeric.
1864 bStrict
= (pTab
->tabFlags
& TF_Strict
)!=0;
1865 for(j
=0; j
<pTab
->nCol
; j
++){
1867 Column
*pCol
= pTab
->aCol
+ j
; /* The column to be checked */
1868 int labelError
; /* Jump here to report an error */
1869 int labelOk
; /* Jump here if all looks ok */
1870 int p1
, p3
, p4
; /* Operands to the OP_IsType opcode */
1871 int doTypeCheck
; /* Check datatypes (besides NOT NULL) */
1873 if( j
==pTab
->iPKey
) continue;
1875 doTypeCheck
= pCol
->eCType
>COLTYPE_ANY
;
1877 doTypeCheck
= pCol
->affinity
>SQLITE_AFF_BLOB
;
1879 if( pCol
->notNull
==0 && !doTypeCheck
) continue;
1881 /* Compute the operands that will be needed for OP_IsType */
1883 if( pCol
->colFlags
& COLFLAG_VIRTUAL
){
1884 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iDataCur
, j
, 3);
1889 sqlite3_value
*pDfltValue
= 0;
1890 sqlite3ValueFromExpr(db
, sqlite3ColumnExpr(pTab
,pCol
), ENC(db
),
1891 pCol
->affinity
, &pDfltValue
);
1893 p4
= sqlite3_value_type(pDfltValue
);
1894 sqlite3ValueFree(pDfltValue
);
1898 if( !HasRowid(pTab
) ){
1899 testcase( j
!=sqlite3TableColumnToStorage(pTab
, j
) );
1900 p3
= sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab
), j
);
1902 p3
= sqlite3TableColumnToStorage(pTab
,j
);
1907 labelError
= sqlite3VdbeMakeLabel(pParse
);
1908 labelOk
= sqlite3VdbeMakeLabel(pParse
);
1909 if( pCol
->notNull
){
1910 /* (1) NOT NULL columns may not contain a NULL */
1912 int jmp2
= sqlite3VdbeAddOp4Int(v
, OP_IsType
, p1
, labelOk
, p3
, p4
);
1915 sqlite3VdbeChangeP5(v
, 0x0f); /* INT, REAL, TEXT, or BLOB */
1918 sqlite3VdbeChangeP5(v
, 0x0d); /* INT, TEXT, or BLOB */
1919 /* OP_IsType does not detect NaN values in the database file
1920 ** which should be treated as a NULL. So if the header type
1921 ** is REAL, we have to load the actual data using OP_Column
1922 ** to reliably determine if the value is a NULL. */
1923 sqlite3VdbeAddOp3(v
, OP_Column
, p1
, p3
, 3);
1924 jmp3
= sqlite3VdbeAddOp2(v
, OP_NotNull
, 3, labelOk
);
1927 zErr
= sqlite3MPrintf(db
, "NULL value in %s.%s", pTab
->zName
,
1929 sqlite3VdbeAddOp4(v
, OP_String8
, 0, 3, 0, zErr
, P4_DYNAMIC
);
1931 sqlite3VdbeGoto(v
, labelError
);
1932 sqlite3VdbeJumpHere(v
, jmp2
);
1933 sqlite3VdbeJumpHere(v
, jmp3
);
1935 /* VDBE byte code will fall thru */
1938 if( bStrict
&& doTypeCheck
){
1939 /* (2) Datatype must be exact for non-ANY columns in STRICT tables*/
1940 static unsigned char aStdTypeMask
[] = {
1948 sqlite3VdbeAddOp4Int(v
, OP_IsType
, p1
, labelOk
, p3
, p4
);
1949 assert( pCol
->eCType
>=1 && pCol
->eCType
<=sizeof(aStdTypeMask
) );
1950 sqlite3VdbeChangeP5(v
, aStdTypeMask
[pCol
->eCType
-1]);
1952 zErr
= sqlite3MPrintf(db
, "non-%s value in %s.%s",
1953 sqlite3StdType
[pCol
->eCType
-1],
1954 pTab
->zName
, pTab
->aCol
[j
].zCnName
);
1955 sqlite3VdbeAddOp4(v
, OP_String8
, 0, 3, 0, zErr
, P4_DYNAMIC
);
1956 }else if( !bStrict
&& pCol
->affinity
==SQLITE_AFF_TEXT
){
1957 /* (3) Datatype for TEXT columns in non-STRICT tables must be
1958 ** NULL, TEXT, or BLOB. */
1959 sqlite3VdbeAddOp4Int(v
, OP_IsType
, p1
, labelOk
, p3
, p4
);
1960 sqlite3VdbeChangeP5(v
, 0x1c); /* NULL, TEXT, or BLOB */
1962 zErr
= sqlite3MPrintf(db
, "NUMERIC value in %s.%s",
1963 pTab
->zName
, pTab
->aCol
[j
].zCnName
);
1964 sqlite3VdbeAddOp4(v
, OP_String8
, 0, 3, 0, zErr
, P4_DYNAMIC
);
1965 }else if( !bStrict
&& pCol
->affinity
>=SQLITE_AFF_NUMERIC
){
1966 /* (4) Datatype for numeric columns in non-STRICT tables must not
1967 ** be a TEXT value that can be converted to numeric. */
1968 sqlite3VdbeAddOp4Int(v
, OP_IsType
, p1
, labelOk
, p3
, p4
);
1969 sqlite3VdbeChangeP5(v
, 0x1b); /* NULL, INT, FLOAT, or BLOB */
1972 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iDataCur
, j
, 3);
1974 sqlite3VdbeAddOp4(v
, OP_Affinity
, 3, 1, 0, "C", P4_STATIC
);
1975 sqlite3VdbeAddOp4Int(v
, OP_IsType
, -1, labelOk
, 3, p4
);
1976 sqlite3VdbeChangeP5(v
, 0x1c); /* NULL, TEXT, or BLOB */
1978 zErr
= sqlite3MPrintf(db
, "TEXT value in %s.%s",
1979 pTab
->zName
, pTab
->aCol
[j
].zCnName
);
1980 sqlite3VdbeAddOp4(v
, OP_String8
, 0, 3, 0, zErr
, P4_DYNAMIC
);
1982 sqlite3VdbeResolveLabel(v
, labelError
);
1983 integrityCheckResultRow(v
);
1984 sqlite3VdbeResolveLabel(v
, labelOk
);
1986 /* Verify CHECK constraints */
1987 if( pTab
->pCheck
&& (db
->flags
& SQLITE_IgnoreChecks
)==0 ){
1988 ExprList
*pCheck
= sqlite3ExprListDup(db
, pTab
->pCheck
, 0);
1989 if( db
->mallocFailed
==0 ){
1990 int addrCkFault
= sqlite3VdbeMakeLabel(pParse
);
1991 int addrCkOk
= sqlite3VdbeMakeLabel(pParse
);
1994 pParse
->iSelfTab
= iDataCur
+ 1;
1995 for(k
=pCheck
->nExpr
-1; k
>0; k
--){
1996 sqlite3ExprIfFalse(pParse
, pCheck
->a
[k
].pExpr
, addrCkFault
, 0);
1998 sqlite3ExprIfTrue(pParse
, pCheck
->a
[0].pExpr
, addrCkOk
,
2000 sqlite3VdbeResolveLabel(v
, addrCkFault
);
2001 pParse
->iSelfTab
= 0;
2002 zErr
= sqlite3MPrintf(db
, "CHECK constraint failed in %s",
2004 sqlite3VdbeAddOp4(v
, OP_String8
, 0, 3, 0, zErr
, P4_DYNAMIC
);
2005 integrityCheckResultRow(v
);
2006 sqlite3VdbeResolveLabel(v
, addrCkOk
);
2008 sqlite3ExprListDelete(db
, pCheck
);
2010 if( !isQuick
){ /* Omit the remaining tests for quick_check */
2011 /* Validate index entries for the current row */
2012 for(j
=0, pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
, j
++){
2013 int jmp2
, jmp3
, jmp4
, jmp5
, label6
;
2015 int ckUniq
= sqlite3VdbeMakeLabel(pParse
);
2016 if( pPk
==pIdx
) continue;
2017 r1
= sqlite3GenerateIndexKey(pParse
, pIdx
, iDataCur
, 0, 0, &jmp3
,
2020 sqlite3VdbeAddOp2(v
, OP_AddImm
, 8+j
, 1);/* increment entry count */
2021 /* Verify that an index entry exists for the current table row */
2022 jmp2
= sqlite3VdbeAddOp4Int(v
, OP_Found
, iIdxCur
+j
, ckUniq
, r1
,
2023 pIdx
->nColumn
); VdbeCoverage(v
);
2024 sqlite3VdbeLoadString(v
, 3, "row ");
2025 sqlite3VdbeAddOp3(v
, OP_Concat
, 7, 3, 3);
2026 sqlite3VdbeLoadString(v
, 4, " missing from index ");
2027 sqlite3VdbeAddOp3(v
, OP_Concat
, 4, 3, 3);
2028 jmp5
= sqlite3VdbeLoadString(v
, 4, pIdx
->zName
);
2029 sqlite3VdbeAddOp3(v
, OP_Concat
, 4, 3, 3);
2030 jmp4
= integrityCheckResultRow(v
);
2031 sqlite3VdbeJumpHere(v
, jmp2
);
2033 /* The OP_IdxRowid opcode is an optimized version of OP_Column
2034 ** that extracts the rowid off the end of the index record.
2035 ** But it only works correctly if index record does not have
2036 ** any extra bytes at the end. Verify that this is the case. */
2037 if( HasRowid(pTab
) ){
2039 sqlite3VdbeAddOp2(v
, OP_IdxRowid
, iIdxCur
+j
, 3);
2040 jmp7
= sqlite3VdbeAddOp3(v
, OP_Eq
, 3, 0, r1
+pIdx
->nColumn
-1);
2041 VdbeCoverageNeverNull(v
);
2042 sqlite3VdbeLoadString(v
, 3,
2043 "rowid not at end-of-record for row ");
2044 sqlite3VdbeAddOp3(v
, OP_Concat
, 7, 3, 3);
2045 sqlite3VdbeLoadString(v
, 4, " of index ");
2046 sqlite3VdbeGoto(v
, jmp5
-1);
2047 sqlite3VdbeJumpHere(v
, jmp7
);
2050 /* Any indexed columns with non-BINARY collations must still hold
2051 ** the exact same text value as the table. */
2053 for(kk
=0; kk
<pIdx
->nKeyCol
; kk
++){
2054 if( pIdx
->azColl
[kk
]==sqlite3StrBINARY
) continue;
2055 if( label6
==0 ) label6
= sqlite3VdbeMakeLabel(pParse
);
2056 sqlite3VdbeAddOp3(v
, OP_Column
, iIdxCur
+j
, kk
, 3);
2057 sqlite3VdbeAddOp3(v
, OP_Ne
, 3, label6
, r1
+kk
); VdbeCoverage(v
);
2060 int jmp6
= sqlite3VdbeAddOp0(v
, OP_Goto
);
2061 sqlite3VdbeResolveLabel(v
, label6
);
2062 sqlite3VdbeLoadString(v
, 3, "row ");
2063 sqlite3VdbeAddOp3(v
, OP_Concat
, 7, 3, 3);
2064 sqlite3VdbeLoadString(v
, 4, " values differ from index ");
2065 sqlite3VdbeGoto(v
, jmp5
-1);
2066 sqlite3VdbeJumpHere(v
, jmp6
);
2069 /* For UNIQUE indexes, verify that only one entry exists with the
2070 ** current key. The entry is unique if (1) any column is NULL
2071 ** or (2) the next entry has a different key */
2072 if( IsUniqueIndex(pIdx
) ){
2073 int uniqOk
= sqlite3VdbeMakeLabel(pParse
);
2075 for(kk
=0; kk
<pIdx
->nKeyCol
; kk
++){
2076 int iCol
= pIdx
->aiColumn
[kk
];
2077 assert( iCol
!=XN_ROWID
&& iCol
<pTab
->nCol
);
2078 if( iCol
>=0 && pTab
->aCol
[iCol
].notNull
) continue;
2079 sqlite3VdbeAddOp2(v
, OP_IsNull
, r1
+kk
, uniqOk
);
2082 jmp6
= sqlite3VdbeAddOp1(v
, OP_Next
, iIdxCur
+j
); VdbeCoverage(v
);
2083 sqlite3VdbeGoto(v
, uniqOk
);
2084 sqlite3VdbeJumpHere(v
, jmp6
);
2085 sqlite3VdbeAddOp4Int(v
, OP_IdxGT
, iIdxCur
+j
, uniqOk
, r1
,
2086 pIdx
->nKeyCol
); VdbeCoverage(v
);
2087 sqlite3VdbeLoadString(v
, 3, "non-unique entry in index ");
2088 sqlite3VdbeGoto(v
, jmp5
);
2089 sqlite3VdbeResolveLabel(v
, uniqOk
);
2091 sqlite3VdbeJumpHere(v
, jmp4
);
2092 sqlite3ResolvePartIdxLabel(pParse
, jmp3
);
2095 sqlite3VdbeAddOp2(v
, OP_Next
, iDataCur
, loopTop
); VdbeCoverage(v
);
2096 sqlite3VdbeJumpHere(v
, loopTop
-1);
2098 sqlite3VdbeLoadString(v
, 2, "wrong # of entries in index ");
2099 for(j
=0, pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
, j
++){
2100 if( pPk
==pIdx
) continue;
2101 sqlite3VdbeAddOp2(v
, OP_Count
, iIdxCur
+j
, 3);
2102 addr
= sqlite3VdbeAddOp3(v
, OP_Eq
, 8+j
, 0, 3); VdbeCoverage(v
);
2103 sqlite3VdbeChangeP5(v
, SQLITE_NOTNULL
);
2104 sqlite3VdbeLoadString(v
, 4, pIdx
->zName
);
2105 sqlite3VdbeAddOp3(v
, OP_Concat
, 4, 2, 3);
2106 integrityCheckResultRow(v
);
2107 sqlite3VdbeJumpHere(v
, addr
);
2110 sqlite3ReleaseTempRange(pParse
, r2
, pPk
->nKeyCol
);
2116 static const int iLn
= VDBE_OFFSET_LINENO(2);
2117 static const VdbeOpList endCode
[] = {
2118 { OP_AddImm
, 1, 0, 0}, /* 0 */
2119 { OP_IfNotZero
, 1, 4, 0}, /* 1 */
2120 { OP_String8
, 0, 3, 0}, /* 2 */
2121 { OP_ResultRow
, 3, 1, 0}, /* 3 */
2122 { OP_Halt
, 0, 0, 0}, /* 4 */
2123 { OP_String8
, 0, 3, 0}, /* 5 */
2124 { OP_Goto
, 0, 3, 0}, /* 6 */
2128 aOp
= sqlite3VdbeAddOpList(v
, ArraySize(endCode
), endCode
, iLn
);
2130 aOp
[0].p2
= 1-mxErr
;
2131 aOp
[2].p4type
= P4_STATIC
;
2133 aOp
[5].p4type
= P4_STATIC
;
2134 aOp
[5].p4
.z
= (char*)sqlite3ErrStr(SQLITE_CORRUPT
);
2136 sqlite3VdbeChangeP3(v
, 0, sqlite3VdbeCurrentAddr(v
)-2);
2140 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
2142 #ifndef SQLITE_OMIT_UTF16
2145 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
2147 ** In its first form, this pragma returns the encoding of the main
2148 ** database. If the database is not initialized, it is initialized now.
2150 ** The second form of this pragma is a no-op if the main database file
2151 ** has not already been initialized. In this case it sets the default
2152 ** encoding that will be used for the main database file if a new file
2153 ** is created. If an existing main database file is opened, then the
2154 ** default text encoding for the existing database is used.
2156 ** In all cases new databases created using the ATTACH command are
2157 ** created to use the same default text encoding as the main database. If
2158 ** the main database has not been initialized and/or created when ATTACH
2159 ** is executed, this is done before the ATTACH operation.
2161 ** In the second form this pragma sets the text encoding to be used in
2162 ** new database files created using this database handle. It is only
2163 ** useful if invoked immediately after the main database i
2165 case PragTyp_ENCODING
: {
2166 static const struct EncName
{
2170 { "UTF8", SQLITE_UTF8
},
2171 { "UTF-8", SQLITE_UTF8
}, /* Must be element [1] */
2172 { "UTF-16le", SQLITE_UTF16LE
}, /* Must be element [2] */
2173 { "UTF-16be", SQLITE_UTF16BE
}, /* Must be element [3] */
2174 { "UTF16le", SQLITE_UTF16LE
},
2175 { "UTF16be", SQLITE_UTF16BE
},
2176 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
2177 { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
2180 const struct EncName
*pEnc
;
2181 if( !zRight
){ /* "PRAGMA encoding" */
2182 if( sqlite3ReadSchema(pParse
) ) goto pragma_out
;
2183 assert( encnames
[SQLITE_UTF8
].enc
==SQLITE_UTF8
);
2184 assert( encnames
[SQLITE_UTF16LE
].enc
==SQLITE_UTF16LE
);
2185 assert( encnames
[SQLITE_UTF16BE
].enc
==SQLITE_UTF16BE
);
2186 returnSingleText(v
, encnames
[ENC(pParse
->db
)].zName
);
2187 }else{ /* "PRAGMA encoding = XXX" */
2188 /* Only change the value of sqlite.enc if the database handle is not
2189 ** initialized. If the main database exists, the new sqlite.enc value
2190 ** will be overwritten when the schema is next loaded. If it does not
2191 ** already exists, it will be created to use the new encoding value.
2193 if( (db
->mDbFlags
& DBFLAG_EncodingFixed
)==0 ){
2194 for(pEnc
=&encnames
[0]; pEnc
->zName
; pEnc
++){
2195 if( 0==sqlite3StrICmp(zRight
, pEnc
->zName
) ){
2196 u8 enc
= pEnc
->enc
? pEnc
->enc
: SQLITE_UTF16NATIVE
;
2197 SCHEMA_ENC(db
) = enc
;
2198 sqlite3SetTextEncoding(db
, enc
);
2203 sqlite3ErrorMsg(pParse
, "unsupported encoding: %s", zRight
);
2209 #endif /* SQLITE_OMIT_UTF16 */
2211 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
2213 ** PRAGMA [schema.]schema_version
2214 ** PRAGMA [schema.]schema_version = <integer>
2216 ** PRAGMA [schema.]user_version
2217 ** PRAGMA [schema.]user_version = <integer>
2219 ** PRAGMA [schema.]freelist_count
2221 ** PRAGMA [schema.]data_version
2223 ** PRAGMA [schema.]application_id
2224 ** PRAGMA [schema.]application_id = <integer>
2226 ** The pragma's schema_version and user_version are used to set or get
2227 ** the value of the schema-version and user-version, respectively. Both
2228 ** the schema-version and the user-version are 32-bit signed integers
2229 ** stored in the database header.
2231 ** The schema-cookie is usually only manipulated internally by SQLite. It
2232 ** is incremented by SQLite whenever the database schema is modified (by
2233 ** creating or dropping a table or index). The schema version is used by
2234 ** SQLite each time a query is executed to ensure that the internal cache
2235 ** of the schema used when compiling the SQL query matches the schema of
2236 ** the database against which the compiled query is actually executed.
2237 ** Subverting this mechanism by using "PRAGMA schema_version" to modify
2238 ** the schema-version is potentially dangerous and may lead to program
2239 ** crashes or database corruption. Use with caution!
2241 ** The user-version is not used internally by SQLite. It may be used by
2242 ** applications for any purpose.
2244 case PragTyp_HEADER_VALUE
: {
2245 int iCookie
= pPragma
->iArg
; /* Which cookie to read or write */
2246 sqlite3VdbeUsesBtree(v
, iDb
);
2247 if( zRight
&& (pPragma
->mPragFlg
& PragFlg_ReadOnly
)==0 ){
2248 /* Write the specified cookie value */
2249 static const VdbeOpList setCookie
[] = {
2250 { OP_Transaction
, 0, 1, 0}, /* 0 */
2251 { OP_SetCookie
, 0, 0, 0}, /* 1 */
2254 sqlite3VdbeVerifyNoMallocRequired(v
, ArraySize(setCookie
));
2255 aOp
= sqlite3VdbeAddOpList(v
, ArraySize(setCookie
), setCookie
, 0);
2256 if( ONLY_IF_REALLOC_STRESS(aOp
==0) ) break;
2259 aOp
[1].p2
= iCookie
;
2260 aOp
[1].p3
= sqlite3Atoi(zRight
);
2262 if( iCookie
==BTREE_SCHEMA_VERSION
&& (db
->flags
& SQLITE_Defensive
)!=0 ){
2263 /* Do not allow the use of PRAGMA schema_version=VALUE in defensive
2264 ** mode. Change the OP_SetCookie opcode into a no-op. */
2265 aOp
[1].opcode
= OP_Noop
;
2268 /* Read the specified cookie value */
2269 static const VdbeOpList readCookie
[] = {
2270 { OP_Transaction
, 0, 0, 0}, /* 0 */
2271 { OP_ReadCookie
, 0, 1, 0}, /* 1 */
2272 { OP_ResultRow
, 1, 1, 0}
2275 sqlite3VdbeVerifyNoMallocRequired(v
, ArraySize(readCookie
));
2276 aOp
= sqlite3VdbeAddOpList(v
, ArraySize(readCookie
),readCookie
,0);
2277 if( ONLY_IF_REALLOC_STRESS(aOp
==0) ) break;
2280 aOp
[1].p3
= iCookie
;
2281 sqlite3VdbeReusable(v
);
2285 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
2287 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
2289 ** PRAGMA compile_options
2291 ** Return the names of all compile-time options used in this build,
2292 ** one option per row.
2294 case PragTyp_COMPILE_OPTIONS
: {
2298 while( (zOpt
= sqlite3_compileoption_get(i
++))!=0 ){
2299 sqlite3VdbeLoadString(v
, 1, zOpt
);
2300 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, 1);
2302 sqlite3VdbeReusable(v
);
2305 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
2307 #ifndef SQLITE_OMIT_WAL
2309 ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
2311 ** Checkpoint the database.
2313 case PragTyp_WAL_CHECKPOINT
: {
2314 int iBt
= (pId2
->z
?iDb
:SQLITE_MAX_DB
);
2315 int eMode
= SQLITE_CHECKPOINT_PASSIVE
;
2317 if( sqlite3StrICmp(zRight
, "full")==0 ){
2318 eMode
= SQLITE_CHECKPOINT_FULL
;
2319 }else if( sqlite3StrICmp(zRight
, "restart")==0 ){
2320 eMode
= SQLITE_CHECKPOINT_RESTART
;
2321 }else if( sqlite3StrICmp(zRight
, "truncate")==0 ){
2322 eMode
= SQLITE_CHECKPOINT_TRUNCATE
;
2326 sqlite3VdbeAddOp3(v
, OP_Checkpoint
, iBt
, eMode
, 1);
2327 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, 3);
2332 ** PRAGMA wal_autocheckpoint
2333 ** PRAGMA wal_autocheckpoint = N
2335 ** Configure a database connection to automatically checkpoint a database
2336 ** after accumulating N frames in the log. Or query for the current value
2339 case PragTyp_WAL_AUTOCHECKPOINT
: {
2341 sqlite3_wal_autocheckpoint(db
, sqlite3Atoi(zRight
));
2344 db
->xWalCallback
==sqlite3WalDefaultHook
?
2345 SQLITE_PTR_TO_INT(db
->pWalArg
) : 0);
2351 ** PRAGMA shrink_memory
2353 ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
2354 ** connection on which it is invoked to free up as much memory as it
2355 ** can, by calling sqlite3_db_release_memory().
2357 case PragTyp_SHRINK_MEMORY
: {
2358 sqlite3_db_release_memory(db
);
2364 ** PRAGMA optimize(MASK)
2365 ** PRAGMA schema.optimize
2366 ** PRAGMA schema.optimize(MASK)
2368 ** Attempt to optimize the database. All schemas are optimized in the first
2369 ** two forms, and only the specified schema is optimized in the latter two.
2371 ** The details of optimizations performed by this pragma are expected
2372 ** to change and improve over time. Applications should anticipate that
2373 ** this pragma will perform new optimizations in future releases.
2375 ** The optional argument is a bitmask of optimizations to perform:
2377 ** 0x0001 Debugging mode. Do not actually perform any optimizations
2378 ** but instead return one line of text for each optimization
2379 ** that would have been done. Off by default.
2381 ** 0x0002 Run ANALYZE on tables that might benefit. On by default.
2382 ** See below for additional information.
2384 ** 0x0004 (Not yet implemented) Record usage and performance
2385 ** information from the current session in the
2386 ** database file so that it will be available to "optimize"
2387 ** pragmas run by future database connections.
2389 ** 0x0008 (Not yet implemented) Create indexes that might have
2390 ** been helpful to recent queries
2392 ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all
2393 ** of the optimizations listed above except Debug Mode, including new
2394 ** optimizations that have not yet been invented. If new optimizations are
2395 ** ever added that should be off by default, those off-by-default
2396 ** optimizations will have bitmasks of 0x10000 or larger.
2398 ** DETERMINATION OF WHEN TO RUN ANALYZE
2400 ** In the current implementation, a table is analyzed if only if all of
2401 ** the following are true:
2403 ** (1) MASK bit 0x02 is set.
2405 ** (2) The query planner used sqlite_stat1-style statistics for one or
2406 ** more indexes of the table at some point during the lifetime of
2407 ** the current connection.
2409 ** (3) One or more indexes of the table are currently unanalyzed OR
2410 ** the number of rows in the table has increased by 25 times or more
2411 ** since the last time ANALYZE was run.
2413 ** The rules for when tables are analyzed are likely to change in
2416 case PragTyp_OPTIMIZE
: {
2417 int iDbLast
; /* Loop termination point for the schema loop */
2418 int iTabCur
; /* Cursor for a table whose size needs checking */
2419 HashElem
*k
; /* Loop over tables of a schema */
2420 Schema
*pSchema
; /* The current schema */
2421 Table
*pTab
; /* A table in the schema */
2422 Index
*pIdx
; /* An index of the table */
2423 LogEst szThreshold
; /* Size threshold above which reanalysis needed */
2424 char *zSubSql
; /* SQL statement for the OP_SqlExec opcode */
2425 u32 opMask
; /* Mask of operations to perform */
2428 opMask
= (u32
)sqlite3Atoi(zRight
);
2429 if( (opMask
& 0x02)==0 ) break;
2433 iTabCur
= pParse
->nTab
++;
2434 for(iDbLast
= zDb
?iDb
:db
->nDb
-1; iDb
<=iDbLast
; iDb
++){
2435 if( iDb
==1 ) continue;
2436 sqlite3CodeVerifySchema(pParse
, iDb
);
2437 pSchema
= db
->aDb
[iDb
].pSchema
;
2438 for(k
=sqliteHashFirst(&pSchema
->tblHash
); k
; k
=sqliteHashNext(k
)){
2439 pTab
= (Table
*)sqliteHashData(k
);
2441 /* If table pTab has not been used in a way that would benefit from
2442 ** having analysis statistics during the current session, then skip it.
2443 ** This also has the effect of skipping virtual tables and views */
2444 if( (pTab
->tabFlags
& TF_StatsUsed
)==0 ) continue;
2446 /* Reanalyze if the table is 25 times larger than the last analysis */
2447 szThreshold
= pTab
->nRowLogEst
+ 46; assert( sqlite3LogEst(25)==46 );
2448 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
2449 if( !pIdx
->hasStat1
){
2450 szThreshold
= 0; /* Always analyze if any index lacks statistics */
2455 sqlite3OpenTable(pParse
, iTabCur
, iDb
, pTab
, OP_OpenRead
);
2456 sqlite3VdbeAddOp3(v
, OP_IfSmaller
, iTabCur
,
2457 sqlite3VdbeCurrentAddr(v
)+2+(opMask
&1), szThreshold
);
2460 zSubSql
= sqlite3MPrintf(db
, "ANALYZE \"%w\".\"%w\"",
2461 db
->aDb
[iDb
].zDbSName
, pTab
->zName
);
2462 if( opMask
& 0x01 ){
2463 int r1
= sqlite3GetTempReg(pParse
);
2464 sqlite3VdbeAddOp4(v
, OP_String8
, 0, r1
, 0, zSubSql
, P4_DYNAMIC
);
2465 sqlite3VdbeAddOp2(v
, OP_ResultRow
, r1
, 1);
2467 sqlite3VdbeAddOp4(v
, OP_SqlExec
, 0, 0, 0, zSubSql
, P4_DYNAMIC
);
2471 sqlite3VdbeAddOp0(v
, OP_Expire
);
2476 ** PRAGMA busy_timeout
2477 ** PRAGMA busy_timeout = N
2479 ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
2480 ** if one is set. If no busy handler or a different busy handler is set
2481 ** then 0 is returned. Setting the busy_timeout to 0 or negative
2482 ** disables the timeout.
2484 /*case PragTyp_BUSY_TIMEOUT*/ default: {
2485 assert( pPragma
->ePragTyp
==PragTyp_BUSY_TIMEOUT
);
2487 sqlite3_busy_timeout(db
, sqlite3Atoi(zRight
));
2489 returnSingleInt(v
, db
->busyTimeout
);
2494 ** PRAGMA soft_heap_limit
2495 ** PRAGMA soft_heap_limit = N
2497 ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
2498 ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
2499 ** specified and is a non-negative integer.
2500 ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
2501 ** returns the same integer that would be returned by the
2502 ** sqlite3_soft_heap_limit64(-1) C-language function.
2504 case PragTyp_SOFT_HEAP_LIMIT
: {
2506 if( zRight
&& sqlite3DecOrHexToI64(zRight
, &N
)==SQLITE_OK
){
2507 sqlite3_soft_heap_limit64(N
);
2509 returnSingleInt(v
, sqlite3_soft_heap_limit64(-1));
2514 ** PRAGMA hard_heap_limit
2515 ** PRAGMA hard_heap_limit = N
2517 ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap
2518 ** limit. The hard heap limit can be activated or lowered by this
2519 ** pragma, but not raised or deactivated. Only the
2520 ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate
2521 ** the hard heap limit. This allows an application to set a heap limit
2522 ** constraint that cannot be relaxed by an untrusted SQL script.
2524 case PragTyp_HARD_HEAP_LIMIT
: {
2526 if( zRight
&& sqlite3DecOrHexToI64(zRight
, &N
)==SQLITE_OK
){
2527 sqlite3_int64 iPrior
= sqlite3_hard_heap_limit64(-1);
2528 if( N
>0 && (iPrior
==0 || iPrior
>N
) ) sqlite3_hard_heap_limit64(N
);
2530 returnSingleInt(v
, sqlite3_hard_heap_limit64(-1));
2536 ** PRAGMA threads = N
2538 ** Configure the maximum number of worker threads. Return the new
2539 ** maximum, which might be less than requested.
2541 case PragTyp_THREADS
: {
2544 && sqlite3DecOrHexToI64(zRight
, &N
)==SQLITE_OK
2547 sqlite3_limit(db
, SQLITE_LIMIT_WORKER_THREADS
, (int)(N
&0x7fffffff));
2549 returnSingleInt(v
, sqlite3_limit(db
, SQLITE_LIMIT_WORKER_THREADS
, -1));
2554 ** PRAGMA analysis_limit
2555 ** PRAGMA analysis_limit = N
2557 ** Configure the maximum number of rows that ANALYZE will examine
2558 ** in each index that it looks at. Return the new limit.
2560 case PragTyp_ANALYSIS_LIMIT
: {
2563 && sqlite3DecOrHexToI64(zRight
, &N
)==SQLITE_OK
/* IMP: R-40975-20399 */
2566 db
->nAnalysisLimit
= (int)(N
&0x7fffffff);
2568 returnSingleInt(v
, db
->nAnalysisLimit
); /* IMP: R-57594-65522 */
2572 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
2574 ** Report the current state of file logs for all databases
2576 case PragTyp_LOCK_STATUS
: {
2577 static const char *const azLockName
[] = {
2578 "unlocked", "shared", "reserved", "pending", "exclusive"
2582 for(i
=0; i
<db
->nDb
; i
++){
2584 const char *zState
= "unknown";
2586 if( db
->aDb
[i
].zDbSName
==0 ) continue;
2587 pBt
= db
->aDb
[i
].pBt
;
2588 if( pBt
==0 || sqlite3BtreePager(pBt
)==0 ){
2590 }else if( sqlite3_file_control(db
, i
? db
->aDb
[i
].zDbSName
: 0,
2591 SQLITE_FCNTL_LOCKSTATE
, &j
)==SQLITE_OK
){
2592 zState
= azLockName
[j
];
2594 sqlite3VdbeMultiLoad(v
, 1, "ss", db
->aDb
[i
].zDbSName
, zState
);
2600 #if defined(SQLITE_ENABLE_CEROD)
2601 case PragTyp_ACTIVATE_EXTENSIONS
: if( zRight
){
2602 if( sqlite3StrNICmp(zRight
, "cerod-", 6)==0 ){
2603 sqlite3_activate_cerod(&zRight
[6]);
2609 } /* End of the PRAGMA switch */
2611 /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
2612 ** purpose is to execute assert() statements to verify that if the
2613 ** PragFlg_NoColumns1 flag is set and the caller specified an argument
2614 ** to the PRAGMA, the implementation has not added any OP_ResultRow
2615 ** instructions to the VM. */
2616 if( (pPragma
->mPragFlg
& PragFlg_NoColumns1
) && zRight
){
2617 sqlite3VdbeVerifyNoResultRow(v
);
2621 sqlite3DbFree(db
, zLeft
);
2622 sqlite3DbFree(db
, zRight
);
2624 #ifndef SQLITE_OMIT_VIRTUALTABLE
2625 /*****************************************************************************
2626 ** Implementation of an eponymous virtual table that runs a pragma.
2629 typedef struct PragmaVtab PragmaVtab
;
2630 typedef struct PragmaVtabCursor PragmaVtabCursor
;
2632 sqlite3_vtab base
; /* Base class. Must be first */
2633 sqlite3
*db
; /* The database connection to which it belongs */
2634 const PragmaName
*pName
; /* Name of the pragma */
2635 u8 nHidden
; /* Number of hidden columns */
2636 u8 iHidden
; /* Index of the first hidden column */
2638 struct PragmaVtabCursor
{
2639 sqlite3_vtab_cursor base
; /* Base class. Must be first */
2640 sqlite3_stmt
*pPragma
; /* The pragma statement to run */
2641 sqlite_int64 iRowid
; /* Current rowid */
2642 char *azArg
[2]; /* Value of the argument and schema */
2646 ** Pragma virtual table module xConnect method.
2648 static int pragmaVtabConnect(
2651 int argc
, const char *const*argv
,
2652 sqlite3_vtab
**ppVtab
,
2655 const PragmaName
*pPragma
= (const PragmaName
*)pAux
;
2656 PragmaVtab
*pTab
= 0;
2663 UNUSED_PARAMETER(argc
);
2664 UNUSED_PARAMETER(argv
);
2665 sqlite3StrAccumInit(&acc
, 0, zBuf
, sizeof(zBuf
), 0);
2666 sqlite3_str_appendall(&acc
, "CREATE TABLE x");
2667 for(i
=0, j
=pPragma
->iPragCName
; i
<pPragma
->nPragCName
; i
++, j
++){
2668 sqlite3_str_appendf(&acc
, "%c\"%s\"", cSep
, pragCName
[j
]);
2672 sqlite3_str_appendf(&acc
, "(\"%s\"", pPragma
->zName
);
2676 if( pPragma
->mPragFlg
& PragFlg_Result1
){
2677 sqlite3_str_appendall(&acc
, ",arg HIDDEN");
2680 if( pPragma
->mPragFlg
& (PragFlg_SchemaOpt
|PragFlg_SchemaReq
) ){
2681 sqlite3_str_appendall(&acc
, ",schema HIDDEN");
2684 sqlite3_str_append(&acc
, ")", 1);
2685 sqlite3StrAccumFinish(&acc
);
2686 assert( strlen(zBuf
) < sizeof(zBuf
)-1 );
2687 rc
= sqlite3_declare_vtab(db
, zBuf
);
2688 if( rc
==SQLITE_OK
){
2689 pTab
= (PragmaVtab
*)sqlite3_malloc(sizeof(PragmaVtab
));
2693 memset(pTab
, 0, sizeof(PragmaVtab
));
2694 pTab
->pName
= pPragma
;
2700 *pzErr
= sqlite3_mprintf("%s", sqlite3_errmsg(db
));
2703 *ppVtab
= (sqlite3_vtab
*)pTab
;
2708 ** Pragma virtual table module xDisconnect method.
2710 static int pragmaVtabDisconnect(sqlite3_vtab
*pVtab
){
2711 PragmaVtab
*pTab
= (PragmaVtab
*)pVtab
;
2716 /* Figure out the best index to use to search a pragma virtual table.
2718 ** There are not really any index choices. But we want to encourage the
2719 ** query planner to give == constraints on as many hidden parameters as
2720 ** possible, and especially on the first hidden parameter. So return a
2721 ** high cost if hidden parameters are unconstrained.
2723 static int pragmaVtabBestIndex(sqlite3_vtab
*tab
, sqlite3_index_info
*pIdxInfo
){
2724 PragmaVtab
*pTab
= (PragmaVtab
*)tab
;
2725 const struct sqlite3_index_constraint
*pConstraint
;
2729 pIdxInfo
->estimatedCost
= (double)1;
2730 if( pTab
->nHidden
==0 ){ return SQLITE_OK
; }
2731 pConstraint
= pIdxInfo
->aConstraint
;
2734 for(i
=0; i
<pIdxInfo
->nConstraint
; i
++, pConstraint
++){
2735 if( pConstraint
->usable
==0 ) continue;
2736 if( pConstraint
->op
!=SQLITE_INDEX_CONSTRAINT_EQ
) continue;
2737 if( pConstraint
->iColumn
< pTab
->iHidden
) continue;
2738 j
= pConstraint
->iColumn
- pTab
->iHidden
;
2743 pIdxInfo
->estimatedCost
= (double)2147483647;
2744 pIdxInfo
->estimatedRows
= 2147483647;
2748 pIdxInfo
->aConstraintUsage
[j
].argvIndex
= 1;
2749 pIdxInfo
->aConstraintUsage
[j
].omit
= 1;
2750 if( seen
[1]==0 ) return SQLITE_OK
;
2751 pIdxInfo
->estimatedCost
= (double)20;
2752 pIdxInfo
->estimatedRows
= 20;
2754 pIdxInfo
->aConstraintUsage
[j
].argvIndex
= 2;
2755 pIdxInfo
->aConstraintUsage
[j
].omit
= 1;
2759 /* Create a new cursor for the pragma virtual table */
2760 static int pragmaVtabOpen(sqlite3_vtab
*pVtab
, sqlite3_vtab_cursor
**ppCursor
){
2761 PragmaVtabCursor
*pCsr
;
2762 pCsr
= (PragmaVtabCursor
*)sqlite3_malloc(sizeof(*pCsr
));
2763 if( pCsr
==0 ) return SQLITE_NOMEM
;
2764 memset(pCsr
, 0, sizeof(PragmaVtabCursor
));
2765 pCsr
->base
.pVtab
= pVtab
;
2766 *ppCursor
= &pCsr
->base
;
2770 /* Clear all content from pragma virtual table cursor. */
2771 static void pragmaVtabCursorClear(PragmaVtabCursor
*pCsr
){
2773 sqlite3_finalize(pCsr
->pPragma
);
2775 for(i
=0; i
<ArraySize(pCsr
->azArg
); i
++){
2776 sqlite3_free(pCsr
->azArg
[i
]);
2781 /* Close a pragma virtual table cursor */
2782 static int pragmaVtabClose(sqlite3_vtab_cursor
*cur
){
2783 PragmaVtabCursor
*pCsr
= (PragmaVtabCursor
*)cur
;
2784 pragmaVtabCursorClear(pCsr
);
2789 /* Advance the pragma virtual table cursor to the next row */
2790 static int pragmaVtabNext(sqlite3_vtab_cursor
*pVtabCursor
){
2791 PragmaVtabCursor
*pCsr
= (PragmaVtabCursor
*)pVtabCursor
;
2794 /* Increment the xRowid value */
2796 assert( pCsr
->pPragma
);
2797 if( SQLITE_ROW
!=sqlite3_step(pCsr
->pPragma
) ){
2798 rc
= sqlite3_finalize(pCsr
->pPragma
);
2800 pragmaVtabCursorClear(pCsr
);
2806 ** Pragma virtual table module xFilter method.
2808 static int pragmaVtabFilter(
2809 sqlite3_vtab_cursor
*pVtabCursor
,
2810 int idxNum
, const char *idxStr
,
2811 int argc
, sqlite3_value
**argv
2813 PragmaVtabCursor
*pCsr
= (PragmaVtabCursor
*)pVtabCursor
;
2814 PragmaVtab
*pTab
= (PragmaVtab
*)(pVtabCursor
->pVtab
);
2820 UNUSED_PARAMETER(idxNum
);
2821 UNUSED_PARAMETER(idxStr
);
2822 pragmaVtabCursorClear(pCsr
);
2823 j
= (pTab
->pName
->mPragFlg
& PragFlg_Result1
)!=0 ? 0 : 1;
2824 for(i
=0; i
<argc
; i
++, j
++){
2825 const char *zText
= (const char*)sqlite3_value_text(argv
[i
]);
2826 assert( j
<ArraySize(pCsr
->azArg
) );
2827 assert( pCsr
->azArg
[j
]==0 );
2829 pCsr
->azArg
[j
] = sqlite3_mprintf("%s", zText
);
2830 if( pCsr
->azArg
[j
]==0 ){
2831 return SQLITE_NOMEM
;
2835 sqlite3StrAccumInit(&acc
, 0, 0, 0, pTab
->db
->aLimit
[SQLITE_LIMIT_SQL_LENGTH
]);
2836 sqlite3_str_appendall(&acc
, "PRAGMA ");
2837 if( pCsr
->azArg
[1] ){
2838 sqlite3_str_appendf(&acc
, "%Q.", pCsr
->azArg
[1]);
2840 sqlite3_str_appendall(&acc
, pTab
->pName
->zName
);
2841 if( pCsr
->azArg
[0] ){
2842 sqlite3_str_appendf(&acc
, "=%Q", pCsr
->azArg
[0]);
2844 zSql
= sqlite3StrAccumFinish(&acc
);
2845 if( zSql
==0 ) return SQLITE_NOMEM
;
2846 rc
= sqlite3_prepare_v2(pTab
->db
, zSql
, -1, &pCsr
->pPragma
, 0);
2848 if( rc
!=SQLITE_OK
){
2849 pTab
->base
.zErrMsg
= sqlite3_mprintf("%s", sqlite3_errmsg(pTab
->db
));
2852 return pragmaVtabNext(pVtabCursor
);
2856 ** Pragma virtual table module xEof method.
2858 static int pragmaVtabEof(sqlite3_vtab_cursor
*pVtabCursor
){
2859 PragmaVtabCursor
*pCsr
= (PragmaVtabCursor
*)pVtabCursor
;
2860 return (pCsr
->pPragma
==0);
2863 /* The xColumn method simply returns the corresponding column from
2866 static int pragmaVtabColumn(
2867 sqlite3_vtab_cursor
*pVtabCursor
,
2868 sqlite3_context
*ctx
,
2871 PragmaVtabCursor
*pCsr
= (PragmaVtabCursor
*)pVtabCursor
;
2872 PragmaVtab
*pTab
= (PragmaVtab
*)(pVtabCursor
->pVtab
);
2873 if( i
<pTab
->iHidden
){
2874 sqlite3_result_value(ctx
, sqlite3_column_value(pCsr
->pPragma
, i
));
2876 sqlite3_result_text(ctx
, pCsr
->azArg
[i
-pTab
->iHidden
],-1,SQLITE_TRANSIENT
);
2882 ** Pragma virtual table module xRowid method.
2884 static int pragmaVtabRowid(sqlite3_vtab_cursor
*pVtabCursor
, sqlite_int64
*p
){
2885 PragmaVtabCursor
*pCsr
= (PragmaVtabCursor
*)pVtabCursor
;
2890 /* The pragma virtual table object */
2891 static const sqlite3_module pragmaVtabModule
= {
2893 0, /* xCreate - create a table */
2894 pragmaVtabConnect
, /* xConnect - connect to an existing table */
2895 pragmaVtabBestIndex
, /* xBestIndex - Determine search strategy */
2896 pragmaVtabDisconnect
, /* xDisconnect - Disconnect from a table */
2897 0, /* xDestroy - Drop a table */
2898 pragmaVtabOpen
, /* xOpen - open a cursor */
2899 pragmaVtabClose
, /* xClose - close a cursor */
2900 pragmaVtabFilter
, /* xFilter - configure scan constraints */
2901 pragmaVtabNext
, /* xNext - advance a cursor */
2902 pragmaVtabEof
, /* xEof */
2903 pragmaVtabColumn
, /* xColumn - read data */
2904 pragmaVtabRowid
, /* xRowid - read data */
2905 0, /* xUpdate - write data */
2906 0, /* xBegin - begin transaction */
2907 0, /* xSync - sync transaction */
2908 0, /* xCommit - commit transaction */
2909 0, /* xRollback - rollback transaction */
2910 0, /* xFindFunction - function overloading */
2911 0, /* xRename - rename the table */
2914 0, /* xRollbackTo */
2915 0, /* xShadowName */
2920 ** Check to see if zTabName is really the name of a pragma. If it is,
2921 ** then register an eponymous virtual table for that pragma and return
2922 ** a pointer to the Module object for the new virtual table.
2924 Module
*sqlite3PragmaVtabRegister(sqlite3
*db
, const char *zName
){
2925 const PragmaName
*pName
;
2926 assert( sqlite3_strnicmp(zName
, "pragma_", 7)==0 );
2927 pName
= pragmaLocate(zName
+7);
2928 if( pName
==0 ) return 0;
2929 if( (pName
->mPragFlg
& (PragFlg_Result0
|PragFlg_Result1
))==0 ) return 0;
2930 assert( sqlite3HashFind(&db
->aModule
, zName
)==0 );
2931 return sqlite3VtabCreateModule(db
, zName
, &pragmaVtabModule
, (void*)pName
, 0);
2934 #endif /* SQLITE_OMIT_VIRTUALTABLE */
2936 #endif /* SQLITE_OMIT_PRAGMA */