• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

tarantool / tarantool / 8999

pending completion
8999

push

travis-ci

TheAviat0r
sql: TEMP db removal

- Remove TEMP database, remove possibility to attach new databases:
  Only main database with id = 0 exists.
- Remove TEMP triggers.
- Remove TEMP tables.
- Remove TEMP views.
- Remove TEMP indexes.
- Modify SQL parser, any kind of statement with TEMP word gives syntax
  error.
- Regenerate SQL parser and keywordhash.h, opcodes.h
- Replace Db * aDb with Db mdb in sqlite3 structure

Closes #2168 , #2169

internal commit with comments

1309 of 1309 new or added lines in 28 files covered. (100.0%)

54772 of 72184 relevant lines covered (75.88%)

1203292.14 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

14.56
/src/box/sql/pragma.c
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
/*
26
*************************************************************************
27
** pragma.h contains several pragmas, including utf's pragmas.
28
** All that is not utf-8 should be omitted
29
*************************************************************************
30
*/
31

32
/***************************************************************************
33
** The "pragma.h" include file is an automatically generated file that
34
** that includes the PragType_XXXX macro definitions and the aPragmaName[]
35
** object.  This ensures that the aPragmaName[] table is arranged in
36
** lexicographical order to facility a binary search of the pragma name.
37
** Do not edit pragma.h directly.  Edit and rerun the script in at 
38
** ../tool/mkpragmatab.tcl. */
39
#include "pragma.h"
40

41
/*
42
** Interpret the given string as a safety level.  Return 0 for OFF,
43
** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA.  Return 1 for an empty or 
44
** unrecognized string argument.  The FULL and EXTRA option is disallowed
45
** if the omitFull parameter it 1.
46
**
47
** Note that the values returned are one less that the values that
48
** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
49
** to support legacy SQL code.  The safety level used to be boolean
50
** and older scripts may have used numbers 0 for OFF and 1 for ON.
51
*/
52
static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
198✔
53
                             /* 123456789 123456789 123 */
54
  static const char zText[] = "onoffalseyestruextrafull";
55
  static const u8 iOffset[] = {0, 1, 2,  4,    9,  12,  15,   20};
56
  static const u8 iLength[] = {2, 2, 3,  5,    3,   4,   5,    4};
57
  static const u8 iValue[] =  {1, 0, 0,  0,    1,   1,   3,    2};
58
                            /* on no off false yes true extra full */
59
  int i, n;
60
  if( sqlite3Isdigit(*z) ){
198✔
61
    return (u8)sqlite3Atoi(z);
13✔
62
  }
63
  n = sqlite3Strlen30(z);
185✔
64
  for(i=0; i<ArraySize(iLength); i++){
652✔
65
    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
652✔
66
     && (!omitFull || iValue[i]<=1)
185✔
67
    ){
68
      return iValue[i];
185✔
69
    }
70
  }
71
  return dflt;
×
72
}
73

74
/*
75
** Interpret the given string as a boolean value.
76
*/
77
u8 sqlite3GetBoolean(const char *z, u8 dflt){
197✔
78
  return getSafetyLevel(z,1,dflt)!=0;
197✔
79
}
80

81
/* The sqlite3GetBoolean() function is used by other modules but the
82
** remainder of this file is specific to PRAGMA processing.  So omit
83
** the rest of the file if PRAGMAs are omitted from the build.
84
*/
85
#if !defined(SQLITE_OMIT_PRAGMA)
86

87
/*
88
** Interpret the given string as a locking mode value.
89
*/
90
static int getLockingMode(const char *z){
×
91
  if( z ){
×
92
    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
×
93
    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
×
94
  }
95
  return PAGER_LOCKINGMODE_QUERY;
×
96
}
97

98
#ifndef SQLITE_OMIT_AUTOVACUUM
99
/*
100
** Interpret the given string as an auto-vacuum mode value.
101
**
102
** The following strings, "none", "full" and "incremental" are 
103
** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
104
*/
105
static int getAutoVacuum(const char *z){
×
106
  int i;
107
  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
×
108
  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
×
109
  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
×
110
  i = sqlite3Atoi(z);
×
111
  return (u8)((i>=0&&i<=2)?i:0);
×
112
}
113
#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
114

115
#ifndef SQLITE_OMIT_PAGER_PRAGMAS
116
/*
117
** Interpret the given string as a temp db location. Return 1 for file
118
** backed temporary databases, 2 for the Red-Black tree in memory database
119
** and 0 to use the compile-time default.
120
*/
121
static int getTempStore(const char *z){
×
122
  if( z[0]>='0' && z[0]<='2' ){
×
123
    return z[0] - '0';
×
124
  }else if( sqlite3StrICmp(z, "file")==0 ){
×
125
    return 1;
×
126
  }else if( sqlite3StrICmp(z, "memory")==0 ){
×
127
    return 2;
×
128
  }else{
129
    return 0;
×
130
  }
131
}
132
#endif /* SQLITE_PAGER_PRAGMAS */
133

134
#ifndef SQLITE_OMIT_PAGER_PRAGMAS
135
/*
136
** Invalidate temp storage, either when the temp storage is changed
137
** from default, or when 'file' and the temp_store_directory has changed
138
*/
139
static int invalidateTempStorage(Parse *pParse){
×
140
}
×
141
#endif /* SQLITE_PAGER_PRAGMAS */
142

143
#ifndef SQLITE_OMIT_PAGER_PRAGMAS
144
/*
145
** If the TEMP database is open, close it and mark the database schema
146
** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
147
** or DEFAULT_TEMP_STORE pragmas.
148
*/
149
static int changeTempStorage(Parse *pParse, const char *zStorageType){
×
150
  return SQLITE_OK;
×
151
}
152
#endif /* SQLITE_PAGER_PRAGMAS */
153

154
/*
155
** Set result column names for a pragma.
156
*/
157
static void setPragmaResultColumnNames(
14✔
158
  Vdbe *v,                     /* The query under construction */
159
  const PragmaName *pPragma    /* The pragma */
160
){
161
  u8 n = pPragma->nPragCName;
14✔
162
  sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
14✔
163
  if( n==0 ){
14✔
164
    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
14✔
165
  }else{
166
    int i, j;
167
    for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
×
168
      sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
×
169
    }
170
  }
171
}
14✔
172

173
/*
174
** Generate code to return a single integer value.
175
*/
176
static void returnSingleInt(Vdbe *v, i64 value){
6✔
177
  sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
6✔
178
  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
6✔
179
}
6✔
180

181
/*
182
** Generate code to return a single text value.
183
*/
184
static void returnSingleText(
2✔
185
  Vdbe *v,                /* Prepared statement under construction */
186
  const char *zValue      /* Value to be returned */
187
){
188
  if( zValue ){
2✔
189
    sqlite3VdbeLoadString(v, 1, (const char*)zValue);
2✔
190
    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
2✔
191
  }
192
}
2✔
193

194

195
/*
196
** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
197
** set these values for all pagers.
198
*/
199
#ifndef SQLITE_OMIT_PAGER_PRAGMAS
200
static void setAllPagerFlags(sqlite3 *db){
196✔
201
  if( db->autoCommit ){
196✔
202
    Db *pDb = &db->mdb;
196✔
203
    assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
204
    assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
205
    assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
206
    assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
207
             ==  PAGER_FLAGS_MASK );
208
    assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
196✔
209
      if( db->mdb.pBt ){
196✔
210
        sqlite3BtreeSetPagerFlags(db->mdb.pBt,
196✔
211
                 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
196✔
212
      }
213
    }
214
}
196✔
215
#else
216
# define setAllPagerFlags(X)  /* no-op */
217
#endif
218

219

220
/*
221
** Return a human-readable name for a constraint resolution action.
222
*/
223
#ifndef SQLITE_OMIT_FOREIGN_KEY
224
static const char *actionName(u8 action){
×
225
  const char *zName;
226
  switch( action ){
×
227
    case OE_SetNull:  zName = "SET NULL";        break;
×
228
    case OE_SetDflt:  zName = "SET DEFAULT";     break;
×
229
    case OE_Cascade:  zName = "CASCADE";         break;
×
230
    case OE_Restrict: zName = "RESTRICT";        break;
×
231
    default:          zName = "NO ACTION";  
×
232
                      assert( action==OE_None ); break;
×
233
  }
234
  return zName;
×
235
}
236
#endif
237

238

239
/*
240
** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
241
** defined in pager.h. This function returns the associated lowercase
242
** journal-mode name.
243
*/
244
const char *sqlite3JournalModename(int eMode){
×
245
  static char * const azModeName[] = {
246
    "delete", "persist", "off", "truncate", "memory"
247
  };
248
  assert( PAGER_JOURNALMODE_DELETE==0 );
249
  assert( PAGER_JOURNALMODE_PERSIST==1 );
250
  assert( PAGER_JOURNALMODE_OFF==2 );
251
  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
252
  assert( PAGER_JOURNALMODE_MEMORY==4 );
253
  assert( PAGER_JOURNALMODE_WAL==5 );
254
  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
×
255

256
  if( eMode==ArraySize(azModeName) ) return 0;
×
257
  return azModeName[eMode];
×
258
}
259

260
/*
261
** Locate a pragma in the aPragmaName[] array.
262
*/
263
static const PragmaName *pragmaLocate(const char *zName){
210✔
264
  int upr, lwr, mid, rc;
265
  lwr = 0;
210✔
266
  upr = ArraySize(aPragmaName)-1;
210✔
267
  while( lwr<=upr ){
1,432✔
268
    mid = (lwr+upr)/2;
1,222✔
269
    rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
1,222✔
270
    if( rc==0 ) break;
1,222✔
271
    if( rc<0 ){
1,012✔
272
      upr = mid - 1;
420✔
273
    }else{
274
      lwr = mid + 1;
592✔
275
    }
276
  }
277
  return lwr>upr ? 0 : &aPragmaName[mid];
210✔
278
}
279

280
/*
281
** Process a pragma statement.  
282
**
283
** Pragmas are of this form:
284
**
285
**      PRAGMA [schema.]id [= value]
286
**
287
** The identifier might also be a string.  The value is a string, and
288
** identifier, or a number.  If minusFlag is true, then the value is
289
** a number that was preceded by a minus sign.
290
**
291
** If the left side is "database.id" then pId1 is the database name
292
** and pId2 is the id.  If the left side is just "id" then pId1 is the
293
** id and pId2 is any empty string.
294
*/
295
void sqlite3Pragma(
210✔
296
  Parse *pParse, 
297
  Token *pId1,        /* First part of [schema.]id field */
298
  Token *pId2,        /* Second part of [schema.]id field, or NULL */
299
  Token *pValue,      /* Token for <value>, or NULL */
300
  int minusFlag       /* True if a '-' sign preceded <value> */
301
) {
302
    char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
210✔
303
    char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
210✔
304
    const char *zDb = 0;   /* The database name */
210✔
305
    Token *pId;            /* Pointer to <id> token */
306
    char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
307
    int iDb;               /* Database index for <database> */
308
    int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
309
    sqlite3 *db = pParse->db;    /* The database connection */
210✔
310
    Db *pDb;                     /* The specific database being pragmaed */
311
    Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
210✔
312
    const PragmaName *pPragma;   /* The pragma */
313

314
    if (v == 0) return;
210✔
315
    sqlite3VdbeRunOnlyOnce(v);
210✔
316
    pParse->nMem = 2;
210✔
317

318
    /* Interpret the [schema.] part of the pragma statement. iDb is the
319
    ** index of the database this pragma is being applied to in db.aDb[]. */
320
    iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
210✔
321
    if (iDb < 0) return;
210✔
322
    pDb = &db->mdb;
210✔
323

324
    /* If the temp database has been explicitly named as part of the
325
    ** pragma, make sure it is open.
326
    */
327
    if (iDb == 1 && sqlite3OpenTempDatabase(pParse)) {
210✔
328
        return;
×
329
    }
330

331
    zLeft = sqlite3NameFromToken(db, pId);
210✔
332
    if (!zLeft) return;
210✔
333
    if (minusFlag) {
210✔
334
        zRight = sqlite3MPrintf(db, "-%T", pValue);
×
335
    } else {
336
        zRight = sqlite3NameFromToken(db, pValue);
210✔
337
    }
338

339
    
340
    zDb = 0;
210✔
341
    if (sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb)) {
210✔
342
        goto pragma_out;
×
343
    }
