Back to index

lightning-sunbird  0.9+nobinonly
tclsqlite.c
Go to the documentation of this file.
00001 /*
00002 ** 2001 September 15
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** A TCL Interface to SQLite
00013 **
00014 ** $Id: tclsqlite.c,v 1.156 2006/05/10 14:39:14 drh Exp $
00015 */
00016 #ifndef NO_TCL     /* Omit this whole file if TCL is unavailable */
00017 
00018 #include "sqliteInt.h"
00019 #include "hash.h"
00020 #include "tcl.h"
00021 #include <stdlib.h>
00022 #include <string.h>
00023 #include <assert.h>
00024 #include <ctype.h>
00025 
00026 
00027 #define NUM_PREPARED_STMTS 10
00028 #define MAX_PREPARED_STMTS 100
00029 
00030 /*
00031 ** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
00032 ** have to do a translation when going between the two.  Set the 
00033 ** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
00034 ** this translation.  
00035 */
00036 #if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
00037 # define UTF_TRANSLATION_NEEDED 1
00038 #endif
00039 
00040 /*
00041 ** New SQL functions can be created as TCL scripts.  Each such function
00042 ** is described by an instance of the following structure.
00043 */
00044 typedef struct SqlFunc SqlFunc;
00045 struct SqlFunc {
00046   Tcl_Interp *interp;   /* The TCL interpret to execute the function */
00047   Tcl_Obj *pScript;     /* The Tcl_Obj representation of the script */
00048   int useEvalObjv;      /* True if it is safe to use Tcl_EvalObjv */
00049   char *zName;          /* Name of this function */
00050   SqlFunc *pNext;       /* Next function on the list of them all */
00051 };
00052 
00053 /*
00054 ** New collation sequences function can be created as TCL scripts.  Each such
00055 ** function is described by an instance of the following structure.
00056 */
00057 typedef struct SqlCollate SqlCollate;
00058 struct SqlCollate {
00059   Tcl_Interp *interp;   /* The TCL interpret to execute the function */
00060   char *zScript;        /* The script to be run */
00061   SqlCollate *pNext;    /* Next function on the list of them all */
00062 };
00063 
00064 /*
00065 ** Prepared statements are cached for faster execution.  Each prepared
00066 ** statement is described by an instance of the following structure.
00067 */
00068 typedef struct SqlPreparedStmt SqlPreparedStmt;
00069 struct SqlPreparedStmt {
00070   SqlPreparedStmt *pNext;  /* Next in linked list */
00071   SqlPreparedStmt *pPrev;  /* Previous on the list */
00072   sqlite3_stmt *pStmt;     /* The prepared statement */
00073   int nSql;                /* chars in zSql[] */
00074   char zSql[1];            /* Text of the SQL statement */
00075 };
00076 
00077 /*
00078 ** There is one instance of this structure for each SQLite database
00079 ** that has been opened by the SQLite TCL interface.
00080 */
00081 typedef struct SqliteDb SqliteDb;
00082 struct SqliteDb {
00083   sqlite3 *db;               /* The "real" database structure. MUST BE FIRST */
00084   Tcl_Interp *interp;        /* The interpreter used for this database */
00085   char *zBusy;               /* The busy callback routine */
00086   char *zCommit;             /* The commit hook callback routine */
00087   char *zTrace;              /* The trace callback routine */
00088   char *zProfile;            /* The profile callback routine */
00089   char *zProgress;           /* The progress callback routine */
00090   char *zAuth;               /* The authorization callback routine */
00091   char *zNull;               /* Text to substitute for an SQL NULL value */
00092   SqlFunc *pFunc;            /* List of SQL functions */
00093   Tcl_Obj *pUpdateHook;      /* Update hook script (if any) */
00094   Tcl_Obj *pRollbackHook;    /* Rollback hook script (if any) */
00095   SqlCollate *pCollate;      /* List of SQL collation functions */
00096   int rc;                    /* Return code of most recent sqlite3_exec() */
00097   Tcl_Obj *pCollateNeeded;   /* Collation needed script */
00098   SqlPreparedStmt *stmtList; /* List of prepared statements*/
00099   SqlPreparedStmt *stmtLast; /* Last statement in the list */
00100   int maxStmt;               /* The next maximum number of stmtList */
00101   int nStmt;                 /* Number of statements in stmtList */
00102 };
00103 
00104 /*
00105 ** Look at the script prefix in pCmd.  We will be executing this script
00106 ** after first appending one or more arguments.  This routine analyzes
00107 ** the script to see if it is safe to use Tcl_EvalObjv() on the script
00108 ** rather than the more general Tcl_EvalEx().  Tcl_EvalObjv() is much
00109 ** faster.
00110 **
00111 ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
00112 ** command name followed by zero or more arguments with no [...] or $
00113 ** or {...} or ; to be seen anywhere.  Most callback scripts consist
00114 ** of just a single procedure name and they meet this requirement.
00115 */
00116 static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
00117   /* We could try to do something with Tcl_Parse().  But we will instead
00118   ** just do a search for forbidden characters.  If any of the forbidden
00119   ** characters appear in pCmd, we will report the string as unsafe.
00120   */
00121   const char *z;
00122   int n;
00123   z = Tcl_GetStringFromObj(pCmd, &n);
00124   while( n-- > 0 ){
00125     int c = *(z++);
00126     if( c=='$' || c=='[' || c==';' ) return 0;
00127   }
00128   return 1;
00129 }
00130 
00131 /*
00132 ** Find an SqlFunc structure with the given name.  Or create a new
00133 ** one if an existing one cannot be found.  Return a pointer to the
00134 ** structure.
00135 */
00136 static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
00137   SqlFunc *p, *pNew;
00138   int i;
00139   pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen(zName) + 1 );
00140   pNew->zName = (char*)&pNew[1];
00141   for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
00142   pNew->zName[i] = 0;
00143   for(p=pDb->pFunc; p; p=p->pNext){ 
00144     if( strcmp(p->zName, pNew->zName)==0 ){
00145       Tcl_Free((char*)pNew);
00146       return p;
00147     }
00148   }
00149   pNew->interp = pDb->interp;
00150   pNew->pScript = 0;
00151   pNew->pNext = pDb->pFunc;
00152   pDb->pFunc = pNew;
00153   return pNew;
00154 }
00155 
00156 /*
00157 ** Finalize and free a list of prepared statements
00158 */
00159 static void flushStmtCache( SqliteDb *pDb ){
00160   SqlPreparedStmt *pPreStmt;
00161 
00162   while(  pDb->stmtList ){
00163     sqlite3_finalize( pDb->stmtList->pStmt );
00164     pPreStmt = pDb->stmtList;
00165     pDb->stmtList = pDb->stmtList->pNext;
00166     Tcl_Free( (char*)pPreStmt );
00167   }
00168   pDb->nStmt = 0;
00169   pDb->stmtLast = 0;
00170 }
00171 
00172 /*
00173 ** TCL calls this procedure when an sqlite3 database command is
00174 ** deleted.
00175 */
00176 static void DbDeleteCmd(void *db){
00177   SqliteDb *pDb = (SqliteDb*)db;
00178   flushStmtCache(pDb);
00179   sqlite3_close(pDb->db);
00180   while( pDb->pFunc ){
00181     SqlFunc *pFunc = pDb->pFunc;
00182     pDb->pFunc = pFunc->pNext;
00183     Tcl_DecrRefCount(pFunc->pScript);
00184     Tcl_Free((char*)pFunc);
00185   }
00186   while( pDb->pCollate ){
00187     SqlCollate *pCollate = pDb->pCollate;
00188     pDb->pCollate = pCollate->pNext;
00189     Tcl_Free((char*)pCollate);
00190   }
00191   if( pDb->zBusy ){
00192     Tcl_Free(pDb->zBusy);
00193   }
00194   if( pDb->zTrace ){
00195     Tcl_Free(pDb->zTrace);
00196   }
00197   if( pDb->zProfile ){
00198     Tcl_Free(pDb->zProfile);
00199   }
00200   if( pDb->zAuth ){
00201     Tcl_Free(pDb->zAuth);
00202   }
00203   if( pDb->zNull ){
00204     Tcl_Free(pDb->zNull);
00205   }
00206   if( pDb->pUpdateHook ){
00207     Tcl_DecrRefCount(pDb->pUpdateHook);
00208   }
00209   if( pDb->pRollbackHook ){
00210     Tcl_DecrRefCount(pDb->pRollbackHook);
00211   }
00212   if( pDb->pCollateNeeded ){
00213     Tcl_DecrRefCount(pDb->pCollateNeeded);
00214   }
00215   Tcl_Free((char*)pDb);
00216 }
00217 
00218 /*
00219 ** This routine is called when a database file is locked while trying
00220 ** to execute SQL.
00221 */
00222 static int DbBusyHandler(void *cd, int nTries){
00223   SqliteDb *pDb = (SqliteDb*)cd;
00224   int rc;
00225   char zVal[30];
00226 
00227   sprintf(zVal, "%d", nTries);
00228   rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
00229   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
00230     return 0;
00231   }
00232   return 1;
00233 }
00234 
00235 /*
00236 ** This routine is invoked as the 'progress callback' for the database.
00237 */
00238 static int DbProgressHandler(void *cd){
00239   SqliteDb *pDb = (SqliteDb*)cd;
00240   int rc;
00241 
00242   assert( pDb->zProgress );
00243   rc = Tcl_Eval(pDb->interp, pDb->zProgress);
00244   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
00245     return 1;
00246   }
00247   return 0;
00248 }
00249 
00250 #ifndef SQLITE_OMIT_TRACE
00251 /*
00252 ** This routine is called by the SQLite trace handler whenever a new
00253 ** block of SQL is executed.  The TCL script in pDb->zTrace is executed.
00254 */
00255 static void DbTraceHandler(void *cd, const char *zSql){
00256   SqliteDb *pDb = (SqliteDb*)cd;
00257   Tcl_DString str;
00258 
00259   Tcl_DStringInit(&str);
00260   Tcl_DStringAppend(&str, pDb->zTrace, -1);
00261   Tcl_DStringAppendElement(&str, zSql);
00262   Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
00263   Tcl_DStringFree(&str);
00264   Tcl_ResetResult(pDb->interp);
00265 }
00266 #endif
00267 
00268 #ifndef SQLITE_OMIT_TRACE
00269 /*
00270 ** This routine is called by the SQLite profile handler after a statement
00271 ** SQL has executed.  The TCL script in pDb->zProfile is evaluated.
00272 */
00273 static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
00274   SqliteDb *pDb = (SqliteDb*)cd;
00275   Tcl_DString str;
00276   char zTm[100];
00277 
00278   sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
00279   Tcl_DStringInit(&str);
00280   Tcl_DStringAppend(&str, pDb->zProfile, -1);
00281   Tcl_DStringAppendElement(&str, zSql);
00282   Tcl_DStringAppendElement(&str, zTm);
00283   Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
00284   Tcl_DStringFree(&str);
00285   Tcl_ResetResult(pDb->interp);
00286 }
00287 #endif
00288 
00289 /*
00290 ** This routine is called when a transaction is committed.  The
00291 ** TCL script in pDb->zCommit is executed.  If it returns non-zero or
00292 ** if it throws an exception, the transaction is rolled back instead
00293 ** of being committed.
00294 */
00295 static int DbCommitHandler(void *cd){
00296   SqliteDb *pDb = (SqliteDb*)cd;
00297   int rc;
00298 
00299   rc = Tcl_Eval(pDb->interp, pDb->zCommit);
00300   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
00301     return 1;
00302   }
00303   return 0;
00304 }
00305 
00306 static void DbRollbackHandler(void *clientData){
00307   SqliteDb *pDb = (SqliteDb*)clientData;
00308   assert(pDb->pRollbackHook);
00309   if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
00310     Tcl_BackgroundError(pDb->interp);
00311   }
00312 }
00313 
00314 static void DbUpdateHandler(
00315   void *p, 
00316   int op,
00317   const char *zDb, 
00318   const char *zTbl, 
00319   sqlite_int64 rowid
00320 ){
00321   SqliteDb *pDb = (SqliteDb *)p;
00322   Tcl_Obj *pCmd;
00323 
00324   assert( pDb->pUpdateHook );
00325   assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
00326 
00327   pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
00328   Tcl_IncrRefCount(pCmd);
00329   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
00330     ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
00331   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
00332   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
00333   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
00334   Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
00335 }
00336 
00337 static void tclCollateNeeded(
00338   void *pCtx,
00339   sqlite3 *db,
00340   int enc,
00341   const char *zName
00342 ){
00343   SqliteDb *pDb = (SqliteDb *)pCtx;
00344   Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
00345   Tcl_IncrRefCount(pScript);
00346   Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
00347   Tcl_EvalObjEx(pDb->interp, pScript, 0);
00348   Tcl_DecrRefCount(pScript);
00349 }
00350 
00351 /*
00352 ** This routine is called to evaluate an SQL collation function implemented
00353 ** using TCL script.
00354 */
00355 static int tclSqlCollate(
00356   void *pCtx,
00357   int nA,
00358   const void *zA,
00359   int nB,
00360   const void *zB
00361 ){
00362   SqlCollate *p = (SqlCollate *)pCtx;
00363   Tcl_Obj *pCmd;
00364 
00365   pCmd = Tcl_NewStringObj(p->zScript, -1);
00366   Tcl_IncrRefCount(pCmd);
00367   Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
00368   Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
00369   Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
00370   Tcl_DecrRefCount(pCmd);
00371   return (atoi(Tcl_GetStringResult(p->interp)));
00372 }
00373 
00374 /*
00375 ** This routine is called to evaluate an SQL function implemented
00376 ** using TCL script.
00377 */
00378 static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
00379   SqlFunc *p = sqlite3_user_data(context);
00380   Tcl_Obj *pCmd;
00381   int i;
00382   int rc;
00383 
00384   if( argc==0 ){
00385     /* If there are no arguments to the function, call Tcl_EvalObjEx on the
00386     ** script object directly.  This allows the TCL compiler to generate
00387     ** bytecode for the command on the first invocation and thus make
00388     ** subsequent invocations much faster. */
00389     pCmd = p->pScript;
00390     Tcl_IncrRefCount(pCmd);
00391     rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
00392     Tcl_DecrRefCount(pCmd);
00393   }else{
00394     /* If there are arguments to the function, make a shallow copy of the
00395     ** script object, lappend the arguments, then evaluate the copy.
00396     **
00397     ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
00398     ** The new Tcl_Obj contains pointers to the original list elements. 
00399     ** That way, when Tcl_EvalObjv() is run and shimmers the first element
00400     ** of the list to tclCmdNameType, that alternate representation will
00401     ** be preserved and reused on the next invocation.
00402     */
00403     Tcl_Obj **aArg;
00404     int nArg;
00405     if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
00406       sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); 
00407       return;
00408     }     
00409     pCmd = Tcl_NewListObj(nArg, aArg);
00410     Tcl_IncrRefCount(pCmd);
00411     for(i=0; i<argc; i++){
00412       sqlite3_value *pIn = argv[i];
00413       Tcl_Obj *pVal;
00414             
00415       /* Set pVal to contain the i'th column of this row. */
00416       switch( sqlite3_value_type(pIn) ){
00417         case SQLITE_BLOB: {
00418           int bytes = sqlite3_value_bytes(pIn);
00419           pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
00420           break;
00421         }
00422         case SQLITE_INTEGER: {
00423           sqlite_int64 v = sqlite3_value_int64(pIn);
00424           if( v>=-2147483647 && v<=2147483647 ){
00425             pVal = Tcl_NewIntObj(v);
00426           }else{
00427             pVal = Tcl_NewWideIntObj(v);
00428           }
00429           break;
00430         }
00431         case SQLITE_FLOAT: {
00432           double r = sqlite3_value_double(pIn);
00433           pVal = Tcl_NewDoubleObj(r);
00434           break;
00435         }
00436         case SQLITE_NULL: {
00437           pVal = Tcl_NewStringObj("", 0);
00438           break;
00439         }
00440         default: {
00441           int bytes = sqlite3_value_bytes(pIn);
00442           pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
00443           break;
00444         }
00445       }
00446       rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
00447       if( rc ){
00448         Tcl_DecrRefCount(pCmd);
00449         sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); 
00450         return;
00451       }
00452     }
00453     if( !p->useEvalObjv ){
00454       /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
00455       ** is a list without a string representation.  To prevent this from
00456       ** happening, make sure pCmd has a valid string representation */
00457       Tcl_GetString(pCmd);
00458     }
00459     rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
00460     Tcl_DecrRefCount(pCmd);
00461   }
00462 
00463   if( rc && rc!=TCL_RETURN ){
00464     sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); 
00465   }else{
00466     Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
00467     int n;
00468     u8 *data;
00469     char *zType = pVar->typePtr ? pVar->typePtr->name : "";
00470     char c = zType[0];
00471     if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
00472       /* Only return a BLOB type if the Tcl variable is a bytearray and
00473       ** has no string representation. */
00474       data = Tcl_GetByteArrayFromObj(pVar, &n);
00475       sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
00476     }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
00477           (c=='i' && strcmp(zType,"int")==0) ){
00478       Tcl_GetIntFromObj(0, pVar, &n);
00479       sqlite3_result_int(context, n);
00480     }else if( c=='d' && strcmp(zType,"double")==0 ){
00481       double r;
00482       Tcl_GetDoubleFromObj(0, pVar, &r);
00483       sqlite3_result_double(context, r);
00484     }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
00485       Tcl_WideInt v;
00486       Tcl_GetWideIntFromObj(0, pVar, &v);
00487       sqlite3_result_int64(context, v);
00488     }else{
00489       data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
00490       sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
00491     }
00492   }
00493 }
00494 
00495 #ifndef SQLITE_OMIT_AUTHORIZATION
00496 /*
00497 ** This is the authentication function.  It appends the authentication
00498 ** type code and the two arguments to zCmd[] then invokes the result
00499 ** on the interpreter.  The reply is examined to determine if the
00500 ** authentication fails or succeeds.
00501 */
00502 static int auth_callback(
00503   void *pArg,
00504   int code,
00505   const char *zArg1,
00506   const char *zArg2,
00507   const char *zArg3,
00508   const char *zArg4
00509 ){
00510   char *zCode;
00511   Tcl_DString str;
00512   int rc;
00513   const char *zReply;
00514   SqliteDb *pDb = (SqliteDb*)pArg;
00515 
00516   switch( code ){
00517     case SQLITE_COPY              : zCode="SQLITE_COPY"; break;
00518     case SQLITE_CREATE_INDEX      : zCode="SQLITE_CREATE_INDEX"; break;
00519     case SQLITE_CREATE_TABLE      : zCode="SQLITE_CREATE_TABLE"; break;
00520     case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
00521     case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
00522     case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
00523     case SQLITE_CREATE_TEMP_VIEW  : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
00524     case SQLITE_CREATE_TRIGGER    : zCode="SQLITE_CREATE_TRIGGER"; break;
00525     case SQLITE_CREATE_VIEW       : zCode="SQLITE_CREATE_VIEW"; break;
00526     case SQLITE_DELETE            : zCode="SQLITE_DELETE"; break;
00527     case SQLITE_DROP_INDEX        : zCode="SQLITE_DROP_INDEX"; break;
00528     case SQLITE_DROP_TABLE        : zCode="SQLITE_DROP_TABLE"; break;
00529     case SQLITE_DROP_TEMP_INDEX   : zCode="SQLITE_DROP_TEMP_INDEX"; break;
00530     case SQLITE_DROP_TEMP_TABLE   : zCode="SQLITE_DROP_TEMP_TABLE"; break;
00531     case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
00532     case SQLITE_DROP_TEMP_VIEW    : zCode="SQLITE_DROP_TEMP_VIEW"; break;
00533     case SQLITE_DROP_TRIGGER      : zCode="SQLITE_DROP_TRIGGER"; break;
00534     case SQLITE_DROP_VIEW         : zCode="SQLITE_DROP_VIEW"; break;
00535     case SQLITE_INSERT            : zCode="SQLITE_INSERT"; break;
00536     case SQLITE_PRAGMA            : zCode="SQLITE_PRAGMA"; break;
00537     case SQLITE_READ              : zCode="SQLITE_READ"; break;
00538     case SQLITE_SELECT            : zCode="SQLITE_SELECT"; break;
00539     case SQLITE_TRANSACTION       : zCode="SQLITE_TRANSACTION"; break;
00540     case SQLITE_UPDATE            : zCode="SQLITE_UPDATE"; break;
00541     case SQLITE_ATTACH            : zCode="SQLITE_ATTACH"; break;
00542     case SQLITE_DETACH            : zCode="SQLITE_DETACH"; break;
00543     case SQLITE_ALTER_TABLE       : zCode="SQLITE_ALTER_TABLE"; break;
00544     case SQLITE_REINDEX           : zCode="SQLITE_REINDEX"; break;
00545     case SQLITE_ANALYZE           : zCode="SQLITE_ANALYZE"; break;
00546     default                       : zCode="????"; break;
00547   }
00548   Tcl_DStringInit(&str);
00549   Tcl_DStringAppend(&str, pDb->zAuth, -1);
00550   Tcl_DStringAppendElement(&str, zCode);
00551   Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
00552   Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
00553   Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
00554   Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
00555   rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
00556   Tcl_DStringFree(&str);
00557   zReply = Tcl_GetStringResult(pDb->interp);
00558   if( strcmp(zReply,"SQLITE_OK")==0 ){
00559     rc = SQLITE_OK;
00560   }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
00561     rc = SQLITE_DENY;
00562   }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
00563     rc = SQLITE_IGNORE;
00564   }else{
00565     rc = 999;
00566   }
00567   return rc;
00568 }
00569 #endif /* SQLITE_OMIT_AUTHORIZATION */
00570 
00571 /*
00572 ** zText is a pointer to text obtained via an sqlite3_result_text()
00573 ** or similar interface. This routine returns a Tcl string object, 
00574 ** reference count set to 0, containing the text. If a translation
00575 ** between iso8859 and UTF-8 is required, it is preformed.
00576 */
00577 static Tcl_Obj *dbTextToObj(char const *zText){
00578   Tcl_Obj *pVal;
00579 #ifdef UTF_TRANSLATION_NEEDED
00580   Tcl_DString dCol;
00581   Tcl_DStringInit(&dCol);
00582   Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
00583   pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
00584   Tcl_DStringFree(&dCol);
00585 #else
00586   pVal = Tcl_NewStringObj(zText, -1);
00587 #endif
00588   return pVal;
00589 }
00590 
00591 /*
00592 ** This routine reads a line of text from FILE in, stores
00593 ** the text in memory obtained from malloc() and returns a pointer
00594 ** to the text.  NULL is returned at end of file, or if malloc()
00595 ** fails.
00596 **
00597 ** The interface is like "readline" but no command-line editing
00598 ** is done.
00599 **
00600 ** copied from shell.c from '.import' command
00601 */
00602 static char *local_getline(char *zPrompt, FILE *in){
00603   char *zLine;
00604   int nLine;
00605   int n;
00606   int eol;
00607 
00608   nLine = 100;
00609   zLine = malloc( nLine );
00610   if( zLine==0 ) return 0;
00611   n = 0;
00612   eol = 0;
00613   while( !eol ){
00614     if( n+100>nLine ){
00615       nLine = nLine*2 + 100;
00616       zLine = realloc(zLine, nLine);
00617       if( zLine==0 ) return 0;
00618     }
00619     if( fgets(&zLine[n], nLine - n, in)==0 ){
00620       if( n==0 ){
00621         free(zLine);
00622         return 0;
00623       }
00624       zLine[n] = 0;
00625       eol = 1;
00626       break;
00627     }
00628     while( zLine[n] ){ n++; }
00629     if( n>0 && zLine[n-1]=='\n' ){
00630       n--;
00631       zLine[n] = 0;
00632       eol = 1;
00633     }
00634   }
00635   zLine = realloc( zLine, n+1 );
00636   return zLine;
00637 }
00638 
00639 /*
00640 ** The "sqlite" command below creates a new Tcl command for each
00641 ** connection it opens to an SQLite database.  This routine is invoked
00642 ** whenever one of those connection-specific commands is executed
00643 ** in Tcl.  For example, if you run Tcl code like this:
00644 **
00645 **       sqlite3 db1  "my_database"
00646 **       db1 close
00647 **
00648 ** The first command opens a connection to the "my_database" database
00649 ** and calls that connection "db1".  The second command causes this
00650 ** subroutine to be invoked.
00651 */
00652 static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
00653   SqliteDb *pDb = (SqliteDb*)cd;
00654   int choice;
00655   int rc = TCL_OK;
00656   static const char *DB_strs[] = {
00657     "authorizer",         "busy",              "cache",
00658     "changes",            "close",             "collate",
00659     "collation_needed",   "commit_hook",       "complete",
00660     "copy",               "errorcode",         "eval",
00661     "exists",             "function",          "last_insert_rowid",
00662     "nullvalue",          "onecolumn",         "profile",
00663     "progress",           "rekey",             "rollback_hook",
00664     "timeout",            "total_changes",     "trace",
00665     "transaction",        "update_hook",       "version",
00666     0                    
00667   };
00668   enum DB_enum {
00669     DB_AUTHORIZER,        DB_BUSY,             DB_CACHE,
00670     DB_CHANGES,           DB_CLOSE,            DB_COLLATE,
00671     DB_COLLATION_NEEDED,  DB_COMMIT_HOOK,      DB_COMPLETE,
00672     DB_COPY,              DB_ERRORCODE,        DB_EVAL,
00673     DB_EXISTS,            DB_FUNCTION,         DB_LAST_INSERT_ROWID,
00674     DB_NULLVALUE,         DB_ONECOLUMN,        DB_PROFILE,
00675     DB_PROGRESS,          DB_REKEY,            DB_ROLLBACK_HOOK,
00676     DB_TIMEOUT,           DB_TOTAL_CHANGES,    DB_TRACE,
00677     DB_TRANSACTION,       DB_UPDATE_HOOK,      DB_VERSION
00678   };
00679   /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
00680 
00681   if( objc<2 ){
00682     Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
00683     return TCL_ERROR;
00684   }
00685   if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
00686     return TCL_ERROR;
00687   }
00688 
00689   switch( (enum DB_enum)choice ){
00690 
00691   /*    $db authorizer ?CALLBACK?
00692   **
00693   ** Invoke the given callback to authorize each SQL operation as it is
00694   ** compiled.  5 arguments are appended to the callback before it is
00695   ** invoked:
00696   **
00697   **   (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
00698   **   (2) First descriptive name (depends on authorization type)
00699   **   (3) Second descriptive name
00700   **   (4) Name of the database (ex: "main", "temp")
00701   **   (5) Name of trigger that is doing the access
00702   **
00703   ** The callback should return on of the following strings: SQLITE_OK,
00704   ** SQLITE_IGNORE, or SQLITE_DENY.  Any other return value is an error.
00705   **
00706   ** If this method is invoked with no arguments, the current authorization
00707   ** callback string is returned.
00708   */
00709   case DB_AUTHORIZER: {
00710 #ifdef SQLITE_OMIT_AUTHORIZATION
00711     Tcl_AppendResult(interp, "authorization not available in this build", 0);
00712     return TCL_ERROR;
00713 #else
00714     if( objc>3 ){
00715       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
00716       return TCL_ERROR;
00717     }else if( objc==2 ){
00718       if( pDb->zAuth ){
00719         Tcl_AppendResult(interp, pDb->zAuth, 0);
00720       }
00721     }else{
00722       char *zAuth;
00723       int len;
00724       if( pDb->zAuth ){
00725         Tcl_Free(pDb->zAuth);
00726       }
00727       zAuth = Tcl_GetStringFromObj(objv[2], &len);
00728       if( zAuth && len>0 ){
00729         pDb->zAuth = Tcl_Alloc( len + 1 );
00730         strcpy(pDb->zAuth, zAuth);
00731       }else{
00732         pDb->zAuth = 0;
00733       }
00734       if( pDb->zAuth ){
00735         pDb->interp = interp;
00736         sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
00737       }else{
00738         sqlite3_set_authorizer(pDb->db, 0, 0);
00739       }
00740     }
00741 #endif
00742     break;
00743   }
00744 
00745   /*    $db busy ?CALLBACK?
00746   **
00747   ** Invoke the given callback if an SQL statement attempts to open
00748   ** a locked database file.
00749   */
00750   case DB_BUSY: {
00751     if( objc>3 ){
00752       Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
00753       return TCL_ERROR;
00754     }else if( objc==2 ){
00755       if( pDb->zBusy ){
00756         Tcl_AppendResult(interp, pDb->zBusy, 0);
00757       }
00758     }else{
00759       char *zBusy;
00760       int len;
00761       if( pDb->zBusy ){
00762         Tcl_Free(pDb->zBusy);
00763       }
00764       zBusy = Tcl_GetStringFromObj(objv[2], &len);
00765       if( zBusy && len>0 ){
00766         pDb->zBusy = Tcl_Alloc( len + 1 );
00767         strcpy(pDb->zBusy, zBusy);
00768       }else{
00769         pDb->zBusy = 0;
00770       }
00771       if( pDb->zBusy ){
00772         pDb->interp = interp;
00773         sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
00774       }else{
00775         sqlite3_busy_handler(pDb->db, 0, 0);
00776       }
00777     }
00778     break;
00779   }
00780 
00781   /*     $db cache flush
00782   **     $db cache size n
00783   **
00784   ** Flush the prepared statement cache, or set the maximum number of
00785   ** cached statements.
00786   */
00787   case DB_CACHE: {
00788     char *subCmd;
00789     int n;
00790 
00791     if( objc<=2 ){
00792       Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
00793       return TCL_ERROR;
00794     }
00795     subCmd = Tcl_GetStringFromObj( objv[2], 0 );
00796     if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
00797       if( objc!=3 ){
00798         Tcl_WrongNumArgs(interp, 2, objv, "flush");
00799         return TCL_ERROR;
00800       }else{
00801         flushStmtCache( pDb );
00802       }
00803     }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
00804       if( objc!=4 ){
00805         Tcl_WrongNumArgs(interp, 2, objv, "size n");
00806         return TCL_ERROR;
00807       }else{
00808         if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
00809           Tcl_AppendResult( interp, "cannot convert \"", 
00810                Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
00811           return TCL_ERROR;
00812         }else{
00813           if( n<0 ){
00814             flushStmtCache( pDb );
00815             n = 0;
00816           }else if( n>MAX_PREPARED_STMTS ){
00817             n = MAX_PREPARED_STMTS;
00818           }
00819           pDb->maxStmt = n;
00820         }
00821       }
00822     }else{
00823       Tcl_AppendResult( interp, "bad option \"", 
00824           Tcl_GetStringFromObj(objv[0],0), "\": must be flush or size", 0);
00825       return TCL_ERROR;
00826     }
00827     break;
00828   }
00829 
00830   /*     $db changes
00831   **
00832   ** Return the number of rows that were modified, inserted, or deleted by
00833   ** the most recent INSERT, UPDATE or DELETE statement, not including 
00834   ** any changes made by trigger programs.
00835   */
00836   case DB_CHANGES: {
00837     Tcl_Obj *pResult;
00838     if( objc!=2 ){
00839       Tcl_WrongNumArgs(interp, 2, objv, "");
00840       return TCL_ERROR;
00841     }
00842     pResult = Tcl_GetObjResult(interp);
00843     Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
00844     break;
00845   }
00846 
00847   /*    $db close
00848   **
00849   ** Shutdown the database
00850   */
00851   case DB_CLOSE: {
00852     Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
00853     break;
00854   }
00855 
00856   /*
00857   **     $db collate NAME SCRIPT
00858   **
00859   ** Create a new SQL collation function called NAME.  Whenever
00860   ** that function is called, invoke SCRIPT to evaluate the function.
00861   */
00862   case DB_COLLATE: {
00863     SqlCollate *pCollate;
00864     char *zName;
00865     char *zScript;
00866     int nScript;
00867     if( objc!=4 ){
00868       Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
00869       return TCL_ERROR;
00870     }
00871     zName = Tcl_GetStringFromObj(objv[2], 0);
00872     zScript = Tcl_GetStringFromObj(objv[3], &nScript);
00873     pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
00874     if( pCollate==0 ) return TCL_ERROR;
00875     pCollate->interp = interp;
00876     pCollate->pNext = pDb->pCollate;
00877     pCollate->zScript = (char*)&pCollate[1];
00878     pDb->pCollate = pCollate;
00879     strcpy(pCollate->zScript, zScript);
00880     if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8, 
00881         pCollate, tclSqlCollate) ){
00882       Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
00883       return TCL_ERROR;
00884     }
00885     break;
00886   }
00887 
00888   /*
00889   **     $db collation_needed SCRIPT
00890   **
00891   ** Create a new SQL collation function called NAME.  Whenever
00892   ** that function is called, invoke SCRIPT to evaluate the function.
00893   */
00894   case DB_COLLATION_NEEDED: {
00895     if( objc!=3 ){
00896       Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
00897       return TCL_ERROR;
00898     }
00899     if( pDb->pCollateNeeded ){
00900       Tcl_DecrRefCount(pDb->pCollateNeeded);
00901     }
00902     pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
00903     Tcl_IncrRefCount(pDb->pCollateNeeded);
00904     sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
00905     break;
00906   }
00907 
00908   /*    $db commit_hook ?CALLBACK?
00909   **
00910   ** Invoke the given callback just before committing every SQL transaction.
00911   ** If the callback throws an exception or returns non-zero, then the
00912   ** transaction is aborted.  If CALLBACK is an empty string, the callback
00913   ** is disabled.
00914   */
00915   case DB_COMMIT_HOOK: {
00916     if( objc>3 ){
00917       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
00918       return TCL_ERROR;
00919     }else if( objc==2 ){
00920       if( pDb->zCommit ){
00921         Tcl_AppendResult(interp, pDb->zCommit, 0);
00922       }
00923     }else{
00924       char *zCommit;
00925       int len;
00926       if( pDb->zCommit ){
00927         Tcl_Free(pDb->zCommit);
00928       }
00929       zCommit = Tcl_GetStringFromObj(objv[2], &len);
00930       if( zCommit && len>0 ){
00931         pDb->zCommit = Tcl_Alloc( len + 1 );
00932         strcpy(pDb->zCommit, zCommit);
00933       }else{
00934         pDb->zCommit = 0;
00935       }
00936       if( pDb->zCommit ){
00937         pDb->interp = interp;
00938         sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
00939       }else{
00940         sqlite3_commit_hook(pDb->db, 0, 0);
00941       }
00942     }
00943     break;
00944   }
00945 
00946   /*    $db complete SQL
00947   **
00948   ** Return TRUE if SQL is a complete SQL statement.  Return FALSE if
00949   ** additional lines of input are needed.  This is similar to the
00950   ** built-in "info complete" command of Tcl.
00951   */
00952   case DB_COMPLETE: {
00953 #ifndef SQLITE_OMIT_COMPLETE
00954     Tcl_Obj *pResult;
00955     int isComplete;
00956     if( objc!=3 ){
00957       Tcl_WrongNumArgs(interp, 2, objv, "SQL");
00958       return TCL_ERROR;
00959     }
00960     isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
00961     pResult = Tcl_GetObjResult(interp);
00962     Tcl_SetBooleanObj(pResult, isComplete);
00963 #endif
00964     break;
00965   }
00966 
00967   /*    $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
00968   **
00969   ** Copy data into table from filename, optionally using SEPARATOR
00970   ** as column separators.  If a column contains a null string, or the
00971   ** value of NULLINDICATOR, a NULL is inserted for the column.
00972   ** conflict-algorithm is one of the sqlite conflict algorithms:
00973   **    rollback, abort, fail, ignore, replace
00974   ** On success, return the number of lines processed, not necessarily same
00975   ** as 'db changes' due to conflict-algorithm selected.
00976   **
00977   ** This code is basically an implementation/enhancement of
00978   ** the sqlite3 shell.c ".import" command.
00979   **
00980   ** This command usage is equivalent to the sqlite2.x COPY statement,
00981   ** which imports file data into a table using the PostgreSQL COPY file format:
00982   **   $db copy $conflit_algo $table_name $filename \t \\N
00983   */
00984   case DB_COPY: {
00985     char *zTable;               /* Insert data into this table */
00986     char *zFile;                /* The file from which to extract data */
00987     char *zConflict;            /* The conflict algorithm to use */
00988     sqlite3_stmt *pStmt;        /* A statement */
00989     int rc;                     /* Result code */
00990     int nCol;                   /* Number of columns in the table */
00991     int nByte;                  /* Number of bytes in an SQL string */
00992     int i, j;                   /* Loop counters */
00993     int nSep;                   /* Number of bytes in zSep[] */
00994     int nNull;                  /* Number of bytes in zNull[] */
00995     char *zSql;                 /* An SQL statement */
00996     char *zLine;                /* A single line of input from the file */
00997     char **azCol;               /* zLine[] broken up into columns */
00998     char *zCommit;              /* How to commit changes */
00999     FILE *in;                   /* The input file */
01000     int lineno = 0;             /* Line number of input file */
01001     char zLineNum[80];          /* Line number print buffer */
01002     Tcl_Obj *pResult;           /* interp result */
01003 
01004     char *zSep;
01005     char *zNull;
01006     if( objc<5 || objc>7 ){
01007       Tcl_WrongNumArgs(interp, 2, objv, 
01008          "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
01009       return TCL_ERROR;
01010     }
01011     if( objc>=6 ){
01012       zSep = Tcl_GetStringFromObj(objv[5], 0);
01013     }else{
01014       zSep = "\t";
01015     }
01016     if( objc>=7 ){
01017       zNull = Tcl_GetStringFromObj(objv[6], 0);
01018     }else{
01019       zNull = "";
01020     }
01021     zConflict = Tcl_GetStringFromObj(objv[2], 0);
01022     zTable = Tcl_GetStringFromObj(objv[3], 0);
01023     zFile = Tcl_GetStringFromObj(objv[4], 0);
01024     nSep = strlen(zSep);
01025     nNull = strlen(zNull);
01026     if( nSep==0 ){
01027       Tcl_AppendResult(interp, "Error: non-null separator required for copy", 0);
01028       return TCL_ERROR;
01029     }
01030     if(sqlite3StrICmp(zConflict, "rollback") != 0 &&
01031        sqlite3StrICmp(zConflict, "abort"   ) != 0 &&
01032        sqlite3StrICmp(zConflict, "fail"    ) != 0 &&
01033        sqlite3StrICmp(zConflict, "ignore"  ) != 0 &&
01034        sqlite3StrICmp(zConflict, "replace" ) != 0 ) {
01035       Tcl_AppendResult(interp, "Error: \"", zConflict, 
01036             "\", conflict-algorithm must be one of: rollback, "
01037             "abort, fail, ignore, or replace", 0);
01038       return TCL_ERROR;
01039     }
01040     zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
01041     if( zSql==0 ){
01042       Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
01043       return TCL_ERROR;
01044     }
01045     nByte = strlen(zSql);
01046     rc = sqlite3_prepare(pDb->db, zSql, 0, &pStmt, 0);
01047     sqlite3_free(zSql);
01048     if( rc ){
01049       Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
01050       nCol = 0;
01051     }else{
01052       nCol = sqlite3_column_count(pStmt);
01053     }
01054     sqlite3_finalize(pStmt);
01055     if( nCol==0 ) {
01056       return TCL_ERROR;
01057     }
01058     zSql = malloc( nByte + 50 + nCol*2 );
01059     if( zSql==0 ) {
01060       Tcl_AppendResult(interp, "Error: can't malloc()", 0);
01061       return TCL_ERROR;
01062     }
01063     sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
01064          zConflict, zTable);
01065     j = strlen(zSql);
01066     for(i=1; i<nCol; i++){
01067       zSql[j++] = ',';
01068       zSql[j++] = '?';
01069     }
01070     zSql[j++] = ')';
01071     zSql[j] = 0;
01072     rc = sqlite3_prepare(pDb->db, zSql, 0, &pStmt, 0);
01073     free(zSql);
01074     if( rc ){
01075       Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
01076       sqlite3_finalize(pStmt);
01077       return TCL_ERROR;
01078     }
01079     in = fopen(zFile, "rb");
01080     if( in==0 ){
01081       Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
01082       sqlite3_finalize(pStmt);
01083       return TCL_ERROR;
01084     }
01085     azCol = malloc( sizeof(azCol[0])*(nCol+1) );
01086     if( azCol==0 ) {
01087       Tcl_AppendResult(interp, "Error: can't malloc()", 0);
01088       fclose(in);
01089       return TCL_ERROR;
01090     }
01091     (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
01092     zCommit = "COMMIT";
01093     while( (zLine = local_getline(0, in))!=0 ){
01094       char *z;
01095       i = 0;
01096       lineno++;
01097       azCol[0] = zLine;
01098       for(i=0, z=zLine; *z; z++){
01099         if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
01100           *z = 0;
01101           i++;
01102           if( i<nCol ){
01103             azCol[i] = &z[nSep];
01104             z += nSep-1;
01105           }
01106         }
01107       }
01108       if( i+1!=nCol ){
01109         char *zErr;
01110         zErr = malloc(200 + strlen(zFile));
01111         if( zErr ){
01112           sprintf(zErr,
01113              "Error: %s line %d: expected %d columns of data but found %d",
01114              zFile, lineno, nCol, i+1);
01115           Tcl_AppendResult(interp, zErr, 0);
01116           free(zErr);
01117         }
01118         zCommit = "ROLLBACK";
01119         break;
01120       }
01121       for(i=0; i<nCol; i++){
01122         /* check for null data, if so, bind as null */
01123         if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
01124           sqlite3_bind_null(pStmt, i+1);
01125         }else{
01126           sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
01127         }
01128       }
01129       sqlite3_step(pStmt);
01130       rc = sqlite3_reset(pStmt);
01131       free(zLine);
01132       if( rc!=SQLITE_OK ){
01133         Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
01134         zCommit = "ROLLBACK";
01135         break;
01136       }
01137     }
01138     free(azCol);
01139     fclose(in);
01140     sqlite3_finalize(pStmt);
01141     (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
01142 
01143     if( zCommit[0] == 'C' ){
01144       /* success, set result as number of lines processed */
01145       pResult = Tcl_GetObjResult(interp);
01146       Tcl_SetIntObj(pResult, lineno);
01147       rc = TCL_OK;
01148     }else{
01149       /* failure, append lineno where failed */
01150       sprintf(zLineNum,"%d",lineno);
01151       Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
01152       rc = TCL_ERROR;
01153     }
01154     break;
01155   }
01156 
01157   /*
01158   **    $db errorcode
01159   **
01160   ** Return the numeric error code that was returned by the most recent
01161   ** call to sqlite3_exec().
01162   */
01163   case DB_ERRORCODE: {
01164     Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
01165     break;
01166   }
01167    
01168   /*
01169   **    $db eval $sql ?array? ?{  ...code... }?
01170   **    $db onecolumn $sql
01171   **
01172   ** The SQL statement in $sql is evaluated.  For each row, the values are
01173   ** placed in elements of the array named "array" and ...code... is executed.
01174   ** If "array" and "code" are omitted, then no callback is every invoked.
01175   ** If "array" is an empty string, then the values are placed in variables
01176   ** that have the same name as the fields extracted by the query.
01177   **
01178   ** The onecolumn method is the equivalent of:
01179   **     lindex [$db eval $sql] 0
01180   */
01181   case DB_ONECOLUMN:
01182   case DB_EVAL:
01183   case DB_EXISTS: {
01184     char const *zSql;      /* Next SQL statement to execute */
01185     char const *zLeft;     /* What is left after first stmt in zSql */
01186     sqlite3_stmt *pStmt;   /* Compiled SQL statment */
01187     Tcl_Obj *pArray;       /* Name of array into which results are written */
01188     Tcl_Obj *pScript;      /* Script to run for each result set */
01189     Tcl_Obj **apParm;      /* Parameters that need a Tcl_DecrRefCount() */
01190     int nParm;             /* Number of entries used in apParm[] */
01191     Tcl_Obj *aParm[10];    /* Static space for apParm[] in the common case */
01192     Tcl_Obj *pRet;         /* Value to be returned */
01193     SqlPreparedStmt *pPreStmt;  /* Pointer to a prepared statement */
01194     int rc2;
01195 
01196     if( choice==DB_EVAL ){
01197       if( objc<3 || objc>5 ){
01198         Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
01199         return TCL_ERROR;
01200       }
01201       pRet = Tcl_NewObj();
01202       Tcl_IncrRefCount(pRet);
01203     }else{
01204       if( objc!=3 ){
01205         Tcl_WrongNumArgs(interp, 2, objv, "SQL");
01206         return TCL_ERROR;
01207       }
01208       if( choice==DB_EXISTS ){
01209         pRet = Tcl_NewBooleanObj(0);
01210         Tcl_IncrRefCount(pRet);
01211       }else{
01212         pRet = 0;
01213       }
01214     }
01215     if( objc==3 ){
01216       pArray = pScript = 0;
01217     }else if( objc==4 ){
01218       pArray = 0;
01219       pScript = objv[3];
01220     }else{
01221       pArray = objv[3];
01222       if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
01223       pScript = objv[4];
01224     }
01225 
01226     Tcl_IncrRefCount(objv[2]);
01227     zSql = Tcl_GetStringFromObj(objv[2], 0);
01228     while( rc==TCL_OK && zSql[0] ){
01229       int i;                     /* Loop counter */
01230       int nVar;                  /* Number of bind parameters in the pStmt */
01231       int nCol;                  /* Number of columns in the result set */
01232       Tcl_Obj **apColName = 0;   /* Array of column names */
01233       int len;                   /* String length of zSql */
01234   
01235       /* Try to find a SQL statement that has already been compiled and
01236       ** which matches the next sequence of SQL.
01237       */
01238       pStmt = 0;
01239       pPreStmt = pDb->stmtList;
01240       len = strlen(zSql);
01241       if( pPreStmt && sqlite3_expired(pPreStmt->pStmt) ){
01242         flushStmtCache(pDb);
01243         pPreStmt = 0;
01244       }
01245       for(; pPreStmt; pPreStmt=pPreStmt->pNext){
01246         int n = pPreStmt->nSql;
01247         if( len>=n 
01248             && memcmp(pPreStmt->zSql, zSql, n)==0
01249             && (zSql[n]==0 || zSql[n-1]==';')
01250         ){
01251           pStmt = pPreStmt->pStmt;
01252           zLeft = &zSql[pPreStmt->nSql];
01253 
01254           /* When a prepared statement is found, unlink it from the
01255           ** cache list.  It will later be added back to the beginning
01256           ** of the cache list in order to implement LRU replacement.
01257           */
01258           if( pPreStmt->pPrev ){
01259             pPreStmt->pPrev->pNext = pPreStmt->pNext;
01260           }else{
01261             pDb->stmtList = pPreStmt->pNext;
01262           }
01263           if( pPreStmt->pNext ){
01264             pPreStmt->pNext->pPrev = pPreStmt->pPrev;
01265           }else{
01266             pDb->stmtLast = pPreStmt->pPrev;
01267           }
01268           pDb->nStmt--;
01269           break;
01270         }
01271       }
01272   
01273       /* If no prepared statement was found.  Compile the SQL text
01274       */
01275       if( pStmt==0 ){
01276         if( SQLITE_OK!=sqlite3_prepare(pDb->db, zSql, -1, &pStmt, &zLeft) ){
01277           Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
01278           rc = TCL_ERROR;
01279           break;
01280         }
01281         if( pStmt==0 ){
01282           if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
01283             /* A compile-time error in the statement
01284             */
01285             Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
01286             rc = TCL_ERROR;
01287             break;
01288           }else{
01289             /* The statement was a no-op.  Continue to the next statement
01290             ** in the SQL string.
01291             */
01292             zSql = zLeft;
01293             continue;
01294           }
01295         }
01296         assert( pPreStmt==0 );
01297       }
01298 
01299       /* Bind values to parameters that begin with $ or :
01300       */  
01301       nVar = sqlite3_bind_parameter_count(pStmt);
01302       nParm = 0;
01303       if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
01304         apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
01305       }else{
01306         apParm = aParm;
01307       }
01308       for(i=1; i<=nVar; i++){
01309         const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
01310         if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':') ){
01311           Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
01312           if( pVar ){
01313             int n;
01314             u8 *data;
01315             char *zType = pVar->typePtr ? pVar->typePtr->name : "";
01316             char c = zType[0];
01317             if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
01318               /* Only load a BLOB type if the Tcl variable is a bytearray and
01319               ** has no string representation. */
01320               data = Tcl_GetByteArrayFromObj(pVar, &n);
01321               sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
01322               Tcl_IncrRefCount(pVar);
01323               apParm[nParm++] = pVar;
01324             }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
01325                   (c=='i' && strcmp(zType,"int")==0) ){
01326               Tcl_GetIntFromObj(interp, pVar, &n);
01327               sqlite3_bind_int(pStmt, i, n);
01328             }else if( c=='d' && strcmp(zType,"double")==0 ){
01329               double r;
01330               Tcl_GetDoubleFromObj(interp, pVar, &r);
01331               sqlite3_bind_double(pStmt, i, r);
01332             }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
01333               Tcl_WideInt v;
01334               Tcl_GetWideIntFromObj(interp, pVar, &v);
01335               sqlite3_bind_int64(pStmt, i, v);
01336             }else{
01337               data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
01338               sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
01339               Tcl_IncrRefCount(pVar);
01340               apParm[nParm++] = pVar;
01341             }
01342           }else{
01343             sqlite3_bind_null( pStmt, i );
01344           }
01345         }
01346       }
01347 
01348       /* Compute column names */
01349       nCol = sqlite3_column_count(pStmt);
01350       if( pScript ){
01351         apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
01352         if( apColName==0 ) break;
01353         for(i=0; i<nCol; i++){
01354           apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
01355           Tcl_IncrRefCount(apColName[i]);
01356         }
01357       }
01358 
01359       /* If results are being stored in an array variable, then create
01360       ** the array(*) entry for that array
01361       */
01362       if( pArray ){
01363         Tcl_Obj *pColList = Tcl_NewObj();
01364         Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
01365         Tcl_IncrRefCount(pColList);
01366         for(i=0; i<nCol; i++){
01367           Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
01368         }
01369         Tcl_ObjSetVar2(interp, pArray, pStar, pColList,0);
01370         Tcl_DecrRefCount(pColList);
01371         Tcl_DecrRefCount(pStar);
01372       }
01373 
01374       /* Execute the SQL
01375       */
01376       while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
01377         for(i=0; i<nCol; i++){
01378           Tcl_Obj *pVal;
01379           
01380           /* Set pVal to contain the i'th column of this row. */
01381           switch( sqlite3_column_type(pStmt, i) ){
01382             case SQLITE_BLOB: {
01383               int bytes = sqlite3_column_bytes(pStmt, i);
01384               pVal = Tcl_NewByteArrayObj(sqlite3_column_blob(pStmt, i), bytes);
01385               break;
01386             }
01387             case SQLITE_INTEGER: {
01388               sqlite_int64 v = sqlite3_column_int64(pStmt, i);
01389               if( v>=-2147483647 && v<=2147483647 ){
01390                 pVal = Tcl_NewIntObj(v);
01391               }else{
01392                 pVal = Tcl_NewWideIntObj(v);
01393               }
01394               break;
01395             }
01396             case SQLITE_FLOAT: {
01397               double r = sqlite3_column_double(pStmt, i);
01398               pVal = Tcl_NewDoubleObj(r);
01399               break;
01400             }
01401             case SQLITE_NULL: {
01402               pVal = dbTextToObj(pDb->zNull);
01403               break;
01404             }
01405             default: {
01406               pVal = dbTextToObj((char *)sqlite3_column_text(pStmt, i));
01407               break;
01408             }
01409           }
01410   
01411           if( pScript ){
01412             if( pArray==0 ){
01413               Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
01414             }else{
01415               Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
01416             }
01417           }else if( choice==DB_ONECOLUMN ){
01418             assert( pRet==0 );
01419             if( pRet==0 ){
01420               pRet = pVal;
01421               Tcl_IncrRefCount(pRet);
01422             }
01423             rc = TCL_BREAK;
01424             i = nCol;
01425           }else if( choice==DB_EXISTS ){
01426             Tcl_DecrRefCount(pRet);
01427             pRet = Tcl_NewBooleanObj(1);
01428             Tcl_IncrRefCount(pRet);
01429             rc = TCL_BREAK;
01430             i = nCol;
01431           }else{
01432             Tcl_ListObjAppendElement(interp, pRet, pVal);
01433           }
01434         }
01435   
01436         if( pScript ){
01437           rc = Tcl_EvalObjEx(interp, pScript, 0);
01438           if( rc==TCL_CONTINUE ){
01439             rc = TCL_OK;
01440           }
01441         }
01442       }
01443       if( rc==TCL_BREAK ){
01444         rc = TCL_OK;
01445       }
01446 
01447       /* Free the column name objects */
01448       if( pScript ){
01449         for(i=0; i<nCol; i++){
01450           Tcl_DecrRefCount(apColName[i]);
01451         }
01452         Tcl_Free((char*)apColName);
01453       }
01454 
01455       /* Free the bound string and blob parameters */
01456       for(i=0; i<nParm; i++){
01457         Tcl_DecrRefCount(apParm[i]);
01458       }
01459       if( apParm!=aParm ){
01460         Tcl_Free((char*)apParm);
01461       }
01462 
01463       /* Reset the statement.  If the result code is SQLITE_SCHEMA, then
01464       ** flush the statement cache and try the statement again.
01465       */
01466       rc2 = sqlite3_reset(pStmt);
01467       if( SQLITE_SCHEMA==rc2 ){
01468         /* After a schema change, flush the cache and try to run the
01469         ** statement again
01470         */
01471         flushStmtCache( pDb );
01472         sqlite3_finalize(pStmt);
01473         if( pPreStmt ) Tcl_Free((char*)pPreStmt);
01474         continue;
01475       }else if( SQLITE_OK!=rc2 ){
01476         /* If a run-time error occurs, report the error and stop reading
01477         ** the SQL
01478         */
01479         Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
01480         sqlite3_finalize(pStmt);
01481         rc = TCL_ERROR;
01482         if( pPreStmt ) Tcl_Free((char*)pPreStmt);
01483         break;
01484       }else if( pDb->maxStmt<=0 ){
01485         /* If the cache is turned off, deallocated the statement */
01486         if( pPreStmt ) Tcl_Free((char*)pPreStmt);
01487         sqlite3_finalize(pStmt);
01488       }else{
01489         /* Everything worked and the cache is operational.
01490         ** Create a new SqlPreparedStmt structure if we need one.
01491         ** (If we already have one we can just reuse it.)
01492         */
01493         if( pPreStmt==0 ){
01494           len = zLeft - zSql;
01495           pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) + len );
01496           if( pPreStmt==0 ) return TCL_ERROR;
01497           pPreStmt->pStmt = pStmt;
01498           pPreStmt->nSql = len;
01499           memcpy(pPreStmt->zSql, zSql, len);
01500           pPreStmt->zSql[len] = 0;
01501         }
01502 
01503         /* Add the prepared statement to the beginning of the cache list
01504         */
01505         pPreStmt->pNext = pDb->stmtList;
01506         pPreStmt->pPrev = 0;
01507         if( pDb->stmtList ){
01508          pDb->stmtList->pPrev = pPreStmt;
01509         }
01510         pDb->stmtList = pPreStmt;
01511         if( pDb->stmtLast==0 ){
01512           assert( pDb->nStmt==0 );
01513           pDb->stmtLast = pPreStmt;
01514         }else{
01515           assert( pDb->nStmt>0 );
01516         }
01517         pDb->nStmt++;
01518    
01519         /* If we have too many statement in cache, remove the surplus from the
01520         ** end of the cache list.
01521         */
01522         while( pDb->nStmt>pDb->maxStmt ){
01523           sqlite3_finalize(pDb->stmtLast->pStmt);
01524           pDb->stmtLast = pDb->stmtLast->pPrev;
01525           Tcl_Free((char*)pDb->stmtLast->pNext);
01526           pDb->stmtLast->pNext = 0;
01527           pDb->nStmt--;
01528         }
01529       }
01530 
01531       /* Proceed to the next statement */
01532       zSql = zLeft;
01533     }
01534     Tcl_DecrRefCount(objv[2]);
01535 
01536     if( pRet ){
01537       if( rc==TCL_OK ){
01538         Tcl_SetObjResult(interp, pRet);
01539       }
01540       Tcl_DecrRefCount(pRet);
01541     }
01542     break;
01543   }
01544 
01545   /*
01546   **     $db function NAME SCRIPT
01547   **
01548   ** Create a new SQL function called NAME.  Whenever that function is
01549   ** called, invoke SCRIPT to evaluate the function.
01550   */
01551   case DB_FUNCTION: {
01552     SqlFunc *pFunc;
01553     Tcl_Obj *pScript;
01554     char *zName;
01555     if( objc!=4 ){
01556       Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
01557       return TCL_ERROR;
01558     }
01559     zName = Tcl_GetStringFromObj(objv[2], 0);
01560     pScript = objv[3];
01561     pFunc = findSqlFunc(pDb, zName);
01562     if( pFunc==0 ) return TCL_ERROR;
01563     if( pFunc->pScript ){
01564       Tcl_DecrRefCount(pFunc->pScript);
01565     }
01566     pFunc->pScript = pScript;
01567     Tcl_IncrRefCount(pScript);
01568     pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
01569     rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
01570         pFunc, tclSqlFunc, 0, 0);
01571     if( rc!=SQLITE_OK ){
01572       rc = TCL_ERROR;
01573       Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
01574     }else{
01575       /* Must flush any cached statements */
01576       flushStmtCache( pDb );
01577     }
01578     break;
01579   }
01580 
01581   /*
01582   **     $db nullvalue ?STRING?
01583   **
01584   ** Change text used when a NULL comes back from the database. If ?STRING?
01585   ** is not present, then the current string used for NULL is returned.
01586   ** If STRING is present, then STRING is returned.
01587   **
01588   */
01589   case DB_NULLVALUE: {
01590     if( objc!=2 && objc!=3 ){
01591       Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
01592       return TCL_ERROR;
01593     }
01594     if( objc==3 ){
01595       int len;
01596       char *zNull = Tcl_GetStringFromObj(objv[2], &len);
01597       if( pDb->zNull ){
01598         Tcl_Free(pDb->zNull);
01599       }
01600       if( zNull && len>0 ){
01601         pDb->zNull = Tcl_Alloc( len + 1 );
01602         strncpy(pDb->zNull, zNull, len);
01603         pDb->zNull[len] = '\0';
01604       }else{
01605         pDb->zNull = 0;
01606       }
01607     }
01608     Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
01609     break;
01610   }
01611 
01612   /*
01613   **     $db last_insert_rowid 
01614   **
01615   ** Return an integer which is the ROWID for the most recent insert.
01616   */
01617   case DB_LAST_INSERT_ROWID: {
01618     Tcl_Obj *pResult;
01619     int rowid;
01620     if( objc!=2 ){
01621       Tcl_WrongNumArgs(interp, 2, objv, "");
01622       return TCL_ERROR;
01623     }
01624     rowid = sqlite3_last_insert_rowid(pDb->db);
01625     pResult = Tcl_GetObjResult(interp);
01626     Tcl_SetIntObj(pResult, rowid);
01627     break;
01628   }
01629 
01630   /*
01631   ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
01632   */
01633 
01634   /*    $db progress ?N CALLBACK?
01635   ** 
01636   ** Invoke the given callback every N virtual machine opcodes while executing
01637   ** queries.
01638   */
01639   case DB_PROGRESS: {
01640     if( objc==2 ){
01641       if( pDb->zProgress ){
01642         Tcl_AppendResult(interp, pDb->zProgress, 0);
01643       }
01644     }else if( objc==4 ){
01645       char *zProgress;
01646       int len;
01647       int N;
01648       if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
01649        return TCL_ERROR;
01650       };
01651       if( pDb->zProgress ){
01652         Tcl_Free(pDb->zProgress);
01653       }
01654       zProgress = Tcl_GetStringFromObj(objv[3], &len);
01655       if( zProgress && len>0 ){
01656         pDb->zProgress = Tcl_Alloc( len + 1 );
01657         strcpy(pDb->zProgress, zProgress);
01658       }else{
01659         pDb->zProgress = 0;
01660       }
01661 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
01662       if( pDb->zProgress ){
01663         pDb->interp = interp;
01664         sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
01665       }else{
01666         sqlite3_progress_handler(pDb->db, 0, 0, 0);
01667       }
01668 #endif
01669     }else{
01670       Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
01671       return TCL_ERROR;
01672     }
01673     break;
01674   }
01675 
01676   /*    $db profile ?CALLBACK?
01677   **
01678   ** Make arrangements to invoke the CALLBACK routine after each SQL statement
01679   ** that has run.  The text of the SQL and the amount of elapse time are
01680   ** appended to CALLBACK before the script is run.
01681   */
01682   case DB_PROFILE: {
01683     if( objc>3 ){
01684       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
01685       return TCL_ERROR;
01686     }else if( objc==2 ){
01687       if( pDb->zProfile ){
01688         Tcl_AppendResult(interp, pDb->zProfile, 0);
01689       }
01690     }else{
01691       char *zProfile;
01692       int len;
01693       if( pDb->zProfile ){
01694         Tcl_Free(pDb->zProfile);
01695       }
01696       zProfile = Tcl_GetStringFromObj(objv[2], &len);
01697       if( zProfile && len>0 ){
01698         pDb->zProfile = Tcl_Alloc( len + 1 );
01699         strcpy(pDb->zProfile, zProfile);
01700       }else{
01701         pDb->zProfile = 0;
01702       }
01703 #ifndef SQLITE_OMIT_TRACE
01704       if( pDb->zProfile ){
01705         pDb->interp = interp;
01706         sqlite3_profile(pDb->db, DbProfileHandler, pDb);
01707       }else{
01708         sqlite3_profile(pDb->db, 0, 0);
01709       }
01710 #endif
01711     }
01712     break;
01713   }
01714 
01715   /*
01716   **     $db rekey KEY
01717   **
01718   ** Change the encryption key on the currently open database.
01719   */
01720   case DB_REKEY: {
01721     int nKey;
01722     void *pKey;
01723     if( objc!=3 ){
01724       Tcl_WrongNumArgs(interp, 2, objv, "KEY");
01725       return TCL_ERROR;
01726     }
01727     pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
01728 #ifdef SQLITE_HAS_CODEC
01729     rc = sqlite3_rekey(pDb->db, pKey, nKey);
01730     if( rc ){
01731       Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
01732       rc = TCL_ERROR;
01733     }
01734 #endif
01735     break;
01736   }
01737 
01738   /*
01739   **     $db timeout MILLESECONDS
01740   **
01741   ** Delay for the number of milliseconds specified when a file is locked.
01742   */
01743   case DB_TIMEOUT: {
01744     int ms;
01745     if( objc!=3 ){
01746       Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
01747       return TCL_ERROR;
01748     }
01749     if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
01750     sqlite3_busy_timeout(pDb->db, ms);
01751     break;
01752   }
01753   
01754   /*
01755   **     $db total_changes
01756   **
01757   ** Return the number of rows that were modified, inserted, or deleted 
01758   ** since the database handle was created.
01759   */
01760   case DB_TOTAL_CHANGES: {
01761     Tcl_Obj *pResult;
01762     if( objc!=2 ){
01763       Tcl_WrongNumArgs(interp, 2, objv, "");
01764       return TCL_ERROR;
01765     }
01766     pResult = Tcl_GetObjResult(interp);
01767     Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
01768     break;
01769   }
01770 
01771   /*    $db trace ?CALLBACK?
01772   **
01773   ** Make arrangements to invoke the CALLBACK routine for each SQL statement
01774   ** that is executed.  The text of the SQL is appended to CALLBACK before
01775   ** it is executed.
01776   */
01777   case DB_TRACE: {
01778     if( objc>3 ){
01779       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
01780       return TCL_ERROR;
01781     }else if( objc==2 ){
01782       if( pDb->zTrace ){
01783         Tcl_AppendResult(interp, pDb->zTrace, 0);
01784       }
01785     }else{
01786       char *zTrace;
01787       int len;
01788       if( pDb->zTrace ){
01789         Tcl_Free(pDb->zTrace);
01790       }
01791       zTrace = Tcl_GetStringFromObj(objv[2], &len);
01792       if( zTrace && len>0 ){
01793         pDb->zTrace = Tcl_Alloc( len + 1 );
01794         strcpy(pDb->zTrace, zTrace);
01795       }else{
01796         pDb->zTrace = 0;
01797       }
01798 #ifndef SQLITE_OMIT_TRACE
01799       if( pDb->zTrace ){
01800         pDb->interp = interp;
01801         sqlite3_trace(pDb->db, DbTraceHandler, pDb);
01802       }else{
01803         sqlite3_trace(pDb->db, 0, 0);
01804       }
01805 #endif
01806     }
01807     break;
01808   }
01809 
01810   /*    $db transaction [-deferred|-immediate|-exclusive] SCRIPT
01811   **
01812   ** Start a new transaction (if we are not already in the midst of a
01813   ** transaction) and execute the TCL script SCRIPT.  After SCRIPT
01814   ** completes, either commit the transaction or roll it back if SCRIPT
01815   ** throws an exception.  Or if no new transation was started, do nothing.
01816   ** pass the exception on up the stack.
01817   **
01818   ** This command was inspired by Dave Thomas's talk on Ruby at the
01819   ** 2005 O'Reilly Open Source Convention (OSCON).
01820   */
01821   case DB_TRANSACTION: {
01822     int inTrans;
01823     Tcl_Obj *pScript;
01824     const char *zBegin = "BEGIN";
01825     if( objc!=3 && objc!=4 ){
01826       Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
01827       return TCL_ERROR;
01828     }
01829     if( objc==3 ){
01830       pScript = objv[2];
01831     } else {
01832       static const char *TTYPE_strs[] = {
01833         "deferred",   "exclusive",  "immediate", 0
01834       };
01835       enum TTYPE_enum {
01836         TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
01837       };
01838       int ttype;
01839       if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
01840                               0, &ttype) ){
01841         return TCL_ERROR;
01842       }
01843       switch( (enum TTYPE_enum)ttype ){
01844         case TTYPE_DEFERRED:    /* no-op */;                 break;
01845         case TTYPE_EXCLUSIVE:   zBegin = "BEGIN EXCLUSIVE";  break;
01846         case TTYPE_IMMEDIATE:   zBegin = "BEGIN IMMEDIATE";  break;
01847       }
01848       pScript = objv[3];
01849     }
01850     inTrans = !sqlite3_get_autocommit(pDb->db);
01851     if( !inTrans ){
01852       (void)sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
01853     }
01854     rc = Tcl_EvalObjEx(interp, pScript, 0);
01855     if( !inTrans ){
01856       const char *zEnd;
01857       if( rc==TCL_ERROR ){
01858         zEnd = "ROLLBACK";
01859       } else {
01860         zEnd = "COMMIT";
01861       }
01862       (void)sqlite3_exec(pDb->db, zEnd, 0, 0, 0);
01863     }
01864     break;
01865   }
01866 
01867   /*
01868   **    $db update_hook ?script?
01869   **    $db rollback_hook ?script?
01870   */
01871   case DB_UPDATE_HOOK: 
01872   case DB_ROLLBACK_HOOK: {
01873 
01874     /* set ppHook to point at pUpdateHook or pRollbackHook, depending on 
01875     ** whether [$db update_hook] or [$db rollback_hook] was invoked.
01876     */
01877     Tcl_Obj **ppHook; 
01878     if( choice==DB_UPDATE_HOOK ){
01879       ppHook = &pDb->pUpdateHook;
01880     }else{
01881       ppHook = &pDb->pRollbackHook;
01882     }
01883 
01884     if( objc!=2 && objc!=3 ){
01885        Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
01886        return TCL_ERROR;
01887     }
01888     if( *ppHook ){
01889       Tcl_SetObjResult(interp, *ppHook);
01890       if( objc==3 ){
01891         Tcl_DecrRefCount(*ppHook);
01892         *ppHook = 0;
01893       }
01894     }
01895     if( objc==3 ){
01896       assert( !(*ppHook) );
01897       if( Tcl_GetCharLength(objv[2])>0 ){
01898         *ppHook = objv[2];
01899         Tcl_IncrRefCount(*ppHook);
01900       }
01901     }
01902 
01903     sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
01904     sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
01905 
01906     break;
01907   }
01908 
01909   /*    $db version
01910   **
01911   ** Return the version string for this database.
01912   */
01913   case DB_VERSION: {
01914     Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
01915     break;
01916   }
01917 
01918 
01919   } /* End of the SWITCH statement */
01920   return rc;
01921 }
01922 
01923 /*
01924 **   sqlite3 DBNAME FILENAME ?MODE? ?-key KEY?
01925 **
01926 ** This is the main Tcl command.  When the "sqlite" Tcl command is
01927 ** invoked, this routine runs to process that command.
01928 **
01929 ** The first argument, DBNAME, is an arbitrary name for a new
01930 ** database connection.  This command creates a new command named
01931 ** DBNAME that is used to control that connection.  The database
01932 ** connection is deleted when the DBNAME command is deleted.
01933 **
01934 ** The second argument is the name of the directory that contains
01935 ** the sqlite database that is to be accessed.
01936 **
01937 ** For testing purposes, we also support the following:
01938 **
01939 **  sqlite3 -encoding
01940 **
01941 **       Return the encoding used by LIKE and GLOB operators.  Choices
01942 **       are UTF-8 and iso8859.
01943 **
01944 **  sqlite3 -version
01945 **
01946 **       Return the version number of the SQLite library.
01947 **
01948 **  sqlite3 -tcl-uses-utf
01949 **
01950 **       Return "1" if compiled with a Tcl uses UTF-8.  Return "0" if
01951 **       not.  Used by tests to make sure the library was compiled 
01952 **       correctly.
01953 */
01954 static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
01955   SqliteDb *p;
01956   void *pKey = 0;
01957   int nKey = 0;
01958   const char *zArg;
01959   char *zErrMsg;
01960   const char *zFile;
01961   if( objc==2 ){
01962     zArg = Tcl_GetStringFromObj(objv[1], 0);
01963     if( strcmp(zArg,"-version")==0 ){
01964       Tcl_AppendResult(interp,sqlite3_version,0);
01965       return TCL_OK;
01966     }
01967     if( strcmp(zArg,"-has-codec")==0 ){
01968 #ifdef SQLITE_HAS_CODEC
01969       Tcl_AppendResult(interp,"1",0);
01970 #else
01971       Tcl_AppendResult(interp,"0",0);
01972 #endif
01973       return TCL_OK;
01974     }
01975     if( strcmp(zArg,"-tcl-uses-utf")==0 ){
01976 #ifdef TCL_UTF_MAX
01977       Tcl_AppendResult(interp,"1",0);
01978 #else
01979       Tcl_AppendResult(interp,"0",0);
01980 #endif
01981       return TCL_OK;
01982     }
01983   }
01984   if( objc==5 || objc==6 ){
01985     zArg = Tcl_GetStringFromObj(objv[objc-2], 0);
01986     if( strcmp(zArg,"-key")==0 ){
01987       pKey = Tcl_GetByteArrayFromObj(objv[objc-1], &nKey);
01988       objc -= 2;
01989     }
01990   }
01991   if( objc!=3 && objc!=4 ){
01992     Tcl_WrongNumArgs(interp, 1, objv, 
01993 #ifdef SQLITE_HAS_CODEC
01994       "HANDLE FILENAME ?-key CODEC-KEY?"
01995 #else
01996       "HANDLE FILENAME ?MODE?"
01997 #endif
01998     );
01999     return TCL_ERROR;
02000   }
02001   zErrMsg = 0;
02002   p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
02003   if( p==0 ){
02004     Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
02005     return TCL_ERROR;
02006   }
02007   memset(p, 0, sizeof(*p));
02008   zFile = Tcl_GetStringFromObj(objv[2], 0);
02009   sqlite3_open(zFile, &p->db);
02010   if( SQLITE_OK!=sqlite3_errcode(p->db) ){
02011     zErrMsg = strdup(sqlite3_errmsg(p->db));
02012     sqlite3_close(p->db);
02013     p->db = 0;
02014   }
02015 #ifdef SQLITE_HAS_CODEC
02016   sqlite3_key(p->db, pKey, nKey);
02017 #endif
02018   if( p->db==0 ){
02019     Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
02020     Tcl_Free((char*)p);
02021     free(zErrMsg);
02022     return TCL_ERROR;
02023   }
02024   p->maxStmt = NUM_PREPARED_STMTS;
02025   zArg = Tcl_GetStringFromObj(objv[1], 0);
02026   Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
02027 
02028   /* If compiled with SQLITE_TEST turned on, then register the "md5sum"
02029   ** SQL function.
02030   */
02031 #ifdef SQLITE_TEST
02032   {
02033     extern void Md5_Register(sqlite3*);
02034 #ifdef SQLITE_MEMDEBUG
02035     int mallocfail = sqlite3_iMallocFail;
02036     sqlite3_iMallocFail = 0;
02037 #endif
02038     Md5_Register(p->db);
02039 #ifdef SQLITE_MEMDEBUG
02040     sqlite3_iMallocFail = mallocfail;
02041 #endif
02042   }
02043 #endif  
02044   p->interp = interp;
02045   return TCL_OK;
02046 }
02047 
02048 /*
02049 ** Provide a dummy Tcl_InitStubs if we are using this as a static
02050 ** library.
02051 */
02052 #ifndef USE_TCL_STUBS
02053 # undef  Tcl_InitStubs
02054 # define Tcl_InitStubs(a,b,c)
02055 #endif
02056 
02057 /*
02058 ** Make sure we have a PACKAGE_VERSION macro defined.  This will be
02059 ** defined automatically by the TEA makefile.  But other makefiles
02060 ** do not define it.
02061 */
02062 #ifndef PACKAGE_VERSION
02063 # define PACKAGE_VERSION SQLITE_VERSION
02064 #endif
02065 
02066 /*
02067 ** Initialize this module.
02068 **
02069 ** This Tcl module contains only a single new Tcl command named "sqlite".
02070 ** (Hence there is no namespace.  There is no point in using a namespace
02071 ** if the extension only supplies one new name!)  The "sqlite" command is
02072 ** used to open a new SQLite database.  See the DbMain() routine above
02073 ** for additional information.
02074 */
02075 extern int Sqlite3_Init(Tcl_Interp *interp){
02076   Tcl_InitStubs(interp, "8.4", 0);
02077   Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
02078   Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
02079   Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
02080   Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
02081   return TCL_OK;
02082 }
02083 extern int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
02084 extern int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
02085 extern int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
02086 
02087 #ifndef SQLITE_3_SUFFIX_ONLY
02088 extern int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
02089 extern int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
02090 extern int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
02091 extern int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
02092 #endif
02093 
02094 #ifdef TCLSH
02095 /*****************************************************************************
02096 ** The code that follows is used to build standalone TCL interpreters
02097 */
02098 
02099 /*
02100 ** If the macro TCLSH is one, then put in code this for the
02101 ** "main" routine that will initialize Tcl and take input from
02102 ** standard input.
02103 */
02104 #if TCLSH==1
02105 static char zMainloop[] =
02106   "set line {}\n"
02107   "while {![eof stdin]} {\n"
02108     "if {$line!=\"\"} {\n"
02109       "puts -nonewline \"> \"\n"
02110     "} else {\n"
02111       "puts -nonewline \"% \"\n"
02112     "}\n"
02113     "flush stdout\n"
02114     "append line [gets stdin]\n"
02115     "if {[info complete $line]} {\n"
02116       "if {[catch {uplevel #0 $line} result]} {\n"
02117         "puts stderr \"Error: $result\"\n"
02118       "} elseif {$result!=\"\"} {\n"
02119         "puts $result\n"
02120       "}\n"
02121       "set line {}\n"
02122     "} else {\n"
02123       "append line \\n\n"
02124     "}\n"
02125   "}\n"
02126 ;
02127 #endif
02128 
02129 /*
02130 ** If the macro TCLSH is two, then get the main loop code out of
02131 ** the separate file "spaceanal_tcl.h".
02132 */
02133 #if TCLSH==2
02134 static char zMainloop[] = 
02135 #include "spaceanal_tcl.h"
02136 ;
02137 #endif
02138 
02139 #define TCLSH_MAIN main   /* Needed to fake out mktclapp */
02140 int TCLSH_MAIN(int argc, char **argv){
02141   Tcl_Interp *interp;
02142   Tcl_FindExecutable(argv[0]);
02143   interp = Tcl_CreateInterp();
02144   Sqlite3_Init(interp);
02145 #ifdef SQLITE_TEST
02146   {
02147     extern int Sqlitetest1_Init(Tcl_Interp*);
02148     extern int Sqlitetest2_Init(Tcl_Interp*);
02149     extern int Sqlitetest3_Init(Tcl_Interp*);
02150     extern int Sqlitetest4_Init(Tcl_Interp*);
02151     extern int Sqlitetest5_Init(Tcl_Interp*);
02152     extern int Sqlitetest6_Init(Tcl_Interp*);
02153     extern int Sqlitetest7_Init(Tcl_Interp*);
02154     extern int Md5_Init(Tcl_Interp*);
02155     extern int Sqlitetestsse_Init(Tcl_Interp*);
02156     extern int Sqlitetestasync_Init(Tcl_Interp*);
02157 
02158     Sqlitetest1_Init(interp);
02159     Sqlitetest2_Init(interp);
02160     Sqlitetest3_Init(interp);
02161     Sqlitetest4_Init(interp);
02162     Sqlitetest5_Init(interp);
02163     Sqlitetest6_Init(interp);
02164     Sqlitetest7_Init(interp);
02165     Sqlitetestasync_Init(interp);
02166     Md5_Init(interp);
02167 #ifdef SQLITE_SSE
02168     Sqlitetestsse_Init(interp);
02169 #endif
02170   }
02171 #endif
02172   if( argc>=2 || TCLSH==2 ){
02173     int i;
02174     Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
02175     Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
02176     for(i=3-TCLSH; i<argc; i++){
02177       Tcl_SetVar(interp, "argv", argv[i],
02178           TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
02179     }
02180     if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
02181       const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
02182       if( zInfo==0 ) zInfo = interp->result;
02183       fprintf(stderr,"%s: %s\n", *argv, zInfo);
02184       return 1;
02185     }
02186   }
02187   if( argc<=1 || TCLSH==2 ){
02188     Tcl_GlobalEval(interp, zMainloop);
02189   }
02190   return 0;
02191 }
02192 #endif /* TCLSH */
02193 
02194 #endif /* !defined(NO_TCL) */