OSDN Git Service

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