344

345
    /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
346
    ** connection.  If it returns SQLITE_OK, then assume that the VFS
347
    ** handled the pragma and generate a no-op prepared statement.
348
    **
349
    ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
350
    ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
351
    ** object corresponding to the database file to which the pragma
352
    ** statement refers.
353
    **
354
    ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
355
    ** file control is an array of pointers to strings (char**) in which the
356
    ** second element of the array is the name of the pragma and the third
357
    ** element is the argument to the pragma or NULL if the pragma has no
358
    ** argument.
359
    */
360
    aFcntl[0] = 0;
210✔
361
    aFcntl[1] = zLeft;
210✔
362
    aFcntl[2] = zRight;
210✔
363
    aFcntl[3] = 0;
210✔
364
    db->busyHandler.nBusy = 0;
210✔
365
    rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void *) aFcntl);
210✔
366
    if (rc == SQLITE_OK) {
210✔
367
        sqlite3VdbeSetNumCols(v, 1);
×
368
        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
×
369
        returnSingleText(v, aFcntl[0]);
×
370
        sqlite3_free(aFcntl[0]);
×
371
        goto pragma_out;
×
372
    }
373
    if (rc != SQLITE_NOTFOUND) {
210✔
374
        if (aFcntl[0]) {
×
375
            sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
×
376
            sqlite3_free(aFcntl[0]);
×
377
        }
378
        pParse->nErr++;
×
379
        pParse->rc = rc;
×
380
        goto pragma_out;
×
381
    }
382

383
    /* Locate the pragma in the lookup table */
384
    pPragma = pragmaLocate(zLeft);
210✔
385
    if (pPragma == 0) goto pragma_out;
210✔
386

387
    /* Make sure the database schema is loaded if the pragma requires that */
388
    if ((pPragma->mPragFlg & PragFlg_NeedSchema) != 0) {
210✔
389
        if (sqlite3ReadSchema(pParse)) goto pragma_out;
2✔
390
    }
391

392
    /* Register the result column names for pragmas that return results */
393
    if ((pPragma->mPragFlg & PragFlg_NoColumns) == 0
210✔
394
        && ((pPragma->mPragFlg & PragFlg_NoColumns1) == 0 || zRight == 0)
208✔
395
            ) {
396
        setPragmaResultColumnNames(v, pPragma);
8✔
397
    }
398

399
    /* Jump to the appropriate pragma handler */
400
    switch (pPragma->ePragTyp) {
210✔
401

402
#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
403
        /*
404
        **  PRAGMA [schema.]default_cache_size
405
        **  PRAGMA [schema.]default_cache_size=N
406
        **
407
        ** The first form reports the current persistent setting for the
408
        ** page cache size.  The value returned is the maximum number of
409
        ** pages in the page cache.  The second form sets both the current
410
        ** page cache size value and the persistent page cache size value
411
        ** stored in the database file.
412
        **
413
        ** Older versions of SQLite would set the default cache size to a
414
        ** negative number to indicate synchronous=OFF.  These days, synchronous
415
        ** is always on by default regardless of the sign of the default cache
416
        ** size.  But continue to take the absolute value of the default cache
417
        ** size of historical compatibility.
418
        */
419
        case PragTyp_DEFAULT_CACHE_SIZE: {
420
            static const int iLn = VDBE_OFFSET_LINENO(2);
421
            static const VdbeOpList getCacheSize[] = {
422
                    {OP_Transaction, 0, 0, 0},                         /* 0 */
423
                    {OP_ReadCookie,  0, 1, BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
424
                    {OP_IfPos,       1, 8, 0},
425
                    {OP_Integer,     0, 2, 0},
426
                    {OP_Subtract,    1, 2, 1},
427
                    {OP_IfPos,       1, 8, 0},
428
                    {OP_Integer,     0, 1, 0},                         /* 6 */
429
                    {OP_Noop,        0, 0, 0},
430
                    {OP_ResultRow,   1, 1, 0},
431
            };
432
            VdbeOp *aOp;
433
            sqlite3VdbeUsesBtree(v, iDb);
×
434
            if (!zRight) {
×
435
                pParse->nMem += 2;
×
436
                sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
×
437
                aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
×
438
                if (ONLY_IF_REALLOC_STRESS(aOp == 0)) break;
×
439
                aOp[0].p1 = iDb;
×
440
                aOp[1].p1 = iDb;
×
441
                aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
×
442
            } else {
443
                int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
×
444
                sqlite3BeginWriteOperation(pParse, 0);
×
445
                sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
×
446
                assert(sqlite3SchemaMutexHeld(db, 0));
×
447
                pDb->pSchema->cache_size = size;
×
448
                sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
×
449
            }
450
            break;
×
451
        }
452
#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
453

454
#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
455
            /*
456
            **  PRAGMA [schema.]page_size
457
            **  PRAGMA [schema.]page_size=N
458
            **
459
            ** The first form reports the current setting for the
460
            ** database page size in bytes.  The second form sets the
461
            ** database page size value.  The value can only be set if
462
            ** the database has not yet been created.
463
            */
464
        case PragTyp_PAGE_SIZE: {
465
            Btree *pBt = pDb->pBt;
×
466
            assert(pBt != 0);
×
467
            if (!zRight) {
×
468
                int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
×
469
                returnSingleInt(v, size);
×
470
            } else {
471
                /* Malloc may fail when setting the page-size, as there is an internal
472
                ** buffer that the pager module resizes using sqlite3_realloc().
473
                */
474
                db->nextPagesize = sqlite3Atoi(zRight);
×
475
                if (SQLITE_NOMEM == sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0)) {
×
476
                    sqlite3OomFault(db);
×
477
                }
478
            }
479
            break;
×
480
        }
481

482
            /*
483
            **  PRAGMA [schema.]secure_delete
484
            **  PRAGMA [schema.]secure_delete=ON/OFF
485
            **
486
            ** The first form reports the current setting for the
487
            ** secure_delete flag.  The second form changes the secure_delete
488
            ** flag setting and reports thenew value.
489
            */
490
        case PragTyp_SECURE_DELETE: {
491
            Btree *pBt = pDb->pBt;
×
492
            int b = -1;
×
493
            assert(pBt != 0);
×
494
            if (zRight) {
×
495
                b = sqlite3GetBoolean(zRight, 0);
×
496
            }
497
            if (pId2->n == 0 && b >= 0) {
×
498
                sqlite3BtreeSecureDelete(db->mdb.pBt, b);
×
499
            }
500
            b = sqlite3BtreeSecureDelete(pBt, b);
×
501
            returnSingleInt(v, b);
×
502
            break;
×
503
        }
504

505
            /*
506
            **  PRAGMA [schema.]max_page_count
507
            **  PRAGMA [schema.]max_page_count=N
508
            **
509
            ** The first form reports the current setting for the
510
            ** maximum number of pages in the database file.  The
511
            ** second form attempts to change this setting.  Both
512
            ** forms return the current setting.
513
            **
514
            ** The absolute value of N is used.  This is undocumented and might
515
            ** change.  The only purpose is to provide an easy way to test
516
            ** the sqlite3AbsInt32() function.
517
            **
518
            **  PRAGMA [schema.]page_count
519
            **
520
            ** Return the number of pages in the specified database.
521
            */
522
        case PragTyp_PAGE_COUNT: {
523
            int iReg;
524
            sqlite3CodeVerifySchema(pParse);
×
525
            iReg = ++pParse->nMem;
×
526
            if (sqlite3Tolower(zLeft[0]) == 'p') {
×
527
                sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
×
528
            } else {
529
                sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
×
530
                                  sqlite3AbsInt32(sqlite3Atoi(zRight)));
531
            }
532
            sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
×
533
            break;
×
534
        }
535

536
            /*
537
            **  PRAGMA [schema.]locking_mode
538
            **  PRAGMA [schema.]locking_mode = (normal|exclusive)
539
            */
540
        case PragTyp_LOCKING_MODE: {
541
            const char *zRet = "normal";
×
542
            int eMode = getLockingMode(zRight);
×
543

544
            if (pId2->n == 0 && eMode == PAGER_LOCKINGMODE_QUERY) {
×
545
                /* Simple "PRAGMA locking_mode;" statement. This is a query for
546
                ** the current default locking mode (which may be different to
547
                ** the locking-mode of the main database).
548
                */
549
                eMode = db->dfltLockMode;
×
550
            } else {
551
                Pager *pPager;
552
                if (pId2->n == 0) {
×
553
                    /* This indicates that no database name was specified as part
554
                    ** of the PRAGMA command. In this case the locking-mode must be
555
                    ** set on all attached databases, as well as the main db file.
556
                    **
557
                    ** Also, the sqlite3.dfltLockMode variable is set so that
558
                    ** any subsequently attached databases also use the specified
559
                    ** locking mode.
560
                    */
561
                    int ii;
562
                    assert(pDb == &db->mdb);
×
563
                    /*  for(ii=2; ii<db->nDb; ii++){
564
                        pPager = sqlite3BtreePager(db->aDb[ii].pBt);
565
                        sqlite3PagerLockingMode(pPager, eMode);
566
                      }*/
567
                    db->dfltLockMode = (u8) eMode;
×
568
                }
569
                pPager = sqlite3BtreePager(pDb->pBt);
×
570
                eMode = sqlite3PagerLockingMode(pPager, eMode);
×
571
            }
572

573
            assert(eMode == PAGER_LOCKINGMODE_NORMAL
×
574
                   || eMode == PAGER_LOCKINGMODE_EXCLUSIVE);
575
            if (eMode == PAGER_LOCKINGMODE_EXCLUSIVE) {
×
576
                zRet = "exclusive";
×
577
            }
578
            returnSingleText(v, zRet);
×
579
            break;
×
580
        }
581

582
            /*
583
            **  PRAGMA [schema.]journal_mode
584
            **  PRAGMA [schema.]journal_mode =
585
            **                      (delete|persist|off|truncate|memory|wal|off)
586
            */
587
        case PragTyp_JOURNAL_MODE: {
588
            int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
589
            int ii;           /* Loop counter */
590

591
            if (zRight == 0) {
×
592
                /* If there is no "=MODE" part of the pragma, do a query for the
593
                ** current mode */
594
                eMode = PAGER_JOURNALMODE_QUERY;
×
595
            } else {
596
                const char *zMode;
597
                int n = sqlite3Strlen30(zRight);
×
598
                for (eMode = 0; (zMode = sqlite3JournalModename(eMode)) != 0; eMode++) {
×
599
                    if (sqlite3StrNICmp(zRight, zMode, n) == 0) break;
×
600
                }
601
                if (!zMode) {
×
602
                    /* If the "=MODE" part does not match any known journal mode,
603
                    ** then do a query */
604
                    eMode = PAGER_JOURNALMODE_QUERY;
×
605
                }
606
            }
607
            if (eMode == PAGER_JOURNALMODE_QUERY && pId2->n == 0) {
×
608
                /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
609
                iDb = 0;
×
610
                pId2->n = 1;
×
611
            }
612
            if (db->mdb.pBt && (ii == iDb || pId2->n == 0)) {
×
613
                sqlite3VdbeUsesBtree(v, ii);
×
614
                sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
×
615
            }
616
            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
×
617
            break;
×
618
        }
