xref: /sqlite-3.40.0/src/tclsqlite.c (revision 5313f2e1)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** A TCL Interface to SQLite.  Append this file to sqlite3.c and
13 ** compile the whole thing to build a TCL-enabled version of SQLite.
14 **
15 ** Compile-time options:
16 **
17 **  -DTCLSH=1             Add a "main()" routine that works as a tclsh.
18 **
19 **  -DSQLITE_TCLMD5       When used in conjuction with -DTCLSH=1, add
20 **                        four new commands to the TCL interpreter for
21 **                        generating MD5 checksums:  md5, md5file,
22 **                        md5-10x8, and md5file-10x8.
23 **
24 **  -DSQLITE_TEST         When used in conjuction with -DTCLSH=1, add
25 **                        hundreds of new commands used for testing
26 **                        SQLite.  This option implies -DSQLITE_TCLMD5.
27 */
28 
29 /*
30 ** If requested, include the SQLite compiler options file for MSVC.
31 */
32 #if defined(INCLUDE_MSVC_H)
33 #include "msvc.h"
34 #endif
35 
36 #include "tcl.h"
37 #include <errno.h>
38 
39 /*
40 ** Some additional include files are needed if this file is not
41 ** appended to the amalgamation.
42 */
43 #ifndef SQLITE_AMALGAMATION
44 # include "sqlite3.h"
45 # include <stdlib.h>
46 # include <string.h>
47 # include <assert.h>
48   typedef unsigned char u8;
49 #endif
50 #include <ctype.h>
51 
52 /* Used to get the current process ID */
53 #if !defined(_WIN32)
54 # include <unistd.h>
55 # define GETPID getpid
56 #elif !defined(_WIN32_WCE)
57 # ifndef SQLITE_AMALGAMATION
58 #  define WIN32_LEAN_AND_MEAN
59 #  include <windows.h>
60 # endif
61 # define GETPID (int)GetCurrentProcessId
62 #endif
63 
64 /*
65  * Windows needs to know which symbols to export.  Unix does not.
66  * BUILD_sqlite should be undefined for Unix.
67  */
68 #ifdef BUILD_sqlite
69 #undef TCL_STORAGE_CLASS
70 #define TCL_STORAGE_CLASS DLLEXPORT
71 #endif /* BUILD_sqlite */
72 
73 #define NUM_PREPARED_STMTS 10
74 #define MAX_PREPARED_STMTS 100
75 
76 /* Forward declaration */
77 typedef struct SqliteDb SqliteDb;
78 
79 /*
80 ** New SQL functions can be created as TCL scripts.  Each such function
81 ** is described by an instance of the following structure.
82 */
83 typedef struct SqlFunc SqlFunc;
84 struct SqlFunc {
85   Tcl_Interp *interp;   /* The TCL interpret to execute the function */
86   Tcl_Obj *pScript;     /* The Tcl_Obj representation of the script */
87   SqliteDb *pDb;        /* Database connection that owns this function */
88   int useEvalObjv;      /* True if it is safe to use Tcl_EvalObjv */
89   char *zName;          /* Name of this function */
90   SqlFunc *pNext;       /* Next function on the list of them all */
91 };
92 
93 /*
94 ** New collation sequences function can be created as TCL scripts.  Each such
95 ** function is described by an instance of the following structure.
96 */
97 typedef struct SqlCollate SqlCollate;
98 struct SqlCollate {
99   Tcl_Interp *interp;   /* The TCL interpret to execute the function */
100   char *zScript;        /* The script to be run */
101   SqlCollate *pNext;    /* Next function on the list of them all */
102 };
103 
104 /*
105 ** Prepared statements are cached for faster execution.  Each prepared
106 ** statement is described by an instance of the following structure.
107 */
108 typedef struct SqlPreparedStmt SqlPreparedStmt;
109 struct SqlPreparedStmt {
110   SqlPreparedStmt *pNext;  /* Next in linked list */
111   SqlPreparedStmt *pPrev;  /* Previous on the list */
112   sqlite3_stmt *pStmt;     /* The prepared statement */
113   int nSql;                /* chars in zSql[] */
114   const char *zSql;        /* Text of the SQL statement */
115   int nParm;               /* Size of apParm array */
116   Tcl_Obj **apParm;        /* Array of referenced object pointers */
117 };
118 
119 typedef struct IncrblobChannel IncrblobChannel;
120 
121 /*
122 ** There is one instance of this structure for each SQLite database
123 ** that has been opened by the SQLite TCL interface.
124 **
125 ** If this module is built with SQLITE_TEST defined (to create the SQLite
126 ** testfixture executable), then it may be configured to use either
127 ** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
128 ** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
129 */
130 struct SqliteDb {
131   sqlite3 *db;               /* The "real" database structure. MUST BE FIRST */
132   Tcl_Interp *interp;        /* The interpreter used for this database */
133   char *zBusy;               /* The busy callback routine */
134   char *zCommit;             /* The commit hook callback routine */
135   char *zTrace;              /* The trace callback routine */
136   char *zProfile;            /* The profile callback routine */
137   char *zProgress;           /* The progress callback routine */
138   char *zAuth;               /* The authorization callback routine */
139   int disableAuth;           /* Disable the authorizer if it exists */
140   char *zNull;               /* Text to substitute for an SQL NULL value */
141   SqlFunc *pFunc;            /* List of SQL functions */
142   Tcl_Obj *pUpdateHook;      /* Update hook script (if any) */
143   Tcl_Obj *pPreUpdateHook;   /* Pre-update hook script (if any) */
144   Tcl_Obj *pRollbackHook;    /* Rollback hook script (if any) */
145   Tcl_Obj *pWalHook;         /* WAL hook script (if any) */
146   Tcl_Obj *pUnlockNotify;    /* Unlock notify script (if any) */
147   SqlCollate *pCollate;      /* List of SQL collation functions */
148   int rc;                    /* Return code of most recent sqlite3_exec() */
149   Tcl_Obj *pCollateNeeded;   /* Collation needed script */
150   SqlPreparedStmt *stmtList; /* List of prepared statements*/
151   SqlPreparedStmt *stmtLast; /* Last statement in the list */
152   int maxStmt;               /* The next maximum number of stmtList */
153   int nStmt;                 /* Number of statements in stmtList */
154   IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
155   int nStep, nSort, nIndex;  /* Statistics for most recent operation */
156   int nTransaction;          /* Number of nested [transaction] methods */
157   int openFlags;             /* Flags used to open.  (SQLITE_OPEN_URI) */
158 #ifdef SQLITE_TEST
159   int bLegacyPrepare;        /* True to use sqlite3_prepare() */
160 #endif
161 };
162 
163 struct IncrblobChannel {
164   sqlite3_blob *pBlob;      /* sqlite3 blob handle */
165   SqliteDb *pDb;            /* Associated database connection */
166   int iSeek;                /* Current seek offset */
167   Tcl_Channel channel;      /* Channel identifier */
168   IncrblobChannel *pNext;   /* Linked list of all open incrblob channels */
169   IncrblobChannel *pPrev;   /* Linked list of all open incrblob channels */
170 };
171 
172 /*
173 ** Compute a string length that is limited to what can be stored in
174 ** lower 30 bits of a 32-bit signed integer.
175 */
176 static int strlen30(const char *z){
177   const char *z2 = z;
178   while( *z2 ){ z2++; }
179   return 0x3fffffff & (int)(z2 - z);
180 }
181 
182 
183 #ifndef SQLITE_OMIT_INCRBLOB
184 /*
185 ** Close all incrblob channels opened using database connection pDb.
186 ** This is called when shutting down the database connection.
187 */
188 static void closeIncrblobChannels(SqliteDb *pDb){
189   IncrblobChannel *p;
190   IncrblobChannel *pNext;
191 
192   for(p=pDb->pIncrblob; p; p=pNext){
193     pNext = p->pNext;
194 
195     /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
196     ** which deletes the IncrblobChannel structure at *p. So do not
197     ** call Tcl_Free() here.
198     */
199     Tcl_UnregisterChannel(pDb->interp, p->channel);
200   }
201 }
202 
203 /*
204 ** Close an incremental blob channel.
205 */
206 static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
207   IncrblobChannel *p = (IncrblobChannel *)instanceData;
208   int rc = sqlite3_blob_close(p->pBlob);
209   sqlite3 *db = p->pDb->db;
210 
211   /* Remove the channel from the SqliteDb.pIncrblob list. */
212   if( p->pNext ){
213     p->pNext->pPrev = p->pPrev;
214   }
215   if( p->pPrev ){
216     p->pPrev->pNext = p->pNext;
217   }
218   if( p->pDb->pIncrblob==p ){
219     p->pDb->pIncrblob = p->pNext;
220   }
221 
222   /* Free the IncrblobChannel structure */
223   Tcl_Free((char *)p);
224 
225   if( rc!=SQLITE_OK ){
226     Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
227     return TCL_ERROR;
228   }
229   return TCL_OK;
230 }
231 
232 /*
233 ** Read data from an incremental blob channel.
234 */
235 static int incrblobInput(
236   ClientData instanceData,
237   char *buf,
238   int bufSize,
239   int *errorCodePtr
240 ){
241   IncrblobChannel *p = (IncrblobChannel *)instanceData;
242   int nRead = bufSize;         /* Number of bytes to read */
243   int nBlob;                   /* Total size of the blob */
244   int rc;                      /* sqlite error code */
245 
246   nBlob = sqlite3_blob_bytes(p->pBlob);
247   if( (p->iSeek+nRead)>nBlob ){
248     nRead = nBlob-p->iSeek;
249   }
250   if( nRead<=0 ){
251     return 0;
252   }
253 
254   rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
255   if( rc!=SQLITE_OK ){
256     *errorCodePtr = rc;
257     return -1;
258   }
259 
260   p->iSeek += nRead;
261   return nRead;
262 }
263 
264 /*
265 ** Write data to an incremental blob channel.
266 */
267 static int incrblobOutput(
268   ClientData instanceData,
269   CONST char *buf,
270   int toWrite,
271   int *errorCodePtr
272 ){
273   IncrblobChannel *p = (IncrblobChannel *)instanceData;
274   int nWrite = toWrite;        /* Number of bytes to write */
275   int nBlob;                   /* Total size of the blob */
276   int rc;                      /* sqlite error code */
277 
278   nBlob = sqlite3_blob_bytes(p->pBlob);
279   if( (p->iSeek+nWrite)>nBlob ){
280     *errorCodePtr = EINVAL;
281     return -1;
282   }
283   if( nWrite<=0 ){
284     return 0;
285   }
286 
287   rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
288   if( rc!=SQLITE_OK ){
289     *errorCodePtr = EIO;
290     return -1;
291   }
292 
293   p->iSeek += nWrite;
294   return nWrite;
295 }
296 
297 /*
298 ** Seek an incremental blob channel.
299 */
300 static int incrblobSeek(
301   ClientData instanceData,
302   long offset,
303   int seekMode,
304   int *errorCodePtr
305 ){
306   IncrblobChannel *p = (IncrblobChannel *)instanceData;
307 
308   switch( seekMode ){
309     case SEEK_SET:
310       p->iSeek = offset;
311       break;
312     case SEEK_CUR:
313       p->iSeek += offset;
314       break;
315     case SEEK_END:
316       p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
317       break;
318 
319     default: assert(!"Bad seekMode");
320   }
321 
322   return p->iSeek;
323 }
324 
325 
326 static void incrblobWatch(ClientData instanceData, int mode){
327   /* NO-OP */
328 }
329 static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
330   return TCL_ERROR;
331 }
332 
333 static Tcl_ChannelType IncrblobChannelType = {
334   "incrblob",                        /* typeName                             */
335   TCL_CHANNEL_VERSION_2,             /* version                              */
336   incrblobClose,                     /* closeProc                            */
337   incrblobInput,                     /* inputProc                            */
338   incrblobOutput,                    /* outputProc                           */
339   incrblobSeek,                      /* seekProc                             */
340   0,                                 /* setOptionProc                        */
341   0,                                 /* getOptionProc                        */
342   incrblobWatch,                     /* watchProc (this is a no-op)          */
343   incrblobHandle,                    /* getHandleProc (always returns error) */
344   0,                                 /* close2Proc                           */
345   0,                                 /* blockModeProc                        */
346   0,                                 /* flushProc                            */
347   0,                                 /* handlerProc                          */
348   0,                                 /* wideSeekProc                         */
349 };
350 
351 /*
352 ** Create a new incrblob channel.
353 */
354 static int createIncrblobChannel(
355   Tcl_Interp *interp,
356   SqliteDb *pDb,
357   const char *zDb,
358   const char *zTable,
359   const char *zColumn,
360   sqlite_int64 iRow,
361   int isReadonly
362 ){
363   IncrblobChannel *p;
364   sqlite3 *db = pDb->db;
365   sqlite3_blob *pBlob;
366   int rc;
367   int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
368 
369   /* This variable is used to name the channels: "incrblob_[incr count]" */
370   static int count = 0;
371   char zChannel[64];
372 
373   rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
374   if( rc!=SQLITE_OK ){
375     Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
376     return TCL_ERROR;
377   }
378 
379   p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
380   p->iSeek = 0;
381   p->pBlob = pBlob;
382 
383   sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
384   p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
385   Tcl_RegisterChannel(interp, p->channel);
386 
387   /* Link the new channel into the SqliteDb.pIncrblob list. */
388   p->pNext = pDb->pIncrblob;
389   p->pPrev = 0;
390   if( p->pNext ){
391     p->pNext->pPrev = p;
392   }
393   pDb->pIncrblob = p;
394   p->pDb = pDb;
395 
396   Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
397   return TCL_OK;
398 }
399 #else  /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
400   #define closeIncrblobChannels(pDb)
401 #endif
402 
403 /*
404 ** Look at the script prefix in pCmd.  We will be executing this script
405 ** after first appending one or more arguments.  This routine analyzes
406 ** the script to see if it is safe to use Tcl_EvalObjv() on the script
407 ** rather than the more general Tcl_EvalEx().  Tcl_EvalObjv() is much
408 ** faster.
409 **
410 ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
411 ** command name followed by zero or more arguments with no [...] or $
412 ** or {...} or ; to be seen anywhere.  Most callback scripts consist
413 ** of just a single procedure name and they meet this requirement.
414 */
415 static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
416   /* We could try to do something with Tcl_Parse().  But we will instead
417   ** just do a search for forbidden characters.  If any of the forbidden
418   ** characters appear in pCmd, we will report the string as unsafe.
419   */
420   const char *z;
421   int n;
422   z = Tcl_GetStringFromObj(pCmd, &n);
423   while( n-- > 0 ){
424     int c = *(z++);
425     if( c=='$' || c=='[' || c==';' ) return 0;
426   }
427   return 1;
428 }
429 
430 /*
431 ** Find an SqlFunc structure with the given name.  Or create a new
432 ** one if an existing one cannot be found.  Return a pointer to the
433 ** structure.
434 */
435 static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
436   SqlFunc *p, *pNew;
437   int nName = strlen30(zName);
438   pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
439   pNew->zName = (char*)&pNew[1];
440   memcpy(pNew->zName, zName, nName+1);
441   for(p=pDb->pFunc; p; p=p->pNext){
442     if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
443       Tcl_Free((char*)pNew);
444       return p;
445     }
446   }
447   pNew->interp = pDb->interp;
448   pNew->pDb = pDb;
449   pNew->pScript = 0;
450   pNew->pNext = pDb->pFunc;
451   pDb->pFunc = pNew;
452   return pNew;
453 }
454 
455 /*
456 ** Free a single SqlPreparedStmt object.
457 */
458 static void dbFreeStmt(SqlPreparedStmt *pStmt){
459 #ifdef SQLITE_TEST
460   if( sqlite3_sql(pStmt->pStmt)==0 ){
461     Tcl_Free((char *)pStmt->zSql);
462   }
463 #endif
464   sqlite3_finalize(pStmt->pStmt);
465   Tcl_Free((char *)pStmt);
466 }
467 
468 /*
469 ** Finalize and free a list of prepared statements
470 */
471 static void flushStmtCache(SqliteDb *pDb){
472   SqlPreparedStmt *pPreStmt;
473   SqlPreparedStmt *pNext;
474 
475   for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
476     pNext = pPreStmt->pNext;
477     dbFreeStmt(pPreStmt);
478   }
479   pDb->nStmt = 0;
480   pDb->stmtLast = 0;
481   pDb->stmtList = 0;
482 }
483 
484 /*
485 ** TCL calls this procedure when an sqlite3 database command is
486 ** deleted.
487 */
488 static void DbDeleteCmd(void *db){
489   SqliteDb *pDb = (SqliteDb*)db;
490   flushStmtCache(pDb);
491   closeIncrblobChannels(pDb);
492   sqlite3_close(pDb->db);
493   while( pDb->pFunc ){
494     SqlFunc *pFunc = pDb->pFunc;
495     pDb->pFunc = pFunc->pNext;
496     assert( pFunc->pDb==pDb );
497     Tcl_DecrRefCount(pFunc->pScript);
498     Tcl_Free((char*)pFunc);
499   }
500   while( pDb->pCollate ){
501     SqlCollate *pCollate = pDb->pCollate;
502     pDb->pCollate = pCollate->pNext;
503     Tcl_Free((char*)pCollate);
504   }
505   if( pDb->zBusy ){
506     Tcl_Free(pDb->zBusy);
507   }
508   if( pDb->zTrace ){
509     Tcl_Free(pDb->zTrace);
510   }
511   if( pDb->zProfile ){
512     Tcl_Free(pDb->zProfile);
513   }
514   if( pDb->zAuth ){
515     Tcl_Free(pDb->zAuth);
516   }
517   if( pDb->zNull ){
518     Tcl_Free(pDb->zNull);
519   }
520   if( pDb->pUpdateHook ){
521     Tcl_DecrRefCount(pDb->pUpdateHook);
522   }
523   if( pDb->pPreUpdateHook ){
524     Tcl_DecrRefCount(pDb->pPreUpdateHook);
525   }
526   if( pDb->pRollbackHook ){
527     Tcl_DecrRefCount(pDb->pRollbackHook);
528   }
529   if( pDb->pWalHook ){
530     Tcl_DecrRefCount(pDb->pWalHook);
531   }
532   if( pDb->pCollateNeeded ){
533     Tcl_DecrRefCount(pDb->pCollateNeeded);
534   }
535   Tcl_Free((char*)pDb);
536 }
537 
538 /*
539 ** This routine is called when a database file is locked while trying
540 ** to execute SQL.
541 */
542 static int DbBusyHandler(void *cd, int nTries){
543   SqliteDb *pDb = (SqliteDb*)cd;
544   int rc;
545   char zVal[30];
546 
547   sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
548   rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
549   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
550     return 0;
551   }
552   return 1;
553 }
554 
555 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
556 /*
557 ** This routine is invoked as the 'progress callback' for the database.
558 */
559 static int DbProgressHandler(void *cd){
560   SqliteDb *pDb = (SqliteDb*)cd;
561   int rc;
562 
563   assert( pDb->zProgress );
564   rc = Tcl_Eval(pDb->interp, pDb->zProgress);
565   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
566     return 1;
567   }
568   return 0;
569 }
570 #endif
571 
572 #ifndef SQLITE_OMIT_TRACE
573 /*
574 ** This routine is called by the SQLite trace handler whenever a new
575 ** block of SQL is executed.  The TCL script in pDb->zTrace is executed.
576 */
577 static void DbTraceHandler(void *cd, const char *zSql){
578   SqliteDb *pDb = (SqliteDb*)cd;
579   Tcl_DString str;
580 
581   Tcl_DStringInit(&str);
582   Tcl_DStringAppend(&str, pDb->zTrace, -1);
583   Tcl_DStringAppendElement(&str, zSql);
584   Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
585   Tcl_DStringFree(&str);
586   Tcl_ResetResult(pDb->interp);
587 }
588 #endif
589 
590 #ifndef SQLITE_OMIT_TRACE
591 /*
592 ** This routine is called by the SQLite profile handler after a statement
593 ** SQL has executed.  The TCL script in pDb->zProfile is evaluated.
594 */
595 static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
596   SqliteDb *pDb = (SqliteDb*)cd;
597   Tcl_DString str;
598   char zTm[100];
599 
600   sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
601   Tcl_DStringInit(&str);
602   Tcl_DStringAppend(&str, pDb->zProfile, -1);
603   Tcl_DStringAppendElement(&str, zSql);
604   Tcl_DStringAppendElement(&str, zTm);
605   Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
606   Tcl_DStringFree(&str);
607   Tcl_ResetResult(pDb->interp);
608 }
609 #endif
610 
611 /*
612 ** This routine is called when a transaction is committed.  The
613 ** TCL script in pDb->zCommit is executed.  If it returns non-zero or
614 ** if it throws an exception, the transaction is rolled back instead
615 ** of being committed.
616 */
617 static int DbCommitHandler(void *cd){
618   SqliteDb *pDb = (SqliteDb*)cd;
619   int rc;
620 
621   rc = Tcl_Eval(pDb->interp, pDb->zCommit);
622   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
623     return 1;
624   }
625   return 0;
626 }
627 
628 static void DbRollbackHandler(void *clientData){
629   SqliteDb *pDb = (SqliteDb*)clientData;
630   assert(pDb->pRollbackHook);
631   if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
632     Tcl_BackgroundError(pDb->interp);
633   }
634 }
635 
636 /*
637 ** This procedure handles wal_hook callbacks.
638 */
639 static int DbWalHandler(
640   void *clientData,
641   sqlite3 *db,
642   const char *zDb,
643   int nEntry
644 ){
645   int ret = SQLITE_OK;
646   Tcl_Obj *p;
647   SqliteDb *pDb = (SqliteDb*)clientData;
648   Tcl_Interp *interp = pDb->interp;
649   assert(pDb->pWalHook);
650 
651   assert( db==pDb->db );
652   p = Tcl_DuplicateObj(pDb->pWalHook);
653   Tcl_IncrRefCount(p);
654   Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
655   Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
656   if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
657    || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
658   ){
659     Tcl_BackgroundError(interp);
660   }
661   Tcl_DecrRefCount(p);
662 
663   return ret;
664 }
665 
666 #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
667 static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
668   char zBuf[64];
669   sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
670   Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
671   sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
672   Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
673 }
674 #else
675 # define setTestUnlockNotifyVars(x,y,z)
676 #endif
677 
678 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
679 static void DbUnlockNotify(void **apArg, int nArg){
680   int i;
681   for(i=0; i<nArg; i++){
682     const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
683     SqliteDb *pDb = (SqliteDb *)apArg[i];
684     setTestUnlockNotifyVars(pDb->interp, i, nArg);
685     assert( pDb->pUnlockNotify);
686     Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
687     Tcl_DecrRefCount(pDb->pUnlockNotify);
688     pDb->pUnlockNotify = 0;
689   }
690 }
691 #endif
692 
693 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
694 /*
695 ** Pre-update hook callback.
696 */
697 static void DbPreUpdateHandler(
698   void *p,
699   sqlite3 *db,
700   int op,
701   const char *zDb,
702   const char *zTbl,
703   sqlite_int64 iKey1,
704   sqlite_int64 iKey2
705 ){
706   SqliteDb *pDb = (SqliteDb *)p;
707   Tcl_Obj *pCmd;
708   static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
709 
710   assert( (SQLITE_DELETE-1)/9 == 0 );
711   assert( (SQLITE_INSERT-1)/9 == 1 );
712   assert( (SQLITE_UPDATE-1)/9 == 2 );
713   assert( pDb->pPreUpdateHook );
714   assert( db==pDb->db );
715   assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
716 
717   pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
718   Tcl_IncrRefCount(pCmd);
719   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
720   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
721   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
722   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
723   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
724   Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
725   Tcl_DecrRefCount(pCmd);
726 }
727 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
728 
729 static void DbUpdateHandler(
730   void *p,
731   int op,
732   const char *zDb,
733   const char *zTbl,
734   sqlite_int64 rowid
735 ){
736   SqliteDb *pDb = (SqliteDb *)p;
737   Tcl_Obj *pCmd;
738   static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
739 
740   assert( (SQLITE_DELETE-1)/9 == 0 );
741   assert( (SQLITE_INSERT-1)/9 == 1 );
742   assert( (SQLITE_UPDATE-1)/9 == 2 );
743 
744   assert( pDb->pUpdateHook );
745   assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
746 
747   pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
748   Tcl_IncrRefCount(pCmd);
749   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
750   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
751   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
752   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
753   Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
754   Tcl_DecrRefCount(pCmd);
755 }
756 
757 static void tclCollateNeeded(
758   void *pCtx,
759   sqlite3 *db,
760   int enc,
761   const char *zName
762 ){
763   SqliteDb *pDb = (SqliteDb *)pCtx;
764   Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
765   Tcl_IncrRefCount(pScript);
766   Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
767   Tcl_EvalObjEx(pDb->interp, pScript, 0);
768   Tcl_DecrRefCount(pScript);
769 }
770 
771 /*
772 ** This routine is called to evaluate an SQL collation function implemented
773 ** using TCL script.
774 */
775 static int tclSqlCollate(
776   void *pCtx,
777   int nA,
778   const void *zA,
779   int nB,
780   const void *zB
781 ){
782   SqlCollate *p = (SqlCollate *)pCtx;
783   Tcl_Obj *pCmd;
784 
785   pCmd = Tcl_NewStringObj(p->zScript, -1);
786   Tcl_IncrRefCount(pCmd);
787   Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
788   Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
789   Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
790   Tcl_DecrRefCount(pCmd);
791   return (atoi(Tcl_GetStringResult(p->interp)));
792 }
793 
794 /*
795 ** This routine is called to evaluate an SQL function implemented
796 ** using TCL script.
797 */
798 static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
799   SqlFunc *p = sqlite3_user_data(context);
800   Tcl_Obj *pCmd;
801   int i;
802   int rc;
803 
804   if( argc==0 ){
805     /* If there are no arguments to the function, call Tcl_EvalObjEx on the
806     ** script object directly.  This allows the TCL compiler to generate
807     ** bytecode for the command on the first invocation and thus make
808     ** subsequent invocations much faster. */
809     pCmd = p->pScript;
810     Tcl_IncrRefCount(pCmd);
811     rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
812     Tcl_DecrRefCount(pCmd);
813   }else{
814     /* If there are arguments to the function, make a shallow copy of the
815     ** script object, lappend the arguments, then evaluate the copy.
816     **
817     ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
818     ** The new Tcl_Obj contains pointers to the original list elements.
819     ** That way, when Tcl_EvalObjv() is run and shimmers the first element
820     ** of the list to tclCmdNameType, that alternate representation will
821     ** be preserved and reused on the next invocation.
822     */
823     Tcl_Obj **aArg;
824     int nArg;
825     if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
826       sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
827       return;
828     }
829     pCmd = Tcl_NewListObj(nArg, aArg);
830     Tcl_IncrRefCount(pCmd);
831     for(i=0; i<argc; i++){
832       sqlite3_value *pIn = argv[i];
833       Tcl_Obj *pVal;
834 
835       /* Set pVal to contain the i'th column of this row. */
836       switch( sqlite3_value_type(pIn) ){
837         case SQLITE_BLOB: {
838           int bytes = sqlite3_value_bytes(pIn);
839           pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
840           break;
841         }
842         case SQLITE_INTEGER: {
843           sqlite_int64 v = sqlite3_value_int64(pIn);
844           if( v>=-2147483647 && v<=2147483647 ){
845             pVal = Tcl_NewIntObj((int)v);
846           }else{
847             pVal = Tcl_NewWideIntObj(v);
848           }
849           break;
850         }
851         case SQLITE_FLOAT: {
852           double r = sqlite3_value_double(pIn);
853           pVal = Tcl_NewDoubleObj(r);
854           break;
855         }
856         case SQLITE_NULL: {
857           pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
858           break;
859         }
860         default: {
861           int bytes = sqlite3_value_bytes(pIn);
862           pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
863           break;
864         }
865       }
866       rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
867       if( rc ){
868         Tcl_DecrRefCount(pCmd);
869         sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
870         return;
871       }
872     }
873     if( !p->useEvalObjv ){
874       /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
875       ** is a list without a string representation.  To prevent this from
876       ** happening, make sure pCmd has a valid string representation */
877       Tcl_GetString(pCmd);
878     }
879     rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
880     Tcl_DecrRefCount(pCmd);
881   }
882 
883   if( rc && rc!=TCL_RETURN ){
884     sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
885   }else{
886     Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
887     int n;
888     u8 *data;
889     const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
890     char c = zType[0];
891     if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
892       /* Only return a BLOB type if the Tcl variable is a bytearray and
893       ** has no string representation. */
894       data = Tcl_GetByteArrayFromObj(pVar, &n);
895       sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
896     }else if( c=='b' && strcmp(zType,"boolean")==0 ){
897       Tcl_GetIntFromObj(0, pVar, &n);
898       sqlite3_result_int(context, n);
899     }else if( c=='d' && strcmp(zType,"double")==0 ){
900       double r;
901       Tcl_GetDoubleFromObj(0, pVar, &r);
902       sqlite3_result_double(context, r);
903     }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
904           (c=='i' && strcmp(zType,"int")==0) ){
905       Tcl_WideInt v;
906       Tcl_GetWideIntFromObj(0, pVar, &v);
907       sqlite3_result_int64(context, v);
908     }else{
909       data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
910       sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
911     }
912   }
913 }
914 
915 #ifndef SQLITE_OMIT_AUTHORIZATION
916 /*
917 ** This is the authentication function.  It appends the authentication
918 ** type code and the two arguments to zCmd[] then invokes the result
919 ** on the interpreter.  The reply is examined to determine if the
920 ** authentication fails or succeeds.
921 */
922 static int auth_callback(
923   void *pArg,
924   int code,
925   const char *zArg1,
926   const char *zArg2,
927   const char *zArg3,
928   const char *zArg4
929 #ifdef SQLITE_USER_AUTHENTICATION
930   ,const char *zArg5
931 #endif
932 ){
933   const char *zCode;
934   Tcl_DString str;
935   int rc;
936   const char *zReply;
937   SqliteDb *pDb = (SqliteDb*)pArg;
938   if( pDb->disableAuth ) return SQLITE_OK;
939 
940   switch( code ){
941     case SQLITE_COPY              : zCode="SQLITE_COPY"; break;
942     case SQLITE_CREATE_INDEX      : zCode="SQLITE_CREATE_INDEX"; break;
943     case SQLITE_CREATE_TABLE      : zCode="SQLITE_CREATE_TABLE"; break;
944     case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
945     case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
946     case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
947     case SQLITE_CREATE_TEMP_VIEW  : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
948     case SQLITE_CREATE_TRIGGER    : zCode="SQLITE_CREATE_TRIGGER"; break;
949     case SQLITE_CREATE_VIEW       : zCode="SQLITE_CREATE_VIEW"; break;
950     case SQLITE_DELETE            : zCode="SQLITE_DELETE"; break;
951     case SQLITE_DROP_INDEX        : zCode="SQLITE_DROP_INDEX"; break;
952     case SQLITE_DROP_TABLE        : zCode="SQLITE_DROP_TABLE"; break;
953     case SQLITE_DROP_TEMP_INDEX   : zCode="SQLITE_DROP_TEMP_INDEX"; break;
954     case SQLITE_DROP_TEMP_TABLE   : zCode="SQLITE_DROP_TEMP_TABLE"; break;
955     case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
956     case SQLITE_DROP_TEMP_VIEW    : zCode="SQLITE_DROP_TEMP_VIEW"; break;
957     case SQLITE_DROP_TRIGGER      : zCode="SQLITE_DROP_TRIGGER"; break;
958     case SQLITE_DROP_VIEW         : zCode="SQLITE_DROP_VIEW"; break;
959     case SQLITE_INSERT            : zCode="SQLITE_INSERT"; break;
960     case SQLITE_PRAGMA            : zCode="SQLITE_PRAGMA"; break;
961     case SQLITE_READ              : zCode="SQLITE_READ"; break;
962     case SQLITE_SELECT            : zCode="SQLITE_SELECT"; break;
963     case SQLITE_TRANSACTION       : zCode="SQLITE_TRANSACTION"; break;
964     case SQLITE_UPDATE            : zCode="SQLITE_UPDATE"; break;
965     case SQLITE_ATTACH            : zCode="SQLITE_ATTACH"; break;
966     case SQLITE_DETACH            : zCode="SQLITE_DETACH"; break;
967     case SQLITE_ALTER_TABLE       : zCode="SQLITE_ALTER_TABLE"; break;
968     case SQLITE_REINDEX           : zCode="SQLITE_REINDEX"; break;
969     case SQLITE_ANALYZE           : zCode="SQLITE_ANALYZE"; break;
970     case SQLITE_CREATE_VTABLE     : zCode="SQLITE_CREATE_VTABLE"; break;
971     case SQLITE_DROP_VTABLE       : zCode="SQLITE_DROP_VTABLE"; break;
972     case SQLITE_FUNCTION          : zCode="SQLITE_FUNCTION"; break;
973     case SQLITE_SAVEPOINT         : zCode="SQLITE_SAVEPOINT"; break;
974     case SQLITE_RECURSIVE         : zCode="SQLITE_RECURSIVE"; break;
975     default                       : zCode="????"; break;
976   }
977   Tcl_DStringInit(&str);
978   Tcl_DStringAppend(&str, pDb->zAuth, -1);
979   Tcl_DStringAppendElement(&str, zCode);
980   Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
981   Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
982   Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
983   Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
984 #ifdef SQLITE_USER_AUTHENTICATION
985   Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
986 #endif
987   rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
988   Tcl_DStringFree(&str);
989   zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
990   if( strcmp(zReply,"SQLITE_OK")==0 ){
991     rc = SQLITE_OK;
992   }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
993     rc = SQLITE_DENY;
994   }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
995     rc = SQLITE_IGNORE;
996   }else{
997     rc = 999;
998   }
999   return rc;
1000 }
1001 #endif /* SQLITE_OMIT_AUTHORIZATION */
1002 
1003 /*
1004 ** This routine reads a line of text from FILE in, stores
1005 ** the text in memory obtained from malloc() and returns a pointer
1006 ** to the text.  NULL is returned at end of file, or if malloc()
1007 ** fails.
1008 **
1009 ** The interface is like "readline" but no command-line editing
1010 ** is done.
1011 **
1012 ** copied from shell.c from '.import' command
1013 */
1014 static char *local_getline(char *zPrompt, FILE *in){
1015   char *zLine;
1016   int nLine;
1017   int n;
1018 
1019   nLine = 100;
1020   zLine = malloc( nLine );
1021   if( zLine==0 ) return 0;
1022   n = 0;
1023   while( 1 ){
1024     if( n+100>nLine ){
1025       nLine = nLine*2 + 100;
1026       zLine = realloc(zLine, nLine);
1027       if( zLine==0 ) return 0;
1028     }
1029     if( fgets(&zLine[n], nLine - n, in)==0 ){
1030       if( n==0 ){
1031         free(zLine);
1032         return 0;
1033       }
1034       zLine[n] = 0;
1035       break;
1036     }
1037     while( zLine[n] ){ n++; }
1038     if( n>0 && zLine[n-1]=='\n' ){
1039       n--;
1040       zLine[n] = 0;
1041       break;
1042     }
1043   }
1044   zLine = realloc( zLine, n+1 );
1045   return zLine;
1046 }
1047 
1048 
1049 /*
1050 ** This function is part of the implementation of the command:
1051 **
1052 **   $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1053 **
1054 ** It is invoked after evaluating the script SCRIPT to commit or rollback
1055 ** the transaction or savepoint opened by the [transaction] command.
1056 */
1057 static int DbTransPostCmd(
1058   ClientData data[],                   /* data[0] is the Sqlite3Db* for $db */
1059   Tcl_Interp *interp,                  /* Tcl interpreter */
1060   int result                           /* Result of evaluating SCRIPT */
1061 ){
1062   static const char *const azEnd[] = {
1063     "RELEASE _tcl_transaction",        /* rc==TCL_ERROR, nTransaction!=0 */
1064     "COMMIT",                          /* rc!=TCL_ERROR, nTransaction==0 */
1065     "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1066     "ROLLBACK"                         /* rc==TCL_ERROR, nTransaction==0 */
1067   };
1068   SqliteDb *pDb = (SqliteDb*)data[0];
1069   int rc = result;
1070   const char *zEnd;
1071 
1072   pDb->nTransaction--;
1073   zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1074 
1075   pDb->disableAuth++;
1076   if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1077       /* This is a tricky scenario to handle. The most likely cause of an
1078       ** error is that the exec() above was an attempt to commit the
1079       ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1080       ** that an IO-error has occurred. In either case, throw a Tcl exception
1081       ** and try to rollback the transaction.
1082       **
1083       ** But it could also be that the user executed one or more BEGIN,
1084       ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1085       ** this method's logic. Not clear how this would be best handled.
1086       */
1087     if( rc!=TCL_ERROR ){
1088       Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
1089       rc = TCL_ERROR;
1090     }
1091     sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1092   }
1093   pDb->disableAuth--;
1094 
1095   return rc;
1096 }
1097 
1098 /*
1099 ** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1100 ** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1101 ** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1102 ** on whether or not the [db_use_legacy_prepare] command has been used to
1103 ** configure the connection.
1104 */
1105 static int dbPrepare(
1106   SqliteDb *pDb,                  /* Database object */
1107   const char *zSql,               /* SQL to compile */
1108   sqlite3_stmt **ppStmt,          /* OUT: Prepared statement */
1109   const char **pzOut              /* OUT: Pointer to next SQL statement */
1110 ){
1111 #ifdef SQLITE_TEST
1112   if( pDb->bLegacyPrepare ){
1113     return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1114   }
1115 #endif
1116   return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut);
1117 }
1118 
1119 /*
1120 ** Search the cache for a prepared-statement object that implements the
1121 ** first SQL statement in the buffer pointed to by parameter zIn. If
1122 ** no such prepared-statement can be found, allocate and prepare a new
1123 ** one. In either case, bind the current values of the relevant Tcl
1124 ** variables to any $var, :var or @var variables in the statement. Before
1125 ** returning, set *ppPreStmt to point to the prepared-statement object.
1126 **
1127 ** Output parameter *pzOut is set to point to the next SQL statement in
1128 ** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1129 ** next statement.
1130 **
1131 ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1132 ** and an error message loaded into interpreter pDb->interp.
1133 */
1134 static int dbPrepareAndBind(
1135   SqliteDb *pDb,                  /* Database object */
1136   char const *zIn,                /* SQL to compile */
1137   char const **pzOut,             /* OUT: Pointer to next SQL statement */
1138   SqlPreparedStmt **ppPreStmt     /* OUT: Object used to cache statement */
1139 ){
1140   const char *zSql = zIn;         /* Pointer to first SQL statement in zIn */
1141   sqlite3_stmt *pStmt = 0;        /* Prepared statement object */
1142   SqlPreparedStmt *pPreStmt;      /* Pointer to cached statement */
1143   int nSql;                       /* Length of zSql in bytes */
1144   int nVar = 0;                   /* Number of variables in statement */
1145   int iParm = 0;                  /* Next free entry in apParm */
1146   char c;
1147   int i;
1148   Tcl_Interp *interp = pDb->interp;
1149 
1150   *ppPreStmt = 0;
1151 
1152   /* Trim spaces from the start of zSql and calculate the remaining length. */
1153   while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
1154   nSql = strlen30(zSql);
1155 
1156   for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1157     int n = pPreStmt->nSql;
1158     if( nSql>=n
1159         && memcmp(pPreStmt->zSql, zSql, n)==0
1160         && (zSql[n]==0 || zSql[n-1]==';')
1161     ){
1162       pStmt = pPreStmt->pStmt;
1163       *pzOut = &zSql[pPreStmt->nSql];
1164 
1165       /* When a prepared statement is found, unlink it from the
1166       ** cache list.  It will later be added back to the beginning
1167       ** of the cache list in order to implement LRU replacement.
1168       */
1169       if( pPreStmt->pPrev ){
1170         pPreStmt->pPrev->pNext = pPreStmt->pNext;
1171       }else{
1172         pDb->stmtList = pPreStmt->pNext;
1173       }
1174       if( pPreStmt->pNext ){
1175         pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1176       }else{
1177         pDb->stmtLast = pPreStmt->pPrev;
1178       }
1179       pDb->nStmt--;
1180       nVar = sqlite3_bind_parameter_count(pStmt);
1181       break;
1182     }
1183   }
1184 
1185   /* If no prepared statement was found. Compile the SQL text. Also allocate
1186   ** a new SqlPreparedStmt structure.  */
1187   if( pPreStmt==0 ){
1188     int nByte;
1189 
1190     if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
1191       Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1192       return TCL_ERROR;
1193     }
1194     if( pStmt==0 ){
1195       if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1196         /* A compile-time error in the statement. */
1197         Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1198         return TCL_ERROR;
1199       }else{
1200         /* The statement was a no-op.  Continue to the next statement
1201         ** in the SQL string.
1202         */
1203         return TCL_OK;
1204       }
1205     }
1206 
1207     assert( pPreStmt==0 );
1208     nVar = sqlite3_bind_parameter_count(pStmt);
1209     nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1210     pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1211     memset(pPreStmt, 0, nByte);
1212 
1213     pPreStmt->pStmt = pStmt;
1214     pPreStmt->nSql = (int)(*pzOut - zSql);
1215     pPreStmt->zSql = sqlite3_sql(pStmt);
1216     pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
1217 #ifdef SQLITE_TEST
1218     if( pPreStmt->zSql==0 ){
1219       char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1220       memcpy(zCopy, zSql, pPreStmt->nSql);
1221       zCopy[pPreStmt->nSql] = '\0';
1222       pPreStmt->zSql = zCopy;
1223     }
1224 #endif
1225   }
1226   assert( pPreStmt );
1227   assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1228   assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1229 
1230   /* Bind values to parameters that begin with $ or : */
1231   for(i=1; i<=nVar; i++){
1232     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1233     if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1234       Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1235       if( pVar ){
1236         int n;
1237         u8 *data;
1238         const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1239         c = zType[0];
1240         if( zVar[0]=='@' ||
1241            (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1242           /* Load a BLOB type if the Tcl variable is a bytearray and
1243           ** it has no string representation or the host
1244           ** parameter name begins with "@". */
1245           data = Tcl_GetByteArrayFromObj(pVar, &n);
1246           sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1247           Tcl_IncrRefCount(pVar);
1248           pPreStmt->apParm[iParm++] = pVar;
1249         }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1250           Tcl_GetIntFromObj(interp, pVar, &n);
1251           sqlite3_bind_int(pStmt, i, n);
1252         }else if( c=='d' && strcmp(zType,"double")==0 ){
1253           double r;
1254           Tcl_GetDoubleFromObj(interp, pVar, &r);
1255           sqlite3_bind_double(pStmt, i, r);
1256         }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1257               (c=='i' && strcmp(zType,"int")==0) ){
1258           Tcl_WideInt v;
1259           Tcl_GetWideIntFromObj(interp, pVar, &v);
1260           sqlite3_bind_int64(pStmt, i, v);
1261         }else{
1262           data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1263           sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1264           Tcl_IncrRefCount(pVar);
1265           pPreStmt->apParm[iParm++] = pVar;
1266         }
1267       }else{
1268         sqlite3_bind_null(pStmt, i);
1269       }
1270     }
1271   }
1272   pPreStmt->nParm = iParm;
1273   *ppPreStmt = pPreStmt;
1274 
1275   return TCL_OK;
1276 }
1277 
1278 /*
1279 ** Release a statement reference obtained by calling dbPrepareAndBind().
1280 ** There should be exactly one call to this function for each call to
1281 ** dbPrepareAndBind().
1282 **
1283 ** If the discard parameter is non-zero, then the statement is deleted
1284 ** immediately. Otherwise it is added to the LRU list and may be returned
1285 ** by a subsequent call to dbPrepareAndBind().
1286 */
1287 static void dbReleaseStmt(
1288   SqliteDb *pDb,                  /* Database handle */
1289   SqlPreparedStmt *pPreStmt,      /* Prepared statement handle to release */
1290   int discard                     /* True to delete (not cache) the pPreStmt */
1291 ){
1292   int i;
1293 
1294   /* Free the bound string and blob parameters */
1295   for(i=0; i<pPreStmt->nParm; i++){
1296     Tcl_DecrRefCount(pPreStmt->apParm[i]);
1297   }
1298   pPreStmt->nParm = 0;
1299 
1300   if( pDb->maxStmt<=0 || discard ){
1301     /* If the cache is turned off, deallocated the statement */
1302     dbFreeStmt(pPreStmt);
1303   }else{
1304     /* Add the prepared statement to the beginning of the cache list. */
1305     pPreStmt->pNext = pDb->stmtList;
1306     pPreStmt->pPrev = 0;
1307     if( pDb->stmtList ){
1308      pDb->stmtList->pPrev = pPreStmt;
1309     }
1310     pDb->stmtList = pPreStmt;
1311     if( pDb->stmtLast==0 ){
1312       assert( pDb->nStmt==0 );
1313       pDb->stmtLast = pPreStmt;
1314     }else{
1315       assert( pDb->nStmt>0 );
1316     }
1317     pDb->nStmt++;
1318 
1319     /* If we have too many statement in cache, remove the surplus from
1320     ** the end of the cache list.  */
1321     while( pDb->nStmt>pDb->maxStmt ){
1322       SqlPreparedStmt *pLast = pDb->stmtLast;
1323       pDb->stmtLast = pLast->pPrev;
1324       pDb->stmtLast->pNext = 0;
1325       pDb->nStmt--;
1326       dbFreeStmt(pLast);
1327     }
1328   }
1329 }
1330 
1331 /*
1332 ** Structure used with dbEvalXXX() functions:
1333 **
1334 **   dbEvalInit()
1335 **   dbEvalStep()
1336 **   dbEvalFinalize()
1337 **   dbEvalRowInfo()
1338 **   dbEvalColumnValue()
1339 */
1340 typedef struct DbEvalContext DbEvalContext;
1341 struct DbEvalContext {
1342   SqliteDb *pDb;                  /* Database handle */
1343   Tcl_Obj *pSql;                  /* Object holding string zSql */
1344   const char *zSql;               /* Remaining SQL to execute */
1345   SqlPreparedStmt *pPreStmt;      /* Current statement */
1346   int nCol;                       /* Number of columns returned by pStmt */
1347   Tcl_Obj *pArray;                /* Name of array variable */
1348   Tcl_Obj **apColName;            /* Array of column names */
1349 };
1350 
1351 /*
1352 ** Release any cache of column names currently held as part of
1353 ** the DbEvalContext structure passed as the first argument.
1354 */
1355 static void dbReleaseColumnNames(DbEvalContext *p){
1356   if( p->apColName ){
1357     int i;
1358     for(i=0; i<p->nCol; i++){
1359       Tcl_DecrRefCount(p->apColName[i]);
1360     }
1361     Tcl_Free((char *)p->apColName);
1362     p->apColName = 0;
1363   }
1364   p->nCol = 0;
1365 }
1366 
1367 /*
1368 ** Initialize a DbEvalContext structure.
1369 **
1370 ** If pArray is not NULL, then it contains the name of a Tcl array
1371 ** variable. The "*" member of this array is set to a list containing
1372 ** the names of the columns returned by the statement as part of each
1373 ** call to dbEvalStep(), in order from left to right. e.g. if the names
1374 ** of the returned columns are a, b and c, it does the equivalent of the
1375 ** tcl command:
1376 **
1377 **     set ${pArray}(*) {a b c}
1378 */
1379 static void dbEvalInit(
1380   DbEvalContext *p,               /* Pointer to structure to initialize */
1381   SqliteDb *pDb,                  /* Database handle */
1382   Tcl_Obj *pSql,                  /* Object containing SQL script */
1383   Tcl_Obj *pArray                 /* Name of Tcl array to set (*) element of */
1384 ){
1385   memset(p, 0, sizeof(DbEvalContext));
1386   p->pDb = pDb;
1387   p->zSql = Tcl_GetString(pSql);
1388   p->pSql = pSql;
1389   Tcl_IncrRefCount(pSql);
1390   if( pArray ){
1391     p->pArray = pArray;
1392     Tcl_IncrRefCount(pArray);
1393   }
1394 }
1395 
1396 /*
1397 ** Obtain information about the row that the DbEvalContext passed as the
1398 ** first argument currently points to.
1399 */
1400 static void dbEvalRowInfo(
1401   DbEvalContext *p,               /* Evaluation context */
1402   int *pnCol,                     /* OUT: Number of column names */
1403   Tcl_Obj ***papColName           /* OUT: Array of column names */
1404 ){
1405   /* Compute column names */
1406   if( 0==p->apColName ){
1407     sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1408     int i;                        /* Iterator variable */
1409     int nCol;                     /* Number of columns returned by pStmt */
1410     Tcl_Obj **apColName = 0;      /* Array of column names */
1411 
1412     p->nCol = nCol = sqlite3_column_count(pStmt);
1413     if( nCol>0 && (papColName || p->pArray) ){
1414       apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1415       for(i=0; i<nCol; i++){
1416         apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
1417         Tcl_IncrRefCount(apColName[i]);
1418       }
1419       p->apColName = apColName;
1420     }
1421 
1422     /* If results are being stored in an array variable, then create
1423     ** the array(*) entry for that array
1424     */
1425     if( p->pArray ){
1426       Tcl_Interp *interp = p->pDb->interp;
1427       Tcl_Obj *pColList = Tcl_NewObj();
1428       Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
1429 
1430       for(i=0; i<nCol; i++){
1431         Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1432       }
1433       Tcl_IncrRefCount(pStar);
1434       Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
1435       Tcl_DecrRefCount(pStar);
1436     }
1437   }
1438 
1439   if( papColName ){
1440     *papColName = p->apColName;
1441   }
1442   if( pnCol ){
1443     *pnCol = p->nCol;
1444   }
1445 }
1446 
1447 /*
1448 ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1449 ** returned, then an error message is stored in the interpreter before
1450 ** returning.
1451 **
1452 ** A return value of TCL_OK means there is a row of data available. The
1453 ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1454 ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1455 ** is returned, then the SQL script has finished executing and there are
1456 ** no further rows available. This is similar to SQLITE_DONE.
1457 */
1458 static int dbEvalStep(DbEvalContext *p){
1459   const char *zPrevSql = 0;       /* Previous value of p->zSql */
1460 
1461   while( p->zSql[0] || p->pPreStmt ){
1462     int rc;
1463     if( p->pPreStmt==0 ){
1464       zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
1465       rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1466       if( rc!=TCL_OK ) return rc;
1467     }else{
1468       int rcs;
1469       SqliteDb *pDb = p->pDb;
1470       SqlPreparedStmt *pPreStmt = p->pPreStmt;
1471       sqlite3_stmt *pStmt = pPreStmt->pStmt;
1472 
1473       rcs = sqlite3_step(pStmt);
1474       if( rcs==SQLITE_ROW ){
1475         return TCL_OK;
1476       }
1477       if( p->pArray ){
1478         dbEvalRowInfo(p, 0, 0);
1479       }
1480       rcs = sqlite3_reset(pStmt);
1481 
1482       pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1483       pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
1484       pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
1485       dbReleaseColumnNames(p);
1486       p->pPreStmt = 0;
1487 
1488       if( rcs!=SQLITE_OK ){
1489         /* If a run-time error occurs, report the error and stop reading
1490         ** the SQL.  */
1491         dbReleaseStmt(pDb, pPreStmt, 1);
1492 #if SQLITE_TEST
1493         if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1494           /* If the runtime error was an SQLITE_SCHEMA, and the database
1495           ** handle is configured to use the legacy sqlite3_prepare()
1496           ** interface, retry prepare()/step() on the same SQL statement.
1497           ** This only happens once. If there is a second SQLITE_SCHEMA
1498           ** error, the error will be returned to the caller. */
1499           p->zSql = zPrevSql;
1500           continue;
1501         }
1502 #endif
1503         Tcl_SetObjResult(pDb->interp,
1504                          Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1505         return TCL_ERROR;
1506       }else{
1507         dbReleaseStmt(pDb, pPreStmt, 0);
1508       }
1509     }
1510   }
1511 
1512   /* Finished */
1513   return TCL_BREAK;
1514 }
1515 
1516 /*
1517 ** Free all resources currently held by the DbEvalContext structure passed
1518 ** as the first argument. There should be exactly one call to this function
1519 ** for each call to dbEvalInit().
1520 */
1521 static void dbEvalFinalize(DbEvalContext *p){
1522   if( p->pPreStmt ){
1523     sqlite3_reset(p->pPreStmt->pStmt);
1524     dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1525     p->pPreStmt = 0;
1526   }
1527   if( p->pArray ){
1528     Tcl_DecrRefCount(p->pArray);
1529     p->pArray = 0;
1530   }
1531   Tcl_DecrRefCount(p->pSql);
1532   dbReleaseColumnNames(p);
1533 }
1534 
1535 /*
1536 ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1537 ** the value for the iCol'th column of the row currently pointed to by
1538 ** the DbEvalContext structure passed as the first argument.
1539 */
1540 static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1541   sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1542   switch( sqlite3_column_type(pStmt, iCol) ){
1543     case SQLITE_BLOB: {
1544       int bytes = sqlite3_column_bytes(pStmt, iCol);
1545       const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1546       if( !zBlob ) bytes = 0;
1547       return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1548     }
1549     case SQLITE_INTEGER: {
1550       sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1551       if( v>=-2147483647 && v<=2147483647 ){
1552         return Tcl_NewIntObj((int)v);
1553       }else{
1554         return Tcl_NewWideIntObj(v);
1555       }
1556     }
1557     case SQLITE_FLOAT: {
1558       return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1559     }
1560     case SQLITE_NULL: {
1561       return Tcl_NewStringObj(p->pDb->zNull, -1);
1562     }
1563   }
1564 
1565   return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
1566 }
1567 
1568 /*
1569 ** If using Tcl version 8.6 or greater, use the NR functions to avoid
1570 ** recursive evalution of scripts by the [db eval] and [db trans]
1571 ** commands. Even if the headers used while compiling the extension
1572 ** are 8.6 or newer, the code still tests the Tcl version at runtime.
1573 ** This allows stubs-enabled builds to be used with older Tcl libraries.
1574 */
1575 #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
1576 # define SQLITE_TCL_NRE 1
1577 static int DbUseNre(void){
1578   int major, minor;
1579   Tcl_GetVersion(&major, &minor, 0, 0);
1580   return( (major==8 && minor>=6) || major>8 );
1581 }
1582 #else
1583 /*
1584 ** Compiling using headers earlier than 8.6. In this case NR cannot be
1585 ** used, so DbUseNre() to always return zero. Add #defines for the other
1586 ** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1587 ** even though the only invocations of them are within conditional blocks
1588 ** of the form:
1589 **
1590 **   if( DbUseNre() ) { ... }
1591 */
1592 # define SQLITE_TCL_NRE 0
1593 # define DbUseNre() 0
1594 # define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
1595 # define Tcl_NREvalObj(a,b,c) 0
1596 # define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
1597 #endif
1598 
1599 /*
1600 ** This function is part of the implementation of the command:
1601 **
1602 **   $db eval SQL ?ARRAYNAME? SCRIPT
1603 */
1604 static int DbEvalNextCmd(
1605   ClientData data[],                   /* data[0] is the (DbEvalContext*) */
1606   Tcl_Interp *interp,                  /* Tcl interpreter */
1607   int result                           /* Result so far */
1608 ){
1609   int rc = result;                     /* Return code */
1610 
1611   /* The first element of the data[] array is a pointer to a DbEvalContext
1612   ** structure allocated using Tcl_Alloc(). The second element of data[]
1613   ** is a pointer to a Tcl_Obj containing the script to run for each row
1614   ** returned by the queries encapsulated in data[0]. */
1615   DbEvalContext *p = (DbEvalContext *)data[0];
1616   Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1617   Tcl_Obj *pArray = p->pArray;
1618 
1619   while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1620     int i;
1621     int nCol;
1622     Tcl_Obj **apColName;
1623     dbEvalRowInfo(p, &nCol, &apColName);
1624     for(i=0; i<nCol; i++){
1625       Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1626       if( pArray==0 ){
1627         Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1628       }else{
1629         Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1630       }
1631     }
1632 
1633     /* The required interpreter variables are now populated with the data
1634     ** from the current row. If using NRE, schedule callbacks to evaluate
1635     ** script pScript, then to invoke this function again to fetch the next
1636     ** row (or clean up if there is no next row or the script throws an
1637     ** exception). After scheduling the callbacks, return control to the
1638     ** caller.
1639     **
1640     ** If not using NRE, evaluate pScript directly and continue with the
1641     ** next iteration of this while(...) loop.  */
1642     if( DbUseNre() ){
1643       Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1644       return Tcl_NREvalObj(interp, pScript, 0);
1645     }else{
1646       rc = Tcl_EvalObjEx(interp, pScript, 0);
1647     }
1648   }
1649 
1650   Tcl_DecrRefCount(pScript);
1651   dbEvalFinalize(p);
1652   Tcl_Free((char *)p);
1653 
1654   if( rc==TCL_OK || rc==TCL_BREAK ){
1655     Tcl_ResetResult(interp);
1656     rc = TCL_OK;
1657   }
1658   return rc;
1659 }
1660 
1661 /*
1662 ** This function is used by the implementations of the following database
1663 ** handle sub-commands:
1664 **
1665 **   $db update_hook ?SCRIPT?
1666 **   $db wal_hook ?SCRIPT?
1667 **   $db commit_hook ?SCRIPT?
1668 **   $db preupdate hook ?SCRIPT?
1669 */
1670 static void DbHookCmd(
1671   Tcl_Interp *interp,             /* Tcl interpreter */
1672   SqliteDb *pDb,                  /* Database handle */
1673   Tcl_Obj *pArg,                  /* SCRIPT argument (or NULL) */
1674   Tcl_Obj **ppHook                /* Pointer to member of SqliteDb */
1675 ){
1676   sqlite3 *db = pDb->db;
1677 
1678   if( *ppHook ){
1679     Tcl_SetObjResult(interp, *ppHook);
1680     if( pArg ){
1681       Tcl_DecrRefCount(*ppHook);
1682       *ppHook = 0;
1683     }
1684   }
1685   if( pArg ){
1686     assert( !(*ppHook) );
1687     if( Tcl_GetCharLength(pArg)>0 ){
1688       *ppHook = pArg;
1689       Tcl_IncrRefCount(*ppHook);
1690     }
1691   }
1692 
1693 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1694   sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
1695 #endif
1696   sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1697   sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1698   sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
1699 }
1700 
1701 /*
1702 ** The "sqlite" command below creates a new Tcl command for each
1703 ** connection it opens to an SQLite database.  This routine is invoked
1704 ** whenever one of those connection-specific commands is executed
1705 ** in Tcl.  For example, if you run Tcl code like this:
1706 **
1707 **       sqlite3 db1  "my_database"
1708 **       db1 close
1709 **
1710 ** The first command opens a connection to the "my_database" database
1711 ** and calls that connection "db1".  The second command causes this
1712 ** subroutine to be invoked.
1713 */
1714 static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
1715   SqliteDb *pDb = (SqliteDb*)cd;
1716   int choice;
1717   int rc = TCL_OK;
1718   static const char *DB_strs[] = {
1719     "authorizer",         "backup",            "busy",
1720     "cache",              "changes",           "close",
1721     "collate",            "collation_needed",  "commit_hook",
1722     "complete",           "copy",              "enable_load_extension",
1723     "errorcode",          "eval",              "exists",
1724     "function",           "incrblob",          "interrupt",
1725     "last_insert_rowid",  "nullvalue",         "onecolumn",
1726     "preupdate",          "profile",           "progress",
1727     "rekey",              "restore",           "rollback_hook",
1728     "status",             "timeout",           "total_changes",
1729     "trace",              "transaction",       "unlock_notify",
1730     "update_hook",        "version",           "wal_hook",
1731     0
1732   };
1733   enum DB_enum {
1734     DB_AUTHORIZER,        DB_BACKUP,           DB_BUSY,
1735     DB_CACHE,             DB_CHANGES,          DB_CLOSE,
1736     DB_COLLATE,           DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1737     DB_COMPLETE,          DB_COPY,             DB_ENABLE_LOAD_EXTENSION,
1738     DB_ERRORCODE,         DB_EVAL,             DB_EXISTS,
1739     DB_FUNCTION,          DB_INCRBLOB,         DB_INTERRUPT,
1740     DB_LAST_INSERT_ROWID, DB_NULLVALUE,        DB_ONECOLUMN,
1741     DB_PREUPDATE,         DB_PROFILE,          DB_PROGRESS,
1742     DB_REKEY,             DB_RESTORE,          DB_ROLLBACK_HOOK,
1743     DB_STATUS,            DB_TIMEOUT,          DB_TOTAL_CHANGES,
1744     DB_TRACE,             DB_TRANSACTION,      DB_UNLOCK_NOTIFY,
1745     DB_UPDATE_HOOK,       DB_VERSION,          DB_WAL_HOOK,
1746   };
1747   /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
1748 
1749   if( objc<2 ){
1750     Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
1751     return TCL_ERROR;
1752   }
1753   if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
1754     return TCL_ERROR;
1755   }
1756 
1757   switch( (enum DB_enum)choice ){
1758 
1759   /*    $db authorizer ?CALLBACK?
1760   **
1761   ** Invoke the given callback to authorize each SQL operation as it is
1762   ** compiled.  5 arguments are appended to the callback before it is
1763   ** invoked:
1764   **
1765   **   (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1766   **   (2) First descriptive name (depends on authorization type)
1767   **   (3) Second descriptive name
1768   **   (4) Name of the database (ex: "main", "temp")
1769   **   (5) Name of trigger that is doing the access
1770   **
1771   ** The callback should return on of the following strings: SQLITE_OK,
1772   ** SQLITE_IGNORE, or SQLITE_DENY.  Any other return value is an error.
1773   **
1774   ** If this method is invoked with no arguments, the current authorization
1775   ** callback string is returned.
1776   */
1777   case DB_AUTHORIZER: {
1778 #ifdef SQLITE_OMIT_AUTHORIZATION
1779     Tcl_AppendResult(interp, "authorization not available in this build",
1780                      (char*)0);
1781     return TCL_ERROR;
1782 #else
1783     if( objc>3 ){
1784       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1785       return TCL_ERROR;
1786     }else if( objc==2 ){
1787       if( pDb->zAuth ){
1788         Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
1789       }
1790     }else{
1791       char *zAuth;
1792       int len;
1793       if( pDb->zAuth ){
1794         Tcl_Free(pDb->zAuth);
1795       }
1796       zAuth = Tcl_GetStringFromObj(objv[2], &len);
1797       if( zAuth && len>0 ){
1798         pDb->zAuth = Tcl_Alloc( len + 1 );
1799         memcpy(pDb->zAuth, zAuth, len+1);
1800       }else{
1801         pDb->zAuth = 0;
1802       }
1803       if( pDb->zAuth ){
1804         typedef int (*sqlite3_auth_cb)(
1805            void*,int,const char*,const char*,
1806            const char*,const char*);
1807         pDb->interp = interp;
1808         sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
1809       }else{
1810         sqlite3_set_authorizer(pDb->db, 0, 0);
1811       }
1812     }
1813 #endif
1814     break;
1815   }
1816 
1817   /*    $db backup ?DATABASE? FILENAME
1818   **
1819   ** Open or create a database file named FILENAME.  Transfer the
1820   ** content of local database DATABASE (default: "main") into the
1821   ** FILENAME database.
1822   */
1823   case DB_BACKUP: {
1824     const char *zDestFile;
1825     const char *zSrcDb;
1826     sqlite3 *pDest;
1827     sqlite3_backup *pBackup;
1828 
1829     if( objc==3 ){
1830       zSrcDb = "main";
1831       zDestFile = Tcl_GetString(objv[2]);
1832     }else if( objc==4 ){
1833       zSrcDb = Tcl_GetString(objv[2]);
1834       zDestFile = Tcl_GetString(objv[3]);
1835     }else{
1836       Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1837       return TCL_ERROR;
1838     }
1839     rc = sqlite3_open_v2(zDestFile, &pDest,
1840                SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
1841     if( rc!=SQLITE_OK ){
1842       Tcl_AppendResult(interp, "cannot open target database: ",
1843            sqlite3_errmsg(pDest), (char*)0);
1844       sqlite3_close(pDest);
1845       return TCL_ERROR;
1846     }
1847     pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1848     if( pBackup==0 ){
1849       Tcl_AppendResult(interp, "backup failed: ",
1850            sqlite3_errmsg(pDest), (char*)0);
1851       sqlite3_close(pDest);
1852       return TCL_ERROR;
1853     }
1854     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1855     sqlite3_backup_finish(pBackup);
1856     if( rc==SQLITE_DONE ){
1857       rc = TCL_OK;
1858     }else{
1859       Tcl_AppendResult(interp, "backup failed: ",
1860            sqlite3_errmsg(pDest), (char*)0);
1861       rc = TCL_ERROR;
1862     }
1863     sqlite3_close(pDest);
1864     break;
1865   }
1866 
1867   /*    $db busy ?CALLBACK?
1868   **
1869   ** Invoke the given callback if an SQL statement attempts to open
1870   ** a locked database file.
1871   */
1872   case DB_BUSY: {
1873     if( objc>3 ){
1874       Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
1875       return TCL_ERROR;
1876     }else if( objc==2 ){
1877       if( pDb->zBusy ){
1878         Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
1879       }
1880     }else{
1881       char *zBusy;
1882       int len;
1883       if( pDb->zBusy ){
1884         Tcl_Free(pDb->zBusy);
1885       }
1886       zBusy = Tcl_GetStringFromObj(objv[2], &len);
1887       if( zBusy && len>0 ){
1888         pDb->zBusy = Tcl_Alloc( len + 1 );
1889         memcpy(pDb->zBusy, zBusy, len+1);
1890       }else{
1891         pDb->zBusy = 0;
1892       }
1893       if( pDb->zBusy ){
1894         pDb->interp = interp;
1895         sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
1896       }else{
1897         sqlite3_busy_handler(pDb->db, 0, 0);
1898       }
1899     }
1900     break;
1901   }
1902 
1903   /*     $db cache flush
1904   **     $db cache size n
1905   **
1906   ** Flush the prepared statement cache, or set the maximum number of
1907   ** cached statements.
1908   */
1909   case DB_CACHE: {
1910     char *subCmd;
1911     int n;
1912 
1913     if( objc<=2 ){
1914       Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1915       return TCL_ERROR;
1916     }
1917     subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1918     if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1919       if( objc!=3 ){
1920         Tcl_WrongNumArgs(interp, 2, objv, "flush");
1921         return TCL_ERROR;
1922       }else{
1923         flushStmtCache( pDb );
1924       }
1925     }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1926       if( objc!=4 ){
1927         Tcl_WrongNumArgs(interp, 2, objv, "size n");
1928         return TCL_ERROR;
1929       }else{
1930         if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1931           Tcl_AppendResult( interp, "cannot convert \"",
1932                Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
1933           return TCL_ERROR;
1934         }else{
1935           if( n<0 ){
1936             flushStmtCache( pDb );
1937             n = 0;
1938           }else if( n>MAX_PREPARED_STMTS ){
1939             n = MAX_PREPARED_STMTS;
1940           }
1941           pDb->maxStmt = n;
1942         }
1943       }
1944     }else{
1945       Tcl_AppendResult( interp, "bad option \"",
1946           Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
1947           (char*)0);
1948       return TCL_ERROR;
1949     }
1950     break;
1951   }
1952 
1953   /*     $db changes
1954   **
1955   ** Return the number of rows that were modified, inserted, or deleted by
1956   ** the most recent INSERT, UPDATE or DELETE statement, not including
1957   ** any changes made by trigger programs.
1958   */
1959   case DB_CHANGES: {
1960     Tcl_Obj *pResult;
1961     if( objc!=2 ){
1962       Tcl_WrongNumArgs(interp, 2, objv, "");
1963       return TCL_ERROR;
1964     }
1965     pResult = Tcl_GetObjResult(interp);
1966     Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
1967     break;
1968   }
1969 
1970   /*    $db close
1971   **
1972   ** Shutdown the database
1973   */
1974   case DB_CLOSE: {
1975     Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1976     break;
1977   }
1978 
1979   /*
1980   **     $db collate NAME SCRIPT
1981   **
1982   ** Create a new SQL collation function called NAME.  Whenever
1983   ** that function is called, invoke SCRIPT to evaluate the function.
1984   */
1985   case DB_COLLATE: {
1986     SqlCollate *pCollate;
1987     char *zName;
1988     char *zScript;
1989     int nScript;
1990     if( objc!=4 ){
1991       Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1992       return TCL_ERROR;
1993     }
1994     zName = Tcl_GetStringFromObj(objv[2], 0);
1995     zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1996     pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1997     if( pCollate==0 ) return TCL_ERROR;
1998     pCollate->interp = interp;
1999     pCollate->pNext = pDb->pCollate;
2000     pCollate->zScript = (char*)&pCollate[1];
2001     pDb->pCollate = pCollate;
2002     memcpy(pCollate->zScript, zScript, nScript+1);
2003     if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
2004         pCollate, tclSqlCollate) ){
2005       Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
2006       return TCL_ERROR;
2007     }
2008     break;
2009   }
2010 
2011   /*
2012   **     $db collation_needed SCRIPT
2013   **
2014   ** Create a new SQL collation function called NAME.  Whenever
2015   ** that function is called, invoke SCRIPT to evaluate the function.
2016   */
2017   case DB_COLLATION_NEEDED: {
2018     if( objc!=3 ){
2019       Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
2020       return TCL_ERROR;
2021     }
2022     if( pDb->pCollateNeeded ){
2023       Tcl_DecrRefCount(pDb->pCollateNeeded);
2024     }
2025     pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
2026     Tcl_IncrRefCount(pDb->pCollateNeeded);
2027     sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
2028     break;
2029   }
2030 
2031   /*    $db commit_hook ?CALLBACK?
2032   **
2033   ** Invoke the given callback just before committing every SQL transaction.
2034   ** If the callback throws an exception or returns non-zero, then the
2035   ** transaction is aborted.  If CALLBACK is an empty string, the callback
2036   ** is disabled.
2037   */
2038   case DB_COMMIT_HOOK: {
2039     if( objc>3 ){
2040       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2041       return TCL_ERROR;
2042     }else if( objc==2 ){
2043       if( pDb->zCommit ){
2044         Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
2045       }
2046     }else{
2047       const char *zCommit;
2048       int len;
2049       if( pDb->zCommit ){
2050         Tcl_Free(pDb->zCommit);
2051       }
2052       zCommit = Tcl_GetStringFromObj(objv[2], &len);
2053       if( zCommit && len>0 ){
2054         pDb->zCommit = Tcl_Alloc( len + 1 );
2055         memcpy(pDb->zCommit, zCommit, len+1);
2056       }else{
2057         pDb->zCommit = 0;
2058       }
2059       if( pDb->zCommit ){
2060         pDb->interp = interp;
2061         sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
2062       }else{
2063         sqlite3_commit_hook(pDb->db, 0, 0);
2064       }
2065     }
2066     break;
2067   }
2068 
2069   /*    $db complete SQL
2070   **
2071   ** Return TRUE if SQL is a complete SQL statement.  Return FALSE if
2072   ** additional lines of input are needed.  This is similar to the
2073   ** built-in "info complete" command of Tcl.
2074   */
2075   case DB_COMPLETE: {
2076 #ifndef SQLITE_OMIT_COMPLETE
2077     Tcl_Obj *pResult;
2078     int isComplete;
2079     if( objc!=3 ){
2080       Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2081       return TCL_ERROR;
2082     }
2083     isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
2084     pResult = Tcl_GetObjResult(interp);
2085     Tcl_SetBooleanObj(pResult, isComplete);
2086 #endif
2087     break;
2088   }
2089 
2090   /*    $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2091   **
2092   ** Copy data into table from filename, optionally using SEPARATOR
2093   ** as column separators.  If a column contains a null string, or the
2094   ** value of NULLINDICATOR, a NULL is inserted for the column.
2095   ** conflict-algorithm is one of the sqlite conflict algorithms:
2096   **    rollback, abort, fail, ignore, replace
2097   ** On success, return the number of lines processed, not necessarily same
2098   ** as 'db changes' due to conflict-algorithm selected.
2099   **
2100   ** This code is basically an implementation/enhancement of
2101   ** the sqlite3 shell.c ".import" command.
2102   **
2103   ** This command usage is equivalent to the sqlite2.x COPY statement,
2104   ** which imports file data into a table using the PostgreSQL COPY file format:
2105   **   $db copy $conflit_algo $table_name $filename \t \\N
2106   */
2107   case DB_COPY: {
2108     char *zTable;               /* Insert data into this table */
2109     char *zFile;                /* The file from which to extract data */
2110     char *zConflict;            /* The conflict algorithm to use */
2111     sqlite3_stmt *pStmt;        /* A statement */
2112     int nCol;                   /* Number of columns in the table */
2113     int nByte;                  /* Number of bytes in an SQL string */
2114     int i, j;                   /* Loop counters */
2115     int nSep;                   /* Number of bytes in zSep[] */
2116     int nNull;                  /* Number of bytes in zNull[] */
2117     char *zSql;                 /* An SQL statement */
2118     char *zLine;                /* A single line of input from the file */
2119     char **azCol;               /* zLine[] broken up into columns */
2120     const char *zCommit;        /* How to commit changes */
2121     FILE *in;                   /* The input file */
2122     int lineno = 0;             /* Line number of input file */
2123     char zLineNum[80];          /* Line number print buffer */
2124     Tcl_Obj *pResult;           /* interp result */
2125 
2126     const char *zSep;
2127     const char *zNull;
2128     if( objc<5 || objc>7 ){
2129       Tcl_WrongNumArgs(interp, 2, objv,
2130          "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2131       return TCL_ERROR;
2132     }
2133     if( objc>=6 ){
2134       zSep = Tcl_GetStringFromObj(objv[5], 0);
2135     }else{
2136       zSep = "\t";
2137     }
2138     if( objc>=7 ){
2139       zNull = Tcl_GetStringFromObj(objv[6], 0);
2140     }else{
2141       zNull = "";
2142     }
2143     zConflict = Tcl_GetStringFromObj(objv[2], 0);
2144     zTable = Tcl_GetStringFromObj(objv[3], 0);
2145     zFile = Tcl_GetStringFromObj(objv[4], 0);
2146     nSep = strlen30(zSep);
2147     nNull = strlen30(zNull);
2148     if( nSep==0 ){
2149       Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2150                        (char*)0);
2151       return TCL_ERROR;
2152     }
2153     if(strcmp(zConflict, "rollback") != 0 &&
2154        strcmp(zConflict, "abort"   ) != 0 &&
2155        strcmp(zConflict, "fail"    ) != 0 &&
2156        strcmp(zConflict, "ignore"  ) != 0 &&
2157        strcmp(zConflict, "replace" ) != 0 ) {
2158       Tcl_AppendResult(interp, "Error: \"", zConflict,
2159             "\", conflict-algorithm must be one of: rollback, "
2160             "abort, fail, ignore, or replace", (char*)0);
2161       return TCL_ERROR;
2162     }
2163     zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2164     if( zSql==0 ){
2165       Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
2166       return TCL_ERROR;
2167     }
2168     nByte = strlen30(zSql);
2169     rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
2170     sqlite3_free(zSql);
2171     if( rc ){
2172       Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2173       nCol = 0;
2174     }else{
2175       nCol = sqlite3_column_count(pStmt);
2176     }
2177     sqlite3_finalize(pStmt);
2178     if( nCol==0 ) {
2179       return TCL_ERROR;
2180     }
2181     zSql = malloc( nByte + 50 + nCol*2 );
2182     if( zSql==0 ) {
2183       Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
2184       return TCL_ERROR;
2185     }
2186     sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2187          zConflict, zTable);
2188     j = strlen30(zSql);
2189     for(i=1; i<nCol; i++){
2190       zSql[j++] = ',';
2191       zSql[j++] = '?';
2192     }
2193     zSql[j++] = ')';
2194     zSql[j] = 0;
2195     rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
2196     free(zSql);
2197     if( rc ){
2198       Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2199       sqlite3_finalize(pStmt);
2200       return TCL_ERROR;
2201     }
2202     in = fopen(zFile, "rb");
2203     if( in==0 ){
2204       Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2205       sqlite3_finalize(pStmt);
2206       return TCL_ERROR;
2207     }
2208     azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2209     if( azCol==0 ) {
2210       Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
2211       fclose(in);
2212       return TCL_ERROR;
2213     }
2214     (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
2215     zCommit = "COMMIT";
2216     while( (zLine = local_getline(0, in))!=0 ){
2217       char *z;
2218       lineno++;
2219       azCol[0] = zLine;
2220       for(i=0, z=zLine; *z; z++){
2221         if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2222           *z = 0;
2223           i++;
2224           if( i<nCol ){
2225             azCol[i] = &z[nSep];
2226             z += nSep-1;
2227           }
2228         }
2229       }
2230       if( i+1!=nCol ){
2231         char *zErr;
2232         int nErr = strlen30(zFile) + 200;
2233         zErr = malloc(nErr);
2234         if( zErr ){
2235           sqlite3_snprintf(nErr, zErr,
2236              "Error: %s line %d: expected %d columns of data but found %d",
2237              zFile, lineno, nCol, i+1);
2238           Tcl_AppendResult(interp, zErr, (char*)0);
2239           free(zErr);
2240         }
2241         zCommit = "ROLLBACK";
2242         break;
2243       }
2244       for(i=0; i<nCol; i++){
2245         /* check for null data, if so, bind as null */
2246         if( (nNull>0 && strcmp(azCol[i], zNull)==0)
2247           || strlen30(azCol[i])==0
2248         ){
2249           sqlite3_bind_null(pStmt, i+1);
2250         }else{
2251           sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2252         }
2253       }
2254       sqlite3_step(pStmt);
2255       rc = sqlite3_reset(pStmt);
2256       free(zLine);
2257       if( rc!=SQLITE_OK ){
2258         Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2259         zCommit = "ROLLBACK";
2260         break;
2261       }
2262     }
2263     free(azCol);
2264     fclose(in);
2265     sqlite3_finalize(pStmt);
2266     (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
2267 
2268     if( zCommit[0] == 'C' ){
2269       /* success, set result as number of lines processed */
2270       pResult = Tcl_GetObjResult(interp);
2271       Tcl_SetIntObj(pResult, lineno);
2272       rc = TCL_OK;
2273     }else{
2274       /* failure, append lineno where failed */
2275       sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
2276       Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2277                        (char*)0);
2278       rc = TCL_ERROR;
2279     }
2280     break;
2281   }
2282 
2283   /*
2284   **    $db enable_load_extension BOOLEAN
2285   **
2286   ** Turn the extension loading feature on or off.  It if off by
2287   ** default.
2288   */
2289   case DB_ENABLE_LOAD_EXTENSION: {
2290 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2291     int onoff;
2292     if( objc!=3 ){
2293       Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2294       return TCL_ERROR;
2295     }
2296     if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2297       return TCL_ERROR;
2298     }
2299     sqlite3_enable_load_extension(pDb->db, onoff);
2300     break;
2301 #else
2302     Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2303                      (char*)0);
2304     return TCL_ERROR;
2305 #endif
2306   }
2307 
2308   /*
2309   **    $db errorcode
2310   **
2311   ** Return the numeric error code that was returned by the most recent
2312   ** call to sqlite3_exec().
2313   */
2314   case DB_ERRORCODE: {
2315     Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
2316     break;
2317   }
2318 
2319   /*
2320   **    $db exists $sql
2321   **    $db onecolumn $sql
2322   **
2323   ** The onecolumn method is the equivalent of:
2324   **     lindex [$db eval $sql] 0
2325   */
2326   case DB_EXISTS:
2327   case DB_ONECOLUMN: {
2328     DbEvalContext sEval;
2329     if( objc!=3 ){
2330       Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2331       return TCL_ERROR;
2332     }
2333 
2334     dbEvalInit(&sEval, pDb, objv[2], 0);
2335     rc = dbEvalStep(&sEval);
2336     if( choice==DB_ONECOLUMN ){
2337       if( rc==TCL_OK ){
2338         Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
2339       }else if( rc==TCL_BREAK ){
2340         Tcl_ResetResult(interp);
2341       }
2342     }else if( rc==TCL_BREAK || rc==TCL_OK ){
2343       Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
2344     }
2345     dbEvalFinalize(&sEval);
2346 
2347     if( rc==TCL_BREAK ){
2348       rc = TCL_OK;
2349     }
2350     break;
2351   }
2352 
2353   /*
2354   **    $db eval $sql ?array? ?{  ...code... }?
2355   **
2356   ** The SQL statement in $sql is evaluated.  For each row, the values are
2357   ** placed in elements of the array named "array" and ...code... is executed.
2358   ** If "array" and "code" are omitted, then no callback is every invoked.
2359   ** If "array" is an empty string, then the values are placed in variables
2360   ** that have the same name as the fields extracted by the query.
2361   */
2362   case DB_EVAL: {
2363     if( objc<3 || objc>5 ){
2364       Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2365       return TCL_ERROR;
2366     }
2367 
2368     if( objc==3 ){
2369       DbEvalContext sEval;
2370       Tcl_Obj *pRet = Tcl_NewObj();
2371       Tcl_IncrRefCount(pRet);
2372       dbEvalInit(&sEval, pDb, objv[2], 0);
2373       while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2374         int i;
2375         int nCol;
2376         dbEvalRowInfo(&sEval, &nCol, 0);
2377         for(i=0; i<nCol; i++){
2378           Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
2379         }
2380       }
2381       dbEvalFinalize(&sEval);
2382       if( rc==TCL_BREAK ){
2383         Tcl_SetObjResult(interp, pRet);
2384         rc = TCL_OK;
2385       }
2386       Tcl_DecrRefCount(pRet);
2387     }else{
2388       ClientData cd2[2];
2389       DbEvalContext *p;
2390       Tcl_Obj *pArray = 0;
2391       Tcl_Obj *pScript;
2392 
2393       if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2394         pArray = objv[3];
2395       }
2396       pScript = objv[objc-1];
2397       Tcl_IncrRefCount(pScript);
2398 
2399       p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2400       dbEvalInit(p, pDb, objv[2], pArray);
2401 
2402       cd2[0] = (void *)p;
2403       cd2[1] = (void *)pScript;
2404       rc = DbEvalNextCmd(cd2, interp, TCL_OK);
2405     }
2406     break;
2407   }
2408 
2409   /*
2410   **     $db function NAME [-argcount N] [-deterministic] SCRIPT
2411   **
2412   ** Create a new SQL function called NAME.  Whenever that function is
2413   ** called, invoke SCRIPT to evaluate the function.
2414   */
2415   case DB_FUNCTION: {
2416     int flags = SQLITE_UTF8;
2417     SqlFunc *pFunc;
2418     Tcl_Obj *pScript;
2419     char *zName;
2420     int nArg = -1;
2421     int i;
2422     if( objc<4 ){
2423       Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
2424       return TCL_ERROR;
2425     }
2426     for(i=3; i<(objc-1); i++){
2427       const char *z = Tcl_GetString(objv[i]);
2428       int n = strlen30(z);
2429       if( n>2 && strncmp(z, "-argcount",n)==0 ){
2430         if( i==(objc-2) ){
2431           Tcl_AppendResult(interp, "option requires an argument: ", z, 0);
2432           return TCL_ERROR;
2433         }
2434         if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
2435         if( nArg<0 ){
2436           Tcl_AppendResult(interp, "number of arguments must be non-negative",
2437                            (char*)0);
2438           return TCL_ERROR;
2439         }
2440         i++;
2441       }else
2442       if( n>2 && strncmp(z, "-deterministic",n)==0 ){
2443         flags |= SQLITE_DETERMINISTIC;
2444       }else{
2445         Tcl_AppendResult(interp, "bad option \"", z,
2446             "\": must be -argcount or -deterministic", 0
2447         );
2448         return TCL_ERROR;
2449       }
2450     }
2451 
2452     pScript = objv[objc-1];
2453     zName = Tcl_GetStringFromObj(objv[2], 0);
2454     pFunc = findSqlFunc(pDb, zName);
2455     if( pFunc==0 ) return TCL_ERROR;
2456     if( pFunc->pScript ){
2457       Tcl_DecrRefCount(pFunc->pScript);
2458     }
2459     pFunc->pScript = pScript;
2460     Tcl_IncrRefCount(pScript);
2461     pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
2462     rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
2463         pFunc, tclSqlFunc, 0, 0);
2464     if( rc!=SQLITE_OK ){
2465       rc = TCL_ERROR;
2466       Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
2467     }
2468     break;
2469   }
2470 
2471   /*
2472   **     $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
2473   */
2474   case DB_INCRBLOB: {
2475 #ifdef SQLITE_OMIT_INCRBLOB
2476     Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
2477     return TCL_ERROR;
2478 #else
2479     int isReadonly = 0;
2480     const char *zDb = "main";
2481     const char *zTable;
2482     const char *zColumn;
2483     Tcl_WideInt iRow;
2484 
2485     /* Check for the -readonly option */
2486     if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2487       isReadonly = 1;
2488     }
2489 
2490     if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2491       Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
2492       return TCL_ERROR;
2493     }
2494 
2495     if( objc==(6+isReadonly) ){
2496       zDb = Tcl_GetString(objv[2]);
2497     }
2498     zTable = Tcl_GetString(objv[objc-3]);
2499     zColumn = Tcl_GetString(objv[objc-2]);
2500     rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2501 
2502     if( rc==TCL_OK ){
2503       rc = createIncrblobChannel(
2504           interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
2505       );
2506     }
2507 #endif
2508     break;
2509   }
2510 
2511   /*
2512   **     $db interrupt
2513   **
2514   ** Interrupt the execution of the inner-most SQL interpreter.  This
2515   ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2516   */
2517   case DB_INTERRUPT: {
2518     sqlite3_interrupt(pDb->db);
2519     break;
2520   }
2521 
2522   /*
2523   **     $db nullvalue ?STRING?
2524   **
2525   ** Change text used when a NULL comes back from the database. If ?STRING?
2526   ** is not present, then the current string used for NULL is returned.
2527   ** If STRING is present, then STRING is returned.
2528   **
2529   */
2530   case DB_NULLVALUE: {
2531     if( objc!=2 && objc!=3 ){
2532       Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2533       return TCL_ERROR;
2534     }
2535     if( objc==3 ){
2536       int len;
2537       char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2538       if( pDb->zNull ){
2539         Tcl_Free(pDb->zNull);
2540       }
2541       if( zNull && len>0 ){
2542         pDb->zNull = Tcl_Alloc( len + 1 );
2543         memcpy(pDb->zNull, zNull, len);
2544         pDb->zNull[len] = '\0';
2545       }else{
2546         pDb->zNull = 0;
2547       }
2548     }
2549     Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
2550     break;
2551   }
2552 
2553   /*
2554   **     $db last_insert_rowid
2555   **
2556   ** Return an integer which is the ROWID for the most recent insert.
2557   */
2558   case DB_LAST_INSERT_ROWID: {
2559     Tcl_Obj *pResult;
2560     Tcl_WideInt rowid;
2561     if( objc!=2 ){
2562       Tcl_WrongNumArgs(interp, 2, objv, "");
2563       return TCL_ERROR;
2564     }
2565     rowid = sqlite3_last_insert_rowid(pDb->db);
2566     pResult = Tcl_GetObjResult(interp);
2567     Tcl_SetWideIntObj(pResult, rowid);
2568     break;
2569   }
2570 
2571   /*
2572   ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
2573   */
2574 
2575   /*    $db progress ?N CALLBACK?
2576   **
2577   ** Invoke the given callback every N virtual machine opcodes while executing
2578   ** queries.
2579   */
2580   case DB_PROGRESS: {
2581     if( objc==2 ){
2582       if( pDb->zProgress ){
2583         Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
2584       }
2585     }else if( objc==4 ){
2586       char *zProgress;
2587       int len;
2588       int N;
2589       if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
2590         return TCL_ERROR;
2591       };
2592       if( pDb->zProgress ){
2593         Tcl_Free(pDb->zProgress);
2594       }
2595       zProgress = Tcl_GetStringFromObj(objv[3], &len);
2596       if( zProgress && len>0 ){
2597         pDb->zProgress = Tcl_Alloc( len + 1 );
2598         memcpy(pDb->zProgress, zProgress, len+1);
2599       }else{
2600         pDb->zProgress = 0;
2601       }
2602 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2603       if( pDb->zProgress ){
2604         pDb->interp = interp;
2605         sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2606       }else{
2607         sqlite3_progress_handler(pDb->db, 0, 0, 0);
2608       }
2609 #endif
2610     }else{
2611       Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
2612       return TCL_ERROR;
2613     }
2614     break;
2615   }
2616 
2617   /*    $db profile ?CALLBACK?
2618   **
2619   ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2620   ** that has run.  The text of the SQL and the amount of elapse time are
2621   ** appended to CALLBACK before the script is run.
2622   */
2623   case DB_PROFILE: {
2624     if( objc>3 ){
2625       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2626       return TCL_ERROR;
2627     }else if( objc==2 ){
2628       if( pDb->zProfile ){
2629         Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
2630       }
2631     }else{
2632       char *zProfile;
2633       int len;
2634       if( pDb->zProfile ){
2635         Tcl_Free(pDb->zProfile);
2636       }
2637       zProfile = Tcl_GetStringFromObj(objv[2], &len);
2638       if( zProfile && len>0 ){
2639         pDb->zProfile = Tcl_Alloc( len + 1 );
2640         memcpy(pDb->zProfile, zProfile, len+1);
2641       }else{
2642         pDb->zProfile = 0;
2643       }
2644 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
2645       if( pDb->zProfile ){
2646         pDb->interp = interp;
2647         sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2648       }else{
2649         sqlite3_profile(pDb->db, 0, 0);
2650       }
2651 #endif
2652     }
2653     break;
2654   }
2655 
2656   /*
2657   **     $db rekey KEY
2658   **
2659   ** Change the encryption key on the currently open database.
2660   */
2661   case DB_REKEY: {
2662 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
2663     int nKey;
2664     void *pKey;
2665 #endif
2666     if( objc!=3 ){
2667       Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2668       return TCL_ERROR;
2669     }
2670 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
2671     pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
2672     rc = sqlite3_rekey(pDb->db, pKey, nKey);
2673     if( rc ){
2674       Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
2675       rc = TCL_ERROR;
2676     }
2677 #endif
2678     break;
2679   }
2680 
2681   /*    $db restore ?DATABASE? FILENAME
2682   **
2683   ** Open a database file named FILENAME.  Transfer the content
2684   ** of FILENAME into the local database DATABASE (default: "main").
2685   */
2686   case DB_RESTORE: {
2687     const char *zSrcFile;
2688     const char *zDestDb;
2689     sqlite3 *pSrc;
2690     sqlite3_backup *pBackup;
2691     int nTimeout = 0;
2692 
2693     if( objc==3 ){
2694       zDestDb = "main";
2695       zSrcFile = Tcl_GetString(objv[2]);
2696     }else if( objc==4 ){
2697       zDestDb = Tcl_GetString(objv[2]);
2698       zSrcFile = Tcl_GetString(objv[3]);
2699     }else{
2700       Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2701       return TCL_ERROR;
2702     }
2703     rc = sqlite3_open_v2(zSrcFile, &pSrc,
2704                          SQLITE_OPEN_READONLY | pDb->openFlags, 0);
2705     if( rc!=SQLITE_OK ){
2706       Tcl_AppendResult(interp, "cannot open source database: ",
2707            sqlite3_errmsg(pSrc), (char*)0);
2708       sqlite3_close(pSrc);
2709       return TCL_ERROR;
2710     }
2711     pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2712     if( pBackup==0 ){
2713       Tcl_AppendResult(interp, "restore failed: ",
2714            sqlite3_errmsg(pDb->db), (char*)0);
2715       sqlite3_close(pSrc);
2716       return TCL_ERROR;
2717     }
2718     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2719               || rc==SQLITE_BUSY ){
2720       if( rc==SQLITE_BUSY ){
2721         if( nTimeout++ >= 3 ) break;
2722         sqlite3_sleep(100);
2723       }
2724     }
2725     sqlite3_backup_finish(pBackup);
2726     if( rc==SQLITE_DONE ){
2727       rc = TCL_OK;
2728     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2729       Tcl_AppendResult(interp, "restore failed: source database busy",
2730                        (char*)0);
2731       rc = TCL_ERROR;
2732     }else{
2733       Tcl_AppendResult(interp, "restore failed: ",
2734            sqlite3_errmsg(pDb->db), (char*)0);
2735       rc = TCL_ERROR;
2736     }
2737     sqlite3_close(pSrc);
2738     break;
2739   }
2740 
2741   /*
2742   **     $db status (step|sort|autoindex)
2743   **
2744   ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2745   ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2746   */
2747   case DB_STATUS: {
2748     int v;
2749     const char *zOp;
2750     if( objc!=3 ){
2751       Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
2752       return TCL_ERROR;
2753     }
2754     zOp = Tcl_GetString(objv[2]);
2755     if( strcmp(zOp, "step")==0 ){
2756       v = pDb->nStep;
2757     }else if( strcmp(zOp, "sort")==0 ){
2758       v = pDb->nSort;
2759     }else if( strcmp(zOp, "autoindex")==0 ){
2760       v = pDb->nIndex;
2761     }else{
2762       Tcl_AppendResult(interp,
2763             "bad argument: should be autoindex, step, or sort",
2764             (char*)0);
2765       return TCL_ERROR;
2766     }
2767     Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2768     break;
2769   }
2770 
2771   /*
2772   **     $db timeout MILLESECONDS
2773   **
2774   ** Delay for the number of milliseconds specified when a file is locked.
2775   */
2776   case DB_TIMEOUT: {
2777     int ms;
2778     if( objc!=3 ){
2779       Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
2780       return TCL_ERROR;
2781     }
2782     if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
2783     sqlite3_busy_timeout(pDb->db, ms);
2784     break;
2785   }
2786 
2787   /*
2788   **     $db total_changes
2789   **
2790   ** Return the number of rows that were modified, inserted, or deleted
2791   ** since the database handle was created.
2792   */
2793   case DB_TOTAL_CHANGES: {
2794     Tcl_Obj *pResult;
2795     if( objc!=2 ){
2796       Tcl_WrongNumArgs(interp, 2, objv, "");
2797       return TCL_ERROR;
2798     }
2799     pResult = Tcl_GetObjResult(interp);
2800     Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2801     break;
2802   }
2803 
2804   /*    $db trace ?CALLBACK?
2805   **
2806   ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2807   ** that is executed.  The text of the SQL is appended to CALLBACK before
2808   ** it is executed.
2809   */
2810   case DB_TRACE: {
2811     if( objc>3 ){
2812       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2813       return TCL_ERROR;
2814     }else if( objc==2 ){
2815       if( pDb->zTrace ){
2816         Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
2817       }
2818     }else{
2819       char *zTrace;
2820       int len;
2821       if( pDb->zTrace ){
2822         Tcl_Free(pDb->zTrace);
2823       }
2824       zTrace = Tcl_GetStringFromObj(objv[2], &len);
2825       if( zTrace && len>0 ){
2826         pDb->zTrace = Tcl_Alloc( len + 1 );
2827         memcpy(pDb->zTrace, zTrace, len+1);
2828       }else{
2829         pDb->zTrace = 0;
2830       }
2831 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
2832       if( pDb->zTrace ){
2833         pDb->interp = interp;
2834         sqlite3_trace(pDb->db, DbTraceHandler, pDb);
2835       }else{
2836         sqlite3_trace(pDb->db, 0, 0);
2837       }
2838 #endif
2839     }
2840     break;
2841   }
2842 
2843   /*    $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2844   **
2845   ** Start a new transaction (if we are not already in the midst of a
2846   ** transaction) and execute the TCL script SCRIPT.  After SCRIPT
2847   ** completes, either commit the transaction or roll it back if SCRIPT
2848   ** throws an exception.  Or if no new transation was started, do nothing.
2849   ** pass the exception on up the stack.
2850   **
2851   ** This command was inspired by Dave Thomas's talk on Ruby at the
2852   ** 2005 O'Reilly Open Source Convention (OSCON).
2853   */
2854   case DB_TRANSACTION: {
2855     Tcl_Obj *pScript;
2856     const char *zBegin = "SAVEPOINT _tcl_transaction";
2857     if( objc!=3 && objc!=4 ){
2858       Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2859       return TCL_ERROR;
2860     }
2861 
2862     if( pDb->nTransaction==0 && objc==4 ){
2863       static const char *TTYPE_strs[] = {
2864         "deferred",   "exclusive",  "immediate", 0
2865       };
2866       enum TTYPE_enum {
2867         TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2868       };
2869       int ttype;
2870       if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
2871                               0, &ttype) ){
2872         return TCL_ERROR;
2873       }
2874       switch( (enum TTYPE_enum)ttype ){
2875         case TTYPE_DEFERRED:    /* no-op */;                 break;
2876         case TTYPE_EXCLUSIVE:   zBegin = "BEGIN EXCLUSIVE";  break;
2877         case TTYPE_IMMEDIATE:   zBegin = "BEGIN IMMEDIATE";  break;
2878       }
2879     }
2880     pScript = objv[objc-1];
2881 
2882     /* Run the SQLite BEGIN command to open a transaction or savepoint. */
2883     pDb->disableAuth++;
2884     rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2885     pDb->disableAuth--;
2886     if( rc!=SQLITE_OK ){
2887       Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
2888       return TCL_ERROR;
2889     }
2890     pDb->nTransaction++;
2891 
2892     /* If using NRE, schedule a callback to invoke the script pScript, then
2893     ** a second callback to commit (or rollback) the transaction or savepoint
2894     ** opened above. If not using NRE, evaluate the script directly, then
2895     ** call function DbTransPostCmd() to commit (or rollback) the transaction
2896     ** or savepoint.  */
2897     if( DbUseNre() ){
2898       Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
2899       (void)Tcl_NREvalObj(interp, pScript, 0);
2900     }else{
2901       rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
2902     }
2903     break;
2904   }
2905 
2906   /*
2907   **    $db unlock_notify ?script?
2908   */
2909   case DB_UNLOCK_NOTIFY: {
2910 #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2911     Tcl_AppendResult(interp, "unlock_notify not available in this build",
2912                      (char*)0);
2913     rc = TCL_ERROR;
2914 #else
2915     if( objc!=2 && objc!=3 ){
2916       Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2917       rc = TCL_ERROR;
2918     }else{
2919       void (*xNotify)(void **, int) = 0;
2920       void *pNotifyArg = 0;
2921 
2922       if( pDb->pUnlockNotify ){
2923         Tcl_DecrRefCount(pDb->pUnlockNotify);
2924         pDb->pUnlockNotify = 0;
2925       }
2926 
2927       if( objc==3 ){
2928         xNotify = DbUnlockNotify;
2929         pNotifyArg = (void *)pDb;
2930         pDb->pUnlockNotify = objv[2];
2931         Tcl_IncrRefCount(pDb->pUnlockNotify);
2932       }
2933 
2934       if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
2935         Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
2936         rc = TCL_ERROR;
2937       }
2938     }
2939 #endif
2940     break;
2941   }
2942 
2943   /*
2944   **    $db preupdate_hook count
2945   **    $db preupdate_hook hook ?SCRIPT?
2946   **    $db preupdate_hook new INDEX
2947   **    $db preupdate_hook old INDEX
2948   */
2949   case DB_PREUPDATE: {
2950 #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
2951     Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time");
2952     rc = TCL_ERROR;
2953 #else
2954     static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
2955     enum DbPreupdateSubCmd {
2956       PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
2957     };
2958     int iSub;
2959 
2960     if( objc<3 ){
2961       Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
2962     }
2963     if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
2964       return TCL_ERROR;
2965     }
2966 
2967     switch( (enum DbPreupdateSubCmd)iSub ){
2968       case PRE_COUNT: {
2969         int nCol = sqlite3_preupdate_count(pDb->db);
2970         Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
2971         break;
2972       }
2973 
2974       case PRE_HOOK: {
2975         if( objc>4 ){
2976           Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
2977           return TCL_ERROR;
2978         }
2979         DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
2980         break;
2981       }
2982 
2983       case PRE_DEPTH: {
2984         Tcl_Obj *pRet;
2985         if( objc!=3 ){
2986           Tcl_WrongNumArgs(interp, 3, objv, "");
2987           return TCL_ERROR;
2988         }
2989         pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
2990         Tcl_SetObjResult(interp, pRet);
2991         break;
2992       }
2993 
2994       case PRE_NEW:
2995       case PRE_OLD: {
2996         int iIdx;
2997         sqlite3_value *pValue;
2998         if( objc!=4 ){
2999           Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
3000           return TCL_ERROR;
3001         }
3002         if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
3003           return TCL_ERROR;
3004         }
3005 
3006         if( iSub==PRE_OLD ){
3007           rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
3008         }else{
3009           assert( iSub==PRE_NEW );
3010           rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
3011         }
3012 
3013         if( rc==SQLITE_OK ){
3014           Tcl_Obj *pObj;
3015           pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
3016           Tcl_SetObjResult(interp, pObj);
3017         }else{
3018           Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
3019           return TCL_ERROR;
3020         }
3021       }
3022     }
3023 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
3024     break;
3025   }
3026 
3027   /*
3028   **    $db wal_hook ?script?
3029   **    $db update_hook ?script?
3030   **    $db rollback_hook ?script?
3031   */
3032   case DB_WAL_HOOK:
3033   case DB_UPDATE_HOOK:
3034   case DB_ROLLBACK_HOOK: {
3035     /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
3036     ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3037     */
3038     Tcl_Obj **ppHook = 0;
3039     if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
3040     if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
3041     if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
3042     if( objc>3 ){
3043        Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3044        return TCL_ERROR;
3045     }
3046 
3047     DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
3048     break;
3049   }
3050 
3051   /*    $db version
3052   **
3053   ** Return the version string for this database.
3054   */
3055   case DB_VERSION: {
3056     Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
3057     break;
3058   }
3059 
3060 
3061   } /* End of the SWITCH statement */
3062   return rc;
3063 }
3064 
3065 #if SQLITE_TCL_NRE
3066 /*
3067 ** Adaptor that provides an objCmd interface to the NRE-enabled
3068 ** interface implementation.
3069 */
3070 static int DbObjCmdAdaptor(
3071   void *cd,
3072   Tcl_Interp *interp,
3073   int objc,
3074   Tcl_Obj *const*objv
3075 ){
3076   return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
3077 }
3078 #endif /* SQLITE_TCL_NRE */
3079 
3080 /*
3081 **   sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
3082 **                           ?-create BOOLEAN? ?-nomutex BOOLEAN?
3083 **
3084 ** This is the main Tcl command.  When the "sqlite" Tcl command is
3085 ** invoked, this routine runs to process that command.
3086 **
3087 ** The first argument, DBNAME, is an arbitrary name for a new
3088 ** database connection.  This command creates a new command named
3089 ** DBNAME that is used to control that connection.  The database
3090 ** connection is deleted when the DBNAME command is deleted.
3091 **
3092 ** The second argument is the name of the database file.
3093 **
3094 */
3095 static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
3096   SqliteDb *p;
3097   const char *zArg;
3098   char *zErrMsg;
3099   int i;
3100   const char *zFile;
3101   const char *zVfs = 0;
3102   int flags;
3103   Tcl_DString translatedFilename;
3104 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3105   void *pKey = 0;
3106   int nKey = 0;
3107 #endif
3108   int rc;
3109 
3110   /* In normal use, each TCL interpreter runs in a single thread.  So
3111   ** by default, we can turn of mutexing on SQLite database connections.
3112   ** However, for testing purposes it is useful to have mutexes turned
3113   ** on.  So, by default, mutexes default off.  But if compiled with
3114   ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3115   */
3116 #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3117   flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3118 #else
3119   flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3120 #endif
3121 
3122   if( objc==2 ){
3123     zArg = Tcl_GetStringFromObj(objv[1], 0);
3124     if( strcmp(zArg,"-version")==0 ){
3125       Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
3126       return TCL_OK;
3127     }
3128     if( strcmp(zArg,"-sourceid")==0 ){
3129       Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0);
3130       return TCL_OK;
3131     }
3132     if( strcmp(zArg,"-has-codec")==0 ){
3133 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3134       Tcl_AppendResult(interp,"1",(char*)0);
3135 #else
3136       Tcl_AppendResult(interp,"0",(char*)0);
3137 #endif
3138       return TCL_OK;
3139     }
3140   }
3141   for(i=3; i+1<objc; i+=2){
3142     zArg = Tcl_GetString(objv[i]);
3143     if( strcmp(zArg,"-key")==0 ){
3144 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3145       pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
3146 #endif
3147     }else if( strcmp(zArg, "-vfs")==0 ){
3148       zVfs = Tcl_GetString(objv[i+1]);
3149     }else if( strcmp(zArg, "-readonly")==0 ){
3150       int b;
3151       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3152       if( b ){
3153         flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
3154         flags |= SQLITE_OPEN_READONLY;
3155       }else{
3156         flags &= ~SQLITE_OPEN_READONLY;
3157         flags |= SQLITE_OPEN_READWRITE;
3158       }
3159     }else if( strcmp(zArg, "-create")==0 ){
3160       int b;
3161       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3162       if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
3163         flags |= SQLITE_OPEN_CREATE;
3164       }else{
3165         flags &= ~SQLITE_OPEN_CREATE;
3166       }
3167     }else if( strcmp(zArg, "-nomutex")==0 ){
3168       int b;
3169       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3170       if( b ){
3171         flags |= SQLITE_OPEN_NOMUTEX;
3172         flags &= ~SQLITE_OPEN_FULLMUTEX;
3173       }else{
3174         flags &= ~SQLITE_OPEN_NOMUTEX;
3175       }
3176     }else if( strcmp(zArg, "-fullmutex")==0 ){
3177       int b;
3178       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3179       if( b ){
3180         flags |= SQLITE_OPEN_FULLMUTEX;
3181         flags &= ~SQLITE_OPEN_NOMUTEX;
3182       }else{
3183         flags &= ~SQLITE_OPEN_FULLMUTEX;
3184       }
3185     }else if( strcmp(zArg, "-uri")==0 ){
3186       int b;
3187       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3188       if( b ){
3189         flags |= SQLITE_OPEN_URI;
3190       }else{
3191         flags &= ~SQLITE_OPEN_URI;
3192       }
3193     }else{
3194       Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3195       return TCL_ERROR;
3196     }
3197   }
3198   if( objc<3 || (objc&1)!=1 ){
3199     Tcl_WrongNumArgs(interp, 1, objv,
3200       "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
3201       " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
3202 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3203       " ?-key CODECKEY?"
3204 #endif
3205     );
3206     return TCL_ERROR;
3207   }
3208   zErrMsg = 0;
3209   p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
3210   if( p==0 ){
3211     Tcl_SetResult(interp, (char *)"malloc failed", TCL_STATIC);
3212     return TCL_ERROR;
3213   }
3214   memset(p, 0, sizeof(*p));
3215   zFile = Tcl_GetStringFromObj(objv[2], 0);
3216   zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
3217   rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
3218   Tcl_DStringFree(&translatedFilename);
3219   if( p->db ){
3220     if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3221       zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3222       sqlite3_close(p->db);
3223       p->db = 0;
3224     }
3225   }else{
3226     zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
3227   }
3228 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3229   if( p->db ){
3230     sqlite3_key(p->db, pKey, nKey);
3231   }
3232 #endif
3233   if( p->db==0 ){
3234     Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
3235     Tcl_Free((char*)p);
3236     sqlite3_free(zErrMsg);
3237     return TCL_ERROR;
3238   }
3239   p->maxStmt = NUM_PREPARED_STMTS;
3240   p->openFlags = flags & SQLITE_OPEN_URI;
3241   p->interp = interp;
3242   zArg = Tcl_GetStringFromObj(objv[1], 0);
3243   if( DbUseNre() ){
3244     Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3245                         (char*)p, DbDeleteCmd);
3246   }else{
3247     Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3248   }
3249   return TCL_OK;
3250 }
3251 
3252 /*
3253 ** Provide a dummy Tcl_InitStubs if we are using this as a static
3254 ** library.
3255 */
3256 #ifndef USE_TCL_STUBS
3257 # undef  Tcl_InitStubs
3258 # define Tcl_InitStubs(a,b,c) TCL_VERSION
3259 #endif
3260 
3261 /*
3262 ** Make sure we have a PACKAGE_VERSION macro defined.  This will be
3263 ** defined automatically by the TEA makefile.  But other makefiles
3264 ** do not define it.
3265 */
3266 #ifndef PACKAGE_VERSION
3267 # define PACKAGE_VERSION SQLITE_VERSION
3268 #endif
3269 
3270 /*
3271 ** Initialize this module.
3272 **
3273 ** This Tcl module contains only a single new Tcl command named "sqlite".
3274 ** (Hence there is no namespace.  There is no point in using a namespace
3275 ** if the extension only supplies one new name!)  The "sqlite" command is
3276 ** used to open a new SQLite database.  See the DbMain() routine above
3277 ** for additional information.
3278 **
3279 ** The EXTERN macros are required by TCL in order to work on windows.
3280 */
3281 EXTERN int Sqlite3_Init(Tcl_Interp *interp){
3282   int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
3283   if( rc==TCL_OK ){
3284     Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
3285 #ifndef SQLITE_3_SUFFIX_ONLY
3286     /* The "sqlite" alias is undocumented.  It is here only to support
3287     ** legacy scripts.  All new scripts should use only the "sqlite3"
3288     ** command. */
3289     Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
3290 #endif
3291     rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3292   }
3293   return rc;
3294 }
3295 EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3296 EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3297 EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3298 
3299 /* Because it accesses the file-system and uses persistent state, SQLite
3300 ** is not considered appropriate for safe interpreters.  Hence, we cause
3301 ** the _SafeInit() interfaces return TCL_ERROR.
3302 */
3303 EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
3304 EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
3305 
3306 
3307 
3308 #ifndef SQLITE_3_SUFFIX_ONLY
3309 int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3310 int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3311 int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3312 int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3313 #endif
3314 
3315 #ifdef TCLSH
3316 /*****************************************************************************
3317 ** All of the code that follows is used to build standalone TCL interpreters
3318 ** that are statically linked with SQLite.  Enable these by compiling
3319 ** with -DTCLSH=n where n can be 1 or 2.  An n of 1 generates a standard
3320 ** tclsh but with SQLite built in.  An n of 2 generates the SQLite space
3321 ** analysis program.
3322 */
3323 
3324 #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3325 /*
3326  * This code implements the MD5 message-digest algorithm.
3327  * The algorithm is due to Ron Rivest.  This code was
3328  * written by Colin Plumb in 1993, no copyright is claimed.
3329  * This code is in the public domain; do with it what you wish.
3330  *
3331  * Equivalent code is available from RSA Data Security, Inc.
3332  * This code has been tested against that, and is equivalent,
3333  * except that you don't need to include two pages of legalese
3334  * with every copy.
3335  *
3336  * To compute the message digest of a chunk of bytes, declare an
3337  * MD5Context structure, pass it to MD5Init, call MD5Update as
3338  * needed on buffers full of bytes, and then call MD5Final, which
3339  * will fill a supplied 16-byte array with the digest.
3340  */
3341 
3342 /*
3343  * If compiled on a machine that doesn't have a 32-bit integer,
3344  * you just set "uint32" to the appropriate datatype for an
3345  * unsigned 32-bit integer.  For example:
3346  *
3347  *       cc -Duint32='unsigned long' md5.c
3348  *
3349  */
3350 #ifndef uint32
3351 #  define uint32 unsigned int
3352 #endif
3353 
3354 struct MD5Context {
3355   int isInit;
3356   uint32 buf[4];
3357   uint32 bits[2];
3358   unsigned char in[64];
3359 };
3360 typedef struct MD5Context MD5Context;
3361 
3362 /*
3363  * Note: this code is harmless on little-endian machines.
3364  */
3365 static void byteReverse (unsigned char *buf, unsigned longs){
3366         uint32 t;
3367         do {
3368                 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3369                             ((unsigned)buf[1]<<8 | buf[0]);
3370                 *(uint32 *)buf = t;
3371                 buf += 4;
3372         } while (--longs);
3373 }
3374 /* The four core functions - F1 is optimized somewhat */
3375 
3376 /* #define F1(x, y, z) (x & y | ~x & z) */
3377 #define F1(x, y, z) (z ^ (x & (y ^ z)))
3378 #define F2(x, y, z) F1(z, x, y)
3379 #define F3(x, y, z) (x ^ y ^ z)
3380 #define F4(x, y, z) (y ^ (x | ~z))
3381 
3382 /* This is the central step in the MD5 algorithm. */
3383 #define MD5STEP(f, w, x, y, z, data, s) \
3384         ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
3385 
3386 /*
3387  * The core of the MD5 algorithm, this alters an existing MD5 hash to
3388  * reflect the addition of 16 longwords of new data.  MD5Update blocks
3389  * the data and converts bytes into longwords for this routine.
3390  */
3391 static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3392         register uint32 a, b, c, d;
3393 
3394         a = buf[0];
3395         b = buf[1];
3396         c = buf[2];
3397         d = buf[3];
3398 
3399         MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478,  7);
3400         MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3401         MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3402         MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3403         MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf,  7);
3404         MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3405         MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3406         MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3407         MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8,  7);
3408         MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3409         MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3410         MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3411         MD5STEP(F1, a, b, c, d, in[12]+0x6b901122,  7);
3412         MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3413         MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3414         MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3415 
3416         MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562,  5);
3417         MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340,  9);
3418         MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3419         MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3420         MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d,  5);
3421         MD5STEP(F2, d, a, b, c, in[10]+0x02441453,  9);
3422         MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3423         MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3424         MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6,  5);
3425         MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6,  9);
3426         MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3427         MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3428         MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905,  5);
3429         MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8,  9);
3430         MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3431         MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3432 
3433         MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942,  4);
3434         MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3435         MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3436         MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3437         MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44,  4);
3438         MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3439         MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3440         MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3441         MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6,  4);
3442         MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3443         MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3444         MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3445         MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039,  4);
3446         MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3447         MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3448         MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3449 
3450         MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244,  6);
3451         MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3452         MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3453         MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3454         MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3,  6);
3455         MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3456         MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3457         MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3458         MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f,  6);
3459         MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3460         MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3461         MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3462         MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82,  6);
3463         MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3464         MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3465         MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3466 
3467         buf[0] += a;
3468         buf[1] += b;
3469         buf[2] += c;
3470         buf[3] += d;
3471 }
3472 
3473 /*
3474  * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
3475  * initialization constants.
3476  */
3477 static void MD5Init(MD5Context *ctx){
3478         ctx->isInit = 1;
3479         ctx->buf[0] = 0x67452301;
3480         ctx->buf[1] = 0xefcdab89;
3481         ctx->buf[2] = 0x98badcfe;
3482         ctx->buf[3] = 0x10325476;
3483         ctx->bits[0] = 0;
3484         ctx->bits[1] = 0;
3485 }
3486 
3487 /*
3488  * Update context to reflect the concatenation of another buffer full
3489  * of bytes.
3490  */
3491 static
3492 void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3493         uint32 t;
3494 
3495         /* Update bitcount */
3496 
3497         t = ctx->bits[0];
3498         if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3499                 ctx->bits[1]++; /* Carry from low to high */
3500         ctx->bits[1] += len >> 29;
3501 
3502         t = (t >> 3) & 0x3f;    /* Bytes already in shsInfo->data */
3503 
3504         /* Handle any leading odd-sized chunks */
3505 
3506         if ( t ) {
3507                 unsigned char *p = (unsigned char *)ctx->in + t;
3508 
3509                 t = 64-t;
3510                 if (len < t) {
3511                         memcpy(p, buf, len);
3512                         return;
3513                 }
3514                 memcpy(p, buf, t);
3515                 byteReverse(ctx->in, 16);
3516                 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3517                 buf += t;
3518                 len -= t;
3519         }
3520 
3521         /* Process data in 64-byte chunks */
3522 
3523         while (len >= 64) {
3524                 memcpy(ctx->in, buf, 64);
3525                 byteReverse(ctx->in, 16);
3526                 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3527                 buf += 64;
3528                 len -= 64;
3529         }
3530 
3531         /* Handle any remaining bytes of data. */
3532 
3533         memcpy(ctx->in, buf, len);
3534 }
3535 
3536 /*
3537  * Final wrapup - pad to 64-byte boundary with the bit pattern
3538  * 1 0* (64-bit count of bits processed, MSB-first)
3539  */
3540 static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3541         unsigned count;
3542         unsigned char *p;
3543 
3544         /* Compute number of bytes mod 64 */
3545         count = (ctx->bits[0] >> 3) & 0x3F;
3546 
3547         /* Set the first char of padding to 0x80.  This is safe since there is
3548            always at least one byte free */
3549         p = ctx->in + count;
3550         *p++ = 0x80;
3551 
3552         /* Bytes of padding needed to make 64 bytes */
3553         count = 64 - 1 - count;
3554 
3555         /* Pad out to 56 mod 64 */
3556         if (count < 8) {
3557                 /* Two lots of padding:  Pad the first block to 64 bytes */
3558                 memset(p, 0, count);
3559                 byteReverse(ctx->in, 16);
3560                 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3561 
3562                 /* Now fill the next block with 56 bytes */
3563                 memset(ctx->in, 0, 56);
3564         } else {
3565                 /* Pad block to 56 bytes */
3566                 memset(p, 0, count-8);
3567         }
3568         byteReverse(ctx->in, 14);
3569 
3570         /* Append length in bits and transform */
3571         memcpy(ctx->in + 14*4, ctx->bits, 8);
3572 
3573         MD5Transform(ctx->buf, (uint32 *)ctx->in);
3574         byteReverse((unsigned char *)ctx->buf, 4);
3575         memcpy(digest, ctx->buf, 16);
3576 }
3577 
3578 /*
3579 ** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3580 */
3581 static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3582   static char const zEncode[] = "0123456789abcdef";
3583   int i, j;
3584 
3585   for(j=i=0; i<16; i++){
3586     int a = digest[i];
3587     zBuf[j++] = zEncode[(a>>4)&0xf];
3588     zBuf[j++] = zEncode[a & 0xf];
3589   }
3590   zBuf[j] = 0;
3591 }
3592 
3593 
3594 /*
3595 ** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3596 ** each representing 16 bits of the digest and separated from each
3597 ** other by a "-" character.
3598 */
3599 static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3600   int i, j;
3601   unsigned int x;
3602   for(i=j=0; i<16; i+=2){
3603     x = digest[i]*256 + digest[i+1];
3604     if( i>0 ) zDigest[j++] = '-';
3605     sqlite3_snprintf(50-j, &zDigest[j], "%05u", x);
3606     j += 5;
3607   }
3608   zDigest[j] = 0;
3609 }
3610 
3611 /*
3612 ** A TCL command for md5.  The argument is the text to be hashed.  The
3613 ** Result is the hash in base64.
3614 */
3615 static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3616   MD5Context ctx;
3617   unsigned char digest[16];
3618   char zBuf[50];
3619   void (*converter)(unsigned char*, char*);
3620 
3621   if( argc!=2 ){
3622     Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3623         " TEXT\"", (char*)0);
3624     return TCL_ERROR;
3625   }
3626   MD5Init(&ctx);
3627   MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3628   MD5Final(digest, &ctx);
3629   converter = (void(*)(unsigned char*,char*))cd;
3630   converter(digest, zBuf);
3631   Tcl_AppendResult(interp, zBuf, (char*)0);
3632   return TCL_OK;
3633 }
3634 
3635 /*
3636 ** A TCL command to take the md5 hash of a file.  The argument is the
3637 ** name of the file.
3638 */
3639 static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3640   FILE *in;
3641   MD5Context ctx;
3642   void (*converter)(unsigned char*, char*);
3643   unsigned char digest[16];
3644   char zBuf[10240];
3645 
3646   if( argc!=2 ){
3647     Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3648         " FILENAME\"", (char*)0);
3649     return TCL_ERROR;
3650   }
3651   in = fopen(argv[1],"rb");
3652   if( in==0 ){
3653     Tcl_AppendResult(interp,"unable to open file \"", argv[1],
3654          "\" for reading", (char*)0);
3655     return TCL_ERROR;
3656   }
3657   MD5Init(&ctx);
3658   for(;;){
3659     int n;
3660     n = (int)fread(zBuf, 1, sizeof(zBuf), in);
3661     if( n<=0 ) break;
3662     MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3663   }
3664   fclose(in);
3665   MD5Final(digest, &ctx);
3666   converter = (void(*)(unsigned char*,char*))cd;
3667   converter(digest, zBuf);
3668   Tcl_AppendResult(interp, zBuf, (char*)0);
3669   return TCL_OK;
3670 }
3671 
3672 /*
3673 ** Register the four new TCL commands for generating MD5 checksums
3674 ** with the TCL interpreter.
3675 */
3676 int Md5_Init(Tcl_Interp *interp){
3677   Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3678                     MD5DigestToBase16, 0);
3679   Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3680                     MD5DigestToBase10x8, 0);
3681   Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3682                     MD5DigestToBase16, 0);
3683   Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3684                     MD5DigestToBase10x8, 0);
3685   return TCL_OK;
3686 }
3687 #endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3688 
3689 #if defined(SQLITE_TEST)
3690 /*
3691 ** During testing, the special md5sum() aggregate function is available.
3692 ** inside SQLite.  The following routines implement that function.
3693 */
3694 static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3695   MD5Context *p;
3696   int i;
3697   if( argc<1 ) return;
3698   p = sqlite3_aggregate_context(context, sizeof(*p));
3699   if( p==0 ) return;
3700   if( !p->isInit ){
3701     MD5Init(p);
3702   }
3703   for(i=0; i<argc; i++){
3704     const char *zData = (char*)sqlite3_value_text(argv[i]);
3705     if( zData ){
3706       MD5Update(p, (unsigned char*)zData, (int)strlen(zData));
3707     }
3708   }
3709 }
3710 static void md5finalize(sqlite3_context *context){
3711   MD5Context *p;
3712   unsigned char digest[16];
3713   char zBuf[33];
3714   p = sqlite3_aggregate_context(context, sizeof(*p));
3715   MD5Final(digest,p);
3716   MD5DigestToBase16(digest, zBuf);
3717   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3718 }
3719 int Md5_Register(sqlite3 *db){
3720   int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
3721                                  md5step, md5finalize);
3722   sqlite3_overload_function(db, "md5sum", -1);  /* To exercise this API */
3723   return rc;
3724 }
3725 #endif /* defined(SQLITE_TEST) */
3726 
3727 
3728 /*
3729 ** If the macro TCLSH is one, then put in code this for the
3730 ** "main" routine that will initialize Tcl and take input from
3731 ** standard input, or if a file is named on the command line
3732 ** the TCL interpreter reads and evaluates that file.
3733 */
3734 #if TCLSH==1
3735 static const char *tclsh_main_loop(void){
3736   static const char zMainloop[] =
3737     "set line {}\n"
3738     "while {![eof stdin]} {\n"
3739       "if {$line!=\"\"} {\n"
3740         "puts -nonewline \"> \"\n"
3741       "} else {\n"
3742         "puts -nonewline \"% \"\n"
3743       "}\n"
3744       "flush stdout\n"
3745       "append line [gets stdin]\n"
3746       "if {[info complete $line]} {\n"
3747         "if {[catch {uplevel #0 $line} result]} {\n"
3748           "puts stderr \"Error: $result\"\n"
3749         "} elseif {$result!=\"\"} {\n"
3750           "puts $result\n"
3751         "}\n"
3752         "set line {}\n"
3753       "} else {\n"
3754         "append line \\n\n"
3755       "}\n"
3756     "}\n"
3757   ;
3758   return zMainloop;
3759 }
3760 #endif
3761 #if TCLSH==2
3762 static const char *tclsh_main_loop(void);
3763 #endif
3764 
3765 #ifdef SQLITE_TEST
3766 static void init_all(Tcl_Interp *);
3767 static int init_all_cmd(
3768   ClientData cd,
3769   Tcl_Interp *interp,
3770   int objc,
3771   Tcl_Obj *CONST objv[]
3772 ){
3773 
3774   Tcl_Interp *slave;
3775   if( objc!=2 ){
3776     Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3777     return TCL_ERROR;
3778   }
3779 
3780   slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3781   if( !slave ){
3782     return TCL_ERROR;
3783   }
3784 
3785   init_all(slave);
3786   return TCL_OK;
3787 }
3788 
3789 /*
3790 ** Tclcmd: db_use_legacy_prepare DB BOOLEAN
3791 **
3792 **   The first argument to this command must be a database command created by
3793 **   [sqlite3]. If the second argument is true, then the handle is configured
3794 **   to use the sqlite3_prepare_v2() function to prepare statements. If it
3795 **   is false, sqlite3_prepare().
3796 */
3797 static int db_use_legacy_prepare_cmd(
3798   ClientData cd,
3799   Tcl_Interp *interp,
3800   int objc,
3801   Tcl_Obj *CONST objv[]
3802 ){
3803   Tcl_CmdInfo cmdInfo;
3804   SqliteDb *pDb;
3805   int bPrepare;
3806 
3807   if( objc!=3 ){
3808     Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
3809     return TCL_ERROR;
3810   }
3811 
3812   if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3813     Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3814     return TCL_ERROR;
3815   }
3816   pDb = (SqliteDb*)cmdInfo.objClientData;
3817   if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
3818     return TCL_ERROR;
3819   }
3820 
3821   pDb->bLegacyPrepare = bPrepare;
3822 
3823   Tcl_ResetResult(interp);
3824   return TCL_OK;
3825 }
3826 
3827 /*
3828 ** Tclcmd: db_last_stmt_ptr DB
3829 **
3830 **   If the statement cache associated with database DB is not empty,
3831 **   return the text representation of the most recently used statement
3832 **   handle.
3833 */
3834 static int db_last_stmt_ptr(
3835   ClientData cd,
3836   Tcl_Interp *interp,
3837   int objc,
3838   Tcl_Obj *CONST objv[]
3839 ){
3840   extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
3841   Tcl_CmdInfo cmdInfo;
3842   SqliteDb *pDb;
3843   sqlite3_stmt *pStmt = 0;
3844   char zBuf[100];
3845 
3846   if( objc!=2 ){
3847     Tcl_WrongNumArgs(interp, 1, objv, "DB");
3848     return TCL_ERROR;
3849   }
3850 
3851   if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3852     Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3853     return TCL_ERROR;
3854   }
3855   pDb = (SqliteDb*)cmdInfo.objClientData;
3856 
3857   if( pDb->stmtList ) pStmt = pDb->stmtList->pStmt;
3858   if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ){
3859     return TCL_ERROR;
3860   }
3861   Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
3862 
3863   return TCL_OK;
3864 }
3865 #endif /* SQLITE_TEST */
3866 
3867 /*
3868 ** Configure the interpreter passed as the first argument to have access
3869 ** to the commands and linked variables that make up:
3870 **
3871 **   * the [sqlite3] extension itself,
3872 **
3873 **   * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
3874 **
3875 **   * If SQLITE_TEST is set, the various test interfaces used by the Tcl
3876 **     test suite.
3877 */
3878 static void init_all(Tcl_Interp *interp){
3879   Sqlite3_Init(interp);
3880 
3881 #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3882   Md5_Init(interp);
3883 #endif
3884 
3885 #ifdef SQLITE_TEST
3886   {
3887     extern int Sqliteconfig_Init(Tcl_Interp*);
3888     extern int Sqlitetest1_Init(Tcl_Interp*);
3889     extern int Sqlitetest2_Init(Tcl_Interp*);
3890     extern int Sqlitetest3_Init(Tcl_Interp*);
3891     extern int Sqlitetest4_Init(Tcl_Interp*);
3892     extern int Sqlitetest5_Init(Tcl_Interp*);
3893     extern int Sqlitetest6_Init(Tcl_Interp*);
3894     extern int Sqlitetest7_Init(Tcl_Interp*);
3895     extern int Sqlitetest8_Init(Tcl_Interp*);
3896     extern int Sqlitetest9_Init(Tcl_Interp*);
3897     extern int Sqlitetestasync_Init(Tcl_Interp*);
3898     extern int Sqlitetest_autoext_Init(Tcl_Interp*);
3899     extern int Sqlitetest_blob_Init(Tcl_Interp*);
3900     extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
3901     extern int Sqlitetest_func_Init(Tcl_Interp*);
3902     extern int Sqlitetest_hexio_Init(Tcl_Interp*);
3903     extern int Sqlitetest_init_Init(Tcl_Interp*);
3904     extern int Sqlitetest_malloc_Init(Tcl_Interp*);
3905     extern int Sqlitetest_mutex_Init(Tcl_Interp*);
3906     extern int Sqlitetestschema_Init(Tcl_Interp*);
3907     extern int Sqlitetestsse_Init(Tcl_Interp*);
3908     extern int Sqlitetesttclvar_Init(Tcl_Interp*);
3909     extern int Sqlitetestfs_Init(Tcl_Interp*);
3910     extern int SqlitetestThread_Init(Tcl_Interp*);
3911     extern int SqlitetestOnefile_Init();
3912     extern int SqlitetestOsinst_Init(Tcl_Interp*);
3913     extern int Sqlitetestbackup_Init(Tcl_Interp*);
3914     extern int Sqlitetestintarray_Init(Tcl_Interp*);
3915     extern int Sqlitetestvfs_Init(Tcl_Interp *);
3916     extern int Sqlitetestrtree_Init(Tcl_Interp*);
3917     extern int Sqlitequota_Init(Tcl_Interp*);
3918     extern int Sqlitemultiplex_Init(Tcl_Interp*);
3919     extern int SqliteSuperlock_Init(Tcl_Interp*);
3920     extern int SqlitetestSyscall_Init(Tcl_Interp*);
3921 #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
3922     extern int TestSession_Init(Tcl_Interp*);
3923 #endif
3924     extern int Fts5tcl_Init(Tcl_Interp *);
3925     extern int SqliteRbu_Init(Tcl_Interp*);
3926     extern int Sqlitetesttcl_Init(Tcl_Interp*);
3927 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
3928     extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
3929 #endif
3930 
3931 #ifdef SQLITE_ENABLE_ZIPVFS
3932     extern int Zipvfs_Init(Tcl_Interp*);
3933     Zipvfs_Init(interp);
3934 #endif
3935 
3936     Sqliteconfig_Init(interp);
3937     Sqlitetest1_Init(interp);
3938     Sqlitetest2_Init(interp);
3939     Sqlitetest3_Init(interp);
3940     Sqlitetest4_Init(interp);
3941     Sqlitetest5_Init(interp);
3942     Sqlitetest6_Init(interp);
3943     Sqlitetest7_Init(interp);
3944     Sqlitetest8_Init(interp);
3945     Sqlitetest9_Init(interp);
3946     Sqlitetestasync_Init(interp);
3947     Sqlitetest_autoext_Init(interp);
3948     Sqlitetest_blob_Init(interp);
3949     Sqlitetest_demovfs_Init(interp);
3950     Sqlitetest_func_Init(interp);
3951     Sqlitetest_hexio_Init(interp);
3952     Sqlitetest_init_Init(interp);
3953     Sqlitetest_malloc_Init(interp);
3954     Sqlitetest_mutex_Init(interp);
3955     Sqlitetestschema_Init(interp);
3956     Sqlitetesttclvar_Init(interp);
3957     Sqlitetestfs_Init(interp);
3958     SqlitetestThread_Init(interp);
3959     SqlitetestOnefile_Init(interp);
3960     SqlitetestOsinst_Init(interp);
3961     Sqlitetestbackup_Init(interp);
3962     Sqlitetestintarray_Init(interp);
3963     Sqlitetestvfs_Init(interp);
3964     Sqlitetestrtree_Init(interp);
3965     Sqlitequota_Init(interp);
3966     Sqlitemultiplex_Init(interp);
3967     SqliteSuperlock_Init(interp);
3968     SqlitetestSyscall_Init(interp);
3969 #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
3970     TestSession_Init(interp);
3971 #endif
3972     Fts5tcl_Init(interp);
3973     SqliteRbu_Init(interp);
3974     Sqlitetesttcl_Init(interp);
3975 
3976 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
3977     Sqlitetestfts3_Init(interp);
3978 #endif
3979 
3980     Tcl_CreateObjCommand(
3981         interp, "load_testfixture_extensions", init_all_cmd, 0, 0
3982     );
3983     Tcl_CreateObjCommand(
3984         interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
3985     );
3986     Tcl_CreateObjCommand(
3987         interp, "db_last_stmt_ptr", db_last_stmt_ptr, 0, 0
3988     );
3989 
3990 #ifdef SQLITE_SSE
3991     Sqlitetestsse_Init(interp);
3992 #endif
3993   }
3994 #endif
3995 }
3996 
3997 /* Needed for the setrlimit() system call on unix */
3998 #if defined(unix)
3999 #include <sys/resource.h>
4000 #endif
4001 
4002 #define TCLSH_MAIN main   /* Needed to fake out mktclapp */
4003 int TCLSH_MAIN(int argc, char **argv){
4004   Tcl_Interp *interp;
4005 
4006 #if !defined(_WIN32_WCE)
4007   if( getenv("BREAK") ){
4008     fprintf(stderr,
4009         "attach debugger to process %d and press any key to continue.\n",
4010         GETPID());
4011     fgetc(stdin);
4012   }
4013 #endif
4014 
4015   /* Since the primary use case for this binary is testing of SQLite,
4016   ** be sure to generate core files if we crash */
4017 #if defined(SQLITE_TEST) && defined(unix)
4018   { struct rlimit x;
4019     getrlimit(RLIMIT_CORE, &x);
4020     x.rlim_cur = x.rlim_max;
4021     setrlimit(RLIMIT_CORE, &x);
4022   }
4023 #endif /* SQLITE_TEST && unix */
4024 
4025 
4026   /* Call sqlite3_shutdown() once before doing anything else. This is to
4027   ** test that sqlite3_shutdown() can be safely called by a process before
4028   ** sqlite3_initialize() is. */
4029   sqlite3_shutdown();
4030 
4031   Tcl_FindExecutable(argv[0]);
4032   Tcl_SetSystemEncoding(NULL, "utf-8");
4033   interp = Tcl_CreateInterp();
4034 
4035 #if TCLSH==2
4036   sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
4037 #endif
4038 
4039   init_all(interp);
4040   if( argc>=2 ){
4041     int i;
4042     char zArgc[32];
4043     sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
4044     Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
4045     Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
4046     Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
4047     for(i=3-TCLSH; i<argc; i++){
4048       Tcl_SetVar(interp, "argv", argv[i],
4049           TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
4050     }
4051     if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
4052       const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
4053       if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
4054       fprintf(stderr,"%s: %s\n", *argv, zInfo);
4055       return 1;
4056     }
4057   }
4058   if( TCLSH==2 || argc<=1 ){
4059     Tcl_GlobalEval(interp, tclsh_main_loop());
4060   }
4061   return 0;
4062 }
4063 #endif /* TCLSH */
4064