Check-in [0acaefd7b1]
Not logged in

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

Overview
Comment:cleanup after merge
Timelines: family | ancestors | descendants | both | wtf-8-experiment
Files: files | file ages | folders
SHA1: 0acaefd7b1a421899fb9e6bfe754e8a4f3deccaf
User & Date: chw 2019-07-12 16:49:12
Context
2019-07-13
05:27
merge with trunk check-in: 027300a91d user: chw tags: wtf-8-experiment
2019-07-12
16:49
cleanup after merge check-in: 0acaefd7b1 user: chw tags: wtf-8-experiment
16:43
merge with trunk check-in: 38e2e19036 user: chw tags: wtf-8-experiment
Changes

Changes to jni/tcl/pkgs/sqlite3.29.0/generic/tclsqlite3.c.

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
...
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
...
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
...
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
...
607
608
609
610
611
612
613

614
615
616
617
618
619
620
...
888
889
890
891
892
893
894











895
896

897
898
899
900
901
902
903
...
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
...
955
956
957
958
959
960
961











962
963

964
965
966
967
968
969
970
...
994
995
996
997
998
999
1000









1001

1002
1003
1004
1005
1006
1007
1008
....
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
....
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
....
1362
1363
1364
1365
1366
1367
1368

1369
1370
1371
1372
1373
1374
1375
....
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
....
1444
1445
1446
1447
1448
1449
1450

1451
1452





1453
1454
1455
1456
1457
1458
1459
....
1495
1496
1497
1498
1499
1500
1501








1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513

1514
1515
1516
1517
1518
1519
1520
....
1580
1581
1582
1583
1584
1585
1586

1587
1588
1589
1590
1591
1592
1593
....
1627
1628
1629
1630
1631
1632
1633





1634

1635
1636
1637
1638
1639
1640
1641
....
1657
1658
1659
1660
1661
1662
1663








1664

1665
1666
1667
1668
1669
1670
1671
....
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
....
1773
1774
1775
1776
1777
1778
1779

1780
1781
1782
1783
1784
1785
1786
....
1806
1807
1808
1809
1810
1811
1812








1813
1814
1815
1816
1817
1818
1819
1820
....
2093
2094
2095
2096
2097
2098
2099







2100
2101

2102



2103




2104

2105
2106
2107







2108

2109



2110




2111

2112
2113
2114
2115
2116
2117
2118
2119



2120




2121

2122
2123
2124
2125
2126
2127
2128
....
2287
2288
2289
2290
2291
2292
2293

2294
2295
2296
2297
2298






2299
2300
2301
2302
2303
2304
2305
2306
2307
2308

2309
2310
2311

2312
2313
2314
2315
2316
2317
2318
....
2461
2462
2463
2464
2465
2466
2467






2468

2469
2470
2471
2472
2473
2474
2475
2476
2477

2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490



2491




2492

2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503

2504
2505
2506
2507
2508
2509
2510
....
2548
2549
2550
2551
2552
2553
2554






2555
2556

2557
2558
2559
2560
2561
2562
2563

2564
2565
2566
2567
2568
2569
2570
....
2642
2643
2644
2645
2646
2647
2648







2649

2650
2651
2652
2653
2654
2655
2656
....
2812
2813
2814
2815
2816
2817
2818

2819
2820
2821
2822
2823
2824
2825
....
2858
2859
2860
2861
2862
2863
2864






2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875

2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
....
2908
2909
2910
2911
2912
2913
2914





2915








2916
2917

2918
2919
2920
2921
2922
2923
2924
....
3079
3080
3081
3082
3083
3084
3085






3086

3087
3088
3089
3090
3091
3092
3093
....
3108
3109
3110
3111
3112
3113
3114







3115
3116

3117



3118




3119

3120
3121
3122







3123

3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
....
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
....
3165
3166
3167
3168
3169
3170
3171







3172


3173
3174
3175
3176
3177
3178
3179
....
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
....
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
....
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
....
3792
3793
3794
3795
3796
3797
3798

3799
3800













3801

3802
3803
3804
3805
3806
3807
3808
....
3811
3812
3813
3814
3815
3816
3817






3818

3819
3820
3821
3822
3823
3824
3825
....
3890
3891
3892
3893
3894
3895
3896







































3897
3898
3899

3900
















3901


3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915


3916


3917
3918
3919
3920
3921
3922
3923
  int nStep, nSort, nIndex;  /* Statistics for most recent operation */
  int nVMStep;               /* Another statistic for most recent operation */
  int nTransaction;          /* Number of nested [transaction] methods */
  int openFlags;             /* Flags used to open.  (SQLITE_OPEN_URI) */
#ifdef SQLITE_TEST
  int bLegacyPrepare;        /* True to use sqlite3_prepare() */
#endif

};

struct IncrblobChannel {
  sqlite3_blob *pBlob;      /* sqlite3 blob handle */
  SqliteDb *pDb;            /* Associated database connection */
  int iSeek;                /* Current seek offset */
  Tcl_Channel channel;      /* Channel identifier */
  IncrblobChannel *pNext;   /* Linked list of all open incrblob channels */
  IncrblobChannel *pPrev;   /* Linked list of all open incrblob channels */
};










/*
** Compute a string length that is limited to what can be stored in
** lower 30 bits of a 32-bit signed integer.
*/
static int strlen30(const char *z){
  const char *z2 = z;
  while( *z2 ){ z2++; }
................................................................................
  return 0x3fffffff & (int)(z2 - z);
}

#ifdef USE_TCL_STUBS
# define tclStubsPtr staticTclStubsPtr
static const TclStubs *tclStubsPtr = 0;
#endif




















#ifndef SQLITE_OMIT_INCRBLOB
/*
** Close all incrblob channels opened using database connection pDb.
** This is called when shutting down the database connection.
*/
static void closeIncrblobChannels(SqliteDb *pDb){
................................................................................
*/
static int SQLITE_TCLAPI incrblobClose(
  ClientData instanceData,
  Tcl_Interp *interp
){
  IncrblobChannel *p = (IncrblobChannel *)instanceData;
  int rc = sqlite3_blob_close(p->pBlob);
  sqlite3 *db = p->pDb->db;

  /* Remove the channel from the SqliteDb.pIncrblob list. */
  if( p->pNext ){
    p->pNext->pPrev = p->pPrev;
  }
  if( p->pPrev ){
    p->pPrev->pNext = p->pNext;
................................................................................
    p->pDb->pIncrblob = p->pNext;
  }

  /* Free the IncrblobChannel structure */
  Tcl_Free((char *)p);

  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, sqlite3_errmsg(db), (char*)0);
    return TCL_ERROR;
  }
  return TCL_OK;
}

/*
** Read data from an incremental blob channel.
................................................................................

  /* This variable is used to name the channels: "incrblob_[incr count]" */
  static int count = 0;
  char zChannel[64];

  rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
    return TCL_ERROR;
  }

  p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
  p->iSeek = 0;
  p->pBlob = pBlob;

................................................................................
  }
  if( pDb->pWalHook ){
    Tcl_DecrRefCount(pDb->pWalHook);
  }
  if( pDb->pCollateNeeded ){
    Tcl_DecrRefCount(pDb->pCollateNeeded);
  }

  Tcl_Free((char*)pDb);
}

/*
** This routine is called when a database file is locked while trying
** to execute SQL.
*/
................................................................................
  assert( pDb->pPreUpdateHook );
  assert( db==pDb->db );
  assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );

  pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
  Tcl_IncrRefCount(pCmd);
  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));











  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));

  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
  Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
  Tcl_DecrRefCount(pCmd);
}
#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */

................................................................................

  assert( pDb->pUpdateHook );
  assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );

  pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
  Tcl_IncrRefCount(pCmd);
  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));











  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));

  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
  Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
  Tcl_DecrRefCount(pCmd);
}

static void tclCollateNeeded(
  void *pCtx,
................................................................................
  sqlite3 *db,
  int enc,
  const char *zName
){
  SqliteDb *pDb = (SqliteDb *)pCtx;
  Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
  Tcl_IncrRefCount(pScript);







  Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));

  Tcl_EvalObjEx(pDb->interp, pScript, 0);
  Tcl_DecrRefCount(pScript);
}