619

620
            /*
621
            **  PRAGMA [schema.]journal_size_limit
622
            **  PRAGMA [schema.]journal_size_limit=N
623
            **
624
            ** Get or set the size limit on rollback journal files.
625
            */
626
        case PragTyp_JOURNAL_SIZE_LIMIT: {
627
            Pager *pPager = sqlite3BtreePager(pDb->pBt);
×
628
            i64 iLimit = -2;
×
629
            if (zRight) {
×
630
                sqlite3DecOrHexToI64(zRight, &iLimit);
×
631
                if (iLimit < -1) iLimit = -1;
×
632
            }
633
            iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
×
634
            returnSingleInt(v, iLimit);
×
635
            break;
×
636
        }
637

638
#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
639

640
            /*
641
            **  PRAGMA [schema.]auto_vacuum
642
            **  PRAGMA [schema.]auto_vacuum=N
643
            **
644
            ** Get or set the value of the database 'auto-vacuum' parameter.
645
            ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
646
            */
647
#ifndef SQLITE_OMIT_AUTOVACUUM
648
        case PragTyp_AUTO_VACUUM: {
649
            Btree *pBt = pDb->pBt;
×
650
            assert(pBt != 0);
×
651
            if (!zRight) {
×
652
                returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
×
653
            } else {
654
                int eAuto = getAutoVacuum(zRight);
×
655
                assert(eAuto >= 0 && eAuto <= 2);
×
656
                db->nextAutovac = (u8) eAuto;
×
657
                /* Call SetAutoVacuum() to set initialize the internal auto and
658
                ** incr-vacuum flags. This is required in case this connection
659
                ** creates the database file. It is important that it is created
660
                ** as an auto-vacuum capable db.
661
                */
662
                rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
×
663
                if (rc == SQLITE_OK && (eAuto == 1 || eAuto == 2)) {
×
664
                    /* When setting the auto_vacuum mode to either "full" or
665
                    ** "incremental", write the value of meta[6] in the database
666
                    ** file. Before writing to meta[6], check that meta[3] indicates
667
                    ** that this really is an auto-vacuum capable database.
668
                    */
669
                    static const int iLn = VDBE_OFFSET_LINENO(2);
670
                    static const VdbeOpList setMeta6[] = {
671
                            {OP_Transaction, 0, 1,                  0},    /* 0 */
672
                            {OP_ReadCookie,  0, 1, BTREE_LARGEST_ROOT_PAGE},
673
                            {OP_If,          1, 0,                  0},    /* 2 */
674
                            {OP_Halt, SQLITE_OK, OE_Abort,          0},    /* 3 */
675
                            {OP_SetCookie,   0,  BTREE_INCR_VACUUM, 0},    /* 4 */
676
                    };
677
                    VdbeOp *aOp;
678
                    int iAddr = sqlite3VdbeCurrentAddr(v);
×
679
                    sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
×
680
                    aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
×
681
                    if (ONLY_IF_REALLOC_STRESS(aOp == 0)) break;
×
682
                    aOp[0].p1 = iDb;
×
683
                    aOp[1].p1 = iDb;
×
684
                    aOp[2].p2 = iAddr + 4;
×
685
                    aOp[4].p1 = iDb;
×
686
                    aOp[4].p3 = eAuto - 1;
×
687
                    sqlite3VdbeUsesBtree(v, iDb);
×
688
                }
689
            }
690
            break;
×
691
        }
692
#endif
693

694
            /*
695
            **  PRAGMA [schema.]incremental_vacuum(N)
696
            **
697
            ** Do N steps of incremental vacuuming on a database.
698
            */
699
#ifndef SQLITE_OMIT_AUTOVACUUM
700
        case PragTyp_INCREMENTAL_VACUUM: {
701
            int iLimit, addr;
702
            if (zRight == 0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit <= 0) {
×
703
                iLimit = 0x7fffffff;
×
704
            }
705
            sqlite3BeginWriteOperation(pParse, 0);
×
706
            sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
×
707
            addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
×
708
            sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
×
709
            sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
×
710
            sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
×
711
            sqlite3VdbeJumpHere(v, addr);
×
712
            break;
×
713
        }
714
#endif
715

716
#ifndef SQLITE_OMIT_PAGER_PRAGMAS
717
            /*
718
            **  PRAGMA [schema.]cache_size
719
            **  PRAGMA [schema.]cache_size=N
720
            **
721
            ** The first form reports the current local setting for the
722
            ** page cache size. The second form sets the local
723
            ** page cache size value.  If N is positive then that is the
724
            ** number of pages in the cache.  If N is negative, then the
725
            ** number of pages is adjusted so that the cache uses -N kibibytes
726
            ** of memory.
727
            */
728
        case PragTyp_CACHE_SIZE: {
729
            assert(sqlite3SchemaMutexHeld(db, 0));
1✔
730
            if (!zRight) {
1✔
731
                returnSingleInt(v, pDb->pSchema->cache_size);
×
732
            } else {
733
                int size = sqlite3Atoi(zRight);
1✔
734
                pDb->pSchema->cache_size = size;
1✔
735
                sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
1✔
736
            }
737
            break;
1✔
738
        }
739

740
            /*
741
            **  PRAGMA [schema.]cache_spill
742
            **  PRAGMA cache_spill=BOOLEAN
743
            **  PRAGMA [schema.]cache_spill=N
744
            **
745
            ** The first form reports the current local setting for the
746
            ** page cache spill size. The second form turns cache spill on
747
            ** or off.  When turnning cache spill on, the size is set to the
748
            ** current cache_size.  The third form sets a spill size that
749
            ** may be different form the cache size.
750
            ** If N is positive then that is the
751
            ** number of pages in the cache.  If N is negative, then the
752
            ** number of pages is adjusted so that the cache uses -N kibibytes
753
            ** of memory.
754
            **
755
            ** If the number of cache_spill pages is less then the number of
756
            ** cache_size pages, no spilling occurs until the page count exceeds
757
            ** the number of cache_size pages.
758
            **
759
            ** The cache_spill=BOOLEAN setting applies to all attached schemas,
760
            ** not just the schema specified.
761
            */
762
        case PragTyp_CACHE_SPILL: {
763
            assert(sqlite3SchemaMutexHeld(db, 0));
×
764
            if (!zRight) {
×
765
                returnSingleInt(v,
×
766
                                (db->flags & SQLITE_CacheSpill) == 0 ? 0 :
×
767
                                sqlite3BtreeSetSpillSize(pDb->pBt, 0));
×
768
            } else {
769
                int size = 1;
×
770
                if (sqlite3GetInt32(zRight, &size)) {
×
771
                    sqlite3BtreeSetSpillSize(pDb->pBt, size);
×
772
                }
773
                if (sqlite3GetBoolean(zRight, size != 0)) {
×
774
                    db->flags |= SQLITE_CacheSpill;
×
775
                } else {
776
                    db->flags &= ~SQLITE_CacheSpill;
×
777
                }
778
                setAllPagerFlags(db);
×
779
            }
780
            break;
×
781
        }
782

783
            /*
784
            **  PRAGMA [schema.]mmap_size(N)
785
            **
786
            ** Used to set mapping size limit. The mapping size limit is
787
            ** used to limit the aggregate size of all memory mapped regions of the
788
            ** database file. If this parameter is set to zero, then memory mapping
789
            ** is not used at all.  If N is negative, then the default memory map
790
            ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
791
            ** The parameter N is measured in bytes.
792
            **
793
            ** This value is advisory.  The underlying VFS is free to memory map
794
            ** as little or as much as it wants.  Except, if N is set to 0 then the
795
            ** upper layers will never invoke the xFetch interfaces to the VFS.
796
            */
797
        case PragTyp_MMAP_SIZE: {
798
            sqlite3_int64 sz;
799
#if SQLITE_MAX_MMAP_SIZE > 0
800
            assert(sqlite3SchemaMutexHeld(db, 0));
×
801
            if (zRight) {
×
802
                int ii;
803
                sqlite3DecOrHexToI64(zRight, &sz);
×
804
                if (sz < 0) sz = sqlite3GlobalConfig.szMmap;
×
805
                if (pId2->n == 0) db->szMmap = sz;
×
806
                if (db->mdb.pBt && pId2->n == 0) {
×
807
                    sqlite3BtreeSetMmapLimit(db->mdb.pBt, sz);
×
808
                }
809
            }
810
            sz = -1;
×
811
            rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
×
812
#else
813
            sz = 0;
814
            rc = SQLITE_OK;
815
#endif
816
            if (rc == SQLITE_OK) {
×
817
                returnSingleInt(v, sz);
×
818
            } else if (rc != SQLITE_NOTFOUND) {
×
819
                pParse->nErr++;
×
820
                pParse->rc = rc;
×
821
            }
822
            break;
×
823
        }
824

825
            /*
826
            **   PRAGMA temp_store
827
            **   PRAGMA temp_store = "default"|"memory"|"file"
828
            **
829
            ** Return or set the local value of the temp_store flag.  Changing
830
            ** the local value does not make changes to the disk file and the default
831
            ** value will be restored the next time the database is opened.
832
            **
833
            ** Note that it is possible for the library compile-time options to
834
            ** override this setting
835
            */
836
        case PragTyp_TEMP_STORE: {
837
            if (!zRight) {
×
838
                returnSingleInt(v, db->temp_store);
×
839
            } else {
840
                changeTempStorage(pParse, zRight);
×
841
            }
842
            break;
×
843
        }
844

845
            /*
846
            **   PRAGMA temp_store_directory
847
            **   PRAGMA temp_store_directory = ""|"directory_name"
848
            **
849
            ** Return or set the local value of the temp_store_directory flag.  Changing
850
            ** the value sets a specific directory to be used for temporary files.
851
            ** Setting to a null string reverts to the default temporary directory search.
852
            ** If temporary directory is changed, then invalidateTempStorage.
853
            **
854
            */
855
        case PragTyp_TEMP_STORE_DIRECTORY: {
856
            if (!zRight) {
×
857
                returnSingleText(v, sqlite3_temp_directory);
×
858
            } else {
859
#ifndef SQLITE_OMIT_WSD
860
                if (zRight[0]) {
×
861
                    int res;
862
                    rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
×
863
                    if (rc != SQLITE_OK || res == 0) {
×
864
                        sqlite3ErrorMsg(pParse, "not a writable directory");
×
865
                        goto pragma_out;
×
866
                    }
867
                }
868
                if (SQLITE_TEMP_STORE == 0
×
869
                    || (SQLITE_TEMP_STORE == 1 && db->temp_store <= 1)
×
870
                    || (SQLITE_TEMP_STORE == 2 && db->temp_store == 1)
871
                        ) {
872
                    invalidateTempStorage(pParse);
×
873
                }
874
                sqlite3_free(sqlite3_temp_directory);
×
875
                if (zRight[0]) {
×
876
                    sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
×
877
                } else {
878
                    sqlite3_temp_directory = 0;
×
879
                }
880
#endif /* SQLITE_OMIT_WSD */
881
            }
882
            break;
×
883
        }
884

885
#if SQLITE_OS_WIN
886
        /*
887
        **   PRAGMA data_store_directory
888
        **   PRAGMA data_store_directory = ""|"directory_name"
889
        **
890
        ** Return or set the local value of the data_store_directory flag.  Changing
891
        ** the value sets a specific directory to be used for database files that
892
        ** were specified with a relative pathname.  Setting to a null string reverts
893
        ** to the default database directory, which for database files specified with
894
        ** a relative path will probably be based on the current directory for the
895
        ** process.  Database file specified with an absolute path are not impacted
896
        ** by this setting, regardless of its value.
897
        **
898
        */
