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)
41 #if defined(INCLUDE_SQLITE_TCL_H)
42 # include "sqlite_tcl.h"
45 # ifndef SQLITE_TCLAPI
46 # define SQLITE_TCLAPI
52 ** Some additional include files are needed if this file is not
53 ** appended to the amalgamation.
55 #ifndef SQLITE_AMALGAMATION
60 typedef unsigned char u8;
64 /* Used to get the current process ID */
67 # define GETPID getpid
68 #elif !defined(_WIN32_WCE)
69 # ifndef SQLITE_AMALGAMATION
70 # define WIN32_LEAN_AND_MEAN
73 # define GETPID (int)GetCurrentProcessId
77 * Windows needs to know which symbols to export. Unix does not.
78 * BUILD_sqlite should be undefined for Unix.
81 #undef TCL_STORAGE_CLASS
82 #define TCL_STORAGE_CLASS DLLEXPORT
83 #endif /* BUILD_sqlite */
85 #define NUM_PREPARED_STMTS 10
86 #define MAX_PREPARED_STMTS 100
88 /* Forward declaration */
89 typedef struct SqliteDb SqliteDb;
92 ** New SQL functions can be created as TCL scripts. Each such function
93 ** is described by an instance of the following structure.
95 typedef struct SqlFunc SqlFunc;
97 Tcl_Interp *interp; /* The TCL interpret to execute the function */
98 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
99 SqliteDb *pDb; /* Database connection that owns this function */
100 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
101 char *zName; /* Name of this function */
102 SqlFunc *pNext; /* Next function on the list of them all */
106 ** New collation sequences function can be created as TCL scripts. Each such
107 ** function is described by an instance of the following structure.
109 typedef struct SqlCollate SqlCollate;
111 Tcl_Interp *interp; /* The TCL interpret to execute the function */
112 char *zScript; /* The script to be run */
113 SqlCollate *pNext; /* Next function on the list of them all */
117 ** Prepared statements are cached for faster execution. Each prepared
118 ** statement is described by an instance of the following structure.
120 typedef struct SqlPreparedStmt SqlPreparedStmt;
121 struct SqlPreparedStmt {
122 SqlPreparedStmt *pNext; /* Next in linked list */
123 SqlPreparedStmt *pPrev; /* Previous on the list */
124 sqlite3_stmt *pStmt; /* The prepared statement */
125 int nSql; /* chars in zSql[] */
126 const char *zSql; /* Text of the SQL statement */
127 int nParm; /* Size of apParm array */
128 Tcl_Obj **apParm; /* Array of referenced object pointers */
131 typedef struct IncrblobChannel IncrblobChannel;
134 ** There is one instance of this structure for each SQLite database
135 ** that has been opened by the SQLite TCL interface.
137 ** If this module is built with SQLITE_TEST defined (to create the SQLite
138 ** testfixture executable), then it may be configured to use either
139 ** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
140 ** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
143 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
144 Tcl_Interp *interp; /* The interpreter used for this database */
145 char *zBusy; /* The busy callback routine */
146 char *zCommit; /* The commit hook callback routine */
147 char *zTrace; /* The trace callback routine */
148 char *zTraceV2; /* The trace_v2 callback routine */
149 char *zProfile; /* The profile callback routine */
150 char *zProgress; /* The progress callback routine */
151 char *zAuth; /* The authorization callback routine */
152 int disableAuth; /* Disable the authorizer if it exists */
153 char *zNull; /* Text to substitute for an SQL NULL value */
154 SqlFunc *pFunc; /* List of SQL functions */
155 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
156 Tcl_Obj *pPreUpdateHook; /* Pre-update hook script (if any) */
157 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
158 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
159 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
160 SqlCollate *pCollate; /* List of SQL collation functions */
161 int rc; /* Return code of most recent sqlite3_exec() */
162 Tcl_Obj *pCollateNeeded; /* Collation needed script */
163 SqlPreparedStmt *stmtList; /* List of prepared statements*/
164 SqlPreparedStmt *stmtLast; /* Last statement in the list */
165 int maxStmt; /* The next maximum number of stmtList */
166 int nStmt; /* Number of statements in stmtList */
167 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
168 int nStep, nSort, nIndex; /* Statistics for most recent operation */
169 int nVMStep; /* Another statistic for most recent operation */
170 int nTransaction; /* Number of nested [transaction] methods */
171 int openFlags; /* Flags used to open. (SQLITE_OPEN_URI) */
173 int bLegacyPrepare; /* True to use sqlite3_prepare() */
177 struct IncrblobChannel {
178 sqlite3_blob *pBlob; /* sqlite3 blob handle */
179 SqliteDb *pDb; /* Associated database connection */
180 int iSeek; /* Current seek offset */
181 Tcl_Channel channel; /* Channel identifier */
182 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
183 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
187 ** Compute a string length that is limited to what can be stored in
188 ** lower 30 bits of a 32-bit signed integer.
190 static int strlen30(const char *z){
192 while( *z2 ){ z2++; }
193 return 0x3fffffff & (int)(z2 - z);
197 #ifndef SQLITE_OMIT_INCRBLOB
199 ** Close all incrblob channels opened using database connection pDb.
200 ** This is called when shutting down the database connection.
202 static void closeIncrblobChannels(SqliteDb *pDb){
204 IncrblobChannel *pNext;
206 for(p=pDb->pIncrblob; p; p=pNext){
209 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
210 ** which deletes the IncrblobChannel structure at *p. So do not
211 ** call Tcl_Free() here.
213 Tcl_UnregisterChannel(pDb->interp, p->channel);
218 ** Close an incremental blob channel.
220 static int SQLITE_TCLAPI incrblobClose(
221 ClientData instanceData,
224 IncrblobChannel *p = (IncrblobChannel *)instanceData;
225 int rc = sqlite3_blob_close(p->pBlob);
226 sqlite3 *db = p->pDb->db;
228 /* Remove the channel from the SqliteDb.pIncrblob list. */
230 p->pNext->pPrev = p->pPrev;
233 p->pPrev->pNext = p->pNext;
235 if( p->pDb->pIncrblob==p ){
236 p->pDb->pIncrblob = p->pNext;
239 /* Free the IncrblobChannel structure */
243 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
250 ** Read data from an incremental blob channel.
252 static int SQLITE_TCLAPI incrblobInput(
253 ClientData instanceData,
258 IncrblobChannel *p = (IncrblobChannel *)instanceData;
259 int nRead = bufSize; /* Number of bytes to read */
260 int nBlob; /* Total size of the blob */
261 int rc; /* sqlite error code */
263 nBlob = sqlite3_blob_bytes(p->pBlob);
264 if( (p->iSeek+nRead)>nBlob ){
265 nRead = nBlob-p->iSeek;
271 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
282 ** Write data to an incremental blob channel.
284 static int SQLITE_TCLAPI incrblobOutput(
285 ClientData instanceData,
290 IncrblobChannel *p = (IncrblobChannel *)instanceData;
291 int nWrite = toWrite; /* Number of bytes to write */
292 int nBlob; /* Total size of the blob */
293 int rc; /* sqlite error code */
295 nBlob = sqlite3_blob_bytes(p->pBlob);
296 if( (p->iSeek+nWrite)>nBlob ){
297 *errorCodePtr = EINVAL;
304 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
315 ** Seek an incremental blob channel.
317 static int SQLITE_TCLAPI incrblobSeek(
318 ClientData instanceData,
323 IncrblobChannel *p = (IncrblobChannel *)instanceData;
333 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
336 default: assert(!"Bad seekMode");
343 static void SQLITE_TCLAPI incrblobWatch(
344 ClientData instanceData,
349 static int SQLITE_TCLAPI incrblobHandle(
350 ClientData instanceData,
357 static Tcl_ChannelType IncrblobChannelType = {
358 "incrblob", /* typeName */
359 TCL_CHANNEL_VERSION_2, /* version */
360 incrblobClose, /* closeProc */
361 incrblobInput, /* inputProc */
362 incrblobOutput, /* outputProc */
363 incrblobSeek, /* seekProc */
364 0, /* setOptionProc */
365 0, /* getOptionProc */
366 incrblobWatch, /* watchProc (this is a no-op) */
367 incrblobHandle, /* getHandleProc (always returns error) */
369 0, /* blockModeProc */
372 0, /* wideSeekProc */
376 ** Create a new incrblob channel.
378 static int createIncrblobChannel(
388 sqlite3 *db = pDb->db;
391 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
393 /* This variable is used to name the channels: "incrblob_[incr count]" */
394 static int count = 0;
397 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
399 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
403 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
407 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
408 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
409 Tcl_RegisterChannel(interp, p->channel);
411 /* Link the new channel into the SqliteDb.pIncrblob list. */
412 p->pNext = pDb->pIncrblob;
420 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
423 #else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
424 #define closeIncrblobChannels(pDb)
428 ** Look at the script prefix in pCmd. We will be executing this script
429 ** after first appending one or more arguments. This routine analyzes
430 ** the script to see if it is safe to use Tcl_EvalObjv() on the script
431 ** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
434 ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
435 ** command name followed by zero or more arguments with no [...] or $
436 ** or {...} or ; to be seen anywhere. Most callback scripts consist
437 ** of just a single procedure name and they meet this requirement.
439 static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
440 /* We could try to do something with Tcl_Parse(). But we will instead
441 ** just do a search for forbidden characters. If any of the forbidden
442 ** characters appear in pCmd, we will report the string as unsafe.
446 z = Tcl_GetStringFromObj(pCmd, &n);
449 if( c=='$' || c=='[' || c==';' ) return 0;
455 ** Find an SqlFunc structure with the given name. Or create a new
456 ** one if an existing one cannot be found. Return a pointer to the
459 static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
461 int nName = strlen30(zName);
462 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
463 pNew->zName = (char*)&pNew[1];
464 memcpy(pNew->zName, zName, nName+1);
465 for(p=pDb->pFunc; p; p=p->pNext){
466 if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
467 Tcl_Free((char*)pNew);
471 pNew->interp = pDb->interp;
474 pNew->pNext = pDb->pFunc;
480 ** Free a single SqlPreparedStmt object.
482 static void dbFreeStmt(SqlPreparedStmt *pStmt){
484 if( sqlite3_sql(pStmt->pStmt)==0 ){
485 Tcl_Free((char *)pStmt->zSql);
488 sqlite3_finalize(pStmt->pStmt);
489 Tcl_Free((char *)pStmt);
493 ** Finalize and free a list of prepared statements
495 static void flushStmtCache(SqliteDb *pDb){
496 SqlPreparedStmt *pPreStmt;
497 SqlPreparedStmt *pNext;
499 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
500 pNext = pPreStmt->pNext;
501 dbFreeStmt(pPreStmt);
509 ** TCL calls this procedure when an sqlite3 database command is
512 static void SQLITE_TCLAPI DbDeleteCmd(void *db){
513 SqliteDb *pDb = (SqliteDb*)db;
515 closeIncrblobChannels(pDb);
516 sqlite3_close(pDb->db);
518 SqlFunc *pFunc = pDb->pFunc;
519 pDb->pFunc = pFunc->pNext;
520 assert( pFunc->pDb==pDb );
521 Tcl_DecrRefCount(pFunc->pScript);
522 Tcl_Free((char*)pFunc);
524 while( pDb->pCollate ){
525 SqlCollate *pCollate = pDb->pCollate;
526 pDb->pCollate = pCollate->pNext;
527 Tcl_Free((char*)pCollate);
530 Tcl_Free(pDb->zBusy);
533 Tcl_Free(pDb->zTrace);
536 Tcl_Free(pDb->zTraceV2);
539 Tcl_Free(pDb->zProfile);
542 Tcl_Free(pDb->zAuth);
545 Tcl_Free(pDb->zNull);
547 if( pDb->pUpdateHook ){
548 Tcl_DecrRefCount(pDb->pUpdateHook);
550 if( pDb->pPreUpdateHook ){
551 Tcl_DecrRefCount(pDb->pPreUpdateHook);
553 if( pDb->pRollbackHook ){
554 Tcl_DecrRefCount(pDb->pRollbackHook);
557 Tcl_DecrRefCount(pDb->pWalHook);
559 if( pDb->pCollateNeeded ){
560 Tcl_DecrRefCount(pDb->pCollateNeeded);
562 Tcl_Free((char*)pDb);
566 ** This routine is called when a database file is locked while trying
569 static int DbBusyHandler(void *cd, int nTries){
570 SqliteDb *pDb = (SqliteDb*)cd;
574 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
575 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
576 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
582 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
584 ** This routine is invoked as the 'progress callback' for the database.
586 static int DbProgressHandler(void *cd){
587 SqliteDb *pDb = (SqliteDb*)cd;
590 assert( pDb->zProgress );
591 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
592 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
599 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
600 !defined(SQLITE_OMIT_DEPRECATED)
602 ** This routine is called by the SQLite trace handler whenever a new
603 ** block of SQL is executed. The TCL script in pDb->zTrace is executed.
605 static void DbTraceHandler(void *cd, const char *zSql){
606 SqliteDb *pDb = (SqliteDb*)cd;
609 Tcl_DStringInit(&str);
610 Tcl_DStringAppend(&str, pDb->zTrace, -1);
611 Tcl_DStringAppendElement(&str, zSql);
612 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
613 Tcl_DStringFree(&str);
614 Tcl_ResetResult(pDb->interp);
618 #ifndef SQLITE_OMIT_TRACE
620 ** This routine is called by the SQLite trace_v2 handler whenever a new
621 ** supported event is generated. Unsupported event types are ignored.
622 ** The TCL script in pDb->zTraceV2 is executed, with the arguments for
623 ** the event appended to it (as list elements).
625 static int DbTraceV2Handler(
626 unsigned type, /* One of the SQLITE_TRACE_* event types. */
627 void *cd, /* The original context data pointer. */
628 void *pd, /* Primary event data, depends on event type. */
629 void *xd /* Extra event data, depends on event type. */
631 SqliteDb *pDb = (SqliteDb*)cd;
635 case SQLITE_TRACE_STMT: {
636 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
637 char *zSql = (char *)xd;
639 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
640 Tcl_IncrRefCount(pCmd);
641 Tcl_ListObjAppendElement(pDb->interp, pCmd,
642 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
643 Tcl_ListObjAppendElement(pDb->interp, pCmd,
644 Tcl_NewStringObj(zSql, -1));
645 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
646 Tcl_DecrRefCount(pCmd);
647 Tcl_ResetResult(pDb->interp);
650 case SQLITE_TRACE_PROFILE: {
651 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
652 sqlite3_int64 ns = (sqlite3_int64)xd;
654 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
655 Tcl_IncrRefCount(pCmd);
656 Tcl_ListObjAppendElement(pDb->interp, pCmd,
657 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
658 Tcl_ListObjAppendElement(pDb->interp, pCmd,
659 Tcl_NewWideIntObj((Tcl_WideInt)ns));
660 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
661 Tcl_DecrRefCount(pCmd);
662 Tcl_ResetResult(pDb->interp);
665 case SQLITE_TRACE_ROW: {
666 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
668 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
669 Tcl_IncrRefCount(pCmd);
670 Tcl_ListObjAppendElement(pDb->interp, pCmd,
671 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
672 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
673 Tcl_DecrRefCount(pCmd);
674 Tcl_ResetResult(pDb->interp);
677 case SQLITE_TRACE_CLOSE: {
678 sqlite3 *db = (sqlite3 *)pd;
680 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
681 Tcl_IncrRefCount(pCmd);
682 Tcl_ListObjAppendElement(pDb->interp, pCmd,
683 Tcl_NewWideIntObj((Tcl_WideInt)db));
684 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
685 Tcl_DecrRefCount(pCmd);
686 Tcl_ResetResult(pDb->interp);
694 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
695 !defined(SQLITE_OMIT_DEPRECATED)
697 ** This routine is called by the SQLite profile handler after a statement
698 ** SQL has executed. The TCL script in pDb->zProfile is evaluated.
700 static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
701 SqliteDb *pDb = (SqliteDb*)cd;
705 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
706 Tcl_DStringInit(&str);
707 Tcl_DStringAppend(&str, pDb->zProfile, -1);
708 Tcl_DStringAppendElement(&str, zSql);
709 Tcl_DStringAppendElement(&str, zTm);
710 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
711 Tcl_DStringFree(&str);
712 Tcl_ResetResult(pDb->interp);
717 ** This routine is called when a transaction is committed. The
718 ** TCL script in pDb->zCommit is executed. If it returns non-zero or
719 ** if it throws an exception, the transaction is rolled back instead
720 ** of being committed.
722 static int DbCommitHandler(void *cd){
723 SqliteDb *pDb = (SqliteDb*)cd;
726 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
727 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
733 static void DbRollbackHandler(void *clientData){
734 SqliteDb *pDb = (SqliteDb*)clientData;
735 assert(pDb->pRollbackHook);
736 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
737 Tcl_BackgroundError(pDb->interp);
742 ** This procedure handles wal_hook callbacks.
744 static int DbWalHandler(
752 SqliteDb *pDb = (SqliteDb*)clientData;
753 Tcl_Interp *interp = pDb->interp;
754 assert(pDb->pWalHook);
756 assert( db==pDb->db );
757 p = Tcl_DuplicateObj(pDb->pWalHook);
759 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
760 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
761 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
762 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
764 Tcl_BackgroundError(interp);
771 #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
772 static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
774 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
775 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
776 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
777 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
780 # define setTestUnlockNotifyVars(x,y,z)
783 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
784 static void DbUnlockNotify(void **apArg, int nArg){
786 for(i=0; i<nArg; i++){
787 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
788 SqliteDb *pDb = (SqliteDb *)apArg[i];
789 setTestUnlockNotifyVars(pDb->interp, i, nArg);
790 assert( pDb->pUnlockNotify);
791 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
792 Tcl_DecrRefCount(pDb->pUnlockNotify);
793 pDb->pUnlockNotify = 0;
798 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
800 ** Pre-update hook callback.
802 static void DbPreUpdateHandler(
811 SqliteDb *pDb = (SqliteDb *)p;
813 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
815 assert( (SQLITE_DELETE-1)/9 == 0 );
816 assert( (SQLITE_INSERT-1)/9 == 1 );
817 assert( (SQLITE_UPDATE-1)/9 == 2 );
818 assert( pDb->pPreUpdateHook );
819 assert( db==pDb->db );
820 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
822 pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
823 Tcl_IncrRefCount(pCmd);
824 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
825 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
826 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
827 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
828 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
829 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
830 Tcl_DecrRefCount(pCmd);
832 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
834 static void DbUpdateHandler(
841 SqliteDb *pDb = (SqliteDb *)p;
843 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
845 assert( (SQLITE_DELETE-1)/9 == 0 );
846 assert( (SQLITE_INSERT-1)/9 == 1 );
847 assert( (SQLITE_UPDATE-1)/9 == 2 );
849 assert( pDb->pUpdateHook );
850 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
852 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
853 Tcl_IncrRefCount(pCmd);
854 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
855 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
856 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
857 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
858 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
859 Tcl_DecrRefCount(pCmd);
862 static void tclCollateNeeded(
868 SqliteDb *pDb = (SqliteDb *)pCtx;
869 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
870 Tcl_IncrRefCount(pScript);
871 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
872 Tcl_EvalObjEx(pDb->interp, pScript, 0);
873 Tcl_DecrRefCount(pScript);
877 ** This routine is called to evaluate an SQL collation function implemented
880 static int tclSqlCollate(
887 SqlCollate *p = (SqlCollate *)pCtx;
890 pCmd = Tcl_NewStringObj(p->zScript, -1);
891 Tcl_IncrRefCount(pCmd);
892 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
893 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
894 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
895 Tcl_DecrRefCount(pCmd);
896 return (atoi(Tcl_GetStringResult(p->interp)));
900 ** This routine is called to evaluate an SQL function implemented
903 static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
904 SqlFunc *p = sqlite3_user_data(context);
910 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
911 ** script object directly. This allows the TCL compiler to generate
912 ** bytecode for the command on the first invocation and thus make
913 ** subsequent invocations much faster. */
915 Tcl_IncrRefCount(pCmd);
916 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
917 Tcl_DecrRefCount(pCmd);
919 /* If there are arguments to the function, make a shallow copy of the
920 ** script object, lappend the arguments, then evaluate the copy.
922 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
923 ** The new Tcl_Obj contains pointers to the original list elements.
924 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
925 ** of the list to tclCmdNameType, that alternate representation will
926 ** be preserved and reused on the next invocation.
930 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
931 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
934 pCmd = Tcl_NewListObj(nArg, aArg);
935 Tcl_IncrRefCount(pCmd);
936 for(i=0; i<argc; i++){
937 sqlite3_value *pIn = argv[i];
940 /* Set pVal to contain the i'th column of this row. */
941 switch( sqlite3_value_type(pIn) ){
943 int bytes = sqlite3_value_bytes(pIn);
944 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
947 case SQLITE_INTEGER: {
948 sqlite_int64 v = sqlite3_value_int64(pIn);
949 if( v>=-2147483647 && v<=2147483647 ){
950 pVal = Tcl_NewIntObj((int)v);
952 pVal = Tcl_NewWideIntObj(v);
957 double r = sqlite3_value_double(pIn);
958 pVal = Tcl_NewDoubleObj(r);
962 pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
966 int bytes = sqlite3_value_bytes(pIn);
967 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
971 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
973 Tcl_DecrRefCount(pCmd);
974 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
978 if( !p->useEvalObjv ){
979 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
980 ** is a list without a string representation. To prevent this from
981 ** happening, make sure pCmd has a valid string representation */
984 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
985 Tcl_DecrRefCount(pCmd);
988 if( rc && rc!=TCL_RETURN ){
989 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
991 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
994 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
996 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
997 /* Only return a BLOB type if the Tcl variable is a bytearray and
998 ** has no string representation. */
999 data = Tcl_GetByteArrayFromObj(pVar, &n);
1000 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
1001 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1002 Tcl_GetIntFromObj(0, pVar, &n);
1003 sqlite3_result_int(context, n);
1004 }else if( c=='d' && strcmp(zType,"double")==0 ){
1006 Tcl_GetDoubleFromObj(0, pVar, &r);
1007 sqlite3_result_double(context, r);
1008 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1009 (c=='i' && strcmp(zType,"int")==0) ){
1011 Tcl_GetWideIntFromObj(0, pVar, &v);
1012 sqlite3_result_int64(context, v);
1014 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1015 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
1020 #ifndef SQLITE_OMIT_AUTHORIZATION
1022 ** This is the authentication function. It appends the authentication
1023 ** type code and the two arguments to zCmd[] then invokes the result
1024 ** on the interpreter. The reply is examined to determine if the
1025 ** authentication fails or succeeds.
1027 static int auth_callback(
1034 #ifdef SQLITE_USER_AUTHENTICATION
1042 /* EVIDENCE-OF: R-38590-62769 The first parameter to the authorizer
1043 ** callback is a copy of the third parameter to the
1044 ** sqlite3_set_authorizer() interface.
1046 SqliteDb *pDb = (SqliteDb*)pArg;
1047 if( pDb->disableAuth ) return SQLITE_OK;
1049 /* EVIDENCE-OF: R-56518-44310 The second parameter to the callback is an
1050 ** integer action code that specifies the particular action to be
1053 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
1054 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
1055 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
1056 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
1057 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
1058 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
1059 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
1060 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
1061 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
1062 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
1063 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
1064 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
1065 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
1066 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
1067 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
1068 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
1069 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
1070 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
1071 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
1072 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
1073 case SQLITE_READ : zCode="SQLITE_READ"; break;
1074 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
1075 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
1076 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
1077 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
1078 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
1079 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
1080 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
1081 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
1082 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
1083 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
1084 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
1085 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
1086 case SQLITE_RECURSIVE : zCode="SQLITE_RECURSIVE"; break;
1087 default : zCode="????"; break;
1089 Tcl_DStringInit(&str);
1090 Tcl_DStringAppend(&str, pDb->zAuth, -1);
1091 Tcl_DStringAppendElement(&str, zCode);
1092 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
1093 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
1094 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
1095 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
1096 #ifdef SQLITE_USER_AUTHENTICATION
1097 Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
1099 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
1100 Tcl_DStringFree(&str);
1101 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
1102 if( strcmp(zReply,"SQLITE_OK")==0 ){
1104 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
1106 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
1113 #endif /* SQLITE_OMIT_AUTHORIZATION */
1116 ** This routine reads a line of text from FILE in, stores
1117 ** the text in memory obtained from malloc() and returns a pointer
1118 ** to the text. NULL is returned at end of file, or if malloc()
1121 ** The interface is like "readline" but no command-line editing
1124 ** copied from shell.c from '.import' command
1126 static char *local_getline(char *zPrompt, FILE *in){
1132 zLine = malloc( nLine );
1133 if( zLine==0 ) return 0;
1137 nLine = nLine*2 + 100;
1138 zLine = realloc(zLine, nLine);
1139 if( zLine==0 ) return 0;
1141 if( fgets(&zLine[n], nLine - n, in)==0 ){
1149 while( zLine[n] ){ n++; }
1150 if( n>0 && zLine[n-1]=='\n' ){
1156 zLine = realloc( zLine, n+1 );
1162 ** This function is part of the implementation of the command:
1164 ** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1166 ** It is invoked after evaluating the script SCRIPT to commit or rollback
1167 ** the transaction or savepoint opened by the [transaction] command.
1169 static int SQLITE_TCLAPI DbTransPostCmd(
1170 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1171 Tcl_Interp *interp, /* Tcl interpreter */
1172 int result /* Result of evaluating SCRIPT */
1174 static const char *const azEnd[] = {
1175 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1176 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1177 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1178 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1180 SqliteDb *pDb = (SqliteDb*)data[0];
1184 pDb->nTransaction--;
1185 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1188 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1189 /* This is a tricky scenario to handle. The most likely cause of an
1190 ** error is that the exec() above was an attempt to commit the
1191 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1192 ** that an IO-error has occurred. In either case, throw a Tcl exception
1193 ** and try to rollback the transaction.
1195 ** But it could also be that the user executed one or more BEGIN,
1196 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1197 ** this method's logic. Not clear how this would be best handled.
1199 if( rc!=TCL_ERROR ){
1200 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
1203 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1211 ** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1212 ** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1213 ** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1214 ** on whether or not the [db_use_legacy_prepare] command has been used to
1215 ** configure the connection.
1217 static int dbPrepare(
1218 SqliteDb *pDb, /* Database object */
1219 const char *zSql, /* SQL to compile */
1220 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1221 const char **pzOut /* OUT: Pointer to next SQL statement */
1223 unsigned int prepFlags = 0;
1225 if( pDb->bLegacyPrepare ){
1226 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1229 /* If the statement cache is large, use the SQLITE_PREPARE_PERSISTENT
1230 ** flags, which uses less lookaside memory. But if the cache is small,
1231 ** omit that flag to make full use of lookaside */
1232 if( pDb->maxStmt>5 ) prepFlags = SQLITE_PREPARE_PERSISTENT;
1234 return sqlite3_prepare_v3(pDb->db, zSql, -1, prepFlags, ppStmt, pzOut);
1238 ** Search the cache for a prepared-statement object that implements the
1239 ** first SQL statement in the buffer pointed to by parameter zIn. If
1240 ** no such prepared-statement can be found, allocate and prepare a new
1241 ** one. In either case, bind the current values of the relevant Tcl
1242 ** variables to any $var, :var or @var variables in the statement. Before
1243 ** returning, set *ppPreStmt to point to the prepared-statement object.
1245 ** Output parameter *pzOut is set to point to the next SQL statement in
1246 ** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1249 ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1250 ** and an error message loaded into interpreter pDb->interp.
1252 static int dbPrepareAndBind(
1253 SqliteDb *pDb, /* Database object */
1254 char const *zIn, /* SQL to compile */
1255 char const **pzOut, /* OUT: Pointer to next SQL statement */
1256 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1258 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
1259 sqlite3_stmt *pStmt = 0; /* Prepared statement object */
1260 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1261 int nSql; /* Length of zSql in bytes */
1262 int nVar = 0; /* Number of variables in statement */
1263 int iParm = 0; /* Next free entry in apParm */
1266 Tcl_Interp *interp = pDb->interp;
1270 /* Trim spaces from the start of zSql and calculate the remaining length. */
1271 while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
1272 nSql = strlen30(zSql);
1274 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1275 int n = pPreStmt->nSql;
1277 && memcmp(pPreStmt->zSql, zSql, n)==0
1278 && (zSql[n]==0 || zSql[n-1]==';')
1280 pStmt = pPreStmt->pStmt;
1281 *pzOut = &zSql[pPreStmt->nSql];
1283 /* When a prepared statement is found, unlink it from the
1284 ** cache list. It will later be added back to the beginning
1285 ** of the cache list in order to implement LRU replacement.
1287 if( pPreStmt->pPrev ){
1288 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1290 pDb->stmtList = pPreStmt->pNext;
1292 if( pPreStmt->pNext ){
1293 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1295 pDb->stmtLast = pPreStmt->pPrev;
1298 nVar = sqlite3_bind_parameter_count(pStmt);
1303 /* If no prepared statement was found. Compile the SQL text. Also allocate
1304 ** a new SqlPreparedStmt structure. */
1308 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
1309 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1313 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1314 /* A compile-time error in the statement. */
1315 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1318 /* The statement was a no-op. Continue to the next statement
1319 ** in the SQL string.
1325 assert( pPreStmt==0 );
1326 nVar = sqlite3_bind_parameter_count(pStmt);
1327 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1328 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1329 memset(pPreStmt, 0, nByte);
1331 pPreStmt->pStmt = pStmt;
1332 pPreStmt->nSql = (int)(*pzOut - zSql);
1333 pPreStmt->zSql = sqlite3_sql(pStmt);
1334 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
1336 if( pPreStmt->zSql==0 ){
1337 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1338 memcpy(zCopy, zSql, pPreStmt->nSql);
1339 zCopy[pPreStmt->nSql] = '\0';
1340 pPreStmt->zSql = zCopy;
1345 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1346 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1348 /* Bind values to parameters that begin with $ or : */
1349 for(i=1; i<=nVar; i++){
1350 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1351 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1352 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1356 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1359 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1360 /* Load a BLOB type if the Tcl variable is a bytearray and
1361 ** it has no string representation or the host
1362 ** parameter name begins with "@". */
1363 data = Tcl_GetByteArrayFromObj(pVar, &n);
1364 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1365 Tcl_IncrRefCount(pVar);
1366 pPreStmt->apParm[iParm++] = pVar;
1367 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1368 Tcl_GetIntFromObj(interp, pVar, &n);
1369 sqlite3_bind_int(pStmt, i, n);
1370 }else if( c=='d' && strcmp(zType,"double")==0 ){
1372 Tcl_GetDoubleFromObj(interp, pVar, &r);
1373 sqlite3_bind_double(pStmt, i, r);
1374 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1375 (c=='i' && strcmp(zType,"int")==0) ){
1377 Tcl_GetWideIntFromObj(interp, pVar, &v);
1378 sqlite3_bind_int64(pStmt, i, v);
1380 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1381 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1382 Tcl_IncrRefCount(pVar);
1383 pPreStmt->apParm[iParm++] = pVar;
1386 sqlite3_bind_null(pStmt, i);
1390 pPreStmt->nParm = iParm;
1391 *ppPreStmt = pPreStmt;
1397 ** Release a statement reference obtained by calling dbPrepareAndBind().
1398 ** There should be exactly one call to this function for each call to
1399 ** dbPrepareAndBind().
1401 ** If the discard parameter is non-zero, then the statement is deleted
1402 ** immediately. Otherwise it is added to the LRU list and may be returned
1403 ** by a subsequent call to dbPrepareAndBind().
1405 static void dbReleaseStmt(
1406 SqliteDb *pDb, /* Database handle */
1407 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1408 int discard /* True to delete (not cache) the pPreStmt */
1412 /* Free the bound string and blob parameters */
1413 for(i=0; i<pPreStmt->nParm; i++){
1414 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1416 pPreStmt->nParm = 0;
1418 if( pDb->maxStmt<=0 || discard ){
1419 /* If the cache is turned off, deallocated the statement */
1420 dbFreeStmt(pPreStmt);
1422 /* Add the prepared statement to the beginning of the cache list. */
1423 pPreStmt->pNext = pDb->stmtList;
1424 pPreStmt->pPrev = 0;
1425 if( pDb->stmtList ){
1426 pDb->stmtList->pPrev = pPreStmt;
1428 pDb->stmtList = pPreStmt;
1429 if( pDb->stmtLast==0 ){
1430 assert( pDb->nStmt==0 );
1431 pDb->stmtLast = pPreStmt;
1433 assert( pDb->nStmt>0 );
1437 /* If we have too many statement in cache, remove the surplus from
1438 ** the end of the cache list. */
1439 while( pDb->nStmt>pDb->maxStmt ){
1440 SqlPreparedStmt *pLast = pDb->stmtLast;
1441 pDb->stmtLast = pLast->pPrev;
1442 pDb->stmtLast->pNext = 0;
1450 ** Structure used with dbEvalXXX() functions:
1456 ** dbEvalColumnValue()
1458 typedef struct DbEvalContext DbEvalContext;
1459 struct DbEvalContext {
1460 SqliteDb *pDb; /* Database handle */
1461 Tcl_Obj *pSql; /* Object holding string zSql */
1462 const char *zSql; /* Remaining SQL to execute */
1463 SqlPreparedStmt *pPreStmt; /* Current statement */
1464 int nCol; /* Number of columns returned by pStmt */
1465 int evalFlags; /* Flags used */
1466 Tcl_Obj *pArray; /* Name of array variable */
1467 Tcl_Obj **apColName; /* Array of column names */
1470 #define SQLITE_EVAL_WITHOUTNULLS 0x00001 /* Unset array(*) for NULL */
1473 ** Release any cache of column names currently held as part of
1474 ** the DbEvalContext structure passed as the first argument.
1476 static void dbReleaseColumnNames(DbEvalContext *p){
1479 for(i=0; i<p->nCol; i++){
1480 Tcl_DecrRefCount(p->apColName[i]);
1482 Tcl_Free((char *)p->apColName);
1489 ** Initialize a DbEvalContext structure.
1491 ** If pArray is not NULL, then it contains the name of a Tcl array
1492 ** variable. The "*" member of this array is set to a list containing
1493 ** the names of the columns returned by the statement as part of each
1494 ** call to dbEvalStep(), in order from left to right. e.g. if the names
1495 ** of the returned columns are a, b and c, it does the equivalent of the
1498 ** set ${pArray}(*) {a b c}
1500 static void dbEvalInit(
1501 DbEvalContext *p, /* Pointer to structure to initialize */
1502 SqliteDb *pDb, /* Database handle */
1503 Tcl_Obj *pSql, /* Object containing SQL script */
1504 Tcl_Obj *pArray, /* Name of Tcl array to set (*) element of */
1505 int evalFlags /* Flags controlling evaluation */
1507 memset(p, 0, sizeof(DbEvalContext));
1509 p->zSql = Tcl_GetString(pSql);
1511 Tcl_IncrRefCount(pSql);
1514 Tcl_IncrRefCount(pArray);
1516 p->evalFlags = evalFlags;
1520 ** Obtain information about the row that the DbEvalContext passed as the
1521 ** first argument currently points to.
1523 static void dbEvalRowInfo(
1524 DbEvalContext *p, /* Evaluation context */
1525 int *pnCol, /* OUT: Number of column names */
1526 Tcl_Obj ***papColName /* OUT: Array of column names */
1528 /* Compute column names */
1529 if( 0==p->apColName ){
1530 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1531 int i; /* Iterator variable */
1532 int nCol; /* Number of columns returned by pStmt */
1533 Tcl_Obj **apColName = 0; /* Array of column names */
1535 p->nCol = nCol = sqlite3_column_count(pStmt);
1536 if( nCol>0 && (papColName || p->pArray) ){
1537 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1538 for(i=0; i<nCol; i++){
1539 apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
1540 Tcl_IncrRefCount(apColName[i]);
1542 p->apColName = apColName;
1545 /* If results are being stored in an array variable, then create
1546 ** the array(*) entry for that array
1549 Tcl_Interp *interp = p->pDb->interp;
1550 Tcl_Obj *pColList = Tcl_NewObj();
1551 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
1553 for(i=0; i<nCol; i++){
1554 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1556 Tcl_IncrRefCount(pStar);
1557 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
1558 Tcl_DecrRefCount(pStar);
1563 *papColName = p->apColName;
1571 ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1572 ** returned, then an error message is stored in the interpreter before
1575 ** A return value of TCL_OK means there is a row of data available. The
1576 ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1577 ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1578 ** is returned, then the SQL script has finished executing and there are
1579 ** no further rows available. This is similar to SQLITE_DONE.
1581 static int dbEvalStep(DbEvalContext *p){
1582 const char *zPrevSql = 0; /* Previous value of p->zSql */
1584 while( p->zSql[0] || p->pPreStmt ){
1586 if( p->pPreStmt==0 ){
1587 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
1588 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1589 if( rc!=TCL_OK ) return rc;
1592 SqliteDb *pDb = p->pDb;
1593 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1594 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1596 rcs = sqlite3_step(pStmt);
1597 if( rcs==SQLITE_ROW ){
1601 dbEvalRowInfo(p, 0, 0);
1603 rcs = sqlite3_reset(pStmt);
1605 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1606 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
1607 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
1608 pDb->nVMStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_VM_STEP,1);
1609 dbReleaseColumnNames(p);
1612 if( rcs!=SQLITE_OK ){
1613 /* If a run-time error occurs, report the error and stop reading
1615 dbReleaseStmt(pDb, pPreStmt, 1);
1617 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1618 /* If the runtime error was an SQLITE_SCHEMA, and the database
1619 ** handle is configured to use the legacy sqlite3_prepare()
1620 ** interface, retry prepare()/step() on the same SQL statement.
1621 ** This only happens once. If there is a second SQLITE_SCHEMA
1622 ** error, the error will be returned to the caller. */
1627 Tcl_SetObjResult(pDb->interp,
1628 Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1631 dbReleaseStmt(pDb, pPreStmt, 0);
1641 ** Free all resources currently held by the DbEvalContext structure passed
1642 ** as the first argument. There should be exactly one call to this function
1643 ** for each call to dbEvalInit().
1645 static void dbEvalFinalize(DbEvalContext *p){
1647 sqlite3_reset(p->pPreStmt->pStmt);
1648 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1652 Tcl_DecrRefCount(p->pArray);
1655 Tcl_DecrRefCount(p->pSql);
1656 dbReleaseColumnNames(p);
1660 ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1661 ** the value for the iCol'th column of the row currently pointed to by
1662 ** the DbEvalContext structure passed as the first argument.
1664 static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1665 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1666 switch( sqlite3_column_type(pStmt, iCol) ){
1668 int bytes = sqlite3_column_bytes(pStmt, iCol);
1669 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1670 if( !zBlob ) bytes = 0;
1671 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1673 case SQLITE_INTEGER: {
1674 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1675 if( v>=-2147483647 && v<=2147483647 ){
1676 return Tcl_NewIntObj((int)v);
1678 return Tcl_NewWideIntObj(v);
1681 case SQLITE_FLOAT: {
1682 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1685 return Tcl_NewStringObj(p->pDb->zNull, -1);
1689 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
1693 ** If using Tcl version 8.6 or greater, use the NR functions to avoid
1694 ** recursive evalution of scripts by the [db eval] and [db trans]
1695 ** commands. Even if the headers used while compiling the extension
1696 ** are 8.6 or newer, the code still tests the Tcl version at runtime.
1697 ** This allows stubs-enabled builds to be used with older Tcl libraries.
1699 #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
1700 # define SQLITE_TCL_NRE 1
1701 static int DbUseNre(void){
1703 Tcl_GetVersion(&major, &minor, 0, 0);
1704 return( (major==8 && minor>=6) || major>8 );
1708 ** Compiling using headers earlier than 8.6. In this case NR cannot be
1709 ** used, so DbUseNre() to always return zero. Add #defines for the other
1710 ** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1711 ** even though the only invocations of them are within conditional blocks
1714 ** if( DbUseNre() ) { ... }
1716 # define SQLITE_TCL_NRE 0
1717 # define DbUseNre() 0
1718 # define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
1719 # define Tcl_NREvalObj(a,b,c) 0
1720 # define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
1724 ** This function is part of the implementation of the command:
1726 ** $db eval SQL ?ARRAYNAME? SCRIPT
1728 static int SQLITE_TCLAPI DbEvalNextCmd(
1729 ClientData data[], /* data[0] is the (DbEvalContext*) */
1730 Tcl_Interp *interp, /* Tcl interpreter */
1731 int result /* Result so far */
1733 int rc = result; /* Return code */
1735 /* The first element of the data[] array is a pointer to a DbEvalContext
1736 ** structure allocated using Tcl_Alloc(). The second element of data[]
1737 ** is a pointer to a Tcl_Obj containing the script to run for each row
1738 ** returned by the queries encapsulated in data[0]. */
1739 DbEvalContext *p = (DbEvalContext *)data[0];
1740 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1741 Tcl_Obj *pArray = p->pArray;
1743 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1746 Tcl_Obj **apColName;
1747 dbEvalRowInfo(p, &nCol, &apColName);
1748 for(i=0; i<nCol; i++){
1750 Tcl_ObjSetVar2(interp, apColName[i], 0, dbEvalColumnValue(p,i), 0);
1751 }else if( (p->evalFlags & SQLITE_EVAL_WITHOUTNULLS)!=0
1752 && sqlite3_column_type(p->pPreStmt->pStmt, i)==SQLITE_NULL
1754 Tcl_UnsetVar2(interp, Tcl_GetString(pArray),
1755 Tcl_GetString(apColName[i]), 0);
1757 Tcl_ObjSetVar2(interp, pArray, apColName[i], dbEvalColumnValue(p,i), 0);
1761 /* The required interpreter variables are now populated with the data
1762 ** from the current row. If using NRE, schedule callbacks to evaluate
1763 ** script pScript, then to invoke this function again to fetch the next
1764 ** row (or clean up if there is no next row or the script throws an
1765 ** exception). After scheduling the callbacks, return control to the
1768 ** If not using NRE, evaluate pScript directly and continue with the
1769 ** next iteration of this while(...) loop. */
1771 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1772 return Tcl_NREvalObj(interp, pScript, 0);
1774 rc = Tcl_EvalObjEx(interp, pScript, 0);
1778 Tcl_DecrRefCount(pScript);
1780 Tcl_Free((char *)p);
1782 if( rc==TCL_OK || rc==TCL_BREAK ){
1783 Tcl_ResetResult(interp);
1790 ** This function is used by the implementations of the following database
1791 ** handle sub-commands:
1793 ** $db update_hook ?SCRIPT?
1794 ** $db wal_hook ?SCRIPT?
1795 ** $db commit_hook ?SCRIPT?
1796 ** $db preupdate hook ?SCRIPT?
1798 static void DbHookCmd(
1799 Tcl_Interp *interp, /* Tcl interpreter */
1800 SqliteDb *pDb, /* Database handle */
1801 Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */
1802 Tcl_Obj **ppHook /* Pointer to member of SqliteDb */
1804 sqlite3 *db = pDb->db;
1807 Tcl_SetObjResult(interp, *ppHook);
1809 Tcl_DecrRefCount(*ppHook);
1814 assert( !(*ppHook) );
1815 if( Tcl_GetCharLength(pArg)>0 ){
1817 Tcl_IncrRefCount(*ppHook);
1821 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1822 sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
1824 sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1825 sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1826 sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
1830 ** The "sqlite" command below creates a new Tcl command for each
1831 ** connection it opens to an SQLite database. This routine is invoked
1832 ** whenever one of those connection-specific commands is executed
1833 ** in Tcl. For example, if you run Tcl code like this:
1835 ** sqlite3 db1 "my_database"
1838 ** The first command opens a connection to the "my_database" database
1839 ** and calls that connection "db1". The second command causes this
1840 ** subroutine to be invoked.
1842 static int SQLITE_TCLAPI DbObjCmd(
1848 SqliteDb *pDb = (SqliteDb*)cd;
1851 static const char *DB_strs[] = {
1852 "authorizer", "backup", "busy",
1853 "cache", "changes", "close",
1854 "collate", "collation_needed", "commit_hook",
1855 "complete", "copy", "enable_load_extension",
1856 "errorcode", "eval", "exists",
1857 "function", "incrblob", "interrupt",
1858 "last_insert_rowid", "nullvalue", "onecolumn",
1859 "preupdate", "profile", "progress",
1860 "rekey", "restore", "rollback_hook",
1861 "status", "timeout", "total_changes",
1862 "trace", "trace_v2", "transaction",
1863 "unlock_notify", "update_hook", "version",
1868 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1869 DB_CACHE, DB_CHANGES, DB_CLOSE,
1870 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1871 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1872 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1873 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
1874 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
1875 DB_PREUPDATE, DB_PROFILE, DB_PROGRESS,
1876 DB_REKEY, DB_RESTORE, DB_ROLLBACK_HOOK,
1877 DB_STATUS, DB_TIMEOUT, DB_TOTAL_CHANGES,
1878 DB_TRACE, DB_TRACE_V2, DB_TRANSACTION,
1879 DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK, DB_VERSION,
1882 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
1885 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
1888 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
1892 switch( (enum DB_enum)choice ){
1894 /* $db authorizer ?CALLBACK?
1896 ** Invoke the given callback to authorize each SQL operation as it is
1897 ** compiled. 5 arguments are appended to the callback before it is
1900 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1901 ** (2) First descriptive name (depends on authorization type)
1902 ** (3) Second descriptive name
1903 ** (4) Name of the database (ex: "main", "temp")
1904 ** (5) Name of trigger that is doing the access
1906 ** The callback should return on of the following strings: SQLITE_OK,
1907 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1909 ** If this method is invoked with no arguments, the current authorization
1910 ** callback string is returned.
1912 case DB_AUTHORIZER: {
1913 #ifdef SQLITE_OMIT_AUTHORIZATION
1914 Tcl_AppendResult(interp, "authorization not available in this build",
1919 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1921 }else if( objc==2 ){
1923 Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
1929 Tcl_Free(pDb->zAuth);
1931 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1932 if( zAuth && len>0 ){
1933 pDb->zAuth = Tcl_Alloc( len + 1 );
1934 memcpy(pDb->zAuth, zAuth, len+1);
1939 typedef int (*sqlite3_auth_cb)(
1940 void*,int,const char*,const char*,
1941 const char*,const char*);
1942 pDb->interp = interp;
1943 sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
1945 sqlite3_set_authorizer(pDb->db, 0, 0);
1952 /* $db backup ?DATABASE? FILENAME
1954 ** Open or create a database file named FILENAME. Transfer the
1955 ** content of local database DATABASE (default: "main") into the
1956 ** FILENAME database.
1959 const char *zDestFile;
1962 sqlite3_backup *pBackup;
1966 zDestFile = Tcl_GetString(objv[2]);
1967 }else if( objc==4 ){
1968 zSrcDb = Tcl_GetString(objv[2]);
1969 zDestFile = Tcl_GetString(objv[3]);
1971 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1974 rc = sqlite3_open_v2(zDestFile, &pDest,
1975 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
1976 if( rc!=SQLITE_OK ){
1977 Tcl_AppendResult(interp, "cannot open target database: ",
1978 sqlite3_errmsg(pDest), (char*)0);
1979 sqlite3_close(pDest);
1982 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1984 Tcl_AppendResult(interp, "backup failed: ",
1985 sqlite3_errmsg(pDest), (char*)0);
1986 sqlite3_close(pDest);
1989 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1990 sqlite3_backup_finish(pBackup);
1991 if( rc==SQLITE_DONE ){
1994 Tcl_AppendResult(interp, "backup failed: ",
1995 sqlite3_errmsg(pDest), (char*)0);
1998 sqlite3_close(pDest);
2002 /* $db busy ?CALLBACK?
2004 ** Invoke the given callback if an SQL statement attempts to open
2005 ** a locked database file.
2009 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
2011 }else if( objc==2 ){
2013 Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
2019 Tcl_Free(pDb->zBusy);
2021 zBusy = Tcl_GetStringFromObj(objv[2], &len);
2022 if( zBusy && len>0 ){
2023 pDb->zBusy = Tcl_Alloc( len + 1 );
2024 memcpy(pDb->zBusy, zBusy, len+1);
2029 pDb->interp = interp;
2030 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
2032 sqlite3_busy_handler(pDb->db, 0, 0);
2041 ** Flush the prepared statement cache, or set the maximum number of
2042 ** cached statements.
2049 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
2052 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
2053 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
2055 Tcl_WrongNumArgs(interp, 2, objv, "flush");
2058 flushStmtCache( pDb );
2060 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
2062 Tcl_WrongNumArgs(interp, 2, objv, "size n");
2065 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
2066 Tcl_AppendResult( interp, "cannot convert \"",
2067 Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
2071 flushStmtCache( pDb );
2073 }else if( n>MAX_PREPARED_STMTS ){
2074 n = MAX_PREPARED_STMTS;
2080 Tcl_AppendResult( interp, "bad option \"",
2081 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
2090 ** Return the number of rows that were modified, inserted, or deleted by
2091 ** the most recent INSERT, UPDATE or DELETE statement, not including
2092 ** any changes made by trigger programs.
2097 Tcl_WrongNumArgs(interp, 2, objv, "");
2100 pResult = Tcl_GetObjResult(interp);
2101 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
2107 ** Shutdown the database
2110 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
2115 ** $db collate NAME SCRIPT
2117 ** Create a new SQL collation function called NAME. Whenever
2118 ** that function is called, invoke SCRIPT to evaluate the function.
2121 SqlCollate *pCollate;
2126 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
2129 zName = Tcl_GetStringFromObj(objv[2], 0);
2130 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
2131 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
2132 if( pCollate==0 ) return TCL_ERROR;
2133 pCollate->interp = interp;
2134 pCollate->pNext = pDb->pCollate;
2135 pCollate->zScript = (char*)&pCollate[1];
2136 pDb->pCollate = pCollate;
2137 memcpy(pCollate->zScript, zScript, nScript+1);
2138 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
2139 pCollate, tclSqlCollate) ){
2140 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
2147 ** $db collation_needed SCRIPT
2149 ** Create a new SQL collation function called NAME. Whenever
2150 ** that function is called, invoke SCRIPT to evaluate the function.
2152 case DB_COLLATION_NEEDED: {
2154 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
2157 if( pDb->pCollateNeeded ){
2158 Tcl_DecrRefCount(pDb->pCollateNeeded);
2160 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
2161 Tcl_IncrRefCount(pDb->pCollateNeeded);
2162 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
2166 /* $db commit_hook ?CALLBACK?
2168 ** Invoke the given callback just before committing every SQL transaction.
2169 ** If the callback throws an exception or returns non-zero, then the
2170 ** transaction is aborted. If CALLBACK is an empty string, the callback
2173 case DB_COMMIT_HOOK: {
2175 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2177 }else if( objc==2 ){
2179 Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
2182 const char *zCommit;
2185 Tcl_Free(pDb->zCommit);
2187 zCommit = Tcl_GetStringFromObj(objv[2], &len);
2188 if( zCommit && len>0 ){
2189 pDb->zCommit = Tcl_Alloc( len + 1 );
2190 memcpy(pDb->zCommit, zCommit, len+1);
2195 pDb->interp = interp;
2196 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
2198 sqlite3_commit_hook(pDb->db, 0, 0);
2206 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2207 ** additional lines of input are needed. This is similar to the
2208 ** built-in "info complete" command of Tcl.
2211 #ifndef SQLITE_OMIT_COMPLETE
2215 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2218 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
2219 pResult = Tcl_GetObjResult(interp);
2220 Tcl_SetBooleanObj(pResult, isComplete);
2225 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2227 ** Copy data into table from filename, optionally using SEPARATOR
2228 ** as column separators. If a column contains a null string, or the
2229 ** value of NULLINDICATOR, a NULL is inserted for the column.
2230 ** conflict-algorithm is one of the sqlite conflict algorithms:
2231 ** rollback, abort, fail, ignore, replace
2232 ** On success, return the number of lines processed, not necessarily same
2233 ** as 'db changes' due to conflict-algorithm selected.
2235 ** This code is basically an implementation/enhancement of
2236 ** the sqlite3 shell.c ".import" command.
2238 ** This command usage is equivalent to the sqlite2.x COPY statement,
2239 ** which imports file data into a table using the PostgreSQL COPY file format:
2240 ** $db copy $conflit_algo $table_name $filename \t \\N
2243 char *zTable; /* Insert data into this table */
2244 char *zFile; /* The file from which to extract data */
2245 char *zConflict; /* The conflict algorithm to use */
2246 sqlite3_stmt *pStmt; /* A statement */
2247 int nCol; /* Number of columns in the table */
2248 int nByte; /* Number of bytes in an SQL string */
2249 int i, j; /* Loop counters */
2250 int nSep; /* Number of bytes in zSep[] */
2251 int nNull; /* Number of bytes in zNull[] */
2252 char *zSql; /* An SQL statement */
2253 char *zLine; /* A single line of input from the file */
2254 char **azCol; /* zLine[] broken up into columns */
2255 const char *zCommit; /* How to commit changes */
2256 FILE *in; /* The input file */
2257 int lineno = 0; /* Line number of input file */
2258 char zLineNum[80]; /* Line number print buffer */
2259 Tcl_Obj *pResult; /* interp result */
2263 if( objc<5 || objc>7 ){
2264 Tcl_WrongNumArgs(interp, 2, objv,
2265 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2269 zSep = Tcl_GetStringFromObj(objv[5], 0);
2274 zNull = Tcl_GetStringFromObj(objv[6], 0);
2278 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2279 zTable = Tcl_GetStringFromObj(objv[3], 0);
2280 zFile = Tcl_GetStringFromObj(objv[4], 0);
2281 nSep = strlen30(zSep);
2282 nNull = strlen30(zNull);
2284 Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2288 if(strcmp(zConflict, "rollback") != 0 &&
2289 strcmp(zConflict, "abort" ) != 0 &&
2290 strcmp(zConflict, "fail" ) != 0 &&
2291 strcmp(zConflict, "ignore" ) != 0 &&
2292 strcmp(zConflict, "replace" ) != 0 ) {
2293 Tcl_AppendResult(interp, "Error: \"", zConflict,
2294 "\", conflict-algorithm must be one of: rollback, "
2295 "abort, fail, ignore, or replace", (char*)0);
2298 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2300 Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
2303 nByte = strlen30(zSql);
2304 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
2307 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2310 nCol = sqlite3_column_count(pStmt);
2312 sqlite3_finalize(pStmt);
2316 zSql = malloc( nByte + 50 + nCol*2 );
2318 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
2321 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2324 for(i=1; i<nCol; i++){
2330 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
2333 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2334 sqlite3_finalize(pStmt);
2337 in = fopen(zFile, "rb");
2339 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, (char*)0);
2340 sqlite3_finalize(pStmt);
2343 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2345 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
2349 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
2351 while( (zLine = local_getline(0, in))!=0 ){
2355 for(i=0, z=zLine; *z; z++){
2356 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2360 azCol[i] = &z[nSep];
2367 int nErr = strlen30(zFile) + 200;
2368 zErr = malloc(nErr);
2370 sqlite3_snprintf(nErr, zErr,
2371 "Error: %s line %d: expected %d columns of data but found %d",
2372 zFile, lineno, nCol, i+1);
2373 Tcl_AppendResult(interp, zErr, (char*)0);
2376 zCommit = "ROLLBACK";
2379 for(i=0; i<nCol; i++){
2380 /* check for null data, if so, bind as null */
2381 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
2382 || strlen30(azCol[i])==0
2384 sqlite3_bind_null(pStmt, i+1);
2386 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2389 sqlite3_step(pStmt);
2390 rc = sqlite3_reset(pStmt);
2392 if( rc!=SQLITE_OK ){
2393 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2394 zCommit = "ROLLBACK";
2400 sqlite3_finalize(pStmt);
2401 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
2403 if( zCommit[0] == 'C' ){
2404 /* success, set result as number of lines processed */
2405 pResult = Tcl_GetObjResult(interp);
2406 Tcl_SetIntObj(pResult, lineno);
2409 /* failure, append lineno where failed */
2410 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
2411 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2419 ** $db enable_load_extension BOOLEAN
2421 ** Turn the extension loading feature on or off. It if off by
2424 case DB_ENABLE_LOAD_EXTENSION: {
2425 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2428 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2431 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2434 sqlite3_enable_load_extension(pDb->db, onoff);
2437 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2446 ** Return the numeric error code that was returned by the most recent
2447 ** call to sqlite3_exec().
2449 case DB_ERRORCODE: {
2450 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
2456 ** $db onecolumn $sql
2458 ** The onecolumn method is the equivalent of:
2459 ** lindex [$db eval $sql] 0
2462 case DB_ONECOLUMN: {
2463 Tcl_Obj *pResult = 0;
2464 DbEvalContext sEval;
2466 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2470 dbEvalInit(&sEval, pDb, objv[2], 0, 0);
2471 rc = dbEvalStep(&sEval);
2472 if( choice==DB_ONECOLUMN ){
2474 pResult = dbEvalColumnValue(&sEval, 0);
2475 }else if( rc==TCL_BREAK ){
2476 Tcl_ResetResult(interp);
2478 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2479 pResult = Tcl_NewBooleanObj(rc==TCL_OK);
2481 dbEvalFinalize(&sEval);
2482 if( pResult ) Tcl_SetObjResult(interp, pResult);
2484 if( rc==TCL_BREAK ){
2491 ** $db eval ?options? $sql ?array? ?{ ...code... }?
2493 ** The SQL statement in $sql is evaluated. For each row, the values are
2494 ** placed in elements of the array named "array" and ...code... is executed.
2495 ** If "array" and "code" are omitted, then no callback is every invoked.
2496 ** If "array" is an empty string, then the values are placed in variables
2497 ** that have the same name as the fields extracted by the query.
2502 while( objc>3 && (zOpt = Tcl_GetString(objv[2]))!=0 && zOpt[0]=='-' ){
2503 if( strcmp(zOpt, "-withoutnulls")==0 ){
2504 evalFlags |= SQLITE_EVAL_WITHOUTNULLS;
2507 Tcl_AppendResult(interp, "unknown option: \"", zOpt, "\"", (void*)0);
2513 if( objc<3 || objc>5 ){
2514 Tcl_WrongNumArgs(interp, 2, objv,
2515 "?OPTIONS? SQL ?ARRAY-NAME? ?SCRIPT?");
2520 DbEvalContext sEval;
2521 Tcl_Obj *pRet = Tcl_NewObj();
2522 Tcl_IncrRefCount(pRet);
2523 dbEvalInit(&sEval, pDb, objv[2], 0, 0);
2524 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2527 dbEvalRowInfo(&sEval, &nCol, 0);
2528 for(i=0; i<nCol; i++){
2529 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
2532 dbEvalFinalize(&sEval);
2533 if( rc==TCL_BREAK ){
2534 Tcl_SetObjResult(interp, pRet);
2537 Tcl_DecrRefCount(pRet);
2541 Tcl_Obj *pArray = 0;
2544 if( objc>=5 && *(char *)Tcl_GetString(objv[3]) ){
2547 pScript = objv[objc-1];
2548 Tcl_IncrRefCount(pScript);
2550 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2551 dbEvalInit(p, pDb, objv[2], pArray, evalFlags);
2554 cd2[1] = (void *)pScript;
2555 rc = DbEvalNextCmd(cd2, interp, TCL_OK);
2561 ** $db function NAME [-argcount N] [-deterministic] SCRIPT
2563 ** Create a new SQL function called NAME. Whenever that function is
2564 ** called, invoke SCRIPT to evaluate the function.
2567 int flags = SQLITE_UTF8;
2574 Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
2577 for(i=3; i<(objc-1); i++){
2578 const char *z = Tcl_GetString(objv[i]);
2579 int n = strlen30(z);
2580 if( n>2 && strncmp(z, "-argcount",n)==0 ){
2582 Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0);
2585 if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
2587 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2593 if( n>2 && strncmp(z, "-deterministic",n)==0 ){
2594 flags |= SQLITE_DETERMINISTIC;
2596 Tcl_AppendResult(interp, "bad option \"", z,
2597 "\": must be -argcount or -deterministic", (char*)0
2603 pScript = objv[objc-1];
2604 zName = Tcl_GetStringFromObj(objv[2], 0);
2605 pFunc = findSqlFunc(pDb, zName);
2606 if( pFunc==0 ) return TCL_ERROR;
2607 if( pFunc->pScript ){
2608 Tcl_DecrRefCount(pFunc->pScript);
2610 pFunc->pScript = pScript;
2611 Tcl_IncrRefCount(pScript);
2612 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
2613 rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
2614 pFunc, tclSqlFunc, 0, 0);
2615 if( rc!=SQLITE_OK ){
2617 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
2623 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
2626 #ifdef SQLITE_OMIT_INCRBLOB
2627 Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
2631 const char *zDb = "main";
2633 const char *zColumn;
2636 /* Check for the -readonly option */
2637 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2641 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2642 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
2646 if( objc==(6+isReadonly) ){
2647 zDb = Tcl_GetString(objv[2]);
2649 zTable = Tcl_GetString(objv[objc-3]);
2650 zColumn = Tcl_GetString(objv[objc-2]);
2651 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2654 rc = createIncrblobChannel(
2655 interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
2665 ** Interrupt the execution of the inner-most SQL interpreter. This
2666 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2668 case DB_INTERRUPT: {
2669 sqlite3_interrupt(pDb->db);
2674 ** $db nullvalue ?STRING?
2676 ** Change text used when a NULL comes back from the database. If ?STRING?
2677 ** is not present, then the current string used for NULL is returned.
2678 ** If STRING is present, then STRING is returned.
2681 case DB_NULLVALUE: {
2682 if( objc!=2 && objc!=3 ){
2683 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2688 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2690 Tcl_Free(pDb->zNull);
2692 if( zNull && len>0 ){
2693 pDb->zNull = Tcl_Alloc( len + 1 );
2694 memcpy(pDb->zNull, zNull, len);
2695 pDb->zNull[len] = '\0';
2700 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
2705 ** $db last_insert_rowid
2707 ** Return an integer which is the ROWID for the most recent insert.
2709 case DB_LAST_INSERT_ROWID: {
2713 Tcl_WrongNumArgs(interp, 2, objv, "");
2716 rowid = sqlite3_last_insert_rowid(pDb->db);
2717 pResult = Tcl_GetObjResult(interp);
2718 Tcl_SetWideIntObj(pResult, rowid);
2723 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
2726 /* $db progress ?N CALLBACK?
2728 ** Invoke the given callback every N virtual machine opcodes while executing
2733 if( pDb->zProgress ){
2734 Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
2736 }else if( objc==4 ){
2740 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
2743 if( pDb->zProgress ){
2744 Tcl_Free(pDb->zProgress);
2746 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2747 if( zProgress && len>0 ){
2748 pDb->zProgress = Tcl_Alloc( len + 1 );
2749 memcpy(pDb->zProgress, zProgress, len+1);
2753 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2754 if( pDb->zProgress ){
2755 pDb->interp = interp;
2756 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2758 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2762 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
2768 /* $db profile ?CALLBACK?
2770 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2771 ** that has run. The text of the SQL and the amount of elapse time are
2772 ** appended to CALLBACK before the script is run.
2776 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2778 }else if( objc==2 ){
2779 if( pDb->zProfile ){
2780 Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
2785 if( pDb->zProfile ){
2786 Tcl_Free(pDb->zProfile);
2788 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2789 if( zProfile && len>0 ){
2790 pDb->zProfile = Tcl_Alloc( len + 1 );
2791 memcpy(pDb->zProfile, zProfile, len+1);
2795 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
2796 !defined(SQLITE_OMIT_DEPRECATED)
2797 if( pDb->zProfile ){
2798 pDb->interp = interp;
2799 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2801 sqlite3_profile(pDb->db, 0, 0);
2811 ** Change the encryption key on the currently open database.
2814 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
2819 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2822 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
2823 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
2824 rc = sqlite3_rekey(pDb->db, pKey, nKey);
2826 Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
2833 /* $db restore ?DATABASE? FILENAME
2835 ** Open a database file named FILENAME. Transfer the content
2836 ** of FILENAME into the local database DATABASE (default: "main").
2839 const char *zSrcFile;
2840 const char *zDestDb;
2842 sqlite3_backup *pBackup;
2847 zSrcFile = Tcl_GetString(objv[2]);
2848 }else if( objc==4 ){
2849 zDestDb = Tcl_GetString(objv[2]);
2850 zSrcFile = Tcl_GetString(objv[3]);
2852 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2855 rc = sqlite3_open_v2(zSrcFile, &pSrc,
2856 SQLITE_OPEN_READONLY | pDb->openFlags, 0);
2857 if( rc!=SQLITE_OK ){
2858 Tcl_AppendResult(interp, "cannot open source database: ",
2859 sqlite3_errmsg(pSrc), (char*)0);
2860 sqlite3_close(pSrc);
2863 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2865 Tcl_AppendResult(interp, "restore failed: ",
2866 sqlite3_errmsg(pDb->db), (char*)0);
2867 sqlite3_close(pSrc);
2870 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2871 || rc==SQLITE_BUSY ){
2872 if( rc==SQLITE_BUSY ){
2873 if( nTimeout++ >= 3 ) break;
2877 sqlite3_backup_finish(pBackup);
2878 if( rc==SQLITE_DONE ){
2880 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2881 Tcl_AppendResult(interp, "restore failed: source database busy",
2885 Tcl_AppendResult(interp, "restore failed: ",
2886 sqlite3_errmsg(pDb->db), (char*)0);
2889 sqlite3_close(pSrc);
2894 ** $db status (step|sort|autoindex|vmstep)
2896 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2897 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2903 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
2906 zOp = Tcl_GetString(objv[2]);
2907 if( strcmp(zOp, "step")==0 ){
2909 }else if( strcmp(zOp, "sort")==0 ){
2911 }else if( strcmp(zOp, "autoindex")==0 ){
2913 }else if( strcmp(zOp, "vmstep")==0 ){
2916 Tcl_AppendResult(interp,
2917 "bad argument: should be autoindex, step, sort or vmstep",
2921 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2926 ** $db timeout MILLESECONDS
2928 ** Delay for the number of milliseconds specified when a file is locked.
2933 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
2936 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
2937 sqlite3_busy_timeout(pDb->db, ms);
2942 ** $db total_changes
2944 ** Return the number of rows that were modified, inserted, or deleted
2945 ** since the database handle was created.
2947 case DB_TOTAL_CHANGES: {
2950 Tcl_WrongNumArgs(interp, 2, objv, "");
2953 pResult = Tcl_GetObjResult(interp);
2954 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2958 /* $db trace ?CALLBACK?
2960 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2961 ** that is executed. The text of the SQL is appended to CALLBACK before
2966 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2968 }else if( objc==2 ){
2970 Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
2976 Tcl_Free(pDb->zTrace);
2978 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2979 if( zTrace && len>0 ){
2980 pDb->zTrace = Tcl_Alloc( len + 1 );
2981 memcpy(pDb->zTrace, zTrace, len+1);
2985 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
2986 !defined(SQLITE_OMIT_DEPRECATED)
2988 pDb->interp = interp;
2989 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
2991 sqlite3_trace(pDb->db, 0, 0);
2998 /* $db trace_v2 ?CALLBACK? ?MASK?
3000 ** Make arrangements to invoke the CALLBACK routine for each trace event
3001 ** matching the mask that is generated. The parameters are appended to
3002 ** CALLBACK before it is executed.
3006 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK? ?MASK?");
3008 }else if( objc==2 ){
3009 if( pDb->zTraceV2 ){
3010 Tcl_AppendResult(interp, pDb->zTraceV2, (char*)0);
3015 Tcl_WideInt wMask = 0;
3017 static const char *TTYPE_strs[] = {
3018 "statement", "profile", "row", "close", 0
3021 TTYPE_STMT, TTYPE_PROFILE, TTYPE_ROW, TTYPE_CLOSE
3024 if( TCL_OK!=Tcl_ListObjLength(interp, objv[3], &len) ){
3027 for(i=0; i<len; i++){
3030 if( TCL_OK!=Tcl_ListObjIndex(interp, objv[3], i, &pObj) ){
3033 if( Tcl_GetIndexFromObj(interp, pObj, TTYPE_strs, "trace type",
3034 0, &ttype)!=TCL_OK ){
3036 Tcl_Obj *pError = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
3037 Tcl_IncrRefCount(pError);
3038 if( TCL_OK==Tcl_GetWideIntFromObj(interp, pObj, &wType) ){
3039 Tcl_DecrRefCount(pError);
3042 Tcl_SetObjResult(interp, pError);
3043 Tcl_DecrRefCount(pError);
3047 switch( (enum TTYPE_enum)ttype ){
3048 case TTYPE_STMT: wMask |= SQLITE_TRACE_STMT; break;
3049 case TTYPE_PROFILE: wMask |= SQLITE_TRACE_PROFILE; break;
3050 case TTYPE_ROW: wMask |= SQLITE_TRACE_ROW; break;
3051 case TTYPE_CLOSE: wMask |= SQLITE_TRACE_CLOSE; break;
3056 wMask = SQLITE_TRACE_STMT; /* use the "legacy" default */
3058 if( pDb->zTraceV2 ){
3059 Tcl_Free(pDb->zTraceV2);
3061 zTraceV2 = Tcl_GetStringFromObj(objv[2], &len);
3062 if( zTraceV2 && len>0 ){
3063 pDb->zTraceV2 = Tcl_Alloc( len + 1 );
3064 memcpy(pDb->zTraceV2, zTraceV2, len+1);
3068 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3069 if( pDb->zTraceV2 ){
3070 pDb->interp = interp;
3071 sqlite3_trace_v2(pDb->db, (unsigned)wMask, DbTraceV2Handler, pDb);
3073 sqlite3_trace_v2(pDb->db, 0, 0, 0);
3080 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
3082 ** Start a new transaction (if we are not already in the midst of a
3083 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
3084 ** completes, either commit the transaction or roll it back if SCRIPT
3085 ** throws an exception. Or if no new transation was started, do nothing.
3086 ** pass the exception on up the stack.
3088 ** This command was inspired by Dave Thomas's talk on Ruby at the
3089 ** 2005 O'Reilly Open Source Convention (OSCON).
3091 case DB_TRANSACTION: {
3093 const char *zBegin = "SAVEPOINT _tcl_transaction";
3094 if( objc!=3 && objc!=4 ){
3095 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
3099 if( pDb->nTransaction==0 && objc==4 ){
3100 static const char *TTYPE_strs[] = {
3101 "deferred", "exclusive", "immediate", 0
3104 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
3107 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
3111 switch( (enum TTYPE_enum)ttype ){
3112 case TTYPE_DEFERRED: /* no-op */; break;
3113 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
3114 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
3117 pScript = objv[objc-1];
3119 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
3121 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
3123 if( rc!=SQLITE_OK ){
3124 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3127 pDb->nTransaction++;
3129 /* If using NRE, schedule a callback to invoke the script pScript, then
3130 ** a second callback to commit (or rollback) the transaction or savepoint
3131 ** opened above. If not using NRE, evaluate the script directly, then
3132 ** call function DbTransPostCmd() to commit (or rollback) the transaction
3135 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
3136 (void)Tcl_NREvalObj(interp, pScript, 0);
3138 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
3144 ** $db unlock_notify ?script?
3146 case DB_UNLOCK_NOTIFY: {
3147 #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
3148 Tcl_AppendResult(interp, "unlock_notify not available in this build",
3152 if( objc!=2 && objc!=3 ){
3153 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3156 void (*xNotify)(void **, int) = 0;
3157 void *pNotifyArg = 0;
3159 if( pDb->pUnlockNotify ){
3160 Tcl_DecrRefCount(pDb->pUnlockNotify);
3161 pDb->pUnlockNotify = 0;
3165 xNotify = DbUnlockNotify;
3166 pNotifyArg = (void *)pDb;
3167 pDb->pUnlockNotify = objv[2];
3168 Tcl_IncrRefCount(pDb->pUnlockNotify);
3171 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
3172 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3181 ** $db preupdate_hook count
3182 ** $db preupdate_hook hook ?SCRIPT?
3183 ** $db preupdate_hook new INDEX
3184 ** $db preupdate_hook old INDEX
3186 case DB_PREUPDATE: {
3187 #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
3188 Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time",
3192 static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
3193 enum DbPreupdateSubCmd {
3194 PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
3199 Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
3201 if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
3205 switch( (enum DbPreupdateSubCmd)iSub ){
3207 int nCol = sqlite3_preupdate_count(pDb->db);
3208 Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
3214 Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
3217 DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
3224 Tcl_WrongNumArgs(interp, 3, objv, "");
3227 pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
3228 Tcl_SetObjResult(interp, pRet);
3235 sqlite3_value *pValue;
3237 Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
3240 if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
3244 if( iSub==PRE_OLD ){
3245 rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
3247 assert( iSub==PRE_NEW );
3248 rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
3251 if( rc==SQLITE_OK ){
3253 pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
3254 Tcl_SetObjResult(interp, pObj);
3256 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3261 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
3266 ** $db wal_hook ?script?
3267 ** $db update_hook ?script?
3268 ** $db rollback_hook ?script?
3271 case DB_UPDATE_HOOK:
3272 case DB_ROLLBACK_HOOK: {
3273 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
3274 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3276 Tcl_Obj **ppHook = 0;
3277 if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
3278 if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
3279 if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
3281 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3285 DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
3291 ** Return the version string for this database.
3294 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
3299 } /* End of the SWITCH statement */
3305 ** Adaptor that provides an objCmd interface to the NRE-enabled
3306 ** interface implementation.
3308 static int SQLITE_TCLAPI DbObjCmdAdaptor(
3314 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
3316 #endif /* SQLITE_TCL_NRE */
3319 ** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
3320 ** ?-create BOOLEAN? ?-nomutex BOOLEAN?
3322 ** This is the main Tcl command. When the "sqlite" Tcl command is
3323 ** invoked, this routine runs to process that command.
3325 ** The first argument, DBNAME, is an arbitrary name for a new
3326 ** database connection. This command creates a new command named
3327 ** DBNAME that is used to control that connection. The database
3328 ** connection is deleted when the DBNAME command is deleted.
3330 ** The second argument is the name of the database file.
3333 static int SQLITE_TCLAPI DbMain(
3344 const char *zVfs = 0;
3346 Tcl_DString translatedFilename;
3347 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3353 /* In normal use, each TCL interpreter runs in a single thread. So
3354 ** by default, we can turn of mutexing on SQLite database connections.
3355 ** However, for testing purposes it is useful to have mutexes turned
3356 ** on. So, by default, mutexes default off. But if compiled with
3357 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3359 #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3360 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3362 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3366 zArg = Tcl_GetStringFromObj(objv[1], 0);
3367 if( strcmp(zArg,"-version")==0 ){
3368 Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
3371 if( strcmp(zArg,"-sourceid")==0 ){
3372 Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0);
3375 if( strcmp(zArg,"-has-codec")==0 ){
3376 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3377 Tcl_AppendResult(interp,"1",(char*)0);
3379 Tcl_AppendResult(interp,"0",(char*)0);
3384 for(i=3; i+1<objc; i+=2){
3385 zArg = Tcl_GetString(objv[i]);
3386 if( strcmp(zArg,"-key")==0 ){
3387 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3388 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
3390 }else if( strcmp(zArg, "-vfs")==0 ){
3391 zVfs = Tcl_GetString(objv[i+1]);
3392 }else if( strcmp(zArg, "-readonly")==0 ){
3394 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3396 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
3397 flags |= SQLITE_OPEN_READONLY;
3399 flags &= ~SQLITE_OPEN_READONLY;
3400 flags |= SQLITE_OPEN_READWRITE;
3402 }else if( strcmp(zArg, "-create")==0 ){
3404 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3405 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
3406 flags |= SQLITE_OPEN_CREATE;
3408 flags &= ~SQLITE_OPEN_CREATE;
3410 }else if( strcmp(zArg, "-nomutex")==0 ){
3412 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3414 flags |= SQLITE_OPEN_NOMUTEX;
3415 flags &= ~SQLITE_OPEN_FULLMUTEX;
3417 flags &= ~SQLITE_OPEN_NOMUTEX;
3419 }else if( strcmp(zArg, "-fullmutex")==0 ){
3421 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3423 flags |= SQLITE_OPEN_FULLMUTEX;
3424 flags &= ~SQLITE_OPEN_NOMUTEX;
3426 flags &= ~SQLITE_OPEN_FULLMUTEX;
3428 }else if( strcmp(zArg, "-uri")==0 ){
3430 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3432 flags |= SQLITE_OPEN_URI;
3434 flags &= ~SQLITE_OPEN_URI;
3437 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3441 if( objc<3 || (objc&1)!=1 ){
3442 Tcl_WrongNumArgs(interp, 1, objv,
3443 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
3444 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
3445 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3452 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
3453 memset(p, 0, sizeof(*p));
3454 zFile = Tcl_GetStringFromObj(objv[2], 0);
3455 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
3456 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
3457 Tcl_DStringFree(&translatedFilename);
3459 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3460 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3461 sqlite3_close(p->db);
3465 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
3467 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3469 sqlite3_key(p->db, pKey, nKey);
3473 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
3475 sqlite3_free(zErrMsg);
3478 p->maxStmt = NUM_PREPARED_STMTS;
3479 p->openFlags = flags & SQLITE_OPEN_URI;
3481 zArg = Tcl_GetStringFromObj(objv[1], 0);
3483 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3484 (char*)p, DbDeleteCmd);
3486 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3492 ** Provide a dummy Tcl_InitStubs if we are using this as a static
3495 #ifndef USE_TCL_STUBS
3496 # undef Tcl_InitStubs
3497 # define Tcl_InitStubs(a,b,c) TCL_VERSION
3501 ** Make sure we have a PACKAGE_VERSION macro defined. This will be
3502 ** defined automatically by the TEA makefile. But other makefiles
3503 ** do not define it.
3505 #ifndef PACKAGE_VERSION
3506 # define PACKAGE_VERSION SQLITE_VERSION
3510 ** Initialize this module.
3512 ** This Tcl module contains only a single new Tcl command named "sqlite".
3513 ** (Hence there is no namespace. There is no point in using a namespace
3514 ** if the extension only supplies one new name!) The "sqlite" command is
3515 ** used to open a new SQLite database. See the DbMain() routine above
3516 ** for additional information.
3518 ** The EXTERN macros are required by TCL in order to work on windows.
3520 EXTERN int Sqlite3_Init(Tcl_Interp *interp){
3521 int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
3523 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
3524 #ifndef SQLITE_3_SUFFIX_ONLY
3525 /* The "sqlite" alias is undocumented. It is here only to support
3526 ** legacy scripts. All new scripts should use only the "sqlite3"
3528 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
3530 rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3534 EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3535 EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3536 EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3538 /* Because it accesses the file-system and uses persistent state, SQLite
3539 ** is not considered appropriate for safe interpreters. Hence, we cause
3540 ** the _SafeInit() interfaces return TCL_ERROR.
3542 EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
3543 EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
3547 #ifndef SQLITE_3_SUFFIX_ONLY
3548 int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3549 int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3550 int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3551 int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3555 /*****************************************************************************
3556 ** All of the code that follows is used to build standalone TCL interpreters
3557 ** that are statically linked with SQLite. Enable these by compiling
3558 ** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3559 ** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3560 ** analysis program.
3563 #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3565 * This code implements the MD5 message-digest algorithm.
3566 * The algorithm is due to Ron Rivest. This code was
3567 * written by Colin Plumb in 1993, no copyright is claimed.
3568 * This code is in the public domain; do with it what you wish.
3570 * Equivalent code is available from RSA Data Security, Inc.
3571 * This code has been tested against that, and is equivalent,
3572 * except that you don't need to include two pages of legalese
3575 * To compute the message digest of a chunk of bytes, declare an
3576 * MD5Context structure, pass it to MD5Init, call MD5Update as
3577 * needed on buffers full of bytes, and then call MD5Final, which
3578 * will fill a supplied 16-byte array with the digest.
3582 * If compiled on a machine that doesn't have a 32-bit integer,
3583 * you just set "uint32" to the appropriate datatype for an
3584 * unsigned 32-bit integer. For example:
3586 * cc -Duint32='unsigned long' md5.c
3590 # define uint32 unsigned int
3597 unsigned char in[64];
3599 typedef struct MD5Context MD5Context;
3602 * Note: this code is harmless on little-endian machines.
3604 static void byteReverse (unsigned char *buf, unsigned longs){
3607 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3608 ((unsigned)buf[1]<<8 | buf[0]);
3613 /* The four core functions - F1 is optimized somewhat */
3615 /* #define F1(x, y, z) (x & y | ~x & z) */
3616 #define F1(x, y, z) (z ^ (x & (y ^ z)))
3617 #define F2(x, y, z) F1(z, x, y)
3618 #define F3(x, y, z) (x ^ y ^ z)
3619 #define F4(x, y, z) (y ^ (x | ~z))
3621 /* This is the central step in the MD5 algorithm. */
3622 #define MD5STEP(f, w, x, y, z, data, s) \
3623 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3626 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3627 * reflect the addition of 16 longwords of new data. MD5Update blocks
3628 * the data and converts bytes into longwords for this routine.
3630 static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3631 register uint32 a, b, c, d;
3638 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3639 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3640 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3641 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3642 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3643 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3644 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3645 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3646 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3647 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3648 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3649 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3650 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3651 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3652 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3653 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3655 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3656 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3657 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3658 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3659 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3660 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3661 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3662 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3663 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3664 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3665 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3666 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3667 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3668 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3669 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3670 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3672 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3673 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3674 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3675 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3676 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3677 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3678 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3679 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3680 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3681 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3682 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3683 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3684 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3685 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3686 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3687 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3689 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3690 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3691 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3692 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3693 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3694 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3695 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3696 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3697 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3698 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3699 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3700 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3701 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3702 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3703 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3704 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3713 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3714 * initialization constants.
3716 static void MD5Init(MD5Context *ctx){
3718 ctx->buf[0] = 0x67452301;
3719 ctx->buf[1] = 0xefcdab89;
3720 ctx->buf[2] = 0x98badcfe;
3721 ctx->buf[3] = 0x10325476;
3727 * Update context to reflect the concatenation of another buffer full
3731 void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3734 /* Update bitcount */
3737 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3738 ctx->bits[1]++; /* Carry from low to high */
3739 ctx->bits[1] += len >> 29;
3741 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3743 /* Handle any leading odd-sized chunks */
3746 unsigned char *p = (unsigned char *)ctx->in + t;
3750 memcpy(p, buf, len);
3754 byteReverse(ctx->in, 16);
3755 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3760 /* Process data in 64-byte chunks */
3763 memcpy(ctx->in, buf, 64);
3764 byteReverse(ctx->in, 16);
3765 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3770 /* Handle any remaining bytes of data. */
3772 memcpy(ctx->in, buf, len);
3776 * Final wrapup - pad to 64-byte boundary with the bit pattern
3777 * 1 0* (64-bit count of bits processed, MSB-first)
3779 static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3783 /* Compute number of bytes mod 64 */
3784 count = (ctx->bits[0] >> 3) & 0x3F;
3786 /* Set the first char of padding to 0x80. This is safe since there is
3787 always at least one byte free */
3788 p = ctx->in + count;
3791 /* Bytes of padding needed to make 64 bytes */
3792 count = 64 - 1 - count;
3794 /* Pad out to 56 mod 64 */
3796 /* Two lots of padding: Pad the first block to 64 bytes */
3797 memset(p, 0, count);
3798 byteReverse(ctx->in, 16);
3799 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3801 /* Now fill the next block with 56 bytes */
3802 memset(ctx->in, 0, 56);
3804 /* Pad block to 56 bytes */
3805 memset(p, 0, count-8);
3807 byteReverse(ctx->in, 14);
3809 /* Append length in bits and transform */
3810 memcpy(ctx->in + 14*4, ctx->bits, 8);
3812 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3813 byteReverse((unsigned char *)ctx->buf, 4);
3814 memcpy(digest, ctx->buf, 16);
3818 ** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3820 static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3821 static char const zEncode[] = "0123456789abcdef";
3824 for(j=i=0; i<16; i++){
3826 zBuf[j++] = zEncode[(a>>4)&0xf];
3827 zBuf[j++] = zEncode[a & 0xf];
3834 ** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3835 ** each representing 16 bits of the digest and separated from each
3836 ** other by a "-" character.
3838 static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3841 for(i=j=0; i<16; i+=2){
3842 x = digest[i]*256 + digest[i+1];
3843 if( i>0 ) zDigest[j++] = '-';
3844 sqlite3_snprintf(50-j, &zDigest[j], "%05u", x);
3851 ** A TCL command for md5. The argument is the text to be hashed. The
3852 ** Result is the hash in base64.
3854 static int SQLITE_TCLAPI md5_cmd(
3861 unsigned char digest[16];
3863 void (*converter)(unsigned char*, char*);
3866 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3867 " TEXT\"", (char*)0);
3871 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3872 MD5Final(digest, &ctx);
3873 converter = (void(*)(unsigned char*,char*))cd;
3874 converter(digest, zBuf);
3875 Tcl_AppendResult(interp, zBuf, (char*)0);
3880 ** A TCL command to take the md5 hash of a file. The argument is the
3881 ** name of the file.
3883 static int SQLITE_TCLAPI md5file_cmd(
3891 void (*converter)(unsigned char*, char*);
3892 unsigned char digest[16];
3896 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3897 " FILENAME\"", (char*)0);
3900 in = fopen(argv[1],"rb");
3902 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
3903 "\" for reading", (char*)0);
3909 n = (int)fread(zBuf, 1, sizeof(zBuf), in);
3911 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3914 MD5Final(digest, &ctx);
3915 converter = (void(*)(unsigned char*,char*))cd;
3916 converter(digest, zBuf);
3917 Tcl_AppendResult(interp, zBuf, (char*)0);
3922 ** Register the four new TCL commands for generating MD5 checksums
3923 ** with the TCL interpreter.
3925 int Md5_Init(Tcl_Interp *interp){
3926 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3927 MD5DigestToBase16, 0);
3928 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3929 MD5DigestToBase10x8, 0);
3930 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3931 MD5DigestToBase16, 0);
3932 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3933 MD5DigestToBase10x8, 0);
3936 #endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3938 #if defined(SQLITE_TEST)
3940 ** During testing, the special md5sum() aggregate function is available.
3941 ** inside SQLite. The following routines implement that function.
3943 static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3946 if( argc<1 ) return;
3947 p = sqlite3_aggregate_context(context, sizeof(*p));
3952 for(i=0; i<argc; i++){
3953 const char *zData = (char*)sqlite3_value_text(argv[i]);
3955 MD5Update(p, (unsigned char*)zData, (int)strlen(zData));
3959 static void md5finalize(sqlite3_context *context){
3961 unsigned char digest[16];
3963 p = sqlite3_aggregate_context(context, sizeof(*p));
3965 MD5DigestToBase16(digest, zBuf);
3966 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3971 const sqlite3_api_routines *pThunk
3973 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
3974 md5step, md5finalize);
3975 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3978 #endif /* defined(SQLITE_TEST) */
3982 ** If the macro TCLSH is one, then put in code this for the
3983 ** "main" routine that will initialize Tcl and take input from
3984 ** standard input, or if a file is named on the command line
3985 ** the TCL interpreter reads and evaluates that file.
3988 static const char *tclsh_main_loop(void){
3989 static const char zMainloop[] =
3991 "while {![eof stdin]} {\n"
3992 "if {$line!=\"\"} {\n"
3993 "puts -nonewline \"> \"\n"
3995 "puts -nonewline \"% \"\n"
3998 "append line [gets stdin]\n"
3999 "if {[info complete $line]} {\n"
4000 "if {[catch {uplevel #0 $line} result]} {\n"
4001 "puts stderr \"Error: $result\"\n"
4002 "} elseif {$result!=\"\"} {\n"
4015 static const char *tclsh_main_loop(void);
4019 static void init_all(Tcl_Interp *);
4020 static int SQLITE_TCLAPI init_all_cmd(
4024 Tcl_Obj *CONST objv[]
4029 Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
4033 slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
4043 ** Tclcmd: db_use_legacy_prepare DB BOOLEAN
4045 ** The first argument to this command must be a database command created by
4046 ** [sqlite3]. If the second argument is true, then the handle is configured
4047 ** to use the sqlite3_prepare_v2() function to prepare statements. If it
4048 ** is false, sqlite3_prepare().
4050 static int SQLITE_TCLAPI db_use_legacy_prepare_cmd(
4054 Tcl_Obj *CONST objv[]
4056 Tcl_CmdInfo cmdInfo;
4061 Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
4065 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
4066 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
4069 pDb = (SqliteDb*)cmdInfo.objClientData;
4070 if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
4074 pDb->bLegacyPrepare = bPrepare;
4076 Tcl_ResetResult(interp);
4081 ** Tclcmd: db_last_stmt_ptr DB
4083 ** If the statement cache associated with database DB is not empty,
4084 ** return the text representation of the most recently used statement
4087 static int SQLITE_TCLAPI db_last_stmt_ptr(
4091 Tcl_Obj *CONST objv[]
4093 extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
4094 Tcl_CmdInfo cmdInfo;
4096 sqlite3_stmt *pStmt = 0;
4100 Tcl_WrongNumArgs(interp, 1, objv, "DB");
4104 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
4105 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
4108 pDb = (SqliteDb*)cmdInfo.objClientData;
4110 if( pDb->stmtList ) pStmt = pDb->stmtList->pStmt;
4111 if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ){
4114 Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
4118 #endif /* SQLITE_TEST */
4121 ** Configure the interpreter passed as the first argument to have access
4122 ** to the commands and linked variables that make up:
4124 ** * the [sqlite3] extension itself,
4126 ** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
4128 ** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
4131 static void init_all(Tcl_Interp *interp){
4132 Sqlite3_Init(interp);
4134 #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
4140 extern int Sqliteconfig_Init(Tcl_Interp*);
4141 extern int Sqlitetest1_Init(Tcl_Interp*);
4142 extern int Sqlitetest2_Init(Tcl_Interp*);
4143 extern int Sqlitetest3_Init(Tcl_Interp*);
4144 extern int Sqlitetest4_Init(Tcl_Interp*);
4145 extern int Sqlitetest5_Init(Tcl_Interp*);
4146 extern int Sqlitetest6_Init(Tcl_Interp*);
4147 extern int Sqlitetest7_Init(Tcl_Interp*);
4148 extern int Sqlitetest8_Init(Tcl_Interp*);
4149 extern int Sqlitetest9_Init(Tcl_Interp*);
4150 extern int Sqlitetestasync_Init(Tcl_Interp*);
4151 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
4152 extern int Sqlitetest_blob_Init(Tcl_Interp*);
4153 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
4154 extern int Sqlitetest_func_Init(Tcl_Interp*);
4155 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
4156 extern int Sqlitetest_init_Init(Tcl_Interp*);
4157 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
4158 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
4159 extern int Sqlitetestschema_Init(Tcl_Interp*);
4160 extern int Sqlitetestsse_Init(Tcl_Interp*);
4161 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
4162 extern int Sqlitetestfs_Init(Tcl_Interp*);
4163 extern int SqlitetestThread_Init(Tcl_Interp*);
4164 extern int SqlitetestOnefile_Init();
4165 extern int SqlitetestOsinst_Init(Tcl_Interp*);
4166 extern int Sqlitetestbackup_Init(Tcl_Interp*);
4167 extern int Sqlitetestintarray_Init(Tcl_Interp*);
4168 extern int Sqlitetestvfs_Init(Tcl_Interp *);
4169 extern int Sqlitetestrtree_Init(Tcl_Interp*);
4170 extern int Sqlitequota_Init(Tcl_Interp*);
4171 extern int Sqlitemultiplex_Init(Tcl_Interp*);
4172 extern int SqliteSuperlock_Init(Tcl_Interp*);
4173 extern int SqlitetestSyscall_Init(Tcl_Interp*);
4174 #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
4175 extern int TestSession_Init(Tcl_Interp*);
4177 extern int Fts5tcl_Init(Tcl_Interp *);
4178 extern int SqliteRbu_Init(Tcl_Interp*);
4179 extern int Sqlitetesttcl_Init(Tcl_Interp*);
4180 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
4181 extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
4184 #ifdef SQLITE_ENABLE_ZIPVFS
4185 extern int Zipvfs_Init(Tcl_Interp*);
4186 Zipvfs_Init(interp);
4189 Sqliteconfig_Init(interp);
4190 Sqlitetest1_Init(interp);
4191 Sqlitetest2_Init(interp);
4192 Sqlitetest3_Init(interp);
4193 Sqlitetest4_Init(interp);
4194 Sqlitetest5_Init(interp);
4195 Sqlitetest6_Init(interp);
4196 Sqlitetest7_Init(interp);
4197 Sqlitetest8_Init(interp);
4198 Sqlitetest9_Init(interp);
4199 Sqlitetestasync_Init(interp);
4200 Sqlitetest_autoext_Init(interp);
4201 Sqlitetest_blob_Init(interp);
4202 Sqlitetest_demovfs_Init(interp);
4203 Sqlitetest_func_Init(interp);
4204 Sqlitetest_hexio_Init(interp);
4205 Sqlitetest_init_Init(interp);
4206 Sqlitetest_malloc_Init(interp);
4207 Sqlitetest_mutex_Init(interp);
4208 Sqlitetestschema_Init(interp);
4209 Sqlitetesttclvar_Init(interp);
4210 Sqlitetestfs_Init(interp);
4211 SqlitetestThread_Init(interp);
4212 SqlitetestOnefile_Init();
4213 SqlitetestOsinst_Init(interp);
4214 Sqlitetestbackup_Init(interp);
4215 Sqlitetestintarray_Init(interp);
4216 Sqlitetestvfs_Init(interp);
4217 Sqlitetestrtree_Init(interp);
4218 Sqlitequota_Init(interp);
4219 Sqlitemultiplex_Init(interp);
4220 SqliteSuperlock_Init(interp);
4221 SqlitetestSyscall_Init(interp);
4222 #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
4223 TestSession_Init(interp);
4225 Fts5tcl_Init(interp);
4226 SqliteRbu_Init(interp);
4227 Sqlitetesttcl_Init(interp);
4229 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
4230 Sqlitetestfts3_Init(interp);
4233 Tcl_CreateObjCommand(
4234 interp, "load_testfixture_extensions", init_all_cmd, 0, 0
4236 Tcl_CreateObjCommand(
4237 interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
4239 Tcl_CreateObjCommand(
4240 interp, "db_last_stmt_ptr", db_last_stmt_ptr, 0, 0
4244 Sqlitetestsse_Init(interp);
4250 /* Needed for the setrlimit() system call on unix */
4252 #include <sys/resource.h>
4255 #define TCLSH_MAIN main /* Needed to fake out mktclapp */
4256 int SQLITE_CDECL TCLSH_MAIN(int argc, char **argv){
4259 #if !defined(_WIN32_WCE)
4260 if( getenv("BREAK") ){
4262 "attach debugger to process %d and press any key to continue.\n",
4268 /* Since the primary use case for this binary is testing of SQLite,
4269 ** be sure to generate core files if we crash */
4270 #if defined(SQLITE_TEST) && defined(unix)
4272 getrlimit(RLIMIT_CORE, &x);
4273 x.rlim_cur = x.rlim_max;
4274 setrlimit(RLIMIT_CORE, &x);
4276 #endif /* SQLITE_TEST && unix */
4279 /* Call sqlite3_shutdown() once before doing anything else. This is to
4280 ** test that sqlite3_shutdown() can be safely called by a process before
4281 ** sqlite3_initialize() is. */
4284 Tcl_FindExecutable(argv[0]);
4285 Tcl_SetSystemEncoding(NULL, "utf-8");
4286 interp = Tcl_CreateInterp();
4289 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
4296 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
4297 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
4298 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
4299 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
4300 for(i=3-TCLSH; i<argc; i++){
4301 Tcl_SetVar(interp, "argv", argv[i],
4302 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
4304 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
4305 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
4306 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
4307 fprintf(stderr,"%s: %s\n", *argv, zInfo);
4311 if( TCLSH==2 || argc<=1 ){
4312 Tcl_GlobalEval(interp, tclsh_main_loop());