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