899
        case PragTyp_DATA_STORE_DIRECTORY: {
900
          if( !zRight ){
901
            returnSingleText(v, sqlite3_data_directory);
902
          }else{
903
#ifndef SQLITE_OMIT_WSD
904
            if( zRight[0] ){
905
              int res;
906
              rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
907
              if( rc!=SQLITE_OK || res==0 ){
908
                sqlite3ErrorMsg(pParse, "not a writable directory");
909
                goto pragma_out;
910
              }
911
            }
912
            sqlite3_free(sqlite3_data_directory);
913
            if( zRight[0] ){
914
              sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
915
            }else{
916
              sqlite3_data_directory = 0;
917
            }
918
#endif /* SQLITE_OMIT_WSD */
919
          }
920
          break;
921
        }
922
#endif
923

924
#if SQLITE_ENABLE_LOCKING_STYLE
925
            /*
926
            **   PRAGMA [schema.]lock_proxy_file
927
            **   PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
928
            **
929
            ** Return or set the value of the lock_proxy_file flag.  Changing
930
            ** the value sets a specific file to be used for database access locks.
931
            **
932
            */
933
        case PragTyp_LOCK_PROXY_FILE: {
934
            if (!zRight) {
935
                Pager *pPager = sqlite3BtreePager(pDb->pBt);
936
                char *proxy_file_path = NULL;
937
                sqlite3_file *pFile = sqlite3PagerFile(pPager);
938
                sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
939
                                         &proxy_file_path);
940
                returnSingleText(v, proxy_file_path);
941
            } else {
942
                Pager *pPager = sqlite3BtreePager(pDb->pBt);
943
                sqlite3_file *pFile = sqlite3PagerFile(pPager);
944
                int res;
945
                if (zRight[0]) {
946
                    res = sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
947
                                               zRight);
948
                } else {
949
                    res = sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
950
                                               NULL);
951
                }
952
                if (res != SQLITE_OK) {
953
                    sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
954
                    goto pragma_out;
955
                }
956
            }
957
            break;
958
        }
959
#endif /* SQLITE_ENABLE_LOCKING_STYLE */
960

961
            /*
962
            **   PRAGMA [schema.]synchronous
963
            **   PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
964
            **
965
            ** Return or set the local value of the synchronous flag.  Changing
966
            ** the local value does not make changes to the disk file and the
967
            ** default value will be restored the next time the database is
968
            ** opened.
969
            */
970
        case PragTyp_SYNCHRONOUS: {
971
            if (!zRight) {
1✔
972
                returnSingleInt(v, pDb->safety_level - 1);
×
973
            } else {
974
                if (!db->autoCommit) {
1✔
975
                    sqlite3ErrorMsg(pParse,
×
976
                                    "Safety level may not be changed inside a transaction");
977
                } else {
978
                    int iLevel = (getSafetyLevel(zRight, 0, 1) + 1) & PAGER_SYNCHRONOUS_MASK;
1✔
979
                    if (iLevel == 0) iLevel = 1;
1✔
980
                    pDb->safety_level = iLevel;
1✔
981
                    pDb->bSyncSet = 1;
1✔
982
                    setAllPagerFlags(db);
1✔
983
                }
984
            }
985
            break;
1✔
986
        }
987
#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
988

989
#ifndef SQLITE_OMIT_FLAG_PRAGMAS
990
        case PragTyp_FLAG: {
991
            if (zRight == 0) {
201✔
992
                setPragmaResultColumnNames(v, pPragma);
6✔
993
                returnSingleInt(v, (db->flags & pPragma->iArg) != 0);
6✔
994
            } else {
995
                int mask = pPragma->iArg;    /* Mask of bits to set or clear. */
195✔
996
                if (db->autoCommit == 0) {
195✔
997
                    /* Foreign key support may not be enabled or disabled while not
998
                    ** in auto-commit mode.  */
999
                    mask &= ~(SQLITE_ForeignKeys);
×
1000
                }
1001
#if SQLITE_USER_AUTHENTICATION
1002
                if( db->auth.authLevel==UAUTH_User ){
1003
                  /* Do not allow non-admin users to modify the schema arbitrarily */
1004
                  mask &= ~(SQLITE_WriteSchema);
1005
                }
1006
#endif
1007

1008
                if (sqlite3GetBoolean(zRight, 0)) {
195✔
1009
                    db->flags |= mask;
98✔
1010
                } else {
1011
                    db->flags &= ~mask;
97✔
1012
                    if (mask == SQLITE_DeferFKs) db->nDeferredImmCons = 0;
97✔
1013
                }
1014

1015
                /* Many of the flag-pragmas modify the code generated by the SQL
1016
                ** compiler (eg. count_changes). So add an opcode to expire all
1017
                ** compiled SQL statements after modifying a pragma value.
1018
                */
1019
                sqlite3VdbeAddOp0(v, OP_Expire);
195✔
1020
                setAllPagerFlags(db);
195✔
1021
            }
1022
            break;
201✔
1023
        }
1024
#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
1025

1026
#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
1027
            /*
1028
            **   PRAGMA table_info(<table>)
1029
            **
1030
            ** Return a single row for each column of the named table. The columns of
1031
            ** the returned data set are:
1032
            **
1033
            ** cid:        Column id (numbered from left to right, starting at 0)
1034
            ** name:       Column name
1035
            ** type:       Column declaration type.
1036
            ** notnull:    True if 'NOT NULL' is part of column declaration
1037
            ** dflt_value: The default value for the column, if any.
1038
            */
1039
        case PragTyp_TABLE_INFO:
1040
            if (zRight) {
×
1041
                Table *pTab;
1042
                pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight);
×
1043
                if (pTab) {
×
1044
                    int i, k;
1045
                    int nHidden = 0;
×
1046
                    Column *pCol;
1047
                    Index *pPk = sqlite3PrimaryKeyIndex(pTab);
×
1048
                    pParse->nMem = 6;
×
1049
                    sqlite3CodeVerifySchema(pParse);
×
1050
                    sqlite3ViewGetColumnNames(pParse, pTab);
×
1051
                    for (i = 0, pCol = pTab->aCol; i < pTab->nCol; i++, pCol++) {
×
1052
                        if (IsHiddenColumn(pCol)) {
×
1053
                            nHidden++;
×
1054
                            continue;
×
1055
                        }
1056
                        if ((pCol->colFlags & COLFLAG_PRIMKEY) == 0) {
×
1057
                            k = 0;
×
1058
                        } else if (pPk == 0) {
×
1059
                            k = 1;
×
1060
                        } else {
1061
                            for (k = 1; k <= pTab->nCol && pPk->aiColumn[k - 1] != i; k++) {}
×
1062
                        }
1063
                        assert(pCol->pDflt == 0 || pCol->pDflt->op == TK_SPAN);
×
1064
                        sqlite3VdbeMultiLoad(v, 1, "issisi",
×
1065
                                             i - nHidden,
1066
                                             pCol->zName,
1067
                                             sqlite3ColumnType(pCol, ""),
1068
                                             pCol->notNull ? 1 : 0,
×
1069
                                             pCol->pDflt ? pCol->pDflt->u.zToken : 0,
×
1070
                                             k);
1071
                        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
×
1072
                    }
1073
                }
1074
            }
1075
            break;
×
1076

1077
        case PragTyp_STATS: {
1078
            Index *pIdx;
1079
            HashElem *i;
1080
            pParse->nMem = 4;
×
1081
            sqlite3CodeVerifySchema(pParse);
×
1082
            for (i = sqliteHashFirst(&pDb->pSchema->tblHash); i; i = sqliteHashNext(i)) {
×
1083
                Table *pTab = sqliteHashData(i);
×
1084
                sqlite3VdbeMultiLoad(v, 1, "ssii",
×
1085
                                     pTab->zName,
1086
                                     0,
1087
                                     pTab->szTabRow,
×
1088
                                     pTab->nRowLogEst);
×
1089
                sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
×
1090
                for (pIdx = pTab->pIndex; pIdx; pIdx = pIdx->pNext) {
×
1091
                    sqlite3VdbeMultiLoad(v, 2, "sii",
×
1092
                                         pIdx->zName,
1093
                                         pIdx->szIdxRow,
×
1094
                                         pIdx->aiRowLogEst[0]);
×
1095
                    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
×
1096
                }
1097
            }
1098
        }
1099
            break;
×
1100

1101
        case PragTyp_INDEX_INFO:
1102
            if (zRight) {
×
1103
                Index *pIdx;
1104
                Table *pTab;
1105
                pIdx = sqlite3FindIndex(db, zRight);
×
1106
                if (pIdx) {
×
1107
                    int i;
1108
                    int mx;
1109
                    if (pPragma->iArg) {
×
1110
                        /* PRAGMA index_xinfo (newer version with more rows and columns) */
1111
                        mx = pIdx->nColumn;
×
1112
                        pParse->nMem = 6;
×
1113
                    } else {
1114
                        /* PRAGMA index_info (legacy version) */
1115
                        mx = pIdx->nKeyCol;
×
1116
                        pParse->nMem = 3;
×
1117
                    }
1118
                    pTab = pIdx->pTable;
×
1119
                    sqlite3CodeVerifySchema(pParse);
×
1120
                    assert(pParse->nMem <= pPragma->nPragCName);
×
1121
                    for (i = 0; i < mx; i++) {
×
1122
                        i16 cnum = pIdx->aiColumn[i];
×
1123
                        sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum,
×
1124
                                             cnum < 0 ? 0 : pTab->aCol[cnum].zName);
×
1125
                        if (pPragma->iArg) {
×
1126
                            sqlite3VdbeMultiLoad(v, 4, "isi",
×
1127
                                                 pIdx->aSortOrder[i],
×
1128
                                                 pIdx->azColl[i],
×
1129
                                                 i < pIdx->nKeyCol);
×
1130
                        }
1131
                        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
×
1132
                    }
1133
                }
1134
            }
1135
            break;
×
1136

1137
        case PragTyp_INDEX_LIST:
1138
            if (zRight) {
×
1139
                Index *pIdx;
1140
                Table *pTab;
1141
                int i;
1142
                pTab = sqlite3FindTable(db, zRight);
×
1143
                if (pTab) {
×
1144
                    pParse->nMem = 5;
×
1145
                    sqlite3CodeVerifySchema(pParse);
×
1146
                    for (pIdx = pTab->pIndex, i = 0; pIdx; pIdx = pIdx->pNext, i++) {
×
1147
                        const char *azOrigin[] = {"c", "u", "pk"};
×
1148
                        sqlite3VdbeMultiLoad(v, 1, "isisi",
×
1149
                                             i,
1150
                                             pIdx->zName,
1151
                                             IsUniqueIndex(pIdx),
×
1152
                                             azOrigin[pIdx->idxType],
×
1153
                                             pIdx->pPartIdxWhere != 0);
×
1154
                        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
×
1155
                    }
1156
                }
1157
            }
1158
            break;
×
1159

1160
        case PragTyp_DATABASE_LIST: {
1161
            pParse->nMem = 3;
×
1162
            assert(db->mdb.pBt == 0);
×
1163
            assert(db->mdb.zDbSName != 0);
×
1164
            sqlite3VdbeMultiLoad(v, 1, "iss",
×
1165
                                 0,
1166
                                 db->mdb.zDbSName,
1167
                                 sqlite3BtreeGetFilename(db->mdb.pBt));
1168
            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
×
1169
        }
1170
            break;
×
1171

