Snapshot of upstream SQLite 3.45.3
[sqlcipher.git] / src / pragma.c
blob0a687320104bb4ab4b82a2e210410f45407fc59c
1 /*
2 ** 2003 April 6
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains code used to implement the PRAGMA command.
14 #include "sqliteInt.h"
16 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
17 # if defined(__APPLE__)
18 # define SQLITE_ENABLE_LOCKING_STYLE 1
19 # else
20 # define SQLITE_ENABLE_LOCKING_STYLE 0
21 # endif
22 #endif
24 /***************************************************************************
25 ** The "pragma.h" include file is an automatically generated file that
26 ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
27 ** object. This ensures that the aPragmaName[] table is arranged in
28 ** lexicographical order to facility a binary search of the pragma name.
29 ** Do not edit pragma.h directly. Edit and rerun the script in at
30 ** ../tool/mkpragmatab.tcl. */
31 #include "pragma.h"
34 ** Interpret the given string as a safety level. Return 0 for OFF,
35 ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
36 ** unrecognized string argument. The FULL and EXTRA option is disallowed
37 ** if the omitFull parameter it 1.
39 ** Note that the values returned are one less that the values that
40 ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
41 ** to support legacy SQL code. The safety level used to be boolean
42 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
44 static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
45 /* 123456789 123456789 123 */
46 static const char zText[] = "onoffalseyestruextrafull";
47 static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20};
48 static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4};
49 static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2};
50 /* on no off false yes true extra full */
51 int i, n;
52 if( sqlite3Isdigit(*z) ){
53 return (u8)sqlite3Atoi(z);
55 n = sqlite3Strlen30(z);
56 for(i=0; i<ArraySize(iLength); i++){
57 if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
58 && (!omitFull || iValue[i]<=1)
60 return iValue[i];
63 return dflt;
67 ** Interpret the given string as a boolean value.
69 u8 sqlite3GetBoolean(const char *z, u8 dflt){
70 return getSafetyLevel(z,1,dflt)!=0;
73 /* The sqlite3GetBoolean() function is used by other modules but the
74 ** remainder of this file is specific to PRAGMA processing. So omit
75 ** the rest of the file if PRAGMAs are omitted from the build.
77 #if !defined(SQLITE_OMIT_PRAGMA)
80 ** Interpret the given string as a locking mode value.
82 static int getLockingMode(const char *z){
83 if( z ){
84 if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
85 if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
87 return PAGER_LOCKINGMODE_QUERY;
90 #ifndef SQLITE_OMIT_AUTOVACUUM
92 ** Interpret the given string as an auto-vacuum mode value.
94 ** The following strings, "none", "full" and "incremental" are
95 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
97 static int getAutoVacuum(const char *z){
98 int i;
99 if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
100 if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
101 if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
102 i = sqlite3Atoi(z);
103 return (u8)((i>=0&&i<=2)?i:0);
105 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
107 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
109 ** Interpret the given string as a temp db location. Return 1 for file
110 ** backed temporary databases, 2 for the Red-Black tree in memory database
111 ** and 0 to use the compile-time default.
113 static int getTempStore(const char *z){
114 if( z[0]>='0' && z[0]<='2' ){
115 return z[0] - '0';
116 }else if( sqlite3StrICmp(z, "file")==0 ){
117 return 1;
118 }else if( sqlite3StrICmp(z, "memory")==0 ){
119 return 2;
120 }else{
121 return 0;
124 #endif /* SQLITE_PAGER_PRAGMAS */
126 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
128 ** Invalidate temp storage, either when the temp storage is changed
129 ** from default, or when 'file' and the temp_store_directory has changed
131 static int invalidateTempStorage(Parse *pParse){
132 sqlite3 *db = pParse->db;
133 if( db->aDb[1].pBt!=0 ){
134 if( !db->autoCommit
135 || sqlite3BtreeTxnState(db->aDb[1].pBt)!=SQLITE_TXN_NONE
137 sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
138 "from within a transaction");
139 return SQLITE_ERROR;
141 sqlite3BtreeClose(db->aDb[1].pBt);
142 db->aDb[1].pBt = 0;
143 sqlite3ResetAllSchemasOfConnection(db);
145 return SQLITE_OK;
147 #endif /* SQLITE_PAGER_PRAGMAS */
149 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
151 ** If the TEMP database is open, close it and mark the database schema
152 ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
153 ** or DEFAULT_TEMP_STORE pragmas.
155 static int changeTempStorage(Parse *pParse, const char *zStorageType){
156 int ts = getTempStore(zStorageType);
157 sqlite3 *db = pParse->db;
158 if( db->temp_store==ts ) return SQLITE_OK;
159 if( invalidateTempStorage( pParse ) != SQLITE_OK ){
160 return SQLITE_ERROR;
162 db->temp_store = (u8)ts;
163 return SQLITE_OK;
165 #endif /* SQLITE_PAGER_PRAGMAS */
168 ** Set result column names for a pragma.
170 static void setPragmaResultColumnNames(
171 Vdbe *v, /* The query under construction */
172 const PragmaName *pPragma /* The pragma */
174 u8 n = pPragma->nPragCName;
175 sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
176 if( n==0 ){
177 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
178 }else{
179 int i, j;
180 for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
181 sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
187 ** Generate code to return a single integer value.
189 static void returnSingleInt(Vdbe *v, i64 value){
190 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
191 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
195 ** Generate code to return a single text value.
197 static void returnSingleText(
198 Vdbe *v, /* Prepared statement under construction */
199 const char *zValue /* Value to be returned */
201 if( zValue ){
202 sqlite3VdbeLoadString(v, 1, (const char*)zValue);
203 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
209 ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
210 ** set these values for all pagers.
212 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
213 static void setAllPagerFlags(sqlite3 *db){
214 if( db->autoCommit ){
215 Db *pDb = db->aDb;
216 int n = db->nDb;
217 assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
218 assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
219 assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
220 assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
221 == PAGER_FLAGS_MASK );
222 assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
223 while( (n--) > 0 ){
224 if( pDb->pBt ){
225 sqlite3BtreeSetPagerFlags(pDb->pBt,
226 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
228 pDb++;
232 #else
233 # define setAllPagerFlags(X) /* no-op */
234 #endif
238 ** Return a human-readable name for a constraint resolution action.
240 #ifndef SQLITE_OMIT_FOREIGN_KEY
241 static const char *actionName(u8 action){
242 const char *zName;
243 switch( action ){
244 case OE_SetNull: zName = "SET NULL"; break;
245 case OE_SetDflt: zName = "SET DEFAULT"; break;
246 case OE_Cascade: zName = "CASCADE"; break;
247 case OE_Restrict: zName = "RESTRICT"; break;
248 default: zName = "NO ACTION";
249 assert( action==OE_None ); break;
251 return zName;
253 #endif
257 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
258 ** defined in pager.h. This function returns the associated lowercase
259 ** journal-mode name.
261 const char *sqlite3JournalModename(int eMode){
262 static char * const azModeName[] = {
263 "delete", "persist", "off", "truncate", "memory"
264 #ifndef SQLITE_OMIT_WAL
265 , "wal"
266 #endif
268 assert( PAGER_JOURNALMODE_DELETE==0 );
269 assert( PAGER_JOURNALMODE_PERSIST==1 );
270 assert( PAGER_JOURNALMODE_OFF==2 );
271 assert( PAGER_JOURNALMODE_TRUNCATE==3 );
272 assert( PAGER_JOURNALMODE_MEMORY==4 );
273 assert( PAGER_JOURNALMODE_WAL==5 );
274 assert( eMode>=0 && eMode<=ArraySize(azModeName) );
276 if( eMode==ArraySize(azModeName) ) return 0;
277 return azModeName[eMode];
281 ** Locate a pragma in the aPragmaName[] array.
283 static const PragmaName *pragmaLocate(const char *zName){
284 int upr, lwr, mid = 0, rc;
285 lwr = 0;
286 upr = ArraySize(aPragmaName)-1;
287 while( lwr<=upr ){
288 mid = (lwr+upr)/2;
289 rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
290 if( rc==0 ) break;
291 if( rc<0 ){
292 upr = mid - 1;
293 }else{
294 lwr = mid + 1;
297 return lwr>upr ? 0 : &aPragmaName[mid];
301 ** Create zero or more entries in the output for the SQL functions
302 ** defined by FuncDef p.
304 static void pragmaFunclistLine(
305 Vdbe *v, /* The prepared statement being created */
306 FuncDef *p, /* A particular function definition */
307 int isBuiltin, /* True if this is a built-in function */
308 int showInternFuncs /* True if showing internal functions */
310 u32 mask =
311 SQLITE_DETERMINISTIC |
312 SQLITE_DIRECTONLY |
313 SQLITE_SUBTYPE |
314 SQLITE_INNOCUOUS |
315 SQLITE_FUNC_INTERNAL
317 if( showInternFuncs ) mask = 0xffffffff;
318 for(; p; p=p->pNext){
319 const char *zType;
320 static const char *azEnc[] = { 0, "utf8", "utf16le", "utf16be" };
322 assert( SQLITE_FUNC_ENCMASK==0x3 );
323 assert( strcmp(azEnc[SQLITE_UTF8],"utf8")==0 );
324 assert( strcmp(azEnc[SQLITE_UTF16LE],"utf16le")==0 );
325 assert( strcmp(azEnc[SQLITE_UTF16BE],"utf16be")==0 );
327 if( p->xSFunc==0 ) continue;
328 if( (p->funcFlags & SQLITE_FUNC_INTERNAL)!=0
329 && showInternFuncs==0
331 continue;
333 if( p->xValue!=0 ){
334 zType = "w";
335 }else if( p->xFinalize!=0 ){
336 zType = "a";
337 }else{
338 zType = "s";
340 sqlite3VdbeMultiLoad(v, 1, "sissii",
341 p->zName, isBuiltin,
342 zType, azEnc[p->funcFlags&SQLITE_FUNC_ENCMASK],
343 p->nArg,
344 (p->funcFlags & mask) ^ SQLITE_INNOCUOUS
351 ** Helper subroutine for PRAGMA integrity_check:
353 ** Generate code to output a single-column result row with a value of the
354 ** string held in register 3. Decrement the result count in register 1
355 ** and halt if the maximum number of result rows have been issued.
357 static int integrityCheckResultRow(Vdbe *v){
358 int addr;
359 sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
360 addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
361 VdbeCoverage(v);
362 sqlite3VdbeAddOp0(v, OP_Halt);
363 return addr;
367 ** Process a pragma statement.
369 ** Pragmas are of this form:
371 ** PRAGMA [schema.]id [= value]
373 ** The identifier might also be a string. The value is a string, and
374 ** identifier, or a number. If minusFlag is true, then the value is
375 ** a number that was preceded by a minus sign.
377 ** If the left side is "database.id" then pId1 is the database name
378 ** and pId2 is the id. If the left side is just "id" then pId1 is the
379 ** id and pId2 is any empty string.
381 void sqlite3Pragma(
382 Parse *pParse,
383 Token *pId1, /* First part of [schema.]id field */
384 Token *pId2, /* Second part of [schema.]id field, or NULL */
385 Token *pValue, /* Token for <value>, or NULL */
386 int minusFlag /* True if a '-' sign preceded <value> */
388 char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
389 char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
390 const char *zDb = 0; /* The database name */
391 Token *pId; /* Pointer to <id> token */
392 char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
393 int iDb; /* Database index for <database> */
394 int rc; /* return value form SQLITE_FCNTL_PRAGMA */
395 sqlite3 *db = pParse->db; /* The database connection */
396 Db *pDb; /* The specific database being pragmaed */
397 Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
398 const PragmaName *pPragma; /* The pragma */
400 if( v==0 ) return;
401 sqlite3VdbeRunOnlyOnce(v);
402 pParse->nMem = 2;
404 /* Interpret the [schema.] part of the pragma statement. iDb is the
405 ** index of the database this pragma is being applied to in db.aDb[]. */
406 iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
407 if( iDb<0 ) return;
408 pDb = &db->aDb[iDb];
410 /* If the temp database has been explicitly named as part of the
411 ** pragma, make sure it is open.
413 if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
414 return;
417 zLeft = sqlite3NameFromToken(db, pId);
418 if( !zLeft ) return;
419 if( minusFlag ){
420 zRight = sqlite3MPrintf(db, "-%T", pValue);
421 }else{
422 zRight = sqlite3NameFromToken(db, pValue);
425 assert( pId2 );
426 zDb = pId2->n>0 ? pDb->zDbSName : 0;
427 if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
428 goto pragma_out;
431 /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
432 ** connection. If it returns SQLITE_OK, then assume that the VFS
433 ** handled the pragma and generate a no-op prepared statement.
435 ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
436 ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
437 ** object corresponding to the database file to which the pragma
438 ** statement refers.
440 ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
441 ** file control is an array of pointers to strings (char**) in which the
442 ** second element of the array is the name of the pragma and the third
443 ** element is the argument to the pragma or NULL if the pragma has no
444 ** argument.
446 aFcntl[0] = 0;
447 aFcntl[1] = zLeft;
448 aFcntl[2] = zRight;
449 aFcntl[3] = 0;
450 db->busyHandler.nBusy = 0;
451 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
452 if( rc==SQLITE_OK ){
453 sqlite3VdbeSetNumCols(v, 1);
454 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
455 returnSingleText(v, aFcntl[0]);
456 sqlite3_free(aFcntl[0]);
457 goto pragma_out;
459 if( rc!=SQLITE_NOTFOUND ){
460 if( aFcntl[0] ){
461 sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
462 sqlite3_free(aFcntl[0]);
464 pParse->nErr++;
465 pParse->rc = rc;
466 goto pragma_out;
469 /* Locate the pragma in the lookup table */
470 pPragma = pragmaLocate(zLeft);
471 if( pPragma==0 ){
472 /* IMP: R-43042-22504 No error messages are generated if an
473 ** unknown pragma is issued. */
474 goto pragma_out;
477 /* Make sure the database schema is loaded if the pragma requires that */
478 if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
479 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
482 /* Register the result column names for pragmas that return results */
483 if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
484 && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
486 setPragmaResultColumnNames(v, pPragma);
489 /* Jump to the appropriate pragma handler */
490 switch( pPragma->ePragTyp ){
492 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
494 ** PRAGMA [schema.]default_cache_size
495 ** PRAGMA [schema.]default_cache_size=N
497 ** The first form reports the current persistent setting for the
498 ** page cache size. The value returned is the maximum number of
499 ** pages in the page cache. The second form sets both the current
500 ** page cache size value and the persistent page cache size value
501 ** stored in the database file.
503 ** Older versions of SQLite would set the default cache size to a
504 ** negative number to indicate synchronous=OFF. These days, synchronous
505 ** is always on by default regardless of the sign of the default cache
506 ** size. But continue to take the absolute value of the default cache
507 ** size of historical compatibility.
509 case PragTyp_DEFAULT_CACHE_SIZE: {
510 static const int iLn = VDBE_OFFSET_LINENO(2);
511 static const VdbeOpList getCacheSize[] = {
512 { OP_Transaction, 0, 0, 0}, /* 0 */
513 { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
514 { OP_IfPos, 1, 8, 0},
515 { OP_Integer, 0, 2, 0},
516 { OP_Subtract, 1, 2, 1},
517 { OP_IfPos, 1, 8, 0},
518 { OP_Integer, 0, 1, 0}, /* 6 */
519 { OP_Noop, 0, 0, 0},
520 { OP_ResultRow, 1, 1, 0},
522 VdbeOp *aOp;
523 sqlite3VdbeUsesBtree(v, iDb);
524 if( !zRight ){
525 pParse->nMem += 2;
526 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
527 aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
528 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
529 aOp[0].p1 = iDb;
530 aOp[1].p1 = iDb;
531 aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
532 }else{
533 int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
534 sqlite3BeginWriteOperation(pParse, 0, iDb);
535 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
536 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
537 pDb->pSchema->cache_size = size;
538 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
540 break;
542 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
544 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
546 ** PRAGMA [schema.]page_size
547 ** PRAGMA [schema.]page_size=N
549 ** The first form reports the current setting for the
550 ** database page size in bytes. The second form sets the
551 ** database page size value. The value can only be set if
552 ** the database has not yet been created.
554 case PragTyp_PAGE_SIZE: {
555 Btree *pBt = pDb->pBt;
556 assert( pBt!=0 );
557 if( !zRight ){
558 int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
559 returnSingleInt(v, size);
560 }else{
561 /* Malloc may fail when setting the page-size, as there is an internal
562 ** buffer that the pager module resizes using sqlite3_realloc().
564 db->nextPagesize = sqlite3Atoi(zRight);
565 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,0,0) ){
566 sqlite3OomFault(db);
569 break;
573 ** PRAGMA [schema.]secure_delete
574 ** PRAGMA [schema.]secure_delete=ON/OFF/FAST
576 ** The first form reports the current setting for the
577 ** secure_delete flag. The second form changes the secure_delete
578 ** flag setting and reports the new value.
580 case PragTyp_SECURE_DELETE: {
581 Btree *pBt = pDb->pBt;
582 int b = -1;
583 assert( pBt!=0 );
584 if( zRight ){
585 if( sqlite3_stricmp(zRight, "fast")==0 ){
586 b = 2;
587 }else{
588 b = sqlite3GetBoolean(zRight, 0);
591 if( pId2->n==0 && b>=0 ){
592 int ii;
593 for(ii=0; ii<db->nDb; ii++){
594 sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
597 b = sqlite3BtreeSecureDelete(pBt, b);
598 returnSingleInt(v, b);
599 break;
603 ** PRAGMA [schema.]max_page_count
604 ** PRAGMA [schema.]max_page_count=N
606 ** The first form reports the current setting for the
607 ** maximum number of pages in the database file. The
608 ** second form attempts to change this setting. Both
609 ** forms return the current setting.
611 ** The absolute value of N is used. This is undocumented and might
612 ** change. The only purpose is to provide an easy way to test
613 ** the sqlite3AbsInt32() function.
615 ** PRAGMA [schema.]page_count
617 ** Return the number of pages in the specified database.
619 case PragTyp_PAGE_COUNT: {
620 int iReg;
621 i64 x = 0;
622 sqlite3CodeVerifySchema(pParse, iDb);
623 iReg = ++pParse->nMem;
624 if( sqlite3Tolower(zLeft[0])=='p' ){
625 sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
626 }else{
627 if( zRight && sqlite3DecOrHexToI64(zRight,&x)==0 ){
628 if( x<0 ) x = 0;
629 else if( x>0xfffffffe ) x = 0xfffffffe;
630 }else{
631 x = 0;
633 sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, (int)x);
635 sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
636 break;
640 ** PRAGMA [schema.]locking_mode
641 ** PRAGMA [schema.]locking_mode = (normal|exclusive)
643 case PragTyp_LOCKING_MODE: {
644 const char *zRet = "normal";
645 int eMode = getLockingMode(zRight);
647 if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
648 /* Simple "PRAGMA locking_mode;" statement. This is a query for
649 ** the current default locking mode (which may be different to
650 ** the locking-mode of the main database).
652 eMode = db->dfltLockMode;
653 }else{
654 Pager *pPager;
655 if( pId2->n==0 ){
656 /* This indicates that no database name was specified as part
657 ** of the PRAGMA command. In this case the locking-mode must be
658 ** set on all attached databases, as well as the main db file.
660 ** Also, the sqlite3.dfltLockMode variable is set so that
661 ** any subsequently attached databases also use the specified
662 ** locking mode.
664 int ii;
665 assert(pDb==&db->aDb[0]);
666 for(ii=2; ii<db->nDb; ii++){
667 pPager = sqlite3BtreePager(db->aDb[ii].pBt);
668 sqlite3PagerLockingMode(pPager, eMode);
670 db->dfltLockMode = (u8)eMode;
672 pPager = sqlite3BtreePager(pDb->pBt);
673 eMode = sqlite3PagerLockingMode(pPager, eMode);
676 assert( eMode==PAGER_LOCKINGMODE_NORMAL
677 || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
678 if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
679 zRet = "exclusive";
681 returnSingleText(v, zRet);
682 break;
686 ** PRAGMA [schema.]journal_mode
687 ** PRAGMA [schema.]journal_mode =
688 ** (delete|persist|off|truncate|memory|wal|off)
690 case PragTyp_JOURNAL_MODE: {
691 int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
692 int ii; /* Loop counter */
694 if( zRight==0 ){
695 /* If there is no "=MODE" part of the pragma, do a query for the
696 ** current mode */
697 eMode = PAGER_JOURNALMODE_QUERY;
698 }else{
699 const char *zMode;
700 int n = sqlite3Strlen30(zRight);
701 for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
702 if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
704 if( !zMode ){
705 /* If the "=MODE" part does not match any known journal mode,
706 ** then do a query */
707 eMode = PAGER_JOURNALMODE_QUERY;
709 if( eMode==PAGER_JOURNALMODE_OFF && (db->flags & SQLITE_Defensive)!=0 ){
710 /* Do not allow journal-mode "OFF" in defensive since the database
711 ** can become corrupted using ordinary SQL when the journal is off */
712 eMode = PAGER_JOURNALMODE_QUERY;
715 if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
716 /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
717 iDb = 0;
718 pId2->n = 1;
720 for(ii=db->nDb-1; ii>=0; ii--){
721 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
722 sqlite3VdbeUsesBtree(v, ii);
723 sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
726 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
727 break;
731 ** PRAGMA [schema.]journal_size_limit
732 ** PRAGMA [schema.]journal_size_limit=N
734 ** Get or set the size limit on rollback journal files.
736 case PragTyp_JOURNAL_SIZE_LIMIT: {
737 Pager *pPager = sqlite3BtreePager(pDb->pBt);
738 i64 iLimit = -2;
739 if( zRight ){
740 sqlite3DecOrHexToI64(zRight, &iLimit);
741 if( iLimit<-1 ) iLimit = -1;
743 iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
744 returnSingleInt(v, iLimit);
745 break;
748 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
751 ** PRAGMA [schema.]auto_vacuum
752 ** PRAGMA [schema.]auto_vacuum=N
754 ** Get or set the value of the database 'auto-vacuum' parameter.
755 ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
757 #ifndef SQLITE_OMIT_AUTOVACUUM
758 case PragTyp_AUTO_VACUUM: {
759 Btree *pBt = pDb->pBt;
760 assert( pBt!=0 );
761 if( !zRight ){
762 returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
763 }else{
764 int eAuto = getAutoVacuum(zRight);
765 assert( eAuto>=0 && eAuto<=2 );
766 db->nextAutovac = (u8)eAuto;
767 /* Call SetAutoVacuum() to set initialize the internal auto and
768 ** incr-vacuum flags. This is required in case this connection
769 ** creates the database file. It is important that it is created
770 ** as an auto-vacuum capable db.
772 rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
773 if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
774 /* When setting the auto_vacuum mode to either "full" or
775 ** "incremental", write the value of meta[6] in the database
776 ** file. Before writing to meta[6], check that meta[3] indicates
777 ** that this really is an auto-vacuum capable database.
779 static const int iLn = VDBE_OFFSET_LINENO(2);
780 static const VdbeOpList setMeta6[] = {
781 { OP_Transaction, 0, 1, 0}, /* 0 */
782 { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
783 { OP_If, 1, 0, 0}, /* 2 */
784 { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
785 { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */
787 VdbeOp *aOp;
788 int iAddr = sqlite3VdbeCurrentAddr(v);
789 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
790 aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
791 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
792 aOp[0].p1 = iDb;
793 aOp[1].p1 = iDb;
794 aOp[2].p2 = iAddr+4;
795 aOp[4].p1 = iDb;
796 aOp[4].p3 = eAuto - 1;
797 sqlite3VdbeUsesBtree(v, iDb);
800 break;
802 #endif
805 ** PRAGMA [schema.]incremental_vacuum(N)
807 ** Do N steps of incremental vacuuming on a database.
809 #ifndef SQLITE_OMIT_AUTOVACUUM
810 case PragTyp_INCREMENTAL_VACUUM: {
811 int iLimit = 0, addr;
812 if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
813 iLimit = 0x7fffffff;
815 sqlite3BeginWriteOperation(pParse, 0, iDb);
816 sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
817 addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
818 sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
819 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
820 sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
821 sqlite3VdbeJumpHere(v, addr);
822 break;
824 #endif
826 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
828 ** PRAGMA [schema.]cache_size
829 ** PRAGMA [schema.]cache_size=N
831 ** The first form reports the current local setting for the
832 ** page cache size. The second form sets the local
833 ** page cache size value. If N is positive then that is the
834 ** number of pages in the cache. If N is negative, then the
835 ** number of pages is adjusted so that the cache uses -N kibibytes
836 ** of memory.
838 case PragTyp_CACHE_SIZE: {
839 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
840 if( !zRight ){
841 returnSingleInt(v, pDb->pSchema->cache_size);
842 }else{
843 int size = sqlite3Atoi(zRight);
844 pDb->pSchema->cache_size = size;
845 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
847 break;
851 ** PRAGMA [schema.]cache_spill
852 ** PRAGMA cache_spill=BOOLEAN
853 ** PRAGMA [schema.]cache_spill=N
855 ** The first form reports the current local setting for the
856 ** page cache spill size. The second form turns cache spill on
857 ** or off. When turning cache spill on, the size is set to the
858 ** current cache_size. The third form sets a spill size that
859 ** may be different form the cache size.
860 ** If N is positive then that is the
861 ** number of pages in the cache. If N is negative, then the
862 ** number of pages is adjusted so that the cache uses -N kibibytes
863 ** of memory.
865 ** If the number of cache_spill pages is less then the number of
866 ** cache_size pages, no spilling occurs until the page count exceeds
867 ** the number of cache_size pages.
869 ** The cache_spill=BOOLEAN setting applies to all attached schemas,
870 ** not just the schema specified.
872 case PragTyp_CACHE_SPILL: {
873 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
874 if( !zRight ){
875 returnSingleInt(v,
876 (db->flags & SQLITE_CacheSpill)==0 ? 0 :
877 sqlite3BtreeSetSpillSize(pDb->pBt,0));
878 }else{
879 int size = 1;
880 if( sqlite3GetInt32(zRight, &size) ){
881 sqlite3BtreeSetSpillSize(pDb->pBt, size);
883 if( sqlite3GetBoolean(zRight, size!=0) ){
884 db->flags |= SQLITE_CacheSpill;
885 }else{
886 db->flags &= ~(u64)SQLITE_CacheSpill;
888 setAllPagerFlags(db);
890 break;
894 ** PRAGMA [schema.]mmap_size(N)
896 ** Used to set mapping size limit. The mapping size limit is
897 ** used to limit the aggregate size of all memory mapped regions of the
898 ** database file. If this parameter is set to zero, then memory mapping
899 ** is not used at all. If N is negative, then the default memory map
900 ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
901 ** The parameter N is measured in bytes.
903 ** This value is advisory. The underlying VFS is free to memory map
904 ** as little or as much as it wants. Except, if N is set to 0 then the
905 ** upper layers will never invoke the xFetch interfaces to the VFS.
907 case PragTyp_MMAP_SIZE: {
908 sqlite3_int64 sz;
909 #if SQLITE_MAX_MMAP_SIZE>0
910 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
911 if( zRight ){
912 int ii;
913 sqlite3DecOrHexToI64(zRight, &sz);
914 if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
915 if( pId2->n==0 ) db->szMmap = sz;
916 for(ii=db->nDb-1; ii>=0; ii--){
917 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
918 sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
922 sz = -1;
923 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
924 #else
925 sz = 0;
926 rc = SQLITE_OK;
927 #endif
928 if( rc==SQLITE_OK ){
929 returnSingleInt(v, sz);
930 }else if( rc!=SQLITE_NOTFOUND ){
931 pParse->nErr++;
932 pParse->rc = rc;
934 break;
938 ** PRAGMA temp_store
939 ** PRAGMA temp_store = "default"|"memory"|"file"
941 ** Return or set the local value of the temp_store flag. Changing
942 ** the local value does not make changes to the disk file and the default
943 ** value will be restored the next time the database is opened.
945 ** Note that it is possible for the library compile-time options to
946 ** override this setting
948 case PragTyp_TEMP_STORE: {
949 if( !zRight ){
950 returnSingleInt(v, db->temp_store);
951 }else{
952 changeTempStorage(pParse, zRight);
954 break;
958 ** PRAGMA temp_store_directory
959 ** PRAGMA temp_store_directory = ""|"directory_name"
961 ** Return or set the local value of the temp_store_directory flag. Changing
962 ** the value sets a specific directory to be used for temporary files.
963 ** Setting to a null string reverts to the default temporary directory search.
964 ** If temporary directory is changed, then invalidateTempStorage.
967 case PragTyp_TEMP_STORE_DIRECTORY: {
968 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
969 if( !zRight ){
970 returnSingleText(v, sqlite3_temp_directory);
971 }else{
972 #ifndef SQLITE_OMIT_WSD
973 if( zRight[0] ){
974 int res;
975 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
976 if( rc!=SQLITE_OK || res==0 ){
977 sqlite3ErrorMsg(pParse, "not a writable directory");
978 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
979 goto pragma_out;
982 if( SQLITE_TEMP_STORE==0
983 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
984 || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
986 invalidateTempStorage(pParse);
988 sqlite3_free(sqlite3_temp_directory);
989 if( zRight[0] ){
990 sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
991 }else{
992 sqlite3_temp_directory = 0;
994 #endif /* SQLITE_OMIT_WSD */
996 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
997 break;
1000 #if SQLITE_OS_WIN
1002 ** PRAGMA data_store_directory
1003 ** PRAGMA data_store_directory = ""|"directory_name"
1005 ** Return or set the local value of the data_store_directory flag. Changing
1006 ** the value sets a specific directory to be used for database files that
1007 ** were specified with a relative pathname. Setting to a null string reverts
1008 ** to the default database directory, which for database files specified with
1009 ** a relative path will probably be based on the current directory for the
1010 ** process. Database file specified with an absolute path are not impacted
1011 ** by this setting, regardless of its value.
1014 case PragTyp_DATA_STORE_DIRECTORY: {
1015 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
1016 if( !zRight ){
1017 returnSingleText(v, sqlite3_data_directory);
1018 }else{
1019 #ifndef SQLITE_OMIT_WSD
1020 if( zRight[0] ){
1021 int res;
1022 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
1023 if( rc!=SQLITE_OK || res==0 ){
1024 sqlite3ErrorMsg(pParse, "not a writable directory");
1025 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
1026 goto pragma_out;
1029 sqlite3_free(sqlite3_data_directory);
1030 if( zRight[0] ){
1031 sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
1032 }else{
1033 sqlite3_data_directory = 0;
1035 #endif /* SQLITE_OMIT_WSD */
1037 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
1038 break;
1040 #endif
1042 #if SQLITE_ENABLE_LOCKING_STYLE
1044 ** PRAGMA [schema.]lock_proxy_file
1045 ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
1047 ** Return or set the value of the lock_proxy_file flag. Changing
1048 ** the value sets a specific file to be used for database access locks.
1051 case PragTyp_LOCK_PROXY_FILE: {
1052 if( !zRight ){
1053 Pager *pPager = sqlite3BtreePager(pDb->pBt);
1054 char *proxy_file_path = NULL;
1055 sqlite3_file *pFile = sqlite3PagerFile(pPager);
1056 sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
1057 &proxy_file_path);
1058 returnSingleText(v, proxy_file_path);
1059 }else{
1060 Pager *pPager = sqlite3BtreePager(pDb->pBt);
1061 sqlite3_file *pFile = sqlite3PagerFile(pPager);
1062 int res;
1063 if( zRight[0] ){
1064 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
1065 zRight);
1066 } else {
1067 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
1068 NULL);
1070 if( res!=SQLITE_OK ){
1071 sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
1072 goto pragma_out;
1075 break;
1077 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
1080 ** PRAGMA [schema.]synchronous
1081 ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
1083 ** Return or set the local value of the synchronous flag. Changing
1084 ** the local value does not make changes to the disk file and the
1085 ** default value will be restored the next time the database is
1086 ** opened.
1088 case PragTyp_SYNCHRONOUS: {
1089 if( !zRight ){
1090 returnSingleInt(v, pDb->safety_level-1);
1091 }else{
1092 if( !db->autoCommit ){
1093 sqlite3ErrorMsg(pParse,
1094 "Safety level may not be changed inside a transaction");
1095 }else if( iDb!=1 ){
1096 int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
1097 if( iLevel==0 ) iLevel = 1;
1098 pDb->safety_level = iLevel;
1099 pDb->bSyncSet = 1;
1100 setAllPagerFlags(db);
1103 break;
1105 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
1107 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
1108 case PragTyp_FLAG: {
1109 if( zRight==0 ){
1110 setPragmaResultColumnNames(v, pPragma);
1111 returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
1112 }else{
1113 u64 mask = pPragma->iArg; /* Mask of bits to set or clear. */
1114 if( db->autoCommit==0 ){
1115 /* Foreign key support may not be enabled or disabled while not
1116 ** in auto-commit mode. */
1117 mask &= ~(SQLITE_ForeignKeys);
1119 #if SQLITE_USER_AUTHENTICATION
1120 if( db->auth.authLevel==UAUTH_User ){
1121 /* Do not allow non-admin users to modify the schema arbitrarily */
1122 mask &= ~(SQLITE_WriteSchema);
1124 #endif
1126 if( sqlite3GetBoolean(zRight, 0) ){
1127 if( (mask & SQLITE_WriteSchema)==0
1128 || (db->flags & SQLITE_Defensive)==0
1130 db->flags |= mask;
1132 }else{
1133 db->flags &= ~mask;
1134 if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
1135 if( (mask & SQLITE_WriteSchema)!=0
1136 && sqlite3_stricmp(zRight, "reset")==0
1138 /* IMP: R-60817-01178 If the argument is "RESET" then schema
1139 ** writing is disabled (as with "PRAGMA writable_schema=OFF") and,
1140 ** in addition, the schema is reloaded. */
1141 sqlite3ResetAllSchemasOfConnection(db);
1145 /* Many of the flag-pragmas modify the code generated by the SQL
1146 ** compiler (eg. count_changes). So add an opcode to expire all
1147 ** compiled SQL statements after modifying a pragma value.
1149 sqlite3VdbeAddOp0(v, OP_Expire);
1150 setAllPagerFlags(db);
1152 break;
1154 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
1156 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
1158 ** PRAGMA table_info(<table>)
1160 ** Return a single row for each column of the named table. The columns of
1161 ** the returned data set are:
1163 ** cid: Column id (numbered from left to right, starting at 0)
1164 ** name: Column name
1165 ** type: Column declaration type.
1166 ** notnull: True if 'NOT NULL' is part of column declaration
1167 ** dflt_value: The default value for the column, if any.
1168 ** pk: Non-zero for PK fields.
1170 case PragTyp_TABLE_INFO: if( zRight ){
1171 Table *pTab;
1172 sqlite3CodeVerifyNamedSchema(pParse, zDb);
1173 pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
1174 if( pTab ){
1175 int i, k;
1176 int nHidden = 0;
1177 Column *pCol;
1178 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
1179 pParse->nMem = 7;
1180 sqlite3ViewGetColumnNames(pParse, pTab);
1181 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
1182 int isHidden = 0;
1183 const Expr *pColExpr;
1184 if( pCol->colFlags & COLFLAG_NOINSERT ){
1185 if( pPragma->iArg==0 ){
1186 nHidden++;
1187 continue;
1189 if( pCol->colFlags & COLFLAG_VIRTUAL ){
1190 isHidden = 2; /* GENERATED ALWAYS AS ... VIRTUAL */
1191 }else if( pCol->colFlags & COLFLAG_STORED ){
1192 isHidden = 3; /* GENERATED ALWAYS AS ... STORED */
1193 }else{ assert( pCol->colFlags & COLFLAG_HIDDEN );
1194 isHidden = 1; /* HIDDEN */
1197 if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
1198 k = 0;
1199 }else if( pPk==0 ){
1200 k = 1;
1201 }else{
1202 for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
1204 pColExpr = sqlite3ColumnExpr(pTab,pCol);
1205 assert( pColExpr==0 || pColExpr->op==TK_SPAN || isHidden>=2 );
1206 assert( pColExpr==0 || !ExprHasProperty(pColExpr, EP_IntValue)
1207 || isHidden>=2 );
1208 sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
1209 i-nHidden,
1210 pCol->zCnName,
1211 sqlite3ColumnType(pCol,""),
1212 pCol->notNull ? 1 : 0,
1213 (isHidden>=2 || pColExpr==0) ? 0 : pColExpr->u.zToken,
1215 isHidden);
1219 break;
1222 ** PRAGMA table_list
1224 ** Return a single row for each table, virtual table, or view in the
1225 ** entire schema.
1227 ** schema: Name of attached database hold this table
1228 ** name: Name of the table itself
1229 ** type: "table", "view", "virtual", "shadow"
1230 ** ncol: Number of columns
1231 ** wr: True for a WITHOUT ROWID table
1232 ** strict: True for a STRICT table
1234 case PragTyp_TABLE_LIST: {
1235 int ii;
1236 pParse->nMem = 6;
1237 sqlite3CodeVerifyNamedSchema(pParse, zDb);
1238 for(ii=0; ii<db->nDb; ii++){
1239 HashElem *k;
1240 Hash *pHash;
1241 int initNCol;
1242 if( zDb && sqlite3_stricmp(zDb, db->aDb[ii].zDbSName)!=0 ) continue;
1244 /* Ensure that the Table.nCol field is initialized for all views
1245 ** and virtual tables. Each time we initialize a Table.nCol value
1246 ** for a table, that can potentially disrupt the hash table, so restart
1247 ** the initialization scan.
1249 pHash = &db->aDb[ii].pSchema->tblHash;
1250 initNCol = sqliteHashCount(pHash);
1251 while( initNCol-- ){
1252 for(k=sqliteHashFirst(pHash); 1; k=sqliteHashNext(k) ){
1253 Table *pTab;
1254 if( k==0 ){ initNCol = 0; break; }
1255 pTab = sqliteHashData(k);
1256 if( pTab->nCol==0 ){
1257 char *zSql = sqlite3MPrintf(db, "SELECT*FROM\"%w\"", pTab->zName);
1258 if( zSql ){
1259 sqlite3_stmt *pDummy = 0;
1260 (void)sqlite3_prepare(db, zSql, -1, &pDummy, 0);
1261 (void)sqlite3_finalize(pDummy);
1262 sqlite3DbFree(db, zSql);
1264 if( db->mallocFailed ){
1265 sqlite3ErrorMsg(db->pParse, "out of memory");
1266 db->pParse->rc = SQLITE_NOMEM_BKPT;
1268 pHash = &db->aDb[ii].pSchema->tblHash;
1269 break;
1274 for(k=sqliteHashFirst(pHash); k; k=sqliteHashNext(k) ){
1275 Table *pTab = sqliteHashData(k);
1276 const char *zType;
1277 if( zRight && sqlite3_stricmp(zRight, pTab->zName)!=0 ) continue;
1278 if( IsView(pTab) ){
1279 zType = "view";
1280 }else if( IsVirtual(pTab) ){
1281 zType = "virtual";
1282 }else if( pTab->tabFlags & TF_Shadow ){
1283 zType = "shadow";
1284 }else{
1285 zType = "table";
1287 sqlite3VdbeMultiLoad(v, 1, "sssiii",
1288 db->aDb[ii].zDbSName,
1289 sqlite3PreferredTableName(pTab->zName),
1290 zType,
1291 pTab->nCol,
1292 (pTab->tabFlags & TF_WithoutRowid)!=0,
1293 (pTab->tabFlags & TF_Strict)!=0
1298 break;
1300 #ifdef SQLITE_DEBUG
1301 case PragTyp_STATS: {
1302 Index *pIdx;
1303 HashElem *i;
1304 pParse->nMem = 5;
1305 sqlite3CodeVerifySchema(pParse, iDb);
1306 for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
1307 Table *pTab = sqliteHashData(i);
1308 sqlite3VdbeMultiLoad(v, 1, "ssiii",
1309 sqlite3PreferredTableName(pTab->zName),
1311 pTab->szTabRow,
1312 pTab->nRowLogEst,
1313 pTab->tabFlags);
1314 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1315 sqlite3VdbeMultiLoad(v, 2, "siiiX",
1316 pIdx->zName,
1317 pIdx->szIdxRow,
1318 pIdx->aiRowLogEst[0],
1319 pIdx->hasStat1);
1320 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
1324 break;
1325 #endif
1327 case PragTyp_INDEX_INFO: if( zRight ){
1328 Index *pIdx;
1329 Table *pTab;
1330 pIdx = sqlite3FindIndex(db, zRight, zDb);
1331 if( pIdx==0 ){
1332 /* If there is no index named zRight, check to see if there is a
1333 ** WITHOUT ROWID table named zRight, and if there is, show the
1334 ** structure of the PRIMARY KEY index for that table. */
1335 pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
1336 if( pTab && !HasRowid(pTab) ){
1337 pIdx = sqlite3PrimaryKeyIndex(pTab);
1340 if( pIdx ){
1341 int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
1342 int i;
1343 int mx;
1344 if( pPragma->iArg ){
1345 /* PRAGMA index_xinfo (newer version with more rows and columns) */
1346 mx = pIdx->nColumn;
1347 pParse->nMem = 6;
1348 }else{
1349 /* PRAGMA index_info (legacy version) */
1350 mx = pIdx->nKeyCol;
1351 pParse->nMem = 3;
1353 pTab = pIdx->pTable;
1354 sqlite3CodeVerifySchema(pParse, iIdxDb);
1355 assert( pParse->nMem<=pPragma->nPragCName );
1356 for(i=0; i<mx; i++){
1357 i16 cnum = pIdx->aiColumn[i];
1358 sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
1359 cnum<0 ? 0 : pTab->aCol[cnum].zCnName);
1360 if( pPragma->iArg ){
1361 sqlite3VdbeMultiLoad(v, 4, "isiX",
1362 pIdx->aSortOrder[i],
1363 pIdx->azColl[i],
1364 i<pIdx->nKeyCol);
1366 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
1370 break;
1372 case PragTyp_INDEX_LIST: if( zRight ){
1373 Index *pIdx;
1374 Table *pTab;
1375 int i;
1376 pTab = sqlite3FindTable(db, zRight, zDb);
1377 if( pTab ){
1378 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1379 pParse->nMem = 5;
1380 sqlite3CodeVerifySchema(pParse, iTabDb);
1381 for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
1382 const char *azOrigin[] = { "c", "u", "pk" };
1383 sqlite3VdbeMultiLoad(v, 1, "isisi",
1385 pIdx->zName,
1386 IsUniqueIndex(pIdx),
1387 azOrigin[pIdx->idxType],
1388 pIdx->pPartIdxWhere!=0);
1392 break;
1394 case PragTyp_DATABASE_LIST: {
1395 int i;
1396 pParse->nMem = 3;
1397 for(i=0; i<db->nDb; i++){
1398 if( db->aDb[i].pBt==0 ) continue;
1399 assert( db->aDb[i].zDbSName!=0 );
1400 sqlite3VdbeMultiLoad(v, 1, "iss",
1402 db->aDb[i].zDbSName,
1403 sqlite3BtreeGetFilename(db->aDb[i].pBt));
1406 break;
1408 case PragTyp_COLLATION_LIST: {
1409 int i = 0;
1410 HashElem *p;
1411 pParse->nMem = 2;
1412 for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
1413 CollSeq *pColl = (CollSeq *)sqliteHashData(p);
1414 sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
1417 break;
1419 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
1420 case PragTyp_FUNCTION_LIST: {
1421 int i;
1422 HashElem *j;
1423 FuncDef *p;
1424 int showInternFunc = (db->mDbFlags & DBFLAG_InternalFunc)!=0;
1425 pParse->nMem = 6;
1426 for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
1427 for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
1428 assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
1429 pragmaFunclistLine(v, p, 1, showInternFunc);
1432 for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
1433 p = (FuncDef*)sqliteHashData(j);
1434 assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
1435 pragmaFunclistLine(v, p, 0, showInternFunc);
1438 break;
1440 #ifndef SQLITE_OMIT_VIRTUALTABLE
1441 case PragTyp_MODULE_LIST: {
1442 HashElem *j;
1443 pParse->nMem = 1;
1444 for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
1445 Module *pMod = (Module*)sqliteHashData(j);
1446 sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
1449 break;
1450 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1452 case PragTyp_PRAGMA_LIST: {
1453 int i;
1454 for(i=0; i<ArraySize(aPragmaName); i++){
1455 sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
1458 break;
1459 #endif /* SQLITE_INTROSPECTION_PRAGMAS */
1461 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
1463 #ifndef SQLITE_OMIT_FOREIGN_KEY
1464 case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
1465 FKey *pFK;
1466 Table *pTab;
1467 pTab = sqlite3FindTable(db, zRight, zDb);
1468 if( pTab && IsOrdinaryTable(pTab) ){
1469 pFK = pTab->u.tab.pFKey;
1470 if( pFK ){
1471 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1472 int i = 0;
1473 pParse->nMem = 8;
1474 sqlite3CodeVerifySchema(pParse, iTabDb);
1475 while(pFK){
1476 int j;
1477 for(j=0; j<pFK->nCol; j++){
1478 sqlite3VdbeMultiLoad(v, 1, "iissssss",
1481 pFK->zTo,
1482 pTab->aCol[pFK->aCol[j].iFrom].zCnName,
1483 pFK->aCol[j].zCol,
1484 actionName(pFK->aAction[1]), /* ON UPDATE */
1485 actionName(pFK->aAction[0]), /* ON DELETE */
1486 "NONE");
1488 ++i;
1489 pFK = pFK->pNextFrom;
1494 break;
1495 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1497 #ifndef SQLITE_OMIT_FOREIGN_KEY
1498 #ifndef SQLITE_OMIT_TRIGGER
1499 case PragTyp_FOREIGN_KEY_CHECK: {
1500 FKey *pFK; /* A foreign key constraint */
1501 Table *pTab; /* Child table contain "REFERENCES" keyword */
1502 Table *pParent; /* Parent table that child points to */
1503 Index *pIdx; /* Index in the parent table */
1504 int i; /* Loop counter: Foreign key number for pTab */
1505 int j; /* Loop counter: Field of the foreign key */
1506 HashElem *k; /* Loop counter: Next table in schema */
1507 int x; /* result variable */
1508 int regResult; /* 3 registers to hold a result row */
1509 int regRow; /* Registers to hold a row from pTab */
1510 int addrTop; /* Top of a loop checking foreign keys */
1511 int addrOk; /* Jump here if the key is OK */
1512 int *aiCols; /* child to parent column mapping */
1514 regResult = pParse->nMem+1;
1515 pParse->nMem += 4;
1516 regRow = ++pParse->nMem;
1517 k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
1518 while( k ){
1519 if( zRight ){
1520 pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
1521 k = 0;
1522 }else{
1523 pTab = (Table*)sqliteHashData(k);
1524 k = sqliteHashNext(k);
1526 if( pTab==0 || !IsOrdinaryTable(pTab) || pTab->u.tab.pFKey==0 ) continue;
1527 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1528 zDb = db->aDb[iDb].zDbSName;
1529 sqlite3CodeVerifySchema(pParse, iDb);
1530 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
1531 sqlite3TouchRegister(pParse, pTab->nCol+regRow);
1532 sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
1533 sqlite3VdbeLoadString(v, regResult, pTab->zName);
1534 assert( IsOrdinaryTable(pTab) );
1535 for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
1536 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
1537 if( pParent==0 ) continue;
1538 pIdx = 0;
1539 sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
1540 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
1541 if( x==0 ){
1542 if( pIdx==0 ){
1543 sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
1544 }else{
1545 sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
1546 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1548 }else{
1549 k = 0;
1550 break;
1553 assert( pParse->nErr>0 || pFK==0 );
1554 if( pFK ) break;
1555 if( pParse->nTab<i ) pParse->nTab = i;
1556 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
1557 assert( IsOrdinaryTable(pTab) );
1558 for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
1559 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
1560 pIdx = 0;
1561 aiCols = 0;
1562 if( pParent ){
1563 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
1564 assert( x==0 || db->mallocFailed );
1566 addrOk = sqlite3VdbeMakeLabel(pParse);
1568 /* Generate code to read the child key values into registers
1569 ** regRow..regRow+n. If any of the child key values are NULL, this
1570 ** row cannot cause an FK violation. Jump directly to addrOk in
1571 ** this case. */
1572 sqlite3TouchRegister(pParse, regRow + pFK->nCol);
1573 for(j=0; j<pFK->nCol; j++){
1574 int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
1575 sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
1576 sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
1579 /* Generate code to query the parent index for a matching parent
1580 ** key. If a match is found, jump to addrOk. */
1581 if( pIdx ){
1582 sqlite3VdbeAddOp4(v, OP_Affinity, regRow, pFK->nCol, 0,
1583 sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
1584 sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regRow, pFK->nCol);
1585 VdbeCoverage(v);
1586 }else if( pParent ){
1587 int jmp = sqlite3VdbeCurrentAddr(v)+2;
1588 sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
1589 sqlite3VdbeGoto(v, addrOk);
1590 assert( pFK->nCol==1 || db->mallocFailed );
1593 /* Generate code to report an FK violation to the caller. */
1594 if( HasRowid(pTab) ){
1595 sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
1596 }else{
1597 sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
1599 sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
1600 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
1601 sqlite3VdbeResolveLabel(v, addrOk);
1602 sqlite3DbFree(db, aiCols);
1604 sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
1605 sqlite3VdbeJumpHere(v, addrTop);
1608 break;
1609 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
1610 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1612 #ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA
1613 /* Reinstall the LIKE and GLOB functions. The variant of LIKE
1614 ** used will be case sensitive or not depending on the RHS.
1616 case PragTyp_CASE_SENSITIVE_LIKE: {
1617 if( zRight ){
1618 sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
1621 break;
1622 #endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */
1624 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
1625 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
1626 #endif
1628 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
1629 /* PRAGMA integrity_check
1630 ** PRAGMA integrity_check(N)
1631 ** PRAGMA quick_check
1632 ** PRAGMA quick_check(N)
1634 ** Verify the integrity of the database.
1636 ** The "quick_check" is reduced version of
1637 ** integrity_check designed to detect most database corruption
1638 ** without the overhead of cross-checking indexes. Quick_check
1639 ** is linear time whereas integrity_check is O(NlogN).
1641 ** The maximum number of errors is 100 by default. A different default
1642 ** can be specified using a numeric parameter N.
1644 ** Or, the parameter N can be the name of a table. In that case, only
1645 ** the one table named is verified. The freelist is only verified if
1646 ** the named table is "sqlite_schema" (or one of its aliases).
1648 ** All schemas are checked by default. To check just a single
1649 ** schema, use the form:
1651 ** PRAGMA schema.integrity_check;
1653 case PragTyp_INTEGRITY_CHECK: {
1654 int i, j, addr, mxErr;
1655 Table *pObjTab = 0; /* Check only this one table, if not NULL */
1657 int isQuick = (sqlite3Tolower(zLeft[0])=='q');
1659 /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
1660 ** then iDb is set to the index of the database identified by <db>.
1661 ** In this case, the integrity of database iDb only is verified by
1662 ** the VDBE created below.
1664 ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
1665 ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
1666 ** to -1 here, to indicate that the VDBE should verify the integrity
1667 ** of all attached databases. */
1668 assert( iDb>=0 );
1669 assert( iDb==0 || pId2->z );
1670 if( pId2->z==0 ) iDb = -1;
1672 /* Initialize the VDBE program */
1673 pParse->nMem = 6;
1675 /* Set the maximum error count */
1676 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
1677 if( zRight ){
1678 if( sqlite3GetInt32(zRight, &mxErr) ){
1679 if( mxErr<=0 ){
1680 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
1682 }else{
1683 pObjTab = sqlite3LocateTable(pParse, 0, zRight,
1684 iDb>=0 ? db->aDb[iDb].zDbSName : 0);
1687 sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
1689 /* Do an integrity check on each database file */
1690 for(i=0; i<db->nDb; i++){
1691 HashElem *x; /* For looping over tables in the schema */
1692 Hash *pTbls; /* Set of all tables in the schema */
1693 int *aRoot; /* Array of root page numbers of all btrees */
1694 int cnt = 0; /* Number of entries in aRoot[] */
1695 int mxIdx = 0; /* Maximum number of indexes for any table */
1697 if( OMIT_TEMPDB && i==1 ) continue;
1698 if( iDb>=0 && i!=iDb ) continue;
1700 sqlite3CodeVerifySchema(pParse, i);
1701 pParse->okConstFactor = 0; /* tag-20230327-1 */
1703 /* Do an integrity check of the B-Tree
1705 ** Begin by finding the root pages numbers
1706 ** for all tables and indices in the database.
1708 assert( sqlite3SchemaMutexHeld(db, i, 0) );
1709 pTbls = &db->aDb[i].pSchema->tblHash;
1710 for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
1711 Table *pTab = sqliteHashData(x); /* Current table */
1712 Index *pIdx; /* An index on pTab */
1713 int nIdx; /* Number of indexes on pTab */
1714 if( pObjTab && pObjTab!=pTab ) continue;
1715 if( HasRowid(pTab) ) cnt++;
1716 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
1717 if( nIdx>mxIdx ) mxIdx = nIdx;
1719 if( cnt==0 ) continue;
1720 if( pObjTab ) cnt++;
1721 aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
1722 if( aRoot==0 ) break;
1723 cnt = 0;
1724 if( pObjTab ) aRoot[++cnt] = 0;
1725 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
1726 Table *pTab = sqliteHashData(x);
1727 Index *pIdx;
1728 if( pObjTab && pObjTab!=pTab ) continue;
1729 if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
1730 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1731 aRoot[++cnt] = pIdx->tnum;
1734 aRoot[0] = cnt;
1736 /* Make sure sufficient number of registers have been allocated */
1737 sqlite3TouchRegister(pParse, 8+mxIdx);
1738 sqlite3ClearTempRegCache(pParse);
1740 /* Do the b-tree integrity checks */
1741 sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
1742 sqlite3VdbeChangeP5(v, (u8)i);
1743 addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
1744 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
1745 sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
1746 P4_DYNAMIC);
1747 sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
1748 integrityCheckResultRow(v);
1749 sqlite3VdbeJumpHere(v, addr);
1751 /* Make sure all the indices are constructed correctly.
1753 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
1754 Table *pTab = sqliteHashData(x);
1755 Index *pIdx, *pPk;
1756 Index *pPrior = 0; /* Previous index */
1757 int loopTop;
1758 int iDataCur, iIdxCur;
1759 int r1 = -1;
1760 int bStrict; /* True for a STRICT table */
1761 int r2; /* Previous key for WITHOUT ROWID tables */
1762 int mxCol; /* Maximum non-virtual column number */
1764 if( pObjTab && pObjTab!=pTab ) continue;
1765 if( !IsOrdinaryTable(pTab) ) continue;
1766 if( isQuick || HasRowid(pTab) ){
1767 pPk = 0;
1768 r2 = 0;
1769 }else{
1770 pPk = sqlite3PrimaryKeyIndex(pTab);
1771 r2 = sqlite3GetTempRange(pParse, pPk->nKeyCol);
1772 sqlite3VdbeAddOp3(v, OP_Null, 1, r2, r2+pPk->nKeyCol-1);
1774 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
1775 1, 0, &iDataCur, &iIdxCur);
1776 /* reg[7] counts the number of entries in the table.
1777 ** reg[8+i] counts the number of entries in the i-th index
1779 sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
1780 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
1781 sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
1783 assert( pParse->nMem>=8+j );
1784 assert( sqlite3NoTempsInRange(pParse,1,7+j) );
1785 sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
1786 loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
1788 /* Fetch the right-most column from the table. This will cause
1789 ** the entire record header to be parsed and sanity checked. It
1790 ** will also prepopulate the cursor column cache that is used
1791 ** by the OP_IsType code, so it is a required step.
1793 assert( !IsVirtual(pTab) );
1794 if( HasRowid(pTab) ){
1795 mxCol = -1;
1796 for(j=0; j<pTab->nCol; j++){
1797 if( (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)==0 ) mxCol++;
1799 if( mxCol==pTab->iPKey ) mxCol--;
1800 }else{
1801 /* COLFLAG_VIRTUAL columns are not included in the WITHOUT ROWID
1802 ** PK index column-count, so there is no need to account for them
1803 ** in this case. */
1804 mxCol = sqlite3PrimaryKeyIndex(pTab)->nColumn-1;
1806 if( mxCol>=0 ){
1807 sqlite3VdbeAddOp3(v, OP_Column, iDataCur, mxCol, 3);
1808 sqlite3VdbeTypeofColumn(v, 3);
1811 if( !isQuick ){
1812 if( pPk ){
1813 /* Verify WITHOUT ROWID keys are in ascending order */
1814 int a1;
1815 char *zErr;
1816 a1 = sqlite3VdbeAddOp4Int(v, OP_IdxGT, iDataCur, 0,r2,pPk->nKeyCol);
1817 VdbeCoverage(v);
1818 sqlite3VdbeAddOp1(v, OP_IsNull, r2); VdbeCoverage(v);
1819 zErr = sqlite3MPrintf(db,
1820 "row not in PRIMARY KEY order for %s",
1821 pTab->zName);
1822 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1823 integrityCheckResultRow(v);
1824 sqlite3VdbeJumpHere(v, a1);
1825 sqlite3VdbeJumpHere(v, a1+1);
1826 for(j=0; j<pPk->nKeyCol; j++){
1827 sqlite3ExprCodeLoadIndexColumn(pParse, pPk, iDataCur, j, r2+j);
1831 /* Verify datatypes for all columns:
1833 ** (1) NOT NULL columns may not contain a NULL
1834 ** (2) Datatype must be exact for non-ANY columns in STRICT tables
1835 ** (3) Datatype for TEXT columns in non-STRICT tables must be
1836 ** NULL, TEXT, or BLOB.
1837 ** (4) Datatype for numeric columns in non-STRICT tables must not
1838 ** be a TEXT value that can be losslessly converted to numeric.
1840 bStrict = (pTab->tabFlags & TF_Strict)!=0;
1841 for(j=0; j<pTab->nCol; j++){
1842 char *zErr;
1843 Column *pCol = pTab->aCol + j; /* The column to be checked */
1844 int labelError; /* Jump here to report an error */
1845 int labelOk; /* Jump here if all looks ok */
1846 int p1, p3, p4; /* Operands to the OP_IsType opcode */
1847 int doTypeCheck; /* Check datatypes (besides NOT NULL) */
1849 if( j==pTab->iPKey ) continue;
1850 if( bStrict ){
1851 doTypeCheck = pCol->eCType>COLTYPE_ANY;
1852 }else{
1853 doTypeCheck = pCol->affinity>SQLITE_AFF_BLOB;
1855 if( pCol->notNull==0 && !doTypeCheck ) continue;
1857 /* Compute the operands that will be needed for OP_IsType */
1858 p4 = SQLITE_NULL;
1859 if( pCol->colFlags & COLFLAG_VIRTUAL ){
1860 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
1861 p1 = -1;
1862 p3 = 3;
1863 }else{
1864 if( pCol->iDflt ){
1865 sqlite3_value *pDfltValue = 0;
1866 sqlite3ValueFromExpr(db, sqlite3ColumnExpr(pTab,pCol), ENC(db),
1867 pCol->affinity, &pDfltValue);
1868 if( pDfltValue ){
1869 p4 = sqlite3_value_type(pDfltValue);
1870 sqlite3ValueFree(pDfltValue);
1873 p1 = iDataCur;
1874 if( !HasRowid(pTab) ){
1875 testcase( j!=sqlite3TableColumnToStorage(pTab, j) );
1876 p3 = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), j);
1877 }else{
1878 p3 = sqlite3TableColumnToStorage(pTab,j);
1879 testcase( p3!=j);
1883 labelError = sqlite3VdbeMakeLabel(pParse);
1884 labelOk = sqlite3VdbeMakeLabel(pParse);
1885 if( pCol->notNull ){
1886 /* (1) NOT NULL columns may not contain a NULL */
1887 int jmp3;
1888 int jmp2 = sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
1889 VdbeCoverage(v);
1890 if( p1<0 ){
1891 sqlite3VdbeChangeP5(v, 0x0f); /* INT, REAL, TEXT, or BLOB */
1892 jmp3 = jmp2;
1893 }else{
1894 sqlite3VdbeChangeP5(v, 0x0d); /* INT, TEXT, or BLOB */
1895 /* OP_IsType does not detect NaN values in the database file
1896 ** which should be treated as a NULL. So if the header type
1897 ** is REAL, we have to load the actual data using OP_Column
1898 ** to reliably determine if the value is a NULL. */
1899 sqlite3VdbeAddOp3(v, OP_Column, p1, p3, 3);
1900 sqlite3ColumnDefault(v, pTab, j, 3);
1901 jmp3 = sqlite3VdbeAddOp2(v, OP_NotNull, 3, labelOk);
1902 VdbeCoverage(v);
1904 zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
1905 pCol->zCnName);
1906 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1907 if( doTypeCheck ){
1908 sqlite3VdbeGoto(v, labelError);
1909 sqlite3VdbeJumpHere(v, jmp2);
1910 sqlite3VdbeJumpHere(v, jmp3);
1911 }else{
1912 /* VDBE byte code will fall thru */
1915 if( bStrict && doTypeCheck ){
1916 /* (2) Datatype must be exact for non-ANY columns in STRICT tables*/
1917 static unsigned char aStdTypeMask[] = {
1918 0x1f, /* ANY */
1919 0x18, /* BLOB */
1920 0x11, /* INT */
1921 0x11, /* INTEGER */
1922 0x13, /* REAL */
1923 0x14 /* TEXT */
1925 sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
1926 assert( pCol->eCType>=1 && pCol->eCType<=sizeof(aStdTypeMask) );
1927 sqlite3VdbeChangeP5(v, aStdTypeMask[pCol->eCType-1]);
1928 VdbeCoverage(v);
1929 zErr = sqlite3MPrintf(db, "non-%s value in %s.%s",
1930 sqlite3StdType[pCol->eCType-1],
1931 pTab->zName, pTab->aCol[j].zCnName);
1932 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1933 }else if( !bStrict && pCol->affinity==SQLITE_AFF_TEXT ){
1934 /* (3) Datatype for TEXT columns in non-STRICT tables must be
1935 ** NULL, TEXT, or BLOB. */
1936 sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
1937 sqlite3VdbeChangeP5(v, 0x1c); /* NULL, TEXT, or BLOB */
1938 VdbeCoverage(v);
1939 zErr = sqlite3MPrintf(db, "NUMERIC value in %s.%s",
1940 pTab->zName, pTab->aCol[j].zCnName);
1941 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1942 }else if( !bStrict && pCol->affinity>=SQLITE_AFF_NUMERIC ){
1943 /* (4) Datatype for numeric columns in non-STRICT tables must not
1944 ** be a TEXT value that can be converted to numeric. */
1945 sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
1946 sqlite3VdbeChangeP5(v, 0x1b); /* NULL, INT, FLOAT, or BLOB */
1947 VdbeCoverage(v);
1948 if( p1>=0 ){
1949 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
1951 sqlite3VdbeAddOp4(v, OP_Affinity, 3, 1, 0, "C", P4_STATIC);
1952 sqlite3VdbeAddOp4Int(v, OP_IsType, -1, labelOk, 3, p4);
1953 sqlite3VdbeChangeP5(v, 0x1c); /* NULL, TEXT, or BLOB */
1954 VdbeCoverage(v);
1955 zErr = sqlite3MPrintf(db, "TEXT value in %s.%s",
1956 pTab->zName, pTab->aCol[j].zCnName);
1957 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1959 sqlite3VdbeResolveLabel(v, labelError);
1960 integrityCheckResultRow(v);
1961 sqlite3VdbeResolveLabel(v, labelOk);
1963 /* Verify CHECK constraints */
1964 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
1965 ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
1966 if( db->mallocFailed==0 ){
1967 int addrCkFault = sqlite3VdbeMakeLabel(pParse);
1968 int addrCkOk = sqlite3VdbeMakeLabel(pParse);
1969 char *zErr;
1970 int k;
1971 pParse->iSelfTab = iDataCur + 1;
1972 for(k=pCheck->nExpr-1; k>0; k--){
1973 sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
1975 sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
1976 SQLITE_JUMPIFNULL);
1977 sqlite3VdbeResolveLabel(v, addrCkFault);
1978 pParse->iSelfTab = 0;
1979 zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
1980 pTab->zName);
1981 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1982 integrityCheckResultRow(v);
1983 sqlite3VdbeResolveLabel(v, addrCkOk);
1985 sqlite3ExprListDelete(db, pCheck);
1987 if( !isQuick ){ /* Omit the remaining tests for quick_check */
1988 /* Validate index entries for the current row */
1989 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
1990 int jmp2, jmp3, jmp4, jmp5, label6;
1991 int kk;
1992 int ckUniq = sqlite3VdbeMakeLabel(pParse);
1993 if( pPk==pIdx ) continue;
1994 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
1995 pPrior, r1);
1996 pPrior = pIdx;
1997 sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
1998 /* Verify that an index entry exists for the current table row */
1999 jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
2000 pIdx->nColumn); VdbeCoverage(v);
2001 sqlite3VdbeLoadString(v, 3, "row ");
2002 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
2003 sqlite3VdbeLoadString(v, 4, " missing from index ");
2004 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
2005 jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
2006 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
2007 jmp4 = integrityCheckResultRow(v);
2008 sqlite3VdbeJumpHere(v, jmp2);
2010 /* The OP_IdxRowid opcode is an optimized version of OP_Column
2011 ** that extracts the rowid off the end of the index record.
2012 ** But it only works correctly if index record does not have
2013 ** any extra bytes at the end. Verify that this is the case. */
2014 if( HasRowid(pTab) ){
2015 int jmp7;
2016 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur+j, 3);
2017 jmp7 = sqlite3VdbeAddOp3(v, OP_Eq, 3, 0, r1+pIdx->nColumn-1);
2018 VdbeCoverageNeverNull(v);
2019 sqlite3VdbeLoadString(v, 3,
2020 "rowid not at end-of-record for row ");
2021 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
2022 sqlite3VdbeLoadString(v, 4, " of index ");
2023 sqlite3VdbeGoto(v, jmp5-1);
2024 sqlite3VdbeJumpHere(v, jmp7);
2027 /* Any indexed columns with non-BINARY collations must still hold
2028 ** the exact same text value as the table. */
2029 label6 = 0;
2030 for(kk=0; kk<pIdx->nKeyCol; kk++){
2031 if( pIdx->azColl[kk]==sqlite3StrBINARY ) continue;
2032 if( label6==0 ) label6 = sqlite3VdbeMakeLabel(pParse);
2033 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur+j, kk, 3);
2034 sqlite3VdbeAddOp3(v, OP_Ne, 3, label6, r1+kk); VdbeCoverage(v);
2036 if( label6 ){
2037 int jmp6 = sqlite3VdbeAddOp0(v, OP_Goto);
2038 sqlite3VdbeResolveLabel(v, label6);
2039 sqlite3VdbeLoadString(v, 3, "row ");
2040 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
2041 sqlite3VdbeLoadString(v, 4, " values differ from index ");
2042 sqlite3VdbeGoto(v, jmp5-1);
2043 sqlite3VdbeJumpHere(v, jmp6);
2046 /* For UNIQUE indexes, verify that only one entry exists with the
2047 ** current key. The entry is unique if (1) any column is NULL
2048 ** or (2) the next entry has a different key */
2049 if( IsUniqueIndex(pIdx) ){
2050 int uniqOk = sqlite3VdbeMakeLabel(pParse);
2051 int jmp6;
2052 for(kk=0; kk<pIdx->nKeyCol; kk++){
2053 int iCol = pIdx->aiColumn[kk];
2054 assert( iCol!=XN_ROWID && iCol<pTab->nCol );
2055 if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
2056 sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
2057 VdbeCoverage(v);
2059 jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
2060 sqlite3VdbeGoto(v, uniqOk);
2061 sqlite3VdbeJumpHere(v, jmp6);
2062 sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
2063 pIdx->nKeyCol); VdbeCoverage(v);
2064 sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
2065 sqlite3VdbeGoto(v, jmp5);
2066 sqlite3VdbeResolveLabel(v, uniqOk);
2068 sqlite3VdbeJumpHere(v, jmp4);
2069 sqlite3ResolvePartIdxLabel(pParse, jmp3);
2072 sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
2073 sqlite3VdbeJumpHere(v, loopTop-1);
2074 if( !isQuick ){
2075 sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
2076 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
2077 if( pPk==pIdx ) continue;
2078 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
2079 addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
2080 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2081 sqlite3VdbeLoadString(v, 4, pIdx->zName);
2082 sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
2083 integrityCheckResultRow(v);
2084 sqlite3VdbeJumpHere(v, addr);
2086 if( pPk ){
2087 sqlite3ReleaseTempRange(pParse, r2, pPk->nKeyCol);
2092 #ifndef SQLITE_OMIT_VIRTUALTABLE
2093 /* Second pass to invoke the xIntegrity method on all virtual
2094 ** tables.
2096 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
2097 Table *pTab = sqliteHashData(x);
2098 sqlite3_vtab *pVTab;
2099 int a1;
2100 if( pObjTab && pObjTab!=pTab ) continue;
2101 if( IsOrdinaryTable(pTab) ) continue;
2102 if( !IsVirtual(pTab) ) continue;
2103 if( pTab->nCol<=0 ){
2104 const char *zMod = pTab->u.vtab.azArg[0];
2105 if( sqlite3HashFind(&db->aModule, zMod)==0 ) continue;
2107 sqlite3ViewGetColumnNames(pParse, pTab);
2108 if( pTab->u.vtab.p==0 ) continue;
2109 pVTab = pTab->u.vtab.p->pVtab;
2110 if( NEVER(pVTab==0) ) continue;
2111 if( NEVER(pVTab->pModule==0) ) continue;
2112 if( pVTab->pModule->iVersion<4 ) continue;
2113 if( pVTab->pModule->xIntegrity==0 ) continue;
2114 sqlite3VdbeAddOp3(v, OP_VCheck, i, 3, isQuick);
2115 pTab->nTabRef++;
2116 sqlite3VdbeAppendP4(v, pTab, P4_TABLEREF);
2117 a1 = sqlite3VdbeAddOp1(v, OP_IsNull, 3); VdbeCoverage(v);
2118 integrityCheckResultRow(v);
2119 sqlite3VdbeJumpHere(v, a1);
2120 continue;
2122 #endif
2125 static const int iLn = VDBE_OFFSET_LINENO(2);
2126 static const VdbeOpList endCode[] = {
2127 { OP_AddImm, 1, 0, 0}, /* 0 */
2128 { OP_IfNotZero, 1, 4, 0}, /* 1 */
2129 { OP_String8, 0, 3, 0}, /* 2 */
2130 { OP_ResultRow, 3, 1, 0}, /* 3 */
2131 { OP_Halt, 0, 0, 0}, /* 4 */
2132 { OP_String8, 0, 3, 0}, /* 5 */
2133 { OP_Goto, 0, 3, 0}, /* 6 */
2135 VdbeOp *aOp;
2137 aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
2138 if( aOp ){
2139 aOp[0].p2 = 1-mxErr;
2140 aOp[2].p4type = P4_STATIC;
2141 aOp[2].p4.z = "ok";
2142 aOp[5].p4type = P4_STATIC;
2143 aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
2145 sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
2148 break;
2149 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
2151 #ifndef SQLITE_OMIT_UTF16
2153 ** PRAGMA encoding
2154 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
2156 ** In its first form, this pragma returns the encoding of the main
2157 ** database. If the database is not initialized, it is initialized now.
2159 ** The second form of this pragma is a no-op if the main database file
2160 ** has not already been initialized. In this case it sets the default
2161 ** encoding that will be used for the main database file if a new file
2162 ** is created. If an existing main database file is opened, then the
2163 ** default text encoding for the existing database is used.
2165 ** In all cases new databases created using the ATTACH command are
2166 ** created to use the same default text encoding as the main database. If
2167 ** the main database has not been initialized and/or created when ATTACH
2168 ** is executed, this is done before the ATTACH operation.
2170 ** In the second form this pragma sets the text encoding to be used in
2171 ** new database files created using this database handle. It is only
2172 ** useful if invoked immediately after the main database i
2174 case PragTyp_ENCODING: {
2175 static const struct EncName {
2176 char *zName;
2177 u8 enc;
2178 } encnames[] = {
2179 { "UTF8", SQLITE_UTF8 },
2180 { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
2181 { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
2182 { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
2183 { "UTF16le", SQLITE_UTF16LE },
2184 { "UTF16be", SQLITE_UTF16BE },
2185 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
2186 { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
2187 { 0, 0 }
2189 const struct EncName *pEnc;
2190 if( !zRight ){ /* "PRAGMA encoding" */
2191 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
2192 assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
2193 assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
2194 assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
2195 returnSingleText(v, encnames[ENC(pParse->db)].zName);
2196 }else{ /* "PRAGMA encoding = XXX" */
2197 /* Only change the value of sqlite.enc if the database handle is not
2198 ** initialized. If the main database exists, the new sqlite.enc value
2199 ** will be overwritten when the schema is next loaded. If it does not
2200 ** already exists, it will be created to use the new encoding value.
2202 if( (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
2203 for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
2204 if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
2205 u8 enc = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
2206 SCHEMA_ENC(db) = enc;
2207 sqlite3SetTextEncoding(db, enc);
2208 break;
2211 if( !pEnc->zName ){
2212 sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
2217 break;
2218 #endif /* SQLITE_OMIT_UTF16 */
2220 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
2222 ** PRAGMA [schema.]schema_version
2223 ** PRAGMA [schema.]schema_version = <integer>
2225 ** PRAGMA [schema.]user_version
2226 ** PRAGMA [schema.]user_version = <integer>
2228 ** PRAGMA [schema.]freelist_count
2230 ** PRAGMA [schema.]data_version
2232 ** PRAGMA [schema.]application_id
2233 ** PRAGMA [schema.]application_id = <integer>
2235 ** The pragma's schema_version and user_version are used to set or get
2236 ** the value of the schema-version and user-version, respectively. Both
2237 ** the schema-version and the user-version are 32-bit signed integers
2238 ** stored in the database header.
2240 ** The schema-cookie is usually only manipulated internally by SQLite. It
2241 ** is incremented by SQLite whenever the database schema is modified (by
2242 ** creating or dropping a table or index). The schema version is used by
2243 ** SQLite each time a query is executed to ensure that the internal cache
2244 ** of the schema used when compiling the SQL query matches the schema of
2245 ** the database against which the compiled query is actually executed.
2246 ** Subverting this mechanism by using "PRAGMA schema_version" to modify
2247 ** the schema-version is potentially dangerous and may lead to program
2248 ** crashes or database corruption. Use with caution!
2250 ** The user-version is not used internally by SQLite. It may be used by
2251 ** applications for any purpose.
2253 case PragTyp_HEADER_VALUE: {
2254 int iCookie = pPragma->iArg; /* Which cookie to read or write */
2255 sqlite3VdbeUsesBtree(v, iDb);
2256 if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
2257 /* Write the specified cookie value */
2258 static const VdbeOpList setCookie[] = {
2259 { OP_Transaction, 0, 1, 0}, /* 0 */
2260 { OP_SetCookie, 0, 0, 0}, /* 1 */
2262 VdbeOp *aOp;
2263 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
2264 aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
2265 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
2266 aOp[0].p1 = iDb;
2267 aOp[1].p1 = iDb;
2268 aOp[1].p2 = iCookie;
2269 aOp[1].p3 = sqlite3Atoi(zRight);
2270 aOp[1].p5 = 1;
2271 if( iCookie==BTREE_SCHEMA_VERSION && (db->flags & SQLITE_Defensive)!=0 ){
2272 /* Do not allow the use of PRAGMA schema_version=VALUE in defensive
2273 ** mode. Change the OP_SetCookie opcode into a no-op. */
2274 aOp[1].opcode = OP_Noop;
2276 }else{
2277 /* Read the specified cookie value */
2278 static const VdbeOpList readCookie[] = {
2279 { OP_Transaction, 0, 0, 0}, /* 0 */
2280 { OP_ReadCookie, 0, 1, 0}, /* 1 */
2281 { OP_ResultRow, 1, 1, 0}
2283 VdbeOp *aOp;
2284 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
2285 aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
2286 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
2287 aOp[0].p1 = iDb;
2288 aOp[1].p1 = iDb;
2289 aOp[1].p3 = iCookie;
2290 sqlite3VdbeReusable(v);
2293 break;
2294 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
2296 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
2298 ** PRAGMA compile_options
2300 ** Return the names of all compile-time options used in this build,
2301 ** one option per row.
2303 case PragTyp_COMPILE_OPTIONS: {
2304 int i = 0;
2305 const char *zOpt;
2306 pParse->nMem = 1;
2307 while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
2308 sqlite3VdbeLoadString(v, 1, zOpt);
2309 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
2311 sqlite3VdbeReusable(v);
2313 break;
2314 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
2316 #ifndef SQLITE_OMIT_WAL
2318 ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
2320 ** Checkpoint the database.
2322 case PragTyp_WAL_CHECKPOINT: {
2323 int iBt = (pId2->z?iDb:SQLITE_MAX_DB);
2324 int eMode = SQLITE_CHECKPOINT_PASSIVE;
2325 if( zRight ){
2326 if( sqlite3StrICmp(zRight, "full")==0 ){
2327 eMode = SQLITE_CHECKPOINT_FULL;
2328 }else if( sqlite3StrICmp(zRight, "restart")==0 ){
2329 eMode = SQLITE_CHECKPOINT_RESTART;
2330 }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
2331 eMode = SQLITE_CHECKPOINT_TRUNCATE;
2334 pParse->nMem = 3;
2335 sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
2336 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
2338 break;
2341 ** PRAGMA wal_autocheckpoint
2342 ** PRAGMA wal_autocheckpoint = N
2344 ** Configure a database connection to automatically checkpoint a database
2345 ** after accumulating N frames in the log. Or query for the current value
2346 ** of N.
2348 case PragTyp_WAL_AUTOCHECKPOINT: {
2349 if( zRight ){
2350 sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
2352 returnSingleInt(v,
2353 db->xWalCallback==sqlite3WalDefaultHook ?
2354 SQLITE_PTR_TO_INT(db->pWalArg) : 0);
2356 break;
2357 #endif
2360 ** PRAGMA shrink_memory
2362 ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
2363 ** connection on which it is invoked to free up as much memory as it
2364 ** can, by calling sqlite3_db_release_memory().
2366 case PragTyp_SHRINK_MEMORY: {
2367 sqlite3_db_release_memory(db);
2368 break;
2372 ** PRAGMA optimize
2373 ** PRAGMA optimize(MASK)
2374 ** PRAGMA schema.optimize
2375 ** PRAGMA schema.optimize(MASK)
2377 ** Attempt to optimize the database. All schemas are optimized in the first
2378 ** two forms, and only the specified schema is optimized in the latter two.
2380 ** The details of optimizations performed by this pragma are expected
2381 ** to change and improve over time. Applications should anticipate that
2382 ** this pragma will perform new optimizations in future releases.
2384 ** The optional argument is a bitmask of optimizations to perform:
2386 ** 0x0001 Debugging mode. Do not actually perform any optimizations
2387 ** but instead return one line of text for each optimization
2388 ** that would have been done. Off by default.
2390 ** 0x0002 Run ANALYZE on tables that might benefit. On by default.
2391 ** See below for additional information.
2393 ** 0x0004 (Not yet implemented) Record usage and performance
2394 ** information from the current session in the
2395 ** database file so that it will be available to "optimize"
2396 ** pragmas run by future database connections.
2398 ** 0x0008 (Not yet implemented) Create indexes that might have
2399 ** been helpful to recent queries
2401 ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all
2402 ** of the optimizations listed above except Debug Mode, including new
2403 ** optimizations that have not yet been invented. If new optimizations are
2404 ** ever added that should be off by default, those off-by-default
2405 ** optimizations will have bitmasks of 0x10000 or larger.
2407 ** DETERMINATION OF WHEN TO RUN ANALYZE
2409 ** In the current implementation, a table is analyzed if only if all of
2410 ** the following are true:
2412 ** (1) MASK bit 0x02 is set.
2414 ** (2) The query planner used sqlite_stat1-style statistics for one or
2415 ** more indexes of the table at some point during the lifetime of
2416 ** the current connection.
2418 ** (3) One or more indexes of the table are currently unanalyzed OR
2419 ** the number of rows in the table has increased by 25 times or more
2420 ** since the last time ANALYZE was run.
2422 ** The rules for when tables are analyzed are likely to change in
2423 ** future releases.
2425 case PragTyp_OPTIMIZE: {
2426 int iDbLast; /* Loop termination point for the schema loop */
2427 int iTabCur; /* Cursor for a table whose size needs checking */
2428 HashElem *k; /* Loop over tables of a schema */
2429 Schema *pSchema; /* The current schema */
2430 Table *pTab; /* A table in the schema */
2431 Index *pIdx; /* An index of the table */
2432 LogEst szThreshold; /* Size threshold above which reanalysis needed */
2433 char *zSubSql; /* SQL statement for the OP_SqlExec opcode */
2434 u32 opMask; /* Mask of operations to perform */
2436 if( zRight ){
2437 opMask = (u32)sqlite3Atoi(zRight);
2438 if( (opMask & 0x02)==0 ) break;
2439 }else{
2440 opMask = 0xfffe;
2442 iTabCur = pParse->nTab++;
2443 for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
2444 if( iDb==1 ) continue;
2445 sqlite3CodeVerifySchema(pParse, iDb);
2446 pSchema = db->aDb[iDb].pSchema;
2447 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
2448 pTab = (Table*)sqliteHashData(k);
2450 /* If table pTab has not been used in a way that would benefit from
2451 ** having analysis statistics during the current session, then skip it.
2452 ** This also has the effect of skipping virtual tables and views */
2453 if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
2455 /* Reanalyze if the table is 25 times larger than the last analysis */
2456 szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
2457 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2458 if( !pIdx->hasStat1 ){
2459 szThreshold = 0; /* Always analyze if any index lacks statistics */
2460 break;
2463 if( szThreshold ){
2464 sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
2465 sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
2466 sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
2467 VdbeCoverage(v);
2469 zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
2470 db->aDb[iDb].zDbSName, pTab->zName);
2471 if( opMask & 0x01 ){
2472 int r1 = sqlite3GetTempReg(pParse);
2473 sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
2474 sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
2475 }else{
2476 sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
2480 sqlite3VdbeAddOp0(v, OP_Expire);
2481 break;
2485 ** PRAGMA busy_timeout
2486 ** PRAGMA busy_timeout = N
2488 ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
2489 ** if one is set. If no busy handler or a different busy handler is set
2490 ** then 0 is returned. Setting the busy_timeout to 0 or negative
2491 ** disables the timeout.
2493 /*case PragTyp_BUSY_TIMEOUT*/ default: {
2494 assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
2495 if( zRight ){
2496 sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
2498 returnSingleInt(v, db->busyTimeout);
2499 break;
2503 ** PRAGMA soft_heap_limit
2504 ** PRAGMA soft_heap_limit = N
2506 ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
2507 ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
2508 ** specified and is a non-negative integer.
2509 ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
2510 ** returns the same integer that would be returned by the
2511 ** sqlite3_soft_heap_limit64(-1) C-language function.
2513 case PragTyp_SOFT_HEAP_LIMIT: {
2514 sqlite3_int64 N;
2515 if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
2516 sqlite3_soft_heap_limit64(N);
2518 returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
2519 break;
2523 ** PRAGMA hard_heap_limit
2524 ** PRAGMA hard_heap_limit = N
2526 ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap
2527 ** limit. The hard heap limit can be activated or lowered by this
2528 ** pragma, but not raised or deactivated. Only the
2529 ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate
2530 ** the hard heap limit. This allows an application to set a heap limit
2531 ** constraint that cannot be relaxed by an untrusted SQL script.
2533 case PragTyp_HARD_HEAP_LIMIT: {
2534 sqlite3_int64 N;
2535 if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
2536 sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1);
2537 if( N>0 && (iPrior==0 || iPrior>N) ) sqlite3_hard_heap_limit64(N);
2539 returnSingleInt(v, sqlite3_hard_heap_limit64(-1));
2540 break;
2544 ** PRAGMA threads
2545 ** PRAGMA threads = N
2547 ** Configure the maximum number of worker threads. Return the new
2548 ** maximum, which might be less than requested.
2550 case PragTyp_THREADS: {
2551 sqlite3_int64 N;
2552 if( zRight
2553 && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
2554 && N>=0
2556 sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
2558 returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
2559 break;
2563 ** PRAGMA analysis_limit
2564 ** PRAGMA analysis_limit = N
2566 ** Configure the maximum number of rows that ANALYZE will examine
2567 ** in each index that it looks at. Return the new limit.
2569 case PragTyp_ANALYSIS_LIMIT: {
2570 sqlite3_int64 N;
2571 if( zRight
2572 && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK /* IMP: R-40975-20399 */
2573 && N>=0
2575 db->nAnalysisLimit = (int)(N&0x7fffffff);
2577 returnSingleInt(v, db->nAnalysisLimit); /* IMP: R-57594-65522 */
2578 break;
2581 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
2583 ** Report the current state of file logs for all databases
2585 case PragTyp_LOCK_STATUS: {
2586 static const char *const azLockName[] = {
2587 "unlocked", "shared", "reserved", "pending", "exclusive"
2589 int i;
2590 pParse->nMem = 2;
2591 for(i=0; i<db->nDb; i++){
2592 Btree *pBt;
2593 const char *zState = "unknown";
2594 int j;
2595 if( db->aDb[i].zDbSName==0 ) continue;
2596 pBt = db->aDb[i].pBt;
2597 if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
2598 zState = "closed";
2599 }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
2600 SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
2601 zState = azLockName[j];
2603 sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
2605 break;
2607 #endif
2609 #if defined(SQLITE_ENABLE_CEROD)
2610 case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
2611 if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
2612 sqlite3_activate_cerod(&zRight[6]);
2615 break;
2616 #endif
2618 } /* End of the PRAGMA switch */
2620 /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
2621 ** purpose is to execute assert() statements to verify that if the
2622 ** PragFlg_NoColumns1 flag is set and the caller specified an argument
2623 ** to the PRAGMA, the implementation has not added any OP_ResultRow
2624 ** instructions to the VM. */
2625 if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
2626 sqlite3VdbeVerifyNoResultRow(v);
2629 pragma_out:
2630 sqlite3DbFree(db, zLeft);
2631 sqlite3DbFree(db, zRight);
2633 #ifndef SQLITE_OMIT_VIRTUALTABLE
2634 /*****************************************************************************
2635 ** Implementation of an eponymous virtual table that runs a pragma.
2638 typedef struct PragmaVtab PragmaVtab;
2639 typedef struct PragmaVtabCursor PragmaVtabCursor;
2640 struct PragmaVtab {
2641 sqlite3_vtab base; /* Base class. Must be first */
2642 sqlite3 *db; /* The database connection to which it belongs */
2643 const PragmaName *pName; /* Name of the pragma */
2644 u8 nHidden; /* Number of hidden columns */
2645 u8 iHidden; /* Index of the first hidden column */
2647 struct PragmaVtabCursor {
2648 sqlite3_vtab_cursor base; /* Base class. Must be first */
2649 sqlite3_stmt *pPragma; /* The pragma statement to run */
2650 sqlite_int64 iRowid; /* Current rowid */
2651 char *azArg[2]; /* Value of the argument and schema */
2655 ** Pragma virtual table module xConnect method.
2657 static int pragmaVtabConnect(
2658 sqlite3 *db,
2659 void *pAux,
2660 int argc, const char *const*argv,
2661 sqlite3_vtab **ppVtab,
2662 char **pzErr
2664 const PragmaName *pPragma = (const PragmaName*)pAux;
2665 PragmaVtab *pTab = 0;
2666 int rc;
2667 int i, j;
2668 char cSep = '(';
2669 StrAccum acc;
2670 char zBuf[200];
2672 UNUSED_PARAMETER(argc);
2673 UNUSED_PARAMETER(argv);
2674 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
2675 sqlite3_str_appendall(&acc, "CREATE TABLE x");
2676 for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
2677 sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]);
2678 cSep = ',';
2680 if( i==0 ){
2681 sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
2682 i++;
2684 j = 0;
2685 if( pPragma->mPragFlg & PragFlg_Result1 ){
2686 sqlite3_str_appendall(&acc, ",arg HIDDEN");
2687 j++;
2689 if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
2690 sqlite3_str_appendall(&acc, ",schema HIDDEN");
2691 j++;
2693 sqlite3_str_append(&acc, ")", 1);
2694 sqlite3StrAccumFinish(&acc);
2695 assert( strlen(zBuf) < sizeof(zBuf)-1 );
2696 rc = sqlite3_declare_vtab(db, zBuf);
2697 if( rc==SQLITE_OK ){
2698 pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
2699 if( pTab==0 ){
2700 rc = SQLITE_NOMEM;
2701 }else{
2702 memset(pTab, 0, sizeof(PragmaVtab));
2703 pTab->pName = pPragma;
2704 pTab->db = db;
2705 pTab->iHidden = i;
2706 pTab->nHidden = j;
2708 }else{
2709 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
2712 *ppVtab = (sqlite3_vtab*)pTab;
2713 return rc;
2717 ** Pragma virtual table module xDisconnect method.
2719 static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
2720 PragmaVtab *pTab = (PragmaVtab*)pVtab;
2721 sqlite3_free(pTab);
2722 return SQLITE_OK;
2725 /* Figure out the best index to use to search a pragma virtual table.
2727 ** There are not really any index choices. But we want to encourage the
2728 ** query planner to give == constraints on as many hidden parameters as
2729 ** possible, and especially on the first hidden parameter. So return a
2730 ** high cost if hidden parameters are unconstrained.
2732 static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
2733 PragmaVtab *pTab = (PragmaVtab*)tab;
2734 const struct sqlite3_index_constraint *pConstraint;
2735 int i, j;
2736 int seen[2];
2738 pIdxInfo->estimatedCost = (double)1;
2739 if( pTab->nHidden==0 ){ return SQLITE_OK; }
2740 pConstraint = pIdxInfo->aConstraint;
2741 seen[0] = 0;
2742 seen[1] = 0;
2743 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
2744 if( pConstraint->usable==0 ) continue;
2745 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
2746 if( pConstraint->iColumn < pTab->iHidden ) continue;
2747 j = pConstraint->iColumn - pTab->iHidden;
2748 assert( j < 2 );
2749 seen[j] = i+1;
2751 if( seen[0]==0 ){
2752 pIdxInfo->estimatedCost = (double)2147483647;
2753 pIdxInfo->estimatedRows = 2147483647;
2754 return SQLITE_OK;
2756 j = seen[0]-1;
2757 pIdxInfo->aConstraintUsage[j].argvIndex = 1;
2758 pIdxInfo->aConstraintUsage[j].omit = 1;
2759 if( seen[1]==0 ){
2760 pIdxInfo->estimatedCost = (double)1000;
2761 pIdxInfo->estimatedRows = 1000;
2762 return SQLITE_OK;
2764 pIdxInfo->estimatedCost = (double)20;
2765 pIdxInfo->estimatedRows = 20;
2766 j = seen[1]-1;
2767 pIdxInfo->aConstraintUsage[j].argvIndex = 2;
2768 pIdxInfo->aConstraintUsage[j].omit = 1;
2769 return SQLITE_OK;
2772 /* Create a new cursor for the pragma virtual table */
2773 static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
2774 PragmaVtabCursor *pCsr;
2775 pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
2776 if( pCsr==0 ) return SQLITE_NOMEM;
2777 memset(pCsr, 0, sizeof(PragmaVtabCursor));
2778 pCsr->base.pVtab = pVtab;
2779 *ppCursor = &pCsr->base;
2780 return SQLITE_OK;
2783 /* Clear all content from pragma virtual table cursor. */
2784 static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
2785 int i;
2786 sqlite3_finalize(pCsr->pPragma);
2787 pCsr->pPragma = 0;
2788 for(i=0; i<ArraySize(pCsr->azArg); i++){
2789 sqlite3_free(pCsr->azArg[i]);
2790 pCsr->azArg[i] = 0;
2794 /* Close a pragma virtual table cursor */
2795 static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
2796 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
2797 pragmaVtabCursorClear(pCsr);
2798 sqlite3_free(pCsr);
2799 return SQLITE_OK;
2802 /* Advance the pragma virtual table cursor to the next row */
2803 static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
2804 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2805 int rc = SQLITE_OK;
2807 /* Increment the xRowid value */
2808 pCsr->iRowid++;
2809 assert( pCsr->pPragma );
2810 if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
2811 rc = sqlite3_finalize(pCsr->pPragma);
2812 pCsr->pPragma = 0;
2813 pragmaVtabCursorClear(pCsr);
2815 return rc;
2819 ** Pragma virtual table module xFilter method.
2821 static int pragmaVtabFilter(
2822 sqlite3_vtab_cursor *pVtabCursor,
2823 int idxNum, const char *idxStr,
2824 int argc, sqlite3_value **argv
2826 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2827 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
2828 int rc;
2829 int i, j;
2830 StrAccum acc;
2831 char *zSql;
2833 UNUSED_PARAMETER(idxNum);
2834 UNUSED_PARAMETER(idxStr);
2835 pragmaVtabCursorClear(pCsr);
2836 j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
2837 for(i=0; i<argc; i++, j++){
2838 const char *zText = (const char*)sqlite3_value_text(argv[i]);
2839 assert( j<ArraySize(pCsr->azArg) );
2840 assert( pCsr->azArg[j]==0 );
2841 if( zText ){
2842 pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
2843 if( pCsr->azArg[j]==0 ){
2844 return SQLITE_NOMEM;
2848 sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
2849 sqlite3_str_appendall(&acc, "PRAGMA ");
2850 if( pCsr->azArg[1] ){
2851 sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
2853 sqlite3_str_appendall(&acc, pTab->pName->zName);
2854 if( pCsr->azArg[0] ){
2855 sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
2857 zSql = sqlite3StrAccumFinish(&acc);
2858 if( zSql==0 ) return SQLITE_NOMEM;
2859 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
2860 sqlite3_free(zSql);
2861 if( rc!=SQLITE_OK ){
2862 pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
2863 return rc;
2865 return pragmaVtabNext(pVtabCursor);
2869 ** Pragma virtual table module xEof method.
2871 static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
2872 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2873 return (pCsr->pPragma==0);
2876 /* The xColumn method simply returns the corresponding column from
2877 ** the PRAGMA.
2879 static int pragmaVtabColumn(
2880 sqlite3_vtab_cursor *pVtabCursor,
2881 sqlite3_context *ctx,
2882 int i
2884 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2885 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
2886 if( i<pTab->iHidden ){
2887 sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
2888 }else{
2889 sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
2891 return SQLITE_OK;
2895 ** Pragma virtual table module xRowid method.
2897 static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
2898 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2899 *p = pCsr->iRowid;
2900 return SQLITE_OK;
2903 /* The pragma virtual table object */
2904 static const sqlite3_module pragmaVtabModule = {
2905 0, /* iVersion */
2906 0, /* xCreate - create a table */
2907 pragmaVtabConnect, /* xConnect - connect to an existing table */
2908 pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */
2909 pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */
2910 0, /* xDestroy - Drop a table */
2911 pragmaVtabOpen, /* xOpen - open a cursor */
2912 pragmaVtabClose, /* xClose - close a cursor */
2913 pragmaVtabFilter, /* xFilter - configure scan constraints */
2914 pragmaVtabNext, /* xNext - advance a cursor */
2915 pragmaVtabEof, /* xEof */
2916 pragmaVtabColumn, /* xColumn - read data */
2917 pragmaVtabRowid, /* xRowid - read data */
2918 0, /* xUpdate - write data */
2919 0, /* xBegin - begin transaction */
2920 0, /* xSync - sync transaction */
2921 0, /* xCommit - commit transaction */
2922 0, /* xRollback - rollback transaction */
2923 0, /* xFindFunction - function overloading */
2924 0, /* xRename - rename the table */
2925 0, /* xSavepoint */
2926 0, /* xRelease */
2927 0, /* xRollbackTo */
2928 0, /* xShadowName */
2929 0 /* xIntegrity */
2933 ** Check to see if zTabName is really the name of a pragma. If it is,
2934 ** then register an eponymous virtual table for that pragma and return
2935 ** a pointer to the Module object for the new virtual table.
2937 Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
2938 const PragmaName *pName;
2939 assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
2940 pName = pragmaLocate(zName+7);
2941 if( pName==0 ) return 0;
2942 if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
2943 assert( sqlite3HashFind(&db->aModule, zName)==0 );
2944 return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
2947 #endif /* SQLITE_OMIT_VIRTUALTABLE */
2949 #endif /* SQLITE_OMIT_PRAGMA */