/*
** This routine is called to evaluate an SQL collation function implemented
** using TCL script.
................................................................................
  const void *zB
){
  SqlCollate *p = (SqlCollate *)pCtx;
  Tcl_Obj *pCmd;

  pCmd = Tcl_NewStringObj(p->zScript, -1);
  Tcl_IncrRefCount(pCmd);











  Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
  Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));

  Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
  Tcl_DecrRefCount(pCmd);
  return (atoi(Tcl_GetStringResult(p->interp)));
}

/*
** This routine is called to evaluate an SQL function implemented
................................................................................
    ** That way, when Tcl_EvalObjv() is run and shimmers the first element
    ** of the list to tclCmdNameType, that alternate representation will
    ** be preserved and reused on the next invocation.
    */
    Tcl_Obj **aArg;
    int nArg;
    if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){









      sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);

      return;
    }
    pCmd = Tcl_NewListObj(nArg, aArg);
    Tcl_IncrRefCount(pCmd);
    for(i=0; i<argc; i++){
      sqlite3_value *pIn = argv[i];
      Tcl_Obj *pVal;
................................................................................
        }
        case SQLITE_NULL: {
          pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
          break;
        }
        default: {
          int bytes = sqlite3_value_bytes(pIn);








          pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);

          break;
        }
      }
      rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
      if( rc ){
        Tcl_DecrRefCount(pCmd);
        sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
        return;
      }
    }
    if( !p->useEvalObjv ){
      /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
      ** is a list without a string representation.  To prevent this from
      ** happening, make sure pCmd has a valid string representation */
      Tcl_GetString(pCmd);
    }
    rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
    Tcl_DecrRefCount(pCmd);
  }

  if( rc && rc!=TCL_RETURN ){
    sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
  }else{
    Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
    int n;
    u8 *data;
    const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
    char c = zType[0];
    int eType = p->eType;
................................................................................
      ** and try to rollback the transaction.
      **
      ** But it could also be that the user executed one or more BEGIN,
      ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
      ** this method's logic. Not clear how this would be best handled.
      */
    if( rc!=TCL_ERROR ){
      Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
      rc = TCL_ERROR;
    }
    sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
  }
  pDb->disableAuth--;

  return rc;
................................................................................
  int nVar = 0;                   /* Number of variables in statement */
  int iParm = 0;                  /* Next free entry in apParm */
  char c;
  int i;
  int needResultReset = 0;        /* Need to invoke Tcl_ResetResult() */
  int rc = SQLITE_OK;             /* Value to return */
  Tcl_Interp *interp = pDb->interp;


  *ppPreStmt = 0;

  /* Trim spaces from the start of zSql and calculate the remaining length. */
  while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
  nSql = strlen30(zSql);

................................................................................

  /* If no prepared statement was found. Compile the SQL text. Also allocate
  ** a new SqlPreparedStmt structure.  */
  if( pPreStmt==0 ){
    int nByte;

    if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
      Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
      return TCL_ERROR;
    }
    if( pStmt==0 ){
      if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
        /* A compile-time error in the statement. */
        Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
        return TCL_ERROR;
      }else{
        /* The statement was a no-op.  Continue to the next statement
        ** in the SQL string.
        */
        return TCL_OK;
      }
................................................................................
#endif
  }
  assert( pPreStmt );
  assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
  assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );

  /* Bind values to parameters that begin with $ or : */

  for(i=1; i<=nVar; i++){
    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);





    if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
      Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
      if( pVar==0 && pDb->zBindFallback!=0 ){
        Tcl_Obj *pCmd;
        int rx;
        pCmd = Tcl_NewStringObj(pDb->zBindFallback, -1);
        Tcl_IncrRefCount(pCmd);
................................................................................
          Tcl_GetDoubleFromObj(interp, pVar, &r);
          sqlite3_bind_double(pStmt, i, r);
        }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
              (c=='i' && strcmp(zType,"int")==0) ){
          Tcl_WideInt v;
          Tcl_GetWideIntFromObj(interp, pVar, &v);
          sqlite3_bind_int64(pStmt, i, v);








        }else{
          data = (unsigned char *)Tcl_GetString(pVar);
          sqlite3_bind_text(pStmt, i, (char *)data, pVar->length, SQLITE_STATIC);
          Tcl_IncrRefCount(pVar);
          pPreStmt->apParm[iParm++] = pVar;
        }
      }else{
        sqlite3_bind_null(pStmt, i);
      }
      if( needResultReset ) Tcl_ResetResult(pDb->interp);
    }
  }

  pPreStmt->nParm = iParm;
  *ppPreStmt = pPreStmt;
  if( needResultReset && rc==TCL_OK ) Tcl_ResetResult(pDb->interp);

  return rc;
}

................................................................................
**   dbEvalRowInfo()
**   dbEvalColumnValue()
*/
typedef struct DbEvalContext DbEvalContext;
struct DbEvalContext {
  SqliteDb *pDb;                  /* Database handle */
  Tcl_Obj *pSql;                  /* Object holding string zSql */

  const char *zSql;               /* Remaining SQL to execute */
  SqlPreparedStmt *pPreStmt;      /* Current statement */
  int nCol;                       /* Number of columns returned by pStmt */
  int evalFlags;                  /* Flags used */
  Tcl_Obj *pArray;                /* Name of array variable */
  Tcl_Obj **apColName;            /* Array of column names */
};
................................................................................
  SqliteDb *pDb,                  /* Database handle */
  Tcl_Obj *pSql,                  /* Object containing SQL script */
  Tcl_Obj *pArray,                /* Name of Tcl array to set (*) element of */
  int evalFlags                   /* Flags controlling evaluation */
){
  memset(p, 0, sizeof(DbEvalContext));
  p->pDb = pDb;





  p->zSql = Tcl_GetString(pSql);

  p->pSql = pSql;
  Tcl_IncrRefCount(pSql);
  if( pArray ){
    p->pArray = pArray;
    Tcl_IncrRefCount(pArray);
  }
  p->evalFlags = evalFlags;
................................................................................
    int nCol;                     /* Number of columns returned by pStmt */
    Tcl_Obj **apColName = 0;      /* Array of column names */

    p->nCol = nCol = sqlite3_column_count(pStmt);
    if( nCol>0 && (papColName || p->pArray) ){
      apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
      for(i=0; i<nCol; i++){








        apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);

        Tcl_IncrRefCount(apColName[i]);
      }
      p->apColName = apColName;
    }

    /* If results are being stored in an array variable, then create
    ** the array(*) entry for that array
................................................................................
          ** This only happens once. If there is a second SQLITE_SCHEMA
          ** error, the error will be returned to the caller. */
          p->zSql = zPrevSql;
          continue;
        }
#endif
        Tcl_SetObjResult(pDb->interp,
                         Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
        return TCL_ERROR;
      }else{
        dbReleaseStmt(pDb, pPreStmt, 0);
      }
    }
  }

................................................................................
    dbReleaseStmt(p->pDb, p->pPreStmt, 0);
    p->pPreStmt = 0;
  }
  if( p->pArray ){
    Tcl_DecrRefCount(p->pArray);
    p->pArray = 0;
  }

  Tcl_DecrRefCount(p->pSql);
  dbReleaseColumnNames(p);
}

