establish default sqlcipher log level and target upon first activation
[sqlcipher.git] / src / pragma.c
blobf2ee98eb01c595d234c68c8361e53b519a038270
1 /*
2 ** 2003 April 6
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains code used to implement the PRAGMA command.
14 #include "sqliteInt.h"
16 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
17 # if defined(__APPLE__)
18 # define SQLITE_ENABLE_LOCKING_STYLE 1
19 # else
20 # define SQLITE_ENABLE_LOCKING_STYLE 0
21 # endif
22 #endif
24 /***************************************************************************
25 ** The "pragma.h" include file is an automatically generated file that
26 ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
27 ** object. This ensures that the aPragmaName[] table is arranged in
28 ** lexicographical order to facility a binary search of the pragma name.
29 ** Do not edit pragma.h directly. Edit and rerun the script in at
30 ** ../tool/mkpragmatab.tcl. */
31 #include "pragma.h"
34 ** Interpret the given string as a safety level. Return 0 for OFF,
35 ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
36 ** unrecognized string argument. The FULL and EXTRA option is disallowed
37 ** if the omitFull parameter it 1.
39 ** Note that the values returned are one less that the values that
40 ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
41 ** to support legacy SQL code. The safety level used to be boolean
42 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
44 static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
45 /* 123456789 123456789 123 */
46 static const char zText[] = "onoffalseyestruextrafull";
47 static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20};
48 static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4};
49 static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2};
50 /* on no off false yes true extra full */
51 int i, n;
52 if( sqlite3Isdigit(*z) ){
53 return (u8)sqlite3Atoi(z);
55 n = sqlite3Strlen30(z);
56 for(i=0; i<ArraySize(iLength); i++){
57 if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
58 && (!omitFull || iValue[i]<=1)
60 return iValue[i];
63 return dflt;
67 ** Interpret the given string as a boolean value.
69 u8 sqlite3GetBoolean(const char *z, u8 dflt){
70 return getSafetyLevel(z,1,dflt)!=0;
73 /* The sqlite3GetBoolean() function is used by other modules but the
74 ** remainder of this file is specific to PRAGMA processing. So omit
75 ** the rest of the file if PRAGMAs are omitted from the build.
77 #if !defined(SQLITE_OMIT_PRAGMA)
80 ** Interpret the given string as a locking mode value.
82 static int getLockingMode(const char *z){
83 if( z ){
84 if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
85 if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
87 return PAGER_LOCKINGMODE_QUERY;
90 #ifndef SQLITE_OMIT_AUTOVACUUM
92 ** Interpret the given string as an auto-vacuum mode value.
94 ** The following strings, "none", "full" and "incremental" are
95 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
97 static int getAutoVacuum(const char *z){
98 int i;
99 if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
100 if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
101 if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
102 i = sqlite3Atoi(z);
103 return (u8)((i>=0&&i<=2)?i:0);
105 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
107 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
109 ** Interpret the given string as a temp db location. Return 1 for file
110 ** backed temporary databases, 2 for the Red-Black tree in memory database
111 ** and 0 to use the compile-time default.
113 static int getTempStore(const char *z){
114 if( z[0]>='0' && z[0]<='2' ){
115 return z[0] - '0';
116 }else if( sqlite3StrICmp(z, "file")==0 ){
117 return 1;
118 }else if( sqlite3StrICmp(z, "memory")==0 ){
119 return 2;
120 }else{
121 return 0;
124 #endif /* SQLITE_PAGER_PRAGMAS */
126 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
128 ** Invalidate temp storage, either when the temp storage is changed
129 ** from default, or when 'file' and the temp_store_directory has changed
131 static int invalidateTempStorage(Parse *pParse){
132 sqlite3 *db = pParse->db;
133 if( db->aDb[1].pBt!=0 ){
134 if( !db->autoCommit
135 || sqlite3BtreeTxnState(db->aDb[1].pBt)!=SQLITE_TXN_NONE
137 sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
138 "from within a transaction");
139 return SQLITE_ERROR;
141 sqlite3BtreeClose(db->aDb[1].pBt);
142 db->aDb[1].pBt = 0;
143 sqlite3ResetAllSchemasOfConnection(db);
145 return SQLITE_OK;
147 #endif /* SQLITE_PAGER_PRAGMAS */
149 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
151 ** If the TEMP database is open, close it and mark the database schema
152 ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
153 ** or DEFAULT_TEMP_STORE pragmas.
155 static int changeTempStorage(Parse *pParse, const char *zStorageType){
156 int ts = getTempStore(zStorageType);
157 sqlite3 *db = pParse->db;
158 if( db->temp_store==ts ) return SQLITE_OK;
159 if( invalidateTempStorage( pParse ) != SQLITE_OK ){
160 return SQLITE_ERROR;
162 db->temp_store = (u8)ts;
163 return SQLITE_OK;
165 #endif /* SQLITE_PAGER_PRAGMAS */
168 ** Set result column names for a pragma.
170 static void setPragmaResultColumnNames(
171 Vdbe *v, /* The query under construction */
172 const PragmaName *pPragma /* The pragma */
174 u8 n = pPragma->nPragCName;
175 sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
176 if( n==0 ){
177 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
178 }else{
179 int i, j;
180 for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
181 sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
187 ** Generate code to return a single integer value.
189 static void returnSingleInt(Vdbe *v, i64 value){
190 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
191 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
195 ** Generate code to return a single text value.
197 static void returnSingleText(
198 Vdbe *v, /* Prepared statement under construction */
199 const char *zValue /* Value to be returned */
201 if( zValue ){
202 sqlite3VdbeLoadString(v, 1, (const char*)zValue);
203 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
209 ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
210 ** set these values for all pagers.
212 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
213 static void setAllPagerFlags(sqlite3 *db){
214 if( db->autoCommit ){
215 Db *pDb = db->aDb;
216 int n = db->nDb;
217 assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
218 assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
219 assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
220 assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
221 == PAGER_FLAGS_MASK );
222 assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
223 while( (n--) > 0 ){
224 if( pDb->pBt ){
225 sqlite3BtreeSetPagerFlags(pDb->pBt,
226 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
228 pDb++;
232 #else
233 # define setAllPagerFlags(X) /* no-op */
234 #endif
238 ** Return a human-readable name for a constraint resolution action.
240 #ifndef SQLITE_OMIT_FOREIGN_KEY
241 static const char *actionName(u8 action){
242 const char *zName;
243 switch( action ){
244 case OE_SetNull: zName = "SET NULL"; break;
245 case OE_SetDflt: zName = "SET DEFAULT"; break;
246 case OE_Cascade: zName = "CASCADE"; break;
247 case OE_Restrict: zName = "RESTRICT"; break;
248 default: zName = "NO ACTION";
249 assert( action==OE_None ); break;
251 return zName;
253 #endif
257 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
258 ** defined in pager.h. This function returns the associated lowercase
259 ** journal-mode name.
261 const char *sqlite3JournalModename(int eMode){
262 static char * const azModeName[] = {
263 "delete", "persist", "off", "truncate", "memory"
264 #ifndef SQLITE_OMIT_WAL
265 , "wal"
266 #endif
268 assert( PAGER_JOURNALMODE_DELETE==0 );
269 assert( PAGER_JOURNALMODE_PERSIST==1 );
270 assert( PAGER_JOURNALMODE_OFF==2 );
271 assert( PAGER_JOURNALMODE_TRUNCATE==3 );
272 assert( PAGER_JOURNALMODE_MEMORY==4 );
273 assert( PAGER_JOURNALMODE_WAL==5 );
274 assert( eMode>=0 && eMode<=ArraySize(azModeName) );
276 if( eMode==ArraySize(azModeName) ) return 0;
277 return azModeName[eMode];
281 ** Locate a pragma in the aPragmaName[] array.
283 static const PragmaName *pragmaLocate(const char *zName){
284 int upr, lwr, mid = 0, rc;
285 lwr = 0;
286 upr = ArraySize(aPragmaName)-1;
287 while( lwr<=upr ){
288 mid = (lwr+upr)/2;
289 rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
290 if( rc==0 ) break;
291 if( rc<0 ){
292 upr = mid - 1;
293 }else{
294 lwr = mid + 1;
297 return lwr>upr ? 0 : &aPragmaName[mid];
301 ** Create zero or more entries in the output for the SQL functions
302 ** defined by FuncDef p.
304 static void pragmaFunclistLine(
305 Vdbe *v, /* The prepared statement being created */
306 FuncDef *p, /* A particular function definition */
307 int isBuiltin, /* True if this is a built-in function */
308 int showInternFuncs /* True if showing internal functions */
310 u32 mask =
311 SQLITE_DETERMINISTIC |
312 SQLITE_DIRECTONLY |
313 SQLITE_SUBTYPE |
314 SQLITE_INNOCUOUS |
315 SQLITE_FUNC_INTERNAL
317 if( showInternFuncs ) mask = 0xffffffff;
318 for(; p; p=p->pNext){
319 const char *zType;
320 static const char *azEnc[] = { 0, "utf8", "utf16le", "utf16be" };
322 assert( SQLITE_FUNC_ENCMASK==0x3 );
323 assert( strcmp(azEnc[SQLITE_UTF8],"utf8")==0 );
324 assert( strcmp(azEnc[SQLITE_UTF16LE],"utf16le")==0 );
325 assert( strcmp(azEnc[SQLITE_UTF16BE],"utf16be")==0 );
327 if( p->xSFunc==0 ) continue;
328 if( (p->funcFlags & SQLITE_FUNC_INTERNAL)!=0
329 && showInternFuncs==0
331 continue;
333 if( p->xValue!=0 ){
334 zType = "w";
335 }else if( p->xFinalize!=0 ){
336 zType = "a";
337 }else{
338 zType = "s";
340 sqlite3VdbeMultiLoad(v, 1, "sissii",
341 p->zName, isBuiltin,
342 zType, azEnc[p->funcFlags&SQLITE_FUNC_ENCMASK],
343 p->nArg,
344 (p->funcFlags & mask) ^ SQLITE_INNOCUOUS
351 ** Helper subroutine for PRAGMA integrity_check:
353 ** Generate code to output a single-column result row with a value of the
354 ** string held in register 3. Decrement the result count in register 1
355 ** and halt if the maximum number of result rows have been issued.
357 static int integrityCheckResultRow(Vdbe *v){
358 int addr;
359 sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
360 addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
361 VdbeCoverage(v);
362 sqlite3VdbeAddOp0(v, OP_Halt);
363 return addr;
367 ** Process a pragma statement.
369 ** Pragmas are of this form:
371 ** PRAGMA [schema.]id [= value]
373 ** The identifier might also be a string. The value is a string, and
374 ** identifier, or a number. If minusFlag is true, then the value is
375 ** a number that was preceded by a minus sign.
377 ** If the left side is "database.id" then pId1 is the database name
378 ** and pId2 is the id. If the left side is just "id" then pId1 is the
379 ** id and pId2 is any empty string.
381 void sqlite3Pragma(
382 Parse *pParse,
383 Token *pId1, /* First part of [schema.]id field */
384 Token *pId2, /* Second part of [schema.]id field, or NULL */
385 Token *pValue, /* Token for <value>, or NULL */
386 int minusFlag /* True if a '-' sign preceded <value> */
388 char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
389 char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
390 const char *zDb = 0; /* The database name */
391 Token *pId; /* Pointer to <id> token */
392 char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
393 int iDb; /* Database index for <database> */
394 int rc; /* return value form SQLITE_FCNTL_PRAGMA */
395 sqlite3 *db = pParse->db; /* The database connection */
396 Db *pDb; /* The specific database being pragmaed */
397 Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
398 const PragmaName *pPragma; /* The pragma */
399 /* BEGIN SQLCIPHER */
400 #ifdef SQLITE_HAS_CODEC
401 extern int sqlcipher_codec_pragma(sqlite3*, int, Parse *, const char *, const char *);
402 #endif
403 /* END SQLCIPHER */
405 if( v==0 ) return;
406 sqlite3VdbeRunOnlyOnce(v);
407 pParse->nMem = 2;
409 /* Interpret the [schema.] part of the pragma statement. iDb is the
410 ** index of the database this pragma is being applied to in db.aDb[]. */
411 iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
412 if( iDb<0 ) return;
413 pDb = &db->aDb[iDb];
415 /* If the temp database has been explicitly named as part of the
416 ** pragma, make sure it is open.
418 if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
419 return;
422 zLeft = sqlite3NameFromToken(db, pId);
423 if( !zLeft ) return;
424 if( minusFlag ){
425 zRight = sqlite3MPrintf(db, "-%T", pValue);
426 }else{
427 zRight = sqlite3NameFromToken(db, pValue);
430 assert( pId2 );
431 zDb = pId2->n>0 ? pDb->zDbSName : 0;
432 if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
433 goto pragma_out;
436 /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
437 ** connection. If it returns SQLITE_OK, then assume that the VFS
438 ** handled the pragma and generate a no-op prepared statement.
440 ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
441 ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
442 ** object corresponding to the database file to which the pragma
443 ** statement refers.
445 ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
446 ** file control is an array of pointers to strings (char**) in which the
447 ** second element of the array is the name of the pragma and the third
448 ** element is the argument to the pragma or NULL if the pragma has no
449 ** argument.
451 aFcntl[0] = 0;
452 aFcntl[1] = zLeft;
453 aFcntl[2] = zRight;
454 aFcntl[3] = 0;
455 db->busyHandler.nBusy = 0;
456 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
457 if( rc==SQLITE_OK ){
458 sqlite3VdbeSetNumCols(v, 1);
459 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
460 returnSingleText(v, aFcntl[0]);
461 sqlite3_free(aFcntl[0]);
462 goto pragma_out;
464 if( rc!=SQLITE_NOTFOUND ){
465 if( aFcntl[0] ){
466 sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
467 sqlite3_free(aFcntl[0]);
469 pParse->nErr++;
470 pParse->rc = rc;
472 goto pragma_out;
475 /* BEGIN SQLCIPHER */
476 #ifdef SQLITE_HAS_CODEC
477 if(sqlcipher_codec_pragma(db, iDb, pParse, zLeft, zRight)) {
478 /* sqlcipher_codec_pragma executes internal */
479 goto pragma_out;
481 #endif
482 /* END SQLCIPHER */
484 /* Locate the pragma in the lookup table */
485 pPragma = pragmaLocate(zLeft);
486 if( pPragma==0 ){
487 /* IMP: R-43042-22504 No error messages are generated if an
488 ** unknown pragma is issued. */
489 goto pragma_out;
492 /* Make sure the database schema is loaded if the pragma requires that */
493 if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
494 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
497 /* Register the result column names for pragmas that return results */
498 if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
499 && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
501 setPragmaResultColumnNames(v, pPragma);
504 /* Jump to the appropriate pragma handler */
505 switch( pPragma->ePragTyp ){
507 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
509 ** PRAGMA [schema.]default_cache_size
510 ** PRAGMA [schema.]default_cache_size=N
512 ** The first form reports the current persistent setting for the
513 ** page cache size. The value returned is the maximum number of
514 ** pages in the page cache. The second form sets both the current
515 ** page cache size value and the persistent page cache size value
516 ** stored in the database file.
518 ** Older versions of SQLite would set the default cache size to a
519 ** negative number to indicate synchronous=OFF. These days, synchronous
520 ** is always on by default regardless of the sign of the default cache
521 ** size. But continue to take the absolute value of the default cache
522 ** size of historical compatibility.
524 case PragTyp_DEFAULT_CACHE_SIZE: {
525 static const int iLn = VDBE_OFFSET_LINENO(2);
526 static const VdbeOpList getCacheSize[] = {
527 { OP_Transaction, 0, 0, 0}, /* 0 */
528 { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
529 { OP_IfPos, 1, 8, 0},
530 { OP_Integer, 0, 2, 0},
531 { OP_Subtract, 1, 2, 1},
532 { OP_IfPos, 1, 8, 0},
533 { OP_Integer, 0, 1, 0}, /* 6 */
534 { OP_Noop, 0, 0, 0},
535 { OP_ResultRow, 1, 1, 0},
537 VdbeOp *aOp;
538 sqlite3VdbeUsesBtree(v, iDb);
539 if( !zRight ){
540 pParse->nMem += 2;
541 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
542 aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
543 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
544 aOp[0].p1 = iDb;
545 aOp[1].p1 = iDb;
546 aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
547 }else{
548 int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
549 sqlite3BeginWriteOperation(pParse, 0, iDb);
550 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
551 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
552 pDb->pSchema->cache_size = size;
553 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
555 break;
557 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
559 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
561 ** PRAGMA [schema.]page_size
562 ** PRAGMA [schema.]page_size=N
564 ** The first form reports the current setting for the
565 ** database page size in bytes. The second form sets the
566 ** database page size value. The value can only be set if
567 ** the database has not yet been created.
569 case PragTyp_PAGE_SIZE: {
570 Btree *pBt = pDb->pBt;
571 assert( pBt!=0 );
572 if( !zRight ){
573 int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
574 returnSingleInt(v, size);
575 }else{
576 /* Malloc may fail when setting the page-size, as there is an internal
577 ** buffer that the pager module resizes using sqlite3_realloc().
579 db->nextPagesize = sqlite3Atoi(zRight);
580 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,0,0) ){
581 sqlite3OomFault(db);
584 break;
588 ** PRAGMA [schema.]secure_delete
589 ** PRAGMA [schema.]secure_delete=ON/OFF/FAST
591 ** The first form reports the current setting for the
592 ** secure_delete flag. The second form changes the secure_delete
593 ** flag setting and reports the new value.
595 case PragTyp_SECURE_DELETE: {
596 Btree *pBt = pDb->pBt;
597 int b = -1;
598 assert( pBt!=0 );
599 if( zRight ){
600 if( sqlite3_stricmp(zRight, "fast")==0 ){
601 b = 2;
602 }else{
603 b = sqlite3GetBoolean(zRight, 0);
606 if( pId2->n==0 && b>=0 ){
607 int ii;
608 for(ii=0; ii<db->nDb; ii++){
609 sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
612 b = sqlite3BtreeSecureDelete(pBt, b);
613 returnSingleInt(v, b);
614 break;
618 ** PRAGMA [schema.]max_page_count
619 ** PRAGMA [schema.]max_page_count=N
621 ** The first form reports the current setting for the
622 ** maximum number of pages in the database file. The
623 ** second form attempts to change this setting. Both
624 ** forms return the current setting.
626 ** The absolute value of N is used. This is undocumented and might
627 ** change. The only purpose is to provide an easy way to test
628 ** the sqlite3AbsInt32() function.
630 ** PRAGMA [schema.]page_count
632 ** Return the number of pages in the specified database.
634 case PragTyp_PAGE_COUNT: {
635 int iReg;
636 i64 x = 0;
637 sqlite3CodeVerifySchema(pParse, iDb);
638 iReg = ++pParse->nMem;
639 if( sqlite3Tolower(zLeft[0])=='p' ){
640 sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
641 }else{
642 if( zRight && sqlite3DecOrHexToI64(zRight,&x)==0 ){
643 if( x<0 ) x = 0;
644 else if( x>0xfffffffe ) x = 0xfffffffe;
645 }else{
646 x = 0;
648 sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, (int)x);
650 sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
651 break;
655 ** PRAGMA [schema.]locking_mode
656 ** PRAGMA [schema.]locking_mode = (normal|exclusive)
658 case PragTyp_LOCKING_MODE: {
659 const char *zRet = "normal";
660 int eMode = getLockingMode(zRight);
662 if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
663 /* Simple "PRAGMA locking_mode;" statement. This is a query for
664 ** the current default locking mode (which may be different to
665 ** the locking-mode of the main database).
667 eMode = db->dfltLockMode;
668 }else{
669 Pager *pPager;
670 if( pId2->n==0 ){
671 /* This indicates that no database name was specified as part
672 ** of the PRAGMA command. In this case the locking-mode must be
673 ** set on all attached databases, as well as the main db file.
675 ** Also, the sqlite3.dfltLockMode variable is set so that
676 ** any subsequently attached databases also use the specified
677 ** locking mode.
679 int ii;
680 assert(pDb==&db->aDb[0]);
681 for(ii=2; ii<db->nDb; ii++){
682 pPager = sqlite3BtreePager(db->aDb[ii].pBt);
683 sqlite3PagerLockingMode(pPager, eMode);
685 db->dfltLockMode = (u8)eMode;
687 pPager = sqlite3BtreePager(pDb->pBt);
688 eMode = sqlite3PagerLockingMode(pPager, eMode);
691 assert( eMode==PAGER_LOCKINGMODE_NORMAL
692 || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
693 if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
694 zRet = "exclusive";
696 returnSingleText(v, zRet);
697 break;
701 ** PRAGMA [schema.]journal_mode
702 ** PRAGMA [schema.]journal_mode =
703 ** (delete|persist|off|truncate|memory|wal|off)
705 case PragTyp_JOURNAL_MODE: {
706 int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
707 int ii; /* Loop counter */
709 if( zRight==0 ){
710 /* If there is no "=MODE" part of the pragma, do a query for the
711 ** current mode */
712 eMode = PAGER_JOURNALMODE_QUERY;
713 }else{
714 const char *zMode;
715 int n = sqlite3Strlen30(zRight);
716 for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
717 if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
719 if( !zMode ){
720 /* If the "=MODE" part does not match any known journal mode,
721 ** then do a query */
722 eMode = PAGER_JOURNALMODE_QUERY;
724 if( eMode==PAGER_JOURNALMODE_OFF && (db->flags & SQLITE_Defensive)!=0 ){
725 /* Do not allow journal-mode "OFF" in defensive since the database
726 ** can become corrupted using ordinary SQL when the journal is off */
727 eMode = PAGER_JOURNALMODE_QUERY;
730 if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
731 /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
732 iDb = 0;
733 pId2->n = 1;
735 for(ii=db->nDb-1; ii>=0; ii--){
736 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
737 sqlite3VdbeUsesBtree(v, ii);
738 sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
741 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
742 break;
746 ** PRAGMA [schema.]journal_size_limit
747 ** PRAGMA [schema.]journal_size_limit=N
749 ** Get or set the size limit on rollback journal files.
751 case PragTyp_JOURNAL_SIZE_LIMIT: {
752 Pager *pPager = sqlite3BtreePager(pDb->pBt);
753 i64 iLimit = -2;
754 if( zRight ){
755 sqlite3DecOrHexToI64(zRight, &iLimit);
756 if( iLimit<-1 ) iLimit = -1;
758 iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
759 returnSingleInt(v, iLimit);
760 break;
763 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
766 ** PRAGMA [schema.]auto_vacuum
767 ** PRAGMA [schema.]auto_vacuum=N
769 ** Get or set the value of the database 'auto-vacuum' parameter.
770 ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
772 #ifndef SQLITE_OMIT_AUTOVACUUM
773 case PragTyp_AUTO_VACUUM: {
774 Btree *pBt = pDb->pBt;
775 assert( pBt!=0 );
776 if( !zRight ){
777 returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
778 }else{
779 int eAuto = getAutoVacuum(zRight);
780 assert( eAuto>=0 && eAuto<=2 );
781 db->nextAutovac = (u8)eAuto;
782 /* Call SetAutoVacuum() to set initialize the internal auto and
783 ** incr-vacuum flags. This is required in case this connection
784 ** creates the database file. It is important that it is created
785 ** as an auto-vacuum capable db.
787 rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
788 if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
789 /* When setting the auto_vacuum mode to either "full" or
790 ** "incremental", write the value of meta[6] in the database
791 ** file. Before writing to meta[6], check that meta[3] indicates
792 ** that this really is an auto-vacuum capable database.
794 static const int iLn = VDBE_OFFSET_LINENO(2);
795 static const VdbeOpList setMeta6[] = {
796 { OP_Transaction, 0, 1, 0}, /* 0 */
797 { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
798 { OP_If, 1, 0, 0}, /* 2 */
799 { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
800 { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */
802 VdbeOp *aOp;
803 int iAddr = sqlite3VdbeCurrentAddr(v);
804 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
805 aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
806 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
807 aOp[0].p1 = iDb;
808 aOp[1].p1 = iDb;
809 aOp[2].p2 = iAddr+4;
810 aOp[4].p1 = iDb;
811 aOp[4].p3 = eAuto - 1;
812 sqlite3VdbeUsesBtree(v, iDb);
815 break;
817 #endif
820 ** PRAGMA [schema.]incremental_vacuum(N)
822 ** Do N steps of incremental vacuuming on a database.
824 #ifndef SQLITE_OMIT_AUTOVACUUM
825 case PragTyp_INCREMENTAL_VACUUM: {
826 int iLimit = 0, addr;
827 if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
828 iLimit = 0x7fffffff;
830 sqlite3BeginWriteOperation(pParse, 0, iDb);
831 sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
832 addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
833 sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
834 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
835 sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
836 sqlite3VdbeJumpHere(v, addr);
837 break;
839 #endif
841 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
843 ** PRAGMA [schema.]cache_size
844 ** PRAGMA [schema.]cache_size=N
846 ** The first form reports the current local setting for the
847 ** page cache size. The second form sets the local
848 ** page cache size value. If N is positive then that is the
849 ** number of pages in the cache. If N is negative, then the
850 ** number of pages is adjusted so that the cache uses -N kibibytes
851 ** of memory.
853 case PragTyp_CACHE_SIZE: {
854 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
855 if( !zRight ){
856 returnSingleInt(v, pDb->pSchema->cache_size);
857 }else{
858 int size = sqlite3Atoi(zRight);
859 pDb->pSchema->cache_size = size;
860 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
862 break;
866 ** PRAGMA [schema.]cache_spill
867 ** PRAGMA cache_spill=BOOLEAN
868 ** PRAGMA [schema.]cache_spill=N
870 ** The first form reports the current local setting for the
871 ** page cache spill size. The second form turns cache spill on
872 ** or off. When turning cache spill on, the size is set to the
873 ** current cache_size. The third form sets a spill size that
874 ** may be different form the cache size.
875 ** If N is positive then that is the
876 ** number of pages in the cache. If N is negative, then the
877 ** number of pages is adjusted so that the cache uses -N kibibytes
878 ** of memory.
880 ** If the number of cache_spill pages is less then the number of
881 ** cache_size pages, no spilling occurs until the page count exceeds
882 ** the number of cache_size pages.
884 ** The cache_spill=BOOLEAN setting applies to all attached schemas,
885 ** not just the schema specified.
887 case PragTyp_CACHE_SPILL: {
888 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
889 if( !zRight ){
890 returnSingleInt(v,
891 (db->flags & SQLITE_CacheSpill)==0 ? 0 :
892 sqlite3BtreeSetSpillSize(pDb->pBt,0));
893 }else{
894 int size = 1;
895 if( sqlite3GetInt32(zRight, &size) ){
896 sqlite3BtreeSetSpillSize(pDb->pBt, size);
898 if( sqlite3GetBoolean(zRight, size!=0) ){
899 db->flags |= SQLITE_CacheSpill;
900 }else{
901 db->flags &= ~(u64)SQLITE_CacheSpill;
903 setAllPagerFlags(db);
905 break;
909 ** PRAGMA [schema.]mmap_size(N)
911 ** Used to set mapping size limit. The mapping size limit is
912 ** used to limit the aggregate size of all memory mapped regions of the
913 ** database file. If this parameter is set to zero, then memory mapping
914 ** is not used at all. If N is negative, then the default memory map
915 ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
916 ** The parameter N is measured in bytes.
918 ** This value is advisory. The underlying VFS is free to memory map
919 ** as little or as much as it wants. Except, if N is set to 0 then the
920 ** upper layers will never invoke the xFetch interfaces to the VFS.
922 case PragTyp_MMAP_SIZE: {
923 sqlite3_int64 sz;
924 #if SQLITE_MAX_MMAP_SIZE>0
925 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
926 if( zRight ){
927 int ii;
928 sqlite3DecOrHexToI64(zRight, &sz);
929 if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
930 if( pId2->n==0 ) db->szMmap = sz;
931 for(ii=db->nDb-1; ii>=0; ii--){
932 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
933 sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
937 sz = -1;
938 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
939 #else
940 sz = 0;
941 rc = SQLITE_OK;
942 #endif
943 if( rc==SQLITE_OK ){
944 returnSingleInt(v, sz);
945 }else if( rc!=SQLITE_NOTFOUND ){
946 pParse->nErr++;
947 pParse->rc = rc;
949 break;
953 ** PRAGMA temp_store
954 ** PRAGMA temp_store = "default"|"memory"|"file"
956 ** Return or set the local value of the temp_store flag. Changing
957 ** the local value does not make changes to the disk file and the default
958 ** value will be restored the next time the database is opened.
960 ** Note that it is possible for the library compile-time options to
961 ** override this setting
963 case PragTyp_TEMP_STORE: {
964 if( !zRight ){
965 returnSingleInt(v, db->temp_store);
966 }else{
967 changeTempStorage(pParse, zRight);
969 break;
973 ** PRAGMA temp_store_directory
974 ** PRAGMA temp_store_directory = ""|"directory_name"
976 ** Return or set the local value of the temp_store_directory flag. Changing
977 ** the value sets a specific directory to be used for temporary files.
978 ** Setting to a null string reverts to the default temporary directory search.
979 ** If temporary directory is changed, then invalidateTempStorage.
982 case PragTyp_TEMP_STORE_DIRECTORY: {
983 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
984 if( !zRight ){
985 returnSingleText(v, sqlite3_temp_directory);
986 }else{
987 #ifndef SQLITE_OMIT_WSD
988 if( zRight[0] ){
989 int res;
990 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
991 if( rc!=SQLITE_OK || res==0 ){
992 sqlite3ErrorMsg(pParse, "not a writable directory");
993 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
994 goto pragma_out;
997 if( SQLITE_TEMP_STORE==0
998 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
999 || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
1001 invalidateTempStorage(pParse);
1003 sqlite3_free(sqlite3_temp_directory);
1004 if( zRight[0] ){
1005 sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
1006 }else{
1007 sqlite3_temp_directory = 0;
1009 #endif /* SQLITE_OMIT_WSD */
1011 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
1012 break;
1015 #if SQLITE_OS_WIN
1017 ** PRAGMA data_store_directory
1018 ** PRAGMA data_store_directory = ""|"directory_name"
1020 ** Return or set the local value of the data_store_directory flag. Changing
1021 ** the value sets a specific directory to be used for database files that
1022 ** were specified with a relative pathname. Setting to a null string reverts
1023 ** to the default database directory, which for database files specified with
1024 ** a relative path will probably be based on the current directory for the
1025 ** process. Database file specified with an absolute path are not impacted
1026 ** by this setting, regardless of its value.
1029 case PragTyp_DATA_STORE_DIRECTORY: {
1030 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
1031 if( !zRight ){
1032 returnSingleText(v, sqlite3_data_directory);
1033 }else{
1034 #ifndef SQLITE_OMIT_WSD
1035 if( zRight[0] ){
1036 int res;
1037 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
1038 if( rc!=SQLITE_OK || res==0 ){
1039 sqlite3ErrorMsg(pParse, "not a writable directory");
1040 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
1041 goto pragma_out;
1044 sqlite3_free(sqlite3_data_directory);
1045 if( zRight[0] ){
1046 sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
1047 }else{
1048 sqlite3_data_directory = 0;
1050 #endif /* SQLITE_OMIT_WSD */
1052 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
1053 break;
1055 #endif
1057 #if SQLITE_ENABLE_LOCKING_STYLE
1059 ** PRAGMA [schema.]lock_proxy_file
1060 ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
1062 ** Return or set the value of the lock_proxy_file flag. Changing
1063 ** the value sets a specific file to be used for database access locks.
1066 case PragTyp_LOCK_PROXY_FILE: {
1067 if( !zRight ){
1068 Pager *pPager = sqlite3BtreePager(pDb->pBt);
1069 char *proxy_file_path = NULL;
1070 sqlite3_file *pFile = sqlite3PagerFile(pPager);
1071 sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
1072 &proxy_file_path);
1073 returnSingleText(v, proxy_file_path);
1074 }else{
1075 Pager *pPager = sqlite3BtreePager(pDb->pBt);
1076 sqlite3_file *pFile = sqlite3PagerFile(pPager);
1077 int res;
1078 if( zRight[0] ){
1079 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
1080 zRight);
1081 } else {
1082 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
1083 NULL);
1085 if( res!=SQLITE_OK ){
1086 sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
1087 goto pragma_out;
1090 break;
1092 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
1095 ** PRAGMA [schema.]synchronous
1096 ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
1098 ** Return or set the local value of the synchronous flag. Changing
1099 ** the local value does not make changes to the disk file and the
1100 ** default value will be restored the next time the database is
1101 ** opened.
1103 case PragTyp_SYNCHRONOUS: {
1104 if( !zRight ){
1105 returnSingleInt(v, pDb->safety_level-1);
1106 }else{
1107 if( !db->autoCommit ){
1108 sqlite3ErrorMsg(pParse,
1109 "Safety level may not be changed inside a transaction");
1110 }else if( iDb!=1 ){
1111 int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
1112 if( iLevel==0 ) iLevel = 1;
1113 pDb->safety_level = iLevel;
1114 pDb->bSyncSet = 1;
1115 setAllPagerFlags(db);
1118 break;
1120 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
1122 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
1123 case PragTyp_FLAG: {
1124 if( zRight==0 ){
1125 setPragmaResultColumnNames(v, pPragma);
1126 returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
1127 }else{
1128 u64 mask = pPragma->iArg; /* Mask of bits to set or clear. */
1129 if( db->autoCommit==0 ){
1130 /* Foreign key support may not be enabled or disabled while not
1131 ** in auto-commit mode. */
1132 mask &= ~(SQLITE_ForeignKeys);
1134 #if SQLITE_USER_AUTHENTICATION
1135 if( db->auth.authLevel==UAUTH_User ){
1136 /* Do not allow non-admin users to modify the schema arbitrarily */
1137 mask &= ~(SQLITE_WriteSchema);
1139 #endif
1141 if( sqlite3GetBoolean(zRight, 0) ){
1142 if( (mask & SQLITE_WriteSchema)==0
1143 || (db->flags & SQLITE_Defensive)==0
1145 db->flags |= mask;
1147 }else{
1148 db->flags &= ~mask;
1149 if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
1150 if( (mask & SQLITE_WriteSchema)!=0
1151 && sqlite3_stricmp(zRight, "reset")==0
1153 /* IMP: R-60817-01178 If the argument is "RESET" then schema
1154 ** writing is disabled (as with "PRAGMA writable_schema=OFF") and,
1155 ** in addition, the schema is reloaded. */
1156 sqlite3ResetAllSchemasOfConnection(db);
1160 /* Many of the flag-pragmas modify the code generated by the SQL
1161 ** compiler (eg. count_changes). So add an opcode to expire all
1162 ** compiled SQL statements after modifying a pragma value.
1164 sqlite3VdbeAddOp0(v, OP_Expire);
1165 setAllPagerFlags(db);
1167 break;
1169 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
1171 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
1173 ** PRAGMA table_info(<table>)
1175 ** Return a single row for each column of the named table. The columns of
1176 ** the returned data set are:
1178 ** cid: Column id (numbered from left to right, starting at 0)
1179 ** name: Column name
1180 ** type: Column declaration type.
1181 ** notnull: True if 'NOT NULL' is part of column declaration
1182 ** dflt_value: The default value for the column, if any.
1183 ** pk: Non-zero for PK fields.
1185 case PragTyp_TABLE_INFO: if( zRight ){
1186 Table *pTab;
1187 sqlite3CodeVerifyNamedSchema(pParse, zDb);
1188 pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
1189 if( pTab ){
1190 int i, k;
1191 int nHidden = 0;
1192 Column *pCol;
1193 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
1194 pParse->nMem = 7;
1195 sqlite3ViewGetColumnNames(pParse, pTab);
1196 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
1197 int isHidden = 0;
1198 const Expr *pColExpr;
1199 if( pCol->colFlags & COLFLAG_NOINSERT ){
1200 if( pPragma->iArg==0 ){
1201 nHidden++;
1202 continue;
1204 if( pCol->colFlags & COLFLAG_VIRTUAL ){
1205 isHidden = 2; /* GENERATED ALWAYS AS ... VIRTUAL */
1206 }else if( pCol->colFlags & COLFLAG_STORED ){
1207 isHidden = 3; /* GENERATED ALWAYS AS ... STORED */
1208 }else{ assert( pCol->colFlags & COLFLAG_HIDDEN );
1209 isHidden = 1; /* HIDDEN */
1212 if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
1213 k = 0;
1214 }else if( pPk==0 ){
1215 k = 1;
1216 }else{
1217 for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
1219 pColExpr = sqlite3ColumnExpr(pTab,pCol);
1220 assert( pColExpr==0 || pColExpr->op==TK_SPAN || isHidden>=2 );
1221 assert( pColExpr==0 || !ExprHasProperty(pColExpr, EP_IntValue)
1222 || isHidden>=2 );
1223 sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
1224 i-nHidden,
1225 pCol->zCnName,
1226 sqlite3ColumnType(pCol,""),
1227 pCol->notNull ? 1 : 0,
1228 (isHidden>=2 || pColExpr==0) ? 0 : pColExpr->u.zToken,
1230 isHidden);
1234 break;
1237 ** PRAGMA table_list
1239 ** Return a single row for each table, virtual table, or view in the
1240 ** entire schema.
1242 ** schema: Name of attached database hold this table
1243 ** name: Name of the table itself
1244 ** type: "table", "view", "virtual", "shadow"
1245 ** ncol: Number of columns
1246 ** wr: True for a WITHOUT ROWID table
1247 ** strict: True for a STRICT table
1249 case PragTyp_TABLE_LIST: {
1250 int ii;
1251 pParse->nMem = 6;
1252 sqlite3CodeVerifyNamedSchema(pParse, zDb);
1253 for(ii=0; ii<db->nDb; ii++){
1254 HashElem *k;
1255 Hash *pHash;
1256 int initNCol;
1257 if( zDb && sqlite3_stricmp(zDb, db->aDb[ii].zDbSName)!=0 ) continue;
1259 /* Ensure that the Table.nCol field is initialized for all views
1260 ** and virtual tables. Each time we initialize a Table.nCol value
1261 ** for a table, that can potentially disrupt the hash table, so restart
1262 ** the initialization scan.
1264 pHash = &db->aDb[ii].pSchema->tblHash;
1265 initNCol = sqliteHashCount(pHash);
1266 while( initNCol-- ){
1267 for(k=sqliteHashFirst(pHash); 1; k=sqliteHashNext(k) ){
1268 Table *pTab;
1269 if( k==0 ){ initNCol = 0; break; }
1270 pTab = sqliteHashData(k);
1271 if( pTab->nCol==0 ){
1272 char *zSql = sqlite3MPrintf(db, "SELECT*FROM\"%w\"", pTab->zName);
1273 if( zSql ){
1274 sqlite3_stmt *pDummy = 0;
1275 (void)sqlite3_prepare(db, zSql, -1, &pDummy, 0);
1276 (void)sqlite3_finalize(pDummy);
1277 sqlite3DbFree(db, zSql);
1279 if( db->mallocFailed ){
1280 sqlite3ErrorMsg(db->pParse, "out of memory");
1281 db->pParse->rc = SQLITE_NOMEM_BKPT;
1283 pHash = &db->aDb[ii].pSchema->tblHash;
1284 break;
1289 for(k=sqliteHashFirst(pHash); k; k=sqliteHashNext(k) ){
1290 Table *pTab = sqliteHashData(k);
1291 const char *zType;
1292 if( zRight && sqlite3_stricmp(zRight, pTab->zName)!=0 ) continue;
1293 if( IsView(pTab) ){
1294 zType = "view";
1295 }else if( IsVirtual(pTab) ){
1296 zType = "virtual";
1297 }else if( pTab->tabFlags & TF_Shadow ){
1298 zType = "shadow";
1299 }else{
1300 zType = "table";
1302 sqlite3VdbeMultiLoad(v, 1, "sssiii",
1303 db->aDb[ii].zDbSName,
1304 sqlite3PreferredTableName(pTab->zName),
1305 zType,
1306 pTab->nCol,
1307 (pTab->tabFlags & TF_WithoutRowid)!=0,
1308 (pTab->tabFlags & TF_Strict)!=0
1313 break;
1315 #ifdef SQLITE_DEBUG
1316 case PragTyp_STATS: {
1317 Index *pIdx;
1318 HashElem *i;
1319 pParse->nMem = 5;
1320 sqlite3CodeVerifySchema(pParse, iDb);
1321 for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
1322 Table *pTab = sqliteHashData(i);
1323 sqlite3VdbeMultiLoad(v, 1, "ssiii",
1324 sqlite3PreferredTableName(pTab->zName),
1326 pTab->szTabRow,
1327 pTab->nRowLogEst,
1328 pTab->tabFlags);
1329 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1330 sqlite3VdbeMultiLoad(v, 2, "siiiX",
1331 pIdx->zName,
1332 pIdx->szIdxRow,
1333 pIdx->aiRowLogEst[0],
1334 pIdx->hasStat1);
1335 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
1339 break;
1340 #endif
1342 case PragTyp_INDEX_INFO: if( zRight ){
1343 Index *pIdx;
1344 Table *pTab;
1345 pIdx = sqlite3FindIndex(db, zRight, zDb);
1346 if( pIdx==0 ){
1347 /* If there is no index named zRight, check to see if there is a
1348 ** WITHOUT ROWID table named zRight, and if there is, show the
1349 ** structure of the PRIMARY KEY index for that table. */
1350 pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
1351 if( pTab && !HasRowid(pTab) ){
1352 pIdx = sqlite3PrimaryKeyIndex(pTab);
1355 if( pIdx ){
1356 int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
1357 int i;
1358 int mx;
1359 if( pPragma->iArg ){
1360 /* PRAGMA index_xinfo (newer version with more rows and columns) */
1361 mx = pIdx->nColumn;
1362 pParse->nMem = 6;
1363 }else{
1364 /* PRAGMA index_info (legacy version) */
1365 mx = pIdx->nKeyCol;
1366 pParse->nMem = 3;
1368 pTab = pIdx->pTable;
1369 sqlite3CodeVerifySchema(pParse, iIdxDb);
1370 assert( pParse->nMem<=pPragma->nPragCName );
1371 for(i=0; i<mx; i++){
1372 i16 cnum = pIdx->aiColumn[i];
1373 sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
1374 cnum<0 ? 0 : pTab->aCol[cnum].zCnName);
1375 if( pPragma->iArg ){
1376 sqlite3VdbeMultiLoad(v, 4, "isiX",
1377 pIdx->aSortOrder[i],
1378 pIdx->azColl[i],
1379 i<pIdx->nKeyCol);
1381 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
1385 break;
1387 case PragTyp_INDEX_LIST: if( zRight ){
1388 Index *pIdx;
1389 Table *pTab;
1390 int i;
1391 pTab = sqlite3FindTable(db, zRight, zDb);
1392 if( pTab ){
1393 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1394 pParse->nMem = 5;
1395 sqlite3CodeVerifySchema(pParse, iTabDb);
1396 for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
1397 const char *azOrigin[] = { "c", "u", "pk" };
1398 sqlite3VdbeMultiLoad(v, 1, "isisi",
1400 pIdx->zName,
1401 IsUniqueIndex(pIdx),
1402 azOrigin[pIdx->idxType],
1403 pIdx->pPartIdxWhere!=0);
1407 break;
1409 case PragTyp_DATABASE_LIST: {
1410 int i;
1411 pParse->nMem = 3;
1412 for(i=0; i<db->nDb; i++){
1413 if( db->aDb[i].pBt==0 ) continue;
1414 assert( db->aDb[i].zDbSName!=0 );
1415 sqlite3VdbeMultiLoad(v, 1, "iss",
1417 db->aDb[i].zDbSName,
1418 sqlite3BtreeGetFilename(db->aDb[i].pBt));
1421 break;
1423 case PragTyp_COLLATION_LIST: {
1424 int i = 0;
1425 HashElem *p;
1426 pParse->nMem = 2;
1427 for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
1428 CollSeq *pColl = (CollSeq *)sqliteHashData(p);
1429 sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
1432 break;
1434 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
1435 case PragTyp_FUNCTION_LIST: {
1436 int i;
1437 HashElem *j;
1438 FuncDef *p;
1439 int showInternFunc = (db->mDbFlags & DBFLAG_InternalFunc)!=0;
1440 pParse->nMem = 6;
1441 for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
1442 for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
1443 assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
1444 pragmaFunclistLine(v, p, 1, showInternFunc);
1447 for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
1448 p = (FuncDef*)sqliteHashData(j);
1449 assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
1450 pragmaFunclistLine(v, p, 0, showInternFunc);
1453 break;
1455 #ifndef SQLITE_OMIT_VIRTUALTABLE
1456 case PragTyp_MODULE_LIST: {
1457 HashElem *j;
1458 pParse->nMem = 1;
1459 for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
1460 Module *pMod = (Module*)sqliteHashData(j);
1461 sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
1464 break;
1465 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1467 case PragTyp_PRAGMA_LIST: {
1468 int i;
1469 for(i=0; i<ArraySize(aPragmaName); i++){
1470 sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
1473 break;
1474 #endif /* SQLITE_INTROSPECTION_PRAGMAS */
1476 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
1478 #ifndef SQLITE_OMIT_FOREIGN_KEY
1479 case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
1480 FKey *pFK;
1481 Table *pTab;
1482 pTab = sqlite3FindTable(db, zRight, zDb);
1483 if( pTab && IsOrdinaryTable(pTab) ){
1484 pFK = pTab->u.tab.pFKey;
1485 if( pFK ){
1486 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1487 int i = 0;
1488 pParse->nMem = 8;
1489 sqlite3CodeVerifySchema(pParse, iTabDb);
1490 while(pFK){
1491 int j;
1492 for(j=0; j<pFK->nCol; j++){
1493 sqlite3VdbeMultiLoad(v, 1, "iissssss",
1496 pFK->zTo,
1497 pTab->aCol[pFK->aCol[j].iFrom].zCnName,
1498 pFK->aCol[j].zCol,
1499 actionName(pFK->aAction[1]), /* ON UPDATE */
1500 actionName(pFK->aAction[0]), /* ON DELETE */
1501 "NONE");
1503 ++i;
1504 pFK = pFK->pNextFrom;
1509 break;
1510 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1512 #ifndef SQLITE_OMIT_FOREIGN_KEY
1513 #ifndef SQLITE_OMIT_TRIGGER
1514 case PragTyp_FOREIGN_KEY_CHECK: {
1515 FKey *pFK; /* A foreign key constraint */
1516 Table *pTab; /* Child table contain "REFERENCES" keyword */
1517 Table *pParent; /* Parent table that child points to */
1518 Index *pIdx; /* Index in the parent table */
1519 int i; /* Loop counter: Foreign key number for pTab */
1520 int j; /* Loop counter: Field of the foreign key */
1521 HashElem *k; /* Loop counter: Next table in schema */
1522 int x; /* result variable */
1523 int regResult; /* 3 registers to hold a result row */
1524 int regRow; /* Registers to hold a row from pTab */
1525 int addrTop; /* Top of a loop checking foreign keys */
1526 int addrOk; /* Jump here if the key is OK */
1527 int *aiCols; /* child to parent column mapping */
1529 regResult = pParse->nMem+1;
1530 pParse->nMem += 4;
1531 regRow = ++pParse->nMem;
1532 k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
1533 while( k ){
1534 if( zRight ){
1535 pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
1536 k = 0;
1537 }else{
1538 pTab = (Table*)sqliteHashData(k);
1539 k = sqliteHashNext(k);
1541 if( pTab==0 || !IsOrdinaryTable(pTab) || pTab->u.tab.pFKey==0 ) continue;
1542 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1543 zDb = db->aDb[iDb].zDbSName;
1544 sqlite3CodeVerifySchema(pParse, iDb);
1545 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
1546 sqlite3TouchRegister(pParse, pTab->nCol+regRow);
1547 sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
1548 sqlite3VdbeLoadString(v, regResult, pTab->zName);
1549 assert( IsOrdinaryTable(pTab) );
1550 for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
1551 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
1552 if( pParent==0 ) continue;
1553 pIdx = 0;
1554 sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
1555 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
1556 if( x==0 ){
1557 if( pIdx==0 ){
1558 sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
1559 }else{
1560 sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
1561 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1563 }else{
1564 k = 0;
1565 break;
1568 assert( pParse->nErr>0 || pFK==0 );
1569 if( pFK ) break;
1570 if( pParse->nTab<i ) pParse->nTab = i;
1571 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
1572 assert( IsOrdinaryTable(pTab) );
1573 for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
1574 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
1575 pIdx = 0;
1576 aiCols = 0;
1577 if( pParent ){
1578 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
1579 assert( x==0 || db->mallocFailed );
1581 addrOk = sqlite3VdbeMakeLabel(pParse);
1583 /* Generate code to read the child key values into registers
1584 ** regRow..regRow+n. If any of the child key values are NULL, this
1585 ** row cannot cause an FK violation. Jump directly to addrOk in
1586 ** this case. */
1587 sqlite3TouchRegister(pParse, regRow + pFK->nCol);
1588 for(j=0; j<pFK->nCol; j++){
1589 int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
1590 sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
1591 sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
1594 /* Generate code to query the parent index for a matching parent
1595 ** key. If a match is found, jump to addrOk. */
1596 if( pIdx ){
1597 sqlite3VdbeAddOp4(v, OP_Affinity, regRow, pFK->nCol, 0,
1598 sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
1599 sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regRow, pFK->nCol);
1600 VdbeCoverage(v);
1601 }else if( pParent ){
1602 int jmp = sqlite3VdbeCurrentAddr(v)+2;
1603 sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
1604 sqlite3VdbeGoto(v, addrOk);
1605 assert( pFK->nCol==1 || db->mallocFailed );
1608 /* Generate code to report an FK violation to the caller. */
1609 if( HasRowid(pTab) ){
1610 sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
1611 }else{
1612 sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
1614 sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
1615 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
1616 sqlite3VdbeResolveLabel(v, addrOk);
1617 sqlite3DbFree(db, aiCols);
1619 sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
1620 sqlite3VdbeJumpHere(v, addrTop);
1623 break;
1624 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
1625 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1627 #ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA
1628 /* Reinstall the LIKE and GLOB functions. The variant of LIKE
1629 ** used will be case sensitive or not depending on the RHS.
1631 case PragTyp_CASE_SENSITIVE_LIKE: {
1632 if( zRight ){
1633 sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
1636 break;
1637 #endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */
1639 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
1640 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
1641 #endif
1643 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
1644 /* PRAGMA integrity_check
1645 ** PRAGMA integrity_check(N)
1646 ** PRAGMA quick_check
1647 ** PRAGMA quick_check(N)
1649 ** Verify the integrity of the database.
1651 ** The "quick_check" is reduced version of
1652 ** integrity_check designed to detect most database corruption
1653 ** without the overhead of cross-checking indexes. Quick_check
1654 ** is linear time whereas integrity_check is O(NlogN).
1656 ** The maximum number of errors is 100 by default. A different default
1657 ** can be specified using a numeric parameter N.
1659 ** Or, the parameter N can be the name of a table. In that case, only
1660 ** the one table named is verified. The freelist is only verified if
1661 ** the named table is "sqlite_schema" (or one of its aliases).
1663 ** All schemas are checked by default. To check just a single
1664 ** schema, use the form:
1666 ** PRAGMA schema.integrity_check;
1668 case PragTyp_INTEGRITY_CHECK: {
1669 int i, j, addr, mxErr;
1670 Table *pObjTab = 0; /* Check only this one table, if not NULL */
1672 int isQuick = (sqlite3Tolower(zLeft[0])=='q');
1674 /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
1675 ** then iDb is set to the index of the database identified by <db>.
1676 ** In this case, the integrity of database iDb only is verified by
1677 ** the VDBE created below.
1679 ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
1680 ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
1681 ** to -1 here, to indicate that the VDBE should verify the integrity
1682 ** of all attached databases. */
1683 assert( iDb>=0 );
1684 assert( iDb==0 || pId2->z );
1685 if( pId2->z==0 ) iDb = -1;
1687 /* Initialize the VDBE program */
1688 pParse->nMem = 6;
1690 /* Set the maximum error count */
1691 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
1692 if( zRight ){
1693 if( sqlite3GetInt32(zRight, &mxErr) ){
1694 if( mxErr<=0 ){
1695 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
1697 }else{
1698 pObjTab = sqlite3LocateTable(pParse, 0, zRight,
1699 iDb>=0 ? db->aDb[iDb].zDbSName : 0);
1702 sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
1704 /* Do an integrity check on each database file */
1705 for(i=0; i<db->nDb; i++){
1706 HashElem *x; /* For looping over tables in the schema */
1707 Hash *pTbls; /* Set of all tables in the schema */
1708 int *aRoot; /* Array of root page numbers of all btrees */
1709 int cnt = 0; /* Number of entries in aRoot[] */
1710 int mxIdx = 0; /* Maximum number of indexes for any table */
1712 if( OMIT_TEMPDB && i==1 ) continue;
1713 if( iDb>=0 && i!=iDb ) continue;
1715 sqlite3CodeVerifySchema(pParse, i);
1716 pParse->okConstFactor = 0; /* tag-20230327-1 */
1718 /* Do an integrity check of the B-Tree
1720 ** Begin by finding the root pages numbers
1721 ** for all tables and indices in the database.
1723 assert( sqlite3SchemaMutexHeld(db, i, 0) );
1724 pTbls = &db->aDb[i].pSchema->tblHash;
1725 for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
1726 Table *pTab = sqliteHashData(x); /* Current table */
1727 Index *pIdx; /* An index on pTab */
1728 int nIdx; /* Number of indexes on pTab */
1729 if( pObjTab && pObjTab!=pTab ) continue;
1730 if( HasRowid(pTab) ) cnt++;
1731 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
1732 if( nIdx>mxIdx ) mxIdx = nIdx;
1734 if( cnt==0 ) continue;
1735 if( pObjTab ) cnt++;
1736 aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
1737 if( aRoot==0 ) break;
1738 cnt = 0;
1739 if( pObjTab ) aRoot[++cnt] = 0;
1740 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
1741 Table *pTab = sqliteHashData(x);
1742 Index *pIdx;
1743 if( pObjTab && pObjTab!=pTab ) continue;
1744 if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
1745 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1746 aRoot[++cnt] = pIdx->tnum;
1749 aRoot[0] = cnt;
1751 /* Make sure sufficient number of registers have been allocated */
1752 sqlite3TouchRegister(pParse, 8+mxIdx);
1753 sqlite3ClearTempRegCache(pParse);
1755 /* Do the b-tree integrity checks */
1756 sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
1757 sqlite3VdbeChangeP5(v, (u8)i);
1758 addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
1759 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
1760 sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
1761 P4_DYNAMIC);
1762 sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
1763 integrityCheckResultRow(v);
1764 sqlite3VdbeJumpHere(v, addr);
1766 /* Make sure all the indices are constructed correctly.
1768 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
1769 Table *pTab = sqliteHashData(x);
1770 Index *pIdx, *pPk;
1771 Index *pPrior = 0; /* Previous index */
1772 int loopTop;
1773 int iDataCur, iIdxCur;
1774 int r1 = -1;
1775 int bStrict; /* True for a STRICT table */
1776 int r2; /* Previous key for WITHOUT ROWID tables */
1777 int mxCol; /* Maximum non-virtual column number */
1779 if( pObjTab && pObjTab!=pTab ) continue;
1780 if( !IsOrdinaryTable(pTab) ) continue;
1781 if( isQuick || HasRowid(pTab) ){
1782 pPk = 0;
1783 r2 = 0;
1784 }else{
1785 pPk = sqlite3PrimaryKeyIndex(pTab);
1786 r2 = sqlite3GetTempRange(pParse, pPk->nKeyCol);
1787 sqlite3VdbeAddOp3(v, OP_Null, 1, r2, r2+pPk->nKeyCol-1);
1789 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
1790 1, 0, &iDataCur, &iIdxCur);
1791 /* reg[7] counts the number of entries in the table.
1792 ** reg[8+i] counts the number of entries in the i-th index
1794 sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
1795 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
1796 sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
1798 assert( pParse->nMem>=8+j );
1799 assert( sqlite3NoTempsInRange(pParse,1,7+j) );
1800 sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
1801 loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
1803 /* Fetch the right-most column from the table. This will cause
1804 ** the entire record header to be parsed and sanity checked. It
1805 ** will also prepopulate the cursor column cache that is used
1806 ** by the OP_IsType code, so it is a required step.
1808 assert( !IsVirtual(pTab) );
1809 if( HasRowid(pTab) ){
1810 mxCol = -1;
1811 for(j=0; j<pTab->nCol; j++){
1812 if( (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)==0 ) mxCol++;
1814 if( mxCol==pTab->iPKey ) mxCol--;
1815 }else{
1816 /* COLFLAG_VIRTUAL columns are not included in the WITHOUT ROWID
1817 ** PK index column-count, so there is no need to account for them
1818 ** in this case. */
1819 mxCol = sqlite3PrimaryKeyIndex(pTab)->nColumn-1;
1821 if( mxCol>=0 ){
1822 sqlite3VdbeAddOp3(v, OP_Column, iDataCur, mxCol, 3);
1823 sqlite3VdbeTypeofColumn(v, 3);
1826 if( !isQuick ){
1827 if( pPk ){
1828 /* Verify WITHOUT ROWID keys are in ascending order */
1829 int a1;
1830 char *zErr;
1831 a1 = sqlite3VdbeAddOp4Int(v, OP_IdxGT, iDataCur, 0,r2,pPk->nKeyCol);
1832 VdbeCoverage(v);
1833 sqlite3VdbeAddOp1(v, OP_IsNull, r2); VdbeCoverage(v);
1834 zErr = sqlite3MPrintf(db,
1835 "row not in PRIMARY KEY order for %s",
1836 pTab->zName);
1837 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1838 integrityCheckResultRow(v);
1839 sqlite3VdbeJumpHere(v, a1);
1840 sqlite3VdbeJumpHere(v, a1+1);
1841 for(j=0; j<pPk->nKeyCol; j++){
1842 sqlite3ExprCodeLoadIndexColumn(pParse, pPk, iDataCur, j, r2+j);
1846 /* Verify datatypes for all columns:
1848 ** (1) NOT NULL columns may not contain a NULL
1849 ** (2) Datatype must be exact for non-ANY columns in STRICT tables
1850 ** (3) Datatype for TEXT columns in non-STRICT tables must be
1851 ** NULL, TEXT, or BLOB.
1852 ** (4) Datatype for numeric columns in non-STRICT tables must not
1853 ** be a TEXT value that can be losslessly converted to numeric.
1855 bStrict = (pTab->tabFlags & TF_Strict)!=0;
1856 for(j=0; j<pTab->nCol; j++){
1857 char *zErr;
1858 Column *pCol = pTab->aCol + j; /* The column to be checked */
1859 int labelError; /* Jump here to report an error */
1860 int labelOk; /* Jump here if all looks ok */
1861 int p1, p3, p4; /* Operands to the OP_IsType opcode */
1862 int doTypeCheck; /* Check datatypes (besides NOT NULL) */
1864 if( j==pTab->iPKey ) continue;
1865 if( bStrict ){
1866 doTypeCheck = pCol->eCType>COLTYPE_ANY;
1867 }else{
1868 doTypeCheck = pCol->affinity>SQLITE_AFF_BLOB;
1870 if( pCol->notNull==0 && !doTypeCheck ) continue;
1872 /* Compute the operands that will be needed for OP_IsType */
1873 p4 = SQLITE_NULL;
1874 if( pCol->colFlags & COLFLAG_VIRTUAL ){
1875 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
1876 p1 = -1;
1877 p3 = 3;
1878 }else{
1879 if( pCol->iDflt ){
1880 sqlite3_value *pDfltValue = 0;
1881 sqlite3ValueFromExpr(db, sqlite3ColumnExpr(pTab,pCol), ENC(db),
1882 pCol->affinity, &pDfltValue);
1883 if( pDfltValue ){
1884 p4 = sqlite3_value_type(pDfltValue);
1885 sqlite3ValueFree(pDfltValue);
1888 p1 = iDataCur;
1889 if( !HasRowid(pTab) ){
1890 testcase( j!=sqlite3TableColumnToStorage(pTab, j) );
1891 p3 = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), j);
1892 }else{
1893 p3 = sqlite3TableColumnToStorage(pTab,j);
1894 testcase( p3!=j);
1898 labelError = sqlite3VdbeMakeLabel(pParse);
1899 labelOk = sqlite3VdbeMakeLabel(pParse);
1900 if( pCol->notNull ){
1901 /* (1) NOT NULL columns may not contain a NULL */
1902 int jmp3;
1903 int jmp2 = sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
1904 VdbeCoverage(v);
1905 if( p1<0 ){
1906 sqlite3VdbeChangeP5(v, 0x0f); /* INT, REAL, TEXT, or BLOB */
1907 jmp3 = jmp2;
1908 }else{
1909 sqlite3VdbeChangeP5(v, 0x0d); /* INT, TEXT, or BLOB */
1910 /* OP_IsType does not detect NaN values in the database file
1911 ** which should be treated as a NULL. So if the header type
1912 ** is REAL, we have to load the actual data using OP_Column
1913 ** to reliably determine if the value is a NULL. */
1914 sqlite3VdbeAddOp3(v, OP_Column, p1, p3, 3);
1915 sqlite3ColumnDefault(v, pTab, j, 3);
1916 jmp3 = sqlite3VdbeAddOp2(v, OP_NotNull, 3, labelOk);
1917 VdbeCoverage(v);
1919 zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
1920 pCol->zCnName);
1921 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1922 if( doTypeCheck ){
1923 sqlite3VdbeGoto(v, labelError);
1924 sqlite3VdbeJumpHere(v, jmp2);
1925 sqlite3VdbeJumpHere(v, jmp3);
1926 }else{
1927 /* VDBE byte code will fall thru */
1930 if( bStrict && doTypeCheck ){
1931 /* (2) Datatype must be exact for non-ANY columns in STRICT tables*/
1932 static unsigned char aStdTypeMask[] = {
1933 0x1f, /* ANY */
1934 0x18, /* BLOB */
1935 0x11, /* INT */
1936 0x11, /* INTEGER */
1937 0x13, /* REAL */
1938 0x14 /* TEXT */
1940 sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
1941 assert( pCol->eCType>=1 && pCol->eCType<=sizeof(aStdTypeMask) );
1942 sqlite3VdbeChangeP5(v, aStdTypeMask[pCol->eCType-1]);
1943 VdbeCoverage(v);
1944 zErr = sqlite3MPrintf(db, "non-%s value in %s.%s",
1945 sqlite3StdType[pCol->eCType-1],
1946 pTab->zName, pTab->aCol[j].zCnName);
1947 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1948 }else if( !bStrict && pCol->affinity==SQLITE_AFF_TEXT ){
1949 /* (3) Datatype for TEXT columns in non-STRICT tables must be
1950 ** NULL, TEXT, or BLOB. */
1951 sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
1952 sqlite3VdbeChangeP5(v, 0x1c); /* NULL, TEXT, or BLOB */
1953 VdbeCoverage(v);
1954 zErr = sqlite3MPrintf(db, "NUMERIC value in %s.%s",
1955 pTab->zName, pTab->aCol[j].zCnName);
1956 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1957 }else if( !bStrict && pCol->affinity>=SQLITE_AFF_NUMERIC ){
1958 /* (4) Datatype for numeric columns in non-STRICT tables must not
1959 ** be a TEXT value that can be converted to numeric. */
1960 sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
1961 sqlite3VdbeChangeP5(v, 0x1b); /* NULL, INT, FLOAT, or BLOB */
1962 VdbeCoverage(v);
1963 if( p1>=0 ){
1964 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
1966 sqlite3VdbeAddOp4(v, OP_Affinity, 3, 1, 0, "C", P4_STATIC);
1967 sqlite3VdbeAddOp4Int(v, OP_IsType, -1, labelOk, 3, p4);
1968 sqlite3VdbeChangeP5(v, 0x1c); /* NULL, TEXT, or BLOB */
1969 VdbeCoverage(v);
1970 zErr = sqlite3MPrintf(db, "TEXT value in %s.%s",
1971 pTab->zName, pTab->aCol[j].zCnName);
1972 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1974 sqlite3VdbeResolveLabel(v, labelError);
1975 integrityCheckResultRow(v);
1976 sqlite3VdbeResolveLabel(v, labelOk);
1978 /* Verify CHECK constraints */
1979 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
1980 ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
1981 if( db->mallocFailed==0 ){
1982 int addrCkFault = sqlite3VdbeMakeLabel(pParse);
1983 int addrCkOk = sqlite3VdbeMakeLabel(pParse);
1984 char *zErr;
1985 int k;
1986 pParse->iSelfTab = iDataCur + 1;
1987 for(k=pCheck->nExpr-1; k>0; k--){
1988 sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
1990 sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
1991 SQLITE_JUMPIFNULL);
1992 sqlite3VdbeResolveLabel(v, addrCkFault);
1993 pParse->iSelfTab = 0;
1994 zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
1995 pTab->zName);
1996 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1997 integrityCheckResultRow(v);
1998 sqlite3VdbeResolveLabel(v, addrCkOk);
2000 sqlite3ExprListDelete(db, pCheck);
2002 if( !isQuick ){ /* Omit the remaining tests for quick_check */
2003 /* Validate index entries for the current row */
2004 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
2005 int jmp2, jmp3, jmp4, jmp5, label6;
2006 int kk;
2007 int ckUniq = sqlite3VdbeMakeLabel(pParse);
2008 if( pPk==pIdx ) continue;
2009 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
2010 pPrior, r1);
2011 pPrior = pIdx;
2012 sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
2013 /* Verify that an index entry exists for the current table row */
2014 jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
2015 pIdx->nColumn); VdbeCoverage(v);
2016 sqlite3VdbeLoadString(v, 3, "row ");
2017 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
2018 sqlite3VdbeLoadString(v, 4, " missing from index ");
2019 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
2020 jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
2021 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
2022 jmp4 = integrityCheckResultRow(v);
2023 sqlite3VdbeJumpHere(v, jmp2);
2025 /* The OP_IdxRowid opcode is an optimized version of OP_Column
2026 ** that extracts the rowid off the end of the index record.
2027 ** But it only works correctly if index record does not have
2028 ** any extra bytes at the end. Verify that this is the case. */
2029 if( HasRowid(pTab) ){
2030 int jmp7;
2031 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur+j, 3);
2032 jmp7 = sqlite3VdbeAddOp3(v, OP_Eq, 3, 0, r1+pIdx->nColumn-1);
2033 VdbeCoverageNeverNull(v);
2034 sqlite3VdbeLoadString(v, 3,
2035 "rowid not at end-of-record for row ");
2036 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
2037 sqlite3VdbeLoadString(v, 4, " of index ");
2038 sqlite3VdbeGoto(v, jmp5-1);
2039 sqlite3VdbeJumpHere(v, jmp7);
2042 /* Any indexed columns with non-BINARY collations must still hold
2043 ** the exact same text value as the table. */
2044 label6 = 0;
2045 for(kk=0; kk<pIdx->nKeyCol; kk++){
2046 if( pIdx->azColl[kk]==sqlite3StrBINARY ) continue;
2047 if( label6==0 ) label6 = sqlite3VdbeMakeLabel(pParse);
2048 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur+j, kk, 3);
2049 sqlite3VdbeAddOp3(v, OP_Ne, 3, label6, r1+kk); VdbeCoverage(v);
2051 if( label6 ){
2052 int jmp6 = sqlite3VdbeAddOp0(v, OP_Goto);
2053 sqlite3VdbeResolveLabel(v, label6);
2054 sqlite3VdbeLoadString(v, 3, "row ");
2055 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
2056 sqlite3VdbeLoadString(v, 4, " values differ from index ");
2057 sqlite3VdbeGoto(v, jmp5-1);
2058 sqlite3VdbeJumpHere(v, jmp6);
2061 /* For UNIQUE indexes, verify that only one entry exists with the
2062 ** current key. The entry is unique if (1) any column is NULL
2063 ** or (2) the next entry has a different key */
2064 if( IsUniqueIndex(pIdx) ){
2065 int uniqOk = sqlite3VdbeMakeLabel(pParse);
2066 int jmp6;
2067 for(kk=0; kk<pIdx->nKeyCol; kk++){
2068 int iCol = pIdx->aiColumn[kk];
2069 assert( iCol!=XN_ROWID && iCol<pTab->nCol );
2070 if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
2071 sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
2072 VdbeCoverage(v);
2074 jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
2075 sqlite3VdbeGoto(v, uniqOk);
2076 sqlite3VdbeJumpHere(v, jmp6);
2077 sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
2078 pIdx->nKeyCol); VdbeCoverage(v);
2079 sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
2080 sqlite3VdbeGoto(v, jmp5);
2081 sqlite3VdbeResolveLabel(v, uniqOk);
2083 sqlite3VdbeJumpHere(v, jmp4);
2084 sqlite3ResolvePartIdxLabel(pParse, jmp3);
2087 sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
2088 sqlite3VdbeJumpHere(v, loopTop-1);
2089 if( !isQuick ){
2090 sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
2091 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
2092 if( pPk==pIdx ) continue;
2093 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
2094 addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
2095 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2096 sqlite3VdbeLoadString(v, 4, pIdx->zName);
2097 sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
2098 integrityCheckResultRow(v);
2099 sqlite3VdbeJumpHere(v, addr);
2101 if( pPk ){
2102 sqlite3ReleaseTempRange(pParse, r2, pPk->nKeyCol);
2107 #ifndef SQLITE_OMIT_VIRTUALTABLE
2108 /* Second pass to invoke the xIntegrity method on all virtual
2109 ** tables.
2111 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
2112 Table *pTab = sqliteHashData(x);
2113 sqlite3_vtab *pVTab;
2114 int a1;
2115 if( pObjTab && pObjTab!=pTab ) continue;
2116 if( IsOrdinaryTable(pTab) ) continue;
2117 if( !IsVirtual(pTab) ) continue;
2118 if( pTab->nCol<=0 ){
2119 const char *zMod = pTab->u.vtab.azArg[0];
2120 if( sqlite3HashFind(&db->aModule, zMod)==0 ) continue;
2122 sqlite3ViewGetColumnNames(pParse, pTab);
2123 if( pTab->u.vtab.p==0 ) continue;
2124 pVTab = pTab->u.vtab.p->pVtab;
2125 if( NEVER(pVTab==0) ) continue;
2126 if( NEVER(pVTab->pModule==0) ) continue;
2127 if( pVTab->pModule->iVersion<4 ) continue;
2128 if( pVTab->pModule->xIntegrity==0 ) continue;
2129 sqlite3VdbeAddOp3(v, OP_VCheck, i, 3, isQuick);
2130 pTab->nTabRef++;
2131 sqlite3VdbeAppendP4(v, pTab, P4_TABLEREF);
2132 a1 = sqlite3VdbeAddOp1(v, OP_IsNull, 3); VdbeCoverage(v);
2133 integrityCheckResultRow(v);
2134 sqlite3VdbeJumpHere(v, a1);
2135 continue;
2137 #endif
2140 static const int iLn = VDBE_OFFSET_LINENO(2);
2141 static const VdbeOpList endCode[] = {
2142 { OP_AddImm, 1, 0, 0}, /* 0 */
2143 { OP_IfNotZero, 1, 4, 0}, /* 1 */
2144 { OP_String8, 0, 3, 0}, /* 2 */
2145 { OP_ResultRow, 3, 1, 0}, /* 3 */
2146 { OP_Halt, 0, 0, 0}, /* 4 */
2147 { OP_String8, 0, 3, 0}, /* 5 */
2148 { OP_Goto, 0, 3, 0}, /* 6 */
2150 VdbeOp *aOp;
2152 aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
2153 if( aOp ){
2154 aOp[0].p2 = 1-mxErr;
2155 aOp[2].p4type = P4_STATIC;
2156 aOp[2].p4.z = "ok";
2157 aOp[5].p4type = P4_STATIC;
2158 aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
2160 sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
2163 break;
2164 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
2166 #ifndef SQLITE_OMIT_UTF16
2168 ** PRAGMA encoding
2169 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
2171 ** In its first form, this pragma returns the encoding of the main
2172 ** database. If the database is not initialized, it is initialized now.
2174 ** The second form of this pragma is a no-op if the main database file
2175 ** has not already been initialized. In this case it sets the default
2176 ** encoding that will be used for the main database file if a new file
2177 ** is created. If an existing main database file is opened, then the
2178 ** default text encoding for the existing database is used.
2180 ** In all cases new databases created using the ATTACH command are
2181 ** created to use the same default text encoding as the main database. If
2182 ** the main database has not been initialized and/or created when ATTACH
2183 ** is executed, this is done before the ATTACH operation.
2185 ** In the second form this pragma sets the text encoding to be used in
2186 ** new database files created using this database handle. It is only
2187 ** useful if invoked immediately after the main database i
2189 case PragTyp_ENCODING: {
2190 static const struct EncName {
2191 char *zName;
2192 u8 enc;
2193 } encnames[] = {
2194 { "UTF8", SQLITE_UTF8 },
2195 { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
2196 { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
2197 { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
2198 { "UTF16le", SQLITE_UTF16LE },
2199 { "UTF16be", SQLITE_UTF16BE },
2200 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
2201 { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
2202 { 0, 0 }
2204 const struct EncName *pEnc;
2205 if( !zRight ){ /* "PRAGMA encoding" */
2206 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
2207 assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
2208 assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
2209 assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
2210 returnSingleText(v, encnames[ENC(pParse->db)].zName);
2211 }else{ /* "PRAGMA encoding = XXX" */
2212 /* Only change the value of sqlite.enc if the database handle is not
2213 ** initialized. If the main database exists, the new sqlite.enc value
2214 ** will be overwritten when the schema is next loaded. If it does not
2215 ** already exists, it will be created to use the new encoding value.
2217 if( (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
2218 for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
2219 if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
2220 u8 enc = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
2221 SCHEMA_ENC(db) = enc;
2222 sqlite3SetTextEncoding(db, enc);
2223 break;
2226 if( !pEnc->zName ){
2227 sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
2232 break;
2233 #endif /* SQLITE_OMIT_UTF16 */
2235 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
2237 ** PRAGMA [schema.]schema_version
2238 ** PRAGMA [schema.]schema_version = <integer>
2240 ** PRAGMA [schema.]user_version
2241 ** PRAGMA [schema.]user_version = <integer>
2243 ** PRAGMA [schema.]freelist_count
2245 ** PRAGMA [schema.]data_version
2247 ** PRAGMA [schema.]application_id
2248 ** PRAGMA [schema.]application_id = <integer>
2250 ** The pragma's schema_version and user_version are used to set or get
2251 ** the value of the schema-version and user-version, respectively. Both
2252 ** the schema-version and the user-version are 32-bit signed integers
2253 ** stored in the database header.
2255 ** The schema-cookie is usually only manipulated internally by SQLite. It
2256 ** is incremented by SQLite whenever the database schema is modified (by
2257 ** creating or dropping a table or index). The schema version is used by
2258 ** SQLite each time a query is executed to ensure that the internal cache
2259 ** of the schema used when compiling the SQL query matches the schema of
2260 ** the database against which the compiled query is actually executed.
2261 ** Subverting this mechanism by using "PRAGMA schema_version" to modify
2262 ** the schema-version is potentially dangerous and may lead to program
2263 ** crashes or database corruption. Use with caution!
2265 ** The user-version is not used internally by SQLite. It may be used by
2266 ** applications for any purpose.
2268 case PragTyp_HEADER_VALUE: {
2269 int iCookie = pPragma->iArg; /* Which cookie to read or write */
2270 sqlite3VdbeUsesBtree(v, iDb);
2271 if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
2272 /* Write the specified cookie value */
2273 static const VdbeOpList setCookie[] = {
2274 { OP_Transaction, 0, 1, 0}, /* 0 */
2275 { OP_SetCookie, 0, 0, 0}, /* 1 */
2277 VdbeOp *aOp;
2278 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
2279 aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
2280 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
2281 aOp[0].p1 = iDb;
2282 aOp[1].p1 = iDb;
2283 aOp[1].p2 = iCookie;
2284 aOp[1].p3 = sqlite3Atoi(zRight);
2285 aOp[1].p5 = 1;
2286 if( iCookie==BTREE_SCHEMA_VERSION && (db->flags & SQLITE_Defensive)!=0 ){
2287 /* Do not allow the use of PRAGMA schema_version=VALUE in defensive
2288 ** mode. Change the OP_SetCookie opcode into a no-op. */
2289 aOp[1].opcode = OP_Noop;
2291 }else{
2292 /* Read the specified cookie value */
2293 static const VdbeOpList readCookie[] = {
2294 { OP_Transaction, 0, 0, 0}, /* 0 */
2295 { OP_ReadCookie, 0, 1, 0}, /* 1 */
2296 { OP_ResultRow, 1, 1, 0}
2298 VdbeOp *aOp;
2299 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
2300 aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
2301 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
2302 aOp[0].p1 = iDb;
2303 aOp[1].p1 = iDb;
2304 aOp[1].p3 = iCookie;
2305 sqlite3VdbeReusable(v);
2308 break;
2309 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
2311 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
2313 ** PRAGMA compile_options
2315 ** Return the names of all compile-time options used in this build,
2316 ** one option per row.
2318 case PragTyp_COMPILE_OPTIONS: {
2319 int i = 0;
2320 const char *zOpt;
2321 pParse->nMem = 1;
2322 while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
2323 sqlite3VdbeLoadString(v, 1, zOpt);
2324 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
2326 sqlite3VdbeReusable(v);
2328 break;
2329 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
2331 #ifndef SQLITE_OMIT_WAL
2333 ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
2335 ** Checkpoint the database.
2337 case PragTyp_WAL_CHECKPOINT: {
2338 int iBt = (pId2->z?iDb:SQLITE_MAX_DB);
2339 int eMode = SQLITE_CHECKPOINT_PASSIVE;
2340 if( zRight ){
2341 if( sqlite3StrICmp(zRight, "full")==0 ){
2342 eMode = SQLITE_CHECKPOINT_FULL;
2343 }else if( sqlite3StrICmp(zRight, "restart")==0 ){
2344 eMode = SQLITE_CHECKPOINT_RESTART;
2345 }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
2346 eMode = SQLITE_CHECKPOINT_TRUNCATE;
2349 pParse->nMem = 3;
2350 sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
2351 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
2353 break;
2356 ** PRAGMA wal_autocheckpoint
2357 ** PRAGMA wal_autocheckpoint = N
2359 ** Configure a database connection to automatically checkpoint a database
2360 ** after accumulating N frames in the log. Or query for the current value
2361 ** of N.
2363 case PragTyp_WAL_AUTOCHECKPOINT: {
2364 if( zRight ){
2365 sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
2367 returnSingleInt(v,
2368 db->xWalCallback==sqlite3WalDefaultHook ?
2369 SQLITE_PTR_TO_INT(db->pWalArg) : 0);
2371 break;
2372 #endif
2375 ** PRAGMA shrink_memory
2377 ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
2378 ** connection on which it is invoked to free up as much memory as it
2379 ** can, by calling sqlite3_db_release_memory().
2381 case PragTyp_SHRINK_MEMORY: {
2382 sqlite3_db_release_memory(db);
2383 break;
2387 ** PRAGMA optimize
2388 ** PRAGMA optimize(MASK)
2389 ** PRAGMA schema.optimize
2390 ** PRAGMA schema.optimize(MASK)
2392 ** Attempt to optimize the database. All schemas are optimized in the first
2393 ** two forms, and only the specified schema is optimized in the latter two.
2395 ** The details of optimizations performed by this pragma are expected
2396 ** to change and improve over time. Applications should anticipate that
2397 ** this pragma will perform new optimizations in future releases.
2399 ** The optional argument is a bitmask of optimizations to perform:
2401 ** 0x0001 Debugging mode. Do not actually perform any optimizations
2402 ** but instead return one line of text for each optimization
2403 ** that would have been done. Off by default.
2405 ** 0x0002 Run ANALYZE on tables that might benefit. On by default.
2406 ** See below for additional information.
2408 ** 0x0004 (Not yet implemented) Record usage and performance
2409 ** information from the current session in the
2410 ** database file so that it will be available to "optimize"
2411 ** pragmas run by future database connections.
2413 ** 0x0008 (Not yet implemented) Create indexes that might have
2414 ** been helpful to recent queries
2416 ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all
2417 ** of the optimizations listed above except Debug Mode, including new
2418 ** optimizations that have not yet been invented. If new optimizations are
2419 ** ever added that should be off by default, those off-by-default
2420 ** optimizations will have bitmasks of 0x10000 or larger.
2422 ** DETERMINATION OF WHEN TO RUN ANALYZE
2424 ** In the current implementation, a table is analyzed if only if all of
2425 ** the following are true:
2427 ** (1) MASK bit 0x02 is set.
2429 ** (2) The query planner used sqlite_stat1-style statistics for one or
2430 ** more indexes of the table at some point during the lifetime of
2431 ** the current connection.
2433 ** (3) One or more indexes of the table are currently unanalyzed OR
2434 ** the number of rows in the table has increased by 25 times or more
2435 ** since the last time ANALYZE was run.
2437 ** The rules for when tables are analyzed are likely to change in
2438 ** future releases.
2440 case PragTyp_OPTIMIZE: {
2441 int iDbLast; /* Loop termination point for the schema loop */
2442 int iTabCur; /* Cursor for a table whose size needs checking */
2443 HashElem *k; /* Loop over tables of a schema */
2444 Schema *pSchema; /* The current schema */
2445 Table *pTab; /* A table in the schema */
2446 Index *pIdx; /* An index of the table */
2447 LogEst szThreshold; /* Size threshold above which reanalysis needed */
2448 char *zSubSql; /* SQL statement for the OP_SqlExec opcode */
2449 u32 opMask; /* Mask of operations to perform */
2451 if( zRight ){
2452 opMask = (u32)sqlite3Atoi(zRight);
2453 if( (opMask & 0x02)==0 ) break;
2454 }else{
2455 opMask = 0xfffe;
2457 iTabCur = pParse->nTab++;
2458 for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
2459 if( iDb==1 ) continue;
2460 sqlite3CodeVerifySchema(pParse, iDb);
2461 pSchema = db->aDb[iDb].pSchema;
2462 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
2463 pTab = (Table*)sqliteHashData(k);
2465 /* If table pTab has not been used in a way that would benefit from
2466 ** having analysis statistics during the current session, then skip it.
2467 ** This also has the effect of skipping virtual tables and views */
2468 if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
2470 /* Reanalyze if the table is 25 times larger than the last analysis */
2471 szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
2472 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2473 if( !pIdx->hasStat1 ){
2474 szThreshold = 0; /* Always analyze if any index lacks statistics */
2475 break;
2478 if( szThreshold ){
2479 sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
2480 sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
2481 sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
2482 VdbeCoverage(v);
2484 zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
2485 db->aDb[iDb].zDbSName, pTab->zName);
2486 if( opMask & 0x01 ){
2487 int r1 = sqlite3GetTempReg(pParse);
2488 sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
2489 sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
2490 }else{
2491 sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
2495 sqlite3VdbeAddOp0(v, OP_Expire);
2496 break;
2500 ** PRAGMA busy_timeout
2501 ** PRAGMA busy_timeout = N
2503 ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
2504 ** if one is set. If no busy handler or a different busy handler is set
2505 ** then 0 is returned. Setting the busy_timeout to 0 or negative
2506 ** disables the timeout.
2508 /*case PragTyp_BUSY_TIMEOUT*/ default: {
2509 assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
2510 if( zRight ){
2511 sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
2513 returnSingleInt(v, db->busyTimeout);
2514 break;
2518 ** PRAGMA soft_heap_limit
2519 ** PRAGMA soft_heap_limit = N
2521 ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
2522 ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
2523 ** specified and is a non-negative integer.
2524 ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
2525 ** returns the same integer that would be returned by the
2526 ** sqlite3_soft_heap_limit64(-1) C-language function.
2528 case PragTyp_SOFT_HEAP_LIMIT: {
2529 sqlite3_int64 N;
2530 if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
2531 sqlite3_soft_heap_limit64(N);
2533 returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
2534 break;
2538 ** PRAGMA hard_heap_limit
2539 ** PRAGMA hard_heap_limit = N
2541 ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap
2542 ** limit. The hard heap limit can be activated or lowered by this
2543 ** pragma, but not raised or deactivated. Only the
2544 ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate
2545 ** the hard heap limit. This allows an application to set a heap limit
2546 ** constraint that cannot be relaxed by an untrusted SQL script.
2548 case PragTyp_HARD_HEAP_LIMIT: {
2549 sqlite3_int64 N;
2550 if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
2551 sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1);
2552 if( N>0 && (iPrior==0 || iPrior>N) ) sqlite3_hard_heap_limit64(N);
2554 returnSingleInt(v, sqlite3_hard_heap_limit64(-1));
2555 break;
2559 ** PRAGMA threads
2560 ** PRAGMA threads = N
2562 ** Configure the maximum number of worker threads. Return the new
2563 ** maximum, which might be less than requested.
2565 case PragTyp_THREADS: {
2566 sqlite3_int64 N;
2567 if( zRight
2568 && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
2569 && N>=0
2571 sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
2573 returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
2574 break;
2578 ** PRAGMA analysis_limit
2579 ** PRAGMA analysis_limit = N
2581 ** Configure the maximum number of rows that ANALYZE will examine
2582 ** in each index that it looks at. Return the new limit.
2584 case PragTyp_ANALYSIS_LIMIT: {
2585 sqlite3_int64 N;
2586 if( zRight
2587 && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK /* IMP: R-40975-20399 */
2588 && N>=0
2590 db->nAnalysisLimit = (int)(N&0x7fffffff);
2592 returnSingleInt(v, db->nAnalysisLimit); /* IMP: R-57594-65522 */
2593 break;
2596 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
2598 ** Report the current state of file logs for all databases
2600 case PragTyp_LOCK_STATUS: {
2601 static const char *const azLockName[] = {
2602 "unlocked", "shared", "reserved", "pending", "exclusive"
2604 int i;
2605 pParse->nMem = 2;
2606 for(i=0; i<db->nDb; i++){
2607 Btree *pBt;
2608 const char *zState = "unknown";
2609 int j;
2610 if( db->aDb[i].zDbSName==0 ) continue;
2611 pBt = db->aDb[i].pBt;
2612 if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
2613 zState = "closed";
2614 }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
2615 SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
2616 zState = azLockName[j];
2618 sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
2620 break;
2622 #endif
2624 /* BEGIN SQLCIPHER */
2625 #ifdef SQLITE_HAS_CODEC
2626 /* Pragma iArg
2627 ** ---------- ------
2628 ** key 0
2629 ** rekey 1
2630 ** hexkey 2
2631 ** hexrekey 3
2632 ** textkey 4
2633 ** textrekey 5
2635 case PragTyp_KEY: {
2636 if( zRight ){
2637 char zBuf[40];
2638 const char *zKey = zRight;
2639 int n;
2640 if( pPragma->iArg==2 || pPragma->iArg==3 ){
2641 u8 iByte;
2642 int i;
2643 for(i=0, iByte=0; i<sizeof(zBuf)*2 && sqlite3Isxdigit(zRight[i]); i++){
2644 iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
2645 if( (i&1)!=0 ) zBuf[i/2] = iByte;
2647 zKey = zBuf;
2648 n = i/2;
2649 }else{
2650 n = pPragma->iArg<4 ? sqlite3Strlen30(zRight) : -1;
2652 if( (pPragma->iArg & 1)==0 ){
2653 rc = sqlite3_key_v2(db, zDb, zKey, n);
2654 }else{
2655 rc = sqlite3_rekey_v2(db, zDb, zKey, n);
2657 if( rc==SQLITE_OK && n!=0 ){
2658 sqlite3VdbeSetNumCols(v, 1);
2659 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "ok", SQLITE_STATIC);
2660 returnSingleText(v, "ok");
2661 } else {
2662 sqlite3ErrorMsg(pParse, "An error occurred with PRAGMA key or rekey. "
2663 "PRAGMA key requires a key of one or more characters. "
2664 "PRAGMA rekey can only be run on an existing encrypted database. "
2665 "Use sqlcipher_export() and ATTACH to convert encrypted/plaintext databases.");
2666 goto pragma_out;
2669 break;
2671 #endif
2672 /* END SQLCIPHER */
2673 #if defined(SQLITE_ENABLE_CEROD)
2674 case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
2675 if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
2676 sqlite3_activate_cerod(&zRight[6]);
2679 break;
2680 #endif
2682 } /* End of the PRAGMA switch */
2684 /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
2685 ** purpose is to execute assert() statements to verify that if the
2686 ** PragFlg_NoColumns1 flag is set and the caller specified an argument
2687 ** to the PRAGMA, the implementation has not added any OP_ResultRow
2688 ** instructions to the VM. */
2689 if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
2690 sqlite3VdbeVerifyNoResultRow(v);
2693 pragma_out:
2694 sqlite3DbFree(db, zLeft);
2695 sqlite3DbFree(db, zRight);
2697 #ifndef SQLITE_OMIT_VIRTUALTABLE
2698 /*****************************************************************************
2699 ** Implementation of an eponymous virtual table that runs a pragma.
2702 typedef struct PragmaVtab PragmaVtab;
2703 typedef struct PragmaVtabCursor PragmaVtabCursor;
2704 struct PragmaVtab {
2705 sqlite3_vtab base; /* Base class. Must be first */
2706 sqlite3 *db; /* The database connection to which it belongs */
2707 const PragmaName *pName; /* Name of the pragma */
2708 u8 nHidden; /* Number of hidden columns */
2709 u8 iHidden; /* Index of the first hidden column */
2711 struct PragmaVtabCursor {
2712 sqlite3_vtab_cursor base; /* Base class. Must be first */
2713 sqlite3_stmt *pPragma; /* The pragma statement to run */
2714 sqlite_int64 iRowid; /* Current rowid */
2715 char *azArg[2]; /* Value of the argument and schema */
2719 ** Pragma virtual table module xConnect method.
2721 static int pragmaVtabConnect(
2722 sqlite3 *db,
2723 void *pAux,
2724 int argc, const char *const*argv,
2725 sqlite3_vtab **ppVtab,
2726 char **pzErr
2728 const PragmaName *pPragma = (const PragmaName*)pAux;
2729 PragmaVtab *pTab = 0;
2730 int rc;
2731 int i, j;
2732 char cSep = '(';
2733 StrAccum acc;
2734 char zBuf[200];
2736 UNUSED_PARAMETER(argc);
2737 UNUSED_PARAMETER(argv);
2738 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
2739 sqlite3_str_appendall(&acc, "CREATE TABLE x");
2740 for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
2741 sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]);
2742 cSep = ',';
2744 if( i==0 ){
2745 sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
2746 i++;
2748 j = 0;
2749 if( pPragma->mPragFlg & PragFlg_Result1 ){
2750 sqlite3_str_appendall(&acc, ",arg HIDDEN");
2751 j++;
2753 if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
2754 sqlite3_str_appendall(&acc, ",schema HIDDEN");
2755 j++;
2757 sqlite3_str_append(&acc, ")", 1);
2758 sqlite3StrAccumFinish(&acc);
2759 assert( strlen(zBuf) < sizeof(zBuf)-1 );
2760 rc = sqlite3_declare_vtab(db, zBuf);
2761 if( rc==SQLITE_OK ){
2762 pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
2763 if( pTab==0 ){
2764 rc = SQLITE_NOMEM;
2765 }else{
2766 memset(pTab, 0, sizeof(PragmaVtab));
2767 pTab->pName = pPragma;
2768 pTab->db = db;
2769 pTab->iHidden = i;
2770 pTab->nHidden = j;
2772 }else{
2773 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
2776 *ppVtab = (sqlite3_vtab*)pTab;
2777 return rc;
2781 ** Pragma virtual table module xDisconnect method.
2783 static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
2784 PragmaVtab *pTab = (PragmaVtab*)pVtab;
2785 sqlite3_free(pTab);
2786 return SQLITE_OK;
2789 /* Figure out the best index to use to search a pragma virtual table.
2791 ** There are not really any index choices. But we want to encourage the
2792 ** query planner to give == constraints on as many hidden parameters as
2793 ** possible, and especially on the first hidden parameter. So return a
2794 ** high cost if hidden parameters are unconstrained.
2796 static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
2797 PragmaVtab *pTab = (PragmaVtab*)tab;
2798 const struct sqlite3_index_constraint *pConstraint;
2799 int i, j;
2800 int seen[2];
2802 pIdxInfo->estimatedCost = (double)1;
2803 if( pTab->nHidden==0 ){ return SQLITE_OK; }
2804 pConstraint = pIdxInfo->aConstraint;
2805 seen[0] = 0;
2806 seen[1] = 0;
2807 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
2808 if( pConstraint->usable==0 ) continue;
2809 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
2810 if( pConstraint->iColumn < pTab->iHidden ) continue;
2811 j = pConstraint->iColumn - pTab->iHidden;
2812 assert( j < 2 );
2813 seen[j] = i+1;
2815 if( seen[0]==0 ){
2816 pIdxInfo->estimatedCost = (double)2147483647;
2817 pIdxInfo->estimatedRows = 2147483647;
2818 return SQLITE_OK;
2820 j = seen[0]-1;
2821 pIdxInfo->aConstraintUsage[j].argvIndex = 1;
2822 pIdxInfo->aConstraintUsage[j].omit = 1;
2823 if( seen[1]==0 ){
2824 pIdxInfo->estimatedCost = (double)1000;
2825 pIdxInfo->estimatedRows = 1000;
2826 return SQLITE_OK;
2828 pIdxInfo->estimatedCost = (double)20;
2829 pIdxInfo->estimatedRows = 20;
2830 j = seen[1]-1;
2831 pIdxInfo->aConstraintUsage[j].argvIndex = 2;
2832 pIdxInfo->aConstraintUsage[j].omit = 1;
2833 return SQLITE_OK;
2836 /* Create a new cursor for the pragma virtual table */
2837 static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
2838 PragmaVtabCursor *pCsr;
2839 pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
2840 if( pCsr==0 ) return SQLITE_NOMEM;
2841 memset(pCsr, 0, sizeof(PragmaVtabCursor));
2842 pCsr->base.pVtab = pVtab;
2843 *ppCursor = &pCsr->base;
2844 return SQLITE_OK;
2847 /* Clear all content from pragma virtual table cursor. */
2848 static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
2849 int i;
2850 sqlite3_finalize(pCsr->pPragma);
2851 pCsr->pPragma = 0;
2852 for(i=0; i<ArraySize(pCsr->azArg); i++){
2853 sqlite3_free(pCsr->azArg[i]);
2854 pCsr->azArg[i] = 0;
2858 /* Close a pragma virtual table cursor */
2859 static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
2860 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
2861 pragmaVtabCursorClear(pCsr);
2862 sqlite3_free(pCsr);
2863 return SQLITE_OK;
2866 /* Advance the pragma virtual table cursor to the next row */
2867 static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
2868 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2869 int rc = SQLITE_OK;
2871 /* Increment the xRowid value */
2872 pCsr->iRowid++;
2873 assert( pCsr->pPragma );
2874 if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
2875 rc = sqlite3_finalize(pCsr->pPragma);
2876 pCsr->pPragma = 0;
2877 pragmaVtabCursorClear(pCsr);
2879 return rc;
2883 ** Pragma virtual table module xFilter method.
2885 static int pragmaVtabFilter(
2886 sqlite3_vtab_cursor *pVtabCursor,
2887 int idxNum, const char *idxStr,
2888 int argc, sqlite3_value **argv
2890 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2891 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
2892 int rc;
2893 int i, j;
2894 StrAccum acc;
2895 char *zSql;
2897 UNUSED_PARAMETER(idxNum);
2898 UNUSED_PARAMETER(idxStr);
2899 pragmaVtabCursorClear(pCsr);
2900 j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
2901 for(i=0; i<argc; i++, j++){
2902 const char *zText = (const char*)sqlite3_value_text(argv[i]);
2903 assert( j<ArraySize(pCsr->azArg) );
2904 assert( pCsr->azArg[j]==0 );
2905 if( zText ){
2906 pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
2907 if( pCsr->azArg[j]==0 ){
2908 return SQLITE_NOMEM;
2912 sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
2913 sqlite3_str_appendall(&acc, "PRAGMA ");
2914 if( pCsr->azArg[1] ){
2915 sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
2917 sqlite3_str_appendall(&acc, pTab->pName->zName);
2918 if( pCsr->azArg[0] ){
2919 sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
2921 zSql = sqlite3StrAccumFinish(&acc);
2922 if( zSql==0 ) return SQLITE_NOMEM;
2923 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
2924 sqlite3_free(zSql);
2925 if( rc!=SQLITE_OK ){
2926 pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
2927 return rc;
2929 return pragmaVtabNext(pVtabCursor);
2933 ** Pragma virtual table module xEof method.
2935 static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
2936 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2937 return (pCsr->pPragma==0);
2940 /* The xColumn method simply returns the corresponding column from
2941 ** the PRAGMA.
2943 static int pragmaVtabColumn(
2944 sqlite3_vtab_cursor *pVtabCursor,
2945 sqlite3_context *ctx,
2946 int i
2948 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2949 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
2950 if( i<pTab->iHidden ){
2951 sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
2952 }else{
2953 sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
2955 return SQLITE_OK;
2959 ** Pragma virtual table module xRowid method.
2961 static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
2962 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2963 *p = pCsr->iRowid;
2964 return SQLITE_OK;
2967 /* The pragma virtual table object */
2968 static const sqlite3_module pragmaVtabModule = {
2969 0, /* iVersion */
2970 0, /* xCreate - create a table */
2971 pragmaVtabConnect, /* xConnect - connect to an existing table */
2972 pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */
2973 pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */
2974 0, /* xDestroy - Drop a table */
2975 pragmaVtabOpen, /* xOpen - open a cursor */
2976 pragmaVtabClose, /* xClose - close a cursor */
2977 pragmaVtabFilter, /* xFilter - configure scan constraints */
2978 pragmaVtabNext, /* xNext - advance a cursor */
2979 pragmaVtabEof, /* xEof */
2980 pragmaVtabColumn, /* xColumn - read data */
2981 pragmaVtabRowid, /* xRowid - read data */
2982 0, /* xUpdate - write data */
2983 0, /* xBegin - begin transaction */
2984 0, /* xSync - sync transaction */
2985 0, /* xCommit - commit transaction */
2986 0, /* xRollback - rollback transaction */
2987 0, /* xFindFunction - function overloading */
2988 0, /* xRename - rename the table */
2989 0, /* xSavepoint */
2990 0, /* xRelease */
2991 0, /* xRollbackTo */
2992 0, /* xShadowName */
2993 0 /* xIntegrity */
2997 ** Check to see if zTabName is really the name of a pragma. If it is,
2998 ** then register an eponymous virtual table for that pragma and return
2999 ** a pointer to the Module object for the new virtual table.
3001 Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
3002 const PragmaName *pName;
3003 assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
3004 pName = pragmaLocate(zName+7);
3005 if( pName==0 ) return 0;
3006 if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
3007 assert( sqlite3HashFind(&db->aModule, zName)==0 );
3008 return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
3011 #endif /* SQLITE_OMIT_VIRTUALTABLE */
3013 #endif /* SQLITE_OMIT_PRAGMA */