1172
        case PragTyp_COLLATION_LIST: {
1173
            int i = 0;
×
1174
            HashElem *p;
1175
            pParse->nMem = 2;
×
1176
            for (p = sqliteHashFirst(&db->aCollSeq); p; p = sqliteHashNext(p)) {
×
1177
                CollSeq *pColl = (CollSeq *) sqliteHashData(p);
×
1178
                sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
×
1179
                sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
×
1180
            }
1181
        }
1182
            break;
×
1183
#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
1184

1185
#ifndef SQLITE_OMIT_FOREIGN_KEY
1186
        case PragTyp_FOREIGN_KEY_LIST:
1187
            if (zRight) {
×
1188
                FKey *pFK;
1189
                Table *pTab;
1190
                pTab = sqlite3FindTable(db, zRight);
×
1191
                if (pTab) {
×
1192
                    pFK = pTab->pFKey;
×
1193
                    if (pFK) {
×
1194
                        int i = 0;
×
1195
                        pParse->nMem = 8;
×
1196
                        sqlite3CodeVerifySchema(pParse);
×
1197
                        while (pFK) {
×
1198
                            int j;
1199
                            for (j = 0; j < pFK->nCol; j++) {
×
1200
                                sqlite3VdbeMultiLoad(v, 1, "iissssss",
×
1201
                                                     i,
1202
                                                     j,
1203
                                                     pFK->zTo,
1204
                                                     pTab->aCol[pFK->aCol[j].iFrom].zName,
×
1205
                                                     pFK->aCol[j].zCol,
1206
                                                     actionName(pFK->aAction[1]),  /* ON UPDATE */
×
1207
                                                     actionName(pFK->aAction[0]),  /* ON DELETE */
×
1208
                                                     "NONE");
1209
                                sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
×
1210
                            }
1211
                            ++i;
×
1212
                            pFK = pFK->pNextFrom;
×
1213
                        }
1214
                    }
1215
                }
1216
            }
1217
            break;
×
1218
#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1219

1220
#ifndef SQLITE_OMIT_FOREIGN_KEY
1221
#ifndef SQLITE_OMIT_TRIGGER
1222
        case PragTyp_FOREIGN_KEY_CHECK: {
1223
            FKey *pFK;             /* A foreign key constraint */
1224
            Table *pTab;           /* Child table contain "REFERENCES" keyword */
1225
            Table *pParent;        /* Parent table that child points to */
1226
            Index *pIdx;           /* Index in the parent table */
1227
            int i;                 /* Loop counter:  Foreign key number for pTab */
1228
            int j;                 /* Loop counter:  Field of the foreign key */
1229
            HashElem *k;           /* Loop counter:  Next table in schema */
1230
            int x;                 /* result variable */
1231
            int regResult;         /* 3 registers to hold a result row */
1232
            int regKey;            /* Register to hold key for checking the FK */
1233
            int regRow;            /* Registers to hold a row from pTab */
1234
            int addrTop;           /* Top of a loop checking foreign keys */
1235
            int addrOk;            /* Jump here if the key is OK */
1236
            int *aiCols;           /* child to parent column mapping */
1237

1238
            regResult = pParse->nMem + 1;
×
1239
            pParse->nMem += 4;
×
1240
            regKey = ++pParse->nMem;
×
1241
            regRow = ++pParse->nMem;
×
1242
            assert(iDb == 0);
×
1243
            sqlite3CodeVerifySchema(pParse);
×
1244
            k = sqliteHashFirst(&db->mdb.pSchema->tblHash);
×
1245
            while (k) {
×
1246
                if (zRight) {
×
1247
                    pTab = sqlite3LocateTable(pParse, 0, zRight);
×
1248
                    k = 0;
×
1249
                } else {
1250
                    pTab = (Table *) sqliteHashData(k);
×
1251
                    k = sqliteHashNext(k);
×
1252
                }
1253
                if (pTab == 0 || pTab->pFKey == 0) continue;
×
1254
                sqlite3TableLock(pParse, pTab->tnum, 0, pTab->zName);
×
1255
                if (pTab->nCol + regRow > pParse->nMem) pParse->nMem = pTab->nCol + regRow;
×
1256
                sqlite3OpenTable(pParse, 0, pTab, OP_OpenRead);
×
1257
                sqlite3VdbeLoadString(v, regResult, pTab->zName);
×
1258
                for (i = 1, pFK = pTab->pFKey; pFK; i++, pFK = pFK->pNextFrom) {
×
1259
                    pParent = sqlite3FindTable(db, pFK->zTo);
×
1260
                    if (pParent == 0) continue;
×
1261
                    pIdx = 0;
×
1262
                    sqlite3TableLock(pParse, pParent->tnum, 0, pParent->zName);
×
1263
                    x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
×
1264
                    if (x == 0) {
×
1265
                        if (pIdx == 0) {
×
1266
                            sqlite3OpenTable(pParse, i, pParent, OP_OpenRead);
×
1267
                        } else {
1268
                            sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
×
1269
                            sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
×
1270
                        }
1271
                    } else {
1272
                        k = 0;
×
1273
                        break;
×
1274
                    }
1275
                }
1276
                assert(pParse->nErr > 0 || pFK == 0);
×
1277
                if (pFK) break;
×
1278
                if (pParse->nTab < i) pParse->nTab = i;
×
1279
                addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
×
1280
                for (i = 1, pFK = pTab->pFKey; pFK; i++, pFK = pFK->pNextFrom) {
×
1281
                    pParent = sqlite3FindTable(db, pFK->zTo);
×
1282
                    pIdx = 0;
×
1283
                    aiCols = 0;
×
1284
                    if (pParent) {
×
1285
                        x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
×
1286
                        assert(x == 0);
×
1287
                    }
1288
                    addrOk = sqlite3VdbeMakeLabel(v);
×
1289
                    if (pParent && pIdx == 0) {
×
1290
                        int iKey = pFK->aCol[0].iFrom;
×
1291
                        assert(iKey >= 0 && iKey < pTab->nCol);
×
1292
                        if (iKey != pTab->iPKey) {
×
1293
                            sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
×
1294
                            sqlite3ColumnDefault(v, pTab, iKey, regRow);
×
1295
                            sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
×
1296
                        } else {
1297
                            sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
×
1298
                        }
1299
                        sqlite3VdbeAddOp3(v, OP_SeekRowid, i, 0, regRow); VdbeCoverage(v);
×
1300
                        sqlite3VdbeGoto(v, addrOk);
×
1301
                        sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v) - 2);
×
1302
                    } else {
1303
                        for (j = 0; j < pFK->nCol; j++) {
×
1304
                            sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
×
1305
                                                            aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow + j);
×
1306
                            sqlite3VdbeAddOp2(v, OP_IsNull, regRow + j, addrOk); VdbeCoverage(v);
×
1307
                        }
1308
                        if (pParent) {
×
1309
                            sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
×
1310
                                              sqlite3IndexAffinityStr(db, pIdx), pFK->nCol);
1311
                            sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
×
1312
                            VdbeCoverage(v);
1313
                        }
1314
                    }
1315
                    sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult + 1);
×
1316
                    sqlite3VdbeMultiLoad(v, regResult + 2, "si", pFK->zTo, i - 1);
×
1317
                    sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
×
1318
                    sqlite3VdbeResolveLabel(v, addrOk);
×
1319
                    sqlite3DbFree(db, aiCols);
×
1320
                }
1321
                sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop + 1); VdbeCoverage(v);
×
1322
                sqlite3VdbeJumpHere(v, addrTop);
×
1323
            }
1324
        }
1325
            break;
×
1326
#endif /* !defined(SQLITE_OMIT_TRIGGER) */
1327
#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1328

1329
#ifndef NDEBUG
1330
        case PragTyp_PARSER_TRACE: {
1331
            if (zRight) {
×
1332
                if (sqlite3GetBoolean(zRight, 0)) {
×
1333
                    sqlite3ParserTrace(stdout, "parser: ");
×
1334
                } else {
1335
                    sqlite3ParserTrace(0, 0);
×
1336
                }
1337
            }
1338
        }
1339
            break;
×
1340
#endif
1341

1342
            /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
1343
            ** used will be case sensitive or not depending on the RHS.
1344
            */
1345
        case PragTyp_CASE_SENSITIVE_LIKE: {
1346
            if (zRight) {
2✔
1347
                sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
2✔
1348
            }
1349
        }
1350
            break;
2✔
1351

1352
#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
1353
# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
1354
#endif
1355

1356
#ifndef SQLITE_OMIT_INTEGRITY_CHECK
1357
            /* Pragma "quick_check" is reduced version of
1358
            ** integrity_check designed to detect most database corruption
1359
            ** without most of the overhead of a full integrity-check.
1360
            */
1361
        case PragTyp_INTEGRITY_CHECK: {
1362
            int i, j, addr, mxErr;
1363

1364
            int isQuick = (sqlite3Tolower(zLeft[0]) == 'q');
×
1365

1366
            /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
1367
            ** then iDb is set to the index of the database identified by <db>.
1368
            ** In this case, the integrity of database iDb only is verified by
1369
            ** the VDBE created below.
1370
            **
1371
            ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
1372
            ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
1373
            ** to -1 here, to indicate that the VDBE should verify the integrity
1374
            ** of all attached databases.  */
1375
            assert(iDb >= 0);
×
1376
            assert(iDb == 0 || pId2->z);
×
1377
            if (pId2->z == 0) iDb = -1;
×
1378

1379
            /* Initialize the VDBE program */
1380
            pParse->nMem = 6;
×
1381

1382
            /* Set the maximum error count */
1383
            mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
×
1384
            if (zRight) {
×
1385
                sqlite3GetInt32(zRight, &mxErr);
×
1386
                if (mxErr <= 0) {
×
1387
                    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
×
1388
                }
1389
            }
1390
            sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
×
1391

1392
            /* Do an integrity check on each database file */
1393
            HashElem *x;
1394
            Hash *pTbls;
1395
            int *aRoot;
1396
            int cnt = 0;
×
1397
            int mxIdx = 0;
×
1398
            int nIdx;
1399

1400
            assert(iDb == 0);
×
1401

1402
            sqlite3CodeVerifySchema(pParse);
×
1403
            addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
×
1404
            VdbeCoverage(v);
1405
            sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
×
1406
            sqlite3VdbeJumpHere(v, addr);
×
1407

1408
            /* Do an integrity check of the B-Tree
1409
            **
1410
            ** Begin by finding the root pages numbers
1411
            ** for all tables and indices in the database.
1412
            */
1413
            assert(sqlite3SchemaMutexHeld(db, 0));
×
1414
            pTbls = &db->mdb.pSchema->tblHash;
×
1415
            for (cnt = 0, x = sqliteHashFirst(pTbls); x; x = sqliteHashNext(x)) {
×
1416
                Table *pTab = sqliteHashData(x);
×
1417
                Index *pIdx;
1418
                if (HasRowid(pTab)) cnt++;
×
1419
                for (nIdx = 0, pIdx = pTab->pIndex; pIdx; pIdx = pIdx->pNext, nIdx++) { cnt++; }
×
1420
                if (nIdx > mxIdx) mxIdx = nIdx;
×
1421
            }
1422
            aRoot = sqlite3DbMallocRawNN(db, sizeof(int) * (cnt + 1));
×
1423
            if (aRoot == 0) break;
5✔
1424
            for (cnt = 0, x = sqliteHashFirst(pTbls); x; x = sqliteHashNext(x)) {
×
1425
                Table *pTab = sqliteHashData(x);
×
1426
                Index *pIdx;
1427
                if (HasRowid(pTab)) aRoot[cnt++] = pTab->tnum;
×
1428
                for (pIdx = pTab->pIndex; pIdx; pIdx = pIdx->pNext) {
×
1429
                    aRoot[cnt++] = pIdx->tnum;
×
1430
                }
1431
            }
1432
            aRoot[cnt] = 0;
×
1433

1434
            /* Make sure sufficient number of registers have been allocated */
1435
            pParse->nMem = MAX(pParse->nMem, 8 + mxIdx);
×
1436

1437
            /* Do the b-tree integrity checks */
1438
            sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char *) aRoot, P4_INTARRAY);
