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