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 ** When the 0x10 bit of PRAGMA optimize is set, any ANALYZE commands
35 ** will be run with an analysis_limit set to the lessor of the value of
36 ** the following macro or to the actual analysis_limit if it is non-zero,
37 ** in order to prevent PRAGMA optimize from running for too long.
39 ** The value of 2000 is chosen emperically so that the worst-case run-time
40 ** for PRAGMA optimize does not exceed 100 milliseconds against a variety
41 ** of test databases on a RaspberryPI-4 compiled using -Os and without
42 ** -DSQLITE_DEBUG. Of course, your mileage may vary. For the purpose of
43 ** this paragraph, "worst-case" means that ANALYZE ends up being
44 ** run on every table in the database. The worst case typically only
45 ** happens if PRAGMA optimize is run on a database file for which ANALYZE
46 ** has not been previously run and the 0x10000 flag is included so that
47 ** all tables are analyzed. The usual case for PRAGMA optimize is that
48 ** no ANALYZE commands will be run at all, or if any ANALYZE happens it
49 ** will be against a single table, so that expected timing for PRAGMA
50 ** optimize on a PI-4 is more like 1 millisecond or less with the 0x10000
51 ** flag or less than 100 microseconds without the 0x10000 flag.
53 ** An analysis limit of 2000 is almost always sufficient for the query
54 ** planner to fully characterize an index. The additional accuracy from
55 ** a larger analysis is not usually helpful.
57 #ifndef SQLITE_DEFAULT_OPTIMIZE_LIMIT
58 # define SQLITE_DEFAULT_OPTIMIZE_LIMIT 2000
62 ** Interpret the given string as a safety level. Return 0 for OFF,
63 ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
64 ** unrecognized string argument. The FULL and EXTRA option is disallowed
65 ** if the omitFull parameter it 1.
67 ** Note that the values returned are one less that the values that
68 ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
69 ** to support legacy SQL code. The safety level used to be boolean
70 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
72 static u8
getSafetyLevel(const char *z
, int omitFull
, u8 dflt
){
73 /* 123456789 123456789 123 */
74 static const char zText
[] = "onoffalseyestruextrafull";
75 static const u8 iOffset
[] = {0, 1, 2, 4, 9, 12, 15, 20};
76 static const u8 iLength
[] = {2, 2, 3, 5, 3, 4, 5, 4};
77 static const u8 iValue
[] = {1, 0, 0, 0, 1, 1, 3, 2};
78 /* on no off false yes true extra full */
80 if( sqlite3Isdigit(*z
) ){
81 return (u8
)sqlite3Atoi(z
);
83 n
= sqlite3Strlen30(z
);
84 for(i
=0; i
<ArraySize(iLength
); i
++){
85 if( iLength
[i
]==n
&& sqlite3StrNICmp(&zText
[iOffset
[i
]],z
,n
)==0
86 && (!omitFull
|| iValue
[i
]<=1)
95 ** Interpret the given string as a boolean value.
97 u8
sqlite3GetBoolean(const char *z
, u8 dflt
){
98 return getSafetyLevel(z
,1,dflt
)!=0;
101 /* The sqlite3GetBoolean() function is used by other modules but the
102 ** remainder of this file is specific to PRAGMA processing. So omit
103 ** the rest of the file if PRAGMAs are omitted from the build.
105 #if !defined(SQLITE_OMIT_PRAGMA)
108 ** Interpret the given string as a locking mode value.
110 static int getLockingMode(const char *z
){
112 if( 0==sqlite3StrICmp(z
, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE
;
113 if( 0==sqlite3StrICmp(z
, "normal") ) return PAGER_LOCKINGMODE_NORMAL
;
115 return PAGER_LOCKINGMODE_QUERY
;
118 #ifndef SQLITE_OMIT_AUTOVACUUM
120 ** Interpret the given string as an auto-vacuum mode value.
122 ** The following strings, "none", "full" and "incremental" are
123 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
125 static int getAutoVacuum(const char *z
){
127 if( 0==sqlite3StrICmp(z
, "none") ) return BTREE_AUTOVACUUM_NONE
;
128 if( 0==sqlite3StrICmp(z
, "full") ) return BTREE_AUTOVACUUM_FULL
;
129 if( 0==sqlite3StrICmp(z
, "incremental") ) return BTREE_AUTOVACUUM_INCR
;
131 return (u8
)((i
>=0&&i
<=2)?i
:0);
133 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
135 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
137 ** Interpret the given string as a temp db location. Return 1 for file
138 ** backed temporary databases, 2 for the Red-Black tree in memory database
139 ** and 0 to use the compile-time default.
141 static int getTempStore(const char *z
){
142 if( z
[0]>='0' && z
[0]<='2' ){
144 }else if( sqlite3StrICmp(z
, "file")==0 ){
146 }else if( sqlite3StrICmp(z
, "memory")==0 ){
152 #endif /* SQLITE_PAGER_PRAGMAS */
154 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
156 ** Invalidate temp storage, either when the temp storage is changed
157 ** from default, or when 'file' and the temp_store_directory has changed
159 static int invalidateTempStorage(Parse
*pParse
){
160 sqlite3
*db
= pParse
->db
;
161 if( db
->aDb
[1].pBt
!=0 ){
163 || sqlite3BtreeTxnState(db
->aDb
[1].pBt
)!=SQLITE_TXN_NONE
165 sqlite3ErrorMsg(pParse
, "temporary storage cannot be changed "
166 "from within a transaction");
169 sqlite3BtreeClose(db
->aDb
[1].pBt
);
171 sqlite3ResetAllSchemasOfConnection(db
);
175 #endif /* SQLITE_PAGER_PRAGMAS */
177 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
179 ** If the TEMP database is open, close it and mark the database schema
180 ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
181 ** or DEFAULT_TEMP_STORE pragmas.
183 static int changeTempStorage(Parse
*pParse
, const char *zStorageType
){
184 int ts
= getTempStore(zStorageType
);
185 sqlite3
*db
= pParse
->db
;
186 if( db
->temp_store
==ts
) return SQLITE_OK
;
187 if( invalidateTempStorage( pParse
) != SQLITE_OK
){
190 db
->temp_store
= (u8
)ts
;
193 #endif /* SQLITE_PAGER_PRAGMAS */
196 ** Set result column names for a pragma.
198 static void setPragmaResultColumnNames(
199 Vdbe
*v
, /* The query under construction */
200 const PragmaName
*pPragma
/* The pragma */
202 u8 n
= pPragma
->nPragCName
;
203 sqlite3VdbeSetNumCols(v
, n
==0 ? 1 : n
);
205 sqlite3VdbeSetColName(v
, 0, COLNAME_NAME
, pPragma
->zName
, SQLITE_STATIC
);
208 for(i
=0, j
=pPragma
->iPragCName
; i
<n
; i
++, j
++){
209 sqlite3VdbeSetColName(v
, i
, COLNAME_NAME
, pragCName
[j
], SQLITE_STATIC
);
215 ** Generate code to return a single integer value.
217 static void returnSingleInt(Vdbe
*v
, i64 value
){
218 sqlite3VdbeAddOp4Dup8(v
, OP_Int64
, 0, 1, 0, (const u8
*)&value
, P4_INT64
);
219 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, 1);
223 ** Generate code to return a single text value.
225 static void returnSingleText(
226 Vdbe
*v
, /* Prepared statement under construction */
227 const char *zValue
/* Value to be returned */
230 sqlite3VdbeLoadString(v
, 1, (const char*)zValue
);
231 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, 1);
237 ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
238 ** set these values for all pagers.
240 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
241 static void setAllPagerFlags(sqlite3
*db
){
242 if( db
->autoCommit
){
245 assert( SQLITE_FullFSync
==PAGER_FULLFSYNC
);
246 assert( SQLITE_CkptFullFSync
==PAGER_CKPT_FULLFSYNC
);
247 assert( SQLITE_CacheSpill
==PAGER_CACHESPILL
);
248 assert( (PAGER_FULLFSYNC
| PAGER_CKPT_FULLFSYNC
| PAGER_CACHESPILL
)
249 == PAGER_FLAGS_MASK
);
250 assert( (pDb
->safety_level
& PAGER_SYNCHRONOUS_MASK
)==pDb
->safety_level
);
253 sqlite3BtreeSetPagerFlags(pDb
->pBt
,
254 pDb
->safety_level
| (db
->flags
& PAGER_FLAGS_MASK
) );
261 # define setAllPagerFlags(X) /* no-op */
266 ** Return a human-readable name for a constraint resolution action.
268 #ifndef SQLITE_OMIT_FOREIGN_KEY
269 static const char *actionName(u8 action
){
272 case OE_SetNull
: zName
= "SET NULL"; break;
273 case OE_SetDflt
: zName
= "SET DEFAULT"; break;
274 case OE_Cascade
: zName
= "CASCADE"; break;
275 case OE_Restrict
: zName
= "RESTRICT"; break;
276 default: zName
= "NO ACTION";
277 assert( action
==OE_None
); break;
285 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
286 ** defined in pager.h. This function returns the associated lowercase
287 ** journal-mode name.
289 const char *sqlite3JournalModename(int eMode
){
290 static char * const azModeName
[] = {
291 "delete", "persist", "off", "truncate", "memory"
292 #ifndef SQLITE_OMIT_WAL
296 assert( PAGER_JOURNALMODE_DELETE
==0 );
297 assert( PAGER_JOURNALMODE_PERSIST
==1 );
298 assert( PAGER_JOURNALMODE_OFF
==2 );
299 assert( PAGER_JOURNALMODE_TRUNCATE
==3 );
300 assert( PAGER_JOURNALMODE_MEMORY
==4 );
301 assert( PAGER_JOURNALMODE_WAL
==5 );
302 assert( eMode
>=0 && eMode
<=ArraySize(azModeName
) );
304 if( eMode
==ArraySize(azModeName
) ) return 0;
305 return azModeName
[eMode
];
309 ** Locate a pragma in the aPragmaName[] array.
311 static const PragmaName
*pragmaLocate(const char *zName
){
312 int upr
, lwr
, mid
= 0, rc
;
314 upr
= ArraySize(aPragmaName
)-1;
317 rc
= sqlite3_stricmp(zName
, aPragmaName
[mid
].zName
);
325 return lwr
>upr
? 0 : &aPragmaName
[mid
];
329 ** Create zero or more entries in the output for the SQL functions
330 ** defined by FuncDef p.
332 static void pragmaFunclistLine(
333 Vdbe
*v
, /* The prepared statement being created */
334 FuncDef
*p
, /* A particular function definition */
335 int isBuiltin
, /* True if this is a built-in function */
336 int showInternFuncs
/* True if showing internal functions */
339 SQLITE_DETERMINISTIC
|
345 if( showInternFuncs
) mask
= 0xffffffff;
346 for(; p
; p
=p
->pNext
){
348 static const char *azEnc
[] = { 0, "utf8", "utf16le", "utf16be" };
350 assert( SQLITE_FUNC_ENCMASK
==0x3 );
351 assert( strcmp(azEnc
[SQLITE_UTF8
],"utf8")==0 );
352 assert( strcmp(azEnc
[SQLITE_UTF16LE
],"utf16le")==0 );
353 assert( strcmp(azEnc
[SQLITE_UTF16BE
],"utf16be")==0 );
355 if( p
->xSFunc
==0 ) continue;
356 if( (p
->funcFlags
& SQLITE_FUNC_INTERNAL
)!=0
357 && showInternFuncs
==0
363 }else if( p
->xFinalize
!=0 ){
368 sqlite3VdbeMultiLoad(v
, 1, "sissii",
370 zType
, azEnc
[p
->funcFlags
&SQLITE_FUNC_ENCMASK
],
372 (p
->funcFlags
& mask
) ^ SQLITE_INNOCUOUS
379 ** Helper subroutine for PRAGMA integrity_check:
381 ** Generate code to output a single-column result row with a value of the
382 ** string held in register 3. Decrement the result count in register 1
383 ** and halt if the maximum number of result rows have been issued.
385 static int integrityCheckResultRow(Vdbe
*v
){
387 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 3, 1);
388 addr
= sqlite3VdbeAddOp3(v
, OP_IfPos
, 1, sqlite3VdbeCurrentAddr(v
)+2, 1);
390 sqlite3VdbeAddOp0(v
, OP_Halt
);
395 ** Process a pragma statement.
397 ** Pragmas are of this form:
399 ** PRAGMA [schema.]id [= value]
401 ** The identifier might also be a string. The value is a string, and
402 ** identifier, or a number. If minusFlag is true, then the value is
403 ** a number that was preceded by a minus sign.
405 ** If the left side is "database.id" then pId1 is the database name
406 ** and pId2 is the id. If the left side is just "id" then pId1 is the
407 ** id and pId2 is any empty string.
411 Token
*pId1
, /* First part of [schema.]id field */
412 Token
*pId2
, /* Second part of [schema.]id field, or NULL */
413 Token
*pValue
, /* Token for <value>, or NULL */
414 int minusFlag
/* True if a '-' sign preceded <value> */
416 char *zLeft
= 0; /* Nul-terminated UTF-8 string <id> */
417 char *zRight
= 0; /* Nul-terminated UTF-8 string <value>, or NULL */
418 const char *zDb
= 0; /* The database name */
419 Token
*pId
; /* Pointer to <id> token */
420 char *aFcntl
[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
421 int iDb
; /* Database index for <database> */
422 int rc
; /* return value form SQLITE_FCNTL_PRAGMA */
423 sqlite3
*db
= pParse
->db
; /* The database connection */
424 Db
*pDb
; /* The specific database being pragmaed */
425 Vdbe
*v
= sqlite3GetVdbe(pParse
); /* Prepared statement */
426 const PragmaName
*pPragma
; /* The pragma */
427 /* BEGIN SQLCIPHER */
428 #ifdef SQLITE_HAS_CODEC
429 extern int sqlcipher_codec_pragma(sqlite3
*, int, Parse
*, const char *, const char *);
434 sqlite3VdbeRunOnlyOnce(v
);
437 /* Interpret the [schema.] part of the pragma statement. iDb is the
438 ** index of the database this pragma is being applied to in db.aDb[]. */
439 iDb
= sqlite3TwoPartName(pParse
, pId1
, pId2
, &pId
);
443 /* If the temp database has been explicitly named as part of the
444 ** pragma, make sure it is open.
446 if( iDb
==1 && sqlite3OpenTempDatabase(pParse
) ){
450 zLeft
= sqlite3NameFromToken(db
, pId
);
453 zRight
= sqlite3MPrintf(db
, "-%T", pValue
);
455 zRight
= sqlite3NameFromToken(db
, pValue
);
459 zDb
= pId2
->n
>0 ? pDb
->zDbSName
: 0;
460 if( sqlite3AuthCheck(pParse
, SQLITE_PRAGMA
, zLeft
, zRight
, zDb
) ){
464 /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
465 ** connection. If it returns SQLITE_OK, then assume that the VFS
466 ** handled the pragma and generate a no-op prepared statement.
468 ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
469 ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
470 ** object corresponding to the database file to which the pragma
473 ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
474 ** file control is an array of pointers to strings (char**) in which the
475 ** second element of the array is the name of the pragma and the third
476 ** element is the argument to the pragma or NULL if the pragma has no
483 db
->busyHandler
.nBusy
= 0;
484 rc
= sqlite3_file_control(db
, zDb
, SQLITE_FCNTL_PRAGMA
, (void*)aFcntl
);
486 sqlite3VdbeSetNumCols(v
, 1);
487 sqlite3VdbeSetColName(v
, 0, COLNAME_NAME
, aFcntl
[0], SQLITE_TRANSIENT
);
488 returnSingleText(v
, aFcntl
[0]);
489 sqlite3_free(aFcntl
[0]);
492 if( rc
!=SQLITE_NOTFOUND
){
494 sqlite3ErrorMsg(pParse
, "%s", aFcntl
[0]);
495 sqlite3_free(aFcntl
[0]);
503 /* BEGIN SQLCIPHER */
504 #ifdef SQLITE_HAS_CODEC
505 if(sqlcipher_codec_pragma(db
, iDb
, pParse
, zLeft
, zRight
)) {
506 /* sqlcipher_codec_pragma executes internal */
512 /* Locate the pragma in the lookup table */
513 pPragma
= pragmaLocate(zLeft
);
515 /* IMP: R-43042-22504 No error messages are generated if an
516 ** unknown pragma is issued. */
520 /* Make sure the database schema is loaded if the pragma requires that */
521 if( (pPragma
->mPragFlg
& PragFlg_NeedSchema
)!=0 ){
522 if( sqlite3ReadSchema(pParse
) ) goto pragma_out
;
525 /* Register the result column names for pragmas that return results */
526 if( (pPragma
->mPragFlg
& PragFlg_NoColumns
)==0
527 && ((pPragma
->mPragFlg
& PragFlg_NoColumns1
)==0 || zRight
==0)
529 setPragmaResultColumnNames(v
, pPragma
);
532 /* Jump to the appropriate pragma handler */
533 switch( pPragma
->ePragTyp
){
535 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
537 ** PRAGMA [schema.]default_cache_size
538 ** PRAGMA [schema.]default_cache_size=N
540 ** The first form reports the current persistent setting for the
541 ** page cache size. The value returned is the maximum number of
542 ** pages in the page cache. The second form sets both the current
543 ** page cache size value and the persistent page cache size value
544 ** stored in the database file.
546 ** Older versions of SQLite would set the default cache size to a
547 ** negative number to indicate synchronous=OFF. These days, synchronous
548 ** is always on by default regardless of the sign of the default cache
549 ** size. But continue to take the absolute value of the default cache
550 ** size of historical compatibility.
552 case PragTyp_DEFAULT_CACHE_SIZE
: {
553 static const int iLn
= VDBE_OFFSET_LINENO(2);
554 static const VdbeOpList getCacheSize
[] = {
555 { OP_Transaction
, 0, 0, 0}, /* 0 */
556 { OP_ReadCookie
, 0, 1, BTREE_DEFAULT_CACHE_SIZE
}, /* 1 */
557 { OP_IfPos
, 1, 8, 0},
558 { OP_Integer
, 0, 2, 0},
559 { OP_Subtract
, 1, 2, 1},
560 { OP_IfPos
, 1, 8, 0},
561 { OP_Integer
, 0, 1, 0}, /* 6 */
563 { OP_ResultRow
, 1, 1, 0},
566 sqlite3VdbeUsesBtree(v
, iDb
);
569 sqlite3VdbeVerifyNoMallocRequired(v
, ArraySize(getCacheSize
));
570 aOp
= sqlite3VdbeAddOpList(v
, ArraySize(getCacheSize
), getCacheSize
, iLn
);
571 if( ONLY_IF_REALLOC_STRESS(aOp
==0) ) break;
574 aOp
[6].p1
= SQLITE_DEFAULT_CACHE_SIZE
;
576 int size
= sqlite3AbsInt32(sqlite3Atoi(zRight
));
577 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
578 sqlite3VdbeAddOp3(v
, OP_SetCookie
, iDb
, BTREE_DEFAULT_CACHE_SIZE
, size
);
579 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
580 pDb
->pSchema
->cache_size
= size
;
581 sqlite3BtreeSetCacheSize(pDb
->pBt
, pDb
->pSchema
->cache_size
);
585 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
587 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
589 ** PRAGMA [schema.]page_size
590 ** PRAGMA [schema.]page_size=N
592 ** The first form reports the current setting for the
593 ** database page size in bytes. The second form sets the
594 ** database page size value. The value can only be set if
595 ** the database has not yet been created.
597 case PragTyp_PAGE_SIZE
: {
598 Btree
*pBt
= pDb
->pBt
;
601 int size
= ALWAYS(pBt
) ? sqlite3BtreeGetPageSize(pBt
) : 0;
602 returnSingleInt(v
, size
);
604 /* Malloc may fail when setting the page-size, as there is an internal
605 ** buffer that the pager module resizes using sqlite3_realloc().
607 db
->nextPagesize
= sqlite3Atoi(zRight
);
608 if( SQLITE_NOMEM
==sqlite3BtreeSetPageSize(pBt
, db
->nextPagesize
,0,0) ){
616 ** PRAGMA [schema.]secure_delete
617 ** PRAGMA [schema.]secure_delete=ON/OFF/FAST
619 ** The first form reports the current setting for the
620 ** secure_delete flag. The second form changes the secure_delete
621 ** flag setting and reports the new value.
623 case PragTyp_SECURE_DELETE
: {
624 Btree
*pBt
= pDb
->pBt
;
628 if( sqlite3_stricmp(zRight
, "fast")==0 ){
631 b
= sqlite3GetBoolean(zRight
, 0);
634 if( pId2
->n
==0 && b
>=0 ){
636 for(ii
=0; ii
<db
->nDb
; ii
++){
637 sqlite3BtreeSecureDelete(db
->aDb
[ii
].pBt
, b
);
640 b
= sqlite3BtreeSecureDelete(pBt
, b
);
641 returnSingleInt(v
, b
);
646 ** PRAGMA [schema.]max_page_count
647 ** PRAGMA [schema.]max_page_count=N
649 ** The first form reports the current setting for the
650 ** maximum number of pages in the database file. The
651 ** second form attempts to change this setting. Both
652 ** forms return the current setting.
654 ** The absolute value of N is used. This is undocumented and might
655 ** change. The only purpose is to provide an easy way to test
656 ** the sqlite3AbsInt32() function.
658 ** PRAGMA [schema.]page_count
660 ** Return the number of pages in the specified database.
662 case PragTyp_PAGE_COUNT
: {
665 sqlite3CodeVerifySchema(pParse
, iDb
);
666 iReg
= ++pParse
->nMem
;
667 if( sqlite3Tolower(zLeft
[0])=='p' ){
668 sqlite3VdbeAddOp2(v
, OP_Pagecount
, iDb
, iReg
);
670 if( zRight
&& sqlite3DecOrHexToI64(zRight
,&x
)==0 ){
672 else if( x
>0xfffffffe ) x
= 0xfffffffe;
676 sqlite3VdbeAddOp3(v
, OP_MaxPgcnt
, iDb
, iReg
, (int)x
);
678 sqlite3VdbeAddOp2(v
, OP_ResultRow
, iReg
, 1);
683 ** PRAGMA [schema.]locking_mode
684 ** PRAGMA [schema.]locking_mode = (normal|exclusive)
686 case PragTyp_LOCKING_MODE
: {
687 const char *zRet
= "normal";
688 int eMode
= getLockingMode(zRight
);
690 if( pId2
->n
==0 && eMode
==PAGER_LOCKINGMODE_QUERY
){
691 /* Simple "PRAGMA locking_mode;" statement. This is a query for
692 ** the current default locking mode (which may be different to
693 ** the locking-mode of the main database).
695 eMode
= db
->dfltLockMode
;
699 /* This indicates that no database name was specified as part
700 ** of the PRAGMA command. In this case the locking-mode must be
701 ** set on all attached databases, as well as the main db file.
703 ** Also, the sqlite3.dfltLockMode variable is set so that
704 ** any subsequently attached databases also use the specified
708 assert(pDb
==&db
->aDb
[0]);
709 for(ii
=2; ii
<db
->nDb
; ii
++){
710 pPager
= sqlite3BtreePager(db
->aDb
[ii
].pBt
);
711 sqlite3PagerLockingMode(pPager
, eMode
);
713 db
->dfltLockMode
= (u8
)eMode
;
715 pPager
= sqlite3BtreePager(pDb
->pBt
);
716 eMode
= sqlite3PagerLockingMode(pPager
, eMode
);
719 assert( eMode
==PAGER_LOCKINGMODE_NORMAL
720 || eMode
==PAGER_LOCKINGMODE_EXCLUSIVE
);
721 if( eMode
==PAGER_LOCKINGMODE_EXCLUSIVE
){
724 returnSingleText(v
, zRet
);
729 ** PRAGMA [schema.]journal_mode
730 ** PRAGMA [schema.]journal_mode =
731 ** (delete|persist|off|truncate|memory|wal|off)
733 case PragTyp_JOURNAL_MODE
: {
734 int eMode
; /* One of the PAGER_JOURNALMODE_XXX symbols */
735 int ii
; /* Loop counter */
738 /* If there is no "=MODE" part of the pragma, do a query for the
740 eMode
= PAGER_JOURNALMODE_QUERY
;
743 int n
= sqlite3Strlen30(zRight
);
744 for(eMode
=0; (zMode
= sqlite3JournalModename(eMode
))!=0; eMode
++){
745 if( sqlite3StrNICmp(zRight
, zMode
, n
)==0 ) break;
748 /* If the "=MODE" part does not match any known journal mode,
749 ** then do a query */
750 eMode
= PAGER_JOURNALMODE_QUERY
;
752 if( eMode
==PAGER_JOURNALMODE_OFF
&& (db
->flags
& SQLITE_Defensive
)!=0 ){
753 /* Do not allow journal-mode "OFF" in defensive since the database
754 ** can become corrupted using ordinary SQL when the journal is off */
755 eMode
= PAGER_JOURNALMODE_QUERY
;
758 if( eMode
==PAGER_JOURNALMODE_QUERY
&& pId2
->n
==0 ){
759 /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
763 for(ii
=db
->nDb
-1; ii
>=0; ii
--){
764 if( db
->aDb
[ii
].pBt
&& (ii
==iDb
|| pId2
->n
==0) ){
765 sqlite3VdbeUsesBtree(v
, ii
);
766 sqlite3VdbeAddOp3(v
, OP_JournalMode
, ii
, 1, eMode
);
769 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, 1);
774 ** PRAGMA [schema.]journal_size_limit
775 ** PRAGMA [schema.]journal_size_limit=N
777 ** Get or set the size limit on rollback journal files.
779 case PragTyp_JOURNAL_SIZE_LIMIT
: {
780 Pager
*pPager
= sqlite3BtreePager(pDb
->pBt
);
783 sqlite3DecOrHexToI64(zRight
, &iLimit
);
784 if( iLimit
<-1 ) iLimit
= -1;
786 iLimit
= sqlite3PagerJournalSizeLimit(pPager
, iLimit
);
787 returnSingleInt(v
, iLimit
);
791 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
794 ** PRAGMA [schema.]auto_vacuum
795 ** PRAGMA [schema.]auto_vacuum=N
797 ** Get or set the value of the database 'auto-vacuum' parameter.
798 ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
800 #ifndef SQLITE_OMIT_AUTOVACUUM
801 case PragTyp_AUTO_VACUUM
: {
802 Btree
*pBt
= pDb
->pBt
;
805 returnSingleInt(v
, sqlite3BtreeGetAutoVacuum(pBt
));
807 int eAuto
= getAutoVacuum(zRight
);
808 assert( eAuto
>=0 && eAuto
<=2 );
809 db
->nextAutovac
= (u8
)eAuto
;
810 /* Call SetAutoVacuum() to set initialize the internal auto and
811 ** incr-vacuum flags. This is required in case this connection
812 ** creates the database file. It is important that it is created
813 ** as an auto-vacuum capable db.
815 rc
= sqlite3BtreeSetAutoVacuum(pBt
, eAuto
);
816 if( rc
==SQLITE_OK
&& (eAuto
==1 || eAuto
==2) ){
817 /* When setting the auto_vacuum mode to either "full" or
818 ** "incremental", write the value of meta[6] in the database
819 ** file. Before writing to meta[6], check that meta[3] indicates
820 ** that this really is an auto-vacuum capable database.
822 static const int iLn
= VDBE_OFFSET_LINENO(2);
823 static const VdbeOpList setMeta6
[] = {
824 { OP_Transaction
, 0, 1, 0}, /* 0 */
825 { OP_ReadCookie
, 0, 1, BTREE_LARGEST_ROOT_PAGE
},
826 { OP_If
, 1, 0, 0}, /* 2 */
827 { OP_Halt
, SQLITE_OK
, OE_Abort
, 0}, /* 3 */
828 { OP_SetCookie
, 0, BTREE_INCR_VACUUM
, 0}, /* 4 */
831 int iAddr
= sqlite3VdbeCurrentAddr(v
);
832 sqlite3VdbeVerifyNoMallocRequired(v
, ArraySize(setMeta6
));
833 aOp
= sqlite3VdbeAddOpList(v
, ArraySize(setMeta6
), setMeta6
, iLn
);
834 if( ONLY_IF_REALLOC_STRESS(aOp
==0) ) break;
839 aOp
[4].p3
= eAuto
- 1;
840 sqlite3VdbeUsesBtree(v
, iDb
);
848 ** PRAGMA [schema.]incremental_vacuum(N)
850 ** Do N steps of incremental vacuuming on a database.
852 #ifndef SQLITE_OMIT_AUTOVACUUM
853 case PragTyp_INCREMENTAL_VACUUM
: {
854 int iLimit
= 0, addr
;
855 if( zRight
==0 || !sqlite3GetInt32(zRight
, &iLimit
) || iLimit
<=0 ){
858 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
859 sqlite3VdbeAddOp2(v
, OP_Integer
, iLimit
, 1);
860 addr
= sqlite3VdbeAddOp1(v
, OP_IncrVacuum
, iDb
); VdbeCoverage(v
);
861 sqlite3VdbeAddOp1(v
, OP_ResultRow
, 1);
862 sqlite3VdbeAddOp2(v
, OP_AddImm
, 1, -1);
863 sqlite3VdbeAddOp2(v
, OP_IfPos
, 1, addr
); VdbeCoverage(v
);
864 sqlite3VdbeJumpHere(v
, addr
);
869 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
871 ** PRAGMA [schema.]cache_size
872 ** PRAGMA [schema.]cache_size=N
874 ** The first form reports the current local setting for the
875 ** page cache size. The second form sets the local
876 ** page cache size value. If N is positive then that is the
877 ** number of pages in the cache. If N is negative, then the
878 ** number of pages is adjusted so that the cache uses -N kibibytes
881 case PragTyp_CACHE_SIZE
: {
882 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
884 returnSingleInt(v
, pDb
->pSchema
->cache_size
);
886 int size
= sqlite3Atoi(zRight
);
887 pDb
->pSchema
->cache_size
= size
;
888 sqlite3BtreeSetCacheSize(pDb
->pBt
, pDb
->pSchema
->cache_size
);
894 ** PRAGMA [schema.]cache_spill
895 ** PRAGMA cache_spill=BOOLEAN
896 ** PRAGMA [schema.]cache_spill=N
898 ** The first form reports the current local setting for the
899 ** page cache spill size. The second form turns cache spill on
900 ** or off. When turning cache spill on, the size is set to the
901 ** current cache_size. The third form sets a spill size that
902 ** may be different form the cache size.
903 ** If N is positive then that is the
904 ** number of pages in the cache. If N is negative, then the
905 ** number of pages is adjusted so that the cache uses -N kibibytes
908 ** If the number of cache_spill pages is less then the number of
909 ** cache_size pages, no spilling occurs until the page count exceeds
910 ** the number of cache_size pages.
912 ** The cache_spill=BOOLEAN setting applies to all attached schemas,
913 ** not just the schema specified.
915 case PragTyp_CACHE_SPILL
: {
916 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
919 (db
->flags
& SQLITE_CacheSpill
)==0 ? 0 :
920 sqlite3BtreeSetSpillSize(pDb
->pBt
,0));
923 if( sqlite3GetInt32(zRight
, &size
) ){
924 sqlite3BtreeSetSpillSize(pDb
->pBt
, size
);
926 if( sqlite3GetBoolean(zRight
, size
!=0) ){
927 db
->flags
|= SQLITE_CacheSpill
;
929 db
->flags
&= ~(u64
)SQLITE_CacheSpill
;
931 setAllPagerFlags(db
);
937 ** PRAGMA [schema.]mmap_size(N)
939 ** Used to set mapping size limit. The mapping size limit is
940 ** used to limit the aggregate size of all memory mapped regions of the
941 ** database file. If this parameter is set to zero, then memory mapping
942 ** is not used at all. If N is negative, then the default memory map
943 ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
944 ** The parameter N is measured in bytes.
946 ** This value is advisory. The underlying VFS is free to memory map
947 ** as little or as much as it wants. Except, if N is set to 0 then the
948 ** upper layers will never invoke the xFetch interfaces to the VFS.
950 case PragTyp_MMAP_SIZE
: {
952 #if SQLITE_MAX_MMAP_SIZE>0
953 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
956 sqlite3DecOrHexToI64(zRight
, &sz
);
957 if( sz
<0 ) sz
= sqlite3GlobalConfig
.szMmap
;
958 if( pId2
->n
==0 ) db
->szMmap
= sz
;
959 for(ii
=db
->nDb
-1; ii
>=0; ii
--){
960 if( db
->aDb
[ii
].pBt
&& (ii
==iDb
|| pId2
->n
==0) ){
961 sqlite3BtreeSetMmapLimit(db
->aDb
[ii
].pBt
, sz
);
966 rc
= sqlite3_file_control(db
, zDb
, SQLITE_FCNTL_MMAP_SIZE
, &sz
);
972 returnSingleInt(v
, sz
);
973 }else if( rc
!=SQLITE_NOTFOUND
){
982 ** PRAGMA temp_store = "default"|"memory"|"file"
984 ** Return or set the local value of the temp_store flag. Changing
985 ** the local value does not make changes to the disk file and the default
986 ** value will be restored the next time the database is opened.
988 ** Note that it is possible for the library compile-time options to
989 ** override this setting
991 case PragTyp_TEMP_STORE
: {
993 returnSingleInt(v
, db
->temp_store
);
995 changeTempStorage(pParse
, zRight
);
1001 ** PRAGMA temp_store_directory
1002 ** PRAGMA temp_store_directory = ""|"directory_name"
1004 ** Return or set the local value of the temp_store_directory flag. Changing
1005 ** the value sets a specific directory to be used for temporary files.
1006 ** Setting to a null string reverts to the default temporary directory search.
1007 ** If temporary directory is changed, then invalidateTempStorage.
1010 case PragTyp_TEMP_STORE_DIRECTORY
: {
1011 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR
));
1013 returnSingleText(v
, sqlite3_temp_directory
);
1015 #ifndef SQLITE_OMIT_WSD
1018 rc
= sqlite3OsAccess(db
->pVfs
, zRight
, SQLITE_ACCESS_READWRITE
, &res
);
1019 if( rc
!=SQLITE_OK
|| res
==0 ){
1020 sqlite3ErrorMsg(pParse
, "not a writable directory");
1021 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR
));
1025 if( SQLITE_TEMP_STORE
==0
1026 || (SQLITE_TEMP_STORE
==1 && db
->temp_store
<=1)
1027 || (SQLITE_TEMP_STORE
==2 && db
->temp_store
==1)
1029 invalidateTempStorage(pParse
);
1031 sqlite3_free(sqlite3_temp_directory
);
1033 sqlite3_temp_directory
= sqlite3_mprintf("%s", zRight
);
1035 sqlite3_temp_directory
= 0;
1037 #endif /* SQLITE_OMIT_WSD */
1039 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR
));
1045 ** PRAGMA data_store_directory
1046 ** PRAGMA data_store_directory = ""|"directory_name"
1048 ** Return or set the local value of the data_store_directory flag. Changing
1049 ** the value sets a specific directory to be used for database files that
1050 ** were specified with a relative pathname. Setting to a null string reverts
1051 ** to the default database directory, which for database files specified with
1052 ** a relative path will probably be based on the current directory for the
1053 ** process. Database file specified with an absolute path are not impacted
1054 ** by this setting, regardless of its value.
1057 case PragTyp_DATA_STORE_DIRECTORY
: {
1058 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR
));
1060 returnSingleText(v
, sqlite3_data_directory
);
1062 #ifndef SQLITE_OMIT_WSD
1065 rc
= sqlite3OsAccess(db
->pVfs
, zRight
, SQLITE_ACCESS_READWRITE
, &res
);
1066 if( rc
!=SQLITE_OK
|| res
==0 ){
1067 sqlite3ErrorMsg(pParse
, "not a writable directory");
1068 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR
));
1072 sqlite3_free(sqlite3_data_directory
);
1074 sqlite3_data_directory
= sqlite3_mprintf("%s", zRight
);
1076 sqlite3_data_directory
= 0;
1078 #endif /* SQLITE_OMIT_WSD */
1080 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR
));
1085 #if SQLITE_ENABLE_LOCKING_STYLE
1087 ** PRAGMA [schema.]lock_proxy_file
1088 ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
1090 ** Return or set the value of the lock_proxy_file flag. Changing
1091 ** the value sets a specific file to be used for database access locks.
1094 case PragTyp_LOCK_PROXY_FILE
: {
1096 Pager
*pPager
= sqlite3BtreePager(pDb
->pBt
);
1097 char *proxy_file_path
= NULL
;
1098 sqlite3_file
*pFile
= sqlite3PagerFile(pPager
);
1099 sqlite3OsFileControlHint(pFile
, SQLITE_GET_LOCKPROXYFILE
,
1101 returnSingleText(v
, proxy_file_path
);
1103 Pager
*pPager
= sqlite3BtreePager(pDb
->pBt
);
1104 sqlite3_file
*pFile
= sqlite3PagerFile(pPager
);
1107 res
=sqlite3OsFileControl(pFile
, SQLITE_SET_LOCKPROXYFILE
,
1110 res
=sqlite3OsFileControl(pFile
, SQLITE_SET_LOCKPROXYFILE
,
1113 if( res
!=SQLITE_OK
){
1114 sqlite3ErrorMsg(pParse
, "failed to set lock proxy file");
1120 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
1123 ** PRAGMA [schema.]synchronous
1124 ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
1126 ** Return or set the local value of the synchronous flag. Changing
1127 ** the local value does not make changes to the disk file and the
1128 ** default value will be restored the next time the database is
1131 case PragTyp_SYNCHRONOUS
: {
1133 returnSingleInt(v
, pDb
->safety_level
-1);
1135 if( !db
->autoCommit
){
1136 sqlite3ErrorMsg(pParse
,
1137 "Safety level may not be changed inside a transaction");
1139 int iLevel
= (getSafetyLevel(zRight
,0,1)+1) & PAGER_SYNCHRONOUS_MASK
;
1140 if( iLevel
==0 ) iLevel
= 1;
1141 pDb
->safety_level
= iLevel
;
1143 setAllPagerFlags(db
);
1148 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
1150 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
1151 case PragTyp_FLAG
: {
1153 setPragmaResultColumnNames(v
, pPragma
);
1154 returnSingleInt(v
, (db
->flags
& pPragma
->iArg
)!=0 );
1156 u64 mask
= pPragma
->iArg
; /* Mask of bits to set or clear. */
1157 if( db
->autoCommit
==0 ){
1158 /* Foreign key support may not be enabled or disabled while not
1159 ** in auto-commit mode. */
1160 mask
&= ~(SQLITE_ForeignKeys
);
1162 #if SQLITE_USER_AUTHENTICATION
1163 if( db
->auth
.authLevel
==UAUTH_User
){
1164 /* Do not allow non-admin users to modify the schema arbitrarily */
1165 mask
&= ~(SQLITE_WriteSchema
);
1169 if( sqlite3GetBoolean(zRight
, 0) ){
1170 if( (mask
& SQLITE_WriteSchema
)==0
1171 || (db
->flags
& SQLITE_Defensive
)==0
1177 if( mask
==SQLITE_DeferFKs
) db
->nDeferredImmCons
= 0;
1178 if( (mask
& SQLITE_WriteSchema
)!=0
1179 && sqlite3_stricmp(zRight
, "reset")==0
1181 /* IMP: R-60817-01178 If the argument is "RESET" then schema
1182 ** writing is disabled (as with "PRAGMA writable_schema=OFF") and,
1183 ** in addition, the schema is reloaded. */
1184 sqlite3ResetAllSchemasOfConnection(db
);
1188 /* Many of the flag-pragmas modify the code generated by the SQL
1189 ** compiler (eg. count_changes). So add an opcode to expire all
1190 ** compiled SQL statements after modifying a pragma value.
1192 sqlite3VdbeAddOp0(v
, OP_Expire
);
1193 setAllPagerFlags(db
);
1197 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
1199 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
1201 ** PRAGMA table_info(<table>)
1203 ** Return a single row for each column of the named table. The columns of
1204 ** the returned data set are:
1206 ** cid: Column id (numbered from left to right, starting at 0)
1207 ** name: Column name
1208 ** type: Column declaration type.
1209 ** notnull: True if 'NOT NULL' is part of column declaration
1210 ** dflt_value: The default value for the column, if any.
1211 ** pk: Non-zero for PK fields.
1213 case PragTyp_TABLE_INFO
: if( zRight
){
1215 sqlite3CodeVerifyNamedSchema(pParse
, zDb
);
1216 pTab
= sqlite3LocateTable(pParse
, LOCATE_NOERR
, zRight
, zDb
);
1221 Index
*pPk
= sqlite3PrimaryKeyIndex(pTab
);
1223 sqlite3ViewGetColumnNames(pParse
, pTab
);
1224 for(i
=0, pCol
=pTab
->aCol
; i
<pTab
->nCol
; i
++, pCol
++){
1226 const Expr
*pColExpr
;
1227 if( pCol
->colFlags
& COLFLAG_NOINSERT
){
1228 if( pPragma
->iArg
==0 ){
1232 if( pCol
->colFlags
& COLFLAG_VIRTUAL
){
1233 isHidden
= 2; /* GENERATED ALWAYS AS ... VIRTUAL */
1234 }else if( pCol
->colFlags
& COLFLAG_STORED
){
1235 isHidden
= 3; /* GENERATED ALWAYS AS ... STORED */
1236 }else{ assert( pCol
->colFlags
& COLFLAG_HIDDEN
);
1237 isHidden
= 1; /* HIDDEN */
1240 if( (pCol
->colFlags
& COLFLAG_PRIMKEY
)==0 ){
1245 for(k
=1; k
<=pTab
->nCol
&& pPk
->aiColumn
[k
-1]!=i
; k
++){}
1247 pColExpr
= sqlite3ColumnExpr(pTab
,pCol
);
1248 assert( pColExpr
==0 || pColExpr
->op
==TK_SPAN
|| isHidden
>=2 );
1249 assert( pColExpr
==0 || !ExprHasProperty(pColExpr
, EP_IntValue
)
1251 sqlite3VdbeMultiLoad(v
, 1, pPragma
->iArg
? "issisii" : "issisi",
1254 sqlite3ColumnType(pCol
,""),
1255 pCol
->notNull
? 1 : 0,
1256 (isHidden
>=2 || pColExpr
==0) ? 0 : pColExpr
->u
.zToken
,
1265 ** PRAGMA table_list
1267 ** Return a single row for each table, virtual table, or view in the
1270 ** schema: Name of attached database hold this table
1271 ** name: Name of the table itself
1272 ** type: "table", "view", "virtual", "shadow"
1273 ** ncol: Number of columns
1274 ** wr: True for a WITHOUT ROWID table
1275 ** strict: True for a STRICT table
1277 case PragTyp_TABLE_LIST
: {
1280 sqlite3CodeVerifyNamedSchema(pParse
, zDb
);
1281 for(ii
=0; ii
<db
->nDb
; ii
++){
1285 if( zDb
&& sqlite3_stricmp(zDb
, db
->aDb
[ii
].zDbSName
)!=0 ) continue;
1287 /* Ensure that the Table.nCol field is initialized for all views
1288 ** and virtual tables. Each time we initialize a Table.nCol value
1289 ** for a table, that can potentially disrupt the hash table, so restart
1290 ** the initialization scan.
1292 pHash
= &db
->aDb
[ii
].pSchema
->tblHash
;
1293 initNCol
= sqliteHashCount(pHash
);
1294 while( initNCol
-- ){
1295 for(k
=sqliteHashFirst(pHash
); 1; k
=sqliteHashNext(k
) ){
1297 if( k
==0 ){ initNCol
= 0; break; }
1298 pTab
= sqliteHashData(k
);
1299 if( pTab
->nCol
==0 ){
1300 char *zSql
= sqlite3MPrintf(db
, "SELECT*FROM\"%w\"", pTab
->zName
);
1302 sqlite3_stmt
*pDummy
= 0;
1303 (void)sqlite3_prepare(db
, zSql
, -1, &pDummy
, 0);
1304 (void)sqlite3_finalize(pDummy
);
1305 sqlite3DbFree(db
, zSql
);
1307 if( db
->mallocFailed
){
1308 sqlite3ErrorMsg(db
->pParse
, "out of memory");
1309 db
->pParse
->rc
= SQLITE_NOMEM_BKPT
;
1311 pHash
= &db
->aDb
[ii
].pSchema
->tblHash
;
1317 for(k
=sqliteHashFirst(pHash
); k
; k
=sqliteHashNext(k
) ){
1318 Table
*pTab
= sqliteHashData(k
);
1320 if( zRight
&& sqlite3_stricmp(zRight
, pTab
->zName
)!=0 ) continue;
1323 }else if( IsVirtual(pTab
) ){
1325 }else if( pTab
->tabFlags
& TF_Shadow
){
1330 sqlite3VdbeMultiLoad(v
, 1, "sssiii",
1331 db
->aDb
[ii
].zDbSName
,
1332 sqlite3PreferredTableName(pTab
->zName
),
1335 (pTab
->tabFlags
& TF_WithoutRowid
)!=0,
1336 (pTab
->tabFlags
& TF_Strict
)!=0
1344 case PragTyp_STATS
: {
1348 sqlite3CodeVerifySchema(pParse
, iDb
);
1349 for(i
=sqliteHashFirst(&pDb
->pSchema
->tblHash
); i
; i
=sqliteHashNext(i
)){
1350 Table
*pTab
= sqliteHashData(i
);
1351 sqlite3VdbeMultiLoad(v
, 1, "ssiii",
1352 sqlite3PreferredTableName(pTab
->zName
),
1357 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1358 sqlite3VdbeMultiLoad(v
, 2, "siiiX",
1361 pIdx
->aiRowLogEst
[0],
1363 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, 5);
1370 case PragTyp_INDEX_INFO
: if( zRight
){
1373 pIdx
= sqlite3FindIndex(db
, zRight
, zDb
);
1375 /* If there is no index named zRight, check to see if there is a
1376 ** WITHOUT ROWID table named zRight, and if there is, show the
1377 ** structure of the PRIMARY KEY index for that table. */
1378 pTab
= sqlite3LocateTable(pParse
, LOCATE_NOERR
, zRight
, zDb
);
1379 if( pTab
&& !HasRowid(pTab
) ){
1380 pIdx
= sqlite3PrimaryKeyIndex(pTab
);
1384 int iIdxDb
= sqlite3SchemaToIndex(db
, pIdx
->pSchema
);
1387 if( pPragma
->iArg
){
1388 /* PRAGMA index_xinfo (newer version with more rows and columns) */
1392 /* PRAGMA index_info (legacy version) */
1396 pTab
= pIdx
->pTable
;
1397 sqlite3CodeVerifySchema(pParse
, iIdxDb
);
1398 assert( pParse
->nMem
<=pPragma
->nPragCName
);
1399 for(i
=0; i
<mx
; i
++){
1400 i16 cnum
= pIdx
->aiColumn
[i
];
1401 sqlite3VdbeMultiLoad(v
, 1, "iisX", i
, cnum
,
1402 cnum
<0 ? 0 : pTab
->aCol
[cnum
].zCnName
);
1403 if( pPragma
->iArg
){
1404 sqlite3VdbeMultiLoad(v
, 4, "isiX",
1405 pIdx
->aSortOrder
[i
],
1409 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, pParse
->nMem
);
1415 case PragTyp_INDEX_LIST
: if( zRight
){
1419 pTab
= sqlite3FindTable(db
, zRight
, zDb
);
1421 int iTabDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
1423 sqlite3CodeVerifySchema(pParse
, iTabDb
);
1424 for(pIdx
=pTab
->pIndex
, i
=0; pIdx
; pIdx
=pIdx
->pNext
, i
++){
1425 const char *azOrigin
[] = { "c", "u", "pk" };
1426 sqlite3VdbeMultiLoad(v
, 1, "isisi",
1429 IsUniqueIndex(pIdx
),
1430 azOrigin
[pIdx
->idxType
],
1431 pIdx
->pPartIdxWhere
!=0);
1437 case PragTyp_DATABASE_LIST
: {
1440 for(i
=0; i
<db
->nDb
; i
++){
1441 if( db
->aDb
[i
].pBt
==0 ) continue;
1442 assert( db
->aDb
[i
].zDbSName
!=0 );
1443 sqlite3VdbeMultiLoad(v
, 1, "iss",
1445 db
->aDb
[i
].zDbSName
,
1446 sqlite3BtreeGetFilename(db
->aDb
[i
].pBt
));
1451 case PragTyp_COLLATION_LIST
: {
1455 for(p
=sqliteHashFirst(&db
->aCollSeq
); p
; p
=sqliteHashNext(p
)){
1456 CollSeq
*pColl
= (CollSeq
*)sqliteHashData(p
);
1457 sqlite3VdbeMultiLoad(v
, 1, "is", i
++, pColl
->zName
);
1462 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
1463 case PragTyp_FUNCTION_LIST
: {
1467 int showInternFunc
= (db
->mDbFlags
& DBFLAG_InternalFunc
)!=0;
1469 for(i
=0; i
<SQLITE_FUNC_HASH_SZ
; i
++){
1470 for(p
=sqlite3BuiltinFunctions
.a
[i
]; p
; p
=p
->u
.pHash
){
1471 assert( p
->funcFlags
& SQLITE_FUNC_BUILTIN
);
1472 pragmaFunclistLine(v
, p
, 1, showInternFunc
);
1475 for(j
=sqliteHashFirst(&db
->aFunc
); j
; j
=sqliteHashNext(j
)){
1476 p
= (FuncDef
*)sqliteHashData(j
);
1477 assert( (p
->funcFlags
& SQLITE_FUNC_BUILTIN
)==0 );
1478 pragmaFunclistLine(v
, p
, 0, showInternFunc
);
1483 #ifndef SQLITE_OMIT_VIRTUALTABLE
1484 case PragTyp_MODULE_LIST
: {
1487 for(j
=sqliteHashFirst(&db
->aModule
); j
; j
=sqliteHashNext(j
)){
1488 Module
*pMod
= (Module
*)sqliteHashData(j
);
1489 sqlite3VdbeMultiLoad(v
, 1, "s", pMod
->zName
);
1493 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1495 case PragTyp_PRAGMA_LIST
: {
1497 for(i
=0; i
<ArraySize(aPragmaName
); i
++){
1498 sqlite3VdbeMultiLoad(v
, 1, "s", aPragmaName
[i
].zName
);
1502 #endif /* SQLITE_INTROSPECTION_PRAGMAS */
1504 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
1506 #ifndef SQLITE_OMIT_FOREIGN_KEY
1507 case PragTyp_FOREIGN_KEY_LIST
: if( zRight
){
1510 pTab
= sqlite3FindTable(db
, zRight
, zDb
);
1511 if( pTab
&& IsOrdinaryTable(pTab
) ){
1512 pFK
= pTab
->u
.tab
.pFKey
;
1514 int iTabDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
1517 sqlite3CodeVerifySchema(pParse
, iTabDb
);
1520 for(j
=0; j
<pFK
->nCol
; j
++){
1521 sqlite3VdbeMultiLoad(v
, 1, "iissssss",
1525 pTab
->aCol
[pFK
->aCol
[j
].iFrom
].zCnName
,
1527 actionName(pFK
->aAction
[1]), /* ON UPDATE */
1528 actionName(pFK
->aAction
[0]), /* ON DELETE */
1532 pFK
= pFK
->pNextFrom
;
1538 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1540 #ifndef SQLITE_OMIT_FOREIGN_KEY
1541 #ifndef SQLITE_OMIT_TRIGGER
1542 case PragTyp_FOREIGN_KEY_CHECK
: {
1543 FKey
*pFK
; /* A foreign key constraint */
1544 Table
*pTab
; /* Child table contain "REFERENCES" keyword */
1545 Table
*pParent
; /* Parent table that child points to */
1546 Index
*pIdx
; /* Index in the parent table */
1547 int i
; /* Loop counter: Foreign key number for pTab */
1548 int j
; /* Loop counter: Field of the foreign key */
1549 HashElem
*k
; /* Loop counter: Next table in schema */
1550 int x
; /* result variable */
1551 int regResult
; /* 3 registers to hold a result row */
1552 int regRow
; /* Registers to hold a row from pTab */
1553 int addrTop
; /* Top of a loop checking foreign keys */
1554 int addrOk
; /* Jump here if the key is OK */
1555 int *aiCols
; /* child to parent column mapping */
1557 regResult
= pParse
->nMem
+1;
1559 regRow
= ++pParse
->nMem
;
1560 k
= sqliteHashFirst(&db
->aDb
[iDb
].pSchema
->tblHash
);
1563 pTab
= sqlite3LocateTable(pParse
, 0, zRight
, zDb
);
1566 pTab
= (Table
*)sqliteHashData(k
);
1567 k
= sqliteHashNext(k
);
1569 if( pTab
==0 || !IsOrdinaryTable(pTab
) || pTab
->u
.tab
.pFKey
==0 ) continue;
1570 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
1571 zDb
= db
->aDb
[iDb
].zDbSName
;
1572 sqlite3CodeVerifySchema(pParse
, iDb
);
1573 sqlite3TableLock(pParse
, iDb
, pTab
->tnum
, 0, pTab
->zName
);
1574 sqlite3TouchRegister(pParse
, pTab
->nCol
+regRow
);
1575 sqlite3OpenTable(pParse
, 0, iDb
, pTab
, OP_OpenRead
);
1576 sqlite3VdbeLoadString(v
, regResult
, pTab
->zName
);
1577 assert( IsOrdinaryTable(pTab
) );
1578 for(i
=1, pFK
=pTab
->u
.tab
.pFKey
; pFK
; i
++, pFK
=pFK
->pNextFrom
){
1579 pParent
= sqlite3FindTable(db
, pFK
->zTo
, zDb
);
1580 if( pParent
==0 ) continue;
1582 sqlite3TableLock(pParse
, iDb
, pParent
->tnum
, 0, pParent
->zName
);
1583 x
= sqlite3FkLocateIndex(pParse
, pParent
, pFK
, &pIdx
, 0);
1586 sqlite3OpenTable(pParse
, i
, iDb
, pParent
, OP_OpenRead
);
1588 sqlite3VdbeAddOp3(v
, OP_OpenRead
, i
, pIdx
->tnum
, iDb
);
1589 sqlite3VdbeSetP4KeyInfo(pParse
, pIdx
);
1596 assert( pParse
->nErr
>0 || pFK
==0 );
1598 if( pParse
->nTab
<i
) pParse
->nTab
= i
;
1599 addrTop
= sqlite3VdbeAddOp1(v
, OP_Rewind
, 0); VdbeCoverage(v
);
1600 assert( IsOrdinaryTable(pTab
) );
1601 for(i
=1, pFK
=pTab
->u
.tab
.pFKey
; pFK
; i
++, pFK
=pFK
->pNextFrom
){
1602 pParent
= sqlite3FindTable(db
, pFK
->zTo
, zDb
);
1606 x
= sqlite3FkLocateIndex(pParse
, pParent
, pFK
, &pIdx
, &aiCols
);
1607 assert( x
==0 || db
->mallocFailed
);
1609 addrOk
= sqlite3VdbeMakeLabel(pParse
);
1611 /* Generate code to read the child key values into registers
1612 ** regRow..regRow+n. If any of the child key values are NULL, this
1613 ** row cannot cause an FK violation. Jump directly to addrOk in
1615 sqlite3TouchRegister(pParse
, regRow
+ pFK
->nCol
);
1616 for(j
=0; j
<pFK
->nCol
; j
++){
1617 int iCol
= aiCols
? aiCols
[j
] : pFK
->aCol
[j
].iFrom
;
1618 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, 0, iCol
, regRow
+j
);
1619 sqlite3VdbeAddOp2(v
, OP_IsNull
, regRow
+j
, addrOk
); VdbeCoverage(v
);
1622 /* Generate code to query the parent index for a matching parent
1623 ** key. If a match is found, jump to addrOk. */
1625 sqlite3VdbeAddOp4(v
, OP_Affinity
, regRow
, pFK
->nCol
, 0,
1626 sqlite3IndexAffinityStr(db
,pIdx
), pFK
->nCol
);
1627 sqlite3VdbeAddOp4Int(v
, OP_Found
, i
, addrOk
, regRow
, pFK
->nCol
);
1629 }else if( pParent
){
1630 int jmp
= sqlite3VdbeCurrentAddr(v
)+2;
1631 sqlite3VdbeAddOp3(v
, OP_SeekRowid
, i
, jmp
, regRow
); VdbeCoverage(v
);
1632 sqlite3VdbeGoto(v
, addrOk
);
1633 assert( pFK
->nCol
==1 || db
->mallocFailed
);
1636 /* Generate code to report an FK violation to the caller. */
1637 if( HasRowid(pTab
) ){
1638 sqlite3VdbeAddOp2(v
, OP_Rowid
, 0, regResult
+1);
1640 sqlite3VdbeAddOp2(v
, OP_Null
, 0, regResult
+1);
1642 sqlite3VdbeMultiLoad(v
, regResult
+2, "siX", pFK
->zTo
, i
-1);
1643 sqlite3VdbeAddOp2(v
, OP_ResultRow
, regResult
, 4);
1644 sqlite3VdbeResolveLabel(v
, addrOk
);
1645 sqlite3DbFree(db
, aiCols
);
1647 sqlite3VdbeAddOp2(v
, OP_Next
, 0, addrTop
+1); VdbeCoverage(v
);
1648 sqlite3VdbeJumpHere(v
, addrTop
);
1652 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
1653 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1655 #ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA
1656 /* Reinstall the LIKE and GLOB functions. The variant of LIKE
1657 ** used will be case sensitive or not depending on the RHS.
1659 case PragTyp_CASE_SENSITIVE_LIKE
: {
1661 sqlite3RegisterLikeFunctions(db
, sqlite3GetBoolean(zRight
, 0));
1665 #endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */
1667 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
1668 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
1671 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
1672 /* PRAGMA integrity_check
1673 ** PRAGMA integrity_check(N)
1674 ** PRAGMA quick_check
1675 ** PRAGMA quick_check(N)
1677 ** Verify the integrity of the database.
1679 ** The "quick_check" is reduced version of
1680 ** integrity_check designed to detect most database corruption
1681 ** without the overhead of cross-checking indexes. Quick_check
1682 ** is linear time whereas integrity_check is O(NlogN).
1684 ** The maximum number of errors is 100 by default. A different default
1685 ** can be specified using a numeric parameter N.
1687 ** Or, the parameter N can be the name of a table. In that case, only
1688 ** the one table named is verified. The freelist is only verified if
1689 ** the named table is "sqlite_schema" (or one of its aliases).
1691 ** All schemas are checked by default. To check just a single
1692 ** schema, use the form:
1694 ** PRAGMA schema.integrity_check;
1696 case PragTyp_INTEGRITY_CHECK
: {
1697 int i
, j
, addr
, mxErr
;
1698 Table
*pObjTab
= 0; /* Check only this one table, if not NULL */
1700 int isQuick
= (sqlite3Tolower(zLeft
[0])=='q');
1702 /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
1703 ** then iDb is set to the index of the database identified by <db>.
1704 ** In this case, the integrity of database iDb only is verified by
1705 ** the VDBE created below.
1707 ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
1708 ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
1709 ** to -1 here, to indicate that the VDBE should verify the integrity
1710 ** of all attached databases. */
1712 assert( iDb
==0 || pId2
->z
);
1713 if( pId2
->z
==0 ) iDb
= -1;
1715 /* Initialize the VDBE program */
1718 /* Set the maximum error count */
1719 mxErr
= SQLITE_INTEGRITY_CHECK_ERROR_MAX
;
1721 if( sqlite3GetInt32(pValue
->z
, &mxErr
) ){
1723 mxErr
= SQLITE_INTEGRITY_CHECK_ERROR_MAX
;
1726 pObjTab
= sqlite3LocateTable(pParse
, 0, zRight
,
1727 iDb
>=0 ? db
->aDb
[iDb
].zDbSName
: 0);
1730 sqlite3VdbeAddOp2(v
, OP_Integer
, mxErr
-1, 1); /* reg[1] holds errors left */
1732 /* Do an integrity check on each database file */
1733 for(i
=0; i
<db
->nDb
; i
++){
1734 HashElem
*x
; /* For looping over tables in the schema */
1735 Hash
*pTbls
; /* Set of all tables in the schema */
1736 int *aRoot
; /* Array of root page numbers of all btrees */
1737 int cnt
= 0; /* Number of entries in aRoot[] */
1739 if( OMIT_TEMPDB
&& i
==1 ) continue;
1740 if( iDb
>=0 && i
!=iDb
) continue;
1742 sqlite3CodeVerifySchema(pParse
, i
);
1743 pParse
->okConstFactor
= 0; /* tag-20230327-1 */
1745 /* Do an integrity check of the B-Tree
1747 ** Begin by finding the root pages numbers
1748 ** for all tables and indices in the database.
1750 assert( sqlite3SchemaMutexHeld(db
, i
, 0) );
1751 pTbls
= &db
->aDb
[i
].pSchema
->tblHash
;
1752 for(cnt
=0, x
=sqliteHashFirst(pTbls
); x
; x
=sqliteHashNext(x
)){
1753 Table
*pTab
= sqliteHashData(x
); /* Current table */
1754 Index
*pIdx
; /* An index on pTab */
1755 int nIdx
; /* Number of indexes on pTab */
1756 if( pObjTab
&& pObjTab
!=pTab
) continue;
1757 if( HasRowid(pTab
) ) cnt
++;
1758 for(nIdx
=0, pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
, nIdx
++){ cnt
++; }
1760 if( cnt
==0 ) continue;
1761 if( pObjTab
) cnt
++;
1762 aRoot
= sqlite3DbMallocRawNN(db
, sizeof(int)*(cnt
+1));
1763 if( aRoot
==0 ) break;
1765 if( pObjTab
) aRoot
[++cnt
] = 0;
1766 for(x
=sqliteHashFirst(pTbls
); x
; x
=sqliteHashNext(x
)){
1767 Table
*pTab
= sqliteHashData(x
);
1769 if( pObjTab
&& pObjTab
!=pTab
) continue;
1770 if( HasRowid(pTab
) ) aRoot
[++cnt
] = pTab
->tnum
;
1771 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1772 aRoot
[++cnt
] = pIdx
->tnum
;
1777 /* Make sure sufficient number of registers have been allocated */
1778 sqlite3TouchRegister(pParse
, 8+cnt
);
1779 sqlite3ClearTempRegCache(pParse
);
1781 /* Do the b-tree integrity checks */
1782 sqlite3VdbeAddOp4(v
, OP_IntegrityCk
, 1, cnt
, 8, (char*)aRoot
,P4_INTARRAY
);
1783 sqlite3VdbeChangeP5(v
, (u8
)i
);
1784 addr
= sqlite3VdbeAddOp1(v
, OP_IsNull
, 2); VdbeCoverage(v
);
1785 sqlite3VdbeAddOp4(v
, OP_String8
, 0, 3, 0,
1786 sqlite3MPrintf(db
, "*** in database %s ***\n", db
->aDb
[i
].zDbSName
),
1788 sqlite3VdbeAddOp3(v
, OP_Concat
, 2, 3, 3);
1789 integrityCheckResultRow(v
);
1790 sqlite3VdbeJumpHere(v
, addr
);
1792 /* Check that the indexes all have the right number of rows */
1793 cnt
= pObjTab
? 1 : 0;
1794 sqlite3VdbeLoadString(v
, 2, "wrong # of entries in index ");
1795 for(x
=sqliteHashFirst(pTbls
); x
; x
=sqliteHashNext(x
)){
1797 Table
*pTab
= sqliteHashData(x
);
1799 if( pObjTab
&& pObjTab
!=pTab
) continue;
1800 if( HasRowid(pTab
) ){
1804 for(pIdx
=pTab
->pIndex
; ALWAYS(pIdx
); pIdx
=pIdx
->pNext
){
1805 if( IsPrimaryKeyIndex(pIdx
) ) break;
1809 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1810 if( pIdx
->pPartIdxWhere
==0 ){
1811 addr
= sqlite3VdbeAddOp3(v
, OP_Eq
, 8+cnt
, 0, 8+iTab
);
1812 VdbeCoverageNeverNull(v
);
1813 sqlite3VdbeLoadString(v
, 4, pIdx
->zName
);
1814 sqlite3VdbeAddOp3(v
, OP_Concat
, 4, 2, 3);
1815 integrityCheckResultRow(v
);
1816 sqlite3VdbeJumpHere(v
, addr
);
1822 /* Make sure all the indices are constructed correctly.
1824 for(x
=sqliteHashFirst(pTbls
); x
; x
=sqliteHashNext(x
)){
1825 Table
*pTab
= sqliteHashData(x
);
1827 Index
*pPrior
= 0; /* Previous index */
1829 int iDataCur
, iIdxCur
;
1831 int bStrict
; /* True for a STRICT table */
1832 int r2
; /* Previous key for WITHOUT ROWID tables */
1833 int mxCol
; /* Maximum non-virtual column number */
1835 if( pObjTab
&& pObjTab
!=pTab
) continue;
1836 if( !IsOrdinaryTable(pTab
) ) continue;
1837 if( isQuick
|| HasRowid(pTab
) ){
1841 pPk
= sqlite3PrimaryKeyIndex(pTab
);
1842 r2
= sqlite3GetTempRange(pParse
, pPk
->nKeyCol
);
1843 sqlite3VdbeAddOp3(v
, OP_Null
, 1, r2
, r2
+pPk
->nKeyCol
-1);
1845 sqlite3OpenTableAndIndices(pParse
, pTab
, OP_OpenRead
, 0,
1846 1, 0, &iDataCur
, &iIdxCur
);
1847 /* reg[7] counts the number of entries in the table.
1848 ** reg[8+i] counts the number of entries in the i-th index
1850 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, 7);
1851 for(j
=0, pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
, j
++){
1852 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, 8+j
); /* index entries counter */
1854 assert( pParse
->nMem
>=8+j
);
1855 assert( sqlite3NoTempsInRange(pParse
,1,7+j
) );
1856 sqlite3VdbeAddOp2(v
, OP_Rewind
, iDataCur
, 0); VdbeCoverage(v
);
1857 loopTop
= sqlite3VdbeAddOp2(v
, OP_AddImm
, 7, 1);
1859 /* Fetch the right-most column from the table. This will cause
1860 ** the entire record header to be parsed and sanity checked. It
1861 ** will also prepopulate the cursor column cache that is used
1862 ** by the OP_IsType code, so it is a required step.
1864 assert( !IsVirtual(pTab
) );
1865 if( HasRowid(pTab
) ){
1867 for(j
=0; j
<pTab
->nCol
; j
++){
1868 if( (pTab
->aCol
[j
].colFlags
& COLFLAG_VIRTUAL
)==0 ) mxCol
++;
1870 if( mxCol
==pTab
->iPKey
) mxCol
--;
1872 /* COLFLAG_VIRTUAL columns are not included in the WITHOUT ROWID
1873 ** PK index column-count, so there is no need to account for them
1875 mxCol
= sqlite3PrimaryKeyIndex(pTab
)->nColumn
-1;
1878 sqlite3VdbeAddOp3(v
, OP_Column
, iDataCur
, mxCol
, 3);
1879 sqlite3VdbeTypeofColumn(v
, 3);
1884 /* Verify WITHOUT ROWID keys are in ascending order */
1887 a1
= sqlite3VdbeAddOp4Int(v
, OP_IdxGT
, iDataCur
, 0,r2
,pPk
->nKeyCol
);
1889 sqlite3VdbeAddOp1(v
, OP_IsNull
, r2
); VdbeCoverage(v
);
1890 zErr
= sqlite3MPrintf(db
,
1891 "row not in PRIMARY KEY order for %s",
1893 sqlite3VdbeAddOp4(v
, OP_String8
, 0, 3, 0, zErr
, P4_DYNAMIC
);
1894 integrityCheckResultRow(v
);
1895 sqlite3VdbeJumpHere(v
, a1
);
1896 sqlite3VdbeJumpHere(v
, a1
+1);
1897 for(j
=0; j
<pPk
->nKeyCol
; j
++){
1898 sqlite3ExprCodeLoadIndexColumn(pParse
, pPk
, iDataCur
, j
, r2
+j
);
1902 /* Verify datatypes for all columns:
1904 ** (1) NOT NULL columns may not contain a NULL
1905 ** (2) Datatype must be exact for non-ANY columns in STRICT tables
1906 ** (3) Datatype for TEXT columns in non-STRICT tables must be
1907 ** NULL, TEXT, or BLOB.
1908 ** (4) Datatype for numeric columns in non-STRICT tables must not
1909 ** be a TEXT value that can be losslessly converted to numeric.
1911 bStrict
= (pTab
->tabFlags
& TF_Strict
)!=0;
1912 for(j
=0; j
<pTab
->nCol
; j
++){
1914 Column
*pCol
= pTab
->aCol
+ j
; /* The column to be checked */
1915 int labelError
; /* Jump here to report an error */
1916 int labelOk
; /* Jump here if all looks ok */
1917 int p1
, p3
, p4
; /* Operands to the OP_IsType opcode */
1918 int doTypeCheck
; /* Check datatypes (besides NOT NULL) */
1920 if( j
==pTab
->iPKey
) continue;
1922 doTypeCheck
= pCol
->eCType
>COLTYPE_ANY
;
1924 doTypeCheck
= pCol
->affinity
>SQLITE_AFF_BLOB
;
1926 if( pCol
->notNull
==0 && !doTypeCheck
) continue;
1928 /* Compute the operands that will be needed for OP_IsType */
1930 if( pCol
->colFlags
& COLFLAG_VIRTUAL
){
1931 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iDataCur
, j
, 3);
1936 sqlite3_value
*pDfltValue
= 0;
1937 sqlite3ValueFromExpr(db
, sqlite3ColumnExpr(pTab
,pCol
), ENC(db
),
1938 pCol
->affinity
, &pDfltValue
);
1940 p4
= sqlite3_value_type(pDfltValue
);
1941 sqlite3ValueFree(pDfltValue
);
1945 if( !HasRowid(pTab
) ){
1946 testcase( j
!=sqlite3TableColumnToStorage(pTab
, j
) );
1947 p3
= sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab
), j
);
1949 p3
= sqlite3TableColumnToStorage(pTab
,j
);
1954 labelError
= sqlite3VdbeMakeLabel(pParse
);
1955 labelOk
= sqlite3VdbeMakeLabel(pParse
);
1956 if( pCol
->notNull
){
1957 /* (1) NOT NULL columns may not contain a NULL */
1959 int jmp2
= sqlite3VdbeAddOp4Int(v
, OP_IsType
, p1
, labelOk
, p3
, p4
);
1962 sqlite3VdbeChangeP5(v
, 0x0f); /* INT, REAL, TEXT, or BLOB */
1965 sqlite3VdbeChangeP5(v
, 0x0d); /* INT, TEXT, or BLOB */
1966 /* OP_IsType does not detect NaN values in the database file
1967 ** which should be treated as a NULL. So if the header type
1968 ** is REAL, we have to load the actual data using OP_Column
1969 ** to reliably determine if the value is a NULL. */
1970 sqlite3VdbeAddOp3(v
, OP_Column
, p1
, p3
, 3);
1971 sqlite3ColumnDefault(v
, pTab
, j
, 3);
1972 jmp3
= sqlite3VdbeAddOp2(v
, OP_NotNull
, 3, labelOk
);
1975 zErr
= sqlite3MPrintf(db
, "NULL value in %s.%s", pTab
->zName
,
1977 sqlite3VdbeAddOp4(v
, OP_String8
, 0, 3, 0, zErr
, P4_DYNAMIC
);
1979 sqlite3VdbeGoto(v
, labelError
);
1980 sqlite3VdbeJumpHere(v
, jmp2
);
1981 sqlite3VdbeJumpHere(v
, jmp3
);
1983 /* VDBE byte code will fall thru */
1986 if( bStrict
&& doTypeCheck
){
1987 /* (2) Datatype must be exact for non-ANY columns in STRICT tables*/
1988 static unsigned char aStdTypeMask
[] = {
1996 sqlite3VdbeAddOp4Int(v
, OP_IsType
, p1
, labelOk
, p3
, p4
);
1997 assert( pCol
->eCType
>=1 && pCol
->eCType
<=sizeof(aStdTypeMask
) );
1998 sqlite3VdbeChangeP5(v
, aStdTypeMask
[pCol
->eCType
-1]);
2000 zErr
= sqlite3MPrintf(db
, "non-%s value in %s.%s",
2001 sqlite3StdType
[pCol
->eCType
-1],
2002 pTab
->zName
, pTab
->aCol
[j
].zCnName
);
2003 sqlite3VdbeAddOp4(v
, OP_String8
, 0, 3, 0, zErr
, P4_DYNAMIC
);
2004 }else if( !bStrict
&& pCol
->affinity
==SQLITE_AFF_TEXT
){
2005 /* (3) Datatype for TEXT columns in non-STRICT tables must be
2006 ** NULL, TEXT, or BLOB. */
2007 sqlite3VdbeAddOp4Int(v
, OP_IsType
, p1
, labelOk
, p3
, p4
);
2008 sqlite3VdbeChangeP5(v
, 0x1c); /* NULL, TEXT, or BLOB */
2010 zErr
= sqlite3MPrintf(db
, "NUMERIC value in %s.%s",
2011 pTab
->zName
, pTab
->aCol
[j
].zCnName
);
2012 sqlite3VdbeAddOp4(v
, OP_String8
, 0, 3, 0, zErr
, P4_DYNAMIC
);
2013 }else if( !bStrict
&& pCol
->affinity
>=SQLITE_AFF_NUMERIC
){
2014 /* (4) Datatype for numeric columns in non-STRICT tables must not
2015 ** be a TEXT value that can be converted to numeric. */
2016 sqlite3VdbeAddOp4Int(v
, OP_IsType
, p1
, labelOk
, p3
, p4
);
2017 sqlite3VdbeChangeP5(v
, 0x1b); /* NULL, INT, FLOAT, or BLOB */
2020 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iDataCur
, j
, 3);
2022 sqlite3VdbeAddOp4(v
, OP_Affinity
, 3, 1, 0, "C", P4_STATIC
);
2023 sqlite3VdbeAddOp4Int(v
, OP_IsType
, -1, labelOk
, 3, p4
);
2024 sqlite3VdbeChangeP5(v
, 0x1c); /* NULL, TEXT, or BLOB */
2026 zErr
= sqlite3MPrintf(db
, "TEXT value in %s.%s",
2027 pTab
->zName
, pTab
->aCol
[j
].zCnName
);
2028 sqlite3VdbeAddOp4(v
, OP_String8
, 0, 3, 0, zErr
, P4_DYNAMIC
);
2030 sqlite3VdbeResolveLabel(v
, labelError
);
2031 integrityCheckResultRow(v
);
2032 sqlite3VdbeResolveLabel(v
, labelOk
);
2034 /* Verify CHECK constraints */
2035 if( pTab
->pCheck
&& (db
->flags
& SQLITE_IgnoreChecks
)==0 ){
2036 ExprList
*pCheck
= sqlite3ExprListDup(db
, pTab
->pCheck
, 0);
2037 if( db
->mallocFailed
==0 ){
2038 int addrCkFault
= sqlite3VdbeMakeLabel(pParse
);
2039 int addrCkOk
= sqlite3VdbeMakeLabel(pParse
);
2042 pParse
->iSelfTab
= iDataCur
+ 1;
2043 for(k
=pCheck
->nExpr
-1; k
>0; k
--){
2044 sqlite3ExprIfFalse(pParse
, pCheck
->a
[k
].pExpr
, addrCkFault
, 0);
2046 sqlite3ExprIfTrue(pParse
, pCheck
->a
[0].pExpr
, addrCkOk
,
2048 sqlite3VdbeResolveLabel(v
, addrCkFault
);
2049 pParse
->iSelfTab
= 0;
2050 zErr
= sqlite3MPrintf(db
, "CHECK constraint failed in %s",
2052 sqlite3VdbeAddOp4(v
, OP_String8
, 0, 3, 0, zErr
, P4_DYNAMIC
);
2053 integrityCheckResultRow(v
);
2054 sqlite3VdbeResolveLabel(v
, addrCkOk
);
2056 sqlite3ExprListDelete(db
, pCheck
);
2058 if( !isQuick
){ /* Omit the remaining tests for quick_check */
2059 /* Validate index entries for the current row */
2060 for(j
=0, pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
, j
++){
2061 int jmp2
, jmp3
, jmp4
, jmp5
, label6
;
2063 int ckUniq
= sqlite3VdbeMakeLabel(pParse
);
2064 if( pPk
==pIdx
) continue;
2065 r1
= sqlite3GenerateIndexKey(pParse
, pIdx
, iDataCur
, 0, 0, &jmp3
,
2068 sqlite3VdbeAddOp2(v
, OP_AddImm
, 8+j
, 1);/* increment entry count */
2069 /* Verify that an index entry exists for the current table row */
2070 jmp2
= sqlite3VdbeAddOp4Int(v
, OP_Found
, iIdxCur
+j
, ckUniq
, r1
,
2071 pIdx
->nColumn
); VdbeCoverage(v
);
2072 sqlite3VdbeLoadString(v
, 3, "row ");
2073 sqlite3VdbeAddOp3(v
, OP_Concat
, 7, 3, 3);
2074 sqlite3VdbeLoadString(v
, 4, " missing from index ");
2075 sqlite3VdbeAddOp3(v
, OP_Concat
, 4, 3, 3);
2076 jmp5
= sqlite3VdbeLoadString(v
, 4, pIdx
->zName
);
2077 sqlite3VdbeAddOp3(v
, OP_Concat
, 4, 3, 3);
2078 jmp4
= integrityCheckResultRow(v
);
2079 sqlite3VdbeJumpHere(v
, jmp2
);
2081 /* The OP_IdxRowid opcode is an optimized version of OP_Column
2082 ** that extracts the rowid off the end of the index record.
2083 ** But it only works correctly if index record does not have
2084 ** any extra bytes at the end. Verify that this is the case. */
2085 if( HasRowid(pTab
) ){
2087 sqlite3VdbeAddOp2(v
, OP_IdxRowid
, iIdxCur
+j
, 3);
2088 jmp7
= sqlite3VdbeAddOp3(v
, OP_Eq
, 3, 0, r1
+pIdx
->nColumn
-1);
2089 VdbeCoverageNeverNull(v
);
2090 sqlite3VdbeLoadString(v
, 3,
2091 "rowid not at end-of-record for row ");
2092 sqlite3VdbeAddOp3(v
, OP_Concat
, 7, 3, 3);
2093 sqlite3VdbeLoadString(v
, 4, " of index ");
2094 sqlite3VdbeGoto(v
, jmp5
-1);
2095 sqlite3VdbeJumpHere(v
, jmp7
);
2098 /* Any indexed columns with non-BINARY collations must still hold
2099 ** the exact same text value as the table. */
2101 for(kk
=0; kk
<pIdx
->nKeyCol
; kk
++){
2102 if( pIdx
->azColl
[kk
]==sqlite3StrBINARY
) continue;
2103 if( label6
==0 ) label6
= sqlite3VdbeMakeLabel(pParse
);
2104 sqlite3VdbeAddOp3(v
, OP_Column
, iIdxCur
+j
, kk
, 3);
2105 sqlite3VdbeAddOp3(v
, OP_Ne
, 3, label6
, r1
+kk
); VdbeCoverage(v
);
2108 int jmp6
= sqlite3VdbeAddOp0(v
, OP_Goto
);
2109 sqlite3VdbeResolveLabel(v
, label6
);
2110 sqlite3VdbeLoadString(v
, 3, "row ");
2111 sqlite3VdbeAddOp3(v
, OP_Concat
, 7, 3, 3);
2112 sqlite3VdbeLoadString(v
, 4, " values differ from index ");
2113 sqlite3VdbeGoto(v
, jmp5
-1);
2114 sqlite3VdbeJumpHere(v
, jmp6
);
2117 /* For UNIQUE indexes, verify that only one entry exists with the
2118 ** current key. The entry is unique if (1) any column is NULL
2119 ** or (2) the next entry has a different key */
2120 if( IsUniqueIndex(pIdx
) ){
2121 int uniqOk
= sqlite3VdbeMakeLabel(pParse
);
2123 for(kk
=0; kk
<pIdx
->nKeyCol
; kk
++){
2124 int iCol
= pIdx
->aiColumn
[kk
];
2125 assert( iCol
!=XN_ROWID
&& iCol
<pTab
->nCol
);
2126 if( iCol
>=0 && pTab
->aCol
[iCol
].notNull
) continue;
2127 sqlite3VdbeAddOp2(v
, OP_IsNull
, r1
+kk
, uniqOk
);
2130 jmp6
= sqlite3VdbeAddOp1(v
, OP_Next
, iIdxCur
+j
); VdbeCoverage(v
);
2131 sqlite3VdbeGoto(v
, uniqOk
);
2132 sqlite3VdbeJumpHere(v
, jmp6
);
2133 sqlite3VdbeAddOp4Int(v
, OP_IdxGT
, iIdxCur
+j
, uniqOk
, r1
,
2134 pIdx
->nKeyCol
); VdbeCoverage(v
);
2135 sqlite3VdbeLoadString(v
, 3, "non-unique entry in index ");
2136 sqlite3VdbeGoto(v
, jmp5
);
2137 sqlite3VdbeResolveLabel(v
, uniqOk
);
2139 sqlite3VdbeJumpHere(v
, jmp4
);
2140 sqlite3ResolvePartIdxLabel(pParse
, jmp3
);
2143 sqlite3VdbeAddOp2(v
, OP_Next
, iDataCur
, loopTop
); VdbeCoverage(v
);
2144 sqlite3VdbeJumpHere(v
, loopTop
-1);
2147 sqlite3ReleaseTempRange(pParse
, r2
, pPk
->nKeyCol
);
2151 #ifndef SQLITE_OMIT_VIRTUALTABLE
2152 /* Second pass to invoke the xIntegrity method on all virtual
2155 for(x
=sqliteHashFirst(pTbls
); x
; x
=sqliteHashNext(x
)){
2156 Table
*pTab
= sqliteHashData(x
);
2157 sqlite3_vtab
*pVTab
;
2159 if( pObjTab
&& pObjTab
!=pTab
) continue;
2160 if( IsOrdinaryTable(pTab
) ) continue;
2161 if( !IsVirtual(pTab
) ) continue;
2162 if( pTab
->nCol
<=0 ){
2163 const char *zMod
= pTab
->u
.vtab
.azArg
[0];
2164 if( sqlite3HashFind(&db
->aModule
, zMod
)==0 ) continue;
2166 sqlite3ViewGetColumnNames(pParse
, pTab
);
2167 if( pTab
->u
.vtab
.p
==0 ) continue;
2168 pVTab
= pTab
->u
.vtab
.p
->pVtab
;
2169 if( NEVER(pVTab
==0) ) continue;
2170 if( NEVER(pVTab
->pModule
==0) ) continue;
2171 if( pVTab
->pModule
->iVersion
<4 ) continue;
2172 if( pVTab
->pModule
->xIntegrity
==0 ) continue;
2173 sqlite3VdbeAddOp3(v
, OP_VCheck
, i
, 3, isQuick
);
2175 sqlite3VdbeAppendP4(v
, pTab
, P4_TABLEREF
);
2176 a1
= sqlite3VdbeAddOp1(v
, OP_IsNull
, 3); VdbeCoverage(v
);
2177 integrityCheckResultRow(v
);
2178 sqlite3VdbeJumpHere(v
, a1
);
2184 static const int iLn
= VDBE_OFFSET_LINENO(2);
2185 static const VdbeOpList endCode
[] = {
2186 { OP_AddImm
, 1, 0, 0}, /* 0 */
2187 { OP_IfNotZero
, 1, 4, 0}, /* 1 */
2188 { OP_String8
, 0, 3, 0}, /* 2 */
2189 { OP_ResultRow
, 3, 1, 0}, /* 3 */
2190 { OP_Halt
, 0, 0, 0}, /* 4 */
2191 { OP_String8
, 0, 3, 0}, /* 5 */
2192 { OP_Goto
, 0, 3, 0}, /* 6 */
2196 aOp
= sqlite3VdbeAddOpList(v
, ArraySize(endCode
), endCode
, iLn
);
2198 aOp
[0].p2
= 1-mxErr
;
2199 aOp
[2].p4type
= P4_STATIC
;
2201 aOp
[5].p4type
= P4_STATIC
;
2202 aOp
[5].p4
.z
= (char*)sqlite3ErrStr(SQLITE_CORRUPT
);
2204 sqlite3VdbeChangeP3(v
, 0, sqlite3VdbeCurrentAddr(v
)-2);
2208 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
2210 #ifndef SQLITE_OMIT_UTF16
2213 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
2215 ** In its first form, this pragma returns the encoding of the main
2216 ** database. If the database is not initialized, it is initialized now.
2218 ** The second form of this pragma is a no-op if the main database file
2219 ** has not already been initialized. In this case it sets the default
2220 ** encoding that will be used for the main database file if a new file
2221 ** is created. If an existing main database file is opened, then the
2222 ** default text encoding for the existing database is used.
2224 ** In all cases new databases created using the ATTACH command are
2225 ** created to use the same default text encoding as the main database. If
2226 ** the main database has not been initialized and/or created when ATTACH
2227 ** is executed, this is done before the ATTACH operation.
2229 ** In the second form this pragma sets the text encoding to be used in
2230 ** new database files created using this database handle. It is only
2231 ** useful if invoked immediately after the main database i
2233 case PragTyp_ENCODING
: {
2234 static const struct EncName
{
2238 { "UTF8", SQLITE_UTF8
},
2239 { "UTF-8", SQLITE_UTF8
}, /* Must be element [1] */
2240 { "UTF-16le", SQLITE_UTF16LE
}, /* Must be element [2] */
2241 { "UTF-16be", SQLITE_UTF16BE
}, /* Must be element [3] */
2242 { "UTF16le", SQLITE_UTF16LE
},
2243 { "UTF16be", SQLITE_UTF16BE
},
2244 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
2245 { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
2248 const struct EncName
*pEnc
;
2249 if( !zRight
){ /* "PRAGMA encoding" */
2250 if( sqlite3ReadSchema(pParse
) ) goto pragma_out
;
2251 assert( encnames
[SQLITE_UTF8
].enc
==SQLITE_UTF8
);
2252 assert( encnames
[SQLITE_UTF16LE
].enc
==SQLITE_UTF16LE
);
2253 assert( encnames
[SQLITE_UTF16BE
].enc
==SQLITE_UTF16BE
);
2254 returnSingleText(v
, encnames
[ENC(pParse
->db
)].zName
);
2255 }else{ /* "PRAGMA encoding = XXX" */
2256 /* Only change the value of sqlite.enc if the database handle is not
2257 ** initialized. If the main database exists, the new sqlite.enc value
2258 ** will be overwritten when the schema is next loaded. If it does not
2259 ** already exists, it will be created to use the new encoding value.
2261 if( (db
->mDbFlags
& DBFLAG_EncodingFixed
)==0 ){
2262 for(pEnc
=&encnames
[0]; pEnc
->zName
; pEnc
++){
2263 if( 0==sqlite3StrICmp(zRight
, pEnc
->zName
) ){
2264 u8 enc
= pEnc
->enc
? pEnc
->enc
: SQLITE_UTF16NATIVE
;
2265 SCHEMA_ENC(db
) = enc
;
2266 sqlite3SetTextEncoding(db
, enc
);
2271 sqlite3ErrorMsg(pParse
, "unsupported encoding: %s", zRight
);
2277 #endif /* SQLITE_OMIT_UTF16 */
2279 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
2281 ** PRAGMA [schema.]schema_version
2282 ** PRAGMA [schema.]schema_version = <integer>
2284 ** PRAGMA [schema.]user_version
2285 ** PRAGMA [schema.]user_version = <integer>
2287 ** PRAGMA [schema.]freelist_count
2289 ** PRAGMA [schema.]data_version
2291 ** PRAGMA [schema.]application_id
2292 ** PRAGMA [schema.]application_id = <integer>
2294 ** The pragma's schema_version and user_version are used to set or get
2295 ** the value of the schema-version and user-version, respectively. Both
2296 ** the schema-version and the user-version are 32-bit signed integers
2297 ** stored in the database header.
2299 ** The schema-cookie is usually only manipulated internally by SQLite. It
2300 ** is incremented by SQLite whenever the database schema is modified (by
2301 ** creating or dropping a table or index). The schema version is used by
2302 ** SQLite each time a query is executed to ensure that the internal cache
2303 ** of the schema used when compiling the SQL query matches the schema of
2304 ** the database against which the compiled query is actually executed.
2305 ** Subverting this mechanism by using "PRAGMA schema_version" to modify
2306 ** the schema-version is potentially dangerous and may lead to program
2307 ** crashes or database corruption. Use with caution!
2309 ** The user-version is not used internally by SQLite. It may be used by
2310 ** applications for any purpose.
2312 case PragTyp_HEADER_VALUE
: {
2313 int iCookie
= pPragma
->iArg
; /* Which cookie to read or write */
2314 sqlite3VdbeUsesBtree(v
, iDb
);
2315 if( zRight
&& (pPragma
->mPragFlg
& PragFlg_ReadOnly
)==0 ){
2316 /* Write the specified cookie value */
2317 static const VdbeOpList setCookie
[] = {
2318 { OP_Transaction
, 0, 1, 0}, /* 0 */
2319 { OP_SetCookie
, 0, 0, 0}, /* 1 */
2322 sqlite3VdbeVerifyNoMallocRequired(v
, ArraySize(setCookie
));
2323 aOp
= sqlite3VdbeAddOpList(v
, ArraySize(setCookie
), setCookie
, 0);
2324 if( ONLY_IF_REALLOC_STRESS(aOp
==0) ) break;
2327 aOp
[1].p2
= iCookie
;
2328 aOp
[1].p3
= sqlite3Atoi(zRight
);
2330 if( iCookie
==BTREE_SCHEMA_VERSION
&& (db
->flags
& SQLITE_Defensive
)!=0 ){
2331 /* Do not allow the use of PRAGMA schema_version=VALUE in defensive
2332 ** mode. Change the OP_SetCookie opcode into a no-op. */
2333 aOp
[1].opcode
= OP_Noop
;
2336 /* Read the specified cookie value */
2337 static const VdbeOpList readCookie
[] = {
2338 { OP_Transaction
, 0, 0, 0}, /* 0 */
2339 { OP_ReadCookie
, 0, 1, 0}, /* 1 */
2340 { OP_ResultRow
, 1, 1, 0}
2343 sqlite3VdbeVerifyNoMallocRequired(v
, ArraySize(readCookie
));
2344 aOp
= sqlite3VdbeAddOpList(v
, ArraySize(readCookie
),readCookie
,0);
2345 if( ONLY_IF_REALLOC_STRESS(aOp
==0) ) break;
2348 aOp
[1].p3
= iCookie
;
2349 sqlite3VdbeReusable(v
);
2353 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
2355 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
2357 ** PRAGMA compile_options
2359 ** Return the names of all compile-time options used in this build,
2360 ** one option per row.
2362 case PragTyp_COMPILE_OPTIONS
: {
2366 while( (zOpt
= sqlite3_compileoption_get(i
++))!=0 ){
2367 sqlite3VdbeLoadString(v
, 1, zOpt
);
2368 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, 1);
2370 sqlite3VdbeReusable(v
);
2373 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
2375 #ifndef SQLITE_OMIT_WAL
2377 ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
2379 ** Checkpoint the database.
2381 case PragTyp_WAL_CHECKPOINT
: {
2382 int iBt
= (pId2
->z
?iDb
:SQLITE_MAX_DB
);
2383 int eMode
= SQLITE_CHECKPOINT_PASSIVE
;
2385 if( sqlite3StrICmp(zRight
, "full")==0 ){
2386 eMode
= SQLITE_CHECKPOINT_FULL
;
2387 }else if( sqlite3StrICmp(zRight
, "restart")==0 ){
2388 eMode
= SQLITE_CHECKPOINT_RESTART
;
2389 }else if( sqlite3StrICmp(zRight
, "truncate")==0 ){
2390 eMode
= SQLITE_CHECKPOINT_TRUNCATE
;
2394 sqlite3VdbeAddOp3(v
, OP_Checkpoint
, iBt
, eMode
, 1);
2395 sqlite3VdbeAddOp2(v
, OP_ResultRow
, 1, 3);
2400 ** PRAGMA wal_autocheckpoint
2401 ** PRAGMA wal_autocheckpoint = N
2403 ** Configure a database connection to automatically checkpoint a database
2404 ** after accumulating N frames in the log. Or query for the current value
2407 case PragTyp_WAL_AUTOCHECKPOINT
: {
2409 sqlite3_wal_autocheckpoint(db
, sqlite3Atoi(zRight
));
2412 db
->xWalCallback
==sqlite3WalDefaultHook
?
2413 SQLITE_PTR_TO_INT(db
->pWalArg
) : 0);
2419 ** PRAGMA shrink_memory
2421 ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
2422 ** connection on which it is invoked to free up as much memory as it
2423 ** can, by calling sqlite3_db_release_memory().
2425 case PragTyp_SHRINK_MEMORY
: {
2426 sqlite3_db_release_memory(db
);
2432 ** PRAGMA optimize(MASK)
2433 ** PRAGMA schema.optimize
2434 ** PRAGMA schema.optimize(MASK)
2436 ** Attempt to optimize the database. All schemas are optimized in the first
2437 ** two forms, and only the specified schema is optimized in the latter two.
2439 ** The details of optimizations performed by this pragma are expected
2440 ** to change and improve over time. Applications should anticipate that
2441 ** this pragma will perform new optimizations in future releases.
2443 ** The optional argument is a bitmask of optimizations to perform:
2445 ** 0x00001 Debugging mode. Do not actually perform any optimizations
2446 ** but instead return one line of text for each optimization
2447 ** that would have been done. Off by default.
2449 ** 0x00002 Run ANALYZE on tables that might benefit. On by default.
2450 ** See below for additional information.
2452 ** 0x00010 Run all ANALYZE operations using an analysis_limit that
2453 ** is the lessor of the current analysis_limit and the
2454 ** SQLITE_DEFAULT_OPTIMIZE_LIMIT compile-time option.
2455 ** The default value of SQLITE_DEFAULT_OPTIMIZE_LIMIT is
2456 ** currently (2024-02-19) set to 2000, which is such that
2457 ** the worst case run-time for PRAGMA optimize on a 100MB
2458 ** database will usually be less than 100 milliseconds on
2459 ** a RaspberryPI-4 class machine. On by default.
2461 ** 0x10000 Look at tables to see if they need to be reanalyzed
2462 ** due to growth or shrinkage even if they have not been
2463 ** queried during the current connection. Off by default.
2465 ** The default MASK is and always shall be 0x0fffe. In the current
2466 ** implementation, the default mask only covers the 0x00002 optimization,
2467 ** though additional optimizations that are covered by 0x0fffe might be
2468 ** added in the future. Optimizations that are off by default and must
2469 ** be explicitly requested have masks of 0x10000 or greater.
2471 ** DETERMINATION OF WHEN TO RUN ANALYZE
2473 ** In the current implementation, a table is analyzed if only if all of
2474 ** the following are true:
2476 ** (1) MASK bit 0x00002 is set.
2478 ** (2) The table is an ordinary table, not a virtual table or view.
2480 ** (3) The table name does not begin with "sqlite_".
2482 ** (4) One or more of the following is true:
2483 ** (4a) The 0x10000 MASK bit is set.
2484 ** (4b) One or more indexes on the table lacks an entry
2485 ** in the sqlite_stat1 table.
2486 ** (4c) The query planner used sqlite_stat1-style statistics for one
2487 ** or more indexes of the table at some point during the lifetime
2488 ** of the current connection.
2490 ** (5) One or more of the following is true:
2491 ** (5a) One or more indexes on the table lacks an entry
2492 ** in the sqlite_stat1 table. (Same as 4a)
2493 ** (5b) The number of rows in the table has increased or decreased by
2494 ** 10-fold. In other words, the current size of the table is
2495 ** 10 times larger than the size in sqlite_stat1 or else the
2496 ** current size is less than 1/10th the size in sqlite_stat1.
2498 ** The rules for when tables are analyzed are likely to change in
2499 ** future releases. Future versions of SQLite might accept a string
2500 ** literal argument to this pragma that contains a mnemonic description
2501 ** of the options rather than a bitmap.
2503 case PragTyp_OPTIMIZE
: {
2504 int iDbLast
; /* Loop termination point for the schema loop */
2505 int iTabCur
; /* Cursor for a table whose size needs checking */
2506 HashElem
*k
; /* Loop over tables of a schema */
2507 Schema
*pSchema
; /* The current schema */
2508 Table
*pTab
; /* A table in the schema */
2509 Index
*pIdx
; /* An index of the table */
2510 LogEst szThreshold
; /* Size threshold above which reanalysis needed */
2511 char *zSubSql
; /* SQL statement for the OP_SqlExec opcode */
2512 u32 opMask
; /* Mask of operations to perform */
2513 int nLimit
; /* Analysis limit to use */
2514 int nCheck
= 0; /* Number of tables to be optimized */
2515 int nBtree
= 0; /* Number of btrees to scan */
2516 int nIndex
; /* Number of indexes on the current table */
2519 opMask
= (u32
)sqlite3Atoi(zRight
);
2520 if( (opMask
& 0x02)==0 ) break;
2524 if( (opMask
& 0x10)==0 ){
2526 }else if( db
->nAnalysisLimit
>0
2527 && db
->nAnalysisLimit
<SQLITE_DEFAULT_OPTIMIZE_LIMIT
){
2530 nLimit
= SQLITE_DEFAULT_OPTIMIZE_LIMIT
;
2532 iTabCur
= pParse
->nTab
++;
2533 for(iDbLast
= zDb
?iDb
:db
->nDb
-1; iDb
<=iDbLast
; iDb
++){
2534 if( iDb
==1 ) continue;
2535 sqlite3CodeVerifySchema(pParse
, iDb
);
2536 pSchema
= db
->aDb
[iDb
].pSchema
;
2537 for(k
=sqliteHashFirst(&pSchema
->tblHash
); k
; k
=sqliteHashNext(k
)){
2538 pTab
= (Table
*)sqliteHashData(k
);
2540 /* This only works for ordinary tables */
2541 if( !IsOrdinaryTable(pTab
) ) continue;
2543 /* Do not scan system tables */
2544 if( 0==sqlite3StrNICmp(pTab
->zName
, "sqlite_", 7) ) continue;
2546 /* Find the size of the table as last recorded in sqlite_stat1.
2547 ** If any index is unanalyzed, then the threshold is -1 to
2548 ** indicate a new, unanalyzed index
2550 szThreshold
= pTab
->nRowLogEst
;
2552 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
2554 if( !pIdx
->hasStat1
){
2555 szThreshold
= -1; /* Always analyze if any index lacks statistics */
2559 /* If table pTab has not been used in a way that would benefit from
2560 ** having analysis statistics during the current session, then skip it,
2561 ** unless the 0x10000 MASK bit is set. */
2562 if( (pTab
->tabFlags
& TF_MaybeReanalyze
)!=0 ){
2563 /* Check for size change if stat1 has been used for a query */
2564 }else if( opMask
& 0x10000 ){
2565 /* Check for size change if 0x10000 is set */
2566 }else if( pTab
->pIndex
!=0 && szThreshold
<0 ){
2567 /* Do analysis if unanalyzed indexes exists */
2569 /* Otherwise, we can skip this table */
2575 /* If ANALYZE might be invoked two or more times, hold a write
2576 ** transaction for efficiency */
2577 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
2581 /* Reanalyze if the table is 10 times larger or smaller than
2582 ** the last analysis. Unconditional reanalysis if there are
2583 ** unanalyzed indexes. */
2584 sqlite3OpenTable(pParse
, iTabCur
, iDb
, pTab
, OP_OpenRead
);
2585 if( szThreshold
>=0 ){
2586 const LogEst iRange
= 33; /* 10x size change */
2587 sqlite3VdbeAddOp4Int(v
, OP_IfSizeBetween
, iTabCur
,
2588 sqlite3VdbeCurrentAddr(v
)+2+(opMask
&1),
2589 szThreshold
>=iRange
? szThreshold
-iRange
: -1,
2590 szThreshold
+iRange
);
2593 sqlite3VdbeAddOp2(v
, OP_Rewind
, iTabCur
,
2594 sqlite3VdbeCurrentAddr(v
)+2+(opMask
&1));
2597 zSubSql
= sqlite3MPrintf(db
, "ANALYZE \"%w\".\"%w\"",
2598 db
->aDb
[iDb
].zDbSName
, pTab
->zName
);
2599 if( opMask
& 0x01 ){
2600 int r1
= sqlite3GetTempReg(pParse
);
2601 sqlite3VdbeAddOp4(v
, OP_String8
, 0, r1
, 0, zSubSql
, P4_DYNAMIC
);
2602 sqlite3VdbeAddOp2(v
, OP_ResultRow
, r1
, 1);
2604 sqlite3VdbeAddOp4(v
, OP_SqlExec
, nLimit
? 0x02 : 00, nLimit
, 0,
2605 zSubSql
, P4_DYNAMIC
);
2609 sqlite3VdbeAddOp0(v
, OP_Expire
);
2611 /* In a schema with a large number of tables and indexes, scale back
2612 ** the analysis_limit to avoid excess run-time in the worst case.
2614 if( !db
->mallocFailed
&& nLimit
>0 && nBtree
>100 ){
2617 nLimit
= 100*nLimit
/nBtree
;
2618 if( nLimit
<100 ) nLimit
= 100;
2619 aOp
= sqlite3VdbeGetOp(v
, 0);
2620 iEnd
= sqlite3VdbeCurrentAddr(v
);
2621 for(iAddr
=0; iAddr
<iEnd
; iAddr
++){
2622 if( aOp
[iAddr
].opcode
==OP_SqlExec
) aOp
[iAddr
].p2
= nLimit
;
2629 ** PRAGMA busy_timeout
2630 ** PRAGMA busy_timeout = N
2632 ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
2633 ** if one is set. If no busy handler or a different busy handler is set
2634 ** then 0 is returned. Setting the busy_timeout to 0 or negative
2635 ** disables the timeout.
2637 /*case PragTyp_BUSY_TIMEOUT*/ default: {
2638 assert( pPragma
->ePragTyp
==PragTyp_BUSY_TIMEOUT
);
2640 sqlite3_busy_timeout(db
, sqlite3Atoi(zRight
));
2642 returnSingleInt(v
, db
->busyTimeout
);
2647 ** PRAGMA soft_heap_limit
2648 ** PRAGMA soft_heap_limit = N
2650 ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
2651 ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
2652 ** specified and is a non-negative integer.
2653 ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
2654 ** returns the same integer that would be returned by the
2655 ** sqlite3_soft_heap_limit64(-1) C-language function.
2657 case PragTyp_SOFT_HEAP_LIMIT
: {
2659 if( zRight
&& sqlite3DecOrHexToI64(zRight
, &N
)==SQLITE_OK
){
2660 sqlite3_soft_heap_limit64(N
);
2662 returnSingleInt(v
, sqlite3_soft_heap_limit64(-1));
2667 ** PRAGMA hard_heap_limit
2668 ** PRAGMA hard_heap_limit = N
2670 ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap
2671 ** limit. The hard heap limit can be activated or lowered by this
2672 ** pragma, but not raised or deactivated. Only the
2673 ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate
2674 ** the hard heap limit. This allows an application to set a heap limit
2675 ** constraint that cannot be relaxed by an untrusted SQL script.
2677 case PragTyp_HARD_HEAP_LIMIT
: {
2679 if( zRight
&& sqlite3DecOrHexToI64(zRight
, &N
)==SQLITE_OK
){
2680 sqlite3_int64 iPrior
= sqlite3_hard_heap_limit64(-1);
2681 if( N
>0 && (iPrior
==0 || iPrior
>N
) ) sqlite3_hard_heap_limit64(N
);
2683 returnSingleInt(v
, sqlite3_hard_heap_limit64(-1));
2689 ** PRAGMA threads = N
2691 ** Configure the maximum number of worker threads. Return the new
2692 ** maximum, which might be less than requested.
2694 case PragTyp_THREADS
: {
2697 && sqlite3DecOrHexToI64(zRight
, &N
)==SQLITE_OK
2700 sqlite3_limit(db
, SQLITE_LIMIT_WORKER_THREADS
, (int)(N
&0x7fffffff));
2702 returnSingleInt(v
, sqlite3_limit(db
, SQLITE_LIMIT_WORKER_THREADS
, -1));
2707 ** PRAGMA analysis_limit
2708 ** PRAGMA analysis_limit = N
2710 ** Configure the maximum number of rows that ANALYZE will examine
2711 ** in each index that it looks at. Return the new limit.
2713 case PragTyp_ANALYSIS_LIMIT
: {
2716 && sqlite3DecOrHexToI64(zRight
, &N
)==SQLITE_OK
/* IMP: R-40975-20399 */
2719 db
->nAnalysisLimit
= (int)(N
&0x7fffffff);
2721 returnSingleInt(v
, db
->nAnalysisLimit
); /* IMP: R-57594-65522 */
2725 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
2727 ** Report the current state of file logs for all databases
2729 case PragTyp_LOCK_STATUS
: {
2730 static const char *const azLockName
[] = {
2731 "unlocked", "shared", "reserved", "pending", "exclusive"
2735 for(i
=0; i
<db
->nDb
; i
++){
2737 const char *zState
= "unknown";
2739 if( db
->aDb
[i
].zDbSName
==0 ) continue;
2740 pBt
= db
->aDb
[i
].pBt
;
2741 if( pBt
==0 || sqlite3BtreePager(pBt
)==0 ){
2743 }else if( sqlite3_file_control(db
, i
? db
->aDb
[i
].zDbSName
: 0,
2744 SQLITE_FCNTL_LOCKSTATE
, &j
)==SQLITE_OK
){
2745 zState
= azLockName
[j
];
2747 sqlite3VdbeMultiLoad(v
, 1, "ss", db
->aDb
[i
].zDbSName
, zState
);
2753 /* BEGIN SQLCIPHER */
2754 #ifdef SQLITE_HAS_CODEC
2756 ** ---------- ------
2767 const char *zKey
= zRight
;
2769 if( pPragma
->iArg
==2 || pPragma
->iArg
==3 ){
2772 for(i
=0, iByte
=0; i
<sizeof(zBuf
)*2 && sqlite3Isxdigit(zRight
[i
]); i
++){
2773 iByte
= (iByte
<<4) + sqlite3HexToInt(zRight
[i
]);
2774 if( (i
&1)!=0 ) zBuf
[i
/2] = iByte
;
2779 n
= pPragma
->iArg
<4 ? sqlite3Strlen30(zRight
) : -1;
2781 if( (pPragma
->iArg
& 1)==0 ){
2782 rc
= sqlite3_key_v2(db
, zDb
, zKey
, n
);
2784 rc
= sqlite3_rekey_v2(db
, zDb
, zKey
, n
);
2786 if( rc
==SQLITE_OK
&& n
!=0 ){
2787 sqlite3VdbeSetNumCols(v
, 1);
2788 sqlite3VdbeSetColName(v
, 0, COLNAME_NAME
, "ok", SQLITE_STATIC
);
2789 returnSingleText(v
, "ok");
2791 sqlite3ErrorMsg(pParse
, "An error occurred with PRAGMA key or rekey. "
2792 "PRAGMA key requires a key of one or more characters. "
2793 "PRAGMA rekey can only be run on an existing encrypted database. "
2794 "Use sqlcipher_export() and ATTACH to convert encrypted/plaintext databases.");
2802 #if defined(SQLITE_ENABLE_CEROD)
2803 case PragTyp_ACTIVATE_EXTENSIONS
: if( zRight
){
2804 if( sqlite3StrNICmp(zRight
, "cerod-", 6)==0 ){
2805 sqlite3_activate_cerod(&zRight
[6]);
2811 } /* End of the PRAGMA switch */
2813 /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
2814 ** purpose is to execute assert() statements to verify that if the
2815 ** PragFlg_NoColumns1 flag is set and the caller specified an argument
2816 ** to the PRAGMA, the implementation has not added any OP_ResultRow
2817 ** instructions to the VM. */
2818 if( (pPragma
->mPragFlg
& PragFlg_NoColumns1
) && zRight
){
2819 sqlite3VdbeVerifyNoResultRow(v
);
2823 sqlite3DbFree(db
, zLeft
);
2824 sqlite3DbFree(db
, zRight
);
2826 #ifndef SQLITE_OMIT_VIRTUALTABLE
2827 /*****************************************************************************
2828 ** Implementation of an eponymous virtual table that runs a pragma.
2831 typedef struct PragmaVtab PragmaVtab
;
2832 typedef struct PragmaVtabCursor PragmaVtabCursor
;
2834 sqlite3_vtab base
; /* Base class. Must be first */
2835 sqlite3
*db
; /* The database connection to which it belongs */
2836 const PragmaName
*pName
; /* Name of the pragma */
2837 u8 nHidden
; /* Number of hidden columns */
2838 u8 iHidden
; /* Index of the first hidden column */
2840 struct PragmaVtabCursor
{
2841 sqlite3_vtab_cursor base
; /* Base class. Must be first */
2842 sqlite3_stmt
*pPragma
; /* The pragma statement to run */
2843 sqlite_int64 iRowid
; /* Current rowid */
2844 char *azArg
[2]; /* Value of the argument and schema */
2848 ** Pragma virtual table module xConnect method.
2850 static int pragmaVtabConnect(
2853 int argc
, const char *const*argv
,
2854 sqlite3_vtab
**ppVtab
,
2857 const PragmaName
*pPragma
= (const PragmaName
*)pAux
;
2858 PragmaVtab
*pTab
= 0;
2865 UNUSED_PARAMETER(argc
);
2866 UNUSED_PARAMETER(argv
);
2867 sqlite3StrAccumInit(&acc
, 0, zBuf
, sizeof(zBuf
), 0);
2868 sqlite3_str_appendall(&acc
, "CREATE TABLE x");
2869 for(i
=0, j
=pPragma
->iPragCName
; i
<pPragma
->nPragCName
; i
++, j
++){
2870 sqlite3_str_appendf(&acc
, "%c\"%s\"", cSep
, pragCName
[j
]);
2874 sqlite3_str_appendf(&acc
, "(\"%s\"", pPragma
->zName
);
2878 if( pPragma
->mPragFlg
& PragFlg_Result1
){
2879 sqlite3_str_appendall(&acc
, ",arg HIDDEN");
2882 if( pPragma
->mPragFlg
& (PragFlg_SchemaOpt
|PragFlg_SchemaReq
) ){
2883 sqlite3_str_appendall(&acc
, ",schema HIDDEN");
2886 sqlite3_str_append(&acc
, ")", 1);
2887 sqlite3StrAccumFinish(&acc
);
2888 assert( strlen(zBuf
) < sizeof(zBuf
)-1 );
2889 rc
= sqlite3_declare_vtab(db
, zBuf
);
2890 if( rc
==SQLITE_OK
){
2891 pTab
= (PragmaVtab
*)sqlite3_malloc(sizeof(PragmaVtab
));
2895 memset(pTab
, 0, sizeof(PragmaVtab
));
2896 pTab
->pName
= pPragma
;
2902 *pzErr
= sqlite3_mprintf("%s", sqlite3_errmsg(db
));
2905 *ppVtab
= (sqlite3_vtab
*)pTab
;
2910 ** Pragma virtual table module xDisconnect method.
2912 static int pragmaVtabDisconnect(sqlite3_vtab
*pVtab
){
2913 PragmaVtab
*pTab
= (PragmaVtab
*)pVtab
;
2918 /* Figure out the best index to use to search a pragma virtual table.
2920 ** There are not really any index choices. But we want to encourage the
2921 ** query planner to give == constraints on as many hidden parameters as
2922 ** possible, and especially on the first hidden parameter. So return a
2923 ** high cost if hidden parameters are unconstrained.
2925 static int pragmaVtabBestIndex(sqlite3_vtab
*tab
, sqlite3_index_info
*pIdxInfo
){
2926 PragmaVtab
*pTab
= (PragmaVtab
*)tab
;
2927 const struct sqlite3_index_constraint
*pConstraint
;
2931 pIdxInfo
->estimatedCost
= (double)1;
2932 if( pTab
->nHidden
==0 ){ return SQLITE_OK
; }
2933 pConstraint
= pIdxInfo
->aConstraint
;
2936 for(i
=0; i
<pIdxInfo
->nConstraint
; i
++, pConstraint
++){
2937 if( pConstraint
->iColumn
< pTab
->iHidden
) continue;
2938 if( pConstraint
->op
!=SQLITE_INDEX_CONSTRAINT_EQ
) continue;
2939 if( pConstraint
->usable
==0 ) return SQLITE_CONSTRAINT
;
2940 j
= pConstraint
->iColumn
- pTab
->iHidden
;
2945 pIdxInfo
->estimatedCost
= (double)2147483647;
2946 pIdxInfo
->estimatedRows
= 2147483647;
2950 pIdxInfo
->aConstraintUsage
[j
].argvIndex
= 1;
2951 pIdxInfo
->aConstraintUsage
[j
].omit
= 1;
2952 pIdxInfo
->estimatedCost
= (double)20;
2953 pIdxInfo
->estimatedRows
= 20;
2956 pIdxInfo
->aConstraintUsage
[j
].argvIndex
= 2;
2957 pIdxInfo
->aConstraintUsage
[j
].omit
= 1;
2962 /* Create a new cursor for the pragma virtual table */
2963 static int pragmaVtabOpen(sqlite3_vtab
*pVtab
, sqlite3_vtab_cursor
**ppCursor
){
2964 PragmaVtabCursor
*pCsr
;
2965 pCsr
= (PragmaVtabCursor
*)sqlite3_malloc(sizeof(*pCsr
));
2966 if( pCsr
==0 ) return SQLITE_NOMEM
;
2967 memset(pCsr
, 0, sizeof(PragmaVtabCursor
));
2968 pCsr
->base
.pVtab
= pVtab
;
2969 *ppCursor
= &pCsr
->base
;
2973 /* Clear all content from pragma virtual table cursor. */
2974 static void pragmaVtabCursorClear(PragmaVtabCursor
*pCsr
){
2976 sqlite3_finalize(pCsr
->pPragma
);
2979 for(i
=0; i
<ArraySize(pCsr
->azArg
); i
++){
2980 sqlite3_free(pCsr
->azArg
[i
]);
2985 /* Close a pragma virtual table cursor */
2986 static int pragmaVtabClose(sqlite3_vtab_cursor
*cur
){
2987 PragmaVtabCursor
*pCsr
= (PragmaVtabCursor
*)cur
;
2988 pragmaVtabCursorClear(pCsr
);
2993 /* Advance the pragma virtual table cursor to the next row */
2994 static int pragmaVtabNext(sqlite3_vtab_cursor
*pVtabCursor
){
2995 PragmaVtabCursor
*pCsr
= (PragmaVtabCursor
*)pVtabCursor
;
2998 /* Increment the xRowid value */
3000 assert( pCsr
->pPragma
);
3001 if( SQLITE_ROW
!=sqlite3_step(pCsr
->pPragma
) ){
3002 rc
= sqlite3_finalize(pCsr
->pPragma
);
3004 pragmaVtabCursorClear(pCsr
);
3010 ** Pragma virtual table module xFilter method.
3012 static int pragmaVtabFilter(
3013 sqlite3_vtab_cursor
*pVtabCursor
,
3014 int idxNum
, const char *idxStr
,
3015 int argc
, sqlite3_value
**argv
3017 PragmaVtabCursor
*pCsr
= (PragmaVtabCursor
*)pVtabCursor
;
3018 PragmaVtab
*pTab
= (PragmaVtab
*)(pVtabCursor
->pVtab
);
3024 UNUSED_PARAMETER(idxNum
);
3025 UNUSED_PARAMETER(idxStr
);
3026 pragmaVtabCursorClear(pCsr
);
3027 j
= (pTab
->pName
->mPragFlg
& PragFlg_Result1
)!=0 ? 0 : 1;
3028 for(i
=0; i
<argc
; i
++, j
++){
3029 const char *zText
= (const char*)sqlite3_value_text(argv
[i
]);
3030 assert( j
<ArraySize(pCsr
->azArg
) );
3031 assert( pCsr
->azArg
[j
]==0 );
3033 pCsr
->azArg
[j
] = sqlite3_mprintf("%s", zText
);
3034 if( pCsr
->azArg
[j
]==0 ){
3035 return SQLITE_NOMEM
;
3039 sqlite3StrAccumInit(&acc
, 0, 0, 0, pTab
->db
->aLimit
[SQLITE_LIMIT_SQL_LENGTH
]);
3040 sqlite3_str_appendall(&acc
, "PRAGMA ");
3041 if( pCsr
->azArg
[1] ){
3042 sqlite3_str_appendf(&acc
, "%Q.", pCsr
->azArg
[1]);
3044 sqlite3_str_appendall(&acc
, pTab
->pName
->zName
);
3045 if( pCsr
->azArg
[0] ){
3046 sqlite3_str_appendf(&acc
, "=%Q", pCsr
->azArg
[0]);
3048 zSql
= sqlite3StrAccumFinish(&acc
);
3049 if( zSql
==0 ) return SQLITE_NOMEM
;
3050 rc
= sqlite3_prepare_v2(pTab
->db
, zSql
, -1, &pCsr
->pPragma
, 0);
3052 if( rc
!=SQLITE_OK
){
3053 pTab
->base
.zErrMsg
= sqlite3_mprintf("%s", sqlite3_errmsg(pTab
->db
));
3056 return pragmaVtabNext(pVtabCursor
);
3060 ** Pragma virtual table module xEof method.
3062 static int pragmaVtabEof(sqlite3_vtab_cursor
*pVtabCursor
){
3063 PragmaVtabCursor
*pCsr
= (PragmaVtabCursor
*)pVtabCursor
;
3064 return (pCsr
->pPragma
==0);
3067 /* The xColumn method simply returns the corresponding column from
3070 static int pragmaVtabColumn(
3071 sqlite3_vtab_cursor
*pVtabCursor
,
3072 sqlite3_context
*ctx
,
3075 PragmaVtabCursor
*pCsr
= (PragmaVtabCursor
*)pVtabCursor
;
3076 PragmaVtab
*pTab
= (PragmaVtab
*)(pVtabCursor
->pVtab
);
3077 if( i
<pTab
->iHidden
){
3078 sqlite3_result_value(ctx
, sqlite3_column_value(pCsr
->pPragma
, i
));
3080 sqlite3_result_text(ctx
, pCsr
->azArg
[i
-pTab
->iHidden
],-1,SQLITE_TRANSIENT
);
3086 ** Pragma virtual table module xRowid method.
3088 static int pragmaVtabRowid(sqlite3_vtab_cursor
*pVtabCursor
, sqlite_int64
*p
){
3089 PragmaVtabCursor
*pCsr
= (PragmaVtabCursor
*)pVtabCursor
;
3094 /* The pragma virtual table object */
3095 static const sqlite3_module pragmaVtabModule
= {
3097 0, /* xCreate - create a table */
3098 pragmaVtabConnect
, /* xConnect - connect to an existing table */
3099 pragmaVtabBestIndex
, /* xBestIndex - Determine search strategy */
3100 pragmaVtabDisconnect
, /* xDisconnect - Disconnect from a table */
3101 0, /* xDestroy - Drop a table */
3102 pragmaVtabOpen
, /* xOpen - open a cursor */
3103 pragmaVtabClose
, /* xClose - close a cursor */
3104 pragmaVtabFilter
, /* xFilter - configure scan constraints */
3105 pragmaVtabNext
, /* xNext - advance a cursor */
3106 pragmaVtabEof
, /* xEof */
3107 pragmaVtabColumn
, /* xColumn - read data */
3108 pragmaVtabRowid
, /* xRowid - read data */
3109 0, /* xUpdate - write data */
3110 0, /* xBegin - begin transaction */
3111 0, /* xSync - sync transaction */
3112 0, /* xCommit - commit transaction */
3113 0, /* xRollback - rollback transaction */
3114 0, /* xFindFunction - function overloading */
3115 0, /* xRename - rename the table */
3118 0, /* xRollbackTo */
3119 0, /* xShadowName */
3124 ** Check to see if zTabName is really the name of a pragma. If it is,
3125 ** then register an eponymous virtual table for that pragma and return
3126 ** a pointer to the Module object for the new virtual table.
3128 Module
*sqlite3PragmaVtabRegister(sqlite3
*db
, const char *zName
){
3129 const PragmaName
*pName
;
3130 assert( sqlite3_strnicmp(zName
, "pragma_", 7)==0 );
3131 pName
= pragmaLocate(zName
+7);
3132 if( pName
==0 ) return 0;
3133 if( (pName
->mPragFlg
& (PragFlg_Result0
|PragFlg_Result1
))==0 ) return 0;
3134 assert( sqlite3HashFind(&db
->aModule
, zName
)==0 );
3135 return sqlite3VtabCreateModule(db
, zName
, &pragmaVtabModule
, (void*)pName
, 0);
3138 #endif /* SQLITE_OMIT_VIRTUALTABLE */
3140 #endif /* SQLITE_OMIT_PRAGMA */