xref: /sqlite-3.40.0/src/tclsqlite.c (revision 9f8a4b43)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** A TCL Interface to SQLite.  Append this file to sqlite3.c and
13 ** compile the whole thing to build a TCL-enabled version of SQLite.
14 **
15 ** $Id: tclsqlite.c,v 1.193 2007/06/26 22:55:38 drh Exp $
16 */
17 #include "tcl.h"
18 #include <errno.h>
19 
20 /*
21 ** Some additional include files are needed if this file is not
22 ** appended to the amalgamation.
23 */
24 #ifndef SQLITE_AMALGAMATION
25 # include "sqliteInt.h"
26 # include "hash.h"
27 # include <stdlib.h>
28 # include <string.h>
29 # include <assert.h>
30 # include <ctype.h>
31 #endif
32 
33 /*
34  * Windows needs to know which symbols to export.  Unix does not.
35  * BUILD_sqlite should be undefined for Unix.
36  */
37 #ifdef BUILD_sqlite
38 #undef TCL_STORAGE_CLASS
39 #define TCL_STORAGE_CLASS DLLEXPORT
40 #endif /* BUILD_sqlite */
41 
42 #define NUM_PREPARED_STMTS 10
43 #define MAX_PREPARED_STMTS 100
44 
45 /*
46 ** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
47 ** have to do a translation when going between the two.  Set the
48 ** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
49 ** this translation.
50 */
51 #if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
52 # define UTF_TRANSLATION_NEEDED 1
53 #endif
54 
55 /*
56 ** New SQL functions can be created as TCL scripts.  Each such function
57 ** is described by an instance of the following structure.
58 */
59 typedef struct SqlFunc SqlFunc;
60 struct SqlFunc {
61   Tcl_Interp *interp;   /* The TCL interpret to execute the function */
62   Tcl_Obj *pScript;     /* The Tcl_Obj representation of the script */
63   int useEvalObjv;      /* True if it is safe to use Tcl_EvalObjv */
64   char *zName;          /* Name of this function */
65   SqlFunc *pNext;       /* Next function on the list of them all */
66 };
67 
68 /*
69 ** New collation sequences function can be created as TCL scripts.  Each such
70 ** function is described by an instance of the following structure.
71 */
72 typedef struct SqlCollate SqlCollate;
73 struct SqlCollate {
74   Tcl_Interp *interp;   /* The TCL interpret to execute the function */
75   char *zScript;        /* The script to be run */
76   SqlCollate *pNext;    /* Next function on the list of them all */
77 };
78 
79 /*
80 ** Prepared statements are cached for faster execution.  Each prepared
81 ** statement is described by an instance of the following structure.
82 */
83 typedef struct SqlPreparedStmt SqlPreparedStmt;
84 struct SqlPreparedStmt {
85   SqlPreparedStmt *pNext;  /* Next in linked list */
86   SqlPreparedStmt *pPrev;  /* Previous on the list */
87   sqlite3_stmt *pStmt;     /* The prepared statement */
88   int nSql;                /* chars in zSql[] */
89   char zSql[1];            /* Text of the SQL statement */
90 };
91 
92 typedef struct IncrblobChannel IncrblobChannel;
93 
94 /*
95 ** There is one instance of this structure for each SQLite database
96 ** that has been opened by the SQLite TCL interface.
97 */
98 typedef struct SqliteDb SqliteDb;
99 struct SqliteDb {
100   sqlite3 *db;               /* The "real" database structure. MUST BE FIRST */
101   Tcl_Interp *interp;        /* The interpreter used for this database */
102   char *zBusy;               /* The busy callback routine */
103   char *zCommit;             /* The commit hook callback routine */
104   char *zTrace;              /* The trace callback routine */
105   char *zProfile;            /* The profile callback routine */
106   char *zProgress;           /* The progress callback routine */
107   char *zAuth;               /* The authorization callback routine */
108   char *zNull;               /* Text to substitute for an SQL NULL value */
109   SqlFunc *pFunc;            /* List of SQL functions */
110   Tcl_Obj *pUpdateHook;      /* Update hook script (if any) */
111   Tcl_Obj *pRollbackHook;    /* Rollback hook script (if any) */
112   SqlCollate *pCollate;      /* List of SQL collation functions */
113   int rc;                    /* Return code of most recent sqlite3_exec() */
114   Tcl_Obj *pCollateNeeded;   /* Collation needed script */
115   SqlPreparedStmt *stmtList; /* List of prepared statements*/
116   SqlPreparedStmt *stmtLast; /* Last statement in the list */
117   int maxStmt;               /* The next maximum number of stmtList */
118   int nStmt;                 /* Number of statements in stmtList */
119   IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
120 };
121 
122 struct IncrblobChannel {
123   sqlite3_blob *pBlob;      /* sqlite3 blob handle */
124   SqliteDb *pDb;            /* Associated database connection */
125   int iSeek;                /* Current seek offset */
126   Tcl_Channel channel;      /* Channel identifier */
127   IncrblobChannel *pNext;   /* Linked list of all open incrblob channels */
128   IncrblobChannel *pPrev;   /* Linked list of all open incrblob channels */
129 };
130 
131 #ifndef SQLITE_OMIT_INCRBLOB
132 /*
133 ** Close all incrblob channels opened using database connection pDb.
134 ** This is called when shutting down the database connection.
135 */
136 static void closeIncrblobChannels(SqliteDb *pDb){
137   IncrblobChannel *p;
138   IncrblobChannel *pNext;
139 
140   for(p=pDb->pIncrblob; p; p=pNext){
141     pNext = p->pNext;
142 
143     /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
144     ** which deletes the IncrblobChannel structure at *p. So do not
145     ** call Tcl_Free() here.
146     */
147     Tcl_UnregisterChannel(pDb->interp, p->channel);
148   }
149 }
150 
151 /*
152 ** Close an incremental blob channel.
153 */
154 static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
155   IncrblobChannel *p = (IncrblobChannel *)instanceData;
156   int rc = sqlite3_blob_close(p->pBlob);
157   sqlite3 *db = p->pDb->db;
158 
159   /* Remove the channel from the SqliteDb.pIncrblob list. */
160   if( p->pNext ){
161     p->pNext->pPrev = p->pPrev;
162   }
163   if( p->pPrev ){
164     p->pPrev->pNext = p->pNext;
165   }
166   if( p->pDb->pIncrblob==p ){
167     p->pDb->pIncrblob = p->pNext;
168   }
169 
170   /* Free the IncrblobChannel structure */
171   Tcl_Free((char *)p);
172 
173   if( rc!=SQLITE_OK ){
174     Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
175     return TCL_ERROR;
176   }
177   return TCL_OK;
178 }
179 
180 /*
181 ** Read data from an incremental blob channel.
182 */
183 static int incrblobInput(
184   ClientData instanceData,
185   char *buf,
186   int bufSize,
187   int *errorCodePtr
188 ){
189   IncrblobChannel *p = (IncrblobChannel *)instanceData;
190   int nRead = bufSize;         /* Number of bytes to read */
191   int nBlob;                   /* Total size of the blob */
192   int rc;                      /* sqlite error code */
193 
194   nBlob = sqlite3_blob_bytes(p->pBlob);
195   if( (p->iSeek+nRead)>nBlob ){
196     nRead = nBlob-p->iSeek;
197   }
198   if( nRead<=0 ){
199     return 0;
200   }
201 
202   rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
203   if( rc!=SQLITE_OK ){
204     *errorCodePtr = rc;
205     return -1;
206   }
207 
208   p->iSeek += nRead;
209   return nRead;
210 }
211 
212 /*
213 ** Write data to an incremental blob channel.
214 */
215 static int incrblobOutput(
216   ClientData instanceData,
217   CONST char *buf,
218   int toWrite,
219   int *errorCodePtr
220 ){
221   IncrblobChannel *p = (IncrblobChannel *)instanceData;
222   int nWrite = toWrite;        /* Number of bytes to write */
223   int nBlob;                   /* Total size of the blob */
224   int rc;                      /* sqlite error code */
225 
226   nBlob = sqlite3_blob_bytes(p->pBlob);
227   if( (p->iSeek+nWrite)>nBlob ){
228     *errorCodePtr = EINVAL;
229     return -1;
230   }
231   if( nWrite<=0 ){
232     return 0;
233   }
234 
235   rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
236   if( rc!=SQLITE_OK ){
237     *errorCodePtr = EIO;
238     return -1;
239   }
240 
241   p->iSeek += nWrite;
242   return nWrite;
243 }
244 
245 /*
246 ** Seek an incremental blob channel.
247 */
248 static int incrblobSeek(
249   ClientData instanceData,
250   long offset,
251   int seekMode,
252   int *errorCodePtr
253 ){
254   IncrblobChannel *p = (IncrblobChannel *)instanceData;
255 
256   switch( seekMode ){
257     case SEEK_SET:
258       p->iSeek = offset;
259       break;
260     case SEEK_CUR:
261       p->iSeek += offset;
262       break;
263     case SEEK_END:
264       p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
265       break;
266 
267     default: assert(!"Bad seekMode");
268   }
269 
270   return p->iSeek;
271 }
272 
273 
274 static void incrblobWatch(ClientData instanceData, int mode){
275   /* NO-OP */
276 }
277 static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
278   return TCL_ERROR;
279 }
280 
281 static Tcl_ChannelType IncrblobChannelType = {
282   "incrblob",                        /* typeName                             */
283   TCL_CHANNEL_VERSION_2,             /* version                              */
284   incrblobClose,                     /* closeProc                            */
285   incrblobInput,                     /* inputProc                            */
286   incrblobOutput,                    /* outputProc                           */
287   incrblobSeek,                      /* seekProc                             */
288   0,                                 /* setOptionProc                        */
289   0,                                 /* getOptionProc                        */
290   incrblobWatch,                     /* watchProc (this is a no-op)          */
291   incrblobHandle,                    /* getHandleProc (always returns error) */
292   0,                                 /* close2Proc                           */
293   0,                                 /* blockModeProc                        */
294   0,                                 /* flushProc                            */
295   0,                                 /* handlerProc                          */
296   0,                                 /* wideSeekProc                         */
297 };
298 
299 /*
300 ** Create a new incrblob channel.
301 */
302 static int createIncrblobChannel(
303   Tcl_Interp *interp,
304   SqliteDb *pDb,
305   const char *zDb,
306   const char *zTable,
307   const char *zColumn,
308   sqlite_int64 iRow,
309   int isReadonly
310 ){
311   IncrblobChannel *p;
312   sqlite3 *db = pDb->db;
313   sqlite3_blob *pBlob;
314   int rc;
315   int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
316 
317   /* This variable is used to name the channels: "incrblob_[incr count]" */
318   static int count = 0;
319   char zChannel[64];
320 
321   rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
322   if( rc!=SQLITE_OK ){
323     Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
324     return TCL_ERROR;
325   }
326 
327   p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
328   p->iSeek = 0;
329   p->pBlob = pBlob;
330 
331   sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
332   p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
333   Tcl_RegisterChannel(interp, p->channel);
334 
335   /* Link the new channel into the SqliteDb.pIncrblob list. */
336   p->pNext = pDb->pIncrblob;
337   p->pPrev = 0;
338   if( p->pNext ){
339     p->pNext->pPrev = p;
340   }
341   pDb->pIncrblob = p;
342   p->pDb = pDb;
343 
344   Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
345   return TCL_OK;
346 }
347 #else  /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
348   #define closeIncrblobChannels(pDb)
349 #endif
350 
351 /*
352 ** Look at the script prefix in pCmd.  We will be executing this script
353 ** after first appending one or more arguments.  This routine analyzes
354 ** the script to see if it is safe to use Tcl_EvalObjv() on the script
355 ** rather than the more general Tcl_EvalEx().  Tcl_EvalObjv() is much
356 ** faster.
357 **
358 ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
359 ** command name followed by zero or more arguments with no [...] or $
360 ** or {...} or ; to be seen anywhere.  Most callback scripts consist
361 ** of just a single procedure name and they meet this requirement.
362 */
363 static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
364   /* We could try to do something with Tcl_Parse().  But we will instead
365   ** just do a search for forbidden characters.  If any of the forbidden
366   ** characters appear in pCmd, we will report the string as unsafe.
367   */
368   const char *z;
369   int n;
370   z = Tcl_GetStringFromObj(pCmd, &n);
371   while( n-- > 0 ){
372     int c = *(z++);
373     if( c=='$' || c=='[' || c==';' ) return 0;
374   }
375   return 1;
376 }
377 
378 /*
379 ** Find an SqlFunc structure with the given name.  Or create a new
380 ** one if an existing one cannot be found.  Return a pointer to the
381 ** structure.
382 */
383 static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
384   SqlFunc *p, *pNew;
385   int i;
386   pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen(zName) + 1 );
387   pNew->zName = (char*)&pNew[1];
388   for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
389   pNew->zName[i] = 0;
390   for(p=pDb->pFunc; p; p=p->pNext){
391     if( strcmp(p->zName, pNew->zName)==0 ){
392       Tcl_Free((char*)pNew);
393       return p;
394     }
395   }
396   pNew->interp = pDb->interp;
397   pNew->pScript = 0;
398   pNew->pNext = pDb->pFunc;
399   pDb->pFunc = pNew;
400   return pNew;
401 }
402 
403 /*
404 ** Finalize and free a list of prepared statements
405 */
406 static void flushStmtCache( SqliteDb *pDb ){
407   SqlPreparedStmt *pPreStmt;
408 
409   while(  pDb->stmtList ){
410     sqlite3_finalize( pDb->stmtList->pStmt );
411     pPreStmt = pDb->stmtList;
412     pDb->stmtList = pDb->stmtList->pNext;
413     Tcl_Free( (char*)pPreStmt );
414   }
415   pDb->nStmt = 0;
416   pDb->stmtLast = 0;
417 }
418 
419 /*
420 ** TCL calls this procedure when an sqlite3 database command is
421 ** deleted.
422 */
423 static void DbDeleteCmd(void *db){
424   SqliteDb *pDb = (SqliteDb*)db;
425   flushStmtCache(pDb);
426   closeIncrblobChannels(pDb);
427   sqlite3_close(pDb->db);
428   while( pDb->pFunc ){
429     SqlFunc *pFunc = pDb->pFunc;
430     pDb->pFunc = pFunc->pNext;
431     Tcl_DecrRefCount(pFunc->pScript);
432     Tcl_Free((char*)pFunc);
433   }
434   while( pDb->pCollate ){
435     SqlCollate *pCollate = pDb->pCollate;
436     pDb->pCollate = pCollate->pNext;
437     Tcl_Free((char*)pCollate);
438   }
439   if( pDb->zBusy ){
440     Tcl_Free(pDb->zBusy);
441   }
442   if( pDb->zTrace ){
443     Tcl_Free(pDb->zTrace);
444   }
445   if( pDb->zProfile ){
446     Tcl_Free(pDb->zProfile);
447   }
448   if( pDb->zAuth ){
449     Tcl_Free(pDb->zAuth);
450   }
451   if( pDb->zNull ){
452     Tcl_Free(pDb->zNull);
453   }
454   if( pDb->pUpdateHook ){
455     Tcl_DecrRefCount(pDb->pUpdateHook);
456   }
457   if( pDb->pRollbackHook ){
458     Tcl_DecrRefCount(pDb->pRollbackHook);
459   }
460   if( pDb->pCollateNeeded ){
461     Tcl_DecrRefCount(pDb->pCollateNeeded);
462   }
463   Tcl_Free((char*)pDb);
464 }
465 
466 /*
467 ** This routine is called when a database file is locked while trying
468 ** to execute SQL.
469 */
470 static int DbBusyHandler(void *cd, int nTries){
471   SqliteDb *pDb = (SqliteDb*)cd;
472   int rc;
473   char zVal[30];
474 
475   sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
476   rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
477   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
478     return 0;
479   }
480   return 1;
481 }
482 
483 /*
484 ** This routine is invoked as the 'progress callback' for the database.
485 */
486 static int DbProgressHandler(void *cd){
487   SqliteDb *pDb = (SqliteDb*)cd;
488   int rc;
489 
490   assert( pDb->zProgress );
491   rc = Tcl_Eval(pDb->interp, pDb->zProgress);
492   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
493     return 1;
494   }
495   return 0;
496 }
497 
498 #ifndef SQLITE_OMIT_TRACE
499 /*
500 ** This routine is called by the SQLite trace handler whenever a new
501 ** block of SQL is executed.  The TCL script in pDb->zTrace is executed.
502 */
503 static void DbTraceHandler(void *cd, const char *zSql){
504   SqliteDb *pDb = (SqliteDb*)cd;
505   Tcl_DString str;
506 
507   Tcl_DStringInit(&str);
508   Tcl_DStringAppend(&str, pDb->zTrace, -1);
509   Tcl_DStringAppendElement(&str, zSql);
510   Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
511   Tcl_DStringFree(&str);
512   Tcl_ResetResult(pDb->interp);
513 }
514 #endif
515 
516 #ifndef SQLITE_OMIT_TRACE
517 /*
518 ** This routine is called by the SQLite profile handler after a statement
519 ** SQL has executed.  The TCL script in pDb->zProfile is evaluated.
520 */
521 static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
522   SqliteDb *pDb = (SqliteDb*)cd;
523   Tcl_DString str;
524   char zTm[100];
525 
526   sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
527   Tcl_DStringInit(&str);
528   Tcl_DStringAppend(&str, pDb->zProfile, -1);
529   Tcl_DStringAppendElement(&str, zSql);
530   Tcl_DStringAppendElement(&str, zTm);
531   Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
532   Tcl_DStringFree(&str);
533   Tcl_ResetResult(pDb->interp);
534 }
535 #endif
536 
537 /*
538 ** This routine is called when a transaction is committed.  The
539 ** TCL script in pDb->zCommit is executed.  If it returns non-zero or
540 ** if it throws an exception, the transaction is rolled back instead
541 ** of being committed.
542 */
543 static int DbCommitHandler(void *cd){
544   SqliteDb *pDb = (SqliteDb*)cd;
545   int rc;
546 
547   rc = Tcl_Eval(pDb->interp, pDb->zCommit);
548   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
549     return 1;
550   }
551   return 0;
552 }
553 
554 static void DbRollbackHandler(void *clientData){
555   SqliteDb *pDb = (SqliteDb*)clientData;
556   assert(pDb->pRollbackHook);
557   if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
558     Tcl_BackgroundError(pDb->interp);
559   }
560 }
561 
562 static void DbUpdateHandler(
563   void *p,
564   int op,
565   const char *zDb,
566   const char *zTbl,
567   sqlite_int64 rowid
568 ){
569   SqliteDb *pDb = (SqliteDb *)p;
570   Tcl_Obj *pCmd;
571 
572   assert( pDb->pUpdateHook );
573   assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
574 
575   pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
576   Tcl_IncrRefCount(pCmd);
577   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
578     ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
579   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
580   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
581   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
582   Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
583 }
584 
585 static void tclCollateNeeded(
586   void *pCtx,
587   sqlite3 *db,
588   int enc,
589   const char *zName
590 ){
591   SqliteDb *pDb = (SqliteDb *)pCtx;
592   Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
593   Tcl_IncrRefCount(pScript);
594   Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
595   Tcl_EvalObjEx(pDb->interp, pScript, 0);
596   Tcl_DecrRefCount(pScript);
597 }
598 
599 /*
600 ** This routine is called to evaluate an SQL collation function implemented
601 ** using TCL script.
602 */
603 static int tclSqlCollate(
604   void *pCtx,
605   int nA,
606   const void *zA,
607   int nB,
608   const void *zB
609 ){
610   SqlCollate *p = (SqlCollate *)pCtx;
611   Tcl_Obj *pCmd;
612 
613   pCmd = Tcl_NewStringObj(p->zScript, -1);
614   Tcl_IncrRefCount(pCmd);
615   Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
616   Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
617   Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
618   Tcl_DecrRefCount(pCmd);
619   return (atoi(Tcl_GetStringResult(p->interp)));
620 }
621 
622 /*
623 ** This routine is called to evaluate an SQL function implemented
624 ** using TCL script.
625 */
626 static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
627   SqlFunc *p = sqlite3_user_data(context);
628   Tcl_Obj *pCmd;
629   int i;
630   int rc;
631 
632   if( argc==0 ){
633     /* If there are no arguments to the function, call Tcl_EvalObjEx on the
634     ** script object directly.  This allows the TCL compiler to generate
635     ** bytecode for the command on the first invocation and thus make
636     ** subsequent invocations much faster. */
637     pCmd = p->pScript;
638     Tcl_IncrRefCount(pCmd);
639     rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
640     Tcl_DecrRefCount(pCmd);
641   }else{
642     /* If there are arguments to the function, make a shallow copy of the
643     ** script object, lappend the arguments, then evaluate the copy.
644     **
645     ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
646     ** The new Tcl_Obj contains pointers to the original list elements.
647     ** That way, when Tcl_EvalObjv() is run and shimmers the first element
648     ** of the list to tclCmdNameType, that alternate representation will
649     ** be preserved and reused on the next invocation.
650     */
651     Tcl_Obj **aArg;
652     int nArg;
653     if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
654       sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
655       return;
656     }
657     pCmd = Tcl_NewListObj(nArg, aArg);
658     Tcl_IncrRefCount(pCmd);
659     for(i=0; i<argc; i++){
660       sqlite3_value *pIn = argv[i];
661       Tcl_Obj *pVal;
662 
663       /* Set pVal to contain the i'th column of this row. */
664       switch( sqlite3_value_type(pIn) ){
665         case SQLITE_BLOB: {
666           int bytes = sqlite3_value_bytes(pIn);
667           pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
668           break;
669         }
670         case SQLITE_INTEGER: {
671           sqlite_int64 v = sqlite3_value_int64(pIn);
672           if( v>=-2147483647 && v<=2147483647 ){
673             pVal = Tcl_NewIntObj(v);
674           }else{
675             pVal = Tcl_NewWideIntObj(v);
676           }
677           break;
678         }
679         case SQLITE_FLOAT: {
680           double r = sqlite3_value_double(pIn);
681           pVal = Tcl_NewDoubleObj(r);
682           break;
683         }
684         case SQLITE_NULL: {
685           pVal = Tcl_NewStringObj("", 0);
686           break;
687         }
688         default: {
689           int bytes = sqlite3_value_bytes(pIn);
690           pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
691           break;
692         }
693       }
694       rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
695       if( rc ){
696         Tcl_DecrRefCount(pCmd);
697         sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
698         return;
699       }
700     }
701     if( !p->useEvalObjv ){
702       /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
703       ** is a list without a string representation.  To prevent this from
704       ** happening, make sure pCmd has a valid string representation */
705       Tcl_GetString(pCmd);
706     }
707     rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
708     Tcl_DecrRefCount(pCmd);
709   }
710 
711   if( rc && rc!=TCL_RETURN ){
712     sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
713   }else{
714     Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
715     int n;
716     u8 *data;
717     char *zType = pVar->typePtr ? pVar->typePtr->name : "";
718     char c = zType[0];
719     if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
720       /* Only return a BLOB type if the Tcl variable is a bytearray and
721       ** has no string representation. */
722       data = Tcl_GetByteArrayFromObj(pVar, &n);
723       sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
724     }else if( c=='b' && strcmp(zType,"boolean")==0 ){
725       Tcl_GetIntFromObj(0, pVar, &n);
726       sqlite3_result_int(context, n);
727     }else if( c=='d' && strcmp(zType,"double")==0 ){
728       double r;
729       Tcl_GetDoubleFromObj(0, pVar, &r);
730       sqlite3_result_double(context, r);
731     }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
732           (c=='i' && strcmp(zType,"int")==0) ){
733       Tcl_WideInt v;
734       Tcl_GetWideIntFromObj(0, pVar, &v);
735       sqlite3_result_int64(context, v);
736     }else{
737       data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
738       sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
739     }
740   }
741 }
742 
743 #ifndef SQLITE_OMIT_AUTHORIZATION
744 /*
745 ** This is the authentication function.  It appends the authentication
746 ** type code and the two arguments to zCmd[] then invokes the result
747 ** on the interpreter.  The reply is examined to determine if the
748 ** authentication fails or succeeds.
749 */
750 static int auth_callback(
751   void *pArg,
752   int code,
753   const char *zArg1,
754   const char *zArg2,
755   const char *zArg3,
756   const char *zArg4
757 ){
758   char *zCode;
759   Tcl_DString str;
760   int rc;
761   const char *zReply;
762   SqliteDb *pDb = (SqliteDb*)pArg;
763 
764   switch( code ){
765     case SQLITE_COPY              : zCode="SQLITE_COPY"; break;
766     case SQLITE_CREATE_INDEX      : zCode="SQLITE_CREATE_INDEX"; break;
767     case SQLITE_CREATE_TABLE      : zCode="SQLITE_CREATE_TABLE"; break;
768     case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
769     case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
770     case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
771     case SQLITE_CREATE_TEMP_VIEW  : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
772     case SQLITE_CREATE_TRIGGER    : zCode="SQLITE_CREATE_TRIGGER"; break;
773     case SQLITE_CREATE_VIEW       : zCode="SQLITE_CREATE_VIEW"; break;
774     case SQLITE_DELETE            : zCode="SQLITE_DELETE"; break;
775     case SQLITE_DROP_INDEX        : zCode="SQLITE_DROP_INDEX"; break;
776     case SQLITE_DROP_TABLE        : zCode="SQLITE_DROP_TABLE"; break;
777     case SQLITE_DROP_TEMP_INDEX   : zCode="SQLITE_DROP_TEMP_INDEX"; break;
778     case SQLITE_DROP_TEMP_TABLE   : zCode="SQLITE_DROP_TEMP_TABLE"; break;
779     case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
780     case SQLITE_DROP_TEMP_VIEW    : zCode="SQLITE_DROP_TEMP_VIEW"; break;
781     case SQLITE_DROP_TRIGGER      : zCode="SQLITE_DROP_TRIGGER"; break;
782     case SQLITE_DROP_VIEW         : zCode="SQLITE_DROP_VIEW"; break;
783     case SQLITE_INSERT            : zCode="SQLITE_INSERT"; break;
784     case SQLITE_PRAGMA            : zCode="SQLITE_PRAGMA"; break;
785     case SQLITE_READ              : zCode="SQLITE_READ"; break;
786     case SQLITE_SELECT            : zCode="SQLITE_SELECT"; break;
787     case SQLITE_TRANSACTION       : zCode="SQLITE_TRANSACTION"; break;
788     case SQLITE_UPDATE            : zCode="SQLITE_UPDATE"; break;
789     case SQLITE_ATTACH            : zCode="SQLITE_ATTACH"; break;
790     case SQLITE_DETACH            : zCode="SQLITE_DETACH"; break;
791     case SQLITE_ALTER_TABLE       : zCode="SQLITE_ALTER_TABLE"; break;
792     case SQLITE_REINDEX           : zCode="SQLITE_REINDEX"; break;
793     case SQLITE_ANALYZE           : zCode="SQLITE_ANALYZE"; break;
794     case SQLITE_CREATE_VTABLE     : zCode="SQLITE_CREATE_VTABLE"; break;
795     case SQLITE_DROP_VTABLE       : zCode="SQLITE_DROP_VTABLE"; break;
796     case SQLITE_FUNCTION          : zCode="SQLITE_FUNCTION"; break;
797     default                       : zCode="????"; break;
798   }
799   Tcl_DStringInit(&str);
800   Tcl_DStringAppend(&str, pDb->zAuth, -1);
801   Tcl_DStringAppendElement(&str, zCode);
802   Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
803   Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
804   Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
805   Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
806   rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
807   Tcl_DStringFree(&str);
808   zReply = Tcl_GetStringResult(pDb->interp);
809   if( strcmp(zReply,"SQLITE_OK")==0 ){
810     rc = SQLITE_OK;
811   }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
812     rc = SQLITE_DENY;
813   }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
814     rc = SQLITE_IGNORE;
815   }else{
816     rc = 999;
817   }
818   return rc;
819 }
820 #endif /* SQLITE_OMIT_AUTHORIZATION */
821 
822 /*
823 ** zText is a pointer to text obtained via an sqlite3_result_text()
824 ** or similar interface. This routine returns a Tcl string object,
825 ** reference count set to 0, containing the text. If a translation
826 ** between iso8859 and UTF-8 is required, it is preformed.
827 */
828 static Tcl_Obj *dbTextToObj(char const *zText){
829   Tcl_Obj *pVal;
830 #ifdef UTF_TRANSLATION_NEEDED
831   Tcl_DString dCol;
832   Tcl_DStringInit(&dCol);
833   Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
834   pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
835   Tcl_DStringFree(&dCol);
836 #else
837   pVal = Tcl_NewStringObj(zText, -1);
838 #endif
839   return pVal;
840 }
841 
842 /*
843 ** This routine reads a line of text from FILE in, stores
844 ** the text in memory obtained from malloc() and returns a pointer
845 ** to the text.  NULL is returned at end of file, or if malloc()
846 ** fails.
847 **
848 ** The interface is like "readline" but no command-line editing
849 ** is done.
850 **
851 ** copied from shell.c from '.import' command
852 */
853 static char *local_getline(char *zPrompt, FILE *in){
854   char *zLine;
855   int nLine;
856   int n;
857   int eol;
858 
859   nLine = 100;
860   zLine = malloc( nLine );
861   if( zLine==0 ) return 0;
862   n = 0;
863   eol = 0;
864   while( !eol ){
865     if( n+100>nLine ){
866       nLine = nLine*2 + 100;
867       zLine = realloc(zLine, nLine);
868       if( zLine==0 ) return 0;
869     }
870     if( fgets(&zLine[n], nLine - n, in)==0 ){
871       if( n==0 ){
872         free(zLine);
873         return 0;
874       }
875       zLine[n] = 0;
876       eol = 1;
877       break;
878     }
879     while( zLine[n] ){ n++; }
880     if( n>0 && zLine[n-1]=='\n' ){
881       n--;
882       zLine[n] = 0;
883       eol = 1;
884     }
885   }
886   zLine = realloc( zLine, n+1 );
887   return zLine;
888 }
889 
890 /*
891 ** The "sqlite" command below creates a new Tcl command for each
892 ** connection it opens to an SQLite database.  This routine is invoked
893 ** whenever one of those connection-specific commands is executed
894 ** in Tcl.  For example, if you run Tcl code like this:
895 **
896 **       sqlite3 db1  "my_database"
897 **       db1 close
898 **
899 ** The first command opens a connection to the "my_database" database
900 ** and calls that connection "db1".  The second command causes this
901 ** subroutine to be invoked.
902 */
903 static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
904   SqliteDb *pDb = (SqliteDb*)cd;
905   int choice;
906   int rc = TCL_OK;
907   static const char *DB_strs[] = {
908     "authorizer",         "busy",              "cache",
909     "changes",            "close",             "collate",
910     "collation_needed",   "commit_hook",       "complete",
911     "copy",               "enable_load_extension","errorcode",
912     "eval",               "exists",            "function",
913     "incrblob",           "interrupt",         "last_insert_rowid",
914     "nullvalue",          "onecolumn",         "profile",
915     "progress",           "rekey",             "rollback_hook",
916     "timeout",            "total_changes",     "trace",
917     "transaction",        "update_hook",       "version",
918     0
919   };
920   enum DB_enum {
921     DB_AUTHORIZER,        DB_BUSY,             DB_CACHE,
922     DB_CHANGES,           DB_CLOSE,            DB_COLLATE,
923     DB_COLLATION_NEEDED,  DB_COMMIT_HOOK,      DB_COMPLETE,
924     DB_COPY,              DB_ENABLE_LOAD_EXTENSION,DB_ERRORCODE,
925     DB_EVAL,              DB_EXISTS,           DB_FUNCTION,
926     DB_INCRBLOB,          DB_INTERRUPT,        DB_LAST_INSERT_ROWID,
927     DB_NULLVALUE,         DB_ONECOLUMN,        DB_PROFILE,
928     DB_PROGRESS,          DB_REKEY,            DB_ROLLBACK_HOOK,
929     DB_TIMEOUT,           DB_TOTAL_CHANGES,    DB_TRACE,
930     DB_TRANSACTION,       DB_UPDATE_HOOK,      DB_VERSION
931   };
932   /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
933 
934   if( objc<2 ){
935     Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
936     return TCL_ERROR;
937   }
938   if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
939     return TCL_ERROR;
940   }
941 
942   switch( (enum DB_enum)choice ){
943 
944   /*    $db authorizer ?CALLBACK?
945   **
946   ** Invoke the given callback to authorize each SQL operation as it is
947   ** compiled.  5 arguments are appended to the callback before it is
948   ** invoked:
949   **
950   **   (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
951   **   (2) First descriptive name (depends on authorization type)
952   **   (3) Second descriptive name
953   **   (4) Name of the database (ex: "main", "temp")
954   **   (5) Name of trigger that is doing the access
955   **
956   ** The callback should return on of the following strings: SQLITE_OK,
957   ** SQLITE_IGNORE, or SQLITE_DENY.  Any other return value is an error.
958   **
959   ** If this method is invoked with no arguments, the current authorization
960   ** callback string is returned.
961   */
962   case DB_AUTHORIZER: {
963 #ifdef SQLITE_OMIT_AUTHORIZATION
964     Tcl_AppendResult(interp, "authorization not available in this build", 0);
965     return TCL_ERROR;
966 #else
967     if( objc>3 ){
968       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
969       return TCL_ERROR;
970     }else if( objc==2 ){
971       if( pDb->zAuth ){
972         Tcl_AppendResult(interp, pDb->zAuth, 0);
973       }
974     }else{
975       char *zAuth;
976       int len;
977       if( pDb->zAuth ){
978         Tcl_Free(pDb->zAuth);
979       }
980       zAuth = Tcl_GetStringFromObj(objv[2], &len);
981       if( zAuth && len>0 ){
982         pDb->zAuth = Tcl_Alloc( len + 1 );
983         memcpy(pDb->zAuth, zAuth, len+1);
984       }else{
985         pDb->zAuth = 0;
986       }
987       if( pDb->zAuth ){
988         pDb->interp = interp;
989         sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
990       }else{
991         sqlite3_set_authorizer(pDb->db, 0, 0);
992       }
993     }
994 #endif
995     break;
996   }
997 
998   /*    $db busy ?CALLBACK?
999   **
1000   ** Invoke the given callback if an SQL statement attempts to open
1001   ** a locked database file.
1002   */
1003   case DB_BUSY: {
1004     if( objc>3 ){
1005       Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
1006       return TCL_ERROR;
1007     }else if( objc==2 ){
1008       if( pDb->zBusy ){
1009         Tcl_AppendResult(interp, pDb->zBusy, 0);
1010       }
1011     }else{
1012       char *zBusy;
1013       int len;
1014       if( pDb->zBusy ){
1015         Tcl_Free(pDb->zBusy);
1016       }
1017       zBusy = Tcl_GetStringFromObj(objv[2], &len);
1018       if( zBusy && len>0 ){
1019         pDb->zBusy = Tcl_Alloc( len + 1 );
1020         memcpy(pDb->zBusy, zBusy, len+1);
1021       }else{
1022         pDb->zBusy = 0;
1023       }
1024       if( pDb->zBusy ){
1025         pDb->interp = interp;
1026         sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
1027       }else{
1028         sqlite3_busy_handler(pDb->db, 0, 0);
1029       }
1030     }
1031     break;
1032   }
1033 
1034   /*     $db cache flush
1035   **     $db cache size n
1036   **
1037   ** Flush the prepared statement cache, or set the maximum number of
1038   ** cached statements.
1039   */
1040   case DB_CACHE: {
1041     char *subCmd;
1042     int n;
1043 
1044     if( objc<=2 ){
1045       Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1046       return TCL_ERROR;
1047     }
1048     subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1049     if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1050       if( objc!=3 ){
1051         Tcl_WrongNumArgs(interp, 2, objv, "flush");
1052         return TCL_ERROR;
1053       }else{
1054         flushStmtCache( pDb );
1055       }
1056     }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1057       if( objc!=4 ){
1058         Tcl_WrongNumArgs(interp, 2, objv, "size n");
1059         return TCL_ERROR;
1060       }else{
1061         if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1062           Tcl_AppendResult( interp, "cannot convert \"",
1063                Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1064           return TCL_ERROR;
1065         }else{
1066           if( n<0 ){
1067             flushStmtCache( pDb );
1068             n = 0;
1069           }else if( n>MAX_PREPARED_STMTS ){
1070             n = MAX_PREPARED_STMTS;
1071           }
1072           pDb->maxStmt = n;
1073         }
1074       }
1075     }else{
1076       Tcl_AppendResult( interp, "bad option \"",
1077           Tcl_GetStringFromObj(objv[0],0), "\": must be flush or size", 0);
1078       return TCL_ERROR;
1079     }
1080     break;
1081   }
1082 
1083   /*     $db changes
1084   **
1085   ** Return the number of rows that were modified, inserted, or deleted by
1086   ** the most recent INSERT, UPDATE or DELETE statement, not including
1087   ** any changes made by trigger programs.
1088   */
1089   case DB_CHANGES: {
1090     Tcl_Obj *pResult;
1091     if( objc!=2 ){
1092       Tcl_WrongNumArgs(interp, 2, objv, "");
1093       return TCL_ERROR;
1094     }
1095     pResult = Tcl_GetObjResult(interp);
1096     Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
1097     break;
1098   }
1099 
1100   /*    $db close
1101   **
1102   ** Shutdown the database
1103   */
1104   case DB_CLOSE: {
1105     Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1106     break;
1107   }
1108 
1109   /*
1110   **     $db collate NAME SCRIPT
1111   **
1112   ** Create a new SQL collation function called NAME.  Whenever
1113   ** that function is called, invoke SCRIPT to evaluate the function.
1114   */
1115   case DB_COLLATE: {
1116     SqlCollate *pCollate;
1117     char *zName;
1118     char *zScript;
1119     int nScript;
1120     if( objc!=4 ){
1121       Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1122       return TCL_ERROR;
1123     }
1124     zName = Tcl_GetStringFromObj(objv[2], 0);
1125     zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1126     pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1127     if( pCollate==0 ) return TCL_ERROR;
1128     pCollate->interp = interp;
1129     pCollate->pNext = pDb->pCollate;
1130     pCollate->zScript = (char*)&pCollate[1];
1131     pDb->pCollate = pCollate;
1132     memcpy(pCollate->zScript, zScript, nScript+1);
1133     if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1134         pCollate, tclSqlCollate) ){
1135       Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
1136       return TCL_ERROR;
1137     }
1138     break;
1139   }
1140 
1141   /*
1142   **     $db collation_needed SCRIPT
1143   **
1144   ** Create a new SQL collation function called NAME.  Whenever
1145   ** that function is called, invoke SCRIPT to evaluate the function.
1146   */
1147   case DB_COLLATION_NEEDED: {
1148     if( objc!=3 ){
1149       Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1150       return TCL_ERROR;
1151     }
1152     if( pDb->pCollateNeeded ){
1153       Tcl_DecrRefCount(pDb->pCollateNeeded);
1154     }
1155     pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1156     Tcl_IncrRefCount(pDb->pCollateNeeded);
1157     sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1158     break;
1159   }
1160 
1161   /*    $db commit_hook ?CALLBACK?
1162   **
1163   ** Invoke the given callback just before committing every SQL transaction.
1164   ** If the callback throws an exception or returns non-zero, then the
1165   ** transaction is aborted.  If CALLBACK is an empty string, the callback
1166   ** is disabled.
1167   */
1168   case DB_COMMIT_HOOK: {
1169     if( objc>3 ){
1170       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1171       return TCL_ERROR;
1172     }else if( objc==2 ){
1173       if( pDb->zCommit ){
1174         Tcl_AppendResult(interp, pDb->zCommit, 0);
1175       }
1176     }else{
1177       char *zCommit;
1178       int len;
1179       if( pDb->zCommit ){
1180         Tcl_Free(pDb->zCommit);
1181       }
1182       zCommit = Tcl_GetStringFromObj(objv[2], &len);
1183       if( zCommit && len>0 ){
1184         pDb->zCommit = Tcl_Alloc( len + 1 );
1185         memcpy(pDb->zCommit, zCommit, len+1);
1186       }else{
1187         pDb->zCommit = 0;
1188       }
1189       if( pDb->zCommit ){
1190         pDb->interp = interp;
1191         sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1192       }else{
1193         sqlite3_commit_hook(pDb->db, 0, 0);
1194       }
1195     }
1196     break;
1197   }
1198 
1199   /*    $db complete SQL
1200   **
1201   ** Return TRUE if SQL is a complete SQL statement.  Return FALSE if
1202   ** additional lines of input are needed.  This is similar to the
1203   ** built-in "info complete" command of Tcl.
1204   */
1205   case DB_COMPLETE: {
1206 #ifndef SQLITE_OMIT_COMPLETE
1207     Tcl_Obj *pResult;
1208     int isComplete;
1209     if( objc!=3 ){
1210       Tcl_WrongNumArgs(interp, 2, objv, "SQL");
1211       return TCL_ERROR;
1212     }
1213     isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
1214     pResult = Tcl_GetObjResult(interp);
1215     Tcl_SetBooleanObj(pResult, isComplete);
1216 #endif
1217     break;
1218   }
1219 
1220   /*    $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1221   **
1222   ** Copy data into table from filename, optionally using SEPARATOR
1223   ** as column separators.  If a column contains a null string, or the
1224   ** value of NULLINDICATOR, a NULL is inserted for the column.
1225   ** conflict-algorithm is one of the sqlite conflict algorithms:
1226   **    rollback, abort, fail, ignore, replace
1227   ** On success, return the number of lines processed, not necessarily same
1228   ** as 'db changes' due to conflict-algorithm selected.
1229   **
1230   ** This code is basically an implementation/enhancement of
1231   ** the sqlite3 shell.c ".import" command.
1232   **
1233   ** This command usage is equivalent to the sqlite2.x COPY statement,
1234   ** which imports file data into a table using the PostgreSQL COPY file format:
1235   **   $db copy $conflit_algo $table_name $filename \t \\N
1236   */
1237   case DB_COPY: {
1238     char *zTable;               /* Insert data into this table */
1239     char *zFile;                /* The file from which to extract data */
1240     char *zConflict;            /* The conflict algorithm to use */
1241     sqlite3_stmt *pStmt;        /* A statement */
1242     int rc;                     /* Result code */
1243     int nCol;                   /* Number of columns in the table */
1244     int nByte;                  /* Number of bytes in an SQL string */
1245     int i, j;                   /* Loop counters */
1246     int nSep;                   /* Number of bytes in zSep[] */
1247     int nNull;                  /* Number of bytes in zNull[] */
1248     char *zSql;                 /* An SQL statement */
1249     char *zLine;                /* A single line of input from the file */
1250     char **azCol;               /* zLine[] broken up into columns */
1251     char *zCommit;              /* How to commit changes */
1252     FILE *in;                   /* The input file */
1253     int lineno = 0;             /* Line number of input file */
1254     char zLineNum[80];          /* Line number print buffer */
1255     Tcl_Obj *pResult;           /* interp result */
1256 
1257     char *zSep;
1258     char *zNull;
1259     if( objc<5 || objc>7 ){
1260       Tcl_WrongNumArgs(interp, 2, objv,
1261          "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1262       return TCL_ERROR;
1263     }
1264     if( objc>=6 ){
1265       zSep = Tcl_GetStringFromObj(objv[5], 0);
1266     }else{
1267       zSep = "\t";
1268     }
1269     if( objc>=7 ){
1270       zNull = Tcl_GetStringFromObj(objv[6], 0);
1271     }else{
1272       zNull = "";
1273     }
1274     zConflict = Tcl_GetStringFromObj(objv[2], 0);
1275     zTable = Tcl_GetStringFromObj(objv[3], 0);
1276     zFile = Tcl_GetStringFromObj(objv[4], 0);
1277     nSep = strlen(zSep);
1278     nNull = strlen(zNull);
1279     if( nSep==0 ){
1280       Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
1281       return TCL_ERROR;
1282     }
1283     if(sqlite3StrICmp(zConflict, "rollback") != 0 &&
1284        sqlite3StrICmp(zConflict, "abort"   ) != 0 &&
1285        sqlite3StrICmp(zConflict, "fail"    ) != 0 &&
1286        sqlite3StrICmp(zConflict, "ignore"  ) != 0 &&
1287        sqlite3StrICmp(zConflict, "replace" ) != 0 ) {
1288       Tcl_AppendResult(interp, "Error: \"", zConflict,
1289             "\", conflict-algorithm must be one of: rollback, "
1290             "abort, fail, ignore, or replace", 0);
1291       return TCL_ERROR;
1292     }
1293     zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1294     if( zSql==0 ){
1295       Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1296       return TCL_ERROR;
1297     }
1298     nByte = strlen(zSql);
1299     rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
1300     sqlite3_free(zSql);
1301     if( rc ){
1302       Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1303       nCol = 0;
1304     }else{
1305       nCol = sqlite3_column_count(pStmt);
1306     }
1307     sqlite3_finalize(pStmt);
1308     if( nCol==0 ) {
1309       return TCL_ERROR;
1310     }
1311     zSql = malloc( nByte + 50 + nCol*2 );
1312     if( zSql==0 ) {
1313       Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1314       return TCL_ERROR;
1315     }
1316     sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1317          zConflict, zTable);
1318     j = strlen(zSql);
1319     for(i=1; i<nCol; i++){
1320       zSql[j++] = ',';
1321       zSql[j++] = '?';
1322     }
1323     zSql[j++] = ')';
1324     zSql[j] = 0;
1325     rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
1326     free(zSql);
1327     if( rc ){
1328       Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1329       sqlite3_finalize(pStmt);
1330       return TCL_ERROR;
1331     }
1332     in = fopen(zFile, "rb");
1333     if( in==0 ){
1334       Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
1335       sqlite3_finalize(pStmt);
1336       return TCL_ERROR;
1337     }
1338     azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1339     if( azCol==0 ) {
1340       Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1341       fclose(in);
1342       return TCL_ERROR;
1343     }
1344     (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
1345     zCommit = "COMMIT";
1346     while( (zLine = local_getline(0, in))!=0 ){
1347       char *z;
1348       i = 0;
1349       lineno++;
1350       azCol[0] = zLine;
1351       for(i=0, z=zLine; *z; z++){
1352         if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
1353           *z = 0;
1354           i++;
1355           if( i<nCol ){
1356             azCol[i] = &z[nSep];
1357             z += nSep-1;
1358           }
1359         }
1360       }
1361       if( i+1!=nCol ){
1362         char *zErr;
1363         int nErr = strlen(zFile) + 200;
1364         zErr = malloc(nErr);
1365         if( zErr ){
1366           sqlite3_snprintf(nErr, zErr,
1367              "Error: %s line %d: expected %d columns of data but found %d",
1368              zFile, lineno, nCol, i+1);
1369           Tcl_AppendResult(interp, zErr, 0);
1370           free(zErr);
1371         }
1372         zCommit = "ROLLBACK";
1373         break;
1374       }
1375       for(i=0; i<nCol; i++){
1376         /* check for null data, if so, bind as null */
1377         if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
1378           sqlite3_bind_null(pStmt, i+1);
1379         }else{
1380           sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1381         }
1382       }
1383       sqlite3_step(pStmt);
1384       rc = sqlite3_reset(pStmt);
1385       free(zLine);
1386       if( rc!=SQLITE_OK ){
1387         Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
1388         zCommit = "ROLLBACK";
1389         break;
1390       }
1391     }
1392     free(azCol);
1393     fclose(in);
1394     sqlite3_finalize(pStmt);
1395     (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
1396 
1397     if( zCommit[0] == 'C' ){
1398       /* success, set result as number of lines processed */
1399       pResult = Tcl_GetObjResult(interp);
1400       Tcl_SetIntObj(pResult, lineno);
1401       rc = TCL_OK;
1402     }else{
1403       /* failure, append lineno where failed */
1404       sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
1405       Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
1406       rc = TCL_ERROR;
1407     }
1408     break;
1409   }
1410 
1411   /*
1412   **    $db enable_load_extension BOOLEAN
1413   **
1414   ** Turn the extension loading feature on or off.  It if off by
1415   ** default.
1416   */
1417   case DB_ENABLE_LOAD_EXTENSION: {
1418 #ifndef SQLITE_OMIT_LOAD_EXTENSION
1419     int onoff;
1420     if( objc!=3 ){
1421       Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
1422       return TCL_ERROR;
1423     }
1424     if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
1425       return TCL_ERROR;
1426     }
1427     sqlite3_enable_load_extension(pDb->db, onoff);
1428     break;
1429 #else
1430     Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
1431                      0);
1432     return TCL_ERROR;
1433 #endif
1434   }
1435 
1436   /*
1437   **    $db errorcode
1438   **
1439   ** Return the numeric error code that was returned by the most recent
1440   ** call to sqlite3_exec().
1441   */
1442   case DB_ERRORCODE: {
1443     Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
1444     break;
1445   }
1446 
1447   /*
1448   **    $db eval $sql ?array? ?{  ...code... }?
1449   **    $db onecolumn $sql
1450   **
1451   ** The SQL statement in $sql is evaluated.  For each row, the values are
1452   ** placed in elements of the array named "array" and ...code... is executed.
1453   ** If "array" and "code" are omitted, then no callback is every invoked.
1454   ** If "array" is an empty string, then the values are placed in variables
1455   ** that have the same name as the fields extracted by the query.
1456   **
1457   ** The onecolumn method is the equivalent of:
1458   **     lindex [$db eval $sql] 0
1459   */
1460   case DB_ONECOLUMN:
1461   case DB_EVAL:
1462   case DB_EXISTS: {
1463     char const *zSql;      /* Next SQL statement to execute */
1464     char const *zLeft;     /* What is left after first stmt in zSql */
1465     sqlite3_stmt *pStmt;   /* Compiled SQL statment */
1466     Tcl_Obj *pArray;       /* Name of array into which results are written */
1467     Tcl_Obj *pScript;      /* Script to run for each result set */
1468     Tcl_Obj **apParm;      /* Parameters that need a Tcl_DecrRefCount() */
1469     int nParm;             /* Number of entries used in apParm[] */
1470     Tcl_Obj *aParm[10];    /* Static space for apParm[] in the common case */
1471     Tcl_Obj *pRet;         /* Value to be returned */
1472     SqlPreparedStmt *pPreStmt;  /* Pointer to a prepared statement */
1473     int rc2;
1474 
1475     if( choice==DB_EVAL ){
1476       if( objc<3 || objc>5 ){
1477         Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
1478         return TCL_ERROR;
1479       }
1480       pRet = Tcl_NewObj();
1481       Tcl_IncrRefCount(pRet);
1482     }else{
1483       if( objc!=3 ){
1484         Tcl_WrongNumArgs(interp, 2, objv, "SQL");
1485         return TCL_ERROR;
1486       }
1487       if( choice==DB_EXISTS ){
1488         pRet = Tcl_NewBooleanObj(0);
1489         Tcl_IncrRefCount(pRet);
1490       }else{
1491         pRet = 0;
1492       }
1493     }
1494     if( objc==3 ){
1495       pArray = pScript = 0;
1496     }else if( objc==4 ){
1497       pArray = 0;
1498       pScript = objv[3];
1499     }else{
1500       pArray = objv[3];
1501       if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
1502       pScript = objv[4];
1503     }
1504 
1505     Tcl_IncrRefCount(objv[2]);
1506     zSql = Tcl_GetStringFromObj(objv[2], 0);
1507     while( rc==TCL_OK && zSql[0] ){
1508       int i;                     /* Loop counter */
1509       int nVar;                  /* Number of bind parameters in the pStmt */
1510       int nCol;                  /* Number of columns in the result set */
1511       Tcl_Obj **apColName = 0;   /* Array of column names */
1512       int len;                   /* String length of zSql */
1513 
1514       /* Try to find a SQL statement that has already been compiled and
1515       ** which matches the next sequence of SQL.
1516       */
1517       pStmt = 0;
1518       pPreStmt = pDb->stmtList;
1519       len = strlen(zSql);
1520       if( pPreStmt && sqlite3_expired(pPreStmt->pStmt) ){
1521         flushStmtCache(pDb);
1522         pPreStmt = 0;
1523       }
1524       for(; pPreStmt; pPreStmt=pPreStmt->pNext){
1525         int n = pPreStmt->nSql;
1526         if( len>=n
1527             && memcmp(pPreStmt->zSql, zSql, n)==0
1528             && (zSql[n]==0 || zSql[n-1]==';')
1529         ){
1530           pStmt = pPreStmt->pStmt;
1531           zLeft = &zSql[pPreStmt->nSql];
1532 
1533           /* When a prepared statement is found, unlink it from the
1534           ** cache list.  It will later be added back to the beginning
1535           ** of the cache list in order to implement LRU replacement.
1536           */
1537           if( pPreStmt->pPrev ){
1538             pPreStmt->pPrev->pNext = pPreStmt->pNext;
1539           }else{
1540             pDb->stmtList = pPreStmt->pNext;
1541           }
1542           if( pPreStmt->pNext ){
1543             pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1544           }else{
1545             pDb->stmtLast = pPreStmt->pPrev;
1546           }
1547           pDb->nStmt--;
1548           break;
1549         }
1550       }
1551 
1552       /* If no prepared statement was found.  Compile the SQL text
1553       */
1554       if( pStmt==0 ){
1555         if( SQLITE_OK!=sqlite3_prepare(pDb->db, zSql, -1, &pStmt, &zLeft) ){
1556           Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1557           rc = TCL_ERROR;
1558           break;
1559         }
1560         if( pStmt==0 ){
1561           if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1562             /* A compile-time error in the statement
1563             */
1564             Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1565             rc = TCL_ERROR;
1566             break;
1567           }else{
1568             /* The statement was a no-op.  Continue to the next statement
1569             ** in the SQL string.
1570             */
1571             zSql = zLeft;
1572             continue;
1573           }
1574         }
1575         assert( pPreStmt==0 );
1576       }
1577 
1578       /* Bind values to parameters that begin with $ or :
1579       */
1580       nVar = sqlite3_bind_parameter_count(pStmt);
1581       nParm = 0;
1582       if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
1583         apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
1584       }else{
1585         apParm = aParm;
1586       }
1587       for(i=1; i<=nVar; i++){
1588         const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1589         if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1590           Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1591           if( pVar ){
1592             int n;
1593             u8 *data;
1594             char *zType = pVar->typePtr ? pVar->typePtr->name : "";
1595             char c = zType[0];
1596             if( zVar[0]=='@' ||
1597                (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1598               /* Load a BLOB type if the Tcl variable is a bytearray and
1599               ** it has no string representation or the host
1600               ** parameter name begins with "@". */
1601               data = Tcl_GetByteArrayFromObj(pVar, &n);
1602               sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1603               Tcl_IncrRefCount(pVar);
1604               apParm[nParm++] = pVar;
1605             }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1606               Tcl_GetIntFromObj(interp, pVar, &n);
1607               sqlite3_bind_int(pStmt, i, n);
1608             }else if( c=='d' && strcmp(zType,"double")==0 ){
1609               double r;
1610               Tcl_GetDoubleFromObj(interp, pVar, &r);
1611               sqlite3_bind_double(pStmt, i, r);
1612             }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1613                   (c=='i' && strcmp(zType,"int")==0) ){
1614               Tcl_WideInt v;
1615               Tcl_GetWideIntFromObj(interp, pVar, &v);
1616               sqlite3_bind_int64(pStmt, i, v);
1617             }else{
1618               data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1619               sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1620               Tcl_IncrRefCount(pVar);
1621               apParm[nParm++] = pVar;
1622             }
1623           }else{
1624             sqlite3_bind_null( pStmt, i );
1625           }
1626         }
1627       }
1628 
1629       /* Compute column names */
1630       nCol = sqlite3_column_count(pStmt);
1631       if( pScript ){
1632         apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1633         if( apColName==0 ) break;
1634         for(i=0; i<nCol; i++){
1635           apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1636           Tcl_IncrRefCount(apColName[i]);
1637         }
1638       }
1639 
1640       /* If results are being stored in an array variable, then create
1641       ** the array(*) entry for that array
1642       */
1643       if( pArray ){
1644         Tcl_Obj *pColList = Tcl_NewObj();
1645         Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
1646         Tcl_IncrRefCount(pColList);
1647         for(i=0; i<nCol; i++){
1648           Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1649         }
1650         Tcl_ObjSetVar2(interp, pArray, pStar, pColList,0);
1651         Tcl_DecrRefCount(pColList);
1652         Tcl_DecrRefCount(pStar);
1653       }
1654 
1655       /* Execute the SQL
1656       */
1657       while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
1658         for(i=0; i<nCol; i++){
1659           Tcl_Obj *pVal;
1660 
1661           /* Set pVal to contain the i'th column of this row. */
1662           switch( sqlite3_column_type(pStmt, i) ){
1663             case SQLITE_BLOB: {
1664               int bytes = sqlite3_column_bytes(pStmt, i);
1665               pVal = Tcl_NewByteArrayObj(sqlite3_column_blob(pStmt, i), bytes);
1666               break;
1667             }
1668             case SQLITE_INTEGER: {
1669               sqlite_int64 v = sqlite3_column_int64(pStmt, i);
1670               if( v>=-2147483647 && v<=2147483647 ){
1671                 pVal = Tcl_NewIntObj(v);
1672               }else{
1673                 pVal = Tcl_NewWideIntObj(v);
1674               }
1675               break;
1676             }
1677             case SQLITE_FLOAT: {
1678               double r = sqlite3_column_double(pStmt, i);
1679               pVal = Tcl_NewDoubleObj(r);
1680               break;
1681             }
1682             case SQLITE_NULL: {
1683               pVal = dbTextToObj(pDb->zNull);
1684               break;
1685             }
1686             default: {
1687               pVal = dbTextToObj((char *)sqlite3_column_text(pStmt, i));
1688               break;
1689             }
1690           }
1691 
1692           if( pScript ){
1693             if( pArray==0 ){
1694               Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1695             }else{
1696               Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1697             }
1698           }else if( choice==DB_ONECOLUMN ){
1699             assert( pRet==0 );
1700             if( pRet==0 ){
1701               pRet = pVal;
1702               Tcl_IncrRefCount(pRet);
1703             }
1704             rc = TCL_BREAK;
1705             i = nCol;
1706           }else if( choice==DB_EXISTS ){
1707             Tcl_DecrRefCount(pRet);
1708             pRet = Tcl_NewBooleanObj(1);
1709             Tcl_IncrRefCount(pRet);
1710             rc = TCL_BREAK;
1711             i = nCol;
1712           }else{
1713             Tcl_ListObjAppendElement(interp, pRet, pVal);
1714           }
1715         }
1716 
1717         if( pScript ){
1718           rc = Tcl_EvalObjEx(interp, pScript, 0);
1719           if( rc==TCL_CONTINUE ){
1720             rc = TCL_OK;
1721           }
1722         }
1723       }
1724       if( rc==TCL_BREAK ){
1725         rc = TCL_OK;
1726       }
1727 
1728       /* Free the column name objects */
1729       if( pScript ){
1730         for(i=0; i<nCol; i++){
1731           Tcl_DecrRefCount(apColName[i]);
1732         }
1733         Tcl_Free((char*)apColName);
1734       }
1735 
1736       /* Free the bound string and blob parameters */
1737       for(i=0; i<nParm; i++){
1738         Tcl_DecrRefCount(apParm[i]);
1739       }
1740       if( apParm!=aParm ){
1741         Tcl_Free((char*)apParm);
1742       }
1743 
1744       /* Reset the statement.  If the result code is SQLITE_SCHEMA, then
1745       ** flush the statement cache and try the statement again.
1746       */
1747       rc2 = sqlite3_reset(pStmt);
1748       if( SQLITE_SCHEMA==rc2 ){
1749         /* After a schema change, flush the cache and try to run the
1750         ** statement again
1751         */
1752         flushStmtCache( pDb );
1753         sqlite3_finalize(pStmt);
1754         if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1755         continue;
1756       }else if( SQLITE_OK!=rc2 ){
1757         /* If a run-time error occurs, report the error and stop reading
1758         ** the SQL
1759         */
1760         Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1761         sqlite3_finalize(pStmt);
1762         rc = TCL_ERROR;
1763         if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1764         break;
1765       }else if( pDb->maxStmt<=0 ){
1766         /* If the cache is turned off, deallocated the statement */
1767         if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1768         sqlite3_finalize(pStmt);
1769       }else{
1770         /* Everything worked and the cache is operational.
1771         ** Create a new SqlPreparedStmt structure if we need one.
1772         ** (If we already have one we can just reuse it.)
1773         */
1774         if( pPreStmt==0 ){
1775           len = zLeft - zSql;
1776           pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) + len );
1777           if( pPreStmt==0 ) return TCL_ERROR;
1778           pPreStmt->pStmt = pStmt;
1779           pPreStmt->nSql = len;
1780           memcpy(pPreStmt->zSql, zSql, len);
1781           pPreStmt->zSql[len] = 0;
1782         }
1783 
1784         /* Add the prepared statement to the beginning of the cache list
1785         */
1786         pPreStmt->pNext = pDb->stmtList;
1787         pPreStmt->pPrev = 0;
1788         if( pDb->stmtList ){
1789          pDb->stmtList->pPrev = pPreStmt;
1790         }
1791         pDb->stmtList = pPreStmt;
1792         if( pDb->stmtLast==0 ){
1793           assert( pDb->nStmt==0 );
1794           pDb->stmtLast = pPreStmt;
1795         }else{
1796           assert( pDb->nStmt>0 );
1797         }
1798         pDb->nStmt++;
1799 
1800         /* If we have too many statement in cache, remove the surplus from the
1801         ** end of the cache list.
1802         */
1803         while( pDb->nStmt>pDb->maxStmt ){
1804           sqlite3_finalize(pDb->stmtLast->pStmt);
1805           pDb->stmtLast = pDb->stmtLast->pPrev;
1806           Tcl_Free((char*)pDb->stmtLast->pNext);
1807           pDb->stmtLast->pNext = 0;
1808           pDb->nStmt--;
1809         }
1810       }
1811 
1812       /* Proceed to the next statement */
1813       zSql = zLeft;
1814     }
1815     Tcl_DecrRefCount(objv[2]);
1816 
1817     if( pRet ){
1818       if( rc==TCL_OK ){
1819         Tcl_SetObjResult(interp, pRet);
1820       }
1821       Tcl_DecrRefCount(pRet);
1822     }else if( rc==TCL_OK ){
1823       Tcl_ResetResult(interp);
1824     }
1825     break;
1826   }
1827 
1828   /*
1829   **     $db function NAME SCRIPT
1830   **
1831   ** Create a new SQL function called NAME.  Whenever that function is
1832   ** called, invoke SCRIPT to evaluate the function.
1833   */
1834   case DB_FUNCTION: {
1835     SqlFunc *pFunc;
1836     Tcl_Obj *pScript;
1837     char *zName;
1838     if( objc!=4 ){
1839       Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1840       return TCL_ERROR;
1841     }
1842     zName = Tcl_GetStringFromObj(objv[2], 0);
1843     pScript = objv[3];
1844     pFunc = findSqlFunc(pDb, zName);
1845     if( pFunc==0 ) return TCL_ERROR;
1846     if( pFunc->pScript ){
1847       Tcl_DecrRefCount(pFunc->pScript);
1848     }
1849     pFunc->pScript = pScript;
1850     Tcl_IncrRefCount(pScript);
1851     pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
1852     rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
1853         pFunc, tclSqlFunc, 0, 0);
1854     if( rc!=SQLITE_OK ){
1855       rc = TCL_ERROR;
1856       Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
1857     }else{
1858       /* Must flush any cached statements */
1859       flushStmtCache( pDb );
1860     }
1861     break;
1862   }
1863 
1864   /*
1865   **     $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
1866   */
1867   case DB_INCRBLOB: {
1868 #ifdef SQLITE_OMIT_INCRBLOB
1869     Tcl_AppendResult(interp, "incrblob not available in this build", 0);
1870     return TCL_ERROR;
1871 #else
1872     int isReadonly = 0;
1873     const char *zDb = "main";
1874     const char *zTable;
1875     const char *zColumn;
1876     sqlite_int64 iRow;
1877 
1878     /* Check for the -readonly option */
1879     if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
1880       isReadonly = 1;
1881     }
1882 
1883     if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
1884       Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
1885       return TCL_ERROR;
1886     }
1887 
1888     if( objc==(6+isReadonly) ){
1889       zDb = Tcl_GetString(objv[2]);
1890     }
1891     zTable = Tcl_GetString(objv[objc-3]);
1892     zColumn = Tcl_GetString(objv[objc-2]);
1893     rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
1894 
1895     if( rc==TCL_OK ){
1896       rc = createIncrblobChannel(
1897           interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
1898       );
1899     }
1900 #endif
1901     break;
1902   }
1903 
1904   /*
1905   **     $db interrupt
1906   **
1907   ** Interrupt the execution of the inner-most SQL interpreter.  This
1908   ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
1909   */
1910   case DB_INTERRUPT: {
1911     sqlite3_interrupt(pDb->db);
1912     break;
1913   }
1914 
1915   /*
1916   **     $db nullvalue ?STRING?
1917   **
1918   ** Change text used when a NULL comes back from the database. If ?STRING?
1919   ** is not present, then the current string used for NULL is returned.
1920   ** If STRING is present, then STRING is returned.
1921   **
1922   */
1923   case DB_NULLVALUE: {
1924     if( objc!=2 && objc!=3 ){
1925       Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
1926       return TCL_ERROR;
1927     }
1928     if( objc==3 ){
1929       int len;
1930       char *zNull = Tcl_GetStringFromObj(objv[2], &len);
1931       if( pDb->zNull ){
1932         Tcl_Free(pDb->zNull);
1933       }
1934       if( zNull && len>0 ){
1935         pDb->zNull = Tcl_Alloc( len + 1 );
1936         strncpy(pDb->zNull, zNull, len);
1937         pDb->zNull[len] = '\0';
1938       }else{
1939         pDb->zNull = 0;
1940       }
1941     }
1942     Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
1943     break;
1944   }
1945 
1946   /*
1947   **     $db last_insert_rowid
1948   **
1949   ** Return an integer which is the ROWID for the most recent insert.
1950   */
1951   case DB_LAST_INSERT_ROWID: {
1952     Tcl_Obj *pResult;
1953     Tcl_WideInt rowid;
1954     if( objc!=2 ){
1955       Tcl_WrongNumArgs(interp, 2, objv, "");
1956       return TCL_ERROR;
1957     }
1958     rowid = sqlite3_last_insert_rowid(pDb->db);
1959     pResult = Tcl_GetObjResult(interp);
1960     Tcl_SetWideIntObj(pResult, rowid);
1961     break;
1962   }
1963 
1964   /*
1965   ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
1966   */
1967 
1968   /*    $db progress ?N CALLBACK?
1969   **
1970   ** Invoke the given callback every N virtual machine opcodes while executing
1971   ** queries.
1972   */
1973   case DB_PROGRESS: {
1974     if( objc==2 ){
1975       if( pDb->zProgress ){
1976         Tcl_AppendResult(interp, pDb->zProgress, 0);
1977       }
1978     }else if( objc==4 ){
1979       char *zProgress;
1980       int len;
1981       int N;
1982       if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
1983 	return TCL_ERROR;
1984       };
1985       if( pDb->zProgress ){
1986         Tcl_Free(pDb->zProgress);
1987       }
1988       zProgress = Tcl_GetStringFromObj(objv[3], &len);
1989       if( zProgress && len>0 ){
1990         pDb->zProgress = Tcl_Alloc( len + 1 );
1991         memcpy(pDb->zProgress, zProgress, len+1);
1992       }else{
1993         pDb->zProgress = 0;
1994       }
1995 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1996       if( pDb->zProgress ){
1997         pDb->interp = interp;
1998         sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
1999       }else{
2000         sqlite3_progress_handler(pDb->db, 0, 0, 0);
2001       }
2002 #endif
2003     }else{
2004       Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
2005       return TCL_ERROR;
2006     }
2007     break;
2008   }
2009 
2010   /*    $db profile ?CALLBACK?
2011   **
2012   ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2013   ** that has run.  The text of the SQL and the amount of elapse time are
2014   ** appended to CALLBACK before the script is run.
2015   */
2016   case DB_PROFILE: {
2017     if( objc>3 ){
2018       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2019       return TCL_ERROR;
2020     }else if( objc==2 ){
2021       if( pDb->zProfile ){
2022         Tcl_AppendResult(interp, pDb->zProfile, 0);
2023       }
2024     }else{
2025       char *zProfile;
2026       int len;
2027       if( pDb->zProfile ){
2028         Tcl_Free(pDb->zProfile);
2029       }
2030       zProfile = Tcl_GetStringFromObj(objv[2], &len);
2031       if( zProfile && len>0 ){
2032         pDb->zProfile = Tcl_Alloc( len + 1 );
2033         memcpy(pDb->zProfile, zProfile, len+1);
2034       }else{
2035         pDb->zProfile = 0;
2036       }
2037 #ifndef SQLITE_OMIT_TRACE
2038       if( pDb->zProfile ){
2039         pDb->interp = interp;
2040         sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2041       }else{
2042         sqlite3_profile(pDb->db, 0, 0);
2043       }
2044 #endif
2045     }
2046     break;
2047   }
2048 
2049   /*
2050   **     $db rekey KEY
2051   **
2052   ** Change the encryption key on the currently open database.
2053   */
2054   case DB_REKEY: {
2055     int nKey;
2056     void *pKey;
2057     if( objc!=3 ){
2058       Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2059       return TCL_ERROR;
2060     }
2061     pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
2062 #ifdef SQLITE_HAS_CODEC
2063     rc = sqlite3_rekey(pDb->db, pKey, nKey);
2064     if( rc ){
2065       Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
2066       rc = TCL_ERROR;
2067     }
2068 #endif
2069     break;
2070   }
2071 
2072   /*
2073   **     $db timeout MILLESECONDS
2074   **
2075   ** Delay for the number of milliseconds specified when a file is locked.
2076   */
2077   case DB_TIMEOUT: {
2078     int ms;
2079     if( objc!=3 ){
2080       Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
2081       return TCL_ERROR;
2082     }
2083     if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
2084     sqlite3_busy_timeout(pDb->db, ms);
2085     break;
2086   }
2087 
2088   /*
2089   **     $db total_changes
2090   **
2091   ** Return the number of rows that were modified, inserted, or deleted
2092   ** since the database handle was created.
2093   */
2094   case DB_TOTAL_CHANGES: {
2095     Tcl_Obj *pResult;
2096     if( objc!=2 ){
2097       Tcl_WrongNumArgs(interp, 2, objv, "");
2098       return TCL_ERROR;
2099     }
2100     pResult = Tcl_GetObjResult(interp);
2101     Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2102     break;
2103   }
2104 
2105   /*    $db trace ?CALLBACK?
2106   **
2107   ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2108   ** that is executed.  The text of the SQL is appended to CALLBACK before
2109   ** it is executed.
2110   */
2111   case DB_TRACE: {
2112     if( objc>3 ){
2113       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2114       return TCL_ERROR;
2115     }else if( objc==2 ){
2116       if( pDb->zTrace ){
2117         Tcl_AppendResult(interp, pDb->zTrace, 0);
2118       }
2119     }else{
2120       char *zTrace;
2121       int len;
2122       if( pDb->zTrace ){
2123         Tcl_Free(pDb->zTrace);
2124       }
2125       zTrace = Tcl_GetStringFromObj(objv[2], &len);
2126       if( zTrace && len>0 ){
2127         pDb->zTrace = Tcl_Alloc( len + 1 );
2128         memcpy(pDb->zTrace, zTrace, len+1);
2129       }else{
2130         pDb->zTrace = 0;
2131       }
2132 #ifndef SQLITE_OMIT_TRACE
2133       if( pDb->zTrace ){
2134         pDb->interp = interp;
2135         sqlite3_trace(pDb->db, DbTraceHandler, pDb);
2136       }else{
2137         sqlite3_trace(pDb->db, 0, 0);
2138       }
2139 #endif
2140     }
2141     break;
2142   }
2143 
2144   /*    $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2145   **
2146   ** Start a new transaction (if we are not already in the midst of a
2147   ** transaction) and execute the TCL script SCRIPT.  After SCRIPT
2148   ** completes, either commit the transaction or roll it back if SCRIPT
2149   ** throws an exception.  Or if no new transation was started, do nothing.
2150   ** pass the exception on up the stack.
2151   **
2152   ** This command was inspired by Dave Thomas's talk on Ruby at the
2153   ** 2005 O'Reilly Open Source Convention (OSCON).
2154   */
2155   case DB_TRANSACTION: {
2156     int inTrans;
2157     Tcl_Obj *pScript;
2158     const char *zBegin = "BEGIN";
2159     if( objc!=3 && objc!=4 ){
2160       Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2161       return TCL_ERROR;
2162     }
2163     if( objc==3 ){
2164       pScript = objv[2];
2165     } else {
2166       static const char *TTYPE_strs[] = {
2167         "deferred",   "exclusive",  "immediate", 0
2168       };
2169       enum TTYPE_enum {
2170         TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2171       };
2172       int ttype;
2173       if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
2174                               0, &ttype) ){
2175         return TCL_ERROR;
2176       }
2177       switch( (enum TTYPE_enum)ttype ){
2178         case TTYPE_DEFERRED:    /* no-op */;                 break;
2179         case TTYPE_EXCLUSIVE:   zBegin = "BEGIN EXCLUSIVE";  break;
2180         case TTYPE_IMMEDIATE:   zBegin = "BEGIN IMMEDIATE";  break;
2181       }
2182       pScript = objv[3];
2183     }
2184     inTrans = !sqlite3_get_autocommit(pDb->db);
2185     if( !inTrans ){
2186       (void)sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2187     }
2188     rc = Tcl_EvalObjEx(interp, pScript, 0);
2189     if( !inTrans ){
2190       const char *zEnd;
2191       if( rc==TCL_ERROR ){
2192         zEnd = "ROLLBACK";
2193       } else {
2194         zEnd = "COMMIT";
2195       }
2196       if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
2197         sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
2198       }
2199     }
2200     break;
2201   }
2202 
2203   /*
2204   **    $db update_hook ?script?
2205   **    $db rollback_hook ?script?
2206   */
2207   case DB_UPDATE_HOOK:
2208   case DB_ROLLBACK_HOOK: {
2209 
2210     /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2211     ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2212     */
2213     Tcl_Obj **ppHook;
2214     if( choice==DB_UPDATE_HOOK ){
2215       ppHook = &pDb->pUpdateHook;
2216     }else{
2217       ppHook = &pDb->pRollbackHook;
2218     }
2219 
2220     if( objc!=2 && objc!=3 ){
2221        Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2222        return TCL_ERROR;
2223     }
2224     if( *ppHook ){
2225       Tcl_SetObjResult(interp, *ppHook);
2226       if( objc==3 ){
2227         Tcl_DecrRefCount(*ppHook);
2228         *ppHook = 0;
2229       }
2230     }
2231     if( objc==3 ){
2232       assert( !(*ppHook) );
2233       if( Tcl_GetCharLength(objv[2])>0 ){
2234         *ppHook = objv[2];
2235         Tcl_IncrRefCount(*ppHook);
2236       }
2237     }
2238 
2239     sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2240     sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
2241 
2242     break;
2243   }
2244 
2245   /*    $db version
2246   **
2247   ** Return the version string for this database.
2248   */
2249   case DB_VERSION: {
2250     Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2251     break;
2252   }
2253 
2254 
2255   } /* End of the SWITCH statement */
2256   return rc;
2257 }
2258 
2259 /*
2260 **   sqlite3 DBNAME FILENAME ?MODE? ?-key KEY?
2261 **
2262 ** This is the main Tcl command.  When the "sqlite" Tcl command is
2263 ** invoked, this routine runs to process that command.
2264 **
2265 ** The first argument, DBNAME, is an arbitrary name for a new
2266 ** database connection.  This command creates a new command named
2267 ** DBNAME that is used to control that connection.  The database
2268 ** connection is deleted when the DBNAME command is deleted.
2269 **
2270 ** The second argument is the name of the directory that contains
2271 ** the sqlite database that is to be accessed.
2272 **
2273 ** For testing purposes, we also support the following:
2274 **
2275 **  sqlite3 -encoding
2276 **
2277 **       Return the encoding used by LIKE and GLOB operators.  Choices
2278 **       are UTF-8 and iso8859.
2279 **
2280 **  sqlite3 -version
2281 **
2282 **       Return the version number of the SQLite library.
2283 **
2284 **  sqlite3 -tcl-uses-utf
2285 **
2286 **       Return "1" if compiled with a Tcl uses UTF-8.  Return "0" if
2287 **       not.  Used by tests to make sure the library was compiled
2288 **       correctly.
2289 */
2290 static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
2291   SqliteDb *p;
2292   void *pKey = 0;
2293   int nKey = 0;
2294   const char *zArg;
2295   char *zErrMsg;
2296   const char *zFile;
2297   Tcl_DString translatedFilename;
2298   if( objc==2 ){
2299     zArg = Tcl_GetStringFromObj(objv[1], 0);
2300     if( strcmp(zArg,"-version")==0 ){
2301       Tcl_AppendResult(interp,sqlite3_version,0);
2302       return TCL_OK;
2303     }
2304     if( strcmp(zArg,"-has-codec")==0 ){
2305 #ifdef SQLITE_HAS_CODEC
2306       Tcl_AppendResult(interp,"1",0);
2307 #else
2308       Tcl_AppendResult(interp,"0",0);
2309 #endif
2310       return TCL_OK;
2311     }
2312     if( strcmp(zArg,"-tcl-uses-utf")==0 ){
2313 #ifdef TCL_UTF_MAX
2314       Tcl_AppendResult(interp,"1",0);
2315 #else
2316       Tcl_AppendResult(interp,"0",0);
2317 #endif
2318       return TCL_OK;
2319     }
2320   }
2321   if( objc==5 || objc==6 ){
2322     zArg = Tcl_GetStringFromObj(objv[objc-2], 0);
2323     if( strcmp(zArg,"-key")==0 ){
2324       pKey = Tcl_GetByteArrayFromObj(objv[objc-1], &nKey);
2325       objc -= 2;
2326     }
2327   }
2328   if( objc!=3 && objc!=4 ){
2329     Tcl_WrongNumArgs(interp, 1, objv,
2330 #ifdef SQLITE_HAS_CODEC
2331       "HANDLE FILENAME ?-key CODEC-KEY?"
2332 #else
2333       "HANDLE FILENAME ?MODE?"
2334 #endif
2335     );
2336     return TCL_ERROR;
2337   }
2338   zErrMsg = 0;
2339   p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
2340   if( p==0 ){
2341     Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
2342     return TCL_ERROR;
2343   }
2344   memset(p, 0, sizeof(*p));
2345   zFile = Tcl_GetStringFromObj(objv[2], 0);
2346   zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
2347   sqlite3_open(zFile, &p->db);
2348   Tcl_DStringFree(&translatedFilename);
2349   if( SQLITE_OK!=sqlite3_errcode(p->db) ){
2350     zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
2351     sqlite3_close(p->db);
2352     p->db = 0;
2353   }
2354 #ifdef SQLITE_HAS_CODEC
2355   sqlite3_key(p->db, pKey, nKey);
2356 #endif
2357   if( p->db==0 ){
2358     Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
2359     Tcl_Free((char*)p);
2360     sqlite3_free(zErrMsg);
2361     return TCL_ERROR;
2362   }
2363   p->maxStmt = NUM_PREPARED_STMTS;
2364   p->interp = interp;
2365   zArg = Tcl_GetStringFromObj(objv[1], 0);
2366   Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
2367 
2368   /* If compiled with SQLITE_TEST turned on, then register the "md5sum"
2369   ** SQL function.
2370   */
2371 #ifdef SQLITE_TEST
2372   {
2373     extern void Md5_Register(sqlite3*);
2374 #ifdef SQLITE_MEMDEBUG
2375     int mallocfail = sqlite3_iMallocFail;
2376     sqlite3_iMallocFail = 0;
2377 #endif
2378     Md5_Register(p->db);
2379 #ifdef SQLITE_MEMDEBUG
2380     sqlite3_iMallocFail = mallocfail;
2381 #endif
2382   }
2383 #endif
2384   return TCL_OK;
2385 }
2386 
2387 /*
2388 ** Provide a dummy Tcl_InitStubs if we are using this as a static
2389 ** library.
2390 */
2391 #ifndef USE_TCL_STUBS
2392 # undef  Tcl_InitStubs
2393 # define Tcl_InitStubs(a,b,c)
2394 #endif
2395 
2396 /*
2397 ** Make sure we have a PACKAGE_VERSION macro defined.  This will be
2398 ** defined automatically by the TEA makefile.  But other makefiles
2399 ** do not define it.
2400 */
2401 #ifndef PACKAGE_VERSION
2402 # define PACKAGE_VERSION SQLITE_VERSION
2403 #endif
2404 
2405 /*
2406 ** Initialize this module.
2407 **
2408 ** This Tcl module contains only a single new Tcl command named "sqlite".
2409 ** (Hence there is no namespace.  There is no point in using a namespace
2410 ** if the extension only supplies one new name!)  The "sqlite" command is
2411 ** used to open a new SQLite database.  See the DbMain() routine above
2412 ** for additional information.
2413 */
2414 EXTERN int Sqlite3_Init(Tcl_Interp *interp){
2415   Tcl_InitStubs(interp, "8.4", 0);
2416   Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
2417   Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
2418   Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
2419   Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
2420   return TCL_OK;
2421 }
2422 EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2423 EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2424 EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2425 
2426 #ifndef SQLITE_3_SUFFIX_ONLY
2427 EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2428 EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2429 EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2430 EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2431 #endif
2432 
2433 #ifdef TCLSH
2434 /*****************************************************************************
2435 ** The code that follows is used to build standalone TCL interpreters
2436 */
2437 
2438 /*
2439 ** If the macro TCLSH is one, then put in code this for the
2440 ** "main" routine that will initialize Tcl and take input from
2441 ** standard input.
2442 */
2443 #if TCLSH==1
2444 static char zMainloop[] =
2445   "set line {}\n"
2446   "while {![eof stdin]} {\n"
2447     "if {$line!=\"\"} {\n"
2448       "puts -nonewline \"> \"\n"
2449     "} else {\n"
2450       "puts -nonewline \"% \"\n"
2451     "}\n"
2452     "flush stdout\n"
2453     "append line [gets stdin]\n"
2454     "if {[info complete $line]} {\n"
2455       "if {[catch {uplevel #0 $line} result]} {\n"
2456         "puts stderr \"Error: $result\"\n"
2457       "} elseif {$result!=\"\"} {\n"
2458         "puts $result\n"
2459       "}\n"
2460       "set line {}\n"
2461     "} else {\n"
2462       "append line \\n\n"
2463     "}\n"
2464   "}\n"
2465 ;
2466 #endif
2467 
2468 /*
2469 ** If the macro TCLSH is two, then get the main loop code out of
2470 ** the separate file "spaceanal_tcl.h".
2471 */
2472 #if TCLSH==2
2473 static char zMainloop[] =
2474 #include "spaceanal_tcl.h"
2475 ;
2476 #endif
2477 
2478 #define TCLSH_MAIN main   /* Needed to fake out mktclapp */
2479 int TCLSH_MAIN(int argc, char **argv){
2480   Tcl_Interp *interp;
2481   Tcl_FindExecutable(argv[0]);
2482   interp = Tcl_CreateInterp();
2483   Sqlite3_Init(interp);
2484 #ifdef SQLITE_TEST
2485   {
2486     extern int Sqlitetest1_Init(Tcl_Interp*);
2487     extern int Sqlitetest2_Init(Tcl_Interp*);
2488     extern int Sqlitetest3_Init(Tcl_Interp*);
2489     extern int Sqlitetest4_Init(Tcl_Interp*);
2490     extern int Sqlitetest5_Init(Tcl_Interp*);
2491     extern int Sqlitetest6_Init(Tcl_Interp*);
2492     extern int Sqlitetest7_Init(Tcl_Interp*);
2493     extern int Sqlitetest8_Init(Tcl_Interp*);
2494     extern int Sqlitetest9_Init(Tcl_Interp*);
2495     extern int Md5_Init(Tcl_Interp*);
2496     extern int Sqlitetestsse_Init(Tcl_Interp*);
2497     extern int Sqlitetestasync_Init(Tcl_Interp*);
2498     extern int Sqlitetesttclvar_Init(Tcl_Interp*);
2499     extern int Sqlitetestschema_Init(Tcl_Interp*);
2500     extern int Sqlitetest_autoext_Init(Tcl_Interp*);
2501     extern int Sqlitetest_hexio_Init(Tcl_Interp*);
2502     extern int Sqliteconfig_Init(Tcl_Interp*);
2503 
2504     Sqlitetest1_Init(interp);
2505     Sqlitetest2_Init(interp);
2506     Sqlitetest3_Init(interp);
2507     Sqlitetest4_Init(interp);
2508     Sqlitetest5_Init(interp);
2509     Sqlitetest6_Init(interp);
2510     Sqlitetest7_Init(interp);
2511     Sqlitetest8_Init(interp);
2512     Sqlitetest9_Init(interp);
2513     Sqlitetestasync_Init(interp);
2514     Sqlitetesttclvar_Init(interp);
2515     Sqlitetestschema_Init(interp);
2516     Sqlitetest_autoext_Init(interp);
2517     Sqlitetest_hexio_Init(interp);
2518     Sqliteconfig_Init(interp);
2519     Md5_Init(interp);
2520 #ifdef SQLITE_SSE
2521     Sqlitetestsse_Init(interp);
2522 #endif
2523   }
2524 #endif
2525   if( argc>=2 || TCLSH==2 ){
2526     int i;
2527     char zArgc[32];
2528     sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
2529     Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
2530     Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
2531     Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
2532     for(i=3-TCLSH; i<argc; i++){
2533       Tcl_SetVar(interp, "argv", argv[i],
2534           TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
2535     }
2536     if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
2537       const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
2538       if( zInfo==0 ) zInfo = interp->result;
2539       fprintf(stderr,"%s: %s\n", *argv, zInfo);
2540       return 1;
2541     }
2542   }
2543   if( argc<=1 || TCLSH==2 ){
2544     Tcl_GlobalEval(interp, zMainloop);
2545   }
2546   return 0;
2547 }
2548 #endif /* TCLSH */
2549