/*
** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
** the value for the iCol'th column of the row currently pointed to by
................................................................................
    case SQLITE_FLOAT: {
      return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
    }
    case SQLITE_NULL: {
      return Tcl_NewStringObj(p->pDb->zNull, -1);
    }
  }









  return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
}

/*
** If using Tcl version 8.6 or greater, use the NR functions to avoid
** recursive evalution of scripts by the [db eval] and [db trans]
** commands. Even if the headers used while compiling the extension
................................................................................
    }else if( objc==4 ){
      zSrcDb = Tcl_GetString(objv[2]);
      zDestFile = Tcl_GetString(objv[3]);
    }else{
      Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
      return TCL_ERROR;
    }







    rc = sqlite3_open_v2(zDestFile, &pDest,
               SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);

    if( rc!=SQLITE_OK ){



      Tcl_AppendResult(interp, "cannot open target database: ",




           sqlite3_errmsg(pDest), (char*)0);

      sqlite3_close(pDest);
      return TCL_ERROR;
    }







    pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);

    if( pBackup==0 ){



      Tcl_AppendResult(interp, "backup failed: ",




           sqlite3_errmsg(pDest), (char*)0);

      sqlite3_close(pDest);
      return TCL_ERROR;
    }
    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
    sqlite3_backup_finish(pBackup);
    if( rc==SQLITE_DONE ){
      rc = TCL_OK;
    }else{



      Tcl_AppendResult(interp, "backup failed: ",




           sqlite3_errmsg(pDest), (char*)0);

      rc = TCL_ERROR;
    }
    sqlite3_close(pDest);
    break;
  }

  /*    $db bind_fallback ?CALLBACK?
................................................................................
  ** that function is called, invoke SCRIPT to evaluate the function.
  */
  case DB_COLLATE: {
    SqlCollate *pCollate;
    char *zName;
    char *zScript;
    int nScript;

    if( objc!=4 ){
      Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
      return TCL_ERROR;
    }
    zName = Tcl_GetString(objv[2]);






    zScript = Tcl_GetStringFromObj(objv[3], &nScript);
    pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
    if( pCollate==0 ) return TCL_ERROR;
    pCollate->interp = interp;
    pCollate->pNext = pDb->pCollate;
    pCollate->zScript = (char*)&pCollate[1];
    pDb->pCollate = pCollate;
    memcpy(pCollate->zScript, zScript, nScript+1);
    if( sqlite3_create_collation_v2(pDb->db, zName, SQLITE_UTF8,
        pCollate, tclSqlCollate, 0) ){

      Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
      return TCL_ERROR;
    }

    break;
  }

  /*
  **     $db collation_needed SCRIPT
  **
  ** Create a new SQL collation function called NAME.  Whenever
................................................................................
       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", (char*)0);
      return TCL_ERROR;
    }






    zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);

    if( zSql==0 ){
      Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
      return TCL_ERROR;
    }
    nByte = strlen30(zSql);
    rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
    sqlite3_free(zSql);
    if( rc ){
      Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);

      nCol = 0;
    }else{
      nCol = sqlite3_column_count(pStmt);
    }
    sqlite3_finalize(pStmt);
    if( nCol==0 ) {
      return TCL_ERROR;
    }
    zSql = sqlite3_malloc( nByte + 50 + nCol*2 );
    if( zSql==0 ) {
      Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
      return TCL_ERROR;
    }



    sqlite3_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 = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
    sqlite3_free(zSql);
    if( rc ){
      Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);

      sqlite3_finalize(pStmt);
      return TCL_ERROR;
    }
    in = Tcl_OpenFileChannel(interp, zFile, "r", 0666);
    if( in==0 ){
      sqlite3_finalize(pStmt);
      return TCL_ERROR;
................................................................................
        break;
      }
      for(i=0; i<nCol; i++){
        /* check for null data, if so, bind as null */
        if( (azCol[i][0]==0) || (nNull>0 && strcmp(azCol[i], zNull)==0)
        ){
          sqlite3_bind_null(pStmt, i+1);






        }else{
          sqlite3_bind_text(pStmt, i+1, azCol[i], strlen30(azCol[i]), SQLITE_STATIC);

        }
      }
      sqlite3_step(pStmt);
      rc = sqlite3_reset(pStmt);
      Tcl_DStringSetLength(&str, 0);
      if( rc!=SQLITE_OK ){
        Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);

        zCommit = "ROLLBACK";
        break;
      }
    }
    Tcl_DStringFree(&str);
    sqlite3_free(azCol);
    Tcl_Close(interp, in);
................................................................................
      int flags;
      if( len>0 ) memcpy(pData, pBA, len);
      if( isReadonly ){
        flags = SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_READONLY;
      }else{
        flags = SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_RESIZEABLE;
      }







      xrc = sqlite3_deserialize(pDb->db, zSchema, pData, len, len, flags);

      if( xrc ){
        Tcl_AppendResult(interp, "unable to set MEMDB content", (char*)0);
        rc = TCL_ERROR;
      }
      if( mxSize>0 ){
        sqlite3_file_control(pDb->db, zSchema,SQLITE_FCNTL_SIZE_LIMIT,&mxSize);
      }
................................................................................
    int flags = SQLITE_UTF8;
    SqlFunc *pFunc;
    Tcl_Obj *pScript;
    char *zName;
    int nArg = -1;
    int i;
    int eType = SQLITE_NULL;

    if( objc<4 ){
      Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
      return TCL_ERROR;
    }
    for(i=3; i<(objc-1); i++){
      const char *z = Tcl_GetString(objv[i]);
      int n = strlen30(z);
................................................................................
        );
        return TCL_ERROR;
      }
    }

    pScript = objv[objc-1];
    zName = Tcl_GetString(objv[2]);






    pFunc = findSqlFunc(pDb, zName);
    if( pFunc==0 ) return TCL_ERROR;
    if( pFunc->pScript ){
      Tcl_DecrRefCount(pFunc->pScript);
    }
    pFunc->pScript = pScript;
    Tcl_IncrRefCount(pScript);
    pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
    pFunc->eType = eType;
    rc = sqlite3_create_function_v2(pDb->db, zName, nArg, flags,
        pFunc, tclSqlFunc, 0, 0, 0);

    if( rc!=SQLITE_OK ){
      rc = TCL_ERROR;
      Tcl_AppendResult(interp, (char *)sqlite3_errmsg(pDb->db), (char*)0);
    }
    break;
  }

  /*
  **     $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
  */
................................................................................
      zDb = Tcl_GetString(objv[2]);
    }
    zTable = Tcl_GetString(objv[objc-3]);
    zColumn = Tcl_GetString(objv[objc-2]);
    rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);

    if( rc==TCL_OK ){





      rc = createIncrblobChannel(








          interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
      );

    }
#endif
    break;
  }

  /*
  **     $db interrupt
................................................................................
      Tcl_WrongNumArgs(interp, 2, objv, "KEY");
      return TCL_ERROR;
    }
#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
    pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
    rc = sqlite3_rekey(pDb->db, pKey, nKey);
    if( rc ){






      Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);

      rc = TCL_ERROR;
    }
#endif
    break;
  }

  /*    $db restore ?DATABASE? FILENAME
................................................................................
    }else if( objc==4 ){
      zDestDb = Tcl_GetString(objv[2]);
      zSrcFile = Tcl_GetString(objv[3]);
    }else{
      Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
      return TCL_ERROR;
    }







    rc = sqlite3_open_v2(zSrcFile, &pSrc,
                         SQLITE_OPEN_READONLY | pDb->openFlags, 0);

    if( rc!=SQLITE_OK ){



      Tcl_AppendResult(interp, "cannot open source database: ",




           sqlite3_errmsg(pSrc), (char*)0);

      sqlite3_close(pSrc);
      return TCL_ERROR;
    }







    pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");

    if( pBackup==0 ){
      Tcl_AppendResult(interp, "restore failed: ",
           sqlite3_errmsg(pDb->db), (char*)0);
      sqlite3_close(pSrc);
      return TCL_ERROR;
    }
    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
              || rc==SQLITE_BUSY ){
      if( rc==SQLITE_BUSY ){
        if( nTimeout++ >= 3 ) break;
................................................................................
      rc = TCL_OK;
    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
      Tcl_AppendResult(interp, "restore failed: source database busy",
                       (char*)0);
      rc = TCL_ERROR;
    }else{
      Tcl_AppendResult(interp, "restore failed: ",
           sqlite3_errmsg(pDb->db), (char*)0);
      rc = TCL_ERROR;
    }
    sqlite3_close(pSrc);
    break;
  }

  /*
................................................................................
    sqlite3_int64 sz = 0;
    unsigned char *pData;
    if( objc!=2 && objc!=3 ){
      Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE?");
      rc = TCL_ERROR;
    }else{
      int needFree;







      pData = sqlite3_serialize(pDb->db, zSchema, &sz, SQLITE_SERIALIZE_NOCOPY);


      if( pData ){
        needFree = 0;
      }else{
        pData = sqlite3_serialize(pDb->db, zSchema, &sz, 0);
        needFree = 1;
      }
      Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(pData,sz));
................................................................................
    pScript = objv[objc-1];

    /* Run the SQLite BEGIN command to open a transaction or savepoint. */
    pDb->disableAuth++;
    rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
    pDb->disableAuth--;
    if( rc!=SQLITE_OK ){
      Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
      return TCL_ERROR;
    }
    pDb->nTransaction++;

    /* If using NRE, schedule a callback to invoke the script pScript, then
    ** a second callback to commit (or rollback) the transaction or savepoint
    ** opened above. If not using NRE, evaluate the script directly, then
................................................................................
        xNotify = DbUnlockNotify;
        pNotifyArg = (void *)pDb;
        pDb->pUnlockNotify = objv[2];
        Tcl_IncrRefCount(pDb->pUnlockNotify);
      }

      if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
        Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
        rc = TCL_ERROR;
      }
    }
#endif
    break;
  }

................................................................................
        }

        if( rc==SQLITE_OK ){
          Tcl_Obj *pObj;
          pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
          Tcl_SetObjResult(interp, pObj);
        }else{
          Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
          return TCL_ERROR;
        }
      }
    }
#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
    break;
  }
................................................................................
      Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
      return TCL_ERROR;
    }
  }
  zErrMsg = 0;
  p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
  memset(p, 0, sizeof(*p));

  if( zFile==0 ) zFile = "";
  zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);













  rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);

  Tcl_DStringFree(&translatedFilename);
  if( p->db ){
    if( SQLITE_OK!=sqlite3_errcode(p->db) ){
      zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
      sqlite3_close(p->db);
      p->db = 0;
    }
................................................................................
  }
#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
  if( p->db ){
    sqlite3_key(p->db, pKey, nKey);
  }
#endif
  if( p->db==0 ){






    Tcl_AppendResult(interp, zErrMsg, (char*)0);

    Tcl_Free((char*)p);
    sqlite3_free(zErrMsg);
    return TCL_ERROR;
  }
  p->maxStmt = NUM_PREPARED_STMTS;
  p->openFlags = flags & SQLITE_OPEN_URI;
  p->interp = interp;
................................................................................
    /* The "sqlite" alias is undocumented.  It is here only to support
    ** legacy scripts.  All new scripts should use only the "sqlite3"
    ** command. */
    Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
