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