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