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