SQLite4
Check-in [df818c275b]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Merge trunk changes.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | embedded-btree
Files: files | file ages | folders
SHA1: df818c275b1977c6ea4bd3786a9159e7d2c4df2a
User & Date: dan 2012-06-22 18:06:42
Context
2012-06-23
10:04
Add untested functions to save and restore b-tree cursor positions. check-in: cc0b45d17e user: dan tags: embedded-btree
2012-06-22
18:06
Merge trunk changes. check-in: df818c275b user: dan tags: embedded-btree
17:57
Add functions to iterate through b-tree keys. Also a complex assert statement to check that b-trees are correct with respect to the main run content. check-in: 29d761c438 user: dan tags: embedded-btree
16:55
Modify sqlite4_mem_methods to remove xRoundup, add the Benign methods, and for all methods to take an environment pointer as their first argument. check-in: 949cb749fe user: drh tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to main.mk.

64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
...
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
         opcodes.o os.o \
         parse.o pragma.o prepare.o printf.o \
         random.o resolve.o rowset.o rtree.o select.o status.o storage.o \
         tokenize.o trigger.o \
         update.o util.o varint.o \
         vdbe.o vdbeapi.o vdbeaux.o vdbecodec.o vdbecursor.o \
         vdbemem.o vdbetrace.o \
         walker.o where.o utf.o vtab.o

# All of the source code files.
#
SRC = \
  $(TOP)/src/alter.c \
  $(TOP)/src/analyze.c \
  $(TOP)/src/attach.c \
................................................................................
#
TESTSRC = \
  $(TOP)/ext/fts3/fts3_term.c \
  $(TOP)/ext/fts3/fts3_test.c \
  $(TOP)/test/test_main.c \
  $(TOP)/test/test_thread0.c \
  $(TOP)/test/test_utf.c \
  $(TOP)/test/test_echo.c \
  $(TOP)/test/test_misc1.c \
  $(TOP)/test/test_config.c \
  $(TOP)/test/test_func.c \
  $(TOP)/test/test_fuzzer.c \
  $(TOP)/test/test_hexio.c \
  $(TOP)/test/test_intarray.c \
  $(TOP)/test/test_lsm.c \
  $(TOP)/test/test_malloc.c \
  $(TOP)/test/test_mutex.c \
  $(TOP)/test/test_rtree.c \
  $(TOP)/test/test_schema.c \
  $(TOP)/test/test_storage.c \
  $(TOP)/test/test_storage2.c \
  $(TOP)/test/test_tclvar.c \
  $(TOP)/test/test_thread.c \
  $(TOP)/test/test_wholenumber.c \
  $(TOP)/test/test_wsd.c

#TESTSRC += $(TOP)/ext/fts2/fts2_tokenizer.c
#TESTSRC += $(TOP)/ext/fts3/fts3_tokenizer.c

TESTSRC2 = \
  $(TOP)/src/attach.c \







|







 







<



<

<



<
<


<

<







64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
...
198
199
200
201
202
203
204

205
206
207

208

209
210
211


212
213

214

215
216
217
218
219
220
221
         opcodes.o os.o \
         parse.o pragma.o prepare.o printf.o \
         random.o resolve.o rowset.o rtree.o select.o status.o storage.o \
         tokenize.o trigger.o \
         update.o util.o varint.o \
         vdbe.o vdbeapi.o vdbeaux.o vdbecodec.o vdbecursor.o \
         vdbemem.o vdbetrace.o \
         walker.o where.o utf.o

# All of the source code files.
#
SRC = \
  $(TOP)/src/alter.c \
  $(TOP)/src/analyze.c \
  $(TOP)/src/attach.c \
................................................................................
#
TESTSRC = \
  $(TOP)/ext/fts3/fts3_term.c \
  $(TOP)/ext/fts3/fts3_test.c \
  $(TOP)/test/test_main.c \
  $(TOP)/test/test_thread0.c \
  $(TOP)/test/test_utf.c \

  $(TOP)/test/test_misc1.c \
  $(TOP)/test/test_config.c \
  $(TOP)/test/test_func.c \

  $(TOP)/test/test_hexio.c \

  $(TOP)/test/test_lsm.c \
  $(TOP)/test/test_malloc.c \
  $(TOP)/test/test_mutex.c \


  $(TOP)/test/test_storage.c \
  $(TOP)/test/test_storage2.c \

  $(TOP)/test/test_thread.c \

  $(TOP)/test/test_wsd.c

#TESTSRC += $(TOP)/ext/fts2/fts2_tokenizer.c
#TESTSRC += $(TOP)/ext/fts3/fts3_tokenizer.c

TESTSRC2 = \
  $(TOP)/src/attach.c \

Changes to src/analyze.c.

245
246
247
248
249
250
251

252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
...
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
....
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
  int argc,
  sqlite4_value **argv
){
  Stat3Accum *p;
  tRowcnt nRow;
  int mxSample;
  int n;


  UNUSED_PARAMETER(argc);
  nRow = (tRowcnt)sqlite4_value_int64(argv[0]);
  mxSample = sqlite4_value_int(argv[1]);
  n = sizeof(*p) + sizeof(p->a[0])*mxSample;
  p = sqlite4_malloc( n );
  if( p==0 ){
    sqlite4_result_error_nomem(context);
    return;
  }
  memset(p, 0, n);
  p->a = (struct Stat3Sample*)&p[1];
  p->nRow = nRow;
  p->mxSample = mxSample;
  p->nPSample = p->nRow/(mxSample/3+1) + 1;
  sqlite4_randomness(sizeof(p->iPrn), &p->iPrn);
  sqlite4_result_blob(context, p, sizeof(p), sqlite4_free);
}
static const FuncDef stat3InitFuncdef = {
  2,                /* nArg */
  SQLITE_UTF8,      /* iPrefEnc */
  0,                /* flags */
  0,                /* pUserData */
  0,                /* pNext */
................................................................................
    zIndex = (char *)sqlite4_column_text(pStmt, 0);
    if( zIndex==0 ) continue;
    nSample = sqlite4_column_int(pStmt, 1);
    pIdx = sqlite4FindIndex(db, zIndex, zDb);
    if( pIdx==0 ) continue;
    assert( pIdx->nSample==0 );
    pIdx->nSample = nSample;
    pIdx->aSample = sqlite4MallocZero( nSample*sizeof(IndexSample) );
    pIdx->avgEq = pIdx->aiRowEst[1];
    if( pIdx->aSample==0 ){
      db->mallocFailed = 1;
      sqlite4_finalize(pStmt);
      return SQLITE_NOMEM;
    }
  }
................................................................................
              sqlite4_column_text(pStmt, 4)
           );
        int n = z ? sqlite4_column_bytes(pStmt, 4) : 0;
        pSample->nByte = n;
        if( n < 1){
          pSample->u.z = 0;
        }else{
          pSample->u.z = sqlite4Malloc(n);
          if( pSample->u.z==0 ){
            db->mallocFailed = 1;
            sqlite4_finalize(pStmt);
            return SQLITE_NOMEM;
          }
          memcpy(pSample->u.z, z, n);
        }







>





|









|
|







 







|







 







|







245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
...
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
....
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
  int argc,
  sqlite4_value **argv
){
  Stat3Accum *p;
  tRowcnt nRow;
  int mxSample;
  int n;
  sqlite4_env *pEnv = sqlite4_context_env(context);

  UNUSED_PARAMETER(argc);
  nRow = (tRowcnt)sqlite4_value_int64(argv[0]);
  mxSample = sqlite4_value_int(argv[1]);
  n = sizeof(*p) + sizeof(p->a[0])*mxSample;
  p = sqlite4_malloc(pEnv, n);
  if( p==0 ){
    sqlite4_result_error_nomem(context);
    return;
  }
  memset(p, 0, n);
  p->a = (struct Stat3Sample*)&p[1];
  p->nRow = nRow;
  p->mxSample = mxSample;
  p->nPSample = p->nRow/(mxSample/3+1) + 1;
  sqlite4_randomness(pEnv, sizeof(p->iPrn), &p->iPrn);
  sqlite4_result_blob(context, p, sizeof(p), SQLITE_DYNAMIC);
}
static const FuncDef stat3InitFuncdef = {
  2,                /* nArg */
  SQLITE_UTF8,      /* iPrefEnc */
  0,                /* flags */
  0,                /* pUserData */
  0,                /* pNext */
................................................................................
    zIndex = (char *)sqlite4_column_text(pStmt, 0);
    if( zIndex==0 ) continue;
    nSample = sqlite4_column_int(pStmt, 1);
    pIdx = sqlite4FindIndex(db, zIndex, zDb);
    if( pIdx==0 ) continue;
    assert( pIdx->nSample==0 );
    pIdx->nSample = nSample;
    pIdx->aSample = sqlite4MallocZero(db->pEnv, nSample*sizeof(IndexSample) );
    pIdx->avgEq = pIdx->aiRowEst[1];
    if( pIdx->aSample==0 ){
      db->mallocFailed = 1;
      sqlite4_finalize(pStmt);
      return SQLITE_NOMEM;
    }
  }
................................................................................
              sqlite4_column_text(pStmt, 4)
           );
        int n = z ? sqlite4_column_bytes(pStmt, 4) : 0;
        pSample->nByte = n;
        if( n < 1){
          pSample->u.z = 0;
        }else{
          pSample->u.z = sqlite4Malloc(db->pEnv, n);
          if( pSample->u.z==0 ){
            db->mallocFailed = 1;
            sqlite4_finalize(pStmt);
            return SQLITE_NOMEM;
          }
          memcpy(pSample->u.z, z, n);
        }

Changes to src/attach.c.

128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
...
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
  ** or may not be initialised.
  */
  flags = db->openFlags;
  rc = sqlite4ParseUri(db->pEnv, zFile, &flags, &zPath, &zErr);
  if( rc!=SQLITE_OK ){
    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
    sqlite4_result_error(context, zErr, -1);
    sqlite4_free(zErr);
    return;
  }
  flags |= SQLITE_OPEN_MAIN_DB;
  rc = sqlite4KVStoreOpen(db, zName, zPath, &aNew->pKV, 0);
  sqlite4_free( zPath );
  db->nDb++;
  if( rc==SQLITE_CONSTRAINT ){
    rc = SQLITE_ERROR;
    zErrDyn = sqlite4MPrintf(db, "database is already attached");
  }else if( rc==SQLITE_OK ){
    aNew->pSchema = sqlite4SchemaGet(db);
    if( !aNew->pSchema ){
................................................................................
  for(i=0; i<db->nDb; i++){
    pDb = &db->aDb[i];
    if( pDb->pKV==0 ) continue;
    if( sqlite4StrICmp(pDb->zName, zName)==0 ) break;
  }

  if( i>=db->nDb ){
    sqlite4_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
    goto detach_error;
  }
  if( i<2 ){
    sqlite4_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
    goto detach_error;
  }
  if( db->pSavepoint ){
    sqlite4_snprintf(sizeof(zErr), zErr,
                     "cannot DETACH database within transaction");
    goto detach_error;
  }
  if( pDb->pKV->iTransLevel ){
    sqlite4_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
    goto detach_error;
  }

  sqlite4KVStoreClose(pDb->pKV);
  pDb->pKV = 0;
  pDb->pSchema = 0;
  sqlite4ResetInternalSchema(db, -1);







|




|







 







|



|



|




|







128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
...
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
  ** or may not be initialised.
  */
  flags = db->openFlags;
  rc = sqlite4ParseUri(db->pEnv, zFile, &flags, &zPath, &zErr);
  if( rc!=SQLITE_OK ){
    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
    sqlite4_result_error(context, zErr, -1);
    sqlite4_free(db->pEnv, zErr);
    return;
  }
  flags |= SQLITE_OPEN_MAIN_DB;
  rc = sqlite4KVStoreOpen(db, zName, zPath, &aNew->pKV, 0);
  sqlite4_free(db->pEnv, zPath);
  db->nDb++;
  if( rc==SQLITE_CONSTRAINT ){
    rc = SQLITE_ERROR;
    zErrDyn = sqlite4MPrintf(db, "database is already attached");
  }else if( rc==SQLITE_OK ){
    aNew->pSchema = sqlite4SchemaGet(db);
    if( !aNew->pSchema ){
................................................................................
  for(i=0; i<db->nDb; i++){
    pDb = &db->aDb[i];
    if( pDb->pKV==0 ) continue;
    if( sqlite4StrICmp(pDb->zName, zName)==0 ) break;
  }

  if( i>=db->nDb ){
    sqlite4_snprintf(zErr,sizeof(zErr), "no such database: %s", zName);
    goto detach_error;
  }
  if( i<2 ){
    sqlite4_snprintf(zErr,sizeof(zErr), "cannot detach database %s", zName);
    goto detach_error;
  }
  if( db->pSavepoint ){
    sqlite4_snprintf(zErr,sizeof(zErr),
                     "cannot DETACH database within transaction");
    goto detach_error;
  }
  if( pDb->pKV->iTransLevel ){
    sqlite4_snprintf(zErr,sizeof(zErr), "database %s is locked", zName);
    goto detach_error;
  }

  sqlite4KVStoreClose(pDb->pKV);
  pDb->pKV = 0;
  pDb->pSchema = 0;
  sqlite4ResetInternalSchema(db, -1);

Changes to src/build.c.

347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
....
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
....
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
....
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
  int i, j;
  assert( iDb<db->nDb );

  if( iDb>=0 ){
    /* Case 1:  Reset the single schema identified by iDb */
    Db *pDb = &db->aDb[iDb];
    assert( pDb->pSchema!=0 );
    sqlite4SchemaClear(pDb->pSchema);

    /* If any database other than TEMP is reset, then also reset TEMP
    ** since TEMP might be holding triggers that reference tables in the
    ** other database.
    */
    if( iDb!=1 ){
      pDb = &db->aDb[1];
      assert( pDb->pSchema!=0 );
      sqlite4SchemaClear(pDb->pSchema);
    }
    return;
  }
  /* Case 2 (from here to the end): Reset all schemas for all attached
  ** databases. */
  assert( iDb<0 );
  for(i=0; i<db->nDb; i++){
    Db *pDb = &db->aDb[i];
    if( pDb->pSchema ){
      sqlite4SchemaClear(pDb->pSchema);
    }
  }
  db->flags &= ~SQLITE_InternChanges;
  sqlite4VtabUnlockList(db);

  /* If one or more of the auxiliary database files has been closed,
  ** then remove them from the auxiliary database list.  We take the
................................................................................
  }
  n += 35 + 6*p->nCol;
  zStmt = sqlite4DbMallocRaw(0, n);
  if( zStmt==0 ){
    db->mallocFailed = 1;
    return 0;
  }
  sqlite4_snprintf(n, zStmt, "CREATE TABLE ");
  k = sqlite4Strlen30(zStmt);
  identPut(zStmt, &k, p->zName);
  zStmt[k++] = '(';
  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
    static const char * const azType[] = {
        /* SQLITE_AFF_TEXT    */ " TEXT",
        /* SQLITE_AFF_NONE    */ "",
        /* SQLITE_AFF_NUMERIC */ " NUM",
        /* SQLITE_AFF_INTEGER */ " INT",
        /* SQLITE_AFF_REAL    */ " REAL"
    };
    int len;
    const char *zType;

    sqlite4_snprintf(n-k, &zStmt[k], zSep);
    k += sqlite4Strlen30(&zStmt[k]);
    zSep = zSep2;
    identPut(zStmt, &k, pCol->zName);
    assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
    assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
    testcase( pCol->affinity==SQLITE_AFF_TEXT );
    testcase( pCol->affinity==SQLITE_AFF_NONE );
    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
................................................................................
    len = sqlite4Strlen30(zType);
    assert( pCol->affinity==SQLITE_AFF_NONE 
            || pCol->affinity==sqlite4AffinityType(zType) );
    memcpy(&zStmt[k], zType, len);
    k += len;
    assert( k<=n );
  }
  sqlite4_snprintf(n-k, &zStmt[k], "%s", zEnd);
  return zStmt;
}

static Index *newIndex(
  Parse *pParse,                  /* Parse context for current statement */
  Table *pTab,                    /* Table index is created on */
  const char *zName,              /* Name of index object to create */
................................................................................
  const char *zType,     /* "idx" or "tbl" */
  const char *zName      /* Name of index or table */
){
  int i;
  const char *zDbName = pParse->db->aDb[iDb].zName;
  for(i=1; i<=3; i++){
    char zTab[24];
    sqlite4_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
    if( sqlite4FindTable(pParse->db, zTab, zDbName) ){
      sqlite4NestedParse(pParse,
        "DELETE FROM %Q.%s WHERE %s=%Q",
        zDbName, zTab, zType, zName
      );
    }
  }







|








|









|







 







|
<













|
<







 







|







 







|







347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
....
1314
1315
1316
1317
1318
1319
1320
1321

1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335

1336
1337
1338
1339
1340
1341
1342
....
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
....
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
  int i, j;
  assert( iDb<db->nDb );

  if( iDb>=0 ){
    /* Case 1:  Reset the single schema identified by iDb */
    Db *pDb = &db->aDb[iDb];
    assert( pDb->pSchema!=0 );
    sqlite4SchemaClear(db->pEnv, pDb->pSchema);

    /* If any database other than TEMP is reset, then also reset TEMP
    ** since TEMP might be holding triggers that reference tables in the
    ** other database.
    */
    if( iDb!=1 ){
      pDb = &db->aDb[1];
      assert( pDb->pSchema!=0 );
      sqlite4SchemaClear(db->pEnv, pDb->pSchema);
    }
    return;
  }
  /* Case 2 (from here to the end): Reset all schemas for all attached
  ** databases. */
  assert( iDb<0 );
  for(i=0; i<db->nDb; i++){
    Db *pDb = &db->aDb[i];
    if( pDb->pSchema ){
      sqlite4SchemaClear(db->pEnv, pDb->pSchema);
    }
  }
  db->flags &= ~SQLITE_InternChanges;
  sqlite4VtabUnlockList(db);

  /* If one or more of the auxiliary database files has been closed,
  ** then remove them from the auxiliary database list.  We take the
................................................................................
  }
  n += 35 + 6*p->nCol;
  zStmt = sqlite4DbMallocRaw(0, n);
  if( zStmt==0 ){
    db->mallocFailed = 1;
    return 0;
  }
  k = sqlite4_snprintf(zStmt, n, "CREATE TABLE ");

  identPut(zStmt, &k, p->zName);
  zStmt[k++] = '(';
  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
    static const char * const azType[] = {
        /* SQLITE_AFF_TEXT    */ " TEXT",
        /* SQLITE_AFF_NONE    */ "",
        /* SQLITE_AFF_NUMERIC */ " NUM",
        /* SQLITE_AFF_INTEGER */ " INT",
        /* SQLITE_AFF_REAL    */ " REAL"
    };
    int len;
    const char *zType;

    k += sqlite4_snprintf(&zStmt[k], n-k, zSep);

    zSep = zSep2;
    identPut(zStmt, &k, pCol->zName);
    assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
    assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
    testcase( pCol->affinity==SQLITE_AFF_TEXT );
    testcase( pCol->affinity==SQLITE_AFF_NONE );
    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
................................................................................
    len = sqlite4Strlen30(zType);
    assert( pCol->affinity==SQLITE_AFF_NONE 
            || pCol->affinity==sqlite4AffinityType(zType) );
    memcpy(&zStmt[k], zType, len);
    k += len;
    assert( k<=n );
  }
  sqlite4_snprintf(&zStmt[k], n-k, "%s", zEnd);
  return zStmt;
}

static Index *newIndex(
  Parse *pParse,                  /* Parse context for current statement */
  Table *pTab,                    /* Table index is created on */
  const char *zName,              /* Name of index object to create */
................................................................................
  const char *zType,     /* "idx" or "tbl" */
  const char *zName      /* Name of index or table */
){
  int i;
  const char *zDbName = pParse->db->aDb[iDb].zName;
  for(i=1; i<=3; i++){
    char zTab[24];
    sqlite4_snprintf(zTab,sizeof(zTab),"sqlite_stat%d",i);
    if( sqlite4FindTable(pParse->db, zTab, zDbName) ){
      sqlite4NestedParse(pParse,
        "DELETE FROM %Q.%s WHERE %s=%Q",
        zDbName, zTab, zType, zName
      );
    }
  }

Changes to src/callback.c.

401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
...
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
** Free all resources held by the schema structure. The void* argument points
** at a Schema struct. This function does not call sqlite4DbFree(db, ) on the 
** pointer itself, it just cleans up subsidiary resources (i.e. the contents
** of the schema hash tables).
**
** The Schema.cache_size variable is not cleared.
*/
void sqlite4SchemaClear(Schema *pSchema){
  Hash temp1;
  Hash temp2;
  HashElem *pElem;

  temp1 = pSchema->tblHash;
  temp2 = pSchema->trigHash;
  sqlite4HashInit(&pSchema->trigHash);
  sqlite4HashClear(&pSchema->idxHash);
  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
    sqlite4DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  }
  sqlite4HashClear(&temp2);
  sqlite4HashInit(&pSchema->tblHash);
  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
    Table *pTab = sqliteHashData(pElem);
    sqlite4DeleteTable(0, pTab);
  }
  sqlite4HashClear(&temp1);
  sqlite4HashClear(&pSchema->fkeyHash);
  pSchema->pSeqTab = 0;
................................................................................
*/
Schema *sqlite4SchemaGet(sqlite4 *db){
  Schema * p;
  p = (Schema *)sqlite4DbMallocZero(0, sizeof(Schema));
  if( !p ){
    db->mallocFailed = 1;
  }else if ( 0==p->file_format ){
    sqlite4HashInit(&p->tblHash);
    sqlite4HashInit(&p->idxHash);
    sqlite4HashInit(&p->trigHash);
    sqlite4HashInit(&p->fkeyHash);
    p->enc = SQLITE_UTF8;
  }
  return p;
}







|






|





|







 







|
|
|
|




401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
...
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
** Free all resources held by the schema structure. The void* argument points
** at a Schema struct. This function does not call sqlite4DbFree(db, ) on the 
** pointer itself, it just cleans up subsidiary resources (i.e. the contents
** of the schema hash tables).
**
** The Schema.cache_size variable is not cleared.
*/
void sqlite4SchemaClear(sqlite4_env *pEnv, Schema *pSchema){
  Hash temp1;
  Hash temp2;
  HashElem *pElem;

  temp1 = pSchema->tblHash;
  temp2 = pSchema->trigHash;
  sqlite4HashInit(pEnv, &pSchema->trigHash);
  sqlite4HashClear(&pSchema->idxHash);
  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
    sqlite4DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  }
  sqlite4HashClear(&temp2);
  sqlite4HashInit(pEnv, &pSchema->tblHash);
  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
    Table *pTab = sqliteHashData(pElem);
    sqlite4DeleteTable(0, pTab);
  }
  sqlite4HashClear(&temp1);
  sqlite4HashClear(&pSchema->fkeyHash);
  pSchema->pSeqTab = 0;
................................................................................
*/
Schema *sqlite4SchemaGet(sqlite4 *db){
  Schema * p;
  p = (Schema *)sqlite4DbMallocZero(0, sizeof(Schema));
  if( !p ){
    db->mallocFailed = 1;
  }else if ( 0==p->file_format ){
    sqlite4HashInit(db->pEnv, &p->tblHash);
    sqlite4HashInit(db->pEnv, &p->idxHash);
    sqlite4HashInit(db->pEnv, &p->trigHash);
    sqlite4HashInit(db->pEnv, &p->fkeyHash);
    p->enc = SQLITE_UTF8;
  }
  return p;
}

Changes to src/date.c.

809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
...
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
...
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
...
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
  int argc,
  sqlite4_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    char zBuf[100];
    computeYMD_HMS(&x);
    sqlite4_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
    sqlite4_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  }
}

/*
**    time( TIMESTRING, MOD, MOD, ...)
................................................................................
  int argc,
  sqlite4_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    char zBuf[100];
    computeHMS(&x);
    sqlite4_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
    sqlite4_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  }
}

/*
**    date( TIMESTRING, MOD, MOD, ...)
**
................................................................................
  int argc,
  sqlite4_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    char zBuf[100];
    computeYMD(&x);
    sqlite4_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
    sqlite4_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  }
}

/*
**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
**
................................................................................
  computeYMD_HMS(&x);
  for(i=j=0; zFmt[i]; i++){
    if( zFmt[i]!='%' ){
      z[j++] = zFmt[i];
    }else{
      i++;
      switch( zFmt[i] ){
        case 'd':  sqlite4_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
        case 'f': {
          double s = x.s;
          if( s>59.999 ) s = 59.999;
          sqlite4_snprintf(7, &z[j],"%06.3f", s);
          j += sqlite4Strlen30(&z[j]);
          break;
        }
        case 'H':  sqlite4_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
        case 'W': /* Fall thru */
        case 'j': {
          int nDay;             /* Number of days since 1st day of year */
          DateTime y = x;
          y.validJD = 0;
          y.M = 1;
          y.D = 1;
          computeJD(&y);
          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
          if( zFmt[i]=='W' ){
            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
            wd = (int)(((x.iJD+43200000)/86400000)%7);
            sqlite4_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
            j += 2;
          }else{
            sqlite4_snprintf(4, &z[j],"%03d",nDay+1);
            j += 3;
          }
          break;
        }
        case 'J': {
          sqlite4_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
          j+=sqlite4Strlen30(&z[j]);
          break;
        }
        case 'm':  sqlite4_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
        case 'M':  sqlite4_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
        case 's': {
          sqlite4_snprintf(30,&z[j],"%lld",
                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
          j += sqlite4Strlen30(&z[j]);
          break;
        }
        case 'S':  sqlite4_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
        case 'w': {
          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
          break;
        }
        case 'Y': {
          sqlite4_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite4Strlen30(&z[j]);
          break;
        }
        default:   z[j++] = '%'; break;
      }
    }
  }
  z[j] = 0;







|







 







|







 







|







 







|



|
<


|












|


|





|
<


|
|

|
|
<


|





|







809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
...
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
...
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
...
943
944
945
946
947
948
949
950
951
952
953
954

955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979

980
981
982
983
984
985
986

987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
  int argc,
  sqlite4_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    char zBuf[100];
    computeYMD_HMS(&x);
    sqlite4_snprintf(zBuf,sizeof(zBuf), "%04d-%02d-%02d %02d:%02d:%02d",
                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
    sqlite4_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  }
}

/*
**    time( TIMESTRING, MOD, MOD, ...)
................................................................................
  int argc,
  sqlite4_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    char zBuf[100];
    computeHMS(&x);
    sqlite4_snprintf(zBuf,sizeof(zBuf), "%02d:%02d:%02d", x.h, x.m, (int)x.s);
    sqlite4_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  }
}

/*
**    date( TIMESTRING, MOD, MOD, ...)
**
................................................................................
  int argc,
  sqlite4_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    char zBuf[100];
    computeYMD(&x);
    sqlite4_snprintf(zBuf,sizeof(zBuf), "%04d-%02d-%02d", x.Y, x.M, x.D);
    sqlite4_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  }
}

/*
**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
**
................................................................................
  computeYMD_HMS(&x);
  for(i=j=0; zFmt[i]; i++){
    if( zFmt[i]!='%' ){
      z[j++] = zFmt[i];
    }else{
      i++;
      switch( zFmt[i] ){
        case 'd':  sqlite4_snprintf(&z[j],3,"%02d",x.D); j+=2; break;
        case 'f': {
          double s = x.s;
          if( s>59.999 ) s = 59.999;
          j += sqlite4_snprintf(&z[j],7,"%06.3f", s);

          break;
        }
        case 'H':  sqlite4_snprintf(&z[j],3,"%02d",x.h); j+=2; break;
        case 'W': /* Fall thru */
        case 'j': {
          int nDay;             /* Number of days since 1st day of year */
          DateTime y = x;
          y.validJD = 0;
          y.M = 1;
          y.D = 1;
          computeJD(&y);
          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
          if( zFmt[i]=='W' ){
            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
            wd = (int)(((x.iJD+43200000)/86400000)%7);
            sqlite4_snprintf(&z[j],3,"%02d",(nDay+7-wd)/7);
            j += 2;
          }else{
            sqlite4_snprintf(&z[j],4,"%03d",nDay+1);
            j += 3;
          }
          break;
        }
        case 'J': {
          j += sqlite4_snprintf(&z[j],20,"%.16g",x.iJD/86400000.0);

          break;
        }
        case 'm':  sqlite4_snprintf(&z[j],3,"%02d",x.M); j+=2; break;
        case 'M':  sqlite4_snprintf(&z[j],3,"%02d",x.m); j+=2; break;
        case 's': {
          j += sqlite4_snprintf(&z[j],30,"%lld",
                                (i64)(x.iJD/1000 - 21086676*(i64)10000));

          break;
        }
        case 'S':  sqlite4_snprintf(&z[j],3,"%02d",(int)x.s); j+=2; break;
        case 'w': {
          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
          break;
        }
        case 'Y': {
          sqlite4_snprintf(&z[j],5,"%04d",x.Y); j+=sqlite4Strlen30(&z[j]);
          break;
        }
        default:   z[j++] = '%'; break;
      }
    }
  }
  z[j] = 0;

Changes to src/fault.c.

54
55
56
57
58
59
60

61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87


/*
** Register hooks to call when sqlite4BeginBenignMalloc() and
** sqlite4EndBenignMalloc() are called, respectively.
*/
void sqlite4BenignMallocHooks(

  void (*xBenignBegin)(void),
  void (*xBenignEnd)(void)
){
  wsdHooksInit;
  wsdHooks.xBenignBegin = xBenignBegin;
  wsdHooks.xBenignEnd = xBenignEnd;
}

/*
** This (sqlite4EndBenignMalloc()) is called by SQLite code to indicate that
** subsequent malloc failures are benign. A call to sqlite4EndBenignMalloc()
** indicates that subsequent malloc failures are non-benign.
*/
void sqlite4BeginBenignMalloc(void){
  wsdHooksInit;
  if( wsdHooks.xBenignBegin ){
    wsdHooks.xBenignBegin();
  }
}
void sqlite4EndBenignMalloc(void){
  wsdHooksInit;
  if( wsdHooks.xBenignEnd ){
    wsdHooks.xBenignEnd();
  }
}

#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */







>













|





|







54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88


/*
** Register hooks to call when sqlite4BeginBenignMalloc() and
** sqlite4EndBenignMalloc() are called, respectively.
*/
void sqlite4BenignMallocHooks(
  sqlite4_env *pEnv,
  void (*xBenignBegin)(void),
  void (*xBenignEnd)(void)
){
  wsdHooksInit;
  wsdHooks.xBenignBegin = xBenignBegin;
  wsdHooks.xBenignEnd = xBenignEnd;
}

/*
** This (sqlite4EndBenignMalloc()) is called by SQLite code to indicate that
** subsequent malloc failures are benign. A call to sqlite4EndBenignMalloc()
** indicates that subsequent malloc failures are non-benign.
*/
void sqlite4BeginBenignMalloc(sqlite4_env *pEnv){
  wsdHooksInit;
  if( wsdHooks.xBenignBegin ){
    wsdHooks.xBenignBegin();
  }
}
void sqlite4EndBenignMalloc(sqlite4_env *pEnv){
  wsdHooksInit;
  if( wsdHooks.xBenignEnd ){
    wsdHooks.xBenignEnd();
  }
}

#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */

Changes to src/func.c.

258
259
260
261
262
263
264

265
266
267
268
269
270
271
...
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
...
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
...
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
...
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
...
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
...
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
...
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
...
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
...
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
....
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
....
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
....
1386
1387
1388
1389
1390
1391
1392

1393
1394
1395
1396
1397
1398
1399
....
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
** Implementation of the round() function
*/
#ifndef SQLITE_OMIT_FLOATING_POINT
static void roundFunc(sqlite4_context *context, int argc, sqlite4_value **argv){
  int n = 0;
  double r;
  char *zBuf;

  assert( argc==1 || argc==2 );
  if( argc==2 ){
    if( SQLITE_NULL==sqlite4_value_type(argv[1]) ) return;
    n = sqlite4_value_int(argv[1]);
    if( n>30 ) n = 30;
    if( n<0 ) n = 0;
  }
................................................................................
  ** otherwise use printf.
  */
  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
    r = (double)((sqlite_int64)(r+0.5));
  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
    r = -(double)((sqlite_int64)((-r)+0.5));
  }else{
    zBuf = sqlite4_mprintf("%.*f",n,r);
    if( zBuf==0 ){
      sqlite4_result_error_nomem(context);
      return;
    }
    sqlite4AtoF(zBuf, &r, sqlite4Strlen30(zBuf), SQLITE_UTF8);
    sqlite4_free(zBuf);
  }
  sqlite4_result_double(context, r);
}
#endif

/*
** Allocate nByte bytes of space using sqlite4_malloc(). If the
................................................................................
  assert( nByte>0 );
  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
    sqlite4_result_error_toobig(context);
    z = 0;
  }else{
    z = sqlite4Malloc((int)nByte);
    if( !z ){
      sqlite4_result_error_nomem(context);
    }
  }
  return z;
}

................................................................................
  assert( z2==(char*)sqlite4_value_text(argv[0]) );
  if( z2 ){
    z1 = contextMalloc(context, ((i64)n)+1);
    if( z1 ){
      for(i=0; i<n; i++){
        z1[i] = (char)sqlite4Toupper(z2[i]);
      }
      sqlite4_result_text(context, z1, n, sqlite4_free);
    }
  }
}
static void lowerFunc(sqlite4_context *context, int argc, sqlite4_value **argv){
  char *z1;
  const char *z2;
  int i, n;
................................................................................
  assert( z2==(char*)sqlite4_value_text(argv[0]) );
  if( z2 ){
    z1 = contextMalloc(context, ((i64)n)+1);
    if( z1 ){
      for(i=0; i<n; i++){
        z1[i] = sqlite4Tolower(z2[i]);
      }
      sqlite4_result_text(context, z1, n, sqlite4_free);
    }
  }
}


#if 0  /* This function is never used. */
/*
................................................................................
static void randomFunc(
  sqlite4_context *context,
  int NotUsed,
  sqlite4_value **NotUsed2
){
  sqlite_int64 r;
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  sqlite4_randomness(sizeof(r), &r);
  if( r<0 ){
    /* We need to prevent a random number of 0x8000000000000000 
    ** (or -9223372036854775808) since when you do abs() of that
    ** number of you get the same value back again.  To do this
    ** in a way that is testable, mask the sign bit off of negative
    ** values, resulting in a positive value.  Then take the 
    ** 2s complement of that positive value.  The end result can
................................................................................
  UNUSED_PARAMETER(argc);
  n = sqlite4_value_int(argv[0]);
  if( n<1 ){
    n = 1;
  }
  p = contextMalloc(context, n);
  if( p ){
    sqlite4_randomness(n, p);
    sqlite4_result_blob(context, (char*)p, n, sqlite4_free);
  }
}

/*
** Implementation of the last_insert_rowid() SQL function.  The return
** value is the same as the sqlite4_last_insert_rowid() API function.
*/
................................................................................
          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
        }
        zText[(nBlob*2)+2] = '\'';
        zText[(nBlob*2)+3] = '\0';
        zText[0] = 'X';
        zText[1] = '\'';
        sqlite4_result_text(context, zText, -1, SQLITE_TRANSIENT);
        sqlite4_free(zText);
      }
      break;
    }
    case SQLITE_TEXT: {
      int i,j;
      u64 n;
      const unsigned char *zArg = sqlite4_value_text(argv[0]);
................................................................................
          z[j++] = zArg[i];
          if( zArg[i]=='\'' ){
            z[j++] = '\'';
          }
        }
        z[j++] = '\'';
        z[j] = 0;
        sqlite4_result_text(context, z, j, sqlite4_free);
      }
      break;
    }
    default: {
      assert( sqlite4_value_type(argv[0])==SQLITE_NULL );
      sqlite4_result_text(context, "NULL", 4, SQLITE_STATIC);
      break;
................................................................................
  if( zHex ){
    for(i=0; i<n; i++, pBlob++){
      unsigned char c = *pBlob;
      *(z++) = hexdigits[(c>>4)&0xf];
      *(z++) = hexdigits[c&0xf];
    }
    *z = 0;
    sqlite4_result_text(context, zHex, n*2, sqlite4_free);
  }
}

/*
** The zeroblob(N) function returns a zero-filled blob of size N bytes.
*/
static void zeroblobFunc(
................................................................................
      u8 *zOld;
      sqlite4 *db = sqlite4_context_db_handle(context);
      nOut += nRep - nPattern;
      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
        sqlite4_result_error_toobig(context);
        sqlite4_free(zOut);
        return;
      }
      zOld = zOut;
      zOut = sqlite4_realloc(zOut, (int)nOut);
      if( zOut==0 ){
        sqlite4_result_error_nomem(context);
        sqlite4_free(zOld);
        return;
      }
      memcpy(&zOut[j], zRep, nRep);
      j += nRep;
      i += nPattern-1;
    }
  }
  assert( j+nStr-i+1==nOut );
  memcpy(&zOut[j], &zStr[i], nStr-i);
  j += nStr - i;
  assert( j<=nOut );
  zOut[j] = 0;
  sqlite4_result_text(context, (char*)zOut, j, sqlite4_free);
}

/*
** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
*/
static void trimFunc(
................................................................................
          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
        }
        if( i>=nChar ) break;
        nIn -= len;
      }
    }
    if( zCharSet ){
      sqlite4_free(azChar);
    }
  }
  sqlite4_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
}


/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
................................................................................
  if( sqlite4_value_type(argv[0])==SQLITE_NULL ) return;
  pAccum = (StrAccum*)sqlite4_aggregate_context(context, sizeof(*pAccum));

  if( pAccum ){
    sqlite4 *db = sqlite4_context_db_handle(context);
    int firstTerm = pAccum->useMalloc==0;
    pAccum->useMalloc = 2;

    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
    if( !firstTerm ){
      if( argc==2 ){
        zSep = (char*)sqlite4_value_text(argv[1]);
        nSep = sqlite4_value_bytes(argv[1]);
      }else{
        zSep = ",";
................................................................................
  if( pAccum ){
    if( pAccum->tooBig ){
      sqlite4_result_error_toobig(context);
    }else if( pAccum->mallocFailed ){
      sqlite4_result_error_nomem(context);
    }else{    
      sqlite4_result_text(context, sqlite4StrAccumFinish(pAccum), -1, 
                          sqlite4_free);
    }
  }
}

/*
** This routine does per-connection function registration.  Most
** of the built-in functions above are part of the global function set.







>







 







|





|







 







|







 







|







 







|







 







|







 







|
|







 







|







 







|







 







|







 







|



|


|












|







 







|







 







>







 







|







258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
...
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
...
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
...
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
...
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
...
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
...
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
...
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
...
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
...
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
....
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
....
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
....
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
....
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
** Implementation of the round() function
*/
#ifndef SQLITE_OMIT_FLOATING_POINT
static void roundFunc(sqlite4_context *context, int argc, sqlite4_value **argv){
  int n = 0;
  double r;
  char *zBuf;
  sqlite4_env *pEnv = sqlite4_context_env(context);
  assert( argc==1 || argc==2 );
  if( argc==2 ){
    if( SQLITE_NULL==sqlite4_value_type(argv[1]) ) return;
    n = sqlite4_value_int(argv[1]);
    if( n>30 ) n = 30;
    if( n<0 ) n = 0;
  }
................................................................................
  ** otherwise use printf.
  */
  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
    r = (double)((sqlite_int64)(r+0.5));
  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
    r = -(double)((sqlite_int64)((-r)+0.5));
  }else{
    zBuf = sqlite4_mprintf(pEnv,"%.*f",n,r);
    if( zBuf==0 ){
      sqlite4_result_error_nomem(context);
      return;
    }
    sqlite4AtoF(zBuf, &r, sqlite4Strlen30(zBuf), SQLITE_UTF8);
    sqlite4_free(pEnv, zBuf);
  }
  sqlite4_result_double(context, r);
}
#endif

/*
** Allocate nByte bytes of space using sqlite4_malloc(). If the
................................................................................
  assert( nByte>0 );
  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
    sqlite4_result_error_toobig(context);
    z = 0;
  }else{
    z = sqlite4Malloc(db->pEnv, (int)nByte);
    if( !z ){
      sqlite4_result_error_nomem(context);
    }
  }
  return z;
}

................................................................................
  assert( z2==(char*)sqlite4_value_text(argv[0]) );
  if( z2 ){
    z1 = contextMalloc(context, ((i64)n)+1);
    if( z1 ){
      for(i=0; i<n; i++){
        z1[i] = (char)sqlite4Toupper(z2[i]);
      }
      sqlite4_result_text(context, z1, n, SQLITE_DYNAMIC);
    }
  }
}
static void lowerFunc(sqlite4_context *context, int argc, sqlite4_value **argv){
  char *z1;
  const char *z2;
  int i, n;
................................................................................
  assert( z2==(char*)sqlite4_value_text(argv[0]) );
  if( z2 ){
    z1 = contextMalloc(context, ((i64)n)+1);
    if( z1 ){
      for(i=0; i<n; i++){
        z1[i] = sqlite4Tolower(z2[i]);
      }
      sqlite4_result_text(context, z1, n, SQLITE_DYNAMIC);
    }
  }
}


#if 0  /* This function is never used. */
/*
................................................................................
static void randomFunc(
  sqlite4_context *context,
  int NotUsed,
  sqlite4_value **NotUsed2
){
  sqlite_int64 r;
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  sqlite4_randomness(sqlite4_context_env(context), sizeof(r), &r);
  if( r<0 ){
    /* We need to prevent a random number of 0x8000000000000000 
    ** (or -9223372036854775808) since when you do abs() of that
    ** number of you get the same value back again.  To do this
    ** in a way that is testable, mask the sign bit off of negative
    ** values, resulting in a positive value.  Then take the 
    ** 2s complement of that positive value.  The end result can
................................................................................
  UNUSED_PARAMETER(argc);
  n = sqlite4_value_int(argv[0]);
  if( n<1 ){
    n = 1;
  }
  p = contextMalloc(context, n);
  if( p ){
    sqlite4_randomness(sqlite4_context_env(context), n, p);
    sqlite4_result_blob(context, (char*)p, n, SQLITE_DYNAMIC);
  }
}

/*
** Implementation of the last_insert_rowid() SQL function.  The return
** value is the same as the sqlite4_last_insert_rowid() API function.
*/
................................................................................
          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
        }
        zText[(nBlob*2)+2] = '\'';
        zText[(nBlob*2)+3] = '\0';
        zText[0] = 'X';
        zText[1] = '\'';
        sqlite4_result_text(context, zText, -1, SQLITE_TRANSIENT);
        sqlite4_free(sqlite4_context_env(context), zText);
      }
      break;
    }
    case SQLITE_TEXT: {
      int i,j;
      u64 n;
      const unsigned char *zArg = sqlite4_value_text(argv[0]);
................................................................................
          z[j++] = zArg[i];
          if( zArg[i]=='\'' ){
            z[j++] = '\'';
          }
        }
        z[j++] = '\'';
        z[j] = 0;
        sqlite4_result_text(context, z, j, SQLITE_DYNAMIC);
      }
      break;
    }
    default: {
      assert( sqlite4_value_type(argv[0])==SQLITE_NULL );
      sqlite4_result_text(context, "NULL", 4, SQLITE_STATIC);
      break;
................................................................................
  if( zHex ){
    for(i=0; i<n; i++, pBlob++){
      unsigned char c = *pBlob;
      *(z++) = hexdigits[(c>>4)&0xf];
      *(z++) = hexdigits[c&0xf];
    }
    *z = 0;
    sqlite4_result_text(context, zHex, n*2, SQLITE_DYNAMIC);
  }
}

/*
** The zeroblob(N) function returns a zero-filled blob of size N bytes.
*/
static void zeroblobFunc(
................................................................................
      u8 *zOld;
      sqlite4 *db = sqlite4_context_db_handle(context);
      nOut += nRep - nPattern;
      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
        sqlite4_result_error_toobig(context);
        sqlite4_free(db->pEnv, zOut);
        return;
      }
      zOld = zOut;
      zOut = sqlite4_realloc(db->pEnv, zOut, (int)nOut);
      if( zOut==0 ){
        sqlite4_result_error_nomem(context);
        sqlite4_free(db->pEnv, zOld);
        return;
      }
      memcpy(&zOut[j], zRep, nRep);
      j += nRep;
      i += nPattern-1;
    }
  }
  assert( j+nStr-i+1==nOut );
  memcpy(&zOut[j], &zStr[i], nStr-i);
  j += nStr - i;
  assert( j<=nOut );
  zOut[j] = 0;
  sqlite4_result_text(context, (char*)zOut, j, SQLITE_DYNAMIC);
}

/*
** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
*/
static void trimFunc(
................................................................................
          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
        }
        if( i>=nChar ) break;
        nIn -= len;
      }
    }
    if( zCharSet ){
      sqlite4_free(sqlite4_context_env(context), azChar);
    }
  }
  sqlite4_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
}


/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
................................................................................
  if( sqlite4_value_type(argv[0])==SQLITE_NULL ) return;
  pAccum = (StrAccum*)sqlite4_aggregate_context(context, sizeof(*pAccum));

  if( pAccum ){
    sqlite4 *db = sqlite4_context_db_handle(context);
    int firstTerm = pAccum->useMalloc==0;
    pAccum->useMalloc = 2;
    pAccum->pEnv = db->pEnv;
    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
    if( !firstTerm ){
      if( argc==2 ){
        zSep = (char*)sqlite4_value_text(argv[1]);
        nSep = sqlite4_value_bytes(argv[1]);
      }else{
        zSep = ",";
................................................................................
  if( pAccum ){
    if( pAccum->tooBig ){
      sqlite4_result_error_toobig(context);
    }else if( pAccum->mallocFailed ){
      sqlite4_result_error_nomem(context);
    }else{    
      sqlite4_result_text(context, sqlite4StrAccumFinish(pAccum), -1, 
                          SQLITE_DYNAMIC);
    }
  }
}

/*
** This routine does per-connection function registration.  Most
** of the built-in functions above are part of the global function set.

Changes to src/hash.c.

16
17
18
19
20
21
22
23
24
25
26
27
28

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
...
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
...
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
...
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
#include <assert.h>

/* Turn bulk memory into a hash table object by initializing the
** fields of the Hash structure.
**
** "pNew" is a pointer to the hash table that is to be initialized.
*/
void sqlite4HashInit(Hash *pNew){
  assert( pNew!=0 );
  pNew->first = 0;
  pNew->count = 0;
  pNew->htsize = 0;
  pNew->ht = 0;

}

/* Remove all entries from a hash table.  Reclaim all memory.
** Call this routine to delete a hash table or to reset a hash table
** to the empty state.
*/
void sqlite4HashClear(Hash *pH){
  HashElem *elem;         /* For looping over all elements of the table */

  assert( pH!=0 );
  elem = pH->first;
  pH->first = 0;
  sqlite4_free(pH->ht);
  pH->ht = 0;
  pH->htsize = 0;
  while( elem ){
    HashElem *next_elem = elem->next;
    sqlite4_free(elem);
    elem = next_elem;
  }
  pH->count = 0;
}

/*
** The hashing function.
................................................................................
  if( new_size==pH->htsize ) return 0;
#endif

  /* The inability to allocates space for a larger hash table is
  ** a performance hit but it is not a fatal error.  So mark the
  ** allocation as a benign.
  */
  sqlite4BeginBenignMalloc();
  new_ht = (struct _ht *)sqlite4Malloc( new_size*sizeof(struct _ht) );
  sqlite4EndBenignMalloc();

  if( new_ht==0 ) return 0;
  sqlite4_free(pH->ht);
  pH->ht = new_ht;
  pH->htsize = new_size = sqlite4MallocSize(new_ht)/sizeof(struct _ht);
  memset(new_ht, 0, new_size*sizeof(struct _ht));
  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
    next_elem = elem->next;
    insertElement(pH, &new_ht[h], elem);
  }
  return 1;
................................................................................
    pEntry = &pH->ht[h];
    if( pEntry->chain==elem ){
      pEntry->chain = elem->next;
    }
    pEntry->count--;
    assert( pEntry->count>=0 );
  }
  sqlite4_free( elem );
  pH->count--;
  if( pH->count<=0 ){
    assert( pH->first==0 );
    assert( pH->count==0 );
    sqlite4HashClear(pH);
  }
}
................................................................................
      elem->data = data;
      elem->pKey = pKey;
      assert(nKey==elem->nKey);
    }
    return old_data;
  }
  if( data==0 ) return 0;
  new_elem = (HashElem*)sqlite4Malloc( sizeof(HashElem) );
  if( new_elem==0 ) return data;
  new_elem->pKey = pKey;
  new_elem->nKey = nKey;
  new_elem->data = data;
  pH->count++;
  if( pH->count>=10 && pH->count > 2*pH->htsize ){
    if( rehash(pH, pH->count*2) ){







|





>












|




|







 







|
|
|


|

|







 







|







 







|







16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
...
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
...
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
...
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#include <assert.h>

/* Turn bulk memory into a hash table object by initializing the
** fields of the Hash structure.
**
** "pNew" is a pointer to the hash table that is to be initialized.
*/
void sqlite4HashInit(sqlite4_env *pEnv, Hash *pNew){
  assert( pNew!=0 );
  pNew->first = 0;
  pNew->count = 0;
  pNew->htsize = 0;
  pNew->ht = 0;
  pNew->pEnv = pEnv;
}

/* Remove all entries from a hash table.  Reclaim all memory.
** Call this routine to delete a hash table or to reset a hash table
** to the empty state.
*/
void sqlite4HashClear(Hash *pH){
  HashElem *elem;         /* For looping over all elements of the table */

  assert( pH!=0 );
  elem = pH->first;
  pH->first = 0;
  sqlite4_free(pH->pEnv, pH->ht);
  pH->ht = 0;
  pH->htsize = 0;
  while( elem ){
    HashElem *next_elem = elem->next;
    sqlite4_free(pH->pEnv, elem);
    elem = next_elem;
  }
  pH->count = 0;
}

/*
** The hashing function.
................................................................................
  if( new_size==pH->htsize ) return 0;
#endif

  /* The inability to allocates space for a larger hash table is
  ** a performance hit but it is not a fatal error.  So mark the
  ** allocation as a benign.
  */
  sqlite4BeginBenignMalloc(pH->pEnv);
  new_ht = (struct _ht *)sqlite4Malloc(pH->pEnv, new_size*sizeof(struct _ht) );
  sqlite4EndBenignMalloc(pH->pEnv);

  if( new_ht==0 ) return 0;
  sqlite4_free(pH->pEnv, pH->ht);
  pH->ht = new_ht;
  pH->htsize = new_size = sqlite4MallocSize(pH->pEnv, new_ht)/sizeof(struct _ht);
  memset(new_ht, 0, new_size*sizeof(struct _ht));
  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
    next_elem = elem->next;
    insertElement(pH, &new_ht[h], elem);
  }
  return 1;
................................................................................
    pEntry = &pH->ht[h];
    if( pEntry->chain==elem ){
      pEntry->chain = elem->next;
    }
    pEntry->count--;
    assert( pEntry->count>=0 );
  }
  sqlite4_free(pH->pEnv, elem);
  pH->count--;
  if( pH->count<=0 ){
    assert( pH->first==0 );
    assert( pH->count==0 );
    sqlite4HashClear(pH);
  }
}
................................................................................
      elem->data = data;
      elem->pKey = pKey;
      assert(nKey==elem->nKey);
    }
    return old_data;
  }
  if( data==0 ) return 0;
  new_elem = (HashElem*)sqlite4Malloc(pH->pEnv, sizeof(HashElem) );
  if( new_elem==0 ) return data;
  new_elem->pKey = pKey;
  new_elem->nKey = nKey;
  new_elem->data = data;
  pH->count++;
  if( pH->count>=10 && pH->count > 2*pH->htsize ){
    if( rehash(pH, pH->count*2) ){

Changes to src/hash.h.

37
38
39
40
41
42
43

44
45
46
47
48
49
50
..
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
** by a linear search of the global list.  For small tables, the 
** Hash.ht table is never allocated because if there are few elements
** in the table, it is faster to do a linear search than to manage
** the hash table.
*/
struct Hash {

  unsigned int htsize;      /* Number of buckets in the hash table */
  unsigned int count;       /* Number of entries in this table */
  HashElem *first;          /* The first element of the array */
  struct _ht {              /* the hash table */
    int count;                 /* Number of entries with this hash */
    HashElem *chain;           /* Pointer to first entry with this hash */
  } *ht;
................................................................................
  void *data;                  /* Data associated with this element */
  const char *pKey; int nKey;  /* Key associated with this element */
};

/*
** Access routines.  To delete, insert a NULL pointer.
*/
void sqlite4HashInit(Hash*);
void *sqlite4HashInsert(Hash*, const char *pKey, int nKey, void *pData);
void *sqlite4HashFind(const Hash*, const char *pKey, int nKey);
void sqlite4HashClear(Hash*);

/*
** Macros for looping over all elements of a hash table.  The idiom is
** like this:







>







 







|







37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
..
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
** by a linear search of the global list.  For small tables, the 
** Hash.ht table is never allocated because if there are few elements
** in the table, it is faster to do a linear search than to manage
** the hash table.
*/
struct Hash {
  struct sqlite4_env *pEnv; /* Memory allocation environment */
  unsigned int htsize;      /* Number of buckets in the hash table */
  unsigned int count;       /* Number of entries in this table */
  HashElem *first;          /* The first element of the array */
  struct _ht {              /* the hash table */
    int count;                 /* Number of entries with this hash */
    HashElem *chain;           /* Pointer to first entry with this hash */
  } *ht;
................................................................................
  void *data;                  /* Data associated with this element */
  const char *pKey; int nKey;  /* Key associated with this element */
};

/*
** Access routines.  To delete, insert a NULL pointer.
*/
void sqlite4HashInit(struct sqlite4_env *pEnv, Hash*);
void *sqlite4HashInsert(Hash*, const char *pKey, int nKey, void *pData);
void *sqlite4HashFind(const Hash*, const char *pKey, int nKey);
void sqlite4HashClear(Hash*);

/*
** Macros for looping over all elements of a hash table.  The idiom is
** like this:

Changes to src/insert.c.

1089
1090
1091
1092
1093
1094
1095

1096
1097
1098
1099
1100
1101
1102
){
  const int nCol = pIdx->nColumn; /* Number of columns indexed by pIdx */
  StrAccum errMsg;                /* Buffer to build error message within */
  int iCol;                       /* Used to iterate through indexed columns */

  sqlite4StrAccumInit(&errMsg, 0, 0, 200);
  errMsg.db = pParse->db;

  if( pIdx->eIndexType==SQLITE_INDEX_PRIMARYKEY ){
    sqlite4StrAccumAppend(&errMsg, "PRIMARY KEY must be unique", -1);
  }else{
    sqlite4StrAccumAppend(&errMsg, (nCol>1 ? "columns " : "column "), -1);
    for(iCol=0; iCol<pIdx->nColumn; iCol++){
      const char *zCol = indexColumnName(pIdx, iCol);
      sqlite4StrAccumAppend(&errMsg, (iCol==0 ? "" : ", "), -1);







>







1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
){
  const int nCol = pIdx->nColumn; /* Number of columns indexed by pIdx */
  StrAccum errMsg;                /* Buffer to build error message within */
  int iCol;                       /* Used to iterate through indexed columns */

  sqlite4StrAccumInit(&errMsg, 0, 0, 200);
  errMsg.db = pParse->db;
  errMsg.pEnv = errMsg.db->pEnv;
  if( pIdx->eIndexType==SQLITE_INDEX_PRIMARYKEY ){
    sqlite4StrAccumAppend(&errMsg, "PRIMARY KEY must be unique", -1);
  }else{
    sqlite4StrAccumAppend(&errMsg, (nCol>1 ? "columns " : "column "), -1);
    for(iCol=0; iCol<pIdx->nColumn; iCol++){
      const char *zCol = indexColumnName(pIdx, iCol);
      sqlite4StrAccumAppend(&errMsg, (iCol==0 ? "" : ", "), -1);

Changes to src/kvlsm.c.

164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
...
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
...
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
...
413
414
415
416
417
418
419
420
421
422
423
424
425

426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
** Create a new cursor object.
*/
static int kvlsmOpenCursor(KVStore *pKVStore, KVCursor **ppKVCursor){
  int rc = SQLITE_OK;
  KVLsm *p = (KVLsm *)pKVStore;
  KVLsmCsr *pCsr;

  pCsr = (KVLsmCsr *)sqlite4_malloc(sizeof(KVLsmCsr));
  if( pCsr==0 ){
    rc = SQLITE_NOMEM;
  }else{
    memset(pCsr, 0, sizeof(KVLsmCsr));
    rc = lsm_csr_open(p->pDb, &pCsr->pCsr);

    if( rc==SQLITE_OK ){
      pCsr->base.pStore = pKVStore;
      pCsr->base.pStoreVfunc = pKVStore->pStoreVfunc;
    }else{
      sqlite4_free(pCsr);
      pCsr = 0;
    }
  }

  *ppKVCursor = (KVCursor*)pCsr;
  return rc;
}
................................................................................

/*
** Destroy a cursor object
*/
static int kvlsmCloseCursor(KVCursor *pKVCursor){
  KVLsmCsr *pCsr = (KVLsmCsr *)pKVCursor;
  lsm_csr_close(pCsr->pCsr);
  sqlite4_free(pCsr);
  return SQLITE_OK;
}

/*
** Move a cursor to the next non-deleted node.
*/
static int kvlsmNextEntry(KVCursor *pKVCursor){
................................................................................
  /* If there is an active transaction, roll it back. The important
  ** part is that the read-transaction cursor is closed. Otherwise, the
  ** call to lsm_close() below will fail.  */
  kvlsmRollback(pKVStore, 0);
  assert( p->pCsr==0 );

  lsm_close(p->pDb);
  sqlite4_free(p);
  return SQLITE_OK;
}

static int kvlsmControl(KVStore *pKVStore, int op, void *pArg){
  int rc = SQLITE_OK;
  KVLsm *p = (KVLsm *)pKVStore;

................................................................................
    kvlsmClose,
    kvlsmControl
  };

  KVLsm *pNew;
  int rc = SQLITE_OK;

  pNew = (KVLsm *)sqlite4_malloc(sizeof(KVLsm));
  if( pNew==0 ){
    rc = SQLITE_NOMEM;
  }else{
    memset(pNew, 0, sizeof(KVLsm));
    pNew->base.pStoreVfunc = &kvlsmMethods;


    rc = lsm_new(0, &pNew->pDb);
    if( rc==SQLITE_OK ){
      rc = lsm_open(pNew->pDb, zName);
    }

    if( rc!=SQLITE_OK ){
      lsm_close(pNew->pDb);
      sqlite4_free(pNew);
      pNew = 0;
    }
  }

  *ppKVStore = (KVStore*)pNew;
  return rc;
}







|










|







 







|







 







|







 







|





>








|







164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
...
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
...
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
...
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
** Create a new cursor object.
*/
static int kvlsmOpenCursor(KVStore *pKVStore, KVCursor **ppKVCursor){
  int rc = SQLITE_OK;
  KVLsm *p = (KVLsm *)pKVStore;
  KVLsmCsr *pCsr;

  pCsr = (KVLsmCsr *)sqlite4_malloc(pKVStore->pEnv, sizeof(KVLsmCsr));
  if( pCsr==0 ){
    rc = SQLITE_NOMEM;
  }else{
    memset(pCsr, 0, sizeof(KVLsmCsr));
    rc = lsm_csr_open(p->pDb, &pCsr->pCsr);

    if( rc==SQLITE_OK ){
      pCsr->base.pStore = pKVStore;
      pCsr->base.pStoreVfunc = pKVStore->pStoreVfunc;
    }else{
      sqlite4_free(pCsr->base.pEnv, pCsr);
      pCsr = 0;
    }
  }

  *ppKVCursor = (KVCursor*)pCsr;
  return rc;
}
................................................................................

/*
** Destroy a cursor object
*/
static int kvlsmCloseCursor(KVCursor *pKVCursor){
  KVLsmCsr *pCsr = (KVLsmCsr *)pKVCursor;
  lsm_csr_close(pCsr->pCsr);
  sqlite4_free(pCsr->base.pEnv, pCsr);
  return SQLITE_OK;
}

/*
** Move a cursor to the next non-deleted node.
*/
static int kvlsmNextEntry(KVCursor *pKVCursor){
................................................................................
  /* If there is an active transaction, roll it back. The important
  ** part is that the read-transaction cursor is closed. Otherwise, the
  ** call to lsm_close() below will fail.  */
  kvlsmRollback(pKVStore, 0);
  assert( p->pCsr==0 );

  lsm_close(p->pDb);
  sqlite4_free(p->base.pEnv, p);
  return SQLITE_OK;
}

static int kvlsmControl(KVStore *pKVStore, int op, void *pArg){
  int rc = SQLITE_OK;
  KVLsm *p = (KVLsm *)pKVStore;

................................................................................
    kvlsmClose,
    kvlsmControl
  };

  KVLsm *pNew;
  int rc = SQLITE_OK;

  pNew = (KVLsm *)sqlite4_malloc(pEnv, sizeof(KVLsm));
  if( pNew==0 ){
    rc = SQLITE_NOMEM;
  }else{
    memset(pNew, 0, sizeof(KVLsm));
    pNew->base.pStoreVfunc = &kvlsmMethods;
    pNew->base.pEnv = pEnv;

    rc = lsm_new(0, &pNew->pDb);
    if( rc==SQLITE_OK ){
      rc = lsm_open(pNew->pDb, zName);
    }

    if( rc!=SQLITE_OK ){
      lsm_close(pNew->pDb);
      sqlite4_free(pEnv, pNew);
      pNew = 0;
    }
  }

  *ppKVStore = (KVStore*)pNew;
  return rc;
}

Changes to src/kvmem.c.

193
194
195
196
197
198
199
200




201
202
203
204
205
206
207
208
...
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
...
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
...
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
...
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
...
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
...
444
445
446
447
448
449
450

451
452
453
454
455
456
457
458
...
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
...
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
...
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
...
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
...
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
...
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
...
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
...
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
...
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
...
887
888
889
890
891
892
893

894
895
896

897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
...
935
936
937
938
939
940
941
942
943
944
945

946
947
948
949
950
  if( c==0 ) c = nK1 - nK2;
  return c;
}

/*
** Create a new KVMemData object
*/
static KVMemData *kvmemDataNew(const KVByteArray *aData, KVSize nData){




  KVMemData *p = sqlite4_malloc( sizeof(*p) + nData - 8 );
  if( p ) {
    p->nRef = 1;
    p->n = nData;
    memcpy(p->a, aData, nData);
  }
  return p;
}
................................................................................
  if( p ) p->nRef++;
  return p;
}

/*
** Dereference a KVMemData object
*/
static void kvmemDataUnref(KVMemData *p){
  if( p && (--p->nRef)<=0 ) sqlite4_free(p);
}

/*
** Reference a KVMemNode object
*/
static KVMemNode *kvmemNodeRef(KVMemNode *p){
  if( p ) p->nRef++;
  return p;
}

/*
** Dereference a KVMemNode object
*/
static void kvmemNodeUnref(KVMemNode *p){
  if( p && (--p->nRef)<=0 ){
    kvmemDataUnref(p->pData);
    sqlite4_free(p);
  }
}

/*
** Recursively delete all nodes in a tree
*/
static void kvmemClearTree(KVMemNode *pNode){
  if( pNode==0 ) return;
  kvmemClearTree(pNode->pBefore);
  kvmemClearTree(pNode->pAfter);
  kvmemNodeUnref(pNode);
}

/*
** End of utilities
***************************************************************************
** Low-level operations on the tree
*/
................................................................................

/*
** Create a new change record
*/
static KVMemChng *kvmemNewChng(KVMem *p, KVMemNode *pNode){
  KVMemChng *pChng;
  assert( p->base.iTransLevel>=2 );
  pChng = sqlite4_malloc( sizeof(*pChng) );
  if( pChng ){
    pChng->pNext = p->apLog[p->base.iTransLevel-2];
    p->apLog[p->base.iTransLevel-2] = pChng;
    pChng->pNode = pNode;
    pChng->oldTrans = pNode->mxTrans;
    pNode->mxTrans = p->base.iTransLevel;
    pChng->pData = pNode->pData;
................................................................................
  KVMem *p,
  const KVByteArray *aKey,
  KVSize nKey
){
  KVMemNode *pNode;
  KVMemChng *pChng;
  assert( p->base.iTransLevel>=2 );
  pNode = sqlite4_malloc( sizeof(*pNode)+nKey-2 );
  if( pNode ){
    memset(pNode, 0, sizeof(*pNode));
    memcpy(pNode->aKey, aKey, nKey);
    pNode->nKey = nKey;
    pNode->nRef = 1;
    pChng = kvmemNewChng(p, pNode);
    if( pChng==0 ){
      sqlite4_free(pNode);
      pNode = 0;
    }
    assert( pChng==0 || pChng->pData==0 );
  }
  return pNode;
}

................................................................................
#endif

/* Remove node pOld from the tree.  pOld must be an element of the tree.
*/
static void kvmemRemoveNode(KVMem *p, KVMemNode *pOld){
  KVMemNode **ppParent;           /* Location of pointer to pOld */
  KVMemNode *pBalance;            /* Node to run kvmemBalance() on */
  kvmemDataUnref(pOld->pData);
  pOld->pData = 0;
  ppParent = kvmemFromPtr(pOld, &p->pRoot);
  if( pOld->pBefore==0 && pOld->pAfter==0 ){
    *ppParent = 0;
    pBalance = pOld->pUp;
  }else if( pOld->pBefore && pOld->pAfter ){
    KVMemNode *pX;                /* Smallest node that is larger than pOld */
................................................................................
    *ppParent = pBalance = pOld->pAfter;
    pBalance->pUp = pOld->pUp;
  }else if( pOld->pAfter==0 ){
    *ppParent = pBalance = pOld->pBefore;
    pBalance->pUp = pOld->pUp;
  }
  p->pRoot = kvmemBalance(pBalance);
  kvmemNodeUnref(pOld);
}

/*
** End of low-level access routines
***************************************************************************
** Interface routines follow
*/
................................................................................
static int kvmemBegin(KVStore *pKVStore, int iLevel){
  KVMem *p = (KVMem*)pKVStore;
  assert( p->iMagicKVMemBase==SQLITE_KVMEMBASE_MAGIC );
  assert( iLevel>0 );
  assert( iLevel==2 || iLevel==p->base.iTransLevel+1 );
  if( iLevel>=2 ){
    KVMemChng **apNewLog;

    apNewLog = sqlite4_realloc(p->apLog, sizeof(apNewLog[0])*(iLevel-1) );
    if( apNewLog==0 ) return SQLITE_NOMEM;
    p->apLog = apNewLog;
    p->apLog[iLevel-2] = 0;
  }
  p->base.iTransLevel = iLevel;
  return SQLITE_OK;
}
................................................................................
      for(pChng=p->apLog[p->base.iTransLevel-2]; pChng; pChng=pNext){
        KVMemNode *pNode = pChng->pNode;
        if( pNode->pData ){
          pNode->mxTrans = pChng->oldTrans;
        }else{
          kvmemRemoveNode(p, pNode);
        }
        kvmemDataUnref(pChng->pData);
        pNext = pChng->pNext;
        sqlite4_free(pChng);
      }
    }else{
      KVMemChng **pp;
      int iFrom = p->base.iTransLevel-2;
      int iTo = p->base.iTransLevel-3;
      assert( iTo>=0 );

................................................................................
  assert( p->iMagicKVMemBase==SQLITE_KVMEMBASE_MAGIC );
  assert( iLevel>=0 );
  while( p->base.iTransLevel>iLevel && p->base.iTransLevel>1 ){
    KVMemChng *pChng, *pNext;
    for(pChng=p->apLog[p->base.iTransLevel-2]; pChng; pChng=pNext){
      KVMemNode *pNode = pChng->pNode;
      if( pChng->pData || pChng->oldTrans>0 ){
        kvmemDataUnref(pNode->pData);
        pNode->pData = pChng->pData;
        pNode->mxTrans = pChng->oldTrans;
      }else{
        kvmemRemoveNode(p, pNode);
      }
      pNext = pChng->pNext;
      sqlite4_free(pChng);
    }
    p->apLog[p->base.iTransLevel-2] = 0;
    p->base.iTransLevel--;
  }
  p->base.iTransLevel = iLevel;
  return SQLITE_OK;
}
................................................................................
){
  KVMem *p = (KVMem*)pKVStore;
  KVMemNode *pNew, *pNode;
  KVMemData *pData;
  KVMemChng *pChng;
  assert( p->iMagicKVMemBase==SQLITE_KVMEMBASE_MAGIC );
  assert( p->base.iTransLevel>=2 );
  pData = kvmemDataNew(aData, nData);
  if( pData==0 ) return SQLITE_NOMEM;
  if( p->pRoot==0 ){
    pNode = pNew = kvmemNewNode(p, aKey, nKey);
    if( pNew==0 ) goto KVMemReplace_nomem;
    pNew->pUp = 0;
  }else{
    pNode = p->pRoot;
................................................................................
          pNode->pAfter = pNew = kvmemNewNode(p, aKey, nKey);
          if( pNew==0 ) goto KVMemReplace_nomem;
          pNew->pUp = pNode;
          break;
        }
      }else{
        if( pNode->mxTrans==p->base.iTransLevel ){
          kvmemDataUnref(pNode->pData);
        }else{
          pChng = kvmemNewChng(p, pNode);
          if( pChng==0 ) goto KVMemReplace_nomem;
        }
        pNode->pData = pData;
        return SQLITE_OK;
      }
................................................................................
  }
  pNew->pData = pData;
  pNew->height = 1;
  p->pRoot = kvmemBalance(pNew);
  return SQLITE_OK;

KVMemReplace_nomem:
  kvmemDataUnref(pData);
  return SQLITE_NOMEM;
}

/*
** Create a new cursor object.
*/
static int kvmemOpenCursor(KVStore *pKVStore, KVCursor **ppKVCursor){
  KVMem *p = (KVMem*)pKVStore;
  KVMemCursor *pCur;
  assert( p->iMagicKVMemBase==SQLITE_KVMEMBASE_MAGIC );
  pCur = sqlite4_malloc( sizeof(*pCur) );
  if( pCur==0 ){
    *ppKVCursor = 0;
    return SQLITE_NOMEM;
  }
  memset(pCur, 0, sizeof(*pCur));
  pCur->pOwner = p;
  p->nCursor++;
................................................................................

/*
** Reset a cursor
*/
static int kvmemReset(KVCursor *pKVCursor){
  KVMemCursor *pCur = (KVMemCursor*)pKVCursor;
  assert( pCur->iMagicKVMemCur==SQLITE_KVMEMCUR_MAGIC );
  kvmemDataUnref(pCur->pData);
  pCur->pData = 0;
  kvmemNodeUnref(pCur->pNode);
  pCur->pNode = 0;
  return SQLITE_OK;
}

/*
** Destroy a cursor object
*/
................................................................................
  KVMemCursor *pCur = (KVMemCursor*)pKVCursor;
  if( pCur ){
    assert( pCur->iMagicKVMemCur==SQLITE_KVMEMCUR_MAGIC );
    assert( pCur->pOwner->iMagicKVMemBase==SQLITE_KVMEMBASE_MAGIC );
    pCur->pOwner->nCursor--;
    kvmemReset(pKVCursor);
    memset(pCur, 0, sizeof(*pCur));
    sqlite4_free(pCur);
  }
  return SQLITE_OK;
}

/*
** Move a cursor to the next non-deleted node.
*/
................................................................................
      if( direction>0 ){
        pBest = pNode;
        rc = SQLITE_INEXACT;
      }
      pNode = pNode->pBefore;
    }
  }
  kvmemNodeUnref(pCur->pNode);
  kvmemDataUnref(pCur->pData);
  if( pBest ){
    pCur->pNode = kvmemNodeRef(pBest);
    pCur->pData = kvmemDataRef(pBest->pData);

    /* The cursor currently points to a deleted node. If parameter 'direction'
    ** was zero (exact matches only), then the search has failed - return
    ** SQLITE_NOTFOUND. Otherwise, advance to the next (if direction is +ve)
................................................................................
  if( pNode==0 ) return SQLITE_OK;
  if( pNode->pData==0 ) return SQLITE_OK;
  if( pNode->mxTrans<p->base.iTransLevel ){
    pChng = kvmemNewChng(p, pNode);
    if( pChng==0 ) return SQLITE_NOMEM;
    assert( pNode->pData==0 );
  }else{
    kvmemDataUnref(pNode->pData);
    pNode->pData = 0;
  }
  return SQLITE_OK;
}

/*
** Return the key of the node the cursor is pointing to.
................................................................................
}

/*
** Destructor for the entire in-memory storage tree.
*/
static int kvmemClose(KVStore *pKVStore){
  KVMem *p = (KVMem*)pKVStore;

  if( p==0 ) return SQLITE_OK;
  assert( p->iMagicKVMemBase==SQLITE_KVMEMBASE_MAGIC );
  assert( p->nCursor==0 );

  if( p->base.iTransLevel ){
    kvmemCommitPhaseOne(pKVStore, 0);
    kvmemCommitPhaseTwo(pKVStore, 0);
  }
  sqlite4_free(p->apLog);
  kvmemClearTree(p->pRoot);
  memset(p, 0, sizeof(*p));
  sqlite4_free(p);
  return SQLITE_OK;
}

static int kvmemControl(KVStore *pKVStore, int op, void *pArg){
  return SQLITE_NOTFOUND;
}

................................................................................
*/
int sqlite4KVStoreOpenMem(
  sqlite4_env *pEnv,              /* Runtime environment */
  KVStore **ppKVStore,            /* OUT: Write the new KVStore here */
  const char *zName,              /* Name of in-memory storage unit */
  unsigned openFlags              /* Flags */
){
  KVMem *pNew = sqlite4_malloc( sizeof(*pNew) );
  if( pNew==0 ) return SQLITE_NOMEM;
  memset(pNew, 0, sizeof(*pNew));
  pNew->base.pStoreVfunc = &kvmemMethods;

  pNew->iMagicKVMemBase = SQLITE_KVMEMBASE_MAGIC;
  pNew->openFlags = openFlags;
  *ppKVStore = (KVStore*)pNew;
  return SQLITE_OK;
}







|
>
>
>
>
|







 







|
|













|

|
|






|

|
|
|







 







|







 







|







|







 







|







 







|







 







>
|







 







|

|







 







|






|







 







|







 







|







 







|










|







 







|

|







 







|







 







|
|







 







|







 







>



>




|
|

|







 







|



>





193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
...
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
...
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
...
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
...
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
...
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
...
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
...
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
...
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
...
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
...
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
...
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
...
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
...
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
...
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
...
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
...
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
...
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
  if( c==0 ) c = nK1 - nK2;
  return c;
}

/*
** Create a new KVMemData object
*/
static KVMemData *kvmemDataNew(
  sqlite4_env *pEnv,            /* Memory allocator context */
  const KVByteArray *aData,     /* Data for the new object */
  KVSize nData                  /* Bytes of content in aData[] */
){
  KVMemData *p = sqlite4_malloc(pEnv, sizeof(*p) + nData - 8 );
  if( p ) {
    p->nRef = 1;
    p->n = nData;
    memcpy(p->a, aData, nData);
  }
  return p;
}
................................................................................
  if( p ) p->nRef++;
  return p;
}

/*
** Dereference a KVMemData object
*/
static void kvmemDataUnref(sqlite4_env *pEnv, KVMemData *p){
  if( p && (--p->nRef)<=0 ) sqlite4_free(pEnv, p);
}

/*
** Reference a KVMemNode object
*/
static KVMemNode *kvmemNodeRef(KVMemNode *p){
  if( p ) p->nRef++;
  return p;
}

/*
** Dereference a KVMemNode object
*/
static void kvmemNodeUnref(sqlite4_env *pEnv, KVMemNode *p){
  if( p && (--p->nRef)<=0 ){
    kvmemDataUnref(pEnv, p->pData);
    sqlite4_free(pEnv, p);
  }
}

/*
** Recursively delete all nodes in a tree
*/
static void kvmemClearTree(sqlite4_env *pEnv, KVMemNode *pNode){
  if( pNode==0 ) return;
  kvmemClearTree(pEnv, pNode->pBefore);
  kvmemClearTree(pEnv, pNode->pAfter);
  kvmemNodeUnref(pEnv, pNode);
}

/*
** End of utilities
***************************************************************************
** Low-level operations on the tree
*/
................................................................................

/*
** Create a new change record
*/
static KVMemChng *kvmemNewChng(KVMem *p, KVMemNode *pNode){
  KVMemChng *pChng;
  assert( p->base.iTransLevel>=2 );
  pChng = sqlite4_malloc(p->base.pEnv, sizeof(*pChng) );
  if( pChng ){
    pChng->pNext = p->apLog[p->base.iTransLevel-2];
    p->apLog[p->base.iTransLevel-2] = pChng;
    pChng->pNode = pNode;
    pChng->oldTrans = pNode->mxTrans;
    pNode->mxTrans = p->base.iTransLevel;
    pChng->pData = pNode->pData;
................................................................................
  KVMem *p,
  const KVByteArray *aKey,
  KVSize nKey
){
  KVMemNode *pNode;
  KVMemChng *pChng;
  assert( p->base.iTransLevel>=2 );
  pNode = sqlite4_malloc(p->base.pEnv, sizeof(*pNode)+nKey-2 );
  if( pNode ){
    memset(pNode, 0, sizeof(*pNode));
    memcpy(pNode->aKey, aKey, nKey);
    pNode->nKey = nKey;
    pNode->nRef = 1;
    pChng = kvmemNewChng(p, pNode);
    if( pChng==0 ){
      sqlite4_free(p->base.pEnv, pNode);
      pNode = 0;
    }
    assert( pChng==0 || pChng->pData==0 );
  }
  return pNode;
}

................................................................................
#endif

/* Remove node pOld from the tree.  pOld must be an element of the tree.
*/
static void kvmemRemoveNode(KVMem *p, KVMemNode *pOld){
  KVMemNode **ppParent;           /* Location of pointer to pOld */
  KVMemNode *pBalance;            /* Node to run kvmemBalance() on */
  kvmemDataUnref(p->base.pEnv, pOld->pData);
  pOld->pData = 0;
  ppParent = kvmemFromPtr(pOld, &p->pRoot);
  if( pOld->pBefore==0 && pOld->pAfter==0 ){
    *ppParent = 0;
    pBalance = pOld->pUp;
  }else if( pOld->pBefore && pOld->pAfter ){
    KVMemNode *pX;                /* Smallest node that is larger than pOld */
................................................................................
    *ppParent = pBalance = pOld->pAfter;
    pBalance->pUp = pOld->pUp;
  }else if( pOld->pAfter==0 ){
    *ppParent = pBalance = pOld->pBefore;
    pBalance->pUp = pOld->pUp;
  }
  p->pRoot = kvmemBalance(pBalance);
  kvmemNodeUnref(p->base.pEnv, pOld);
}

/*
** End of low-level access routines
***************************************************************************
** Interface routines follow
*/
................................................................................
static int kvmemBegin(KVStore *pKVStore, int iLevel){
  KVMem *p = (KVMem*)pKVStore;
  assert( p->iMagicKVMemBase==SQLITE_KVMEMBASE_MAGIC );
  assert( iLevel>0 );
  assert( iLevel==2 || iLevel==p->base.iTransLevel+1 );
  if( iLevel>=2 ){
    KVMemChng **apNewLog;
    apNewLog = sqlite4_realloc(p->base.pEnv, p->apLog,
                               sizeof(apNewLog[0])*(iLevel-1) );
    if( apNewLog==0 ) return SQLITE_NOMEM;
    p->apLog = apNewLog;
    p->apLog[iLevel-2] = 0;
  }
  p->base.iTransLevel = iLevel;
  return SQLITE_OK;
}
................................................................................
      for(pChng=p->apLog[p->base.iTransLevel-2]; pChng; pChng=pNext){
        KVMemNode *pNode = pChng->pNode;
        if( pNode->pData ){
          pNode->mxTrans = pChng->oldTrans;
        }else{
          kvmemRemoveNode(p, pNode);
        }
        kvmemDataUnref(p->base.pEnv, pChng->pData);
        pNext = pChng->pNext;
        sqlite4_free(p->base.pEnv, pChng);
      }
    }else{
      KVMemChng **pp;
      int iFrom = p->base.iTransLevel-2;
      int iTo = p->base.iTransLevel-3;
      assert( iTo>=0 );

................................................................................
  assert( p->iMagicKVMemBase==SQLITE_KVMEMBASE_MAGIC );
  assert( iLevel>=0 );
  while( p->base.iTransLevel>iLevel && p->base.iTransLevel>1 ){
    KVMemChng *pChng, *pNext;
    for(pChng=p->apLog[p->base.iTransLevel-2]; pChng; pChng=pNext){
      KVMemNode *pNode = pChng->pNode;
      if( pChng->pData || pChng->oldTrans>0 ){
        kvmemDataUnref(p->base.pEnv, pNode->pData);
        pNode->pData = pChng->pData;
        pNode->mxTrans = pChng->oldTrans;
      }else{
        kvmemRemoveNode(p, pNode);
      }
      pNext = pChng->pNext;
      sqlite4_free(p->base.pEnv, pChng);
    }
    p->apLog[p->base.iTransLevel-2] = 0;
    p->base.iTransLevel--;
  }
  p->base.iTransLevel = iLevel;
  return SQLITE_OK;
}
................................................................................
){
  KVMem *p = (KVMem*)pKVStore;
  KVMemNode *pNew, *pNode;
  KVMemData *pData;
  KVMemChng *pChng;
  assert( p->iMagicKVMemBase==SQLITE_KVMEMBASE_MAGIC );
  assert( p->base.iTransLevel>=2 );
  pData = kvmemDataNew(p->base.pEnv, aData, nData);
  if( pData==0 ) return SQLITE_NOMEM;
  if( p->pRoot==0 ){
    pNode = pNew = kvmemNewNode(p, aKey, nKey);
    if( pNew==0 ) goto KVMemReplace_nomem;
    pNew->pUp = 0;
  }else{
    pNode = p->pRoot;
................................................................................
          pNode->pAfter = pNew = kvmemNewNode(p, aKey, nKey);
          if( pNew==0 ) goto KVMemReplace_nomem;
          pNew->pUp = pNode;
          break;
        }
      }else{
        if( pNode->mxTrans==p->base.iTransLevel ){
          kvmemDataUnref(p->base.pEnv, pNode->pData);
        }else{
          pChng = kvmemNewChng(p, pNode);
          if( pChng==0 ) goto KVMemReplace_nomem;
        }
        pNode->pData = pData;
        return SQLITE_OK;
      }
................................................................................
  }
  pNew->pData = pData;
  pNew->height = 1;
  p->pRoot = kvmemBalance(pNew);
  return SQLITE_OK;

KVMemReplace_nomem:
  kvmemDataUnref(p->base.pEnv, pData);
  return SQLITE_NOMEM;
}

/*
** Create a new cursor object.
*/
static int kvmemOpenCursor(KVStore *pKVStore, KVCursor **ppKVCursor){
  KVMem *p = (KVMem*)pKVStore;
  KVMemCursor *pCur;
  assert( p->iMagicKVMemBase==SQLITE_KVMEMBASE_MAGIC );
  pCur = sqlite4_malloc(p->base.pEnv, sizeof(*pCur) );
  if( pCur==0 ){
    *ppKVCursor = 0;
    return SQLITE_NOMEM;
  }
  memset(pCur, 0, sizeof(*pCur));
  pCur->pOwner = p;
  p->nCursor++;
................................................................................

/*
** Reset a cursor
*/
static int kvmemReset(KVCursor *pKVCursor){
  KVMemCursor *pCur = (KVMemCursor*)pKVCursor;
  assert( pCur->iMagicKVMemCur==SQLITE_KVMEMCUR_MAGIC );
  kvmemDataUnref(pCur->base.pEnv, pCur->pData);
  pCur->pData = 0;
  kvmemNodeUnref(pCur->base.pEnv, pCur->pNode);
  pCur->pNode = 0;
  return SQLITE_OK;
}

/*
** Destroy a cursor object
*/
................................................................................
  KVMemCursor *pCur = (KVMemCursor*)pKVCursor;
  if( pCur ){
    assert( pCur->iMagicKVMemCur==SQLITE_KVMEMCUR_MAGIC );
    assert( pCur->pOwner->iMagicKVMemBase==SQLITE_KVMEMBASE_MAGIC );
    pCur->pOwner->nCursor--;
    kvmemReset(pKVCursor);
    memset(pCur, 0, sizeof(*pCur));
    sqlite4_free(pCur->base.pEnv, pCur);
  }
  return SQLITE_OK;
}

/*
** Move a cursor to the next non-deleted node.
*/
................................................................................
      if( direction>0 ){
        pBest = pNode;
        rc = SQLITE_INEXACT;
      }
      pNode = pNode->pBefore;
    }
  }
  kvmemNodeUnref(pCur->base.pEnv, pCur->pNode);
  kvmemDataUnref(pCur->base.pEnv, pCur->pData);
  if( pBest ){
    pCur->pNode = kvmemNodeRef(pBest);
    pCur->pData = kvmemDataRef(pBest->pData);

    /* The cursor currently points to a deleted node. If parameter 'direction'
    ** was zero (exact matches only), then the search has failed - return
    ** SQLITE_NOTFOUND. Otherwise, advance to the next (if direction is +ve)
................................................................................
  if( pNode==0 ) return SQLITE_OK;
  if( pNode->pData==0 ) return SQLITE_OK;
  if( pNode->mxTrans<p->base.iTransLevel ){
    pChng = kvmemNewChng(p, pNode);
    if( pChng==0 ) return SQLITE_NOMEM;
    assert( pNode->pData==0 );
  }else{
    kvmemDataUnref(pCur->base.pEnv, pNode->pData);
    pNode->pData = 0;
  }
  return SQLITE_OK;
}

/*
** Return the key of the node the cursor is pointing to.
................................................................................
}

/*
** Destructor for the entire in-memory storage tree.
*/
static int kvmemClose(KVStore *pKVStore){
  KVMem *p = (KVMem*)pKVStore;
  sqlite4_env *pEnv;
  if( p==0 ) return SQLITE_OK;
  assert( p->iMagicKVMemBase==SQLITE_KVMEMBASE_MAGIC );
  assert( p->nCursor==0 );
  pEnv = p->base.pEnv;
  if( p->base.iTransLevel ){
    kvmemCommitPhaseOne(pKVStore, 0);
    kvmemCommitPhaseTwo(pKVStore, 0);
  }
  sqlite4_free(pEnv, p->apLog);
  kvmemClearTree(pEnv, p->pRoot);
  memset(p, 0, sizeof(*p));
  sqlite4_free(pEnv, p);
  return SQLITE_OK;
}

static int kvmemControl(KVStore *pKVStore, int op, void *pArg){
  return SQLITE_NOTFOUND;
}

................................................................................
*/
int sqlite4KVStoreOpenMem(
  sqlite4_env *pEnv,              /* Runtime environment */
  KVStore **ppKVStore,            /* OUT: Write the new KVStore here */
  const char *zName,              /* Name of in-memory storage unit */
  unsigned openFlags              /* Flags */
){
  KVMem *pNew = sqlite4_malloc(pEnv, sizeof(*pNew) );
  if( pNew==0 ) return SQLITE_NOMEM;
  memset(pNew, 0, sizeof(*pNew));
  pNew->base.pStoreVfunc = &kvmemMethods;
  pNew->base.pEnv = pEnv;
  pNew->iMagicKVMemBase = SQLITE_KVMEMBASE_MAGIC;
  pNew->openFlags = openFlags;
  *ppKVStore = (KVStore*)pNew;
  return SQLITE_OK;
}

Changes to src/legacy.c.

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
exec_out:
  if( pStmt ) sqlite4VdbeFinalize((Vdbe *)pStmt);
  sqlite4DbFree(db, azCols);

  rc = sqlite4ApiExit(db, rc);
  if( rc!=SQLITE_OK && ALWAYS(rc==sqlite4_errcode(db)) && pzErrMsg ){
    int nErrMsg = 1 + sqlite4Strlen30(sqlite4_errmsg(db));
    *pzErrMsg = sqlite4Malloc(nErrMsg);
    if( *pzErrMsg ){
      memcpy(*pzErrMsg, sqlite4_errmsg(db), nErrMsg);
    }else{
      rc = SQLITE_NOMEM;
      sqlite4Error(db, SQLITE_NOMEM, 0);
    }
  }else if( pzErrMsg ){
    *pzErrMsg = 0;
  }

  sqlite4_mutex_leave(db->mutex);
  return rc;
}







|













122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
exec_out:
  if( pStmt ) sqlite4VdbeFinalize((Vdbe *)pStmt);
  sqlite4DbFree(db, azCols);

  rc = sqlite4ApiExit(db, rc);
  if( rc!=SQLITE_OK && ALWAYS(rc==sqlite4_errcode(db)) && pzErrMsg ){
    int nErrMsg = 1 + sqlite4Strlen30(sqlite4_errmsg(db));
    *pzErrMsg = sqlite4Malloc(0, nErrMsg);
    if( *pzErrMsg ){
      memcpy(*pzErrMsg, sqlite4_errmsg(db), nErrMsg);
    }else{
      rc = SQLITE_NOMEM;
      sqlite4Error(db, SQLITE_NOMEM, 0);
    }
  }else if( pzErrMsg ){
    *pzErrMsg = 0;
  }

  sqlite4_mutex_leave(db->mutex);
  return rc;
}

Changes to src/lempar.c.

180
181
182
183
184
185
186

187
188
189
190
191
192
193
...
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286

287
288
289
290
291
292
293
...
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
  ParseARG_SDECL                /* A place to hold %extra_argument */
#if YYSTACKDEPTH<=0
  int yystksz;                  /* Current side of the stack */
  yyStackEntry *yystack;        /* The parser's stack */
#else
  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
#endif

};
typedef struct yyParser yyParser;

#ifndef NDEBUG
#include <stdio.h>
static FILE *yyTraceFILE = 0;
static char *yyTracePrompt = 0;
................................................................................
** Inputs:
** A pointer to the function used to allocate memory.
**
** Outputs:
** A pointer to a parser.  This pointer is used in subsequent calls
** to Parse and ParseFree.
*/
void *ParseAlloc(void *(*mallocProc)(size_t)){
  yyParser *pParser;
  pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
  if( pParser ){
    pParser->yyidx = -1;
#ifdef YYTRACKMAXSTACKDEPTH
    pParser->yyidxMax = 0;
#endif
#if YYSTACKDEPTH<=0
    pParser->yystack = NULL;
    pParser->yystksz = 0;
    yyGrowStack(pParser);
#endif

  }
  return pParser;
}

/* The following function deletes the value associated with a
** symbol.  The symbol can be either a terminal or nonterminal.
** "yymajor" is the symbol code, and "yypminor" is a pointer to
................................................................................
** <li>  A pointer to the parser.  This should be a pointer
**       obtained from ParseAlloc.
** <li>  A pointer to a function used to reclaim memory obtained
**       from malloc.
** </ul>
*/
void ParseFree(
  void *p,                    /* The parser to be deleted */
  void (*freeProc)(void*)     /* Function used to reclaim memory */
){
  yyParser *pParser = (yyParser*)p;
  /* In SQLite, we never try to destroy a parser that was not successfully
  ** created in the first place. */
  if( NEVER(pParser==0) ) return;
  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
#if YYSTACKDEPTH<=0
  free(pParser->yystack);
#endif
  (*freeProc)((void*)pParser);
}

/*
** Return the peak depth of the stack for a parser.
*/
#ifdef YYTRACKMAXSTACKDEPTH
int ParseStackPeak(void *p){







>







 







|

|










>







 







|
|









|







180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
...
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
...
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
  ParseARG_SDECL                /* A place to hold %extra_argument */
#if YYSTACKDEPTH<=0
  int yystksz;                  /* Current side of the stack */
  yyStackEntry *yystack;        /* The parser's stack */
#else
  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
#endif
  void *pEnv;                   /* Malloc context */
};
typedef struct yyParser yyParser;

#ifndef NDEBUG
#include <stdio.h>
static FILE *yyTraceFILE = 0;
static char *yyTracePrompt = 0;
................................................................................
** Inputs:
** A pointer to the function used to allocate memory.
**
** Outputs:
** A pointer to a parser.  This pointer is used in subsequent calls
** to Parse and ParseFree.
*/
void *ParseAlloc(void *(*mallocProc)(void*,size_t), void *pEnv){
  yyParser *pParser;
  pParser = (yyParser*)(*mallocProc)(pEnv, (size_t)sizeof(yyParser) );
  if( pParser ){
    pParser->yyidx = -1;
#ifdef YYTRACKMAXSTACKDEPTH
    pParser->yyidxMax = 0;
#endif
#if YYSTACKDEPTH<=0
    pParser->yystack = NULL;
    pParser->yystksz = 0;
    yyGrowStack(pParser);
#endif
    pParser->pEnv = pEnv;
  }
  return pParser;
}

/* The following function deletes the value associated with a
** symbol.  The symbol can be either a terminal or nonterminal.
** "yymajor" is the symbol code, and "yypminor" is a pointer to
................................................................................
** <li>  A pointer to the parser.  This should be a pointer
**       obtained from ParseAlloc.
** <li>  A pointer to a function used to reclaim memory obtained
**       from malloc.
** </ul>
*/
void ParseFree(
  void *p,                      /* The parser to be deleted */
  void (*freeProc)(void*,void*) /* Function used to reclaim memory */
){
  yyParser *pParser = (yyParser*)p;
  /* In SQLite, we never try to destroy a parser that was not successfully
  ** created in the first place. */
  if( NEVER(pParser==0) ) return;
  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
#if YYSTACKDEPTH<=0
  free(pParser->yystack);
#endif
  (*freeProc)(pParser->pEnv, (void*)pParser);
}

/*
** Return the peak depth of the stack for a parser.
*/
#ifdef YYTRACKMAXSTACKDEPTH
int ParseStackPeak(void *p){

Changes to src/lsm_sorted.c.

4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
....
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
  int nMin,
  SortedRun *pRun
){
  int i = 0;
  char *zSeg;

  zSeg = segToString(pEnv, pRun, nMin);
  i += snprintf(&aBuf[i], nBuf-i, "%s", zSeg);
  lsmFree(pEnv, zSeg);

  return i;
}

void sortedDumpPage(lsm_db *pDb, SortedRun *pRun, Page *pPg, int bVals){
  Blob blob = {0, 0, 0};         /* Blob used for keys */
................................................................................
          fileToString(pDb->pEnv, zLeft, sizeof(zLeft), 28, aLeft[i]); 
        }
        if( i<nRight ){ 
          fileToString(pDb->pEnv, zRight, sizeof(zRight), 28, aRight[i]); 
        }

        if( i==0 ){
          snprintf(zLevel, sizeof(zLevel), "L%d:", iLevel);
        }else{
          zLevel[0] = '\0';
        }

        if( nRight==0 ){
          iPad = 28 - (strlen(zLeft)/2) ;
        }







|







 







|







4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
....
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
  int nMin,
  SortedRun *pRun
){
  int i = 0;
  char *zSeg;

  zSeg = segToString(pEnv, pRun, nMin);
  i += sqlite4_snprintf(&aBuf[i], nBuf-i, "%s", zSeg);
  lsmFree(pEnv, zSeg);

  return i;
}

void sortedDumpPage(lsm_db *pDb, SortedRun *pRun, Page *pPg, int bVals){
  Blob blob = {0, 0, 0};         /* Blob used for keys */
................................................................................
          fileToString(pDb->pEnv, zLeft, sizeof(zLeft), 28, aLeft[i]); 
        }
        if( i<nRight ){ 
          fileToString(pDb->pEnv, zRight, sizeof(zRight), 28, aRight[i]); 
        }

        if( i==0 ){
          sqlite4_snprintf(zLevel, sizeof(zLevel), "L%d:", iLevel);
        }else{
          zLevel[0] = '\0';
        }

        if( nRight==0 ){
          iPad = 28 - (strlen(zLeft)/2) ;
        }

Changes to src/main.c.

22
23
24
25
26
27
28





29
30
31
32
33
34
35
..
45
46
47
48
49
50
51
52
53
54
55
56

57
58
59
60
61
62
63
...
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
...
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
...
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
...
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
....
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
....
1675
1676
1677
1678
1679
1680
1681
1682

1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
....
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
....
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
....
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
....
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
....
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
#ifdef SQLITE_ENABLE_RTREE
# include "rtree.h"
#endif
#ifdef SQLITE_ENABLE_ICU
# include "sqliteicu.h"
#endif






#ifndef SQLITE_AMALGAMATION
/* IMPLEMENTATION-OF: R-46656-45156 The sqlite4_version[] string constant
** contains the text of SQLITE_VERSION macro. 
*/
const char sqlite4_version[] = SQLITE_VERSION;
#endif

................................................................................
const char *sqlite4_sourceid(void){ return SQLITE_SOURCE_ID; }

/* IMPLEMENTATION-OF: R-35210-63508 The sqlite4_libversion_number() function
** returns an integer equal to SQLITE_VERSION_NUMBER.
*/
int sqlite4_libversion_number(void){ return SQLITE_VERSION_NUMBER; }

/* IMPLEMENTATION-OF: R-20790-14025 The sqlite4_threadsafe() function returns
** zero if and only if SQLite was compiled with mutexing code omitted due to
** the SQLITE_THREADSAFE compile-time option being set to 0.
*/
int sqlite4_threadsafe(void){ return SQLITE_THREADSAFE; }


#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
/*
** If the following function pointer is not NULL and if
** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
** I/O active are written using this function.  These messages
** are intended for debugging activity only.
................................................................................
  ** malloc subsystem - this implies that the allocation of a static
  ** mutex must not require support from the malloc subsystem.
  */
  MUTEX_LOGIC( pMaster = sqlite4MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  sqlite4_mutex_enter(pMaster);
  pEnv->isMutexInit = 1;
  if( !pEnv->isMallocInit ){
    rc = sqlite4MallocInit();
  }
  if( rc==SQLITE_OK ){
    pEnv->isMallocInit = 1;
    if( !pEnv->pInitMutex ){
      pEnv->pInitMutex =
           sqlite4MutexAlloc(SQLITE_MUTEX_RECURSIVE);
      if( pEnv->bCoreMutex && !pEnv->pInitMutex ){
................................................................................
    SQLITE_EXTRA_SHUTDOWN();
#endif
    /*sqlite4_os_end();*/
    /* sqlite4_reset_auto_extension(); */
    pEnv->isInit = 0;
  }
  if( pEnv->isMallocInit ){
    sqlite4MallocEnd();
    pEnv->isMallocInit = 0;
  }
  if( pEnv->isMutexInit ){
    sqlite4MutexEnd();
    pEnv->isMutexInit = 0;
  }

  return SQLITE_OK;
}

/*
** This API allows applications to modify the configuration described by
** an sqlite4_env object.
................................................................................
    return SQLITE_BUSY;
  }
  /* Free any existing lookaside buffer for this handle before
  ** allocating a new one so we don't have to have space for 
  ** both at the same time.
  */
  if( db->lookaside.bMalloced ){
    sqlite4_free(db->lookaside.pStart);
  }
  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  ** than a pointer to be useful.
  */
  sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  if( cnt<0 ) cnt = 0;
  if( sz==0 || cnt==0 ){
    sz = 0;
    pStart = 0;
  }else if( pBuf==0 ){
    sqlite4BeginBenignMalloc();
    pStart = sqlite4Malloc( sz*cnt );  /* IMP: R-61949-35727 */
    sqlite4EndBenignMalloc();
    if( pStart ) cnt = sqlite4MallocSize(pStart)/sz;
  }else{
    pStart = pBuf;
  }
  db->lookaside.pStart = pStart;
  db->lookaside.pFree = 0;
  db->lookaside.sz = (u16)sz;
  if( pStart ){
................................................................................
  */
  sqlite4DbFree(db, db->aDb[1].pSchema);
  sqlite4_mutex_leave(db->mutex);
  db->magic = SQLITE_MAGIC_CLOSED;
  sqlite4_mutex_free(db->mutex);
  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
  if( db->lookaside.bMalloced ){
    sqlite4_free(db->lookaside.pStart);
  }
  sqlite4_free(db);
  return SQLITE_OK;
}

/*
** Return a static string that describes the kind of error specified in the
** argument.
*/
................................................................................
    char *zOpt;
    int eState;                   /* Parser state when parsing URI */
    int iIn;                      /* Input character index */
    int iOut = 0;                 /* Output character index */
    int nByte = nUri+2;           /* Bytes of space to allocate */

    for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
    zFile = sqlite4_malloc(nByte);
    if( !zFile ) return SQLITE_NOMEM;

    /* Discard the scheme and authority segments of the URI. */
    if( zUri[5]=='/' && zUri[6]=='/' ){
      iIn = 7;
      while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;

      if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
        *pzErrMsg = sqlite4_mprintf("invalid uri authority: %.*s", 
            iIn-7, &zUri[7]);
        rc = SQLITE_ERROR;
        goto parse_uri_out;
      }
    }else{
      iIn = 5;
    }
................................................................................
          const char *z = aMode[i].z;
          if( nVal==sqlite4Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
            mode = aMode[i].mode;
            break;
          }
        }
        if( mode==0 ){
          *pzErrMsg = sqlite4_mprintf("no such %s mode: %s", zModeType, zVal);

          rc = SQLITE_ERROR;
          goto parse_uri_out;
        }
        if( mode>limit ){
          *pzErrMsg = sqlite4_mprintf("%s mode not allowed: %s",
                                      zModeType, zVal);
          rc = SQLITE_PERM;
          goto parse_uri_out;
        }
        flags = (flags & ~mask) | mode;
      }

      zOpt = &zVal[nVal+1];
    }

  }else{
    zFile = sqlite4_malloc(nUri+2);
    if( !zFile ) return SQLITE_NOMEM;
    memcpy(zFile, zUri, nUri);
    zFile[nUri] = '\0';
    zFile[nUri+1] = '\0';
  }

 parse_uri_out:
  if( rc!=SQLITE_OK ){
    sqlite4_free(zFile);
    zFile = 0;
  }
  *pFlags = flags;
  *pzFile = zFile;
  return rc;
}

................................................................................
  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
    isThreadsafe = 1;
  }else{
    isThreadsafe = pEnv->bFullMutex;
  }

  /* Allocate the sqlite data structure */
  db = sqlite4MallocZero( sizeof(sqlite4) );
  if( db==0 ) goto opendb_out;
  db->pEnv = pEnv;
  if( isThreadsafe ){
    db->mutex = sqlite4MutexAlloc(SQLITE_MUTEX_RECURSIVE);
    if( db->mutex==0 ){
      sqlite4_free(db);
      db = 0;
      goto opendb_out;
    }
  }
  sqlite4_mutex_enter(db->mutex);
  db->nDb = 2;
  db->magic = SQLITE_MAGIC_BUSY;
................................................................................
  db->nextAutovac = -1;
  db->nextPagesize = 0;
  db->flags |=  SQLITE_AutoIndex
                 | SQLITE_EnableTrigger
                 | SQLITE_ForeignKeys
            ;

  sqlite4HashInit(&db->aCollSeq);
#ifndef SQLITE_OMIT_VIRTUALTABLE
  sqlite4HashInit(&db->aModule);
#endif

  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  ** and UTF-16, so add a version for each to avoid any unnecessary
  ** conversions. The only error that can occur here is a malloc() failure.
  */
  createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0, 0);
................................................................................

  /* Parse the filename/URI argument. */
  db->openFlags = flags;
  rc = sqlite4ParseUri(pEnv, zFilename, &flags, &zOpen, &zErrMsg);
  if( rc!=SQLITE_OK ){
    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
    sqlite4Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
    sqlite4_free(zErrMsg);
    goto opendb_out;
  }

  /* Open the backend database driver */
  rc = sqlite4KVStoreOpen(db, "main", zOpen, &db->aDb[0].pKV, 0);
  if( rc!=SQLITE_OK ){
    if( rc==SQLITE_IOERR_NOMEM ){
................................................................................
  sqlite4Error(db, rc, 0);

  /* Enable the lookaside-malloc subsystem */
  setupLookaside(db, 0, pEnv->szLookaside,
                        pEnv->nLookaside);

opendb_out:
  sqlite4_free(zOpen);
  if( db ){
    assert( db->mutex!=0 || isThreadsafe==0 || pEnv->bFullMutex==0 );
    sqlite4_mutex_leave(db->mutex);
  }
  rc = sqlite4_errcode(db);
  assert( db!=0 || rc==SQLITE_NOMEM );
  if( rc==SQLITE_NOMEM ){
................................................................................
    */
    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
      typedef void (*void_function)(void);
      void_function xBenignBegin;
      void_function xBenignEnd;
      xBenignBegin = va_arg(ap, void_function);
      xBenignEnd = va_arg(ap, void_function);
      sqlite4BenignMallocHooks(xBenignBegin, xBenignEnd);
      break;
    }

    /*
    **  sqlite4_test_control(SQLITE_TESTCTRL_ASSERT, int X)
    **
    ** This action provides a run-time test to see whether or not







>
>
>
>
>







 







|
|
|
|
|
>







 







|







 







|


<
<
<
<







 







|











|
|
|
|







 







|

|







 







|








|







 







|
>




|











|








|







 







|





|







 







|

|







 







|







 







|







 







|







22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
..
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
...
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
...
236
237
238
239
240
241
242
243
244
245




246
247
248
249
250
251
252
...
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
...
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
....
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
....
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
....
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
....
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
....
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
....
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
....
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
#ifdef SQLITE_ENABLE_RTREE
# include "rtree.h"
#endif
#ifdef SQLITE_ENABLE_ICU
# include "sqliteicu.h"
#endif

/*
** Dummy function used as a unique symbol for SQLITE_DYNAMIC
*/
void sqlite4_dynamic(void *p){ (void)p; }

#ifndef SQLITE_AMALGAMATION
/* IMPLEMENTATION-OF: R-46656-45156 The sqlite4_version[] string constant
** contains the text of SQLITE_VERSION macro. 
*/
const char sqlite4_version[] = SQLITE_VERSION;
#endif

................................................................................
const char *sqlite4_sourceid(void){ return SQLITE_SOURCE_ID; }

/* IMPLEMENTATION-OF: R-35210-63508 The sqlite4_libversion_number() function
** returns an integer equal to SQLITE_VERSION_NUMBER.
*/
int sqlite4_libversion_number(void){ return SQLITE_VERSION_NUMBER; }

/* Return the thread-safety setting.
*/
int sqlite4_threadsafe(sqlite4_env *pEnv){
  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;
  return pEnv->bCoreMutex + pEnv->bFullMutex;
}

#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
/*
** If the following function pointer is not NULL and if
** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
** I/O active are written using this function.  These messages
** are intended for debugging activity only.
................................................................................
  ** malloc subsystem - this implies that the allocation of a static
  ** mutex must not require support from the malloc subsystem.
  */
  MUTEX_LOGIC( pMaster = sqlite4MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  sqlite4_mutex_enter(pMaster);
  pEnv->isMutexInit = 1;
  if( !pEnv->isMallocInit ){
    rc = sqlite4MallocInit(pEnv);
  }
  if( rc==SQLITE_OK ){
    pEnv->isMallocInit = 1;
    if( !pEnv->pInitMutex ){
      pEnv->pInitMutex =
           sqlite4MutexAlloc(SQLITE_MUTEX_RECURSIVE);
      if( pEnv->bCoreMutex && !pEnv->pInitMutex ){
................................................................................
    SQLITE_EXTRA_SHUTDOWN();
#endif
    /*sqlite4_os_end();*/
    /* sqlite4_reset_auto_extension(); */
    pEnv->isInit = 0;
  }
  if( pEnv->isMallocInit ){
    sqlite4MallocEnd(pEnv);
    pEnv->isMallocInit = 0;
  }





  return SQLITE_OK;
}

/*
** This API allows applications to modify the configuration described by
** an sqlite4_env object.
................................................................................
    return SQLITE_BUSY;
  }
  /* Free any existing lookaside buffer for this handle before
  ** allocating a new one so we don't have to have space for 
  ** both at the same time.
  */
  if( db->lookaside.bMalloced ){
    sqlite4_free(db->pEnv, db->lookaside.pStart);
  }
  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  ** than a pointer to be useful.
  */
  sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  if( cnt<0 ) cnt = 0;
  if( sz==0 || cnt==0 ){
    sz = 0;
    pStart = 0;
  }else if( pBuf==0 ){
    sqlite4BeginBenignMalloc(db->pEnv);
    pStart = sqlite4Malloc(db->pEnv, sz*cnt );  /* IMP: R-61949-35727 */
    sqlite4EndBenignMalloc(db->pEnv);
    if( pStart ) cnt = sqlite4MallocSize(db->pEnv, pStart)/sz;
  }else{
    pStart = pBuf;
  }
  db->lookaside.pStart = pStart;
  db->lookaside.pFree = 0;
  db->lookaside.sz = (u16)sz;
  if( pStart ){
................................................................................
  */
  sqlite4DbFree(db, db->aDb[1].pSchema);
  sqlite4_mutex_leave(db->mutex);
  db->magic = SQLITE_MAGIC_CLOSED;
  sqlite4_mutex_free(db->mutex);
  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
  if( db->lookaside.bMalloced ){
    sqlite4_free(db->pEnv, db->lookaside.pStart);
  }
  sqlite4_free(db->pEnv, db);
  return SQLITE_OK;
}

/*
** Return a static string that describes the kind of error specified in the
** argument.
*/
................................................................................
    char *zOpt;
    int eState;                   /* Parser state when parsing URI */
    int iIn;                      /* Input character index */
    int iOut = 0;                 /* Output character index */
    int nByte = nUri+2;           /* Bytes of space to allocate */

    for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
    zFile = sqlite4_malloc(pEnv, nByte);
    if( !zFile ) return SQLITE_NOMEM;

    /* Discard the scheme and authority segments of the URI. */
    if( zUri[5]=='/' && zUri[6]=='/' ){
      iIn = 7;
      while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;

      if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
        *pzErrMsg = sqlite4_mprintf(pEnv,"invalid uri authority: %.*s", 
            iIn-7, &zUri[7]);
        rc = SQLITE_ERROR;
        goto parse_uri_out;
      }
    }else{
      iIn = 5;
    }
................................................................................
          const char *z = aMode[i].z;
          if( nVal==sqlite4Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
            mode = aMode[i].mode;
            break;
          }
        }
        if( mode==0 ){
          *pzErrMsg = sqlite4_mprintf(pEnv, "no such %s mode: %s",
                                      zModeType, zVal);
          rc = SQLITE_ERROR;
          goto parse_uri_out;
        }
        if( mode>limit ){
          *pzErrMsg = sqlite4_mprintf(pEnv, "%s mode not allowed: %s",
                                      zModeType, zVal);
          rc = SQLITE_PERM;
          goto parse_uri_out;
        }
        flags = (flags & ~mask) | mode;
      }

      zOpt = &zVal[nVal+1];
    }

  }else{
    zFile = sqlite4_malloc(pEnv, nUri+2);
    if( !zFile ) return SQLITE_NOMEM;
    memcpy(zFile, zUri, nUri);
    zFile[nUri] = '\0';
    zFile[nUri+1] = '\0';
  }

 parse_uri_out:
  if( rc!=SQLITE_OK ){
    sqlite4_free(pEnv, zFile);
    zFile = 0;
  }
  *pFlags = flags;
  *pzFile = zFile;
  return rc;
}

................................................................................
  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
    isThreadsafe = 1;
  }else{
    isThreadsafe = pEnv->bFullMutex;
  }

  /* Allocate the sqlite data structure */
  db = sqlite4MallocZero(pEnv, sizeof(sqlite4) );
  if( db==0 ) goto opendb_out;
  db->pEnv = pEnv;
  if( isThreadsafe ){
    db->mutex = sqlite4MutexAlloc(SQLITE_MUTEX_RECURSIVE);
    if( db->mutex==0 ){
      sqlite4_free(pEnv, db);
      db = 0;
      goto opendb_out;
    }
  }
  sqlite4_mutex_enter(db->mutex);
  db->nDb = 2;
  db->magic = SQLITE_MAGIC_BUSY;
................................................................................
  db->nextAutovac = -1;
  db->nextPagesize = 0;
  db->flags |=  SQLITE_AutoIndex
                 | SQLITE_EnableTrigger
                 | SQLITE_ForeignKeys
            ;

  sqlite4HashInit(pEnv, &db->aCollSeq);
#ifndef SQLITE_OMIT_VIRTUALTABLE
  sqlite4HashInit(pEnv, &db->aModule);
#endif

  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  ** and UTF-16, so add a version for each to avoid any unnecessary
  ** conversions. The only error that can occur here is a malloc() failure.
  */
  createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0, 0);
................................................................................

  /* Parse the filename/URI argument. */
  db->openFlags = flags;
  rc = sqlite4ParseUri(pEnv, zFilename, &flags, &zOpen, &zErrMsg);
  if( rc!=SQLITE_OK ){
    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
    sqlite4Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
    sqlite4_free(pEnv, zErrMsg);
    goto opendb_out;
  }

  /* Open the backend database driver */
  rc = sqlite4KVStoreOpen(db, "main", zOpen, &db->aDb[0].pKV, 0);
  if( rc!=SQLITE_OK ){
    if( rc==SQLITE_IOERR_NOMEM ){
................................................................................
  sqlite4Error(db, rc, 0);

  /* Enable the lookaside-malloc subsystem */
  setupLookaside(db, 0, pEnv->szLookaside,
                        pEnv->nLookaside);

opendb_out:
  sqlite4_free(pEnv, zOpen);
  if( db ){
    assert( db->mutex!=0 || isThreadsafe==0 || pEnv->bFullMutex==0 );
    sqlite4_mutex_leave(db->mutex);
  }
  rc = sqlite4_errcode(db);
  assert( db!=0 || rc==SQLITE_NOMEM );
  if( rc==SQLITE_NOMEM ){
................................................................................
    */
    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
      typedef void (*void_function)(void);
      void_function xBenignBegin;
      void_function xBenignEnd;
      xBenignBegin = va_arg(ap, void_function);
      xBenignEnd = va_arg(ap, void_function);
      sqlite4BenignMallocHooks(0, xBenignBegin, xBenignEnd);
      break;
    }

    /*
    **  sqlite4_test_control(SQLITE_TESTCTRL_ASSERT, int X)
    **
    ** This action provides a run-time test to see whether or not

Changes to src/malloc.c.

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
..
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98

99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115

116
117
118
119
120
121
122
123
...
128
129
130
131
132
133
134
135
136
137
138

139
140
141
142
143
144

145
146
147
148
149
150
151
152
153
154
155
156
157
158
159

160
161
162

163
164
165
166
167
168
169
170
171
172
173
174
...
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248

249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
...
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
...
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
static SQLITE_WSD struct Mem0Global {
  sqlite4_mutex *mutex;         /* Mutex to serialize access */
} mem0 = { 0 };

/*
** Initialize the memory allocation subsystem.
*/
int sqlite4MallocInit(void){
  if( sqlite4DefaultEnv.m.xMalloc==0 ){
    sqlite4MemSetDefault(0);
  }
  memset(&mem0, 0, sizeof(mem0));
  if( sqlite4DefaultEnv.bCoreMutex ){
    mem0.mutex = sqlite4MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  }
  return sqlite4DefaultEnv.m.xInit(sqlite4DefaultEnv.m.pAppData);
}

/*
** Deinitialize the memory allocation subsystem.
*/
void sqlite4MallocEnd(void){
  if( sqlite4DefaultEnv.m.xShutdown ){
    sqlite4DefaultEnv.m.xShutdown(sqlite4DefaultEnv.m.pAppData);
  }
  memset(&mem0, 0, sizeof(mem0));
}

/*
** Return the amount of memory currently checked out.
*/
................................................................................
  return mx;
}

/*
** Allocate memory.  This routine is like sqlite4_malloc() except that it
** assumes the memory subsystem has already been initialized.
*/
void *sqlite4Malloc(int n){
  void *p;
  sqlite4_env *pEnv = &sqlite4DefaultEnv;

  if( n<=0               /* IMP: R-65312-04917 */ 
   || n>=0x7fffff00
  ){
    /* A memory allocation of a number of bytes which is near the maximum
    ** signed integer value might cause an integer overflow inside of the
    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
    ** 255 bytes of overhead.  SQLite itself will never use anything near
    ** this amount.  The only way to reach the limit is with sqlite4_malloc() */
    p = 0;
  }else if( pEnv->bMemstat ){
    int nFull;
    sqlite4_mutex_enter(mem0.mutex);
    nFull = pEnv->m.xRoundup(n);
    sqlite4StatusSet(pEnv, SQLITE_ENVSTATUS_MALLOC_SIZE, n);
    p = pEnv->m.xMalloc(nFull);
    if( p ){
      nFull = sqlite4MallocSize(p);
      sqlite4StatusAdd(pEnv, SQLITE_ENVSTATUS_MEMORY_USED, nFull);
      sqlite4StatusAdd(pEnv, SQLITE_ENVSTATUS_MALLOC_COUNT, 1);
    }

    sqlite4_mutex_leave(mem0.mutex);
  }else{
    p = pEnv->m.xMalloc(n);
  }
  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
  return p;
}

/*
** This version of the memory allocation is for use by the application.
** First make sure the memory subsystem is initialized, then do the
** allocation.
*/
void *sqlite4_malloc(int n){
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite4_initialize(0) ) return 0;
#endif

  return sqlite4Malloc(n);
}


/*
** TRUE if p is a lookaside memory allocation from db
*/
#ifndef SQLITE_OMIT_LOOKASIDE
................................................................................
#define isLookaside(A,B) 0
#endif

/*
** Return the size of a memory allocation previously obtained from
** sqlite4Malloc() or sqlite4_malloc().
*/
int sqlite4MallocSize(void *p){
  assert( sqlite4MemdebugHasType(p, MEMTYPE_HEAP) );
  assert( sqlite4MemdebugNoType(p, MEMTYPE_DB) );
  return sqlite4DefaultEnv.m.xSize(p);

}
int sqlite4DbMallocSize(sqlite4 *db, void *p){
  assert( db==0 || sqlite4_mutex_held(db->mutex) );
  if( db && isLookaside(db, p) ){
    return db->lookaside.sz;
  }else{

    assert( sqlite4MemdebugHasType(p, MEMTYPE_DB) );
    assert( sqlite4MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
    assert( db!=0 || sqlite4MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
    return sqlite4DefaultEnv.m.xSize(p);
  }
}

/*
** Free memory previously obtained from sqlite4Malloc().
*/
void sqlite4_free(void *p){
  sqlite4_env *pEnv = &sqlite4DefaultEnv;
  if( p==0 ) return;  /* IMP: R-49053-54554 */
  assert( sqlite4MemdebugNoType(p, MEMTYPE_DB) );
  assert( sqlite4MemdebugHasType(p, MEMTYPE_HEAP) );

  if( pEnv->bMemstat ){
    sqlite4_mutex_enter(mem0.mutex);
    sqlite4StatusAdd(pEnv,SQLITE_ENVSTATUS_MEMORY_USED, -sqlite4MallocSize(p));

    sqlite4StatusAdd(pEnv,SQLITE_ENVSTATUS_MALLOC_COUNT, -1);
    pEnv->m.xFree(p);
    sqlite4_mutex_leave(mem0.mutex);
  }else{
    pEnv->m.xFree(p);
  }
}

/*
** Free memory that might be associated with a particular database
** connection.
*/
................................................................................
      return;
    }
  }
  assert( sqlite4MemdebugHasType(p, MEMTYPE_DB) );
  assert( sqlite4MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  assert( db!=0 || sqlite4MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  sqlite4MemdebugSetType(p, MEMTYPE_HEAP);
  sqlite4_free(p);
}

/*
** Change the size of an existing memory allocation
*/
void *sqlite4Realloc(void *pOld, int nBytes){
  int nOld, nNew;
  void *pNew;
  sqlite4_env *pEnv = &sqlite4DefaultEnv;

  if( pOld==0 ){
    return sqlite4Malloc(nBytes); /* IMP: R-28354-25769 */
  }
  if( nBytes<=0 ){
    sqlite4_free(pOld); /* IMP: R-31593-10574 */
    return 0;
  }
  if( nBytes>=0x7fffff00 ){
    /* The 0x7ffff00 limit term is explained in comments on sqlite4Malloc() */
    return 0;
  }
  nOld = sqlite4MallocSize(pOld);
  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  ** argument to xRealloc is always a value returned by a prior call to
  ** xRoundup. */
  nNew = pEnv->m.xRoundup(nBytes);
  if( nOld==nNew ){
    pNew = pOld;
  }else if( pEnv->bMemstat ){
    sqlite4_mutex_enter(mem0.mutex);
    sqlite4StatusSet(pEnv, SQLITE_ENVSTATUS_MALLOC_SIZE, nBytes);
    assert( sqlite4MemdebugHasType(pOld, MEMTYPE_HEAP) );
    assert( sqlite4MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
    pNew = pEnv->m.xRealloc(pOld, nNew);
    if( pNew ){
      nNew = sqlite4MallocSize(pNew);
      sqlite4StatusAdd(pEnv, SQLITE_ENVSTATUS_MEMORY_USED, nNew-nOld);
    }
    sqlite4_mutex_leave(mem0.mutex);
  }else{
    pNew = pEnv->m.xRealloc(pOld, nNew);
  }
  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
  return pNew;
}

/*
** The public interface to sqlite4Realloc.  Make sure that the memory
** subsystem is initialized prior to invoking sqliteRealloc.
*/
void *sqlite4_realloc(void *pOld, int n){
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite4_initialize(0) ) return 0;
#endif

  return sqlite4Realloc(pOld, n);
}


/*
** Allocate and zero memory.
*/ 
void *sqlite4MallocZero(int n){
  void *p = sqlite4Malloc(n);
  if( p ){
    memset(p, 0, n);
  }
  return p;
}

/*
................................................................................
    }
  }
#else
  if( db && db->mallocFailed ){
    return 0;
  }
#endif
  p = sqlite4Malloc(n);
  if( !p && db ){
    db->mallocFailed = 1;
  }
  sqlite4MemdebugSetType(p, MEMTYPE_DB |
         ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  return p;
}
................................................................................
        memcpy(pNew, p, db->lookaside.sz);
        sqlite4DbFree(db, p);
      }
    }else{
      assert( sqlite4MemdebugHasType(p, MEMTYPE_DB) );
      assert( sqlite4MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
      sqlite4MemdebugSetType(p, MEMTYPE_HEAP);
      pNew = sqlite4_realloc(p, n);
      if( !pNew ){
        sqlite4MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
        db->mallocFailed = 1;
      }
      sqlite4MemdebugSetType(pNew, MEMTYPE_DB | 
            (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
    }







|
|
|


|


|





|
|
|







 







|

|











|

<
<
|

|



>


|










|

|

>
|







 







|


|
>






>



|






|
<



>


|
>

|


|







 







|





|


|


|


|






|
|
<
<
<
<
<
|




|

|




|









|

|

>
|






|
|







 







|







 







|







21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
..
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90


91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
...
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157

158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
...
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220





221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
...
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
...
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
static SQLITE_WSD struct Mem0Global {
  sqlite4_mutex *mutex;         /* Mutex to serialize access */
} mem0 = { 0 };

/*
** Initialize the memory allocation subsystem.
*/
int sqlite4MallocInit(sqlite4_env *pEnv){
  if( pEnv->m.xMalloc==0 ){
    sqlite4MemSetDefault(pEnv);
  }
  memset(&mem0, 0, sizeof(mem0));
  if( pEnv->bCoreMutex ){
    mem0.mutex = sqlite4MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  }
  return pEnv->m.xInit(pEnv->m.pAppData);
}

/*
** Deinitialize the memory allocation subsystem.
*/
void sqlite4MallocEnd(sqlite4_env *pEnv){
  if( pEnv->m.xShutdown ){
    pEnv->m.xShutdown(pEnv->m.pAppData);
  }
  memset(&mem0, 0, sizeof(mem0));
}

/*
** Return the amount of memory currently checked out.
*/
................................................................................
  return mx;
}

/*
** Allocate memory.  This routine is like sqlite4_malloc() except that it
** assumes the memory subsystem has already been initialized.
*/
void *sqlite4Malloc(sqlite4_env *pEnv, int n){
  void *p;
  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;

  if( n<=0               /* IMP: R-65312-04917 */ 
   || n>=0x7fffff00
  ){
    /* A memory allocation of a number of bytes which is near the maximum
    ** signed integer value might cause an integer overflow inside of the
    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
    ** 255 bytes of overhead.  SQLite itself will never use anything near
    ** this amount.  The only way to reach the limit is with sqlite4_malloc() */
    p = 0;
  }else if( pEnv->bMemstat ){
    int nFull = (n + 7)&~7;
    sqlite4_mutex_enter(mem0.mutex);


    p = pEnv->m.xMalloc(pEnv->m.pAppData, nFull);
    if( p ){
      nFull = sqlite4MallocSize(pEnv, p);
      sqlite4StatusAdd(pEnv, SQLITE_ENVSTATUS_MEMORY_USED, nFull);
      sqlite4StatusAdd(pEnv, SQLITE_ENVSTATUS_MALLOC_COUNT, 1);
    }
    sqlite4StatusSet(pEnv, SQLITE_ENVSTATUS_MALLOC_SIZE, n);
    sqlite4_mutex_leave(mem0.mutex);
  }else{
    p = pEnv->m.xMalloc(pEnv->m.pAppData, n);
  }
  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
  return p;
}

/*
** This version of the memory allocation is for use by the application.
** First make sure the memory subsystem is initialized, then do the
** allocation.
*/
void *sqlite4_malloc(sqlite4_env *pEnv, sqlite4_size_t n){
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite4_initialize(pEnv) ) return 0;
#endif
  if( n>0x7fff0000 ) return 0;
  return sqlite4Malloc(pEnv, (int)n);
}


/*
** TRUE if p is a lookaside memory allocation from db
*/
#ifndef SQLITE_OMIT_LOOKASIDE
................................................................................
#define isLookaside(A,B) 0
#endif

/*
** Return the size of a memory allocation previously obtained from
** sqlite4Malloc() or sqlite4_malloc().
*/
int sqlite4MallocSize(sqlite4_env *pEnv, void *p){
  assert( sqlite4MemdebugHasType(p, MEMTYPE_HEAP) );
  assert( sqlite4MemdebugNoType(p, MEMTYPE_DB) );
  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;
  return pEnv->m.xSize(pEnv->m.pAppData, p);
}
int sqlite4DbMallocSize(sqlite4 *db, void *p){
  assert( db==0 || sqlite4_mutex_held(db->mutex) );
  if( db && isLookaside(db, p) ){
    return db->lookaside.sz;
  }else{
    sqlite4_env *pEnv = db->pEnv;
    assert( sqlite4MemdebugHasType(p, MEMTYPE_DB) );
    assert( sqlite4MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
    assert( db!=0 || sqlite4MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
    return pEnv->m.xSize(pEnv->m.pAppData, p);
  }
}

/*
** Free memory previously obtained from sqlite4Malloc().
*/
void sqlite4_free(sqlite4_env *pEnv, void *p){

  if( p==0 ) return;  /* IMP: R-49053-54554 */
  assert( sqlite4MemdebugNoType(p, MEMTYPE_DB) );
  assert( sqlite4MemdebugHasType(p, MEMTYPE_HEAP) );
  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;
  if( pEnv->bMemstat ){
    sqlite4_mutex_enter(mem0.mutex);
    sqlite4StatusAdd(pEnv,SQLITE_ENVSTATUS_MEMORY_USED,
                     -sqlite4MallocSize(pEnv, p));
    sqlite4StatusAdd(pEnv,SQLITE_ENVSTATUS_MALLOC_COUNT, -1);
    pEnv->m.xFree(pEnv->m.pAppData, p);
    sqlite4_mutex_leave(mem0.mutex);
  }else{
    pEnv->m.xFree(pEnv->m.pAppData, p);
  }
}

/*
** Free memory that might be associated with a particular database
** connection.
*/
................................................................................
      return;
    }
  }
  assert( sqlite4MemdebugHasType(p, MEMTYPE_DB) );
  assert( sqlite4MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  assert( db!=0 || sqlite4MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  sqlite4MemdebugSetType(p, MEMTYPE_HEAP);
  sqlite4_free(db==0 ? 0 : db->pEnv, p);
}

/*
** Change the size of an existing memory allocation
*/
void *sqlite4Realloc(sqlite4_env *pEnv, void *pOld, int nBytes){
  int nOld, nNew;
  void *pNew;
  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;

  if( pOld==0 ){
    return sqlite4Malloc(pEnv, nBytes); /* IMP: R-28354-25769 */
  }
  if( nBytes<=0 ){
    sqlite4_free(pEnv, pOld); /* IMP: R-31593-10574 */
    return 0;
  }
  if( nBytes>=0x7fffff00 ){
    /* The 0x7ffff00 limit term is explained in comments on sqlite4Malloc() */
    return 0;
  }
  nOld = sqlite4MallocSize(pEnv, pOld);
  nNew = (nBytes + 7)&~7;





  if( pEnv->bMemstat ){
    sqlite4_mutex_enter(mem0.mutex);
    sqlite4StatusSet(pEnv, SQLITE_ENVSTATUS_MALLOC_SIZE, nBytes);
    assert( sqlite4MemdebugHasType(pOld, MEMTYPE_HEAP) );
    assert( sqlite4MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
    pNew = pEnv->m.xRealloc(pEnv->m.pAppData, pOld, nNew);
    if( pNew ){
      nNew = sqlite4MallocSize(pEnv, pNew);
      sqlite4StatusAdd(pEnv, SQLITE_ENVSTATUS_MEMORY_USED, nNew-nOld);
    }
    sqlite4_mutex_leave(mem0.mutex);
  }else{
    pNew = pEnv->m.xRealloc(pEnv->m.pAppData, pOld, nNew);
  }
  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
  return pNew;
}

/*
** The public interface to sqlite4Realloc.  Make sure that the memory
** subsystem is initialized prior to invoking sqliteRealloc.
*/
void *sqlite4_realloc(sqlite4_env *pEnv, void *pOld, sqlite4_size_t n){
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite4_initialize(pEnv) ) return 0;
#endif
  if( n>0x7fff0000 ) return 0;
  return sqlite4Realloc(pEnv, pOld, (int)n);
}


/*
** Allocate and zero memory.
*/ 
void *sqlite4MallocZero(sqlite4_env *pEnv, int n){
  void *p = sqlite4Malloc(pEnv, n);
  if( p ){
    memset(p, 0, n);
  }
  return p;
}

/*
................................................................................
    }
  }
#else
  if( db && db->mallocFailed ){
    return 0;
  }
#endif
  p = sqlite4Malloc((db ? db->pEnv: 0), n);
  if( !p && db ){
    db->mallocFailed = 1;
  }
  sqlite4MemdebugSetType(p, MEMTYPE_DB |
         ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  return p;
}
................................................................................
        memcpy(pNew, p, db->lookaside.sz);
        sqlite4DbFree(db, p);
      }
    }else{
      assert( sqlite4MemdebugHasType(p, MEMTYPE_DB) );
      assert( sqlite4MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
      sqlite4MemdebugSetType(p, MEMTYPE_HEAP);
      pNew = sqlite4_realloc(db->pEnv, p, n);
      if( !pNew ){
        sqlite4MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
        db->mallocFailed = 1;
      }
      sqlite4MemdebugSetType(pNew, MEMTYPE_DB | 
            (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
    }

Changes to src/mem0.c.

24
25
26
27
28
29
30
31
32
33
34

35
36
37
38
39
40
41
42
..
44
45
46
47
48
49
50
51
52
53
54


55
56

57
58
59
** macros.
*/
#ifdef SQLITE_ZERO_MALLOC

/*
** No-op versions of all memory allocation routines
*/
static void *sqlite4MemMalloc(int nByte){ return 0; }
static void sqlite4MemFree(void *pPrior){ return; }
static void *sqlite4MemRealloc(void *pPrior, int nByte){ return 0; }
static int sqlite4MemSize(void *pPrior){ return 0; }

static int sqlite4MemRoundup(int n){ return n; }
static int sqlite4MemInit(void *NotUsed){ return SQLITE_OK; }
static void sqlite4MemShutdown(void *NotUsed){ return; }

/*
** This routine is the only routine in this file with external linkage.
**
** Populate the low-level memory allocation function pointers in
................................................................................
*/
void sqlite4MemSetDefault(sqlite4_env *pEnv){
  static const sqlite4_mem_methods defaultMethods = {
     sqlite4MemMalloc,
     sqlite4MemFree,
     sqlite4MemRealloc,
     sqlite4MemSize,
     sqlite4MemRoundup,
     sqlite4MemInit,
     sqlite4MemShutdown,
     0


  };
  sqlite4_env_config(pEnv, SQLITE_ENVCONFIG_MALLOC, &defaultMethods);

}

#endif /* SQLITE_ZERO_MALLOC */







|
|
|
|
>
|







 







<


|
>
>

<
>



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
..
45
46
47
48
49
50
51

52
53
54
55
56
57

58
59
60
61
** macros.
*/
#ifdef SQLITE_ZERO_MALLOC

/*
** No-op versions of all memory allocation routines
*/
static void *sqlite4MemMalloc(void *p, sqlite4_size_t nByte){ return 0; }
static void sqlite4MemFree(void *p, void *pPrior){ return; }
static void *sqlite4MemRealloc(void *p, void *pPrior, sqlite4_size_t nByte){
  return 0;
}
static int sqlite4MemSize(void*p, void *pPrior){ return 0; }
static int sqlite4MemInit(void *NotUsed){ return SQLITE_OK; }
static void sqlite4MemShutdown(void *NotUsed){ return; }

/*
** This routine is the only routine in this file with external linkage.
**
** Populate the low-level memory allocation function pointers in
................................................................................
*/
void sqlite4MemSetDefault(sqlite4_env *pEnv){
  static const sqlite4_mem_methods defaultMethods = {
     sqlite4MemMalloc,
     sqlite4MemFree,
     sqlite4MemRealloc,
     sqlite4MemSize,

     sqlite4MemInit,
     sqlite4MemShutdown,
     0, 
     0,
     0
  };

  pEnv->m = defaultMethods;
}

#endif /* SQLITE_ZERO_MALLOC */

Changes to src/mem1.c.

106
107
108
109
110
111
112
113
114
115

116
117
118
119
120
121
122
123

124
125
126
127
128
129
130
...
138
139
140
141
142
143
144
145
146

147
148
149

150
151
152
153
154
155
156
157
158
159
160
161

162
163
164

165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184

185
186
187
188
189
190
191
192
193
194
195

196
197
198
199
200
201
202
...
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
...
267
268
269
270
271
272
273
274
275
276
277


278
279

280
281
282
** Like malloc(), but remember the size of the allocation
** so that we can find it later using sqlite4MemSize().
**
** For this low-level routine, we are guaranteed that nByte>0 because
** cases of nByte<=0 will be intercepted and dealt with by higher level
** routines.
*/
static void *sqlite4MemMalloc(int nByte){
#ifdef SQLITE_MALLOCSIZE
  void *p = SQLITE_MALLOC( nByte );

  if( p==0 ){
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  }
  return p;
#else
  sqlite4_int64 *p;
  assert( nByte>0 );

  nByte = ROUND8(nByte);
  p = SQLITE_MALLOC( nByte+8 );
  if( p ){
    p[0] = nByte;
    p++;
  }else{
    testcase( sqlite4DefaultEnv.xLog!=0 );
................................................................................
** Like free() but works for allocations obtained from sqlite4MemMalloc()
** or sqlite4MemRealloc().
**
** For this low-level routine, we already know that pPrior!=0 since
** cases where pPrior==0 will have been intecepted and dealt with
** by higher-level routines.
*/
static void sqlite4MemFree(void *pPrior){
#ifdef SQLITE_MALLOCSIZE

  SQLITE_FREE(pPrior);
#else
  sqlite4_int64 *p = (sqlite4_int64*)pPrior;

  assert( pPrior!=0 );
  p--;
  SQLITE_FREE(p);
#endif
}

/*
** Report the allocated size of a prior return from xMalloc()
** or xRealloc().
*/
static int sqlite4MemSize(void *pPrior){
#ifdef SQLITE_MALLOCSIZE

  return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
#else
  sqlite4_int64 *p;

  if( pPrior==0 ) return 0;
  p = (sqlite4_int64*)pPrior;
  p--;
  return (int)p[0];
#endif
}

/*
** Like realloc().  Resize an allocation previously obtained from
** sqlite4MemMalloc().
**
** For this low-level interface, we know that pPrior!=0.  Cases where
** pPrior==0 while have been intercepted by higher-level routine and
** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
** cases where nByte<=0 will have been intercepted by higher-level
** routines and redirected to xFree.
*/
static void *sqlite4MemRealloc(void *pPrior, int nByte){
#ifdef SQLITE_MALLOCSIZE
  void *p = SQLITE_REALLOC(pPrior, nByte);

  if( p==0 ){
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(SQLITE_NOMEM,
      "failed memory resize %u to %u bytes",
      SQLITE_MALLOCSIZE(pPrior), nByte);
  }
  return p;
#else
  sqlite4_int64 *p = (sqlite4_int64*)pPrior;
  assert( pPrior!=0 && nByte>0 );
  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */

  p--;
  p = SQLITE_REALLOC(p, nByte+8 );
  if( p ){
    p[0] = nByte;
    p++;
  }else{
    testcase( sqlite4DefaultEnv.xLog!=0 );
................................................................................
      "failed memory resize %u to %u bytes",
      sqlite4MemSize(pPrior), nByte);
  }
  return (void*)p;
#endif
}

/*
** Round up a request size to the next valid allocation size.
*/
static int sqlite4MemRoundup(int n){
  return ROUND8(n);
}

/*
** Initialize this module.
*/
static int sqlite4MemInit(void *NotUsed){
#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  int cpuCount;
  size_t len;
................................................................................
*/
void sqlite4MemSetDefault(sqlite4_env *pEnv){
  static const sqlite4_mem_methods defaultMethods = {
     sqlite4MemMalloc,
     sqlite4MemFree,
     sqlite4MemRealloc,
     sqlite4MemSize,
     sqlite4MemRoundup,
     sqlite4MemInit,
     sqlite4MemShutdown,
     0


  };
  sqlite4_env_config(pEnv, SQLITE_ENVCONFIG_MALLOC, &defaultMethods);

}

#endif /* SQLITE_SYSTEM_MALLOC */







|


>








>







 







|

>



>










|

>



>



|













|


>











>







 







<
<
<
<
<
<
<







 







<


|
>
>

<
>



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
...
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
...
212
213
214
215
216
217
218







219
220
221
222
223
224
225
...
268
269
270
271
272
273
274

275
276
277
278
279
280

281
282
283
284
** Like malloc(), but remember the size of the allocation
** so that we can find it later using sqlite4MemSize().
**
** For this low-level routine, we are guaranteed that nByte>0 because
** cases of nByte<=0 will be intercepted and dealt with by higher level
** routines.
*/
static void *sqlite4MemMalloc(void *NotUsed, sqlite4_size_t nByte){
#ifdef SQLITE_MALLOCSIZE
  void *p = SQLITE_MALLOC( nByte );
  UNUSED_PARAMETER(NotUsed);
  if( p==0 ){
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  }
  return p;
#else
  sqlite4_int64 *p;
  assert( nByte>0 );
  UNUSED_PARAMETER(NotUsed);
  nByte = ROUND8(nByte);
  p = SQLITE_MALLOC( nByte+8 );
  if( p ){
    p[0] = nByte;
    p++;
  }else{
    testcase( sqlite4DefaultEnv.xLog!=0 );
................................................................................
** Like free() but works for allocations obtained from sqlite4MemMalloc()
** or sqlite4MemRealloc().
**
** For this low-level routine, we already know that pPrior!=0 since
** cases where pPrior==0 will have been intecepted and dealt with
** by higher-level routines.
*/
static void sqlite4MemFree(void *NotUsed, void *pPrior){
#ifdef SQLITE_MALLOCSIZE
  UNUSED_PARAMETER(NotUsed);
  SQLITE_FREE(pPrior);
#else
  sqlite4_int64 *p = (sqlite4_int64*)pPrior;
  UNUSED_PARAMETER(NotUsed);
  assert( pPrior!=0 );
  p--;
  SQLITE_FREE(p);
#endif
}

/*
** Report the allocated size of a prior return from xMalloc()
** or xRealloc().
*/
static sqlite4_size_t sqlite4MemSize(void *NotUsed, void *pPrior){
#ifdef SQLITE_MALLOCSIZE
  UNUSED_PARAMETER(NotUsed);
  return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
#else
  sqlite4_int64 *p;
  UNUSED_PARAMETER(NotUsed);
  if( pPrior==0 ) return 0;
  p = (sqlite4_int64*)pPrior;
  p--;
  return (sqlite4_size_t)p[0];
#endif
}

/*
** Like realloc().  Resize an allocation previously obtained from
** sqlite4MemMalloc().
**
** For this low-level interface, we know that pPrior!=0.  Cases where
** pPrior==0 while have been intercepted by higher-level routine and
** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
** cases where nByte<=0 will have been intercepted by higher-level
** routines and redirected to xFree.
*/
static void *sqlite4MemRealloc(void *NotUsed, void *pPrior, int nByte){
#ifdef SQLITE_MALLOCSIZE
  void *p = SQLITE_REALLOC(pPrior, nByte);
  UNUSED_PARAMETER(NotUsed);
  if( p==0 ){
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(SQLITE_NOMEM,
      "failed memory resize %u to %u bytes",
      SQLITE_MALLOCSIZE(pPrior), nByte);
  }
  return p;
#else
  sqlite4_int64 *p = (sqlite4_int64*)pPrior;
  assert( pPrior!=0 && nByte>0 );
  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  UNUSED_PARAMETER(NotUsed);
  p--;
  p = SQLITE_REALLOC(p, nByte+8 );
  if( p ){
    p[0] = nByte;
    p++;
  }else{
    testcase( sqlite4DefaultEnv.xLog!=0 );
................................................................................
      "failed memory resize %u to %u bytes",
      sqlite4MemSize(pPrior), nByte);
  }
  return (void*)p;
#endif
}








/*
** Initialize this module.
*/
static int sqlite4MemInit(void *NotUsed){
#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  int cpuCount;
  size_t len;
................................................................................
*/
void sqlite4MemSetDefault(sqlite4_env *pEnv){
  static const sqlite4_mem_methods defaultMethods = {
     sqlite4MemMalloc,
     sqlite4MemFree,
     sqlite4MemRealloc,
     sqlite4MemSize,

     sqlite4MemInit,
     sqlite4MemShutdown,
     0,
     0,
     0
  };

  pEnv->m = defaultMethods;
}

#endif /* SQLITE_SYSTEM_MALLOC */

Changes to src/mem2.c.

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
...
169
170
171
172
173
174
175
176
177

178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
...
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254

255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304

305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345

346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
...
363
364
365
366
367
368
369
370
371
372
373


374
375

376
377
378
379
380
381
382
...
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
...
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
...
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
  ** bytes.  i==NCSIZE is the number of allocation attempts for
  ** sizes more than NCSIZE*8 bytes.
  */
  int nAlloc[NCSIZE];      /* Total number of allocations */
  int nCurrent[NCSIZE];    /* Current number of allocations */
  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */

} mem;


/*
** Adjust memory usage statistics
*/
static void adjustStats(int iSize, int increment){
  int i = ROUND8(iSize)/8;
  if( i>NCSIZE-1 ){
    i = NCSIZE - 1;
  }
  if( increment>0 ){
    mem.nAlloc[i]++;
    mem.nCurrent[i]++;
    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
      mem.mxCurrent[i] = mem.nCurrent[i];
    }
  }else{
    mem.nCurrent[i]--;
    assert( mem.nCurrent[i]>=0 );
  }
}

/*
** Given an allocation, find the MemBlockHdr for that allocation.
**
** This routine checks the guards at either end of the allocation and
................................................................................
  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  return p;
}

/*
** Return the number of bytes currently allocated at address p.
*/
static int sqlite4MemSize(void *p){
  struct MemBlockHdr *pHdr;

  if( !p ){
    return 0;
  }
  pHdr = sqlite4MemsysGetHeader(p);
  return pHdr->iSize;
}

/*
** Initialize the memory allocation subsystem.
*/
static int sqlite4MemInit(void *NotUsed){
  UNUSED_PARAMETER(NotUsed);
  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  if( !sqlite4DefaultEnv.bMemstat ){
    /* If memory status is enabled, then the malloc.c wrapper will already
    ** hold the STATIC_MEM mutex when the routines here are invoked. */
    mem.mutex = sqlite4MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  }
  return SQLITE_OK;
}

/*
** Deinitialize the memory allocation subsystem.
*/
static void sqlite4MemShutdown(void *NotUsed){
  UNUSED_PARAMETER(NotUsed);
  mem.mutex = 0;
}

/*
** Round up a request size to the next valid allocation size.
*/
static int sqlite4MemRoundup(int n){
  return ROUND8(n);
}

/*
** Fill a buffer with pseudo-random bytes.  This is used to preset
** the content of a new memory allocation to unpredictable values and
** to clear the content of a freed allocation to unpredictable values.
*/
................................................................................
    *(pBuf++) = r & 0xff;
  }
}

/*
** Allocate nByte bytes of memory.
*/
static void *sqlite4MemMalloc(int nByte){
  struct MemBlockHdr *pHdr;
  void **pBt;
  char *z;
  int *pInt;
  void *p = 0;
  int totalSize;
  int nReserve;
  sqlite4_mutex_enter(mem.mutex);
  assert( mem.disallow==0 );
  nReserve = ROUND8(nByte);
  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
               mem.nBacktrace*sizeof(void*) + mem.nTitle;

  p = malloc(totalSize);
  if( p ){
    z = p;
    pBt = (void**)&z[mem.nTitle];
    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
    pHdr->pNext = 0;
    pHdr->pPrev = mem.pLast;
    if( mem.pLast ){
      mem.pLast->pNext = pHdr;
    }else{
      mem.pFirst = pHdr;
    }
    mem.pLast = pHdr;
    pHdr->iForeGuard = FOREGUARD;
    pHdr->eType = MEMTYPE_HEAP;
    pHdr->nBacktraceSlots = mem.nBacktrace;
    pHdr->nTitle = mem.nTitle;
    if( mem.nBacktrace ){
      void *aAddr[40];
      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
      assert(pBt[0]);
      if( mem.xBacktrace ){
        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
      }
    }else{
      pHdr->nBacktrace = 0;
    }
    if( mem.nTitle ){
      memcpy(z, mem.zTitle, mem.nTitle);
    }
    pHdr->iSize = nByte;
    adjustStats(nByte, +1);
    pInt = (int*)&pHdr[1];
    pInt[nReserve/sizeof(int)] = REARGUARD;
    randomFill((char*)pInt, nByte);
    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
    p = (void*)pInt;
  }
  sqlite4_mutex_leave(mem.mutex);
  return p; 
}

/*
** Free memory.
*/
static void sqlite4MemFree(void *pPrior){
  struct MemBlockHdr *pHdr;
  void **pBt;
  char *z;

  assert( sqlite4DefaultEnv.bMemstat || sqlite4DefaultEnv.bCoreMutex==0 
       || mem.mutex!=0 );
  pHdr = sqlite4MemsysGetHeader(pPrior);
  pBt = (void**)pHdr;
  pBt -= pHdr->nBacktraceSlots;
  sqlite4_mutex_enter(mem.mutex);
  if( pHdr->pPrev ){
    assert( pHdr->pPrev->pNext==pHdr );
    pHdr->pPrev->pNext = pHdr->pNext;
  }else{
    assert( mem.pFirst==pHdr );
    mem.pFirst = pHdr->pNext;
  }
  if( pHdr->pNext ){
    assert( pHdr->pNext->pPrev==pHdr );
    pHdr->pNext->pPrev = pHdr->pPrev;
  }else{
    assert( mem.pLast==pHdr );
    mem.pLast = pHdr->pPrev;
  }
  z = (char*)pBt;
  z -= pHdr->nTitle;
  adjustStats(pHdr->iSize, -1);
  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
                pHdr->iSize + sizeof(int) + pHdr->nTitle);
  free(z);
  sqlite4_mutex_leave(mem.mutex);  
}

/*
** Change the size of an existing memory allocation.
**
** For this debugging implementation, we *always* make a copy of the
** allocation into a new place in memory.  In this way, if the 
** higher level code is using pointer to the old allocation, it is 
** much more likely to break and we are much more liking to find
** the error.
*/
static void *sqlite4MemRealloc(void *pPrior, int nByte){
  struct MemBlockHdr *pOldHdr;
  void *pNew;

  assert( mem.disallow==0 );
  assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
  pOldHdr = sqlite4MemsysGetHeader(pPrior);
  pNew = sqlite4MemMalloc(nByte);
  if( pNew ){
    memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
    if( nByte>pOldHdr->iSize ){
      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
    }
    sqlite4MemFree(pPrior);
  }
  return pNew;
}

/*
** Populate the low-level memory allocation function pointers in
** sqlite4DefaultEnv.m with pointers to the routines in this file.
................................................................................
*/
void sqlite4MemSetDefault(sqlite4_env *pEnv){
  static const sqlite4_mem_methods defaultMethods = {
     sqlite4MemMalloc,
     sqlite4MemFree,
     sqlite4MemRealloc,
     sqlite4MemSize,
     sqlite4MemRoundup,
     sqlite4MemInit,
     sqlite4MemShutdown,
     0


  };
  sqlite4_config(pEnv, SQLITE_ENVCONFIG_MALLOC, &defaultMethods);

}

/*
** Set the "type" of an allocation.
*/
void sqlite4MemdebugSetType(void *p, u8 eType){
  if( p && sqlite4DefaultEnv.m.xMalloc==sqlite4MemMalloc ){
................................................................................
** A value of zero turns off backtracing.  The number is always rounded
** up to a multiple of 2.
*/
void sqlite4MemdebugBacktrace(int depth){
  if( depth<0 ){ depth = 0; }
  if( depth>20 ){ depth = 20; }
  depth = (depth+1)&0xfe;
  mem.nBacktrace = depth;
}

void sqlite4MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  mem.xBacktrace = xBacktrace;
}

/*
** Set the title string for subsequent allocations.
*/
void sqlite4MemdebugSettitle(const char *zTitle){
  unsigned int n = sqlite4Strlen30(zTitle) + 1;
  sqlite4_mutex_enter(mem.mutex);
  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  memcpy(mem.zTitle, zTitle, n);
  mem.zTitle[n] = 0;
  mem.nTitle = ROUND8(n);
  sqlite4_mutex_leave(mem.mutex);
}

void sqlite4MemdebugSync(){
  struct MemBlockHdr *pHdr;
  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
    void **pBt = (void**)pHdr;
    pBt -= pHdr->nBacktraceSlots;
    mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  }
}

/*
** Open the file indicated and write a log of all unfreed memory 
** allocations into that log.
*/
................................................................................
  int i;
  out = fopen(zFilename, "w");
  if( out==0 ){
    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
                    zFilename);
    return;
  }
  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
    char *z = (char*)pHdr;
    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
    fprintf(out, "**** %lld bytes at %p from %s ****\n", 
            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
    if( pHdr->nBacktrace ){
      fflush(out);
      pBt = (void**)pHdr;
................................................................................
      pBt -= pHdr->nBacktraceSlots;
      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
      fprintf(out, "\n");
    }
  }
  fprintf(out, "COUNTS:\n");
  for(i=0; i<NCSIZE-1; i++){
    if( mem.nAlloc[i] ){
      fprintf(out, "   %5d: %10d %10d %10d\n", 
            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
    }
  }
  if( mem.nAlloc[NCSIZE-1] ){
    fprintf(out, "   %5d: %10d %10d %10d\n",
             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  }
  fclose(out);
}

/*
** Return the number of times sqlite4MemMalloc() has been called.
*/
int sqlite4MemdebugMallocCount(){
  int i;
  int nTotal = 0;
  for(i=0; i<NCSIZE; i++){
    nTotal += mem.nAlloc[i];
  }
  return nTotal;
}


#endif /* SQLITE_MEMDEBUG */







|











|
|
|
|


|
|







 







|

>










|
|




|







|
|
|
<
<
<
<
<
<
<







 







|







|
|


|
>



|
|

|
|
|

|

|


|
|
|

|


|
|




|
|









|






|



>

|



|




|
|





|
|







|











|


>
|


|





|







 







<


|
>
>

<
>







 







|



|







|
|
|
|
|
|




|


|







 







|







 







|

|


|

|
|











|






116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
...
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205







206
207
208
209
210
211
212
...
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
...
360
361
362
363
364
365
366

367
368
369
370
371
372

373
374
375
376
377
378
379
380
...
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
...
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
...
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
  ** bytes.  i==NCSIZE is the number of allocation attempts for
  ** sizes more than NCSIZE*8 bytes.
  */
  int nAlloc[NCSIZE];      /* Total number of allocations */
  int nCurrent[NCSIZE];    /* Current number of allocations */
  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */

} mem2;


/*
** Adjust memory usage statistics
*/
static void adjustStats(int iSize, int increment){
  int i = ROUND8(iSize)/8;
  if( i>NCSIZE-1 ){
    i = NCSIZE - 1;
  }
  if( increment>0 ){
    mem2.nAlloc[i]++;
    mem2.nCurrent[i]++;
    if( mem2.nCurrent[i]>mem2.mxCurrent[i] ){
      mem2.mxCurrent[i] = mem2.nCurrent[i];
    }
  }else{
    mem2.nCurrent[i]--;
    assert( mem2.nCurrent[i]>=0 );
  }
}

/*
** Given an allocation, find the MemBlockHdr for that allocation.
**
** This routine checks the guards at either end of the allocation and
................................................................................
  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  return p;
}

/*
** Return the number of bytes currently allocated at address p.
*/
static int sqlite4MemSize(void *pMem, void *p){
  struct MemBlockHdr *pHdr;
  assert( pMem==(void*)&mem2 );
  if( !p ){
    return 0;
  }
  pHdr = sqlite4MemsysGetHeader(p);
  return pHdr->iSize;
}

/*
** Initialize the memory allocation subsystem.
*/
static int sqlite4MemInit(void *pMem){
  assert( pMem==(void*)&mem2 );
  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  if( !sqlite4DefaultEnv.bMemstat ){
    /* If memory status is enabled, then the malloc.c wrapper will already
    ** hold the STATIC_MEM mutex when the routines here are invoked. */
    mem2.mutex = sqlite4MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  }
  return SQLITE_OK;
}

/*
** Deinitialize the memory allocation subsystem.
*/
static void sqlite4MemShutdown(void *pMem){
  assert( pMem==(void*)&mem2 );
  mem2.mutex = 0;







}

/*
** Fill a buffer with pseudo-random bytes.  This is used to preset
** the content of a new memory allocation to unpredictable values and
** to clear the content of a freed allocation to unpredictable values.
*/
................................................................................
    *(pBuf++) = r & 0xff;
  }
}

/*
** Allocate nByte bytes of memory.
*/
static void *sqlite4MemMalloc(void *pMem, sqlite4_size_t nByte){
  struct MemBlockHdr *pHdr;
  void **pBt;
  char *z;
  int *pInt;
  void *p = 0;
  int totalSize;
  int nReserve;
  sqlite4_mutex_enter(mem2.mutex);
  assert( mem2.disallow==0 );
  nReserve = ROUND8(nByte);
  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
               mem2.nBacktrace*sizeof(void*) + mem2.nTitle;
  assert( pMem==(void*)&mem2 );
  p = malloc(totalSize);
  if( p ){
    z = p;
    pBt = (void**)&z[mem2.nTitle];
    pHdr = (struct MemBlockHdr*)&pBt[mem2.nBacktrace];
    pHdr->pNext = 0;
    pHdr->pPrev = mem2.pLast;
    if( mem2.pLast ){
      mem2.pLast->pNext = pHdr;
    }else{
      mem2.pFirst = pHdr;
    }
    mem2.pLast = pHdr;
    pHdr->iForeGuard = FOREGUARD;
    pHdr->eType = MEMTYPE_HEAP;
    pHdr->nBacktraceSlots = mem2.nBacktrace;
    pHdr->nTitle = mem2.nTitle;
    if( mem2.nBacktrace ){
      void *aAddr[40];
      pHdr->nBacktrace = backtrace(aAddr, mem2.nBacktrace+1)-1;
      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
      assert(pBt[0]);
      if( mem2.xBacktrace ){
        mem2.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
      }
    }else{
      pHdr->nBacktrace = 0;
    }
    if( mem2.nTitle ){
      memcpy(z, mem2.zTitle, mem2.nTitle);
    }
    pHdr->iSize = nByte;
    adjustStats(nByte, +1);
    pInt = (int*)&pHdr[1];
    pInt[nReserve/sizeof(int)] = REARGUARD;
    randomFill((char*)pInt, nByte);
    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
    p = (void*)pInt;
  }
  sqlite4_mutex_leave(mem2.mutex);
  return p; 
}

/*
** Free memory.
*/
static void sqlite4MemFree(void *pMem, void *pPrior){
  struct MemBlockHdr *pHdr;
  void **pBt;
  char *z;
  assert( pMem==(void*)&mem2 );
  assert( sqlite4DefaultEnv.bMemstat || sqlite4DefaultEnv.bCoreMutex==0 
       || mem2.mutex!=0 );
  pHdr = sqlite4MemsysGetHeader(pPrior);
  pBt = (void**)pHdr;
  pBt -= pHdr->nBacktraceSlots;
  sqlite4_mutex_enter(mem2.mutex);
  if( pHdr->pPrev ){
    assert( pHdr->pPrev->pNext==pHdr );
    pHdr->pPrev->pNext = pHdr->pNext;
  }else{
    assert( mem2.pFirst==pHdr );
    mem2.pFirst = pHdr->pNext;
  }
  if( pHdr->pNext ){
    assert( pHdr->pNext->pPrev==pHdr );
    pHdr->pNext->pPrev = pHdr->pPrev;
  }else{
    assert( mem2.pLast==pHdr );
    mem2.pLast = pHdr->pPrev;
  }
  z = (char*)pBt;
  z -= pHdr->nTitle;
  adjustStats(pHdr->iSize, -1);
  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
                pHdr->iSize + sizeof(int) + pHdr->nTitle);
  free(z);
  sqlite4_mutex_leave(mem2.mutex);  
}

/*
** Change the size of an existing memory allocation.
**
** For this debugging implementation, we *always* make a copy of the
** allocation into a new place in memory.  In this way, if the 
** higher level code is using pointer to the old allocation, it is 
** much more likely to break and we are much more liking to find
** the error.
*/
static void *sqlite4MemRealloc(void *p, void *pPrior, sqlite4_size_t nByte){
  struct MemBlockHdr *pOldHdr;
  void *pNew;
  assert( p==(void*)&mem2 );
  assert( mem2.disallow==0 );
  assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
  pOldHdr = sqlite4MemsysGetHeader(pPrior);
  pNew = sqlite4MemMalloc(p, nByte);
  if( pNew ){
    memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
    if( nByte>pOldHdr->iSize ){
      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
    }
    sqlite4MemFree(p, pPrior);
  }
  return pNew;
}

/*
** Populate the low-level memory allocation function pointers in
** sqlite4DefaultEnv.m with pointers to the routines in this file.
................................................................................
*/
void sqlite4MemSetDefault(sqlite4_env *pEnv){
  static const sqlite4_mem_methods defaultMethods = {
     sqlite4MemMalloc,
     sqlite4MemFree,
     sqlite4MemRealloc,
     sqlite4MemSize,

     sqlite4MemInit,
     sqlite4MemShutdown,
     0,
     0,
     &mem2
  };

  pEnv->m = defaultMethods;
}

/*
** Set the "type" of an allocation.
*/
void sqlite4MemdebugSetType(void *p, u8 eType){
  if( p && sqlite4DefaultEnv.m.xMalloc==sqlite4MemMalloc ){
................................................................................
** A value of zero turns off backtracing.  The number is always rounded
** up to a multiple of 2.
*/
void sqlite4MemdebugBacktrace(int depth){
  if( depth<0 ){ depth = 0; }
  if( depth>20 ){ depth = 20; }
  depth = (depth+1)&0xfe;
  mem2.nBacktrace = depth;
}

void sqlite4MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  mem2.xBacktrace = xBacktrace;
}

/*
** Set the title string for subsequent allocations.
*/
void sqlite4MemdebugSettitle(const char *zTitle){
  unsigned int n = sqlite4Strlen30(zTitle) + 1;
  sqlite4_mutex_enter(mem2.mutex);
  if( n>=sizeof(mem2.zTitle) ) n = sizeof(mem2.zTitle)-1;
  memcpy(mem2.zTitle, zTitle, n);
  mem2.zTitle[n] = 0;
  mem2.nTitle = ROUND8(n);
  sqlite4_mutex_leave(mem2.mutex);
}

void sqlite4MemdebugSync(){
  struct MemBlockHdr *pHdr;
  for(pHdr=mem2.pFirst; pHdr; pHdr=pHdr->pNext){
    void **pBt = (void**)pHdr;
    pBt -= pHdr->nBacktraceSlots;
    mem2.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  }
}

/*
** Open the file indicated and write a log of all unfreed memory 
** allocations into that log.
*/
................................................................................
  int i;
  out = fopen(zFilename, "w");
  if( out==0 ){
    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
                    zFilename);
    return;
  }
  for(pHdr=mem2.pFirst; pHdr; pHdr=pHdr->pNext){
    char *z = (char*)pHdr;
    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
    fprintf(out, "**** %lld bytes at %p from %s ****\n", 
            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
    if( pHdr->nBacktrace ){
      fflush(out);
      pBt = (void**)pHdr;
................................................................................
      pBt -= pHdr->nBacktraceSlots;
      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
      fprintf(out, "\n");
    }
  }
  fprintf(out, "COUNTS:\n");
  for(i=0; i<NCSIZE-1; i++){
    if( mem2.nAlloc[i] ){
      fprintf(out, "   %5d: %10d %10d %10d\n", 
            i*8, mem2.nAlloc[i], mem2.nCurrent[i], mem2.mxCurrent[i]);
    }
  }
  if( mem2.nAlloc[NCSIZE-1] ){
    fprintf(out, "   %5d: %10d %10d %10d\n",
             NCSIZE*8-8, mem2.nAlloc[NCSIZE-1],
             mem2.nCurrent[NCSIZE-1], mem2.mxCurrent[NCSIZE-1]);
  }
  fclose(out);
}

/*
** Return the number of times sqlite4MemMalloc() has been called.
*/
int sqlite4MemdebugMallocCount(){
  int i;
  int nTotal = 0;
  for(i=0; i<NCSIZE; i++){
    nTotal += mem2.nAlloc[i];
  }
  return nTotal;
}


#endif /* SQLITE_MEMDEBUG */

Changes to src/mem3.c.

512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
  memsys3FreeUnsafe(pPrior);
  memsys3Leave();
}

/*
** Change the size of an existing memory allocation
*/
static void *memsys3Realloc(void *pPrior, int nBytes){
  int nOld;
  void *p;
  if( pPrior==0 ){
    return sqlite4_malloc(nBytes);
  }
  if( nBytes<=0 ){
    sqlite4_free(pPrior);
    return 0;
  }
  nOld = memsys3Size(pPrior);
  if( nBytes<=nOld && nBytes>=nOld-128 ){
    return pPrior;
  }
  memsys3Enter();







|



|


|







512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
  memsys3FreeUnsafe(pPrior);
  memsys3Leave();
}

/*
** Change the size of an existing memory allocation
*/
static void *memsys3Realloc(sqlite4_env*pEnv, void *pPrior, int nBytes){
  int nOld;
  void *p;
  if( pPrior==0 ){
    return sqlite4_malloc(pEnv, nBytes);
  }
  if( nBytes<=0 ){
    sqlite4_free(pEnv, pPrior);
    return 0;
  }
  nOld = memsys3Size(pPrior);
  if( nBytes<=nOld && nBytes>=nOld-128 ){
    return pPrior;
  }
  memsys3Enter();

Changes to src/mutex_noop.c.

108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
...
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
*/
static sqlite4_mutex *debugMutexAlloc(int id){
  static sqlite4_debug_mutex aStatic[6];
  sqlite4_debug_mutex *pNew = 0;
  switch( id ){
    case SQLITE_MUTEX_FAST:
    case SQLITE_MUTEX_RECURSIVE: {
      pNew = sqlite4Malloc(sizeof(*pNew));
      if( pNew ){
        pNew->id = id;
        pNew->cnt = 0;
      }
      break;
    }
    default: {
................................................................................
/*
** This routine deallocates a previously allocated mutex.
*/
static void debugMutexFree(sqlite4_mutex *pX){
  sqlite4_debug_mutex *p = (sqlite4_debug_mutex*)pX;
  assert( p->cnt==0 );
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  sqlite4_free(p);
}

/*
** The sqlite4_mutex_enter() and sqlite4_mutex_try() routines attempt
** to enter a mutex.  If another thread is already within the mutex,
** sqlite4_mutex_enter() will block and sqlite4_mutex_try() will return
** SQLITE_BUSY.  The sqlite4_mutex_try() interface returns SQLITE_OK







|







 







|







108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
...
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
*/
static sqlite4_mutex *debugMutexAlloc(int id){
  static sqlite4_debug_mutex aStatic[6];
  sqlite4_debug_mutex *pNew = 0;
  switch( id ){
    case SQLITE_MUTEX_FAST:
    case SQLITE_MUTEX_RECURSIVE: {
      pNew = sqlite4Malloc(0, sizeof(*pNew));
      if( pNew ){
        pNew->id = id;
        pNew->cnt = 0;
      }
      break;
    }
    default: {
................................................................................
/*
** This routine deallocates a previously allocated mutex.
*/
static void debugMutexFree(sqlite4_mutex *pX){
  sqlite4_debug_mutex *p = (sqlite4_debug_mutex*)pX;
  assert( p->cnt==0 );
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  sqlite4_free(0, p);
}

/*
** The sqlite4_mutex_enter() and sqlite4_mutex_try() routines attempt
** to enter a mutex.  If another thread is already within the mutex,
** sqlite4_mutex_enter() will block and sqlite4_mutex_try() will return
** SQLITE_BUSY.  The sqlite4_mutex_try() interface returns SQLITE_OK

Changes to src/mutex_unix.c.

134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
...
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
...
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
    SQLITE3_MUTEX_INITIALIZER,
    SQLITE3_MUTEX_INITIALIZER,
    SQLITE3_MUTEX_INITIALIZER
  };
  sqlite4_mutex *p;
  switch( iType ){
    case SQLITE_MUTEX_RECURSIVE: {
      p = sqlite4MallocZero( sizeof(*p) );
      if( p ){
#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
        /* If recursive mutexes are not available, we will have to
        ** build our own.  See below. */
        pthread_mutex_init(&p->mutex, 0);
#else
        /* Use a recursive mutex if it is available */
................................................................................
#if SQLITE_MUTEX_NREF
        p->id = iType;
#endif
      }
      break;
    }
    case SQLITE_MUTEX_FAST: {
      p = sqlite4MallocZero( sizeof(*p) );
      if( p ){
#if SQLITE_MUTEX_NREF
        p->id = iType;
#endif
        pthread_mutex_init(&p->mutex, 0);
      }
      break;
................................................................................
** allocated mutex.  SQLite is careful to deallocate every
** mutex that it allocates.
*/
static void pthreadMutexFree(sqlite4_mutex *p){
  assert( p->nRef==0 );
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  pthread_mutex_destroy(&p->mutex);
  sqlite4_free(p);
}

/*
** The sqlite4_mutex_enter() and sqlite4_mutex_try() routines attempt
** to enter a mutex.  If another thread is already within the mutex,
** sqlite4_mutex_enter() will block and sqlite4_mutex_try() will return
** SQLITE_BUSY.  The sqlite4_mutex_try() interface returns SQLITE_OK







|







 







|







 







|







134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
...
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
...
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
    SQLITE3_MUTEX_INITIALIZER,
    SQLITE3_MUTEX_INITIALIZER,
    SQLITE3_MUTEX_INITIALIZER
  };
  sqlite4_mutex *p;
  switch( iType ){
    case SQLITE_MUTEX_RECURSIVE: {
      p = sqlite4MallocZero(0, sizeof(*p) );
      if( p ){
#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
        /* If recursive mutexes are not available, we will have to
        ** build our own.  See below. */
        pthread_mutex_init(&p->mutex, 0);
#else
        /* Use a recursive mutex if it is available */
................................................................................
#if SQLITE_MUTEX_NREF
        p->id = iType;
#endif
      }
      break;
    }
    case SQLITE_MUTEX_FAST: {
      p = sqlite4MallocZero(0, sizeof(*p) );
      if( p ){
#if SQLITE_MUTEX_NREF
        p->id = iType;
#endif
        pthread_mutex_init(&p->mutex, 0);
      }
      break;
................................................................................
** allocated mutex.  SQLite is careful to deallocate every
** mutex that it allocates.
*/
static void pthreadMutexFree(sqlite4_mutex *p){
  assert( p->nRef==0 );
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  pthread_mutex_destroy(&p->mutex);
  sqlite4_free(0, p);
}

/*
** The sqlite4_mutex_enter() and sqlite4_mutex_try() routines attempt
** to enter a mutex.  If another thread is already within the mutex,
** sqlite4_mutex_enter() will block and sqlite4_mutex_try() will return
** SQLITE_BUSY.  The sqlite4_mutex_try() interface returns SQLITE_OK

Changes to src/mutex_w32.c.

185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
...
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
*/
static sqlite4_mutex *winMutexAlloc(int iType){
  sqlite4_mutex *p;

  switch( iType ){
    case SQLITE_MUTEX_FAST:
    case SQLITE_MUTEX_RECURSIVE: {
      p = sqlite4MallocZero( sizeof(*p) );
      if( p ){  
#ifdef SQLITE_DEBUG
        p->id = iType;
#endif
        InitializeCriticalSection(&p->mutex);
      }
      break;
................................................................................
** mutex that it allocates.
*/
static void winMutexFree(sqlite4_mutex *p){
  assert( p );
  assert( p->nRef==0 && p->owner==0 );
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  DeleteCriticalSection(&p->mutex);
  sqlite4_free(p);
}

/*
** The sqlite4_mutex_enter() and sqlite4_mutex_try() routines attempt
** to enter a mutex.  If another thread is already within the mutex,
** sqlite4_mutex_enter() will block and sqlite4_mutex_try() will return
** SQLITE_BUSY.  The sqlite4_mutex_try() interface returns SQLITE_OK







|







 







|







185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
...
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
*/
static sqlite4_mutex *winMutexAlloc(int iType){
  sqlite4_mutex *p;

  switch( iType ){
    case SQLITE_MUTEX_FAST:
    case SQLITE_MUTEX_RECURSIVE: {
      p = sqlite4MallocZero(0, sizeof(*p) );
      if( p ){  
#ifdef SQLITE_DEBUG
        p->id = iType;
#endif
        InitializeCriticalSection(&p->mutex);
      }
      break;
................................................................................
** mutex that it allocates.
*/
static void winMutexFree(sqlite4_mutex *p){
  assert( p );
  assert( p->nRef==0 && p->owner==0 );
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  DeleteCriticalSection(&p->mutex);
  sqlite4_free(0, p);
}

/*
** The sqlite4_mutex_enter() and sqlite4_mutex_try() routines attempt
** to enter a mutex.  If another thread is already within the mutex,
** sqlite4_mutex_enter() will block and sqlite4_mutex_try() will return
** SQLITE_BUSY.  The sqlite4_mutex_try() interface returns SQLITE_OK

Changes to src/os.c.

37
38
39
40
41
42
43
44
45
46
47
48
/*
** This function is a wrapper around the OS specific implementation of
** sqlite4_os_init(). The purpose of the wrapper is to provide the
** ability to simulate a malloc failure, so that the handling of an
** error in sqlite4_os_init() by the upper layers can be tested.
*/
int sqlite4OsInit(sqlite4_env *pEnv){
  void *p = sqlite4_malloc(10);
  if( p==0 ) return SQLITE_NOMEM;
  sqlite4_free(p);
  return SQLITE_OK; /*sqlite4_os_init();*/
}







|

|


37
38
39
40
41
42
43
44
45
46
47
48
/*
** This function is a wrapper around the OS specific implementation of
** sqlite4_os_init(). The purpose of the wrapper is to provide the
** ability to simulate a malloc failure, so that the handling of an
** error in sqlite4_os_init() by the upper layers can be tested.
*/
int sqlite4OsInit(sqlite4_env *pEnv){
  void *p = sqlite4_malloc(pEnv, 10);
  if( p==0 ) return SQLITE_NOMEM;
  sqlite4_free(pEnv, p);
  return SQLITE_OK; /*sqlite4_os_init();*/
}

Changes to src/printf.c.

352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
...
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
...
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
...
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
...
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
...
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
...
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783

784
785
786
787
788
789
790
...
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855

856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
...
883
884
885
886
887
888
889
890





891
892
893
894
895
896

897



898
899


900
901
902
903
904
905
906
907
908
909
910
911
          precision = width-(prefix!=0);
        }
        if( precision<etBUFSIZE-10 ){
          nOut = etBUFSIZE;
          zOut = buf;
        }else{
          nOut = precision + 10;
          zOut = zExtra = sqlite4Malloc( nOut );
          if( zOut==0 ){
            pAccum->mallocFailed = 1;
            return;
          }
        }
        bufpt = &zOut[nOut-1];
        if( xtype==etORDINAL ){
................................................................................
        }
        if( xtype==etEXP ){
          e2 = 0;
        }else{
          e2 = exp;
        }
        if( e2+precision+width > etBUFSIZE - 15 ){
          bufpt = zExtra = sqlite4Malloc( e2+precision+width+15 );
          if( bufpt==0 ){
            pAccum->mallocFailed = 1;
            return;
          }
        }
        zOut = bufpt;
        nsd = 0;
................................................................................
        k = precision;
        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
          if( ch==q )  n++;
        }
        needQuote = !isnull && xtype==etSQLESCAPE2;
        n += i + 1 + needQuote*2;
        if( n>etBUFSIZE ){
          bufpt = zExtra = sqlite4Malloc( n );
          if( bufpt==0 ){
            pAccum->mallocFailed = 1;
            return;
          }
        }else{
          bufpt = buf;
        }
................................................................................
    if( flag_leftjustify ){
      register int nspace;
      nspace = width-length;
      if( nspace>0 ){
        sqlite4AppendSpace(pAccum, nspace);
      }
    }
    sqlite4_free(zExtra);
  }/* End for loop over the format string */
} /* End of function */

/*
** Append N bytes of text from z to the StrAccum object.
*/
void sqlite4StrAccumAppend(StrAccum *p, const char *z, int N){
................................................................................
        return;
      }else{
        p->nAlloc = (int)szNew;
      }
      if( p->useMalloc==1 ){
        zNew = sqlite4DbRealloc(p->db, zOld, p->nAlloc);
      }else{
        zNew = sqlite4_realloc(zOld, p->nAlloc);
      }
      if( zNew ){
        if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
        p->zText = zNew;
      }else{
        p->mallocFailed = 1;
        sqlite4StrAccumReset(p);
................................................................................
char *sqlite4StrAccumFinish(StrAccum *p){
  if( p->zText ){
    p->zText[p->nChar] = 0;
    if( p->useMalloc && p->zText==p->zBase ){
      if( p->useMalloc==1 ){
        p->zText = sqlite4DbMallocRaw(p->db, p->nChar+1 );
      }else{
        p->zText = sqlite4_malloc(p->nChar+1);
      }
      if( p->zText ){
        memcpy(p->zText, p->zBase, p->nChar+1);
      }else{
        p->mallocFailed = 1;
      }
    }
................................................................................
** Reset an StrAccum string.  Reclaim all malloced memory.
*/
void sqlite4StrAccumReset(StrAccum *p){
  if( p->zText!=p->zBase ){
    if( p->useMalloc==1 ){
      sqlite4DbFree(p->db, p->zText);
    }else{
      sqlite4_free(p->zText);
    }
  }
  p->zText = 0;
}

/*
** Initialize a string accumulator
*/
void sqlite4StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
  p->zText = p->zBase = zBase;
  p->db = 0;

  p->nChar = 0;
  p->nAlloc = n;
  p->mxAlloc = mx;
  p->useMalloc = 1;
  p->tooBig = 0;
  p->mallocFailed = 0;
}
................................................................................
  return z;
}

/*
** Print into memory obtained from sqlite4_malloc().  Omit the internal
** %-conversion extensions.
*/
char *sqlite4_vmprintf(const char *zFormat, va_list ap){
  char *z;
  char zBase[SQLITE_PRINT_BUF_SIZE];
  StrAccum acc;
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite4_initialize(0) ) return 0;
#endif
  sqlite4StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  acc.useMalloc = 2;

  sqlite4VXPrintf(&acc, 0, zFormat, ap);
  z = sqlite4StrAccumFinish(&acc);
  return z;
}

/*
** Print into memory obtained from sqlite4_malloc()().  Omit the internal
** %-conversion extensions.
*/
char *sqlite4_mprintf(const char *zFormat, ...){
  va_list ap;
  char *z;
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite4_initialize(0) ) return 0;
#endif
  va_start(ap, zFormat);
  z = sqlite4_vmprintf(zFormat, ap);
  va_end(ap);
  return z;
}

/*
** sqlite4_snprintf() works like snprintf() except that it ignores the
** current locale settings.  This is important for SQLite because we
................................................................................
** Oops:  The first two arguments of sqlite4_snprintf() are backwards
** from the snprintf() standard.  Unfortunately, it is too late to change
** this without breaking compatibility, so we just have to live with the
** mistake.
**
** sqlite4_vsnprintf() is the varargs version.
*/
char *sqlite4_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){





  StrAccum acc;
  if( n<=0 ) return zBuf;
  sqlite4StrAccumInit(&acc, zBuf, n, 0);
  acc.useMalloc = 0;
  sqlite4VXPrintf(&acc, 0, zFormat, ap);
  return sqlite4StrAccumFinish(&acc);

}



char *sqlite4_snprintf(int n, char *zBuf, const char *zFormat, ...){
  char *z;


  va_list ap;
  va_start(ap,zFormat);
  z = sqlite4_vsnprintf(n, zBuf, zFormat, ap);
  va_end(ap);
  return z;
}

/*
** This is the routine that actually formats the sqlite4_log() message.
** We house it in a separate routine from sqlite4_log() to avoid using
** stack space on small-stack systems when logging is disabled.
**







|







 







|







 







|







 







|







 







|







 







|







 







|











>







 







|




|



>









|



|


|







 







|
>
>
>
>
>

|



|
>

>
>
>
|
<
>
>


|

|







352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
...
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
...
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
...
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
...
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
...
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
...
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
...
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
...
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909

910
911
912
913
914
915
916
917
918
919
920
921
922
923
          precision = width-(prefix!=0);
        }
        if( precision<etBUFSIZE-10 ){
          nOut = etBUFSIZE;
          zOut = buf;
        }else{
          nOut = precision + 10;
          zOut = zExtra = sqlite4Malloc(pAccum->pEnv, nOut);
          if( zOut==0 ){
            pAccum->mallocFailed = 1;
            return;
          }
        }
        bufpt = &zOut[nOut-1];
        if( xtype==etORDINAL ){
................................................................................
        }
        if( xtype==etEXP ){
          e2 = 0;
        }else{
          e2 = exp;
        }
        if( e2+precision+width > etBUFSIZE - 15 ){
          bufpt = zExtra = sqlite4Malloc(pAccum->pEnv, e2+precision+width+15 );
          if( bufpt==0 ){
            pAccum->mallocFailed = 1;
            return;
          }
        }
        zOut = bufpt;
        nsd = 0;
................................................................................
        k = precision;
        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
          if( ch==q )  n++;
        }
        needQuote = !isnull && xtype==etSQLESCAPE2;
        n += i + 1 + needQuote*2;
        if( n>etBUFSIZE ){
          bufpt = zExtra = sqlite4Malloc(pAccum->pEnv, n);
          if( bufpt==0 ){
            pAccum->mallocFailed = 1;
            return;
          }
        }else{
          bufpt = buf;
        }
................................................................................
    if( flag_leftjustify ){
      register int nspace;
      nspace = width-length;
      if( nspace>0 ){
        sqlite4AppendSpace(pAccum, nspace);
      }
    }
    sqlite4_free(pAccum->pEnv, zExtra);
  }/* End for loop over the format string */
} /* End of function */

/*
** Append N bytes of text from z to the StrAccum object.
*/
void sqlite4StrAccumAppend(StrAccum *p, const char *z, int N){
................................................................................
        return;
      }else{
        p->nAlloc = (int)szNew;
      }
      if( p->useMalloc==1 ){
        zNew = sqlite4DbRealloc(p->db, zOld, p->nAlloc);
      }else{
        zNew = sqlite4_realloc(p->pEnv, zOld, p->nAlloc);
      }
      if( zNew ){
        if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
        p->zText = zNew;
      }else{
        p->mallocFailed = 1;
        sqlite4StrAccumReset(p);
................................................................................
char *sqlite4StrAccumFinish(StrAccum *p){
  if( p->zText ){
    p->zText[p->nChar] = 0;
    if( p->useMalloc && p->zText==p->zBase ){
      if( p->useMalloc==1 ){
        p->zText = sqlite4DbMallocRaw(p->db, p->nChar+1 );
      }else{
        p->zText = sqlite4_malloc(p->pEnv, p->nChar+1);
      }
      if( p->zText ){
        memcpy(p->zText, p->zBase, p->nChar+1);
      }else{
        p->mallocFailed = 1;
      }
    }
................................................................................
** Reset an StrAccum string.  Reclaim all malloced memory.
*/
void sqlite4StrAccumReset(StrAccum *p){
  if( p->zText!=p->zBase ){
    if( p->useMalloc==1 ){
      sqlite4DbFree(p->db, p->zText);
    }else{
      sqlite4_free(p->pEnv, p->zText);
    }
  }
  p->zText = 0;
}

/*
** Initialize a string accumulator
*/
void sqlite4StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
  p->zText = p->zBase = zBase;
  p->db = 0;
  p->pEnv = 0;
  p->nChar = 0;
  p->nAlloc = n;
  p->mxAlloc = mx;
  p->useMalloc = 1;
  p->tooBig = 0;
  p->mallocFailed = 0;
}
................................................................................
  return z;
}

/*
** Print into memory obtained from sqlite4_malloc().  Omit the internal
** %-conversion extensions.
*/
char *sqlite4_vmprintf(sqlite4_env *pEnv, const char *zFormat, va_list ap){
  char *z;
  char zBase[SQLITE_PRINT_BUF_SIZE];
  StrAccum acc;
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite4_initialize(pEnv) ) return 0;
#endif
  sqlite4StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  acc.useMalloc = 2;
  acc.pEnv = pEnv;
  sqlite4VXPrintf(&acc, 0, zFormat, ap);
  z = sqlite4StrAccumFinish(&acc);
  return z;
}

/*
** Print into memory obtained from sqlite4_malloc()().  Omit the internal
** %-conversion extensions.
*/
char *sqlite4_mprintf(sqlite4_env *pEnv, const char *zFormat, ...){
  va_list ap;
  char *z;
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite4_initialize(pEnv) ) return 0;
#endif
  va_start(ap, zFormat);
  z = sqlite4_vmprintf(pEnv, zFormat, ap);
  va_end(ap);
  return z;
}

/*
** sqlite4_snprintf() works like snprintf() except that it ignores the
** current locale settings.  This is important for SQLite because we
................................................................................
** Oops:  The first two arguments of sqlite4_snprintf() are backwards
** from the snprintf() standard.  Unfortunately, it is too late to change
** this without breaking compatibility, so we just have to live with the
** mistake.
**
** sqlite4_vsnprintf() is the varargs version.
*/
sqlite4_size_t sqlite4_vsnprintf(
  char *zBuf,              /* Write results here */
  sqlite4_size_t n,        /* Bytes available in zBuf[] */
  const char *zFormat,     /* Format string */
  va_list ap               /* Arguments */
){
  StrAccum acc;
  if( n<=0 ) return 0;
  sqlite4StrAccumInit(&acc, zBuf, n, 0);
  acc.useMalloc = 0;
  sqlite4VXPrintf(&acc, 0, zFormat, ap);
  sqlite4StrAccumFinish(&acc);
  return acc.nChar;
}
sqlite4_size_t sqlite4_snprintf(
  char *zBuf,              /* Write results here */
  sqlite4_size_t n,        /* Bytes available in zBuf[] */
  const char *zFormat,     /* Format string */

  ...                      /* Arguments */
){
  va_list ap;
  va_start(ap,zFormat);
  n = sqlite4_vsnprintf(zBuf, n, zFormat, ap);
  va_end(ap);
  return n;
}

/*
** This is the routine that actually formats the sqlite4_log() message.
** We house it in a separate routine from sqlite4_log() to avoid using
** stack space on small-stack systems when logging is disabled.
**

Changes to src/random.c.

98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
  t += wsdPrng.s[wsdPrng.i];
  return wsdPrng.s[t];
}

/*
** Return N random bytes.
*/
void sqlite4_randomness(int N, void *pBuf){
  unsigned char *zBuf = pBuf;
#if SQLITE_THREADSAFE
  sqlite4_mutex *mutex = sqlite4MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
#endif
  sqlite4_mutex_enter(mutex);
  while( N-- ){
    *(zBuf++) = randomByte();







|







98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
  t += wsdPrng.s[wsdPrng.i];
  return wsdPrng.s[t];
}

/*
** Return N random bytes.
*/
void sqlite4_randomness(sqlite4_env *pEnv, int N, void *pBuf){
  unsigned char *zBuf = pBuf;
#if SQLITE_THREADSAFE
  sqlite4_mutex *mutex = sqlite4MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
#endif
  sqlite4_mutex_enter(mutex);
  while( N-- ){
    *(zBuf++) = randomByte();

Changes to src/shell.c.

264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
...
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
....
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
....
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
....
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
....
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
....
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
....
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
....
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
....
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
....
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
....
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
....
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
....
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
....
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
....
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
....
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
....
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
....
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
....
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
....
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
....
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
*/
#ifdef SQLITE_ENABLE_IOTRACE
static void iotracePrintf(const char *zFormat, ...){
  va_list ap;
  char *z;
  if( iotrace==0 ) return;
  va_start(ap, zFormat);
  z = sqlite4_vmprintf(zFormat, ap);
  va_end(ap);
  fprintf(iotrace, "%s", z);
  sqlite4_free(z);
}
#endif


/*
** Determines if a string is a number of not.
*/
................................................................................
/*
** Allocate space and save off current error string.
*/
static char *save_err_msg(
  sqlite4 *db            /* Database to query */
){
  int nErrMsg = 1+strlen30(sqlite4_errmsg(db));
  char *zErrMsg = sqlite4_malloc(nErrMsg);
  if( zErrMsg ){
    memcpy(zErrMsg, sqlite4_errmsg(db), nErrMsg);
  }
  return zErrMsg;
}

/*
................................................................................
      rc = sqlite4_step(pStmt);
      /* if we have a result set... */
      if( SQLITE_ROW == rc ){
        /* if we have a callback... */
        if( xCallback ){
          /* allocate space for col name ptr, value ptr, and type */
          int nCol = sqlite4_column_count(pStmt);
          void *pData = sqlite4_malloc(3*nCol*sizeof(const char*) + 1);
          if( !pData ){
            rc = SQLITE_NOMEM;
          }else{
            char **azCols = (char **)pData;      /* Names of result columns */
            char **azVals = &azCols[nCol];       /* Results */
            int *aiTypes = (int *)&azVals[nCol]; /* Result types */
            int i;
................................................................................
                if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
                  rc = SQLITE_ABORT;
                }else{
                  rc = sqlite4_step(pStmt);
                }
              }
            } while( SQLITE_ROW == rc );
            sqlite4_free(pData);
          }
        }else{
          do{
            rc = sqlite4_step(pStmt);
          } while( rc == SQLITE_ROW );
        }
      }
................................................................................
    return 0;
  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
    char *zIns;
    if( !p->writableSchema ){
      fprintf(p->out, "PRAGMA writable_schema=ON;\n");
      p->writableSchema = 1;
    }
    zIns = sqlite4_mprintf(
       "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
       "VALUES('table','%q','%q',0,'%q');",
       zTable, zTable, zSql);
    fprintf(p->out, "%s\n", zIns);
    sqlite4_free(zIns);
    return 0;
  }else{
    fprintf(p->out, "%s;\n", zSql);
  }

  if( strcmp(zType, "table")==0 ){
    sqlite4_stmt *pTableInfo = 0;
................................................................................
  rc = sqlite4_exec(p->db, zQuery, dump_callback, p, &zErr);
  if( rc==SQLITE_CORRUPT ){
    char *zQ2;
    int len = strlen30(zQuery);
    fprintf(p->out, "/****** CORRUPTION ERROR *******/\n");
    if( zErr ){
      fprintf(p->out, "/****** %s ******/\n", zErr);
      sqlite4_free(zErr);
      zErr = 0;
    }
    zQ2 = malloc( len+100 );
    if( zQ2==0 ) return rc;
    sqlite4_snprintf(sizeof(zQ2), zQ2, "%s ORDER BY rowid DESC", zQuery);
    rc = sqlite4_exec(p->db, zQ2, dump_callback, p, &zErr);
    if( rc ){
      fprintf(p->out, "/****** ERROR: %s ******/\n", zErr);
    }else{
      rc = SQLITE_CORRUPT;
    }
    sqlite4_free(zErr);
    free(zQ2);
  }
  return rc;
}

/*
** Text of a help message
................................................................................
    data.colWidth[0] = 3;
    data.colWidth[1] = 15;
    data.colWidth[2] = 58;
    data.cnt = 0;
    sqlite4_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
    if( zErrMsg ){
      fprintf(stderr,"Error: %s\n", zErrMsg);
      sqlite4_free(zErrMsg);
      rc = 1;
    }
  }else

  if( c=='d' && strncmp(azArg[0], "dump", n)==0 && nArg<3 ){
    open_db(p);
    /* When playing back a "dump", the content might appear in an order
................................................................................

    open_db(p);
    nSep = strlen30(p->separator);
    if( nSep==0 ){
      fprintf(stderr, "Error: non-null separator required for import\n");
      return 1;
    }
    zSql = sqlite4_mprintf("SELECT * FROM %s", zTable);
    if( zSql==0 ){
      fprintf(stderr, "Error: out of memory\n");
      return 1;
    }
    nByte = strlen30(zSql);
    rc = sqlite4_prepare(p->db, zSql, -1, &pStmt, 0);
    sqlite4_free(zSql);
    if( rc ){
      if (pStmt) sqlite4_finalize(pStmt);
      fprintf(stderr,"Error: %s\n", sqlite4_errmsg(db));
      return 1;
    }
    nCol = sqlite4_column_count(pStmt);
    sqlite4_finalize(pStmt);
................................................................................
    pStmt = 0;
    if( nCol==0 ) return 0; /* no columns, no error */
    zSql = malloc( nByte + 20 + nCol*2 );
    if( zSql==0 ){
      fprintf(stderr, "Error: out of memory\n");
      return 1;
    }
    sqlite4_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zTable);
    j = strlen30(zSql);
    for(i=1; i<nCol; i++){
      zSql[j++] = ',';
      zSql[j++] = '?';
    }
    zSql[j++] = ')';
    zSql[j] = 0;
................................................................................
        "ORDER BY 1",
        callback, &data, &zErrMsg
      );
      zShellStatic = 0;
    }
    if( zErrMsg ){
      fprintf(stderr,"Error: %s\n", zErrMsg);
      sqlite4_free(zErrMsg);
      rc = 1;
    }else if( rc != SQLITE_OK ){
      fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n");
      rc = 1;
    }
  }else

................................................................................
    char *zErrMsg = 0;
    zFile = azArg[1];
    zProc = nArg>=3 ? azArg[2] : 0;
    open_db(p);
    rc = sqlite4_load_extension(p->db, zFile, zProc, &zErrMsg);
    if( rc!=SQLITE_OK ){
      fprintf(stderr, "Error: %s\n", zErrMsg);
      sqlite4_free(zErrMsg);
      rc = 1;
    }
  }else
#endif

  if( c=='l' && strncmp(azArg[0], "log", n)==0 && nArg>=2 ){
    const char *zFile = azArg[1];
................................................................................
      p->mode = MODE_List;
    }else if( n2==4 && strncmp(azArg[1],"html",n2)==0 ){
      p->mode = MODE_Html;
    }else if( n2==3 && strncmp(azArg[1],"tcl",n2)==0 ){
      p->mode = MODE_Tcl;
    }else if( n2==3 && strncmp(azArg[1],"csv",n2)==0 ){
      p->mode = MODE_Csv;
      sqlite4_snprintf(sizeof(p->separator), p->separator, ",");
    }else if( n2==4 && strncmp(azArg[1],"tabs",n2)==0 ){
      p->mode = MODE_List;
      sqlite4_snprintf(sizeof(p->separator), p->separator, "\t");
    }else if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){
      p->mode = MODE_Insert;
      set_table_name(p, "table");
    }else {
      fprintf(stderr,"Error: mode should be one of: "
         "column csv html insert line list tabs tcl\n");
      rc = 1;
................................................................................
      fprintf(stderr, "Error: invalid arguments: "
        " \"%s\". Enter \".help\" for help\n", azArg[2]);
      rc = 1;
    }
  }else

  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) {
    sqlite4_snprintf(sizeof(p->nullvalue), p->nullvalue,
                     "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]);
  }else

  if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){
    if( p->out!=stdout ){
      fclose(p->out);
    }
    if( strcmp(azArg[1],"stdout")==0 ){
      p->out = stdout;
      sqlite4_snprintf(sizeof(p->outfile), p->outfile, "stdout");
    }else{
      p->out = fopen(azArg[1], "wb");
      if( p->out==0 ){
        fprintf(stderr,"Error: cannot write to \"%s\"\n", azArg[1]);
        p->out = stdout;
        rc = 1;
      } else {
         sqlite4_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]);
      }
    }
  }else

  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 && (nArg==2 || nArg==3)){
    if( nArg >= 2) {
      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
................................................................................
         "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'"
         "ORDER BY substr(type,2,1), name",
         callback, &data, &zErrMsg
      );
    }
    if( zErrMsg ){
      fprintf(stderr,"Error: %s\n", zErrMsg);
      sqlite4_free(zErrMsg);
      rc = 1;
    }else if( rc != SQLITE_OK ){
      fprintf(stderr,"Error: querying schema information\n");
      rc = 1;
    }else{
      rc = 0;
    }
  }else

  if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){
    sqlite4_snprintf(sizeof(p->separator), p->separator,
                     "%.*s", (int)sizeof(p->separator)-1, azArg[1]);
  }else

  if( c=='s' && strncmp(azArg[0], "show", n)==0 && nArg==1 ){
    int i;
    fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off");
    fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off");
................................................................................
    char **azResult;
    int nRow, nAlloc;
    char *zSql = 0;
    int ii;
    open_db(p);
    rc = sqlite4_prepare(p->db, "PRAGMA database_list", -1, &pStmt, 0);
    if( rc ) return rc;
    zSql = sqlite4_mprintf(
        "SELECT name FROM sqlite_master"
        " WHERE type IN ('table','view')"
        "   AND name NOT LIKE 'sqlite_%%'"
        "   AND name LIKE ?1");
    while( sqlite4_step(pStmt)==SQLITE_ROW ){
      const char *zDbName = (const char*)sqlite4_column_text(pStmt, 1);
      if( zDbName==0 || strcmp(zDbName,"main")==0 ) continue;
      if( strcmp(zDbName,"temp")==0 ){
        zSql = sqlite4_mprintf(
                 "%z UNION ALL "
                 "SELECT 'temp.' || name FROM sqlite_temp_master"
                 " WHERE type IN ('table','view')"
                 "   AND name NOT LIKE 'sqlite_%%'"
                 "   AND name LIKE ?1", zSql);
      }else{
        zSql = sqlite4_mprintf(
                 "%z UNION ALL "
                 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
                 " WHERE type IN ('table','view')"
                 "   AND name NOT LIKE 'sqlite_%%'"
                 "   AND name LIKE ?1", zSql, zDbName, zDbName);
      }
    }
    sqlite4_finalize(pStmt);
    zSql = sqlite4_mprintf("%z ORDER BY 1", zSql);
    rc = sqlite4_prepare(p->db, zSql, -1, &pStmt, 0);
    sqlite4_free(zSql);
    if( rc ) return rc;
    nRow = nAlloc = 0;
    azResult = 0;
    if( nArg>1 ){
      sqlite4_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
    }else{
      sqlite4_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
    }
    while( sqlite4_step(pStmt)==SQLITE_ROW ){
      if( nRow>=nAlloc ){
        char **azNew;
        int n = nAlloc*2 + 10;
        azNew = sqlite4_realloc(azResult, sizeof(azResult[0])*n);
        if( azNew==0 ){
          fprintf(stderr, "Error: out of memory\n");
          break;
        }
        nAlloc = n;
        azResult = azNew;
      }
      azResult[nRow] = sqlite4_mprintf("%s", sqlite4_column_text(pStmt, 0));
      if( azResult[nRow] ) nRow++;
    }
    sqlite4_finalize(pStmt);        
    if( nRow>0 ){
      int len, maxlen = 0;
      int i, j;
      int nPrintCol, nPrintRow;
................................................................................
        for(j=i; j<nRow; j+=nPrintRow){
          char *zSp = j<nPrintRow ? "" : "  ";
          printf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j] : "");
        }
        printf("\n");
      }
    }
    for(ii=0; ii<nRow; ii++) sqlite4_free(azResult[ii]);
    sqlite4_free(azResult);
  }else

  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
    static const struct {
       const char *zCtrlName;   /* Name of a test-control option */
       int ctrlCode;            /* Integer code for that option */
    } aCtrl[] = {
................................................................................
      open_db(p);
      BEGIN_TIMER;
      rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
      END_TIMER;
      if( rc || zErrMsg ){
        char zPrefix[100];
        if( in!=0 || !stdin_is_interactive ){
          sqlite4_snprintf(sizeof(zPrefix), zPrefix, 
                           "Error: near line %d:", startline);
        }else{
          sqlite4_snprintf(sizeof(zPrefix), zPrefix, "Error:");
        }
        if( zErrMsg!=0 ){
          fprintf(stderr, "%s %s\n", zPrefix, zErrMsg);
          sqlite4_free(zErrMsg);
          zErrMsg = 0;
        }else{
          fprintf(stderr, "%s %s\n", zPrefix, sqlite4_errmsg(p->db));
        }
        errCnt++;
      }
      free(zSql);
................................................................................
    int n;
    zDrive = getenv("HOMEDRIVE");
    zPath = getenv("HOMEPATH");
    if( zDrive && zPath ){
      n = strlen30(zDrive) + strlen30(zPath) + 1;
      home_dir = malloc( n );
      if( home_dir==0 ) return 0;
      sqlite4_snprintf(n, home_dir, "%s%s", zDrive, zPath);
      return home_dir;
    }
    home_dir = "c:\\";
  }
#endif

#endif /* !_WIN32_WCE */
................................................................................
    }
    nBuf = strlen30(home_dir) + 16;
    zBuf = malloc( nBuf );
    if( zBuf==0 ){
      fprintf(stderr,"%s: Error: out of memory\n",Argv0);
      return 1;
    }
    sqlite4_snprintf(nBuf, zBuf,"%s/.sqliterc",home_dir);
    free(home_dir);
    sqliterc = (const char*)zBuf;
  }
  in = fopen(sqliterc,"rb");
  if( in ){
    if( stdin_is_interactive ){
      fprintf(stderr,"-- Loading resources from %s\n",sqliterc);
................................................................................
*/
static void main_init(struct callback_data *data) {
  memset(data, 0, sizeof(*data));
  data->mode = MODE_List;
  memcpy(data->separator,"|", 2);
  data->showHeader = 0;
  sqlite4_env_config(0, SQLITE_ENVCONFIG_LOG, shellLog, data);
  sqlite4_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
  sqlite4_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
  sqlite4_env_config(0, SQLITE_ENVCONFIG_SINGLETHREAD);
}

int main(int argc, char **argv){
  char *zErrMsg = 0;
  struct callback_data data;
  const char *zInitFile = 0;
................................................................................
    }else if( strcmp(z,"-separator")==0 ){
      i++;
      if(i>=argc){
        fprintf(stderr,"%s: Error: missing argument for option: %s\n", Argv0, z);
        fprintf(stderr,"Use -help for a list of options.\n");
        return 1;
      }
      sqlite4_snprintf(sizeof(data.separator), data.separator,
                       "%.*s",(int)sizeof(data.separator)-1,argv[i]);
    }else if( strcmp(z,"-nullvalue")==0 ){
      i++;
      if(i>=argc){
        fprintf(stderr,"%s: Error: missing argument for option: %s\n", Argv0, z);
        fprintf(stderr,"Use -help for a list of options.\n");
        return 1;
      }
      sqlite4_snprintf(sizeof(data.nullvalue), data.nullvalue,
                       "%.*s",(int)sizeof(data.nullvalue)-1,argv[i]);
    }else if( strcmp(z,"-header")==0 ){
      data.showHeader = 1;
    }else if( strcmp(z,"-noheader")==0 ){
      data.showHeader = 0;
    }else if( strcmp(z,"-echo")==0 ){
      data.echoOn = 1;
................................................................................
        "Enter SQL statements terminated with a \";\"\n",
        sqlite4_libversion(), sqlite4_sourceid()
      );
      zHome = find_home_dir();
      if( zHome ){
        nHistory = strlen30(zHome) + 20;
        if( (zHistory = malloc(nHistory))!=0 ){
          sqlite4_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
        }
      }
#if defined(HAVE_READLINE) && HAVE_READLINE==1
      if( zHistory ) read_history(zHistory);
#endif
      rc = process_input(&data, 0);
      if( zHistory ){







|


|







 







|







 







|







 







|







 







|




|







 







|




|






|







 







|







 







|






|







 







|







 







|







 







|







 







|


|







 







|









|







|







 







|










|







 







|








|






|








|

|












|







|







 







|
|







 







|


|



|







 







|







 







|







 







|
|







 







|








|







 







|







264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
...
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
....
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
....
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
....
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
....
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
....
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
....
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
....
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
....
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
....
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
....
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
....
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
....
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
....
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
....
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
....
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
....
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
....
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
....
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
....
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
....
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
*/
#ifdef SQLITE_ENABLE_IOTRACE
static void iotracePrintf(const char *zFormat, ...){
  va_list ap;
  char *z;
  if( iotrace==0 ) return;
  va_start(ap, zFormat);
  z = sqlite4_vmprintf(0, zFormat, ap);
  va_end(ap);
  fprintf(iotrace, "%s", z);
  sqlite4_free(0, z);
}
#endif


/*
** Determines if a string is a number of not.
*/
................................................................................
/*
** Allocate space and save off current error string.
*/
static char *save_err_msg(
  sqlite4 *db            /* Database to query */
){
  int nErrMsg = 1+strlen30(sqlite4_errmsg(db));
  char *zErrMsg = sqlite4_malloc(0, nErrMsg);
  if( zErrMsg ){
    memcpy(zErrMsg, sqlite4_errmsg(db), nErrMsg);
  }
  return zErrMsg;
}

/*
................................................................................
      rc = sqlite4_step(pStmt);
      /* if we have a result set... */
      if( SQLITE_ROW == rc ){
        /* if we have a callback... */
        if( xCallback ){
          /* allocate space for col name ptr, value ptr, and type */
          int nCol = sqlite4_column_count(pStmt);
          void *pData = sqlite4_malloc(0, 3*nCol*sizeof(const char*) + 1);
          if( !pData ){
            rc = SQLITE_NOMEM;
          }else{
            char **azCols = (char **)pData;      /* Names of result columns */
            char **azVals = &azCols[nCol];       /* Results */
            int *aiTypes = (int *)&azVals[nCol]; /* Result types */
            int i;
................................................................................
                if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
                  rc = SQLITE_ABORT;
                }else{
                  rc = sqlite4_step(pStmt);
                }
              }
            } while( SQLITE_ROW == rc );
            sqlite4_free(0, pData);
          }
        }else{
          do{
            rc = sqlite4_step(pStmt);
          } while( rc == SQLITE_ROW );
        }
      }
................................................................................
    return 0;
  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
    char *zIns;
    if( !p->writableSchema ){
      fprintf(p->out, "PRAGMA writable_schema=ON;\n");
      p->writableSchema = 1;
    }
    zIns = sqlite4_mprintf(0, 
       "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
       "VALUES('table','%q','%q',0,'%q');",
       zTable, zTable, zSql);
    fprintf(p->out, "%s\n", zIns);
    sqlite4_free(0, zIns);
    return 0;
  }else{
    fprintf(p->out, "%s;\n", zSql);
  }

  if( strcmp(zType, "table")==0 ){
    sqlite4_stmt *pTableInfo = 0;
................................................................................
  rc = sqlite4_exec(p->db, zQuery, dump_callback, p, &zErr);
  if( rc==SQLITE_CORRUPT ){
    char *zQ2;
    int len = strlen30(zQuery);
    fprintf(p->out, "/****** CORRUPTION ERROR *******/\n");
    if( zErr ){
      fprintf(p->out, "/****** %s ******/\n", zErr);
      sqlite4_free(0, zErr);
      zErr = 0;
    }
    zQ2 = malloc( len+100 );
    if( zQ2==0 ) return rc;
    sqlite4_snprintf(zQ2,sizeof(zQ2), "%s ORDER BY rowid DESC", zQuery);
    rc = sqlite4_exec(p->db, zQ2, dump_callback, p, &zErr);
    if( rc ){
      fprintf(p->out, "/****** ERROR: %s ******/\n", zErr);
    }else{
      rc = SQLITE_CORRUPT;
    }
    sqlite4_free(0, zErr);
    free(zQ2);
  }
  return rc;
}

/*
** Text of a help message
................................................................................
    data.colWidth[0] = 3;
    data.colWidth[1] = 15;
    data.colWidth[2] = 58;
    data.cnt = 0;
    sqlite4_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
    if( zErrMsg ){
      fprintf(stderr,"Error: %s\n", zErrMsg);
      sqlite4_free(0, zErrMsg);
      rc = 1;
    }
  }else

  if( c=='d' && strncmp(azArg[0], "dump", n)==0 && nArg<3 ){
    open_db(p);
    /* When playing back a "dump", the content might appear in an order
................................................................................

    open_db(p);
    nSep = strlen30(p->separator);
    if( nSep==0 ){
      fprintf(stderr, "Error: non-null separator required for import\n");
      return 1;
    }
    zSql = sqlite4_mprintf(0, "SELECT * FROM %s", zTable);
    if( zSql==0 ){
      fprintf(stderr, "Error: out of memory\n");
      return 1;
    }
    nByte = strlen30(zSql);
    rc = sqlite4_prepare(p->db, zSql, -1, &pStmt, 0);
    sqlite4_free(0, zSql);
    if( rc ){
      if (pStmt) sqlite4_finalize(pStmt);
      fprintf(stderr,"Error: %s\n", sqlite4_errmsg(db));
      return 1;
    }
    nCol = sqlite4_column_count(pStmt);
    sqlite4_finalize(pStmt);
................................................................................
    pStmt = 0;
    if( nCol==0 ) return 0; /* no columns, no error */
    zSql = malloc( nByte + 20 + nCol*2 );
    if( zSql==0 ){
      fprintf(stderr, "Error: out of memory\n");
      return 1;
    }
    sqlite4_snprintf(zSql, nByte+20, "INSERT INTO %s VALUES(?", zTable);
    j = strlen30(zSql);
    for(i=1; i<nCol; i++){
      zSql[j++] = ',';
      zSql[j++] = '?';
    }
    zSql[j++] = ')';
    zSql[j] = 0;
................................................................................
        "ORDER BY 1",
        callback, &data, &zErrMsg
      );
      zShellStatic = 0;
    }
    if( zErrMsg ){
      fprintf(stderr,"Error: %s\n", zErrMsg);
      sqlite4_free(0, zErrMsg);
      rc = 1;
    }else if( rc != SQLITE_OK ){
      fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n");
      rc = 1;
    }
  }else

................................................................................
    char *zErrMsg = 0;
    zFile = azArg[1];
    zProc = nArg>=3 ? azArg[2] : 0;
    open_db(p);
    rc = sqlite4_load_extension(p->db, zFile, zProc, &zErrMsg);
    if( rc!=SQLITE_OK ){
      fprintf(stderr, "Error: %s\n", zErrMsg);
      sqlite4_free(0, zErrMsg);
      rc = 1;
    }
  }else
#endif

  if( c=='l' && strncmp(azArg[0], "log", n)==0 && nArg>=2 ){
    const char *zFile = azArg[1];
................................................................................
      p->mode = MODE_List;
    }else if( n2==4 && strncmp(azArg[1],"html",n2)==0 ){
      p->mode = MODE_Html;
    }else if( n2==3 && strncmp(azArg[1],"tcl",n2)==0 ){
      p->mode = MODE_Tcl;
    }else if( n2==3 && strncmp(azArg[1],"csv",n2)==0 ){
      p->mode = MODE_Csv;
      sqlite4_snprintf(p->separator, sizeof(p->separator), ",");
    }else if( n2==4 && strncmp(azArg[1],"tabs",n2)==0 ){
      p->mode = MODE_List;
      sqlite4_snprintf(p->separator, sizeof(p->separator), "\t");
    }else if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){
      p->mode = MODE_Insert;
      set_table_name(p, "table");
    }else {
      fprintf(stderr,"Error: mode should be one of: "
         "column csv html insert line list tabs tcl\n");
      rc = 1;
................................................................................
      fprintf(stderr, "Error: invalid arguments: "
        " \"%s\". Enter \".help\" for help\n", azArg[2]);
      rc = 1;
    }
  }else

  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) {
    sqlite4_snprintf(p->nullvalue, sizeof(p->nullvalue),
                     "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]);
  }else

  if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){
    if( p->out!=stdout ){
      fclose(p->out);
    }
    if( strcmp(azArg[1],"stdout")==0 ){
      p->out = stdout;
      sqlite4_snprintf(p->outfile, sizeof(p->outfile), "stdout");
    }else{
      p->out = fopen(azArg[1], "wb");
      if( p->out==0 ){
        fprintf(stderr,"Error: cannot write to \"%s\"\n", azArg[1]);
        p->out = stdout;
        rc = 1;
      } else {
         sqlite4_snprintf(p->outfile, sizeof(p->outfile), "%s", azArg[1]);
      }
    }
  }else

  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 && (nArg==2 || nArg==3)){
    if( nArg >= 2) {
      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
................................................................................
         "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'"
         "ORDER BY substr(type,2,1), name",
         callback, &data, &zErrMsg
      );
    }
    if( zErrMsg ){
      fprintf(stderr,"Error: %s\n", zErrMsg);
      sqlite4_free(0, zErrMsg);
      rc = 1;
    }else if( rc != SQLITE_OK ){
      fprintf(stderr,"Error: querying schema information\n");
      rc = 1;
    }else{
      rc = 0;
    }
  }else

  if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){
    sqlite4_snprintf(p->separator, sizeof(p->separator),
                     "%.*s", (int)sizeof(p->separator)-1, azArg[1]);
  }else

  if( c=='s' && strncmp(azArg[0], "show", n)==0 && nArg==1 ){
    int i;
    fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off");
    fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off");
................................................................................
    char **azResult;
    int nRow, nAlloc;
    char *zSql = 0;
    int ii;
    open_db(p);
    rc = sqlite4_prepare(p->db, "PRAGMA database_list", -1, &pStmt, 0);
    if( rc ) return rc;
    zSql = sqlite4_mprintf(0, 
        "SELECT name FROM sqlite_master"
        " WHERE type IN ('table','view')"
        "   AND name NOT LIKE 'sqlite_%%'"
        "   AND name LIKE ?1");
    while( sqlite4_step(pStmt)==SQLITE_ROW ){
      const char *zDbName = (const char*)sqlite4_column_text(pStmt, 1);
      if( zDbName==0 || strcmp(zDbName,"main")==0 ) continue;
      if( strcmp(zDbName,"temp")==0 ){
        zSql = sqlite4_mprintf(0, 
                 "%z UNION ALL "
                 "SELECT 'temp.' || name FROM sqlite_temp_master"
                 " WHERE type IN ('table','view')"
                 "   AND name NOT LIKE 'sqlite_%%'"
                 "   AND name LIKE ?1", zSql);
      }else{
        zSql = sqlite4_mprintf(0, 
                 "%z UNION ALL "
                 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
                 " WHERE type IN ('table','view')"
                 "   AND name NOT LIKE 'sqlite_%%'"
                 "   AND name LIKE ?1", zSql, zDbName, zDbName);
      }
    }
    sqlite4_finalize(pStmt);
    zSql = sqlite4_mprintf(0, "%z ORDER BY 1", zSql);
    rc = sqlite4_prepare(p->db, zSql, -1, &pStmt, 0);
    sqlite4_free(0, zSql);
    if( rc ) return rc;
    nRow = nAlloc = 0;
    azResult = 0;
    if( nArg>1 ){
      sqlite4_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
    }else{
      sqlite4_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
    }
    while( sqlite4_step(pStmt)==SQLITE_ROW ){
      if( nRow>=nAlloc ){
        char **azNew;
        int n = nAlloc*2 + 10;
        azNew = sqlite4_realloc(0, azResult, sizeof(azResult[0])*n);
        if( azNew==0 ){
          fprintf(stderr, "Error: out of memory\n");
          break;
        }
        nAlloc = n;
        azResult = azNew;
      }
      azResult[nRow] = sqlite4_mprintf(0, "%s", sqlite4_column_text(pStmt, 0));
      if( azResult[nRow] ) nRow++;
    }
    sqlite4_finalize(pStmt);        
    if( nRow>0 ){
      int len, maxlen = 0;
      int i, j;
      int nPrintCol, nPrintRow;
................................................................................
        for(j=i; j<nRow; j+=nPrintRow){
          char *zSp = j<nPrintRow ? "" : "  ";
          printf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j] : "");
        }
        printf("\n");
      }
    }
    for(ii=0; ii<nRow; ii++) sqlite4_free(0, azResult[ii]);
    sqlite4_free(0, azResult);
  }else

  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
    static const struct {
       const char *zCtrlName;   /* Name of a test-control option */
       int ctrlCode;            /* Integer code for that option */
    } aCtrl[] = {
................................................................................
      open_db(p);
      BEGIN_TIMER;
      rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
      END_TIMER;
      if( rc || zErrMsg ){
        char zPrefix[100];
        if( in!=0 || !stdin_is_interactive ){
          sqlite4_snprintf(zPrefix, sizeof(zPrefix),
                           "Error: near line %d:", startline);
        }else{
          sqlite4_snprintf(zPrefix, sizeof(zPrefix), "Error:");
        }
        if( zErrMsg!=0 ){
          fprintf(stderr, "%s %s\n", zPrefix, zErrMsg);
          sqlite4_free(0, zErrMsg);
          zErrMsg = 0;
        }else{
          fprintf(stderr, "%s %s\n", zPrefix, sqlite4_errmsg(p->db));
        }
        errCnt++;
      }
      free(zSql);
................................................................................
    int n;
    zDrive = getenv("HOMEDRIVE");
    zPath = getenv("HOMEPATH");
    if( zDrive && zPath ){
      n = strlen30(zDrive) + strlen30(zPath) + 1;
      home_dir = malloc( n );
      if( home_dir==0 ) return 0;
      sqlite4_snprintf(home_dir, n, "%s%s", zDrive, zPath);
      return home_dir;
    }
    home_dir = "c:\\";
  }
#endif

#endif /* !_WIN32_WCE */
................................................................................
    }
    nBuf = strlen30(home_dir) + 16;
    zBuf = malloc( nBuf );
    if( zBuf==0 ){
      fprintf(stderr,"%s: Error: out of memory\n",Argv0);
      return 1;
    }
    sqlite4_snprintf(zBuf,nBuf,"%s/.sqliterc",home_dir);
    free(home_dir);
    sqliterc = (const char*)zBuf;
  }
  in = fopen(sqliterc,"rb");
  if( in ){
    if( stdin_is_interactive ){
      fprintf(stderr,"-- Loading resources from %s\n",sqliterc);
................................................................................
*/
static void main_init(struct callback_data *data) {
  memset(data, 0, sizeof(*data));
  data->mode = MODE_List;
  memcpy(data->separator,"|", 2);
  data->showHeader = 0;
  sqlite4_env_config(0, SQLITE_ENVCONFIG_LOG, shellLog, data);
  sqlite4_snprintf(mainPrompt,sizeof(mainPrompt),        "sqlite> ");
  sqlite4_snprintf(continuePrompt,sizeof(continuePrompt),"   ...> ");
  sqlite4_env_config(0, SQLITE_ENVCONFIG_SINGLETHREAD);
}

int main(int argc, char **argv){
  char *zErrMsg = 0;
  struct callback_data data;
  const char *zInitFile = 0;
................................................................................
    }else if( strcmp(z,"-separator")==0 ){
      i++;
      if(i>=argc){
        fprintf(stderr,"%s: Error: missing argument for option: %s\n", Argv0, z);
        fprintf(stderr,"Use -help for a list of options.\n");
        return 1;
      }
      sqlite4_snprintf(data.separator, sizeof(data.separator),
                       "%.*s",(int)sizeof(data.separator)-1,argv[i]);
    }else if( strcmp(z,"-nullvalue")==0 ){
      i++;
      if(i>=argc){
        fprintf(stderr,"%s: Error: missing argument for option: %s\n", Argv0, z);
        fprintf(stderr,"Use -help for a list of options.\n");
        return 1;
      }
      sqlite4_snprintf(data.nullvalue, sizeof(data.nullvalue),
                       "%.*s",(int)sizeof(data.nullvalue)-1,argv[i]);
    }else if( strcmp(z,"-header")==0 ){
      data.showHeader = 1;
    }else if( strcmp(z,"-noheader")==0 ){
      data.showHeader = 0;
    }else if( strcmp(z,"-echo")==0 ){
      data.echoOn = 1;
................................................................................
        "Enter SQL statements terminated with a \";\"\n",
        sqlite4_libversion(), sqlite4_sourceid()
      );
      zHome = find_home_dir();
      if( zHome ){
        nHistory = strlen30(zHome) + 20;
        if( (zHistory = malloc(nHistory))!=0 ){
          sqlite4_snprintf(zHistory, nHistory, "%s/.sqlite_history", zHome);
        }
      }
#if defined(HAVE_READLINE) && HAVE_READLINE==1
      if( zHistory ) read_history(zHistory);
#endif
      rc = process_input(&data, 0);
      if( zHistory ){

Changes to src/sqlite.h.in.

213
214
215
216
217
218
219
220
221
222

223
224
225
226
227
228
229
230
231
232
233
234
235

236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
...
292
293
294
295
296
297
298








299
300
301
302
303
304
305
...
709
710
711
712
713
714
715
716
717
718
719
720
721
722


723
724
725
726
727
728
729
730
....
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184


1185
1186
1187
1188
1189
1190
1191
....
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
....
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
....
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
....
2895
2896
2897
2898
2899
2900
2901

2902
2903
2904
2905
2906
2907
2908
....
2957
2958
2959
2960
2961
2962
2963

2964
2965


2966
2967
2968
2969
2970
2971
2972
int sqlite4_compileoption_used(const char *zOptName);
const char *sqlite4_compileoption_get(int N);
#endif

/*
** CAPIREF: Test To See If The Library Is Threadsafe
**
** ^The sqlite4_threadsafe() function returns zero if and only if
** SQLite was compiled with mutexing code omitted due to the
** [SQLITE_THREADSAFE] compile-time option being set to 0.

**
** SQLite can be compiled with or without mutexes.  When
** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
** are enabled and SQLite is threadsafe.  When the
** [SQLITE_THREADSAFE] macro is 0, 
** the mutexes are omitted.  Without the mutexes, it is not safe
** to use SQLite concurrently from more than one thread.
**
** Enabling mutexes incurs a measurable performance penalty.
** So if speed is of utmost importance, it makes sense to disable
** the mutexes.  But for maximum safety, mutexes should be enabled.
** ^The default behavior is for mutexes to be enabled.
**

** This interface can be used by an application to make sure that the
** version of SQLite that it is linking against was compiled with
** the desired setting of the [SQLITE_THREADSAFE] macro.
**
** This interface only reports on the compile-time mutex setting
** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
** can be fully or partially disabled using a call to [sqlite4_config()]
** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
** sqlite4_threadsafe() function shows only the compile-time setting of
** thread safety, not any run-time changes to that setting made by
** sqlite4_config(). In other words, the return value from sqlite4_threadsafe()
** is unchanged by calls to sqlite4_config().)^
**
** See the [threading mode] documentation for additional information.
*/
int sqlite4_threadsafe(void);

/*
** CAPIREF: Database Connection Handle
** KEYWORDS: {database connection} {database connections}
**
** Each open SQLite database is represented by a pointer to an instance of
** the opaque structure named "sqlite4".  It is useful to think of an sqlite4
................................................................................
#else
  typedef long long int sqlite_int64;
  typedef unsigned long long int sqlite_uint64;
#endif
typedef sqlite_int64 sqlite4_int64;
typedef sqlite_uint64 sqlite4_uint64;









/*
** If compiling for a processor that lacks floating point support,
** substitute integer for floating-point.
*/
#ifdef SQLITE_OMIT_FLOATING_POINT
# define double sqlite4_int64
#endif
................................................................................
** serialization.
**
** SQLite will never invoke xInit() more than once without an intervening
** call to xShutdown().
*/
typedef struct sqlite4_mem_methods sqlite4_mem_methods;
struct sqlite4_mem_methods {
  void *(*xMalloc)(int);         /* Memory allocation function */
  void (*xFree)(void*);          /* Free a prior allocation */
  void *(*xRealloc)(void*,int);  /* Resize an allocation */
  int (*xSize)(void*);           /* Return the size of an allocation */
  int (*xRoundup)(int);          /* Round up request size to allocation size */
  int (*xInit)(void*);           /* Initialize the memory allocator */
  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */


  void *pAppData;                /* Argument to xInit() and xShutdown() */
};

/*
** CAPIREF: Configuration Options
** KEYWORDS: {configuration option}
**
** These constants are the available integer configuration options that
................................................................................
** The strings returned by these two routines should be
** released by [sqlite4_free()].  ^Both routines return a
** NULL pointer if [sqlite4_malloc()] is unable to allocate enough
** memory to hold the resulting string.
**
** ^(The sqlite4_snprintf() routine is similar to "snprintf()" from
** the standard C library.  The result is written into the
** buffer supplied as the second parameter whose size is given by
** the first parameter. Note that the order of the
** first two parameters is reversed from snprintf().)^  This is an
** historical accident that cannot be fixed without breaking
** backwards compatibility.  ^(Note also that sqlite4_snprintf()
** returns a pointer to its buffer instead of the number of
** characters actually written into the buffer.)^  We admit that
** the number of characters written would be a more useful return
** value but we cannot change the implementation of sqlite4_snprintf()
** now without breaking compatibility.
**
** ^As long as the buffer size is greater than zero, sqlite4_snprintf()
** guarantees that the buffer is always zero-terminated.  ^The first


** parameter "n" is the total size of the buffer, including space for
** the zero terminator.  So the longest string that can be completely
** written will be n-1 characters.
**
** ^The sqlite4_vsnprintf() routine is a varargs version of sqlite4_snprintf().
**
** These routines all implement some additional formatting
................................................................................
** The code above will render a correct SQL statement in the zSQL
** variable even if the zText variable is a NULL pointer.
**
** ^(The "%z" formatting option works like "%s" but with the
** addition that after the string has been read and copied into
** the result, [sqlite4_free()] is called on the input string.)^
*/
char *sqlite4_mprintf(const char*,...);
char *sqlite4_vmprintf(const char*, va_list);
char *sqlite4_snprintf(int,char*,const char*, ...);
char *sqlite4_vsnprintf(int,char*,const char*, va_list);

/*
** CAPIREF: Memory Allocation Subsystem
**
** The SQLite core uses these three routines for all of its own
** internal memory allocation needs. "Core" in the previous sentence
** does not include operating-system specific VFS implementation.  The
** Windows VFS uses native malloc() and free() for some operations.
**
** ^The sqlite4_malloc() routine returns a pointer to a block
** of memory at least N bytes in length, where N is the parameter.
** ^If sqlite4_malloc() is unable to obtain sufficient free
** memory, it returns a NULL pointer.  ^If the parameter N to
** sqlite4_malloc() is zero or negative then sqlite4_malloc() returns
** a NULL pointer.
................................................................................
** is not freed.
**
** ^The memory returned by sqlite4_malloc() and sqlite4_realloc()
** is always aligned to at least an 8 byte boundary, or to a
** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
** option is used.
**
** In SQLite version 3.5.0 and 3.5.1, it was possible to define
** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
** implementation of these routines to be omitted.  That capability
** is no longer provided.  Only built-in memory allocators can be used.
**
** The Windows OS interface layer calls
** the system malloc() and free() directly when converting
** filenames between the UTF-8 encoding used by SQLite
** and whatever filename encoding is used by the particular Windows
** installation.  Memory allocation errors are detected, but
** they are reported back as [SQLITE_CANTOPEN] or
** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
**
** The pointer arguments to [sqlite4_free()] and [sqlite4_realloc()]
** must be either NULL or else pointers obtained from a prior
** invocation of [sqlite4_malloc()] or [sqlite4_realloc()] that have
** not yet been released.
**
** The application must not read or write any part of
** a block of memory after it has been released using
** [sqlite4_free()] or [sqlite4_realloc()].
*/
void *sqlite4_malloc(int);
void *sqlite4_realloc(void*, int);
void sqlite4_free(void*);

/*
** CAPIREF: Memory Allocator Statistics
**
** SQLite provides these two interfaces for reporting on the status
** of the [sqlite4_malloc()], [sqlite4_free()], and [sqlite4_realloc()]
** routines, which form the built-in memory allocation subsystem.
................................................................................
*/
sqlite4_uint64 sqlite4_memory_used(sqlite4_env*);
sqlite4_uint64 sqlite4_memory_highwater(sqlite4_env*, int resetFlag);

/*
** CAPIREF: Pseudo-Random Number Generator
**
** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
** select random [ROWID | ROWIDs] when inserting new records into a table that
** already uses the largest possible [ROWID].  The PRNG is also used for
** the build-in random() and randomblob() SQL functions.  This interface allows
** applications to access the same PRNG for other purposes.
**
** ^A call to this routine stores N bytes of randomness into buffer P.
**
** ^The first time this routine is invoked (either internally or by
** the application) the PRNG is seeded using randomness obtained
** from the xRandomness method of the default [sqlite4_vfs] object.
** ^On all subsequent invocations, the pseudo-randomness is generated
** internally and without recourse to the [sqlite4_vfs] xRandomness
** method.
*/
void sqlite4_randomness(int N, void *P);

/*
** CAPIREF: Compile-Time Authorization Callbacks
**
** ^This routine registers an authorizer callback with a particular
** [database connection], supplied in the first argument.
** ^The authorizer callback is invoked as SQL statements are being compiled
................................................................................
** ^The sqlite4_context_db_handle() interface returns a copy of
** the pointer to the [database connection] (the 1st parameter)
** of the [sqlite4_create_function()]
** and [sqlite4_create_function16()] routines that originally
** registered the application defined function.
*/
sqlite4 *sqlite4_context_db_handle(sqlite4_context*);


/*
** CAPIREF: Function Auxiliary Data
**
** The following two functions may be used by scalar SQL functions to
** associate metadata with argument values. If the same value is passed to
** multiple invocations of the same SQL function during query execution, under
................................................................................
** the near future and that SQLite should make its own private copy of
** the content before returning.
**
** The typedef is necessary to work around problems in certain
** C++ compilers.  See ticket #2191.
*/
typedef void (*sqlite4_destructor_type)(void*);

#define SQLITE_STATIC      ((sqlite4_destructor_type)0)
#define SQLITE_TRANSIENT   ((sqlite4_destructor_type)-1)



/*
** CAPIREF: Setting The Result Of An SQL Function
**
** These routines are used by the xFunc or xFinal callbacks that
** implement SQL functions and aggregates.  See
** [sqlite4_create_function()] and [sqlite4_create_function16()]







|
|
|
>

<
|
|
|
|
|

|
|
|
<

>
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<

|







 







>
>
>
>
>
>
>
>







 







|
|
|
|
<
|
|
>
>
|







 







|
|
|
|
|
|
|
|
|
|
|
|
|
>
>







 







|
|
|
|





|
<
<







 







<
<
<
<
<
<
<
<
<
<
<
<
<









|
|
|







 







<
<
<
<
<
<
|
<
<
<
<
<
<
<

|







 







>







 







>


>
>







213
214
215
216
217
218
219
220
221
222
223
224

225
226
227
228
229
230
231
232
233

234
235
236
237














238
239
240
241
242
243
244
245
246
...
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
...
703
704
705
706
707
708
709
710
711
712
713

714
715
716
717
718
719
720
721
722
723
724
725
....
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
....
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257


1258
1259
1260
1261
1262
1263
1264
....
1292
1293
1294
1295
1296
1297
1298













1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
....
1335
1336
1337
1338
1339
1340
1341






1342







1343
1344
1345
1346
1347
1348
1349
1350
1351
....
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
....
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
int sqlite4_compileoption_used(const char *zOptName);
const char *sqlite4_compileoption_get(int N);
#endif

/*
** CAPIREF: Test To See If The Library Is Threadsafe
**
** ^The sqlite4_threadsafe(E) function returns zero if the [sqlite4_env]
** object is configured in such a way that it should only be used by a
** single thread at a time.  In other words, this routine returns zero
** if the environment is configured as [SQLITE_ENVCONFIG_SINGLETHREAD].
**

** ^The sqlite4_threadsafe(E) function returns one if multiple
** [database connection] objects associated with E can be used at the
** same time in different threads, so long as no single [database connection]
** object is used by two or more threads at the same time.  This
** corresponds to [SQLITE_ENVCONFIG_MULTITHREAD].
**
** ^The sqlite4_threadsafe(E) function returns two if the same
** [database connection] can be used at the same time from two or more
** separate threads.  This setting corresponds to [SQLITE_ENVCONFIG_SERIALIZED].

**
** Note that SQLite4 is always threadsafe in this sense: Two or more
** objects each associated with different [sqlite4_env] objects can
** always be used at the same time in separate threads.














*/
int sqlite4_threadsafe(sqlite4_env*);

/*
** CAPIREF: Database Connection Handle
** KEYWORDS: {database connection} {database connections}
**
** Each open SQLite database is represented by a pointer to an instance of
** the opaque structure named "sqlite4".  It is useful to think of an sqlite4
................................................................................
#else
  typedef long long int sqlite_int64;
  typedef unsigned long long int sqlite_uint64;
#endif
typedef sqlite_int64 sqlite4_int64;
typedef sqlite_uint64 sqlite4_uint64;

/*
** CAPIREF: String length type
**
** A type for measuring the length of the string.  Like size_t but
** does not require &lt;stddef.h&gt;
*/
typedef int sqlite4_size_t;

/*
** If compiling for a processor that lacks floating point support,
** substitute integer for floating-point.
*/
#ifdef SQLITE_OMIT_FLOATING_POINT
# define double sqlite4_int64
#endif
................................................................................
** serialization.
**
** SQLite will never invoke xInit() more than once without an intervening
** call to xShutdown().
*/
typedef struct sqlite4_mem_methods sqlite4_mem_methods;
struct sqlite4_mem_methods {
  void *(*xMalloc)(void*,sqlite4_size_t); /* Memory allocation function */
  void (*xFree)(void*,void*);             /* Free a prior allocation */
  void *(*xRealloc)(void*,void*,int);     /* Resize an allocation */
  sqlite4_size_t (*xSize)(void*,void*);   /* Return the size of an allocation */

  int (*xInit)(void*);                    /* Initialize the memory allocator */
  void (*xShutdown)(void*);               /* Deinitialize the allocator */
  void (*xBeginBenign)(void*);            /* Enter a benign malloc region */
  void (*xEndBenign)(void*);              /* Leave a benign malloc region */
  void *pAppData;                         /* 1st argument to all routines */
};

/*
** CAPIREF: Configuration Options
** KEYWORDS: {configuration option}
**
** These constants are the available integer configuration options that
................................................................................
** The strings returned by these two routines should be
** released by [sqlite4_free()].  ^Both routines return a
** NULL pointer if [sqlite4_malloc()] is unable to allocate enough
** memory to hold the resulting string.
**
** ^(The sqlite4_snprintf() routine is similar to "snprintf()" from
** the standard C library.  The result is written into the
** buffer supplied as the first parameter whose size is given by
** the second parameter.)^  The return value from sqltie4_snprintf()
** is the number of bytes actually written into the buffer, not
** counting the zero terminator.  The buffer is always zero-terminated
** as long as it it at least one byte in length.
**
** The sqlite4_snprintf() differs from the standard library snprintf()
** routine in two ways:  (1) sqlite4_snprintf() returns the number of
** bytes actually written, not the number of bytes that would have been
** written if the buffer had been infinitely long.  (2) If the buffer is
** at least one byte long, sqlite4_snprintf() always zero-terminates its
** result.
**
** ^As long as the buffer size is greater than zero, sqlite4_snprintf()
** guarantees that the buffer is always zero-terminated.  ^The second
** parameter "n" is the total size of the buffer, including space for
** the zero terminator.  So the longest string that can be completely
** written will be n-1 characters.
**
** ^The sqlite4_vsnprintf() routine is a varargs version of sqlite4_snprintf().
**
** These routines all implement some additional formatting
................................................................................
** The code above will render a correct SQL statement in the zSQL
** variable even if the zText variable is a NULL pointer.
**
** ^(The "%z" formatting option works like "%s" but with the
** addition that after the string has been read and copied into
** the result, [sqlite4_free()] is called on the input string.)^
*/
char *sqlite4_mprintf(sqlite4_env*, const char*,...);
char *sqlite4_vmprintf(sqlite4_env*, const char*, va_list);
sqlite4_size_t sqlite4_snprintf(char*,sqlite4_size_t,const char*, ...);
sqlite4_size_t sqlite4_vsnprintf(char*,sqlite4_size_t,const char*, va_list);

/*
** CAPIREF: Memory Allocation Subsystem
**
** The SQLite core uses these three routines for all of its own
** internal memory allocation needs.


**
** ^The sqlite4_malloc() routine returns a pointer to a block
** of memory at least N bytes in length, where N is the parameter.
** ^If sqlite4_malloc() is unable to obtain sufficient free
** memory, it returns a NULL pointer.  ^If the parameter N to
** sqlite4_malloc() is zero or negative then sqlite4_malloc() returns
** a NULL pointer.
................................................................................
** is not freed.
**
** ^The memory returned by sqlite4_malloc() and sqlite4_realloc()
** is always aligned to at least an 8 byte boundary, or to a
** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
** option is used.
**













** The pointer arguments to [sqlite4_free()] and [sqlite4_realloc()]
** must be either NULL or else pointers obtained from a prior
** invocation of [sqlite4_malloc()] or [sqlite4_realloc()] that have
** not yet been released.
**
** The application must not read or write any part of
** a block of memory after it has been released using
** [sqlite4_free()] or [sqlite4_realloc()].
*/
void *sqlite4_malloc(sqlite4_env*, sqlite4_size_t);
void *sqlite4_realloc(sqlite4_env*, void*, sqlite4_size_t);
void sqlite4_free(sqlite4_env*, void*);

/*
** CAPIREF: Memory Allocator Statistics
**
** SQLite provides these two interfaces for reporting on the status
** of the [sqlite4_malloc()], [sqlite4_free()], and [sqlite4_realloc()]
** routines, which form the built-in memory allocation subsystem.
................................................................................
*/
sqlite4_uint64 sqlite4_memory_used(sqlite4_env*);
sqlite4_uint64 sqlite4_memory_highwater(sqlite4_env*, int resetFlag);

/*
** CAPIREF: Pseudo-Random Number Generator
**






** ^A call to this routine stores N bytes of pseudo-randomness into buffer P.







*/
void sqlite4_randomness(sqlite4_env*, int N, void *P);

/*
** CAPIREF: Compile-Time Authorization Callbacks
**
** ^This routine registers an authorizer callback with a particular
** [database connection], supplied in the first argument.
** ^The authorizer callback is invoked as SQL statements are being compiled
................................................................................
** ^The sqlite4_context_db_handle() interface returns a copy of
** the pointer to the [database connection] (the 1st parameter)
** of the [sqlite4_create_function()]
** and [sqlite4_create_function16()] routines that originally
** registered the application defined function.
*/
sqlite4 *sqlite4_context_db_handle(sqlite4_context*);
sqlite4_env *sqlite4_context_env(sqlite4_context*);

/*
** CAPIREF: Function Auxiliary Data
**
** The following two functions may be used by scalar SQL functions to
** associate metadata with argument values. If the same value is passed to
** multiple invocations of the same SQL function during query execution, under
................................................................................
** the near future and that SQLite should make its own private copy of
** the content before returning.
**
** The typedef is necessary to work around problems in certain
** C++ compilers.  See ticket #2191.
*/
typedef void (*sqlite4_destructor_type)(void*);
void sqlite4_dynamic(void*);
#define SQLITE_STATIC      ((sqlite4_destructor_type)0)
#define SQLITE_TRANSIENT   ((sqlite4_destructor_type)-1)
#define SQLITE_DYNAMIC     (sqlite4_dynamic)


/*
** CAPIREF: Setting The Result Of An SQL Function
**
** These routines are used by the xFunc or xFinal callbacks that
** implement SQL functions and aggregates.  See
** [sqlite4_create_function()] and [sqlite4_create_function16()]

Changes to src/sqliteInt.h.

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
...
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
....
2372
2373
2374
2375
2376
2377
2378

2379
2380
2381
2382
2383
2384
2385
....
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
....
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
....
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
....
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
#ifndef _SQLITEINT_H_
#define _SQLITEINT_H_

#define SQLITE_OMIT_ANALYZE 1
#define SQLITE_OMIT_PROGRESS_CALLBACK 1
#define SQLITE_OMIT_VIRTUALTABLE 1
#define SQLITE_OMIT_XFER_OPT 1
#define SQLITE_OMIT_AUTOMATIC_INDEX 1

/*
** These #defines should enable >2GB file support on POSIX if the
** underlying operating system supports it.  If the OS lacks
** large file support, or if the OS is windows, these should be no-ops.
**
** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
................................................................................

/*
** A convenience macro that returns the number of elements in
** an array.
*/
#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))

/*
** The following value as a destructor means to use sqlite4DbFree().
** The sqlite4DbFree() routine requires two parameters instead of the 
** one parameter that destructors normally want.  So we have to introduce 
** this magic value that the code knows to handle differently.  Any 
** pointer will work here as long as it is distinct from SQLITE_STATIC
** and SQLITE_TRANSIENT.
*/
#define SQLITE_DYNAMIC   ((sqlite4_destructor_type)sqlite4MallocSize)

/*
** Mark instances of static data that needs to be folded into the
** environment structure.
*/
#define SQLITE_WSD 

/*
................................................................................

/*
** An objected used to accumulate the text of a string where we
** do not necessarily know how big the string will be in the end.
*/
struct StrAccum {
  sqlite4 *db;         /* Optional database for lookaside.  Can be NULL */

  char *zBase;         /* A base allocation.  Not from malloc. */
  char *zText;         /* The string collected so far */
  int  nChar;          /* Length of the string so far */
  int  nAlloc;         /* Amount of space allocated in zText */
  int  mxAlloc;        /* Maximum allowed string length */
  u8   mallocFailed;   /* Becomes true if any memory allocation fails */
  u8   useMalloc;      /* 0: none,  1: sqlite4DbMalloc,  2: sqlite4_malloc */
................................................................................
/*
** Internal function prototypes
*/
int sqlite4StrICmp(const char *, const char *);
int sqlite4Strlen30(const char*);
#define sqlite4StrNICmp sqlite4_strnicmp

int sqlite4MallocInit(void);
void sqlite4MallocEnd(void);
void *sqlite4Malloc(int);
void *sqlite4MallocZero(int);
void *sqlite4DbMallocZero(sqlite4*, int);
void *sqlite4DbMallocRaw(sqlite4*, int);
char *sqlite4DbStrDup(sqlite4*,const char*);
char *sqlite4DbStrNDup(sqlite4*,const char*, int);
void *sqlite4Realloc(void*, int);
void *sqlite4DbReallocOrFree(sqlite4 *, void *, int);
void *sqlite4DbRealloc(sqlite4 *, void *, int);
void sqlite4DbFree(sqlite4*, void*);
int sqlite4MallocSize(void*);
int sqlite4DbMallocSize(sqlite4*, void*);
void *sqlite4ScratchMalloc(int);
void sqlite4ScratchFree(void*);
void *sqlite4PageMalloc(int);
void sqlite4PageFree(void*);
void sqlite4MemSetDefault(sqlite4_env*);
void sqlite4BenignMallocHooks(void (*)(void), void (*)(void));

/*
** On systems with ample stack space and that support alloca(), make
** use of alloca() to obtain space for large automatic objects.  By default,
** obtain space from malloc().
**
** The alloca() routine never returns NULL.  This will cause code paths
................................................................................
int sqlite4FindDb(sqlite4*, Token*);
int sqlite4FindDbName(sqlite4 *, const char *);
int sqlite4AnalysisLoad(sqlite4*,int iDB);
void sqlite4DeleteIndexSamples(sqlite4*,Index*);
void sqlite4DefaultRowEst(Index*);
void sqlite4RegisterLikeFunctions(sqlite4*, int);
int sqlite4IsLikeFunction(sqlite4*,Expr*,int*,char*);
void sqlite4SchemaClear(Schema*);
Schema *sqlite4SchemaGet(sqlite4*);
int sqlite4SchemaToIndex(sqlite4 *db, Schema *);
KeyInfo *sqlite4IndexKeyinfo(Parse *, Index *);
int sqlite4CreateFunc(sqlite4 *, const char *, int, int, void *, 
  void (*)(sqlite4_context*,int,sqlite4_value **),
  void (*)(sqlite4_context*,int,sqlite4_value **), void (*)(sqlite4_context*),
  FuncDestructor *pDestructor
................................................................................
int sqlite4OpenAllIndexes(Parse *, Table *, int, int);
void sqlite4CloseAllIndexes(Parse *, Table *, int);
Index *sqlite4FindPrimaryKey(Table *, int *);

/*
** The interface to the LEMON-generated parser
*/
void *sqlite4ParserAlloc(void*(*)(size_t));
void sqlite4ParserFree(void*, void(*)(void*));
void sqlite4Parser(void*, int, Token, Parse*);
#ifdef YYTRACKMAXSTACKDEPTH
  int sqlite4ParserStackPeak(void*);
#endif

void sqlite4AutoLoadExtensions(sqlite4*);
#ifndef SQLITE_OMIT_LOAD_EXTENSION
................................................................................

/*
** The interface to the code in fault.c used for identifying "benign"
** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
** is not defined.
*/
#ifndef SQLITE_OMIT_BUILTIN_TEST
  void sqlite4BeginBenignMalloc(void);
  void sqlite4EndBenignMalloc(void);
#else
  #define sqlite4BeginBenignMalloc()
  #define sqlite4EndBenignMalloc()
#endif

#define IN_INDEX_ROWID           1
#define IN_INDEX_EPH             2
#define IN_INDEX_INDEX           3
int sqlite4FindInIndex(Parse *, Expr *, int*);
Index *sqlite4FindExistingInIndex(Parse *, Expr *, int);







|







 







<
<
<
<
<
<
<
<
<
<







 







>







 







|
|
|
|




|



|

<
<
<
<

|







 







|







 







|
|







 







|
|

|
|







15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
...
556
557
558
559
560
561
562










563
564
565
566
567
568
569
....
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
....
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542




2543
2544
2545
2546
2547
2548
2549
2550
2551
....
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
....
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
....
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
#ifndef _SQLITEINT_H_
#define _SQLITEINT_H_

#define SQLITE_OMIT_ANALYZE 1
#define SQLITE_OMIT_PROGRESS_CALLBACK 1
#define SQLITE_OMIT_VIRTUALTABLE 1
#define SQLITE_OMIT_XFER_OPT 1
/* #define SQLITE_OMIT_AUTOMATIC_INDEX 1 */

/*
** These #defines should enable >2GB file support on POSIX if the
** underlying operating system supports it.  If the OS lacks
** large file support, or if the OS is windows, these should be no-ops.
**
** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
................................................................................

/*
** A convenience macro that returns the number of elements in
** an array.
*/
#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))











/*
** Mark instances of static data that needs to be folded into the
** environment structure.
*/
#define SQLITE_WSD 

/*
................................................................................

/*
** An objected used to accumulate the text of a string where we
** do not necessarily know how big the string will be in the end.
*/
struct StrAccum {
  sqlite4 *db;         /* Optional database for lookaside.  Can be NULL */
  sqlite4_env *pEnv;   /* Malloc context */
  char *zBase;         /* A base allocation.  Not from malloc. */
  char *zText;         /* The string collected so far */
  int  nChar;          /* Length of the string so far */
  int  nAlloc;         /* Amount of space allocated in zText */
  int  mxAlloc;        /* Maximum allowed string length */
  u8   mallocFailed;   /* Becomes true if any memory allocation fails */
  u8   useMalloc;      /* 0: none,  1: sqlite4DbMalloc,  2: sqlite4_malloc */
................................................................................
/*
** Internal function prototypes
*/
int sqlite4StrICmp(const char *, const char *);
int sqlite4Strlen30(const char*);
#define sqlite4StrNICmp sqlite4_strnicmp

int sqlite4MallocInit(sqlite4_env*);
void sqlite4MallocEnd(sqlite4_env*);
void *sqlite4Malloc(sqlite4_env*, int);
void *sqlite4MallocZero(sqlite4_env*, int);
void *sqlite4DbMallocZero(sqlite4*, int);
void *sqlite4DbMallocRaw(sqlite4*, int);
char *sqlite4DbStrDup(sqlite4*,const char*);
char *sqlite4DbStrNDup(sqlite4*,const char*, int);
void *sqlite4Realloc(sqlite4_env*, void*, int);
void *sqlite4DbReallocOrFree(sqlite4 *, void *, int);
void *sqlite4DbRealloc(sqlite4 *, void *, int);
void sqlite4DbFree(sqlite4*, void*);
int sqlite4MallocSize(sqlite4_env*, void*);
int sqlite4DbMallocSize(sqlite4*, void*);




void sqlite4MemSetDefault(sqlite4_env*);
void sqlite4BenignMallocHooks(sqlite4_env*,void (*)(void), void (*)(void));

/*
** On systems with ample stack space and that support alloca(), make
** use of alloca() to obtain space for large automatic objects.  By default,
** obtain space from malloc().
**
** The alloca() routine never returns NULL.  This will cause code paths
................................................................................
int sqlite4FindDb(sqlite4*, Token*);
int sqlite4FindDbName(sqlite4 *, const char *);
int sqlite4AnalysisLoad(sqlite4*,int iDB);
void sqlite4DeleteIndexSamples(sqlite4*,Index*);
void sqlite4DefaultRowEst(Index*);
void sqlite4RegisterLikeFunctions(sqlite4*, int);
int sqlite4IsLikeFunction(sqlite4*,Expr*,int*,char*);
void sqlite4SchemaClear(sqlite4_env*,Schema*);
Schema *sqlite4SchemaGet(sqlite4*);
int sqlite4SchemaToIndex(sqlite4 *db, Schema *);
KeyInfo *sqlite4IndexKeyinfo(Parse *, Index *);
int sqlite4CreateFunc(sqlite4 *, const char *, int, int, void *, 
  void (*)(sqlite4_context*,int,sqlite4_value **),
  void (*)(sqlite4_context*,int,sqlite4_value **), void (*)(sqlite4_context*),
  FuncDestructor *pDestructor
................................................................................
int sqlite4OpenAllIndexes(Parse *, Table *, int, int);
void sqlite4CloseAllIndexes(Parse *, Table *, int);
Index *sqlite4FindPrimaryKey(Table *, int *);

/*
** The interface to the LEMON-generated parser
*/
void *sqlite4ParserAlloc(void*(*)(void*,size_t), void*);
void sqlite4ParserFree(void*, void(*)(void*,void*));
void sqlite4Parser(void*, int, Token, Parse*);
#ifdef YYTRACKMAXSTACKDEPTH
  int sqlite4ParserStackPeak(void*);
#endif

void sqlite4AutoLoadExtensions(sqlite4*);
#ifndef SQLITE_OMIT_LOAD_EXTENSION
................................................................................

/*
** The interface to the code in fault.c used for identifying "benign"
** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
** is not defined.
*/
#ifndef SQLITE_OMIT_BUILTIN_TEST
  void sqlite4BeginBenignMalloc(sqlite4_env*);
  void sqlite4EndBenignMalloc(sqlite4_env*);
#else
  #define sqlite4BeginBenignMalloc(X)
  #define sqlite4EndBenignMalloc(X)
#endif

#define IN_INDEX_ROWID           1
#define IN_INDEX_EPH             2
#define IN_INDEX_INDEX           3
int sqlite4FindInIndex(Parse *, Expr *, int*);
Index *sqlite4FindExistingInIndex(Parse *, Expr *, int);

Changes to src/status.c.

72
73
74
75
76
77
78

79

80
81
82
83
84
85
86
...
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
  sqlite4 *db,          /* The database connection whose status is desired */
  int op,               /* Status verb */
  int *pCurrent,        /* Write current value here */
  int *pHighwater,      /* Write high-water mark here */
  int resetFlag         /* Reset high-water mark if true */
){
  int rc = SQLITE_OK;   /* Return code */

  sqlite4_mutex_enter(db->mutex);

  switch( op ){
    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
      *pCurrent = db->lookaside.nOut;
      *pHighwater = db->lookaside.mxOut;
      if( resetFlag ){
        db->lookaside.mxOut = db->lookaside.nOut;
      }
................................................................................

      db->pnBytesFreed = &nByte;
      for(i=0; i<db->nDb; i++){
        Schema *pSchema = db->aDb[i].pSchema;
        if( ALWAYS(pSchema!=0) ){
          HashElem *p;

          nByte += sqlite4DefaultEnv.m.xRoundup(sizeof(HashElem)) * (
              pSchema->tblHash.count 
            + pSchema->trigHash.count
            + pSchema->idxHash.count
            + pSchema->fkeyHash.count
          );
          nByte += sqlite4MallocSize(pSchema->tblHash.ht);
          nByte += sqlite4MallocSize(pSchema->trigHash.ht);
          nByte += sqlite4MallocSize(pSchema->idxHash.ht);
          nByte += sqlite4MallocSize(pSchema->fkeyHash.ht);

          for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
            sqlite4DeleteTrigger(db, (Trigger*)sqliteHashData(p));
          }
          for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
            sqlite4DeleteTable(db, (Table *)sqliteHashData(p));
          }







>

>







 







|





|
|
|
|







72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
...
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
  sqlite4 *db,          /* The database connection whose status is desired */
  int op,               /* Status verb */
  int *pCurrent,        /* Write current value here */
  int *pHighwater,      /* Write high-water mark here */
  int resetFlag         /* Reset high-water mark if true */
){
  int rc = SQLITE_OK;   /* Return code */
  sqlite4_env *pEnv;
  sqlite4_mutex_enter(db->mutex);
  pEnv = db->pEnv;
  switch( op ){
    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
      *pCurrent = db->lookaside.nOut;
      *pHighwater = db->lookaside.mxOut;
      if( resetFlag ){
        db->lookaside.mxOut = db->lookaside.nOut;
      }
................................................................................

      db->pnBytesFreed = &nByte;
      for(i=0; i<db->nDb; i++){
        Schema *pSchema = db->aDb[i].pSchema;
        if( ALWAYS(pSchema!=0) ){
          HashElem *p;

          nByte += sizeof(HashElem) * (
              pSchema->tblHash.count 
            + pSchema->trigHash.count
            + pSchema->idxHash.count
            + pSchema->fkeyHash.count
          );
          nByte += sqlite4MallocSize(pEnv, pSchema->tblHash.ht);
          nByte += sqlite4MallocSize(pEnv, pSchema->trigHash.ht);
          nByte += sqlite4MallocSize(pEnv, pSchema->idxHash.ht);
          nByte += sqlite4MallocSize(pEnv, pSchema->fkeyHash.ht);

          for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
            sqlite4DeleteTrigger(db, (Trigger*)sqliteHashData(p));
          }
          for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
            sqlite4DeleteTable(db, (Table *)sqliteHashData(p));
          }

Changes to src/storage.c.

63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
..
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
...
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
*/
static void kvTrace(KVStore *p, const char *zFormat, ...){
  if( p->fTrace ){
    va_list ap;
    char *z;

    va_start(ap, zFormat);
    z = sqlite4_vmprintf(zFormat, ap);
    va_end(ap);
    printf("%s.%s\n", p->zKVName, z);
    fflush(stdout);
    sqlite4_free(z);
  }
}

/*
** Open a storage engine via URI
*/
int sqlite4KVStoreOpen(
................................................................................
    rc = pEnv->xKVFile(pEnv, &pNew, zUri, flags);
  }else{
    rc = pEnv->xKVTmp(pEnv, &pNew, zUri, flags);
  }

  *ppKVStore = pNew;
  if( pNew ){
    sqlite4_randomness(sizeof(pNew->kvId), &pNew->kvId);
    sqlite4_snprintf(sizeof(pNew->zKVName), pNew->zKVName,
                     "%s", zName);
    pNew->fTrace = (db->flags & SQLITE_KvTrace)!=0;
    kvTrace(pNew, "open(%s,%d,0x%04x)", zUri, pNew->kvId, flags);
  }
  return rc;
}

................................................................................
int sqlite4KVStoreOpenCursor(KVStore *p, KVCursor **ppKVCursor){
  KVCursor *pCur;
  int rc;

  rc = p->pStoreVfunc->xOpenCursor(p, &pCur);
  *ppKVCursor = pCur;
  if( pCur ){
    sqlite4_randomness(sizeof(pCur->curId), &pCur->curId);
    pCur->fTrace = p->fTrace;
    pCur->pStore = p;
  }
  kvTrace(p, "xOpenCursor(%d,%d) -> %s",
          p->kvId, pCur?pCur->curId:-1, kvErrName(rc));
  return rc;
}







|



|







 







|
|







 







|







63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
..
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
...
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
*/
static void kvTrace(KVStore *p, const char *zFormat, ...){
  if( p->fTrace ){
    va_list ap;
    char *z;

    va_start(ap, zFormat);
    z = sqlite4_vmprintf(p->pEnv, zFormat, ap);
    va_end(ap);
    printf("%s.%s\n", p->zKVName, z);
    fflush(stdout);
    sqlite4_free(p->pEnv, z);
  }
}

/*
** Open a storage engine via URI
*/
int sqlite4KVStoreOpen(
................................................................................
    rc = pEnv->xKVFile(pEnv, &pNew, zUri, flags);
  }else{
    rc = pEnv->xKVTmp(pEnv, &pNew, zUri, flags);
  }

  *ppKVStore = pNew;
  if( pNew ){
    sqlite4_randomness(pEnv, sizeof(pNew->kvId), &pNew->kvId);
    sqlite4_snprintf(pNew->zKVName, sizeof(pNew->zKVName),
                     "%s", zName);
    pNew->fTrace = (db->flags & SQLITE_KvTrace)!=0;
    kvTrace(pNew, "open(%s,%d,0x%04x)", zUri, pNew->kvId, flags);
  }
  return rc;
}

................................................................................
int sqlite4KVStoreOpenCursor(KVStore *p, KVCursor **ppKVCursor){
  KVCursor *pCur;
  int rc;

  rc = p->pStoreVfunc->xOpenCursor(p, &pCur);
  *ppKVCursor = pCur;
  if( pCur ){
    sqlite4_randomness(pCur->pEnv, sizeof(pCur->curId), &pCur->curId);
    pCur->fTrace = p->fTrace;
    pCur->pStore = p;
  }
  kvTrace(p, "xOpenCursor(%d,%d) -> %s",
          p->kvId, pCur?pCur->curId:-1, kvErrName(rc));
  return rc;
}

Changes to src/storage.h.

153
154
155
156
157
158
159

160
161
162
163
164
165
166
167
168
169
170
171
172

173
174
175
176
177
178
179
  int (*xRollback)(KVStore*, int);
  int (*xRevert)(KVStore*, int);
  int (*xClose)(KVStore*);
  int (*xControl)(KVStore*, int, void *);
};
struct KVStore {
  const KVStoreMethods *pStoreVfunc;    /* Virtual method table */

  int iTransLevel;                      /* Current transaction level */
  u16 kvId;                             /* Unique ID used for tracing */
  u8 fTrace;                            /* True to enable tracing */
  char zKVName[12];                     /* Used for debugging */
  /* Subclasses will typically append additional fields */
};

/*
** Base class for cursors
*/
struct KVCursor {
  KVStore *pStore;                    /* The owner of this cursor */
  const KVStoreMethods *pStoreVfunc;  /* Methods */

  int iTransLevel;                    /* Current transaction level */
  u16 curId;                          /* Unique ID for tracing */
  u8 fTrace;                          /* True to enable tracing */
  /* Subclasses will typically add additional fields */
};

/*







>













>







153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
  int (*xRollback)(KVStore*, int);
  int (*xRevert)(KVStore*, int);
  int (*xClose)(KVStore*);
  int (*xControl)(KVStore*, int, void *);
};
struct KVStore {
  const KVStoreMethods *pStoreVfunc;    /* Virtual method table */
  sqlite4_env *pEnv;                    /* Runtime environment for this store */
  int iTransLevel;                      /* Current transaction level */
  u16 kvId;                             /* Unique ID used for tracing */
  u8 fTrace;                            /* True to enable tracing */
  char zKVName[12];                     /* Used for debugging */
  /* Subclasses will typically append additional fields */
};

/*
** Base class for cursors
*/
struct KVCursor {
  KVStore *pStore;                    /* The owner of this cursor */
  const KVStoreMethods *pStoreVfunc;  /* Methods */
  sqlite4_env *pEnv;                  /* Runtime environment for this cursor */
  int iTransLevel;                    /* Current transaction level */
  u16 curId;                          /* Unique ID for tracing */
  u8 fTrace;                          /* True to enable tracing */
  /* Subclasses will typically add additional fields */
};

/*

Changes to src/tclsqlite.c.

301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
....
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
....
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
....
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
....
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
....
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
....
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
....
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
....
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
....
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
** SQL has executed.  The TCL script in pDb->zProfile is evaluated.
*/
static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
  SqliteDb *pDb = (SqliteDb*)cd;
  Tcl_DString str;
  char zTm[100];

  sqlite4_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
  Tcl_DStringInit(&str);
  Tcl_DStringAppend(&str, pDb->zProfile, -1);
  Tcl_DStringAppendElement(&str, zSql);
  Tcl_DStringAppendElement(&str, zTm);
  Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
  Tcl_DStringFree(&str);
  Tcl_ResetResult(pDb->interp);
................................................................................
       strcmp(zConflict, "ignore"  ) != 0 &&
       strcmp(zConflict, "replace" ) != 0 ) {
      Tcl_AppendResult(interp, "Error: \"", zConflict, 
            "\", conflict-algorithm must be one of: rollback, "
            "abort, fail, ignore, or replace", 0);
      return TCL_ERROR;
    }
    zSql = sqlite4_mprintf("SELECT * FROM '%q'", zTable);
    if( zSql==0 ){
      Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
      return TCL_ERROR;
    }
    nByte = strlen30(zSql);
    rc = sqlite4_prepare(pDb->db, zSql, -1, &pStmt, 0);
    sqlite4_free(zSql);
    if( rc ){
      Tcl_AppendResult(interp, "Error: ", sqlite4_errmsg(pDb->db), 0);
      nCol = 0;
    }else{
      nCol = sqlite4_column_count(pStmt);
    }
    sqlite4_finalize(pStmt);
................................................................................
      return TCL_ERROR;
    }
    zSql = malloc( nByte + 50 + nCol*2 );
    if( zSql==0 ) {
      Tcl_AppendResult(interp, "Error: can't malloc()", 0);
      return TCL_ERROR;
    }
    sqlite4_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
         zConflict, zTable);
    j = strlen30(zSql);
    for(i=1; i<nCol; i++){
      zSql[j++] = ',';
      zSql[j++] = '?';
    }
    zSql[j++] = ')';
    zSql[j] = 0;
    rc = sqlite4_prepare(pDb->db, zSql, -1, &pStmt, 0);
................................................................................
        }
      }
      if( i+1!=nCol ){
        char *zErr;
        int nErr = strlen30(zFile) + 200;
        zErr = malloc(nErr);
        if( zErr ){
          sqlite4_snprintf(nErr, zErr,
             "Error: %s line %d: expected %d columns of data but found %d",
             zFile, lineno, nCol, i+1);
          Tcl_AppendResult(interp, zErr, 0);
          free(zErr);
        }
        zCommit = "ROLLBACK";
        break;
................................................................................
    if( zCommit[0] == 'C' ){
      /* success, set result as number of lines processed */
      pResult = Tcl_GetObjResult(interp);
      Tcl_SetIntObj(pResult, lineno);
      rc = TCL_OK;
    }else{
      /* failure, append lineno where failed */
      sqlite4_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
      Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
      rc = TCL_ERROR;
    }
    break;
  }

  /*
................................................................................
  }
  memset(p, 0, sizeof(*p));
  zFile = Tcl_GetStringFromObj(objv[2], 0);
  zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
  sqlite4_open(0, zFile, &p->db, 0);
  Tcl_DStringFree(&translatedFilename);
  if( SQLITE_OK!=sqlite4_errcode(p->db) ){
    zErrMsg = sqlite4_mprintf("%s", sqlite4_errmsg(p->db));
    sqlite4_close(p->db);
    p->db = 0;
  }
#ifdef SQLITE_TEST
  else{
    extern int sqlite4test_install_test_functions(sqlite4*);
    sqlite4test_install_test_functions(p->db);
................................................................................
  if( p->db ){
    sqlite4_key(p->db, pKey, nKey);
  }
#endif
  if( p->db==0 ){
    Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
    Tcl_Free((char*)p);
    sqlite4_free(zErrMsg);
    return TCL_ERROR;
  }
  p->maxStmt = NUM_PREPARED_STMTS;
  p->interp = interp;
  zArg = Tcl_GetStringFromObj(objv[1], 0);
  if( DbUseNre() ){
    Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
................................................................................
  Md5_Init(interp);
#endif

#ifdef SQLITE_TEST
  {
    extern int Sqliteconfig_Init(Tcl_Interp*);
    extern int Sqlitetest1_Init(Tcl_Interp*);
    extern int Sqlitetest3_Init(Tcl_Interp*);
    extern int Sqlitetest4_Init(Tcl_Interp*);
    extern int Sqlitetest5_Init(Tcl_Interp*);
    extern int Sqlitetest8_Init(Tcl_Interp*);
    extern int Sqlitetest9_Init(Tcl_Interp*);
    extern int Sqlitetest_func_Init(Tcl_Interp*);
    extern int Sqlitetest_hexio_Init(Tcl_Interp*);
    extern int Sqlitetest_malloc_Init(Tcl_Interp*);
    extern int Sqlitetest_mutex_Init(Tcl_Interp*);
    extern int Sqlitetestschema_Init(Tcl_Interp*);
    extern int Sqlitetestsse_Init(Tcl_Interp*);
................................................................................
    extern int Sqlitetesttclvar_Init(Tcl_Interp*);
    extern int SqlitetestThread_Init(Tcl_Interp*);
    extern int Sqlitetestintarray_Init(Tcl_Interp*);
    extern int Sqlitetestrtree_Init(Tcl_Interp*);
    extern int Sqlitequota_Init(Tcl_Interp*);
    extern int SqliteSuperlock_Init(Tcl_Interp*);
    extern int SqlitetestSyscall_Init(Tcl_Interp*);
    extern int Sqlitetestfuzzer_Init(Tcl_Interp*);
    extern int Sqlitetestwholenumber_Init(Tcl_Interp*);
    extern int Sqliteteststorage_Init(Tcl_Interp*);
    extern int Sqliteteststorage2_Init(Tcl_Interp*);
    extern int SqlitetestLsm_Init(Tcl_Interp*);

#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
    extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
#endif

#ifdef SQLITE_ENABLE_ZIPVFS
    extern int Zipvfs_Init(Tcl_Interp*);
    Zipvfs_Init(interp);
#endif

    Sqliteconfig_Init(interp);
    Sqlitetest1_Init(interp);
    Sqlitetest4_Init(interp);
    Sqlitetest5_Init(interp);
    Sqlitetest8_Init(interp);
    Sqlitetest9_Init(interp);
    Sqlitetest_hexio_Init(interp);
    Sqlitetest_malloc_Init(interp);
    Sqlitetest_mutex_Init(interp);
    Sqlitetestschema_Init(interp);
    Sqlitetesttclvar_Init(interp);
    SqlitetestThread_Init(interp);
    Sqlitetestintarray_Init(interp);
    Sqlitetestrtree_Init(interp);
    Sqlitetestfuzzer_Init(interp);
    Sqlitetestwholenumber_Init(interp);
    Sqliteteststorage_Init(interp);
    Sqliteteststorage2_Init(interp);
    SqlitetestLsm_Init(interp);

#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
    Sqlitetestfts3_Init(interp);
#endif

    Tcl_CreateObjCommand(
        interp, "load_testfixture_extensions", init_all_cmd, 0, 0
    );
    Tcl_CreateObjCommand(
        interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
    );
................................................................................
  sqlite4_config(0, SQLITE_CONFIG_SINGLETHREAD);
#endif

  init_all(interp);
  if( argc>=2 ){
    int i;
    char zArgc[32];
    sqlite4_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
    Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
    Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
    Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
    for(i=3-TCLSH; i<argc; i++){
      Tcl_SetVar(interp, "argv", argv[i],
          TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
    }







|







 







|






|







 







|
|
<







 







|







 







|







 







|







 







|







 







<


<







 







<
<




<
<
<
<
<
<
<
<
<




<




<
<

<
<
<
<




<
<
<







 







|







301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
....
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
....
1602
1603
1604
1605
1606
1607
1608
1609
1610

1611
1612
1613
1614
1615
1616
1617
....
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
....
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
....
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
....
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
....
2959
2960
2961
2962
2963
2964
2965

2966
2967

2968
2969
2970
2971
2972
2973
2974
....
2975
2976
2977
2978
2979
2980
2981


2982
2983
2984
2985









2986
2987
2988
2989

2990
2991
2992
2993


2994




2995
2996
2997
2998



2999
3000
3001
3002
3003
3004
3005
....
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
** SQL has executed.  The TCL script in pDb->zProfile is evaluated.
*/
static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
  SqliteDb *pDb = (SqliteDb*)cd;
  Tcl_DString str;
  char zTm[100];

  sqlite4_snprintf(zTm, sizeof(zTm)-1, "%lld", tm);
  Tcl_DStringInit(&str);
  Tcl_DStringAppend(&str, pDb->zProfile, -1);
  Tcl_DStringAppendElement(&str, zSql);
  Tcl_DStringAppendElement(&str, zTm);
  Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
  Tcl_DStringFree(&str);
  Tcl_ResetResult(pDb->interp);
................................................................................
       strcmp(zConflict, "ignore"  ) != 0 &&
       strcmp(zConflict, "replace" ) != 0 ) {
      Tcl_AppendResult(interp, "Error: \"", zConflict, 
            "\", conflict-algorithm must be one of: rollback, "
            "abort, fail, ignore, or replace", 0);
      return TCL_ERROR;
    }
    zSql = sqlite4_mprintf(0, "SELECT * FROM '%q'", zTable);
    if( zSql==0 ){
      Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
      return TCL_ERROR;
    }
    nByte = strlen30(zSql);
    rc = sqlite4_prepare(pDb->db, zSql, -1, &pStmt, 0);
    sqlite4_free(0, zSql);
    if( rc ){
      Tcl_AppendResult(interp, "Error: ", sqlite4_errmsg(pDb->db), 0);
      nCol = 0;
    }else{
      nCol = sqlite4_column_count(pStmt);
    }
    sqlite4_finalize(pStmt);
................................................................................
      return TCL_ERROR;
    }
    zSql = malloc( nByte + 50 + nCol*2 );
    if( zSql==0 ) {
      Tcl_AppendResult(interp, "Error: can't malloc()", 0);
      return TCL_ERROR;
    }
    j = sqlite4_snprintf(zSql, nByte+50, "INSERT OR %q INTO '%q' VALUES(?",
                         zConflict, zTable);

    for(i=1; i<nCol; i++){
      zSql[j++] = ',';
      zSql[j++] = '?';
    }
    zSql[j++] = ')';
    zSql[j] = 0;
    rc = sqlite4_prepare(pDb->db, zSql, -1, &pStmt, 0);
................................................................................
        }
      }
      if( i+1!=nCol ){
        char *zErr;
        int nErr = strlen30(zFile) + 200;
        zErr = malloc(nErr);
        if( zErr ){
          sqlite4_snprintf(zErr, nErr,
             "Error: %s line %d: expected %d columns of data but found %d",
             zFile, lineno, nCol, i+1);
          Tcl_AppendResult(interp, zErr, 0);
          free(zErr);
        }
        zCommit = "ROLLBACK";
        break;
................................................................................
    if( zCommit[0] == 'C' ){
      /* success, set result as number of lines processed */
      pResult = Tcl_GetObjResult(interp);
      Tcl_SetIntObj(pResult, lineno);
      rc = TCL_OK;
    }else{
      /* failure, append lineno where failed */
      sqlite4_snprintf(zLineNum, sizeof(zLineNum),"%d",lineno);
      Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
      rc = TCL_ERROR;
    }
    break;
  }

  /*
................................................................................
  }
  memset(p, 0, sizeof(*p));
  zFile = Tcl_GetStringFromObj(objv[2], 0);
  zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
  sqlite4_open(0, zFile, &p->db, 0);
  Tcl_DStringFree(&translatedFilename);
  if( SQLITE_OK!=sqlite4_errcode(p->db) ){
    zErrMsg = sqlite4_mprintf(0, "%s", sqlite4_errmsg(p->db));
    sqlite4_close(p->db);
    p->db = 0;
  }
#ifdef SQLITE_TEST
  else{
    extern int sqlite4test_install_test_functions(sqlite4*);
    sqlite4test_install_test_functions(p->db);
................................................................................
  if( p->db ){
    sqlite4_key(p->db, pKey, nKey);
  }
#endif
  if( p->db==0 ){
    Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
    Tcl_Free((char*)p);
    sqlite4_free(0, zErrMsg);
    return TCL_ERROR;
  }
  p->maxStmt = NUM_PREPARED_STMTS;
  p->interp = interp;
  zArg = Tcl_GetStringFromObj(objv[1], 0);
  if( DbUseNre() ){
    Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
................................................................................
  Md5_Init(interp);
#endif

#ifdef SQLITE_TEST
  {
    extern int Sqliteconfig_Init(Tcl_Interp*);
    extern int Sqlitetest1_Init(Tcl_Interp*);

    extern int Sqlitetest4_Init(Tcl_Interp*);
    extern int Sqlitetest5_Init(Tcl_Interp*);

    extern int Sqlitetest9_Init(Tcl_Interp*);
    extern int Sqlitetest_func_Init(Tcl_Interp*);
    extern int Sqlitetest_hexio_Init(Tcl_Interp*);
    extern int Sqlitetest_malloc_Init(Tcl_Interp*);
    extern int Sqlitetest_mutex_Init(Tcl_Interp*);
    extern int Sqlitetestschema_Init(Tcl_Interp*);
    extern int Sqlitetestsse_Init(Tcl_Interp*);
................................................................................
    extern int Sqlitetesttclvar_Init(Tcl_Interp*);
    extern int SqlitetestThread_Init(Tcl_Interp*);
    extern int Sqlitetestintarray_Init(Tcl_Interp*);
    extern int Sqlitetestrtree_Init(Tcl_Interp*);
    extern int Sqlitequota_Init(Tcl_Interp*);
    extern int SqliteSuperlock_Init(Tcl_Interp*);
    extern int SqlitetestSyscall_Init(Tcl_Interp*);


    extern int Sqliteteststorage_Init(Tcl_Interp*);
    extern int Sqliteteststorage2_Init(Tcl_Interp*);
    extern int SqlitetestLsm_Init(Tcl_Interp*);










    Sqliteconfig_Init(interp);
    Sqlitetest1_Init(interp);
    Sqlitetest4_Init(interp);
    Sqlitetest5_Init(interp);

    Sqlitetest9_Init(interp);
    Sqlitetest_hexio_Init(interp);
    Sqlitetest_malloc_Init(interp);
    Sqlitetest_mutex_Init(interp);


    SqlitetestThread_Init(interp);




    Sqliteteststorage_Init(interp);
    Sqliteteststorage2_Init(interp);
    SqlitetestLsm_Init(interp);





    Tcl_CreateObjCommand(
        interp, "load_testfixture_extensions", init_all_cmd, 0, 0
    );
    Tcl_CreateObjCommand(
        interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
    );
................................................................................
  sqlite4_config(0, SQLITE_CONFIG_SINGLETHREAD);
#endif

  init_all(interp);
  if( argc>=2 ){
    int i;
    char zArgc[32];
    sqlite4_snprintf(zArgc, sizeof(zArgc), "%d", argc-(3-TCLSH));
    Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
    Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
    Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
    for(i=3-TCLSH; i<argc; i++){
      Tcl_SetVar(interp, "argv", argv[i],
          TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
    }

Changes to src/tokenize.c.

399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
...
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
...
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
  if( db->activeVdbeCnt==0 ){
    db->u1.isInterrupted = 0;
  }
  pParse->rc = SQLITE_OK;
  pParse->zTail = zSql;
  i = 0;
  assert( pzErrMsg!=0 );
  pEngine = sqlite4ParserAlloc((void*(*)(size_t))sqlite4Malloc);
  if( pEngine==0 ){
    db->mallocFailed = 1;
    return SQLITE_NOMEM;
  }
  assert( pParse->pNewTable==0 );
  assert( pParse->pNewTrigger==0 );
  assert( pParse->nVar==0 );
................................................................................
    sqlite4Parser(pEngine, 0, pParse->sLastToken, pParse);
  }
#if YYTRACKMAXSTACKDEPTH
  sqlite4StatusSet(SQLITE_STATUS_PARSER_STACK,
      sqlite4ParserStackPeak(pEngine)
  );
#endif
  sqlite4ParserFree(pEngine, sqlite4_free);
  db->lookaside.bEnabled = enableLookaside;
  if( db->mallocFailed ){
    pParse->rc = SQLITE_NOMEM;
  }
  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
    sqlite4SetString(&pParse->zErrMsg, db, "%s", sqlite4ErrStr(pParse->rc));
  }
................................................................................
    nErr++;
  }
  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
    sqlite4VdbeDelete(pParse->pVdbe);
    pParse->pVdbe = 0;
  }
#ifndef SQLITE_OMIT_VIRTUALTABLE
  sqlite4_free(pParse->apVtabLock);
#endif

  if( !IN_DECLARE_VTAB ){
    /* If the pParse->declareVtab flag is set, do not delete any table 
    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
    ** will take responsibility for freeing the Table structure.
    */







|







 







|







 







|







399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
...
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
...
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
  if( db->activeVdbeCnt==0 ){
    db->u1.isInterrupted = 0;
  }
  pParse->rc = SQLITE_OK;
  pParse->zTail = zSql;
  i = 0;
  assert( pzErrMsg!=0 );
  pEngine = sqlite4ParserAlloc((void*(*)(void*,size_t))sqlite4_malloc,db->pEnv);
  if( pEngine==0 ){
    db->mallocFailed = 1;
    return SQLITE_NOMEM;
  }
  assert( pParse->pNewTable==0 );
  assert( pParse->pNewTrigger==0 );
  assert( pParse->nVar==0 );
................................................................................
    sqlite4Parser(pEngine, 0, pParse->sLastToken, pParse);
  }
#if YYTRACKMAXSTACKDEPTH
  sqlite4StatusSet(SQLITE_STATUS_PARSER_STACK,
      sqlite4ParserStackPeak(pEngine)
  );
#endif
  sqlite4ParserFree(pEngine, (void(*)(void*,void*))sqlite4_free);
  db->lookaside.bEnabled = enableLookaside;
  if( db->mallocFailed ){
    pParse->rc = SQLITE_NOMEM;
  }
  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
    sqlite4SetString(&pParse->zErrMsg, db, "%s", sqlite4ErrStr(pParse->rc));
  }
................................................................................
    nErr++;
  }
  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
    sqlite4VdbeDelete(pParse->pVdbe);
    pParse->pVdbe = 0;
  }
#ifndef SQLITE_OMIT_VIRTUALTABLE
  sqlite4_free(0, pParse->apVtabLock);
#endif

  if( !IN_DECLARE_VTAB ){
    /* If the pParse->declareVtab flag is set, do not delete any table 
    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
    ** will take responsibility for freeing the Table structure.
    */

Changes to src/vdbe.c.

337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
...
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
...
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
...
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
    }else if( f & MEM_Ephem ){
      c = 'e';
      assert( (f & (MEM_Static|MEM_Dyn))==0 );
    }else{
      c = 's';
    }

    sqlite4_snprintf(100, zCsr, "%c", c);
    zCsr += sqlite4Strlen30(zCsr);
    sqlite4_snprintf(100, zCsr, "%d[", pMem->n);
    zCsr += sqlite4Strlen30(zCsr);
    for(i=0; i<16 && i<pMem->n; i++){
      sqlite4_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
      zCsr += sqlite4Strlen30(zCsr);
    }
    for(i=0; i<16 && i<pMem->n; i++){
      char z = pMem->z[i];
      if( z<32 || z>126 ) *zCsr++ = '.';
      else *zCsr++ = z;
    }

    sqlite4_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
    zCsr += sqlite4Strlen30(zCsr);
    if( f & MEM_Zero ){
      sqlite4_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
      zCsr += sqlite4Strlen30(zCsr);
    }
    *zCsr = '\0';
  }else if( f & MEM_Str ){
    int j, k;
    zBuf[0] = ' ';
    if( f & MEM_Dyn ){
      zBuf[1] = 'z';
................................................................................
    }else if( f & MEM_Ephem ){
      zBuf[1] = 'e';
      assert( (f & (MEM_Static|MEM_Dyn))==0 );
    }else{
      zBuf[1] = 's';
    }
    k = 2;
    sqlite4_snprintf(100, &zBuf[k], "%d", pMem->n);
    k += sqlite4Strlen30(&zBuf[k]);
    zBuf[k++] = '[';
    for(j=0; j<15 && j<pMem->n; j++){
      u8 c = pMem->z[j];
      if( c>=0x20 && c<0x7f ){
        zBuf[k++] = c;
      }else{
        zBuf[k++] = '.';
      }
    }
    zBuf[k++] = ']';
    sqlite4_snprintf(100,&zBuf[k], encnames[pMem->enc]);
    k += sqlite4Strlen30(&zBuf[k]);
    zBuf[k++] = 0;
  }
}
#endif

#ifdef SQLITE_DEBUG
/*
................................................................................
** in memory obtained from sqlite4_malloc) into a Vdbe.zErrMsg (text stored
** in memory obtained from sqlite4DbMalloc).
*/
static void importVtabErrMsg(Vdbe *p, sqlite4_vtab *pVtab){
  sqlite4 *db = p->db;
  sqlite4DbFree(db, p->zErrMsg);
  p->zErrMsg = sqlite4DbStrDup(db, pVtab->zErrMsg);
  sqlite4_free(pVtab->zErrMsg);
  pVtab->zErrMsg = 0;
}


/*
** Execute as much of a VDBE program as we can then return.
**
................................................................................
  p->pResultSet = 0;
  CHECK_FOR_INTERRUPT;
  sqlite4VdbeIOTraceSql(p);
#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  checkProgress = db->xProgress!=0;
#endif
#ifdef SQLITE_DEBUG
  sqlite4BeginBenignMalloc();
  if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
    int i;
    printf("VDBE Program Listing:\n");
    sqlite4VdbePrintSql(p);
    for(i=0; i<p->nOp; i++){
      sqlite4VdbePrintOp(stdout, i, &aOp[i]);
    }
  }
  sqlite4EndBenignMalloc();
#endif
  for(pc=p->pc; rc==SQLITE_OK; pc++){
    assert( pc>=0 && pc<p->nOp );
    if( db->mallocFailed ) goto no_mem;
#ifdef VDBE_PROFILE
    origPc = pc;
    start = sqlite4Hwtime();







|
|
<
<

|
<







|
<

|
<







 







|
<










|
<







 







|







 







|
|







|







337
338
339
340
341
342
343
344
345


346
347

348
349
350
351
352
353
354
355

356
357

358
359
360
361
362
363
364
...
369
370
371
372
373
374
375
376

377
378
379
380
381
382
383
384
385
386
387

388
389
390
391
392
393
394
...
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
...
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
    }else if( f & MEM_Ephem ){
      c = 'e';
      assert( (f & (MEM_Static|MEM_Dyn))==0 );
    }else{
      c = 's';
    }

    zCsr += sqlite4_snprintf(zCsr, 100, "%c", c);
    zCsr += sqlite4_snprintf(zCsr, 100, "%d[", pMem->n);


    for(i=0; i<16 && i<pMem->n; i++){
      zCsr += sqlite4_snprintf(zCsr, 100, "%02X", ((int)pMem->z[i] & 0xFF));

    }
    for(i=0; i<16 && i<pMem->n; i++){
      char z = pMem->z[i];
      if( z<32 || z>126 ) *zCsr++ = '.';
      else *zCsr++ = z;
    }

    zCsr += sqlite4_snprintf(zCsr, 100, "]%s", encnames[pMem->enc]);

    if( f & MEM_Zero ){
      zCsr += sqlite4_snprintf(zCsr, 100, "+%dz",pMem->u.nZero);

    }
    *zCsr = '\0';
  }else if( f & MEM_Str ){
    int j, k;
    zBuf[0] = ' ';
    if( f & MEM_Dyn ){
      zBuf[1] = 'z';
................................................................................
    }else if( f & MEM_Ephem ){
      zBuf[1] = 'e';
      assert( (f & (MEM_Static|MEM_Dyn))==0 );
    }else{
      zBuf[1] = 's';
    }
    k = 2;
    k += sqlite4_snprintf(&zBuf[k], 100, "%d", pMem->n);

    zBuf[k++] = '[';
    for(j=0; j<15 && j<pMem->n; j++){
      u8 c = pMem->z[j];
      if( c>=0x20 && c<0x7f ){
        zBuf[k++] = c;
      }else{
        zBuf[k++] = '.';
      }
    }
    zBuf[k++] = ']';
    k += sqlite4_snprintf(&zBuf[k], 100, encnames[pMem->enc]);

    zBuf[k++] = 0;
  }
}
#endif

#ifdef SQLITE_DEBUG
/*
................................................................................
** in memory obtained from sqlite4_malloc) into a Vdbe.zErrMsg (text stored
** in memory obtained from sqlite4DbMalloc).
*/
static void importVtabErrMsg(Vdbe *p, sqlite4_vtab *pVtab){
  sqlite4 *db = p->db;
  sqlite4DbFree(db, p->zErrMsg);
  p->zErrMsg = sqlite4DbStrDup(db, pVtab->zErrMsg);
  sqlite4_free(db->pEnv, pVtab->zErrMsg);
  pVtab->zErrMsg = 0;
}


/*
** Execute as much of a VDBE program as we can then return.
**
................................................................................
  p->pResultSet = 0;
  CHECK_FOR_INTERRUPT;
  sqlite4VdbeIOTraceSql(p);
#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  checkProgress = db->xProgress!=0;
#endif
#ifdef SQLITE_DEBUG
  sqlite4BeginBenignMalloc(db->pEnv);
  if( p->pc==0  && (db->flags & SQLITE_VdbeListing)!=0 ){
    int i;
    printf("VDBE Program Listing:\n");
    sqlite4VdbePrintSql(p);
    for(i=0; i<p->nOp; i++){
      sqlite4VdbePrintOp(stdout, i, &aOp[i]);
    }
  }
  sqlite4EndBenignMalloc(db->pEnv);
#endif
  for(pc=p->pc; rc==SQLITE_OK; pc++){
    assert( pc>=0 && pc<p->nOp );
    if( db->mallocFailed ) goto no_mem;
#ifdef VDBE_PROFILE
    origPc = pc;
    start = sqlite4Hwtime();

Changes to src/vdbeapi.c.

486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505








506
507
508
509
510
511
512
...
515
516
517
518
519
520
521

522
523
524
525
526
527
528
529
530
531
532
533
*/
void *sqlite4_user_data(sqlite4_context *p){
  assert( p && p->pFunc );
  return p->pFunc->pUserData;
}

/*
** Extract the user data from a sqlite4_context structure and return a
** pointer to it.
**
** IMPLEMENTATION-OF: R-46798-50301 The sqlite4_context_db_handle() interface
** returns a copy of the pointer to the database connection (the 1st
** parameter) of the sqlite4_create_function() and
** sqlite4_create_function16() routines that originally registered the
** application defined function.
*/
sqlite4 *sqlite4_context_db_handle(sqlite4_context *p){
  assert( p && p->pFunc );
  return p->s.db;
}









/*
** The following is the implementation of an SQL function that always
** fails with an error message stating that the function is used in the
** wrong context.  The sqlite4_overload_function() API might construct
** SQL function that use this routine so that the functions will exist
** for name resolution but are actually overloaded by the xFindFunction
................................................................................
void sqlite4InvalidFunction(
  sqlite4_context *context,  /* The function calling context */
  int NotUsed,               /* Number of arguments to the function */
  sqlite4_value **NotUsed2   /* Value of each argument */
){
  const char *zName = context->pFunc->zName;
  char *zErr;

  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  zErr = sqlite4_mprintf(
      "unable to use function %s in the requested context", zName);
  sqlite4_result_error(context, zErr, -1);
  sqlite4_free(zErr);
}

/*
** Allocate or return the aggregate context for a user function.  A new
** context is allocated on the first call.  Subsequent calls return the
** same context that was returned on prior calls.
*/







|
<











>
>
>
>
>
>
>
>







 







>

|


|







486
487
488
489
490
491
492
493

494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
...
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
*/
void *sqlite4_user_data(sqlite4_context *p){
  assert( p && p->pFunc );
  return p->pFunc->pUserData;
}

/*
** Return the sqlite4 object that owns the sqlite4_context.

**
** IMPLEMENTATION-OF: R-46798-50301 The sqlite4_context_db_handle() interface
** returns a copy of the pointer to the database connection (the 1st
** parameter) of the sqlite4_create_function() and
** sqlite4_create_function16() routines that originally registered the
** application defined function.
*/
sqlite4 *sqlite4_context_db_handle(sqlite4_context *p){
  assert( p && p->pFunc );
  return p->s.db;
}

/*
** Return the sqlite4_env object associated with the sqlite4_context.
*/
sqlite4_env *sqlite4_context_env(sqlite4_context *p){
  assert( p && p->pFunc );
  return p->s.db->pEnv;
}

/*
** The following is the implementation of an SQL function that always
** fails with an error message stating that the function is used in the
** wrong context.  The sqlite4_overload_function() API might construct
** SQL function that use this routine so that the functions will exist
** for name resolution but are actually overloaded by the xFindFunction
................................................................................
void sqlite4InvalidFunction(
  sqlite4_context *context,  /* The function calling context */
  int NotUsed,               /* Number of arguments to the function */
  sqlite4_value **NotUsed2   /* Value of each argument */
){
  const char *zName = context->pFunc->zName;
  char *zErr;
  sqlite4_env *pEnv = sqlite4_context_env(context);
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  zErr = sqlite4_mprintf(pEnv,
      "unable to use function %s in the requested context", zName);
  sqlite4_result_error(context, zErr, -1);
  sqlite4_free(pEnv, zErr);
}

/*
** Allocate or return the aggregate context for a user function.  A new
** context is allocated on the first call.  Subsequent calls return the
** same context that was returned on prior calls.
*/

Changes to src/vdbeaux.c.

596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
...
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
...
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
....
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
....
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
....
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
....
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
      case P4_KEYINFO:
      case P4_INTARRAY:
      case P4_KEYINFO_HANDOFF: {
        sqlite4DbFree(db, p4);
        break;
      }
      case P4_MPRINTF: {
        if( db->pnBytesFreed==0 ) sqlite4_free(p4);
        break;
      }
      case P4_VDBEFUNC: {
        VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
        freeEphemeralFunction(db, pVdbeFunc->pFunc);
        if( db->pnBytesFreed==0 ) sqlite4VdbeDeleteAuxData(pVdbeFunc, 0);
        sqlite4DbFree(db, pVdbeFunc);
................................................................................
  char *zP4 = zTemp;
  assert( nTemp>=20 );
  switch( pOp->p4type ){
    case P4_KEYINFO_STATIC:
    case P4_KEYINFO: {
      int i, j;
      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
      sqlite4_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
      i = sqlite4Strlen30(zTemp);
      for(j=0; j<pKeyInfo->nField; j++){
        CollSeq *pColl = pKeyInfo->aColl[j];
        if( pColl ){
          int n = sqlite4Strlen30(pColl->zName);
          if( i+n>nTemp-6 ){
            memcpy(&zTemp[i],",...",4);
            break;
................................................................................
      zTemp[i++] = ')';
      zTemp[i] = 0;
      assert( i<nTemp );
      break;
    }
    case P4_COLLSEQ: {
      CollSeq *pColl = pOp->p4.pColl;
      sqlite4_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
      break;
    }
    case P4_FUNCDEF: {
      FuncDef *pDef = pOp->p4.pFunc;
      sqlite4_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
      break;
    }
    case P4_INT64: {
      sqlite4_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
      break;
    }
    case P4_INT32: {
      sqlite4_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
      break;
    }
    case P4_REAL: {
      sqlite4_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
      break;
    }
    case P4_MEM: {
      Mem *pMem = pOp->p4.pMem;
      if( pMem->flags & MEM_Str ){
        zP4 = pMem->z;
      }else if( pMem->flags & MEM_Int ){
        sqlite4_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
      }else if( pMem->flags & MEM_Real ){
        sqlite4_snprintf(nTemp, zTemp, "%.16g", pMem->r);
      }else if( pMem->flags & MEM_Null ){
        sqlite4_snprintf(nTemp, zTemp, "NULL");
      }else{
        assert( pMem->flags & MEM_Blob );
        zP4 = "(blob)";
      }
      break;
    }
#ifndef SQLITE_OMIT_VIRTUALTABLE
    case P4_VTAB: {
      sqlite4_vtab *pVtab = pOp->p4.pVtab->pVtab;
      sqlite4_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
      break;
    }
#endif
    case P4_INTARRAY: {
      sqlite4_snprintf(nTemp, zTemp, "intarray");
      break;
    }
    case P4_SUBPROGRAM: {
      sqlite4_snprintf(nTemp, zTemp, "program");
      break;
    }
    case P4_ADVANCE: {
      zTemp[0] = 0;
      break;
    }
    default: {
................................................................................
    if( p->explain==1 ){
      if( sqlite4VdbeMemGrow(pMem, 4, 0) ){
        assert( p->db->mallocFailed );
        return SQLITE_ERROR;
      }
      pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
      pMem->n = 2;
      sqlite4_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
      pMem->type = SQLITE_TEXT;
      pMem->enc = SQLITE_UTF8;
      pMem++;
  
#ifdef SQLITE_DEBUG
      if( pOp->zComment ){
        pMem->flags = MEM_Str|MEM_Term;
................................................................................
  VdbeOp *pOp;
  if( sqlite4IoTrace==0 ) return;
  if( nOp<1 ) return;
  pOp = &p->aOp[0];
  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
    int i, j;
    char z[1000];
    sqlite4_snprintf(sizeof(z), z, "%s", pOp->p4.z);
    for(i=0; sqlite4Isspace(z[i]); i++){}
    for(j=0; z[i]; i++){
      if( sqlite4Isspace(z[i]) ){
        if( z[i-1]!=' ' ){
          z[j++] = ' ';
        }
      }else{
................................................................................
*/
int sqlite4VdbeRollback(sqlite4 *db, int iLevel){
  int i;
  assert( sqlite4_mutex_held(db->mutex) );
  assert( db->nSavepoint==countSavepoints(db) );

  /* Invoke the xRollback() hook on all backends. */
  sqlite4BeginBenignMalloc();
  for(i=0; i<db->nDb; i++){
    KVStore *pKV = db->aDb[i].pKV;
    if( pKV && pKV->iTransLevel>=iLevel ){
      sqlite4KVStoreRollback(pKV, iLevel);
    }
  }
  sqlite4EndBenignMalloc();

  /* If the InternChanges flag is set, expire prepared statements and
  ** reload the schema. If this is not a rollback of the top-level 
  ** transaction, do not clear the SQLITE_InternChanges flag.  */ 
  if( db->flags&SQLITE_InternChanges ){
    sqlite4ExpirePreparedStatements(db);
    sqlite4ResetInternalSchema(db, -1);
................................................................................
** copies them to the database handle.
*/
int sqlite4VdbeTransferError(Vdbe *p){
  sqlite4 *db = p->db;
  int rc = p->rc;
  if( p->zErrMsg ){
    u8 mallocFailed = db->mallocFailed;
    sqlite4BeginBenignMalloc();
    sqlite4ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
    sqlite4EndBenignMalloc();
    db->mallocFailed = mallocFailed;
    db->errCode = rc;
  }else{
    sqlite4Error(db, rc, 0);
  }
  return rc;
}







|







 







|
<







 







|




|



|



|



|







|

|

|









|




|



|







 







|







 







|







 







|






|







 







|

|







596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
...
850
851
852
853
854
855
856
857

858
859
860
861
862
863
864
...
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
....
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
....
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
....
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
....
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
      case P4_KEYINFO:
      case P4_INTARRAY:
      case P4_KEYINFO_HANDOFF: {
        sqlite4DbFree(db, p4);
        break;
      }
      case P4_MPRINTF: {
        if( db->pnBytesFreed==0 ) sqlite4_free(db->pEnv, p4);
        break;
      }
      case P4_VDBEFUNC: {
        VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
        freeEphemeralFunction(db, pVdbeFunc->pFunc);
        if( db->pnBytesFreed==0 ) sqlite4VdbeDeleteAuxData(pVdbeFunc, 0);
        sqlite4DbFree(db, pVdbeFunc);
................................................................................
  char *zP4 = zTemp;
  assert( nTemp>=20 );
  switch( pOp->p4type ){
    case P4_KEYINFO_STATIC:
    case P4_KEYINFO: {
      int i, j;
      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
      i = sqlite4_snprintf(zTemp, nTemp, "keyinfo(%d", pKeyInfo->nField);

      for(j=0; j<pKeyInfo->nField; j++){
        CollSeq *pColl = pKeyInfo->aColl[j];
        if( pColl ){
          int n = sqlite4Strlen30(pColl->zName);
          if( i+n>nTemp-6 ){
            memcpy(&zTemp[i],",...",4);
            break;
................................................................................
      zTemp[i++] = ')';
      zTemp[i] = 0;
      assert( i<nTemp );
      break;
    }
    case P4_COLLSEQ: {
      CollSeq *pColl = pOp->p4.pColl;
      sqlite4_snprintf(zTemp, nTemp, "collseq(%.20s)", pColl->zName);
      break;
    }
    case P4_FUNCDEF: {
      FuncDef *pDef = pOp->p4.pFunc;
      sqlite4_snprintf(zTemp, nTemp, "%s(%d)", pDef->zName, pDef->nArg);
      break;
    }
    case P4_INT64: {
      sqlite4_snprintf(zTemp, nTemp, "%lld", *pOp->p4.pI64);
      break;
    }
    case P4_INT32: {
      sqlite4_snprintf(zTemp, nTemp, "%d", pOp->p4.i);
      break;
    }
    case P4_REAL: {
      sqlite4_snprintf(zTemp, nTemp, "%.16g", *pOp->p4.pReal);
      break;
    }
    case P4_MEM: {
      Mem *pMem = pOp->p4.pMem;
      if( pMem->flags & MEM_Str ){
        zP4 = pMem->z;
      }else if( pMem->flags & MEM_Int ){
        sqlite4_snprintf(zTemp, nTemp, "%lld", pMem->u.i);
      }else if( pMem->flags & MEM_Real ){
        sqlite4_snprintf(zTemp, nTemp, "%.16g", pMem->r);
      }else if( pMem->flags & MEM_Null ){
        sqlite4_snprintf(zTemp, nTemp, "NULL");
      }else{
        assert( pMem->flags & MEM_Blob );
        zP4 = "(blob)";
      }
      break;
    }
#ifndef SQLITE_OMIT_VIRTUALTABLE
    case P4_VTAB: {
      sqlite4_vtab *pVtab = pOp->p4.pVtab->pVtab;
      sqlite4_snprintf(zTemp, nTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
      break;
    }
#endif
    case P4_INTARRAY: {
      sqlite4_snprintf(zTemp, nTemp, "intarray");
      break;
    }
    case P4_SUBPROGRAM: {
      sqlite4_snprintf(zTemp, nTemp, "program");
      break;
    }
    case P4_ADVANCE: {
      zTemp[0] = 0;
      break;
    }
    default: {
................................................................................
    if( p->explain==1 ){
      if( sqlite4VdbeMemGrow(pMem, 4, 0) ){
        assert( p->db->mallocFailed );
        return SQLITE_ERROR;
      }
      pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
      pMem->n = 2;
      sqlite4_snprintf(pMem->z, 3, "%.2x", pOp->p5);   /* P5 */
      pMem->type = SQLITE_TEXT;
      pMem->enc = SQLITE_UTF8;
      pMem++;
  
#ifdef SQLITE_DEBUG
      if( pOp->zComment ){
        pMem->flags = MEM_Str|MEM_Term;
................................................................................
  VdbeOp *pOp;
  if( sqlite4IoTrace==0 ) return;
  if( nOp<1 ) return;
  pOp = &p->aOp[0];
  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
    int i, j;
    char z[1000];
    sqlite4_snprintf(z, sizeof(z), "%s", pOp->p4.z);
    for(i=0; sqlite4Isspace(z[i]); i++){}
    for(j=0; z[i]; i++){
      if( sqlite4Isspace(z[i]) ){
        if( z[i-1]!=' ' ){
          z[j++] = ' ';
        }
      }else{
................................................................................
*/
int sqlite4VdbeRollback(sqlite4 *db, int iLevel){
  int i;
  assert( sqlite4_mutex_held(db->mutex) );
  assert( db->nSavepoint==countSavepoints(db) );

  /* Invoke the xRollback() hook on all backends. */
  sqlite4BeginBenignMalloc(db->pEnv);
  for(i=0; i<db->nDb; i++){
    KVStore *pKV = db->aDb[i].pKV;
    if( pKV && pKV->iTransLevel>=iLevel ){
      sqlite4KVStoreRollback(pKV, iLevel);
    }
  }
  sqlite4EndBenignMalloc(db->pEnv);

  /* If the InternChanges flag is set, expire prepared statements and
  ** reload the schema. If this is not a rollback of the top-level 
  ** transaction, do not clear the SQLITE_InternChanges flag.  */ 
  if( db->flags&SQLITE_InternChanges ){
    sqlite4ExpirePreparedStatements(db);
    sqlite4ResetInternalSchema(db, -1);
................................................................................
** copies them to the database handle.
*/
int sqlite4VdbeTransferError(Vdbe *p){
  sqlite4 *db = p->db;
  int rc = p->rc;
  if( p->zErrMsg ){
    u8 mallocFailed = db->mallocFailed;
    sqlite4BeginBenignMalloc(db->pEnv);
    sqlite4ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
    sqlite4EndBenignMalloc(db->pEnv);
    db->mallocFailed = mallocFailed;
    db->errCode = rc;
  }else{
    sqlite4Error(db, rc, 0);
  }
  return rc;
}

Changes to src/vdbemem.c.

186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
  /* For a Real or Integer, use sqlite4_mprintf() to produce the UTF-8
  ** string representation of the value. Then, if the required encoding
  ** is UTF-16le or UTF-16be do a translation.
  ** 
  ** FIX ME: It would be better if sqlite4_snprintf() could do UTF-16.
  */
  if( fg & MEM_Int ){
    sqlite4_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  }else{
    assert( fg & MEM_Real );
    sqlite4_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
  }
  pMem->n = sqlite4Strlen30(pMem->z);
  pMem->enc = SQLITE_UTF8;
  pMem->flags |= MEM_Str|MEM_Term;
  sqlite4VdbeChangeEncoding(pMem, enc);
  return rc;
}







|


|







186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
  /* For a Real or Integer, use sqlite4_mprintf() to produce the UTF-8
  ** string representation of the value. Then, if the required encoding
  ** is UTF-16le or UTF-16be do a translation.
  ** 
  ** FIX ME: It would be better if sqlite4_snprintf() could do UTF-16.
  */
  if( fg & MEM_Int ){
    sqlite4_snprintf(pMem->z, nByte, "%lld", pMem->u.i);
  }else{
    assert( fg & MEM_Real );
    sqlite4_snprintf(pMem->z, nByte, "%!.15g", pMem->r);
  }
  pMem->n = sqlite4Strlen30(pMem->z);
  pMem->enc = SQLITE_UTF8;
  pMem->flags |= MEM_Str|MEM_Term;
  sqlite4VdbeChangeEncoding(pMem, enc);
  return rc;
}

Changes to src/vdbetrace.c.

78
79
80
81
82
83
84

85
86
87
88
89
90
91
...
163
164
165
166
167
168
169



170
171
172
173
174
175
176
177
178
179

180
181
182
183
184
185
186
187
188
...
249
250
251
252
253
254
255

256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
  StrAccum out;            /* Accumulate the output here */
  char zBase[100];         /* Initial working space */

  db = p->db;
  sqlite4StrAccumInit(&out, zBase, sizeof(zBase), 
                      db->aLimit[SQLITE_LIMIT_LENGTH]);
  out.db = db;

  if( db->vdbeExecCnt>1 ){
    while( *zRawSql ){
      const char *zStart = zRawSql;
      while( *(zRawSql++)!='\n' && *zRawSql );
      sqlite4StrAccumAppend(&out, "-- ", 3);
      sqlite4StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
    }
................................................................................
#if defined(SQLITE_ENABLE_TREE_EXPLAIN)

/*
** Allocate a new Explain object
*/
void sqlite4ExplainBegin(Vdbe *pVdbe){
  if( pVdbe ){



    sqlite4BeginBenignMalloc();
    Explain *p = sqlite4_malloc( sizeof(Explain) );
    if( p ){
      memset(p, 0, sizeof(*p));
      p->pVdbe = pVdbe;
      sqlite4_free(pVdbe->pExplain);
      pVdbe->pExplain = p;
      sqlite4StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
                          SQLITE_MAX_LENGTH);
      p->str.useMalloc = 2;

    }else{
      sqlite4EndBenignMalloc();
    }
  }
}

/*
** Return true if the Explain ends with a new-line.
*/
................................................................................
}

/*
** Free the indentation structure
*/
void sqlite4ExplainFinish(Vdbe *pVdbe){
  if( pVdbe && pVdbe->pExplain ){

    sqlite4_free(pVdbe->zExplain);
    sqlite4ExplainNL(pVdbe);
    pVdbe->zExplain = sqlite4StrAccumFinish(&pVdbe->pExplain->str);
    sqlite4_free(pVdbe->pExplain);
    pVdbe->pExplain = 0;
    sqlite4EndBenignMalloc();
  }
}

/*
** Return the explanation of a virtual machine.
*/
const char *sqlite4VdbeExplanation(Vdbe *pVdbe){
  return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
}
#endif /* defined(SQLITE_DEBUG) */







>







 







>
>
>
|
|



|




>

|







 







>
|


|

|










78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
...
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
...
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
  StrAccum out;            /* Accumulate the output here */
  char zBase[100];         /* Initial working space */

  db = p->db;
  sqlite4StrAccumInit(&out, zBase, sizeof(zBase), 
                      db->aLimit[SQLITE_LIMIT_LENGTH]);
  out.db = db;
  out.pEnv = db->pEnv;
  if( db->vdbeExecCnt>1 ){
    while( *zRawSql ){
      const char *zStart = zRawSql;
      while( *(zRawSql++)!='\n' && *zRawSql );
      sqlite4StrAccumAppend(&out, "-- ", 3);
      sqlite4StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
    }
................................................................................
#if defined(SQLITE_ENABLE_TREE_EXPLAIN)

/*
** Allocate a new Explain object
*/
void sqlite4ExplainBegin(Vdbe *pVdbe){
  if( pVdbe ){
    Explain *p;
    sqlite4 *db = pVdbe->db;
    sqlite4_env *pEnv = db->pEnv;
    sqlite4BeginBenignMalloc(pEnv);
    p = sqlite4_malloc(pEnv, sizeof(Explain) );
    if( p ){
      memset(p, 0, sizeof(*p));
      p->pVdbe = pVdbe;
      sqlite4_free(pEnv, pVdbe->pExplain);
      pVdbe->pExplain = p;
      sqlite4StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
                          SQLITE_MAX_LENGTH);
      p->str.useMalloc = 2;
      p->str.pEnv = pEnv;
    }else{
      sqlite4EndBenignMalloc(pEnv);
    }
  }
}

/*
** Return true if the Explain ends with a new-line.
*/
................................................................................
}

/*
** Free the indentation structure
*/
void sqlite4ExplainFinish(Vdbe *pVdbe){
  if( pVdbe && pVdbe->pExplain ){
    sqlite4_env *pEnv = pVdbe->db->pEnv;
    sqlite4_free(pEnv, pVdbe->zExplain);
    sqlite4ExplainNL(pVdbe);
    pVdbe->zExplain = sqlite4StrAccumFinish(&pVdbe->pExplain->str);
    sqlite4_free(pEnv, pVdbe->pExplain);
    pVdbe->pExplain = 0;
    sqlite4EndBenignMalloc(pEnv);
  }
}

/*
** Return the explanation of a virtual machine.
*/
const char *sqlite4VdbeExplanation(Vdbe *pVdbe){
  return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
}
#endif /* defined(SQLITE_DEBUG) */

Deleted src/vtab.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
/*
** 2006 June 10
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to help implement virtual tables.
*/
#ifndef SQLITE_OMIT_VIRTUALTABLE
#include "sqliteInt.h"

/*
** Before a virtual table xCreate() or xConnect() method is invoked, the
** sqlite4.pVtabCtx member variable is set to point to an instance of
** this struct allocated on the stack. It is used by the implementation of 
** the sqlite4_declare_vtab() and sqlite4_vtab_config() APIs, both of which
** are invoked only from within xCreate and xConnect methods.
*/
struct VtabCtx {
  Table *pTab;
  VTable *pVTable;
};

/*
** The actual function that does the work of creating a new module.
** This function implements the sqlite4_create_module() and
** sqlite4_create_module_v2() interfaces.
*/
static int createModule(
  sqlite4 *db,                    /* Database in which module is registered */
  const char *zName,              /* Name assigned to this module */
  const sqlite4_module *pModule,  /* The definition of the module */
  void *pAux,                     /* Context pointer for xCreate/xConnect */
  void (*xDestroy)(void *)        /* Module destructor function */
){
  int rc, nName;
  Module *pMod;

  sqlite4_mutex_enter(db->mutex);
  nName = sqlite4Strlen30(zName);
  pMod = (Module *)sqlite4DbMallocRaw(db, sizeof(Module) + nName + 1);
  if( pMod ){
    Module *pDel;
    char *zCopy = (char *)(&pMod[1]);
    memcpy(zCopy, zName, nName+1);
    pMod->zName = zCopy;
    pMod->pModule = pModule;
    pMod->pAux = pAux;
    pMod->xDestroy = xDestroy;
    pDel = (Module *)sqlite4HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
    if( pDel && pDel->xDestroy ){
      sqlite4ResetInternalSchema(db, -1);
      pDel->xDestroy(pDel->pAux);
    }
    sqlite4DbFree(db, pDel);
    if( pDel==pMod ){
      db->mallocFailed = 1;
    }
  }else if( xDestroy ){
    xDestroy(pAux);
  }
  rc = sqlite4ApiExit(db, SQLITE_OK);
  sqlite4_mutex_leave(db->mutex);
  return rc;
}


/*
** External API function used to create a new virtual-table module.
*/
int sqlite4_create_module(
  sqlite4 *db,                    /* Database in which module is registered */
  const char *zName,              /* Name assigned to this module */
  const sqlite4_module *pModule,  /* The definition of the module */
  void *pAux                      /* Context pointer for xCreate/xConnect */
){
  return createModule(db, zName, pModule, pAux, 0);
}

/*
** External API function used to create a new virtual-table module.
*/
int sqlite4_create_module_v2(
  sqlite4 *db,                    /* Database in which module is registered */
  const char *zName,              /* Name assigned to this module */
  const sqlite4_module *pModule,  /* The definition of the module */
  void *pAux,                     /* Context pointer for xCreate/xConnect */
  void (*xDestroy)(void *)        /* Module destructor function */
){
  return createModule(db, zName, pModule, pAux, xDestroy);
}

/*
** Lock the virtual table so that it cannot be disconnected.
** Locks nest.  Every lock should have a corresponding unlock.
** If an unlock is omitted, resources leaks will occur.  
**
** If a disconnect is attempted while a virtual table is locked,
** the disconnect is deferred until all locks have been removed.
*/
void sqlite4VtabLock(VTable *pVTab){
  pVTab->nRef++;
}


/*
** pTab is a pointer to a Table structure representing a virtual-table.
** Return a pointer to the VTable object used by connection db to access 
** this virtual-table, if one has been created, or NULL otherwise.
*/
VTable *sqlite4GetVTable(sqlite4 *db, Table *pTab){
  VTable *pVtab;
  assert( IsVirtual(pTab) );
  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  return pVtab;
}

/*
** Decrement the ref-count on a virtual table object. When the ref-count
** reaches zero, call the xDisconnect() method to delete the object.
*/
void sqlite4VtabUnlock(VTable *pVTab){
  sqlite4 *db = pVTab->db;

  assert( db );
  assert( pVTab->nRef>0 );
  assert( sqlite4SafetyCheckOk(db) );

  pVTab->nRef--;
  if( pVTab->nRef==0 ){
    sqlite4_vtab *p = pVTab->pVtab;
    if( p ){
      p->pModule->xDisconnect(p);
    }
    sqlite4DbFree(db, pVTab);
  }
}

/*
** Table p is a virtual table. This function moves all elements in the
** p->pVTable list to the sqlite4.pDisconnect lists of their associated
** database connections to be disconnected at the next opportunity. 
** Except, if argument db is not NULL, then the entry associated with
** connection db is left in the p->pVTable list.
*/
static VTable *vtabDisconnectAll(sqlite4 *db, Table *p){
  VTable *pRet = 0;
  VTable *pVTable = p->pVTable;
  p->pVTable = 0;

  while( pVTable ){
    sqlite4 *db2 = pVTable->db;
    VTable *pNext = pVTable->pNext;
    assert( db2 );
    if( db2==db ){
      pRet = pVTable;
      p->pVTable = pRet;
      pRet->pNext = 0;
    }else{
      pVTable->pNext = db2->pDisconnect;
      db2->pDisconnect = pVTable;
    }
    pVTable = pNext;
  }

  assert( !db || pRet );
  return pRet;
}


/*
** Disconnect all the virtual table objects in the sqlite4.pDisconnect list.
**
** This function may only be called when the mutexes associated with all
** shared b-tree databases opened using connection db are held by the 
** caller. This is done to protect the sqlite4.pDisconnect list. The
** sqlite4.pDisconnect list is accessed only as follows:
**
**   1) By this function. In this case, all BtShared mutexes and the mutex
**      associated with the database handle itself must be held.
**
**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
**      the sqlite4.pDisconnect list. In this case either the BtShared mutex
**      associated with the database the virtual table is stored in is held
**      or, if the virtual table is stored in a non-sharable database, then
**      the database handle mutex is held.
**
** As a result, a sqlite4.pDisconnect cannot be accessed simultaneously 
** by multiple threads. It is thread-safe.
*/
void sqlite4VtabUnlockList(sqlite4 *db){
  VTable *p = db->pDisconnect;
  db->pDisconnect = 0;

  assert( sqlite4_mutex_held(db->mutex) );

  if( p ){
    sqlite4ExpirePreparedStatements(db);
    do {
      VTable *pNext = p->pNext;
      sqlite4VtabUnlock(p);
      p = pNext;
    }while( p );
  }
}

/*
** Clear any and all virtual-table information from the Table record.
** This routine is called, for example, just before deleting the Table
** record.
**
** Since it is a virtual-table, the Table structure contains a pointer
** to the head of a linked list of VTable structures. Each VTable 
** structure is associated with a single sqlite4* user of the schema.
** The reference count of the VTable structure associated with database 
** connection db is decremented immediately (which may lead to the 
** structure being xDisconnected and free). Any other VTable structures
** in the list are moved to the sqlite4.pDisconnect list of the associated 
** database connection.
*/
void sqlite4VtabClear(sqlite4 *db, Table *p){
  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  if( p->azModuleArg ){
    int i;
    for(i=0; i<p->nModuleArg; i++){
      sqlite4DbFree(db, p->azModuleArg[i]);
    }
    sqlite4DbFree(db, p->azModuleArg);
  }
}

/*
** Add a new module argument to pTable->azModuleArg[].
** The string is not copied - the pointer is stored.  The
** string will be freed automatically when the table is
** deleted.
*/
static void addModuleArgument(sqlite4 *db, Table *pTable, char *zArg){
  int i = pTable->nModuleArg++;
  int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
  char **azModuleArg;
  azModuleArg = sqlite4DbRealloc(db, pTable->azModuleArg, nBytes);
  if( azModuleArg==0 ){
    int j;
    for(j=0; j<i; j++){
      sqlite4DbFree(db, pTable->azModuleArg[j]);
    }
    sqlite4DbFree(db, zArg);
    sqlite4DbFree(db, pTable->azModuleArg);
    pTable->nModuleArg = 0;
  }else{
    azModuleArg[i] = zArg;
    azModuleArg[i+1] = 0;
  }
  pTable->azModuleArg = azModuleArg;
}

/*
** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
** statement.  The module name has been parsed, but the optional list
** of parameters that follow the module name are still pending.
*/
void sqlite4VtabBeginParse(
  Parse *pParse,        /* Parsing context */
  Token *pName1,        /* Name of new table, or database name */
  Token *pName2,        /* Name of new table or NULL */
  Token *pModuleName    /* Name of the module for the virtual table */
){
  int iDb;              /* The database the table is being created in */
  Table *pTable;        /* The new virtual table */
  sqlite4 *db;          /* Database connection */

  sqlite4StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
  pTable = pParse->pNewTable;
  if( pTable==0 ) return;
  assert( 0==pTable->pIndex );

  db = pParse->db;
  iDb = sqlite4SchemaToIndex(db, pTable->pSchema);
  assert( iDb>=0 );

  pTable->tabFlags |= TF_Virtual;
  pTable->nModuleArg = 0;
  addModuleArgument(db, pTable, sqlite4NameFromToken(db, pModuleName));
  addModuleArgument(db, pTable, sqlite4DbStrDup(db, db->aDb[iDb].zName));
  addModuleArgument(db, pTable, sqlite4DbStrDup(db, pTable->zName));
  pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);

#ifndef SQLITE_OMIT_AUTHORIZATION
  /* Creating a virtual table invokes the authorization callback twice.
  ** The first invocation, to obtain permission to INSERT a row into the
  ** sqlite_master table, has already been made by sqlite4StartTable().
  ** The second call, to obtain permission to create the table, is made now.
  */
  if( pTable->azModuleArg ){
    sqlite4AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  }
#endif
}

/*
** This routine takes the module argument that has been accumulating
** in pParse->zArg[] and appends it to the list of arguments on the
** virtual table currently under construction in pParse->pTable.
*/
static void addArgumentToVtab(Parse *pParse){
  if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
    const char *z = (const char*)pParse->sArg.z;
    int n = pParse->sArg.n;
    sqlite4 *db = pParse->db;
    addModuleArgument(db, pParse->pNewTable, sqlite4DbStrNDup(db, z, n));
  }
}

/*
** The parser calls this routine after the CREATE VIRTUAL TABLE statement
** has been completely parsed.
*/
void sqlite4VtabFinishParse(Parse *pParse, Token *pEnd){
  Table *pTab = pParse->pNewTable;  /* The table being constructed */
  sqlite4 *db = pParse->db;         /* The database connection */

  if( pTab==0 ) return;
  addArgumentToVtab(pParse);
  pParse->sArg.z = 0;
  if( pTab->nModuleArg<1 ) return;
  
  /* If the CREATE VIRTUAL TABLE statement is being entered for the
  ** first time (in other words if the virtual table is actually being
  ** created now instead of just being read out of sqlite_master) then
  ** do additional initialization work and store the statement text
  ** in the sqlite_master table.
  */
  if( !db->init.busy ){
    char *zStmt;
    char *zWhere;
    int iDb;
    Vdbe *v;

    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
    if( pEnd ){
      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
    }
    zStmt = sqlite4MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);

    /* A slot for the record has already been allocated in the 
    ** SQLITE_MASTER table.  We just need to update that slot with all
    ** the information we've collected.  
    **
    ** The VM register number pParse->regRowid holds the rowid of an
    ** entry in the sqlite_master table tht was created for this vtab
    ** by sqlite4StartTable().
    */
    iDb = sqlite4SchemaToIndex(db, pTab->pSchema);
    sqlite4NestedParse(pParse,
      "UPDATE %Q.%s "
         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
       "WHERE rowid=#%d",
      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
      pTab->zName,
      pTab->zName,
      zStmt,
      pParse->regRowid
    );
    sqlite4DbFree(db, zStmt);
    v = sqlite4GetVdbe(pParse);
    sqlite4ChangeCookie(pParse, iDb);

    sqlite4VdbeAddOp2(v, OP_Expire, 0, 0);
    zWhere = sqlite4MPrintf(db, "name='%q' AND type='table'", pTab->zName);
    sqlite4VdbeAddParseSchemaOp(v, iDb, zWhere);
    sqlite4VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
                         pTab->zName, sqlite4Strlen30(pTab->zName) + 1);
  }

  /* If we are rereading the sqlite_master table create the in-memory
  ** record of the table. The xConnect() method is not called until
  ** the first time the virtual table is used in an SQL statement. This
  ** allows a schema that contains virtual tables to be loaded before
  ** the required virtual table implementations are registered.  */
  else {
    Table *pOld;
    Schema *pSchema = pTab->pSchema;
    const char *zName = pTab->zName;
    int nName = sqlite4Strlen30(zName);
    pOld = sqlite4HashInsert(&pSchema->tblHash, zName, nName, pTab);
    if( pOld ){
      db->mallocFailed = 1;
      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
      return;
    }
    pParse->pNewTable = 0;
  }
}

/*
** The parser calls this routine when it sees the first token
** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
*/
void sqlite4VtabArgInit(Parse *pParse){
  addArgumentToVtab(pParse);
  pParse->sArg.z = 0;
  pParse->sArg.n = 0;
}

/*
** The parser calls this routine for each token after the first token
** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
*/
void sqlite4VtabArgExtend(Parse *pParse, Token *p){
  Token *pArg = &pParse->sArg;
  if( pArg->z==0 ){
    pArg->z = p->z;
    pArg->n = p->n;
  }else{
    assert(pArg->z < p->z);
    pArg->n = (int)(&p->z[p->n] - pArg->z);
  }
}

/*
** Invoke a virtual table constructor (either xCreate or xConnect). The
** pointer to the function to invoke is passed as the fourth parameter
** to this procedure.
*/
static int vtabCallConstructor(
  sqlite4 *db, 
  Table *pTab,
  Module *pMod,
  int (*xConstruct)(sqlite4*,void*,int,const char*const*,sqlite4_vtab**,char**),
  char **pzErr
){
  VtabCtx sCtx;
  VTable *pVTable;
  int rc;
  const char *const*azArg = (const char *const*)pTab->azModuleArg;
  int nArg = pTab->nModuleArg;
  char *zErr = 0;
  char *zModuleName = sqlite4MPrintf(db, "%s", pTab->zName);

  if( !zModuleName ){
    return SQLITE_NOMEM;
  }

  pVTable = sqlite4DbMallocZero(db, sizeof(VTable));
  if( !pVTable ){
    sqlite4DbFree(db, zModuleName);
    return SQLITE_NOMEM;
  }
  pVTable->db = db;
  pVTable->pMod = pMod;

  /* Invoke the virtual table constructor */
  assert( &db->pVtabCtx );
  assert( xConstruct );
  sCtx.pTab = pTab;
  sCtx.pVTable = pVTable;
  db->pVtabCtx = &sCtx;
  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  db->pVtabCtx = 0;
  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;

  if( SQLITE_OK!=rc ){
    if( zErr==0 ){
      *pzErr = sqlite4MPrintf(db, "vtable constructor failed: %s", zModuleName);
    }else {
      *pzErr = sqlite4MPrintf(db, "%s", zErr);
      sqlite4_free(zErr);
    }
    sqlite4DbFree(db, pVTable);
  }else if( ALWAYS(pVTable->pVtab) ){
    /* Justification of ALWAYS():  A correct vtab constructor must allocate
    ** the sqlite4_vtab object if successful.  */
    pVTable->pVtab->pModule = pMod->pModule;
    pVTable->nRef = 1;
    if( sCtx.pTab ){
      const char *zFormat = "vtable constructor did not declare schema: %s";
      *pzErr = sqlite4MPrintf(db, zFormat, pTab->zName);
      sqlite4VtabUnlock(pVTable);
      rc = SQLITE_ERROR;
    }else{
      int iCol;
      /* If everything went according to plan, link the new VTable structure
      ** into the linked list headed by pTab->pVTable. Then loop through the 
      ** columns of the table to see if any of them contain the token "hidden".
      ** If so, set the Column.isHidden flag and remove the token from
      ** the type string.  */
      pVTable->pNext = pTab->pVTable;
      pTab->pVTable = pVTable;

      for(iCol=0; iCol<pTab->nCol; iCol++){
        char *zType = pTab->aCol[iCol].zType;
        int nType;
        int i = 0;
        if( !zType ) continue;
        nType = sqlite4Strlen30(zType);
        if( sqlite4StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
          for(i=0; i<nType; i++){
            if( (0==sqlite4StrNICmp(" hidden", &zType[i], 7))
             && (zType[i+7]=='\0' || zType[i+7]==' ')
            ){
              i++;
              break;
            }
          }
        }
        if( i<nType ){
          int j;
          int nDel = 6 + (zType[i+6] ? 1 : 0);
          for(j=i; (j+nDel)<=nType; j++){
            zType[j] = zType[j+nDel];
          }
          if( zType[i]=='\0' && i>0 ){
            assert(zType[i-1]==' ');
            zType[i-1] = '\0';
          }
          pTab->aCol[iCol].isHidden = 1;
        }
      }
    }
  }

  sqlite4DbFree(db, zModuleName);
  return rc;
}

/*
** This function is invoked by the parser to call the xConnect() method
** of the virtual table pTab. If an error occurs, an error code is returned 
** and an error left in pParse.
**
** This call is a no-op if table pTab is not a virtual table.
*/
int sqlite4VtabCallConnect(Parse *pParse, Table *pTab){
  sqlite4 *db = pParse->db;
  const char *zMod;
  Module *pMod;
  int rc;

  assert( pTab );
  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite4GetVTable(db, pTab) ){
    return SQLITE_OK;
  }

  /* Locate the required virtual table module */
  zMod = pTab->azModuleArg[0];
  pMod = (Module*)sqlite4HashFind(&db->aModule, zMod, sqlite4Strlen30(zMod));

  if( !pMod ){
    const char *zModule = pTab->azModuleArg[0];
    sqlite4ErrorMsg(pParse, "no such module: %s", zModule);
    rc = SQLITE_ERROR;
  }else{
    char *zErr = 0;
    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
    if( rc!=SQLITE_OK ){
      sqlite4ErrorMsg(pParse, "%s", zErr);
    }
    sqlite4DbFree(db, zErr);
  }

  return rc;
}
/*
** Grow the db->aVTrans[] array so that there is room for at least one
** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
*/
static int growVTrans(sqlite4 *db){
  const int ARRAY_INCR = 5;

  /* Grow the sqlite4.aVTrans array if required */
  if( (db->nVTrans%ARRAY_INCR)==0 ){
    VTable **aVTrans;
    int nBytes = sizeof(sqlite4_vtab *) * (db->nVTrans + ARRAY_INCR);
    aVTrans = sqlite4DbRealloc(db, (void *)db->aVTrans, nBytes);
    if( !aVTrans ){
      return SQLITE_NOMEM;
    }
    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite4_vtab *)*ARRAY_INCR);
    db->aVTrans = aVTrans;
  }

  return SQLITE_OK;
}

/*
** Add the virtual table pVTab to the array sqlite4.aVTrans[]. Space should
** have already been reserved using growVTrans().
*/
static void addToVTrans(sqlite4 *db, VTable *pVTab){
  /* Add pVtab to the end of sqlite4.aVTrans */
  db->aVTrans[db->nVTrans++] = pVTab;
  sqlite4VtabLock(pVTab);
}

/*
** This function is invoked by the vdbe to call the xCreate method
** of the virtual table named zTab in database iDb. 
**
** If an error occurs, *pzErr is set to point an an English language
** description of the error and an SQLITE_XXX error code is returned.
** In this case the caller must call sqlite4DbFree(db, ) on *pzErr.
*/
int sqlite4VtabCallCreate(sqlite4 *db, int iDb, const char *zTab, char **pzErr){
  int rc = SQLITE_OK;
  Table *pTab;
  Module *pMod;
  const char *zMod;

  pTab = sqlite4FindTable(db, zTab, db->aDb[iDb].zName);
  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );

  /* Locate the required virtual table module */
  zMod = pTab->azModuleArg[0];
  pMod = (Module*)sqlite4HashFind(&db->aModule, zMod, sqlite4Strlen30(zMod));

  /* If the module has been registered and includes a Create method, 
  ** invoke it now. If the module has not been registered, return an 
  ** error. Otherwise, do nothing.
  */
  if( !pMod ){
    *pzErr = sqlite4MPrintf(db, "no such module: %s", zMod);
    rc = SQLITE_ERROR;
  }else{
    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  }

  /* Justification of ALWAYS():  The xConstructor method is required to
  ** create a valid sqlite4_vtab if it returns SQLITE_OK. */
  if( rc==SQLITE_OK && ALWAYS(sqlite4GetVTable(db, pTab)) ){
    rc = growVTrans(db);
    if( rc==SQLITE_OK ){
      addToVTrans(db, sqlite4GetVTable(db, pTab));
    }
  }

  return rc;
}

/*
** This function is used to set the schema of a virtual table.  It is only
** valid to call this function from within the xCreate() or xConnect() of a
** virtual table module.
*/
int sqlite4_declare_vtab(sqlite4 *db, const char *zCreateTable){
  Parse *pParse;

  int rc = SQLITE_OK;
  Table *pTab;
  char *zErr = 0;

  sqlite4_mutex_enter(db->mutex);
  if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
    sqlite4Error(db, SQLITE_MISUSE, 0);
    sqlite4_mutex_leave(db->mutex);
    return SQLITE_MISUSE_BKPT;
  }
  assert( (pTab->tabFlags & TF_Virtual)!=0 );

  pParse = sqlite4StackAllocZero(db, sizeof(*pParse));
  if( pParse==0 ){
    rc = SQLITE_NOMEM;
  }else{
    pParse->declareVtab = 1;
    pParse->db = db;
    pParse->nQueryLoop = 1;
  
    if( SQLITE_OK==sqlite4RunParser(pParse, zCreateTable, &zErr) 
     && pParse->pNewTable
     && !db->mallocFailed
     && !pParse->pNewTable->pSelect
     && (pParse->pNewTable->tabFlags & TF_Virtual)==0
    ){
      if( !pTab->aCol ){
        pTab->aCol = pParse->pNewTable->aCol;
        pTab->nCol = pParse->pNewTable->nCol;
        pParse->pNewTable->nCol = 0;
        pParse->pNewTable->aCol = 0;
      }
      db->pVtabCtx->pTab = 0;
    }else{
      sqlite4Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
      sqlite4DbFree(db, zErr);
      rc = SQLITE_ERROR;
    }
    pParse->declareVtab = 0;
  
    if( pParse->pVdbe ){
      sqlite4VdbeFinalize(pParse->pVdbe);
    }
    sqlite4DeleteTable(db, pParse->pNewTable);
    sqlite4StackFree(db, pParse);
  }

  assert( (rc&0xff)==rc );
  rc = sqlite4ApiExit(db, rc);
  sqlite4_mutex_leave(db->mutex);
  return rc;
}

/*
** This function is invoked by the vdbe to call the xDestroy method
** of the virtual table named zTab in database iDb. This occurs
** when a DROP TABLE is mentioned.
**
** This call is a no-op if zTab is not a virtual table.
*/
int sqlite4VtabCallDestroy(sqlite4 *db, int iDb, const char *zTab){
  int rc = SQLITE_OK;
  Table *pTab;

  pTab = sqlite4FindTable(db, zTab, db->aDb[iDb].zName);
  if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
    VTable *p = vtabDisconnectAll(db, pTab);

    assert( rc==SQLITE_OK );
    rc = p->pMod->pModule->xDestroy(p->pVtab);

    /* Remove the sqlite4_vtab* from the aVTrans[] array, if applicable */
    if( rc==SQLITE_OK ){
      assert( pTab->pVTable==p && p->pNext==0 );
      p->pVtab = 0;
      pTab->pVTable = 0;
      sqlite4VtabUnlock(p);
    }
  }

  return rc;
}

/*
** This function invokes either the xRollback or xCommit method
** of each of the virtual tables in the sqlite4.aVTrans array. The method
** called is identified by the second argument, "offset", which is
** the offset of the method to call in the sqlite4_module structure.
**
** The array is cleared after invoking the callbacks. 
*/
static void callFinaliser(sqlite4 *db, int offset){
  int i;
  if( db->aVTrans ){
    for(i=0; i<db->nVTrans; i++){
      VTable *pVTab = db->aVTrans[i];
      sqlite4_vtab *p = pVTab->pVtab;
      if( p ){
        int (*x)(sqlite4_vtab *);
        x = *(int (**)(sqlite4_vtab *))((char *)p->pModule + offset);
        if( x ) x(p);
      }
      pVTab->iSavepoint = 0;
      sqlite4VtabUnlock(pVTab);
    }
    sqlite4DbFree(db, db->aVTrans);
    db->nVTrans = 0;
    db->aVTrans = 0;
  }
}

/*
** Invoke the xSync method of all virtual tables in the sqlite4.aVTrans
** array. Return the error code for the first error that occurs, or
** SQLITE_OK if all xSync operations are successful.
**
** Set *pzErrmsg to point to a buffer that should be released using 
** sqlite4DbFree() containing an error message, if one is available.
*/
int sqlite4VtabSync(sqlite4 *db, char **pzErrmsg){
  int i;
  int rc = SQLITE_OK;
  VTable **aVTrans = db->aVTrans;

  db->aVTrans = 0;
  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
    int (*x)(sqlite4_vtab *);
    sqlite4_vtab *pVtab = aVTrans[i]->pVtab;
    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
      rc = x(pVtab);
      sqlite4DbFree(db, *pzErrmsg);
      *pzErrmsg = sqlite4DbStrDup(db, pVtab->zErrMsg);
      sqlite4_free(pVtab->zErrMsg);
    }
  }
  db->aVTrans = aVTrans;
  return rc;
}

/*
** Invoke the xRollback method of all virtual tables in the 
** sqlite4.aVTrans array. Then clear the array itself.
*/
int sqlite4VtabRollback(sqlite4 *db){
  callFinaliser(db, offsetof(sqlite4_module,xRollback));
  return SQLITE_OK;
}

/*
** Invoke the xCommit method of all virtual tables in the 
** sqlite4.aVTrans array. Then clear the array itself.
*/
int sqlite4VtabCommit(sqlite4 *db){
  callFinaliser(db, offsetof(sqlite4_module,xCommit));
  return SQLITE_OK;
}

/*
** If the virtual table pVtab supports the transaction interface
** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
** not currently open, invoke the xBegin method now.
**
** If the xBegin call is successful, place the sqlite4_vtab pointer
** in the sqlite4.aVTrans array.
*/
int sqlite4VtabBegin(sqlite4 *db, VTable *pVTab){
  int rc = SQLITE_OK;
  const sqlite4_module *pModule;

  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  ** than zero, then this function is being called from within a
  ** virtual module xSync() callback. It is illegal to write to 
  ** virtual module tables in this case, so return SQLITE_LOCKED.
  */
  if( sqlite4VtabInSync(db) ){
    return SQLITE_LOCKED;
  }
  if( !pVTab ){
    return SQLITE_OK;
  } 
  pModule = pVTab->pVtab->pModule;

  if( pModule->xBegin ){
    int i;

    /* If pVtab is already in the aVTrans array, return early */
    for(i=0; i<db->nVTrans; i++){
      if( db->aVTrans[i]==pVTab ){
        return SQLITE_OK;
      }
    }

    /* Invoke the xBegin method. If successful, add the vtab to the 
    ** sqlite4.aVTrans[] array. */
    rc = growVTrans(db);
    if( rc==SQLITE_OK ){
      rc = pModule->xBegin(pVTab->pVtab);
      if( rc==SQLITE_OK ){
        addToVTrans(db, pVTab);
      }
    }
  }
  return rc;
}

/*
** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
** virtual tables that currently have an open transaction. Pass iSavepoint
** as the second argument to the virtual table method invoked.
**
** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is 
** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
** an open transaction is invoked.
**
** If any virtual table method returns an error code other than SQLITE_OK, 
** processing is abandoned and the error returned to the caller of this
** function immediately. If all calls to virtual table methods are successful,
** SQLITE_OK is returned.
*/
int sqlite4VtabSavepoint(sqlite4 *db, int op, int iSavepoint){
  int rc = SQLITE_OK;

  assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  assert( iSavepoint>=0 );
  if( db->aVTrans ){
    int i;
    for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
      VTable *pVTab = db->aVTrans[i];
      const sqlite4_module *pMod = pVTab->pMod->pModule;
      if( pVTab->pVtab && pMod->iVersion>=2 ){
        int (*xMethod)(sqlite4_vtab *, int);
        switch( op ){
          case SAVEPOINT_BEGIN:
            xMethod = pMod->xSavepoint;
            pVTab->iSavepoint = iSavepoint+1;
            break;
          case SAVEPOINT_ROLLBACK:
            xMethod = pMod->xRollbackTo;
            break;
          default:
            xMethod = pMod->xRelease;
            break;
        }
        if( xMethod && pVTab->iSavepoint>iSavepoint ){
          rc = xMethod(pVTab->pVtab, iSavepoint);
        }
      }
    }
  }
  return rc;
}

/*
** The first parameter (pDef) is a function implementation.  The
** second parameter (pExpr) is the first argument to this function.
** If pExpr is a column in a virtual table, then let the virtual
** table implementation have an opportunity to overload the function.
**
** This routine is used to allow virtual table implementations to
** overload MATCH, LIKE, GLOB, and REGEXP operators.
**
** Return either the pDef argument (indicating no change) or a 
** new FuncDef structure that is marked as ephemeral using the
** SQLITE_FUNC_EPHEM flag.
*/
FuncDef *sqlite4VtabOverloadFunction(
  sqlite4 *db,    /* Database connection for reporting malloc problems */
  FuncDef *pDef,  /* Function to possibly overload */
  int nArg,       /* Number of arguments to the function */
  Expr *pExpr     /* First argument to the function */
){
  Table *pTab;
  sqlite4_vtab *pVtab;
  sqlite4_module *pMod;
  void (*xFunc)(sqlite4_context*,int,sqlite4_value**) = 0;
  void *pArg = 0;
  FuncDef *pNew;
  int rc = 0;
  char *zLowerName;
  unsigned char *z;


  /* Check to see the left operand is a column in a virtual table */
  if( NEVER(pExpr==0) ) return pDef;
  if( pExpr->op!=TK_COLUMN ) return pDef;
  pTab = pExpr->pTab;
  if( NEVER(pTab==0) ) return pDef;
  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  pVtab = sqlite4GetVTable(db, pTab)->pVtab;
  assert( pVtab!=0 );
  assert( pVtab->pModule!=0 );
  pMod = (sqlite4_module *)pVtab->pModule;
  if( pMod->xFindFunction==0 ) return pDef;
 
  /* Call the xFindFunction method on the virtual table implementation
  ** to see if the implementation wants to overload this function 
  */
  zLowerName = sqlite4DbStrDup(db, pDef->zName);
  if( zLowerName ){
    for(z=(unsigned char*)zLowerName; *z; z++){
      *z = sqlite4UpperToLower[*z];
    }
    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
    sqlite4DbFree(db, zLowerName);
  }
  if( rc==0 ){
    return pDef;
  }

  /* Create a new ephemeral function definition for the overloaded
  ** function */
  pNew = sqlite4DbMallocZero(db, sizeof(*pNew)
                             + sqlite4Strlen30(pDef->zName) + 1);
  if( pNew==0 ){
    return pDef;
  }
  *pNew = *pDef;
  pNew->zName = (char *)&pNew[1];
  memcpy(pNew->zName, pDef->zName, sqlite4Strlen30(pDef->zName)+1);
  pNew->xFunc = xFunc;
  pNew->pUserData = pArg;
  pNew->flags |= SQLITE_FUNC_EPHEM;
  return pNew;
}

/*
** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
** array so that an OP_VBegin will get generated for it.  Add pTab to the
** array if it is missing.  If pTab is already in the array, this routine
** is a no-op.
*/
void sqlite4VtabMakeWritable(Parse *pParse, Table *pTab){
  Parse *pToplevel = sqlite4ParseToplevel(pParse);
  int i, n;
  Table **apVtabLock;

  assert( IsVirtual(pTab) );
  for(i=0; i<pToplevel->nVtabLock; i++){
    if( pTab==pToplevel->apVtabLock[i] ) return;
  }
  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  apVtabLock = sqlite4_realloc(pToplevel->apVtabLock, n);
  if( apVtabLock ){
    pToplevel->apVtabLock = apVtabLock;
    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  }else{
    pToplevel->db->mallocFailed = 1;
  }
}

/*
** Return the ON CONFLICT resolution mode in effect for the virtual
** table update operation currently in progress.
**
** The results of this routine are undefined unless it is called from
** within an xUpdate method.
*/
int sqlite4_vtab_on_conflict(sqlite4 *db){
  static const unsigned char aMap[] = { 
    SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE 
  };
  assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  assert( OE_Ignore==4 && OE_Replace==5 );
  assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  return (int)aMap[db->vtabOnConflict-1];
}

/*
** Call from within the xCreate() or xConnect() methods to provide 
** the SQLite core with additional information about the behavior
** of the virtual table being implemented.
*/
int sqlite4_vtab_config(sqlite4 *db, int op, ...){
  va_list ap;
  int rc = SQLITE_OK;

  sqlite4_mutex_enter(db->mutex);

  va_start(ap, op);
  switch( op ){
    case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
      VtabCtx *p = db->pVtabCtx;
      if( !p ){
        rc = SQLITE_MISUSE_BKPT;
      }else{
        assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
        p->pVTable->bConstraint = (u8)va_arg(ap, int);
      }
      break;
    }
    default:
      rc = SQLITE_MISUSE_BKPT;
      break;
  }
  va_end(ap);

  if( rc!=SQLITE_OK ) sqlite4Error(db, rc, 0);
  sqlite4_mutex_leave(db->mutex);
  return rc;
}

#endif /* SQLITE_OMIT_VIRTUALTABLE */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Changes to src/where.c.

3723
3724
3725
3726
3727
3728
3729

3730
3731
3732
3733
3734
3735
3736
....
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447

  pPk = sqlite4FindPrimaryKey(pTab, 0);
  if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
    return 0;
  }
  sqlite4StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
  txt.db = db;


  sqlite4StrAccumAppend(&txt, " (", 2);
  for(i=0; i<nEq; i++){
    const char *zCol = tblColumnName(pTab, idxColumnNumber(pIdx, pPk, i));
    explainAppendTerm(&txt, i, zCol, "=");
  }
  if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
................................................................................
  if( ALWAYS(pWInfo) ){
    int i;
    for(i=0; i<pWInfo->nLevel; i++){
      sqlite4_index_info *pInfo = pWInfo->a[i].pIdxInfo;
      if( pInfo ){
        /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
        if( pInfo->needToFreeIdxStr ){
          sqlite4_free(pInfo->idxStr);
        }
        sqlite4DbFree(db, pInfo);
      }
      if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
        Index *pIdx = pWInfo->a[i].plan.u.pIdx;
        if( pIdx ){
          assert( pIdx->eIndexType==SQLITE_INDEX_TEMP );







>







 







|







3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
....
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448

  pPk = sqlite4FindPrimaryKey(pTab, 0);
  if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
    return 0;
  }
  sqlite4StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
  txt.db = db;
  txt.pEnv = db->pEnv;

  sqlite4StrAccumAppend(&txt, " (", 2);
  for(i=0; i<nEq; i++){
    const char *zCol = tblColumnName(pTab, idxColumnNumber(pIdx, pPk, i));
    explainAppendTerm(&txt, i, zCol, "=");
  }
  if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
................................................................................
  if( ALWAYS(pWInfo) ){
    int i;
    for(i=0; i<pWInfo->nLevel; i++){
      sqlite4_index_info *pInfo = pWInfo->a[i].pIdxInfo;
      if( pInfo ){
        /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
        if( pInfo->needToFreeIdxStr ){
          sqlite4_free(db->pEnv, pInfo->idxStr);
        }
        sqlite4DbFree(db, pInfo);
      }
      if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
        Index *pIdx = pWInfo->a[i].plan.u.pIdx;
        if( pIdx ){
          assert( pIdx->eIndexType==SQLITE_INDEX_TEMP );

Changes to test/permutations.test.

198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
  update.test
  view.test

  where.test  where5.test where6.test where7.test where8.test whereA.test 
  whereB.test whereC.test

  tkt-02a8e81d44.test tkt-26ff0c2d1e.test tkt-2d1a5c67d.test
  tkt-2ea2425d34.test tkt-31338dca7e.test tkt-313723c356.test
  tkt-38cb5df375.test tkt-3998683a16.test tkt-3a77c9714e.test
  tkt-3fe897352e.test tkt-4a03edc4c8.test tkt-54844eea3f.test
  tkt-5e10420e8d.test tkt-752e1646fc.test tkt-80ba201079.test
  tkt-80e031a00f.test tkt-91e2e8ba6f.test tkt-9d68c883.test
  tkt-b1d3a2e531.test tkt-b351d95f9.test  tkt-b72787b1.test
  tkt-bd484a090c.test tkt-cbd054fa6b.test tkt-d11f09d36e.test
  tkt-d635236375.test tkt-f973c7ac31.test tkt-fa7bf5ec.test
  tkt1443.test tkt1444.test tkt1449.test tkt1473.test tkt1501.test
  tkt1512.test tkt1514.test tkt1537.test tkt1667.test tkt1873.test
  tkt2141.test tkt2192.test tkt2213.test tkt2285.test tkt2339.test
  tkt2391.test tkt2450.test tkt2640.test tkt2767.test tkt2817.test
  tkt2822.test tkt2832.test tkt2927.test tkt2942.test tkt3121.test
  tkt3201.test tkt3292.test tkt3298.test tkt3334.test tkt3346.test
  tkt3419.test tkt3424.test tkt3442.test tkt3461.test tkt3493.test
  tkt3508.test tkt3522.test tkt3527.test tkt3541.test tkt3554.test
  tkt3581.test tkt35xx.test tkt3630.test tkt3718.test tkt3761.test







|








|







198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
  update.test
  view.test

  where.test  where5.test where6.test where7.test where8.test whereA.test 
  whereB.test whereC.test

  tkt-02a8e81d44.test tkt-26ff0c2d1e.test tkt-2d1a5c67d.test
  tkt-2ea2425d34.test tkt-31338dca7e.test
  tkt-38cb5df375.test tkt-3998683a16.test tkt-3a77c9714e.test
  tkt-3fe897352e.test tkt-4a03edc4c8.test tkt-54844eea3f.test
  tkt-5e10420e8d.test tkt-752e1646fc.test tkt-80ba201079.test
  tkt-80e031a00f.test tkt-91e2e8ba6f.test tkt-9d68c883.test
  tkt-b1d3a2e531.test tkt-b351d95f9.test  tkt-b72787b1.test
  tkt-bd484a090c.test tkt-cbd054fa6b.test tkt-d11f09d36e.test
  tkt-d635236375.test tkt-f973c7ac31.test tkt-fa7bf5ec.test
  tkt1443.test tkt1444.test tkt1449.test tkt1473.test tkt1501.test
  tkt1514.test tkt1537.test tkt1873.test
  tkt2141.test tkt2192.test tkt2213.test tkt2285.test tkt2339.test
  tkt2391.test tkt2450.test tkt2640.test tkt2767.test tkt2817.test
  tkt2822.test tkt2832.test tkt2927.test tkt2942.test tkt3121.test
  tkt3201.test tkt3292.test tkt3298.test tkt3334.test tkt3346.test
  tkt3419.test tkt3424.test tkt3442.test tkt3461.test tkt3493.test
  tkt3508.test tkt3522.test tkt3527.test tkt3541.test tkt3554.test
  tkt3581.test tkt35xx.test tkt3630.test tkt3718.test tkt3761.test

Changes to test/test_config.c.

455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
  Tcl_SetVar2(interp, "sqlite_options", "tclvar", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "tclvar", "1", TCL_GLOBAL_ONLY);
#endif

  Tcl_SetVar2(interp, "sqlite_options", "threadsafe", 
      STRINGVALUE(SQLITE_THREADSAFE), TCL_GLOBAL_ONLY);
  assert( sqlite4_threadsafe()==SQLITE_THREADSAFE );

#ifdef SQLITE_OMIT_TEMPDB
  Tcl_SetVar2(interp, "sqlite_options", "tempdb", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "tempdb", "1", TCL_GLOBAL_ONLY);
#endif








<







455
456
457
458
459
460
461

462
463
464
465
466
467
468
  Tcl_SetVar2(interp, "sqlite_options", "tclvar", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "tclvar", "1", TCL_GLOBAL_ONLY);
#endif

  Tcl_SetVar2(interp, "sqlite_options", "threadsafe", 
      STRINGVALUE(SQLITE_THREADSAFE), TCL_GLOBAL_ONLY);


#ifdef SQLITE_OMIT_TEMPDB
  Tcl_SetVar2(interp, "sqlite_options", "tempdb", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "tempdb", "1", TCL_GLOBAL_ONLY);
#endif

Deleted test/test_echo.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
/*
** 2006 June 10
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing the virtual table interfaces.  This code
** is not included in the SQLite library.  It is used for automated
** testing of the SQLite library.
*/
#include "sqliteInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>

#ifndef SQLITE_OMIT_VIRTUALTABLE

typedef struct echo_vtab echo_vtab;
typedef struct echo_cursor echo_cursor;

/*
** The test module defined in this file uses four global Tcl variables to
** commicate with test-scripts:
**
**     $::echo_module
**     $::echo_module_sync_fail
**     $::echo_module_begin_fail
**     $::echo_module_cost
**
** The variable ::echo_module is a list. Each time one of the following
** methods is called, one or more elements are appended to the list.
** This is used for automated testing of virtual table modules.
**
** The ::echo_module_sync_fail variable is set by test scripts and read
** by code in this file. If it is set to the name of a real table in the
** the database, then all xSync operations on echo virtual tables that
** use the named table as a backing store will fail.
*/

/*
** Errors can be provoked within the following echo virtual table methods:
**
**   xBestIndex   xOpen     xFilter   xNext   
**   xColumn      xRowid    xUpdate   xSync   
**   xBegin       xRename
**
** This is done by setting the global tcl variable:
**
**   echo_module_fail($method,$tbl)
**
** where $method is set to the name of the virtual table method to fail
** (i.e. "xBestIndex") and $tbl is the name of the table being echoed (not
** the name of the virtual table, the name of the underlying real table).
*/

/* 
** An echo virtual-table object.
**
** echo.vtab.aIndex is an array of booleans. The nth entry is true if 
** the nth column of the real table is the left-most column of an index
** (implicit or otherwise). In other words, if SQLite can optimize
** a query like "SELECT * FROM real_table WHERE col = ?".
**
** Member variable aCol[] contains copies of the column names of the real
** table.
*/
struct echo_vtab {
  sqlite4_vtab base;
  Tcl_Interp *interp;     /* Tcl interpreter containing debug variables */
  sqlite4 *db;            /* Database connection */

  int isPattern;
  int inTransaction;      /* True if within a transaction */
  char *zThis;            /* Name of the echo table */
  char *zTableName;       /* Name of the real table */
  char *zLogName;         /* Name of the log table */
  int nCol;               /* Number of columns in the real table */
  int *aIndex;            /* Array of size nCol. True if column has an index */
  char **aCol;            /* Array of size nCol. Column names */
};

/* An echo cursor object */
struct echo_cursor {
  sqlite4_vtab_cursor base;
  sqlite4_stmt *pStmt;
};

static int simulateVtabError(echo_vtab *p, const char *zMethod){
  const char *zErr;
  char zVarname[128];
  zVarname[127] = '\0';
  sqlite4_snprintf(127, zVarname, "echo_module_fail(%s,%s)", zMethod, p->zTableName);
  zErr = Tcl_GetVar(p->interp, zVarname, TCL_GLOBAL_ONLY);
  if( zErr ){
    p->base.zErrMsg = sqlite4_mprintf("echo-vtab-error: %s", zErr);
  }
  return (zErr!=0);
}

/*
** Convert an SQL-style quoted string into a normal string by removing
** the quote characters.  The conversion is done in-place.  If the
** input does not begin with a quote character, then this routine
** is a no-op.
**
** Examples:
**
**     "abc"   becomes   abc
**     'xyz'   becomes   xyz
**     [pqr]   becomes   pqr
**     `mno`   becomes   mno
*/
static void dequoteString(char *z){
  int quote;
  int i, j;
  if( z==0 ) return;
  quote = z[0];
  switch( quote ){
    case '\'':  break;
    case '"':   break;
    case '`':   break;                /* For MySQL compatibility */
    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
    default:    return;
  }
  for(i=1, j=0; z[i]; i++){
    if( z[i]==quote ){
      if( z[i+1]==quote ){
        z[j++] = quote;
        i++;
      }else{
        z[j++] = 0;
        break;
      }
    }else{
      z[j++] = z[i];
    }
  }
}

/*
** Retrieve the column names for the table named zTab via database
** connection db. SQLITE_OK is returned on success, or an sqlite error
** code otherwise.
**
** If successful, the number of columns is written to *pnCol. *paCol is
** set to point at sqlite4_malloc()'d space containing the array of
** nCol column names. The caller is responsible for calling sqlite4_free
** on *paCol.
*/
static int getColumnNames(
  sqlite4 *db, 
  const char *zTab,
  char ***paCol, 
  int *pnCol
){
  char **aCol = 0;
  char *zSql;
  sqlite4_stmt *pStmt = 0;
  int rc = SQLITE_OK;
  int nCol = 0;

  /* Prepare the statement "SELECT * FROM <tbl>". The column names
  ** of the result set of the compiled SELECT will be the same as
  ** the column names of table <tbl>.
  */
  zSql = sqlite4_mprintf("SELECT * FROM %Q", zTab);
  if( !zSql ){
    rc = SQLITE_NOMEM;
    goto out;
  }
  rc = sqlite4_prepare(db, zSql, -1, &pStmt, 0);
  sqlite4_free(zSql);

  if( rc==SQLITE_OK ){
    int ii;
    int nBytes;
    char *zSpace;
    nCol = sqlite4_column_count(pStmt);

    /* Figure out how much space to allocate for the array of column names 
    ** (including space for the strings themselves). Then allocate it.
    */
    nBytes = sizeof(char *) * nCol;
    for(ii=0; ii<nCol; ii++){
      const char *zName = sqlite4_column_name(pStmt, ii);
      if( !zName ){
        rc = SQLITE_NOMEM;
        goto out;
      }
      nBytes += strlen(zName)+1;
    }
    aCol = (char **)sqlite4MallocZero(nBytes);
    if( !aCol ){
      rc = SQLITE_NOMEM;
      goto out;
    }

    /* Copy the column names into the allocated space and set up the
    ** pointers in the aCol[] array.
    */
    zSpace = (char *)(&aCol[nCol]);
    for(ii=0; ii<nCol; ii++){
      aCol[ii] = zSpace;
      zSpace += sprintf(zSpace, "%s", sqlite4_column_name(pStmt, ii));
      zSpace++;
    }
    assert( (zSpace-nBytes)==(char *)aCol );
  }

  *paCol = aCol;
  *pnCol = nCol;

out:
  sqlite4_finalize(pStmt);
  return rc;
}

/*
** Parameter zTab is the name of a table in database db with nCol 
** columns. This function allocates an array of integers nCol in 
** size and populates it according to any implicit or explicit 
** indices on table zTab.
**
** If successful, SQLITE_OK is returned and *paIndex set to point 
** at the allocated array. Otherwise, an error code is returned.
**
** See comments associated with the member variable aIndex above 
** "struct echo_vtab" for details of the contents of the array.
*/
static int getIndexArray(
  sqlite4 *db,             /* Database connection */
  const char *zTab,        /* Name of table in database db */
  int nCol,
  int **paIndex
){
  sqlite4_stmt *pStmt = 0;
  int *aIndex = 0;
  int rc;
  char *zSql;

  /* Allocate space for the index array */
  aIndex = (int *)sqlite4MallocZero(sizeof(int) * nCol);
  if( !aIndex ){
    rc = SQLITE_NOMEM;
    goto get_index_array_out;
  }

  /* Compile an sqlite pragma to loop through all indices on table zTab */
  zSql = sqlite4_mprintf("PRAGMA index_list(%s)", zTab);
  if( !zSql ){
    rc = SQLITE_NOMEM;
    goto get_index_array_out;
  }
  rc = sqlite4_prepare(db, zSql, -1, &pStmt, 0);
  sqlite4_free(zSql);

  /* For each index, figure out the left-most column and set the 
  ** corresponding entry in aIndex[] to 1.
  */
  while( pStmt && sqlite4_step(pStmt)==SQLITE_ROW ){
    const char *zIdx = (const char *)sqlite4_column_text(pStmt, 1);
    sqlite4_stmt *pStmt2 = 0;
    zSql = sqlite4_mprintf("PRAGMA index_info(%s)", zIdx);
    if( !zSql ){
      rc = SQLITE_NOMEM;
      goto get_index_array_out;
    }
    rc = sqlite4_prepare(db, zSql, -1, &pStmt2, 0);
    sqlite4_free(zSql);
    if( pStmt2 && sqlite4_step(pStmt2)==SQLITE_ROW ){
      int cid = sqlite4_column_int(pStmt2, 1);
      assert( cid>=0 && cid<nCol );
      aIndex[cid] = 1;
    }
    if( pStmt2 ){
      rc = sqlite4_finalize(pStmt2);
    }
    if( rc!=SQLITE_OK ){
      goto get_index_array_out;
    }
  }


get_index_array_out:
  if( pStmt ){
    int rc2 = sqlite4_finalize(pStmt);
    if( rc==SQLITE_OK ){
      rc = rc2;
    }
  }
  if( rc!=SQLITE_OK ){
    sqlite4_free(aIndex);
    aIndex = 0;
  }
  *paIndex = aIndex;
  return rc;
}

/*
** Global Tcl variable $echo_module is a list. This routine appends
** the string element zArg to that list in interpreter interp.
*/
static void appendToEchoModule(Tcl_Interp *interp, const char *zArg){
  int flags = (TCL_APPEND_VALUE | TCL_LIST_ELEMENT | TCL_GLOBAL_ONLY);
  Tcl_SetVar(interp, "echo_module", (zArg?zArg:""), flags);
}

/*
** This function is called from within the echo-modules xCreate and
** xConnect methods. The argc and argv arguments are copies of those 
** passed to the calling method. This function is responsible for
** calling sqlite4_declare_vtab() to declare the schema of the virtual
** table being created or connected.
**
** If the constructor was passed just one argument, i.e.:
**
**   CREATE TABLE t1 AS echo(t2);
**
** Then t2 is assumed to be the name of a *real* database table. The
** schema of the virtual table is declared by passing a copy of the 
** CREATE TABLE statement for the real table to sqlite4_declare_vtab().
** Hence, the virtual table should have exactly the same column names and 
** types as the real table.
*/
static int echoDeclareVtab(
  echo_vtab *pVtab, 
  sqlite4 *db 
){
  int rc = SQLITE_OK;

  if( pVtab->zTableName ){
    sqlite4_stmt *pStmt = 0;
    rc = sqlite4_prepare(db, 
        "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",
        -1, &pStmt, 0);
    if( rc==SQLITE_OK ){
      sqlite4_bind_text(pStmt, 1, pVtab->zTableName, -1, 0);
      if( sqlite4_step(pStmt)==SQLITE_ROW ){
        int rc2;
        const char *zCreateTable = (const char *)sqlite4_column_text(pStmt, 0);
        rc = sqlite4_declare_vtab(db, zCreateTable);
        rc2 = sqlite4_finalize(pStmt);
        if( rc==SQLITE_OK ){
          rc = rc2;
        }
      } else {
        rc = sqlite4_finalize(pStmt);
        if( rc==SQLITE_OK ){ 
          rc = SQLITE_ERROR;
        }
      }
      if( rc==SQLITE_OK ){
        rc = getColumnNames(db, pVtab->zTableName, &pVtab->aCol, &pVtab->nCol);
      }
      if( rc==SQLITE_OK ){
        rc = getIndexArray(db, pVtab->zTableName, pVtab->nCol, &pVtab->aIndex);
      }
    }
  }

  return rc;
}

/*
** This function frees all runtime structures associated with the virtual
** table pVtab.
*/
static int echoDestructor(sqlite4_vtab *pVtab){
  echo_vtab *p = (echo_vtab*)pVtab;
  sqlite4_free(p->aIndex);
  sqlite4_free(p->aCol);
  sqlite4_free(p->zThis);
  sqlite4_free(p->zTableName);
  sqlite4_free(p->zLogName);
  sqlite4_free(p);
  return 0;
}

typedef struct EchoModule EchoModule;
struct EchoModule {
  Tcl_Interp *interp;
};

/*
** This function is called to do the work of the xConnect() method -
** to allocate the required in-memory structures for a newly connected
** virtual table.
*/
static int echoConstructor(
  sqlite4 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite4_vtab **ppVtab,
  char **pzErr
){
  int rc;
  int i;
  echo_vtab *pVtab;

  /* Allocate the sqlite4_vtab/echo_vtab structure itself */
  pVtab = sqlite4MallocZero( sizeof(*pVtab) );
  if( !pVtab ){
    return SQLITE_NOMEM;
  }
  pVtab->interp = ((EchoModule *)pAux)->interp;
  pVtab->db = db;

  /* Allocate echo_vtab.zThis */
  pVtab->zThis = sqlite4_mprintf("%s", argv[2]);
  if( !pVtab->zThis ){
    echoDestructor((sqlite4_vtab *)pVtab);
    return SQLITE_NOMEM;
  }

  /* Allocate echo_vtab.zTableName */
  if( argc>3 ){
    pVtab->zTableName = sqlite4_mprintf("%s", argv[3]);
    dequoteString(pVtab->zTableName);
    if( pVtab->zTableName && pVtab->zTableName[0]=='*' ){
      char *z = sqlite4_mprintf("%s%s", argv[2], &(pVtab->zTableName[1]));
      sqlite4_free(pVtab->zTableName);
      pVtab->zTableName = z;
      pVtab->isPattern = 1;
    }
    if( !pVtab->zTableName ){
      echoDestructor((sqlite4_vtab *)pVtab);
      return SQLITE_NOMEM;
    }
  }

  /* Log the arguments to this function to Tcl var ::echo_module */
  for(i=0; i<argc; i++){
    appendToEchoModule(pVtab->interp, argv[i]);
  }

  /* Invoke sqlite4_declare_vtab and set up other members of the echo_vtab
  ** structure. If an error occurs, delete the sqlite4_vtab structure and
  ** return an error code.
  */
  rc = echoDeclareVtab(pVtab, db);
  if( rc!=SQLITE_OK ){
    echoDestructor((sqlite4_vtab *)pVtab);
    return rc;
  }

  /* Success. Set *ppVtab and return */
  *ppVtab = &pVtab->base;
  return SQLITE_OK;
}

/* 
** Echo virtual table module xCreate method.
*/
static int echoCreate(
  sqlite4 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite4_vtab **ppVtab,
  char **pzErr
){
  int rc = SQLITE_OK;
  appendToEchoModule(((EchoModule *)pAux)->interp, "xCreate");
  rc = echoConstructor(db, pAux, argc, argv, ppVtab, pzErr);

  /* If there were two arguments passed to the module at the SQL level 
  ** (i.e. "CREATE VIRTUAL TABLE tbl USING echo(arg1, arg2)"), then 
  ** the second argument is used as a table name. Attempt to create
  ** such a table with a single column, "logmsg". This table will
  ** be used to log calls to the xUpdate method. It will be deleted
  ** when the virtual table is DROPed.
  **
  ** Note: The main point of this is to test that we can drop tables
  ** from within an xDestroy method call.
  */
  if( rc==SQLITE_OK && argc==5 ){
    char *zSql;
    echo_vtab *pVtab = *(echo_vtab **)ppVtab;
    pVtab->zLogName = sqlite4_mprintf("%s", argv[4]);
    zSql = sqlite4_mprintf("CREATE TABLE %Q(logmsg)", pVtab->zLogName);
    rc = sqlite4_exec(db, zSql, 0, 0, 0);
    sqlite4_free(zSql);
    if( rc!=SQLITE_OK ){
      *pzErr = sqlite4_mprintf("%s", sqlite4_errmsg(db));
    }
  }

  if( *ppVtab && rc!=SQLITE_OK ){
    echoDestructor(*ppVtab);
    *ppVtab = 0;
  }

  if( rc==SQLITE_OK ){
    (*(echo_vtab**)ppVtab)->inTransaction = 1;
  }

  return rc;
}

/* 
** Echo virtual table module xConnect method.
*/
static int echoConnect(
  sqlite4 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite4_vtab **ppVtab,
  char **pzErr
){
  appendToEchoModule(((EchoModule *)pAux)->interp, "xConnect");
  return echoConstructor(db, pAux, argc, argv, ppVtab, pzErr);
}

/* 
** Echo virtual table module xDisconnect method.
*/
static int echoDisconnect(sqlite4_vtab *pVtab){
  appendToEchoModule(((echo_vtab *)pVtab)->interp, "xDisconnect");
  return echoDestructor(pVtab);
}

/* 
** Echo virtual table module xDestroy method.
*/
static int echoDestroy(sqlite4_vtab *pVtab){
  int rc = SQLITE_OK;
  echo_vtab *p = (echo_vtab *)pVtab;
  appendToEchoModule(((echo_vtab *)pVtab)->interp, "xDestroy");

  /* Drop the "log" table, if one exists (see echoCreate() for details) */
  if( p && p->zLogName ){
    char *zSql;
    zSql = sqlite4_mprintf("DROP TABLE %Q", p->zLogName);
    rc = sqlite4_exec(p->db, zSql, 0, 0, 0);
    sqlite4_free(zSql);
  }

  if( rc==SQLITE_OK ){
    rc = echoDestructor(pVtab);
  }
  return rc;
}

/* 
** Echo virtual table module xOpen method.
*/
static int echoOpen(sqlite4_vtab *pVTab, sqlite4_vtab_cursor **ppCursor){
  echo_cursor *pCur;
  if( simulateVtabError((echo_vtab *)pVTab, "xOpen") ){
    return SQLITE_ERROR;
  }
  pCur = sqlite4MallocZero(sizeof(echo_cursor));
  *ppCursor = (sqlite4_vtab_cursor *)pCur;
  return (pCur ? SQLITE_OK : SQLITE_NOMEM);
}

/* 
** Echo virtual table module xClose method.
*/
static int echoClose(sqlite4_vtab_cursor *cur){
  int rc;
  echo_cursor *pCur = (echo_cursor *)cur;
  sqlite4_stmt *pStmt = pCur->pStmt;
  pCur->pStmt = 0;
  sqlite4_free(pCur);
  rc = sqlite4_finalize(pStmt);
  return rc;
}

/*
** Return non-zero if the cursor does not currently point to a valid record
** (i.e if the scan has finished), or zero otherwise.
*/
static int echoEof(sqlite4_vtab_cursor *cur){
  return (((echo_cursor *)cur)->pStmt ? 0 : 1);
}

/* 
** Echo virtual table module xNext method.
*/
static int echoNext(sqlite4_vtab_cursor *cur){
  int rc = SQLITE_OK;
  echo_cursor *pCur = (echo_cursor *)cur;

  if( simulateVtabError((echo_vtab *)(cur->pVtab), "xNext") ){
    return SQLITE_ERROR;
  }

  if( pCur->pStmt ){
    rc = sqlite4_step(pCur->pStmt);
    if( rc==SQLITE_ROW ){
      rc = SQLITE_OK;
    }else{
      rc = sqlite4_finalize(pCur->pStmt);
      pCur->pStmt = 0;
    }
  }

  return rc;
}

/* 
** Echo virtual table module xColumn method.
*/
static int echoColumn(sqlite4_vtab_cursor *cur, sqlite4_context *ctx, int i){
  int iCol = i + 1;
  sqlite4_stmt *pStmt = ((echo_cursor *)cur)->pStmt;

  if( simulateVtabError((echo_vtab *)(cur->pVtab), "xColumn") ){
    return SQLITE_ERROR;
  }

  if( !pStmt ){
    sqlite4_result_null(ctx);
  }else{
    assert( sqlite4_data_count(pStmt)>iCol );
    sqlite4_result_value(ctx, sqlite4_column_value(pStmt, iCol));
  }
  return SQLITE_OK;
}

/* 
** Echo virtual table module xRowid method.
*/
static int echoRowid(sqlite4_vtab_cursor *cur, sqlite_int64 *pRowid){
  sqlite4_stmt *pStmt = ((echo_cursor *)cur)->pStmt;

  if( simulateVtabError((echo_vtab *)(cur->pVtab), "xRowid") ){
    return SQLITE_ERROR;
  }

  *pRowid = sqlite4_column_int64(pStmt, 0);
  return SQLITE_OK;
}

/*
** Compute a simple hash of the null terminated string zString.
**
** This module uses only sqlite4_index_info.idxStr, not 
** sqlite4_index_info.idxNum. So to test idxNum, when idxStr is set
** in echoBestIndex(), idxNum is set to the corresponding hash value.
** In echoFilter(), code assert()s that the supplied idxNum value is
** indeed the hash of the supplied idxStr.
*/
static int hashString(const char *zString){
  int val = 0;
  int ii;
  for(ii=0; zString[ii]; ii++){
    val = (val << 3) + (int)zString[ii];
  }
  return val;
}

/* 
** Echo virtual table module xFilter method.
*/
static int echoFilter(
  sqlite4_vtab_cursor *pVtabCursor, 
  int idxNum, const char *idxStr,
  int argc, sqlite4_value **argv
){
  int rc;
  int i;

  echo_cursor *pCur = (echo_cursor *)pVtabCursor;
  echo_vtab *pVtab = (echo_vtab *)pVtabCursor->pVtab;
  sqlite4 *db = pVtab->db;

  if( simulateVtabError(pVtab, "xFilter") ){
    return SQLITE_ERROR;
  }

  /* Check that idxNum matches idxStr */
  assert( idxNum==hashString(idxStr) );

  /* Log arguments to the ::echo_module Tcl variable */
  appendToEchoModule(pVtab->interp, "xFilter");
  appendToEchoModule(pVtab->interp, idxStr);
  for(i=0; i<argc; i++){
    appendToEchoModule(pVtab->interp, (const char*)sqlite4_value_text(argv[i]));
  }

  sqlite4_finalize(pCur->pStmt);
  pCur->pStmt = 0;

  /* Prepare the SQL statement created by echoBestIndex and bind the
  ** runtime parameters passed to this function to it.
  */
  rc = sqlite4_prepare(db, idxStr, -1, &pCur->pStmt, 0);
  assert( pCur->pStmt || rc!=SQLITE_OK );
  for(i=0; rc==SQLITE_OK && i<argc; i++){
    rc = sqlite4_bind_value(pCur->pStmt, i+1, argv[i]);
  }

  /* If everything was successful, advance to the first row of the scan */
  if( rc==SQLITE_OK ){
    rc = echoNext(pVtabCursor);
  }

  return rc;
}


/*
** A helper function used by echoUpdate() and echoBestIndex() for
** manipulating strings in concert with the sqlite4_mprintf() function.
**
** Parameter pzStr points to a pointer to a string allocated with
** sqlite4_mprintf. The second parameter, zAppend, points to another
** string. The two strings are concatenated together and *pzStr
** set to point at the result. The initial buffer pointed to by *pzStr
** is deallocated via sqlite4_free().
**
** If the third argument, doFree, is true, then sqlite4_free() is
** also called to free the buffer pointed to by zAppend.
*/
static void string_concat(char **pzStr, char *zAppend, int doFree, int *pRc){
  char *zIn = *pzStr;
  if( !zAppend && doFree && *pRc==SQLITE_OK ){
    *pRc = SQLITE_NOMEM;
  }
  if( *pRc!=SQLITE_OK ){
    sqlite4_free(zIn);
    zIn = 0;
  }else{
    if( zIn ){
      char *zTemp = zIn;
      zIn = sqlite4_mprintf("%s%s", zIn, zAppend);
      sqlite4_free(zTemp);
    }else{
      zIn = sqlite4_mprintf("%s", zAppend);
    }
    if( !zIn ){
      *pRc = SQLITE_NOMEM;
    }
  }
  *pzStr = zIn;
  if( doFree ){
    sqlite4_free(zAppend);
  }
}

/*
** The echo module implements the subset of query constraints and sort
** orders that may take advantage of SQLite indices on the underlying
** real table. For example, if the real table is declared as:
**
**     CREATE TABLE real(a, b, c);
**     CREATE INDEX real_index ON real(b);
**
** then the echo module handles WHERE or ORDER BY clauses that refer
** to the column "b", but not "a" or "c". If a multi-column index is
** present, only its left most column is considered. 
**
** This xBestIndex method encodes the proposed search strategy as
** an SQL query on the real table underlying the virtual echo module 
** table and stores the query in sqlite4_index_info.idxStr. The SQL
** statement is of the form:
**
**   SELECT rowid, * FROM <real-table> ?<where-clause>? ?<order-by-clause>?
**
** where the <where-clause> and <order-by-clause> are determined
** by the contents of the structure pointed to by the pIdxInfo argument.
*/
static int echoBestIndex(sqlite4_vtab *tab, sqlite4_index_info *pIdxInfo){
  int ii;
  char *zQuery = 0;
  char *zNew;
  int nArg = 0;
  const char *zSep = "WHERE";
  echo_vtab *pVtab = (echo_vtab *)tab;
  sqlite4_stmt *pStmt = 0;
  Tcl_Interp *interp = pVtab->interp;

  int nRow;
  int useIdx = 0;
  int rc = SQLITE_OK;
  int useCost = 0;
  double cost;
  int isIgnoreUsable = 0;
  if( Tcl_GetVar(interp, "echo_module_ignore_usable", TCL_GLOBAL_ONLY) ){
    isIgnoreUsable = 1;
  }

  if( simulateVtabError(pVtab, "xBestIndex") ){
    return SQLITE_ERROR;
  }

  /* Determine the number of rows in the table and store this value in local
  ** variable nRow. The 'estimated-cost' of the scan will be the number of
  ** rows in the table for a linear scan, or the log (base 2) of the 
  ** number of rows if the proposed scan uses an index.  
  */
  if( Tcl_GetVar(interp, "echo_module_cost", TCL_GLOBAL_ONLY) ){
    cost = atof(Tcl_GetVar(interp, "echo_module_cost", TCL_GLOBAL_ONLY));
    useCost = 1;
  } else {
    zQuery = sqlite4_mprintf("SELECT count(*) FROM %Q", pVtab->zTableName);
    if( !zQuery ){
      return SQLITE_NOMEM;
    }
    rc = sqlite4_prepare(pVtab->db, zQuery, -1, &pStmt, 0);
    sqlite4_free(zQuery);
    if( rc!=SQLITE_OK ){
      return rc;
    }
    sqlite4_step(pStmt);
    nRow = sqlite4_column_int(pStmt, 0);
    rc = sqlite4_finalize(pStmt);
    if( rc!=SQLITE_OK ){
      return rc;
    }
  }

  zQuery = sqlite4_mprintf("SELECT rowid, * FROM %Q", pVtab->zTableName);
  if( !zQuery ){
    return SQLITE_NOMEM;
  }
  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
    const struct sqlite4_index_constraint *pConstraint;
    struct sqlite4_index_constraint_usage *pUsage;
    int iCol;

    pConstraint = &pIdxInfo->aConstraint[ii];
    pUsage = &pIdxInfo->aConstraintUsage[ii];

    if( !isIgnoreUsable && !pConstraint->usable ) continue;

    iCol = pConstraint->iColumn;
    if( pVtab->aIndex[iCol] || iCol<0 ){
      char *zCol = pVtab->aCol[iCol];
      char *zOp = 0;
      useIdx = 1;
      if( iCol<0 ){
        zCol = "rowid";
      }
      switch( pConstraint->op ){
        case SQLITE_INDEX_CONSTRAINT_EQ:
          zOp = "="; break;
        case SQLITE_INDEX_CONSTRAINT_LT:
          zOp = "<"; break;
        case SQLITE_INDEX_CONSTRAINT_GT:
          zOp = ">"; break;
        case SQLITE_INDEX_CONSTRAINT_LE:
          zOp = "<="; break;
        case SQLITE_INDEX_CONSTRAINT_GE:
          zOp = ">="; break;
        case SQLITE_INDEX_CONSTRAINT_MATCH:
          zOp = "LIKE"; break;
      }
      if( zOp[0]=='L' ){
        zNew = sqlite4_mprintf(" %s %s LIKE (SELECT '%%'||?||'%%')", 
                               zSep, zCol);
      } else {
        zNew = sqlite4_mprintf(" %s %s %s ?", zSep, zCol, zOp);
      }
      string_concat(&zQuery, zNew, 1, &rc);

      zSep = "AND";
      pUsage->argvIndex = ++nArg;
      pUsage->omit = 1;
    }
  }

  /* If there is only one term in the ORDER BY clause, and it is
  ** on a column that this virtual table has an index for, then consume 
  ** the ORDER BY clause.
  */
  if( pIdxInfo->nOrderBy==1 && pVtab->aIndex[pIdxInfo->aOrderBy->iColumn] ){
    int iCol = pIdxInfo->aOrderBy->iColumn;
    char *zCol = pVtab->aCol[iCol];
    char *zDir = pIdxInfo->aOrderBy->desc?"DESC":"ASC";
    if( iCol<0 ){
      zCol = "rowid";
    }
    zNew = sqlite4_mprintf(" ORDER BY %s %s", zCol, zDir);
    string_concat(&zQuery, zNew, 1, &rc);
    pIdxInfo->orderByConsumed = 1;
  }

  appendToEchoModule(pVtab->interp, "xBestIndex");;
  appendToEchoModule(pVtab->interp, zQuery);

  if( !zQuery ){
    return rc;
  }
  pIdxInfo->idxNum = hashString(zQuery);
  pIdxInfo->idxStr = zQuery;
  pIdxInfo->needToFreeIdxStr = 1;
  if( useCost ){
    pIdxInfo->estimatedCost = cost;
  }else if( useIdx ){
    /* Approximation of log2(nRow). */
    for( ii=0; ii<(sizeof(int)*8); ii++ ){
      if( nRow & (1<<ii) ){
        pIdxInfo->estimatedCost = (double)ii;
      }
    }
  }else{
    pIdxInfo->estimatedCost = (double)nRow;
  }
  return rc;
}

/*
** The xUpdate method for echo module virtual tables.
** 
**    apData[0]  apData[1]  apData[2..]
**
**    INTEGER                              DELETE            
**
**    INTEGER    NULL       (nCol args)    UPDATE (do not set rowid)
**    INTEGER    INTEGER    (nCol args)    UPDATE (with SET rowid = <arg1>)
**
**    NULL       NULL       (nCol args)    INSERT INTO (automatic rowid value)
**    NULL       INTEGER    (nCol args)    INSERT (incl. rowid value)
**
*/
int echoUpdate(
  sqlite4_vtab *tab, 
  int nData, 
  sqlite4_value **apData, 
  sqlite_int64 *pRowid
){
  echo_vtab *pVtab = (echo_vtab *)tab;
  sqlite4 *db = pVtab->db;
  int rc = SQLITE_OK;

  sqlite4_stmt *pStmt;
  char *z = 0;               /* SQL statement to execute */
  int bindArgZero = 0;       /* True to bind apData[0] to sql var no. nData */
  int bindArgOne = 0;        /* True to bind apData[1] to sql var no. 1 */
  int i;                     /* Counter variable used by for loops */

  assert( nData==pVtab->nCol+2 || nData==1 );

  /* Ticket #3083 - make sure we always start a transaction prior to
  ** making any changes to a virtual table */
  assert( pVtab->inTransaction );

  if( simulateVtabError(pVtab, "xUpdate") ){
    return SQLITE_ERROR;
  }

  /* If apData[0] is an integer and nData>1 then do an UPDATE */
  if( nData>1 && sqlite4_value_type(apData[0])==SQLITE_INTEGER ){
    char *zSep = " SET";
    z = sqlite4_mprintf("UPDATE %Q", pVtab->zTableName);
    if( !z ){
      rc = SQLITE_NOMEM;
    }

    bindArgOne = (apData[1] && sqlite4_value_type(apData[1])==SQLITE_INTEGER);
    bindArgZero = 1;

    if( bindArgOne ){
       string_concat(&z, " SET rowid=?1 ", 0, &rc);
       zSep = ",";
    }
    for(i=2; i<nData; i++){
      if( apData[i]==0 ) continue;
      string_concat(&z, sqlite4_mprintf(
          "%s %Q=?%d", zSep, pVtab->aCol[i-2], i), 1, &rc);
      zSep = ",";
    }
    string_concat(&z, sqlite4_mprintf(" WHERE rowid=?%d", nData), 1, &rc);
  }

  /* If apData[0] is an integer and nData==1 then do a DELETE */
  else if( nData==1 && sqlite4_value_type(apData[0])==SQLITE_INTEGER ){
    z = sqlite4_mprintf("DELETE FROM %Q WHERE rowid = ?1", pVtab->zTableName);
    if( !z ){
      rc = SQLITE_NOMEM;
    }
    bindArgZero = 1;
  }

  /* If the first argument is NULL and there are more than two args, INSERT */
  else if( nData>2 && sqlite4_value_type(apData[0])==SQLITE_NULL ){
    int ii;
    char *zInsert = 0;
    char *zValues = 0;
  
    zInsert = sqlite4_mprintf("INSERT INTO %Q (", pVtab->zTableName);
    if( !zInsert ){
      rc = SQLITE_NOMEM;
    }
    if( sqlite4_value_type(apData[1])==SQLITE_INTEGER ){
      bindArgOne = 1;
      zValues = sqlite4_mprintf("?");
      string_concat(&zInsert, "rowid", 0, &rc);
    }

    assert((pVtab->nCol+2)==nData);
    for(ii=2; ii<nData; ii++){
      string_concat(&zInsert, 
          sqlite4_mprintf("%s%Q", zValues?", ":"", pVtab->aCol[ii-2]), 1, &rc);
      string_concat(&zValues, 
          sqlite4_mprintf("%s?%d", zValues?", ":"", ii), 1, &rc);
    }

    string_concat(&z, zInsert, 1, &rc);
    string_concat(&z, ") VALUES(", 0, &rc);
    string_concat(&z, zValues, 1, &rc);
    string_concat(&z, ")", 0, &rc);
  }

  /* Anything else is an error */
  else{
    assert(0);
    return SQLITE_ERROR;
  }

  if( rc==SQLITE_OK ){
    rc = sqlite4_prepare(db, z, -1, &pStmt, 0);
  }
  assert( rc!=SQLITE_OK || pStmt );
  sqlite4_free(z);
  if( rc==SQLITE_OK ) {
    if( bindArgZero ){
      sqlite4_bind_value(pStmt, nData, apData[0]);
    }
    if( bindArgOne ){
      sqlite4_bind_value(pStmt, 1, apData[1]);
    }
    for(i=2; i<nData && rc==SQLITE_OK; i++){
      if( apData[i] ) rc = sqlite4_bind_value(pStmt, i, apData[i]);
    }
    if( rc==SQLITE_OK ){
      sqlite4_step(pStmt);
      rc = sqlite4_finalize(pStmt);
    }else{
      sqlite4_finalize(pStmt);
    }
  }

  if( pRowid && rc==SQLITE_OK ){
    *pRowid = sqlite4_last_insert_rowid(db);
  }
  if( rc!=SQLITE_OK ){
    tab->zErrMsg = sqlite4_mprintf("echo-vtab-error: %s", sqlite4_errmsg(db));
  }

  return rc;
}

/*
** xBegin, xSync, xCommit and xRollback callbacks for echo module
** virtual tables. Do nothing other than add the name of the callback
** to the $::echo_module Tcl variable.
*/
static int echoTransactionCall(sqlite4_vtab *tab, const char *zCall){
  char *z;
  echo_vtab *pVtab = (echo_vtab *)tab;
  z = sqlite4_mprintf("echo(%s)", pVtab->zTableName);
  if( z==0 ) return SQLITE_NOMEM;
  appendToEchoModule(pVtab->interp, zCall);
  appendToEchoModule(pVtab->interp, z);
  sqlite4_free(z);
  return SQLITE_OK;
}
static int echoBegin(sqlite4_vtab *tab){
  int rc;
  echo_vtab *pVtab = (echo_vtab *)tab;
  Tcl_Interp *interp = pVtab->interp;
  const char *zVal; 

  /* Ticket #3083 - do not start a transaction if we are already in
  ** a transaction */
  assert( !pVtab->inTransaction );

  if( simulateVtabError(pVtab, "xBegin") ){
    return SQLITE_ERROR;
  }

  rc = echoTransactionCall(tab, "xBegin");

  if( rc==SQLITE_OK ){
    /* Check if the $::echo_module_begin_fail variable is defined. If it is,
    ** and it is set to the name of the real table underlying this virtual
    ** echo module table, then cause this xSync operation to fail.
    */
    zVal = Tcl_GetVar(interp, "echo_module_begin_fail", TCL_GLOBAL_ONLY);
    if( zVal && 0==strcmp(zVal, pVtab->zTableName) ){
      rc = SQLITE_ERROR;
    }
  }
  if( rc==SQLITE_OK ){
    pVtab->inTransaction = 1;
  }
  return rc;
}
static int echoSync(sqlite4_vtab *tab){
  int rc;
  echo_vtab *pVtab = (echo_vtab *)tab;
  Tcl_Interp *interp = pVtab->interp;
  const char *zVal; 

  /* Ticket #3083 - Only call xSync if we have previously started a
  ** transaction */
  assert( pVtab->inTransaction );

  if( simulateVtabError(pVtab, "xSync") ){
    return SQLITE_ERROR;
  }

  rc = echoTransactionCall(tab, "xSync");

  if( rc==SQLITE_OK ){
    /* Check if the $::echo_module_sync_fail variable is defined. If it is,
    ** and it is set to the name of the real table underlying this virtual
    ** echo module table, then cause this xSync operation to fail.
    */
    zVal = Tcl_GetVar(interp, "echo_module_sync_fail", TCL_GLOBAL_ONLY);
    if( zVal && 0==strcmp(zVal, pVtab->zTableName) ){
      rc = -1;
    }
  }
  return rc;
}
static int echoCommit(sqlite4_vtab *tab){
  echo_vtab *pVtab = (echo_vtab*)tab;
  int rc;

  /* Ticket #3083 - Only call xCommit if we have previously started
  ** a transaction */
  assert( pVtab->inTransaction );

  if( simulateVtabError(pVtab, "xCommit") ){
    return SQLITE_ERROR;
  }

  sqlite4BeginBenignMalloc();
  rc = echoTransactionCall(tab, "xCommit");
  sqlite4EndBenignMalloc();
  pVtab->inTransaction = 0;
  return rc;
}
static int echoRollback(sqlite4_vtab *tab){
  int rc;
  echo_vtab *pVtab = (echo_vtab*)tab;

  /* Ticket #3083 - Only call xRollback if we have previously started
  ** a transaction */
  assert( pVtab->inTransaction );

  rc = echoTransactionCall(tab, "xRollback");
  pVtab->inTransaction = 0;
  return rc;
}

/*
** Implementation of "GLOB" function on the echo module.  Pass
** all arguments to the ::echo_glob_overload procedure of TCL
** and return the result of that procedure as a string.
*/
static void overloadedGlobFunction(
  sqlite4_context *pContext,
  int nArg,
  sqlite4_value **apArg
){
  Tcl_Interp *interp = sqlite4_user_data(pContext);
  Tcl_DString str;
  int i;
  int rc;
  Tcl_DStringInit(&str);
  Tcl_DStringAppendElement(&str, "::echo_glob_overload");
  for(i=0; i<nArg; i++){
    Tcl_DStringAppendElement(&str, (char*)sqlite4_value_text(apArg[i]));
  }
  rc = Tcl_Eval(interp, Tcl_DStringValue(&str));
  Tcl_DStringFree(&str);
  if( rc ){
    sqlite4_result_error(pContext, Tcl_GetStringResult(interp), -1);
  }else{
    sqlite4_result_text(pContext, Tcl_GetStringResult(interp),
                        -1, SQLITE_TRANSIENT);
  }
  Tcl_ResetResult(interp);
}

/*
** This is the xFindFunction implementation for the echo module.
** SQLite calls this routine when the first argument of a function
** is a column of an echo virtual table.  This routine can optionally
** override the implementation of that function.  It will choose to
** do so if the function is named "glob", and a TCL command named
** ::echo_glob_overload exists.
*/
static int echoFindFunction(
  sqlite4_vtab *vtab,
  int nArg,
  const char *zFuncName,
  void (**pxFunc)(sqlite4_context*,int,sqlite4_value**),
  void **ppArg
){
  echo_vtab *pVtab = (echo_vtab *)vtab;
  Tcl_Interp *interp = pVtab->interp;
  Tcl_CmdInfo info;
  if( strcmp(zFuncName,"glob")!=0 ){
    return 0;
  }
  if( Tcl_GetCommandInfo(interp, "::echo_glob_overload", &info)==0 ){
    return 0;
  }
  *pxFunc = overloadedGlobFunction;
  *ppArg = interp;
  return 1;
}

static int echoRename(sqlite4_vtab *vtab, const char *zNewName){
  int rc = SQLITE_OK;
  echo_vtab *p = (echo_vtab *)vtab;

  if( simulateVtabError(p, "xRename") ){
    return SQLITE_ERROR;
  }

  if( p->isPattern ){
    int nThis = strlen(p->zThis);
    char *zSql = sqlite4_mprintf("ALTER TABLE %s RENAME TO %s%s", 
        p->zTableName, zNewName, &p->zTableName[nThis]
    );
    rc = sqlite4_exec(p->db, zSql, 0, 0, 0);
    sqlite4_free(zSql);
  }

  return rc;
}

static int echoSavepoint(sqlite4_vtab *pVTab, int iSavepoint){
  assert( pVTab );
  return SQLITE_OK;
}

static int echoRelease(sqlite4_vtab *pVTab, int iSavepoint){
  assert( pVTab );
  return SQLITE_OK;
}

static int echoRollbackTo(sqlite4_vtab *pVTab, int iSavepoint){
  assert( pVTab );
  return SQLITE_OK;
}

/*
** A virtual table module that merely "echos" the contents of another
** table (like an SQL VIEW).
*/
static sqlite4_module echoModule = {
  1,                         /* iVersion */
  echoCreate,
  echoConnect,
  echoBestIndex,
  echoDisconnect, 
  echoDestroy,
  echoOpen,                  /* xOpen - open a cursor */
  echoClose,                 /* xClose - close a cursor */
  echoFilter,                /* xFilter - configure scan constraints */
  echoNext,                  /* xNext - advance a cursor */
  echoEof,                   /* xEof */
  echoColumn,                /* xColumn - read data */
  echoRowid,                 /* xRowid - read data */
  echoUpdate,                /* xUpdate - write data */
  echoBegin,                 /* xBegin - begin transaction */
  echoSync,                  /* xSync - sync transaction */
  echoCommit,                /* xCommit - commit transaction */
  echoRollback,              /* xRollback - rollback transaction */
  echoFindFunction,          /* xFindFunction - function overloading */
  echoRename                 /* xRename - rename the table */
};

static sqlite4_module echoModuleV2 = {
  2,                         /* iVersion */
  echoCreate,
  echoConnect,
  echoBestIndex,
  echoDisconnect, 
  echoDestroy,
  echoOpen,                  /* xOpen - open a cursor */
  echoClose,                 /* xClose - close a cursor */
  echoFilter,                /* xFilter - configure scan constraints */
  echoNext,                  /* xNext - advance a cursor */
  echoEof,                   /* xEof */
  echoColumn,                /* xColumn - read data */
  echoRowid,                 /* xRowid - read data */
  echoUpdate,                /* xUpdate - write data */
  echoBegin,                 /* xBegin - begin transaction */
  echoSync,                  /* xSync - sync transaction */
  echoCommit,                /* xCommit - commit transaction */
  echoRollback,              /* xRollback - rollback transaction */
  echoFindFunction,          /* xFindFunction - function overloading */
  echoRename,                /* xRename - rename the table */
  echoSavepoint,
  echoRelease,
  echoRollbackTo
};

/*
** Decode a pointer to an sqlite4 object.
*/
extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite4 **ppDb);

static void moduleDestroy(void *p){
  sqlite4_free(p);
}

/*
** Register the echo virtual table module.
*/
static int register_echo_module(
  ClientData clientData, /* Pointer to sqlite4_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite4 *db;
  EchoModule *pMod;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;

  /* Virtual table module "echo" */
  pMod = sqlite4_malloc(sizeof(EchoModule));
  pMod->interp = interp;
  sqlite4_create_module_v2(db, "echo", &echoModule, (void*)pMod, moduleDestroy);

  /* Virtual table module "echo_v2" */
  pMod = sqlite4_malloc(sizeof(EchoModule));
  pMod->interp = interp;
  sqlite4_create_module_v2(db, "echo_v2", 
      &echoModuleV2, (void*)pMod, moduleDestroy
  );
  return TCL_OK;
}

/*
** Tcl interface to sqlite4_declare_vtab, invoked as follows from Tcl:
**
** sqlite4_declare_vtab DB SQL
*/
static int declare_vtab(
  ClientData clientData, /* Pointer to sqlite4_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite4 *db;
  int rc;
  if( objc!=3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB SQL");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  rc = sqlite4_declare_vtab(db, Tcl_GetString(objv[2]));
  if( rc!=SQLITE_OK ){
    Tcl_SetResult(interp, (char *)sqlite4_errmsg(db), TCL_VOLATILE);
    return TCL_ERROR;
  }
  return TCL_OK;
}

#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */

/*
** Register commands with the TCL interpreter.
*/
int Sqlitetest8_Init(Tcl_Interp *interp){
#ifndef SQLITE_OMIT_VIRTUALTABLE
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
     void *clientData;
  } aObjCmd[] = {
     { "register_echo_module",   register_echo_module, 0 },
     { "sqlite4_declare_vtab",   declare_vtab, 0 },
  };
  int i;
  for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
    Tcl_CreateObjCommand(interp, aObjCmd[i].zName, 
        aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
  }
#endif
  return TCL_OK;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Changes to test/test_func.c.

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
..
39
40
41
42
43
44
45

46
47
48
49
50
51
52
..
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
..
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
...
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
...
225
226
227
228
229
230
231








232
233
234
235
236
237
238
239
240
241
242
243

244
245
246
247
248
249
250
251

252
253
254
255
256
257
258
259
260
261
262
263
...
304
305
306
307
308
309
310

311
312

313
314
315
316
317
318
319
320
...
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
...
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
...
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
...
561
562
563
564
565
566
567
568

/*
** Allocate nByte bytes of space using sqlite4_malloc(). If the
** allocation fails, call sqlite4_result_error_nomem() to notify
** the database handle that malloc() has failed.
*/
static void *testContextMalloc(sqlite4_context *context, int nByte){
  char *z = sqlite4_malloc(nByte);
  if( !z && nByte>0 ){
    sqlite4_result_error_nomem(context);
  }
  return z;
}

/*
................................................................................
static void randStr(sqlite4_context *context, int argc, sqlite4_value **argv){
  static const unsigned char zSrc[] = 
     "abcdefghijklmnopqrstuvwxyz"
     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
     "0123456789"
     ".-!,:*^+=_|?/<> ";
  int iMin, iMax, n, r, i;

  unsigned char zBuf[1000];

  /* It used to be possible to call randstr() with any number of arguments,
  ** but now it is registered with SQLite as requiring exactly 2.
  */
  assert(argc==2);

................................................................................
  if( iMin<0 ) iMin = 0;
  if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
  iMax = sqlite4_value_int(argv[1]);
  if( iMax<iMin ) iMax = iMin;
  if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
  n = iMin;
  if( iMax>iMin ){
    sqlite4_randomness(sizeof(r), &r);
    r &= 0x7fffffff;
    n += r%(iMax + 1 - iMin);
  }
  assert( n<sizeof(zBuf) );
  sqlite4_randomness(n, zBuf);
  for(i=0; i<n; i++){
    zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
  }
  zBuf[n] = 0;
  sqlite4_result_text(context, (char*)zBuf, n, SQLITE_TRANSIENT);
}

................................................................................
** WARNING: Not threadsafe.
*/
static int test_destructor_count_var = 0;
static void destructor(void *p){
  char *zVal = (char *)p;
  assert(zVal);
  zVal--;
  sqlite4_free(zVal);
  test_destructor_count_var--;
}
static void test_destructor(
  sqlite4_context *pCtx, 
  int nArg,
  sqlite4_value **argv
){
................................................................................
** The test_auxdata() SQL function attempts to register each of its arguments
** as auxiliary data.  If there are no prior registrations of aux data for
** that argument (meaning the argument is not a constant or this is its first
** call) then the result for that argument is 0.  If there is a prior
** registration, the result for that argument is 1.  The overall result
** is the individual argument results separated by spaces.
*/
static void free_test_auxdata(void *p) {sqlite4_free(p);}
static void test_auxdata(
  sqlite4_context *pCtx, 
  int nArg,
  sqlite4_value **argv
){
  int i;
  char *zRet = testContextMalloc(pCtx, nArg*2);
................................................................................
  sqlite4_value **argv
){
  sqlite4_result_error(pCtx, (char*)sqlite4_value_text(argv[0]), -1);
  if( nArg==2 ){
    sqlite4_result_error_code(pCtx, sqlite4_value_int(argv[1]));
  }
}









/*
** Implementation of the counter(X) function.  If X is an integer
** constant, then the first invocation will return X.  The second X+1.
** and so forth.  Can be used (for example) to provide a sequence number
** in a result set.
*/
static void counterFunc(
  sqlite4_context *pCtx,   /* Function context */
  int nArg,                /* Number of function arguments */
  sqlite4_value **argv     /* Values for all function arguments */
){

  int *pCounter = (int*)sqlite4_get_auxdata(pCtx, 0);
  if( pCounter==0 ){
    pCounter = sqlite4_malloc( sizeof(*pCounter) );
    if( pCounter==0 ){
      sqlite4_result_error_nomem(pCtx);
      return;
    }
    *pCounter = sqlite4_value_int(argv[0]);

    sqlite4_set_auxdata(pCtx, 0, pCounter, sqlite4_free);
  }else{
    ++*pCounter;
  }
  sqlite4_result_int(pCtx, *pCounter);
}


/*
** This function takes two arguments.  It performance UTF-8/16 type
** conversions on the first argument then returns a copy of the second
** argument.
................................................................................
    if( rc==SQLITE_ROW ){
      sqlite4_result_value(pCtx, sqlite4_column_value(pStmt, 0));
    }
    rc = sqlite4_finalize(pStmt);
  }
  if( rc ){
    char *zErr;

    assert( pStmt==0 );
    zErr = sqlite4_mprintf("sqlite4_prepare() error: %s",sqlite4_errmsg(db));

    sqlite4_result_text(pCtx, zErr, -1, sqlite4_free);
    sqlite4_result_error_code(pCtx, rc);
  }
}


/*
** convert one character from hex to binary
................................................................................
){
  int n;
  const char *zIn;
  char *zOut;
  assert( nArg==1 );
  n = sqlite4_value_bytes(argv[0]);
  zIn = (const char*)sqlite4_value_text(argv[0]);
  zOut = sqlite4_malloc( n/2 );
  if( zOut==0 ){
    sqlite4_result_error_nomem(pCtx);
  }else{
    testHexToBin(zIn, zOut);
    sqlite4_result_text16be(pCtx, zOut, n/2, sqlite4_free);
  }
}
#endif

/*
**      hex_to_utf8(HEX)
**
................................................................................
){
  int n;
  const char *zIn;
  char *zOut;
  assert( nArg==1 );
  n = sqlite4_value_bytes(argv[0]);
  zIn = (const char*)sqlite4_value_text(argv[0]);
  zOut = sqlite4_malloc( n/2 );
  if( zOut==0 ){
    sqlite4_result_error_nomem(pCtx);
  }else{
    testHexToBin(zIn, zOut);
    sqlite4_result_text(pCtx, zOut, n/2, sqlite4_free);
  }
}

/*
**      hex_to_utf16le(HEX)
**
** Convert the input string from HEX into binary.  Then return the
................................................................................
){
  int n;
  const char *zIn;
  char *zOut;
  assert( nArg==1 );
  n = sqlite4_value_bytes(argv[0]);
  zIn = (const char*)sqlite4_value_text(argv[0]);
  zOut = sqlite4_malloc( n/2 );
  if( zOut==0 ){
    sqlite4_result_error_nomem(pCtx);
  }else{
    testHexToBin(zIn, zOut);
    sqlite4_result_text16le(pCtx, zOut, n/2, sqlite4_free);
  }
}
#endif

static int registerTestFunctions(sqlite4 *db){
  static const struct {
     char *zName;
................................................................................

  rc = registerTestFunctions(db);
  if( rc==SQLITE_OK ){
    rc = Md5_Register(db);
  }
  return rc;
}








|







 







>







 







|




|







 







|







 







|







 







>
>
>
>
>
>
>
>












>
|

|




|
>
|

|

|







 







>

|
>
|







 







|




|







 







|




|







 







|




|







 







<
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
..
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
..
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
..
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
...
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
...
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
...
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
...
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
...
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
...
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
...
574
575
576
577
578
579
580


/*
** Allocate nByte bytes of space using sqlite4_malloc(). If the
** allocation fails, call sqlite4_result_error_nomem() to notify
** the database handle that malloc() has failed.
*/
static void *testContextMalloc(sqlite4_context *context, int nByte){
  char *z = sqlite4_malloc(sqlite4_context_env(context), nByte);
  if( !z && nByte>0 ){
    sqlite4_result_error_nomem(context);
  }
  return z;
}

/*
................................................................................
static void randStr(sqlite4_context *context, int argc, sqlite4_value **argv){
  static const unsigned char zSrc[] = 
     "abcdefghijklmnopqrstuvwxyz"
     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
     "0123456789"
     ".-!,:*^+=_|?/<> ";
  int iMin, iMax, n, r, i;
  sqlite4_env *pEnv = sqlite4_context_env(context);
  unsigned char zBuf[1000];

  /* It used to be possible to call randstr() with any number of arguments,
  ** but now it is registered with SQLite as requiring exactly 2.
  */
  assert(argc==2);

................................................................................
  if( iMin<0 ) iMin = 0;
  if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
  iMax = sqlite4_value_int(argv[1]);
  if( iMax<iMin ) iMax = iMin;
  if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
  n = iMin;
  if( iMax>iMin ){
    sqlite4_randomness(pEnv, sizeof(r), &r);
    r &= 0x7fffffff;
    n += r%(iMax + 1 - iMin);
  }
  assert( n<sizeof(zBuf) );
  sqlite4_randomness(pEnv, n, zBuf);
  for(i=0; i<n; i++){
    zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
  }
  zBuf[n] = 0;
  sqlite4_result_text(context, (char*)zBuf, n, SQLITE_TRANSIENT);
}

................................................................................
** WARNING: Not threadsafe.
*/
static int test_destructor_count_var = 0;
static void destructor(void *p){
  char *zVal = (char *)p;
  assert(zVal);
  zVal--;
  sqlite4_free(0, zVal);
  test_destructor_count_var--;
}
static void test_destructor(
  sqlite4_context *pCtx, 
  int nArg,
  sqlite4_value **argv
){
................................................................................
** The test_auxdata() SQL function attempts to register each of its arguments
** as auxiliary data.  If there are no prior registrations of aux data for
** that argument (meaning the argument is not a constant or this is its first
** call) then the result for that argument is 0.  If there is a prior
** registration, the result for that argument is 1.  The overall result
** is the individual argument results separated by spaces.
*/
static void free_test_auxdata(void *p) {sqlite4_free(0, p);}
static void test_auxdata(
  sqlite4_context *pCtx, 
  int nArg,
  sqlite4_value **argv
){
  int i;
  char *zRet = testContextMalloc(pCtx, nArg*2);
................................................................................
  sqlite4_value **argv
){
  sqlite4_result_error(pCtx, (char*)sqlite4_value_text(argv[0]), -1);
  if( nArg==2 ){
    sqlite4_result_error_code(pCtx, sqlite4_value_int(argv[1]));
  }
}

/* A counter object with its destructor.  Used by counterFunc() below.
*/
struct counterObject { int cnt; sqlite4_env *pEnv; };
void counterFree(void *x){
  struct counterObject *p = (struct counterObject*)x;
  sqlite4_free(p->pEnv, p);
}

/*
** Implementation of the counter(X) function.  If X is an integer
** constant, then the first invocation will return X.  The second X+1.
** and so forth.  Can be used (for example) to provide a sequence number
** in a result set.
*/
static void counterFunc(
  sqlite4_context *pCtx,   /* Function context */
  int nArg,                /* Number of function arguments */
  sqlite4_value **argv     /* Values for all function arguments */
){
  struct counterObject *pCounter;
  pCounter = (struct counterObject*)sqlite4_get_auxdata(pCtx, 0);
  if( pCounter==0 ){
    pCounter = sqlite4_malloc(sqlite4_context_env(pCtx), sizeof(*pCounter) );
    if( pCounter==0 ){
      sqlite4_result_error_nomem(pCtx);
      return;
    }
    pCounter->cnt = sqlite4_value_int(argv[0]);
    pCounter->pEnv = sqlite4_context_env(pCtx);
    sqlite4_set_auxdata(pCtx, 0, pCounter, counterFree);
  }else{
    pCounter->cnt++;
  }
  sqlite4_result_int(pCtx, pCounter->cnt);
}


/*
** This function takes two arguments.  It performance UTF-8/16 type
** conversions on the first argument then returns a copy of the second
** argument.
................................................................................
    if( rc==SQLITE_ROW ){
      sqlite4_result_value(pCtx, sqlite4_column_value(pStmt, 0));
    }
    rc = sqlite4_finalize(pStmt);
  }
  if( rc ){
    char *zErr;
    sqlite4_env *pEnv = sqlite4_context_env(pCtx);
    assert( pStmt==0 );
    zErr = sqlite4_mprintf(pEnv, "sqlite4_prepare() error: %s",
                           sqlite4_errmsg(db));
    sqlite4_result_text(pCtx, zErr, -1, SQLITE_DYNAMIC);
    sqlite4_result_error_code(pCtx, rc);
  }
}


/*
** convert one character from hex to binary
................................................................................
){
  int n;
  const char *zIn;
  char *zOut;
  assert( nArg==1 );
  n = sqlite4_value_bytes(argv[0]);
  zIn = (const char*)sqlite4_value_text(argv[0]);
  zOut = sqlite4_malloc(sqlite4_context_env(pCtx), n/2 );
  if( zOut==0 ){
    sqlite4_result_error_nomem(pCtx);
  }else{
    testHexToBin(zIn, zOut);
    sqlite4_result_text16be(pCtx, zOut, n/2, SQLITE_DYNAMIC);
  }
}
#endif

/*
**      hex_to_utf8(HEX)
**
................................................................................
){
  int n;
  const char *zIn;
  char *zOut;
  assert( nArg==1 );
  n = sqlite4_value_bytes(argv[0]);
  zIn = (const char*)sqlite4_value_text(argv[0]);
  zOut = sqlite4_malloc(sqlite4_context_env(pCtx), n/2 );
  if( zOut==0 ){
    sqlite4_result_error_nomem(pCtx);
  }else{
    testHexToBin(zIn, zOut);
    sqlite4_result_text(pCtx, zOut, n/2, SQLITE_DYNAMIC);
  }
}

/*
**      hex_to_utf16le(HEX)
**
** Convert the input string from HEX into binary.  Then return the
................................................................................
){
  int n;
  const char *zIn;
  char *zOut;
  assert( nArg==1 );
  n = sqlite4_value_bytes(argv[0]);
  zIn = (const char*)sqlite4_value_text(argv[0]);
  zOut = sqlite4_malloc(sqlite4_context_env(pCtx), n/2 );
  if( zOut==0 ){
    sqlite4_result_error_nomem(pCtx);
  }else{
    testHexToBin(zIn, zOut);
    sqlite4_result_text16le(pCtx, zOut, n/2, SQLITE_DYNAMIC);
  }
}
#endif

static int registerTestFunctions(sqlite4 *db){
  static const struct {
     char *zName;
................................................................................

  rc = registerTestFunctions(db);
  if( rc==SQLITE_OK ){
    rc = Md5_Register(db);
  }
  return rc;
}

Deleted test/test_fuzzer.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
/*
** 2011 March 24
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** Code for demonstartion virtual table that generates variations
** on an input word at increasing edit distances from the original.
**
** A fuzzer virtual table is created like this:
**
**     CREATE VIRTUAL TABLE temp.f USING fuzzer;
**
** The name of the new virtual table in the example above is "f".
** Note that all fuzzer virtual tables must be TEMP tables.  The
** "temp." prefix in front of the table name is required when the
** table is being created.  The "temp." prefix can be omitted when
** using the table as long as the name is unambiguous.
**
** Before being used, the fuzzer needs to be programmed by giving it
** character transformations and a cost associated with each transformation.
** Examples:
**
**    INSERT INTO f(cFrom,cTo,Cost) VALUES('','a',100);
**
** The above statement says that the cost of inserting a letter 'a' is
** 100.  (All costs are integers.  We recommend that costs be scaled so
** that the average cost is around 100.)
**
**    INSERT INTO f(cFrom,cTo,Cost) VALUES('b','',87);
**
** The above statement says that the cost of deleting a single letter
** 'b' is 87.
**
**    INSERT INTO f(cFrom,cTo,Cost) VALUES('o','oe',38);
**    INSERT INTO f(cFrom,cTo,Cost) VALUES('oe','o',40);
**
** This third example says that the cost of transforming the single
** letter "o" into the two-letter sequence "oe" is 38 and that the
** cost of transforming "oe" back into "o" is 40.
**
** After all the transformation costs have been set, the fuzzer table
** can be queried as follows:
**
**    SELECT word, distance FROM f
**     WHERE word MATCH 'abcdefg'
**       AND distance<200;
**
** This first query outputs the string "abcdefg" and all strings that
** can be derived from that string by appling the specified transformations.
** The strings are output together with their total transformation cost
** (called "distance") and appear in order of increasing cost.  No string
** is output more than once.  If there are multiple ways to transform the
** target string into the output string then the lowest cost transform is
** the one that is returned.  In the example, the search is limited to 
** strings with a total distance of less than 200.
**
** It is important to put some kind of a limit on the fuzzer output.  This
** can be either in the form of a LIMIT clause at the end of the query,
** or better, a "distance<NNN" constraint where NNN is some number.  The
** running time and memory requirement is exponential in the value of NNN 
** so you want to make sure that NNN is not too big.  A value of NNN that
** is about twice the average transformation cost seems to give good results.
**
** The fuzzer table can be useful for tasks such as spelling correction.
** Suppose there is a second table vocabulary(w) where the w column contains
** all correctly spelled words.   Let $word be a word you want to look up.
**
**   SELECT vocabulary.w FROM f, vocabulary
**    WHERE f.word MATCH $word
**      AND f.distance<=200
**      AND f.word=vocabulary.w
**    LIMIT 20
**
** The query above gives the 20 closest words to the $word being tested.
** (Note that for good performance, the vocubulary.w column should be
** indexed.)
**
** A similar query can be used to find all words in the dictionary that
** begin with some prefix $prefix:
**
**   SELECT vocabulary.w FROM f, vocabulary
**    WHERE f.word MATCH $prefix
**      AND f.distance<=200
**      AND vocabulary.w BETWEEN f.word AND (f.word || x'F7BFBFBF')
**    LIMIT 50
**
** This last query will show up to 50 words out of the vocabulary that
** match or nearly match the $prefix.
*/
#include "sqlite4.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdio.h>

#ifndef SQLITE_OMIT_VIRTUALTABLE

/*
** Forward declaration of objects used by this implementation
*/
typedef struct fuzzer_vtab fuzzer_vtab;
typedef struct fuzzer_cursor fuzzer_cursor;
typedef struct fuzzer_rule fuzzer_rule;
typedef struct fuzzer_seen fuzzer_seen;
typedef struct fuzzer_stem fuzzer_stem;

/*
** Type of the "cost" of an edit operation.  Might be changed to
** "float" or "double" or "sqlite4_int64" in the future.
*/
typedef int fuzzer_cost;


/*
** Each transformation rule is stored as an instance of this object.
** All rules are kept on a linked list sorted by rCost.
*/
struct fuzzer_rule {
  fuzzer_rule *pNext;        /* Next rule in order of increasing rCost */
  fuzzer_cost rCost;         /* Cost of this transformation */
  int nFrom, nTo;            /* Length of the zFrom and zTo strings */
  char *zFrom;               /* Transform from */
  char zTo[4];               /* Transform to (extra space appended) */
};

/*
** A stem object is used to generate variants.  It is also used to record
** previously generated outputs.
**
** Every stem is added to a hash table as it is output.  Generation of
** duplicate stems is suppressed.
**
** Active stems (those that might generate new outputs) are kepts on a linked
** list sorted by increasing cost.  The cost is the sum of rBaseCost and
** pRule->rCost.
*/
struct fuzzer_stem {
  char *zBasis;              /* Word being fuzzed */
  int nBasis;                /* Length of the zBasis string */
  const fuzzer_rule *pRule;  /* Current rule to apply */
  int n;                     /* Apply pRule at this character offset */
  fuzzer_cost rBaseCost;     /* Base cost of getting to zBasis */
  fuzzer_cost rCostX;        /* Precomputed rBaseCost + pRule->rCost */
  fuzzer_stem *pNext;        /* Next stem in rCost order */
  fuzzer_stem *pHash;        /* Next stem with same hash on zBasis */
};

/* 
** A fuzzer virtual-table object 
*/
struct fuzzer_vtab {
  sqlite4_vtab base;         /* Base class - must be first */
  char *zClassName;          /* Name of this class.  Default: "fuzzer" */
  fuzzer_rule *pRule;        /* All active rules in this fuzzer */
  fuzzer_rule *pNewRule;     /* New rules to add when last cursor expires */
  int nCursor;               /* Number of active cursors */
};

#define FUZZER_HASH  4001    /* Hash table size */
#define FUZZER_NQUEUE  20    /* Number of slots on the stem queue */

/* A fuzzer cursor object */
struct fuzzer_cursor {
  sqlite4_vtab_cursor base;  /* Base class - must be first */
  sqlite4_int64 iRowid;      /* The rowid of the current word */
  fuzzer_vtab *pVtab;        /* The virtual table this cursor belongs to */
  fuzzer_cost rLimit;        /* Maximum cost of any term */
  fuzzer_stem *pStem;        /* Stem with smallest rCostX */
  fuzzer_stem *pDone;        /* Stems already processed to completion */
  fuzzer_stem *aQueue[FUZZER_NQUEUE];  /* Queue of stems with higher rCostX */
  int mxQueue;               /* Largest used index in aQueue[] */
  char *zBuf;                /* Temporary use buffer */
  int nBuf;                  /* Bytes allocated for zBuf */
  int nStem;                 /* Number of stems allocated */
  fuzzer_rule nullRule;      /* Null rule used first */
  fuzzer_stem *apHash[FUZZER_HASH]; /* Hash of previously generated terms */
};

/* Methods for the fuzzer module */
static int fuzzerConnect(
  sqlite4 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite4_vtab **ppVtab,
  char **pzErr
){
  fuzzer_vtab *pNew;
  int n;
  if( strcmp(argv[1],"temp")!=0 ){
    *pzErr = sqlite4_mprintf("%s virtual tables must be TEMP", argv[0]);
    return SQLITE_ERROR;
  }
  n = strlen(argv[0]) + 1;
  pNew = sqlite4_malloc( sizeof(*pNew) + n );
  if( pNew==0 ) return SQLITE_NOMEM;
  pNew->zClassName = (char*)&pNew[1];
  memcpy(pNew->zClassName, argv[0], n);
  sqlite4_declare_vtab(db, "CREATE TABLE x(word,distance,cFrom,cTo,cost)");
  memset(pNew, 0, sizeof(*pNew));
  *ppVtab = &pNew->base;
  return SQLITE_OK;
}
/* Note that for this virtual table, the xCreate and xConnect
** methods are identical. */

static int fuzzerDisconnect(sqlite4_vtab *pVtab){
  fuzzer_vtab *p = (fuzzer_vtab*)pVtab;
  assert( p->nCursor==0 );
  do{
    while( p->pRule ){
      fuzzer_rule *pRule = p->pRule;
      p->pRule = pRule->pNext;
      sqlite4_free(pRule);
    }
    p->pRule = p->pNewRule;
    p->pNewRule = 0;
  }while( p->pRule );
  sqlite4_free(p);
  return SQLITE_OK;
}
/* The xDisconnect and xDestroy methods are also the same */

/*
** The two input rule lists are both sorted in order of increasing
** cost.  Merge them together into a single list, sorted by cost, and
** return a pointer to the head of that list.
*/
static fuzzer_rule *fuzzerMergeRules(fuzzer_rule *pA, fuzzer_rule *pB){
  fuzzer_rule head;
  fuzzer_rule *pTail;

  pTail =  &head;
  while( pA && pB ){
    if( pA->rCost<=pB->rCost ){
      pTail->pNext = pA;
      pTail = pA;
      pA = pA->pNext;
    }else{
      pTail->pNext = pB;
      pTail = pB;
      pB = pB->pNext;
    }
  }
  if( pA==0 ){
    pTail->pNext = pB;
  }else{
    pTail->pNext = pA;
  }
  return head.pNext;
}


/*
** Open a new fuzzer cursor.
*/
static int fuzzerOpen(sqlite4_vtab *pVTab, sqlite4_vtab_cursor **ppCursor){
  fuzzer_vtab *p = (fuzzer_vtab*)pVTab;
  fuzzer_cursor *pCur;
  pCur = sqlite4_malloc( sizeof(*pCur) );
  if( pCur==0 ) return SQLITE_NOMEM;
  memset(pCur, 0, sizeof(*pCur));
  pCur->pVtab = p;
  *ppCursor = &pCur->base;
  if( p->nCursor==0 && p->pNewRule ){
    unsigned int i;
    fuzzer_rule *pX;
    fuzzer_rule *a[15];
    for(i=0; i<sizeof(a)/sizeof(a[0]); i++) a[i] = 0;
    while( (pX = p->pNewRule)!=0 ){
      p->pNewRule = pX->pNext;
      pX->pNext = 0;
      for(i=0; a[i] && i<sizeof(a)/sizeof(a[0])-1; i++){
        pX = fuzzerMergeRules(a[i], pX);
        a[i] = 0;
      }
      a[i] = fuzzerMergeRules(a[i], pX);
    }
    for(pX=a[0], i=1; i<sizeof(a)/sizeof(a[0]); i++){
      pX = fuzzerMergeRules(a[i], pX);
    }
    p->pRule = fuzzerMergeRules(p->pRule, pX);
  }
  p->nCursor++;
  return SQLITE_OK;
}

/*
** Free all stems in a list.
*/
static void fuzzerClearStemList(fuzzer_stem *pStem){
  while( pStem ){
    fuzzer_stem *pNext = pStem->pNext;
    sqlite4_free(pStem);
    pStem = pNext;
  }
}

/*
** Free up all the memory allocated by a cursor.  Set it rLimit to 0
** to indicate that it is at EOF.
*/
static void fuzzerClearCursor(fuzzer_cursor *pCur, int clearHash){
  int i;
  fuzzerClearStemList(pCur->pStem);
  fuzzerClearStemList(pCur->pDone);
  for(i=0; i<FUZZER_NQUEUE; i++) fuzzerClearStemList(pCur->aQueue[i]);
  pCur->rLimit = (fuzzer_cost)0;
  if( clearHash && pCur->nStem ){
    pCur->mxQueue = 0;
    pCur->pStem = 0;
    pCur->pDone = 0;
    memset(pCur->aQueue, 0, sizeof(pCur->aQueue));
    memset(pCur->apHash, 0, sizeof(pCur->apHash));
  }
  pCur->nStem = 0;
}

/*
** Close a fuzzer cursor.
*/
static int fuzzerClose(sqlite4_vtab_cursor *cur){
  fuzzer_cursor *pCur = (fuzzer_cursor *)cur;
  fuzzerClearCursor(pCur, 0);
  sqlite4_free(pCur->zBuf);
  pCur->pVtab->nCursor--;
  sqlite4_free(pCur);
  return SQLITE_OK;
}

/*
** Compute the current output term for a fuzzer_stem.
*/
static int fuzzerRender(
  fuzzer_stem *pStem,   /* The stem to be rendered */
  char **pzBuf,         /* Write results into this buffer.  realloc if needed */
  int *pnBuf            /* Size of the buffer */
){
  const fuzzer_rule *pRule = pStem->pRule;
  int n;
  char *z;

  n = pStem->nBasis + pRule->nTo - pRule->nFrom;
  if( (*pnBuf)<n+1 ){
    (*pzBuf) = sqlite4_realloc((*pzBuf), n+100);
    if( (*pzBuf)==0 ) return SQLITE_NOMEM;
    (*pnBuf) = n+100;
  }
  n = pStem->n;
  z = *pzBuf;
  if( n<0 ){
    memcpy(z, pStem->zBasis, pStem->nBasis+1);
  }else{
    memcpy(z, pStem->zBasis, n);
    memcpy(&z[n], pRule->zTo, pRule->nTo);
    memcpy(&z[n+pRule->nTo], &pStem->zBasis[n+pRule->nFrom], 
           pStem->nBasis-n-pRule->nFrom+1);
  }
  return SQLITE_OK;
}

/*
** Compute a hash on zBasis.
*/
static unsigned int fuzzerHash(const char *z){
  unsigned int h = 0;
  while( *z ){ h = (h<<3) ^ (h>>29) ^ *(z++); }
  return h % FUZZER_HASH;
}

/*
** Current cost of a stem
*/
static fuzzer_cost fuzzerCost(fuzzer_stem *pStem){
  return pStem->rCostX = pStem->rBaseCost + pStem->pRule->rCost;
}

#if 0
/*
** Print a description of a fuzzer_stem on stderr.
*/
static void fuzzerStemPrint(
  const char *zPrefix,
  fuzzer_stem *pStem,
  const char *zSuffix
){
  if( pStem->n<0 ){
    fprintf(stderr, "%s[%s](%d)-->self%s",
       zPrefix,
       pStem->zBasis, pStem->rBaseCost,
       zSuffix
    );
  }else{
    char *zBuf = 0;
    int nBuf = 0;
    if( fuzzerRender(pStem, &zBuf, &nBuf)!=SQLITE_OK ) return;
    fprintf(stderr, "%s[%s](%d)-->{%s}(%d)%s",
      zPrefix,
      pStem->zBasis, pStem->rBaseCost, zBuf, pStem->,
      zSuffix
    );
    sqlite4_free(zBuf);
  }
}
#endif

/*
** Return 1 if the string to which the cursor is point has already
** been emitted.  Return 0 if not.  Return -1 on a memory allocation
** failures.
*/
static int fuzzerSeen(fuzzer_cursor *pCur, fuzzer_stem *pStem){
  unsigned int h;
  fuzzer_stem *pLookup;

  if( fuzzerRender(pStem, &pCur->zBuf, &pCur->nBuf)==SQLITE_NOMEM ){
    return -1;
  }
  h = fuzzerHash(pCur->zBuf);
  pLookup = pCur->apHash[h];
    while( pLookup && strcmp(pLookup->zBasis, pCur->zBuf)!=0 ){
    pLookup = pLookup->pHash;
  }
  return pLookup!=0;
}

/*
** Advance a fuzzer_stem to its next value.   Return 0 if there are
** no more values that can be generated by this fuzzer_stem.  Return
** -1 on a memory allocation failure.
*/
static int fuzzerAdvance(fuzzer_cursor *pCur, fuzzer_stem *pStem){
  const fuzzer_rule *pRule;
  while( (pRule = pStem->pRule)!=0 ){
    while( pStem->n < pStem->nBasis - pRule->nFrom ){
      pStem->n++;
      if( pRule->nFrom==0
       || memcmp(&pStem->zBasis[pStem->n], pRule->zFrom, pRule->nFrom)==0
      ){
        /* Found a rewrite case.  Make sure it is not a duplicate */
        int rc = fuzzerSeen(pCur, pStem);
        if( rc<0 ) return -1;
        if( rc==0 ){
          fuzzerCost(pStem);
          return 1;
        }
      }
    }
    pStem->n = -1;
    pStem->pRule = pRule->pNext;
    if( pStem->pRule && fuzzerCost(pStem)>pCur->rLimit ) pStem->pRule = 0;
  }
  return 0;
}

/*
** The two input stem lists are both sorted in order of increasing
** rCostX.  Merge them together into a single list, sorted by rCostX, and
** return a pointer to the head of that new list.
*/
static fuzzer_stem *fuzzerMergeStems(fuzzer_stem *pA, fuzzer_stem *pB){
  fuzzer_stem head;
  fuzzer_stem *pTail;

  pTail =  &head;
  while( pA && pB ){
    if( pA->rCostX<=pB->rCostX ){
      pTail->pNext = pA;
      pTail = pA;
      pA = pA->pNext;
    }else{
      pTail->pNext = pB;
      pTail = pB;
      pB = pB->pNext;
    }
  }
  if( pA==0 ){
    pTail->pNext = pB;
  }else{
    pTail->pNext = pA;
  }
  return head.pNext;
}

/*
** Load pCur->pStem with the lowest-cost stem.  Return a pointer
** to the lowest-cost stem.
*/
static fuzzer_stem *fuzzerLowestCostStem(fuzzer_cursor *pCur){
  fuzzer_stem *pBest, *pX;
  int iBest;
  int i;

  if( pCur->pStem==0 ){
    iBest = -1;
    pBest = 0;
    for(i=0; i<=pCur->mxQueue; i++){
      pX = pCur->aQueue[i];
      if( pX==0 ) continue;
      if( pBest==0 || pBest->rCostX>pX->rCostX ){
        pBest = pX;
        iBest = i;
      }
    } 
    if( pBest ){
      pCur->aQueue[iBest] = pBest->pNext;
      pBest->pNext = 0;
      pCur->pStem = pBest;
    }
  }
  return pCur->pStem;
}

/*
** Insert pNew into queue of pending stems.  Then find the stem
** with the lowest rCostX and move it into pCur->pStem.
** list.  The insert is done such the pNew is in the correct order
** according to fuzzer_stem.zBaseCost+fuzzer_stem.pRule->rCost.
*/
static fuzzer_stem *fuzzerInsert(fuzzer_cursor *pCur, fuzzer_stem *pNew){
  fuzzer_stem *pX;
  int i;

  /* If pCur->pStem exists and is greater than pNew, then make pNew
  ** the new pCur->pStem and insert the old pCur->pStem instead.
  */
  if( (pX = pCur->pStem)!=0 && pX->rCostX>pNew->rCostX ){
    pNew->pNext = 0;
    pCur->pStem = pNew;
    pNew = pX;
  }

  /* Insert the new value */
  pNew->pNext = 0;
  pX = pNew;
  for(i=0; i<=pCur->mxQueue; i++){
    if( pCur->aQueue[i] ){
      pX = fuzzerMergeStems(pX, pCur->aQueue[i]);
      pCur->aQueue[i] = 0;
    }else{
      pCur->aQueue[i] = pX;
      break;
    }
  }
  if( i>pCur->mxQueue ){
    if( i<FUZZER_NQUEUE ){
      pCur->mxQueue = i;
      pCur->aQueue[i] = pX;
    }else{
      assert( pCur->mxQueue==FUZZER_NQUEUE-1 );
      pX = fuzzerMergeStems(pX, pCur->aQueue[FUZZER_NQUEUE-1]);
      pCur->aQueue[FUZZER_NQUEUE-1] = pX;
    }
  }

  return fuzzerLowestCostStem(pCur);
}

/*
** Allocate a new fuzzer_stem.  Add it to the hash table but do not
** link it into either the pCur->pStem or pCur->pDone lists.
*/
static fuzzer_stem *fuzzerNewStem(
  fuzzer_cursor *pCur,
  const char *zWord,
  fuzzer_cost rBaseCost
){
  fuzzer_stem *pNew;
  unsigned int h;

  pNew = sqlite4_malloc( sizeof(*pNew) + strlen(zWord) + 1 );
  if( pNew==0 ) return 0;
  memset(pNew, 0, sizeof(*pNew));
  pNew->zBasis = (char*)&pNew[1];
  pNew->nBasis = strlen(zWord);
  memcpy(pNew->zBasis, zWord, pNew->nBasis+1);
  pNew->pRule = pCur->pVtab->pRule;
  pNew->n = -1;
  pNew->rBaseCost = pNew->rCostX = rBaseCost;
  h = fuzzerHash(pNew->zBasis);
  pNew->pHash = pCur->apHash[h];
  pCur->apHash[h] = pNew;
  pCur->nStem++;
  return pNew;
}


/*
** Advance a cursor to its next row of output
*/
static int fuzzerNext(sqlite4_vtab_cursor *cur){
  fuzzer_cursor *pCur = (fuzzer_cursor*)cur;
  int rc;
  fuzzer_stem *pStem, *pNew;

  pCur->iRowid++;

  /* Use the element the cursor is currently point to to create
  ** a new stem and insert the new stem into the priority queue.
  */
  pStem = pCur->pStem;
  if( pStem->rCostX>0 ){
    rc = fuzzerRender(pStem, &pCur->zBuf, &pCur->nBuf);
    if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
    pNew = fuzzerNewStem(pCur, pCur->zBuf, pStem->rCostX);
    if( pNew ){
      if( fuzzerAdvance(pCur, pNew)==0 ){
        pNew->pNext = pCur->pDone;
        pCur->pDone = pNew;
      }else{
        if( fuzzerInsert(pCur, pNew)==pNew ){
          return SQLITE_OK;
        }
      }
    }else{
      return SQLITE_NOMEM;
    }
  }

  /* Adjust the priority queue so that the first element of the
  ** stem list is the next lowest cost word.
  */
  while( (pStem = pCur->pStem)!=0 ){
    if( fuzzerAdvance(pCur, pStem) ){
      pCur->pStem = 0;
      pStem = fuzzerInsert(pCur, pStem);
      if( (rc = fuzzerSeen(pCur, pStem))!=0 ){
        if( rc<0 ) return SQLITE_NOMEM;
        continue;
      }
      return SQLITE_OK;  /* New word found */
    }
    pCur->pStem = 0;
    pStem->pNext = pCur->pDone;
    pCur->pDone = pStem;
    if( fuzzerLowestCostStem(pCur) ){
      rc = fuzzerSeen(pCur, pCur->pStem);
      if( rc<0 ) return SQLITE_NOMEM;
      if( rc==0 ){
        return SQLITE_OK;
      }
    }
  }

  /* Reach this point only if queue has been exhausted and there is
  ** nothing left to be output. */
  pCur->rLimit = (fuzzer_cost)0;
  return SQLITE_OK;
}

/*
** Called to "rewind" a cursor back to the beginning so that
** it starts its output over again.  Always called at least once
** prior to any fuzzerColumn, fuzzerRowid, or fuzzerEof call.
*/
static int fuzzerFilter(
  sqlite4_vtab_cursor *pVtabCursor, 
  int idxNum, const char *idxStr,
  int argc, sqlite4_value **argv
){
  fuzzer_cursor *pCur = (fuzzer_cursor *)pVtabCursor;
  const char *zWord = 0;
  fuzzer_stem *pStem;

  fuzzerClearCursor(pCur, 1);
  pCur->rLimit = 2147483647;
  if( idxNum==1 ){
    zWord = (const char*)sqlite4_value_text(argv[0]);
  }else if( idxNum==2 ){
    pCur->rLimit = (fuzzer_cost)sqlite4_value_int(argv[0]);
  }else if( idxNum==3 ){
    zWord = (const char*)sqlite4_value_text(argv[0]);
    pCur->rLimit = (fuzzer_cost)sqlite4_value_int(argv[1]);
  }
  if( zWord==0 ) zWord = "";
  pCur->pStem = pStem = fuzzerNewStem(pCur, zWord, (fuzzer_cost)0);
  if( pStem==0 ) return SQLITE_NOMEM;
  pCur->nullRule.pNext = pCur->pVtab->pRule;
  pCur->nullRule.rCost = 0;
  pCur->nullRule.nFrom = 0;
  pCur->nullRule.nTo = 0;
  pCur->nullRule.zFrom = "";
  pStem->pRule = &pCur->nullRule;
  pStem->n = pStem->nBasis;
  pCur->iRowid = 1;
  return SQLITE_OK;
}

/*
** Only the word and distance columns have values.  All other columns
** return NULL
*/
static int fuzzerColumn(sqlite4_vtab_cursor *cur, sqlite4_context *ctx, int i){
  fuzzer_cursor *pCur = (fuzzer_cursor*)cur;
  if( i==0 ){
    /* the "word" column */
    if( fuzzerRender(pCur->pStem, &pCur->zBuf, &pCur->nBuf)==SQLITE_NOMEM ){
      return SQLITE_NOMEM;
    }
    sqlite4_result_text(ctx, pCur->zBuf, -1, SQLITE_TRANSIENT);
  }else if( i==1 ){
    /* the "distance" column */
    sqlite4_result_int(ctx, pCur->pStem->rCostX);
  }else{
    /* All other columns are NULL */
    sqlite4_result_null(ctx);
  }
  return SQLITE_OK;
}

/*
** The rowid.
*/
static int fuzzerRowid(sqlite4_vtab_cursor *cur, sqlite_int64 *pRowid){
  fuzzer_cursor *pCur = (fuzzer_cursor*)cur;
  *pRowid = pCur->iRowid;
  return SQLITE_OK;
}

/*
** When the fuzzer_cursor.rLimit value is 0 or less, that is a signal
** that the cursor has nothing more to output.
*/
static int fuzzerEof(sqlite4_vtab_cursor *cur){
  fuzzer_cursor *pCur = (fuzzer_cursor*)cur;
  return pCur->rLimit<=(fuzzer_cost)0;
}

/*
** Search for terms of these forms:
**
**       word MATCH $str
**       distance < $value
**       distance <= $value
**
** The distance< and distance<= are both treated as distance<=.
** The query plan number is as follows:
**
**   0:    None of the terms above are found
**   1:    There is a "word MATCH" term with $str in filter.argv[0].
**   2:    There is a "distance<" term with $value in filter.argv[0].
**   3:    Both "word MATCH" and "distance<" with $str in argv[0] and
**         $value in argv[1].
*/
static int fuzzerBestIndex(sqlite4_vtab *tab, sqlite4_index_info *pIdxInfo){
  int iPlan = 0;
  int iDistTerm = -1;
  int i;
  const struct sqlite4_index_constraint *pConstraint;
  pConstraint = pIdxInfo->aConstraint;
  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
    if( pConstraint->usable==0 ) continue;
    if( (iPlan & 1)==0 
     && pConstraint->iColumn==0
     && pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH
    ){
      iPlan |= 1;
      pIdxInfo->aConstraintUsage[i].argvIndex = 1;
      pIdxInfo->aConstraintUsage[i].omit = 1;
    }
    if( (iPlan & 2)==0
     && pConstraint->iColumn==1
     && (pConstraint->op==SQLITE_INDEX_CONSTRAINT_LT
           || pConstraint->op==SQLITE_INDEX_CONSTRAINT_LE)
    ){
      iPlan |= 2;
      iDistTerm = i;
    }
  }
  if( iPlan==2 ){
    pIdxInfo->aConstraintUsage[iDistTerm].argvIndex = 1;
  }else if( iPlan==3 ){
    pIdxInfo->aConstraintUsage[iDistTerm].argvIndex = 2;
  }
  pIdxInfo->idxNum = iPlan;
  if( pIdxInfo->nOrderBy==1
   && pIdxInfo->aOrderBy[0].iColumn==1
   && pIdxInfo->aOrderBy[0].desc==0
  ){
    pIdxInfo->orderByConsumed = 1;
  }
  pIdxInfo->estimatedCost = (double)10000;
   
  return SQLITE_OK;
}

/*
** Disallow all attempts to DELETE or UPDATE.  Only INSERTs are allowed.
**
** On an insert, the cFrom, cTo, and cost columns are used to construct
** a new rule.   All other columns are ignored.  The rule is ignored
** if cFrom and cTo are identical.  A NULL value for cFrom or cTo is
** interpreted as an empty string.  The cost must be positive.
*/
static int fuzzerUpdate(
  sqlite4_vtab *pVTab,
  int argc,
  sqlite4_value **argv,
  sqlite_int64 *pRowid
){
  fuzzer_vtab *p = (fuzzer_vtab*)pVTab;
  fuzzer_rule *pRule;
  const char *zFrom;
  int nFrom;
  const char *zTo;
  int nTo;
  fuzzer_cost rCost;
  if( argc!=7 ){
    sqlite4_free(pVTab->zErrMsg);
    pVTab->zErrMsg = sqlite4_mprintf("cannot delete from a %s virtual table",
                                     p->zClassName);
    return SQLITE_CONSTRAINT;
  }
  if( sqlite4_value_type(argv[0])!=SQLITE_NULL ){
    sqlite4_free(pVTab->zErrMsg);
    pVTab->zErrMsg = sqlite4_mprintf("cannot update a %s virtual table",
                                     p->zClassName);
    return SQLITE_CONSTRAINT;
  }
  zFrom = (char*)sqlite4_value_text(argv[4]);
  if( zFrom==0 ) zFrom = "";
  zTo = (char*)sqlite4_value_text(argv[5]);
  if( zTo==0 ) zTo = "";
  if( strcmp(zFrom,zTo)==0 ){
    /* Silently ignore null transformations */
    return SQLITE_OK;
  }
  rCost = sqlite4_value_int(argv[6]);
  if( rCost<=0 ){
    sqlite4_free(pVTab->zErrMsg);
    pVTab->zErrMsg = sqlite4_mprintf("cost must be positive");
    return SQLITE_CONSTRAINT;    
  }
  nFrom = strlen(zFrom);
  nTo = strlen(zTo);
  pRule = sqlite4_malloc( sizeof(*pRule) + nFrom + nTo );
  if( pRule==0 ){
    return SQLITE_NOMEM;
  }
  pRule->zFrom = &pRule->zTo[nTo+1];
  pRule->nFrom = nFrom;
  memcpy(pRule->zFrom, zFrom, nFrom+1);
  memcpy(pRule->zTo, zTo, nTo+1);
  pRule->nTo = nTo;
  pRule->rCost = rCost;
  pRule->pNext = p->pNewRule;
  p->pNewRule = pRule;
  return SQLITE_OK;
}

/*
** A virtual table module that provides read-only access to a
** Tcl global variable namespace.
*/
static sqlite4_module fuzzerModule = {
  0,                           /* iVersion */
  fuzzerConnect,
  fuzzerConnect,
  fuzzerBestIndex,
  fuzzerDisconnect, 
  fuzzerDisconnect,
  fuzzerOpen,                  /* xOpen - open a cursor */
  fuzzerClose,                 /* xClose - close a cursor */
  fuzzerFilter,                /* xFilter - configure scan constraints */
  fuzzerNext,                  /* xNext - advance a cursor */
  fuzzerEof,                   /* xEof - check for end of scan */
  fuzzerColumn,                /* xColumn - read data */
  fuzzerRowid,                 /* xRowid - read data */
  fuzzerUpdate,                /* xUpdate - INSERT */
  0,                           /* xBegin */
  0,                           /* xSync */
  0,                           /* xCommit */
  0,                           /* xRollback */
  0,                           /* xFindMethod */
  0,                           /* xRename */
};

#endif /* SQLITE_OMIT_VIRTUALTABLE */


/*
** Register the fuzzer virtual table
*/
int fuzzer_register(sqlite4 *db){
  int rc = SQLITE_OK;
#ifndef SQLITE_OMIT_VIRTUALTABLE
  rc = sqlite4_create_module(db, "fuzzer", &fuzzerModule, 0);
#endif
  return rc;
}

#ifdef SQLITE_TEST
#include <tcl.h>
/*
** Decode a pointer to an sqlite4 object.
*/
extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite4 **ppDb);

/*
** Register the echo virtual table module.
*/
static int register_fuzzer_module(
  ClientData clientData, /* Pointer to sqlite4_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite4 *db;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  fuzzer_register(db);
  return TCL_OK;
}


/*
** Register commands with the TCL interpreter.
*/
int Sqlitetestfuzzer_Init(Tcl_Interp *interp){
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
     void *clientData;
  } aObjCmd[] = {
     { "register_fuzzer_module",   register_fuzzer_module, 0 },
  };
  int i;
  for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
    Tcl_CreateObjCommand(interp, aObjCmd[i].zName, 
        aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
  }
  return TCL_OK;
}

#endif /* SQLITE_TEST */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Changes to test/test_hexio.c.

109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
...
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
...
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
...
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
...
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
...
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
  if( objc!=4 ){
    Tcl_WrongNumArgs(interp, 1, objv, "FILENAME OFFSET AMT");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[2], &offset) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[3], &amt) ) return TCL_ERROR;
  zFile = Tcl_GetString(objv[1]);
  zBuf = sqlite4_malloc( amt*2+1 );
  if( zBuf==0 ){
    return TCL_ERROR;
  }
  in = fopen(zFile, "rb");
  if( in==0 ){
    in = fopen(zFile, "r");
  }
................................................................................
  got = fread(zBuf, 1, amt, in);
  fclose(in);
  if( got<0 ){
    got = 0;
  }
  sqlite4TestBinToHex(zBuf, got);
  Tcl_AppendResult(interp, zBuf, 0);
  sqlite4_free(zBuf);
  return TCL_OK;
}


/*
** Usage:   hexio_write  FILENAME  OFFSET  DATA
**
................................................................................
  if( objc!=4 ){
    Tcl_WrongNumArgs(interp, 1, objv, "FILENAME OFFSET HEXDATA");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[2], &offset) ) return TCL_ERROR;
  zFile = Tcl_GetString(objv[1]);
  zIn = (const unsigned char *)Tcl_GetStringFromObj(objv[3], &nIn);
  aOut = sqlite4_malloc( nIn/2 );
  if( aOut==0 ){
    return TCL_ERROR;
  }
  nOut = sqlite4TestHexToBin(zIn, nIn, aOut);
  out = fopen(zFile, "r+b");
  if( out==0 ){
    out = fopen(zFile, "r+");
................................................................................
  }
  if( out==0 ){
    Tcl_AppendResult(interp, "cannot open output file ", zFile, 0);
    return TCL_ERROR;
  }
  fseek(out, offset, SEEK_SET);
  written = fwrite(aOut, 1, nOut, out);
  sqlite4_free(aOut);
  fclose(out);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(written));
  return TCL_OK;
}

/*
** USAGE:   hexio_get_int   HEXDATA
................................................................................
  unsigned char aNum[4];

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "HEXDATA");
    return TCL_ERROR;
  }
  zIn = (const unsigned char *)Tcl_GetStringFromObj(objv[1], &nIn);
  aOut = sqlite4_malloc( nIn/2 );
  if( aOut==0 ){
    return TCL_ERROR;
  }
  nOut = sqlite4TestHexToBin(zIn, nIn, aOut);
  if( nOut>=4 ){
    memcpy(aNum, aOut, 4);
  }else{
    memset(aNum, 0, sizeof(aNum));
    memcpy(&aNum[4-nOut], aOut, nOut);
  }
  sqlite4_free(aOut);
  val = (aNum[0]<<24) | (aNum[1]<<16) | (aNum[2]<<8) | aNum[3];
  Tcl_SetObjResult(interp, Tcl_NewIntObj(val));
  return TCL_OK;
}


/*
................................................................................
  const unsigned char *zOrig;
  unsigned char *z;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "HEX");
    return TCL_ERROR;
  }
  zOrig = (unsigned char *)Tcl_GetStringFromObj(objv[1], &n);
  z = sqlite4_malloc( n+3 );
  n = sqlite4TestHexToBin(zOrig, n, z);
  z[n] = 0;
  nOut = sqlite4Utf8To8(z);
  sqlite4TestBinToHex(z,nOut);
  Tcl_AppendResult(interp, (char*)z, 0);
  sqlite4_free(z);
  return TCL_OK;
#else
  Tcl_AppendResult(interp, 
      "[utf8_to_utf8] unavailable - SQLITE_DEBUG not defined", 0
  );
  return TCL_ERROR;
#endif







|







 







|







 







|







 







|







 







|










|







 







|





|







109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
...
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
...
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
...
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
...
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
...
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
  if( objc!=4 ){
    Tcl_WrongNumArgs(interp, 1, objv, "FILENAME OFFSET AMT");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[2], &offset) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[3], &amt) ) return TCL_ERROR;
  zFile = Tcl_GetString(objv[1]);
  zBuf = sqlite4_malloc(0, amt*2+1 );
  if( zBuf==0 ){
    return TCL_ERROR;
  }
  in = fopen(zFile, "rb");
  if( in==0 ){
    in = fopen(zFile, "r");
  }
................................................................................
  got = fread(zBuf, 1, amt, in);
  fclose(in);
  if( got<0 ){
    got = 0;
  }
  sqlite4TestBinToHex(zBuf, got);
  Tcl_AppendResult(interp, zBuf, 0);
  sqlite4_free(0, zBuf);
  return TCL_OK;
}


/*
** Usage:   hexio_write  FILENAME  OFFSET  DATA
**
................................................................................
  if( objc!=4 ){
    Tcl_WrongNumArgs(interp, 1, objv, "FILENAME OFFSET HEXDATA");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[2], &offset) ) return TCL_ERROR;
  zFile = Tcl_GetString(objv[1]);
  zIn = (const unsigned char *)Tcl_GetStringFromObj(objv[3], &nIn);
  aOut = sqlite4_malloc(0, nIn/2 );
  if( aOut==0 ){
    return TCL_ERROR;
  }
  nOut = sqlite4TestHexToBin(zIn, nIn, aOut);
  out = fopen(zFile, "r+b");
  if( out==0 ){
    out = fopen(zFile, "r+");
................................................................................
  }
  if( out==0 ){
    Tcl_AppendResult(interp, "cannot open output file ", zFile, 0);
    return TCL_ERROR;
  }
  fseek(out, offset, SEEK_SET);
  written = fwrite(aOut, 1, nOut, out);
  sqlite4_free(0, aOut);
  fclose(out);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(written));
  return TCL_OK;
}

/*
** USAGE:   hexio_get_int   HEXDATA
................................................................................
  unsigned char aNum[4];

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "HEXDATA");
    return TCL_ERROR;
  }
  zIn = (const unsigned char *)Tcl_GetStringFromObj(objv[1], &nIn);
  aOut = sqlite4_malloc(0, nIn/2 );
  if( aOut==0 ){
    return TCL_ERROR;
  }
  nOut = sqlite4TestHexToBin(zIn, nIn, aOut);
  if( nOut>=4 ){
    memcpy(aNum, aOut, 4);
  }else{
    memset(aNum, 0, sizeof(aNum));
    memcpy(&aNum[4-nOut], aOut, nOut);
  }
  sqlite4_free(0, aOut);
  val = (aNum[0]<<24) | (aNum[1]<<16) | (aNum[2]<<8) | aNum[3];
  Tcl_SetObjResult(interp, Tcl_NewIntObj(val));
  return TCL_OK;
}


/*
................................................................................
  const unsigned char *zOrig;
  unsigned char *z;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "HEX");
    return TCL_ERROR;
  }
  zOrig = (unsigned char *)Tcl_GetStringFromObj(objv[1], &n);
  z = sqlite4_malloc(0, n+3 );
  n = sqlite4TestHexToBin(zOrig, n, z);
  z[n] = 0;
  nOut = sqlite4Utf8To8(z);
  sqlite4TestBinToHex(z,nOut);
  Tcl_AppendResult(interp, (char*)z, 0);
  sqlite4_free(0, z);
  return TCL_OK;
#else
  Tcl_AppendResult(interp, 
      "[utf8_to_utf8] unavailable - SQLITE_DEBUG not defined", 0
  );
  return TCL_ERROR;
#endif

Deleted test/test_intarray.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/*
** 2009 November 10
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file implements a read-only VIRTUAL TABLE that contains the
** content of a C-language array of integer values.  See the corresponding
** header file for full details.
*/
#include "test_intarray.h"
#include <string.h>
#include <assert.h>


/*
** Definition of the sqlite4_intarray object.
**
** The internal representation of an intarray object is subject
** to change, is not externally visible, and should be used by
** the implementation of intarray only.  This object is opaque
** to users.
*/
struct sqlite4_intarray {
  int n;                    /* Number of elements in the array */
  sqlite4_int64 *a;         /* Contents of the array */
  void (*xFree)(void*);     /* Function used to free a[] */
};

/* Objects used internally by the virtual table implementation */
typedef struct intarray_vtab intarray_vtab;
typedef struct intarray_cursor intarray_cursor;

/* A intarray table object */
struct intarray_vtab {
  sqlite4_vtab base;            /* Base class */
  sqlite4_intarray *pContent;   /* Content of the integer array */
};

/* A intarray cursor object */
struct intarray_cursor {
  sqlite4_vtab_cursor base;    /* Base class */
  int i;                       /* Current cursor position */
};

/*
** None of this works unless we have virtual tables.
*/
#ifndef SQLITE_OMIT_VIRTUALTABLE

/*
** Free an sqlite4_intarray object.
*/
static void intarrayFree(sqlite4_intarray *p){
  if( p->xFree ){
    p->xFree(p->a);
  }
  sqlite4_free(p);
}

/*
** Table destructor for the intarray module.
*/
static int intarrayDestroy(sqlite4_vtab *p){
  intarray_vtab *pVtab = (intarray_vtab*)p;
  sqlite4_free(pVtab);
  return 0;
}

/*
** Table constructor for the intarray module.
*/
static int intarrayCreate(
  sqlite4 *db,              /* Database where module is created */
  void *pAux,               /* clientdata for the module */
  int argc,                 /* Number of arguments */
  const char *const*argv,   /* Value for all arguments */
  sqlite4_vtab **ppVtab,    /* Write the new virtual table object here */
  char **pzErr              /* Put error message text here */
){
  int rc = SQLITE_NOMEM;
  intarray_vtab *pVtab = sqlite4_malloc(sizeof(intarray_vtab));

  if( pVtab ){
    memset(pVtab, 0, sizeof(intarray_vtab));
    pVtab->pContent = (sqlite4_intarray*)pAux;
    rc = sqlite4_declare_vtab(db, "CREATE TABLE x(value INTEGER PRIMARY KEY)");
  }
  *ppVtab = (sqlite4_vtab *)pVtab;
  return rc;
}

/*
** Open a new cursor on the intarray table.
*/
static int intarrayOpen(sqlite4_vtab *pVTab, sqlite4_vtab_cursor **ppCursor){
  int rc = SQLITE_NOMEM;
  intarray_cursor *pCur;
  pCur = sqlite4_malloc(sizeof(intarray_cursor));
  if( pCur ){
    memset(pCur, 0, sizeof(intarray_cursor));
    *ppCursor = (sqlite4_vtab_cursor *)pCur;
    rc = SQLITE_OK;
  }
  return rc;
}

/*
** Close a intarray table cursor.
*/
static int intarrayClose(sqlite4_vtab_cursor *cur){
  intarray_cursor *pCur = (intarray_cursor *)cur;
  sqlite4_free(pCur);
  return SQLITE_OK;
}

/*
** Retrieve a column of data.
*/
static int intarrayColumn(sqlite4_vtab_cursor *cur, sqlite4_context *ctx, int i){
  intarray_cursor *pCur = (intarray_cursor*)cur;
  intarray_vtab *pVtab = (intarray_vtab*)cur->pVtab;
  if( pCur->i>=0 && pCur->i<pVtab->pContent->n ){
    sqlite4_result_int64(ctx, pVtab->pContent->a[pCur->i]);
  }
  return SQLITE_OK;
}

/*
** Retrieve the current rowid.
*/
static int intarrayRowid(sqlite4_vtab_cursor *cur, sqlite_int64 *pRowid){
  intarray_cursor *pCur = (intarray_cursor *)cur;
  *pRowid = pCur->i;
  return SQLITE_OK;
}

static int intarrayEof(sqlite4_vtab_cursor *cur){
  intarray_cursor *pCur = (intarray_cursor *)cur;
  intarray_vtab *pVtab = (intarray_vtab *)cur->pVtab;
  return pCur->i>=pVtab->pContent->n;
}

/*
** Advance the cursor to the next row.
*/
static int intarrayNext(sqlite4_vtab_cursor *cur){
  intarray_cursor *pCur = (intarray_cursor *)cur;
  pCur->i++;
  return SQLITE_OK;
}

/*
** Reset a intarray table cursor.
*/
static int intarrayFilter(
  sqlite4_vtab_cursor *pVtabCursor, 
  int idxNum, const char *idxStr,
  int argc, sqlite4_value **argv
){
  intarray_cursor *pCur = (intarray_cursor *)pVtabCursor;
  pCur->i = 0;
  return SQLITE_OK;
}

/*
** Analyse the WHERE condition.
*/
static int intarrayBestIndex(sqlite4_vtab *tab, sqlite4_index_info *pIdxInfo){
  return SQLITE_OK;
}

/*
** A virtual table module that merely echos method calls into TCL
** variables.
*/
static sqlite4_module intarrayModule = {
  0,                           /* iVersion */
  intarrayCreate,              /* xCreate - create a new virtual table */
  intarrayCreate,              /* xConnect - connect to an existing vtab */
  intarrayBestIndex,           /* xBestIndex - find the best query index */
  intarrayDestroy,             /* xDisconnect - disconnect a vtab */
  intarrayDestroy,             /* xDestroy - destroy a vtab */
  intarrayOpen,                /* xOpen - open a cursor */
  intarrayClose,               /* xClose - close a cursor */
  intarrayFilter,              /* xFilter - configure scan constraints */
  intarrayNext,                /* xNext - advance a cursor */
  intarrayEof,                 /* xEof */
  intarrayColumn,              /* xColumn - read data */
  intarrayRowid,               /* xRowid - read data */
  0,                           /* xUpdate */
  0,                           /* xBegin */
  0,                           /* xSync */
  0,                           /* xCommit */
  0,                           /* xRollback */
  0,                           /* xFindMethod */
  0,                           /* xRename */
};

#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */

/*
** Invoke this routine to create a specific instance of an intarray object.
** The new intarray object is returned by the 3rd parameter.
**
** Each intarray object corresponds to a virtual table in the TEMP table
** with a name of zName.
**
** Destroy the intarray object by dropping the virtual table.  If not done
** explicitly by the application, the virtual table will be dropped implicitly
** by the system when the database connection is closed.
*/
int sqlite4_intarray_create(
  sqlite4 *db,
  const char *zName,
  sqlite4_intarray **ppReturn
){
  int rc = SQLITE_OK;
#ifndef SQLITE_OMIT_VIRTUALTABLE
  sqlite4_intarray *p;

  *ppReturn = p = sqlite4_malloc( sizeof(*p) );
  if( p==0 ){
    return SQLITE_NOMEM;
  }
  memset(p, 0, sizeof(*p));
  rc = sqlite4_create_module_v2(db, zName, &intarrayModule, p,
                                (void(*)(void*))intarrayFree);
  if( rc==SQLITE_OK ){
    char *zSql;
    zSql = sqlite4_mprintf("CREATE VIRTUAL TABLE temp.%Q USING %Q",
                           zName, zName);
    rc = sqlite4_exec(db, zSql, 0, 0, 0);
    sqlite4_free(zSql);
  }
#endif
  return rc;
}

/*
** Bind a new array array of integers to a specific intarray object.
**
** The array of integers bound must be unchanged for the duration of
** any query against the corresponding virtual table.  If the integer
** array does change or is deallocated undefined behavior will result.
*/
int sqlite4_intarray_bind(
  sqlite4_intarray *pIntArray,   /* The intarray object to bind to */
  int nElements,                 /* Number of elements in the intarray */
  sqlite4_int64 *aElements,      /* Content of the intarray */
  void (*xFree)(void*)           /* How to dispose of the intarray when done */
){
  if( pIntArray->xFree ){
    pIntArray->xFree(pIntArray->a);
  }
  pIntArray->n = nElements;
  pIntArray->a = aElements;
  pIntArray->xFree = xFree;
  return SQLITE_OK;
}


/*****************************************************************************
** Everything below is interface for testing this module.
*/
#ifdef SQLITE_TEST
#include <tcl.h>

/*
** Routines to encode and decode pointers
*/
extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite4 **ppDb);
extern void *sqlite4TestTextToPtr(const char*);
extern int sqlite4TestMakePointerStr(Tcl_Interp*, char *zPtr, void*);
extern const char *sqlite4TestErrorName(int);

/*
**    sqlite4_intarray_create  DB  NAME
**
** Invoke the sqlite4_intarray_create interface.  A string that becomes
** the first parameter to sqlite4_intarray_bind.
*/
static int test_intarray_create(
  ClientData clientData, /* Not used */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite4 *db;
  const char *zName;
  sqlite4_intarray *pArray;
  int rc = SQLITE_OK;
  char zPtr[100];

  if( objc!=3 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  zName = Tcl_GetString(objv[2]);
#ifndef SQLITE_OMIT_VIRTUALTABLE
  rc = sqlite4_intarray_create(db, zName, &pArray);
#endif
  if( rc!=SQLITE_OK ){
    assert( pArray==0 );
    Tcl_AppendResult(interp, sqlite4TestErrorName(rc), (char*)0);
    return TCL_ERROR;
  }
  sqlite4TestMakePointerStr(interp, zPtr, pArray);
  Tcl_AppendResult(interp, zPtr, (char*)0);
  return TCL_OK;
}

/*
**    sqlite4_intarray_bind  INTARRAY  ?VALUE ...?
**
** Invoke the sqlite4_intarray_bind interface on the given array of integers.
*/
static int test_intarray_bind(
  ClientData clientData, /* Not used */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite4_intarray *pArray;
  int rc = SQLITE_OK;
  int i, n;
  sqlite4_int64 *a;

  if( objc<2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "INTARRAY");
    return TCL_ERROR;
  }
  pArray = (sqlite4_intarray*)sqlite4TestTextToPtr(Tcl_GetString(objv[1]));
  n = objc - 2;
#ifndef SQLITE_OMIT_VIRTUALTABLE
  a = sqlite4_malloc( sizeof(a[0])*n );
  if( a==0 ){
    Tcl_AppendResult(interp, "SQLITE_NOMEM", (char*)0);
    return TCL_ERROR;
  }
  for(i=0; i<n; i++){
    a[i] = 0;
    Tcl_GetWideIntFromObj(0, objv[i+2], &a[i]);
  }
  rc = sqlite4_intarray_bind(pArray, n, a, sqlite4_free);
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, sqlite4TestErrorName(rc), (char*)0);
    return TCL_ERROR;
  }
#endif
  return TCL_OK;
}

/*
** Register commands with the TCL interpreter.
*/
int Sqlitetestintarray_Init(Tcl_Interp *interp){
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
     void *clientData;
  } aObjCmd[] = {
     { "sqlite4_intarray_create", test_intarray_create, 0 },
     { "sqlite4_intarray_bind", test_intarray_bind, 0 },
  };
  int i;
  for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
    Tcl_CreateObjCommand(interp, aObjCmd[i].zName, 
        aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
  }
  return TCL_OK;
}

#endif /* SQLITE_TEST */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































































































































































































































































































































































































































































































































































































































































































































































Deleted test/test_intarray.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/*
** 2009 November 10
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This is the C-language interface definition for the "intarray" or
** integer array virtual table for SQLite.
**
** The intarray virtual table is designed to facilitate using an
** array of integers as the right-hand side of an IN operator.  So
** instead of doing a prepared statement like this:
**
**     SELECT * FROM table WHERE x IN (?,?,?,...,?);
**
** And then binding indivdual integers to each of ? slots, a C-language
** application can create an intarray object (named "ex1" in the following
** example), prepare a statement like this:
**
**     SELECT * FROM table WHERE x IN ex1;
**
** Then bind an ordinary C/C++ array of integer values to the ex1 object
** to run the statement.
**
** USAGE:
**
** One or more intarray objects can be created as follows:
**
**      sqlite4_intarray *p1, *p2, *p3;
**      sqlite4_intarray_create(db, "ex1", &p1);
**      sqlite4_intarray_create(db, "ex2", &p2);
**      sqlite4_intarray_create(db, "ex3", &p3);
**
** Each call to sqlite4_intarray_create() generates a new virtual table
** module and a singleton of that virtual table module in the TEMP
** database.  Both the module and the virtual table instance use the
** name given by the second parameter.  The virtual tables can then be
** used in prepared statements:
**
**      SELECT * FROM t1, t2, t3
**       WHERE t1.x IN ex1
**         AND t2.y IN ex2
**         AND t3.z IN ex3;
**
** Each integer array is initially empty.  New arrays can be bound to
** an integer array as follows:
**
**     sqlite4_int64 a1[] = { 1, 2, 3, 4 };
**     sqlite4_int64 a2[] = { 5, 6, 7, 8, 9, 10, 11 };
**     sqlite4_int64 *a3 = sqlite4_malloc( 100*sizeof(sqlite4_int64) );
**     // Fill in content of a3[]
**     sqlite4_intarray_bind(p1, 4, a1, 0);
**     sqlite4_intarray_bind(p2, 7, a2, 0);
**     sqlite4_intarray_bind(p3, 100, a3, sqlite4_free);
**
** A single intarray object can be rebound multiple times.  But do not
** attempt to change the bindings of an intarray while it is in the middle
** of a query.
**
** The array that holds the integers is automatically freed by the function
** in the fourth parameter to sqlite4_intarray_bind() when the array is no
** longer needed.  The application must not change the intarray values
** while an intarray is in the middle of a query.
**
** The intarray object is automatically destroyed when its corresponding
** virtual table is dropped.  Since the virtual tables are created in the
** TEMP database, they are automatically dropped when the database connection
** closes so the application does not normally need to take any special
** action to free the intarray objects.
*/
#include "sqlite4.h"

/*
** An sqlite4_intarray is an abstract type to stores an instance of
** an integer array.
*/
typedef struct sqlite4_intarray sqlite4_intarray;

/*
** Invoke this routine to create a specific instance of an intarray object.
** The new intarray object is returned by the 3rd parameter.
**
** Each intarray object corresponds to a virtual table in the TEMP table
** with a name of zName.
**
** Destroy the intarray object by dropping the virtual table.  If not done
** explicitly by the application, the virtual table will be dropped implicitly
** by the system when the database connection is closed.
*/
int sqlite4_intarray_create(
  sqlite4 *db,
  const char *zName,
  sqlite4_intarray **ppReturn
);

/*
** Bind a new array array of integers to a specific intarray object.
**
** The array of integers bound must be unchanged for the duration of
** any query against the corresponding virtual table.  If the integer
** array does change or is deallocated undefined behavior will result.
*/
int sqlite4_intarray_bind(
  sqlite4_intarray *pIntArray,   /* The intarray object to bind to */
  int nElements,                 /* Number of elements in the intarray */
  sqlite4_int64 *aElements,      /* Content of the intarray */
  void (*xFree)(void*)           /* How to dispose of the intarray when done */
);
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































































































































































Changes to test/test_main.c.

180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
...
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
...
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
...
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
...
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
...
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
...
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
...
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
...
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
...
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
...
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
....
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
....
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
....
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
....
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
....
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
....
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
....
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
....
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
....
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
....
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
....
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
....
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
....
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
....
2159
2160
2161
2162
2163
2164
2165

2166
2167
2168
2169
2170
2171
2172
....
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
....
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
....
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
....
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
#define StmtToDb(X)   sqlite4_db_handle(X)

/*
** Check a return value to make sure it agrees with the results
** from sqlite4_errcode.
*/
int sqlite4TestErrCode(Tcl_Interp *interp, sqlite4 *db, int rc){
  if( sqlite4_threadsafe()==0 && rc!=SQLITE_MISUSE && rc!=SQLITE_OK
   && sqlite4_errcode(db)!=rc ){
    char zBuf[200];
    int r2 = sqlite4_errcode(db);
    sprintf(zBuf, "error code %s (%d) does not match sqlite4_errcode %s (%d)",
       t1ErrorName(rc), rc, t1ErrorName(r2), r2);
    Tcl_ResetResult(interp);
    Tcl_AppendResult(interp, zBuf, 0);
    return 1;
................................................................................
** work.  Or at least that is what is reported to me (drh).  But this
** behavior varies from machine to machine.  The solution used her is
** to test the string right after it is generated to see if it can be
** understood by scanf, and if not, try prepending an "0x" to see if
** that helps.  If nothing works, a fatal error is generated.
*/
int sqlite4TestMakePointerStr(Tcl_Interp *interp, char *zPtr, void *p){
  sqlite4_snprintf(100, zPtr, "%p", p);
  return TCL_OK;
}

/*
** The callback routine for sqlite4_exec_printf().
*/
static int exec_printf_cb(void *pArg, int argc, char **argv, char **name){
................................................................................
  if( argc!=4 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
       " DB FORMAT STRING", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  Tcl_DStringInit(&str);
  zSql = sqlite4_mprintf(argv[2], argv[3]);
  rc = sqlite4_exec(db, zSql, exec_printf_cb, &str, &zErr);
  sqlite4_free(zSql);
  sprintf(zBuf, "%d", rc);
  Tcl_AppendElement(interp, zBuf);
  Tcl_AppendElement(interp, rc==SQLITE_OK ? Tcl_DStringValue(&str) : zErr);
  Tcl_DStringFree(&str);
  if( zErr ) sqlite4_free(zErr);
  if( sqlite4TestErrCode(interp, db, rc) ) return TCL_ERROR;
  return TCL_OK;
}

/*
** Usage:  sqlite4_exec_hex  DB  HEX
**
................................................................................
  zSql[i] = 0;
  Tcl_DStringInit(&str);
  rc = sqlite4_exec(db, zSql, exec_printf_cb, &str, &zErr);
  sprintf(zBuf, "%d", rc);
  Tcl_AppendElement(interp, zBuf);
  Tcl_AppendElement(interp, rc==SQLITE_OK ? Tcl_DStringValue(&str) : zErr);
  Tcl_DStringFree(&str);
  if( zErr ) sqlite4_free(zErr);
  if( sqlite4TestErrCode(interp, db, rc) ) return TCL_ERROR;
  return TCL_OK;
}

/*
** Usage:  db_enter DB
**         db_leave DB
................................................................................
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
       " DB SQL", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  Tcl_DStringInit(&str);
  zSql = sqlite4_mprintf("%s", argv[2]);
  for(i=j=0; zSql[i];){
    if( zSql[i]=='%' ){
      zSql[j++] = (testHexToInt(zSql[i+1])<<4) + testHexToInt(zSql[i+2]);
      i += 3;
    }else{
      zSql[j++] = zSql[i++];
    }
  }
  zSql[j] = 0;
  rc = sqlite4_exec(db, zSql, exec_printf_cb, &str, &zErr);
  sqlite4_free(zSql);
  sprintf(zBuf, "%d", rc);
  Tcl_AppendElement(interp, zBuf);
  Tcl_AppendElement(interp, rc==SQLITE_OK ? Tcl_DStringValue(&str) : zErr);
  Tcl_DStringFree(&str);
  if( zErr ) sqlite4_free(zErr);
  if( sqlite4TestErrCode(interp, db, rc) ) return TCL_ERROR;
  return TCL_OK;
}

/*
** Usage:  sqlite4_exec_nr  DB  SQL
**
................................................................................
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  char *zResult = 0;
  int i;

  for(i=2; i<argc && (i==2 || zResult); i++){
    zResult = sqlite4_mprintf("%z%s%s", zResult, argv[1], argv[i]);
  }
  Tcl_AppendResult(interp, zResult, 0);
  sqlite4_free(zResult);
  return TCL_OK;
}

/*
** Usage:  sqlite4_mprintf_n_test  STRING
**
** Test the %n format of sqlite_mprintf().  Return the length of the
................................................................................
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  char *zStr;
  int n = 0;
  zStr = sqlite4_mprintf("%s%n", argv[1], &n);
  sqlite4_free(zStr);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(n));
  return TCL_OK;
}

/*
** Usage:  sqlite4_snprintf_int  SIZE FORMAT  INT
**
................................................................................
  char **argv            /* Text of each argument */
){
  char zStr[100];
  int n = atoi(argv[1]);
  const char *zFormat = argv[2];
  int a1 = atoi(argv[3]);
  if( n>sizeof(zStr) ) n = sizeof(zStr);
  sqlite4_snprintf(sizeof(zStr), zStr, "abcdefghijklmnopqrstuvwxyz");
  sqlite4_snprintf(n, zStr, zFormat, a1);
  Tcl_AppendResult(interp, zStr, 0);
  return TCL_OK;
}



/*
................................................................................
** Append text to a dstr
*/
static void dstrAppend(struct dstr *p, const char *z, int divider){
  int n = strlen(z);
  if( p->nUsed + n + 2 > p->nAlloc ){
    char *zNew;
    p->nAlloc = p->nAlloc*2 + n + 200;
    zNew = sqlite4_realloc(p->z, p->nAlloc);
    if( zNew==0 ){
      sqlite4_free(p->z);
      memset(p, 0, sizeof(*p));
      return;
    }
    p->z = zNew;
  }
  if( divider && p->nUsed>0 ){
    p->z[p->nUsed++] = divider;
................................................................................
){
  struct dstr x;
  memset(&x, 0, sizeof(x));
  (void)sqlite4_exec((sqlite4*)sqlite4_user_data(context),
      (char*)sqlite4_value_text(argv[0]),
      execFuncCallback, &x, 0);
  sqlite4_result_text(context, x.z, x.nUsed, SQLITE_TRANSIENT);
  sqlite4_free(x.z);
}

/*
** Implementation of tkt2213func(), a scalar function that takes exactly
** one argument. It has two interesting features:
**
** * It calls sqlite4_value_text() 3 times on the argument sqlite4_value*.
................................................................................
  zText1 = sqlite4_value_text(argv[0]);
  zText2 = sqlite4_value_text(argv[0]);
  zText3 = sqlite4_value_text(argv[0]);

  if( zText1!=zText2 || zText2!=zText3 ){
    sqlite4_result_error(context, "tkt2213 is not fixed", -1);
  }else{
    char *zCopy = (char *)sqlite4_malloc(nText);
    memcpy(zCopy, zText1, nText);
    sqlite4_result_text(context, zCopy, nText, sqlite4_free);
  }
}

/*
** The following SQL function takes 4 arguments.  The 2nd and
** 4th argument must be one of these strings:  'text', 'text16',
** or 'blob' corresponding to API functions
................................................................................
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FORMAT INT INT INT\"", 0);
    return TCL_ERROR;
  }
  for(i=2; i<5; i++){
    if( Tcl_GetInt(interp, argv[i], &a[i-2]) ) return TCL_ERROR;
  }
  z = sqlite4_mprintf(argv[1], a[0], a[1], a[2]);
  Tcl_AppendResult(interp, z, 0);
  sqlite4_free(z);
  return TCL_OK;
}

/*
** Usage:  sqlite4_mprintf_int64 FORMAT INTEGER INTEGER INTEGER
**
** Call mprintf with three 64-bit integer arguments
................................................................................
  }
  for(i=2; i<5; i++){
    if( sqlite4Atoi64(argv[i], &a[i-2], 1000000, SQLITE_UTF8) ){
      Tcl_AppendResult(interp, "argument is not a valid 64-bit integer", 0);
      return TCL_ERROR;
    }
  }
  z = sqlite4_mprintf(argv[1], a[0], a[1], a[2]);
  Tcl_AppendResult(interp, z, 0);
  sqlite4_free(z);
  return TCL_OK;
}

/*
** Usage:  sqlite4_mprintf_long FORMAT INTEGER INTEGER INTEGER
**
** Call mprintf with three long integer arguments.   This might be the
................................................................................
    return TCL_ERROR;
  }
  for(i=2; i<5; i++){
    if( Tcl_GetInt(interp, argv[i], &b[i-2]) ) return TCL_ERROR;
    a[i-2] = (long int)b[i-2];
    a[i-2] &= (((u64)1)<<(sizeof(int)*8))-1;
  }
  z = sqlite4_mprintf(argv[1], a[0], a[1], a[2]);
  Tcl_AppendResult(interp, z, 0);
  sqlite4_free(z);
  return TCL_OK;
}

/*
** Usage:  sqlite4_mprintf_str FORMAT INTEGER INTEGER STRING
**
** Call mprintf with two integer arguments and one string argument
................................................................................
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FORMAT INT INT ?STRING?\"", 0);
    return TCL_ERROR;
  }
  for(i=2; i<4; i++){
    if( Tcl_GetInt(interp, argv[i], &a[i-2]) ) return TCL_ERROR;
  }
  z = sqlite4_mprintf(argv[1], a[0], a[1], argc>4 ? argv[4] : NULL);
  Tcl_AppendResult(interp, z, 0);
  sqlite4_free(z);
  return TCL_OK;
}

/*
** Usage:  sqlite4_snprintf_str INTEGER FORMAT INTEGER INTEGER STRING
**
** Call mprintf with two integer arguments and one string argument
................................................................................
  if( n<0 ){
    Tcl_AppendResult(interp, "N must be non-negative", 0);
    return TCL_ERROR;
  }
  for(i=3; i<5; i++){
    if( Tcl_GetInt(interp, argv[i], &a[i-3]) ) return TCL_ERROR;
  }
  z = sqlite4_malloc( n+1 );
  sqlite4_snprintf(n, z, argv[2], a[0], a[1], argc>4 ? argv[5] : NULL);
  Tcl_AppendResult(interp, z, 0);
  sqlite4_free(z);
  return TCL_OK;
}

/*
** Usage:  sqlite4_mprintf_double FORMAT INTEGER INTEGER DOUBLE
**
** Call mprintf with two integer arguments and one double argument
................................................................................
       " FORMAT INT INT DOUBLE\"", 0);
    return TCL_ERROR;
  }
  for(i=2; i<4; i++){
    if( Tcl_GetInt(interp, argv[i], &a[i-2]) ) return TCL_ERROR;
  }
  if( Tcl_GetDouble(interp, argv[4], &r) ) return TCL_ERROR;
  z = sqlite4_mprintf(argv[1], a[0], a[1], r);
  Tcl_AppendResult(interp, z, 0);
  sqlite4_free(z);
  return TCL_OK;
}

/*
** Usage:  sqlite4_mprintf_scaled FORMAT DOUBLE DOUBLE
**
** Call mprintf with a single double argument which is the product of the
................................................................................
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FORMAT DOUBLE DOUBLE\"", 0);
    return TCL_ERROR;
  }
  for(i=2; i<4; i++){
    if( Tcl_GetDouble(interp, argv[i], &r[i-2]) ) return TCL_ERROR;
  }
  z = sqlite4_mprintf(argv[1], r[0]*r[1]);
  Tcl_AppendResult(interp, z, 0);
  sqlite4_free(z);
  return TCL_OK;
}

/*
** Usage:  sqlite4_mprintf_stronly FORMAT STRING
**
** Call mprintf with a single double argument which is the product of the
................................................................................
){
  char *z;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FORMAT STRING\"", 0);
    return TCL_ERROR;
  }
  z = sqlite4_mprintf(argv[1], argv[2]);
  Tcl_AppendResult(interp, z, 0);
  sqlite4_free(z);
  return TCL_OK;
}

/*
** Usage:  sqlite4_mprintf_hexdouble FORMAT HEX
**
** Call mprintf with a single double argument which is derived from the
................................................................................
  if( sscanf(argv[2], "%08x%08x", &x2, &x1)!=2 ){
    Tcl_AppendResult(interp, "2nd argument should be 16-characters of hex", 0);
    return TCL_ERROR;
  }
  d = x2;
  d = (d<<32) + x1;
  memcpy(&r, &d, sizeof(r));
  z = sqlite4_mprintf(argv[1], r);
  Tcl_AppendResult(interp, z, 0);
  sqlite4_free(z);
  return TCL_OK;
}

/*
** Usage: sqlite4_libversion_number
**
*/
................................................................................
  int rc = Tcl_EvalObjEx(p->interp, p->pDel, TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL);
  if( rc!=TCL_OK ){
    Tcl_BackgroundError(p->interp);
  }

  Tcl_DecrRefCount(p->pCmp);
  Tcl_DecrRefCount(p->pDel);
  sqlite4_free((void *)p);
}
static int testCreateCollationCmp(
  void *pCtx,
  int nLeft,
  const void *zLeft,
  int nRight,
  const void *zRight
................................................................................

  if( objc!=5 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB-HANDLE NAME CMP-PROC DEL-PROC");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;

  p = (TestCollationX *)sqlite4_malloc(sizeof(TestCollationX));
  p->pCmp = objv[3];
  p->pDel = objv[4];
  p->interp = interp;
  Tcl_IncrRefCount(p->pCmp);
  Tcl_IncrRefCount(p->pDel);

  rc = sqlite4_create_collation(db, Tcl_GetString(objv[2]), 16, 
................................................................................
    if( rc!=TCL_OK ) Tcl_BackgroundError(p->interp);
  }

  if( p->pFunc ) Tcl_DecrRefCount(p->pFunc); 
  if( p->pStep ) Tcl_DecrRefCount(p->pStep); 
  if( p->pFinal ) Tcl_DecrRefCount(p->pFinal); 
  if( p->pDestroy ) Tcl_DecrRefCount(p->pDestroy); 
  sqlite4_free(p);
}
static int test_create_function_v2(
  ClientData clientData,          /* Not used */
  Tcl_Interp *interp,             /* The invoking TCL interpreter */
  int objc,                       /* Number of arguments */
  Tcl_Obj *CONST objv[]           /* Command arguments */
){
................................................................................
  if( Tcl_GetIndexFromObjStruct(interp, objv[4], aEnc, sizeof(aEnc[0]), 
          "encoding", 0, &enc)
  ){
    return TCL_ERROR;
  }
  enc = aEnc[enc].enc;

  p = sqlite4_malloc(sizeof(CreateFunctionV2));
  assert( p );
  memset(p, 0, sizeof(CreateFunctionV2));
  p->interp = interp;

  for(i=5; i<objc; i+=2){
    int iSwitch;
    const char *azSwitch[] = {"-func", "-step", "-final", "-destroy", 0};
    if( Tcl_GetIndexFromObj(interp, objv[i], azSwitch, "switch", 0, &iSwitch) ){
      sqlite4_free(p);
      return TCL_ERROR;
    }

    switch( iSwitch ){
      case 0: p->pFunc = objv[i+1];      break;
      case 1: p->pStep = objv[i+1];      break;
      case 2: p->pFinal = objv[i+1];     break;
................................................................................
  int nA, const void *zA,
  int nB, const void *zB
){
  Tcl_Interp *i = pTestCollateInterp;
  int encin = SQLITE_PTR_TO_INT(pCtx);
  int res;
  int n;


  sqlite4_value *pVal;
  Tcl_Obj *pX;

  pX = Tcl_NewStringObj("test_collate", -1);
  Tcl_IncrRefCount(pX);

................................................................................
    case SQLITE_UTF16BE:
      Tcl_ListObjAppendElement(i,pX,Tcl_NewStringObj("UTF-16BE",-1));
      break;
    default:
      assert(0);
  }

  sqlite4BeginBenignMalloc();
  pVal = sqlite4ValueNew(0);
  if( pVal ){
    sqlite4ValueSetStr(pVal, nA, zA, encin, SQLITE_STATIC);
    n = sqlite4_value_bytes(pVal);
    Tcl_ListObjAppendElement(i,pX,
        Tcl_NewStringObj((char*)sqlite4_value_text(pVal),n));
    sqlite4ValueSetStr(pVal, nB, zB, encin, SQLITE_STATIC);
    n = sqlite4_value_bytes(pVal);
    Tcl_ListObjAppendElement(i,pX,
        Tcl_NewStringObj((char*)sqlite4_value_text(pVal),n));
    sqlite4ValueFree(pVal);
  }
  sqlite4EndBenignMalloc();

  Tcl_EvalObjEx(i, pX, 0);
  Tcl_DecrRefCount(pX);
  Tcl_GetIntFromObj(i, Tcl_GetObjResult(i), &res);
  return res;
}
static int test_collate(
................................................................................
  char *zExplain;                 /* SQL with EXPLAIN QUERY PLAN prepended */
  sqlite4_stmt *pExplain;         /* Compiled EXPLAIN QUERY PLAN command */
  int rc;                         /* Return code from sqlite4_prepare() */

  zSql = sqlite4_sql(pStmt);
  if( zSql==0 ) return SQLITE_ERROR;

  zExplain = sqlite4_mprintf("EXPLAIN QUERY PLAN %s", zSql);
  if( zExplain==0 ) return SQLITE_NOMEM;

  rc = sqlite4_prepare(sqlite4_db_handle(pStmt), zExplain, -1, &pExplain, 0);
  sqlite4_free(zExplain);
  if( rc!=SQLITE_OK ) return rc;

  while( SQLITE_ROW==sqlite4_step(pExplain) ){
    int iSelectid = sqlite4_column_int(pExplain, 0);
    int iOrder = sqlite4_column_int(pExplain, 1);
    int iFrom = sqlite4_column_int(pExplain, 2);
    const char *zDetail = (const char *)sqlite4_column_text(pExplain, 3);
................................................................................
  DWORD wResult;
  
  if( objc!=4 && objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "FILENAME DELAY1 DELAY2");
    return TCL_ERROR;
  }
  if( objc==1 ){
    sqlite4_snprintf(sizeof(zBuf), zBuf, "%d %d %d %d %d",
                     x.ok, x.err, x.delay1, x.delay2, x.h);
    Tcl_AppendResult(interp, zBuf, (char*)0);
    return TCL_OK;
  }
  while( x.h && retry<30 ){
    retry++;
    Sleep(100);
................................................................................
  if ( !ev ){
    Tcl_AppendResult(interp, "cannot create event: ", x.evName, (char*)0);
    return TCL_ERROR;
  }
  _beginthread(win32_file_locker, 0, (void*)&x);
  Sleep(0);
  if ( (wResult = WaitForSingleObject(ev, 10000))!=WAIT_OBJECT_0 ){
    sqlite4_snprintf(sizeof(zBuf), zBuf, "0x%x", wResult);
    Tcl_AppendResult(interp, "wait failed: ", zBuf, (char*)0);
    CloseHandle(ev);
    return TCL_ERROR;
  }
  CloseHandle(ev);
  return TCL_OK;
}







|
|







 







|







 







|

|




|







 







|







 







|










|




|







 







|


|







 







|
|







 







|
|







 







|

|







 







|







 







|

|







 







|

|







 







|

|







 







|

|







 







|

|







 







|
|

|







 







|

|







 







|

|







 







|

|







 







|

|







 







|







 







|







 







|







 







|








|







 







>







 







|












|







 







|



|







 







|







 







|







180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
...
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
...
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
...
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
...
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
...
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
...
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
...
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
...
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
...
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
...
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
....
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
....
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
....
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
....
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
....
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
....
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
....
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
....
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
....
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
....
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
....
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
....
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
....
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
....
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
....
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
....
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
....
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
....
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
#define StmtToDb(X)   sqlite4_db_handle(X)

/*
** Check a return value to make sure it agrees with the results
** from sqlite4_errcode.
*/
int sqlite4TestErrCode(Tcl_Interp *interp, sqlite4 *db, int rc){
  sqlite4_env *pEnv = sqlite4_db_env(db);
  if( rc!=SQLITE_MISUSE && rc!=SQLITE_OK && sqlite4_errcode(db)!=rc ){
    char zBuf[200];
    int r2 = sqlite4_errcode(db);
    sprintf(zBuf, "error code %s (%d) does not match sqlite4_errcode %s (%d)",
       t1ErrorName(rc), rc, t1ErrorName(r2), r2);
    Tcl_ResetResult(interp);
    Tcl_AppendResult(interp, zBuf, 0);
    return 1;
................................................................................
** work.  Or at least that is what is reported to me (drh).  But this
** behavior varies from machine to machine.  The solution used her is
** to test the string right after it is generated to see if it can be
** understood by scanf, and if not, try prepending an "0x" to see if
** that helps.  If nothing works, a fatal error is generated.
*/
int sqlite4TestMakePointerStr(Tcl_Interp *interp, char *zPtr, void *p){
  sqlite4_snprintf(zPtr, 100, "%p", p);
  return TCL_OK;
}

/*
** The callback routine for sqlite4_exec_printf().
*/
static int exec_printf_cb(void *pArg, int argc, char **argv, char **name){
................................................................................
  if( argc!=4 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
       " DB FORMAT STRING", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  Tcl_DStringInit(&str);
  zSql = sqlite4_mprintf(0, argv[2], argv[3]);
  rc = sqlite4_exec(db, zSql, exec_printf_cb, &str, &zErr);
  sqlite4_free(0, zSql);
  sprintf(zBuf, "%d", rc);
  Tcl_AppendElement(interp, zBuf);
  Tcl_AppendElement(interp, rc==SQLITE_OK ? Tcl_DStringValue(&str) : zErr);
  Tcl_DStringFree(&str);
  if( zErr ) sqlite4_free(0, zErr);
  if( sqlite4TestErrCode(interp, db, rc) ) return TCL_ERROR;
  return TCL_OK;
}

/*
** Usage:  sqlite4_exec_hex  DB  HEX
**
................................................................................
  zSql[i] = 0;
  Tcl_DStringInit(&str);
  rc = sqlite4_exec(db, zSql, exec_printf_cb, &str, &zErr);
  sprintf(zBuf, "%d", rc);
  Tcl_AppendElement(interp, zBuf);
  Tcl_AppendElement(interp, rc==SQLITE_OK ? Tcl_DStringValue(&str) : zErr);
  Tcl_DStringFree(&str);
  if( zErr ) sqlite4_free(0, zErr);
  if( sqlite4TestErrCode(interp, db, rc) ) return TCL_ERROR;
  return TCL_OK;
}

/*
** Usage:  db_enter DB
**         db_leave DB
................................................................................
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
       " DB SQL", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  Tcl_DStringInit(&str);
  zSql = sqlite4_mprintf(0, "%s", argv[2]);
  for(i=j=0; zSql[i];){
    if( zSql[i]=='%' ){
      zSql[j++] = (testHexToInt(zSql[i+1])<<4) + testHexToInt(zSql[i+2]);
      i += 3;
    }else{
      zSql[j++] = zSql[i++];
    }
  }
  zSql[j] = 0;
  rc = sqlite4_exec(db, zSql, exec_printf_cb, &str, &zErr);
  sqlite4_free(0, zSql);
  sprintf(zBuf, "%d", rc);
  Tcl_AppendElement(interp, zBuf);
  Tcl_AppendElement(interp, rc==SQLITE_OK ? Tcl_DStringValue(&str) : zErr);
  Tcl_DStringFree(&str);
  if( zErr ) sqlite4_free(0, zErr);
  if( sqlite4TestErrCode(interp, db, rc) ) return TCL_ERROR;
  return TCL_OK;
}

/*
** Usage:  sqlite4_exec_nr  DB  SQL
**
................................................................................
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  char *zResult = 0;
  int i;

  for(i=2; i<argc && (i==2 || zResult); i++){
    zResult = sqlite4_mprintf(0, "%z%s%s", zResult, argv[1], argv[i]);
  }
  Tcl_AppendResult(interp, zResult, 0);
  sqlite4_free(0, zResult);
  return TCL_OK;
}

/*
** Usage:  sqlite4_mprintf_n_test  STRING
**
** Test the %n format of sqlite_mprintf().  Return the length of the
................................................................................
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  char *zStr;
  int n = 0;
  zStr = sqlite4_mprintf(0, "%s%n", argv[1], &n);
  sqlite4_free(0, zStr);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(n));
  return TCL_OK;
}

/*
** Usage:  sqlite4_snprintf_int  SIZE FORMAT  INT
**
................................................................................
  char **argv            /* Text of each argument */
){
  char zStr[100];
  int n = atoi(argv[1]);
  const char *zFormat = argv[2];
  int a1 = atoi(argv[3]);
  if( n>sizeof(zStr) ) n = sizeof(zStr);
  sqlite4_snprintf(zStr, sizeof(zStr), "abcdefghijklmnopqrstuvwxyz");
  sqlite4_snprintf(zStr, n, zFormat, a1);
  Tcl_AppendResult(interp, zStr, 0);
  return TCL_OK;
}



/*
................................................................................
** Append text to a dstr
*/
static void dstrAppend(struct dstr *p, const char *z, int divider){
  int n = strlen(z);
  if( p->nUsed + n + 2 > p->nAlloc ){
    char *zNew;
    p->nAlloc = p->nAlloc*2 + n + 200;
    zNew = sqlite4_realloc(0, p->z, p->nAlloc);
    if( zNew==0 ){
      sqlite4_free(0, p->z);
      memset(p, 0, sizeof(*p));
      return;
    }
    p->z = zNew;
  }
  if( divider && p->nUsed>0 ){
    p->z[p->nUsed++] = divider;
................................................................................
){
  struct dstr x;
  memset(&x, 0, sizeof(x));
  (void)sqlite4_exec((sqlite4*)sqlite4_user_data(context),
      (char*)sqlite4_value_text(argv[0]),
      execFuncCallback, &x, 0);
  sqlite4_result_text(context, x.z, x.nUsed, SQLITE_TRANSIENT);
  sqlite4_free(0, x.z);
}

/*
** Implementation of tkt2213func(), a scalar function that takes exactly
** one argument. It has two interesting features:
**
** * It calls sqlite4_value_text() 3 times on the argument sqlite4_value*.
................................................................................
  zText1 = sqlite4_value_text(argv[0]);
  zText2 = sqlite4_value_text(argv[0]);
  zText3 = sqlite4_value_text(argv[0]);

  if( zText1!=zText2 || zText2!=zText3 ){
    sqlite4_result_error(context, "tkt2213 is not fixed", -1);
  }else{
    char *zCopy = (char *)sqlite4_malloc(sqlite4_context_env(context),nText);
    memcpy(zCopy, zText1, nText);
    sqlite4_result_text(context, zCopy, nText, SQLITE_DYNAMIC);
  }
}

/*
** The following SQL function takes 4 arguments.  The 2nd and
** 4th argument must be one of these strings:  'text', 'text16',
** or 'blob' corresponding to API functions
................................................................................
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FORMAT INT INT INT\"", 0);
    return TCL_ERROR;
  }
  for(i=2; i<5; i++){
    if( Tcl_GetInt(interp, argv[i], &a[i-2]) ) return TCL_ERROR;
  }
  z = sqlite4_mprintf(0, argv[1], a[0], a[1], a[2]);
  Tcl_AppendResult(interp, z, 0);
  sqlite4_free(0, z);
  return TCL_OK;
}

/*
** Usage:  sqlite4_mprintf_int64 FORMAT INTEGER INTEGER INTEGER
**
** Call mprintf with three 64-bit integer arguments
................................................................................
  }
  for(i=2; i<5; i++){
    if( sqlite4Atoi64(argv[i], &a[i-2], 1000000, SQLITE_UTF8) ){
      Tcl_AppendResult(interp, "argument is not a valid 64-bit integer", 0);
      return TCL_ERROR;
    }
  }
  z = sqlite4_mprintf(0, argv[1], a[0], a[1], a[2]);
  Tcl_AppendResult(interp, z, 0);
  sqlite4_free(0, z);
  return TCL_OK;
}

/*
** Usage:  sqlite4_mprintf_long FORMAT INTEGER INTEGER INTEGER
**
** Call mprintf with three long integer arguments.   This might be the
................................................................................
    return TCL_ERROR;
  }
  for(i=2; i<5; i++){
    if( Tcl_GetInt(interp, argv[i], &b[i-2]) ) return TCL_ERROR;
    a[i-2] = (long int)b[i-2];
    a[i-2] &= (((u64)1)<<(sizeof(int)*8))-1;
  }
  z = sqlite4_mprintf(0, argv[1], a[0], a[1], a[2]);
  Tcl_AppendResult(interp, z, 0);
  sqlite4_free(0, z);
  return TCL_OK;
}

/*
** Usage:  sqlite4_mprintf_str FORMAT INTEGER INTEGER STRING
**
** Call mprintf with two integer arguments and one string argument
................................................................................
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FORMAT INT INT ?STRING?\"", 0);
    return TCL_ERROR;
  }
  for(i=2; i<4; i++){
    if( Tcl_GetInt(interp, argv[i], &a[i-2]) ) return TCL_ERROR;
  }
  z = sqlite4_mprintf(0, argv[1], a[0], a[1], argc>4 ? argv[4] : NULL);
  Tcl_AppendResult(interp, z, 0);
  sqlite4_free(0, z);
  return TCL_OK;
}

/*
** Usage:  sqlite4_snprintf_str INTEGER FORMAT INTEGER INTEGER STRING
**
** Call mprintf with two integer arguments and one string argument
................................................................................
  if( n<0 ){
    Tcl_AppendResult(interp, "N must be non-negative", 0);
    return TCL_ERROR;
  }
  for(i=3; i<5; i++){
    if( Tcl_GetInt(interp, argv[i], &a[i-3]) ) return TCL_ERROR;
  }
  z = sqlite4_malloc(0, n+1);
  sqlite4_snprintf(z, n, argv[2], a[0], a[1], argc>4 ? argv[5] : NULL);
  Tcl_AppendResult(interp, z, 0);
  sqlite4_free(0, z);
  return TCL_OK;
}

/*
** Usage:  sqlite4_mprintf_double FORMAT INTEGER INTEGER DOUBLE
**
** Call mprintf with two integer arguments and one double argument
................................................................................
       " FORMAT INT INT DOUBLE\"", 0);
    return TCL_ERROR;
  }
  for(i=2; i<4; i++){
    if( Tcl_GetInt(interp, argv[i], &a[i-2]) ) return TCL_ERROR;
  }
  if( Tcl_GetDouble(interp, argv[4], &r) ) return TCL_ERROR;
  z = sqlite4_mprintf(0, argv[1], a[0], a[1], r);
  Tcl_AppendResult(interp, z, 0);
  sqlite4_free(0, z);
  return TCL_OK;
}

/*
** Usage:  sqlite4_mprintf_scaled FORMAT DOUBLE DOUBLE
**
** Call mprintf with a single double argument which is the product of the
................................................................................
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FORMAT DOUBLE DOUBLE\"", 0);
    return TCL_ERROR;
  }
  for(i=2; i<4; i++){
    if( Tcl_GetDouble(interp, argv[i], &r[i-2]) ) return TCL_ERROR;
  }
  z = sqlite4_mprintf(0, argv[1], r[0]*r[1]);
  Tcl_AppendResult(interp, z, 0);
  sqlite4_free(0, z);
  return TCL_OK;
}

/*
** Usage:  sqlite4_mprintf_stronly FORMAT STRING
**
** Call mprintf with a single double argument which is the product of the
................................................................................
){
  char *z;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FORMAT STRING\"", 0);
    return TCL_ERROR;
  }
  z = sqlite4_mprintf(0, argv[1], argv[2]);
  Tcl_AppendResult(interp, z, 0);
  sqlite4_free(0, z);
  return TCL_OK;
}

/*
** Usage:  sqlite4_mprintf_hexdouble FORMAT HEX
**
** Call mprintf with a single double argument which is derived from the
................................................................................
  if( sscanf(argv[2], "%08x%08x", &x2, &x1)!=2 ){
    Tcl_AppendResult(interp, "2nd argument should be 16-characters of hex", 0);
    return TCL_ERROR;
  }
  d = x2;
  d = (d<<32) + x1;
  memcpy(&r, &d, sizeof(r));
  z = sqlite4_mprintf(0, argv[1], r);
  Tcl_AppendResult(interp, z, 0);
  sqlite4_free(0, z);
  return TCL_OK;
}

/*
** Usage: sqlite4_libversion_number
**
*/
................................................................................
  int rc = Tcl_EvalObjEx(p->interp, p->pDel, TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL);
  if( rc!=TCL_OK ){
    Tcl_BackgroundError(p->interp);
  }

  Tcl_DecrRefCount(p->pCmp);
  Tcl_DecrRefCount(p->pDel);
  sqlite4_free(0, (void *)p);
}
static int testCreateCollationCmp(
  void *pCtx,
  int nLeft,
  const void *zLeft,
  int nRight,
  const void *zRight
................................................................................

  if( objc!=5 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB-HANDLE NAME CMP-PROC DEL-PROC");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;

  p = (TestCollationX *)sqlite4_malloc(0, sizeof(TestCollationX));
  p->pCmp = objv[3];
  p->pDel = objv[4];
  p->interp = interp;
  Tcl_IncrRefCount(p->pCmp);
  Tcl_IncrRefCount(p->pDel);

  rc = sqlite4_create_collation(db, Tcl_GetString(objv[2]), 16, 
................................................................................
    if( rc!=TCL_OK ) Tcl_BackgroundError(p->interp);
  }

  if( p->pFunc ) Tcl_DecrRefCount(p->pFunc); 
  if( p->pStep ) Tcl_DecrRefCount(p->pStep); 
  if( p->pFinal ) Tcl_DecrRefCount(p->pFinal); 
  if( p->pDestroy ) Tcl_DecrRefCount(p->pDestroy); 
  sqlite4_free(0, p);
}
static int test_create_function_v2(
  ClientData clientData,          /* Not used */
  Tcl_Interp *interp,             /* The invoking TCL interpreter */
  int objc,                       /* Number of arguments */
  Tcl_Obj *CONST objv[]           /* Command arguments */
){
................................................................................
  if( Tcl_GetIndexFromObjStruct(interp, objv[4], aEnc, sizeof(aEnc[0]), 
          "encoding", 0, &enc)
  ){
    return TCL_ERROR;
  }
  enc = aEnc[enc].enc;

  p = sqlite4_malloc(0, sizeof(CreateFunctionV2));
  assert( p );
  memset(p, 0, sizeof(CreateFunctionV2));
  p->interp = interp;

  for(i=5; i<objc; i+=2){
    int iSwitch;
    const char *azSwitch[] = {"-func", "-step", "-final", "-destroy", 0};
    if( Tcl_GetIndexFromObj(interp, objv[i], azSwitch, "switch", 0, &iSwitch) ){
      sqlite4_free(0, p);
      return TCL_ERROR;
    }

    switch( iSwitch ){
      case 0: p->pFunc = objv[i+1];      break;
      case 1: p->pStep = objv[i+1];      break;
      case 2: p->pFinal = objv[i+1];     break;
................................................................................
  int nA, const void *zA,
  int nB, const void *zB
){
  Tcl_Interp *i = pTestCollateInterp;
  int encin = SQLITE_PTR_TO_INT(pCtx);
  int res;
  int n;
  sqlite4_env *pEnv = sqlite4_context_env(pCtx);

  sqlite4_value *pVal;
  Tcl_Obj *pX;

  pX = Tcl_NewStringObj("test_collate", -1);
  Tcl_IncrRefCount(pX);

................................................................................
    case SQLITE_UTF16BE:
      Tcl_ListObjAppendElement(i,pX,Tcl_NewStringObj("UTF-16BE",-1));
      break;
    default:
      assert(0);
  }

  sqlite4BeginBenignMalloc(pEnv);
  pVal = sqlite4ValueNew(0);
  if( pVal ){
    sqlite4ValueSetStr(pVal, nA, zA, encin, SQLITE_STATIC);
    n = sqlite4_value_bytes(pVal);
    Tcl_ListObjAppendElement(i,pX,
        Tcl_NewStringObj((char*)sqlite4_value_text(pVal),n));
    sqlite4ValueSetStr(pVal, nB, zB, encin, SQLITE_STATIC);
    n = sqlite4_value_bytes(pVal);
    Tcl_ListObjAppendElement(i,pX,
        Tcl_NewStringObj((char*)sqlite4_value_text(pVal),n));
    sqlite4ValueFree(pVal);
  }
  sqlite4EndBenignMalloc(pEnv);

  Tcl_EvalObjEx(i, pX, 0);
  Tcl_DecrRefCount(pX);
  Tcl_GetIntFromObj(i, Tcl_GetObjResult(i), &res);
  return res;
}
static int test_collate(
................................................................................
  char *zExplain;                 /* SQL with EXPLAIN QUERY PLAN prepended */
  sqlite4_stmt *pExplain;         /* Compiled EXPLAIN QUERY PLAN command */
  int rc;                         /* Return code from sqlite4_prepare() */

  zSql = sqlite4_sql(pStmt);
  if( zSql==0 ) return SQLITE_ERROR;

  zExplain = sqlite4_mprintf(0, "EXPLAIN QUERY PLAN %s", zSql);
  if( zExplain==0 ) return SQLITE_NOMEM;

  rc = sqlite4_prepare(sqlite4_db_handle(pStmt), zExplain, -1, &pExplain, 0);
  sqlite4_free(0, zExplain);
  if( rc!=SQLITE_OK ) return rc;

  while( SQLITE_ROW==sqlite4_step(pExplain) ){
    int iSelectid = sqlite4_column_int(pExplain, 0);
    int iOrder = sqlite4_column_int(pExplain, 1);
    int iFrom = sqlite4_column_int(pExplain, 2);
    const char *zDetail = (const char *)sqlite4_column_text(pExplain, 3);
................................................................................
  DWORD wResult;
  
  if( objc!=4 && objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "FILENAME DELAY1 DELAY2");
    return TCL_ERROR;
  }
  if( objc==1 ){
    sqlite4_snprintf(zBuf, sizeof(zBuf), "%d %d %d %d %d",
                     x.ok, x.err, x.delay1, x.delay2, x.h);
    Tcl_AppendResult(interp, zBuf, (char*)0);
    return TCL_OK;
  }
  while( x.h && retry<30 ){
    retry++;
    Sleep(100);
................................................................................
  if ( !ev ){
    Tcl_AppendResult(interp, "cannot create event: ", x.evName, (char*)0);
    return TCL_ERROR;
  }
  _beginthread(win32_file_locker, 0, (void*)&x);
  Sleep(0);
  if ( (wResult = WaitForSingleObject(ev, 10000))!=WAIT_OBJECT_0 ){
    sqlite4_snprintf(zBuf, sizeof(zBuf), "0x%x", wResult);
    Tcl_AppendResult(interp, "wait failed: ", zBuf, (char*)0);
    CloseHandle(ev);
    return TCL_ERROR;
  }
  CloseHandle(ev);
  return TCL_OK;
}

Changes to test/test_malloc.c.

67
68
69
70
71
72
73
74
75

76
77
78
79
80
81
82
83
84
85
86
87
88

89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

106
107
108

109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
...
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192


193
194
195
196
197
198
199
200
201
202
203
204

205
206
207
208
209
210
211
...
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
...
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
...
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
  return 1;  
}

/*
** A version of sqlite4_mem_methods.xMalloc() that includes fault simulation
** logic.
*/
static void *faultsimMalloc(int n){
  void *p = 0;

  if( !faultsimStep() ){
    p = memfault.m.xMalloc(n);
  }
  return p;
}


/*
** A version of sqlite4_mem_methods.xRealloc() that includes fault simulation
** logic.
*/
static void *faultsimRealloc(void *pOld, int n){
  void *p = 0;

  if( !faultsimStep() ){
    p = memfault.m.xRealloc(pOld, n);
  }
  return p;
}

/* 
** The following method calls are passed directly through to the underlying
** malloc system:
**
**     xFree
**     xSize
**     xRoundup
**     xInit
**     xShutdown
*/
static void faultsimFree(void *p){

  memfault.m.xFree(p);
}
static int faultsimSize(void *p){

  return memfault.m.xSize(p);
}
static int faultsimRoundup(int n){
  return memfault.m.xRoundup(n);
}
static int faultsimInit(void *p){
  return memfault.m.xInit(memfault.m.pAppData);
}
static void faultsimShutdown(void *p){
  memfault.m.xShutdown(memfault.m.pAppData);
}

/*
** This routine configures the malloc failure simulation.  After
** calling this routine, the next nDelay mallocs will succeed, followed
** by a block of nRepeat failures, after which malloc() calls will begin
................................................................................
    return memfault.iCountdown;
  }else{
    return -1;
  }
}


static void faultsimBeginBenign(void){
  memfault.isBenignMode++;
}
static void faultsimEndBenign(void){
  memfault.isBenignMode--;
}

/*
** Add or remove the fault-simulation layer using sqlite4_env_config(). If
** the argument is non-zero, the 
*/
static int faultsimInstall(int install){
  static struct sqlite4_mem_methods m = {
    faultsimMalloc,                   /* xMalloc */
    faultsimFree,                     /* xFree */
    faultsimRealloc,                  /* xRealloc */
    faultsimSize,                     /* xSize */
    faultsimRoundup,                  /* xRoundup */
    faultsimInit,                     /* xInit */
    faultsimShutdown,                 /* xShutdown */


    0                                 /* pAppData */
  };
  int rc;

  install = (install ? 1 : 0);
  assert(memfault.isInstalled==1 || memfault.isInstalled==0);

  if( install==memfault.isInstalled ){
    return SQLITE_ERROR;
  }

  if( install ){

    rc = sqlite4_env_config(0, SQLITE_ENVCONFIG_GETMALLOC, &memfault.m);
    assert(memfault.m.xMalloc);
    if( rc==SQLITE_OK ){
      rc = sqlite4_env_config(0, SQLITE_ENVCONFIG_MALLOC, &m);
    }
    sqlite4_test_control(SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, 
        faultsimBeginBenign, faultsimEndBenign
................................................................................
  void *p;
  char zOut[100];
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "NBYTES");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[1], &nByte) ) return TCL_ERROR;
  p = sqlite4_malloc((unsigned)nByte);
  pointerToText(p, zOut);
  Tcl_AppendResult(interp, zOut, NULL);
  return TCL_OK;
}

/*
** Usage:    sqlite4_realloc  PRIOR  NBYTES
................................................................................
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[2], &nByte) ) return TCL_ERROR;
  if( textToPointer(Tcl_GetString(objv[1]), &pPrior) ){
    Tcl_AppendResult(interp, "bad pointer: ", Tcl_GetString(objv[1]), (char*)0);
    return TCL_ERROR;
  }
  p = sqlite4_realloc(pPrior, (unsigned)nByte);
  pointerToText(p, zOut);
  Tcl_AppendResult(interp, zOut, NULL);
  return TCL_OK;
}

/*
** Usage:    sqlite4_free  PRIOR
................................................................................
    Tcl_WrongNumArgs(interp, 1, objv, "PRIOR");
    return TCL_ERROR;
  }
  if( textToPointer(Tcl_GetString(objv[1]), &pPrior) ){
    Tcl_AppendResult(interp, "bad pointer: ", Tcl_GetString(objv[1]), (char*)0);
    return TCL_ERROR;
  }
  sqlite4_free(pPrior);
  return TCL_OK;
}

/*
** These routines are in test_hexio.c
*/
int sqlite4TestHexToBin(const char *, int, char *);







|

>

|









|

>

|










<



|
>
|

|
>
|

<
<
<
|


|







 







|


|













<


>
>
|











>







 







|







 







|







 







|







67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102

103
104
105
106
107
108
109
110
111
112
113



114
115
116
117
118
119
120
121
122
123
124
...
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189

190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
...
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
...
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
...
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
  return 1;  
}

/*
** A version of sqlite4_mem_methods.xMalloc() that includes fault simulation
** logic.
*/
static void *faultsimMalloc(void *pMem, sqlite4_size_t n){
  void *p = 0;
  assert( pMem==(void*)&memfault );
  if( !faultsimStep() ){
    p = memfault.m.xMalloc(memfault.m.pAppData, n);
  }
  return p;
}


/*
** A version of sqlite4_mem_methods.xRealloc() that includes fault simulation
** logic.
*/
static void *faultsimRealloc(void *pMem, void *pOld, sqlite4_size_t n){
  void *p = 0;
  assert( pMem==(void*)&memfault );
  if( !faultsimStep() ){
    p = memfault.m.xRealloc(memfault.m.pAppData, pOld, n);
  }
  return p;
}

/* 
** The following method calls are passed directly through to the underlying
** malloc system:
**
**     xFree
**     xSize

**     xInit
**     xShutdown
*/
static void faultsimFree(void *pMem, void *p){
  assert( pMem==(void*)&memfault );
  memfault.m.xFree(memfault.m.pAppData, p);
}
static sqlite4_size_t faultsimSize(void *pMem, void *p){
  assert( pMem==(void*)&memfault );
  return memfault.m.xSize(memfault.m.pAppData, p);
}



static int faultsimInit(void *pMem){
  return memfault.m.xInit(memfault.m.pAppData);
}
static void faultsimShutdown(void *pMem){
  memfault.m.xShutdown(memfault.m.pAppData);
}

/*
** This routine configures the malloc failure simulation.  After
** calling this routine, the next nDelay mallocs will succeed, followed
** by a block of nRepeat failures, after which malloc() calls will begin
................................................................................
    return memfault.iCountdown;
  }else{
    return -1;
  }
}


static void faultsimBeginBenign(void *pMem){
  memfault.isBenignMode++;
}
static void faultsimEndBenign(void *pMem){
  memfault.isBenignMode--;
}

/*
** Add or remove the fault-simulation layer using sqlite4_env_config(). If
** the argument is non-zero, the 
*/
static int faultsimInstall(int install){
  static struct sqlite4_mem_methods m = {
    faultsimMalloc,                   /* xMalloc */
    faultsimFree,                     /* xFree */
    faultsimRealloc,                  /* xRealloc */
    faultsimSize,                     /* xSize */

    faultsimInit,                     /* xInit */
    faultsimShutdown,                 /* xShutdown */
    faultsimBeginBenign,              /* xBeginBenign */
    faultsimEndBenign,                /* xEndBenign */
    (void*)&memfault                  /* pAppData */
  };
  int rc;

  install = (install ? 1 : 0);
  assert(memfault.isInstalled==1 || memfault.isInstalled==0);

  if( install==memfault.isInstalled ){
    return SQLITE_ERROR;
  }

  if( install ){
    sqlite4_initialize(0);
    rc = sqlite4_env_config(0, SQLITE_ENVCONFIG_GETMALLOC, &memfault.m);
    assert(memfault.m.xMalloc);
    if( rc==SQLITE_OK ){
      rc = sqlite4_env_config(0, SQLITE_ENVCONFIG_MALLOC, &m);
    }
    sqlite4_test_control(SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, 
        faultsimBeginBenign, faultsimEndBenign
................................................................................
  void *p;
  char zOut[100];
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "NBYTES");
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[1], &nByte) ) return TCL_ERROR;
  p = sqlite4_malloc(0, (unsigned)nByte);
  pointerToText(p, zOut);
  Tcl_AppendResult(interp, zOut, NULL);
  return TCL_OK;
}

/*
** Usage:    sqlite4_realloc  PRIOR  NBYTES
................................................................................
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[2], &nByte) ) return TCL_ERROR;
  if( textToPointer(Tcl_GetString(objv[1]), &pPrior) ){
    Tcl_AppendResult(interp, "bad pointer: ", Tcl_GetString(objv[1]), (char*)0);
    return TCL_ERROR;
  }
  p = sqlite4_realloc(0, pPrior, (unsigned)nByte);
  pointerToText(p, zOut);
  Tcl_AppendResult(interp, zOut, NULL);
  return TCL_OK;
}

/*
** Usage:    sqlite4_free  PRIOR
................................................................................
    Tcl_WrongNumArgs(interp, 1, objv, "PRIOR");
    return TCL_ERROR;
  }
  if( textToPointer(Tcl_GetString(objv[1]), &pPrior) ){
    Tcl_AppendResult(interp, "bad pointer: ", Tcl_GetString(objv[1]), (char*)0);
    return TCL_ERROR;
  }
  sqlite4_free(0, pPrior);
  return TCL_OK;
}

/*
** These routines are in test_hexio.c
*/
int sqlite4TestHexToBin(const char *, int, char *);

Changes to test/test_misc1.c.

73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
  const char *zErrFunction = "N/A";

  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }

  p = sqlite4_malloc(5);
  if( !p ){
    zErrFunction = "sqlite4_malloc";
    goto error_out;
  }

  /* Test that realloc()ing a block of memory to a negative size is
  ** the same as free()ing that memory.
  */
  p = sqlite4_realloc(p, -1);
  if( p ){
    zErrFunction = "sqlite4_realloc";
    goto error_out;
  }

  return TCL_OK;








|








|







73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
  const char *zErrFunction = "N/A";

  if( objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "");
    return TCL_ERROR;
  }

  p = sqlite4_malloc(0, 5);
  if( !p ){
    zErrFunction = "sqlite4_malloc";
    goto error_out;
  }

  /* Test that realloc()ing a block of memory to a negative size is
  ** the same as free()ing that memory.
  */
  p = sqlite4_realloc(0, p, -1);
  if( p ){
    zErrFunction = "sqlite4_realloc";
    goto error_out;
  }

  return TCL_OK;

Changes to test/test_mutex.c.

300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
  int objc,
  Tcl_Obj *CONST objv[]
){
#if SQLITE_THREADSAFE
  sqlite4_mutex *p = sqlite4_mutex_alloc(SQLITE_MUTEX_FAST);
  char zBuf[100];
  sqlite4_mutex_free(p);
  sqlite4_snprintf(sizeof(zBuf), zBuf, "%p", p);
  Tcl_AppendResult(interp, zBuf, (char*)0);
#endif
  return TCL_OK;
}

/*
** sqlite4_env_config OPTION







|







300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
  int objc,
  Tcl_Obj *CONST objv[]
){
#if SQLITE_THREADSAFE
  sqlite4_mutex *p = sqlite4_mutex_alloc(SQLITE_MUTEX_FAST);
  char zBuf[100];
  sqlite4_mutex_free(p);
  sqlite4_snprintf(zBuf, sizeof(zBuf), "%p", p);
  Tcl_AppendResult(interp, zBuf, (char*)0);
#endif
  return TCL_OK;
}

/*
** sqlite4_env_config OPTION

Deleted test/test_rtree.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/*
** 2010 August 28
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing all sorts of SQLite interfaces. This code
** is not included in the SQLite library. 
*/

#include <sqlite4.h>

/* Solely for the UNUSED_PARAMETER() macro. */
#include "sqliteInt.h"

#ifdef SQLITE_ENABLE_RTREE
/* 
** Type used to cache parameter information for the "circle" r-tree geometry
** callback.
*/
typedef struct Circle Circle;
struct Circle {
  struct Box {
    double xmin;
    double xmax;
    double ymin;
    double ymax;
  } aBox[2];
  double centerx;
  double centery;
  double radius;
};

/*
** Destructor function for Circle objects allocated by circle_geom().
*/
static void circle_del(void *p){
  sqlite4_free(p);
}

/*
** Implementation of "circle" r-tree geometry callback.
*/
static int circle_geom(
  sqlite4_rtree_geometry *p,
  int nCoord, 
  double *aCoord, 
  int *pRes
){
  int i;                          /* Iterator variable */
  Circle *pCircle;                /* Structure defining circular region */
  double xmin, xmax;              /* X dimensions of box being tested */
  double ymin, ymax;              /* X dimensions of box being tested */

  if( p->pUser==0 ){
    /* If pUser is still 0, then the parameter values have not been tested
    ** for correctness or stored into a Circle structure yet. Do this now. */

    /* This geometry callback is for use with a 2-dimensional r-tree table.
    ** Return an error if the table does not have exactly 2 dimensions. */
    if( nCoord!=4 ) return SQLITE_ERROR;

    /* Test that the correct number of parameters (3) have been supplied,
    ** and that the parameters are in range (that the radius of the circle 
    ** radius is greater than zero). */
    if( p->nParam!=3 || p->aParam[2]<0.0 ) return SQLITE_ERROR;

    /* Allocate a structure to cache parameter data in. Return SQLITE_NOMEM
    ** if the allocation fails. */
    pCircle = (Circle *)(p->pUser = sqlite4_malloc(sizeof(Circle)));
    if( !pCircle ) return SQLITE_NOMEM;
    p->xDelUser = circle_del;

    /* Record the center and radius of the circular region. One way that
    ** tested bounding boxes that intersect the circular region are detected
    ** is by testing if each corner of the bounding box lies within radius
    ** units of the center of the circle. */
    pCircle->centerx = p->aParam[0];
    pCircle->centery = p->aParam[1];
    pCircle->radius = p->aParam[2];

    /* Define two bounding box regions. The first, aBox[0], extends to
    ** infinity in the X dimension. It covers the same range of the Y dimension
    ** as the circular region. The second, aBox[1], extends to infinity in
    ** the Y dimension and is constrained to the range of the circle in the
    ** X dimension.
    **
    ** Then imagine each box is split in half along its short axis by a line
    ** that intersects the center of the circular region. A bounding box
    ** being tested can be said to intersect the circular region if it contains
    ** points from each half of either of the two infinite bounding boxes.
    */
    pCircle->aBox[0].xmin = pCircle->centerx;
    pCircle->aBox[0].xmax = pCircle->centerx;
    pCircle->aBox[0].ymin = pCircle->centery + pCircle->radius;
    pCircle->aBox[0].ymax = pCircle->centery - pCircle->radius;
    pCircle->aBox[1].xmin = pCircle->centerx + pCircle->radius;
    pCircle->aBox[1].xmax = pCircle->centerx - pCircle->radius;
    pCircle->aBox[1].ymin = pCircle->centery;
    pCircle->aBox[1].ymax = pCircle->centery;
  }

  pCircle = (Circle *)p->pUser;
  xmin = aCoord[0];
  xmax = aCoord[1];
  ymin = aCoord[2];
  ymax = aCoord[3];

  /* Check if any of the 4 corners of the bounding-box being tested lie 
  ** inside the circular region. If they do, then the bounding-box does
  ** intersect the region of interest. Set the output variable to true and
  ** return SQLITE_OK in this case. */
  for(i=0; i<4; i++){
    double x = (i&0x01) ? xmax : xmin;
    double y = (i&0x02) ? ymax : ymin;
    double d2;
    
    d2  = (x-pCircle->centerx)*(x-pCircle->centerx);
    d2 += (y-pCircle->centery)*(y-pCircle->centery);
    if( d2<(pCircle->radius*pCircle->radius) ){
      *pRes = 1;
      return SQLITE_OK;
    }
  }

  /* Check if the bounding box covers any other part of the circular region.
  ** See comments above for a description of how this test works. If it does
  ** cover part of the circular region, set the output variable to true
  ** and return SQLITE_OK. */
  for(i=0; i<2; i++){
    if( xmin<=pCircle->aBox[i].xmin 
     && xmax>=pCircle->aBox[i].xmax 
     && ymin<=pCircle->aBox[i].ymin 
     && ymax>=pCircle->aBox[i].ymax 
    ){
      *pRes = 1;
      return SQLITE_OK;
    }
  }

  /* The specified bounding box does not intersect the circular region. Set
  ** the output variable to zero and return SQLITE_OK. */
  *pRes = 0;
  return SQLITE_OK;
}

/* END of implementation of "circle" geometry callback.
**************************************************************************
*************************************************************************/

#include <assert.h>
#include "tcl.h"

typedef struct Cube Cube;
struct Cube {
  double x;
  double y;
  double z;
  double width;
  double height;
  double depth;
};

static void cube_context_free(void *p){
  sqlite4_free(p);
}

/*
** The context pointer registered along with the 'cube' callback is
** always ((void *)&gHere). This is just to facilitate testing, it is not
** actually used for anything.
*/
static int gHere = 42;

/*
** Implementation of a simple r-tree geom callback to test for intersection
** of r-tree rows with a "cube" shape. Cubes are defined by six scalar
** coordinates as follows:
**
**   cube(x, y, z, width, height, depth)
**
** The width, height and depth parameters must all be greater than zero.
*/
static int cube_geom(
  sqlite4_rtree_geometry *p,
  int nCoord, 
  double *aCoord, 
  int *piRes
){
  Cube *pCube = (Cube *)p->pUser;

  assert( p->pContext==(void *)&gHere );

  if( pCube==0 ){
    if( p->nParam!=6 || nCoord!=6
     || p->aParam[3]<=0.0 || p->aParam[4]<=0.0 || p->aParam[5]<=0.0
    ){
      return SQLITE_ERROR;
    }
    pCube = (Cube *)sqlite4_malloc(sizeof(Cube));
    if( !pCube ){
      return SQLITE_NOMEM;
    }
    pCube->x = p->aParam[0];
    pCube->y = p->aParam[1];
    pCube->z = p->aParam[2];
    pCube->width = p->aParam[3];
    pCube->height = p->aParam[4];
    pCube->depth = p->aParam[5];

    p->pUser = (void *)pCube;
    p->xDelUser = cube_context_free;
  }

  assert( nCoord==6 );
  *piRes = 0;
  if( aCoord[0]<=(pCube->x+pCube->width)
   && aCoord[1]>=pCube->x
   && aCoord[2]<=(pCube->y+pCube->height)
   && aCoord[3]>=pCube->y
   && aCoord[4]<=(pCube->z+pCube->depth)
   && aCoord[5]>=pCube->z
  ){
    *piRes = 1;
  }

  return SQLITE_OK;
}
#endif /* SQLITE_ENABLE_RTREE */

static int register_cube_geom(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#ifndef SQLITE_ENABLE_RTREE
  UNUSED_PARAMETER(clientData);
  UNUSED_PARAMETER(interp);
  UNUSED_PARAMETER(objc);
  UNUSED_PARAMETER(objv);
#else
  extern int getDbPointer(Tcl_Interp*, const char*, sqlite4**);
  extern const char *sqlite4TestErrorName(int);
  sqlite4 *db;
  int rc;

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  rc = sqlite4_rtree_geometry_callback(db, "cube", cube_geom, (void *)&gHere);
  Tcl_SetResult(interp, (char *)sqlite4TestErrorName(rc), TCL_STATIC);
#endif
  return TCL_OK;
}

static int register_circle_geom(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#ifndef SQLITE_ENABLE_RTREE
  UNUSED_PARAMETER(clientData);
  UNUSED_PARAMETER(interp);
  UNUSED_PARAMETER(objc);
  UNUSED_PARAMETER(objv);
#else
  extern int getDbPointer(Tcl_Interp*, const char*, sqlite4**);
  extern const char *sqlite4TestErrorName(int);
  sqlite4 *db;
  int rc;

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  rc = sqlite4_rtree_geometry_callback(db, "circle", circle_geom, 0);
  Tcl_SetResult(interp, (char *)sqlite4TestErrorName(rc), TCL_STATIC);
#endif
  return TCL_OK;
}

int Sqlitetestrtree_Init(Tcl_Interp *interp){
  Tcl_CreateObjCommand(interp, "register_cube_geom", register_cube_geom, 0, 0);
  Tcl_CreateObjCommand(interp, "register_circle_geom",register_circle_geom,0,0);
  return TCL_OK;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































































































































































































































































































































































































































































































































Deleted test/test_schema.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*
** 2006 June 10
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing the virtual table interfaces.  This code
** is not included in the SQLite library.  It is used for automated
** testing of the SQLite library.
*/

/* The code in this file defines a sqlite4 virtual-table module that
** provides a read-only view of the current database schema. There is one
** row in the schema table for each column in the database schema.
*/
#define SCHEMA \
"CREATE TABLE x("                                                            \
  "database,"          /* Name of database (i.e. main, temp etc.) */         \
  "tablename,"         /* Name of table */                                   \
  "cid,"               /* Column number (from left-to-right, 0 upward) */    \
  "name,"              /* Column name */                                     \
  "type,"              /* Specified type (i.e. VARCHAR(32)) */               \
  "not_null,"          /* Boolean. True if NOT NULL was specified */         \
  "dflt_value,"        /* Default value for this column */                   \
  "pk"                 /* True if this column is part of the primary key */  \
")"

#include "sqliteInt.h"
#include "tcl.h"

#include <stdlib.h>
#include <string.h>
#include <assert.h>

typedef struct schema_vtab schema_vtab;
typedef struct schema_cursor schema_cursor;

/* A schema table object */
struct schema_vtab {
  sqlite4_vtab base;
  sqlite4 *db;
};

/* A schema table cursor object */
struct schema_cursor {
  sqlite4_vtab_cursor base;
  sqlite4_stmt *pDbList;
  sqlite4_stmt *pTableList;
  sqlite4_stmt *pColumnList;
  int rowid;
};

/*
** None of this works unless we have virtual tables.
*/
#ifndef SQLITE_OMIT_VIRTUALTABLE

/*
** Table destructor for the schema module.
*/
static int schemaDestroy(sqlite4_vtab *pVtab){
  sqlite4_free(pVtab);
  return 0;
}

/*
** Table constructor for the schema module.
*/
static int schemaCreate(
  sqlite4 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite4_vtab **ppVtab,
  char **pzErr
){
  int rc = SQLITE_NOMEM;
  schema_vtab *pVtab = sqlite4_malloc(sizeof(schema_vtab));
  if( pVtab ){
    memset(pVtab, 0, sizeof(schema_vtab));
    pVtab->db = db;
#ifndef SQLITE_OMIT_VIRTUALTABLE
    rc = sqlite4_declare_vtab(db, SCHEMA);
#endif
  }
  *ppVtab = (sqlite4_vtab *)pVtab;
  return rc;
}

/*
** Open a new cursor on the schema table.
*/
static int schemaOpen(sqlite4_vtab *pVTab, sqlite4_vtab_cursor **ppCursor){
  int rc = SQLITE_NOMEM;
  schema_cursor *pCur;
  pCur = sqlite4_malloc(sizeof(schema_cursor));
  if( pCur ){
    memset(pCur, 0, sizeof(schema_cursor));
    *ppCursor = (sqlite4_vtab_cursor *)pCur;
    rc = SQLITE_OK;
  }
  return rc;
}

/*
** Close a schema table cursor.
*/
static int schemaClose(sqlite4_vtab_cursor *cur){
  schema_cursor *pCur = (schema_cursor *)cur;
  sqlite4_finalize(pCur->pDbList);
  sqlite4_finalize(pCur->pTableList);
  sqlite4_finalize(pCur->pColumnList);
  sqlite4_free(pCur);
  return SQLITE_OK;
}

/*
** Retrieve a column of data.
*/
static int schemaColumn(sqlite4_vtab_cursor *cur, sqlite4_context *ctx, int i){
  schema_cursor *pCur = (schema_cursor *)cur;
  switch( i ){
    case 0:
      sqlite4_result_value(ctx, sqlite4_column_value(pCur->pDbList, 1));
      break;
    case 1:
      sqlite4_result_value(ctx, sqlite4_column_value(pCur->pTableList, 0));
      break;
    default:
      sqlite4_result_value(ctx, sqlite4_column_value(pCur->pColumnList, i-2));
      break;
  }
  return SQLITE_OK;
}

/*
** Retrieve the current rowid.
*/
static int schemaRowid(sqlite4_vtab_cursor *cur, sqlite_int64 *pRowid){
  schema_cursor *pCur = (schema_cursor *)cur;
  *pRowid = pCur->rowid;
  return SQLITE_OK;
}

static int finalize(sqlite4_stmt **ppStmt){
  int rc = sqlite4_finalize(*ppStmt);
  *ppStmt = 0;
  return rc;
}

static int schemaEof(sqlite4_vtab_cursor *cur){
  schema_cursor *pCur = (schema_cursor *)cur;
  return (pCur->pDbList ? 0 : 1);
}

/*
** Advance the cursor to the next row.
*/
static int schemaNext(sqlite4_vtab_cursor *cur){
  int rc = SQLITE_OK;
  schema_cursor *pCur = (schema_cursor *)cur;
  schema_vtab *pVtab = (schema_vtab *)(cur->pVtab);
  char *zSql = 0;

  while( !pCur->pColumnList || SQLITE_ROW!=sqlite4_step(pCur->pColumnList) ){
    if( SQLITE_OK!=(rc = finalize(&pCur->pColumnList)) ) goto next_exit;

    while( !pCur->pTableList || SQLITE_ROW!=sqlite4_step(pCur->pTableList) ){
      if( SQLITE_OK!=(rc = finalize(&pCur->pTableList)) ) goto next_exit;

      assert(pCur->pDbList);
      while( SQLITE_ROW!=sqlite4_step(pCur->pDbList) ){
        rc = finalize(&pCur->pDbList);
        goto next_exit;
      }

      /* Set zSql to the SQL to pull the list of tables from the 
      ** sqlite_master (or sqlite_temp_master) table of the database
      ** identfied by the row pointed to by the SQL statement pCur->pDbList
      ** (iterating through a "PRAGMA database_list;" statement).
      */
      if( sqlite4_column_int(pCur->pDbList, 0)==1 ){
        zSql = sqlite4_mprintf(
            "SELECT name FROM sqlite_temp_master WHERE type='table'"
        );
      }else{
        sqlite4_stmt *pDbList = pCur->pDbList;
        zSql = sqlite4_mprintf(
            "SELECT name FROM %Q.sqlite_master WHERE type='table'",
             sqlite4_column_text(pDbList, 1)
        );
      }
      if( !zSql ){
        rc = SQLITE_NOMEM;
        goto next_exit;
      }

      rc = sqlite4_prepare(pVtab->db, zSql, -1, &pCur->pTableList, 0);
      sqlite4_free(zSql);
      if( rc!=SQLITE_OK ) goto next_exit;
    }

    /* Set zSql to the SQL to the table_info pragma for the table currently
    ** identified by the rows pointed to by statements pCur->pDbList and
    ** pCur->pTableList.
    */
    zSql = sqlite4_mprintf("PRAGMA %Q.table_info(%Q)", 
        sqlite4_column_text(pCur->pDbList, 1),
        sqlite4_column_text(pCur->pTableList, 0)
    );

    if( !zSql ){
      rc = SQLITE_NOMEM;
      goto next_exit;
    }
    rc = sqlite4_prepare(pVtab->db, zSql, -1, &pCur->pColumnList, 0);
    sqlite4_free(zSql);
    if( rc!=SQLITE_OK ) goto next_exit;
  }
  pCur->rowid++;

next_exit:
  /* TODO: Handle rc */
  return rc;
}

/*
** Reset a schema table cursor.
*/
static int schemaFilter(
  sqlite4_vtab_cursor *pVtabCursor, 
  int idxNum, const char *idxStr,
  int argc, sqlite4_value **argv
){
  int rc;
  schema_vtab *pVtab = (schema_vtab *)(pVtabCursor->pVtab);
  schema_cursor *pCur = (schema_cursor *)pVtabCursor;
  pCur->rowid = 0;
  finalize(&pCur->pTableList);
  finalize(&pCur->pColumnList);
  finalize(&pCur->pDbList);
  rc = sqlite4_prepare(pVtab->db,"PRAGMA database_list", -1, &pCur->pDbList, 0);
  return (rc==SQLITE_OK ? schemaNext(pVtabCursor) : rc);
}

/*
** Analyse the WHERE condition.
*/
static int schemaBestIndex(sqlite4_vtab *tab, sqlite4_index_info *pIdxInfo){
  return SQLITE_OK;
}

/*
** A virtual table module that merely echos method calls into TCL
** variables.
*/
static sqlite4_module schemaModule = {
  0,                           /* iVersion */
  schemaCreate,
  schemaCreate,
  schemaBestIndex,
  schemaDestroy,
  schemaDestroy,
  schemaOpen,                  /* xOpen - open a cursor */
  schemaClose,                 /* xClose - close a cursor */
  schemaFilter,                /* xFilter - configure scan constraints */
  schemaNext,                  /* xNext - advance a cursor */
  schemaEof,                   /* xEof */
  schemaColumn,                /* xColumn - read data */
  schemaRowid,                 /* xRowid - read data */
  0,                           /* xUpdate */
  0,                           /* xBegin */
  0,                           /* xSync */
  0,                           /* xCommit */
  0,                           /* xRollback */
  0,                           /* xFindMethod */
  0,                           /* xRename */
};

#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */

#ifdef SQLITE_TEST

/*
** Decode a pointer to an sqlite4 object.
*/
extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite4 **ppDb);

/*
** Register the schema virtual table module.
*/
static int register_schema_module(
  ClientData clientData, /* Not used */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite4 *db;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
#ifndef SQLITE_OMIT_VIRTUALTABLE
  sqlite4_create_module(db, "schema", &schemaModule, 0);
#endif
  return TCL_OK;
}

/*
** Register commands with the TCL interpreter.
*/
int Sqlitetestschema_Init(Tcl_Interp *interp){
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
     void *clientData;
  } aObjCmd[] = {
     { "register_schema_module", register_schema_module, 0 },
  };
  int i;
  for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
    Tcl_CreateObjCommand(interp, aObjCmd[i].zName, 
        aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
  }
  return TCL_OK;
}

#else

/*
** Extension load function.
*/
int sqlite4_extension_init(
  sqlite4 *db, 
  char **pzErrMsg, 
  const sqlite4_api_routines *pApi
){
  SQLITE_EXTENSION_INIT2(pApi);
#ifndef SQLITE_OMIT_VIRTUALTABLE
  sqlite4_create_module(db, "schema", &schemaModule, 0);
#endif
  return 0;
}

#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































































































































































































































































































































































































































































































































































































































































Changes to test/test_storage.c.

54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
...
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
  memset(&db, 0, sizeof(db));
  rc = sqlite4KVStoreOpen(&db, "test", Tcl_GetString(objv[1]), &pNew, flags);
  if( rc ){
    sqlite4KVStoreClose(pNew);
    storageSetTclErrorName(interp, rc);
    return TCL_ERROR;
  }
  sqlite4_snprintf(sizeof(zRes),zRes, "%p", pNew);
  Tcl_SetObjResult(interp, Tcl_NewStringObj(zRes,-1));
  return TCL_OK;
}

/*
** TCLCMD:    storage_close STORAGE
**
................................................................................
  pStore = sqlite4TestTextToPtr(Tcl_GetString(objv[1]));
  rc = sqlite4KVStoreOpenCursor(pStore, &pNew);
  if( rc ){
    sqlite4KVCursorClose(pNew);
    storageSetTclErrorName(interp, rc);
    return TCL_ERROR;
  }
  sqlite4_snprintf(sizeof(zRes),zRes, "%p", pNew);
  Tcl_SetObjResult(interp, Tcl_NewStringObj(zRes,-1));
  return TCL_OK;
}

/*
** TCLCMD:    storage_close_cursor CURSOR
**







|







 







|







54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
...
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
  memset(&db, 0, sizeof(db));
  rc = sqlite4KVStoreOpen(&db, "test", Tcl_GetString(objv[1]), &pNew, flags);
  if( rc ){
    sqlite4KVStoreClose(pNew);
    storageSetTclErrorName(interp, rc);
    return TCL_ERROR;
  }
  sqlite4_snprintf(zRes,sizeof(zRes), "%p", pNew);
  Tcl_SetObjResult(interp, Tcl_NewStringObj(zRes,-1));
  return TCL_OK;
}

/*
** TCLCMD:    storage_close STORAGE
**
................................................................................
  pStore = sqlite4TestTextToPtr(Tcl_GetString(objv[1]));
  rc = sqlite4KVStoreOpenCursor(pStore, &pNew);
  if( rc ){
    sqlite4KVCursorClose(pNew);
    storageSetTclErrorName(interp, rc);
    return TCL_ERROR;
  }
  sqlite4_snprintf(zRes,sizeof(zRes), "%p", pNew);
  Tcl_SetObjResult(interp, Tcl_NewStringObj(zRes,-1));
  return TCL_OK;
}

/*
** TCLCMD:    storage_close_cursor CURSOR
**

Changes to test/test_storage2.c.

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
...
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
...
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
...
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
** Create a new cursor object.
*/
static int kvwrapOpenCursor(KVStore *pKVStore, KVCursor **ppKVCursor){
  int rc = SQLITE_OK;
  KVWrap *p = (KVWrap *)pKVStore;
  KVWrapCsr *pCsr;

  pCsr = (KVWrapCsr *)sqlite4_malloc(sizeof(KVWrapCsr));
  if( pCsr==0 ){
    rc = SQLITE_NOMEM;
  }else{
    memset(pCsr, 0, sizeof(KVWrapCsr));
    rc = p->pReal->pStoreVfunc->xOpenCursor(p->pReal, &pCsr->pReal);
    if( rc!=SQLITE_OK ){
      sqlite4_free(pCsr);
      pCsr = 0;
    }else{
      pCsr->base.pStore = pKVStore;
      pCsr->base.pStoreVfunc = pKVStore->pStoreVfunc;
    }
  }

................................................................................
** Destroy a cursor object
*/
static int kvwrapCloseCursor(KVCursor *pKVCursor){
  int rc;
  KVWrap *p = (KVWrap *)(pKVCursor->pStore);
  KVWrapCsr *pCsr = (KVWrapCsr *)pKVCursor;
  rc = p->pReal->pStoreVfunc->xCloseCursor(pCsr->pReal);
  sqlite4_free(pCsr);
  return rc;
}

/*
** Move a cursor to the next non-deleted node.
*/
static int kvwrapNextEntry(KVCursor *pKVCursor){
................................................................................
/*
** Destructor for the entire in-memory storage tree.
*/
static int kvwrapClose(KVStore *pKVStore){
  int rc;
  KVWrap *p = (KVWrap *)pKVStore;
  rc = p->pReal->pStoreVfunc->xClose(p->pReal);
  sqlite4_free(p);
  return rc;
}

/*
** Invoke the xControl() method of the underlying KVStore object.
*/
static int kvwrapControl(KVStore *pKVStore, int op, void *pArg){
................................................................................
    kvwrapClose,
    kvwrapControl
  };

  KVWrap *pNew;
  int rc = SQLITE_OK;

  pNew = (KVWrap *)sqlite4_malloc(sizeof(KVWrap));
  if( pNew==0 ){
    rc = SQLITE_NOMEM;
  }else{
    memset(pNew, 0, sizeof(KVWrap));
    pNew->base.pStoreVfunc = &kvwrapMethods;
    rc = kvwg.xFactory(pEnv, &pNew->pReal, zName, openFlags);
    if( rc!=SQLITE_OK ){
      sqlite4_free(pNew);
      pNew = 0;
    }
  }

  *ppKVStore = (KVStore*)pNew;
  return rc;
}







|






|







 







|







 







|







 







|







|







87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
...
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
...
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
...
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
** Create a new cursor object.
*/
static int kvwrapOpenCursor(KVStore *pKVStore, KVCursor **ppKVCursor){
  int rc = SQLITE_OK;
  KVWrap *p = (KVWrap *)pKVStore;
  KVWrapCsr *pCsr;

  pCsr = (KVWrapCsr *)sqlite4_malloc(0, sizeof(KVWrapCsr));
  if( pCsr==0 ){
    rc = SQLITE_NOMEM;
  }else{
    memset(pCsr, 0, sizeof(KVWrapCsr));
    rc = p->pReal->pStoreVfunc->xOpenCursor(p->pReal, &pCsr->pReal);
    if( rc!=SQLITE_OK ){
      sqlite4_free(0, pCsr);
      pCsr = 0;
    }else{
      pCsr->base.pStore = pKVStore;
      pCsr->base.pStoreVfunc = pKVStore->pStoreVfunc;
    }
  }

................................................................................
** Destroy a cursor object
*/
static int kvwrapCloseCursor(KVCursor *pKVCursor){
  int rc;
  KVWrap *p = (KVWrap *)(pKVCursor->pStore);
  KVWrapCsr *pCsr = (KVWrapCsr *)pKVCursor;
  rc = p->pReal->pStoreVfunc->xCloseCursor(pCsr->pReal);
  sqlite4_free(0, pCsr);
  return rc;
}

/*
** Move a cursor to the next non-deleted node.
*/
static int kvwrapNextEntry(KVCursor *pKVCursor){
................................................................................
/*
** Destructor for the entire in-memory storage tree.
*/
static int kvwrapClose(KVStore *pKVStore){
  int rc;
  KVWrap *p = (KVWrap *)pKVStore;
  rc = p->pReal->pStoreVfunc->xClose(p->pReal);
  sqlite4_free(0, p);
  return rc;
}

/*
** Invoke the xControl() method of the underlying KVStore object.
*/
static int kvwrapControl(KVStore *pKVStore, int op, void *pArg){
................................................................................
    kvwrapClose,
    kvwrapControl
  };

  KVWrap *pNew;
  int rc = SQLITE_OK;

  pNew = (KVWrap *)sqlite4_malloc(0, sizeof(KVWrap));
  if( pNew==0 ){
    rc = SQLITE_NOMEM;
  }else{
    memset(pNew, 0, sizeof(KVWrap));
    pNew->base.pStoreVfunc = &kvwrapMethods;
    rc = kvwg.xFactory(pEnv, &pNew->pReal, zName, openFlags);
    if( rc!=SQLITE_OK ){
      sqlite4_free(0, pNew);
      pNew = 0;
    }
  }

  *ppKVStore = (KVStore*)pNew;
  return rc;
}

Deleted test/test_tclvar.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/*
** 2006 June 13
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing the virtual table interfaces.  This code
** is not included in the SQLite library.  It is used for automated
** testing of the SQLite library.
**
** The emphasis of this file is a virtual table that provides
** access to TCL variables.
*/
#include "sqliteInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>

#ifndef SQLITE_OMIT_VIRTUALTABLE

typedef struct tclvar_vtab tclvar_vtab;
typedef struct tclvar_cursor tclvar_cursor;

/* 
** A tclvar virtual-table object 
*/
struct tclvar_vtab {
  sqlite4_vtab base;
  Tcl_Interp *interp;
};

/* A tclvar cursor object */
struct tclvar_cursor {
  sqlite4_vtab_cursor base;

  Tcl_Obj *pList1;     /* Result of [info vars ?pattern?] */
  Tcl_Obj *pList2;     /* Result of [array names [lindex $pList1 $i1]] */
  int i1;              /* Current item in pList1 */
  int i2;              /* Current item (if any) in pList2 */
};

/* Methods for the tclvar module */
static int tclvarConnect(
  sqlite4 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite4_vtab **ppVtab,
  char **pzErr
){
  tclvar_vtab *pVtab;
  static const char zSchema[] = 
     "CREATE TABLE whatever(name TEXT, arrayname TEXT, value TEXT)";
  pVtab = sqlite4MallocZero( sizeof(*pVtab) );
  if( pVtab==0 ) return SQLITE_NOMEM;
  *ppVtab = &pVtab->base;
  pVtab->interp = (Tcl_Interp *)pAux;
  sqlite4_declare_vtab(db, zSchema);
  return SQLITE_OK;
}
/* Note that for this virtual table, the xCreate and xConnect
** methods are identical. */

static int tclvarDisconnect(sqlite4_vtab *pVtab){
  sqlite4_free(pVtab);
  return SQLITE_OK;
}
/* The xDisconnect and xDestroy methods are also the same */

/*
** Open a new tclvar cursor.
*/
static int tclvarOpen(sqlite4_vtab *pVTab, sqlite4_vtab_cursor **ppCursor){
  tclvar_cursor *pCur;
  pCur = sqlite4MallocZero(sizeof(tclvar_cursor));
  *ppCursor = &pCur->base;
  return SQLITE_OK;
}

/*
** Close a tclvar cursor.
*/
static int tclvarClose(sqlite4_vtab_cursor *cur){
  tclvar_cursor *pCur = (tclvar_cursor *)cur;
  if( pCur->pList1 ){
    Tcl_DecrRefCount(pCur->pList1);
  }
  if( pCur->pList2 ){
    Tcl_DecrRefCount(pCur->pList2);
  }
  sqlite4_free(pCur);
  return SQLITE_OK;
}

/*
** Returns 1 if data is ready, or 0 if not.
*/
static int next2(Tcl_Interp *interp, tclvar_cursor *pCur, Tcl_Obj *pObj){
  Tcl_Obj *p;

  if( pObj ){
    if( !pCur->pList2 ){
      p = Tcl_NewStringObj("array names", -1);
      Tcl_IncrRefCount(p);
      Tcl_ListObjAppendElement(0, p, pObj);
      Tcl_EvalObjEx(interp, p, TCL_EVAL_GLOBAL);
      Tcl_DecrRefCount(p);
      pCur->pList2 = Tcl_GetObjResult(interp);
      Tcl_IncrRefCount(pCur->pList2);
      assert( pCur->i2==0 );
    }else{
      int n = 0;
      pCur->i2++;
      Tcl_ListObjLength(0, pCur->pList2, &n);
      if( pCur->i2>=n ){
        Tcl_DecrRefCount(pCur->pList2);
        pCur->pList2 = 0;
        pCur->i2 = 0;
        return 0;
      }
    }
  }

  return 1;
}

static int tclvarNext(sqlite4_vtab_cursor *cur){
  Tcl_Obj *pObj;
  int n = 0;
  int ok = 0;

  tclvar_cursor *pCur = (tclvar_cursor *)cur;
  Tcl_Interp *interp = ((tclvar_vtab *)(cur->pVtab))->interp;

  Tcl_ListObjLength(0, pCur->pList1, &n);
  while( !ok && pCur->i1<n ){
    Tcl_ListObjIndex(0, pCur->pList1, pCur->i1, &pObj);
    ok = next2(interp, pCur, pObj);
    if( !ok ){
      pCur->i1++;
    }
  }

  return 0;
}

static int tclvarFilter(
  sqlite4_vtab_cursor *pVtabCursor, 
  int idxNum, const char *idxStr,
  int argc, sqlite4_value **argv
){
  tclvar_cursor *pCur = (tclvar_cursor *)pVtabCursor;
  Tcl_Interp *interp = ((tclvar_vtab *)(pVtabCursor->pVtab))->interp;

  Tcl_Obj *p = Tcl_NewStringObj("info vars", -1);
  Tcl_IncrRefCount(p);

  assert( argc==0 || argc==1 );
  if( argc==1 ){
    Tcl_Obj *pArg = Tcl_NewStringObj((char*)sqlite4_value_text(argv[0]), -1);
    Tcl_ListObjAppendElement(0, p, pArg);
  }
  Tcl_EvalObjEx(interp, p, TCL_EVAL_GLOBAL);
  if( pCur->pList1 ){
    Tcl_DecrRefCount(pCur->pList1);
  }
  if( pCur->pList2 ){
    Tcl_DecrRefCount(pCur->pList2);
    pCur->pList2 = 0;
  }
  pCur->i1 = 0;
  pCur->i2 = 0;
  pCur->pList1 = Tcl_GetObjResult(interp);
  Tcl_IncrRefCount(pCur->pList1);
  assert( pCur->i1==0 && pCur->i2==0 && pCur->pList2==0 );

  Tcl_DecrRefCount(p);
  return tclvarNext(pVtabCursor);
}

static int tclvarColumn(sqlite4_vtab_cursor *cur, sqlite4_context *ctx, int i){
  Tcl_Obj *p1;
  Tcl_Obj *p2;
  const char *z1; 
  const char *z2 = "";
  tclvar_cursor *pCur = (tclvar_cursor*)cur;
  Tcl_Interp *interp = ((tclvar_vtab *)cur->pVtab)->interp;

  Tcl_ListObjIndex(interp, pCur->pList1, pCur->i1, &p1);
  Tcl_ListObjIndex(interp, pCur->pList2, pCur->i2, &p2);
  z1 = Tcl_GetString(p1);
  if( p2 ){
    z2 = Tcl_GetString(p2);
  }
  switch (i) {
    case 0: {
      sqlite4_result_text(ctx, z1, -1, SQLITE_TRANSIENT);
      break;
    }
    case 1: {
      sqlite4_result_text(ctx, z2, -1, SQLITE_TRANSIENT);
      break;
    }
    case 2: {
      Tcl_Obj *pVal = Tcl_GetVar2Ex(interp, z1, *z2?z2:0, TCL_GLOBAL_ONLY);
      sqlite4_result_text(ctx, Tcl_GetString(pVal), -1, SQLITE_TRANSIENT);
      break;
    }
  }
  return SQLITE_OK;
}

static int tclvarRowid(sqlite4_vtab_cursor *cur, sqlite_int64 *pRowid){
  *pRowid = 0;
  return SQLITE_OK;
}

static int tclvarEof(sqlite4_vtab_cursor *cur){
  tclvar_cursor *pCur = (tclvar_cursor*)cur;
  return (pCur->pList2?0:1);
}

static int tclvarBestIndex(sqlite4_vtab *tab, sqlite4_index_info *pIdxInfo){
  int ii;

  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
    struct sqlite4_index_constraint const *pCons = &pIdxInfo->aConstraint[ii];
    if( pCons->iColumn==0 && pCons->usable
           && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
      struct sqlite4_index_constraint_usage *pUsage;
      pUsage = &pIdxInfo->aConstraintUsage[ii];
      pUsage->omit = 0;
      pUsage->argvIndex = 1;
      return SQLITE_OK;
    }
  }

  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
    struct sqlite4_index_constraint const *pCons = &pIdxInfo->aConstraint[ii];
    if( pCons->iColumn==0 && pCons->usable
           && pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
      struct sqlite4_index_constraint_usage *pUsage;
      pUsage = &pIdxInfo->aConstraintUsage[ii];
      pUsage->omit = 1;
      pUsage->argvIndex = 1;
      return SQLITE_OK;
    }
  }

  return SQLITE_OK;
}

/*
** A virtual table module that provides read-only access to a
** Tcl global variable namespace.
*/
static sqlite4_module tclvarModule = {
  0,                         /* iVersion */
  tclvarConnect,
  tclvarConnect,
  tclvarBestIndex,
  tclvarDisconnect, 
  tclvarDisconnect,
  tclvarOpen,                  /* xOpen - open a cursor */
  tclvarClose,                 /* xClose - close a cursor */
  tclvarFilter,                /* xFilter - configure scan constraints */
  tclvarNext,                  /* xNext - advance a cursor */
  tclvarEof,                   /* xEof - check for end of scan */
  tclvarColumn,                /* xColumn - read data */
  tclvarRowid,                 /* xRowid - read data */
  0,                           /* xUpdate */
  0,                           /* xBegin */
  0,                           /* xSync */
  0,                           /* xCommit */
  0,                           /* xRollback */
  0,                           /* xFindMethod */
  0,                           /* xRename */
};

/*
** Decode a pointer to an sqlite4 object.
*/
extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite4 **ppDb);

/*
** Register the echo virtual table module.
*/
static int register_tclvar_module(
  ClientData clientData, /* Pointer to sqlite4_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite4 *db;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
#ifndef SQLITE_OMIT_VIRTUALTABLE
  sqlite4_create_module(db, "tclvar", &tclvarModule, (void *)interp);
#endif
  return TCL_OK;
}

#endif


/*
** Register commands with the TCL interpreter.
*/
int Sqlitetesttclvar_Init(Tcl_Interp *interp){
#ifndef SQLITE_OMIT_VIRTUALTABLE
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
     void *clientData;
  } aObjCmd[] = {
     { "register_tclvar_module",   register_tclvar_module, 0 },
  };
  int i;
  for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
    Tcl_CreateObjCommand(interp, aObjCmd[i].zName, 
        aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
  }
#endif
  return TCL_OK;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































































































































































































































































































































































































































































































































































































Changes to test/test_thread.c.

271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
  extern void Md5_Register(sqlite4*);

  UNUSED_PARAMETER(clientData);
  UNUSED_PARAMETER(objc);

  zFilename = Tcl_GetString(objv[2]);
  rc = sqlite4_open(0, zFilename, &db, 0);
#ifdef SQLITE_HAS_CODEC
  if( db && objc>=4 ){
    const char *zKey;
    int nKey;
    zKey = Tcl_GetStringFromObj(objv[3], &nKey);
    rc = sqlite4_key(db, zKey, nKey);
    if( rc!=SQLITE_OK ){
      char *zErrMsg = sqlite4_mprintf("error %d: %s", rc, sqlite4_errmsg(db));
      sqlite4_close(db);
      Tcl_AppendResult(interp, zErrMsg, (char*)0);
      sqlite4_free(zErrMsg);
      return TCL_ERROR;
    }
  }
#endif
  Md5_Register(db);
  
  if( sqlite4TestMakePointerStr(interp, zBuf, db) ) return TCL_ERROR;
  Tcl_AppendResult(interp, zBuf, 0);

  return TCL_OK;
}







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







271
272
273
274
275
276
277















278
279
280
281
282
283
284
  extern void Md5_Register(sqlite4*);

  UNUSED_PARAMETER(clientData);
  UNUSED_PARAMETER(objc);

  zFilename = Tcl_GetString(objv[2]);
  rc = sqlite4_open(0, zFilename, &db, 0);















  Md5_Register(db);
  
  if( sqlite4TestMakePointerStr(interp, zBuf, db) ) return TCL_ERROR;
  Tcl_AppendResult(interp, zBuf, 0);

  return TCL_OK;
}

Changes to test/test_thread0.c.

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
..
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
...
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
...
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
...
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
...
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
    p->db = 0;
  }
  p->pStmt = 0;
  p->completed = 1;
  while( p->opnum<=p->completed ) sched_yield();
  while( p->xOp ){
    if( p->zErr && p->zErr!=p->zStaticErr ){
      sqlite4_free(p->zErr);
      p->zErr = 0;
    }
    (*p->xOp)(p);
    p->completed++;
    while( p->opnum<=p->completed ) sched_yield();
  }
  if( p->pStmt ){
................................................................................
    p->pStmt = 0;
  }
  if( p->db ){
    sqlite4_close(p->db);
    p->db = 0;
  }
  if( p->zErr && p->zErr!=p->zStaticErr ){
    sqlite4_free(p->zErr);
    p->zErr = 0;
  }
  p->completed++;
  return 0;
}

/*
................................................................................
  i = parse_thread_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( threadset[i].busy ){
    Tcl_AppendResult(interp, "thread ", argv[1], " is already running", 0);
    return TCL_ERROR;
  }
  threadset[i].busy = 1;
  sqlite4_free(threadset[i].zFilename);
  threadset[i].zFilename = sqlite4_mprintf("%s", argv[2]);
  threadset[i].opnum = 1;
  threadset[i].completed = 0;
  rc = pthread_create(&x, 0, thread_main, &threadset[i]);
  if( rc ){
    Tcl_AppendResult(interp, "failed to create the thread", 0);
    sqlite4_free(threadset[i].zFilename);
    threadset[i].busy = 0;
    return TCL_ERROR;
  }
  pthread_detach(x);
  return TCL_OK;
}

................................................................................
** Stop a thread.
*/
static void stop_thread(Thread *p){
  thread_wait(p);
  p->xOp = 0;
  p->opnum++;
  thread_wait(p);
  sqlite4_free(p->zArg);
  p->zArg = 0;
  sqlite4_free(p->zFilename);
  p->zFilename = 0;
  p->busy = 0;
}

/*
** Usage:  thread_halt ID
**
................................................................................
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  thread_wait(&threadset[i]);
  threadset[i].xOp = do_compile;
  sqlite4_free(threadset[i].zArg);
  threadset[i].zArg = sqlite4_mprintf("%s", argv[2]);
  threadset[i].opnum++;
  return TCL_OK;
}

/*
** This procedure runs in the thread to step the virtual machine.
*/
................................................................................
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  thread_wait(&threadset[i]);
  threadset[i].xOp = do_finalize;
  sqlite4_free(threadset[i].zArg);
  threadset[i].zArg = 0;
  threadset[i].opnum++;
  return TCL_OK;
}

/*
** Usage: thread_swap ID ID







|







 







|







 







|
|





|







 







|

|







 







|
|







 







|







70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
..
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
...
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
...
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
...
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
...
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
    p->db = 0;
  }
  p->pStmt = 0;
  p->completed = 1;
  while( p->opnum<=p->completed ) sched_yield();
  while( p->xOp ){
    if( p->zErr && p->zErr!=p->zStaticErr ){
      sqlite4_free(0, p->zErr);
      p->zErr = 0;
    }
    (*p->xOp)(p);
    p->completed++;
    while( p->opnum<=p->completed ) sched_yield();
  }
  if( p->pStmt ){
................................................................................
    p->pStmt = 0;
  }
  if( p->db ){
    sqlite4_close(p->db);
    p->db = 0;
  }
  if( p->zErr && p->zErr!=p->zStaticErr ){
    sqlite4_free(0, p->zErr);
    p->zErr = 0;
  }
  p->completed++;
  return 0;
}

/*
................................................................................
  i = parse_thread_id(interp, argv[1]);
  if( i<0 ) return TCL_ERROR;
  if( threadset[i].busy ){
    Tcl_AppendResult(interp, "thread ", argv[1], " is already running", 0);
    return TCL_ERROR;
  }
  threadset[i].busy = 1;
  sqlite4_free(0, threadset[i].zFilename);
  threadset[i].zFilename = sqlite4_mprintf(0, "%s", argv[2]);
  threadset[i].opnum = 1;
  threadset[i].completed = 0;
  rc = pthread_create(&x, 0, thread_main, &threadset[i]);
  if( rc ){
    Tcl_AppendResult(interp, "failed to create the thread", 0);
    sqlite4_free(0, threadset[i].zFilename);
    threadset[i].busy = 0;
    return TCL_ERROR;
  }
  pthread_detach(x);
  return TCL_OK;
}

................................................................................
** Stop a thread.
*/
static void stop_thread(Thread *p){
  thread_wait(p);
  p->xOp = 0;
  p->opnum++;
  thread_wait(p);
  sqlite4_free(0, p->zArg);
  p->zArg = 0;
  sqlite4_free(0, p->zFilename);
  p->zFilename = 0;
  p->busy = 0;
}

/*
** Usage:  thread_halt ID
**
................................................................................
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  thread_wait(&threadset[i]);
  threadset[i].xOp = do_compile;
  sqlite4_free(0, threadset[i].zArg);
  threadset[i].zArg = sqlite4_mprintf(0, "%s", argv[2]);
  threadset[i].opnum++;
  return TCL_OK;
}

/*
** This procedure runs in the thread to step the virtual machine.
*/
................................................................................
  if( i<0 ) return TCL_ERROR;
  if( !threadset[i].busy ){
    Tcl_AppendResult(interp, "no such thread", 0);
    return TCL_ERROR;
  }
  thread_wait(&threadset[i]);
  threadset[i].xOp = do_finalize;
  sqlite4_free(0, threadset[i].zArg);
  threadset[i].zArg = 0;
  threadset[i].opnum++;
  return TCL_OK;
}

/*
** Usage: thread_swap ID ID

Changes to test/test_utf.c.

112
113
114
115
116
117
118


119
120
121
122
123
124
125
...
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
  }
  if( pEnc->enc==SQLITE_UTF16 ){
    return SQLITE_UTF16NATIVE;
  }
  return pEnc->enc;
}



/*
** Usage:   test_translate <string/blob> <from enc> <to enc> ?<transient>?
**
*/
static int test_translate(
  void * clientData,
  Tcl_Interp *interp,
................................................................................
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), 
        " <string/blob> <from enc> <to enc>", 0
    );
    return TCL_ERROR;
  }
  if( objc==5 ){
    xDel = sqlite4_free;
  }

  enc_from = name_to_enc(interp, objv[2]);
  if( !enc_from ) return TCL_ERROR;
  enc_to = name_to_enc(interp, objv[3]);
  if( !enc_to ) return TCL_ERROR;

  pVal = sqlite4ValueNew(0);

  if( enc_from==SQLITE_UTF8 ){
    z = Tcl_GetString(objv[1]);
    if( objc==5 ){
      z = sqlite4_mprintf("%s", z);
    }
    sqlite4ValueSetStr(pVal, -1, z, enc_from, xDel);
  }else{
    z = (char*)Tcl_GetByteArrayFromObj(objv[1], &len);
    if( objc==5 ){
      char *zTmp = z;
      z = sqlite4_malloc(len);
      memcpy(z, zTmp, len);
    }
    sqlite4ValueSetStr(pVal, -1, z, enc_from, xDel);
  }

  z = (char *)sqlite4ValueText(pVal, enc_to);
  len = sqlite4ValueBytes(pVal, enc_to) + (enc_to==SQLITE_UTF8?1:2);







>
>







 







|












|






|







112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
...
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
  }
  if( pEnc->enc==SQLITE_UTF16 ){
    return SQLITE_UTF16NATIVE;
  }
  return pEnc->enc;
}

static void freeStr(void *pStr){ sqlite4_free(0, pStr); }

/*
** Usage:   test_translate <string/blob> <from enc> <to enc> ?<transient>?
**
*/
static int test_translate(
  void * clientData,
  Tcl_Interp *interp,
................................................................................
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), 
        " <string/blob> <from enc> <to enc>", 0
    );
    return TCL_ERROR;
  }
  if( objc==5 ){
    xDel = freeStr;
  }

  enc_from = name_to_enc(interp, objv[2]);
  if( !enc_from ) return TCL_ERROR;
  enc_to = name_to_enc(interp, objv[3]);
  if( !enc_to ) return TCL_ERROR;

  pVal = sqlite4ValueNew(0);

  if( enc_from==SQLITE_UTF8 ){
    z = Tcl_GetString(objv[1]);
    if( objc==5 ){
      z = sqlite4_mprintf(0, "%s", z);
    }
    sqlite4ValueSetStr(pVal, -1, z, enc_from, xDel);
  }else{
    z = (char*)Tcl_GetByteArrayFromObj(objv[1], &len);
    if( objc==5 ){
      char *zTmp = z;
      z = sqlite4_malloc(0, len);
      memcpy(z, zTmp, len);
    }
    sqlite4ValueSetStr(pVal, -1, z, enc_from, xDel);
  }

  z = (char *)sqlite4ValueText(pVal, enc_to);
  len = sqlite4ValueBytes(pVal, enc_to) + (enc_to==SQLITE_UTF8?1:2);

Deleted test/test_wholenumber.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/*
** 2011 April 02
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file implements a virtual table that returns the whole numbers
** between 1 and 4294967295, inclusive.
**
** Example:
**
**     CREATE VIRTUAL TABLE nums USING wholenumber;
**     SELECT value FROM nums WHERE value<10;
**
** Results in:
**
**     1 2 3 4 5 6 7 8 9
*/
#include "sqlite4.h"
#include <assert.h>
#include <string.h>

#ifndef SQLITE_OMIT_VIRTUALTABLE


/* A wholenumber cursor object */
typedef struct wholenumber_cursor wholenumber_cursor;
struct wholenumber_cursor {
  sqlite4_vtab_cursor base;  /* Base class - must be first */
  unsigned iValue;           /* Current value */
  unsigned mxValue;          /* Maximum value */
};

/* Methods for the wholenumber module */
static int wholenumberConnect(
  sqlite4 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite4_vtab **ppVtab,
  char **pzErr
){
  sqlite4_vtab *pNew;
  pNew = *ppVtab = sqlite4_malloc( sizeof(*pNew) );
  if( pNew==0 ) return SQLITE_NOMEM;
  sqlite4_declare_vtab(db, "CREATE TABLE x(value)");
  memset(pNew, 0, sizeof(*pNew));
  return SQLITE_OK;
}
/* Note that for this virtual table, the xCreate and xConnect
** methods are identical. */

static int wholenumberDisconnect(sqlite4_vtab *pVtab){
  sqlite4_free(pVtab);
  return SQLITE_OK;
}
/* The xDisconnect and xDestroy methods are also the same */


/*
** Open a new wholenumber cursor.
*/
static int wholenumberOpen(sqlite4_vtab *p, sqlite4_vtab_cursor **ppCursor){
  wholenumber_cursor *pCur;
  pCur = sqlite4_malloc( sizeof(*pCur) );
  if( pCur==0 ) return SQLITE_NOMEM;
  memset(pCur, 0, sizeof(*pCur));
  *ppCursor = &pCur->base;
  return SQLITE_OK;
}

/*
** Close a wholenumber cursor.
*/
static int wholenumberClose(sqlite4_vtab_cursor *cur){
  sqlite4_free(cur);
  return SQLITE_OK;
}


/*
** Advance a cursor to its next row of output
*/
static int wholenumberNext(sqlite4_vtab_cursor *cur){
  wholenumber_cursor *pCur = (wholenumber_cursor*)cur;
  pCur->iValue++;
  return SQLITE_OK;
}

/*
** Return the value associated with a wholenumber.
*/
static int wholenumberColumn(
  sqlite4_vtab_cursor *cur,
  sqlite4_context *ctx,
  int i
){
  wholenumber_cursor *pCur = (wholenumber_cursor*)cur;
  sqlite4_result_int64(ctx, pCur->iValue);
  return SQLITE_OK;
}

/*
** The rowid.
*/
static int wholenumberRowid(sqlite4_vtab_cursor *cur, sqlite_int64 *pRowid){
  wholenumber_cursor *pCur = (wholenumber_cursor*)cur;
  *pRowid = pCur->iValue;
  return SQLITE_OK;
}

/*
** When the wholenumber_cursor.rLimit value is 0 or less, that is a signal
** that the cursor has nothing more to output.
*/
static int wholenumberEof(sqlite4_vtab_cursor *cur){
  wholenumber_cursor *pCur = (wholenumber_cursor*)cur;
  return pCur->iValue>pCur->mxValue || pCur->iValue==0;
}

/*
** Called to "rewind" a cursor back to the beginning so that
** it starts its output over again.  Always called at least once
** prior to any wholenumberColumn, wholenumberRowid, or wholenumberEof call.
**
**    idxNum   Constraints
**    ------   ---------------------
**      0      (none)
**      1      value > $argv0
**      2      value >= $argv0
**      4      value < $argv0
**      8      value <= $argv0
**
**      5      value > $argv0 AND value < $argv1
**      6      value >= $argv0 AND value < $argv1
**      9      value > $argv0 AND value <= $argv1
**     10      value >= $argv0 AND value <= $argv1
*/
static int wholenumberFilter(
  sqlite4_vtab_cursor *pVtabCursor, 
  int idxNum, const char *idxStr,
  int argc, sqlite4_value **argv
){
  wholenumber_cursor *pCur = (wholenumber_cursor *)pVtabCursor;
  sqlite4_int64 v;
  int i = 0;
  pCur->iValue = 1;
  pCur->mxValue = 0xffffffff;  /* 4294967295 */
  if( idxNum & 3 ){
    v = sqlite4_value_int64(argv[0]) + (idxNum&1);
    if( v>pCur->iValue && v<=pCur->mxValue ) pCur->iValue = v;
    i++;
  }
  if( idxNum & 12 ){
    v = sqlite4_value_int64(argv[i]) - ((idxNum>>2)&1);
    if( v>=pCur->iValue && v<pCur->mxValue ) pCur->mxValue = v;
  }
  return SQLITE_OK;
}

/*
** Search for terms of these forms:
**
**  (1)  value > $value
**  (2)  value >= $value
**  (4)  value < $value
**  (8)  value <= $value
**
** idxNum is an ORed combination of 1 or 2 with 4 or 8.
*/
static int wholenumberBestIndex(
  sqlite4_vtab *tab,
  sqlite4_index_info *pIdxInfo
){
  int i;
  int idxNum = 0;
  int argvIdx = 1;
  int ltIdx = -1;
  int gtIdx = -1;
  const struct sqlite4_index_constraint *pConstraint;
  pConstraint = pIdxInfo->aConstraint;
  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
    if( pConstraint->usable==0 ) continue;
    if( (idxNum & 3)==0 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_GT ){
      idxNum |= 1;
      ltIdx = i;
    }
    if( (idxNum & 3)==0 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_GE ){
      idxNum |= 2;
      ltIdx = i;
    }
    if( (idxNum & 12)==0 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_LT ){
      idxNum |= 4;
      gtIdx = i;
    }
    if( (idxNum & 12)==0 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_LE ){
      idxNum |= 8;
      gtIdx = i;
    }
  }
  pIdxInfo->idxNum = idxNum;
  if( ltIdx>=0 ){
    pIdxInfo->aConstraintUsage[ltIdx].argvIndex = argvIdx++;
    pIdxInfo->aConstraintUsage[ltIdx].omit = 1;
  }
  if( gtIdx>=0 ){
    pIdxInfo->aConstraintUsage[gtIdx].argvIndex = argvIdx;
    pIdxInfo->aConstraintUsage[gtIdx].omit = 1;
  }
  if( pIdxInfo->nOrderBy==1
   && pIdxInfo->aOrderBy[0].desc==0
  ){
    pIdxInfo->orderByConsumed = 1;
  }
  pIdxInfo->estimatedCost = (double)1;
  return SQLITE_OK;
}

/*
** A virtual table module that provides read-only access to a
** Tcl global variable namespace.
*/
static sqlite4_module wholenumberModule = {
  0,                         /* iVersion */
  wholenumberConnect,
  wholenumberConnect,
  wholenumberBestIndex,
  wholenumberDisconnect, 
  wholenumberDisconnect,
  wholenumberOpen,           /* xOpen - open a cursor */
  wholenumberClose,          /* xClose - close a cursor */
  wholenumberFilter,         /* xFilter - configure scan constraints */
  wholenumberNext,           /* xNext - advance a cursor */
  wholenumberEof,            /* xEof - check for end of scan */
  wholenumberColumn,         /* xColumn - read data */
  wholenumberRowid,          /* xRowid - read data */
  0,                         /* xUpdate */
  0,                         /* xBegin */
  0,                         /* xSync */
  0,                         /* xCommit */
  0,                         /* xRollback */
  0,                         /* xFindMethod */
  0,                         /* xRename */
};

#endif /* SQLITE_OMIT_VIRTUALTABLE */


/*
** Register the wholenumber virtual table
*/
int wholenumber_register(sqlite4 *db){
  int rc = SQLITE_OK;
#ifndef SQLITE_OMIT_VIRTUALTABLE
  rc = sqlite4_create_module(db, "wholenumber", &wholenumberModule, 0);
#endif
  return rc;
}

#ifdef SQLITE_TEST
#include <tcl.h>
/*
** Decode a pointer to an sqlite4 object.
*/
extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite4 **ppDb);

/*
** Register the echo virtual table module.
*/
static int register_wholenumber_module(
  ClientData clientData, /* Pointer to sqlite4_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite4 *db;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
  wholenumber_register(db);
  return TCL_OK;
}


/*
** Register commands with the TCL interpreter.
*/
int Sqlitetestwholenumber_Init(Tcl_Interp *interp){
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
     void *clientData;
  } aObjCmd[] = {
     { "register_wholenumber_module",   register_wholenumber_module, 0 },
  };
  int i;
  for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
    Tcl_CreateObjCommand(interp, aObjCmd[i].zName, 
        aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
  }
  return TCL_OK;
}

#endif /* SQLITE_TEST */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































































































































































































































































































































































































































































































































Deleted test/tkt-313723c356.test.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# 2010 September 20
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket [313723c356] has been
# fixed.  
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/malloc_common.tcl

ifcapable !wal { finish_test ; return }

do_execsql_test tkt-313723c356.1 {
  PRAGMA page_size = 1024;
  PRAGMA journal_mode = WAL;
  CREATE TABLE t1(a, b);
  CREATE INDEX i1 ON t1(a, b);
  INSERT INTO t1 VALUES(randomblob(400), randomblob(400));
  INSERT INTO t1 SELECT randomblob(400), randomblob(400) FROM t1;
  INSERT INTO t1 SELECT randomblob(400), randomblob(400) FROM t1;
  INSERT INTO t1 SELECT randomblob(400), randomblob(400) FROM t1;
  INSERT INTO t1 SELECT randomblob(400), randomblob(400) FROM t1;
} {wal}
faultsim_save_and_close

do_faultsim_test tkt-313723c356.2 -faults shmerr* -prep {
  faultsim_restore_and_reopen
  sqlite4 db2 test.db
  db eval  { SELECT * FROM t1 }
  db2 eval { UPDATE t1 SET a = randomblob(399) }
  db2 close
} -body {
  # At this point, the cache contains all of table t1 and none of index i1. The
  # cache is out of date. When the bug existed and the right xShmLock() fails
  # in the following statement, the internal cache of the WAL header was
  # being updated, but the contents of the page-cache not flushed. This causes
  # the integrity-check in the "-test" code to fail, as it is comparing the
  # cached (out-of-date) version of table t1 with the on disk (up-to-date)
  # version of index i1.
  #
  execsql { SELECT min(rowid) FROM t1 }
} -test {
  faultsim_test_result {0 1}
  faultsim_integrity_check
}

finish_test
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































































Deleted test/tkt1512.test.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 2005 September 19
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #1512 is
# fixed.  
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable {!vacuum || !autovacuum} {
  finish_test
  return
}
if {[db one {PRAGMA auto_vacuum}]} {
  finish_test
  return
}

do_test tkt1512-1.1 {
  execsql {
    CREATE TABLE t1(a,b);
    INSERT INTO t1 VALUES(1,2);
    INSERT INTO t1 VALUES(3,4);
    SELECT * FROM t1
  }
} {1 2 3 4}
do_test tkt1512-1.2 {
  file size test.db
} {2048}
do_test tkt1512-1.3 {
  execsql {
    DROP TABLE t1;
  }
  file size test.db
} {2048}
do_test tkt1512-1.4 {
  execsql {
    VACUUM;
  }
  file size test.db
} {1024}


finish_test
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































Deleted test/tkt1667.test.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# 2006 February 10
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.
#
# This file implements tests to verify that ticket #1667 has been
# fixed.  
#
#
# $Id: tkt1667.test,v 1.4 2009/02/05 17:00:54 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

ifcapable !autovacuum||!tclvar {
  finish_test
  return
}

db close
forcedelete test.db test.db-journal

# Set the pending byte offset such that the page it is on is
# the first autovacuum pointer map page in the file (assume a page 
# size of 1024).

set first_ptrmap_page   [expr 1024/5 + 3]
sqlite4_test_control_pending_byte [expr 1024 * ($first_ptrmap_page-1)]

sqlite4 db test.db

do_test tkt1667-1 {
  execsql {
    PRAGMA auto_vacuum = 1;
    BEGIN;
    CREATE TABLE t1(a, b);
  }
  for {set i 0} {$i < 500} {incr i} {
    execsql {
      INSERT INTO t1 VALUES($i, randstr(1000, 2000))
    }
  }
  execsql {
    COMMIT;
  }
} {}
for {set i 0} {$i < 500} {incr i} {
  do_test tkt1667-2.$i.1 {
    execsql {
      DELETE FROM t1 WHERE a = $i;
    }
  } {}
  integrity_check tkt1667-2.$i.2
}

do_test tkt1667-3 {
  execsql {
    BEGIN;
  }
  for {set i 0} {$i < 500} {incr i} {
    execsql {
      INSERT INTO t1 VALUES($i, randstr(1000, 2000))
    }
  }
  execsql {
    COMMIT;
  }
} {}
do_test tkt1667-4.1 {
  execsql {
    DELETE FROM t1;
  }
} {}
integrity_check tkt1667-4.2

finish_test
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































































































































Changes to test/tt3_checkpoint.c.

142
143
144
145
146
147
148
149
150
  CheckpointStarvationCtx ctx = { SQLITE_CHECKPOINT_RESTART, 0 };
  checkpoint_starvation_main(nMs, &ctx);
  if( ctx.nMaxFrame>CHECKPOINT_STARVATION_FRAMELIMIT+10 ){
    test_error(&err, "WAL grew too large - %d frames", ctx.nMaxFrame);
  }
  print_and_free_err(&err);
}









<
<
142
143
144
145
146
147
148


  CheckpointStarvationCtx ctx = { SQLITE_CHECKPOINT_RESTART, 0 };
  checkpoint_starvation_main(nMs, &ctx);
  if( ctx.nMaxFrame>CHECKPOINT_STARVATION_FRAMELIMIT+10 ){
    test_error(&err, "WAL grew too large - %d frames", ctx.nMaxFrame);
  }
  print_and_free_err(&err);
}


Changes to www/index.wiki.

2
3
4
5
6
7
8


  *  [./design.wiki | The Design Of SQLite4]
  *  [./env.wiki | The Run-time Environment Object]
  *  [./varint.wiki | The Varint format]
  *  [./data_encoding.wiki | The Data Encoding]
  *  [./key_encoding.wiki | The Key Encoding]
  *  [./decimal.wiki | Internal representation of numeric values]








>
2
3
4
5
6
7
8
9

  *  [./design.wiki | The Design Of SQLite4]
  *  [./env.wiki | The Run-time Environment Object]
  *  [./varint.wiki | The Varint format]
  *  [./data_encoding.wiki | The Data Encoding]
  *  [./key_encoding.wiki | The Key Encoding]
  *  [./decimal.wiki | Internal representation of numeric values]
  *  [./porting.wiki | Porting an app from SQLite3 to SQLite4]

Added www/porting.wiki.























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<title>Porting SQLite3 to SQLite4</title>
<nowiki>

<p>The following are notes on how to port an application from using SQLite3
to use SQLite4:

<ul>
<li><p>Global change "sqlite3" to "sqlite4"

<li><p>Add the sqlite4_env* parameter (probably NULL) as the first
    argument to the following interfaces:
<ul>
<li> sqlite4_open()
<li> sqlite4_malloc()
<li> sqlite4_realloc()
<li> sqlite4_free()
<li> sqlite4_mprintf()
<li> sqlite4_vmprintf()
</ul>

<li><p>Check all uses of sqlite4_snprintf() and sqlite4_vnsprintf() for
    the new function signature:
<ul>
<li>The order of the first two arguments is reversed
<li>Both routines return the length of the result string.
</ul>
</ul>