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", "config",
1926 "copy", "deserialize", "enable_load_extension",
1927 "errorcode", "eval", "exists",
1928 "function", "incrblob", "interrupt",
1929 "last_insert_rowid", "nullvalue", "onecolumn",
1930 "preupdate", "profile", "progress",
1931 "rekey", "restore", "rollback_hook",
1932 "serialize", "status", "timeout",
1933 "total_changes", "trace", "trace_v2",
1934 "transaction", "unlock_notify", "update_hook",
1935 "version", "wal_hook", 0
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_CONFIG,
1942 DB_COPY, DB_DESERIALIZE, DB_ENABLE_LOAD_EXTENSION,
1943 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1944 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
1945 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
1946 DB_PREUPDATE, DB_PROFILE, DB_PROGRESS,
1947 DB_REKEY, DB_RESTORE, DB_ROLLBACK_HOOK,
1948 DB_SERIALIZE, DB_STATUS, DB_TIMEOUT,
1949 DB_TOTAL_CHANGES, DB_TRACE, DB_TRACE_V2,
1950 DB_TRANSACTION, DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK,
1951 DB_VERSION, DB_WAL_HOOK
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 config ?OPTION? ?BOOLEAN?
2341 ** Configure the database connection using the sqlite3_db_config()
2345 static const struct DbConfigChoices {
2349 { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
2350 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL },
2351 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML },
2352 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
2353 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
2354 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
2355 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW },
2356 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
2357 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE },
2358 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT },
2359 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
2360 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
2361 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
2362 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
2363 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA },
2364 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA },
2369 Tcl_WrongNumArgs(interp, 2, objv, "?OPTION? ?BOOLEAN?");
2373 /* With no arguments, list all configuration options and with the
2375 pResult = Tcl_NewListObj(0,0);
2376 for(ii=0; ii<sizeof(aDbConfig)/sizeof(aDbConfig[0]); ii++){
2378 sqlite3_db_config(pDb->db, aDbConfig[ii].op, -1, &v);
2379 Tcl_ListObjAppendElement(interp, pResult,
2380 Tcl_NewStringObj(aDbConfig[ii].zName,-1));
2381 Tcl_ListObjAppendElement(interp, pResult,
2385 const char *zOpt = Tcl_GetString(objv[2]);
2388 if( zOpt[0]=='-' ) zOpt++;
2389 for(ii=0; ii<sizeof(aDbConfig)/sizeof(aDbConfig[0]); ii++){
2390 if( strcmp(aDbConfig[ii].zName, zOpt)==0 ) break;
2392 if( ii>=sizeof(aDbConfig)/sizeof(aDbConfig[0]) ){
2393 Tcl_AppendResult(interp, "unknown config option: \"", zOpt,
2398 if( Tcl_GetBooleanFromObj(interp, objv[3], &onoff) ){
2402 sqlite3_db_config(pDb->db, aDbConfig[ii].op, onoff, &v);
2403 pResult = Tcl_NewIntObj(v);
2405 Tcl_SetObjResult(interp, pResult);
2409 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2411 ** Copy data into table from filename, optionally using SEPARATOR
2412 ** as column separators. If a column contains a null string, or the
2413 ** value of NULLINDICATOR, a NULL is inserted for the column.
2414 ** conflict-algorithm is one of the sqlite conflict algorithms:
2415 ** rollback, abort, fail, ignore, replace
2416 ** On success, return the number of lines processed, not necessarily same
2417 ** as 'db changes' due to conflict-algorithm selected.
2419 ** This code is basically an implementation/enhancement of
2420 ** the sqlite3 shell.c ".import" command.
2422 ** This command usage is equivalent to the sqlite2.x COPY statement,
2423 ** which imports file data into a table using the PostgreSQL COPY file format:
2424 ** $db copy $conflit_algo $table_name $filename \t \\N
2427 char *zTable; /* Insert data into this table */
2428 char *zFile; /* The file from which to extract data */
2429 char *zConflict; /* The conflict algorithm to use */
2430 sqlite3_stmt *pStmt; /* A statement */
2431 int nCol; /* Number of columns in the table */
2432 int nByte; /* Number of bytes in an SQL string */
2433 int i, j; /* Loop counters */
2434 int nSep; /* Number of bytes in zSep[] */
2435 int nNull; /* Number of bytes in zNull[] */
2436 char *zSql; /* An SQL statement */
2437 char *zLine; /* A single line of input from the file */
2438 char **azCol; /* zLine[] broken up into columns */
2439 const char *zCommit; /* How to commit changes */
2440 FILE *in; /* The input file */
2441 int lineno = 0; /* Line number of input file */
2442 char zLineNum[80]; /* Line number print buffer */
2443 Tcl_Obj *pResult; /* interp result */
2447 if( objc<5 || objc>7 ){
2448 Tcl_WrongNumArgs(interp, 2, objv,
2449 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2453 zSep = Tcl_GetStringFromObj(objv[5], 0);
2458 zNull = Tcl_GetStringFromObj(objv[6], 0);
2462 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2463 zTable = Tcl_GetStringFromObj(objv[3], 0);
2464 zFile = Tcl_GetStringFromObj(objv[4], 0);
2465 nSep = strlen30(zSep);
2466 nNull = strlen30(zNull);
2468 Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2472 if(strcmp(zConflict, "rollback") != 0 &&
2473 strcmp(zConflict, "abort" ) != 0 &&
2474 strcmp(zConflict, "fail" ) != 0 &&
2475 strcmp(zConflict, "ignore" ) != 0 &&
2476 strcmp(zConflict, "replace" ) != 0 ) {
2477 Tcl_AppendResult(interp, "Error: \"", zConflict,
2478 "\", conflict-algorithm must be one of: rollback, "
2479 "abort, fail, ignore, or replace", (char*)0);
2482 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2484 Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
2487 nByte = strlen30(zSql);
2488 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
2491 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2494 nCol = sqlite3_column_count(pStmt);
2496 sqlite3_finalize(pStmt);
2500 zSql = malloc( nByte + 50 + nCol*2 );
2502 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
2505 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2508 for(i=1; i<nCol; i++){
2514 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
2517 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2518 sqlite3_finalize(pStmt);
2521 in = fopen(zFile, "rb");
2523 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, (char*)0);
2524 sqlite3_finalize(pStmt);
2527 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2529 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
2533 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
2535 while( (zLine = local_getline(0, in))!=0 ){
2539 for(i=0, z=zLine; *z; z++){
2540 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2544 azCol[i] = &z[nSep];
2551 int nErr = strlen30(zFile) + 200;
2552 zErr = malloc(nErr);
2554 sqlite3_snprintf(nErr, zErr,
2555 "Error: %s line %d: expected %d columns of data but found %d",
2556 zFile, lineno, nCol, i+1);
2557 Tcl_AppendResult(interp, zErr, (char*)0);
2560 zCommit = "ROLLBACK";
2563 for(i=0; i<nCol; i++){
2564 /* check for null data, if so, bind as null */
2565 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
2566 || strlen30(azCol[i])==0
2568 sqlite3_bind_null(pStmt, i+1);
2570 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2573 sqlite3_step(pStmt);
2574 rc = sqlite3_reset(pStmt);
2576 if( rc!=SQLITE_OK ){
2577 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2578 zCommit = "ROLLBACK";
2584 sqlite3_finalize(pStmt);
2585 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
2587 if( zCommit[0] == 'C' ){
2588 /* success, set result as number of lines processed */
2589 pResult = Tcl_GetObjResult(interp);
2590 Tcl_SetIntObj(pResult, lineno);
2593 /* failure, append lineno where failed */
2594 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
2595 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2603 ** $db deserialize ?-maxsize N? ?-readonly BOOL? ?DATABASE? VALUE
2605 ** Reopen DATABASE (default "main") using the content in $VALUE
2607 case DB_DESERIALIZE: {
2608 #ifndef SQLITE_ENABLE_DESERIALIZE
2609 Tcl_AppendResult(interp, "MEMDB not available in this build",
2613 const char *zSchema = 0;
2614 Tcl_Obj *pValue = 0;
2616 unsigned char *pData;
2618 sqlite3_int64 mxSize = 0;
2624 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? VALUE");
2628 for(i=2; i<objc-1; i++){
2629 const char *z = Tcl_GetString(objv[i]);
2630 if( strcmp(z,"-maxsize")==0 && i<objc-2 ){
2631 rc = Tcl_GetWideIntFromObj(interp, objv[++i], &mxSize);
2632 if( rc ) goto deserialize_error;
2635 if( strcmp(z,"-readonly")==0 && i<objc-2 ){
2636 rc = Tcl_GetBooleanFromObj(interp, objv[++i], &isReadonly);
2637 if( rc ) goto deserialize_error;
2640 if( zSchema==0 && i==objc-2 && z[0]!='-' ){
2644 Tcl_AppendResult(interp, "unknown option: ", z, (char*)0);
2646 goto deserialize_error;
2648 pValue = objv[objc-1];
2649 pBA = Tcl_GetByteArrayFromObj(pValue, &len);
2650 pData = sqlite3_malloc64( len );
2651 if( pData==0 && len>0 ){
2652 Tcl_AppendResult(interp, "out of memory", (char*)0);
2656 if( len>0 ) memcpy(pData, pBA, len);
2658 flags = SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_READONLY;
2660 flags = SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_RESIZEABLE;
2662 xrc = sqlite3_deserialize(pDb->db, zSchema, pData, len, len, flags);
2664 Tcl_AppendResult(interp, "unable to set MEMDB content", (char*)0);
2668 sqlite3_file_control(pDb->db, zSchema,SQLITE_FCNTL_SIZE_LIMIT,&mxSize);
2677 ** $db enable_load_extension BOOLEAN
2679 ** Turn the extension loading feature on or off. It if off by
2682 case DB_ENABLE_LOAD_EXTENSION: {
2683 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2686 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2689 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2692 sqlite3_enable_load_extension(pDb->db, onoff);
2695 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2704 ** Return the numeric error code that was returned by the most recent
2705 ** call to sqlite3_exec().
2707 case DB_ERRORCODE: {
2708 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
2714 ** $db onecolumn $sql
2716 ** The onecolumn method is the equivalent of:
2717 ** lindex [$db eval $sql] 0
2720 case DB_ONECOLUMN: {
2721 Tcl_Obj *pResult = 0;
2722 DbEvalContext sEval;
2724 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2728 dbEvalInit(&sEval, pDb, objv[2], 0, 0);
2729 rc = dbEvalStep(&sEval);
2730 if( choice==DB_ONECOLUMN ){
2732 pResult = dbEvalColumnValue(&sEval, 0);
2733 }else if( rc==TCL_BREAK ){
2734 Tcl_ResetResult(interp);
2736 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2737 pResult = Tcl_NewBooleanObj(rc==TCL_OK);
2739 dbEvalFinalize(&sEval);
2740 if( pResult ) Tcl_SetObjResult(interp, pResult);
2742 if( rc==TCL_BREAK ){
2749 ** $db eval ?options? $sql ?array? ?{ ...code... }?
2751 ** The SQL statement in $sql is evaluated. For each row, the values are
2752 ** placed in elements of the array named "array" and ...code... is executed.
2753 ** If "array" and "code" are omitted, then no callback is every invoked.
2754 ** If "array" is an empty string, then the values are placed in variables
2755 ** that have the same name as the fields extracted by the query.
2760 while( objc>3 && (zOpt = Tcl_GetString(objv[2]))!=0 && zOpt[0]=='-' ){
2761 if( strcmp(zOpt, "-withoutnulls")==0 ){
2762 evalFlags |= SQLITE_EVAL_WITHOUTNULLS;
2765 Tcl_AppendResult(interp, "unknown option: \"", zOpt, "\"", (void*)0);
2771 if( objc<3 || objc>5 ){
2772 Tcl_WrongNumArgs(interp, 2, objv,
2773 "?OPTIONS? SQL ?ARRAY-NAME? ?SCRIPT?");
2778 DbEvalContext sEval;
2779 Tcl_Obj *pRet = Tcl_NewObj();
2780 Tcl_IncrRefCount(pRet);
2781 dbEvalInit(&sEval, pDb, objv[2], 0, 0);
2782 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2785 dbEvalRowInfo(&sEval, &nCol, 0);
2786 for(i=0; i<nCol; i++){
2787 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
2790 dbEvalFinalize(&sEval);
2791 if( rc==TCL_BREAK ){
2792 Tcl_SetObjResult(interp, pRet);
2795 Tcl_DecrRefCount(pRet);
2799 Tcl_Obj *pArray = 0;
2802 if( objc>=5 && *(char *)Tcl_GetString(objv[3]) ){
2805 pScript = objv[objc-1];
2806 Tcl_IncrRefCount(pScript);
2808 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2809 dbEvalInit(p, pDb, objv[2], pArray, evalFlags);
2812 cd2[1] = (void *)pScript;
2813 rc = DbEvalNextCmd(cd2, interp, TCL_OK);
2819 ** $db function NAME [OPTIONS] SCRIPT
2821 ** Create a new SQL function called NAME. Whenever that function is
2822 ** called, invoke SCRIPT to evaluate the function.
2825 ** --argcount N Function has exactly N arguments
2826 ** --deterministic The function is pure
2827 ** --directonly Prohibit use inside triggers and views
2828 ** --innocuous Has no side effects or information leaks
2829 ** --returntype TYPE Specify the return type of the function
2832 int flags = SQLITE_UTF8;
2838 int eType = SQLITE_NULL;
2840 Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
2843 for(i=3; i<(objc-1); i++){
2844 const char *z = Tcl_GetString(objv[i]);
2845 int n = strlen30(z);
2846 if( n>1 && strncmp(z, "-argcount",n)==0 ){
2848 Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0);
2851 if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
2853 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2859 if( n>1 && strncmp(z, "-deterministic",n)==0 ){
2860 flags |= SQLITE_DETERMINISTIC;
2862 if( n>1 && strncmp(z, "-directonly",n)==0 ){
2863 flags |= SQLITE_DIRECTONLY;
2865 if( n>1 && strncmp(z, "-innocuous",n)==0 ){
2866 flags |= SQLITE_INNOCUOUS;
2868 if( n>1 && strncmp(z, "-returntype", n)==0 ){
2869 const char *azType[] = {"integer", "real", "text", "blob", "any", 0};
2870 assert( SQLITE_INTEGER==1 && SQLITE_FLOAT==2 && SQLITE_TEXT==3 );
2871 assert( SQLITE_BLOB==4 && SQLITE_NULL==5 );
2873 Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0);
2877 if( Tcl_GetIndexFromObj(interp, objv[i], azType, "type", 0, &eType) ){
2882 Tcl_AppendResult(interp, "bad option \"", z,
2883 "\": must be -argcount, -deterministic, -directonly,"
2884 " -innocuous, or -returntype", (char*)0
2890 pScript = objv[objc-1];
2891 zName = Tcl_GetStringFromObj(objv[2], 0);
2892 pFunc = findSqlFunc(pDb, zName);
2893 if( pFunc==0 ) return TCL_ERROR;
2894 if( pFunc->pScript ){
2895 Tcl_DecrRefCount(pFunc->pScript);
2897 pFunc->pScript = pScript;
2898 Tcl_IncrRefCount(pScript);
2899 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
2900 pFunc->eType = eType;
2901 rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
2902 pFunc, tclSqlFunc, 0, 0);
2903 if( rc!=SQLITE_OK ){
2905 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
2911 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
2914 #ifdef SQLITE_OMIT_INCRBLOB
2915 Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
2919 const char *zDb = "main";
2921 const char *zColumn;
2924 /* Check for the -readonly option */
2925 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2929 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2930 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
2934 if( objc==(6+isReadonly) ){
2935 zDb = Tcl_GetString(objv[2]);
2937 zTable = Tcl_GetString(objv[objc-3]);
2938 zColumn = Tcl_GetString(objv[objc-2]);
2939 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2942 rc = createIncrblobChannel(
2943 interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
2953 ** Interrupt the execution of the inner-most SQL interpreter. This
2954 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2956 case DB_INTERRUPT: {
2957 sqlite3_interrupt(pDb->db);
2962 ** $db nullvalue ?STRING?
2964 ** Change text used when a NULL comes back from the database. If ?STRING?
2965 ** is not present, then the current string used for NULL is returned.
2966 ** If STRING is present, then STRING is returned.
2969 case DB_NULLVALUE: {
2970 if( objc!=2 && objc!=3 ){
2971 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2976 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2978 Tcl_Free(pDb->zNull);
2980 if( zNull && len>0 ){
2981 pDb->zNull = Tcl_Alloc( len + 1 );
2982 memcpy(pDb->zNull, zNull, len);
2983 pDb->zNull[len] = '\0';
2988 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
2993 ** $db last_insert_rowid
2995 ** Return an integer which is the ROWID for the most recent insert.
2997 case DB_LAST_INSERT_ROWID: {
3001 Tcl_WrongNumArgs(interp, 2, objv, "");
3004 rowid = sqlite3_last_insert_rowid(pDb->db);
3005 pResult = Tcl_GetObjResult(interp);
3006 Tcl_SetWideIntObj(pResult, rowid);
3011 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
3014 /* $db progress ?N CALLBACK?
3016 ** Invoke the given callback every N virtual machine opcodes while executing
3021 if( pDb->zProgress ){
3022 Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
3024 }else if( objc==4 ){
3028 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
3031 if( pDb->zProgress ){
3032 Tcl_Free(pDb->zProgress);
3034 zProgress = Tcl_GetStringFromObj(objv[3], &len);
3035 if( zProgress && len>0 ){
3036 pDb->zProgress = Tcl_Alloc( len + 1 );
3037 memcpy(pDb->zProgress, zProgress, len+1);
3041 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
3042 if( pDb->zProgress ){
3043 pDb->interp = interp;
3044 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
3046 sqlite3_progress_handler(pDb->db, 0, 0, 0);
3050 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
3056 /* $db profile ?CALLBACK?
3058 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
3059 ** that has run. The text of the SQL and the amount of elapse time are
3060 ** appended to CALLBACK before the script is run.
3064 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
3066 }else if( objc==2 ){
3067 if( pDb->zProfile ){
3068 Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
3073 if( pDb->zProfile ){
3074 Tcl_Free(pDb->zProfile);
3076 zProfile = Tcl_GetStringFromObj(objv[2], &len);
3077 if( zProfile && len>0 ){
3078 pDb->zProfile = Tcl_Alloc( len + 1 );
3079 memcpy(pDb->zProfile, zProfile, len+1);
3083 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3084 !defined(SQLITE_OMIT_DEPRECATED)
3085 if( pDb->zProfile ){
3086 pDb->interp = interp;
3087 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
3089 sqlite3_profile(pDb->db, 0, 0);
3099 ** Change the encryption key on the currently open database.
3103 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
3109 /* $db restore ?DATABASE? FILENAME
3111 ** Open a database file named FILENAME. Transfer the content
3112 ** of FILENAME into the local database DATABASE (default: "main").
3115 const char *zSrcFile;
3116 const char *zDestDb;
3118 sqlite3_backup *pBackup;
3123 zSrcFile = Tcl_GetString(objv[2]);
3124 }else if( objc==4 ){
3125 zDestDb = Tcl_GetString(objv[2]);
3126 zSrcFile = Tcl_GetString(objv[3]);
3128 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
3131 rc = sqlite3_open_v2(zSrcFile, &pSrc,
3132 SQLITE_OPEN_READONLY | pDb->openFlags, 0);
3133 if( rc!=SQLITE_OK ){
3134 Tcl_AppendResult(interp, "cannot open source database: ",
3135 sqlite3_errmsg(pSrc), (char*)0);
3136 sqlite3_close(pSrc);
3139 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
3141 Tcl_AppendResult(interp, "restore failed: ",
3142 sqlite3_errmsg(pDb->db), (char*)0);
3143 sqlite3_close(pSrc);
3146 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
3147 || rc==SQLITE_BUSY ){
3148 if( rc==SQLITE_BUSY ){
3149 if( nTimeout++ >= 3 ) break;
3153 sqlite3_backup_finish(pBackup);
3154 if( rc==SQLITE_DONE ){
3156 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
3157 Tcl_AppendResult(interp, "restore failed: source database busy",
3161 Tcl_AppendResult(interp, "restore failed: ",
3162 sqlite3_errmsg(pDb->db), (char*)0);
3165 sqlite3_close(pSrc);
3170 ** $db serialize ?DATABASE?
3172 ** Return a serialization of a database.
3174 case DB_SERIALIZE: {
3175 #ifndef SQLITE_ENABLE_DESERIALIZE
3176 Tcl_AppendResult(interp, "MEMDB not available in this build",
3180 const char *zSchema = objc>=3 ? Tcl_GetString(objv[2]) : "main";
3181 sqlite3_int64 sz = 0;
3182 unsigned char *pData;
3183 if( objc!=2 && objc!=3 ){
3184 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE?");
3188 pData = sqlite3_serialize(pDb->db, zSchema, &sz, SQLITE_SERIALIZE_NOCOPY);
3192 pData = sqlite3_serialize(pDb->db, zSchema, &sz, 0);
3195 Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(pData,sz));
3196 if( needFree ) sqlite3_free(pData);
3203 ** $db status (step|sort|autoindex|vmstep)
3205 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
3206 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
3212 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
3215 zOp = Tcl_GetString(objv[2]);
3216 if( strcmp(zOp, "step")==0 ){
3218 }else if( strcmp(zOp, "sort")==0 ){
3220 }else if( strcmp(zOp, "autoindex")==0 ){
3222 }else if( strcmp(zOp, "vmstep")==0 ){
3225 Tcl_AppendResult(interp,
3226 "bad argument: should be autoindex, step, sort or vmstep",
3230 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
3235 ** $db timeout MILLESECONDS
3237 ** Delay for the number of milliseconds specified when a file is locked.
3242 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
3245 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
3246 sqlite3_busy_timeout(pDb->db, ms);
3251 ** $db total_changes
3253 ** Return the number of rows that were modified, inserted, or deleted
3254 ** since the database handle was created.
3256 case DB_TOTAL_CHANGES: {
3259 Tcl_WrongNumArgs(interp, 2, objv, "");
3262 pResult = Tcl_GetObjResult(interp);
3263 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
3267 /* $db trace ?CALLBACK?
3269 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
3270 ** that is executed. The text of the SQL is appended to CALLBACK before
3275 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
3277 }else if( objc==2 ){
3279 Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
3285 Tcl_Free(pDb->zTrace);
3287 zTrace = Tcl_GetStringFromObj(objv[2], &len);
3288 if( zTrace && len>0 ){
3289 pDb->zTrace = Tcl_Alloc( len + 1 );
3290 memcpy(pDb->zTrace, zTrace, len+1);
3294 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3295 !defined(SQLITE_OMIT_DEPRECATED)
3297 pDb->interp = interp;
3298 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
3300 sqlite3_trace(pDb->db, 0, 0);
3307 /* $db trace_v2 ?CALLBACK? ?MASK?
3309 ** Make arrangements to invoke the CALLBACK routine for each trace event
3310 ** matching the mask that is generated. The parameters are appended to
3311 ** CALLBACK before it is executed.
3315 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK? ?MASK?");
3317 }else if( objc==2 ){
3318 if( pDb->zTraceV2 ){
3319 Tcl_AppendResult(interp, pDb->zTraceV2, (char*)0);
3324 Tcl_WideInt wMask = 0;
3326 static const char *TTYPE_strs[] = {
3327 "statement", "profile", "row", "close", 0
3330 TTYPE_STMT, TTYPE_PROFILE, TTYPE_ROW, TTYPE_CLOSE
3333 if( TCL_OK!=Tcl_ListObjLength(interp, objv[3], &len) ){
3336 for(i=0; i<len; i++){
3339 if( TCL_OK!=Tcl_ListObjIndex(interp, objv[3], i, &pObj) ){
3342 if( Tcl_GetIndexFromObj(interp, pObj, TTYPE_strs, "trace type",
3343 0, &ttype)!=TCL_OK ){
3345 Tcl_Obj *pError = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
3346 Tcl_IncrRefCount(pError);
3347 if( TCL_OK==Tcl_GetWideIntFromObj(interp, pObj, &wType) ){
3348 Tcl_DecrRefCount(pError);
3351 Tcl_SetObjResult(interp, pError);
3352 Tcl_DecrRefCount(pError);
3356 switch( (enum TTYPE_enum)ttype ){
3357 case TTYPE_STMT: wMask |= SQLITE_TRACE_STMT; break;
3358 case TTYPE_PROFILE: wMask |= SQLITE_TRACE_PROFILE; break;
3359 case TTYPE_ROW: wMask |= SQLITE_TRACE_ROW; break;
3360 case TTYPE_CLOSE: wMask |= SQLITE_TRACE_CLOSE; break;
3365 wMask = SQLITE_TRACE_STMT; /* use the "legacy" default */
3367 if( pDb->zTraceV2 ){
3368 Tcl_Free(pDb->zTraceV2);
3370 zTraceV2 = Tcl_GetStringFromObj(objv[2], &len);
3371 if( zTraceV2 && len>0 ){
3372 pDb->zTraceV2 = Tcl_Alloc( len + 1 );
3373 memcpy(pDb->zTraceV2, zTraceV2, len+1);
3377 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3378 if( pDb->zTraceV2 ){
3379 pDb->interp = interp;
3380 sqlite3_trace_v2(pDb->db, (unsigned)wMask, DbTraceV2Handler, pDb);
3382 sqlite3_trace_v2(pDb->db, 0, 0, 0);
3389 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
3391 ** Start a new transaction (if we are not already in the midst of a
3392 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
3393 ** completes, either commit the transaction or roll it back if SCRIPT
3394 ** throws an exception. Or if no new transation was started, do nothing.
3395 ** pass the exception on up the stack.
3397 ** This command was inspired by Dave Thomas's talk on Ruby at the
3398 ** 2005 O'Reilly Open Source Convention (OSCON).
3400 case DB_TRANSACTION: {
3402 const char *zBegin = "SAVEPOINT _tcl_transaction";
3403 if( objc!=3 && objc!=4 ){
3404 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
3408 if( pDb->nTransaction==0 && objc==4 ){
3409 static const char *TTYPE_strs[] = {
3410 "deferred", "exclusive", "immediate", 0
3413 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
3416 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
3420 switch( (enum TTYPE_enum)ttype ){
3421 case TTYPE_DEFERRED: /* no-op */; break;
3422 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
3423 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
3426 pScript = objv[objc-1];
3428 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
3430 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
3432 if( rc!=SQLITE_OK ){
3433 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3436 pDb->nTransaction++;
3438 /* If using NRE, schedule a callback to invoke the script pScript, then
3439 ** a second callback to commit (or rollback) the transaction or savepoint
3440 ** opened above. If not using NRE, evaluate the script directly, then
3441 ** call function DbTransPostCmd() to commit (or rollback) the transaction
3444 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
3445 (void)Tcl_NREvalObj(interp, pScript, 0);
3447 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
3453 ** $db unlock_notify ?script?
3455 case DB_UNLOCK_NOTIFY: {
3456 #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
3457 Tcl_AppendResult(interp, "unlock_notify not available in this build",
3461 if( objc!=2 && objc!=3 ){
3462 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3465 void (*xNotify)(void **, int) = 0;
3466 void *pNotifyArg = 0;
3468 if( pDb->pUnlockNotify ){
3469 Tcl_DecrRefCount(pDb->pUnlockNotify);
3470 pDb->pUnlockNotify = 0;
3474 xNotify = DbUnlockNotify;
3475 pNotifyArg = (void *)pDb;
3476 pDb->pUnlockNotify = objv[2];
3477 Tcl_IncrRefCount(pDb->pUnlockNotify);
3480 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
3481 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3490 ** $db preupdate_hook count
3491 ** $db preupdate_hook hook ?SCRIPT?
3492 ** $db preupdate_hook new INDEX
3493 ** $db preupdate_hook old INDEX
3495 case DB_PREUPDATE: {
3496 #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
3497 Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time",
3501 static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
3502 enum DbPreupdateSubCmd {
3503 PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
3508 Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
3510 if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
3514 switch( (enum DbPreupdateSubCmd)iSub ){
3516 int nCol = sqlite3_preupdate_count(pDb->db);
3517 Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
3523 Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
3526 DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
3533 Tcl_WrongNumArgs(interp, 3, objv, "");
3536 pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
3537 Tcl_SetObjResult(interp, pRet);
3544 sqlite3_value *pValue;
3546 Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
3549 if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
3553 if( iSub==PRE_OLD ){
3554 rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
3556 assert( iSub==PRE_NEW );
3557 rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
3560 if( rc==SQLITE_OK ){
3562 pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
3563 Tcl_SetObjResult(interp, pObj);
3565 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3570 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
3575 ** $db wal_hook ?script?
3576 ** $db update_hook ?script?
3577 ** $db rollback_hook ?script?
3580 case DB_UPDATE_HOOK:
3581 case DB_ROLLBACK_HOOK: {
3582 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
3583 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3585 Tcl_Obj **ppHook = 0;
3586 if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
3587 if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
3588 if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
3590 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3594 DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
3600 ** Return the version string for this database.
3604 for(i=2; i<objc; i++){
3605 const char *zArg = Tcl_GetString(objv[i]);
3606 /* Optional arguments to $db version are used for testing purpose */
3608 /* $db version -use-legacy-prepare BOOLEAN
3610 ** Turn the use of legacy sqlite3_prepare() on or off.
3612 if( strcmp(zArg, "-use-legacy-prepare")==0 && i+1<objc ){
3614 if( Tcl_GetBooleanFromObj(interp, objv[i], &pDb->bLegacyPrepare) ){
3619 /* $db version -last-stmt-ptr
3621 ** Return a string which is a hex encoding of the pointer to the
3622 ** most recent sqlite3_stmt in the statement cache.
3624 if( strcmp(zArg, "-last-stmt-ptr")==0 ){
3626 sqlite3_snprintf(sizeof(zBuf), zBuf, "%p",
3627 pDb->stmtList ? pDb->stmtList->pStmt: 0);
3628 Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
3630 #endif /* SQLITE_TEST */
3632 Tcl_AppendResult(interp, "unknown argument: ", zArg, (char*)0);
3637 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
3643 } /* End of the SWITCH statement */
3649 ** Adaptor that provides an objCmd interface to the NRE-enabled
3650 ** interface implementation.
3652 static int SQLITE_TCLAPI DbObjCmdAdaptor(
3658 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
3660 #endif /* SQLITE_TCL_NRE */
3663 ** Issue the usage message when the "sqlite3" command arguments are
3666 static int sqliteCmdUsage(
3670 Tcl_WrongNumArgs(interp, 1, objv,
3671 "HANDLE ?FILENAME? ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
3672 " ?-nofollow BOOLEAN?"
3673 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
3679 ** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
3680 ** ?-create BOOLEAN? ?-nomutex BOOLEAN?
3681 ** ?-nofollow BOOLEAN?
3683 ** This is the main Tcl command. When the "sqlite" Tcl command is
3684 ** invoked, this routine runs to process that command.
3686 ** The first argument, DBNAME, is an arbitrary name for a new
3687 ** database connection. This command creates a new command named
3688 ** DBNAME that is used to control that connection. The database
3689 ** connection is deleted when the DBNAME command is deleted.
3691 ** The second argument is the name of the database file.
3694 static int SQLITE_TCLAPI DbMain(
3704 const char *zFile = 0;
3705 const char *zVfs = 0;
3707 int bTranslateFileName = 1;
3708 Tcl_DString translatedFilename;
3711 /* In normal use, each TCL interpreter runs in a single thread. So
3712 ** by default, we can turn off mutexing on SQLite database connections.
3713 ** However, for testing purposes it is useful to have mutexes turned
3714 ** on. So, by default, mutexes default off. But if compiled with
3715 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3717 #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3718 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3720 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3723 if( objc==1 ) return sqliteCmdUsage(interp, objv);
3725 zArg = Tcl_GetStringFromObj(objv[1], 0);
3726 if( strcmp(zArg,"-version")==0 ){
3727 Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
3730 if( strcmp(zArg,"-sourceid")==0 ){
3731 Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0);
3734 if( strcmp(zArg,"-has-codec")==0 ){
3735 Tcl_AppendResult(interp,"0",(char*)0);
3738 if( zArg[0]=='-' ) return sqliteCmdUsage(interp, objv);
3740 for(i=2; i<objc; i++){
3741 zArg = Tcl_GetString(objv[i]);
3743 if( zFile!=0 ) return sqliteCmdUsage(interp, objv);
3747 if( i==objc-1 ) return sqliteCmdUsage(interp, objv);
3749 if( strcmp(zArg,"-key")==0 ){
3751 }else if( strcmp(zArg, "-vfs")==0 ){
3752 zVfs = Tcl_GetString(objv[i]);
3753 }else if( strcmp(zArg, "-readonly")==0 ){
3755 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3757 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
3758 flags |= SQLITE_OPEN_READONLY;
3760 flags &= ~SQLITE_OPEN_READONLY;
3761 flags |= SQLITE_OPEN_READWRITE;
3763 }else if( strcmp(zArg, "-create")==0 ){
3765 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3766 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
3767 flags |= SQLITE_OPEN_CREATE;
3769 flags &= ~SQLITE_OPEN_CREATE;
3771 }else if( strcmp(zArg, "-nofollow")==0 ){
3773 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3775 flags |= SQLITE_OPEN_NOFOLLOW;
3777 flags &= ~SQLITE_OPEN_NOFOLLOW;
3779 }else if( strcmp(zArg, "-nomutex")==0 ){
3781 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3783 flags |= SQLITE_OPEN_NOMUTEX;
3784 flags &= ~SQLITE_OPEN_FULLMUTEX;
3786 flags &= ~SQLITE_OPEN_NOMUTEX;
3788 }else if( strcmp(zArg, "-fullmutex")==0 ){
3790 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3792 flags |= SQLITE_OPEN_FULLMUTEX;
3793 flags &= ~SQLITE_OPEN_NOMUTEX;
3795 flags &= ~SQLITE_OPEN_FULLMUTEX;
3797 }else if( strcmp(zArg, "-uri")==0 ){
3799 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3801 flags |= SQLITE_OPEN_URI;
3803 flags &= ~SQLITE_OPEN_URI;
3805 }else if( strcmp(zArg, "-translatefilename")==0 ){
3806 if( Tcl_GetBooleanFromObj(interp, objv[i], &bTranslateFileName) ){
3810 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3815 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
3816 memset(p, 0, sizeof(*p));
3817 if( zFile==0 ) zFile = "";
3818 if( bTranslateFileName ){
3819 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
3821 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
3822 if( bTranslateFileName ){
3823 Tcl_DStringFree(&translatedFilename);
3826 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3827 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3828 sqlite3_close(p->db);
3832 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
3835 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
3837 sqlite3_free(zErrMsg);
3840 p->maxStmt = NUM_PREPARED_STMTS;
3841 p->openFlags = flags & SQLITE_OPEN_URI;
3843 zArg = Tcl_GetStringFromObj(objv[1], 0);
3845 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3846 (char*)p, DbDeleteCmd);
3848 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3854 ** Provide a dummy Tcl_InitStubs if we are using this as a static
3857 #ifndef USE_TCL_STUBS
3858 # undef Tcl_InitStubs
3859 # define Tcl_InitStubs(a,b,c) TCL_VERSION
3863 ** Make sure we have a PACKAGE_VERSION macro defined. This will be
3864 ** defined automatically by the TEA makefile. But other makefiles
3865 ** do not define it.
3867 #ifndef PACKAGE_VERSION
3868 # define PACKAGE_VERSION SQLITE_VERSION
3872 ** Initialize this module.
3874 ** This Tcl module contains only a single new Tcl command named "sqlite".
3875 ** (Hence there is no namespace. There is no point in using a namespace
3876 ** if the extension only supplies one new name!) The "sqlite" command is
3877 ** used to open a new SQLite database. See the DbMain() routine above
3878 ** for additional information.
3880 ** The EXTERN macros are required by TCL in order to work on windows.
3882 EXTERN int Sqlite3_Init(Tcl_Interp *interp){
3883 int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
3885 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
3886 #ifndef SQLITE_3_SUFFIX_ONLY
3887 /* The "sqlite" alias is undocumented. It is here only to support
3888 ** legacy scripts. All new scripts should use only the "sqlite3"
3890 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
3892 rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3896 EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3897 EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3898 EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3900 /* Because it accesses the file-system and uses persistent state, SQLite
3901 ** is not considered appropriate for safe interpreters. Hence, we cause
3902 ** the _SafeInit() interfaces return TCL_ERROR.
3904 EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
3905 EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
3909 #ifndef SQLITE_3_SUFFIX_ONLY
3910 int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3911 int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3912 int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3913 int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3917 ** If the TCLSH macro is defined, add code to make a stand-alone program.
3921 /* This is the main routine for an ordinary TCL shell. If there are
3922 ** are arguments, run the first argument as a script. Otherwise,
3923 ** read TCL commands from standard input
3925 static const char *tclsh_main_loop(void){
3926 static const char zMainloop[] =
3927 "if {[llength $argv]>=1} {\n"
3928 "set argv0 [lindex $argv 0]\n"
3929 "set argv [lrange $argv 1 end]\n"
3933 "while {![eof stdin]} {\n"
3934 "if {$line!=\"\"} {\n"
3935 "puts -nonewline \"> \"\n"
3937 "puts -nonewline \"% \"\n"
3940 "append line [gets stdin]\n"
3941 "if {[info complete $line]} {\n"
3942 "if {[catch {uplevel #0 $line} result]} {\n"
3943 "puts stderr \"Error: $result\"\n"
3944 "} elseif {$result!=\"\"} {\n"
3957 #define TCLSH_MAIN main /* Needed to fake out mktclapp */
3958 int SQLITE_CDECL TCLSH_MAIN(int argc, char **argv){
3961 const char *zScript = 0;
3963 #if defined(TCLSH_INIT_PROC)
3964 extern const char *TCLSH_INIT_PROC(Tcl_Interp*);
3967 #if !defined(_WIN32_WCE)
3968 if( getenv("SQLITE_DEBUG_BREAK") ){
3969 if( isatty(0) && isatty(2) ){
3971 "attach debugger to process %d and press any key to continue.\n",
3975 #if defined(_WIN32) || defined(WIN32)
3977 #elif defined(SIGTRAP)
3984 /* Call sqlite3_shutdown() once before doing anything else. This is to
3985 ** test that sqlite3_shutdown() can be safely called by a process before
3986 ** sqlite3_initialize() is. */
3989 Tcl_FindExecutable(argv[0]);
3990 Tcl_SetSystemEncoding(NULL, "utf-8");
3991 interp = Tcl_CreateInterp();
3992 Sqlite3_Init(interp);
3994 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-1);
3995 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
3996 Tcl_SetVar(interp,"argv0",argv[0],TCL_GLOBAL_ONLY);
3997 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
3998 for(i=1; i<argc; i++){
3999 Tcl_SetVar(interp, "argv", argv[i],
4000 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
4002 #if defined(TCLSH_INIT_PROC)
4003 zScript = TCLSH_INIT_PROC(interp);
4006 zScript = tclsh_main_loop();
4008 if( Tcl_GlobalEval(interp, zScript)!=TCL_OK ){
4009 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
4010 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
4011 fprintf(stderr,"%s: %s\n", *argv, zInfo);