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