×
1439
            sqlite3VdbeChangeP5(v, (u8) i);
×
1440
            addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
×
1441
            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
×
1442
                              sqlite3MPrintf(db, "*** in database %s ***\n", db->mdb.zDbSName),
×
1443
                              P4_DYNAMIC);
1444
            sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
×
1445
            sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
×
1446
            sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
×
1447
            sqlite3VdbeJumpHere(v, addr);
×
1448

1449
            /* Make sure all the indices are constructed correctly.
1450
            */
1451
            for (x = sqliteHashFirst(pTbls); x && !isQuick; x = sqliteHashNext(x)) {
×
1452
                Table *pTab = sqliteHashData(x);
×
1453
                Index *pIdx, *pPk;
1454
                Index *pPrior = 0;
×
1455
                int loopTop;
1456
                int iDataCur, iIdxCur;
1457
                int r1 = -1;
×
1458

1459
                if (pTab->pIndex == 0) continue;
×
1460
                pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
×
1461
                addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
×
1462
                VdbeCoverage(v);
1463
                sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
×
1464
                sqlite3VdbeJumpHere(v, addr);
×
1465
                sqlite3ExprCacheClear(pParse);
×
1466
                sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
×
1467
                                           1, 0, &iDataCur, &iIdxCur);
1468
                sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
×
1469
                for (j = 0, pIdx = pTab->pIndex; pIdx; pIdx = pIdx->pNext, j++) {
×
1470
                    sqlite3VdbeAddOp2(v, OP_Integer, 0, 8 + j); /* index entries counter */
×
1471
                }
1472
                assert(pParse->nMem >= 8 + j);
×
1473
                assert(sqlite3NoTempsInRange(pParse, 1, 7 + j));
×
1474
                sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
×
1475
                loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
×
1476
                /* Verify that all NOT NULL columns really are NOT NULL */
1477
                for (j = 0; j < pTab->nCol; j++) {
×
1478
                    char *zErr;
1479
                    int jmp2, jmp3;
1480
                    if (j == pTab->iPKey) continue;
×
1481
                    if (pTab->aCol[j].notNull == 0) continue;
×
1482
                    sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
×
1483
                    sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
×
1484
                    jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
×
1485
                    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
×
1486
                    zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
×
1487
                                          pTab->aCol[j].zName);
×
1488
                    sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
×
1489
                    sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
×
1490
                    jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
×
1491
                    sqlite3VdbeAddOp0(v, OP_Halt);
×
1492
                    sqlite3VdbeJumpHere(v, jmp2);
×
1493
                    sqlite3VdbeJumpHere(v, jmp3);
×
1494
                }
1495
                /* Validate index entries for the current row */
1496
                for (j = 0, pIdx = pTab->pIndex; pIdx; pIdx = pIdx->pNext, j++) {
×
1497
                    int jmp2, jmp3, jmp4, jmp5;
1498
                    int ckUniq = sqlite3VdbeMakeLabel(v);
×
1499
                    if (pPk == pIdx) continue;
×
1500
                    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
×
1501
                                                 pPrior, r1);
1502
                    pPrior = pIdx;
×
1503
                    sqlite3VdbeAddOp2(v, OP_AddImm, 8 + j, 1);  /* increment entry count */
×
1504
                    /* Verify that an index entry exists for the current table row */
1505
                    jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur + j, ckUniq, r1,
×
1506
                                                pIdx->nColumn); VdbeCoverage(v);
×
1507
                    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
×
1508
                    sqlite3VdbeLoadString(v, 3, "row ");
×
1509
                    sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
×
1510
                    sqlite3VdbeLoadString(v, 4, " missing from index ");
×
1511
                    sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
×
1512
                    jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
×
1513
                    sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
×
1514
                    sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
×
1515
                    jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
×
1516
                    sqlite3VdbeAddOp0(v, OP_Halt);
×
1517
                    sqlite3VdbeJumpHere(v, jmp2);
×
1518
                    /* For UNIQUE indexes, verify that only one entry exists with the
1519
                    ** current key.  The entry is unique if (1) any column is NULL
1520
                    ** or (2) the next entry has a different key */
1521
                    if (IsUniqueIndex(pIdx)) {
×
1522
                        int uniqOk = sqlite3VdbeMakeLabel(v);
×
1523
                        int jmp6;
1524
                        int kk;
1525
                        for (kk = 0; kk < pIdx->nKeyCol; kk++) {
×
1526
                            int iCol = pIdx->aiColumn[kk];
×
1527
                            assert(iCol != XN_ROWID && iCol < pTab->nCol);
×
1528
                            if (iCol >= 0 && pTab->aCol[iCol].notNull) continue;
×
1529
                            sqlite3VdbeAddOp2(v, OP_IsNull, r1 + kk, uniqOk);
×
1530
                            VdbeCoverage(v);
1531
                        }
1532
                        jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur + j); VdbeCoverage(v);
×
1533
                        sqlite3VdbeGoto(v, uniqOk);
×
1534
                        sqlite3VdbeJumpHere(v, jmp6);
×
1535
                        sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur + j, uniqOk, r1,
×
1536
                                             pIdx->nKeyCol); VdbeCoverage(v);
×
1537
                        sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
×
1538
                        sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
×
1539
                        sqlite3VdbeGoto(v, jmp5);
×
1540
                        sqlite3VdbeResolveLabel(v, uniqOk);
×
1541
                    }
1542
                    sqlite3VdbeJumpHere(v, jmp4);
×
1543
                    sqlite3ResolvePartIdxLabel(pParse, jmp3);
×
1544
                }
1545
                sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
×
1546
                sqlite3VdbeJumpHere(v, loopTop - 1);
×
1547
#ifndef SQLITE_OMIT_BTREECOUNT
1548
                sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
×
1549
                for (j = 0, pIdx = pTab->pIndex; pIdx; pIdx = pIdx->pNext, j++) {
×
1550
                    if (pPk == pIdx) continue;
×
1551
                    addr = sqlite3VdbeCurrentAddr(v);
×
1552
                    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr + 2); VdbeCoverage(v);
×
1553
                    sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
×
1554
                    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur + j, 3);
×
1555
                    sqlite3VdbeAddOp3(v, OP_Eq, 8 + j, addr + 8, 3); VdbeCoverage(v);
×
1556
                    sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
×
1557
                    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
×
1558
                    sqlite3VdbeLoadString(v, 3, pIdx->zName);
×
1559
                    sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
×
1560
                    sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
×
1561
                }
1562
#endif /* SQLITE_OMIT_BTREECOUNT */
1563
            }
1564
            {
1565
                static const int iLn = VDBE_OFFSET_LINENO(2);
1566
                static const VdbeOpList endCode[] = {
1567
                        {OP_AddImm,    1, 0, 0},    /* 0 */
1568
                        {OP_If,        1, 4, 0},    /* 1 */
1569
                        {OP_String8,   0, 3, 0},    /* 2 */
1570
                        {OP_ResultRow, 3, 1, 0},    /* 3 */
1571
                };
1572
                VdbeOp *aOp;
1573

1574
                aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
×
1575
                if (aOp) {
×
1576
                    aOp[0].p2 = -mxErr;
×
1577
                    aOp[2].p4type = P4_STATIC;
×
1578
                    aOp[2].p4.z = "ok";
×
1579
                }
1580
            }
1581
            break;
×
1582
#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
1583

1584
            /*
1585
            **   PRAGMA encoding
1586
            **   PRAGMA encoding = "utf-8"
1587
            **
1588
            ** In its first form, this pragma returns the encoding of the main
1589
            ** database. If the database is not initialized, it is initialized now.
1590
            **
1591
            ** The second form of this pragma is a no-op if the main database file
1592
            ** has not already been initialized. In this case it sets the default
1593
            ** encoding that will be used for the main database file if a new file
1594
            ** is created. If an existing main database file is opened, then the
1595
            ** default text encoding for the existing database is used.
1596
            **
1597
            ** In all cases new databases created using the ATTACH command are
1598
            ** created to use the same default text encoding as the main database. If
1599
            ** the main database has not been initialized and/or created when ATTACH
1600
            ** is executed, this is done before the ATTACH operation.
1601
            **
1602
            ** In the second form this pragma sets the text encoding to be used in
1603
            ** new database files created using this database handle. It is only
1604
            ** useful if invoked immediately after the main database i
1605
            */
1606
            case PragTyp_ENCODING: {
1607
                static const struct EncName {
1608
                    char *zName;
1609
                    u8 enc;
1610
                } encnames[] = {
1611
                        {"UTF8",  SQLITE_UTF8},
1612
                        {"UTF-8", SQLITE_UTF8},  /* Must be element [1] */
1613
                        {0, 0}
1614
                };
1615
                const struct EncName *pEnc;
1616
                if (!zRight) {    /* "PRAGMA encoding" */
5✔
1617
                    if (sqlite3ReadSchema(pParse)) goto pragma_out;
2✔
1618
                    assert(encnames[SQLITE_UTF8].enc == SQLITE_UTF8);
2✔
1619
                    returnSingleText(v, encnames[ENC(pParse->db)].zName);
2✔
1620
                } else {                        /* "PRAGMA encoding = XXX" */
1621
                    /* Only change the value of sqlite.enc if the database handle is not
1622
                    ** initialized. If the main database exists, the new sqlite.enc value
1623
                    ** will be overwritten when the schema is next loaded. If it does not
1624
                    ** already exists, it will be created to use the new encoding value.
1625
                    */
1626
                    if (
3✔
1627
                            !(DbHasProperty(db, DB_SchemaLoaded)) ||
6✔
1628
                            DbHasProperty(db, DB_Empty)
3✔
1629
                            ) {
1630
                        for (pEnc = &encnames[0]; pEnc->zName; pEnc++) {
3✔
1631
                            if (0 == sqlite3StrICmp(zRight, pEnc->zName)) {
3✔
1632
                                SCHEMA_ENC(db) = ENC(db) =
6✔
1633
                                        pEnc->enc;
3✔
1634
                                break;
3✔
1635
                            }
1636
                        }
1637
                        if (!pEnc->zName) {
3✔
1638
                            sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
×
1639
                        }
1640
                    }
1641
                }
1642
            }
1643
            break;
5✔
1644

1645
#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
1646
            /*
1647
            **   PRAGMA [schema.]schema_version
1648
            **   PRAGMA [schema.]schema_version = <integer>
1649
            **
1650
            **   PRAGMA [schema.]user_version
1651
            **   PRAGMA [schema.]user_version = <integer>
1652
            **
1653
            **   PRAGMA [schema.]freelist_count
1654
            **
1655
            **   PRAGMA [schema.]data_version
1656
            **
1657
            **   PRAGMA [schema.]application_id
1658
            **   PRAGMA [schema.]application_id = <integer>
1659
            **
1660
            ** The pragma's schema_version and user_version are used to set or get
1661
            ** the value of the schema-version and user-version, respectively. Both
1662
            ** the schema-version and the user-version are 32-bit signed integers
1663
            ** stored in the database header.
1664
            **
1665
            ** The schema-cookie is usually only manipulated internally by SQLite. It
1666
            ** is incremented by SQLite whenever the database schema is modified (by
1667
            ** creating or dropping a table or index). The schema version is used by
1668
            ** SQLite each time a query is executed to ensure that the internal cache
1669
            ** of the schema used when compiling the SQL query matches the schema of
1670
            ** the database against which the compiled query is actually executed.
1671
            ** Subverting this mechanism by using "PRAGMA schema_version" to modify
1672
            ** the schema-version is potentially dangerous and may lead to program
1673
            ** crashes or database corruption. Use with caution!
1674
            **
1675
            ** The user-version is not used internally by SQLite. It may be used by
1676
            ** applications for any purpose.
1677
            */