#endif
    rc = Tcl_PkgProvideEx(interp, "sqlite3", PACKAGE_VERSION, NULL);
  }







































  return rc;
}
DLLEXPORT int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }

DLLEXPORT int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
















DLLEXPORT int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }



/* Because it accesses the file-system and uses persistent state, SQLite
** is not considered appropriate for safe interpreters.  Hence, we cause
** the _SafeInit() interfaces return TCL_ERROR.
*/
DLLEXPORT int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
DLLEXPORT int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}



#ifndef SQLITE_3_SUFFIX_ONLY
int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }


int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }


#endif

/*
** If the TCLSH macro is defined, add code to make a stand-alone program.
*/
#if defined(TCLSH)








>











>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|







 







|







 







|







 







>







 







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







 







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







 







>
>
>
>
>
>
>
|
>







 







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







 







>
>
>
>
>
>
>
>
>
|
>







 







>
>
>
>
>
>
>
>
|
>






|
<













|







 







|







 







>







 







|





|







 







>


>
>
>
>
>







 







>
>
>
>
>
>
>
>












>







 







>







 







>
>
>
>
>
|
>







 







>
>
>
>
>
>
>
>
|
>







 







|







 







>







 







>
>
>
>
>
>
>
>
|







 







>
>
>
>
>
>
>
|

>

>
>
>
|
>
>
>
>
|
>



>
>
>
>
>
>
>
|
>

>
>
>
|
>
>
>
>
|
>








>
>
>
|
>
>
>
>
|
>







 







>





>
>
>
>
>
>










>
|


>







 







>
>
>
>
>
>
|
>








|
>













>
>
>
|
>
>
>
>
|
>










|
>







 







>
>
>
>
>
>

|
>






|
>







 







>
>
>
>
>
>
>
|
>







 







>







 







>
>
>
>
>
>











>


|







 







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







 







>
>
>
>
>
>
|
>







 







>
>
>
>
>
>
>
|
|
>

>
>
>
|
>
>
>
>
|
>



>
>
>
>
>
>
>
|
>


|







 







|







 







>
>
>
>
>
>
>
|
>
>







 







|







 







|







 







|







 







>


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







 







>
>
>
>
>
>
|
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


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













|
>
>
|
>
>







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
...
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
...
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
...
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
...
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
...
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
...
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
....
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
....
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
....
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
....
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
....
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
....
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
....
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
....
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
....
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
....
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
....
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
....
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
....
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
....
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
....
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
....
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
....
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
....
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
....
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
....
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
....
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
....
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
....
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
....
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
....
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
....
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
....
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
....
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
....
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
....
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
....
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
....
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236

4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
  int nStep, nSort, nIndex;  /* Statistics for most recent operation */
  int nVMStep;               /* Another statistic for most recent operation */
  int nTransaction;          /* Number of nested [transaction] methods */
  int openFlags;             /* Flags used to open.  (SQLITE_OPEN_URI) */
#ifdef SQLITE_TEST
  int bLegacyPrepare;        /* True to use sqlite3_prepare() */
#endif
  Tcl_DString dsErr;         /* Used for error messages (utf8Encoding) */
};

struct IncrblobChannel {
  sqlite3_blob *pBlob;      /* sqlite3 blob handle */
  SqliteDb *pDb;            /* Associated database connection */
  int iSeek;                /* Current seek offset */
  Tcl_Channel channel;      /* Channel identifier */
  IncrblobChannel *pNext;   /* Linked list of all open incrblob channels */
  IncrblobChannel *pPrev;   /* Linked list of all open incrblob channels */
};

/*
 ** Tcl UTF-8 encoding; loaded and tested on module init. Depending
 ** on unicode support detected, it is reset to NULL or kept until
 ** module gets unloaded.
 */
static Tcl_Encoding utf8Encoding = NULL;
static int utf8EncInit = 0;
TCL_DECLARE_MUTEX(utf8EncMutex);

/*
** Compute a string length that is limited to what can be stored in
** lower 30 bits of a 32-bit signed integer.
*/
static int strlen30(const char *z){
  const char *z2 = z;
  while( *z2 ){ z2++; }
................................................................................
  return 0x3fffffff & (int)(z2 - z);
}

#ifdef USE_TCL_STUBS
# define tclStubsPtr staticTclStubsPtr
static const TclStubs *tclStubsPtr = 0;
#endif

/*
 ** Error message converter.
 */
static const char *SQLITEDB_ERRMSG(SqliteDb *pDb){
  if( pDb!=NULL ){
    if( pDb->db!=NULL ){
      if( utf8Encoding!=NULL ){
        Tcl_DStringFree(&pDb->dsErr);
        Tcl_ExternalToUtfDString(utf8Encoding, sqlite3_errmsg(pDb->db),
            -1, &pDb->dsErr);
        return Tcl_DStringValue(&pDb->dsErr);
      }
      return sqlite3_errmsg(pDb->db);
    }
    return "not a valid database";
  }
  return "unknown error";
}

#ifndef SQLITE_OMIT_INCRBLOB
/*
** Close all incrblob channels opened using database connection pDb.
** This is called when shutting down the database connection.
*/
static void closeIncrblobChannels(SqliteDb *pDb){
................................................................................
*/
static int SQLITE_TCLAPI incrblobClose(
  ClientData instanceData,
  Tcl_Interp *interp
){
  IncrblobChannel *p = (IncrblobChannel *)instanceData;
  int rc = sqlite3_blob_close(p->pBlob);
  SqliteDb *pDb = p->pDb;

  /* Remove the channel from the SqliteDb.pIncrblob list. */
  if( p->pNext ){
    p->pNext->pPrev = p->pPrev;
  }
  if( p->pPrev ){
    p->pPrev->pNext = p->pNext;
................................................................................
    p->pDb->pIncrblob = p->pNext;
  }

  /* Free the IncrblobChannel structure */
  Tcl_Free((char *)p);

  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, (char*)SQLITEDB_ERRMSG(pDb), (char*)0);
    return TCL_ERROR;
  }
  return TCL_OK;
}

/*
** Read data from an incremental blob channel.
................................................................................

  /* This variable is used to name the channels: "incrblob_[incr count]" */
  static int count = 0;
  char zChannel[64];

  rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, (char*)SQLITEDB_ERRMSG(pDb), (char*)0);
    return TCL_ERROR;
  }

  p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
  p->iSeek = 0;
  p->pBlob = pBlob;

................................................................................
  }
  if( pDb->pWalHook ){
    Tcl_DecrRefCount(pDb->pWalHook);
  }
  if( pDb->pCollateNeeded ){
    Tcl_DecrRefCount(pDb->pCollateNeeded);
  }
  Tcl_DStringFree(&pDb->dsErr);
  Tcl_Free((char*)pDb);
}

/*
** This routine is called when a database file is locked while trying
** to execute SQL.
*/
................................................................................
  assert( pDb->pPreUpdateHook );
  assert( db==pDb->db );
  assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );

  pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
  Tcl_IncrRefCount(pCmd);
  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
  if( utf8Encoding!=NULL ){
    Tcl_DString ds;
    Tcl_ExternalToUtfDString(utf8Encoding, zDb, -1, &ds);
    Tcl_ListObjAppendElement(0, pCmd,
        Tcl_NewStringObj(Tcl_DStringValue(&ds), Tcl_DStringLength(&ds)));
    Tcl_DStringFree(&ds);
    Tcl_ExternalToUtfDString(utf8Encoding, zTbl, -1, &ds);
    Tcl_ListObjAppendElement(0, pCmd,
        Tcl_NewStringObj(Tcl_DStringValue(&ds), Tcl_DStringLength(&ds)));
    Tcl_DStringFree(&ds);
  }else{
    Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
    Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
  }
  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
  Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
  Tcl_DecrRefCount(pCmd);
}
#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */

................................................................................

  assert( pDb->pUpdateHook );
  assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );

  pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
  Tcl_IncrRefCount(pCmd);
  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
  if( utf8Encoding!=NULL ){
    Tcl_DString ds;
    Tcl_ExternalToUtfDString(utf8Encoding, zDb, -1, &ds);
    Tcl_ListObjAppendElement(0, pCmd,
        Tcl_NewStringObj(Tcl_DStringValue(&ds), Tcl_DStringLength(&ds)));
    Tcl_DStringFree(&ds);
    Tcl_ExternalToUtfDString(utf8Encoding, zTbl, -1, &ds);
    Tcl_ListObjAppendElement(0, pCmd,
        Tcl_NewStringObj(Tcl_DStringValue(&ds), Tcl_DStringLength(&ds)));
    Tcl_DStringFree(&ds);
  }else{
    Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
    Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
  }
  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
  Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
  Tcl_DecrRefCount(pCmd);
}

