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