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