static void tclCollateNeeded(
  void *pCtx,
................................................................................
  sqlite3 *db,
  int enc,
  const char *zName
){
  SqliteDb *pDb = (SqliteDb *)pCtx;
  Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
  Tcl_IncrRefCount(pScript);
  if( utf8Encoding!=NULL ){
    Tcl_DString ds;
    Tcl_ExternalToUtfDString(utf8Encoding, zName, -1, &ds);
    Tcl_ListObjAppendElement(0, pScript,
        Tcl_NewStringObj(Tcl_DStringValue(&ds), Tcl_DStringLength(&ds)));
    Tcl_DStringFree(&ds);
  }else{
    Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
  }
  Tcl_EvalObjEx(pDb->interp, pScript, 0);
  Tcl_DecrRefCount(pScript);
}

/*
** This routine is called to evaluate an SQL collation function implemented
** using TCL script.
................................................................................
  const void *zB
){
  SqlCollate *p = (SqlCollate *)pCtx;
  Tcl_Obj *pCmd;

  pCmd = Tcl_NewStringObj(p->zScript, -1);
  Tcl_IncrRefCount(pCmd);
  if( utf8Encoding!=NULL ){
    Tcl_DString dsA, dsB;
    Tcl_ExternalToUtfDString(utf8Encoding, (char*)zA, nA, &dsA);
    Tcl_ExternalToUtfDString(utf8Encoding, (char*)zB, nB, &dsB);
    Tcl_ListObjAppendElement(p->interp, pCmd,
        Tcl_NewStringObj(Tcl_DStringValue(&dsA), Tcl_DStringLength(&dsA)));
    Tcl_ListObjAppendElement(p->interp, pCmd,
        Tcl_NewStringObj(Tcl_DStringValue(&dsB), Tcl_DStringLength(&dsB)));
    Tcl_DStringFree(&dsA);
    Tcl_DStringFree(&dsB);
  }else{
    Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
    Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
  }
  Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
  Tcl_DecrRefCount(pCmd);
  return (atoi(Tcl_GetStringResult(p->interp)));
}

/*
** This routine is called to evaluate an SQL function implemented
................................................................................
    ** That way, when Tcl_EvalObjv() is run and shimmers the first element
    ** of the list to tclCmdNameType, that alternate representation will
    ** be preserved and reused on the next invocation.
    */
    Tcl_Obj **aArg;
    int nArg;
    if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
resultError:
      if( utf8Encoding!=NULL ){
        Tcl_DString ds;
        Tcl_UtfToExternalDString(utf8Encoding, Tcl_GetStringResult(p->interp),
            -1, &ds);
        sqlite3_result_error(context, Tcl_DStringValue(&ds),
            Tcl_DStringLength(&ds));
        Tcl_DStringFree(&ds);
      }else{
        sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
      }
      return;
    }
    pCmd = Tcl_NewListObj(nArg, aArg);
    Tcl_IncrRefCount(pCmd);
    for(i=0; i<argc; i++){
      sqlite3_value *pIn = argv[i];
      Tcl_Obj *pVal;
................................................................................
        }
        case SQLITE_NULL: {
          pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
          break;
        }
        default: {
          int bytes = sqlite3_value_bytes(pIn);
          if( utf8Encoding!=NULL ){
            Tcl_DString ds;
            Tcl_ExternalToUtfDString(utf8Encoding,
                (char *)sqlite3_value_text(pIn), bytes, &ds);
            pVal = Tcl_NewStringObj(Tcl_DStringValue(&ds),
                       Tcl_DStringLength(&ds));
            Tcl_DStringFree(&ds);
          }else{
            pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
          }
          break;
        }
      }
      rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
      if( rc ){
        Tcl_DecrRefCount(pCmd);
        goto resultError;

      }
    }
    if( !p->useEvalObjv ){
      /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
      ** is a list without a string representation.  To prevent this from
      ** happening, make sure pCmd has a valid string representation */
      Tcl_GetString(pCmd);
    }
    rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
    Tcl_DecrRefCount(pCmd);
  }

  if( rc && rc!=TCL_RETURN ){
    goto resultError;
  }else{
    Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
    int n;
    u8 *data;
    const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
    char c = zType[0];
    int eType = p->eType;
................................................................................
      ** and try to rollback the transaction.
      **
      ** But it could also be that the user executed one or more BEGIN,
      ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
      ** this method's logic. Not clear how this would be best handled.
      */
    if( rc!=TCL_ERROR ){
      Tcl_AppendResult(interp, (char*)SQLITEDB_ERRMSG(pDb), (char*)0);
      rc = TCL_ERROR;
    }
    sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
  }
  pDb->disableAuth--;

  return rc;
................................................................................
  int nVar = 0;                   /* Number of variables in statement */
  int iParm = 0;                  /* Next free entry in apParm */
  char c;
  int i;
  int needResultReset = 0;        /* Need to invoke Tcl_ResetResult() */
  int rc = SQLITE_OK;             /* Value to return */
  Tcl_Interp *interp = pDb->interp;
  Tcl_DString ds;

  *ppPreStmt = 0;

  /* Trim spaces from the start of zSql and calculate the remaining length. */
  while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
  nSql = strlen30(zSql);

................................................................................

  /* If no prepared statement was found. Compile the SQL text. Also allocate
  ** a new SqlPreparedStmt structure.  */
  if( pPreStmt==0 ){
    int nByte;

    if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
      Tcl_SetObjResult(interp, Tcl_NewStringObj(SQLITEDB_ERRMSG(pDb), -1));
      return TCL_ERROR;
    }
    if( pStmt==0 ){
      if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
        /* A compile-time error in the statement. */
        Tcl_SetObjResult(interp, Tcl_NewStringObj(SQLITEDB_ERRMSG(pDb), -1));
        return TCL_ERROR;
      }else{
        /* The statement was a no-op.  Continue to the next statement
        ** in the SQL string.
        */
        return TCL_OK;
      }
................................................................................
#endif
  }
  assert( pPreStmt );
  assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
  assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );

  /* Bind values to parameters that begin with $ or : */
  Tcl_DStringInit(&ds);
  for(i=1; i<=nVar; i++){
    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
    if( utf8Encoding!= NULL ){
      Tcl_DStringFree(&ds);
      Tcl_ExternalToUtfDString(utf8Encoding, zVar, -1, &ds);
      zVar = Tcl_DStringValue(&ds);
    }
    if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
      Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
      if( pVar==0 && pDb->zBindFallback!=0 ){
        Tcl_Obj *pCmd;
        int rx;
        pCmd = Tcl_NewStringObj(pDb->zBindFallback, -1);
        Tcl_IncrRefCount(pCmd);
................................................................................
          Tcl_GetDoubleFromObj(interp, pVar, &r);
          sqlite3_bind_double(pStmt, i, r);
        }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
              (c=='i' && strcmp(zType,"int")==0) ){
          Tcl_WideInt v;
          Tcl_GetWideIntFromObj(interp, pVar, &v);
          sqlite3_bind_int64(pStmt, i, v);
        }else if( utf8Encoding!=NULL ){
          Tcl_DStringFree(&ds);
          Tcl_UtfToExternalDString(utf8Encoding, Tcl_GetString(pVar),
              pVar->length, &ds);
          sqlite3_bind_text(pStmt, i, Tcl_DStringValue(&ds),
              Tcl_DStringLength(&ds), SQLITE_TRANSIENT);
          Tcl_IncrRefCount(pVar);
          pPreStmt->apParm[iParm++] = pVar;
        }else{
          data = (unsigned char *)Tcl_GetString(pVar);
          sqlite3_bind_text(pStmt, i, (char *)data, pVar->length, SQLITE_STATIC);
          Tcl_IncrRefCount(pVar);
          pPreStmt->apParm[iParm++] = pVar;
        }
      }else{
        sqlite3_bind_null(pStmt, i);
      }
      if( needResultReset ) Tcl_ResetResult(pDb->interp);
    }
  }
  Tcl_DStringFree(&ds);
  pPreStmt->nParm = iParm;
  *ppPreStmt = pPreStmt;
  if( needResultReset && rc==TCL_OK ) Tcl_ResetResult(pDb->interp);

  return rc;
}

