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