Merge sqlite-release(3.41.0) into prerelease-integration
[sqlcipher.git] / src / pragma.c
blob26f5c2922147d13802f97bf02b02f8fec279417c
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 turnning 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 db->flags |= mask;
1143 }else{
1144 db->flags &= ~mask;
1145 if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
1146 if( (mask & SQLITE_WriteSchema)!=0
1147 && sqlite3_stricmp(zRight, "reset")==0
1149 /* IMP: R-60817-01178 If the argument is "RESET" then schema
1150 ** writing is disabled (as with "PRAGMA writable_schema=OFF") and,
1151 ** in addition, the schema is reloaded. */
1152 sqlite3ResetAllSchemasOfConnection(db);
1156 /* Many of the flag-pragmas modify the code generated by the SQL
1157 ** compiler (eg. count_changes). So add an opcode to expire all
1158 ** compiled SQL statements after modifying a pragma value.
1160 sqlite3VdbeAddOp0(v, OP_Expire);
1161 setAllPagerFlags(db);
1163 break;
1165 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
1167 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
1169 ** PRAGMA table_info(<table>)
1171 ** Return a single row for each column of the named table. The columns of
1172 ** the returned data set are:
1174 ** cid: Column id (numbered from left to right, starting at 0)
1175 ** name: Column name
1176 ** type: Column declaration type.
1177 ** notnull: True if 'NOT NULL' is part of column declaration
1178 ** dflt_value: The default value for the column, if any.
1179 ** pk: Non-zero for PK fields.
1181 case PragTyp_TABLE_INFO: if( zRight ){
1182 Table *pTab;
1183 sqlite3CodeVerifyNamedSchema(pParse, zDb);
1184 pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
1185 if( pTab ){
1186 int i, k;
1187 int nHidden = 0;
1188 Column *pCol;
1189 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
1190 pParse->nMem = 7;
1191 sqlite3ViewGetColumnNames(pParse, pTab);
1192 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
1193 int isHidden = 0;
1194 const Expr *pColExpr;
1195 if( pCol->colFlags & COLFLAG_NOINSERT ){
1196 if( pPragma->iArg==0 ){
1197 nHidden++;
1198 continue;
1200 if( pCol->colFlags & COLFLAG_VIRTUAL ){
1201 isHidden = 2; /* GENERATED ALWAYS AS ... VIRTUAL */
1202 }else if( pCol->colFlags & COLFLAG_STORED ){
1203 isHidden = 3; /* GENERATED ALWAYS AS ... STORED */
1204 }else{ assert( pCol->colFlags & COLFLAG_HIDDEN );
1205 isHidden = 1; /* HIDDEN */
1208 if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
1209 k = 0;
1210 }else if( pPk==0 ){
1211 k = 1;
1212 }else{
1213 for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
1215 pColExpr = sqlite3ColumnExpr(pTab,pCol);
1216 assert( pColExpr==0 || pColExpr->op==TK_SPAN || isHidden>=2 );
1217 assert( pColExpr==0 || !ExprHasProperty(pColExpr, EP_IntValue)
1218 || isHidden>=2 );
1219 sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
1220 i-nHidden,
1221 pCol->zCnName,
1222 sqlite3ColumnType(pCol,""),
1223 pCol->notNull ? 1 : 0,
1224 (isHidden>=2 || pColExpr==0) ? 0 : pColExpr->u.zToken,
1226 isHidden);
1230 break;
1233 ** PRAGMA table_list
1235 ** Return a single row for each table, virtual table, or view in the
1236 ** entire schema.
1238 ** schema: Name of attached database hold this table
1239 ** name: Name of the table itself
1240 ** type: "table", "view", "virtual", "shadow"
1241 ** ncol: Number of columns
1242 ** wr: True for a WITHOUT ROWID table
1243 ** strict: True for a STRICT table
1245 case PragTyp_TABLE_LIST: {
1246 int ii;
1247 pParse->nMem = 6;
1248 sqlite3CodeVerifyNamedSchema(pParse, zDb);
1249 for(ii=0; ii<db->nDb; ii++){
1250 HashElem *k;
1251 Hash *pHash;
1252 int initNCol;
1253 if( zDb && sqlite3_stricmp(zDb, db->aDb[ii].zDbSName)!=0 ) continue;
1255 /* Ensure that the Table.nCol field is initialized for all views
1256 ** and virtual tables. Each time we initialize a Table.nCol value
1257 ** for a table, that can potentially disrupt the hash table, so restart
1258 ** the initialization scan.
1260 pHash = &db->aDb[ii].pSchema->tblHash;
1261 initNCol = sqliteHashCount(pHash);
1262 while( initNCol-- ){
1263 for(k=sqliteHashFirst(pHash); 1; k=sqliteHashNext(k) ){
1264 Table *pTab;
1265 if( k==0 ){ initNCol = 0; break; }
1266 pTab = sqliteHashData(k);
1267 if( pTab->nCol==0 ){
1268 char *zSql = sqlite3MPrintf(db, "SELECT*FROM\"%w\"", pTab->zName);
1269 if( zSql ){
1270 sqlite3_stmt *pDummy = 0;
1271 (void)sqlite3_prepare(db, zSql, -1, &pDummy, 0);
1272 (void)sqlite3_finalize(pDummy);
1273 sqlite3DbFree(db, zSql);
1275 if( db->mallocFailed ){
1276 sqlite3ErrorMsg(db->pParse, "out of memory");
1277 db->pParse->rc = SQLITE_NOMEM_BKPT;
1279 pHash = &db->aDb[ii].pSchema->tblHash;
1280 break;
1285 for(k=sqliteHashFirst(pHash); k; k=sqliteHashNext(k) ){
1286 Table *pTab = sqliteHashData(k);
1287 const char *zType;
1288 if( zRight && sqlite3_stricmp(zRight, pTab->zName)!=0 ) continue;
1289 if( IsView(pTab) ){
1290 zType = "view";
1291 }else if( IsVirtual(pTab) ){
1292 zType = "virtual";
1293 }else if( pTab->tabFlags & TF_Shadow ){
1294 zType = "shadow";
1295 }else{
1296 zType = "table";
1298 sqlite3VdbeMultiLoad(v, 1, "sssiii",
1299 db->aDb[ii].zDbSName,
1300 sqlite3PreferredTableName(pTab->zName),
1301 zType,
1302 pTab->nCol,
1303 (pTab->tabFlags & TF_WithoutRowid)!=0,
1304 (pTab->tabFlags & TF_Strict)!=0
1309 break;
1311 #ifdef SQLITE_DEBUG
1312 case PragTyp_STATS: {
1313 Index *pIdx;
1314 HashElem *i;
1315 pParse->nMem = 5;
1316 sqlite3CodeVerifySchema(pParse, iDb);
1317 for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
1318 Table *pTab = sqliteHashData(i);
1319 sqlite3VdbeMultiLoad(v, 1, "ssiii",
1320 sqlite3PreferredTableName(pTab->zName),
1322 pTab->szTabRow,
1323 pTab->nRowLogEst,
1324 pTab->tabFlags);
1325 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1326 sqlite3VdbeMultiLoad(v, 2, "siiiX",
1327 pIdx->zName,
1328 pIdx->szIdxRow,
1329 pIdx->aiRowLogEst[0],
1330 pIdx->hasStat1);
1331 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
1335 break;
1336 #endif
1338 case PragTyp_INDEX_INFO: if( zRight ){
1339 Index *pIdx;
1340 Table *pTab;
1341 pIdx = sqlite3FindIndex(db, zRight, zDb);
1342 if( pIdx==0 ){
1343 /* If there is no index named zRight, check to see if there is a
1344 ** WITHOUT ROWID table named zRight, and if there is, show the
1345 ** structure of the PRIMARY KEY index for that table. */
1346 pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
1347 if( pTab && !HasRowid(pTab) ){
1348 pIdx = sqlite3PrimaryKeyIndex(pTab);
1351 if( pIdx ){
1352 int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
1353 int i;
1354 int mx;
1355 if( pPragma->iArg ){
1356 /* PRAGMA index_xinfo (newer version with more rows and columns) */
1357 mx = pIdx->nColumn;
1358 pParse->nMem = 6;
1359 }else{
1360 /* PRAGMA index_info (legacy version) */
1361 mx = pIdx->nKeyCol;
1362 pParse->nMem = 3;
1364 pTab = pIdx->pTable;
1365 sqlite3CodeVerifySchema(pParse, iIdxDb);
1366 assert( pParse->nMem<=pPragma->nPragCName );
1367 for(i=0; i<mx; i++){
1368 i16 cnum = pIdx->aiColumn[i];
1369 sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
1370 cnum<0 ? 0 : pTab->aCol[cnum].zCnName);
1371 if( pPragma->iArg ){
1372 sqlite3VdbeMultiLoad(v, 4, "isiX",
1373 pIdx->aSortOrder[i],
1374 pIdx->azColl[i],
1375 i<pIdx->nKeyCol);
1377 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
1381 break;
1383 case PragTyp_INDEX_LIST: if( zRight ){
1384 Index *pIdx;
1385 Table *pTab;
1386 int i;
1387 pTab = sqlite3FindTable(db, zRight, zDb);
1388 if( pTab ){
1389 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1390 pParse->nMem = 5;
1391 sqlite3CodeVerifySchema(pParse, iTabDb);
1392 for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
1393 const char *azOrigin[] = { "c", "u", "pk" };
1394 sqlite3VdbeMultiLoad(v, 1, "isisi",
1396 pIdx->zName,
1397 IsUniqueIndex(pIdx),
1398 azOrigin[pIdx->idxType],
1399 pIdx->pPartIdxWhere!=0);
1403 break;
1405 case PragTyp_DATABASE_LIST: {
1406 int i;
1407 pParse->nMem = 3;
1408 for(i=0; i<db->nDb; i++){
1409 if( db->aDb[i].pBt==0 ) continue;
1410 assert( db->aDb[i].zDbSName!=0 );
1411 sqlite3VdbeMultiLoad(v, 1, "iss",
1413 db->aDb[i].zDbSName,
1414 sqlite3BtreeGetFilename(db->aDb[i].pBt));
1417 break;
1419 case PragTyp_COLLATION_LIST: {
1420 int i = 0;
1421 HashElem *p;
1422 pParse->nMem = 2;
1423 for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
1424 CollSeq *pColl = (CollSeq *)sqliteHashData(p);
1425 sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
1428 break;
1430 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
1431 case PragTyp_FUNCTION_LIST: {
1432 int i;
1433 HashElem *j;
1434 FuncDef *p;
1435 int showInternFunc = (db->mDbFlags & DBFLAG_InternalFunc)!=0;
1436 pParse->nMem = 6;
1437 for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
1438 for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
1439 assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
1440 pragmaFunclistLine(v, p, 1, showInternFunc);
1443 for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
1444 p = (FuncDef*)sqliteHashData(j);
1445 assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
1446 pragmaFunclistLine(v, p, 0, showInternFunc);
1449 break;
1451 #ifndef SQLITE_OMIT_VIRTUALTABLE
1452 case PragTyp_MODULE_LIST: {
1453 HashElem *j;
1454 pParse->nMem = 1;
1455 for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
1456 Module *pMod = (Module*)sqliteHashData(j);
1457 sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
1460 break;
1461 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1463 case PragTyp_PRAGMA_LIST: {
1464 int i;
1465 for(i=0; i<ArraySize(aPragmaName); i++){
1466 sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
1469 break;
1470 #endif /* SQLITE_INTROSPECTION_PRAGMAS */
1472 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
1474 #ifndef SQLITE_OMIT_FOREIGN_KEY
1475 case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
1476 FKey *pFK;
1477 Table *pTab;
1478 pTab = sqlite3FindTable(db, zRight, zDb);
1479 if( pTab && IsOrdinaryTable(pTab) ){
1480 pFK = pTab->u.tab.pFKey;
1481 if( pFK ){
1482 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1483 int i = 0;
1484 pParse->nMem = 8;
1485 sqlite3CodeVerifySchema(pParse, iTabDb);
1486 while(pFK){
1487 int j;
1488 for(j=0; j<pFK->nCol; j++){
1489 sqlite3VdbeMultiLoad(v, 1, "iissssss",
1492 pFK->zTo,
1493 pTab->aCol[pFK->aCol[j].iFrom].zCnName,
1494 pFK->aCol[j].zCol,
1495 actionName(pFK->aAction[1]), /* ON UPDATE */
1496 actionName(pFK->aAction[0]), /* ON DELETE */
1497 "NONE");
1499 ++i;
1500 pFK = pFK->pNextFrom;
1505 break;
1506 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1508 #ifndef SQLITE_OMIT_FOREIGN_KEY
1509 #ifndef SQLITE_OMIT_TRIGGER
1510 case PragTyp_FOREIGN_KEY_CHECK: {
1511 FKey *pFK; /* A foreign key constraint */
1512 Table *pTab; /* Child table contain "REFERENCES" keyword */
1513 Table *pParent; /* Parent table that child points to */
1514 Index *pIdx; /* Index in the parent table */
1515 int i; /* Loop counter: Foreign key number for pTab */
1516 int j; /* Loop counter: Field of the foreign key */
1517 HashElem *k; /* Loop counter: Next table in schema */
1518 int x; /* result variable */
1519 int regResult; /* 3 registers to hold a result row */
1520 int regRow; /* Registers to hold a row from pTab */
1521 int addrTop; /* Top of a loop checking foreign keys */
1522 int addrOk; /* Jump here if the key is OK */
1523 int *aiCols; /* child to parent column mapping */
1525 regResult = pParse->nMem+1;
1526 pParse->nMem += 4;
1527 regRow = ++pParse->nMem;
1528 k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
1529 while( k ){
1530 if( zRight ){
1531 pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
1532 k = 0;
1533 }else{
1534 pTab = (Table*)sqliteHashData(k);
1535 k = sqliteHashNext(k);
1537 if( pTab==0 || !IsOrdinaryTable(pTab) || pTab->u.tab.pFKey==0 ) continue;
1538 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1539 zDb = db->aDb[iDb].zDbSName;
1540 sqlite3CodeVerifySchema(pParse, iDb);
1541 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
1542 if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
1543 sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
1544 sqlite3VdbeLoadString(v, regResult, pTab->zName);
1545 assert( IsOrdinaryTable(pTab) );
1546 for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
1547 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
1548 if( pParent==0 ) continue;
1549 pIdx = 0;
1550 sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
1551 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
1552 if( x==0 ){
1553 if( pIdx==0 ){
1554 sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
1555 }else{
1556 sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
1557 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1559 }else{
1560 k = 0;
1561 break;
1564 assert( pParse->nErr>0 || pFK==0 );
1565 if( pFK ) break;
1566 if( pParse->nTab<i ) pParse->nTab = i;
1567 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
1568 assert( IsOrdinaryTable(pTab) );
1569 for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
1570 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
1571 pIdx = 0;
1572 aiCols = 0;
1573 if( pParent ){
1574 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
1575 assert( x==0 || db->mallocFailed );
1577 addrOk = sqlite3VdbeMakeLabel(pParse);
1579 /* Generate code to read the child key values into registers
1580 ** regRow..regRow+n. If any of the child key values are NULL, this
1581 ** row cannot cause an FK violation. Jump directly to addrOk in
1582 ** this case. */
1583 if( regRow+pFK->nCol>pParse->nMem ) pParse->nMem = regRow+pFK->nCol;
1584 for(j=0; j<pFK->nCol; j++){
1585 int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
1586 sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
1587 sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
1590 /* Generate code to query the parent index for a matching parent
1591 ** key. If a match is found, jump to addrOk. */
1592 if( pIdx ){
1593 sqlite3VdbeAddOp4(v, OP_Affinity, regRow, pFK->nCol, 0,
1594 sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
1595 sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regRow, pFK->nCol);
1596 VdbeCoverage(v);
1597 }else if( pParent ){
1598 int jmp = sqlite3VdbeCurrentAddr(v)+2;
1599 sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
1600 sqlite3VdbeGoto(v, addrOk);
1601 assert( pFK->nCol==1 || db->mallocFailed );
1604 /* Generate code to report an FK violation to the caller. */
1605 if( HasRowid(pTab) ){
1606 sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
1607 }else{
1608 sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
1610 sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
1611 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
1612 sqlite3VdbeResolveLabel(v, addrOk);
1613 sqlite3DbFree(db, aiCols);
1615 sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
1616 sqlite3VdbeJumpHere(v, addrTop);
1619 break;
1620 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
1621 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1623 #ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA
1624 /* Reinstall the LIKE and GLOB functions. The variant of LIKE
1625 ** used will be case sensitive or not depending on the RHS.
1627 case PragTyp_CASE_SENSITIVE_LIKE: {
1628 if( zRight ){
1629 sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
1632 break;
1633 #endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */
1635 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
1636 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
1637 #endif
1639 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
1640 /* PRAGMA integrity_check
1641 ** PRAGMA integrity_check(N)
1642 ** PRAGMA quick_check
1643 ** PRAGMA quick_check(N)
1645 ** Verify the integrity of the database.
1647 ** The "quick_check" is reduced version of
1648 ** integrity_check designed to detect most database corruption
1649 ** without the overhead of cross-checking indexes. Quick_check
1650 ** is linear time wherease integrity_check is O(NlogN).
1652 ** The maximum nubmer of errors is 100 by default. A different default
1653 ** can be specified using a numeric parameter N.
1655 ** Or, the parameter N can be the name of a table. In that case, only
1656 ** the one table named is verified. The freelist is only verified if
1657 ** the named table is "sqlite_schema" (or one of its aliases).
1659 ** All schemas are checked by default. To check just a single
1660 ** schema, use the form:
1662 ** PRAGMA schema.integrity_check;
1664 case PragTyp_INTEGRITY_CHECK: {
1665 int i, j, addr, mxErr;
1666 Table *pObjTab = 0; /* Check only this one table, if not NULL */
1668 int isQuick = (sqlite3Tolower(zLeft[0])=='q');
1670 /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
1671 ** then iDb is set to the index of the database identified by <db>.
1672 ** In this case, the integrity of database iDb only is verified by
1673 ** the VDBE created below.
1675 ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
1676 ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
1677 ** to -1 here, to indicate that the VDBE should verify the integrity
1678 ** of all attached databases. */
1679 assert( iDb>=0 );
1680 assert( iDb==0 || pId2->z );
1681 if( pId2->z==0 ) iDb = -1;
1683 /* Initialize the VDBE program */
1684 pParse->nMem = 6;
1686 /* Set the maximum error count */
1687 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
1688 if( zRight ){
1689 if( sqlite3GetInt32(zRight, &mxErr) ){
1690 if( mxErr<=0 ){
1691 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
1693 }else{
1694 pObjTab = sqlite3LocateTable(pParse, 0, zRight,
1695 iDb>=0 ? db->aDb[iDb].zDbSName : 0);
1698 sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
1700 /* Do an integrity check on each database file */
1701 for(i=0; i<db->nDb; i++){
1702 HashElem *x; /* For looping over tables in the schema */
1703 Hash *pTbls; /* Set of all tables in the schema */
1704 int *aRoot; /* Array of root page numbers of all btrees */
1705 int cnt = 0; /* Number of entries in aRoot[] */
1706 int mxIdx = 0; /* Maximum number of indexes for any table */
1708 if( OMIT_TEMPDB && i==1 ) continue;
1709 if( iDb>=0 && i!=iDb ) continue;
1711 sqlite3CodeVerifySchema(pParse, i);
1713 /* Do an integrity check of the B-Tree
1715 ** Begin by finding the root pages numbers
1716 ** for all tables and indices in the database.
1718 assert( sqlite3SchemaMutexHeld(db, i, 0) );
1719 pTbls = &db->aDb[i].pSchema->tblHash;
1720 for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
1721 Table *pTab = sqliteHashData(x); /* Current table */
1722 Index *pIdx; /* An index on pTab */
1723 int nIdx; /* Number of indexes on pTab */
1724 if( pObjTab && pObjTab!=pTab ) continue;
1725 if( HasRowid(pTab) ) cnt++;
1726 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
1727 if( nIdx>mxIdx ) mxIdx = nIdx;
1729 if( cnt==0 ) continue;
1730 if( pObjTab ) cnt++;
1731 aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
1732 if( aRoot==0 ) break;
1733 cnt = 0;
1734 if( pObjTab ) aRoot[++cnt] = 0;
1735 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
1736 Table *pTab = sqliteHashData(x);
1737 Index *pIdx;
1738 if( pObjTab && pObjTab!=pTab ) continue;
1739 if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
1740 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1741 aRoot[++cnt] = pIdx->tnum;
1744 aRoot[0] = cnt;
1746 /* Make sure sufficient number of registers have been allocated */
1747 pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
1748 sqlite3ClearTempRegCache(pParse);
1750 /* Do the b-tree integrity checks */
1751 sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
1752 sqlite3VdbeChangeP5(v, (u8)i);
1753 addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
1754 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
1755 sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
1756 P4_DYNAMIC);
1757 sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
1758 integrityCheckResultRow(v);
1759 sqlite3VdbeJumpHere(v, addr);
1761 /* Make sure all the indices are constructed correctly.
1763 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
1764 Table *pTab = sqliteHashData(x);
1765 Index *pIdx, *pPk;
1766 Index *pPrior = 0; /* Previous index */
1767 int loopTop;
1768 int iDataCur, iIdxCur;
1769 int r1 = -1;
1770 int bStrict; /* True for a STRICT table */
1771 int r2; /* Previous key for WITHOUT ROWID tables */
1772 int mxCol; /* Maximum non-virtual column number */
1774 if( !IsOrdinaryTable(pTab) ) continue;
1775 if( pObjTab && pObjTab!=pTab ) continue;
1776 if( isQuick || HasRowid(pTab) ){
1777 pPk = 0;
1778 r2 = 0;
1779 }else{
1780 pPk = sqlite3PrimaryKeyIndex(pTab);
1781 r2 = sqlite3GetTempRange(pParse, pPk->nKeyCol);
1782 sqlite3VdbeAddOp3(v, OP_Null, 1, r2, r2+pPk->nKeyCol-1);
1784 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
1785 1, 0, &iDataCur, &iIdxCur);
1786 /* reg[7] counts the number of entries in the table.
1787 ** reg[8+i] counts the number of entries in the i-th index
1789 sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
1790 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
1791 sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
1793 assert( pParse->nMem>=8+j );
1794 assert( sqlite3NoTempsInRange(pParse,1,7+j) );
1795 sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
1796 loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
1798 /* Fetch the right-most column from the table. This will cause
1799 ** the entire record header to be parsed and sanity checked. It
1800 ** will also prepopulate the cursor column cache that is used
1801 ** by the OP_IsType code, so it is a required step.
1803 assert( !IsVirtual(pTab) );
1804 if( HasRowid(pTab) ){
1805 mxCol = -1;
1806 for(j=0; j<pTab->nCol; j++){
1807 if( (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)==0 ) mxCol++;
1809 if( mxCol==pTab->iPKey ) mxCol--;
1810 }else{
1811 /* COLFLAG_VIRTUAL columns are not included in the WITHOUT ROWID
1812 ** PK index column-count, so there is no need to account for them
1813 ** in this case. */
1814 mxCol = sqlite3PrimaryKeyIndex(pTab)->nColumn-1;
1816 if( mxCol>=0 ){
1817 sqlite3VdbeAddOp3(v, OP_Column, iDataCur, mxCol, 3);
1818 sqlite3VdbeTypeofColumn(v, 3);
1821 if( !isQuick ){
1822 if( pPk ){
1823 /* Verify WITHOUT ROWID keys are in ascending order */
1824 int a1;
1825 char *zErr;
1826 a1 = sqlite3VdbeAddOp4Int(v, OP_IdxGT, iDataCur, 0,r2,pPk->nKeyCol);
1827 VdbeCoverage(v);
1828 sqlite3VdbeAddOp1(v, OP_IsNull, r2); VdbeCoverage(v);
1829 zErr = sqlite3MPrintf(db,
1830 "row not in PRIMARY KEY order for %s",
1831 pTab->zName);
1832 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1833 integrityCheckResultRow(v);
1834 sqlite3VdbeJumpHere(v, a1);
1835 sqlite3VdbeJumpHere(v, a1+1);
1836 for(j=0; j<pPk->nKeyCol; j++){
1837 sqlite3ExprCodeLoadIndexColumn(pParse, pPk, iDataCur, j, r2+j);
1841 /* Verify datatypes for all columns:
1843 ** (1) NOT NULL columns may not contain a NULL
1844 ** (2) Datatype must be exact for non-ANY columns in STRICT tables
1845 ** (3) Datatype for TEXT columns in non-STRICT tables must be
1846 ** NULL, TEXT, or BLOB.
1847 ** (4) Datatype for numeric columns in non-STRICT tables must not
1848 ** be a TEXT value that can be losslessly converted to numeric.
1850 bStrict = (pTab->tabFlags & TF_Strict)!=0;
1851 for(j=0; j<pTab->nCol; j++){
1852 char *zErr;
1853 Column *pCol = pTab->aCol + j; /* The column to be checked */
1854 int labelError; /* Jump here to report an error */
1855 int labelOk; /* Jump here if all looks ok */
1856 int p1, p3, p4; /* Operands to the OP_IsType opcode */
1857 int doTypeCheck; /* Check datatypes (besides NOT NULL) */
1859 if( j==pTab->iPKey ) continue;
1860 if( bStrict ){
1861 doTypeCheck = pCol->eCType>COLTYPE_ANY;
1862 }else{
1863 doTypeCheck = pCol->affinity>SQLITE_AFF_BLOB;
1865 if( pCol->notNull==0 && !doTypeCheck ) continue;
1867 /* Compute the operands that will be needed for OP_IsType */
1868 p4 = SQLITE_NULL;
1869 if( pCol->colFlags & COLFLAG_VIRTUAL ){
1870 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
1871 p1 = -1;
1872 p3 = 3;
1873 }else{
1874 if( pCol->iDflt ){
1875 sqlite3_value *pDfltValue = 0;
1876 sqlite3ValueFromExpr(db, sqlite3ColumnExpr(pTab,pCol), ENC(db),
1877 pCol->affinity, &pDfltValue);
1878 if( pDfltValue ){
1879 p4 = sqlite3_value_type(pDfltValue);
1880 sqlite3ValueFree(pDfltValue);
1883 p1 = iDataCur;
1884 if( !HasRowid(pTab) ){
1885 testcase( j!=sqlite3TableColumnToStorage(pTab, j) );
1886 p3 = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), j);
1887 }else{
1888 p3 = sqlite3TableColumnToStorage(pTab,j);
1889 testcase( p3!=j);
1893 labelError = sqlite3VdbeMakeLabel(pParse);
1894 labelOk = sqlite3VdbeMakeLabel(pParse);
1895 if( pCol->notNull ){
1896 /* (1) NOT NULL columns may not contain a NULL */
1897 int jmp2 = sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
1898 sqlite3VdbeChangeP5(v, 0x0f);
1899 VdbeCoverage(v);
1900 zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
1901 pCol->zCnName);
1902 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1903 if( doTypeCheck ){
1904 sqlite3VdbeGoto(v, labelError);
1905 sqlite3VdbeJumpHere(v, jmp2);
1906 }else{
1907 /* VDBE byte code will fall thru */
1910 if( bStrict && doTypeCheck ){
1911 /* (2) Datatype must be exact for non-ANY columns in STRICT tables*/
1912 static unsigned char aStdTypeMask[] = {
1913 0x1f, /* ANY */
1914 0x18, /* BLOB */
1915 0x11, /* INT */
1916 0x11, /* INTEGER */
1917 0x13, /* REAL */
1918 0x14 /* TEXT */
1920 sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
1921 assert( pCol->eCType>=1 && pCol->eCType<=sizeof(aStdTypeMask) );
1922 sqlite3VdbeChangeP5(v, aStdTypeMask[pCol->eCType-1]);
1923 VdbeCoverage(v);
1924 zErr = sqlite3MPrintf(db, "non-%s value in %s.%s",
1925 sqlite3StdType[pCol->eCType-1],
1926 pTab->zName, pTab->aCol[j].zCnName);
1927 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1928 }else if( !bStrict && pCol->affinity==SQLITE_AFF_TEXT ){
1929 /* (3) Datatype for TEXT columns in non-STRICT tables must be
1930 ** NULL, TEXT, or BLOB. */
1931 sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
1932 sqlite3VdbeChangeP5(v, 0x1c); /* NULL, TEXT, or BLOB */
1933 VdbeCoverage(v);
1934 zErr = sqlite3MPrintf(db, "NUMERIC value in %s.%s",
1935 pTab->zName, pTab->aCol[j].zCnName);
1936 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1937 }else if( !bStrict && pCol->affinity>=SQLITE_AFF_NUMERIC ){
1938 /* (4) Datatype for numeric columns in non-STRICT tables must not
1939 ** be a TEXT value that can be converted to numeric. */
1940 sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
1941 sqlite3VdbeChangeP5(v, 0x1b); /* NULL, INT, FLOAT, or BLOB */
1942 VdbeCoverage(v);
1943 if( p1>=0 ){
1944 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
1946 sqlite3VdbeAddOp4(v, OP_Affinity, 3, 1, 0, "C", P4_STATIC);
1947 sqlite3VdbeAddOp4Int(v, OP_IsType, -1, labelOk, 3, p4);
1948 sqlite3VdbeChangeP5(v, 0x1c); /* NULL, TEXT, or BLOB */
1949 VdbeCoverage(v);
1950 zErr = sqlite3MPrintf(db, "TEXT value in %s.%s",
1951 pTab->zName, pTab->aCol[j].zCnName);
1952 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1954 sqlite3VdbeResolveLabel(v, labelError);
1955 integrityCheckResultRow(v);
1956 sqlite3VdbeResolveLabel(v, labelOk);
1958 /* Verify CHECK constraints */
1959 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
1960 ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
1961 if( db->mallocFailed==0 ){
1962 int addrCkFault = sqlite3VdbeMakeLabel(pParse);
1963 int addrCkOk = sqlite3VdbeMakeLabel(pParse);
1964 char *zErr;
1965 int k;
1966 pParse->iSelfTab = iDataCur + 1;
1967 for(k=pCheck->nExpr-1; k>0; k--){
1968 sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
1970 sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
1971 SQLITE_JUMPIFNULL);
1972 sqlite3VdbeResolveLabel(v, addrCkFault);
1973 pParse->iSelfTab = 0;
1974 zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
1975 pTab->zName);
1976 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
1977 integrityCheckResultRow(v);
1978 sqlite3VdbeResolveLabel(v, addrCkOk);
1980 sqlite3ExprListDelete(db, pCheck);
1982 if( !isQuick ){ /* Omit the remaining tests for quick_check */
1983 /* Validate index entries for the current row */
1984 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
1985 int jmp2, jmp3, jmp4, jmp5, label6;
1986 int kk;
1987 int ckUniq = sqlite3VdbeMakeLabel(pParse);
1988 if( pPk==pIdx ) continue;
1989 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
1990 pPrior, r1);
1991 pPrior = pIdx;
1992 sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
1993 /* Verify that an index entry exists for the current table row */
1994 jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
1995 pIdx->nColumn); VdbeCoverage(v);
1996 sqlite3VdbeLoadString(v, 3, "row ");
1997 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
1998 sqlite3VdbeLoadString(v, 4, " missing from index ");
1999 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
2000 jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
2001 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
2002 jmp4 = integrityCheckResultRow(v);
2003 sqlite3VdbeJumpHere(v, jmp2);
2005 /* Any indexed columns with non-BINARY collations must still hold
2006 ** the exact same text value as the table. */
2007 label6 = 0;
2008 for(kk=0; kk<pIdx->nKeyCol; kk++){
2009 if( pIdx->azColl[kk]==sqlite3StrBINARY ) continue;
2010 if( label6==0 ) label6 = sqlite3VdbeMakeLabel(pParse);
2011 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur+j, kk, 3);
2012 sqlite3VdbeAddOp3(v, OP_Ne, 3, label6, r1+kk); VdbeCoverage(v);
2014 if( label6 ){
2015 int jmp6 = sqlite3VdbeAddOp0(v, OP_Goto);
2016 sqlite3VdbeResolveLabel(v, label6);
2017 sqlite3VdbeLoadString(v, 3, "row ");
2018 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
2019 sqlite3VdbeLoadString(v, 4, " values differ from index ");
2020 sqlite3VdbeGoto(v, jmp5-1);
2021 sqlite3VdbeJumpHere(v, jmp6);
2024 /* For UNIQUE indexes, verify that only one entry exists with the
2025 ** current key. The entry is unique if (1) any column is NULL
2026 ** or (2) the next entry has a different key */
2027 if( IsUniqueIndex(pIdx) ){
2028 int uniqOk = sqlite3VdbeMakeLabel(pParse);
2029 int jmp6;
2030 for(kk=0; kk<pIdx->nKeyCol; kk++){
2031 int iCol = pIdx->aiColumn[kk];
2032 assert( iCol!=XN_ROWID && iCol<pTab->nCol );
2033 if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
2034 sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
2035 VdbeCoverage(v);
2037 jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
2038 sqlite3VdbeGoto(v, uniqOk);
2039 sqlite3VdbeJumpHere(v, jmp6);
2040 sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
2041 pIdx->nKeyCol); VdbeCoverage(v);
2042 sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
2043 sqlite3VdbeGoto(v, jmp5);
2044 sqlite3VdbeResolveLabel(v, uniqOk);
2046 sqlite3VdbeJumpHere(v, jmp4);
2047 sqlite3ResolvePartIdxLabel(pParse, jmp3);
2050 sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
2051 sqlite3VdbeJumpHere(v, loopTop-1);
2052 if( !isQuick ){
2053 sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
2054 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
2055 if( pPk==pIdx ) continue;
2056 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
2057 addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
2058 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2059 sqlite3VdbeLoadString(v, 4, pIdx->zName);
2060 sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
2061 integrityCheckResultRow(v);
2062 sqlite3VdbeJumpHere(v, addr);
2064 if( pPk ){
2065 sqlite3ReleaseTempRange(pParse, r2, pPk->nKeyCol);
2071 static const int iLn = VDBE_OFFSET_LINENO(2);
2072 static const VdbeOpList endCode[] = {
2073 { OP_AddImm, 1, 0, 0}, /* 0 */
2074 { OP_IfNotZero, 1, 4, 0}, /* 1 */
2075 { OP_String8, 0, 3, 0}, /* 2 */
2076 { OP_ResultRow, 3, 1, 0}, /* 3 */
2077 { OP_Halt, 0, 0, 0}, /* 4 */
2078 { OP_String8, 0, 3, 0}, /* 5 */
2079 { OP_Goto, 0, 3, 0}, /* 6 */
2081 VdbeOp *aOp;
2083 aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
2084 if( aOp ){
2085 aOp[0].p2 = 1-mxErr;
2086 aOp[2].p4type = P4_STATIC;
2087 aOp[2].p4.z = "ok";
2088 aOp[5].p4type = P4_STATIC;
2089 aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
2091 sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
2094 break;
2095 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
2097 #ifndef SQLITE_OMIT_UTF16
2099 ** PRAGMA encoding
2100 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
2102 ** In its first form, this pragma returns the encoding of the main
2103 ** database. If the database is not initialized, it is initialized now.
2105 ** The second form of this pragma is a no-op if the main database file
2106 ** has not already been initialized. In this case it sets the default
2107 ** encoding that will be used for the main database file if a new file
2108 ** is created. If an existing main database file is opened, then the
2109 ** default text encoding for the existing database is used.
2111 ** In all cases new databases created using the ATTACH command are
2112 ** created to use the same default text encoding as the main database. If
2113 ** the main database has not been initialized and/or created when ATTACH
2114 ** is executed, this is done before the ATTACH operation.
2116 ** In the second form this pragma sets the text encoding to be used in
2117 ** new database files created using this database handle. It is only
2118 ** useful if invoked immediately after the main database i
2120 case PragTyp_ENCODING: {
2121 static const struct EncName {
2122 char *zName;
2123 u8 enc;
2124 } encnames[] = {
2125 { "UTF8", SQLITE_UTF8 },
2126 { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
2127 { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
2128 { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
2129 { "UTF16le", SQLITE_UTF16LE },
2130 { "UTF16be", SQLITE_UTF16BE },
2131 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
2132 { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
2133 { 0, 0 }
2135 const struct EncName *pEnc;
2136 if( !zRight ){ /* "PRAGMA encoding" */
2137 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
2138 assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
2139 assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
2140 assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
2141 returnSingleText(v, encnames[ENC(pParse->db)].zName);
2142 }else{ /* "PRAGMA encoding = XXX" */
2143 /* Only change the value of sqlite.enc if the database handle is not
2144 ** initialized. If the main database exists, the new sqlite.enc value
2145 ** will be overwritten when the schema is next loaded. If it does not
2146 ** already exists, it will be created to use the new encoding value.
2148 if( (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
2149 for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
2150 if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
2151 u8 enc = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
2152 SCHEMA_ENC(db) = enc;
2153 sqlite3SetTextEncoding(db, enc);
2154 break;
2157 if( !pEnc->zName ){
2158 sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
2163 break;
2164 #endif /* SQLITE_OMIT_UTF16 */
2166 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
2168 ** PRAGMA [schema.]schema_version
2169 ** PRAGMA [schema.]schema_version = <integer>
2171 ** PRAGMA [schema.]user_version
2172 ** PRAGMA [schema.]user_version = <integer>
2174 ** PRAGMA [schema.]freelist_count
2176 ** PRAGMA [schema.]data_version
2178 ** PRAGMA [schema.]application_id
2179 ** PRAGMA [schema.]application_id = <integer>
2181 ** The pragma's schema_version and user_version are used to set or get
2182 ** the value of the schema-version and user-version, respectively. Both
2183 ** the schema-version and the user-version are 32-bit signed integers
2184 ** stored in the database header.
2186 ** The schema-cookie is usually only manipulated internally by SQLite. It
2187 ** is incremented by SQLite whenever the database schema is modified (by
2188 ** creating or dropping a table or index). The schema version is used by
2189 ** SQLite each time a query is executed to ensure that the internal cache
2190 ** of the schema used when compiling the SQL query matches the schema of
2191 ** the database against which the compiled query is actually executed.
2192 ** Subverting this mechanism by using "PRAGMA schema_version" to modify
2193 ** the schema-version is potentially dangerous and may lead to program
2194 ** crashes or database corruption. Use with caution!
2196 ** The user-version is not used internally by SQLite. It may be used by
2197 ** applications for any purpose.
2199 case PragTyp_HEADER_VALUE: {
2200 int iCookie = pPragma->iArg; /* Which cookie to read or write */
2201 sqlite3VdbeUsesBtree(v, iDb);
2202 if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
2203 /* Write the specified cookie value */
2204 static const VdbeOpList setCookie[] = {
2205 { OP_Transaction, 0, 1, 0}, /* 0 */
2206 { OP_SetCookie, 0, 0, 0}, /* 1 */
2208 VdbeOp *aOp;
2209 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
2210 aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
2211 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
2212 aOp[0].p1 = iDb;
2213 aOp[1].p1 = iDb;
2214 aOp[1].p2 = iCookie;
2215 aOp[1].p3 = sqlite3Atoi(zRight);
2216 aOp[1].p5 = 1;
2217 if( iCookie==BTREE_SCHEMA_VERSION && (db->flags & SQLITE_Defensive)!=0 ){
2218 /* Do not allow the use of PRAGMA schema_version=VALUE in defensive
2219 ** mode. Change the OP_SetCookie opcode into a no-op. */
2220 aOp[1].opcode = OP_Noop;
2222 }else{
2223 /* Read the specified cookie value */
2224 static const VdbeOpList readCookie[] = {
2225 { OP_Transaction, 0, 0, 0}, /* 0 */
2226 { OP_ReadCookie, 0, 1, 0}, /* 1 */
2227 { OP_ResultRow, 1, 1, 0}
2229 VdbeOp *aOp;
2230 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
2231 aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
2232 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
2233 aOp[0].p1 = iDb;
2234 aOp[1].p1 = iDb;
2235 aOp[1].p3 = iCookie;
2236 sqlite3VdbeReusable(v);
2239 break;
2240 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
2242 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
2244 ** PRAGMA compile_options
2246 ** Return the names of all compile-time options used in this build,
2247 ** one option per row.
2249 case PragTyp_COMPILE_OPTIONS: {
2250 int i = 0;
2251 const char *zOpt;
2252 pParse->nMem = 1;
2253 while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
2254 sqlite3VdbeLoadString(v, 1, zOpt);
2255 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
2257 sqlite3VdbeReusable(v);
2259 break;
2260 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
2262 #ifndef SQLITE_OMIT_WAL
2264 ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
2266 ** Checkpoint the database.
2268 case PragTyp_WAL_CHECKPOINT: {
2269 int iBt = (pId2->z?iDb:SQLITE_MAX_DB);
2270 int eMode = SQLITE_CHECKPOINT_PASSIVE;
2271 if( zRight ){
2272 if( sqlite3StrICmp(zRight, "full")==0 ){
2273 eMode = SQLITE_CHECKPOINT_FULL;
2274 }else if( sqlite3StrICmp(zRight, "restart")==0 ){
2275 eMode = SQLITE_CHECKPOINT_RESTART;
2276 }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
2277 eMode = SQLITE_CHECKPOINT_TRUNCATE;
2280 pParse->nMem = 3;
2281 sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
2282 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
2284 break;
2287 ** PRAGMA wal_autocheckpoint
2288 ** PRAGMA wal_autocheckpoint = N
2290 ** Configure a database connection to automatically checkpoint a database
2291 ** after accumulating N frames in the log. Or query for the current value
2292 ** of N.
2294 case PragTyp_WAL_AUTOCHECKPOINT: {
2295 if( zRight ){
2296 sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
2298 returnSingleInt(v,
2299 db->xWalCallback==sqlite3WalDefaultHook ?
2300 SQLITE_PTR_TO_INT(db->pWalArg) : 0);
2302 break;
2303 #endif
2306 ** PRAGMA shrink_memory
2308 ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
2309 ** connection on which it is invoked to free up as much memory as it
2310 ** can, by calling sqlite3_db_release_memory().
2312 case PragTyp_SHRINK_MEMORY: {
2313 sqlite3_db_release_memory(db);
2314 break;
2318 ** PRAGMA optimize
2319 ** PRAGMA optimize(MASK)
2320 ** PRAGMA schema.optimize
2321 ** PRAGMA schema.optimize(MASK)
2323 ** Attempt to optimize the database. All schemas are optimized in the first
2324 ** two forms, and only the specified schema is optimized in the latter two.
2326 ** The details of optimizations performed by this pragma are expected
2327 ** to change and improve over time. Applications should anticipate that
2328 ** this pragma will perform new optimizations in future releases.
2330 ** The optional argument is a bitmask of optimizations to perform:
2332 ** 0x0001 Debugging mode. Do not actually perform any optimizations
2333 ** but instead return one line of text for each optimization
2334 ** that would have been done. Off by default.
2336 ** 0x0002 Run ANALYZE on tables that might benefit. On by default.
2337 ** See below for additional information.
2339 ** 0x0004 (Not yet implemented) Record usage and performance
2340 ** information from the current session in the
2341 ** database file so that it will be available to "optimize"
2342 ** pragmas run by future database connections.
2344 ** 0x0008 (Not yet implemented) Create indexes that might have
2345 ** been helpful to recent queries
2347 ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all
2348 ** of the optimizations listed above except Debug Mode, including new
2349 ** optimizations that have not yet been invented. If new optimizations are
2350 ** ever added that should be off by default, those off-by-default
2351 ** optimizations will have bitmasks of 0x10000 or larger.
2353 ** DETERMINATION OF WHEN TO RUN ANALYZE
2355 ** In the current implementation, a table is analyzed if only if all of
2356 ** the following are true:
2358 ** (1) MASK bit 0x02 is set.
2360 ** (2) The query planner used sqlite_stat1-style statistics for one or
2361 ** more indexes of the table at some point during the lifetime of
2362 ** the current connection.
2364 ** (3) One or more indexes of the table are currently unanalyzed OR
2365 ** the number of rows in the table has increased by 25 times or more
2366 ** since the last time ANALYZE was run.
2368 ** The rules for when tables are analyzed are likely to change in
2369 ** future releases.
2371 case PragTyp_OPTIMIZE: {
2372 int iDbLast; /* Loop termination point for the schema loop */
2373 int iTabCur; /* Cursor for a table whose size needs checking */
2374 HashElem *k; /* Loop over tables of a schema */
2375 Schema *pSchema; /* The current schema */
2376 Table *pTab; /* A table in the schema */
2377 Index *pIdx; /* An index of the table */
2378 LogEst szThreshold; /* Size threshold above which reanalysis is needd */
2379 char *zSubSql; /* SQL statement for the OP_SqlExec opcode */
2380 u32 opMask; /* Mask of operations to perform */
2382 if( zRight ){
2383 opMask = (u32)sqlite3Atoi(zRight);
2384 if( (opMask & 0x02)==0 ) break;
2385 }else{
2386 opMask = 0xfffe;
2388 iTabCur = pParse->nTab++;
2389 for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
2390 if( iDb==1 ) continue;
2391 sqlite3CodeVerifySchema(pParse, iDb);
2392 pSchema = db->aDb[iDb].pSchema;
2393 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
2394 pTab = (Table*)sqliteHashData(k);
2396 /* If table pTab has not been used in a way that would benefit from
2397 ** having analysis statistics during the current session, then skip it.
2398 ** This also has the effect of skipping virtual tables and views */
2399 if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
2401 /* Reanalyze if the table is 25 times larger than the last analysis */
2402 szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
2403 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2404 if( !pIdx->hasStat1 ){
2405 szThreshold = 0; /* Always analyze if any index lacks statistics */
2406 break;
2409 if( szThreshold ){
2410 sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
2411 sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
2412 sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
2413 VdbeCoverage(v);
2415 zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
2416 db->aDb[iDb].zDbSName, pTab->zName);
2417 if( opMask & 0x01 ){
2418 int r1 = sqlite3GetTempReg(pParse);
2419 sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
2420 sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
2421 }else{
2422 sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
2426 sqlite3VdbeAddOp0(v, OP_Expire);
2427 break;
2431 ** PRAGMA busy_timeout
2432 ** PRAGMA busy_timeout = N
2434 ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
2435 ** if one is set. If no busy handler or a different busy handler is set
2436 ** then 0 is returned. Setting the busy_timeout to 0 or negative
2437 ** disables the timeout.
2439 /*case PragTyp_BUSY_TIMEOUT*/ default: {
2440 assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
2441 if( zRight ){
2442 sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
2444 returnSingleInt(v, db->busyTimeout);
2445 break;
2449 ** PRAGMA soft_heap_limit
2450 ** PRAGMA soft_heap_limit = N
2452 ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
2453 ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
2454 ** specified and is a non-negative integer.
2455 ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
2456 ** returns the same integer that would be returned by the
2457 ** sqlite3_soft_heap_limit64(-1) C-language function.
2459 case PragTyp_SOFT_HEAP_LIMIT: {
2460 sqlite3_int64 N;
2461 if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
2462 sqlite3_soft_heap_limit64(N);
2464 returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
2465 break;
2469 ** PRAGMA hard_heap_limit
2470 ** PRAGMA hard_heap_limit = N
2472 ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap
2473 ** limit. The hard heap limit can be activated or lowered by this
2474 ** pragma, but not raised or deactivated. Only the
2475 ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate
2476 ** the hard heap limit. This allows an application to set a heap limit
2477 ** constraint that cannot be relaxed by an untrusted SQL script.
2479 case PragTyp_HARD_HEAP_LIMIT: {
2480 sqlite3_int64 N;
2481 if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
2482 sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1);
2483 if( N>0 && (iPrior==0 || iPrior>N) ) sqlite3_hard_heap_limit64(N);
2485 returnSingleInt(v, sqlite3_hard_heap_limit64(-1));
2486 break;
2490 ** PRAGMA threads
2491 ** PRAGMA threads = N
2493 ** Configure the maximum number of worker threads. Return the new
2494 ** maximum, which might be less than requested.
2496 case PragTyp_THREADS: {
2497 sqlite3_int64 N;
2498 if( zRight
2499 && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
2500 && N>=0
2502 sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
2504 returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
2505 break;
2509 ** PRAGMA analysis_limit
2510 ** PRAGMA analysis_limit = N
2512 ** Configure the maximum number of rows that ANALYZE will examine
2513 ** in each index that it looks at. Return the new limit.
2515 case PragTyp_ANALYSIS_LIMIT: {
2516 sqlite3_int64 N;
2517 if( zRight
2518 && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK /* IMP: R-40975-20399 */
2519 && N>=0
2521 db->nAnalysisLimit = (int)(N&0x7fffffff);
2523 returnSingleInt(v, db->nAnalysisLimit); /* IMP: R-57594-65522 */
2524 break;
2527 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
2529 ** Report the current state of file logs for all databases
2531 case PragTyp_LOCK_STATUS: {
2532 static const char *const azLockName[] = {
2533 "unlocked", "shared", "reserved", "pending", "exclusive"
2535 int i;
2536 pParse->nMem = 2;
2537 for(i=0; i<db->nDb; i++){
2538 Btree *pBt;
2539 const char *zState = "unknown";
2540 int j;
2541 if( db->aDb[i].zDbSName==0 ) continue;
2542 pBt = db->aDb[i].pBt;
2543 if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
2544 zState = "closed";
2545 }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
2546 SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
2547 zState = azLockName[j];
2549 sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
2551 break;
2553 #endif
2555 /* BEGIN SQLCIPHER */
2556 #ifdef SQLITE_HAS_CODEC
2557 /* Pragma iArg
2558 ** ---------- ------
2559 ** key 0
2560 ** rekey 1
2561 ** hexkey 2
2562 ** hexrekey 3
2563 ** textkey 4
2564 ** textrekey 5
2566 case PragTyp_KEY: {
2567 if( zRight ){
2568 char zBuf[40];
2569 const char *zKey = zRight;
2570 int n;
2571 if( pPragma->iArg==2 || pPragma->iArg==3 ){
2572 u8 iByte;
2573 int i;
2574 for(i=0, iByte=0; i<sizeof(zBuf)*2 && sqlite3Isxdigit(zRight[i]); i++){
2575 iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
2576 if( (i&1)!=0 ) zBuf[i/2] = iByte;
2578 zKey = zBuf;
2579 n = i/2;
2580 }else{
2581 n = pPragma->iArg<4 ? sqlite3Strlen30(zRight) : -1;
2583 if( (pPragma->iArg & 1)==0 ){
2584 rc = sqlite3_key_v2(db, zDb, zKey, n);
2585 }else{
2586 rc = sqlite3_rekey_v2(db, zDb, zKey, n);
2588 if( rc==SQLITE_OK && n!=0 ){
2589 sqlite3VdbeSetNumCols(v, 1);
2590 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "ok", SQLITE_STATIC);
2591 returnSingleText(v, "ok");
2594 break;
2596 #endif
2597 /* END SQLCIPHER */
2598 #if defined(SQLITE_ENABLE_CEROD)
2599 case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
2600 if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
2601 sqlite3_activate_cerod(&zRight[6]);
2604 break;
2605 #endif
2607 } /* End of the PRAGMA switch */
2609 /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
2610 ** purpose is to execute assert() statements to verify that if the
2611 ** PragFlg_NoColumns1 flag is set and the caller specified an argument
2612 ** to the PRAGMA, the implementation has not added any OP_ResultRow
2613 ** instructions to the VM. */
2614 if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
2615 sqlite3VdbeVerifyNoResultRow(v);
2618 pragma_out:
2619 sqlite3DbFree(db, zLeft);
2620 sqlite3DbFree(db, zRight);
2622 #ifndef SQLITE_OMIT_VIRTUALTABLE
2623 /*****************************************************************************
2624 ** Implementation of an eponymous virtual table that runs a pragma.
2627 typedef struct PragmaVtab PragmaVtab;
2628 typedef struct PragmaVtabCursor PragmaVtabCursor;
2629 struct PragmaVtab {
2630 sqlite3_vtab base; /* Base class. Must be first */
2631 sqlite3 *db; /* The database connection to which it belongs */
2632 const PragmaName *pName; /* Name of the pragma */
2633 u8 nHidden; /* Number of hidden columns */
2634 u8 iHidden; /* Index of the first hidden column */
2636 struct PragmaVtabCursor {
2637 sqlite3_vtab_cursor base; /* Base class. Must be first */
2638 sqlite3_stmt *pPragma; /* The pragma statement to run */
2639 sqlite_int64 iRowid; /* Current rowid */
2640 char *azArg[2]; /* Value of the argument and schema */
2644 ** Pragma virtual table module xConnect method.
2646 static int pragmaVtabConnect(
2647 sqlite3 *db,
2648 void *pAux,
2649 int argc, const char *const*argv,
2650 sqlite3_vtab **ppVtab,
2651 char **pzErr
2653 const PragmaName *pPragma = (const PragmaName*)pAux;
2654 PragmaVtab *pTab = 0;
2655 int rc;
2656 int i, j;
2657 char cSep = '(';
2658 StrAccum acc;
2659 char zBuf[200];
2661 UNUSED_PARAMETER(argc);
2662 UNUSED_PARAMETER(argv);
2663 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
2664 sqlite3_str_appendall(&acc, "CREATE TABLE x");
2665 for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
2666 sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]);
2667 cSep = ',';
2669 if( i==0 ){
2670 sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
2671 i++;
2673 j = 0;
2674 if( pPragma->mPragFlg & PragFlg_Result1 ){
2675 sqlite3_str_appendall(&acc, ",arg HIDDEN");
2676 j++;
2678 if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
2679 sqlite3_str_appendall(&acc, ",schema HIDDEN");
2680 j++;
2682 sqlite3_str_append(&acc, ")", 1);
2683 sqlite3StrAccumFinish(&acc);
2684 assert( strlen(zBuf) < sizeof(zBuf)-1 );
2685 rc = sqlite3_declare_vtab(db, zBuf);
2686 if( rc==SQLITE_OK ){
2687 pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
2688 if( pTab==0 ){
2689 rc = SQLITE_NOMEM;
2690 }else{
2691 memset(pTab, 0, sizeof(PragmaVtab));
2692 pTab->pName = pPragma;
2693 pTab->db = db;
2694 pTab->iHidden = i;
2695 pTab->nHidden = j;
2697 }else{
2698 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
2701 *ppVtab = (sqlite3_vtab*)pTab;
2702 return rc;
2706 ** Pragma virtual table module xDisconnect method.
2708 static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
2709 PragmaVtab *pTab = (PragmaVtab*)pVtab;
2710 sqlite3_free(pTab);
2711 return SQLITE_OK;
2714 /* Figure out the best index to use to search a pragma virtual table.
2716 ** There are not really any index choices. But we want to encourage the
2717 ** query planner to give == constraints on as many hidden parameters as
2718 ** possible, and especially on the first hidden parameter. So return a
2719 ** high cost if hidden parameters are unconstrained.
2721 static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
2722 PragmaVtab *pTab = (PragmaVtab*)tab;
2723 const struct sqlite3_index_constraint *pConstraint;
2724 int i, j;
2725 int seen[2];
2727 pIdxInfo->estimatedCost = (double)1;
2728 if( pTab->nHidden==0 ){ return SQLITE_OK; }
2729 pConstraint = pIdxInfo->aConstraint;
2730 seen[0] = 0;
2731 seen[1] = 0;
2732 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
2733 if( pConstraint->usable==0 ) continue;
2734 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
2735 if( pConstraint->iColumn < pTab->iHidden ) continue;
2736 j = pConstraint->iColumn - pTab->iHidden;
2737 assert( j < 2 );
2738 seen[j] = i+1;
2740 if( seen[0]==0 ){
2741 pIdxInfo->estimatedCost = (double)2147483647;
2742 pIdxInfo->estimatedRows = 2147483647;
2743 return SQLITE_OK;
2745 j = seen[0]-1;
2746 pIdxInfo->aConstraintUsage[j].argvIndex = 1;
2747 pIdxInfo->aConstraintUsage[j].omit = 1;
2748 if( seen[1]==0 ) return SQLITE_OK;
2749 pIdxInfo->estimatedCost = (double)20;
2750 pIdxInfo->estimatedRows = 20;
2751 j = seen[1]-1;
2752 pIdxInfo->aConstraintUsage[j].argvIndex = 2;
2753 pIdxInfo->aConstraintUsage[j].omit = 1;
2754 return SQLITE_OK;
2757 /* Create a new cursor for the pragma virtual table */
2758 static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
2759 PragmaVtabCursor *pCsr;
2760 pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
2761 if( pCsr==0 ) return SQLITE_NOMEM;
2762 memset(pCsr, 0, sizeof(PragmaVtabCursor));
2763 pCsr->base.pVtab = pVtab;
2764 *ppCursor = &pCsr->base;
2765 return SQLITE_OK;
2768 /* Clear all content from pragma virtual table cursor. */
2769 static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
2770 int i;
2771 sqlite3_finalize(pCsr->pPragma);
2772 pCsr->pPragma = 0;
2773 for(i=0; i<ArraySize(pCsr->azArg); i++){
2774 sqlite3_free(pCsr->azArg[i]);
2775 pCsr->azArg[i] = 0;
2779 /* Close a pragma virtual table cursor */
2780 static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
2781 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
2782 pragmaVtabCursorClear(pCsr);
2783 sqlite3_free(pCsr);
2784 return SQLITE_OK;
2787 /* Advance the pragma virtual table cursor to the next row */
2788 static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
2789 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2790 int rc = SQLITE_OK;
2792 /* Increment the xRowid value */
2793 pCsr->iRowid++;
2794 assert( pCsr->pPragma );
2795 if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
2796 rc = sqlite3_finalize(pCsr->pPragma);
2797 pCsr->pPragma = 0;
2798 pragmaVtabCursorClear(pCsr);
2800 return rc;
2804 ** Pragma virtual table module xFilter method.
2806 static int pragmaVtabFilter(
2807 sqlite3_vtab_cursor *pVtabCursor,
2808 int idxNum, const char *idxStr,
2809 int argc, sqlite3_value **argv
2811 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2812 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
2813 int rc;
2814 int i, j;
2815 StrAccum acc;
2816 char *zSql;
2818 UNUSED_PARAMETER(idxNum);
2819 UNUSED_PARAMETER(idxStr);
2820 pragmaVtabCursorClear(pCsr);
2821 j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
2822 for(i=0; i<argc; i++, j++){
2823 const char *zText = (const char*)sqlite3_value_text(argv[i]);
2824 assert( j<ArraySize(pCsr->azArg) );
2825 assert( pCsr->azArg[j]==0 );
2826 if( zText ){
2827 pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
2828 if( pCsr->azArg[j]==0 ){
2829 return SQLITE_NOMEM;
2833 sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
2834 sqlite3_str_appendall(&acc, "PRAGMA ");
2835 if( pCsr->azArg[1] ){
2836 sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
2838 sqlite3_str_appendall(&acc, pTab->pName->zName);
2839 if( pCsr->azArg[0] ){
2840 sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
2842 zSql = sqlite3StrAccumFinish(&acc);
2843 if( zSql==0 ) return SQLITE_NOMEM;
2844 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
2845 sqlite3_free(zSql);
2846 if( rc!=SQLITE_OK ){
2847 pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
2848 return rc;
2850 return pragmaVtabNext(pVtabCursor);
2854 ** Pragma virtual table module xEof method.
2856 static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
2857 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2858 return (pCsr->pPragma==0);
2861 /* The xColumn method simply returns the corresponding column from
2862 ** the PRAGMA.
2864 static int pragmaVtabColumn(
2865 sqlite3_vtab_cursor *pVtabCursor,
2866 sqlite3_context *ctx,
2867 int i
2869 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2870 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
2871 if( i<pTab->iHidden ){
2872 sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
2873 }else{
2874 sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
2876 return SQLITE_OK;
2880 ** Pragma virtual table module xRowid method.
2882 static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
2883 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2884 *p = pCsr->iRowid;
2885 return SQLITE_OK;
2888 /* The pragma virtual table object */
2889 static const sqlite3_module pragmaVtabModule = {
2890 0, /* iVersion */
2891 0, /* xCreate - create a table */
2892 pragmaVtabConnect, /* xConnect - connect to an existing table */
2893 pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */
2894 pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */
2895 0, /* xDestroy - Drop a table */
2896 pragmaVtabOpen, /* xOpen - open a cursor */
2897 pragmaVtabClose, /* xClose - close a cursor */
2898 pragmaVtabFilter, /* xFilter - configure scan constraints */
2899 pragmaVtabNext, /* xNext - advance a cursor */
2900 pragmaVtabEof, /* xEof */
2901 pragmaVtabColumn, /* xColumn - read data */
2902 pragmaVtabRowid, /* xRowid - read data */
2903 0, /* xUpdate - write data */
2904 0, /* xBegin - begin transaction */
2905 0, /* xSync - sync transaction */
2906 0, /* xCommit - commit transaction */
2907 0, /* xRollback - rollback transaction */
2908 0, /* xFindFunction - function overloading */
2909 0, /* xRename - rename the table */
2910 0, /* xSavepoint */
2911 0, /* xRelease */
2912 0, /* xRollbackTo */
2913 0 /* xShadowName */
2917 ** Check to see if zTabName is really the name of a pragma. If it is,
2918 ** then register an eponymous virtual table for that pragma and return
2919 ** a pointer to the Module object for the new virtual table.
2921 Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
2922 const PragmaName *pName;
2923 assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
2924 pName = pragmaLocate(zName+7);
2925 if( pName==0 ) return 0;
2926 if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
2927 assert( sqlite3HashFind(&db->aModule, zName)==0 );
2928 return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
2931 #endif /* SQLITE_OMIT_VIRTUALTABLE */
2933 #endif /* SQLITE_OMIT_PRAGMA */