................................................................................
**   dbEvalRowInfo()
**   dbEvalColumnValue()
*/
typedef struct DbEvalContext DbEvalContext;
struct DbEvalContext {
  SqliteDb *pDb;                  /* Database handle */
  Tcl_Obj *pSql;                  /* Object holding string zSql */
  Tcl_DString dsSql;              /* Encoded SQL text */
  const char *zSql;               /* Remaining SQL to execute */
  SqlPreparedStmt *pPreStmt;      /* Current statement */
  int nCol;                       /* Number of columns returned by pStmt */
  int evalFlags;                  /* Flags used */
  Tcl_Obj *pArray;                /* Name of array variable */
  Tcl_Obj **apColName;            /* Array of column names */
};
................................................................................
  SqliteDb *pDb,                  /* Database handle */
  Tcl_Obj *pSql,                  /* Object containing SQL script */
  Tcl_Obj *pArray,                /* Name of Tcl array to set (*) element of */
  int evalFlags                   /* Flags controlling evaluation */
){
  memset(p, 0, sizeof(DbEvalContext));
  p->pDb = pDb;
  if( utf8Encoding!=NULL ){
    p->zSql = Tcl_UtfToExternalDString(utf8Encoding, Tcl_GetString(pSql),
                  pSql->length, &p->dsSql);
  }else{
    Tcl_DStringInit(&p->dsSql);
    p->zSql = Tcl_GetString(pSql);
  }
  p->pSql = pSql;
  Tcl_IncrRefCount(pSql);
  if( pArray ){
    p->pArray = pArray;
    Tcl_IncrRefCount(pArray);
  }
  p->evalFlags = evalFlags;
................................................................................
    int nCol;                     /* Number of columns returned by pStmt */
    Tcl_Obj **apColName = 0;      /* Array of column names */

    p->nCol = nCol = sqlite3_column_count(pStmt);
    if( nCol>0 && (papColName || p->pArray) ){
      apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
      for(i=0; i<nCol; i++){
        if( utf8Encoding!=NULL ){
          Tcl_DString ds;
          Tcl_ExternalToUtfDString(utf8Encoding, sqlite3_column_name(pStmt,i),
              -1, &ds);
          apColName[i] = Tcl_NewStringObj(Tcl_DStringValue(&ds),
                             Tcl_DStringLength(&ds));
          Tcl_DStringFree(&ds);
        }else{
          apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
        }
        Tcl_IncrRefCount(apColName[i]);
      }
      p->apColName = apColName;
    }

    /* If results are being stored in an array variable, then create
    ** the array(*) entry for that array
................................................................................
          ** This only happens once. If there is a second SQLITE_SCHEMA
          ** error, the error will be returned to the caller. */
          p->zSql = zPrevSql;
          continue;
        }
#endif
        Tcl_SetObjResult(pDb->interp,
            Tcl_NewStringObj(SQLITEDB_ERRMSG(pDb), -1));
        return TCL_ERROR;
      }else{
        dbReleaseStmt(pDb, pPreStmt, 0);
      }
    }
  }

................................................................................
    dbReleaseStmt(p->pDb, p->pPreStmt, 0);
    p->pPreStmt = 0;
  }
  if( p->pArray ){
    Tcl_DecrRefCount(p->pArray);
    p->pArray = 0;
  }
  Tcl_DStringFree(&p->dsSql);
  Tcl_DecrRefCount(p->pSql);
  dbReleaseColumnNames(p);
}

/*
** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
** the value for the iCol'th column of the row currently pointed to by
................................................................................
    case SQLITE_FLOAT: {
      return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
    }
    case SQLITE_NULL: {
      return Tcl_NewStringObj(p->pDb->zNull, -1);
    }
  }
  if( utf8Encoding!=NULL ){
    Tcl_DString ds;
    Tcl_Obj *obj;
    Tcl_ExternalToUtfDString(utf8Encoding,
        (char*)sqlite3_column_text(pStmt, iCol), -1, &ds);
    obj = Tcl_NewStringObj(Tcl_DStringValue(&ds), Tcl_DStringLength(&ds));
    Tcl_DStringFree(&ds);
    return obj;
  }
  return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
}

/*
** If using Tcl version 8.6 or greater, use the NR functions to avoid
** recursive evalution of scripts by the [db eval] and [db trans]
** commands. Even if the headers used while compiling the extension
................................................................................
    }else if( objc==4 ){
      zSrcDb = Tcl_GetString(objv[2]);
      zDestFile = Tcl_GetString(objv[3]);
    }else{
      Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
      return TCL_ERROR;
    }
    if( utf8Encoding!=NULL ){
      Tcl_DString ds;
      Tcl_UtfToExternalDString(utf8Encoding, zDestFile, -1, &ds);
      rc = sqlite3_open_v2(Tcl_DStringValue(&ds), &pDest,
               SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
      Tcl_DStringFree(&ds);
    }else{
      rc = sqlite3_open_v2(zDestFile, &pDest,
               SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
    }
    if( rc!=SQLITE_OK ){
      if( utf8Encoding!=NULL ){
        Tcl_DString ds;
        Tcl_ExternalToUtfDString(utf8Encoding, sqlite3_errmsg(pDest), -1, &ds);
        Tcl_AppendResult(interp, "cannot open target database: ",
             Tcl_DStringValue(&ds), (char*)0);
        Tcl_DStringFree(&ds);
      }else{
        Tcl_AppendResult(interp, "cannot open target database: ",
             sqlite3_errmsg(pDest), (char*)0);
      }
      sqlite3_close(pDest);
      return TCL_ERROR;
    }
    if( utf8Encoding!=NULL ){
      Tcl_DString ds;
      Tcl_UtfToExternalDString(utf8Encoding, zSrcDb, -1, &ds);
      pBackup = sqlite3_backup_init(pDest, "main", pDb->db,
                    Tcl_DStringValue(&ds));
      Tcl_DStringFree(&ds);
    }else{
      pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
    }
    if( pBackup==0 ){
      if( utf8Encoding!=NULL ){
        Tcl_DString ds;
        Tcl_ExternalToUtfDString(utf8Encoding, sqlite3_errmsg(pDest), -1, &ds);
        Tcl_AppendResult(interp, "backup failed: ",
             Tcl_DStringValue(&ds), (char*)0);
        Tcl_DStringFree(&ds);
      }else{
        Tcl_AppendResult(interp, "backup failed: ",
             sqlite3_errmsg(pDest), (char*)0);
      }
      sqlite3_close(pDest);
      return TCL_ERROR;
    }
    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
    sqlite3_backup_finish(pBackup);
    if( rc==SQLITE_DONE ){
      rc = TCL_OK;
    }else{
      if( utf8Encoding!=NULL ){
        Tcl_DString ds;
        Tcl_ExternalToUtfDString(utf8Encoding, sqlite3_errmsg(pDest), -1, &ds);
        Tcl_AppendResult(interp, "backup failed: ",
             Tcl_DStringValue(&ds), (char*)0);
        Tcl_DStringFree(&ds);
      }else{
        Tcl_AppendResult(interp, "backup failed: ",
             sqlite3_errmsg(pDest), (char*)0);
      }
      rc = TCL_ERROR;
    }
    sqlite3_close(pDest);
    break;
  }

  /*    $db bind_fallback ?CALLBACK?
................................................................................
  ** that function is called, invoke SCRIPT to evaluate the function.
  */
  case DB_COLLATE: {
    SqlCollate *pCollate;
    char *zName;
    char *zScript;
    int nScript;
    Tcl_DString ds;
    if( objc!=4 ){
      Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
      return TCL_ERROR;
    }
    zName = Tcl_GetString(objv[2]);
    if( utf8Encoding!=NULL ){
      Tcl_UtfToExternalDString(utf8Encoding, zName, -1, &ds);
      zName = Tcl_DStringValue(&ds);
    }else{
      Tcl_DStringInit(&ds);
    }
    zScript = Tcl_GetStringFromObj(objv[3], &nScript);
    pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
    if( pCollate==0 ) return TCL_ERROR;
    pCollate->interp = interp;
    pCollate->pNext = pDb->pCollate;
    pCollate->zScript = (char*)&pCollate[1];
    pDb->pCollate = pCollate;
    memcpy(pCollate->zScript, zScript, nScript+1);
    if( sqlite3_create_collation_v2(pDb->db, zName, SQLITE_UTF8,
        pCollate, tclSqlCollate, 0) ){
      Tcl_DStringFree(&ds);
      Tcl_AppendResult(interp, (char*)SQLITEDB_ERRMSG(pDb), (char*)0);
      return TCL_ERROR;
    }
    Tcl_DStringFree(&ds);
    break;
  }

  /*
  **     $db collation_needed SCRIPT
  **
  ** Create a new SQL collation function called NAME.  Whenever
................................................................................
       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", (char*)0);
      return TCL_ERROR;
    }
    if( utf8Encoding!=NULL ){
      Tcl_DString ds;
      Tcl_UtfToExternalDString(utf8Encoding, zTable, -1, &ds);
      zSql = sqlite3_mprintf("SELECT * FROM '%q'", Tcl_DStringValue(&ds));
      Tcl_DStringFree(&ds);
    }else{
      zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
    }
    if( zSql==0 ){
      Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
      return TCL_ERROR;
    }
    nByte = strlen30(zSql);
    rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
    sqlite3_free(zSql);
    if( rc ){
      Tcl_AppendResult(interp, "Error: ", (char*)SQLITEDB_ERRMSG(pDb),
          (char*)0);
      nCol = 0;
    }else{
      nCol = sqlite3_column_count(pStmt);
    }
    sqlite3_finalize(pStmt);
    if( nCol==0 ) {
      return TCL_ERROR;
    }
    zSql = sqlite3_malloc( nByte + 50 + nCol*2 );
    if( zSql==0 ) {
      Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
      return TCL_ERROR;
    }
    if( utf8Encoding!=NULL ){
      Tcl_DString ds;
      Tcl_UtfToExternalDString(utf8Encoding, zTable, -1, &ds);
      sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
                       zConflict, Tcl_DStringValue(&ds));
      Tcl_DStringFree(&ds);
    }else{
      sqlite3_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 = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
    sqlite3_free(zSql);
    if( rc ){
      Tcl_AppendResult(interp, "Error: ", (char*)SQLITEDB_ERRMSG(pDb),
          (char*)0);
      sqlite3_finalize(pStmt);
      return TCL_ERROR;
    }
    in = Tcl_OpenFileChannel(interp, zFile, "r", 0666);
    if( in==0 ){
      sqlite3_finalize(pStmt);
      return TCL_ERROR;
................................................................................
        break;
      }
      for(i=0; i<nCol; i++){
        /* check for null data, if so, bind as null */
        if( (azCol[i][0]==0) || (nNull>0 && strcmp(azCol[i], zNull)==0)
        ){
          sqlite3_bind_null(pStmt, i+1);
        }else if( utf8Encoding!=NULL ){
          Tcl_DString ds;
          Tcl_UtfToExternalDString(utf8Encoding, azCol[i], -1, &ds);
          sqlite3_bind_text(pStmt, i+1, Tcl_DStringValue(&ds),
              Tcl_DStringLength(&ds), SQLITE_TRANSIENT);
          Tcl_DStringFree(&ds);
        }else{
          sqlite3_bind_text(pStmt, i+1, azCol[i], strlen30(azCol[i]),
              SQLITE_STATIC);
        }
      }
      sqlite3_step(pStmt);
      rc = sqlite3_reset(pStmt);
      Tcl_DStringSetLength(&str, 0);
      if( rc!=SQLITE_OK ){
        Tcl_AppendResult(interp,"Error: ", (char*)SQLITEDB_ERRMSG(pDb),
            (char*)0);
        zCommit = "ROLLBACK";
        break;
      }
    }
    Tcl_DStringFree(&str);
    sqlite3_free(azCol);
    Tcl_Close(interp, in);
