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