1678
            case PragTyp_HEADER_VALUE: {
1679
                int iCookie = pPragma->iArg;  /* Which cookie to read or write */
×
1680
                sqlite3VdbeUsesBtree(v, iDb);
×
1681
                if (zRight && (pPragma->mPragFlg & PragFlg_ReadOnly) == 0) {
×
1682
                    /* Write the specified cookie value */
1683
                    static const VdbeOpList setCookie[] = {
1684
                            {OP_Transaction, 0, 1, 0},    /* 0 */
1685
                            {OP_SetCookie,   0, 0, 0},    /* 1 */
1686
                    };
1687
                    VdbeOp *aOp;
1688
                    sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
×
1689
                    aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
×
1690
                    if (ONLY_IF_REALLOC_STRESS(aOp == 0)) break;
×
1691
                    aOp[0].p1 = iDb;
×
1692
                    aOp[1].p1 = iDb;
×
1693
                    aOp[1].p2 = iCookie;
×
1694
                    aOp[1].p3 = sqlite3Atoi(zRight);
×
1695
                } else {
1696
                    /* Read the specified cookie value */
1697
                    static const VdbeOpList readCookie[] = {
1698
                            {OP_Transaction, 0, 0, 0},    /* 0 */
1699
                            {OP_ReadCookie,  0, 1, 0},    /* 1 */
1700
                            {OP_ResultRow,   1, 1, 0}
1701
                    };
1702
                    VdbeOp *aOp;
1703
                    sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
×
1704
                    aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
×
1705
                    if (ONLY_IF_REALLOC_STRESS(aOp == 0)) break;
×
1706
                    aOp[0].p1 = iDb;
×
1707
                    aOp[1].p1 = iDb;
×
1708
                    aOp[1].p3 = iCookie;
×
1709
                    sqlite3VdbeReusable(v);
×
1710
                }
1711
            }
1712
            break;
×
1713
#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
1714

1715
#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
1716
            /*
1717
            **   PRAGMA compile_options
1718
            **
1719
            ** Return the names of all compile-time options used in this build,
1720
            ** one option per row.
1721
            */
1722
            case PragTyp_COMPILE_OPTIONS: {
1723
                int i = 0;
×
1724
                const char *zOpt;
1725
                pParse->nMem = 1;
×
1726
                while ((zOpt = sqlite3_compileoption_get(i++)) != 0) {
×
1727
                    sqlite3VdbeLoadString(v, 1, zOpt);
×
1728
                    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
×
1729
                }
1730
                sqlite3VdbeReusable(v);
×
1731
            }
1732
            break;
×
1733
#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
1734

1735
/* Tarantool: TODO: comment this so far, since native SQLite WAL was remoced.
1736
   This might be used with native Tarantool's WAL.  */
1737
#if 0
1738
            /*
1739
            **   PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
1740
            **
1741
            ** Checkpoint the database.
1742
            */
1743
            case PragTyp_WAL_CHECKPOINT: {
1744
              int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
1745
              int eMode = SQLITE_CHECKPOINT_PASSIVE;
1746
              if( zRight ){
1747
                if( sqlite3StrICmp(zRight, "full")==0 ){
1748
                  eMode = SQLITE_CHECKPOINT_FULL;
1749
                }else if( sqlite3StrICmp(zRight, "restart")==0 ){
1750
                  eMode = SQLITE_CHECKPOINT_RESTART;
1751
                }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
1752
                  eMode = SQLITE_CHECKPOINT_TRUNCATE;
1753
                }
1754
              }
1755
              pParse->nMem = 3;
1756
              sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
1757
              sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
1758
            }
1759
            break;
1760

1761
            /*
1762
            **   PRAGMA wal_autocheckpoint
1763
            **   PRAGMA wal_autocheckpoint = N
1764
            **
1765
            ** Configure a database connection to automatically checkpoint a database
1766
            ** after accumulating N frames in the log. Or query for the current value
1767
            ** of N.
1768
            */
1769
            case PragTyp_WAL_AUTOCHECKPOINT: {
1770
              if( zRight ){
1771
                sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
1772
              }
1773
              returnSingleInt(v,
1774
                 db->xWalCallback==sqlite3WalDefaultHook ?
1775
                     SQLITE_PTR_TO_INT(db->pWalArg) : 0);
1776
            }
1777
            break;
1778
#endif
1779

1780
            /*
1781
            **  PRAGMA shrink_memory
1782
            **
1783
            ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
1784
            ** connection on which it is invoked to free up as much memory as it
1785
            ** can, by calling sqlite3_db_release_memory().
1786
            */
1787
            case PragTyp_SHRINK_MEMORY: {
1788
                sqlite3_db_release_memory(db);
×
1789
                break;
×
1790
            }
1791

1792
            /*
1793
            **   PRAGMA busy_timeout
1794
            **   PRAGMA busy_timeout = N
1795
            **
1796
            ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
1797
            ** if one is set.  If no busy handler or a different busy handler is set
1798
            ** then 0 is returned.  Setting the busy_timeout to 0 or negative
1799
            ** disables the timeout.
1800
            */
1801
            /*case PragTyp_BUSY_TIMEOUT*/ default: {
1802
                assert(pPragma->ePragTyp == PragTyp_BUSY_TIMEOUT);
×
1803
                if (zRight) {
×
1804
                    sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
×
1805
                }
1806
                returnSingleInt(v, db->busyTimeout);
×
1807
                break;
×
1808
            }
1809

1810
            /*
1811
            **   PRAGMA soft_heap_limit
1812
            **   PRAGMA soft_heap_limit = N
1813
            **
1814
            ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
1815
            ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
1816
            ** specified and is a non-negative integer.
1817
            ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
1818
            ** returns the same integer that would be returned by the
1819
            ** sqlite3_soft_heap_limit64(-1) C-language function.
1820
            */
1821
            case PragTyp_SOFT_HEAP_LIMIT: {
1822
                sqlite3_int64 N;
1823
                if (zRight && sqlite3DecOrHexToI64(zRight, &N) == SQLITE_OK) {
×
1824
                    sqlite3_soft_heap_limit64(N);
×
1825
                }
1826
                returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
×
1827
                break;
×
1828
            }
1829

1830
            /*
1831
            **   PRAGMA threads
1832
            **   PRAGMA threads = N
1833
            **
1834
            ** Configure the maximum number of worker threads.  Return the new
1835
            ** maximum, which might be less than requested.
1836
            */
1837
            case PragTyp_THREADS: {
1838
                sqlite3_int64 N;
1839
                if (zRight
×
1840
                    && sqlite3DecOrHexToI64(zRight, &N) == SQLITE_OK
×
1841
                    && N >= 0
×
1842
                        ) {
1843
                    sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int) (N & 0x7fffffff));
×
1844
                }
1845
                returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
×
1846
                break;
×
1847
            }
1848

1849
#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
1850
            /*
1851
            ** Report the current state of file logs for all databases
1852
            */
1853
            case PragTyp_LOCK_STATUS: {
1854
                static const char *const azLockName[] = {
1855
                        "unlocked", "shared", "reserved", "pending", "exclusive"
1856
                };
1857
                pParse->nMem = 2;
×
1858
                Btree *pBt;
1859
                const char *zState = "unknown";
×
1860
                int j;
1861
                assert(db->mdb.zDbSName);
×
1862
                pBt = db->mdb.pBt;
×
1863
                if (pBt == 0 || sqlite3BtreePager(pBt) == 0) {
×
1864
                    zState = "closed";
×
1865
                } else if (sqlite3_file_control(db, 0 ? db->mdb.zDbSName : 0,
×
1866
                                                SQLITE_FCNTL_LOCKSTATE, &j) == SQLITE_OK) {
1867
                    zState = azLockName[j];
×
1868
                }
1869
                sqlite3VdbeMultiLoad(v, 1, "ss", db->mdb.zDbSName, zState);
×
1870
                sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
×
1871
                break;
×
1872
            }
1873
#endif
1874

1875
#ifdef SQLITE_HAS_CODEC
1876
            case PragTyp_KEY: {
1877
              if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
1878
              break;
1879
            }
1880
            case PragTyp_REKEY: {
1881
              if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
1882
              break;
1883
            }
1884
            case PragTyp_HEXKEY: {
1885
              if( zRight ){
1886
                u8 iByte;
1887
                int i;
1888
                char zKey[40];
1889
                for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
1890
                  iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
1891
                  if( (i&1)!=0 ) zKey[i/2] = iByte;
1892
                }
1893
                if( (zLeft[3] & 0xf)==0xb ){
1894
                  sqlite3_key_v2(db, zDb, zKey, i/2);
1895
                }else{
1896
                  sqlite3_rekey_v2(db, zDb, zKey, i/2);
1897
                }
1898
              }
1899
              break;
1900
            }
1901
#endif
1902
#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
1903
            case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
1904
#ifdef SQLITE_HAS_CODEC
1905
              if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
1906
                sqlite3_activate_see(&zRight[4]);
1907
              }
1908
#endif
1909
#ifdef SQLITE_ENABLE_CEROD
1910
              if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
1911
                sqlite3_activate_cerod(&zRight[6]);
1912
              }
1913
#endif
1914
            }
1915
            break;
1916
#endif
1917

1918
        } /* End of the PRAGMA switch */
1919

1920
            /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
1921
            ** purpose is to execute assert() statements to verify that if the
1922
            ** PragFlg_NoColumns1 flag is set and the caller specified an argument
1923
            ** to the PRAGMA, the implementation has not added any OP_ResultRow
1924
            ** instructions to the VM.  */
1925
            if ((pPragma->mPragFlg & PragFlg_NoColumns1) && zRight) {
1926
                sqlite3VdbeVerifyNoResultRow(v);
1927
            }
1928

1929
        pragma_out:
1930
            sqlite3DbFree(db, zLeft);
×
1931
            sqlite3DbFree(db, zRight);
×
1932
    }
1933
}
1934
#ifndef SQLITE_OMIT_VIRTUALTABLE
1935
/*****************************************************************************
1936
** Implementation of an eponymous virtual table that runs a pragma.
1937
**
1938
*/
1939
typedef struct PragmaVtab PragmaVtab;
1940
typedef struct PragmaVtabCursor PragmaVtabCursor;
1941
struct PragmaVtab {
1942
  sqlite3_vtab base;        /* Base class.  Must be first */
1943
  sqlite3 *db;              /* The database connection to which it belongs */
1944
  const PragmaName *pName;  /* Name of the pragma */
1945
  u8 nHidden;               /* Number of hidden columns */
1946
  u8 iHidden;               /* Index of the first hidden column */
1947
};
1948
struct PragmaVtabCursor {
1949
  sqlite3_vtab_cursor base; /* Base class.  Must be first */
1950
  sqlite3_stmt *pPragma;    /* The pragma statement to run */
1951
  sqlite_int64 iRowid;      /* Current rowid */
1952
  char *azArg[2];           /* Value of the argument and schema */
1953
};
1954

