1 #ifdef USE_SYSTEM_SQLITE
9 ** The author disclaims copyright to this source code. In place of
10 ** a legal notice, here is a blessing:
12 ** May you do good and not evil.
13 ** May you find forgiveness for yourself and forgive others.
14 ** May you share freely, never taking more than you give.
16 *************************************************************************
17 ** A TCL Interface to SQLite. Append this file to sqlite3.c and
18 ** compile the whole thing to build a TCL-enabled version of SQLite.
20 ** Compile-time options:
22 ** -DTCLSH=1 Add a "main()" routine that works as a tclsh.
24 ** -DSQLITE_TCLMD5 When used in conjuction with -DTCLSH=1, add
25 ** four new commands to the TCL interpreter for
26 ** generating MD5 checksums: md5, md5file,
27 ** md5-10x8, and md5file-10x8.
29 ** -DSQLITE_TEST When used in conjuction with -DTCLSH=1, add
30 ** hundreds of new commands used for testing
31 ** SQLite. This option implies -DSQLITE_TCLMD5.
35 ** If requested, include the SQLite compiler options file for MSVC.
37 #if defined(INCLUDE_MSVC_H)
45 ** Some additional include files are needed if this file is not
46 ** appended to the amalgamation.
48 #ifndef SQLITE_AMALGAMATION
53 typedef unsigned char u8;
57 /* Used to get the current process ID */
60 # define GETPID getpid
61 #elif !defined(_WIN32_WCE)
62 # ifndef SQLITE_AMALGAMATION
63 # define WIN32_LEAN_AND_MEAN
66 # define GETPID (int)GetCurrentProcessId
70 * Windows needs to know which symbols to export. Unix does not.
71 * BUILD_sqlite should be undefined for Unix.
74 #undef TCL_STORAGE_CLASS
75 #define TCL_STORAGE_CLASS DLLEXPORT
76 #endif /* BUILD_sqlite */
78 #define NUM_PREPARED_STMTS 10
79 #define MAX_PREPARED_STMTS 100
81 /* Forward declaration */
82 typedef struct SqliteDb SqliteDb;
85 ** New SQL functions can be created as TCL scripts. Each such function
86 ** is described by an instance of the following structure.
88 typedef struct SqlFunc SqlFunc;
90 Tcl_Interp *interp; /* The TCL interpret to execute the function */
91 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
92 SqliteDb *pDb; /* Database connection that owns this function */
93 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
94 char *zName; /* Name of this function */
95 SqlFunc *pNext; /* Next function on the list of them all */
99 ** New collation sequences function can be created as TCL scripts. Each such
100 ** function is described by an instance of the following structure.
102 typedef struct SqlCollate SqlCollate;
104 Tcl_Interp *interp; /* The TCL interpret to execute the function */
105 char *zScript; /* The script to be run */
106 SqlCollate *pNext; /* Next function on the list of them all */
110 ** Prepared statements are cached for faster execution. Each prepared
111 ** statement is described by an instance of the following structure.
113 typedef struct SqlPreparedStmt SqlPreparedStmt;
114 struct SqlPreparedStmt {
115 SqlPreparedStmt *pNext; /* Next in linked list */
116 SqlPreparedStmt *pPrev; /* Previous on the list */
117 sqlite3_stmt *pStmt; /* The prepared statement */
118 int nSql; /* chars in zSql[] */
119 const char *zSql; /* Text of the SQL statement */
120 int nParm; /* Size of apParm array */
121 Tcl_Obj **apParm; /* Array of referenced object pointers */
124 typedef struct IncrblobChannel IncrblobChannel;
127 ** There is one instance of this structure for each SQLite database
128 ** that has been opened by the SQLite TCL interface.
130 ** If this module is built with SQLITE_TEST defined (to create the SQLite
131 ** testfixture executable), then it may be configured to use either
132 ** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
133 ** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
136 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
137 Tcl_Interp *interp; /* The interpreter used for this database */
138 char *zBusy; /* The busy callback routine */
139 char *zCommit; /* The commit hook callback routine */
140 char *zTrace; /* The trace callback routine */
141 char *zProfile; /* The profile callback routine */
142 char *zProgress; /* The progress callback routine */
143 char *zAuth; /* The authorization callback routine */
144 int disableAuth; /* Disable the authorizer if it exists */
145 char *zNull; /* Text to substitute for an SQL NULL value */
146 SqlFunc *pFunc; /* List of SQL functions */
147 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
148 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
149 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
150 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
151 SqlCollate *pCollate; /* List of SQL collation functions */
152 int rc; /* Return code of most recent sqlite3_exec() */
153 Tcl_Obj *pCollateNeeded; /* Collation needed script */
154 SqlPreparedStmt *stmtList; /* List of prepared statements*/
155 SqlPreparedStmt *stmtLast; /* Last statement in the list */
156 int maxStmt; /* The next maximum number of stmtList */
157 int nStmt; /* Number of statements in stmtList */
158 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
159 int nStep, nSort, nIndex; /* Statistics for most recent operation */
160 int nTransaction; /* Number of nested [transaction] methods */
162 int bLegacyPrepare; /* True to use sqlite3_prepare() */
166 struct IncrblobChannel {
167 sqlite3_blob *pBlob; /* sqlite3 blob handle */
168 SqliteDb *pDb; /* Associated database connection */
169 int iSeek; /* Current seek offset */
170 Tcl_Channel channel; /* Channel identifier */
171 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
172 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
176 ** Compute a string length that is limited to what can be stored in
177 ** lower 30 bits of a 32-bit signed integer.
179 static int strlen30(const char *z){
181 while( *z2 ){ z2++; }
182 return 0x3fffffff & (int)(z2 - z);
186 #ifndef SQLITE_OMIT_INCRBLOB
188 ** Close all incrblob channels opened using database connection pDb.
189 ** This is called when shutting down the database connection.
191 static void closeIncrblobChannels(SqliteDb *pDb){
193 IncrblobChannel *pNext;
195 for(p=pDb->pIncrblob; p; p=pNext){
198 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
199 ** which deletes the IncrblobChannel structure at *p. So do not
200 ** call Tcl_Free() here.
202 Tcl_UnregisterChannel(pDb->interp, p->channel);
207 ** Close an incremental blob channel.
209 static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
210 IncrblobChannel *p = (IncrblobChannel *)instanceData;
211 int rc = sqlite3_blob_close(p->pBlob);
212 sqlite3 *db = p->pDb->db;
214 /* Remove the channel from the SqliteDb.pIncrblob list. */
216 p->pNext->pPrev = p->pPrev;
219 p->pPrev->pNext = p->pNext;
221 if( p->pDb->pIncrblob==p ){
222 p->pDb->pIncrblob = p->pNext;
225 /* Free the IncrblobChannel structure */
229 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
236 ** Read data from an incremental blob channel.
238 static int incrblobInput(
239 ClientData instanceData,
244 IncrblobChannel *p = (IncrblobChannel *)instanceData;
245 int nRead = bufSize; /* Number of bytes to read */
246 int nBlob; /* Total size of the blob */
247 int rc; /* sqlite error code */
249 nBlob = sqlite3_blob_bytes(p->pBlob);
250 if( (p->iSeek+nRead)>nBlob ){
251 nRead = nBlob-p->iSeek;
257 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
268 ** Write data to an incremental blob channel.
270 static int incrblobOutput(
271 ClientData instanceData,
276 IncrblobChannel *p = (IncrblobChannel *)instanceData;
277 int nWrite = toWrite; /* Number of bytes to write */
278 int nBlob; /* Total size of the blob */
279 int rc; /* sqlite error code */
281 nBlob = sqlite3_blob_bytes(p->pBlob);
282 if( (p->iSeek+nWrite)>nBlob ){
283 *errorCodePtr = EINVAL;
290 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
301 ** Seek an incremental blob channel.
303 static int incrblobSeek(
304 ClientData instanceData,
309 IncrblobChannel *p = (IncrblobChannel *)instanceData;
319 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
322 default: assert(!"Bad seekMode");
329 static void incrblobWatch(ClientData instanceData, int mode){
332 static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
336 static Tcl_ChannelType IncrblobChannelType = {
337 "incrblob", /* typeName */
338 TCL_CHANNEL_VERSION_2, /* version */
339 incrblobClose, /* closeProc */
340 incrblobInput, /* inputProc */
341 incrblobOutput, /* outputProc */
342 incrblobSeek, /* seekProc */
343 0, /* setOptionProc */
344 0, /* getOptionProc */
345 incrblobWatch, /* watchProc (this is a no-op) */
346 incrblobHandle, /* getHandleProc (always returns error) */
348 0, /* blockModeProc */
351 0, /* wideSeekProc */
355 ** Create a new incrblob channel.
357 static int createIncrblobChannel(
367 sqlite3 *db = pDb->db;
370 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
372 /* This variable is used to name the channels: "incrblob_[incr count]" */
373 static int count = 0;
376 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
378 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
382 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
386 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
387 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
388 Tcl_RegisterChannel(interp, p->channel);
390 /* Link the new channel into the SqliteDb.pIncrblob list. */
391 p->pNext = pDb->pIncrblob;
399 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
402 #else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
403 #define closeIncrblobChannels(pDb)
407 ** Look at the script prefix in pCmd. We will be executing this script
408 ** after first appending one or more arguments. This routine analyzes
409 ** the script to see if it is safe to use Tcl_EvalObjv() on the script
410 ** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
413 ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
414 ** command name followed by zero or more arguments with no [...] or $
415 ** or {...} or ; to be seen anywhere. Most callback scripts consist
416 ** of just a single procedure name and they meet this requirement.
418 static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
419 /* We could try to do something with Tcl_Parse(). But we will instead
420 ** just do a search for forbidden characters. If any of the forbidden
421 ** characters appear in pCmd, we will report the string as unsafe.
425 z = Tcl_GetStringFromObj(pCmd, &n);
428 if( c=='$' || c=='[' || c==';' ) return 0;
434 ** Find an SqlFunc structure with the given name. Or create a new
435 ** one if an existing one cannot be found. Return a pointer to the
438 static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
440 int nName = strlen30(zName);
441 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
442 pNew->zName = (char*)&pNew[1];
443 memcpy(pNew->zName, zName, nName+1);
444 for(p=pDb->pFunc; p; p=p->pNext){
445 if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
446 Tcl_Free((char*)pNew);
450 pNew->interp = pDb->interp;
453 pNew->pNext = pDb->pFunc;
459 ** Free a single SqlPreparedStmt object.
461 static void dbFreeStmt(SqlPreparedStmt *pStmt){
463 if( sqlite3_sql(pStmt->pStmt)==0 ){
464 Tcl_Free((char *)pStmt->zSql);
467 sqlite3_finalize(pStmt->pStmt);
468 Tcl_Free((char *)pStmt);
472 ** Finalize and free a list of prepared statements
474 static void flushStmtCache(SqliteDb *pDb){
475 SqlPreparedStmt *pPreStmt;
476 SqlPreparedStmt *pNext;
478 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
479 pNext = pPreStmt->pNext;
480 dbFreeStmt(pPreStmt);
488 ** TCL calls this procedure when an sqlite3 database command is
491 static void DbDeleteCmd(void *db){
492 SqliteDb *pDb = (SqliteDb*)db;
494 closeIncrblobChannels(pDb);
495 sqlite3_close(pDb->db);
497 SqlFunc *pFunc = pDb->pFunc;
498 pDb->pFunc = pFunc->pNext;
499 assert( pFunc->pDb==pDb );
500 Tcl_DecrRefCount(pFunc->pScript);
501 Tcl_Free((char*)pFunc);
503 while( pDb->pCollate ){
504 SqlCollate *pCollate = pDb->pCollate;
505 pDb->pCollate = pCollate->pNext;
506 Tcl_Free((char*)pCollate);
509 Tcl_Free(pDb->zBusy);
512 Tcl_Free(pDb->zTrace);
515 Tcl_Free(pDb->zProfile);
518 Tcl_Free(pDb->zAuth);
521 Tcl_Free(pDb->zNull);
523 if( pDb->pUpdateHook ){
524 Tcl_DecrRefCount(pDb->pUpdateHook);
526 if( pDb->pRollbackHook ){
527 Tcl_DecrRefCount(pDb->pRollbackHook);
530 Tcl_DecrRefCount(pDb->pWalHook);
532 if( pDb->pCollateNeeded ){
533 Tcl_DecrRefCount(pDb->pCollateNeeded);
535 Tcl_Free((char*)pDb);
539 ** This routine is called when a database file is locked while trying
542 static int DbBusyHandler(void *cd, int nTries){
543 SqliteDb *pDb = (SqliteDb*)cd;
547 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
548 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
549 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
555 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
557 ** This routine is invoked as the 'progress callback' for the database.
559 static int DbProgressHandler(void *cd){
560 SqliteDb *pDb = (SqliteDb*)cd;
563 assert( pDb->zProgress );
564 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
565 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
572 #ifndef SQLITE_OMIT_TRACE
574 ** This routine is called by the SQLite trace handler whenever a new
575 ** block of SQL is executed. The TCL script in pDb->zTrace is executed.
577 static void DbTraceHandler(void *cd, const char *zSql){
578 SqliteDb *pDb = (SqliteDb*)cd;
581 Tcl_DStringInit(&str);
582 Tcl_DStringAppend(&str, pDb->zTrace, -1);
583 Tcl_DStringAppendElement(&str, zSql);
584 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
585 Tcl_DStringFree(&str);
586 Tcl_ResetResult(pDb->interp);
590 #ifndef SQLITE_OMIT_TRACE
592 ** This routine is called by the SQLite profile handler after a statement
593 ** SQL has executed. The TCL script in pDb->zProfile is evaluated.
595 static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
596 SqliteDb *pDb = (SqliteDb*)cd;
600 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
601 Tcl_DStringInit(&str);
602 Tcl_DStringAppend(&str, pDb->zProfile, -1);
603 Tcl_DStringAppendElement(&str, zSql);
604 Tcl_DStringAppendElement(&str, zTm);
605 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
606 Tcl_DStringFree(&str);
607 Tcl_ResetResult(pDb->interp);
612 ** This routine is called when a transaction is committed. The
613 ** TCL script in pDb->zCommit is executed. If it returns non-zero or
614 ** if it throws an exception, the transaction is rolled back instead
615 ** of being committed.
617 static int DbCommitHandler(void *cd){
618 SqliteDb *pDb = (SqliteDb*)cd;
621 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
622 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
628 static void DbRollbackHandler(void *clientData){
629 SqliteDb *pDb = (SqliteDb*)clientData;
630 assert(pDb->pRollbackHook);
631 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
632 Tcl_BackgroundError(pDb->interp);
637 ** This procedure handles wal_hook callbacks.
639 static int DbWalHandler(
647 SqliteDb *pDb = (SqliteDb*)clientData;
648 Tcl_Interp *interp = pDb->interp;
649 assert(pDb->pWalHook);
651 assert( db==pDb->db );
652 p = Tcl_DuplicateObj(pDb->pWalHook);
654 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
655 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
656 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
657 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
659 Tcl_BackgroundError(interp);
666 #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
667 static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
669 sprintf(zBuf, "%d", iArg);
670 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
671 sprintf(zBuf, "%d", nArg);
672 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
675 # define setTestUnlockNotifyVars(x,y,z)
678 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
679 static void DbUnlockNotify(void **apArg, int nArg){
681 for(i=0; i<nArg; i++){
682 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
683 SqliteDb *pDb = (SqliteDb *)apArg[i];
684 setTestUnlockNotifyVars(pDb->interp, i, nArg);
685 assert( pDb->pUnlockNotify);
686 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
687 Tcl_DecrRefCount(pDb->pUnlockNotify);
688 pDb->pUnlockNotify = 0;
693 static void DbUpdateHandler(
700 SqliteDb *pDb = (SqliteDb *)p;
703 assert( pDb->pUpdateHook );
704 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
706 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
707 Tcl_IncrRefCount(pCmd);
708 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
709 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
710 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
711 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
712 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
713 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
714 Tcl_DecrRefCount(pCmd);
717 static void tclCollateNeeded(
723 SqliteDb *pDb = (SqliteDb *)pCtx;
724 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
725 Tcl_IncrRefCount(pScript);
726 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
727 Tcl_EvalObjEx(pDb->interp, pScript, 0);
728 Tcl_DecrRefCount(pScript);
732 ** This routine is called to evaluate an SQL collation function implemented
735 static int tclSqlCollate(
742 SqlCollate *p = (SqlCollate *)pCtx;
745 pCmd = Tcl_NewStringObj(p->zScript, -1);
746 Tcl_IncrRefCount(pCmd);
747 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
748 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
749 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
750 Tcl_DecrRefCount(pCmd);
751 return (atoi(Tcl_GetStringResult(p->interp)));
755 ** This routine is called to evaluate an SQL function implemented
758 static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
759 SqlFunc *p = sqlite3_user_data(context);
765 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
766 ** script object directly. This allows the TCL compiler to generate
767 ** bytecode for the command on the first invocation and thus make
768 ** subsequent invocations much faster. */
770 Tcl_IncrRefCount(pCmd);
771 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
772 Tcl_DecrRefCount(pCmd);
774 /* If there are arguments to the function, make a shallow copy of the
775 ** script object, lappend the arguments, then evaluate the copy.
777 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
778 ** The new Tcl_Obj contains pointers to the original list elements.
779 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
780 ** of the list to tclCmdNameType, that alternate representation will
781 ** be preserved and reused on the next invocation.
785 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
786 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
789 pCmd = Tcl_NewListObj(nArg, aArg);
790 Tcl_IncrRefCount(pCmd);
791 for(i=0; i<argc; i++){
792 sqlite3_value *pIn = argv[i];
795 /* Set pVal to contain the i'th column of this row. */
796 switch( sqlite3_value_type(pIn) ){
798 int bytes = sqlite3_value_bytes(pIn);
799 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
802 case SQLITE_INTEGER: {
803 sqlite_int64 v = sqlite3_value_int64(pIn);
804 if( v>=-2147483647 && v<=2147483647 ){
805 pVal = Tcl_NewIntObj((int)v);
807 pVal = Tcl_NewWideIntObj(v);
812 double r = sqlite3_value_double(pIn);
813 pVal = Tcl_NewDoubleObj(r);
817 pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
821 int bytes = sqlite3_value_bytes(pIn);
822 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
826 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
828 Tcl_DecrRefCount(pCmd);
829 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
833 if( !p->useEvalObjv ){
834 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
835 ** is a list without a string representation. To prevent this from
836 ** happening, make sure pCmd has a valid string representation */
839 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
840 Tcl_DecrRefCount(pCmd);
843 if( rc && rc!=TCL_RETURN ){
844 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
846 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
849 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
851 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
852 /* Only return a BLOB type if the Tcl variable is a bytearray and
853 ** has no string representation. */
854 data = Tcl_GetByteArrayFromObj(pVar, &n);
855 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
856 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
857 Tcl_GetIntFromObj(0, pVar, &n);
858 sqlite3_result_int(context, n);
859 }else if( c=='d' && strcmp(zType,"double")==0 ){
861 Tcl_GetDoubleFromObj(0, pVar, &r);
862 sqlite3_result_double(context, r);
863 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
864 (c=='i' && strcmp(zType,"int")==0) ){
866 Tcl_GetWideIntFromObj(0, pVar, &v);
867 sqlite3_result_int64(context, v);
869 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
870 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
875 #ifndef SQLITE_OMIT_AUTHORIZATION
877 ** This is the authentication function. It appends the authentication
878 ** type code and the two arguments to zCmd[] then invokes the result
879 ** on the interpreter. The reply is examined to determine if the
880 ** authentication fails or succeeds.
882 static int auth_callback(
889 #ifdef SQLITE_USER_AUTHENTICATION
897 SqliteDb *pDb = (SqliteDb*)pArg;
898 if( pDb->disableAuth ) return SQLITE_OK;
901 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
902 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
903 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
904 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
905 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
906 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
907 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
908 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
909 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
910 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
911 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
912 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
913 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
914 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
915 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
916 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
917 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
918 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
919 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
920 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
921 case SQLITE_READ : zCode="SQLITE_READ"; break;
922 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
923 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
924 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
925 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
926 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
927 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
928 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
929 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
930 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
931 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
932 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
933 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
934 case SQLITE_RECURSIVE : zCode="SQLITE_RECURSIVE"; break;
935 default : zCode="????"; break;
937 Tcl_DStringInit(&str);
938 Tcl_DStringAppend(&str, pDb->zAuth, -1);
939 Tcl_DStringAppendElement(&str, zCode);
940 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
941 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
942 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
943 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
944 #ifdef SQLITE_USER_AUTHENTICATION
945 Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
947 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
948 Tcl_DStringFree(&str);
949 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
950 if( strcmp(zReply,"SQLITE_OK")==0 ){
952 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
954 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
961 #endif /* SQLITE_OMIT_AUTHORIZATION */
964 ** This routine reads a line of text from FILE in, stores
965 ** the text in memory obtained from malloc() and returns a pointer
966 ** to the text. NULL is returned at end of file, or if malloc()
969 ** The interface is like "readline" but no command-line editing
972 ** copied from shell.c from '.import' command
974 static char *local_getline(char *zPrompt, FILE *in){
980 zLine = malloc( nLine );
981 if( zLine==0 ) return 0;
985 nLine = nLine*2 + 100;
986 zLine = realloc(zLine, nLine);
987 if( zLine==0 ) return 0;
989 if( fgets(&zLine[n], nLine - n, in)==0 ){
997 while( zLine[n] ){ n++; }
998 if( n>0 && zLine[n-1]=='\n' ){
1004 zLine = realloc( zLine, n+1 );
1010 ** This function is part of the implementation of the command:
1012 ** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1014 ** It is invoked after evaluating the script SCRIPT to commit or rollback
1015 ** the transaction or savepoint opened by the [transaction] command.
1017 static int DbTransPostCmd(
1018 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1019 Tcl_Interp *interp, /* Tcl interpreter */
1020 int result /* Result of evaluating SCRIPT */
1022 static const char *const azEnd[] = {
1023 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1024 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1025 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1026 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1028 SqliteDb *pDb = (SqliteDb*)data[0];
1032 pDb->nTransaction--;
1033 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1036 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1037 /* This is a tricky scenario to handle. The most likely cause of an
1038 ** error is that the exec() above was an attempt to commit the
1039 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1040 ** that an IO-error has occurred. In either case, throw a Tcl exception
1041 ** and try to rollback the transaction.
1043 ** But it could also be that the user executed one or more BEGIN,
1044 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1045 ** this method's logic. Not clear how this would be best handled.
1047 if( rc!=TCL_ERROR ){
1048 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
1051 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1059 ** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1060 ** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1061 ** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1062 ** on whether or not the [db_use_legacy_prepare] command has been used to
1063 ** configure the connection.
1065 static int dbPrepare(
1066 SqliteDb *pDb, /* Database object */
1067 const char *zSql, /* SQL to compile */
1068 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1069 const char **pzOut /* OUT: Pointer to next SQL statement */
1072 if( pDb->bLegacyPrepare ){
1073 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1076 return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut);
1080 ** Search the cache for a prepared-statement object that implements the
1081 ** first SQL statement in the buffer pointed to by parameter zIn. If
1082 ** no such prepared-statement can be found, allocate and prepare a new
1083 ** one. In either case, bind the current values of the relevant Tcl
1084 ** variables to any $var, :var or @var variables in the statement. Before
1085 ** returning, set *ppPreStmt to point to the prepared-statement object.
1087 ** Output parameter *pzOut is set to point to the next SQL statement in
1088 ** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1091 ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1092 ** and an error message loaded into interpreter pDb->interp.
1094 static int dbPrepareAndBind(
1095 SqliteDb *pDb, /* Database object */
1096 char const *zIn, /* SQL to compile */
1097 char const **pzOut, /* OUT: Pointer to next SQL statement */
1098 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1100 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
1101 sqlite3_stmt *pStmt = 0; /* Prepared statement object */
1102 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1103 int nSql; /* Length of zSql in bytes */
1104 int nVar = 0; /* Number of variables in statement */
1105 int iParm = 0; /* Next free entry in apParm */
1108 Tcl_Interp *interp = pDb->interp;
1112 /* Trim spaces from the start of zSql and calculate the remaining length. */
1113 while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
1114 nSql = strlen30(zSql);
1116 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1117 int n = pPreStmt->nSql;
1119 && memcmp(pPreStmt->zSql, zSql, n)==0
1120 && (zSql[n]==0 || zSql[n-1]==';')
1122 pStmt = pPreStmt->pStmt;
1123 *pzOut = &zSql[pPreStmt->nSql];
1125 /* When a prepared statement is found, unlink it from the
1126 ** cache list. It will later be added back to the beginning
1127 ** of the cache list in order to implement LRU replacement.
1129 if( pPreStmt->pPrev ){
1130 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1132 pDb->stmtList = pPreStmt->pNext;
1134 if( pPreStmt->pNext ){
1135 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1137 pDb->stmtLast = pPreStmt->pPrev;
1140 nVar = sqlite3_bind_parameter_count(pStmt);
1145 /* If no prepared statement was found. Compile the SQL text. Also allocate
1146 ** a new SqlPreparedStmt structure. */
1150 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
1151 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1155 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1156 /* A compile-time error in the statement. */
1157 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1160 /* The statement was a no-op. Continue to the next statement
1161 ** in the SQL string.
1167 assert( pPreStmt==0 );
1168 nVar = sqlite3_bind_parameter_count(pStmt);
1169 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1170 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1171 memset(pPreStmt, 0, nByte);
1173 pPreStmt->pStmt = pStmt;
1174 pPreStmt->nSql = (int)(*pzOut - zSql);
1175 pPreStmt->zSql = sqlite3_sql(pStmt);
1176 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
1178 if( pPreStmt->zSql==0 ){
1179 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1180 memcpy(zCopy, zSql, pPreStmt->nSql);
1181 zCopy[pPreStmt->nSql] = '\0';
1182 pPreStmt->zSql = zCopy;
1187 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1188 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1190 /* Bind values to parameters that begin with $ or : */
1191 for(i=1; i<=nVar; i++){
1192 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1193 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1194 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1198 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1201 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1202 /* Load a BLOB type if the Tcl variable is a bytearray and
1203 ** it has no string representation or the host
1204 ** parameter name begins with "@". */
1205 data = Tcl_GetByteArrayFromObj(pVar, &n);
1206 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1207 Tcl_IncrRefCount(pVar);
1208 pPreStmt->apParm[iParm++] = pVar;
1209 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1210 Tcl_GetIntFromObj(interp, pVar, &n);
1211 sqlite3_bind_int(pStmt, i, n);
1212 }else if( c=='d' && strcmp(zType,"double")==0 ){
1214 Tcl_GetDoubleFromObj(interp, pVar, &r);
1215 sqlite3_bind_double(pStmt, i, r);
1216 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1217 (c=='i' && strcmp(zType,"int")==0) ){
1219 Tcl_GetWideIntFromObj(interp, pVar, &v);
1220 sqlite3_bind_int64(pStmt, i, v);
1222 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1223 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1224 Tcl_IncrRefCount(pVar);
1225 pPreStmt->apParm[iParm++] = pVar;
1228 sqlite3_bind_null(pStmt, i);
1232 pPreStmt->nParm = iParm;
1233 *ppPreStmt = pPreStmt;
1239 ** Release a statement reference obtained by calling dbPrepareAndBind().
1240 ** There should be exactly one call to this function for each call to
1241 ** dbPrepareAndBind().
1243 ** If the discard parameter is non-zero, then the statement is deleted
1244 ** immediately. Otherwise it is added to the LRU list and may be returned
1245 ** by a subsequent call to dbPrepareAndBind().
1247 static void dbReleaseStmt(
1248 SqliteDb *pDb, /* Database handle */
1249 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1250 int discard /* True to delete (not cache) the pPreStmt */
1254 /* Free the bound string and blob parameters */
1255 for(i=0; i<pPreStmt->nParm; i++){
1256 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1258 pPreStmt->nParm = 0;
1260 if( pDb->maxStmt<=0 || discard ){
1261 /* If the cache is turned off, deallocated the statement */
1262 dbFreeStmt(pPreStmt);
1264 /* Add the prepared statement to the beginning of the cache list. */
1265 pPreStmt->pNext = pDb->stmtList;
1266 pPreStmt->pPrev = 0;
1267 if( pDb->stmtList ){
1268 pDb->stmtList->pPrev = pPreStmt;
1270 pDb->stmtList = pPreStmt;
1271 if( pDb->stmtLast==0 ){
1272 assert( pDb->nStmt==0 );
1273 pDb->stmtLast = pPreStmt;
1275 assert( pDb->nStmt>0 );
1279 /* If we have too many statement in cache, remove the surplus from
1280 ** the end of the cache list. */
1281 while( pDb->nStmt>pDb->maxStmt ){
1282 SqlPreparedStmt *pLast = pDb->stmtLast;
1283 pDb->stmtLast = pLast->pPrev;
1284 pDb->stmtLast->pNext = 0;
1292 ** Structure used with dbEvalXXX() functions:
1298 ** dbEvalColumnValue()
1300 typedef struct DbEvalContext DbEvalContext;
1301 struct DbEvalContext {
1302 SqliteDb *pDb; /* Database handle */
1303 Tcl_Obj *pSql; /* Object holding string zSql */
1304 const char *zSql; /* Remaining SQL to execute */
1305 SqlPreparedStmt *pPreStmt; /* Current statement */
1306 int nCol; /* Number of columns returned by pStmt */
1307 Tcl_Obj *pArray; /* Name of array variable */
1308 Tcl_Obj **apColName; /* Array of column names */
1312 ** Release any cache of column names currently held as part of
1313 ** the DbEvalContext structure passed as the first argument.
1315 static void dbReleaseColumnNames(DbEvalContext *p){
1318 for(i=0; i<p->nCol; i++){
1319 Tcl_DecrRefCount(p->apColName[i]);
1321 Tcl_Free((char *)p->apColName);
1328 ** Initialize a DbEvalContext structure.
1330 ** If pArray is not NULL, then it contains the name of a Tcl array
1331 ** variable. The "*" member of this array is set to a list containing
1332 ** the names of the columns returned by the statement as part of each
1333 ** call to dbEvalStep(), in order from left to right. e.g. if the names
1334 ** of the returned columns are a, b and c, it does the equivalent of the
1337 ** set ${pArray}(*) {a b c}
1339 static void dbEvalInit(
1340 DbEvalContext *p, /* Pointer to structure to initialize */
1341 SqliteDb *pDb, /* Database handle */
1342 Tcl_Obj *pSql, /* Object containing SQL script */
1343 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
1345 memset(p, 0, sizeof(DbEvalContext));
1347 p->zSql = Tcl_GetString(pSql);
1349 Tcl_IncrRefCount(pSql);
1352 Tcl_IncrRefCount(pArray);
1357 ** Obtain information about the row that the DbEvalContext passed as the
1358 ** first argument currently points to.
1360 static void dbEvalRowInfo(
1361 DbEvalContext *p, /* Evaluation context */
1362 int *pnCol, /* OUT: Number of column names */
1363 Tcl_Obj ***papColName /* OUT: Array of column names */
1365 /* Compute column names */
1366 if( 0==p->apColName ){
1367 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1368 int i; /* Iterator variable */
1369 int nCol; /* Number of columns returned by pStmt */
1370 Tcl_Obj **apColName = 0; /* Array of column names */
1372 p->nCol = nCol = sqlite3_column_count(pStmt);
1373 if( nCol>0 && (papColName || p->pArray) ){
1374 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1375 for(i=0; i<nCol; i++){
1376 apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
1377 Tcl_IncrRefCount(apColName[i]);
1379 p->apColName = apColName;
1382 /* If results are being stored in an array variable, then create
1383 ** the array(*) entry for that array
1386 Tcl_Interp *interp = p->pDb->interp;
1387 Tcl_Obj *pColList = Tcl_NewObj();
1388 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
1390 for(i=0; i<nCol; i++){
1391 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1393 Tcl_IncrRefCount(pStar);
1394 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
1395 Tcl_DecrRefCount(pStar);
1400 *papColName = p->apColName;
1408 ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1409 ** returned, then an error message is stored in the interpreter before
1412 ** A return value of TCL_OK means there is a row of data available. The
1413 ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1414 ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1415 ** is returned, then the SQL script has finished executing and there are
1416 ** no further rows available. This is similar to SQLITE_DONE.
1418 static int dbEvalStep(DbEvalContext *p){
1419 const char *zPrevSql = 0; /* Previous value of p->zSql */
1421 while( p->zSql[0] || p->pPreStmt ){
1423 if( p->pPreStmt==0 ){
1424 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
1425 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1426 if( rc!=TCL_OK ) return rc;
1429 SqliteDb *pDb = p->pDb;
1430 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1431 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1433 rcs = sqlite3_step(pStmt);
1434 if( rcs==SQLITE_ROW ){
1438 dbEvalRowInfo(p, 0, 0);
1440 rcs = sqlite3_reset(pStmt);
1442 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1443 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
1444 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
1445 dbReleaseColumnNames(p);
1448 if( rcs!=SQLITE_OK ){
1449 /* If a run-time error occurs, report the error and stop reading
1451 dbReleaseStmt(pDb, pPreStmt, 1);
1453 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1454 /* If the runtime error was an SQLITE_SCHEMA, and the database
1455 ** handle is configured to use the legacy sqlite3_prepare()
1456 ** interface, retry prepare()/step() on the same SQL statement.
1457 ** This only happens once. If there is a second SQLITE_SCHEMA
1458 ** error, the error will be returned to the caller. */
1463 Tcl_SetObjResult(pDb->interp,
1464 Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1467 dbReleaseStmt(pDb, pPreStmt, 0);
1477 ** Free all resources currently held by the DbEvalContext structure passed
1478 ** as the first argument. There should be exactly one call to this function
1479 ** for each call to dbEvalInit().
1481 static void dbEvalFinalize(DbEvalContext *p){
1483 sqlite3_reset(p->pPreStmt->pStmt);
1484 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1488 Tcl_DecrRefCount(p->pArray);
1491 Tcl_DecrRefCount(p->pSql);
1492 dbReleaseColumnNames(p);
1496 ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1497 ** the value for the iCol'th column of the row currently pointed to by
1498 ** the DbEvalContext structure passed as the first argument.
1500 static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1501 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1502 switch( sqlite3_column_type(pStmt, iCol) ){
1504 int bytes = sqlite3_column_bytes(pStmt, iCol);
1505 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1506 if( !zBlob ) bytes = 0;
1507 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1509 case SQLITE_INTEGER: {
1510 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1511 if( v>=-2147483647 && v<=2147483647 ){
1512 return Tcl_NewIntObj((int)v);
1514 return Tcl_NewWideIntObj(v);
1517 case SQLITE_FLOAT: {
1518 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1521 return Tcl_NewStringObj(p->pDb->zNull, -1);
1525 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
1529 ** If using Tcl version 8.6 or greater, use the NR functions to avoid
1530 ** recursive evalution of scripts by the [db eval] and [db trans]
1531 ** commands. Even if the headers used while compiling the extension
1532 ** are 8.6 or newer, the code still tests the Tcl version at runtime.
1533 ** This allows stubs-enabled builds to be used with older Tcl libraries.
1535 #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
1536 # define SQLITE_TCL_NRE 1
1537 static int DbUseNre(void){
1539 Tcl_GetVersion(&major, &minor, 0, 0);
1540 return( (major==8 && minor>=6) || major>8 );
1544 ** Compiling using headers earlier than 8.6. In this case NR cannot be
1545 ** used, so DbUseNre() to always return zero. Add #defines for the other
1546 ** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1547 ** even though the only invocations of them are within conditional blocks
1550 ** if( DbUseNre() ) { ... }
1552 # define SQLITE_TCL_NRE 0
1553 # define DbUseNre() 0
1554 # define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
1555 # define Tcl_NREvalObj(a,b,c) 0
1556 # define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
1560 ** This function is part of the implementation of the command:
1562 ** $db eval SQL ?ARRAYNAME? SCRIPT
1564 static int DbEvalNextCmd(
1565 ClientData data[], /* data[0] is the (DbEvalContext*) */
1566 Tcl_Interp *interp, /* Tcl interpreter */
1567 int result /* Result so far */
1569 int rc = result; /* Return code */
1571 /* The first element of the data[] array is a pointer to a DbEvalContext
1572 ** structure allocated using Tcl_Alloc(). The second element of data[]
1573 ** is a pointer to a Tcl_Obj containing the script to run for each row
1574 ** returned by the queries encapsulated in data[0]. */
1575 DbEvalContext *p = (DbEvalContext *)data[0];
1576 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1577 Tcl_Obj *pArray = p->pArray;
1579 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1582 Tcl_Obj **apColName;
1583 dbEvalRowInfo(p, &nCol, &apColName);
1584 for(i=0; i<nCol; i++){
1585 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1587 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1589 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1593 /* The required interpreter variables are now populated with the data
1594 ** from the current row. If using NRE, schedule callbacks to evaluate
1595 ** script pScript, then to invoke this function again to fetch the next
1596 ** row (or clean up if there is no next row or the script throws an
1597 ** exception). After scheduling the callbacks, return control to the
1600 ** If not using NRE, evaluate pScript directly and continue with the
1601 ** next iteration of this while(...) loop. */
1603 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1604 return Tcl_NREvalObj(interp, pScript, 0);
1606 rc = Tcl_EvalObjEx(interp, pScript, 0);
1610 Tcl_DecrRefCount(pScript);
1612 Tcl_Free((char *)p);
1614 if( rc==TCL_OK || rc==TCL_BREAK ){
1615 Tcl_ResetResult(interp);
1622 ** The "sqlite" command below creates a new Tcl command for each
1623 ** connection it opens to an SQLite database. This routine is invoked
1624 ** whenever one of those connection-specific commands is executed
1625 ** in Tcl. For example, if you run Tcl code like this:
1627 ** sqlite3 db1 "my_database"
1630 ** The first command opens a connection to the "my_database" database
1631 ** and calls that connection "db1". The second command causes this
1632 ** subroutine to be invoked.
1634 static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
1635 SqliteDb *pDb = (SqliteDb*)cd;
1638 static const char *DB_strs[] = {
1639 "authorizer", "backup", "busy",
1640 "cache", "changes", "close",
1641 "collate", "collation_needed", "commit_hook",
1642 "complete", "copy", "enable_load_extension",
1643 "errorcode", "eval", "exists",
1644 "function", "incrblob", "interrupt",
1645 "last_insert_rowid", "nullvalue", "onecolumn",
1646 "profile", "progress", "rekey",
1647 "restore", "rollback_hook", "status",
1648 "timeout", "total_changes", "trace",
1649 "transaction", "unlock_notify", "update_hook",
1650 "version", "wal_hook", 0
1653 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1654 DB_CACHE, DB_CHANGES, DB_CLOSE,
1655 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1656 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1657 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1658 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
1659 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
1660 DB_PROFILE, DB_PROGRESS, DB_REKEY,
1661 DB_RESTORE, DB_ROLLBACK_HOOK, DB_STATUS,
1662 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
1663 DB_TRANSACTION, DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK,
1664 DB_VERSION, DB_WAL_HOOK
1666 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
1669 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
1672 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
1676 switch( (enum DB_enum)choice ){
1678 /* $db authorizer ?CALLBACK?
1680 ** Invoke the given callback to authorize each SQL operation as it is
1681 ** compiled. 5 arguments are appended to the callback before it is
1684 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1685 ** (2) First descriptive name (depends on authorization type)
1686 ** (3) Second descriptive name
1687 ** (4) Name of the database (ex: "main", "temp")
1688 ** (5) Name of trigger that is doing the access
1690 ** The callback should return on of the following strings: SQLITE_OK,
1691 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1693 ** If this method is invoked with no arguments, the current authorization
1694 ** callback string is returned.
1696 case DB_AUTHORIZER: {
1697 #ifdef SQLITE_OMIT_AUTHORIZATION
1698 Tcl_AppendResult(interp, "authorization not available in this build",
1703 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1705 }else if( objc==2 ){
1707 Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
1713 Tcl_Free(pDb->zAuth);
1715 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1716 if( zAuth && len>0 ){
1717 pDb->zAuth = Tcl_Alloc( len + 1 );
1718 memcpy(pDb->zAuth, zAuth, len+1);
1723 typedef int (*sqlite3_auth_cb)(
1724 void*,int,const char*,const char*,
1725 const char*,const char*);
1726 pDb->interp = interp;
1727 sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
1729 sqlite3_set_authorizer(pDb->db, 0, 0);
1736 /* $db backup ?DATABASE? FILENAME
1738 ** Open or create a database file named FILENAME. Transfer the
1739 ** content of local database DATABASE (default: "main") into the
1740 ** FILENAME database.
1743 const char *zDestFile;
1746 sqlite3_backup *pBackup;
1750 zDestFile = Tcl_GetString(objv[2]);
1751 }else if( objc==4 ){
1752 zSrcDb = Tcl_GetString(objv[2]);
1753 zDestFile = Tcl_GetString(objv[3]);
1755 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1758 rc = sqlite3_open(zDestFile, &pDest);
1759 if( rc!=SQLITE_OK ){
1760 Tcl_AppendResult(interp, "cannot open target database: ",
1761 sqlite3_errmsg(pDest), (char*)0);
1762 sqlite3_close(pDest);
1765 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1767 Tcl_AppendResult(interp, "backup failed: ",
1768 sqlite3_errmsg(pDest), (char*)0);
1769 sqlite3_close(pDest);
1772 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1773 sqlite3_backup_finish(pBackup);
1774 if( rc==SQLITE_DONE ){
1777 Tcl_AppendResult(interp, "backup failed: ",
1778 sqlite3_errmsg(pDest), (char*)0);
1781 sqlite3_close(pDest);
1785 /* $db busy ?CALLBACK?
1787 ** Invoke the given callback if an SQL statement attempts to open
1788 ** a locked database file.
1792 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
1794 }else if( objc==2 ){
1796 Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
1802 Tcl_Free(pDb->zBusy);
1804 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1805 if( zBusy && len>0 ){
1806 pDb->zBusy = Tcl_Alloc( len + 1 );
1807 memcpy(pDb->zBusy, zBusy, len+1);
1812 pDb->interp = interp;
1813 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
1815 sqlite3_busy_handler(pDb->db, 0, 0);
1824 ** Flush the prepared statement cache, or set the maximum number of
1825 ** cached statements.
1832 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1835 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1836 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1838 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1841 flushStmtCache( pDb );
1843 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1845 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1848 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1849 Tcl_AppendResult( interp, "cannot convert \"",
1850 Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
1854 flushStmtCache( pDb );
1856 }else if( n>MAX_PREPARED_STMTS ){
1857 n = MAX_PREPARED_STMTS;
1863 Tcl_AppendResult( interp, "bad option \"",
1864 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
1873 ** Return the number of rows that were modified, inserted, or deleted by
1874 ** the most recent INSERT, UPDATE or DELETE statement, not including
1875 ** any changes made by trigger programs.
1880 Tcl_WrongNumArgs(interp, 2, objv, "");
1883 pResult = Tcl_GetObjResult(interp);
1884 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
1890 ** Shutdown the database
1893 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1898 ** $db collate NAME SCRIPT
1900 ** Create a new SQL collation function called NAME. Whenever
1901 ** that function is called, invoke SCRIPT to evaluate the function.
1904 SqlCollate *pCollate;
1909 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1912 zName = Tcl_GetStringFromObj(objv[2], 0);
1913 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1914 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1915 if( pCollate==0 ) return TCL_ERROR;
1916 pCollate->interp = interp;
1917 pCollate->pNext = pDb->pCollate;
1918 pCollate->zScript = (char*)&pCollate[1];
1919 pDb->pCollate = pCollate;
1920 memcpy(pCollate->zScript, zScript, nScript+1);
1921 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1922 pCollate, tclSqlCollate) ){
1923 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
1930 ** $db collation_needed SCRIPT
1932 ** Create a new SQL collation function called NAME. Whenever
1933 ** that function is called, invoke SCRIPT to evaluate the function.
1935 case DB_COLLATION_NEEDED: {
1937 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1940 if( pDb->pCollateNeeded ){
1941 Tcl_DecrRefCount(pDb->pCollateNeeded);
1943 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1944 Tcl_IncrRefCount(pDb->pCollateNeeded);
1945 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1949 /* $db commit_hook ?CALLBACK?
1951 ** Invoke the given callback just before committing every SQL transaction.
1952 ** If the callback throws an exception or returns non-zero, then the
1953 ** transaction is aborted. If CALLBACK is an empty string, the callback
1956 case DB_COMMIT_HOOK: {
1958 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1960 }else if( objc==2 ){
1962 Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
1965 const char *zCommit;
1968 Tcl_Free(pDb->zCommit);
1970 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1971 if( zCommit && len>0 ){
1972 pDb->zCommit = Tcl_Alloc( len + 1 );
1973 memcpy(pDb->zCommit, zCommit, len+1);
1978 pDb->interp = interp;
1979 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1981 sqlite3_commit_hook(pDb->db, 0, 0);
1989 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1990 ** additional lines of input are needed. This is similar to the
1991 ** built-in "info complete" command of Tcl.
1994 #ifndef SQLITE_OMIT_COMPLETE
1998 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2001 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
2002 pResult = Tcl_GetObjResult(interp);
2003 Tcl_SetBooleanObj(pResult, isComplete);
2008 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2010 ** Copy data into table from filename, optionally using SEPARATOR
2011 ** as column separators. If a column contains a null string, or the
2012 ** value of NULLINDICATOR, a NULL is inserted for the column.
2013 ** conflict-algorithm is one of the sqlite conflict algorithms:
2014 ** rollback, abort, fail, ignore, replace
2015 ** On success, return the number of lines processed, not necessarily same
2016 ** as 'db changes' due to conflict-algorithm selected.
2018 ** This code is basically an implementation/enhancement of
2019 ** the sqlite3 shell.c ".import" command.
2021 ** This command usage is equivalent to the sqlite2.x COPY statement,
2022 ** which imports file data into a table using the PostgreSQL COPY file format:
2023 ** $db copy $conflit_algo $table_name $filename \t \\N
2026 char *zTable; /* Insert data into this table */
2027 char *zFile; /* The file from which to extract data */
2028 char *zConflict; /* The conflict algorithm to use */
2029 sqlite3_stmt *pStmt; /* A statement */
2030 int nCol; /* Number of columns in the table */
2031 int nByte; /* Number of bytes in an SQL string */
2032 int i, j; /* Loop counters */
2033 int nSep; /* Number of bytes in zSep[] */
2034 int nNull; /* Number of bytes in zNull[] */
2035 char *zSql; /* An SQL statement */
2036 char *zLine; /* A single line of input from the file */
2037 char **azCol; /* zLine[] broken up into columns */
2038 const char *zCommit; /* How to commit changes */
2039 FILE *in; /* The input file */
2040 int lineno = 0; /* Line number of input file */
2041 char zLineNum[80]; /* Line number print buffer */
2042 Tcl_Obj *pResult; /* interp result */
2046 if( objc<5 || objc>7 ){
2047 Tcl_WrongNumArgs(interp, 2, objv,
2048 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2052 zSep = Tcl_GetStringFromObj(objv[5], 0);
2057 zNull = Tcl_GetStringFromObj(objv[6], 0);
2061 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2062 zTable = Tcl_GetStringFromObj(objv[3], 0);
2063 zFile = Tcl_GetStringFromObj(objv[4], 0);
2064 nSep = strlen30(zSep);
2065 nNull = strlen30(zNull);
2067 Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2071 if(strcmp(zConflict, "rollback") != 0 &&
2072 strcmp(zConflict, "abort" ) != 0 &&
2073 strcmp(zConflict, "fail" ) != 0 &&
2074 strcmp(zConflict, "ignore" ) != 0 &&
2075 strcmp(zConflict, "replace" ) != 0 ) {
2076 Tcl_AppendResult(interp, "Error: \"", zConflict,
2077 "\", conflict-algorithm must be one of: rollback, "
2078 "abort, fail, ignore, or replace", (char*)0);
2081 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2083 Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
2086 nByte = strlen30(zSql);
2087 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
2090 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2093 nCol = sqlite3_column_count(pStmt);
2095 sqlite3_finalize(pStmt);
2099 zSql = malloc( nByte + 50 + nCol*2 );
2101 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
2104 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2107 for(i=1; i<nCol; i++){
2113 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
2116 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2117 sqlite3_finalize(pStmt);
2120 in = fopen(zFile, "rb");
2122 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2123 sqlite3_finalize(pStmt);
2126 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2128 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
2132 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
2134 while( (zLine = local_getline(0, in))!=0 ){
2138 for(i=0, z=zLine; *z; z++){
2139 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2143 azCol[i] = &z[nSep];
2150 int nErr = strlen30(zFile) + 200;
2151 zErr = malloc(nErr);
2153 sqlite3_snprintf(nErr, zErr,
2154 "Error: %s line %d: expected %d columns of data but found %d",
2155 zFile, lineno, nCol, i+1);
2156 Tcl_AppendResult(interp, zErr, (char*)0);
2159 zCommit = "ROLLBACK";
2162 for(i=0; i<nCol; i++){
2163 /* check for null data, if so, bind as null */
2164 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
2165 || strlen30(azCol[i])==0
2167 sqlite3_bind_null(pStmt, i+1);
2169 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2172 sqlite3_step(pStmt);
2173 rc = sqlite3_reset(pStmt);
2175 if( rc!=SQLITE_OK ){
2176 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2177 zCommit = "ROLLBACK";
2183 sqlite3_finalize(pStmt);
2184 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
2186 if( zCommit[0] == 'C' ){
2187 /* success, set result as number of lines processed */
2188 pResult = Tcl_GetObjResult(interp);
2189 Tcl_SetIntObj(pResult, lineno);
2192 /* failure, append lineno where failed */
2193 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
2194 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2202 ** $db enable_load_extension BOOLEAN
2204 ** Turn the extension loading feature on or off. It if off by
2207 case DB_ENABLE_LOAD_EXTENSION: {
2208 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2211 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2214 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2217 sqlite3_enable_load_extension(pDb->db, onoff);
2220 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2229 ** Return the numeric error code that was returned by the most recent
2230 ** call to sqlite3_exec().
2232 case DB_ERRORCODE: {
2233 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
2239 ** $db onecolumn $sql
2241 ** The onecolumn method is the equivalent of:
2242 ** lindex [$db eval $sql] 0
2245 case DB_ONECOLUMN: {
2246 DbEvalContext sEval;
2248 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2252 dbEvalInit(&sEval, pDb, objv[2], 0);
2253 rc = dbEvalStep(&sEval);
2254 if( choice==DB_ONECOLUMN ){
2256 Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
2257 }else if( rc==TCL_BREAK ){
2258 Tcl_ResetResult(interp);
2260 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2261 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
2263 dbEvalFinalize(&sEval);
2265 if( rc==TCL_BREAK ){
2272 ** $db eval $sql ?array? ?{ ...code... }?
2274 ** The SQL statement in $sql is evaluated. For each row, the values are
2275 ** placed in elements of the array named "array" and ...code... is executed.
2276 ** If "array" and "code" are omitted, then no callback is every invoked.
2277 ** If "array" is an empty string, then the values are placed in variables
2278 ** that have the same name as the fields extracted by the query.
2281 if( objc<3 || objc>5 ){
2282 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2287 DbEvalContext sEval;
2288 Tcl_Obj *pRet = Tcl_NewObj();
2289 Tcl_IncrRefCount(pRet);
2290 dbEvalInit(&sEval, pDb, objv[2], 0);
2291 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2294 dbEvalRowInfo(&sEval, &nCol, 0);
2295 for(i=0; i<nCol; i++){
2296 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
2299 dbEvalFinalize(&sEval);
2300 if( rc==TCL_BREAK ){
2301 Tcl_SetObjResult(interp, pRet);
2304 Tcl_DecrRefCount(pRet);
2308 Tcl_Obj *pArray = 0;
2311 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2314 pScript = objv[objc-1];
2315 Tcl_IncrRefCount(pScript);
2317 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2318 dbEvalInit(p, pDb, objv[2], pArray);
2321 cd[1] = (void *)pScript;
2322 rc = DbEvalNextCmd(cd, interp, TCL_OK);
2328 ** $db function NAME [-argcount N] SCRIPT
2330 ** Create a new SQL function called NAME. Whenever that function is
2331 ** called, invoke SCRIPT to evaluate the function.
2339 const char *z = Tcl_GetString(objv[3]);
2340 int n = strlen30(z);
2341 if( n>2 && strncmp(z, "-argcount",n)==0 ){
2342 if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
2344 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2350 }else if( objc!=4 ){
2351 Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
2356 zName = Tcl_GetStringFromObj(objv[2], 0);
2357 pFunc = findSqlFunc(pDb, zName);
2358 if( pFunc==0 ) return TCL_ERROR;
2359 if( pFunc->pScript ){
2360 Tcl_DecrRefCount(pFunc->pScript);
2362 pFunc->pScript = pScript;
2363 Tcl_IncrRefCount(pScript);
2364 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
2365 rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
2366 pFunc, tclSqlFunc, 0, 0);
2367 if( rc!=SQLITE_OK ){
2369 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
2375 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
2378 #ifdef SQLITE_OMIT_INCRBLOB
2379 Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
2383 const char *zDb = "main";
2385 const char *zColumn;
2388 /* Check for the -readonly option */
2389 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2393 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2394 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
2398 if( objc==(6+isReadonly) ){
2399 zDb = Tcl_GetString(objv[2]);
2401 zTable = Tcl_GetString(objv[objc-3]);
2402 zColumn = Tcl_GetString(objv[objc-2]);
2403 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2406 rc = createIncrblobChannel(
2407 interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
2417 ** Interrupt the execution of the inner-most SQL interpreter. This
2418 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2420 case DB_INTERRUPT: {
2421 sqlite3_interrupt(pDb->db);
2426 ** $db nullvalue ?STRING?
2428 ** Change text used when a NULL comes back from the database. If ?STRING?
2429 ** is not present, then the current string used for NULL is returned.
2430 ** If STRING is present, then STRING is returned.
2433 case DB_NULLVALUE: {
2434 if( objc!=2 && objc!=3 ){
2435 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2440 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2442 Tcl_Free(pDb->zNull);
2444 if( zNull && len>0 ){
2445 pDb->zNull = Tcl_Alloc( len + 1 );
2446 memcpy(pDb->zNull, zNull, len);
2447 pDb->zNull[len] = '\0';
2452 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
2457 ** $db last_insert_rowid
2459 ** Return an integer which is the ROWID for the most recent insert.
2461 case DB_LAST_INSERT_ROWID: {
2465 Tcl_WrongNumArgs(interp, 2, objv, "");
2468 rowid = sqlite3_last_insert_rowid(pDb->db);
2469 pResult = Tcl_GetObjResult(interp);
2470 Tcl_SetWideIntObj(pResult, rowid);
2475 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
2478 /* $db progress ?N CALLBACK?
2480 ** Invoke the given callback every N virtual machine opcodes while executing
2485 if( pDb->zProgress ){
2486 Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
2488 }else if( objc==4 ){
2492 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
2495 if( pDb->zProgress ){
2496 Tcl_Free(pDb->zProgress);
2498 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2499 if( zProgress && len>0 ){
2500 pDb->zProgress = Tcl_Alloc( len + 1 );
2501 memcpy(pDb->zProgress, zProgress, len+1);
2505 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2506 if( pDb->zProgress ){
2507 pDb->interp = interp;
2508 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2510 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2514 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
2520 /* $db profile ?CALLBACK?
2522 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2523 ** that has run. The text of the SQL and the amount of elapse time are
2524 ** appended to CALLBACK before the script is run.
2528 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2530 }else if( objc==2 ){
2531 if( pDb->zProfile ){
2532 Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
2537 if( pDb->zProfile ){
2538 Tcl_Free(pDb->zProfile);
2540 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2541 if( zProfile && len>0 ){
2542 pDb->zProfile = Tcl_Alloc( len + 1 );
2543 memcpy(pDb->zProfile, zProfile, len+1);
2547 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
2548 if( pDb->zProfile ){
2549 pDb->interp = interp;
2550 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2552 sqlite3_profile(pDb->db, 0, 0);
2562 ** Change the encryption key on the currently open database.
2565 #ifdef SQLITE_HAS_CODEC
2570 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2573 #ifdef SQLITE_HAS_CODEC
2574 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
2575 rc = sqlite3_rekey(pDb->db, pKey, nKey);
2577 Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
2584 /* $db restore ?DATABASE? FILENAME
2586 ** Open a database file named FILENAME. Transfer the content
2587 ** of FILENAME into the local database DATABASE (default: "main").
2590 const char *zSrcFile;
2591 const char *zDestDb;
2593 sqlite3_backup *pBackup;
2598 zSrcFile = Tcl_GetString(objv[2]);
2599 }else if( objc==4 ){
2600 zDestDb = Tcl_GetString(objv[2]);
2601 zSrcFile = Tcl_GetString(objv[3]);
2603 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2606 rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
2607 if( rc!=SQLITE_OK ){
2608 Tcl_AppendResult(interp, "cannot open source database: ",
2609 sqlite3_errmsg(pSrc), (char*)0);
2610 sqlite3_close(pSrc);
2613 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2615 Tcl_AppendResult(interp, "restore failed: ",
2616 sqlite3_errmsg(pDb->db), (char*)0);
2617 sqlite3_close(pSrc);
2620 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2621 || rc==SQLITE_BUSY ){
2622 if( rc==SQLITE_BUSY ){
2623 if( nTimeout++ >= 3 ) break;
2627 sqlite3_backup_finish(pBackup);
2628 if( rc==SQLITE_DONE ){
2630 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2631 Tcl_AppendResult(interp, "restore failed: source database busy",
2635 Tcl_AppendResult(interp, "restore failed: ",
2636 sqlite3_errmsg(pDb->db), (char*)0);
2639 sqlite3_close(pSrc);
2644 ** $db status (step|sort|autoindex)
2646 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2647 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2653 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
2656 zOp = Tcl_GetString(objv[2]);
2657 if( strcmp(zOp, "step")==0 ){
2659 }else if( strcmp(zOp, "sort")==0 ){
2661 }else if( strcmp(zOp, "autoindex")==0 ){
2664 Tcl_AppendResult(interp,
2665 "bad argument: should be autoindex, step, or sort",
2669 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2674 ** $db timeout MILLESECONDS
2676 ** Delay for the number of milliseconds specified when a file is locked.
2681 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
2684 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
2685 sqlite3_busy_timeout(pDb->db, ms);
2690 ** $db total_changes
2692 ** Return the number of rows that were modified, inserted, or deleted
2693 ** since the database handle was created.
2695 case DB_TOTAL_CHANGES: {
2698 Tcl_WrongNumArgs(interp, 2, objv, "");
2701 pResult = Tcl_GetObjResult(interp);
2702 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2706 /* $db trace ?CALLBACK?
2708 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2709 ** that is executed. The text of the SQL is appended to CALLBACK before
2714 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2716 }else if( objc==2 ){
2718 Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
2724 Tcl_Free(pDb->zTrace);
2726 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2727 if( zTrace && len>0 ){
2728 pDb->zTrace = Tcl_Alloc( len + 1 );
2729 memcpy(pDb->zTrace, zTrace, len+1);
2733 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
2735 pDb->interp = interp;
2736 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
2738 sqlite3_trace(pDb->db, 0, 0);
2745 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2747 ** Start a new transaction (if we are not already in the midst of a
2748 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2749 ** completes, either commit the transaction or roll it back if SCRIPT
2750 ** throws an exception. Or if no new transation was started, do nothing.
2751 ** pass the exception on up the stack.
2753 ** This command was inspired by Dave Thomas's talk on Ruby at the
2754 ** 2005 O'Reilly Open Source Convention (OSCON).
2756 case DB_TRANSACTION: {
2758 const char *zBegin = "SAVEPOINT _tcl_transaction";
2759 if( objc!=3 && objc!=4 ){
2760 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2764 if( pDb->nTransaction==0 && objc==4 ){
2765 static const char *TTYPE_strs[] = {
2766 "deferred", "exclusive", "immediate", 0
2769 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2772 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
2776 switch( (enum TTYPE_enum)ttype ){
2777 case TTYPE_DEFERRED: /* no-op */; break;
2778 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2779 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2782 pScript = objv[objc-1];
2784 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
2786 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2788 if( rc!=SQLITE_OK ){
2789 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
2792 pDb->nTransaction++;
2794 /* If using NRE, schedule a callback to invoke the script pScript, then
2795 ** a second callback to commit (or rollback) the transaction or savepoint
2796 ** opened above. If not using NRE, evaluate the script directly, then
2797 ** call function DbTransPostCmd() to commit (or rollback) the transaction
2800 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
2801 (void)Tcl_NREvalObj(interp, pScript, 0);
2803 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
2809 ** $db unlock_notify ?script?
2811 case DB_UNLOCK_NOTIFY: {
2812 #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2813 Tcl_AppendResult(interp, "unlock_notify not available in this build",
2817 if( objc!=2 && objc!=3 ){
2818 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2821 void (*xNotify)(void **, int) = 0;
2822 void *pNotifyArg = 0;
2824 if( pDb->pUnlockNotify ){
2825 Tcl_DecrRefCount(pDb->pUnlockNotify);
2826 pDb->pUnlockNotify = 0;
2830 xNotify = DbUnlockNotify;
2831 pNotifyArg = (void *)pDb;
2832 pDb->pUnlockNotify = objv[2];
2833 Tcl_IncrRefCount(pDb->pUnlockNotify);
2836 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
2837 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
2846 ** $db wal_hook ?script?
2847 ** $db update_hook ?script?
2848 ** $db rollback_hook ?script?
2851 case DB_UPDATE_HOOK:
2852 case DB_ROLLBACK_HOOK: {
2854 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2855 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2858 if( choice==DB_UPDATE_HOOK ){
2859 ppHook = &pDb->pUpdateHook;
2860 }else if( choice==DB_WAL_HOOK ){
2861 ppHook = &pDb->pWalHook;
2863 ppHook = &pDb->pRollbackHook;
2866 if( objc!=2 && objc!=3 ){
2867 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2871 Tcl_SetObjResult(interp, *ppHook);
2873 Tcl_DecrRefCount(*ppHook);
2878 assert( !(*ppHook) );
2879 if( Tcl_GetCharLength(objv[2])>0 ){
2881 Tcl_IncrRefCount(*ppHook);
2885 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2886 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
2887 sqlite3_wal_hook(pDb->db,(pDb->pWalHook?DbWalHandler:0),pDb);
2894 ** Return the version string for this database.
2897 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2902 } /* End of the SWITCH statement */
2908 ** Adaptor that provides an objCmd interface to the NRE-enabled
2909 ** interface implementation.
2911 static int DbObjCmdAdaptor(
2917 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
2919 #endif /* SQLITE_TCL_NRE */
2922 ** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
2923 ** ?-create BOOLEAN? ?-nomutex BOOLEAN?
2925 ** This is the main Tcl command. When the "sqlite" Tcl command is
2926 ** invoked, this routine runs to process that command.
2928 ** The first argument, DBNAME, is an arbitrary name for a new
2929 ** database connection. This command creates a new command named
2930 ** DBNAME that is used to control that connection. The database
2931 ** connection is deleted when the DBNAME command is deleted.
2933 ** The second argument is the name of the database file.
2936 static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
2942 const char *zVfs = 0;
2944 Tcl_DString translatedFilename;
2945 #ifdef SQLITE_HAS_CODEC
2951 /* In normal use, each TCL interpreter runs in a single thread. So
2952 ** by default, we can turn of mutexing on SQLite database connections.
2953 ** However, for testing purposes it is useful to have mutexes turned
2954 ** on. So, by default, mutexes default off. But if compiled with
2955 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
2957 #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
2958 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
2960 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
2964 zArg = Tcl_GetStringFromObj(objv[1], 0);
2965 if( strcmp(zArg,"-version")==0 ){
2966 Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
2969 if( strcmp(zArg,"-has-codec")==0 ){
2970 #ifdef SQLITE_HAS_CODEC
2971 Tcl_AppendResult(interp,"1",(char*)0);
2973 Tcl_AppendResult(interp,"0",(char*)0);
2978 for(i=3; i+1<objc; i+=2){
2979 zArg = Tcl_GetString(objv[i]);
2980 if( strcmp(zArg,"-key")==0 ){
2981 #ifdef SQLITE_HAS_CODEC
2982 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
2984 }else if( strcmp(zArg, "-vfs")==0 ){
2985 zVfs = Tcl_GetString(objv[i+1]);
2986 }else if( strcmp(zArg, "-readonly")==0 ){
2988 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2990 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
2991 flags |= SQLITE_OPEN_READONLY;
2993 flags &= ~SQLITE_OPEN_READONLY;
2994 flags |= SQLITE_OPEN_READWRITE;
2996 }else if( strcmp(zArg, "-create")==0 ){
2998 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2999 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
3000 flags |= SQLITE_OPEN_CREATE;
3002 flags &= ~SQLITE_OPEN_CREATE;
3004 }else if( strcmp(zArg, "-nomutex")==0 ){
3006 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3008 flags |= SQLITE_OPEN_NOMUTEX;
3009 flags &= ~SQLITE_OPEN_FULLMUTEX;
3011 flags &= ~SQLITE_OPEN_NOMUTEX;
3013 }else if( strcmp(zArg, "-fullmutex")==0 ){
3015 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3017 flags |= SQLITE_OPEN_FULLMUTEX;
3018 flags &= ~SQLITE_OPEN_NOMUTEX;
3020 flags &= ~SQLITE_OPEN_FULLMUTEX;
3022 }else if( strcmp(zArg, "-uri")==0 ){
3024 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3026 flags |= SQLITE_OPEN_URI;
3028 flags &= ~SQLITE_OPEN_URI;
3031 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3035 if( objc<3 || (objc&1)!=1 ){
3036 Tcl_WrongNumArgs(interp, 1, objv,
3037 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
3038 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
3039 #ifdef SQLITE_HAS_CODEC
3046 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
3048 Tcl_SetResult(interp, (char *)"malloc failed", TCL_STATIC);
3051 memset(p, 0, sizeof(*p));
3052 zFile = Tcl_GetStringFromObj(objv[2], 0);
3053 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
3054 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
3055 Tcl_DStringFree(&translatedFilename);
3057 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3058 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3059 sqlite3_close(p->db);
3063 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
3065 #ifdef SQLITE_HAS_CODEC
3067 sqlite3_key(p->db, pKey, nKey);
3071 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
3073 sqlite3_free(zErrMsg);
3076 p->maxStmt = NUM_PREPARED_STMTS;
3078 zArg = Tcl_GetStringFromObj(objv[1], 0);
3080 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3081 (char*)p, DbDeleteCmd);
3083 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3089 ** Provide a dummy Tcl_InitStubs if we are using this as a static
3092 #ifndef USE_TCL_STUBS
3093 # undef Tcl_InitStubs
3094 # define Tcl_InitStubs(a,b,c) TCL_VERSION
3098 ** Make sure we have a PACKAGE_VERSION macro defined. This will be
3099 ** defined automatically by the TEA makefile. But other makefiles
3100 ** do not define it.
3102 #ifndef PACKAGE_VERSION
3103 # define PACKAGE_VERSION SQLITE_VERSION
3107 ** Initialize this module.
3109 ** This Tcl module contains only a single new Tcl command named "sqlite".
3110 ** (Hence there is no namespace. There is no point in using a namespace
3111 ** if the extension only supplies one new name!) The "sqlite" command is
3112 ** used to open a new SQLite database. See the DbMain() routine above
3113 ** for additional information.
3115 ** The EXTERN macros are required by TCL in order to work on windows.
3117 EXTERN int Sqlite3_Init(Tcl_Interp *interp){
3118 int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
3120 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
3121 #ifndef SQLITE_3_SUFFIX_ONLY
3122 /* The "sqlite" alias is undocumented. It is here only to support
3123 ** legacy scripts. All new scripts should use only the "sqlite3"
3125 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
3127 rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3131 EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3132 EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3133 EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3135 /* Because it accesses the file-system and uses persistent state, SQLite
3136 ** is not considered appropriate for safe interpreters. Hence, we deliberately
3137 ** omit the _SafeInit() interfaces.
3140 #ifndef SQLITE_3_SUFFIX_ONLY
3141 int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3142 int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3143 int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3144 int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3148 /*****************************************************************************
3149 ** All of the code that follows is used to build standalone TCL interpreters
3150 ** that are statically linked with SQLite. Enable these by compiling
3151 ** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3152 ** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3153 ** analysis program.
3156 #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3158 * This code implements the MD5 message-digest algorithm.
3159 * The algorithm is due to Ron Rivest. This code was
3160 * written by Colin Plumb in 1993, no copyright is claimed.
3161 * This code is in the public domain; do with it what you wish.
3163 * Equivalent code is available from RSA Data Security, Inc.
3164 * This code has been tested against that, and is equivalent,
3165 * except that you don't need to include two pages of legalese
3168 * To compute the message digest of a chunk of bytes, declare an
3169 * MD5Context structure, pass it to MD5Init, call MD5Update as
3170 * needed on buffers full of bytes, and then call MD5Final, which
3171 * will fill a supplied 16-byte array with the digest.
3175 * If compiled on a machine that doesn't have a 32-bit integer,
3176 * you just set "uint32" to the appropriate datatype for an
3177 * unsigned 32-bit integer. For example:
3179 * cc -Duint32='unsigned long' md5.c
3183 # define uint32 unsigned int
3190 unsigned char in[64];
3192 typedef struct MD5Context MD5Context;
3195 * Note: this code is harmless on little-endian machines.
3197 static void byteReverse (unsigned char *buf, unsigned longs){
3200 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3201 ((unsigned)buf[1]<<8 | buf[0]);
3206 /* The four core functions - F1 is optimized somewhat */
3208 /* #define F1(x, y, z) (x & y | ~x & z) */
3209 #define F1(x, y, z) (z ^ (x & (y ^ z)))
3210 #define F2(x, y, z) F1(z, x, y)
3211 #define F3(x, y, z) (x ^ y ^ z)
3212 #define F4(x, y, z) (y ^ (x | ~z))
3214 /* This is the central step in the MD5 algorithm. */
3215 #define MD5STEP(f, w, x, y, z, data, s) \
3216 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3219 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3220 * reflect the addition of 16 longwords of new data. MD5Update blocks
3221 * the data and converts bytes into longwords for this routine.
3223 static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3224 register uint32 a, b, c, d;
3231 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3232 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3233 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3234 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3235 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3236 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3237 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3238 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3239 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3240 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3241 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3242 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3243 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3244 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3245 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3246 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3248 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3249 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3250 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3251 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3252 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3253 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3254 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3255 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3256 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3257 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3258 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3259 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3260 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3261 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3262 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3263 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3265 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3266 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3267 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3268 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3269 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3270 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3271 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3272 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3273 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3274 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3275 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3276 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3277 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3278 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3279 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3280 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3282 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3283 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3284 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3285 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3286 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3287 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3288 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3289 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3290 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3291 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3292 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3293 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3294 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3295 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3296 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3297 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3306 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3307 * initialization constants.
3309 static void MD5Init(MD5Context *ctx){
3311 ctx->buf[0] = 0x67452301;
3312 ctx->buf[1] = 0xefcdab89;
3313 ctx->buf[2] = 0x98badcfe;
3314 ctx->buf[3] = 0x10325476;
3320 * Update context to reflect the concatenation of another buffer full
3324 void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3327 /* Update bitcount */
3330 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3331 ctx->bits[1]++; /* Carry from low to high */
3332 ctx->bits[1] += len >> 29;
3334 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3336 /* Handle any leading odd-sized chunks */
3339 unsigned char *p = (unsigned char *)ctx->in + t;
3343 memcpy(p, buf, len);
3347 byteReverse(ctx->in, 16);
3348 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3353 /* Process data in 64-byte chunks */
3356 memcpy(ctx->in, buf, 64);
3357 byteReverse(ctx->in, 16);
3358 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3363 /* Handle any remaining bytes of data. */
3365 memcpy(ctx->in, buf, len);
3369 * Final wrapup - pad to 64-byte boundary with the bit pattern
3370 * 1 0* (64-bit count of bits processed, MSB-first)
3372 static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3376 /* Compute number of bytes mod 64 */
3377 count = (ctx->bits[0] >> 3) & 0x3F;
3379 /* Set the first char of padding to 0x80. This is safe since there is
3380 always at least one byte free */
3381 p = ctx->in + count;
3384 /* Bytes of padding needed to make 64 bytes */
3385 count = 64 - 1 - count;
3387 /* Pad out to 56 mod 64 */
3389 /* Two lots of padding: Pad the first block to 64 bytes */
3390 memset(p, 0, count);
3391 byteReverse(ctx->in, 16);
3392 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3394 /* Now fill the next block with 56 bytes */
3395 memset(ctx->in, 0, 56);
3397 /* Pad block to 56 bytes */
3398 memset(p, 0, count-8);
3400 byteReverse(ctx->in, 14);
3402 /* Append length in bits and transform */
3403 memcpy(ctx->in + 14*4, ctx->bits, 8);
3405 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3406 byteReverse((unsigned char *)ctx->buf, 4);
3407 memcpy(digest, ctx->buf, 16);
3411 ** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3413 static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3414 static char const zEncode[] = "0123456789abcdef";
3417 for(j=i=0; i<16; i++){
3419 zBuf[j++] = zEncode[(a>>4)&0xf];
3420 zBuf[j++] = zEncode[a & 0xf];
3427 ** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3428 ** each representing 16 bits of the digest and separated from each
3429 ** other by a "-" character.
3431 static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3434 for(i=j=0; i<16; i+=2){
3435 x = digest[i]*256 + digest[i+1];
3436 if( i>0 ) zDigest[j++] = '-';
3437 sprintf(&zDigest[j], "%05u", x);
3444 ** A TCL command for md5. The argument is the text to be hashed. The
3445 ** Result is the hash in base64.
3447 static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3449 unsigned char digest[16];
3451 void (*converter)(unsigned char*, char*);
3454 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3455 " TEXT\"", (char*)0);
3459 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3460 MD5Final(digest, &ctx);
3461 converter = (void(*)(unsigned char*,char*))cd;
3462 converter(digest, zBuf);
3463 Tcl_AppendResult(interp, zBuf, (char*)0);
3468 ** A TCL command to take the md5 hash of a file. The argument is the
3469 ** name of the file.
3471 static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3474 void (*converter)(unsigned char*, char*);
3475 unsigned char digest[16];
3479 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3480 " FILENAME\"", (char*)0);
3483 in = fopen(argv[1],"rb");
3485 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
3486 "\" for reading", (char*)0);
3492 n = (int)fread(zBuf, 1, sizeof(zBuf), in);
3494 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3497 MD5Final(digest, &ctx);
3498 converter = (void(*)(unsigned char*,char*))cd;
3499 converter(digest, zBuf);
3500 Tcl_AppendResult(interp, zBuf, (char*)0);
3505 ** Register the four new TCL commands for generating MD5 checksums
3506 ** with the TCL interpreter.
3508 int Md5_Init(Tcl_Interp *interp){
3509 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3510 MD5DigestToBase16, 0);
3511 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3512 MD5DigestToBase10x8, 0);
3513 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3514 MD5DigestToBase16, 0);
3515 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3516 MD5DigestToBase10x8, 0);
3519 #endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3521 #if defined(SQLITE_TEST)
3523 ** During testing, the special md5sum() aggregate function is available.
3524 ** inside SQLite. The following routines implement that function.
3526 static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3529 if( argc<1 ) return;
3530 p = sqlite3_aggregate_context(context, sizeof(*p));
3535 for(i=0; i<argc; i++){
3536 const char *zData = (char*)sqlite3_value_text(argv[i]);
3538 MD5Update(p, (unsigned char*)zData, (int)strlen(zData));
3542 static void md5finalize(sqlite3_context *context){
3544 unsigned char digest[16];
3546 p = sqlite3_aggregate_context(context, sizeof(*p));
3548 MD5DigestToBase16(digest, zBuf);
3549 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3551 int Md5_Register(sqlite3 *db){
3552 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
3553 md5step, md5finalize);
3554 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3557 #endif /* defined(SQLITE_TEST) */
3561 ** If the macro TCLSH is one, then put in code this for the
3562 ** "main" routine that will initialize Tcl and take input from
3563 ** standard input, or if a file is named on the command line
3564 ** the TCL interpreter reads and evaluates that file.
3567 static const char *tclsh_main_loop(void){
3568 static const char zMainloop[] =
3570 "while {![eof stdin]} {\n"
3571 "if {$line!=\"\"} {\n"
3572 "puts -nonewline \"> \"\n"
3574 "puts -nonewline \"% \"\n"
3577 "append line [gets stdin]\n"
3578 "if {[info complete $line]} {\n"
3579 "if {[catch {uplevel #0 $line} result]} {\n"
3580 "puts stderr \"Error: $result\"\n"
3581 "} elseif {$result!=\"\"} {\n"
3594 static const char *tclsh_main_loop(void);
3598 static void init_all(Tcl_Interp *);
3599 static int init_all_cmd(
3603 Tcl_Obj *CONST objv[]
3608 Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3612 slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3622 ** Tclcmd: db_use_legacy_prepare DB BOOLEAN
3624 ** The first argument to this command must be a database command created by
3625 ** [sqlite3]. If the second argument is true, then the handle is configured
3626 ** to use the sqlite3_prepare_v2() function to prepare statements. If it
3627 ** is false, sqlite3_prepare().
3629 static int db_use_legacy_prepare_cmd(
3633 Tcl_Obj *CONST objv[]
3635 Tcl_CmdInfo cmdInfo;
3640 Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
3644 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3645 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3648 pDb = (SqliteDb*)cmdInfo.objClientData;
3649 if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
3653 pDb->bLegacyPrepare = bPrepare;
3655 Tcl_ResetResult(interp);
3660 ** Tclcmd: db_last_stmt_ptr DB
3662 ** If the statement cache associated with database DB is not empty,
3663 ** return the text representation of the most recently used statement
3666 static int db_last_stmt_ptr(
3670 Tcl_Obj *CONST objv[]
3672 extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
3673 Tcl_CmdInfo cmdInfo;
3675 sqlite3_stmt *pStmt = 0;
3679 Tcl_WrongNumArgs(interp, 1, objv, "DB");
3683 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3684 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3687 pDb = (SqliteDb*)cmdInfo.objClientData;
3689 if( pDb->stmtList ) pStmt = pDb->stmtList->pStmt;
3690 if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ){
3693 Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
3700 ** Configure the interpreter passed as the first argument to have access
3701 ** to the commands and linked variables that make up:
3703 ** * the [sqlite3] extension itself,
3705 ** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
3707 ** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
3710 static void init_all(Tcl_Interp *interp){
3711 Sqlite3_Init(interp);
3713 #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3717 /* Install the [register_dbstat_vtab] command to access the implementation
3718 ** of virtual table dbstat (source file test_stat.c). This command is
3719 ** required for testfixture and sqlite3_analyzer, but not by the production
3720 ** Tcl extension. */
3721 #if defined(SQLITE_TEST) || TCLSH==2
3723 extern int SqlitetestStat_Init(Tcl_Interp*);
3724 SqlitetestStat_Init(interp);
3730 extern int Sqliteconfig_Init(Tcl_Interp*);
3731 extern int Sqlitetest1_Init(Tcl_Interp*);
3732 extern int Sqlitetest2_Init(Tcl_Interp*);
3733 extern int Sqlitetest3_Init(Tcl_Interp*);
3734 extern int Sqlitetest4_Init(Tcl_Interp*);
3735 extern int Sqlitetest5_Init(Tcl_Interp*);
3736 extern int Sqlitetest6_Init(Tcl_Interp*);
3737 extern int Sqlitetest7_Init(Tcl_Interp*);
3738 extern int Sqlitetest8_Init(Tcl_Interp*);
3739 extern int Sqlitetest9_Init(Tcl_Interp*);
3740 extern int Sqlitetestasync_Init(Tcl_Interp*);
3741 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
3742 extern int Sqlitetest_blob_Init(Tcl_Interp*);
3743 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
3744 extern int Sqlitetest_func_Init(Tcl_Interp*);
3745 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
3746 extern int Sqlitetest_init_Init(Tcl_Interp*);
3747 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
3748 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
3749 extern int Sqlitetestschema_Init(Tcl_Interp*);
3750 extern int Sqlitetestsse_Init(Tcl_Interp*);
3751 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
3752 extern int Sqlitetestfs_Init(Tcl_Interp*);
3753 extern int SqlitetestThread_Init(Tcl_Interp*);
3754 extern int SqlitetestOnefile_Init();
3755 extern int SqlitetestOsinst_Init(Tcl_Interp*);
3756 extern int Sqlitetestbackup_Init(Tcl_Interp*);
3757 extern int Sqlitetestintarray_Init(Tcl_Interp*);
3758 extern int Sqlitetestvfs_Init(Tcl_Interp *);
3759 extern int Sqlitetestrtree_Init(Tcl_Interp*);
3760 extern int Sqlitequota_Init(Tcl_Interp*);
3761 extern int Sqlitemultiplex_Init(Tcl_Interp*);
3762 extern int SqliteSuperlock_Init(Tcl_Interp*);
3763 extern int SqlitetestSyscall_Init(Tcl_Interp*);
3765 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
3766 extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
3769 #ifdef SQLITE_ENABLE_ZIPVFS
3770 extern int Zipvfs_Init(Tcl_Interp*);
3771 Zipvfs_Init(interp);
3774 Sqliteconfig_Init(interp);
3775 Sqlitetest1_Init(interp);
3776 Sqlitetest2_Init(interp);
3777 Sqlitetest3_Init(interp);
3778 Sqlitetest4_Init(interp);
3779 Sqlitetest5_Init(interp);
3780 Sqlitetest6_Init(interp);
3781 Sqlitetest7_Init(interp);
3782 Sqlitetest8_Init(interp);
3783 Sqlitetest9_Init(interp);
3784 Sqlitetestasync_Init(interp);
3785 Sqlitetest_autoext_Init(interp);
3786 Sqlitetest_blob_Init(interp);
3787 Sqlitetest_demovfs_Init(interp);
3788 Sqlitetest_func_Init(interp);
3789 Sqlitetest_hexio_Init(interp);
3790 Sqlitetest_init_Init(interp);
3791 Sqlitetest_malloc_Init(interp);
3792 Sqlitetest_mutex_Init(interp);
3793 Sqlitetestschema_Init(interp);
3794 Sqlitetesttclvar_Init(interp);
3795 Sqlitetestfs_Init(interp);
3796 SqlitetestThread_Init(interp);
3797 SqlitetestOnefile_Init(interp);
3798 SqlitetestOsinst_Init(interp);
3799 Sqlitetestbackup_Init(interp);
3800 Sqlitetestintarray_Init(interp);
3801 Sqlitetestvfs_Init(interp);
3802 Sqlitetestrtree_Init(interp);
3803 Sqlitequota_Init(interp);
3804 Sqlitemultiplex_Init(interp);
3805 SqliteSuperlock_Init(interp);
3806 SqlitetestSyscall_Init(interp);
3808 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
3809 Sqlitetestfts3_Init(interp);
3812 Tcl_CreateObjCommand(
3813 interp, "load_testfixture_extensions", init_all_cmd, 0, 0
3815 Tcl_CreateObjCommand(
3816 interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
3818 Tcl_CreateObjCommand(
3819 interp, "db_last_stmt_ptr", db_last_stmt_ptr, 0, 0
3823 Sqlitetestsse_Init(interp);
3829 /* Needed for the setrlimit() system call on unix */
3831 #include <sys/resource.h>
3834 #define TCLSH_MAIN main /* Needed to fake out mktclapp */
3835 int TCLSH_MAIN(int argc, char **argv){
3838 #if !defined(_WIN32_WCE)
3839 if( getenv("BREAK") ){
3841 "attach debugger to process %d and press any key to continue.\n",
3847 /* Since the primary use case for this binary is testing of SQLite,
3848 ** be sure to generate core files if we crash */
3849 #if defined(SQLITE_TEST) && defined(unix)
3851 getrlimit(RLIMIT_CORE, &x);
3852 x.rlim_cur = x.rlim_max;
3853 setrlimit(RLIMIT_CORE, &x);
3855 #endif /* SQLITE_TEST && unix */
3858 /* Call sqlite3_shutdown() once before doing anything else. This is to
3859 ** test that sqlite3_shutdown() can be safely called by a process before
3860 ** sqlite3_initialize() is. */
3863 Tcl_FindExecutable(argv[0]);
3864 Tcl_SetSystemEncoding(NULL, "utf-8");
3865 interp = Tcl_CreateInterp();
3868 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
3875 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
3876 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
3877 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
3878 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
3879 for(i=3-TCLSH; i<argc; i++){
3880 Tcl_SetVar(interp, "argv", argv[i],
3881 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3883 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
3884 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
3885 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
3886 fprintf(stderr,"%s: %s\n", *argv, zInfo);
3890 if( TCLSH==2 || argc<=1 ){
3891 Tcl_GlobalEval(interp, tclsh_main_loop());