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 Add a "main()" routine that works as a tclsh.
24 ** -DTCLSH_INIT_PROC=name
26 ** Invoke name(interp) to initialize the Tcl interpreter.
27 ** If name(interp) returns a non-NULL string, then run
28 ** that string as a Tcl script to launch the application.
29 ** If name(interp) returns NULL, then run the regular
30 ** tclsh-emulator code.
32 #ifdef TCLSH_INIT_PROC
37 ** If requested, include the SQLite compiler options file for MSVC.
39 #if defined(INCLUDE_MSVC_H)
43 #if defined(INCLUDE_SQLITE_TCL_H)
44 # include "sqlite_tcl.h"
47 # ifndef SQLITE_TCLAPI
48 # define SQLITE_TCLAPI
54 ** Some additional include files are needed if this file is not
55 ** appended to the amalgamation.
57 #ifndef SQLITE_AMALGAMATION
62 typedef unsigned char u8;
66 /* Used to get the current process ID */
70 # define GETPID getpid
71 #elif !defined(_WIN32_WCE)
72 # ifndef SQLITE_AMALGAMATION
73 # ifndef WIN32_LEAN_AND_MEAN
74 # define WIN32_LEAN_AND_MEAN
79 # define isatty(h) _isatty(h)
80 # define GETPID (int)GetCurrentProcessId
84 * Windows needs to know which symbols to export. Unix does not.
85 * BUILD_sqlite should be undefined for Unix.
88 #undef TCL_STORAGE_CLASS
89 #define TCL_STORAGE_CLASS DLLEXPORT
90 #endif /* BUILD_sqlite */
92 #define NUM_PREPARED_STMTS 10
93 #define MAX_PREPARED_STMTS 100
95 /* Forward declaration */
96 typedef struct SqliteDb SqliteDb;
99 ** New SQL functions can be created as TCL scripts. Each such function
100 ** is described by an instance of the following structure.
102 ** Variable eType may be set to SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT,
103 ** SQLITE_BLOB or SQLITE_NULL. If it is SQLITE_NULL, then the implementation
104 ** attempts to determine the type of the result based on the Tcl object.
105 ** If it is SQLITE_TEXT or SQLITE_BLOB, then a text (sqlite3_result_text())
106 ** or blob (sqlite3_result_blob()) is returned. If it is SQLITE_INTEGER
107 ** or SQLITE_FLOAT, then an attempt is made to return an integer or float
108 ** value, falling back to float and then text if this is not possible.
110 typedef struct SqlFunc SqlFunc;
112 Tcl_Interp *interp; /* The TCL interpret to execute the function */
113 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
114 SqliteDb *pDb; /* Database connection that owns this function */
115 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
116 int eType; /* Type of value to return */
117 char *zName; /* Name of this function */
118 SqlFunc *pNext; /* Next function on the list of them all */
122 ** New collation sequences function can be created as TCL scripts. Each such
123 ** function is described by an instance of the following structure.
125 typedef struct SqlCollate SqlCollate;
127 Tcl_Interp *interp; /* The TCL interpret to execute the function */
128 char *zScript; /* The script to be run */
129 SqlCollate *pNext; /* Next function on the list of them all */
133 ** Prepared statements are cached for faster execution. Each prepared
134 ** statement is described by an instance of the following structure.
136 typedef struct SqlPreparedStmt SqlPreparedStmt;
137 struct SqlPreparedStmt {
138 SqlPreparedStmt *pNext; /* Next in linked list */
139 SqlPreparedStmt *pPrev; /* Previous on the list */
140 sqlite3_stmt *pStmt; /* The prepared statement */
141 int nSql; /* chars in zSql[] */
142 const char *zSql; /* Text of the SQL statement */
143 int nParm; /* Size of apParm array */
144 Tcl_Obj **apParm; /* Array of referenced object pointers */
147 typedef struct IncrblobChannel IncrblobChannel;
150 ** There is one instance of this structure for each SQLite database
151 ** that has been opened by the SQLite TCL interface.
153 ** If this module is built with SQLITE_TEST defined (to create the SQLite
154 ** testfixture executable), then it may be configured to use either
155 ** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
156 ** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
159 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
160 Tcl_Interp *interp; /* The interpreter used for this database */
161 char *zBusy; /* The busy callback routine */
162 char *zCommit; /* The commit hook callback routine */
163 char *zTrace; /* The trace callback routine */
164 char *zTraceV2; /* The trace_v2 callback routine */
165 char *zProfile; /* The profile callback routine */
166 char *zProgress; /* The progress callback routine */
167 char *zBindFallback; /* Callback to invoke on a binding miss */
168 char *zAuth; /* The authorization callback routine */
169 int disableAuth; /* Disable the authorizer if it exists */
170 char *zNull; /* Text to substitute for an SQL NULL value */
171 SqlFunc *pFunc; /* List of SQL functions */
172 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
173 Tcl_Obj *pPreUpdateHook; /* Pre-update hook script (if any) */
174 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
175 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
176 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
177 SqlCollate *pCollate; /* List of SQL collation functions */
178 int rc; /* Return code of most recent sqlite3_exec() */
179 Tcl_Obj *pCollateNeeded; /* Collation needed script */
180 SqlPreparedStmt *stmtList; /* List of prepared statements*/
181 SqlPreparedStmt *stmtLast; /* Last statement in the list */
182 int maxStmt; /* The next maximum number of stmtList */
183 int nStmt; /* Number of statements in stmtList */
184 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
185 int nStep, nSort, nIndex; /* Statistics for most recent operation */
186 int nVMStep; /* Another statistic for most recent operation */
187 int nTransaction; /* Number of nested [transaction] methods */
188 int openFlags; /* Flags used to open. (SQLITE_OPEN_URI) */
190 int bLegacyPrepare; /* True to use sqlite3_prepare() */
194 struct IncrblobChannel {
195 sqlite3_blob *pBlob; /* sqlite3 blob handle */
196 SqliteDb *pDb; /* Associated database connection */
197 int iSeek; /* Current seek offset */
198 Tcl_Channel channel; /* Channel identifier */
199 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
200 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
204 ** Compute a string length that is limited to what can be stored in
205 ** lower 30 bits of a 32-bit signed integer.
207 static int strlen30(const char *z){
209 while( *z2 ){ z2++; }
210 return 0x3fffffff & (int)(z2 - z);
214 #ifndef SQLITE_OMIT_INCRBLOB
216 ** Close all incrblob channels opened using database connection pDb.
217 ** This is called when shutting down the database connection.
219 static void closeIncrblobChannels(SqliteDb *pDb){
221 IncrblobChannel *pNext;
223 for(p=pDb->pIncrblob; p; p=pNext){
226 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
227 ** which deletes the IncrblobChannel structure at *p. So do not
228 ** call Tcl_Free() here.
230 Tcl_UnregisterChannel(pDb->interp, p->channel);
235 ** Close an incremental blob channel.
237 static int SQLITE_TCLAPI incrblobClose(
238 ClientData instanceData,
241 IncrblobChannel *p = (IncrblobChannel *)instanceData;
242 int rc = sqlite3_blob_close(p->pBlob);
243 sqlite3 *db = p->pDb->db;
245 /* Remove the channel from the SqliteDb.pIncrblob list. */
247 p->pNext->pPrev = p->pPrev;
250 p->pPrev->pNext = p->pNext;
252 if( p->pDb->pIncrblob==p ){
253 p->pDb->pIncrblob = p->pNext;
256 /* Free the IncrblobChannel structure */
260 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
267 ** Read data from an incremental blob channel.
269 static int SQLITE_TCLAPI incrblobInput(
270 ClientData instanceData,
275 IncrblobChannel *p = (IncrblobChannel *)instanceData;
276 int nRead = bufSize; /* Number of bytes to read */
277 int nBlob; /* Total size of the blob */
278 int rc; /* sqlite error code */
280 nBlob = sqlite3_blob_bytes(p->pBlob);
281 if( (p->iSeek+nRead)>nBlob ){
282 nRead = nBlob-p->iSeek;
288 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
299 ** Write data to an incremental blob channel.
301 static int SQLITE_TCLAPI incrblobOutput(
302 ClientData instanceData,
307 IncrblobChannel *p = (IncrblobChannel *)instanceData;
308 int nWrite = toWrite; /* Number of bytes to write */
309 int nBlob; /* Total size of the blob */
310 int rc; /* sqlite error code */
312 nBlob = sqlite3_blob_bytes(p->pBlob);
313 if( (p->iSeek+nWrite)>nBlob ){
314 *errorCodePtr = EINVAL;
321 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
332 ** Seek an incremental blob channel.
334 static int SQLITE_TCLAPI incrblobSeek(
335 ClientData instanceData,
340 IncrblobChannel *p = (IncrblobChannel *)instanceData;
350 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
353 default: assert(!"Bad seekMode");
360 static void SQLITE_TCLAPI incrblobWatch(
361 ClientData instanceData,
366 static int SQLITE_TCLAPI incrblobHandle(
367 ClientData instanceData,
374 static Tcl_ChannelType IncrblobChannelType = {
375 "incrblob", /* typeName */
376 TCL_CHANNEL_VERSION_2, /* version */
377 incrblobClose, /* closeProc */
378 incrblobInput, /* inputProc */
379 incrblobOutput, /* outputProc */
380 incrblobSeek, /* seekProc */
381 0, /* setOptionProc */
382 0, /* getOptionProc */
383 incrblobWatch, /* watchProc (this is a no-op) */
384 incrblobHandle, /* getHandleProc (always returns error) */
386 0, /* blockModeProc */
389 0, /* wideSeekProc */
393 ** Create a new incrblob channel.
395 static int createIncrblobChannel(
405 sqlite3 *db = pDb->db;
408 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
410 /* This variable is used to name the channels: "incrblob_[incr count]" */
411 static int count = 0;
414 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
416 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
420 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
424 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
425 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
426 Tcl_RegisterChannel(interp, p->channel);
428 /* Link the new channel into the SqliteDb.pIncrblob list. */
429 p->pNext = pDb->pIncrblob;
437 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
440 #else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
441 #define closeIncrblobChannels(pDb)
445 ** Look at the script prefix in pCmd. We will be executing this script
446 ** after first appending one or more arguments. This routine analyzes
447 ** the script to see if it is safe to use Tcl_EvalObjv() on the script
448 ** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
451 ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
452 ** command name followed by zero or more arguments with no [...] or $
453 ** or {...} or ; to be seen anywhere. Most callback scripts consist
454 ** of just a single procedure name and they meet this requirement.
456 static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
457 /* We could try to do something with Tcl_Parse(). But we will instead
458 ** just do a search for forbidden characters. If any of the forbidden
459 ** characters appear in pCmd, we will report the string as unsafe.
463 z = Tcl_GetStringFromObj(pCmd, &n);
466 if( c=='$' || c=='[' || c==';' ) return 0;
472 ** Find an SqlFunc structure with the given name. Or create a new
473 ** one if an existing one cannot be found. Return a pointer to the
476 static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
478 int nName = strlen30(zName);
479 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
480 pNew->zName = (char*)&pNew[1];
481 memcpy(pNew->zName, zName, nName+1);
482 for(p=pDb->pFunc; p; p=p->pNext){
483 if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
484 Tcl_Free((char*)pNew);
488 pNew->interp = pDb->interp;
491 pNew->pNext = pDb->pFunc;
497 ** Free a single SqlPreparedStmt object.
499 static void dbFreeStmt(SqlPreparedStmt *pStmt){
501 if( sqlite3_sql(pStmt->pStmt)==0 ){
502 Tcl_Free((char *)pStmt->zSql);
505 sqlite3_finalize(pStmt->pStmt);
506 Tcl_Free((char *)pStmt);
510 ** Finalize and free a list of prepared statements
512 static void flushStmtCache(SqliteDb *pDb){
513 SqlPreparedStmt *pPreStmt;
514 SqlPreparedStmt *pNext;
516 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
517 pNext = pPreStmt->pNext;
518 dbFreeStmt(pPreStmt);
526 ** TCL calls this procedure when an sqlite3 database command is
529 static void SQLITE_TCLAPI DbDeleteCmd(void *db){
530 SqliteDb *pDb = (SqliteDb*)db;
532 closeIncrblobChannels(pDb);
533 sqlite3_close(pDb->db);
535 SqlFunc *pFunc = pDb->pFunc;
536 pDb->pFunc = pFunc->pNext;
537 assert( pFunc->pDb==pDb );
538 Tcl_DecrRefCount(pFunc->pScript);
539 Tcl_Free((char*)pFunc);
541 while( pDb->pCollate ){
542 SqlCollate *pCollate = pDb->pCollate;
543 pDb->pCollate = pCollate->pNext;
544 Tcl_Free((char*)pCollate);
547 Tcl_Free(pDb->zBusy);
550 Tcl_Free(pDb->zTrace);
553 Tcl_Free(pDb->zTraceV2);
556 Tcl_Free(pDb->zProfile);
558 if( pDb->zBindFallback ){
559 Tcl_Free(pDb->zBindFallback);
562 Tcl_Free(pDb->zAuth);
565 Tcl_Free(pDb->zNull);
567 if( pDb->pUpdateHook ){
568 Tcl_DecrRefCount(pDb->pUpdateHook);
570 if( pDb->pPreUpdateHook ){
571 Tcl_DecrRefCount(pDb->pPreUpdateHook);
573 if( pDb->pRollbackHook ){
574 Tcl_DecrRefCount(pDb->pRollbackHook);
577 Tcl_DecrRefCount(pDb->pWalHook);
579 if( pDb->pCollateNeeded ){
580 Tcl_DecrRefCount(pDb->pCollateNeeded);
582 Tcl_Free((char*)pDb);
586 ** This routine is called when a database file is locked while trying
589 static int DbBusyHandler(void *cd, int nTries){
590 SqliteDb *pDb = (SqliteDb*)cd;
594 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
595 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
596 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
602 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
604 ** This routine is invoked as the 'progress callback' for the database.
606 static int DbProgressHandler(void *cd){
607 SqliteDb *pDb = (SqliteDb*)cd;
610 assert( pDb->zProgress );
611 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
612 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
619 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
620 !defined(SQLITE_OMIT_DEPRECATED)
622 ** This routine is called by the SQLite trace handler whenever a new
623 ** block of SQL is executed. The TCL script in pDb->zTrace is executed.
625 static void DbTraceHandler(void *cd, const char *zSql){
626 SqliteDb *pDb = (SqliteDb*)cd;
629 Tcl_DStringInit(&str);
630 Tcl_DStringAppend(&str, pDb->zTrace, -1);
631 Tcl_DStringAppendElement(&str, zSql);
632 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
633 Tcl_DStringFree(&str);
634 Tcl_ResetResult(pDb->interp);
638 #ifndef SQLITE_OMIT_TRACE
640 ** This routine is called by the SQLite trace_v2 handler whenever a new
641 ** supported event is generated. Unsupported event types are ignored.
642 ** The TCL script in pDb->zTraceV2 is executed, with the arguments for
643 ** the event appended to it (as list elements).
645 static int DbTraceV2Handler(
646 unsigned type, /* One of the SQLITE_TRACE_* event types. */
647 void *cd, /* The original context data pointer. */
648 void *pd, /* Primary event data, depends on event type. */
649 void *xd /* Extra event data, depends on event type. */
651 SqliteDb *pDb = (SqliteDb*)cd;
655 case SQLITE_TRACE_STMT: {
656 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
657 char *zSql = (char *)xd;
659 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
660 Tcl_IncrRefCount(pCmd);
661 Tcl_ListObjAppendElement(pDb->interp, pCmd,
662 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
663 Tcl_ListObjAppendElement(pDb->interp, pCmd,
664 Tcl_NewStringObj(zSql, -1));
665 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
666 Tcl_DecrRefCount(pCmd);
667 Tcl_ResetResult(pDb->interp);
670 case SQLITE_TRACE_PROFILE: {
671 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
672 sqlite3_int64 ns = *(sqlite3_int64*)xd;
674 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
675 Tcl_IncrRefCount(pCmd);
676 Tcl_ListObjAppendElement(pDb->interp, pCmd,
677 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
678 Tcl_ListObjAppendElement(pDb->interp, pCmd,
679 Tcl_NewWideIntObj((Tcl_WideInt)ns));
680 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
681 Tcl_DecrRefCount(pCmd);
682 Tcl_ResetResult(pDb->interp);
685 case SQLITE_TRACE_ROW: {
686 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
688 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
689 Tcl_IncrRefCount(pCmd);
690 Tcl_ListObjAppendElement(pDb->interp, pCmd,
691 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
692 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
693 Tcl_DecrRefCount(pCmd);
694 Tcl_ResetResult(pDb->interp);
697 case SQLITE_TRACE_CLOSE: {
698 sqlite3 *db = (sqlite3 *)pd;
700 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
701 Tcl_IncrRefCount(pCmd);
702 Tcl_ListObjAppendElement(pDb->interp, pCmd,
703 Tcl_NewWideIntObj((Tcl_WideInt)db));
704 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
705 Tcl_DecrRefCount(pCmd);
706 Tcl_ResetResult(pDb->interp);
714 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
715 !defined(SQLITE_OMIT_DEPRECATED)
717 ** This routine is called by the SQLite profile handler after a statement
718 ** SQL has executed. The TCL script in pDb->zProfile is evaluated.
720 static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
721 SqliteDb *pDb = (SqliteDb*)cd;
725 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
726 Tcl_DStringInit(&str);
727 Tcl_DStringAppend(&str, pDb->zProfile, -1);
728 Tcl_DStringAppendElement(&str, zSql);
729 Tcl_DStringAppendElement(&str, zTm);
730 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
731 Tcl_DStringFree(&str);
732 Tcl_ResetResult(pDb->interp);
737 ** This routine is called when a transaction is committed. The
738 ** TCL script in pDb->zCommit is executed. If it returns non-zero or
739 ** if it throws an exception, the transaction is rolled back instead
740 ** of being committed.
742 static int DbCommitHandler(void *cd){
743 SqliteDb *pDb = (SqliteDb*)cd;
746 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
747 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
753 static void DbRollbackHandler(void *clientData){
754 SqliteDb *pDb = (SqliteDb*)clientData;
755 assert(pDb->pRollbackHook);
756 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
757 Tcl_BackgroundError(pDb->interp);
762 ** This procedure handles wal_hook callbacks.
764 static int DbWalHandler(
772 SqliteDb *pDb = (SqliteDb*)clientData;
773 Tcl_Interp *interp = pDb->interp;
774 assert(pDb->pWalHook);
776 assert( db==pDb->db );
777 p = Tcl_DuplicateObj(pDb->pWalHook);
779 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
780 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
781 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
782 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
784 Tcl_BackgroundError(interp);
791 #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
792 static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
794 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
795 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
796 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
797 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
800 # define setTestUnlockNotifyVars(x,y,z)
803 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
804 static void DbUnlockNotify(void **apArg, int nArg){
806 for(i=0; i<nArg; i++){
807 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
808 SqliteDb *pDb = (SqliteDb *)apArg[i];
809 setTestUnlockNotifyVars(pDb->interp, i, nArg);
810 assert( pDb->pUnlockNotify);
811 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
812 Tcl_DecrRefCount(pDb->pUnlockNotify);
813 pDb->pUnlockNotify = 0;
818 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
820 ** Pre-update hook callback.
822 static void DbPreUpdateHandler(
831 SqliteDb *pDb = (SqliteDb *)p;
833 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
835 assert( (SQLITE_DELETE-1)/9 == 0 );
836 assert( (SQLITE_INSERT-1)/9 == 1 );
837 assert( (SQLITE_UPDATE-1)/9 == 2 );
838 assert( pDb->pPreUpdateHook );
839 assert( db==pDb->db );
840 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
842 pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
843 Tcl_IncrRefCount(pCmd);
844 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
845 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
846 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
847 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
848 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
849 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
850 Tcl_DecrRefCount(pCmd);
852 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
854 static void DbUpdateHandler(
861 SqliteDb *pDb = (SqliteDb *)p;
863 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
865 assert( (SQLITE_DELETE-1)/9 == 0 );
866 assert( (SQLITE_INSERT-1)/9 == 1 );
867 assert( (SQLITE_UPDATE-1)/9 == 2 );
869 assert( pDb->pUpdateHook );
870 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
872 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
873 Tcl_IncrRefCount(pCmd);
874 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
875 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
876 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
877 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
878 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
879 Tcl_DecrRefCount(pCmd);
882 static void tclCollateNeeded(
888 SqliteDb *pDb = (SqliteDb *)pCtx;
889 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
890 Tcl_IncrRefCount(pScript);
891 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
892 Tcl_EvalObjEx(pDb->interp, pScript, 0);
893 Tcl_DecrRefCount(pScript);
897 ** This routine is called to evaluate an SQL collation function implemented
900 static int tclSqlCollate(
907 SqlCollate *p = (SqlCollate *)pCtx;
910 pCmd = Tcl_NewStringObj(p->zScript, -1);
911 Tcl_IncrRefCount(pCmd);
912 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
913 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
914 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
915 Tcl_DecrRefCount(pCmd);
916 return (atoi(Tcl_GetStringResult(p->interp)));
920 ** This routine is called to evaluate an SQL function implemented
923 static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
924 SqlFunc *p = sqlite3_user_data(context);
930 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
931 ** script object directly. This allows the TCL compiler to generate
932 ** bytecode for the command on the first invocation and thus make
933 ** subsequent invocations much faster. */
935 Tcl_IncrRefCount(pCmd);
936 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
937 Tcl_DecrRefCount(pCmd);
939 /* If there are arguments to the function, make a shallow copy of the
940 ** script object, lappend the arguments, then evaluate the copy.
942 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
943 ** The new Tcl_Obj contains pointers to the original list elements.
944 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
945 ** of the list to tclCmdNameType, that alternate representation will
946 ** be preserved and reused on the next invocation.
950 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
951 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
954 pCmd = Tcl_NewListObj(nArg, aArg);
955 Tcl_IncrRefCount(pCmd);
956 for(i=0; i<argc; i++){
957 sqlite3_value *pIn = argv[i];
960 /* Set pVal to contain the i'th column of this row. */
961 switch( sqlite3_value_type(pIn) ){
963 int bytes = sqlite3_value_bytes(pIn);
964 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
967 case SQLITE_INTEGER: {
968 sqlite_int64 v = sqlite3_value_int64(pIn);
969 if( v>=-2147483647 && v<=2147483647 ){
970 pVal = Tcl_NewIntObj((int)v);
972 pVal = Tcl_NewWideIntObj(v);
977 double r = sqlite3_value_double(pIn);
978 pVal = Tcl_NewDoubleObj(r);
982 pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
986 int bytes = sqlite3_value_bytes(pIn);
987 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
991 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
993 Tcl_DecrRefCount(pCmd);
994 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
998 if( !p->useEvalObjv ){
999 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
1000 ** is a list without a string representation. To prevent this from
1001 ** happening, make sure pCmd has a valid string representation */
1002 Tcl_GetString(pCmd);
1004 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
1005 Tcl_DecrRefCount(pCmd);
1008 if( rc && rc!=TCL_RETURN ){
1009 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
1011 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
1014 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1016 int eType = p->eType;
1018 if( eType==SQLITE_NULL ){
1019 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
1020 /* Only return a BLOB type if the Tcl variable is a bytearray and
1021 ** has no string representation. */
1022 eType = SQLITE_BLOB;
1023 }else if( (c=='b' && strcmp(zType,"boolean")==0)
1024 || (c=='w' && strcmp(zType,"wideInt")==0)
1025 || (c=='i' && strcmp(zType,"int")==0)
1027 eType = SQLITE_INTEGER;
1028 }else if( c=='d' && strcmp(zType,"double")==0 ){
1029 eType = SQLITE_FLOAT;
1031 eType = SQLITE_TEXT;
1037 data = Tcl_GetByteArrayFromObj(pVar, &n);
1038 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
1041 case SQLITE_INTEGER: {
1043 if( TCL_OK==Tcl_GetWideIntFromObj(0, pVar, &v) ){
1044 sqlite3_result_int64(context, v);
1049 case SQLITE_FLOAT: {
1051 if( TCL_OK==Tcl_GetDoubleFromObj(0, pVar, &r) ){
1052 sqlite3_result_double(context, r);
1058 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1059 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
1067 #ifndef SQLITE_OMIT_AUTHORIZATION
1069 ** This is the authentication function. It appends the authentication
1070 ** type code and the two arguments to zCmd[] then invokes the result
1071 ** on the interpreter. The reply is examined to determine if the
1072 ** authentication fails or succeeds.
1074 static int auth_callback(
1081 #ifdef SQLITE_USER_AUTHENTICATION
1089 /* EVIDENCE-OF: R-38590-62769 The first parameter to the authorizer
1090 ** callback is a copy of the third parameter to the
1091 ** sqlite3_set_authorizer() interface.
1093 SqliteDb *pDb = (SqliteDb*)pArg;
1094 if( pDb->disableAuth ) return SQLITE_OK;
1096 /* EVIDENCE-OF: R-56518-44310 The second parameter to the callback is an
1097 ** integer action code that specifies the particular action to be
1100 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
1101 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
1102 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
1103 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
1104 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
1105 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
1106 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
1107 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
1108 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
1109 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
1110 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
1111 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
1112 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
1113 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
1114 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
1115 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
1116 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
1117 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
1118 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
1119 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
1120 case SQLITE_READ : zCode="SQLITE_READ"; break;
1121 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
1122 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
1123 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
1124 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
1125 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
1126 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
1127 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
1128 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
1129 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
1130 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
1131 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
1132 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
1133 case SQLITE_RECURSIVE : zCode="SQLITE_RECURSIVE"; break;
1134 default : zCode="????"; break;
1136 Tcl_DStringInit(&str);
1137 Tcl_DStringAppend(&str, pDb->zAuth, -1);
1138 Tcl_DStringAppendElement(&str, zCode);
1139 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
1140 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
1141 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
1142 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
1143 #ifdef SQLITE_USER_AUTHENTICATION
1144 Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
1146 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
1147 Tcl_DStringFree(&str);
1148 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
1149 if( strcmp(zReply,"SQLITE_OK")==0 ){
1151 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
1153 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
1160 #endif /* SQLITE_OMIT_AUTHORIZATION */
1163 ** This routine reads a line of text from FILE in, stores
1164 ** the text in memory obtained from malloc() and returns a pointer
1165 ** to the text. NULL is returned at end of file, or if malloc()
1168 ** The interface is like "readline" but no command-line editing
1171 ** copied from shell.c from '.import' command
1173 static char *local_getline(char *zPrompt, FILE *in){
1179 zLine = malloc( nLine );
1180 if( zLine==0 ) return 0;
1184 nLine = nLine*2 + 100;
1185 zLine = realloc(zLine, nLine);
1186 if( zLine==0 ) return 0;
1188 if( fgets(&zLine[n], nLine - n, in)==0 ){
1196 while( zLine[n] ){ n++; }
1197 if( n>0 && zLine[n-1]=='\n' ){
1203 zLine = realloc( zLine, n+1 );
1209 ** This function is part of the implementation of the command:
1211 ** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1213 ** It is invoked after evaluating the script SCRIPT to commit or rollback
1214 ** the transaction or savepoint opened by the [transaction] command.
1216 static int SQLITE_TCLAPI DbTransPostCmd(
1217 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1218 Tcl_Interp *interp, /* Tcl interpreter */
1219 int result /* Result of evaluating SCRIPT */
1221 static const char *const azEnd[] = {
1222 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1223 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1224 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1225 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1227 SqliteDb *pDb = (SqliteDb*)data[0];
1231 pDb->nTransaction--;
1232 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1235 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1236 /* This is a tricky scenario to handle. The most likely cause of an
1237 ** error is that the exec() above was an attempt to commit the
1238 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1239 ** that an IO-error has occurred. In either case, throw a Tcl exception
1240 ** and try to rollback the transaction.
1242 ** But it could also be that the user executed one or more BEGIN,
1243 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1244 ** this method's logic. Not clear how this would be best handled.
1246 if( rc!=TCL_ERROR ){
1247 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
1250 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1258 ** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1259 ** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1260 ** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1261 ** on whether or not the [db_use_legacy_prepare] command has been used to
1262 ** configure the connection.
1264 static int dbPrepare(
1265 SqliteDb *pDb, /* Database object */
1266 const char *zSql, /* SQL to compile */
1267 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1268 const char **pzOut /* OUT: Pointer to next SQL statement */
1270 unsigned int prepFlags = 0;
1272 if( pDb->bLegacyPrepare ){
1273 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1276 /* If the statement cache is large, use the SQLITE_PREPARE_PERSISTENT
1277 ** flags, which uses less lookaside memory. But if the cache is small,
1278 ** omit that flag to make full use of lookaside */
1279 if( pDb->maxStmt>5 ) prepFlags = SQLITE_PREPARE_PERSISTENT;
1281 return sqlite3_prepare_v3(pDb->db, zSql, -1, prepFlags, ppStmt, pzOut);
1285 ** Search the cache for a prepared-statement object that implements the
1286 ** first SQL statement in the buffer pointed to by parameter zIn. If
1287 ** no such prepared-statement can be found, allocate and prepare a new
1288 ** one. In either case, bind the current values of the relevant Tcl
1289 ** variables to any $var, :var or @var variables in the statement. Before
1290 ** returning, set *ppPreStmt to point to the prepared-statement object.
1292 ** Output parameter *pzOut is set to point to the next SQL statement in
1293 ** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1296 ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1297 ** and an error message loaded into interpreter pDb->interp.
1299 static int dbPrepareAndBind(
1300 SqliteDb *pDb, /* Database object */
1301 char const *zIn, /* SQL to compile */
1302 char const **pzOut, /* OUT: Pointer to next SQL statement */
1303 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1305 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
1306 sqlite3_stmt *pStmt = 0; /* Prepared statement object */
1307 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1308 int nSql; /* Length of zSql in bytes */
1309 int nVar = 0; /* Number of variables in statement */
1310 int iParm = 0; /* Next free entry in apParm */
1313 int needResultReset = 0; /* Need to invoke Tcl_ResetResult() */
1314 int rc = SQLITE_OK; /* Value to return */
1315 Tcl_Interp *interp = pDb->interp;
1319 /* Trim spaces from the start of zSql and calculate the remaining length. */
1320 while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
1321 nSql = strlen30(zSql);
1323 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1324 int n = pPreStmt->nSql;
1326 && memcmp(pPreStmt->zSql, zSql, n)==0
1327 && (zSql[n]==0 || zSql[n-1]==';')
1329 pStmt = pPreStmt->pStmt;
1330 *pzOut = &zSql[pPreStmt->nSql];
1332 /* When a prepared statement is found, unlink it from the
1333 ** cache list. It will later be added back to the beginning
1334 ** of the cache list in order to implement LRU replacement.
1336 if( pPreStmt->pPrev ){
1337 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1339 pDb->stmtList = pPreStmt->pNext;
1341 if( pPreStmt->pNext ){
1342 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1344 pDb->stmtLast = pPreStmt->pPrev;
1347 nVar = sqlite3_bind_parameter_count(pStmt);
1352 /* If no prepared statement was found. Compile the SQL text. Also allocate
1353 ** a new SqlPreparedStmt structure. */
1357 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
1358 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1362 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1363 /* A compile-time error in the statement. */
1364 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1367 /* The statement was a no-op. Continue to the next statement
1368 ** in the SQL string.
1374 assert( pPreStmt==0 );
1375 nVar = sqlite3_bind_parameter_count(pStmt);
1376 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1377 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1378 memset(pPreStmt, 0, nByte);
1380 pPreStmt->pStmt = pStmt;
1381 pPreStmt->nSql = (int)(*pzOut - zSql);
1382 pPreStmt->zSql = sqlite3_sql(pStmt);
1383 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
1385 if( pPreStmt->zSql==0 ){
1386 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1387 memcpy(zCopy, zSql, pPreStmt->nSql);
1388 zCopy[pPreStmt->nSql] = '\0';
1389 pPreStmt->zSql = zCopy;
1394 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1395 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1397 /* Bind values to parameters that begin with $ or : */
1398 for(i=1; i<=nVar; i++){
1399 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1400 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1401 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1402 if( pVar==0 && pDb->zBindFallback!=0 ){
1405 pCmd = Tcl_NewStringObj(pDb->zBindFallback, -1);
1406 Tcl_IncrRefCount(pCmd);
1407 Tcl_ListObjAppendElement(interp, pCmd, Tcl_NewStringObj(zVar,-1));
1408 if( needResultReset ) Tcl_ResetResult(interp);
1409 needResultReset = 1;
1410 rx = Tcl_EvalObjEx(interp, pCmd, TCL_EVAL_DIRECT);
1411 Tcl_DecrRefCount(pCmd);
1413 pVar = Tcl_GetObjResult(interp);
1414 }else if( rx==TCL_ERROR ){
1424 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1427 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1428 /* Load a BLOB type if the Tcl variable is a bytearray and
1429 ** it has no string representation or the host
1430 ** parameter name begins with "@". */
1431 data = Tcl_GetByteArrayFromObj(pVar, &n);
1432 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1433 Tcl_IncrRefCount(pVar);
1434 pPreStmt->apParm[iParm++] = pVar;
1435 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1436 Tcl_GetIntFromObj(interp, pVar, &n);
1437 sqlite3_bind_int(pStmt, i, n);
1438 }else if( c=='d' && strcmp(zType,"double")==0 ){
1440 Tcl_GetDoubleFromObj(interp, pVar, &r);
1441 sqlite3_bind_double(pStmt, i, r);
1442 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1443 (c=='i' && strcmp(zType,"int")==0) ){
1445 Tcl_GetWideIntFromObj(interp, pVar, &v);
1446 sqlite3_bind_int64(pStmt, i, v);
1448 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1449 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1450 Tcl_IncrRefCount(pVar);
1451 pPreStmt->apParm[iParm++] = pVar;
1454 sqlite3_bind_null(pStmt, i);
1456 if( needResultReset ) Tcl_ResetResult(pDb->interp);
1459 pPreStmt->nParm = iParm;
1460 *ppPreStmt = pPreStmt;
1461 if( needResultReset && rc==TCL_OK ) Tcl_ResetResult(pDb->interp);
1467 ** Release a statement reference obtained by calling dbPrepareAndBind().
1468 ** There should be exactly one call to this function for each call to
1469 ** dbPrepareAndBind().
1471 ** If the discard parameter is non-zero, then the statement is deleted
1472 ** immediately. Otherwise it is added to the LRU list and may be returned
1473 ** by a subsequent call to dbPrepareAndBind().
1475 static void dbReleaseStmt(
1476 SqliteDb *pDb, /* Database handle */
1477 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1478 int discard /* True to delete (not cache) the pPreStmt */
1482 /* Free the bound string and blob parameters */
1483 for(i=0; i<pPreStmt->nParm; i++){
1484 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1486 pPreStmt->nParm = 0;
1488 if( pDb->maxStmt<=0 || discard ){
1489 /* If the cache is turned off, deallocated the statement */
1490 dbFreeStmt(pPreStmt);
1492 /* Add the prepared statement to the beginning of the cache list. */
1493 pPreStmt->pNext = pDb->stmtList;
1494 pPreStmt->pPrev = 0;
1495 if( pDb->stmtList ){
1496 pDb->stmtList->pPrev = pPreStmt;
1498 pDb->stmtList = pPreStmt;
1499 if( pDb->stmtLast==0 ){
1500 assert( pDb->nStmt==0 );
1501 pDb->stmtLast = pPreStmt;
1503 assert( pDb->nStmt>0 );
1507 /* If we have too many statement in cache, remove the surplus from
1508 ** the end of the cache list. */
1509 while( pDb->nStmt>pDb->maxStmt ){
1510 SqlPreparedStmt *pLast = pDb->stmtLast;
1511 pDb->stmtLast = pLast->pPrev;
1512 pDb->stmtLast->pNext = 0;
1520 ** Structure used with dbEvalXXX() functions:
1526 ** dbEvalColumnValue()
1528 typedef struct DbEvalContext DbEvalContext;
1529 struct DbEvalContext {
1530 SqliteDb *pDb; /* Database handle */
1531 Tcl_Obj *pSql; /* Object holding string zSql */
1532 const char *zSql; /* Remaining SQL to execute */
1533 SqlPreparedStmt *pPreStmt; /* Current statement */
1534 int nCol; /* Number of columns returned by pStmt */
1535 int evalFlags; /* Flags used */
1536 Tcl_Obj *pArray; /* Name of array variable */
1537 Tcl_Obj **apColName; /* Array of column names */
1540 #define SQLITE_EVAL_WITHOUTNULLS 0x00001 /* Unset array(*) for NULL */
1543 ** Release any cache of column names currently held as part of
1544 ** the DbEvalContext structure passed as the first argument.
1546 static void dbReleaseColumnNames(DbEvalContext *p){
1549 for(i=0; i<p->nCol; i++){
1550 Tcl_DecrRefCount(p->apColName[i]);
1552 Tcl_Free((char *)p->apColName);
1559 ** Initialize a DbEvalContext structure.
1561 ** If pArray is not NULL, then it contains the name of a Tcl array
1562 ** variable. The "*" member of this array is set to a list containing
1563 ** the names of the columns returned by the statement as part of each
1564 ** call to dbEvalStep(), in order from left to right. e.g. if the names
1565 ** of the returned columns are a, b and c, it does the equivalent of the
1568 ** set ${pArray}(*) {a b c}
1570 static void dbEvalInit(
1571 DbEvalContext *p, /* Pointer to structure to initialize */
1572 SqliteDb *pDb, /* Database handle */
1573 Tcl_Obj *pSql, /* Object containing SQL script */
1574 Tcl_Obj *pArray, /* Name of Tcl array to set (*) element of */
1575 int evalFlags /* Flags controlling evaluation */
1577 memset(p, 0, sizeof(DbEvalContext));
1579 p->zSql = Tcl_GetString(pSql);
1581 Tcl_IncrRefCount(pSql);
1584 Tcl_IncrRefCount(pArray);
1586 p->evalFlags = evalFlags;
1590 ** Obtain information about the row that the DbEvalContext passed as the
1591 ** first argument currently points to.
1593 static void dbEvalRowInfo(
1594 DbEvalContext *p, /* Evaluation context */
1595 int *pnCol, /* OUT: Number of column names */
1596 Tcl_Obj ***papColName /* OUT: Array of column names */
1598 /* Compute column names */
1599 if( 0==p->apColName ){
1600 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1601 int i; /* Iterator variable */
1602 int nCol; /* Number of columns returned by pStmt */
1603 Tcl_Obj **apColName = 0; /* Array of column names */
1605 p->nCol = nCol = sqlite3_column_count(pStmt);
1606 if( nCol>0 && (papColName || p->pArray) ){
1607 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1608 for(i=0; i<nCol; i++){
1609 apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
1610 Tcl_IncrRefCount(apColName[i]);
1612 p->apColName = apColName;
1615 /* If results are being stored in an array variable, then create
1616 ** the array(*) entry for that array
1619 Tcl_Interp *interp = p->pDb->interp;
1620 Tcl_Obj *pColList = Tcl_NewObj();
1621 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
1623 for(i=0; i<nCol; i++){
1624 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1626 Tcl_IncrRefCount(pStar);
1627 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
1628 Tcl_DecrRefCount(pStar);
1633 *papColName = p->apColName;
1641 ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1642 ** returned, then an error message is stored in the interpreter before
1645 ** A return value of TCL_OK means there is a row of data available. The
1646 ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1647 ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1648 ** is returned, then the SQL script has finished executing and there are
1649 ** no further rows available. This is similar to SQLITE_DONE.
1651 static int dbEvalStep(DbEvalContext *p){
1652 const char *zPrevSql = 0; /* Previous value of p->zSql */
1654 while( p->zSql[0] || p->pPreStmt ){
1656 if( p->pPreStmt==0 ){
1657 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
1658 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1659 if( rc!=TCL_OK ) return rc;
1662 SqliteDb *pDb = p->pDb;
1663 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1664 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1666 rcs = sqlite3_step(pStmt);
1667 if( rcs==SQLITE_ROW ){
1671 dbEvalRowInfo(p, 0, 0);
1673 rcs = sqlite3_reset(pStmt);
1675 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1676 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
1677 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
1678 pDb->nVMStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_VM_STEP,1);
1679 dbReleaseColumnNames(p);
1682 if( rcs!=SQLITE_OK ){
1683 /* If a run-time error occurs, report the error and stop reading
1685 dbReleaseStmt(pDb, pPreStmt, 1);
1687 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1688 /* If the runtime error was an SQLITE_SCHEMA, and the database
1689 ** handle is configured to use the legacy sqlite3_prepare()
1690 ** interface, retry prepare()/step() on the same SQL statement.
1691 ** This only happens once. If there is a second SQLITE_SCHEMA
1692 ** error, the error will be returned to the caller. */
1697 Tcl_SetObjResult(pDb->interp,
1698 Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1701 dbReleaseStmt(pDb, pPreStmt, 0);
1711 ** Free all resources currently held by the DbEvalContext structure passed
1712 ** as the first argument. There should be exactly one call to this function
1713 ** for each call to dbEvalInit().
1715 static void dbEvalFinalize(DbEvalContext *p){
1717 sqlite3_reset(p->pPreStmt->pStmt);
1718 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1722 Tcl_DecrRefCount(p->pArray);
1725 Tcl_DecrRefCount(p->pSql);
1726 dbReleaseColumnNames(p);
1730 ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1731 ** the value for the iCol'th column of the row currently pointed to by
1732 ** the DbEvalContext structure passed as the first argument.
1734 static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1735 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1736 switch( sqlite3_column_type(pStmt, iCol) ){
1738 int bytes = sqlite3_column_bytes(pStmt, iCol);
1739 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1740 if( !zBlob ) bytes = 0;
1741 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1743 case SQLITE_INTEGER: {
1744 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1745 if( v>=-2147483647 && v<=2147483647 ){
1746 return Tcl_NewIntObj((int)v);
1748 return Tcl_NewWideIntObj(v);
1751 case SQLITE_FLOAT: {
1752 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1755 return Tcl_NewStringObj(p->pDb->zNull, -1);
1759 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
1763 ** If using Tcl version 8.6 or greater, use the NR functions to avoid
1764 ** recursive evalution of scripts by the [db eval] and [db trans]
1765 ** commands. Even if the headers used while compiling the extension
1766 ** are 8.6 or newer, the code still tests the Tcl version at runtime.
1767 ** This allows stubs-enabled builds to be used with older Tcl libraries.
1769 #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
1770 # define SQLITE_TCL_NRE 1
1771 static int DbUseNre(void){
1773 Tcl_GetVersion(&major, &minor, 0, 0);
1774 return( (major==8 && minor>=6) || major>8 );
1778 ** Compiling using headers earlier than 8.6. In this case NR cannot be
1779 ** used, so DbUseNre() to always return zero. Add #defines for the other
1780 ** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1781 ** even though the only invocations of them are within conditional blocks
1784 ** if( DbUseNre() ) { ... }
1786 # define SQLITE_TCL_NRE 0
1787 # define DbUseNre() 0
1788 # define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
1789 # define Tcl_NREvalObj(a,b,c) 0
1790 # define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
1794 ** This function is part of the implementation of the command:
1796 ** $db eval SQL ?ARRAYNAME? SCRIPT
1798 static int SQLITE_TCLAPI DbEvalNextCmd(
1799 ClientData data[], /* data[0] is the (DbEvalContext*) */
1800 Tcl_Interp *interp, /* Tcl interpreter */
1801 int result /* Result so far */
1803 int rc = result; /* Return code */
1805 /* The first element of the data[] array is a pointer to a DbEvalContext
1806 ** structure allocated using Tcl_Alloc(). The second element of data[]
1807 ** is a pointer to a Tcl_Obj containing the script to run for each row
1808 ** returned by the queries encapsulated in data[0]. */
1809 DbEvalContext *p = (DbEvalContext *)data[0];
1810 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1811 Tcl_Obj *pArray = p->pArray;
1813 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1816 Tcl_Obj **apColName;
1817 dbEvalRowInfo(p, &nCol, &apColName);
1818 for(i=0; i<nCol; i++){
1820 Tcl_ObjSetVar2(interp, apColName[i], 0, dbEvalColumnValue(p,i), 0);
1821 }else if( (p->evalFlags & SQLITE_EVAL_WITHOUTNULLS)!=0
1822 && sqlite3_column_type(p->pPreStmt->pStmt, i)==SQLITE_NULL
1824 Tcl_UnsetVar2(interp, Tcl_GetString(pArray),
1825 Tcl_GetString(apColName[i]), 0);
1827 Tcl_ObjSetVar2(interp, pArray, apColName[i], dbEvalColumnValue(p,i), 0);
1831 /* The required interpreter variables are now populated with the data
1832 ** from the current row. If using NRE, schedule callbacks to evaluate
1833 ** script pScript, then to invoke this function again to fetch the next
1834 ** row (or clean up if there is no next row or the script throws an
1835 ** exception). After scheduling the callbacks, return control to the
1838 ** If not using NRE, evaluate pScript directly and continue with the
1839 ** next iteration of this while(...) loop. */
1841 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1842 return Tcl_NREvalObj(interp, pScript, 0);
1844 rc = Tcl_EvalObjEx(interp, pScript, 0);
1848 Tcl_DecrRefCount(pScript);
1850 Tcl_Free((char *)p);
1852 if( rc==TCL_OK || rc==TCL_BREAK ){
1853 Tcl_ResetResult(interp);
1860 ** This function is used by the implementations of the following database
1861 ** handle sub-commands:
1863 ** $db update_hook ?SCRIPT?
1864 ** $db wal_hook ?SCRIPT?
1865 ** $db commit_hook ?SCRIPT?
1866 ** $db preupdate hook ?SCRIPT?
1868 static void DbHookCmd(
1869 Tcl_Interp *interp, /* Tcl interpreter */
1870 SqliteDb *pDb, /* Database handle */
1871 Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */
1872 Tcl_Obj **ppHook /* Pointer to member of SqliteDb */
1874 sqlite3 *db = pDb->db;
1877 Tcl_SetObjResult(interp, *ppHook);
1879 Tcl_DecrRefCount(*ppHook);
1884 assert( !(*ppHook) );
1885 if( Tcl_GetCharLength(pArg)>0 ){
1887 Tcl_IncrRefCount(*ppHook);
1891 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1892 sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
1894 sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1895 sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1896 sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
1900 ** The "sqlite" command below creates a new Tcl command for each
1901 ** connection it opens to an SQLite database. This routine is invoked
1902 ** whenever one of those connection-specific commands is executed
1903 ** in Tcl. For example, if you run Tcl code like this:
1905 ** sqlite3 db1 "my_database"
1908 ** The first command opens a connection to the "my_database" database
1909 ** and calls that connection "db1". The second command causes this
1910 ** subroutine to be invoked.
1912 static int SQLITE_TCLAPI DbObjCmd(
1918 SqliteDb *pDb = (SqliteDb*)cd;
1921 static const char *DB_strs[] = {
1922 "authorizer", "backup", "bind_fallback",
1923 "busy", "cache", "changes",
1924 "close", "collate", "collation_needed",
1925 "commit_hook", "complete", "copy",
1926 "deserialize", "enable_load_extension", "errorcode",
1927 "eval", "exists", "function",
1928 "incrblob", "interrupt", "last_insert_rowid",
1929 "nullvalue", "onecolumn", "preupdate",
1930 "profile", "progress", "rekey",
1931 "restore", "rollback_hook", "serialize",
1932 "status", "timeout", "total_changes",
1933 "trace", "trace_v2", "transaction",
1934 "unlock_notify", "update_hook", "version",
1938 DB_AUTHORIZER, DB_BACKUP, DB_BIND_FALLBACK,
1939 DB_BUSY, DB_CACHE, DB_CHANGES,
1940 DB_CLOSE, DB_COLLATE, DB_COLLATION_NEEDED,
1941 DB_COMMIT_HOOK, DB_COMPLETE, DB_COPY,
1942 DB_DESERIALIZE, DB_ENABLE_LOAD_EXTENSION,DB_ERRORCODE,
1943 DB_EVAL, DB_EXISTS, DB_FUNCTION,
1944 DB_INCRBLOB, DB_INTERRUPT, DB_LAST_INSERT_ROWID,
1945 DB_NULLVALUE, DB_ONECOLUMN, DB_PREUPDATE,
1946 DB_PROFILE, DB_PROGRESS, DB_REKEY,
1947 DB_RESTORE, DB_ROLLBACK_HOOK, DB_SERIALIZE,
1948 DB_STATUS, DB_TIMEOUT, DB_TOTAL_CHANGES,
1949 DB_TRACE, DB_TRACE_V2, DB_TRANSACTION,
1950 DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK, DB_VERSION,
1953 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
1956 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
1959 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
1963 switch( (enum DB_enum)choice ){
1965 /* $db authorizer ?CALLBACK?
1967 ** Invoke the given callback to authorize each SQL operation as it is
1968 ** compiled. 5 arguments are appended to the callback before it is
1971 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1972 ** (2) First descriptive name (depends on authorization type)
1973 ** (3) Second descriptive name
1974 ** (4) Name of the database (ex: "main", "temp")
1975 ** (5) Name of trigger that is doing the access
1977 ** The callback should return on of the following strings: SQLITE_OK,
1978 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1980 ** If this method is invoked with no arguments, the current authorization
1981 ** callback string is returned.
1983 case DB_AUTHORIZER: {
1984 #ifdef SQLITE_OMIT_AUTHORIZATION
1985 Tcl_AppendResult(interp, "authorization not available in this build",
1990 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1992 }else if( objc==2 ){
1994 Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
2000 Tcl_Free(pDb->zAuth);
2002 zAuth = Tcl_GetStringFromObj(objv[2], &len);
2003 if( zAuth && len>0 ){
2004 pDb->zAuth = Tcl_Alloc( len + 1 );
2005 memcpy(pDb->zAuth, zAuth, len+1);
2010 typedef int (*sqlite3_auth_cb)(
2011 void*,int,const char*,const char*,
2012 const char*,const char*);
2013 pDb->interp = interp;
2014 sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
2016 sqlite3_set_authorizer(pDb->db, 0, 0);
2023 /* $db backup ?DATABASE? FILENAME
2025 ** Open or create a database file named FILENAME. Transfer the
2026 ** content of local database DATABASE (default: "main") into the
2027 ** FILENAME database.
2030 const char *zDestFile;
2033 sqlite3_backup *pBackup;
2037 zDestFile = Tcl_GetString(objv[2]);
2038 }else if( objc==4 ){
2039 zSrcDb = Tcl_GetString(objv[2]);
2040 zDestFile = Tcl_GetString(objv[3]);
2042 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2045 rc = sqlite3_open_v2(zDestFile, &pDest,
2046 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
2047 if( rc!=SQLITE_OK ){
2048 Tcl_AppendResult(interp, "cannot open target database: ",
2049 sqlite3_errmsg(pDest), (char*)0);
2050 sqlite3_close(pDest);
2053 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
2055 Tcl_AppendResult(interp, "backup failed: ",
2056 sqlite3_errmsg(pDest), (char*)0);
2057 sqlite3_close(pDest);
2060 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
2061 sqlite3_backup_finish(pBackup);
2062 if( rc==SQLITE_DONE ){
2065 Tcl_AppendResult(interp, "backup failed: ",
2066 sqlite3_errmsg(pDest), (char*)0);
2069 sqlite3_close(pDest);
2073 /* $db bind_fallback ?CALLBACK?
2075 ** When resolving bind parameters in an SQL statement, if the parameter
2076 ** cannot be associated with a TCL variable then invoke CALLBACK with a
2077 ** single argument that is the name of the parameter and use the return
2078 ** value of the CALLBACK as the binding. If CALLBACK returns something
2079 ** other than TCL_OK or TCL_ERROR then bind a NULL.
2081 ** If CALLBACK is an empty string, then revert to the default behavior
2082 ** which is to set the binding to NULL.
2084 ** If CALLBACK returns an error, that causes the statement execution to
2085 ** abort. Hence, to configure a connection so that it throws an error
2086 ** on an attempt to bind an unknown variable, do something like this:
2088 ** proc bind_error {name} {error "no such variable: $name"}
2089 ** db bind_fallback bind_error
2091 case DB_BIND_FALLBACK: {
2093 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2095 }else if( objc==2 ){
2096 if( pDb->zBindFallback ){
2097 Tcl_AppendResult(interp, pDb->zBindFallback, (char*)0);
2102 if( pDb->zBindFallback ){
2103 Tcl_Free(pDb->zBindFallback);
2105 zCallback = Tcl_GetStringFromObj(objv[2], &len);
2106 if( zCallback && len>0 ){
2107 pDb->zBindFallback = Tcl_Alloc( len + 1 );
2108 memcpy(pDb->zBindFallback, zCallback, len+1);
2110 pDb->zBindFallback = 0;
2116 /* $db busy ?CALLBACK?
2118 ** Invoke the given callback if an SQL statement attempts to open
2119 ** a locked database file.
2123 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
2125 }else if( objc==2 ){
2127 Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
2133 Tcl_Free(pDb->zBusy);
2135 zBusy = Tcl_GetStringFromObj(objv[2], &len);
2136 if( zBusy && len>0 ){
2137 pDb->zBusy = Tcl_Alloc( len + 1 );
2138 memcpy(pDb->zBusy, zBusy, len+1);
2143 pDb->interp = interp;
2144 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
2146 sqlite3_busy_handler(pDb->db, 0, 0);
2155 ** Flush the prepared statement cache, or set the maximum number of
2156 ** cached statements.
2163 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
2166 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
2167 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
2169 Tcl_WrongNumArgs(interp, 2, objv, "flush");
2172 flushStmtCache( pDb );
2174 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
2176 Tcl_WrongNumArgs(interp, 2, objv, "size n");
2179 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
2180 Tcl_AppendResult( interp, "cannot convert \"",
2181 Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
2185 flushStmtCache( pDb );
2187 }else if( n>MAX_PREPARED_STMTS ){
2188 n = MAX_PREPARED_STMTS;
2194 Tcl_AppendResult( interp, "bad option \"",
2195 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
2204 ** Return the number of rows that were modified, inserted, or deleted by
2205 ** the most recent INSERT, UPDATE or DELETE statement, not including
2206 ** any changes made by trigger programs.
2211 Tcl_WrongNumArgs(interp, 2, objv, "");
2214 pResult = Tcl_GetObjResult(interp);
2215 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
2221 ** Shutdown the database
2224 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
2229 ** $db collate NAME SCRIPT
2231 ** Create a new SQL collation function called NAME. Whenever
2232 ** that function is called, invoke SCRIPT to evaluate the function.
2235 SqlCollate *pCollate;
2240 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
2243 zName = Tcl_GetStringFromObj(objv[2], 0);
2244 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
2245 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
2246 if( pCollate==0 ) return TCL_ERROR;
2247 pCollate->interp = interp;
2248 pCollate->pNext = pDb->pCollate;
2249 pCollate->zScript = (char*)&pCollate[1];
2250 pDb->pCollate = pCollate;
2251 memcpy(pCollate->zScript, zScript, nScript+1);
2252 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
2253 pCollate, tclSqlCollate) ){
2254 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
2261 ** $db collation_needed SCRIPT
2263 ** Create a new SQL collation function called NAME. Whenever
2264 ** that function is called, invoke SCRIPT to evaluate the function.
2266 case DB_COLLATION_NEEDED: {
2268 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
2271 if( pDb->pCollateNeeded ){
2272 Tcl_DecrRefCount(pDb->pCollateNeeded);
2274 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
2275 Tcl_IncrRefCount(pDb->pCollateNeeded);
2276 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
2280 /* $db commit_hook ?CALLBACK?
2282 ** Invoke the given callback just before committing every SQL transaction.
2283 ** If the callback throws an exception or returns non-zero, then the
2284 ** transaction is aborted. If CALLBACK is an empty string, the callback
2287 case DB_COMMIT_HOOK: {
2289 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2291 }else if( objc==2 ){
2293 Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
2296 const char *zCommit;
2299 Tcl_Free(pDb->zCommit);
2301 zCommit = Tcl_GetStringFromObj(objv[2], &len);
2302 if( zCommit && len>0 ){
2303 pDb->zCommit = Tcl_Alloc( len + 1 );
2304 memcpy(pDb->zCommit, zCommit, len+1);
2309 pDb->interp = interp;
2310 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
2312 sqlite3_commit_hook(pDb->db, 0, 0);
2320 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2321 ** additional lines of input are needed. This is similar to the
2322 ** built-in "info complete" command of Tcl.
2325 #ifndef SQLITE_OMIT_COMPLETE
2329 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2332 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
2333 pResult = Tcl_GetObjResult(interp);
2334 Tcl_SetBooleanObj(pResult, isComplete);
2339 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2341 ** Copy data into table from filename, optionally using SEPARATOR
2342 ** as column separators. If a column contains a null string, or the
2343 ** value of NULLINDICATOR, a NULL is inserted for the column.
2344 ** conflict-algorithm is one of the sqlite conflict algorithms:
2345 ** rollback, abort, fail, ignore, replace
2346 ** On success, return the number of lines processed, not necessarily same
2347 ** as 'db changes' due to conflict-algorithm selected.
2349 ** This code is basically an implementation/enhancement of
2350 ** the sqlite3 shell.c ".import" command.
2352 ** This command usage is equivalent to the sqlite2.x COPY statement,
2353 ** which imports file data into a table using the PostgreSQL COPY file format:
2354 ** $db copy $conflit_algo $table_name $filename \t \\N
2357 char *zTable; /* Insert data into this table */
2358 char *zFile; /* The file from which to extract data */
2359 char *zConflict; /* The conflict algorithm to use */
2360 sqlite3_stmt *pStmt; /* A statement */
2361 int nCol; /* Number of columns in the table */
2362 int nByte; /* Number of bytes in an SQL string */
2363 int i, j; /* Loop counters */
2364 int nSep; /* Number of bytes in zSep[] */
2365 int nNull; /* Number of bytes in zNull[] */
2366 char *zSql; /* An SQL statement */
2367 char *zLine; /* A single line of input from the file */
2368 char **azCol; /* zLine[] broken up into columns */
2369 const char *zCommit; /* How to commit changes */
2370 FILE *in; /* The input file */
2371 int lineno = 0; /* Line number of input file */
2372 char zLineNum[80]; /* Line number print buffer */
2373 Tcl_Obj *pResult; /* interp result */
2377 if( objc<5 || objc>7 ){
2378 Tcl_WrongNumArgs(interp, 2, objv,
2379 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2383 zSep = Tcl_GetStringFromObj(objv[5], 0);
2388 zNull = Tcl_GetStringFromObj(objv[6], 0);
2392 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2393 zTable = Tcl_GetStringFromObj(objv[3], 0);
2394 zFile = Tcl_GetStringFromObj(objv[4], 0);
2395 nSep = strlen30(zSep);
2396 nNull = strlen30(zNull);
2398 Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2402 if(strcmp(zConflict, "rollback") != 0 &&
2403 strcmp(zConflict, "abort" ) != 0 &&
2404 strcmp(zConflict, "fail" ) != 0 &&
2405 strcmp(zConflict, "ignore" ) != 0 &&
2406 strcmp(zConflict, "replace" ) != 0 ) {
2407 Tcl_AppendResult(interp, "Error: \"", zConflict,
2408 "\", conflict-algorithm must be one of: rollback, "
2409 "abort, fail, ignore, or replace", (char*)0);
2412 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2414 Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
2417 nByte = strlen30(zSql);
2418 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
2421 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2424 nCol = sqlite3_column_count(pStmt);
2426 sqlite3_finalize(pStmt);
2430 zSql = malloc( nByte + 50 + nCol*2 );
2432 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
2435 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2438 for(i=1; i<nCol; i++){
2444 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
2447 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2448 sqlite3_finalize(pStmt);
2451 in = fopen(zFile, "rb");
2453 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, (char*)0);
2454 sqlite3_finalize(pStmt);
2457 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2459 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
2463 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
2465 while( (zLine = local_getline(0, in))!=0 ){
2469 for(i=0, z=zLine; *z; z++){
2470 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2474 azCol[i] = &z[nSep];
2481 int nErr = strlen30(zFile) + 200;
2482 zErr = malloc(nErr);
2484 sqlite3_snprintf(nErr, zErr,
2485 "Error: %s line %d: expected %d columns of data but found %d",
2486 zFile, lineno, nCol, i+1);
2487 Tcl_AppendResult(interp, zErr, (char*)0);
2490 zCommit = "ROLLBACK";
2493 for(i=0; i<nCol; i++){
2494 /* check for null data, if so, bind as null */
2495 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
2496 || strlen30(azCol[i])==0
2498 sqlite3_bind_null(pStmt, i+1);
2500 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2503 sqlite3_step(pStmt);
2504 rc = sqlite3_reset(pStmt);
2506 if( rc!=SQLITE_OK ){
2507 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2508 zCommit = "ROLLBACK";
2514 sqlite3_finalize(pStmt);
2515 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
2517 if( zCommit[0] == 'C' ){
2518 /* success, set result as number of lines processed */
2519 pResult = Tcl_GetObjResult(interp);
2520 Tcl_SetIntObj(pResult, lineno);
2523 /* failure, append lineno where failed */
2524 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
2525 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2533 ** $db deserialize ?-maxsize N? ?-readonly BOOL? ?DATABASE? VALUE
2535 ** Reopen DATABASE (default "main") using the content in $VALUE
2537 case DB_DESERIALIZE: {
2538 #ifndef SQLITE_ENABLE_DESERIALIZE
2539 Tcl_AppendResult(interp, "MEMDB not available in this build",
2543 const char *zSchema = 0;
2544 Tcl_Obj *pValue = 0;
2546 unsigned char *pData;
2548 sqlite3_int64 mxSize = 0;
2554 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? VALUE");
2558 for(i=2; i<objc-1; i++){
2559 const char *z = Tcl_GetString(objv[i]);
2560 if( strcmp(z,"-maxsize")==0 && i<objc-2 ){
2561 rc = Tcl_GetWideIntFromObj(interp, objv[++i], &mxSize);
2562 if( rc ) goto deserialize_error;
2565 if( strcmp(z,"-readonly")==0 && i<objc-2 ){
2566 rc = Tcl_GetBooleanFromObj(interp, objv[++i], &isReadonly);
2567 if( rc ) goto deserialize_error;
2570 if( zSchema==0 && i==objc-2 && z[0]!='-' ){
2574 Tcl_AppendResult(interp, "unknown option: ", z, (char*)0);
2576 goto deserialize_error;
2578 pValue = objv[objc-1];
2579 pBA = Tcl_GetByteArrayFromObj(pValue, &len);
2580 pData = sqlite3_malloc64( len );
2581 if( pData==0 && len>0 ){
2582 Tcl_AppendResult(interp, "out of memory", (char*)0);
2586 if( len>0 ) memcpy(pData, pBA, len);
2588 flags = SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_READONLY;
2590 flags = SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_RESIZEABLE;
2592 xrc = sqlite3_deserialize(pDb->db, zSchema, pData, len, len, flags);
2594 Tcl_AppendResult(interp, "unable to set MEMDB content", (char*)0);
2598 sqlite3_file_control(pDb->db, zSchema,SQLITE_FCNTL_SIZE_LIMIT,&mxSize);
2607 ** $db enable_load_extension BOOLEAN
2609 ** Turn the extension loading feature on or off. It if off by
2612 case DB_ENABLE_LOAD_EXTENSION: {
2613 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2616 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2619 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2622 sqlite3_enable_load_extension(pDb->db, onoff);
2625 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2634 ** Return the numeric error code that was returned by the most recent
2635 ** call to sqlite3_exec().
2637 case DB_ERRORCODE: {
2638 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
2644 ** $db onecolumn $sql
2646 ** The onecolumn method is the equivalent of:
2647 ** lindex [$db eval $sql] 0
2650 case DB_ONECOLUMN: {
2651 Tcl_Obj *pResult = 0;
2652 DbEvalContext sEval;
2654 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2658 dbEvalInit(&sEval, pDb, objv[2], 0, 0);
2659 rc = dbEvalStep(&sEval);
2660 if( choice==DB_ONECOLUMN ){
2662 pResult = dbEvalColumnValue(&sEval, 0);
2663 }else if( rc==TCL_BREAK ){
2664 Tcl_ResetResult(interp);
2666 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2667 pResult = Tcl_NewBooleanObj(rc==TCL_OK);
2669 dbEvalFinalize(&sEval);
2670 if( pResult ) Tcl_SetObjResult(interp, pResult);
2672 if( rc==TCL_BREAK ){
2679 ** $db eval ?options? $sql ?array? ?{ ...code... }?
2681 ** The SQL statement in $sql is evaluated. For each row, the values are
2682 ** placed in elements of the array named "array" and ...code... is executed.
2683 ** If "array" and "code" are omitted, then no callback is every invoked.
2684 ** If "array" is an empty string, then the values are placed in variables
2685 ** that have the same name as the fields extracted by the query.
2690 while( objc>3 && (zOpt = Tcl_GetString(objv[2]))!=0 && zOpt[0]=='-' ){
2691 if( strcmp(zOpt, "-withoutnulls")==0 ){
2692 evalFlags |= SQLITE_EVAL_WITHOUTNULLS;
2695 Tcl_AppendResult(interp, "unknown option: \"", zOpt, "\"", (void*)0);
2701 if( objc<3 || objc>5 ){
2702 Tcl_WrongNumArgs(interp, 2, objv,
2703 "?OPTIONS? SQL ?ARRAY-NAME? ?SCRIPT?");
2708 DbEvalContext sEval;
2709 Tcl_Obj *pRet = Tcl_NewObj();
2710 Tcl_IncrRefCount(pRet);
2711 dbEvalInit(&sEval, pDb, objv[2], 0, 0);
2712 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2715 dbEvalRowInfo(&sEval, &nCol, 0);
2716 for(i=0; i<nCol; i++){
2717 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
2720 dbEvalFinalize(&sEval);
2721 if( rc==TCL_BREAK ){
2722 Tcl_SetObjResult(interp, pRet);
2725 Tcl_DecrRefCount(pRet);
2729 Tcl_Obj *pArray = 0;
2732 if( objc>=5 && *(char *)Tcl_GetString(objv[3]) ){
2735 pScript = objv[objc-1];
2736 Tcl_IncrRefCount(pScript);
2738 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2739 dbEvalInit(p, pDb, objv[2], pArray, evalFlags);
2742 cd2[1] = (void *)pScript;
2743 rc = DbEvalNextCmd(cd2, interp, TCL_OK);
2749 ** $db function NAME [-argcount N] [-deterministic] SCRIPT
2751 ** Create a new SQL function called NAME. Whenever that function is
2752 ** called, invoke SCRIPT to evaluate the function.
2755 int flags = SQLITE_UTF8;
2761 int eType = SQLITE_NULL;
2763 Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
2766 for(i=3; i<(objc-1); i++){
2767 const char *z = Tcl_GetString(objv[i]);
2768 int n = strlen30(z);
2769 if( n>1 && strncmp(z, "-argcount",n)==0 ){
2771 Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0);
2774 if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
2776 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2782 if( n>1 && strncmp(z, "-deterministic",n)==0 ){
2783 flags |= SQLITE_DETERMINISTIC;
2785 if( n>1 && strncmp(z, "-returntype", n)==0 ){
2786 const char *azType[] = {"integer", "real", "text", "blob", "any", 0};
2787 assert( SQLITE_INTEGER==1 && SQLITE_FLOAT==2 && SQLITE_TEXT==3 );
2788 assert( SQLITE_BLOB==4 && SQLITE_NULL==5 );
2790 Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0);
2794 if( Tcl_GetIndexFromObj(interp, objv[i], azType, "type", 0, &eType) ){
2799 Tcl_AppendResult(interp, "bad option \"", z,
2800 "\": must be -argcount, -deterministic or -returntype", (char*)0
2806 pScript = objv[objc-1];
2807 zName = Tcl_GetStringFromObj(objv[2], 0);
2808 pFunc = findSqlFunc(pDb, zName);
2809 if( pFunc==0 ) return TCL_ERROR;
2810 if( pFunc->pScript ){
2811 Tcl_DecrRefCount(pFunc->pScript);
2813 pFunc->pScript = pScript;
2814 Tcl_IncrRefCount(pScript);
2815 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
2816 pFunc->eType = eType;
2817 rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
2818 pFunc, tclSqlFunc, 0, 0);
2819 if( rc!=SQLITE_OK ){
2821 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
2827 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
2830 #ifdef SQLITE_OMIT_INCRBLOB
2831 Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
2835 const char *zDb = "main";
2837 const char *zColumn;
2840 /* Check for the -readonly option */
2841 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2845 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2846 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
2850 if( objc==(6+isReadonly) ){
2851 zDb = Tcl_GetString(objv[2]);
2853 zTable = Tcl_GetString(objv[objc-3]);
2854 zColumn = Tcl_GetString(objv[objc-2]);
2855 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2858 rc = createIncrblobChannel(
2859 interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
2869 ** Interrupt the execution of the inner-most SQL interpreter. This
2870 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2872 case DB_INTERRUPT: {
2873 sqlite3_interrupt(pDb->db);
2878 ** $db nullvalue ?STRING?
2880 ** Change text used when a NULL comes back from the database. If ?STRING?
2881 ** is not present, then the current string used for NULL is returned.
2882 ** If STRING is present, then STRING is returned.
2885 case DB_NULLVALUE: {
2886 if( objc!=2 && objc!=3 ){
2887 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2892 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2894 Tcl_Free(pDb->zNull);
2896 if( zNull && len>0 ){
2897 pDb->zNull = Tcl_Alloc( len + 1 );
2898 memcpy(pDb->zNull, zNull, len);
2899 pDb->zNull[len] = '\0';
2904 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
2909 ** $db last_insert_rowid
2911 ** Return an integer which is the ROWID for the most recent insert.
2913 case DB_LAST_INSERT_ROWID: {
2917 Tcl_WrongNumArgs(interp, 2, objv, "");
2920 rowid = sqlite3_last_insert_rowid(pDb->db);
2921 pResult = Tcl_GetObjResult(interp);
2922 Tcl_SetWideIntObj(pResult, rowid);
2927 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
2930 /* $db progress ?N CALLBACK?
2932 ** Invoke the given callback every N virtual machine opcodes while executing
2937 if( pDb->zProgress ){
2938 Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
2940 }else if( objc==4 ){
2944 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
2947 if( pDb->zProgress ){
2948 Tcl_Free(pDb->zProgress);
2950 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2951 if( zProgress && len>0 ){
2952 pDb->zProgress = Tcl_Alloc( len + 1 );
2953 memcpy(pDb->zProgress, zProgress, len+1);
2957 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2958 if( pDb->zProgress ){
2959 pDb->interp = interp;
2960 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2962 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2966 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
2972 /* $db profile ?CALLBACK?
2974 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2975 ** that has run. The text of the SQL and the amount of elapse time are
2976 ** appended to CALLBACK before the script is run.
2980 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2982 }else if( objc==2 ){
2983 if( pDb->zProfile ){
2984 Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
2989 if( pDb->zProfile ){
2990 Tcl_Free(pDb->zProfile);
2992 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2993 if( zProfile && len>0 ){
2994 pDb->zProfile = Tcl_Alloc( len + 1 );
2995 memcpy(pDb->zProfile, zProfile, len+1);
2999 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3000 !defined(SQLITE_OMIT_DEPRECATED)
3001 if( pDb->zProfile ){
3002 pDb->interp = interp;
3003 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
3005 sqlite3_profile(pDb->db, 0, 0);
3015 ** Change the encryption key on the currently open database.
3018 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3023 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
3026 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3027 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
3028 rc = sqlite3_rekey(pDb->db, pKey, nKey);
3030 Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
3037 /* $db restore ?DATABASE? FILENAME
3039 ** Open a database file named FILENAME. Transfer the content
3040 ** of FILENAME into the local database DATABASE (default: "main").
3043 const char *zSrcFile;
3044 const char *zDestDb;
3046 sqlite3_backup *pBackup;
3051 zSrcFile = Tcl_GetString(objv[2]);
3052 }else if( objc==4 ){
3053 zDestDb = Tcl_GetString(objv[2]);
3054 zSrcFile = Tcl_GetString(objv[3]);
3056 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
3059 rc = sqlite3_open_v2(zSrcFile, &pSrc,
3060 SQLITE_OPEN_READONLY | pDb->openFlags, 0);
3061 if( rc!=SQLITE_OK ){
3062 Tcl_AppendResult(interp, "cannot open source database: ",
3063 sqlite3_errmsg(pSrc), (char*)0);
3064 sqlite3_close(pSrc);
3067 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
3069 Tcl_AppendResult(interp, "restore failed: ",
3070 sqlite3_errmsg(pDb->db), (char*)0);
3071 sqlite3_close(pSrc);
3074 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
3075 || rc==SQLITE_BUSY ){
3076 if( rc==SQLITE_BUSY ){
3077 if( nTimeout++ >= 3 ) break;
3081 sqlite3_backup_finish(pBackup);
3082 if( rc==SQLITE_DONE ){
3084 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
3085 Tcl_AppendResult(interp, "restore failed: source database busy",
3089 Tcl_AppendResult(interp, "restore failed: ",
3090 sqlite3_errmsg(pDb->db), (char*)0);
3093 sqlite3_close(pSrc);
3098 ** $db serialize ?DATABASE?
3100 ** Return a serialization of a database.
3102 case DB_SERIALIZE: {
3103 #ifndef SQLITE_ENABLE_DESERIALIZE
3104 Tcl_AppendResult(interp, "MEMDB not available in this build",
3108 const char *zSchema = objc>=3 ? Tcl_GetString(objv[2]) : "main";
3109 sqlite3_int64 sz = 0;
3110 unsigned char *pData;
3111 if( objc!=2 && objc!=3 ){
3112 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE?");
3116 pData = sqlite3_serialize(pDb->db, zSchema, &sz, SQLITE_SERIALIZE_NOCOPY);
3120 pData = sqlite3_serialize(pDb->db, zSchema, &sz, 0);
3123 Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(pData,sz));
3124 if( needFree ) sqlite3_free(pData);
3131 ** $db status (step|sort|autoindex|vmstep)
3133 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
3134 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
3140 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
3143 zOp = Tcl_GetString(objv[2]);
3144 if( strcmp(zOp, "step")==0 ){
3146 }else if( strcmp(zOp, "sort")==0 ){
3148 }else if( strcmp(zOp, "autoindex")==0 ){
3150 }else if( strcmp(zOp, "vmstep")==0 ){
3153 Tcl_AppendResult(interp,
3154 "bad argument: should be autoindex, step, sort or vmstep",
3158 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
3163 ** $db timeout MILLESECONDS
3165 ** Delay for the number of milliseconds specified when a file is locked.
3170 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
3173 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
3174 sqlite3_busy_timeout(pDb->db, ms);
3179 ** $db total_changes
3181 ** Return the number of rows that were modified, inserted, or deleted
3182 ** since the database handle was created.
3184 case DB_TOTAL_CHANGES: {
3187 Tcl_WrongNumArgs(interp, 2, objv, "");
3190 pResult = Tcl_GetObjResult(interp);
3191 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
3195 /* $db trace ?CALLBACK?
3197 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
3198 ** that is executed. The text of the SQL is appended to CALLBACK before
3203 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
3205 }else if( objc==2 ){
3207 Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
3213 Tcl_Free(pDb->zTrace);
3215 zTrace = Tcl_GetStringFromObj(objv[2], &len);
3216 if( zTrace && len>0 ){
3217 pDb->zTrace = Tcl_Alloc( len + 1 );
3218 memcpy(pDb->zTrace, zTrace, len+1);
3222 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3223 !defined(SQLITE_OMIT_DEPRECATED)
3225 pDb->interp = interp;
3226 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
3228 sqlite3_trace(pDb->db, 0, 0);
3235 /* $db trace_v2 ?CALLBACK? ?MASK?
3237 ** Make arrangements to invoke the CALLBACK routine for each trace event
3238 ** matching the mask that is generated. The parameters are appended to
3239 ** CALLBACK before it is executed.
3243 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK? ?MASK?");
3245 }else if( objc==2 ){
3246 if( pDb->zTraceV2 ){
3247 Tcl_AppendResult(interp, pDb->zTraceV2, (char*)0);
3252 Tcl_WideInt wMask = 0;
3254 static const char *TTYPE_strs[] = {
3255 "statement", "profile", "row", "close", 0
3258 TTYPE_STMT, TTYPE_PROFILE, TTYPE_ROW, TTYPE_CLOSE
3261 if( TCL_OK!=Tcl_ListObjLength(interp, objv[3], &len) ){
3264 for(i=0; i<len; i++){
3267 if( TCL_OK!=Tcl_ListObjIndex(interp, objv[3], i, &pObj) ){
3270 if( Tcl_GetIndexFromObj(interp, pObj, TTYPE_strs, "trace type",
3271 0, &ttype)!=TCL_OK ){
3273 Tcl_Obj *pError = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
3274 Tcl_IncrRefCount(pError);
3275 if( TCL_OK==Tcl_GetWideIntFromObj(interp, pObj, &wType) ){
3276 Tcl_DecrRefCount(pError);
3279 Tcl_SetObjResult(interp, pError);
3280 Tcl_DecrRefCount(pError);
3284 switch( (enum TTYPE_enum)ttype ){
3285 case TTYPE_STMT: wMask |= SQLITE_TRACE_STMT; break;
3286 case TTYPE_PROFILE: wMask |= SQLITE_TRACE_PROFILE; break;
3287 case TTYPE_ROW: wMask |= SQLITE_TRACE_ROW; break;
3288 case TTYPE_CLOSE: wMask |= SQLITE_TRACE_CLOSE; break;
3293 wMask = SQLITE_TRACE_STMT; /* use the "legacy" default */
3295 if( pDb->zTraceV2 ){
3296 Tcl_Free(pDb->zTraceV2);
3298 zTraceV2 = Tcl_GetStringFromObj(objv[2], &len);
3299 if( zTraceV2 && len>0 ){
3300 pDb->zTraceV2 = Tcl_Alloc( len + 1 );
3301 memcpy(pDb->zTraceV2, zTraceV2, len+1);
3305 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3306 if( pDb->zTraceV2 ){
3307 pDb->interp = interp;
3308 sqlite3_trace_v2(pDb->db, (unsigned)wMask, DbTraceV2Handler, pDb);
3310 sqlite3_trace_v2(pDb->db, 0, 0, 0);
3317 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
3319 ** Start a new transaction (if we are not already in the midst of a
3320 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
3321 ** completes, either commit the transaction or roll it back if SCRIPT
3322 ** throws an exception. Or if no new transation was started, do nothing.
3323 ** pass the exception on up the stack.
3325 ** This command was inspired by Dave Thomas's talk on Ruby at the
3326 ** 2005 O'Reilly Open Source Convention (OSCON).
3328 case DB_TRANSACTION: {
3330 const char *zBegin = "SAVEPOINT _tcl_transaction";
3331 if( objc!=3 && objc!=4 ){
3332 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
3336 if( pDb->nTransaction==0 && objc==4 ){
3337 static const char *TTYPE_strs[] = {
3338 "deferred", "exclusive", "immediate", 0
3341 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
3344 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
3348 switch( (enum TTYPE_enum)ttype ){
3349 case TTYPE_DEFERRED: /* no-op */; break;
3350 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
3351 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
3354 pScript = objv[objc-1];
3356 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
3358 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
3360 if( rc!=SQLITE_OK ){
3361 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3364 pDb->nTransaction++;
3366 /* If using NRE, schedule a callback to invoke the script pScript, then
3367 ** a second callback to commit (or rollback) the transaction or savepoint
3368 ** opened above. If not using NRE, evaluate the script directly, then
3369 ** call function DbTransPostCmd() to commit (or rollback) the transaction
3372 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
3373 (void)Tcl_NREvalObj(interp, pScript, 0);
3375 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
3381 ** $db unlock_notify ?script?
3383 case DB_UNLOCK_NOTIFY: {
3384 #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
3385 Tcl_AppendResult(interp, "unlock_notify not available in this build",
3389 if( objc!=2 && objc!=3 ){
3390 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3393 void (*xNotify)(void **, int) = 0;
3394 void *pNotifyArg = 0;
3396 if( pDb->pUnlockNotify ){
3397 Tcl_DecrRefCount(pDb->pUnlockNotify);
3398 pDb->pUnlockNotify = 0;
3402 xNotify = DbUnlockNotify;
3403 pNotifyArg = (void *)pDb;
3404 pDb->pUnlockNotify = objv[2];
3405 Tcl_IncrRefCount(pDb->pUnlockNotify);
3408 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
3409 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3418 ** $db preupdate_hook count
3419 ** $db preupdate_hook hook ?SCRIPT?
3420 ** $db preupdate_hook new INDEX
3421 ** $db preupdate_hook old INDEX
3423 case DB_PREUPDATE: {
3424 #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
3425 Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time",
3429 static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
3430 enum DbPreupdateSubCmd {
3431 PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
3436 Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
3438 if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
3442 switch( (enum DbPreupdateSubCmd)iSub ){
3444 int nCol = sqlite3_preupdate_count(pDb->db);
3445 Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
3451 Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
3454 DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
3461 Tcl_WrongNumArgs(interp, 3, objv, "");
3464 pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
3465 Tcl_SetObjResult(interp, pRet);
3472 sqlite3_value *pValue;
3474 Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
3477 if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
3481 if( iSub==PRE_OLD ){
3482 rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
3484 assert( iSub==PRE_NEW );
3485 rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
3488 if( rc==SQLITE_OK ){
3490 pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
3491 Tcl_SetObjResult(interp, pObj);
3493 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3498 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
3503 ** $db wal_hook ?script?
3504 ** $db update_hook ?script?
3505 ** $db rollback_hook ?script?
3508 case DB_UPDATE_HOOK:
3509 case DB_ROLLBACK_HOOK: {
3510 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
3511 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3513 Tcl_Obj **ppHook = 0;
3514 if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
3515 if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
3516 if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
3518 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3522 DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
3528 ** Return the version string for this database.
3532 for(i=2; i<objc; i++){
3533 const char *zArg = Tcl_GetString(objv[i]);
3534 /* Optional arguments to $db version are used for testing purpose */
3536 /* $db version -use-legacy-prepare BOOLEAN
3538 ** Turn the use of legacy sqlite3_prepare() on or off.
3540 if( strcmp(zArg, "-use-legacy-prepare")==0 && i+1<objc ){
3542 if( Tcl_GetBooleanFromObj(interp, objv[i], &pDb->bLegacyPrepare) ){
3547 /* $db version -last-stmt-ptr
3549 ** Return a string which is a hex encoding of the pointer to the
3550 ** most recent sqlite3_stmt in the statement cache.
3552 if( strcmp(zArg, "-last-stmt-ptr")==0 ){
3554 sqlite3_snprintf(sizeof(zBuf), zBuf, "%p",
3555 pDb->stmtList ? pDb->stmtList->pStmt: 0);
3556 Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
3558 #endif /* SQLITE_TEST */
3560 Tcl_AppendResult(interp, "unknown argument: ", zArg, (char*)0);
3565 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
3571 } /* End of the SWITCH statement */
3577 ** Adaptor that provides an objCmd interface to the NRE-enabled
3578 ** interface implementation.
3580 static int SQLITE_TCLAPI DbObjCmdAdaptor(
3586 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
3588 #endif /* SQLITE_TCL_NRE */
3591 ** Issue the usage message when the "sqlite3" command arguments are
3594 static int sqliteCmdUsage(
3598 Tcl_WrongNumArgs(interp, 1, objv,
3599 "HANDLE ?FILENAME? ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
3600 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
3601 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3609 ** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
3610 ** ?-create BOOLEAN? ?-nomutex BOOLEAN?
3612 ** This is the main Tcl command. When the "sqlite" Tcl command is
3613 ** invoked, this routine runs to process that command.
3615 ** The first argument, DBNAME, is an arbitrary name for a new
3616 ** database connection. This command creates a new command named
3617 ** DBNAME that is used to control that connection. The database
3618 ** connection is deleted when the DBNAME command is deleted.
3620 ** The second argument is the name of the database file.
3623 static int SQLITE_TCLAPI DbMain(
3633 const char *zFile = 0;
3634 const char *zVfs = 0;
3636 Tcl_DString translatedFilename;
3637 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3643 /* In normal use, each TCL interpreter runs in a single thread. So
3644 ** by default, we can turn off mutexing on SQLite database connections.
3645 ** However, for testing purposes it is useful to have mutexes turned
3646 ** on. So, by default, mutexes default off. But if compiled with
3647 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3649 #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3650 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3652 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3655 if( objc==1 ) return sqliteCmdUsage(interp, objv);
3657 zArg = Tcl_GetStringFromObj(objv[1], 0);
3658 if( strcmp(zArg,"-version")==0 ){
3659 Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
3662 if( strcmp(zArg,"-sourceid")==0 ){
3663 Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0);
3666 if( strcmp(zArg,"-has-codec")==0 ){
3667 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3668 Tcl_AppendResult(interp,"1",(char*)0);
3670 Tcl_AppendResult(interp,"0",(char*)0);
3674 if( zArg[0]=='-' ) return sqliteCmdUsage(interp, objv);
3676 for(i=2; i<objc; i++){
3677 zArg = Tcl_GetString(objv[i]);
3679 if( zFile!=0 ) return sqliteCmdUsage(interp, objv);
3683 if( i==objc-1 ) return sqliteCmdUsage(interp, objv);
3685 if( strcmp(zArg,"-key")==0 ){
3686 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3687 pKey = Tcl_GetByteArrayFromObj(objv[i], &nKey);
3689 }else if( strcmp(zArg, "-vfs")==0 ){
3690 zVfs = Tcl_GetString(objv[i]);
3691 }else if( strcmp(zArg, "-readonly")==0 ){
3693 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3695 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
3696 flags |= SQLITE_OPEN_READONLY;
3698 flags &= ~SQLITE_OPEN_READONLY;
3699 flags |= SQLITE_OPEN_READWRITE;
3701 }else if( strcmp(zArg, "-create")==0 ){
3703 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3704 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
3705 flags |= SQLITE_OPEN_CREATE;
3707 flags &= ~SQLITE_OPEN_CREATE;
3709 }else if( strcmp(zArg, "-nomutex")==0 ){
3711 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3713 flags |= SQLITE_OPEN_NOMUTEX;
3714 flags &= ~SQLITE_OPEN_FULLMUTEX;
3716 flags &= ~SQLITE_OPEN_NOMUTEX;
3718 }else if( strcmp(zArg, "-fullmutex")==0 ){
3720 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3722 flags |= SQLITE_OPEN_FULLMUTEX;
3723 flags &= ~SQLITE_OPEN_NOMUTEX;
3725 flags &= ~SQLITE_OPEN_FULLMUTEX;
3727 }else if( strcmp(zArg, "-uri")==0 ){
3729 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3731 flags |= SQLITE_OPEN_URI;
3733 flags &= ~SQLITE_OPEN_URI;
3736 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3741 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
3742 memset(p, 0, sizeof(*p));
3743 if( zFile==0 ) zFile = "";
3744 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
3745 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
3746 Tcl_DStringFree(&translatedFilename);
3748 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3749 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3750 sqlite3_close(p->db);
3754 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
3756 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3758 sqlite3_key(p->db, pKey, nKey);
3762 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
3764 sqlite3_free(zErrMsg);
3767 p->maxStmt = NUM_PREPARED_STMTS;
3768 p->openFlags = flags & SQLITE_OPEN_URI;
3770 zArg = Tcl_GetStringFromObj(objv[1], 0);
3772 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3773 (char*)p, DbDeleteCmd);
3775 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3781 ** Provide a dummy Tcl_InitStubs if we are using this as a static
3784 #ifndef USE_TCL_STUBS
3785 # undef Tcl_InitStubs
3786 # define Tcl_InitStubs(a,b,c) TCL_VERSION
3790 ** Make sure we have a PACKAGE_VERSION macro defined. This will be
3791 ** defined automatically by the TEA makefile. But other makefiles
3792 ** do not define it.
3794 #ifndef PACKAGE_VERSION
3795 # define PACKAGE_VERSION SQLITE_VERSION
3799 ** Initialize this module.
3801 ** This Tcl module contains only a single new Tcl command named "sqlite".
3802 ** (Hence there is no namespace. There is no point in using a namespace
3803 ** if the extension only supplies one new name!) The "sqlite" command is
3804 ** used to open a new SQLite database. See the DbMain() routine above
3805 ** for additional information.
3807 ** The EXTERN macros are required by TCL in order to work on windows.
3809 EXTERN int Sqlite3_Init(Tcl_Interp *interp){
3810 int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
3812 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
3813 #ifndef SQLITE_3_SUFFIX_ONLY
3814 /* The "sqlite" alias is undocumented. It is here only to support
3815 ** legacy scripts. All new scripts should use only the "sqlite3"
3817 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
3819 rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3823 EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3824 EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3825 EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3827 /* Because it accesses the file-system and uses persistent state, SQLite
3828 ** is not considered appropriate for safe interpreters. Hence, we cause
3829 ** the _SafeInit() interfaces return TCL_ERROR.
3831 EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
3832 EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
3836 #ifndef SQLITE_3_SUFFIX_ONLY
3837 int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3838 int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3839 int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3840 int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3844 ** If the TCLSH macro is defined, add code to make a stand-alone program.
3848 /* This is the main routine for an ordinary TCL shell. If there are
3849 ** are arguments, run the first argument as a script. Otherwise,
3850 ** read TCL commands from standard input
3852 static const char *tclsh_main_loop(void){
3853 static const char zMainloop[] =
3854 "if {[llength $argv]>=1} {\n"
3855 "set argv0 [lindex $argv 0]\n"
3856 "set argv [lrange $argv 1 end]\n"
3860 "while {![eof stdin]} {\n"
3861 "if {$line!=\"\"} {\n"
3862 "puts -nonewline \"> \"\n"
3864 "puts -nonewline \"% \"\n"
3867 "append line [gets stdin]\n"
3868 "if {[info complete $line]} {\n"
3869 "if {[catch {uplevel #0 $line} result]} {\n"
3870 "puts stderr \"Error: $result\"\n"
3871 "} elseif {$result!=\"\"} {\n"
3884 #define TCLSH_MAIN main /* Needed to fake out mktclapp */
3885 int SQLITE_CDECL TCLSH_MAIN(int argc, char **argv){
3888 const char *zScript = 0;
3890 #if defined(TCLSH_INIT_PROC)
3891 extern const char *TCLSH_INIT_PROC(Tcl_Interp*);
3894 #if !defined(_WIN32_WCE)
3895 if( getenv("SQLITE_DEBUG_BREAK") ){
3896 if( isatty(0) && isatty(2) ){
3898 "attach debugger to process %d and press any key to continue.\n",
3902 #if defined(_WIN32) || defined(WIN32)
3904 #elif defined(SIGTRAP)
3911 /* Call sqlite3_shutdown() once before doing anything else. This is to
3912 ** test that sqlite3_shutdown() can be safely called by a process before
3913 ** sqlite3_initialize() is. */
3916 Tcl_FindExecutable(argv[0]);
3917 Tcl_SetSystemEncoding(NULL, "utf-8");
3918 interp = Tcl_CreateInterp();
3919 Sqlite3_Init(interp);
3921 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-1);
3922 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
3923 Tcl_SetVar(interp,"argv0",argv[0],TCL_GLOBAL_ONLY);
3924 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
3925 for(i=1; i<argc; i++){
3926 Tcl_SetVar(interp, "argv", argv[i],
3927 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3929 #if defined(TCLSH_INIT_PROC)
3930 zScript = TCLSH_INIT_PROC(interp);
3933 zScript = tclsh_main_loop();
3935 if( Tcl_GlobalEval(interp, zScript)!=TCL_OK ){
3936 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
3937 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
3938 fprintf(stderr,"%s: %s\n", *argv, zInfo);