1955
/* 
1956
** Pragma virtual table module xConnect method.
1957
*/
1958
static int pragmaVtabConnect(
×
1959
  sqlite3 *db,
1960
  void *pAux,
1961
  int argc, const char *const*argv,
1962
  sqlite3_vtab **ppVtab,
1963
  char **pzErr
1964
){
1965
  const PragmaName *pPragma = (const PragmaName*)pAux;
×
1966
  PragmaVtab *pTab = 0;
×
1967
  int rc;
1968
  int i, j;
1969
  char cSep = '(';
×
1970
  StrAccum acc;
1971
  char zBuf[200];
1972

1973
  UNUSED_PARAMETER(argc);
1974
  UNUSED_PARAMETER(argv);
1975
  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
×
1976
  sqlite3StrAccumAppendAll(&acc, "CREATE TABLE x");
×
1977
  for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
×
1978
    sqlite3XPrintf(&acc, "%c\"%s\"", cSep, pragCName[j]);
×
1979
    cSep = ',';
×
1980
  }
1981
  if( i==0 ){
×
1982
    sqlite3XPrintf(&acc, "(\"%s\"", pPragma->zName);
×
1983
    cSep = ',';
×
1984
    i++;
×
1985
  }
1986
  j = 0;
×
1987
  if( pPragma->mPragFlg & PragFlg_Result1 ){
×
1988
    sqlite3StrAccumAppendAll(&acc, ",arg HIDDEN");
×
1989
    j++;
×
1990
  }
1991
  if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
×
1992
    sqlite3StrAccumAppendAll(&acc, ",schema HIDDEN");
×
1993
    j++;
×
1994
  }
1995
  sqlite3StrAccumAppend(&acc, ")", 1);
×
1996
  sqlite3StrAccumFinish(&acc);
×
1997
  assert( strlen(zBuf) < sizeof(zBuf)-1 );
×
1998
  rc = sqlite3_declare_vtab(db, zBuf);
×
1999
  if( rc==SQLITE_OK ){
×
2000
    pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
×
2001
    if( pTab==0 ){
×
2002
      rc = SQLITE_NOMEM;
×
2003
    }else{
2004
      memset(pTab, 0, sizeof(PragmaVtab));
×
2005
      pTab->pName = pPragma;
×
2006
      pTab->db = db;
×
2007
      pTab->iHidden = i;
×
2008
      pTab->nHidden = j;
×
2009
    }
2010
  }else{
2011
    *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
×
2012
  }
2013

2014
  *ppVtab = (sqlite3_vtab*)pTab;
×
2015
  return rc;
×
2016
}
2017

2018
/* 
2019
** Pragma virtual table module xDisconnect method.
2020
*/
2021
static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
×
2022
  PragmaVtab *pTab = (PragmaVtab*)pVtab;
×
2023
  sqlite3_free(pTab);
×
2024
  return SQLITE_OK;
×
2025
}
2026

2027
/* Figure out the best index to use to search a pragma virtual table.
2028
**
2029
** There are not really any index choices.  But we want to encourage the
2030
** query planner to give == constraints on as many hidden parameters as
2031
** possible, and especially on the first hidden parameter.  So return a
2032
** high cost if hidden parameters are unconstrained.
2033
*/
2034
static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
×
2035
  PragmaVtab *pTab = (PragmaVtab*)tab;
×
2036
  const struct sqlite3_index_constraint *pConstraint;
2037
  int i, j;
2038
  int seen[2];
2039

2040
  pIdxInfo->estimatedCost = (double)1;
×
2041
  if( pTab->nHidden==0 ){ return SQLITE_OK; }
×
2042
  pConstraint = pIdxInfo->aConstraint;
×
2043
  seen[0] = 0;
×
2044
  seen[1] = 0;
×
2045
  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
×
2046
    if( pConstraint->usable==0 ) continue;
×
2047
    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
×
2048
    if( pConstraint->iColumn < pTab->iHidden ) continue;
×
2049
    j = pConstraint->iColumn - pTab->iHidden;
×
2050
    assert( j < 2 );
×
2051
    seen[j] = i+1;
×
2052
  }
2053
  if( seen[0]==0 ){
×
2054
    pIdxInfo->estimatedCost = (double)2147483647;
×
2055
    pIdxInfo->estimatedRows = 2147483647;
×
2056
    return SQLITE_OK;
×
2057
  }
2058
  j = seen[0]-1;
×
2059
  pIdxInfo->aConstraintUsage[j].argvIndex = 1;
×
2060
  pIdxInfo->aConstraintUsage[j].omit = 1;
×
2061
  if( seen[1]==0 ) return SQLITE_OK;
×
2062
  pIdxInfo->estimatedCost = (double)20;
×
2063
  pIdxInfo->estimatedRows = 20;
×
2064
  j = seen[1]-1;
×
2065
  pIdxInfo->aConstraintUsage[j].argvIndex = 2;
×
2066
  pIdxInfo->aConstraintUsage[j].omit = 1;
×
2067
  return SQLITE_OK;
×
2068
}
2069

2070
/* Create a new cursor for the pragma virtual table */
2071
static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
×
2072
  PragmaVtabCursor *pCsr;
2073
  pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
×
2074
  if( pCsr==0 ) return SQLITE_NOMEM;
×
2075
  memset(pCsr, 0, sizeof(PragmaVtabCursor));
×
2076
  pCsr->base.pVtab = pVtab;
×
2077
  *ppCursor = &pCsr->base;
×
2078
  return SQLITE_OK;
×
2079
}
2080

2081
/* Clear all content from pragma virtual table cursor. */
2082
static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
×
2083
  int i;
2084
  sqlite3_finalize(pCsr->pPragma);
×
2085
  pCsr->pPragma = 0;
×
2086
  for(i=0; i<ArraySize(pCsr->azArg); i++){
×
2087
    sqlite3_free(pCsr->azArg[i]);
×
2088
    pCsr->azArg[i] = 0;
×
2089
  }
2090
}
×
2091

2092
/* Close a pragma virtual table cursor */
2093
static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
×
2094
  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
×
2095
  pragmaVtabCursorClear(pCsr);
×
2096
  sqlite3_free(pCsr);
×
2097
  return SQLITE_OK;
×
2098
}
2099

2100
/* Advance the pragma virtual table cursor to the next row */
2101
static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
×
2102
  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
×
2103
  int rc = SQLITE_OK;
×
2104

2105
  /* Increment the xRowid value */
2106
  pCsr->iRowid++;
×
2107
  assert( pCsr->pPragma );
×
2108
  if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
×
2109
    rc = sqlite3_finalize(pCsr->pPragma);
×
2110
    pCsr->pPragma = 0;
×
2111
    pragmaVtabCursorClear(pCsr);
×
2112
  }
2113
  return rc;
×
2114
}
2115

2116
/* 
2117
** Pragma virtual table module xFilter method.
2118
*/
2119
static int pragmaVtabFilter(
×
2120
  sqlite3_vtab_cursor *pVtabCursor, 
2121
  int idxNum, const char *idxStr,
2122
  int argc, sqlite3_value **argv
2123
){
2124
  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
×
2125
  PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
×
2126
  int rc;
2127
  int i, j;
2128
  StrAccum acc;
2129
  char *zSql;
2130

2131
  UNUSED_PARAMETER(idxNum);
2132
  UNUSED_PARAMETER(idxStr);
2133
  pragmaVtabCursorClear(pCsr);
×
2134
  j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
×
2135
  for(i=0; i<argc; i++, j++){
×
2136
    assert( j<ArraySize(pCsr->azArg) );
×
2137
    pCsr->azArg[j] = sqlite3_mprintf("%s", sqlite3_value_text(argv[i]));
×
2138
    if( pCsr->azArg[j]==0 ){
×
2139
      return SQLITE_NOMEM;
×
2140
    }
2141
  }
2142
  sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
×
2143
  sqlite3StrAccumAppendAll(&acc, "PRAGMA ");
×
2144
  if( pCsr->azArg[1] ){
×
2145
    sqlite3XPrintf(&acc, "%Q.", pCsr->azArg[1]);
×
2146
  }
2147
  sqlite3StrAccumAppendAll(&acc, pTab->pName->zName);
×
2148
  if( pCsr->azArg[0] ){
×
2149
    sqlite3XPrintf(&acc, "=%Q", pCsr->azArg[0]);
×
2150
  }
2151
  zSql = sqlite3StrAccumFinish(&acc);
×
2152
  if( zSql==0 ) return SQLITE_NOMEM;
×
2153
  rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
×
2154
  sqlite3_free(zSql);
×
2155
  if( rc!=SQLITE_OK ){
×
2156
    pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
×
2157
    return rc;
×
2158
  }
2159
  return pragmaVtabNext(pVtabCursor);
×
2160
}
2161

2162
/*
2163
** Pragma virtual table module xEof method.
2164
*/
2165
static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
×
2166
  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
×
2167
  return (pCsr->pPragma==0);
×
2168
}
2169

2170
/* The xColumn method simply returns the corresponding column from
2171
** the PRAGMA.  
2172
*/
2173
static int pragmaVtabColumn(
×
2174
  sqlite3_vtab_cursor *pVtabCursor, 
2175
  sqlite3_context *ctx, 
2176
  int i
2177
){
2178
  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
×
2179
  PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
×
2180
  if( i<pTab->iHidden ){
×
2181
    sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
×
2182
  }else{
2183
    sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
×
2184
  }
2185
  return SQLITE_OK;
×
2186
}
2187

2188
/* 
2189
** Pragma virtual table module xRowid method.
2190
*/
2191
static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
×
2192
  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
×
2193
  *p = pCsr->iRowid;
×
2194
  return SQLITE_OK;
×
2195
}
2196

2197
/* The pragma virtual table object */
2198
static const sqlite3_module pragmaVtabModule = {
2199
  0,                           /* iVersion */
2200
  0,                           /* xCreate - create a table */
2201
  pragmaVtabConnect,           /* xConnect - connect to an existing table */
2202
  pragmaVtabBestIndex,         /* xBestIndex - Determine search strategy */
2203
  pragmaVtabDisconnect,        /* xDisconnect - Disconnect from a table */
2204
  0,                           /* xDestroy - Drop a table */
2205
  pragmaVtabOpen,              /* xOpen - open a cursor */
2206
  pragmaVtabClose,             /* xClose - close a cursor */
2207
  pragmaVtabFilter,            /* xFilter - configure scan constraints */
2208
  pragmaVtabNext,              /* xNext - advance a cursor */
2209
  pragmaVtabEof,               /* xEof */
2210
  pragmaVtabColumn,            /* xColumn - read data */
2211
  pragmaVtabRowid,             /* xRowid - read data */
2212
  0,                           /* xUpdate - write data */
2213
  0,                           /* xBegin - begin transaction */
2214
  0,                           /* xSync - sync transaction */
2215
  0,                           /* xCommit - commit transaction */
2216
  0,                           /* xRollback - rollback transaction */
2217
  0,                           /* xFindFunction - function overloading */
2218
  0,                           /* xRename - rename the table */
2219
  0,                           /* xSavepoint */
2220
  0,                           /* xRelease */
2221
  0                            /* xRollbackTo */
2222
};
2223

2224
/*
2225
** Check to see if zTabName is really the name of a pragma.  If it is,
2226
** then register an eponymous virtual table for that pragma and return
2227
** a pointer to the Module object for the new virtual table.
2228
*/
2229
Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
×
2230
  const PragmaName *pName;
2231
  assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
×
2232
  pName = pragmaLocate(zName+7);
×
2233
  if( pName==0 ) return 0;
×
2234
  if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
×
2235
  assert( sqlite3HashFind(&db->aModule, zName)==0 );
×
2236
  return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
×
2237
}
2238

2239
#endif /* SQLITE_OMIT_VIRTUALTABLE */
2240

2241
#endif /* SQLITE_OMIT_PRAGMA */
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc