interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / src / pragma.c

3105 lines · 110629 bytes Raw Blame History
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.
10**
11*************************************************************************
12** This file contains code used to implement the PRAGMA command.
13*/
14#include "sqliteInt.h"
15
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
23
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"
32
33/*
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.
38**
39** The value of 2000 is chosen empirically 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.
52**
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.
56*/
57#ifndef SQLITE_DEFAULT_OPTIMIZE_LIMIT
58# define SQLITE_DEFAULT_OPTIMIZE_LIMIT 2000
59#endif
60
61/*
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.
66**
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.
71*/
72static 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 sqlite3Atoi(z)!=0;
82 }
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)
87 ){
88 return iValue[i];
89 }
90 }
91 return dflt;
92}
93
94/*
95** Interpret the given string as a boolean value.
96*/
97u8 sqlite3GetBoolean(const char *z, u8 dflt){
98 return getSafetyLevel(z,1,dflt)!=0;
99}
100
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.
104*/
105#if !defined(SQLITE_OMIT_PRAGMA)
106
107/*
108** Interpret the given string as a locking mode value.
109*/
110static 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;
114 }
115 return PAGER_LOCKINGMODE_QUERY;
116}
117
118#ifndef SQLITE_OMIT_AUTOVACUUM
119/*
120** Interpret the given string as an auto-vacuum mode value.
121**
122** The following strings, "none", "full" and "incremental" are
123** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
124*/
125static 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);
132}
133#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
134
135#ifndef SQLITE_OMIT_PAGER_PRAGMAS
136/*
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.
140*/
141static 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;
150 }
151}
152#endif /* SQLITE_PAGER_PRAGMAS */
153
154#ifndef SQLITE_OMIT_PAGER_PRAGMAS
155/*
156** Invalidate temp storage, either when the temp storage is changed
157** from default, or when 'file' and the temp_store_directory has changed
158*/
159static 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
164 ){
165 sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
166 "from within a transaction");
167 return SQLITE_ERROR;
168 }
169 sqlite3BtreeClose(db->aDb[1].pBt);
170 db->aDb[1].pBt = 0;
171 sqlite3ResetAllSchemasOfConnection(db);
172 }
173 return SQLITE_OK;
174}
175#endif /* SQLITE_PAGER_PRAGMAS */
176
177#ifndef SQLITE_OMIT_PAGER_PRAGMAS
178/*
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.
182*/
183static 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;
189 }
190 db->temp_store = (u8)ts;
191 return SQLITE_OK;
192}
193#endif /* SQLITE_PAGER_PRAGMAS */
194
195/*
196** Set result column names for a pragma.
197*/
198static void setPragmaResultColumnNames(
199 Vdbe *v, /* The query under construction */
200 const PragmaName *pPragma /* The pragma */
201){
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);
210 }
211 }
212}
213
214/*
215** Generate code to return a single integer value.
216*/
217static void returnSingleInt(Vdbe *v, i64 value){
218 sqlite3VdbeAddInt64(v, 1, value);
219 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
220}
221
222/*
223** Generate code to return a single text value.
224*/
225static void returnSingleText(
226 Vdbe *v, /* Prepared statement under construction */
227 const char *zValue /* Value to be returned */
228){
229 if( zValue ){
230 sqlite3VdbeLoadString(v, 1, (const char*)zValue);
231 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
232 }
233}
234
235
236/*
237** Set the safety_level and pager flags for pager iDb. Or if iDb<0
238** set these values for all pagers.
239*/
240#ifndef SQLITE_OMIT_PAGER_PRAGMAS
241static 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) );
255 }
256 pDb++;
257 }
258 }
259}
260#else
261# define setAllPagerFlags(X) /* no-op */
262#endif
263
264
265/*
266** Return a human-readable name for a constraint resolution action.
267*/
268#ifndef SQLITE_OMIT_FOREIGN_KEY
269static 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;
278 }
279 return zName;
280}
281#endif
282
283
284/*
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.
288*/
289const char *sqlite3JournalModename(int eMode){
290 static char * const azModeName[] = {
291 "delete", "persist", "off", "truncate", "memory"
292#ifndef SQLITE_OMIT_WAL
293 , "wal"
294#endif
295 };
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) );
303
304 if( eMode==ArraySize(azModeName) ) return 0;
305 return azModeName[eMode];
306}
307
308/*
309** Locate a pragma in the aPragmaName[] array.
310*/
311static 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;
323 }
324 }
325 return lwr>upr ? 0 : &aPragmaName[mid];
326}
327
328/*
329** Create zero or more entries in the output for the SQL functions
330** defined by FuncDef p.
331*/
332static 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 */
337){
338 u32 mask =
339 SQLITE_DETERMINISTIC |
340 SQLITE_DIRECTONLY |
341 SQLITE_SUBTYPE |
342 SQLITE_INNOCUOUS |
343 SQLITE_FUNC_INTERNAL
344 ;
345 if( showInternFuncs ) mask = 0xffffffff;
346 for(; p; p=p->pNext){
347 const char *zType;
348 static const char *azEnc[] = { 0, "utf8", "utf16le", "utf16be" };
349
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 );
354
355 if( p->xSFunc==0 ) continue;
356 if( (p->funcFlags & SQLITE_FUNC_INTERNAL)!=0
357 && showInternFuncs==0
358 ){
359 continue;
360 }
361 if( p->xValue!=0 ){
362 zType = "w";
363 }else if( p->xFinalize!=0 ){
364 zType = "a";
365 }else{
366 zType = "s";
367 }
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
373 );
374 }
375}
376
377
378/*
379** Helper subroutine for PRAGMA integrity_check:
380**
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.
384*/
385static 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;
392}
393
394/*
395** Should table pTab be skipped when doing an integrity_check?
396** Return true or false.
397**
398** If pObjTab is not null, the return true if pTab matches pObjTab.
399**
400** If pObjTab is null, then return true only if pTab is an imposter table.
401*/
402static int tableSkipIntegrityCheck(const Table *pTab, const Table *pObjTab){
403 if( pObjTab ){
404 return pTab!=pObjTab;
405 }else{
406 return (pTab->tabFlags & TF_Imposter)!=0;
407 }
408}
409
410/*
411** Process a pragma statement.
412**
413** Pragmas are of this form:
414**
415** PRAGMA [schema.]id [= value]
416**
417** The identifier might also be a string. The value is a string, and
418** identifier, or a number. If minusFlag is true, then the value is
419** a number that was preceded by a minus sign.
420**
421** If the left side is "database.id" then pId1 is the database name
422** and pId2 is the id. If the left side is just "id" then pId1 is the
423** id and pId2 is any empty string.
424*/
425void sqlite3Pragma(
426 Parse *pParse,
427 Token *pId1, /* First part of [schema.]id field */
428 Token *pId2, /* Second part of [schema.]id field, or NULL */
429 Token *pValue, /* Token for <value>, or NULL */
430 int minusFlag /* True if a '-' sign preceded <value> */
431){
432 char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
433 char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
434 const char *zDb = 0; /* The database name */
435 Token *pId; /* Pointer to <id> token */
436 char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
437 int iDb; /* Database index for <database> */
438 int rc; /* return value form SQLITE_FCNTL_PRAGMA */
439 sqlite3 *db = pParse->db; /* The database connection */
440 Db *pDb; /* The specific database being pragmaed */
441 Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
442 const PragmaName *pPragma; /* The pragma */
443
444 if( v==0 ) return;
445 sqlite3VdbeRunOnlyOnce(v);
446 pParse->nMem = 2;
447
448 /* Interpret the [schema.] part of the pragma statement. iDb is the
449 ** index of the database this pragma is being applied to in db.aDb[]. */
450 iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
451 if( iDb<0 ) return;
452 pDb = &db->aDb[iDb];
453
454 /* If the temp database has been explicitly named as part of the
455 ** pragma, make sure it is open.
456 */
457 if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
458 return;
459 }
460
461 zLeft = sqlite3NameFromToken(db, pId);
462 if( !zLeft ) return;
463 if( minusFlag ){
464 zRight = sqlite3MPrintf(db, "-%T", pValue);
465 }else{
466 zRight = sqlite3NameFromToken(db, pValue);
467 }
468
469 assert( pId2 );
470 zDb = pId2->n>0 ? pDb->zDbSName : 0;
471 if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
472 goto pragma_out;
473 }
474
475 /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
476 ** connection. If it returns SQLITE_OK, then assume that the VFS
477 ** handled the pragma and generate a no-op prepared statement.
478 **
479 ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
480 ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
481 ** object corresponding to the database file to which the pragma
482 ** statement refers.
483 **
484 ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
485 ** file control is an array of pointers to strings (char**) in which the
486 ** second element of the array is the name of the pragma and the third
487 ** element is the argument to the pragma or NULL if the pragma has no
488 ** argument.
489 */
490 aFcntl[0] = 0;
491 aFcntl[1] = zLeft;
492 aFcntl[2] = zRight;
493 aFcntl[3] = 0;
494 db->busyHandler.nBusy = 0;
495 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
496 if( rc==SQLITE_OK ){
497 sqlite3VdbeSetNumCols(v, 1);
498 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
499 returnSingleText(v, aFcntl[0]);
500 sqlite3_free(aFcntl[0]);
501 goto pragma_out;
502 }
503 if( rc!=SQLITE_NOTFOUND ){
504 if( aFcntl[0] ){
505 sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
506 sqlite3_free(aFcntl[0]);
507 }
508 pParse->nErr++;
509 pParse->rc = rc;
510 goto pragma_out;
511 }
512
513 /* Locate the pragma in the lookup table */
514 pPragma = pragmaLocate(zLeft);
515 if( pPragma==0 ){
516 /* IMP: R-43042-22504 No error messages are generated if an
517 ** unknown pragma is issued. */
518 goto pragma_out;
519 }
520
521 /* Make sure the database schema is loaded if the pragma requires that */
522 if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
523 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
524 }
525
526 /* Register the result column names for pragmas that return results */
527 if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
528 && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
529 ){
530 setPragmaResultColumnNames(v, pPragma);
531 }
532
533 /* Jump to the appropriate pragma handler */
534 switch( pPragma->ePragTyp ){
535
536#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
537 /*
538 ** PRAGMA [schema.]default_cache_size
539 ** PRAGMA [schema.]default_cache_size=N
540 **
541 ** The first form reports the current persistent setting for the
542 ** page cache size. The value returned is the maximum number of
543 ** pages in the page cache. The second form sets both the current
544 ** page cache size value and the persistent page cache size value
545 ** stored in the database file.
546 **
547 ** Older versions of SQLite would set the default cache size to a
548 ** negative number to indicate synchronous=OFF. These days, synchronous
549 ** is always on by default regardless of the sign of the default cache
550 ** size. But continue to take the absolute value of the default cache
551 ** size of historical compatibility.
552 */
553 case PragTyp_DEFAULT_CACHE_SIZE: {
554 static const int iLn = VDBE_OFFSET_LINENO(2);
555 static const VdbeOpList getCacheSize[] = {
556 { OP_Transaction, 0, 0, 0}, /* 0 */
557 { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
558 { OP_IfPos, 1, 8, 0},
559 { OP_Integer, 0, 2, 0},
560 { OP_Subtract, 1, 2, 1},
561 { OP_IfPos, 1, 8, 0},
562 { OP_Integer, 0, 1, 0}, /* 6 */
563 { OP_Noop, 0, 0, 0},
564 { OP_ResultRow, 1, 1, 0},
565 };
566 VdbeOp *aOp;
567 sqlite3VdbeUsesBtree(v, iDb);
568 if( !zRight ){
569 pParse->nMem += 2;
570 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
571 aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
572 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
573 aOp[0].p1 = iDb;
574 aOp[1].p1 = iDb;
575 aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
576 }else{
577 int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
578 sqlite3BeginWriteOperation(pParse, 0, iDb);
579 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
580 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
581 pDb->pSchema->cache_size = size;
582 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
583 }
584 break;
585 }
586#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
587
588#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
589 /*
590 ** PRAGMA [schema.]page_size
591 ** PRAGMA [schema.]page_size=N
592 **
593 ** The first form reports the current setting for the
594 ** database page size in bytes. The second form sets the
595 ** database page size value. The value can only be set if
596 ** the database has not yet been created.
597 */
598 case PragTyp_PAGE_SIZE: {
599 Btree *pBt = pDb->pBt;
600 assert( pBt!=0 );
601 if( !zRight ){
602 int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
603 returnSingleInt(v, size);
604 }else{
605 /* Malloc may fail when setting the page-size, as there is an internal
606 ** buffer that the pager module resizes using sqlite3_realloc().
607 */
608 db->nextPagesize = sqlite3Atoi(zRight);
609 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,0,0) ){
610 sqlite3OomFault(db);
611 }
612 }
613 break;
614 }
615
616 /*
617 ** PRAGMA [schema.]secure_delete
618 ** PRAGMA [schema.]secure_delete=ON/OFF/FAST
619 **
620 ** The first form reports the current setting for the
621 ** secure_delete flag. The second form changes the secure_delete
622 ** flag setting and reports the new value.
623 */
624 case PragTyp_SECURE_DELETE: {
625 Btree *pBt = pDb->pBt;
626 int b = -1;
627 assert( pBt!=0 );
628 if( zRight ){
629 if( sqlite3_stricmp(zRight, "fast")==0 ){
630 b = 2;
631 }else{
632 b = sqlite3GetBoolean(zRight, 0);
633 }
634 }
635 if( pId2->n==0 && b>=0 ){
636 int ii;
637 for(ii=0; ii<db->nDb; ii++){
638 sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
639 }
640 }
641 b = sqlite3BtreeSecureDelete(pBt, b);
642 returnSingleInt(v, b);
643 break;
644 }
645
646 /*
647 ** PRAGMA [schema.]max_page_count
648 ** PRAGMA [schema.]max_page_count=N
649 **
650 ** The first form reports the current setting for the
651 ** maximum number of pages in the database file. The
652 ** second form attempts to change this setting. Both
653 ** forms return the current setting.
654 **
655 ** The absolute value of N is used. This is undocumented and might
656 ** change. The only purpose is to provide an easy way to test
657 ** the sqlite3AbsInt32() function.
658 **
659 ** PRAGMA [schema.]page_count
660 **
661 ** Return the number of pages in the specified database.
662 */
663 case PragTyp_PAGE_COUNT: {
664 int iReg;
665 i64 x = 0;
666 sqlite3CodeVerifySchema(pParse, iDb);
667 iReg = ++pParse->nMem;
668 if( sqlite3Tolower(zLeft[0])=='p' ){
669 sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
670 }else{
671 if( zRight && sqlite3DecOrHexToI64(zRight,&x)==0 ){
672 if( x<0 ) x = 0;
673 else if( x>0xfffffffe ) x = 0xfffffffe;
674 }else{
675 x = 0;
676 }
677 sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, (int)x);
678 }
679 sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
680 break;
681 }
682
683 /*
684 ** PRAGMA [schema.]locking_mode
685 ** PRAGMA [schema.]locking_mode = (normal|exclusive)
686 */
687 case PragTyp_LOCKING_MODE: {
688 const char *zRet = "normal";
689 int eMode = getLockingMode(zRight);
690
691 if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
692 /* Simple "PRAGMA locking_mode;" statement. This is a query for
693 ** the current default locking mode (which may be different to
694 ** the locking-mode of the main database).
695 */
696 eMode = db->dfltLockMode;
697 }else{
698 Pager *pPager;
699 if( pId2->n==0 ){
700 /* This indicates that no database name was specified as part
701 ** of the PRAGMA command. In this case the locking-mode must be
702 ** set on all attached databases, as well as the main db file.
703 **
704 ** Also, the sqlite3.dfltLockMode variable is set so that
705 ** any subsequently attached databases also use the specified
706 ** locking mode.
707 */
708 int ii;
709 assert(pDb==&db->aDb[0]);
710 for(ii=2; ii<db->nDb; ii++){
711 pPager = sqlite3BtreePager(db->aDb[ii].pBt);
712 sqlite3PagerLockingMode(pPager, eMode);
713 }
714 db->dfltLockMode = (u8)eMode;
715 }
716 pPager = sqlite3BtreePager(pDb->pBt);
717 eMode = sqlite3PagerLockingMode(pPager, eMode);
718 }
719
720 assert( eMode==PAGER_LOCKINGMODE_NORMAL
721 || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
722 if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
723 zRet = "exclusive";
724 }
725 returnSingleText(v, zRet);
726 break;
727 }
728
729 /*
730 ** PRAGMA [schema.]journal_mode
731 ** PRAGMA [schema.]journal_mode =
732 ** (delete|persist|off|truncate|memory|wal|off)
733 */
734 case PragTyp_JOURNAL_MODE: {
735 int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
736 int ii; /* Loop counter */
737
738 if( zRight==0 ){
739 /* If there is no "=MODE" part of the pragma, do a query for the
740 ** current mode */
741 eMode = PAGER_JOURNALMODE_QUERY;
742 }else{
743 const char *zMode;
744 int n = sqlite3Strlen30(zRight);
745 for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
746 if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
747 }
748 if( !zMode ){
749 /* If the "=MODE" part does not match any known journal mode,
750 ** then do a query */
751 eMode = PAGER_JOURNALMODE_QUERY;
752 }
753 if( eMode==PAGER_JOURNALMODE_OFF && (db->flags & SQLITE_Defensive)!=0 ){
754 /* Do not allow journal-mode "OFF" in defensive since the database
755 ** can become corrupted using ordinary SQL when the journal is off */
756 eMode = PAGER_JOURNALMODE_QUERY;
757 }
758 }
759 if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
760 /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
761 iDb = 0;
762 pId2->n = 1;
763 }
764 for(ii=db->nDb-1; ii>=0; ii--){
765 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
766 sqlite3VdbeUsesBtree(v, ii);
767 sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
768 }
769 }
770 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
771 break;
772 }
773
774 /*
775 ** PRAGMA [schema.]journal_size_limit
776 ** PRAGMA [schema.]journal_size_limit=N
777 **
778 ** Get or set the size limit on rollback journal files.
779 */
780 case PragTyp_JOURNAL_SIZE_LIMIT: {
781 Pager *pPager = sqlite3BtreePager(pDb->pBt);
782 i64 iLimit = -2;
783 if( zRight ){
784 sqlite3DecOrHexToI64(zRight, &iLimit);
785 if( iLimit<-1 ) iLimit = -1;
786 }
787 iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
788 returnSingleInt(v, iLimit);
789 break;
790 }
791
792#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
793
794 /*
795 ** PRAGMA [schema.]auto_vacuum
796 ** PRAGMA [schema.]auto_vacuum=N
797 **
798 ** Get or set the value of the database 'auto-vacuum' parameter.
799 ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
800 */
801#ifndef SQLITE_OMIT_AUTOVACUUM
802 case PragTyp_AUTO_VACUUM: {
803 Btree *pBt = pDb->pBt;
804 assert( pBt!=0 );
805 if( !zRight ){
806 returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
807 }else{
808 int eAuto = getAutoVacuum(zRight);
809 assert( eAuto>=0 && eAuto<=2 );
810 db->nextAutovac = (u8)eAuto;
811 /* Call SetAutoVacuum() to set initialize the internal auto and
812 ** incr-vacuum flags. This is required in case this connection
813 ** creates the database file. It is important that it is created
814 ** as an auto-vacuum capable db.
815 */
816 rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
817 if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
818 /* When setting the auto_vacuum mode to either "full" or
819 ** "incremental", write the value of meta[6] in the database
820 ** file. Before writing to meta[6], check that meta[3] indicates
821 ** that this really is an auto-vacuum capable database.
822 */
823 static const int iLn = VDBE_OFFSET_LINENO(2);
824 static const VdbeOpList setMeta6[] = {
825 { OP_Transaction, 0, 1, 0}, /* 0 */
826 { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
827 { OP_If, 1, 0, 0}, /* 2 */
828 { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
829 { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */
830 };
831 VdbeOp *aOp;
832 int iAddr = sqlite3VdbeCurrentAddr(v);
833 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
834 aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
835 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
836 aOp[0].p1 = iDb;
837 aOp[1].p1 = iDb;
838 aOp[2].p2 = iAddr+4;
839 aOp[4].p1 = iDb;
840 aOp[4].p3 = eAuto - 1;
841 sqlite3VdbeUsesBtree(v, iDb);
842 }
843 }
844 break;
845 }
846#endif
847
848 /*
849 ** PRAGMA [schema.]incremental_vacuum(N)
850 **
851 ** Do N steps of incremental vacuuming on a database.
852 */
853#ifndef SQLITE_OMIT_AUTOVACUUM
854 case PragTyp_INCREMENTAL_VACUUM: {
855 int iLimit = 0, addr;
856 if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
857 iLimit = 0x7fffffff;
858 }
859 sqlite3BeginWriteOperation(pParse, 0, iDb);
860 sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
861 addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
862 sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
863 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
864 sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
865 sqlite3VdbeJumpHere(v, addr);
866 break;
867 }
868#endif
869
870#ifndef SQLITE_OMIT_PAGER_PRAGMAS
871 /*
872 ** PRAGMA [schema.]cache_size
873 ** PRAGMA [schema.]cache_size=N
874 **
875 ** The first form reports the current local setting for the
876 ** page cache size. The second form sets the local
877 ** page cache size value. If N is positive then that is the
878 ** number of pages in the cache. If N is negative, then the
879 ** number of pages is adjusted so that the cache uses -N kibibytes
880 ** of memory.
881 */
882 case PragTyp_CACHE_SIZE: {
883 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
884 if( !zRight ){
885 returnSingleInt(v, pDb->pSchema->cache_size);
886 }else{
887 int size = sqlite3Atoi(zRight);
888 pDb->pSchema->cache_size = size;
889 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
890 }
891 break;
892 }
893
894 /*
895 ** PRAGMA [schema.]cache_spill
896 ** PRAGMA cache_spill=BOOLEAN
897 ** PRAGMA [schema.]cache_spill=N
898 **
899 ** The first form reports the current local setting for the
900 ** page cache spill size. The second form turns cache spill on
901 ** or off. When turning cache spill on, the size is set to the
902 ** current cache_size. The third form sets a spill size that
903 ** may be different form the cache size.
904 ** If N is positive then that is the
905 ** number of pages in the cache. If N is negative, then the
906 ** number of pages is adjusted so that the cache uses -N kibibytes
907 ** of memory.
908 **
909 ** If the number of cache_spill pages is less then the number of
910 ** cache_size pages, no spilling occurs until the page count exceeds
911 ** the number of cache_size pages.
912 **
913 ** The cache_spill=BOOLEAN setting applies to all attached schemas,
914 ** not just the schema specified.
915 */
916 case PragTyp_CACHE_SPILL: {
917 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
918 if( !zRight ){
919 returnSingleInt(v,
920 (db->flags & SQLITE_CacheSpill)==0 ? 0 :
921 sqlite3BtreeSetSpillSize(pDb->pBt,0));
922 }else{
923 int size = 1;
924 if( sqlite3GetInt32(zRight, &size) ){
925 sqlite3BtreeSetSpillSize(pDb->pBt, size);
926 }
927 if( sqlite3GetBoolean(zRight, size!=0) ){
928 db->flags |= SQLITE_CacheSpill;
929 }else{
930 db->flags &= ~(u64)SQLITE_CacheSpill;
931 }
932 setAllPagerFlags(db);
933 }
934 break;
935 }
936
937 /*
938 ** PRAGMA [schema.]mmap_size(N)
939 **
940 ** Used to set mapping size limit. The mapping size limit is
941 ** used to limit the aggregate size of all memory mapped regions of the
942 ** database file. If this parameter is set to zero, then memory mapping
943 ** is not used at all. If N is negative, then the default memory map
944 ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
945 ** The parameter N is measured in bytes.
946 **
947 ** This value is advisory. The underlying VFS is free to memory map
948 ** as little or as much as it wants. Except, if N is set to 0 then the
949 ** upper layers will never invoke the xFetch interfaces to the VFS.
950 */
951 case PragTyp_MMAP_SIZE: {
952 sqlite3_int64 sz;
953#if SQLITE_MAX_MMAP_SIZE>0
954 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
955 if( zRight ){
956 int ii;
957 sqlite3DecOrHexToI64(zRight, &sz);
958 if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
959 if( pId2->n==0 ) db->szMmap = sz;
960 for(ii=db->nDb-1; ii>=0; ii--){
961 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
962 sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
963 }
964 }
965 }
966 sz = -1;
967 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
968#else
969 sz = 0;
970 rc = SQLITE_OK;
971#endif
972 if( rc==SQLITE_OK ){
973 returnSingleInt(v, sz);
974 }else if( rc!=SQLITE_NOTFOUND ){
975 pParse->nErr++;
976 pParse->rc = rc;
977 }
978 break;
979 }
980
981 /*
982 ** PRAGMA temp_store
983 ** PRAGMA temp_store = "default"|"memory"|"file"
984 **
985 ** Return or set the local value of the temp_store flag. Changing
986 ** the local value does not make changes to the disk file and the default
987 ** value will be restored the next time the database is opened.
988 **
989 ** Note that it is possible for the library compile-time options to
990 ** override this setting
991 */
992 case PragTyp_TEMP_STORE: {
993 if( !zRight ){
994 returnSingleInt(v, db->temp_store);
995 }else{
996 changeTempStorage(pParse, zRight);
997 }
998 break;
999 }
1000
1001 /*
1002 ** PRAGMA temp_store_directory
1003 ** PRAGMA temp_store_directory = ""|"directory_name"
1004 **
1005 ** Return or set the local value of the temp_store_directory flag. Changing
1006 ** the value sets a specific directory to be used for temporary files.
1007 ** Setting to a null string reverts to the default temporary directory search.
1008 ** If temporary directory is changed, then invalidateTempStorage.
1009 **
1010 */
1011 case PragTyp_TEMP_STORE_DIRECTORY: {
1012 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
1013 if( !zRight ){
1014 returnSingleText(v, sqlite3_temp_directory);
1015 }else{
1016#ifndef SQLITE_OMIT_WSD
1017 if( zRight[0] ){
1018 int res;
1019 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
1020 if( rc!=SQLITE_OK || res==0 ){
1021 sqlite3ErrorMsg(pParse, "not a writable directory");
1022 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
1023 goto pragma_out;
1024 }
1025 }
1026 if( SQLITE_TEMP_STORE==0
1027 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
1028 || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
1029 ){
1030 invalidateTempStorage(pParse);
1031 }
1032 sqlite3_free(sqlite3_temp_directory);
1033 if( zRight[0] ){
1034 sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
1035 }else{
1036 sqlite3_temp_directory = 0;
1037 }
1038#endif /* SQLITE_OMIT_WSD */
1039 }
1040 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
1041 break;
1042 }
1043
1044#if SQLITE_OS_WIN
1045 /*
1046 ** PRAGMA data_store_directory
1047 ** PRAGMA data_store_directory = ""|"directory_name"
1048 **
1049 ** Return or set the local value of the data_store_directory flag. Changing
1050 ** the value sets a specific directory to be used for database files that
1051 ** were specified with a relative pathname. Setting to a null string reverts
1052 ** to the default database directory, which for database files specified with
1053 ** a relative path will probably be based on the current directory for the
1054 ** process. Database file specified with an absolute path are not impacted
1055 ** by this setting, regardless of its value.
1056 **
1057 */
1058 case PragTyp_DATA_STORE_DIRECTORY: {
1059 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
1060 if( !zRight ){
1061 returnSingleText(v, sqlite3_data_directory);
1062 }else{
1063#ifndef SQLITE_OMIT_WSD
1064 if( zRight[0] ){
1065 int res;
1066 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
1067 if( rc!=SQLITE_OK || res==0 ){
1068 sqlite3ErrorMsg(pParse, "not a writable directory");
1069 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
1070 goto pragma_out;
1071 }
1072 }
1073 sqlite3_free(sqlite3_data_directory);
1074 if( zRight[0] ){
1075 sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
1076 }else{
1077 sqlite3_data_directory = 0;
1078 }
1079#endif /* SQLITE_OMIT_WSD */
1080 }
1081 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
1082 break;
1083 }
1084#endif
1085
1086#if SQLITE_ENABLE_LOCKING_STYLE
1087 /*
1088 ** PRAGMA [schema.]lock_proxy_file
1089 ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
1090 **
1091 ** Return or set the value of the lock_proxy_file flag. Changing
1092 ** the value sets a specific file to be used for database access locks.
1093 **
1094 */
1095 case PragTyp_LOCK_PROXY_FILE: {
1096 if( !zRight ){
1097 Pager *pPager = sqlite3BtreePager(pDb->pBt);
1098 char *proxy_file_path = NULL;
1099 sqlite3_file *pFile = sqlite3PagerFile(pPager);
1100 sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
1101 &proxy_file_path);
1102 returnSingleText(v, proxy_file_path);
1103 }else{
1104 Pager *pPager = sqlite3BtreePager(pDb->pBt);
1105 sqlite3_file *pFile = sqlite3PagerFile(pPager);
1106 int res;
1107 if( zRight[0] ){
1108 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
1109 zRight);
1110 } else {
1111 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
1112 NULL);
1113 }
1114 if( res!=SQLITE_OK ){
1115 sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
1116 goto pragma_out;
1117 }
1118 }
1119 break;
1120 }
1121#endif /* SQLITE_ENABLE_LOCKING_STYLE */
1122
1123 /*
1124 ** PRAGMA [schema.]synchronous
1125 ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
1126 **
1127 ** Return or set the local value of the synchronous flag. Changing
1128 ** the local value does not make changes to the disk file and the
1129 ** default value will be restored the next time the database is
1130 ** opened.
1131 */
1132 case PragTyp_SYNCHRONOUS: {
1133 if( !zRight ){
1134 returnSingleInt(v, pDb->safety_level-1);
1135 }else{
1136 if( !db->autoCommit ){
1137 sqlite3ErrorMsg(pParse,
1138 "Safety level may not be changed inside a transaction");
1139 }else if( iDb!=1 ){
1140 int iLevel;
1141 if( sqlite3Isdigit(zRight[0]) ){
1142 iLevel = sqlite3Atoi(zRight);
1143 }else{
1144 iLevel = getSafetyLevel(zRight,0,1);
1145 }
1146 iLevel = (iLevel+1) & PAGER_SYNCHRONOUS_MASK;
1147 if( iLevel==0 ) iLevel = 1;
1148 pDb->safety_level = iLevel;
1149 pDb->bSyncSet = 1;
1150 setAllPagerFlags(db);
1151 }
1152 }
1153 break;
1154 }
1155#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
1156
1157#ifndef SQLITE_OMIT_FLAG_PRAGMAS
1158 case PragTyp_FLAG: {
1159 if( zRight==0 ){
1160 setPragmaResultColumnNames(v, pPragma);
1161 returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
1162 }else{
1163 u64 mask = pPragma->iArg; /* Mask of bits to set or clear. */
1164 if( db->autoCommit==0 ){
1165 /* Foreign key support may not be enabled or disabled while not
1166 ** in auto-commit mode. */
1167 mask &= ~(SQLITE_ForeignKeys);
1168 }
1169
1170 if( sqlite3GetBoolean(zRight, 0) ){
1171 if( (mask & SQLITE_WriteSchema)==0
1172 || (db->flags & SQLITE_Defensive)==0
1173 ){
1174 db->flags |= mask;
1175 }
1176 }else{
1177 db->flags &= ~mask;
1178 if( mask==SQLITE_DeferFKs ){
1179 db->nDeferredImmCons = 0;
1180 db->nDeferredCons = 0;
1181 }
1182 if( (mask & SQLITE_WriteSchema)!=0
1183 && sqlite3_stricmp(zRight, "reset")==0
1184 ){
1185 /* IMP: R-60817-01178 If the argument is "RESET" then schema
1186 ** writing is disabled (as with "PRAGMA writable_schema=OFF") and,
1187 ** in addition, the schema is reloaded. */
1188 sqlite3ResetAllSchemasOfConnection(db);
1189 }
1190 }
1191
1192 /* Many of the flag-pragmas modify the code generated by the SQL
1193 ** compiler (eg. count_changes). So add an opcode to expire all
1194 ** compiled SQL statements after modifying a pragma value.
1195 */
1196 sqlite3VdbeAddOp0(v, OP_Expire);
1197 setAllPagerFlags(db);
1198 }
1199 break;
1200 }
1201#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
1202
1203#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
1204 /*
1205 ** PRAGMA table_info(<table>)
1206 **
1207 ** Return a single row for each column of the named table. The columns of
1208 ** the returned data set are:
1209 **
1210 ** cid: Column id (numbered from left to right, starting at 0)
1211 ** name: Column name
1212 ** type: Column declaration type.
1213 ** notnull: True if 'NOT NULL' is part of column declaration
1214 ** dflt_value: The default value for the column, if any.
1215 ** pk: Non-zero for PK fields.
1216 */
1217 case PragTyp_TABLE_INFO: if( zRight ){
1218 Table *pTab;
1219 sqlite3CodeVerifyNamedSchema(pParse, zDb);
1220 pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
1221 if( pTab ){
1222 int i, k;
1223 int nHidden = 0;
1224 Column *pCol;
1225 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
1226 pParse->nMem = 7;
1227 sqlite3ViewGetColumnNames(pParse, pTab);
1228 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
1229 int isHidden = 0;
1230 const Expr *pColExpr;
1231 if( pCol->colFlags & COLFLAG_NOINSERT ){
1232 if( pPragma->iArg==0 ){
1233 nHidden++;
1234 continue;
1235 }
1236 if( pCol->colFlags & COLFLAG_VIRTUAL ){
1237 isHidden = 2; /* GENERATED ALWAYS AS ... VIRTUAL */
1238 }else if( pCol->colFlags & COLFLAG_STORED ){
1239 isHidden = 3; /* GENERATED ALWAYS AS ... STORED */
1240 }else{ assert( pCol->colFlags & COLFLAG_HIDDEN );
1241 isHidden = 1; /* HIDDEN */
1242 }
1243 }
1244 if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
1245 k = 0;
1246 }else if( pPk==0 ){
1247 k = 1;
1248 }else{
1249 for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
1250 }
1251 pColExpr = sqlite3ColumnExpr(pTab,pCol);
1252 assert( pColExpr==0 || pColExpr->op==TK_SPAN || isHidden>=2 );
1253 assert( pColExpr==0 || !ExprHasProperty(pColExpr, EP_IntValue)
1254 || isHidden>=2 );
1255 sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
1256 i-nHidden,
1257 pCol->zCnName,
1258 sqlite3ColumnType(pCol,""),
1259 pCol->notNull ? 1 : 0,
1260 (isHidden>=2 || pColExpr==0) ? 0 : pColExpr->u.zToken,
1261 k,
1262 isHidden);
1263 }
1264 }
1265 }
1266 break;
1267
1268 /*
1269 ** PRAGMA table_list
1270 **
1271 ** Return a single row for each table, virtual table, or view in the
1272 ** entire schema.
1273 **
1274 ** schema: Name of attached database hold this table
1275 ** name: Name of the table itself
1276 ** type: "table", "view", "virtual", "shadow"
1277 ** ncol: Number of columns
1278 ** wr: True for a WITHOUT ROWID table
1279 ** strict: True for a STRICT table
1280 */
1281 case PragTyp_TABLE_LIST: {
1282 int ii;
1283 pParse->nMem = 6;
1284 sqlite3CodeVerifyNamedSchema(pParse, zDb);
1285 for(ii=0; ii<db->nDb; ii++){
1286 HashElem *k;
1287 Hash *pHash;
1288 int initNCol;
1289 if( zDb && sqlite3_stricmp(zDb, db->aDb[ii].zDbSName)!=0 ) continue;
1290
1291 /* Ensure that the Table.nCol field is initialized for all views
1292 ** and virtual tables. Each time we initialize a Table.nCol value
1293 ** for a table, that can potentially disrupt the hash table, so restart
1294 ** the initialization scan.
1295 */
1296 pHash = &db->aDb[ii].pSchema->tblHash;
1297 initNCol = sqliteHashCount(pHash);
1298 while( initNCol-- ){
1299 for(k=sqliteHashFirst(pHash); 1; k=sqliteHashNext(k) ){
1300 Table *pTab;
1301 if( k==0 ){ initNCol = 0; break; }
1302 pTab = sqliteHashData(k);
1303 if( pTab->nCol==0 ){
1304 char *zSql = sqlite3MPrintf(db, "SELECT*FROM\"%w\"", pTab->zName);
1305 if( zSql ){
1306 sqlite3_stmt *pDummy = 0;
1307 (void)sqlite3_prepare_v3(db, zSql, -1, SQLITE_PREPARE_DONT_LOG,
1308 &pDummy, 0);
1309 (void)sqlite3_finalize(pDummy);
1310 sqlite3DbFree(db, zSql);
1311 }
1312 if( db->mallocFailed ){
1313 sqlite3ErrorMsg(db->pParse, "out of memory");
1314 db->pParse->rc = SQLITE_NOMEM_BKPT;
1315 }
1316 pHash = &db->aDb[ii].pSchema->tblHash;
1317 break;
1318 }
1319 }
1320 }
1321
1322 for(k=sqliteHashFirst(pHash); k; k=sqliteHashNext(k) ){
1323 Table *pTab = sqliteHashData(k);
1324 const char *zType;
1325 if( zRight && sqlite3_stricmp(zRight, pTab->zName)!=0 ) continue;
1326 if( IsView(pTab) ){
1327 zType = "view";
1328 }else if( IsVirtual(pTab) ){
1329 zType = "virtual";
1330 }else if( pTab->tabFlags & TF_Shadow ){
1331 zType = "shadow";
1332 }else{
1333 zType = "table";
1334 }
1335 sqlite3VdbeMultiLoad(v, 1, "sssiii",
1336 db->aDb[ii].zDbSName,
1337 sqlite3PreferredTableName(pTab->zName),
1338 zType,
1339 pTab->nCol,
1340 (pTab->tabFlags & TF_WithoutRowid)!=0,
1341 (pTab->tabFlags & TF_Strict)!=0
1342 );
1343 }
1344 }
1345 }
1346 break;
1347
1348#ifdef SQLITE_DEBUG
1349 case PragTyp_STATS: {
1350 Index *pIdx;
1351 HashElem *i;
1352 pParse->nMem = 5;
1353 sqlite3CodeVerifySchema(pParse, iDb);
1354 for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
1355 Table *pTab = sqliteHashData(i);
1356 sqlite3VdbeMultiLoad(v, 1, "ssiii",
1357 sqlite3PreferredTableName(pTab->zName),
1358 0,
1359 pTab->szTabRow,
1360 pTab->nRowLogEst,
1361 pTab->tabFlags);
1362 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1363 sqlite3VdbeMultiLoad(v, 2, "siiiX",
1364 pIdx->zName,
1365 pIdx->szIdxRow,
1366 pIdx->aiRowLogEst[0],
1367 pIdx->hasStat1);
1368 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
1369 }
1370 }
1371 }
1372 break;
1373#endif
1374
1375 case PragTyp_INDEX_INFO: if( zRight ){
1376 Index *pIdx;
1377 Table *pTab;
1378 pIdx = sqlite3FindIndex(db, zRight, zDb);
1379 if( pIdx==0 ){
1380 /* If there is no index named zRight, check to see if there is a
1381 ** WITHOUT ROWID table named zRight, and if there is, show the
1382 ** structure of the PRIMARY KEY index for that table. */
1383 pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
1384 if( pTab && !HasRowid(pTab) ){
1385 pIdx = sqlite3PrimaryKeyIndex(pTab);
1386 }
1387 }
1388 if( pIdx ){
1389 int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
1390 int i;
1391 int mx;
1392 if( pPragma->iArg ){
1393 /* PRAGMA index_xinfo (newer version with more rows and columns) */
1394 mx = pIdx->nColumn;
1395 pParse->nMem = 6;
1396 }else{
1397 /* PRAGMA index_info (legacy version) */
1398 mx = pIdx->nKeyCol;
1399 pParse->nMem = 3;
1400 }
1401 pTab = pIdx->pTable;
1402 sqlite3CodeVerifySchema(pParse, iIdxDb);
1403 assert( pParse->nMem<=pPragma->nPragCName );
1404 for(i=0; i<mx; i++){
1405 i16 cnum = pIdx->aiColumn[i];
1406 sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
1407 cnum<0 ? 0 : pTab->aCol[cnum].zCnName);
1408 if( pPragma->iArg ){
1409 sqlite3VdbeMultiLoad(v, 4, "isiX",
1410 pIdx->aSortOrder[i],
1411 pIdx->azColl[i],
1412 i<pIdx->nKeyCol);
1413 }
1414 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
1415 }
1416 }
1417 }
1418 break;
1419
1420 case PragTyp_INDEX_LIST: if( zRight ){
1421 Index *pIdx;
1422 Table *pTab;
1423 int i;
1424 pTab = sqlite3FindTable(db, zRight, zDb);
1425 if( pTab ){
1426 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1427 pParse->nMem = 5;
1428 sqlite3CodeVerifySchema(pParse, iTabDb);
1429 for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
1430 const char *azOrigin[] = { "c", "u", "pk" };
1431 sqlite3VdbeMultiLoad(v, 1, "isisi",
1432 i,
1433 pIdx->zName,
1434 IsUniqueIndex(pIdx),
1435 azOrigin[pIdx->idxType],
1436 pIdx->pPartIdxWhere!=0);
1437 }
1438 }
1439 }
1440 break;
1441
1442 case PragTyp_DATABASE_LIST: {
1443 int i;
1444 pParse->nMem = 3;
1445 for(i=0; i<db->nDb; i++){
1446 if( db->aDb[i].pBt==0 ) continue;
1447 assert( db->aDb[i].zDbSName!=0 );
1448 sqlite3VdbeMultiLoad(v, 1, "iss",
1449 i,
1450 db->aDb[i].zDbSName,
1451 sqlite3BtreeGetFilename(db->aDb[i].pBt));
1452 }
1453 }
1454 break;
1455
1456 case PragTyp_COLLATION_LIST: {
1457 int i = 0;
1458 HashElem *p;
1459 pParse->nMem = 2;
1460 for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
1461 CollSeq *pColl = (CollSeq *)sqliteHashData(p);
1462 sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
1463 }
1464 }
1465 break;
1466
1467#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
1468 case PragTyp_FUNCTION_LIST: {
1469 int i;
1470 HashElem *j;
1471 FuncDef *p;
1472 int showInternFunc = (db->mDbFlags & DBFLAG_InternalFunc)!=0;
1473 pParse->nMem = 6;
1474 for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
1475 for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
1476 assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
1477 pragmaFunclistLine(v, p, 1, showInternFunc);
1478 }
1479 }
1480 for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
1481 p = (FuncDef*)sqliteHashData(j);
1482 assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
1483 pragmaFunclistLine(v, p, 0, showInternFunc);
1484 }
1485 }
1486 break;
1487
1488#ifndef SQLITE_OMIT_VIRTUALTABLE
1489 case PragTyp_MODULE_LIST: {
1490 HashElem *j;
1491 pParse->nMem = 1;
1492 for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
1493 Module *pMod = (Module*)sqliteHashData(j);
1494 sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
1495 }
1496 }
1497 break;
1498#endif /* SQLITE_OMIT_VIRTUALTABLE */
1499
1500 case PragTyp_PRAGMA_LIST: {
1501 int i;
1502 for(i=0; i<ArraySize(aPragmaName); i++){
1503 sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
1504 }
1505 }
1506 break;
1507#endif /* SQLITE_INTROSPECTION_PRAGMAS */
1508
1509#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
1510
1511#ifndef SQLITE_OMIT_FOREIGN_KEY
1512 case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
1513 FKey *pFK;
1514 Table *pTab;
1515 pTab = sqlite3FindTable(db, zRight, zDb);
1516 if( pTab && IsOrdinaryTable(pTab) ){
1517 pFK = pTab->u.tab.pFKey;
1518 if( pFK ){
1519 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1520 int i = 0;
1521 pParse->nMem = 8;
1522 sqlite3CodeVerifySchema(pParse, iTabDb);
1523 while(pFK){
1524 int j;
1525 for(j=0; j<pFK->nCol; j++){
1526 sqlite3VdbeMultiLoad(v, 1, "iissssss",
1527 i,
1528 j,
1529 pFK->zTo,
1530 pTab->aCol[pFK->aCol[j].iFrom].zCnName,
1531 pFK->aCol[j].zCol,
1532 actionName(pFK->aAction[1]), /* ON UPDATE */
1533 actionName(pFK->aAction[0]), /* ON DELETE */
1534 "NONE");
1535 }
1536 ++i;
1537 pFK = pFK->pNextFrom;
1538 }
1539 }
1540 }
1541 }
1542 break;
1543#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1544
1545#ifndef SQLITE_OMIT_FOREIGN_KEY
1546#ifndef SQLITE_OMIT_TRIGGER
1547 case PragTyp_FOREIGN_KEY_CHECK: {
1548 FKey *pFK; /* A foreign key constraint */
1549 Table *pTab; /* Child table contain "REFERENCES" keyword */
1550 Table *pParent; /* Parent table that child points to */
1551 Index *pIdx; /* Index in the parent table */
1552 int i; /* Loop counter: Foreign key number for pTab */
1553 int j; /* Loop counter: Field of the foreign key */
1554 HashElem *k; /* Loop counter: Next table in schema */
1555 int x; /* result variable */
1556 int regResult; /* 3 registers to hold a result row */
1557 int regRow; /* Registers to hold a row from pTab */
1558 int addrTop; /* Top of a loop checking foreign keys */
1559 int addrOk; /* Jump here if the key is OK */
1560 int *aiCols; /* child to parent column mapping */
1561
1562 regResult = pParse->nMem+1;
1563 pParse->nMem += 4;
1564 regRow = ++pParse->nMem;
1565 k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
1566 while( k ){
1567 if( zRight ){
1568 pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
1569 k = 0;
1570 }else{
1571 pTab = (Table*)sqliteHashData(k);
1572 k = sqliteHashNext(k);
1573 }
1574 if( pTab==0 || !IsOrdinaryTable(pTab) || pTab->u.tab.pFKey==0 ) continue;
1575 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1576 zDb = db->aDb[iDb].zDbSName;
1577 sqlite3CodeVerifySchema(pParse, iDb);
1578 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
1579 sqlite3TouchRegister(pParse, pTab->nCol+regRow);
1580 sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
1581 sqlite3VdbeLoadString(v, regResult, pTab->zName);
1582 assert( IsOrdinaryTable(pTab) );
1583 for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
1584 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
1585 if( pParent==0 ) continue;
1586 pIdx = 0;
1587 sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
1588 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
1589 if( x==0 ){
1590 if( pIdx==0 ){
1591 sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
1592 }else{
1593 sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
1594 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1595 }
1596 }else{
1597 k = 0;
1598 break;
1599 }
1600 }
1601 assert( pParse->nErr>0 || pFK==0 );
1602 if( pFK ) break;
1603 if( pParse->nTab<i ) pParse->nTab = i;
1604 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
1605 assert( IsOrdinaryTable(pTab) );
1606 for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
1607 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
1608 pIdx = 0;
1609 aiCols = 0;
1610 if( pParent ){
1611 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
1612 assert( x==0 || db->mallocFailed );
1613 }
1614 addrOk = sqlite3VdbeMakeLabel(pParse);
1615
1616 /* Generate code to read the child key values into registers
1617 ** regRow..regRow+n. If any of the child key values are NULL, this
1618 ** row cannot cause an FK violation. Jump directly to addrOk in
1619 ** this case. */
1620 sqlite3TouchRegister(pParse, regRow + pFK->nCol);
1621 for(j=0; j<pFK->nCol; j++){
1622 int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
1623 sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
1624 sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
1625 }
1626
1627 /* Generate code to query the parent index for a matching parent
1628 ** key. If a match is found, jump to addrOk. */
1629 if( pIdx ){
1630 sqlite3VdbeAddOp4(v, OP_Affinity, regRow, pFK->nCol, 0,
1631 sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
1632 sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regRow, pFK->nCol);
1633 VdbeCoverage(v);
1634 }else if( pParent ){
1635 int jmp = sqlite3VdbeCurrentAddr(v)+2;
1636 sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
1637 sqlite3VdbeGoto(v, addrOk);
1638 assert( pFK->nCol==1 || db->mallocFailed );
1639 }
1640
1641 /* Generate code to report an FK violation to the caller. */
1642 if( HasRowid(pTab) ){
1643 sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
1644 }else{
1645 sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
1646 }
1647 sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
1648 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
1649 sqlite3VdbeResolveLabel(v, addrOk);
1650 sqlite3DbFree(db, aiCols);
1651 }
1652 sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
1653 sqlite3VdbeJumpHere(v, addrTop);
1654 }
1655 }
1656 break;
1657#endif /* !defined(SQLITE_OMIT_TRIGGER) */
1658#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1659
1660#ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA
1661 /* Reinstall the LIKE and GLOB functions. The variant of LIKE
1662 ** used will be case sensitive or not depending on the RHS.
1663 */
1664 case PragTyp_CASE_SENSITIVE_LIKE: {
1665 if( zRight ){
1666 sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
1667 }
1668 }
1669 break;
1670#endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */
1671
1672#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
1673# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
1674#endif
1675
1676#ifndef SQLITE_OMIT_INTEGRITY_CHECK
1677 /* PRAGMA integrity_check
1678 ** PRAGMA integrity_check(N)
1679 ** PRAGMA quick_check
1680 ** PRAGMA quick_check(N)
1681 **
1682 ** Verify the integrity of the database.
1683 **
1684 ** The "quick_check" is reduced version of
1685 ** integrity_check designed to detect most database corruption
1686 ** without the overhead of cross-checking indexes. Quick_check
1687 ** is linear time whereas integrity_check is O(NlogN).
1688 **
1689 ** The maximum number of errors is 100 by default. A different default
1690 ** can be specified using a numeric parameter N.
1691 **
1692 ** Or, the parameter N can be the name of a table. In that case, only
1693 ** the one table named is verified. The freelist is only verified if
1694 ** the named table is "sqlite_schema" (or one of its aliases).
1695 **
1696 ** All schemas are checked by default. To check just a single
1697 ** schema, use the form:
1698 **
1699 ** PRAGMA schema.integrity_check;
1700 */
1701 case PragTyp_INTEGRITY_CHECK: {
1702 int i, j, addr, mxErr;
1703 Table *pObjTab = 0; /* Check only this one table, if not NULL */
1704
1705 int isQuick = (sqlite3Tolower(zLeft[0])=='q');
1706
1707 /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
1708 ** then iDb is set to the index of the database identified by <db>.
1709 ** In this case, the integrity of database iDb only is verified by
1710 ** the VDBE created below.
1711 **
1712 ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
1713 ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
1714 ** to -1 here, to indicate that the VDBE should verify the integrity
1715 ** of all attached databases. */
1716 assert( iDb>=0 );
1717 assert( iDb==0 || pId2->z );
1718 if( pId2->z==0 ) iDb = -1;
1719
1720 /* Initialize the VDBE program */
1721 pParse->nMem = 6;
1722
1723 /* Set the maximum error count */
1724 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
1725 if( zRight ){
1726 if( sqlite3GetInt32(pValue->z, &mxErr) ){
1727 if( mxErr<=0 ){
1728 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
1729 }
1730 }else{
1731 pObjTab = sqlite3LocateTable(pParse, 0, zRight,
1732 iDb>=0 ? db->aDb[iDb].zDbSName : 0);
1733 }
1734 }
1735 sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
1736
1737 /* Do an integrity check on each database file */
1738 for(i=0; i<db->nDb; i++){
1739 HashElem *x; /* For looping over tables in the schema */
1740 Hash *pTbls; /* Set of all tables in the schema */
1741 int *aRoot; /* Array of root page numbers of all btrees */
1742 int cnt = 0; /* Number of entries in aRoot[] */
1743
1744 if( OMIT_TEMPDB && i==1 ) continue;
1745 if( iDb>=0 && i!=iDb ) continue;
1746
1747 sqlite3CodeVerifySchema(pParse, i);
1748 pParse->okConstFactor = 0; /* tag-20230327-1 */
1749
1750 /* Do an integrity check of the B-Tree
1751 **
1752 ** Begin by finding the root pages numbers
1753 ** for all tables and indices in the database.
1754 */
1755 assert( sqlite3SchemaMutexHeld(db, i, 0) );
1756 pTbls = &db->aDb[i].pSchema->tblHash;
1757 for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
1758 Table *pTab = sqliteHashData(x); /* Current table */
1759 Index *pIdx; /* An index on pTab */
1760 if( tableSkipIntegrityCheck(pTab,pObjTab) ) continue;
1761 if( HasRowid(pTab) ) cnt++;
1762 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ cnt++; }
1763 }
1764 if( cnt==0 ) continue;
1765 if( pObjTab ) cnt++;
1766 aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
1767 if( aRoot==0 ) break;
1768 cnt = 0;
1769 if( pObjTab ) aRoot[++cnt] = 0;
1770 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
1771 Table *pTab = sqliteHashData(x);
1772 Index *pIdx;
1773 if( tableSkipIntegrityCheck(pTab,pObjTab) ) continue;
1774 if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
1775 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1776 aRoot[++cnt] = pIdx->tnum;
1777 }
1778 }
1779 aRoot[0] = cnt;
1780
1781 /* Make sure sufficient number of registers have been allocated */
1782 sqlite3TouchRegister(pParse, 8+cnt);
1783 sqlite3VdbeAddOp3(v, OP_Null, 0, 8, 8+cnt);
1784 sqlite3ClearTempRegCache(pParse);
1785
1786 /* Do the b-tree integrity checks */
1787 sqlite3VdbeAddOp4(v, OP_IntegrityCk, 1, cnt, 8, (char*)aRoot,P4_INTARRAY);
1788 sqlite3VdbeChangeP5(v, (u16)i);
1789 addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
1790 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
1791 sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
1792 P4_DYNAMIC);
1793 sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
1794 integrityCheckResultRow(v);
1795 sqlite3VdbeJumpHere(v, addr);
1796
1797 /* Check that the indexes all have the right number of rows */
1798 cnt = pObjTab ? 1 : 0;
1799 sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
1800 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
1801 int iTab = 0;
1802 Table *pTab = sqliteHashData(x);
1803 Index *pIdx;
1804 if( tableSkipIntegrityCheck(pTab,pObjTab) ) continue;
1805 if( HasRowid(pTab) ){
1806 iTab = cnt++;
1807 }else{
1808 iTab = cnt;
1809 for(pIdx=pTab->pIndex; ALWAYS(pIdx); pIdx=pIdx->pNext){
1810 if( IsPrimaryKeyIndex(pIdx) ) break;
1811 iTab++;
1812 }
1813 }
1814 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1815 if( pIdx->pPartIdxWhere==0 ){
1816 addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+cnt, 0, 8+iTab);
1817 VdbeCoverageNeverNull(v);
1818 sqlite3VdbeLoadString(v, 4, pIdx->zName);
1819 sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
1820 integrityCheckResultRow(v);
1821 sqlite3VdbeJumpHere(v, addr);
1822 }
1823 cnt++;
1824 }
1825 }
1826
1827 /* Make sure all the indices are constructed correctly.
1828 */
1829 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
1830 Table *pTab = sqliteHashData(x);
1831 Index *pIdx, *pPk;
1832 Index *pPrior = 0; /* Previous index */
1833 int loopTop;
1834 int iDataCur, iIdxCur;
1835 int r1 = -1;
1836 int bStrict; /* True for a STRICT table */
1837 int r2; /* Previous key for WITHOUT ROWID tables */
1838 int mxCol; /* Maximum non-virtual column number */
1839
1840 if( tableSkipIntegrityCheck(pTab,pObjTab) ) continue;
1841 if( !IsOrdinaryTable(pTab) ) continue;
1842 if( isQuick || HasRowid(pTab) ){
1843 pPk = 0;
1844 r2 = 0;
1845 }else{
1846 pPk = sqlite3PrimaryKeyIndex(pTab);
1847 r2 = sqlite3GetTempRange(pParse, pPk->nKeyCol);
1848 sqlite3VdbeAddOp3(v, OP_Null, 1, r2, r2+pPk->nKeyCol-1);
1849 }
1850 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
1851 1, 0, &iDataCur, &iIdxCur);
1852 /* reg[7] counts the number of entries in the table.
1853 */
1854 sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
1855 assert( sqlite3NoTempsInRange(pParse,1,7) );
1856 sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
1857 loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
1858
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.
1863 */
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++;
1869 }
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;
1876 }
1877 if( mxCol>=0 ){
1878 sqlite3VdbeAddOp3(v, OP_Column, iDataCur, mxCol, 3);
1879 sqlite3VdbeTypeofColumn(v, 3);
1880 }
1881
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);
1899 }
1900 }
1901 }
1902 /* Verify datatypes for all columns:
1903 **
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.
1910 */
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) */
1919
1920 if( j==pTab->iPKey ) continue;
1921 if( bStrict ){
1922 doTypeCheck = pCol->eCType>COLTYPE_ANY;
1923 }else{
1924 doTypeCheck = pCol->affinity>SQLITE_AFF_BLOB;
1925 }
1926 if( pCol->notNull==0 && !doTypeCheck ) continue;
1927
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, sqlite3ColumnExprAuth(pTab,pCol,pParse),
1938 ENC(db), pCol->affinity, &pDfltValue);
1939 if( pDfltValue ){
1940 p4 = sqlite3_value_type(pDfltValue);
1941 sqlite3ValueFree(pDfltValue);
1942 }
1943 }
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);
1951 }
1952 }
1953
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);
1974 }
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 */
1984 }
1985 }
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 */
1995 };
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);
2021 }
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);
2029 }
2030 sqlite3VdbeResolveLabel(v, labelError);
2031 integrityCheckResultRow(v);
2032 sqlite3VdbeResolveLabel(v, labelOk);
2033 }
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);
2045 }
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);
2055 }
2056 sqlite3ExprListDelete(db, pCheck);
2057 }
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 /* Verify that an index entry exists for the current table row */
2069 sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
2070 pIdx->nColumn); VdbeCoverage(v);
2071 jmp2 = sqlite3VdbeAddOp3(v, OP_IFindKey, iIdxCur+j, ckUniq, r1);
2072 VdbeCoverage(v);
2073 sqlite3VdbeChangeP4(v, -1, (const char*)pIdx, P4_INDEX);
2074 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
2075 sqlite3MPrintf(db, "index %s stores an imprecise floating-point "
2076 "value for row ", pIdx->zName),
2077 P4_DYNAMIC);
2078 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
2079 integrityCheckResultRow(v);
2080 sqlite3VdbeAddOp2(v, OP_Goto, 0, ckUniq);
2081
2082 sqlite3VdbeJumpHere(v, jmp2);
2083 sqlite3VdbeLoadString(v, 3, "row ");
2084 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
2085 sqlite3VdbeLoadString(v, 4, " missing from index ");
2086 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
2087 jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
2088 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
2089 jmp4 = integrityCheckResultRow(v);
2090 sqlite3VdbeResolveLabel(v, ckUniq);
2091
2092 /* The OP_IdxRowid opcode is an optimized version of OP_Column
2093 ** that extracts the rowid off the end of the index record.
2094 ** But it only works correctly if index record does not have
2095 ** any extra bytes at the end. Verify that this is the case. */
2096 if( HasRowid(pTab) ){
2097 int jmp7;
2098 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur+j, 3);
2099 jmp7 = sqlite3VdbeAddOp3(v, OP_Eq, 3, 0, r1+pIdx->nColumn-1);
2100 VdbeCoverageNeverNull(v);
2101 sqlite3VdbeLoadString(v, 3,
2102 "rowid not at end-of-record for row ");
2103 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
2104 sqlite3VdbeLoadString(v, 4, " of index ");
2105 sqlite3VdbeGoto(v, jmp5-1);
2106 sqlite3VdbeJumpHere(v, jmp7);
2107 }
2108
2109 /* Any indexed columns with non-BINARY collations must still hold
2110 ** the exact same text value as the table. */
2111 label6 = 0;
2112 for(kk=0; kk<pIdx->nKeyCol; kk++){
2113 if( pIdx->azColl[kk]==sqlite3StrBINARY ) continue;
2114 if( label6==0 ) label6 = sqlite3VdbeMakeLabel(pParse);
2115 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur+j, kk, 3);
2116 sqlite3VdbeAddOp3(v, OP_Ne, 3, label6, r1+kk); VdbeCoverage(v);
2117 }
2118 if( label6 ){
2119 int jmp6 = sqlite3VdbeAddOp0(v, OP_Goto);
2120 sqlite3VdbeResolveLabel(v, label6);
2121 sqlite3VdbeLoadString(v, 3, "row ");
2122 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
2123 sqlite3VdbeLoadString(v, 4, " values differ from index ");
2124 sqlite3VdbeGoto(v, jmp5-1);
2125 sqlite3VdbeJumpHere(v, jmp6);
2126 }
2127
2128 /* For UNIQUE indexes, verify that only one entry exists with the
2129 ** current key. The entry is unique if (1) any column is NULL
2130 ** or (2) the next entry has a different key */
2131 if( IsUniqueIndex(pIdx) ){
2132 int uniqOk = sqlite3VdbeMakeLabel(pParse);
2133 int jmp6;
2134 for(kk=0; kk<pIdx->nKeyCol; kk++){
2135 int iCol = pIdx->aiColumn[kk];
2136 assert( iCol!=XN_ROWID && iCol<pTab->nCol );
2137 if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
2138 sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
2139 VdbeCoverage(v);
2140 }
2141 jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
2142 sqlite3VdbeGoto(v, uniqOk);
2143 sqlite3VdbeJumpHere(v, jmp6);
2144 sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
2145 pIdx->nKeyCol); VdbeCoverage(v);
2146 sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
2147 sqlite3VdbeGoto(v, jmp5);
2148 sqlite3VdbeResolveLabel(v, uniqOk);
2149 }
2150 sqlite3VdbeJumpHere(v, jmp4);
2151 sqlite3ResolvePartIdxLabel(pParse, jmp3);
2152 }
2153 }
2154 sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
2155 sqlite3VdbeJumpHere(v, loopTop-1);
2156 if( pPk ){
2157 assert( !isQuick );
2158 sqlite3ReleaseTempRange(pParse, r2, pPk->nKeyCol);
2159 }
2160 }
2161
2162#ifndef SQLITE_OMIT_VIRTUALTABLE
2163 /* Second pass to invoke the xIntegrity method on all virtual
2164 ** tables.
2165 */
2166 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
2167 Table *pTab = sqliteHashData(x);
2168 sqlite3_vtab *pVTab;
2169 int a1;
2170 if( tableSkipIntegrityCheck(pTab,pObjTab) ) continue;
2171 if( IsOrdinaryTable(pTab) ) continue;
2172 if( !IsVirtual(pTab) ) continue;
2173 if( pTab->nCol<=0 ){
2174 const char *zMod = pTab->u.vtab.azArg[0];
2175 if( sqlite3HashFind(&db->aModule, zMod)==0 ) continue;
2176 }
2177 sqlite3ViewGetColumnNames(pParse, pTab);
2178 if( pTab->u.vtab.p==0 ) continue;
2179 pVTab = pTab->u.vtab.p->pVtab;
2180 if( NEVER(pVTab==0) ) continue;
2181 if( NEVER(pVTab->pModule==0) ) continue;
2182 if( pVTab->pModule->iVersion<4 ) continue;
2183 if( pVTab->pModule->xIntegrity==0 ) continue;
2184 sqlite3VdbeAddOp3(v, OP_VCheck, i, 3, isQuick);
2185 pTab->nTabRef++;
2186 sqlite3VdbeAppendP4(v, pTab, P4_TABLEREF);
2187 a1 = sqlite3VdbeAddOp1(v, OP_IsNull, 3); VdbeCoverage(v);
2188 integrityCheckResultRow(v);
2189 sqlite3VdbeJumpHere(v, a1);
2190 continue;
2191 }
2192#endif
2193 }
2194 {
2195 static const int iLn = VDBE_OFFSET_LINENO(2);
2196 static const VdbeOpList endCode[] = {
2197 { OP_AddImm, 1, 0, 0}, /* 0 */
2198 { OP_IfNotZero, 1, 4, 0}, /* 1 */
2199 { OP_String8, 0, 3, 0}, /* 2 */
2200 { OP_ResultRow, 3, 1, 0}, /* 3 */
2201 { OP_Halt, 0, 0, 0}, /* 4 */
2202 { OP_String8, 0, 3, 0}, /* 5 */
2203 { OP_Goto, 0, 3, 0}, /* 6 */
2204 };
2205 VdbeOp *aOp;
2206
2207 aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
2208 if( aOp ){
2209 aOp[0].p2 = 1-mxErr;
2210 aOp[2].p4type = P4_STATIC;
2211 aOp[2].p4.z = "ok";
2212 aOp[5].p4type = P4_STATIC;
2213 aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
2214 }
2215 sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
2216 }
2217 }
2218 break;
2219#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
2220
2221#ifndef SQLITE_OMIT_UTF16
2222 /*
2223 ** PRAGMA encoding
2224 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
2225 **
2226 ** In its first form, this pragma returns the encoding of the main
2227 ** database. If the database is not initialized, it is initialized now.
2228 **
2229 ** The second form of this pragma is a no-op if the main database file
2230 ** has not already been initialized. In this case it sets the default
2231 ** encoding that will be used for the main database file if a new file
2232 ** is created. If an existing main database file is opened, then the
2233 ** default text encoding for the existing database is used.
2234 **
2235 ** In all cases new databases created using the ATTACH command are
2236 ** created to use the same default text encoding as the main database. If
2237 ** the main database has not been initialized and/or created when ATTACH
2238 ** is executed, this is done before the ATTACH operation.
2239 **
2240 ** In the second form this pragma sets the text encoding to be used in
2241 ** new database files created using this database handle. It is only
2242 ** useful if invoked immediately after the main database i
2243 */
2244 case PragTyp_ENCODING: {
2245 static const struct EncName {
2246 char *zName;
2247 u8 enc;
2248 } encnames[] = {
2249 { "UTF8", SQLITE_UTF8 },
2250 { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
2251 { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
2252 { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
2253 { "UTF16le", SQLITE_UTF16LE },
2254 { "UTF16be", SQLITE_UTF16BE },
2255 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
2256 { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
2257 { 0, 0 }
2258 };
2259 const struct EncName *pEnc;
2260 if( !zRight ){ /* "PRAGMA encoding" */
2261 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
2262 assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
2263 assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
2264 assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
2265 returnSingleText(v, encnames[ENC(pParse->db)].zName);
2266 }else{ /* "PRAGMA encoding = XXX" */
2267 /* Only change the value of sqlite.enc if the database handle is not
2268 ** initialized. If the main database exists, the new sqlite.enc value
2269 ** will be overwritten when the schema is next loaded. If it does not
2270 ** already exists, it will be created to use the new encoding value.
2271 */
2272 if( (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
2273 for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
2274 if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
2275 u8 enc = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
2276 SCHEMA_ENC(db) = enc;
2277 sqlite3SetTextEncoding(db, enc);
2278 break;
2279 }
2280 }
2281 if( !pEnc->zName ){
2282 sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
2283 }
2284 }
2285 }
2286 }
2287 break;
2288#endif /* SQLITE_OMIT_UTF16 */
2289
2290#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
2291 /*
2292 ** PRAGMA [schema.]schema_version
2293 ** PRAGMA [schema.]schema_version = <integer>
2294 **
2295 ** PRAGMA [schema.]user_version
2296 ** PRAGMA [schema.]user_version = <integer>
2297 **
2298 ** PRAGMA [schema.]freelist_count
2299 **
2300 ** PRAGMA [schema.]data_version
2301 **
2302 ** PRAGMA [schema.]application_id
2303 ** PRAGMA [schema.]application_id = <integer>
2304 **
2305 ** The pragma's schema_version and user_version are used to set or get
2306 ** the value of the schema-version and user-version, respectively. Both
2307 ** the schema-version and the user-version are 32-bit signed integers
2308 ** stored in the database header.
2309 **
2310 ** The schema-cookie is usually only manipulated internally by SQLite. It
2311 ** is incremented by SQLite whenever the database schema is modified (by
2312 ** creating or dropping a table or index). The schema version is used by
2313 ** SQLite each time a query is executed to ensure that the internal cache
2314 ** of the schema used when compiling the SQL query matches the schema of
2315 ** the database against which the compiled query is actually executed.
2316 ** Subverting this mechanism by using "PRAGMA schema_version" to modify
2317 ** the schema-version is potentially dangerous and may lead to program
2318 ** crashes or database corruption. Use with caution!
2319 **
2320 ** The user-version is not used internally by SQLite. It may be used by
2321 ** applications for any purpose.
2322 */
2323 case PragTyp_HEADER_VALUE: {
2324 int iCookie = pPragma->iArg; /* Which cookie to read or write */
2325 sqlite3VdbeUsesBtree(v, iDb);
2326 if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
2327 /* Write the specified cookie value */
2328 static const VdbeOpList setCookie[] = {
2329 { OP_Transaction, 0, 1, 0}, /* 0 */
2330 { OP_SetCookie, 0, 0, 0}, /* 1 */
2331 };
2332 VdbeOp *aOp;
2333 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
2334 aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
2335 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
2336 aOp[0].p1 = iDb;
2337 aOp[1].p1 = iDb;
2338 aOp[1].p2 = iCookie;
2339 aOp[1].p3 = sqlite3Atoi(zRight);
2340 aOp[1].p5 = 1;
2341 if( iCookie==BTREE_SCHEMA_VERSION && (db->flags & SQLITE_Defensive)!=0 ){
2342 /* Do not allow the use of PRAGMA schema_version=VALUE in defensive
2343 ** mode. Change the OP_SetCookie opcode into a no-op. */
2344 aOp[1].opcode = OP_Noop;
2345 }
2346 }else{
2347 /* Read the specified cookie value */
2348 static const VdbeOpList readCookie[] = {
2349 { OP_Transaction, 0, 0, 0}, /* 0 */
2350 { OP_ReadCookie, 0, 1, 0}, /* 1 */
2351 { OP_ResultRow, 1, 1, 0}
2352 };
2353 VdbeOp *aOp;
2354 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
2355 aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
2356 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
2357 aOp[0].p1 = iDb;
2358 aOp[1].p1 = iDb;
2359 aOp[1].p3 = iCookie;
2360 sqlite3VdbeReusable(v);
2361 }
2362 }
2363 break;
2364#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
2365
2366#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
2367 /*
2368 ** PRAGMA compile_options
2369 **
2370 ** Return the names of all compile-time options used in this build,
2371 ** one option per row.
2372 */
2373 case PragTyp_COMPILE_OPTIONS: {
2374 int i = 0;
2375 const char *zOpt;
2376 pParse->nMem = 1;
2377 while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
2378 sqlite3VdbeLoadString(v, 1, zOpt);
2379 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
2380 }
2381 sqlite3VdbeReusable(v);
2382 }
2383 break;
2384#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
2385
2386#ifndef SQLITE_OMIT_WAL
2387 /*
2388 ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
2389 **
2390 ** Checkpoint the database.
2391 */
2392 case PragTyp_WAL_CHECKPOINT: {
2393 int iBt = (pId2->z?iDb:SQLITE_MAX_DB);
2394 int eMode = SQLITE_CHECKPOINT_PASSIVE;
2395 if( zRight ){
2396 if( sqlite3StrICmp(zRight, "full")==0 ){
2397 eMode = SQLITE_CHECKPOINT_FULL;
2398 }else if( sqlite3StrICmp(zRight, "restart")==0 ){
2399 eMode = SQLITE_CHECKPOINT_RESTART;
2400 }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
2401 eMode = SQLITE_CHECKPOINT_TRUNCATE;
2402 }else if( sqlite3StrICmp(zRight, "noop")==0 ){
2403 eMode = SQLITE_CHECKPOINT_NOOP;
2404 }
2405 }
2406 pParse->nMem = 3;
2407 sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
2408 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
2409 }
2410 break;
2411
2412 /*
2413 ** PRAGMA wal_autocheckpoint
2414 ** PRAGMA wal_autocheckpoint = N
2415 **
2416 ** Configure a database connection to automatically checkpoint a database
2417 ** after accumulating N frames in the log. Or query for the current value
2418 ** of N.
2419 */
2420 case PragTyp_WAL_AUTOCHECKPOINT: {
2421 if( zRight ){
2422 sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
2423 }
2424 returnSingleInt(v,
2425 db->xWalCallback==sqlite3WalDefaultHook ?
2426 SQLITE_PTR_TO_INT(db->pWalArg) : 0);
2427 }
2428 break;
2429#endif
2430
2431 /*
2432 ** PRAGMA shrink_memory
2433 **
2434 ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
2435 ** connection on which it is invoked to free up as much memory as it
2436 ** can, by calling sqlite3_db_release_memory().
2437 */
2438 case PragTyp_SHRINK_MEMORY: {
2439 sqlite3_db_release_memory(db);
2440 break;
2441 }
2442
2443 /*
2444 ** PRAGMA optimize
2445 ** PRAGMA optimize(MASK)
2446 ** PRAGMA schema.optimize
2447 ** PRAGMA schema.optimize(MASK)
2448 **
2449 ** Attempt to optimize the database. All schemas are optimized in the first
2450 ** two forms, and only the specified schema is optimized in the latter two.
2451 **
2452 ** The details of optimizations performed by this pragma are expected
2453 ** to change and improve over time. Applications should anticipate that
2454 ** this pragma will perform new optimizations in future releases.
2455 **
2456 ** The optional argument is a bitmask of optimizations to perform:
2457 **
2458 ** 0x00001 Debugging mode. Do not actually perform any optimizations
2459 ** but instead return one line of text for each optimization
2460 ** that would have been done. Off by default.
2461 **
2462 ** 0x00002 Run ANALYZE on tables that might benefit. On by default.
2463 ** See below for additional information.
2464 **
2465 ** 0x00010 Run all ANALYZE operations using an analysis_limit that
2466 ** is the lessor of the current analysis_limit and the
2467 ** SQLITE_DEFAULT_OPTIMIZE_LIMIT compile-time option.
2468 ** The default value of SQLITE_DEFAULT_OPTIMIZE_LIMIT is
2469 ** currently (2024-02-19) set to 2000, which is such that
2470 ** the worst case run-time for PRAGMA optimize on a 100MB
2471 ** database will usually be less than 100 milliseconds on
2472 ** a RaspberryPI-4 class machine. On by default.
2473 **
2474 ** 0x10000 Look at tables to see if they need to be reanalyzed
2475 ** due to growth or shrinkage even if they have not been
2476 ** queried during the current connection. Off by default.
2477 **
2478 ** The default MASK is and always shall be 0x0fffe. In the current
2479 ** implementation, the default mask only covers the 0x00002 optimization,
2480 ** though additional optimizations that are covered by 0x0fffe might be
2481 ** added in the future. Optimizations that are off by default and must
2482 ** be explicitly requested have masks of 0x10000 or greater.
2483 **
2484 ** DETERMINATION OF WHEN TO RUN ANALYZE
2485 **
2486 ** In the current implementation, a table is analyzed if only if all of
2487 ** the following are true:
2488 **
2489 ** (1) MASK bit 0x00002 is set.
2490 **
2491 ** (2) The table is an ordinary table, not a virtual table or view.
2492 **
2493 ** (3) The table name does not begin with "sqlite_".
2494 **
2495 ** (4) One or more of the following is true:
2496 ** (4a) The 0x10000 MASK bit is set.
2497 ** (4b) One or more indexes on the table lacks an entry
2498 ** in the sqlite_stat1 table.
2499 ** (4c) The query planner used sqlite_stat1-style statistics for one
2500 ** or more indexes of the table at some point during the lifetime
2501 ** of the current connection.
2502 **
2503 ** (5) One or more of the following is true:
2504 ** (5a) One or more indexes on the table lacks an entry
2505 ** in the sqlite_stat1 table. (Same as 4a)
2506 ** (5b) The number of rows in the table has increased or decreased by
2507 ** 10-fold. In other words, the current size of the table is
2508 ** 10 times larger than the size in sqlite_stat1 or else the
2509 ** current size is less than 1/10th the size in sqlite_stat1.
2510 **
2511 ** The rules for when tables are analyzed are likely to change in
2512 ** future releases. Future versions of SQLite might accept a string
2513 ** literal argument to this pragma that contains a mnemonic description
2514 ** of the options rather than a bitmap.
2515 */
2516 case PragTyp_OPTIMIZE: {
2517 int iDbLast; /* Loop termination point for the schema loop */
2518 int iTabCur; /* Cursor for a table whose size needs checking */
2519 HashElem *k; /* Loop over tables of a schema */
2520 Schema *pSchema; /* The current schema */
2521 Table *pTab; /* A table in the schema */
2522 Index *pIdx; /* An index of the table */
2523 LogEst szThreshold; /* Size threshold above which reanalysis needed */
2524 char *zSubSql; /* SQL statement for the OP_SqlExec opcode */
2525 u32 opMask; /* Mask of operations to perform */
2526 int nLimit; /* Analysis limit to use */
2527 int nCheck = 0; /* Number of tables to be optimized */
2528 int nBtree = 0; /* Number of btrees to scan */
2529 int nIndex; /* Number of indexes on the current table */
2530
2531 if( zRight ){
2532 opMask = (u32)sqlite3Atoi(zRight);
2533 if( (opMask & 0x02)==0 ) break;
2534 }else{
2535 opMask = 0xfffe;
2536 }
2537 if( (opMask & 0x10)==0 ){
2538 nLimit = 0;
2539 }else if( db->nAnalysisLimit>0
2540 && db->nAnalysisLimit<SQLITE_DEFAULT_OPTIMIZE_LIMIT ){
2541 nLimit = 0;
2542 }else{
2543 nLimit = SQLITE_DEFAULT_OPTIMIZE_LIMIT;
2544 }
2545 iTabCur = pParse->nTab++;
2546 for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
2547 if( iDb==1 ) continue;
2548 sqlite3CodeVerifySchema(pParse, iDb);
2549 pSchema = db->aDb[iDb].pSchema;
2550 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
2551 pTab = (Table*)sqliteHashData(k);
2552
2553 /* This only works for ordinary tables */
2554 if( !IsOrdinaryTable(pTab) ) continue;
2555
2556 /* Do not scan system tables */
2557 if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) ) continue;
2558
2559 /* Find the size of the table as last recorded in sqlite_stat1.
2560 ** If any index is unanalyzed, then the threshold is -1 to
2561 ** indicate a new, unanalyzed index
2562 */
2563 szThreshold = pTab->nRowLogEst;
2564 nIndex = 0;
2565 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2566 nIndex++;
2567 if( !pIdx->hasStat1 ){
2568 szThreshold = -1; /* Always analyze if any index lacks statistics */
2569 }
2570 }
2571
2572 /* If table pTab has not been used in a way that would benefit from
2573 ** having analysis statistics during the current session, then skip it,
2574 ** unless the 0x10000 MASK bit is set. */
2575 if( (pTab->tabFlags & TF_MaybeReanalyze)!=0 ){
2576 /* Check for size change if stat1 has been used for a query */
2577 }else if( opMask & 0x10000 ){
2578 /* Check for size change if 0x10000 is set */
2579 }else if( pTab->pIndex!=0 && szThreshold<0 ){
2580 /* Do analysis if unanalyzed indexes exists */
2581 }else{
2582 /* Otherwise, we can skip this table */
2583 continue;
2584 }
2585
2586 nCheck++;
2587 if( nCheck==2 ){
2588 /* If ANALYZE might be invoked two or more times, hold a write
2589 ** transaction for efficiency */
2590 sqlite3BeginWriteOperation(pParse, 0, iDb);
2591 }
2592 nBtree += nIndex+1;
2593
2594 /* Reanalyze if the table is 10 times larger or smaller than
2595 ** the last analysis. Unconditional reanalysis if there are
2596 ** unanalyzed indexes. */
2597 sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
2598 if( szThreshold>=0 ){
2599 const LogEst iRange = 33; /* 10x size change */
2600 sqlite3VdbeAddOp4Int(v, OP_IfSizeBetween, iTabCur,
2601 sqlite3VdbeCurrentAddr(v)+2+(opMask&1),
2602 szThreshold>=iRange ? szThreshold-iRange : -1,
2603 szThreshold+iRange);
2604 VdbeCoverage(v);
2605 }else{
2606 sqlite3VdbeAddOp2(v, OP_Rewind, iTabCur,
2607 sqlite3VdbeCurrentAddr(v)+2+(opMask&1));
2608 VdbeCoverage(v);
2609 }
2610 zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
2611 db->aDb[iDb].zDbSName, pTab->zName);
2612 if( opMask & 0x01 ){
2613 int r1 = sqlite3GetTempReg(pParse);
2614 sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
2615 sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
2616 }else{
2617 sqlite3VdbeAddOp4(v, OP_SqlExec, nLimit ? 0x02 : 00, nLimit, 0,
2618 zSubSql, P4_DYNAMIC);
2619 }
2620 }
2621 }
2622 sqlite3VdbeAddOp0(v, OP_Expire);
2623
2624 /* In a schema with a large number of tables and indexes, scale back
2625 ** the analysis_limit to avoid excess run-time in the worst case.
2626 */
2627 if( !db->mallocFailed && nLimit>0 && nBtree>100 ){
2628 int iAddr, iEnd;
2629 VdbeOp *aOp;
2630 nLimit = 100*nLimit/nBtree;
2631 if( nLimit<100 ) nLimit = 100;
2632 aOp = sqlite3VdbeGetOp(v, 0);
2633 iEnd = sqlite3VdbeCurrentAddr(v);
2634 for(iAddr=0; iAddr<iEnd; iAddr++){
2635 if( aOp[iAddr].opcode==OP_SqlExec ) aOp[iAddr].p2 = nLimit;
2636 }
2637 }
2638 break;
2639 }
2640
2641 /*
2642 ** PRAGMA busy_timeout
2643 ** PRAGMA busy_timeout = N
2644 **
2645 ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
2646 ** if one is set. If no busy handler or a different busy handler is set
2647 ** then 0 is returned. Setting the busy_timeout to 0 or negative
2648 ** disables the timeout.
2649 */
2650 /*case PragTyp_BUSY_TIMEOUT*/ default: {
2651 int n = 0;
2652 assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
2653 if( zRight && sqlite3GetInt32(zRight,&n) ){
2654 sqlite3_busy_timeout(db, n);
2655 }
2656 returnSingleInt(v, db->busyTimeout);
2657 break;
2658 }
2659
2660 /*
2661 ** PRAGMA soft_heap_limit
2662 ** PRAGMA soft_heap_limit = N
2663 **
2664 ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
2665 ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
2666 ** specified and is a non-negative integer.
2667 ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
2668 ** returns the same integer that would be returned by the
2669 ** sqlite3_soft_heap_limit64(-1) C-language function.
2670 */
2671 case PragTyp_SOFT_HEAP_LIMIT: {
2672 sqlite3_int64 N;
2673 if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
2674 sqlite3_soft_heap_limit64(N);
2675 }
2676 returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
2677 break;
2678 }
2679
2680 /*
2681 ** PRAGMA hard_heap_limit
2682 ** PRAGMA hard_heap_limit = N
2683 **
2684 ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap
2685 ** limit. The hard heap limit can be activated or lowered by this
2686 ** pragma, but not raised or deactivated. Only the
2687 ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate
2688 ** the hard heap limit. This allows an application to set a heap limit
2689 ** constraint that cannot be relaxed by an untrusted SQL script.
2690 */
2691 case PragTyp_HARD_HEAP_LIMIT: {
2692 sqlite3_int64 N;
2693 if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
2694 sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1);
2695 if( N>0 && (iPrior==0 || iPrior>N) ) sqlite3_hard_heap_limit64(N);
2696 }
2697 returnSingleInt(v, sqlite3_hard_heap_limit64(-1));
2698 break;
2699 }
2700
2701 /*
2702 ** PRAGMA threads
2703 ** PRAGMA threads = N
2704 **
2705 ** Configure the maximum number of worker threads. Return the new
2706 ** maximum, which might be less than requested.
2707 */
2708 case PragTyp_THREADS: {
2709 sqlite3_int64 N;
2710 if( zRight
2711 && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
2712 && N>=0
2713 ){
2714 sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
2715 }
2716 returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
2717 break;
2718 }
2719
2720 /*
2721 ** PRAGMA analysis_limit
2722 ** PRAGMA analysis_limit = N
2723 **
2724 ** Configure the maximum number of rows that ANALYZE will examine
2725 ** in each index that it looks at. Return the new limit.
2726 */
2727 case PragTyp_ANALYSIS_LIMIT: {
2728 sqlite3_int64 N;
2729 if( zRight
2730 && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK /* IMP: R-40975-20399 */
2731 && N>=0
2732 ){
2733 db->nAnalysisLimit = (int)(N&0x7fffffff);
2734 }
2735 returnSingleInt(v, db->nAnalysisLimit); /* IMP: R-57594-65522 */
2736 break;
2737 }
2738
2739#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
2740 /*
2741 ** Report the current state of file logs for all databases
2742 */
2743 case PragTyp_LOCK_STATUS: {
2744 static const char *const azLockName[] = {
2745 "unlocked", "shared", "reserved", "pending", "exclusive"
2746 };
2747 int i;
2748 pParse->nMem = 2;
2749 for(i=0; i<db->nDb; i++){
2750 Btree *pBt;
2751 const char *zState = "unknown";
2752 int j;
2753 if( db->aDb[i].zDbSName==0 ) continue;
2754 pBt = db->aDb[i].pBt;
2755 if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
2756 zState = "closed";
2757 }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
2758 SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
2759 zState = azLockName[j];
2760 }
2761 sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
2762 }
2763 break;
2764 }
2765#endif
2766
2767#if defined(SQLITE_ENABLE_CEROD)
2768 case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
2769 if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
2770 sqlite3_activate_cerod(&zRight[6]);
2771 }
2772 }
2773 break;
2774#endif
2775
2776 } /* End of the PRAGMA switch */
2777
2778 /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
2779 ** purpose is to execute assert() statements to verify that if the
2780 ** PragFlg_NoColumns1 flag is set and the caller specified an argument
2781 ** to the PRAGMA, the implementation has not added any OP_ResultRow
2782 ** instructions to the VM. */
2783 if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
2784 sqlite3VdbeVerifyNoResultRow(v);
2785 }
2786
2787pragma_out:
2788 sqlite3DbFree(db, zLeft);
2789 sqlite3DbFree(db, zRight);
2790}
2791#ifndef SQLITE_OMIT_VIRTUALTABLE
2792/*****************************************************************************
2793** Implementation of an eponymous virtual table that runs a pragma.
2794**
2795*/
2796typedef struct PragmaVtab PragmaVtab;
2797typedef struct PragmaVtabCursor PragmaVtabCursor;
2798struct PragmaVtab {
2799 sqlite3_vtab base; /* Base class. Must be first */
2800 sqlite3 *db; /* The database connection to which it belongs */
2801 const PragmaName *pName; /* Name of the pragma */
2802 u8 nHidden; /* Number of hidden columns */
2803 u8 iHidden; /* Index of the first hidden column */
2804};
2805struct PragmaVtabCursor {
2806 sqlite3_vtab_cursor base; /* Base class. Must be first */
2807 sqlite3_stmt *pPragma; /* The pragma statement to run */
2808 sqlite_int64 iRowid; /* Current rowid */
2809 char *azArg[2]; /* Value of the argument and schema */
2810};
2811
2812/*
2813** Pragma virtual table module xConnect method.
2814*/
2815static int pragmaVtabConnect(
2816 sqlite3 *db,
2817 void *pAux,
2818 int argc, const char *const*argv,
2819 sqlite3_vtab **ppVtab,
2820 char **pzErr
2821){
2822 const PragmaName *pPragma = (const PragmaName*)pAux;
2823 PragmaVtab *pTab = 0;
2824 int rc;
2825 int i, j;
2826 char cSep = '(';
2827 StrAccum acc;
2828 char zBuf[200];
2829
2830 UNUSED_PARAMETER(argc);
2831 UNUSED_PARAMETER(argv);
2832 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
2833 sqlite3_str_appendall(&acc, "CREATE TABLE x");
2834 for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
2835 sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]);
2836 cSep = ',';
2837 }
2838 if( i==0 ){
2839 sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
2840 i++;
2841 }
2842 j = 0;
2843 if( pPragma->mPragFlg & PragFlg_Result1 ){
2844 sqlite3_str_appendall(&acc, ",arg HIDDEN");
2845 j++;
2846 }
2847 if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
2848 sqlite3_str_appendall(&acc, ",schema HIDDEN");
2849 j++;
2850 }
2851 sqlite3_str_append(&acc, ")", 1);
2852 sqlite3StrAccumFinish(&acc);
2853 assert( strlen(zBuf) < sizeof(zBuf)-1 );
2854 rc = sqlite3_declare_vtab(db, zBuf);
2855 if( rc==SQLITE_OK ){
2856 pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
2857 if( pTab==0 ){
2858 rc = SQLITE_NOMEM;
2859 }else{
2860 memset(pTab, 0, sizeof(PragmaVtab));
2861 pTab->pName = pPragma;
2862 pTab->db = db;
2863 pTab->iHidden = i;
2864 pTab->nHidden = j;
2865 }
2866 }else{
2867 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
2868 }
2869
2870 *ppVtab = (sqlite3_vtab*)pTab;
2871 return rc;
2872}
2873
2874/*
2875** Pragma virtual table module xDisconnect method.
2876*/
2877static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
2878 PragmaVtab *pTab = (PragmaVtab*)pVtab;
2879 sqlite3_free(pTab);
2880 return SQLITE_OK;
2881}
2882
2883/* Figure out the best index to use to search a pragma virtual table.
2884**
2885** There are not really any index choices. But we want to encourage the
2886** query planner to give == constraints on as many hidden parameters as
2887** possible, and especially on the first hidden parameter. So return a
2888** high cost if hidden parameters are unconstrained.
2889*/
2890static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
2891 PragmaVtab *pTab = (PragmaVtab*)tab;
2892 const struct sqlite3_index_constraint *pConstraint;
2893 int i, j;
2894 int seen[2];
2895
2896 pIdxInfo->estimatedCost = (double)1;
2897 if( pTab->nHidden==0 ){ return SQLITE_OK; }
2898 pConstraint = pIdxInfo->aConstraint;
2899 seen[0] = 0;
2900 seen[1] = 0;
2901 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
2902 if( pConstraint->iColumn < pTab->iHidden ) continue;
2903 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
2904 if( pConstraint->usable==0 ) return SQLITE_CONSTRAINT;
2905 j = pConstraint->iColumn - pTab->iHidden;
2906 assert( j < 2 );
2907 seen[j] = i+1;
2908 }
2909 if( seen[0]==0 ){
2910 pIdxInfo->estimatedCost = (double)2147483647;
2911 pIdxInfo->estimatedRows = 2147483647;
2912 return SQLITE_OK;
2913 }
2914 j = seen[0]-1;
2915 pIdxInfo->aConstraintUsage[j].argvIndex = 1;
2916 pIdxInfo->aConstraintUsage[j].omit = 1;
2917 pIdxInfo->estimatedCost = (double)20;
2918 pIdxInfo->estimatedRows = 20;
2919 if( seen[1] ){
2920 j = seen[1]-1;
2921 pIdxInfo->aConstraintUsage[j].argvIndex = 2;
2922 pIdxInfo->aConstraintUsage[j].omit = 1;
2923 }
2924 return SQLITE_OK;
2925}
2926
2927/* Create a new cursor for the pragma virtual table */
2928static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
2929 PragmaVtabCursor *pCsr;
2930 pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
2931 if( pCsr==0 ) return SQLITE_NOMEM;
2932 memset(pCsr, 0, sizeof(PragmaVtabCursor));
2933 pCsr->base.pVtab = pVtab;
2934 *ppCursor = &pCsr->base;
2935 return SQLITE_OK;
2936}
2937
2938/* Clear all content from pragma virtual table cursor. */
2939static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
2940 int i;
2941 sqlite3_finalize(pCsr->pPragma);
2942 pCsr->pPragma = 0;
2943 pCsr->iRowid = 0;
2944 for(i=0; i<ArraySize(pCsr->azArg); i++){
2945 sqlite3_free(pCsr->azArg[i]);
2946 pCsr->azArg[i] = 0;
2947 }
2948}
2949
2950/* Close a pragma virtual table cursor */
2951static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
2952 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
2953 pragmaVtabCursorClear(pCsr);
2954 sqlite3_free(pCsr);
2955 return SQLITE_OK;
2956}
2957
2958/* Advance the pragma virtual table cursor to the next row */
2959static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
2960 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2961 int rc = SQLITE_OK;
2962
2963 /* Increment the xRowid value */
2964 pCsr->iRowid++;
2965 assert( pCsr->pPragma );
2966 if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
2967 rc = sqlite3_finalize(pCsr->pPragma);
2968 pCsr->pPragma = 0;
2969 pragmaVtabCursorClear(pCsr);
2970 }
2971 return rc;
2972}
2973
2974/*
2975** Pragma virtual table module xFilter method.
2976*/
2977static int pragmaVtabFilter(
2978 sqlite3_vtab_cursor *pVtabCursor,
2979 int idxNum, const char *idxStr,
2980 int argc, sqlite3_value **argv
2981){
2982 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
2983 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
2984 int rc;
2985 int i, j;
2986 StrAccum acc;
2987 char *zSql;
2988
2989 UNUSED_PARAMETER(idxNum);
2990 UNUSED_PARAMETER(idxStr);
2991 pragmaVtabCursorClear(pCsr);
2992 j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
2993 for(i=0; i<argc; i++, j++){
2994 const char *zText = (const char*)sqlite3_value_text(argv[i]);
2995 assert( j<ArraySize(pCsr->azArg) );
2996 assert( pCsr->azArg[j]==0 );
2997 if( zText ){
2998 pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
2999 if( pCsr->azArg[j]==0 ){
3000 return SQLITE_NOMEM;
3001 }
3002 }
3003 }
3004 sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
3005 sqlite3_str_appendall(&acc, "PRAGMA ");
3006 if( pCsr->azArg[1] ){
3007 sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
3008 }
3009 sqlite3_str_appendall(&acc, pTab->pName->zName);
3010 if( pCsr->azArg[0] ){
3011 sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
3012 }
3013 zSql = sqlite3StrAccumFinish(&acc);
3014 if( zSql==0 ) return SQLITE_NOMEM;
3015 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
3016 sqlite3_free(zSql);
3017 if( rc!=SQLITE_OK ){
3018 pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
3019 return rc;
3020 }
3021 return pragmaVtabNext(pVtabCursor);
3022}
3023
3024/*
3025** Pragma virtual table module xEof method.
3026*/
3027static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
3028 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
3029 return (pCsr->pPragma==0);
3030}
3031
3032/* The xColumn method simply returns the corresponding column from
3033** the PRAGMA.
3034*/
3035static int pragmaVtabColumn(
3036 sqlite3_vtab_cursor *pVtabCursor,
3037 sqlite3_context *ctx,
3038 int i
3039){
3040 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
3041 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
3042 if( i<pTab->iHidden ){
3043 sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
3044 }else{
3045 sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
3046 }
3047 return SQLITE_OK;
3048}
3049
3050/*
3051** Pragma virtual table module xRowid method.
3052*/
3053static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
3054 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
3055 *p = pCsr->iRowid;
3056 return SQLITE_OK;
3057}
3058
3059/* The pragma virtual table object */
3060static const sqlite3_module pragmaVtabModule = {
3061 0, /* iVersion */
3062 0, /* xCreate - create a table */
3063 pragmaVtabConnect, /* xConnect - connect to an existing table */
3064 pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */
3065 pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */
3066 0, /* xDestroy - Drop a table */
3067 pragmaVtabOpen, /* xOpen - open a cursor */
3068 pragmaVtabClose, /* xClose - close a cursor */
3069 pragmaVtabFilter, /* xFilter - configure scan constraints */
3070 pragmaVtabNext, /* xNext - advance a cursor */
3071 pragmaVtabEof, /* xEof */
3072 pragmaVtabColumn, /* xColumn - read data */
3073 pragmaVtabRowid, /* xRowid - read data */
3074 0, /* xUpdate - write data */
3075 0, /* xBegin - begin transaction */
3076 0, /* xSync - sync transaction */
3077 0, /* xCommit - commit transaction */
3078 0, /* xRollback - rollback transaction */
3079 0, /* xFindFunction - function overloading */
3080 0, /* xRename - rename the table */
3081 0, /* xSavepoint */
3082 0, /* xRelease */
3083 0, /* xRollbackTo */
3084 0, /* xShadowName */
3085 0 /* xIntegrity */
3086};
3087
3088/*
3089** Check to see if zTabName is really the name of a pragma. If it is,
3090** then register an eponymous virtual table for that pragma and return
3091** a pointer to the Module object for the new virtual table.
3092*/
3093Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
3094 const PragmaName *pName;
3095 assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
3096 pName = pragmaLocate(zName+7);
3097 if( pName==0 ) return 0;
3098 if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
3099 assert( sqlite3HashFind(&db->aModule, zName)==0 );
3100 return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
3101}
3102
3103#endif /* SQLITE_OMIT_VIRTUALTABLE */
3104
3105#endif /* SQLITE_OMIT_PRAGMA */