................................................................................
      int flags;
      if( len>0 ) memcpy(pData, pBA, len);
      if( isReadonly ){
        flags = SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_READONLY;
      }else{
        flags = SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_RESIZEABLE;
      }
      if( utf8Encoding!=NULL ){
        Tcl_DString ds;
        Tcl_ExternalToUtfDString(utf8Encoding, (char*)zSchema, -1, &ds);
        xrc = sqlite3_deserialize(pDb->db, Tcl_DStringValue(&ds),
                  pData, len, len, flags);
        Tcl_DStringFree(&ds);
      } else {
        xrc = sqlite3_deserialize(pDb->db, zSchema, pData, len, len, flags);
      }
      if( xrc ){
        Tcl_AppendResult(interp, "unable to set MEMDB content", (char*)0);
        rc = TCL_ERROR;
      }
      if( mxSize>0 ){
        sqlite3_file_control(pDb->db, zSchema,SQLITE_FCNTL_SIZE_LIMIT,&mxSize);
      }
................................................................................
    int flags = SQLITE_UTF8;
    SqlFunc *pFunc;
    Tcl_Obj *pScript;
    char *zName;
    int nArg = -1;
    int i;
    int eType = SQLITE_NULL;
    Tcl_DString ds;
    if( objc<4 ){
      Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
      return TCL_ERROR;
    }
    for(i=3; i<(objc-1); i++){
      const char *z = Tcl_GetString(objv[i]);
      int n = strlen30(z);
................................................................................
        );
        return TCL_ERROR;
      }
    }

    pScript = objv[objc-1];
    zName = Tcl_GetString(objv[2]);
    if( utf8Encoding!=NULL ){
      Tcl_UtfToExternalDString(utf8Encoding, zName, -1, &ds);
      zName = Tcl_DStringValue(&ds);
    }else{
      Tcl_DStringInit(&ds);
    }
    pFunc = findSqlFunc(pDb, zName);
    if( pFunc==0 ) return TCL_ERROR;
    if( pFunc->pScript ){
      Tcl_DecrRefCount(pFunc->pScript);
    }
    pFunc->pScript = pScript;
    Tcl_IncrRefCount(pScript);
    pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
    pFunc->eType = eType;
    rc = sqlite3_create_function_v2(pDb->db, zName, nArg, flags,
        pFunc, tclSqlFunc, 0, 0, 0);
    Tcl_DStringFree(&ds);
    if( rc!=SQLITE_OK ){
      rc = TCL_ERROR;
      Tcl_AppendResult(interp, (char*)SQLITEDB_ERRMSG(pDb), (char*)0);
    }
    break;
  }

  /*
  **     $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
  */
................................................................................
      zDb = Tcl_GetString(objv[2]);
    }
    zTable = Tcl_GetString(objv[objc-3]);
    zColumn = Tcl_GetString(objv[objc-2]);
    rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);

    if( rc==TCL_OK ){
      if( utf8Encoding!=NULL ){
        Tcl_DString ds1, ds2, ds3;
        Tcl_UtfToExternalDString(utf8Encoding, zDb, -1, &ds1);
        Tcl_UtfToExternalDString(utf8Encoding, zTable, -1, &ds2);
        Tcl_UtfToExternalDString(utf8Encoding, zColumn, -1, &ds3);
        rc = createIncrblobChannel(
            interp, pDb, Tcl_DStringValue(&ds1), Tcl_DStringValue(&ds2),
            Tcl_DStringValue(&ds3), (sqlite3_int64)iRow, isReadonly
        );
        Tcl_DStringFree(&ds1);
        Tcl_DStringFree(&ds2);
        Tcl_DStringFree(&ds3);
      }else{
        rc = createIncrblobChannel(
            interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
        );
      }
    }
