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