#endif
    break;
  }

  /*
  **     $db interrupt
................................................................................
      Tcl_WrongNumArgs(interp, 2, objv, "KEY");
      return TCL_ERROR;
    }
#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
    pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
    rc = sqlite3_rekey(pDb->db, pKey, nKey);
    if( rc ){
      if( utf8Encoding!=NULL){
        Tcl_DString ds;
        Tcl_ExternalToUtfDString(utf8Encoding, sqlite3_errstr(rc), -1, &ds);
        Tcl_AppendResult(interp, Tcl_DStringValue(&ds), (char*)0);
        Tcl_DStringFree(&ds);
      }else{
        Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
      }
      rc = TCL_ERROR;
    }
#endif
    break;
  }

  /*    $db restore ?DATABASE? FILENAME
................................................................................
    }else if( objc==4 ){
      zDestDb = Tcl_GetString(objv[2]);
      zSrcFile = Tcl_GetString(objv[3]);
    }else{
      Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
      return TCL_ERROR;
    }
    if( utf8Encoding!=NULL ){
      Tcl_DString ds;
      Tcl_UtfToExternalDString(utf8Encoding, zSrcFile, -1, &ds);
      rc = sqlite3_open_v2(Tcl_DStringValue(&ds), &pSrc,
               SQLITE_OPEN_READONLY | pDb->openFlags, 0);
      Tcl_DStringFree(&ds);
    }else{
      rc = sqlite3_open_v2(zSrcFile, &pSrc,
                           SQLITE_OPEN_READONLY | pDb->openFlags, 0);
    }
    if( rc!=SQLITE_OK ){
      if( utf8Encoding!=NULL ){
        Tcl_DString ds;
        Tcl_ExternalToUtfDString(utf8Encoding, sqlite3_errmsg(pSrc), -1, &ds);
        Tcl_AppendResult(interp, "cannot open source database: ",
             Tcl_DStringValue(&ds), (char*)0);
        Tcl_DStringFree(&ds);
      }else{
        Tcl_AppendResult(interp, "cannot open source database: ",
             sqlite3_errmsg(pSrc), (char*)0);
      }
      sqlite3_close(pSrc);
      return TCL_ERROR;
    }
    if( utf8Encoding!=NULL ){
      Tcl_DString ds;
      Tcl_UtfToExternalDString(utf8Encoding, zDestDb, -1, &ds);
      pBackup = sqlite3_backup_init(pDb->db, Tcl_DStringValue(&ds), pSrc,
                    "main");
      Tcl_DStringFree(&ds);
    }else{
      pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
    }
    if( pBackup==0 ){
      Tcl_AppendResult(interp, "restore failed: ",
          (char*)SQLITEDB_ERRMSG(pDb), (char*)0);
      sqlite3_close(pSrc);
      return TCL_ERROR;
    }
    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
              || rc==SQLITE_BUSY ){
      if( rc==SQLITE_BUSY ){
        if( nTimeout++ >= 3 ) break;
................................................................................
      rc = TCL_OK;
    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
      Tcl_AppendResult(interp, "restore failed: source database busy",
                       (char*)0);
      rc = TCL_ERROR;
    }else{
      Tcl_AppendResult(interp, "restore failed: ",
          (char*)SQLITEDB_ERRMSG(pDb), (char*)0);
      rc = TCL_ERROR;
    }
    sqlite3_close(pSrc);
    break;
  }

  /*
................................................................................
    sqlite3_int64 sz = 0;
    unsigned char *pData;
    if( objc!=2 && objc!=3 ){
      Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE?");
      rc = TCL_ERROR;
    }else{
      int needFree;
      if( utf8Encoding!=NULL ){
        Tcl_DString ds;
        Tcl_ExternalToUtfDString(utf8Encoding, (char*)zSchema, -1, &ds);
        pData = sqlite3_serialize(pDb->db, Tcl_DStringValue(&ds), &sz,
                    SQLITE_SERIALIZE_NOCOPY);
        Tcl_DStringFree(&ds);
      } else {
        pData = sqlite3_serialize(pDb->db, zSchema, &sz,
                    SQLITE_SERIALIZE_NOCOPY);
      }
      if( pData ){
        needFree = 0;
      }else{
        pData = sqlite3_serialize(pDb->db, zSchema, &sz, 0);
        needFree = 1;
      }
      Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(pData,sz));
................................................................................
    pScript = objv[objc-1];

    /* Run the SQLite BEGIN command to open a transaction or savepoint. */
    pDb->disableAuth++;
    rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
    pDb->disableAuth--;
    if( rc!=SQLITE_OK ){
      Tcl_AppendResult(interp, (char*)SQLITEDB_ERRMSG(pDb), (char*)0);
      return TCL_ERROR;
    }
    pDb->nTransaction++;

    /* If using NRE, schedule a callback to invoke the script pScript, then
    ** a second callback to commit (or rollback) the transaction or savepoint
    ** opened above. If not using NRE, evaluate the script directly, then
................................................................................
        xNotify = DbUnlockNotify;
        pNotifyArg = (void *)pDb;
        pDb->pUnlockNotify = objv[2];
        Tcl_IncrRefCount(pDb->pUnlockNotify);
      }

      if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
        Tcl_AppendResult(interp, (char*)SQLITEDB_ERRMSG(pDb), (char*)0);
        rc = TCL_ERROR;
      }
    }
#endif
    break;
  }

................................................................................
        }

        if( rc==SQLITE_OK ){
          Tcl_Obj *pObj;
          pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
          Tcl_SetObjResult(interp, pObj);
        }else{
          Tcl_AppendResult(interp, (char*)SQLITEDB_ERRMSG(pDb), (char*)0);
          return TCL_ERROR;
        }
      }
    }
#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
    break;
  }
................................................................................
      Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
      return TCL_ERROR;
    }
  }
  zErrMsg = 0;
  p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
  memset(p, 0, sizeof(*p));
  Tcl_DStringInit(&p->dsErr);
  if( zFile==0 ) zFile = "";
  zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
  if( utf8Encoding!=NULL ){
    Tcl_DString ds1, ds2;
    Tcl_UtfToExternalDString(utf8Encoding, zFile, -1, &ds1);
    if ( zVfs!=NULL ){
      Tcl_UtfToExternalDString(utf8Encoding, zVfs, -1, &ds2);
      zVfs = Tcl_DStringValue(&ds2);
    }
    rc = sqlite3_open_v2(Tcl_DStringValue(&ds1), &p->db, flags, zVfs);
    Tcl_DStringFree(&ds1);
    if( zVfs!=NULL ){
      Tcl_DStringFree(&ds2);
    }
  }else{
    rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
  }
  Tcl_DStringFree(&translatedFilename);
  if( p->db ){
    if( SQLITE_OK!=sqlite3_errcode(p->db) ){
      zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
      sqlite3_close(p->db);
      p->db = 0;
    }
................................................................................
  }
#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
  if( p->db ){
    sqlite3_key(p->db, pKey, nKey);
  }
#endif
  if( p->db==0 ){
    if( utf8Encoding!=NULL && zErrMsg ){
      Tcl_DString ds;
      Tcl_ExternalToUtfDString(utf8Encoding, zErrMsg, -1, &ds);
      Tcl_AppendResult(interp, Tcl_DStringValue(&ds), (char*)0);
      Tcl_DStringFree(&ds);
    }else{
      Tcl_AppendResult(interp, zErrMsg, (char*)0);
    }
    Tcl_Free((char*)p);
    sqlite3_free(zErrMsg);
    return TCL_ERROR;
  }
  p->maxStmt = NUM_PREPARED_STMTS;
  p->openFlags = flags & SQLITE_OPEN_URI;
  p->interp = interp;
................................................................................
    /* The "sqlite" alias is undocumented.  It is here only to support
    ** legacy scripts.  All new scripts should use only the "sqlite3"
    ** command. */
    Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
#endif
    rc = Tcl_PkgProvideEx(interp, "sqlite3", PACKAGE_VERSION, NULL);
  }
  if( !utf8EncInit ){
    Tcl_Encoding enc;
    Tcl_MutexLock(&utf8EncMutex);
    if( ++utf8EncInit>1 ){
      goto utf8EncInitDone;
    }
    enc = Tcl_GetEncoding(NULL, "utf-8");
    /*
     ** Try to detect the level of UTF-8 support in the Tcl core.
     */
    if( enc!=NULL ){
      const char probe1[] = { 0xF0, 0x9F, 0x98, 0x82 };
      const char probe1sp[] = { 0xED, 0xA0, 0xBD, 0xED, 0xB8, 0x82 };
      Tcl_DString ds;
      Tcl_ExternalToUtfDString(enc, probe1, sizeof(probe1), &ds);
      if( Tcl_DStringLength(&ds)==sizeof(probe1) &&
          memcmp(probe1, Tcl_DStringValue(&ds), sizeof(probe1))==0 ){
        /*
         ** Tcl core supports full Unicode.
         */
        Tcl_FreeEncoding(enc);
      }else if( Tcl_DStringLength(&ds)==sizeof(probe1sp) &&
          memcmp(probe1sp, Tcl_DStringValue(&ds), sizeof(probe1sp))==0 ){
        /*
         ** Tcl core supports full Unicode using surrogate pairs,
         ** keep utf8Encoding for conversion to/from 4 byte UTF-8 sequences.
         */
        utf8Encoding = enc;
      }else{
        /*
         ** Tcl core supports BMP only, let SQLite handle corner cases.
         */
        Tcl_FreeEncoding(enc);
      }
      Tcl_DStringFree(&ds);
    }
utf8EncInitDone:
    Tcl_MutexUnlock(&utf8EncMutex);
  }
  return rc;
}


DLLEXPORT int Sqlite3_Unload(Tcl_Interp *interp, int flags){
  Tcl_MutexLock(&utf8EncMutex);
  if( --utf8EncInit<1 ){
    if( utf8Encoding!=NULL ){
      Tcl_FreeEncoding(utf8Encoding);
      utf8Encoding = NULL;
    }
    utf8EncInit = 0;
  }
  Tcl_MutexUnlock(&utf8EncMutex);
  return TCL_OK;
}

DLLEXPORT int Tclsqlite3_Init(Tcl_Interp *interp){
  return Sqlite3_Init(interp);
}

DLLEXPORT int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){
  return Sqlite3_Unload(interp, flags);
}

/* Because it accesses the file-system and uses persistent state, SQLite
** is not considered appropriate for safe interpreters.  Hence, we cause
** the _SafeInit() interfaces return TCL_ERROR.
*/
DLLEXPORT int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
DLLEXPORT int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}



#ifndef SQLITE_3_SUFFIX_ONLY
int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
int Sqlite_Unload(Tcl_Interp *interp, int flags){
  return SqLite3_Unload(interp, flags);
}
int Tclsqlite_Unload(Tcl_Interp *interp, int flags){
  return Sqlite3_Unload(interp, flags);
}
#endif

/*
** If the TCLSH macro is defined, add code to make a stand-alone program.
*/
#if defined(TCLSH)