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 typedef struct SqlFunc SqlFunc;
104 Tcl_Interp *interp; /* The TCL interpret to execute the function */
105 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
106 SqliteDb *pDb; /* Database connection that owns this function */
107 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
108 char *zName; /* Name of this function */
109 SqlFunc *pNext; /* Next function on the list of them all */
113 ** New collation sequences function can be created as TCL scripts. Each such
114 ** function is described by an instance of the following structure.
116 typedef struct SqlCollate SqlCollate;
118 Tcl_Interp *interp; /* The TCL interpret to execute the function */
119 char *zScript; /* The script to be run */
120 SqlCollate *pNext; /* Next function on the list of them all */
124 ** Prepared statements are cached for faster execution. Each prepared
125 ** statement is described by an instance of the following structure.
127 typedef struct SqlPreparedStmt SqlPreparedStmt;
128 struct SqlPreparedStmt {
129 SqlPreparedStmt *pNext; /* Next in linked list */
130 SqlPreparedStmt *pPrev; /* Previous on the list */
131 sqlite3_stmt *pStmt; /* The prepared statement */
132 int nSql; /* chars in zSql[] */
133 const char *zSql; /* Text of the SQL statement */
134 int nParm; /* Size of apParm array */
135 Tcl_Obj **apParm; /* Array of referenced object pointers */
138 typedef struct IncrblobChannel IncrblobChannel;
141 ** There is one instance of this structure for each SQLite database
142 ** that has been opened by the SQLite TCL interface.
144 ** If this module is built with SQLITE_TEST defined (to create the SQLite
145 ** testfixture executable), then it may be configured to use either
146 ** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
147 ** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
150 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
151 Tcl_Interp *interp; /* The interpreter used for this database */
152 char *zBusy; /* The busy callback routine */
153 char *zCommit; /* The commit hook callback routine */
154 char *zTrace; /* The trace callback routine */
155 char *zTraceV2; /* The trace_v2 callback routine */
156 char *zProfile; /* The profile callback routine */
157 char *zProgress; /* The progress callback routine */
158 char *zAuth; /* The authorization callback routine */
159 int disableAuth; /* Disable the authorizer if it exists */
160 char *zNull; /* Text to substitute for an SQL NULL value */
161 SqlFunc *pFunc; /* List of SQL functions */
162 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
163 Tcl_Obj *pPreUpdateHook; /* Pre-update hook script (if any) */
164 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
165 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
166 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
167 SqlCollate *pCollate; /* List of SQL collation functions */
168 int rc; /* Return code of most recent sqlite3_exec() */
169 Tcl_Obj *pCollateNeeded; /* Collation needed script */
170 SqlPreparedStmt *stmtList; /* List of prepared statements*/
171 SqlPreparedStmt *stmtLast; /* Last statement in the list */
172 int maxStmt; /* The next maximum number of stmtList */
173 int nStmt; /* Number of statements in stmtList */
174 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
175 int nStep, nSort, nIndex; /* Statistics for most recent operation */
176 int nVMStep; /* Another statistic for most recent operation */
177 int nTransaction; /* Number of nested [transaction] methods */
178 int openFlags; /* Flags used to open. (SQLITE_OPEN_URI) */
180 int bLegacyPrepare; /* True to use sqlite3_prepare() */
184 struct IncrblobChannel {
185 sqlite3_blob *pBlob; /* sqlite3 blob handle */
186 SqliteDb *pDb; /* Associated database connection */
187 int iSeek; /* Current seek offset */
188 Tcl_Channel channel; /* Channel identifier */
189 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
190 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
194 ** Compute a string length that is limited to what can be stored in
195 ** lower 30 bits of a 32-bit signed integer.
197 static int strlen30(const char *z){
199 while( *z2 ){ z2++; }
200 return 0x3fffffff & (int)(z2 - z);
204 #ifndef SQLITE_OMIT_INCRBLOB
206 ** Close all incrblob channels opened using database connection pDb.
207 ** This is called when shutting down the database connection.
209 static void closeIncrblobChannels(SqliteDb *pDb){
211 IncrblobChannel *pNext;
213 for(p=pDb->pIncrblob; p; p=pNext){
216 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
217 ** which deletes the IncrblobChannel structure at *p. So do not
218 ** call Tcl_Free() here.
220 Tcl_UnregisterChannel(pDb->interp, p->channel);
225 ** Close an incremental blob channel.
227 static int SQLITE_TCLAPI incrblobClose(
228 ClientData instanceData,
231 IncrblobChannel *p = (IncrblobChannel *)instanceData;
232 int rc = sqlite3_blob_close(p->pBlob);
233 sqlite3 *db = p->pDb->db;
235 /* Remove the channel from the SqliteDb.pIncrblob list. */
237 p->pNext->pPrev = p->pPrev;
240 p->pPrev->pNext = p->pNext;
242 if( p->pDb->pIncrblob==p ){
243 p->pDb->pIncrblob = p->pNext;
246 /* Free the IncrblobChannel structure */
250 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
257 ** Read data from an incremental blob channel.
259 static int SQLITE_TCLAPI incrblobInput(
260 ClientData instanceData,
265 IncrblobChannel *p = (IncrblobChannel *)instanceData;
266 int nRead = bufSize; /* Number of bytes to read */
267 int nBlob; /* Total size of the blob */
268 int rc; /* sqlite error code */
270 nBlob = sqlite3_blob_bytes(p->pBlob);
271 if( (p->iSeek+nRead)>nBlob ){
272 nRead = nBlob-p->iSeek;
278 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
289 ** Write data to an incremental blob channel.
291 static int SQLITE_TCLAPI incrblobOutput(
292 ClientData instanceData,
297 IncrblobChannel *p = (IncrblobChannel *)instanceData;
298 int nWrite = toWrite; /* Number of bytes to write */
299 int nBlob; /* Total size of the blob */
300 int rc; /* sqlite error code */
302 nBlob = sqlite3_blob_bytes(p->pBlob);
303 if( (p->iSeek+nWrite)>nBlob ){
304 *errorCodePtr = EINVAL;
311 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
322 ** Seek an incremental blob channel.
324 static int SQLITE_TCLAPI incrblobSeek(
325 ClientData instanceData,
330 IncrblobChannel *p = (IncrblobChannel *)instanceData;
340 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
343 default: assert(!"Bad seekMode");
350 static void SQLITE_TCLAPI incrblobWatch(
351 ClientData instanceData,
356 static int SQLITE_TCLAPI incrblobHandle(
357 ClientData instanceData,
364 static Tcl_ChannelType IncrblobChannelType = {
365 "incrblob", /* typeName */
366 TCL_CHANNEL_VERSION_2, /* version */
367 incrblobClose, /* closeProc */
368 incrblobInput, /* inputProc */
369 incrblobOutput, /* outputProc */
370 incrblobSeek, /* seekProc */
371 0, /* setOptionProc */
372 0, /* getOptionProc */
373 incrblobWatch, /* watchProc (this is a no-op) */
374 incrblobHandle, /* getHandleProc (always returns error) */
376 0, /* blockModeProc */
379 0, /* wideSeekProc */
383 ** Create a new incrblob channel.
385 static int createIncrblobChannel(
395 sqlite3 *db = pDb->db;
398 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
400 /* This variable is used to name the channels: "incrblob_[incr count]" */
401 static int count = 0;
404 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
406 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
410 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
414 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
415 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
416 Tcl_RegisterChannel(interp, p->channel);
418 /* Link the new channel into the SqliteDb.pIncrblob list. */
419 p->pNext = pDb->pIncrblob;
427 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
430 #else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
431 #define closeIncrblobChannels(pDb)
435 ** Look at the script prefix in pCmd. We will be executing this script
436 ** after first appending one or more arguments. This routine analyzes
437 ** the script to see if it is safe to use Tcl_EvalObjv() on the script
438 ** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
441 ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
442 ** command name followed by zero or more arguments with no [...] or $
443 ** or {...} or ; to be seen anywhere. Most callback scripts consist
444 ** of just a single procedure name and they meet this requirement.
446 static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
447 /* We could try to do something with Tcl_Parse(). But we will instead
448 ** just do a search for forbidden characters. If any of the forbidden
449 ** characters appear in pCmd, we will report the string as unsafe.
453 z = Tcl_GetStringFromObj(pCmd, &n);
456 if( c=='$' || c=='[' || c==';' ) return 0;
462 ** Find an SqlFunc structure with the given name. Or create a new
463 ** one if an existing one cannot be found. Return a pointer to the
466 static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
468 int nName = strlen30(zName);
469 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
470 pNew->zName = (char*)&pNew[1];
471 memcpy(pNew->zName, zName, nName+1);
472 for(p=pDb->pFunc; p; p=p->pNext){
473 if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
474 Tcl_Free((char*)pNew);
478 pNew->interp = pDb->interp;
481 pNew->pNext = pDb->pFunc;
487 ** Free a single SqlPreparedStmt object.
489 static void dbFreeStmt(SqlPreparedStmt *pStmt){
491 if( sqlite3_sql(pStmt->pStmt)==0 ){
492 Tcl_Free((char *)pStmt->zSql);
495 sqlite3_finalize(pStmt->pStmt);
496 Tcl_Free((char *)pStmt);
500 ** Finalize and free a list of prepared statements
502 static void flushStmtCache(SqliteDb *pDb){
503 SqlPreparedStmt *pPreStmt;
504 SqlPreparedStmt *pNext;
506 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
507 pNext = pPreStmt->pNext;
508 dbFreeStmt(pPreStmt);
516 ** TCL calls this procedure when an sqlite3 database command is
519 static void SQLITE_TCLAPI DbDeleteCmd(void *db){
520 SqliteDb *pDb = (SqliteDb*)db;
522 closeIncrblobChannels(pDb);
523 sqlite3_close(pDb->db);
525 SqlFunc *pFunc = pDb->pFunc;
526 pDb->pFunc = pFunc->pNext;
527 assert( pFunc->pDb==pDb );
528 Tcl_DecrRefCount(pFunc->pScript);
529 Tcl_Free((char*)pFunc);
531 while( pDb->pCollate ){
532 SqlCollate *pCollate = pDb->pCollate;
533 pDb->pCollate = pCollate->pNext;
534 Tcl_Free((char*)pCollate);
537 Tcl_Free(pDb->zBusy);
540 Tcl_Free(pDb->zTrace);
543 Tcl_Free(pDb->zTraceV2);
546 Tcl_Free(pDb->zProfile);
549 Tcl_Free(pDb->zAuth);
552 Tcl_Free(pDb->zNull);
554 if( pDb->pUpdateHook ){
555 Tcl_DecrRefCount(pDb->pUpdateHook);
557 if( pDb->pPreUpdateHook ){
558 Tcl_DecrRefCount(pDb->pPreUpdateHook);
560 if( pDb->pRollbackHook ){
561 Tcl_DecrRefCount(pDb->pRollbackHook);
564 Tcl_DecrRefCount(pDb->pWalHook);
566 if( pDb->pCollateNeeded ){
567 Tcl_DecrRefCount(pDb->pCollateNeeded);
569 Tcl_Free((char*)pDb);
573 ** This routine is called when a database file is locked while trying
576 static int DbBusyHandler(void *cd, int nTries){
577 SqliteDb *pDb = (SqliteDb*)cd;
581 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
582 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
583 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
589 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
591 ** This routine is invoked as the 'progress callback' for the database.
593 static int DbProgressHandler(void *cd){
594 SqliteDb *pDb = (SqliteDb*)cd;
597 assert( pDb->zProgress );
598 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
599 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
606 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
607 !defined(SQLITE_OMIT_DEPRECATED)
609 ** This routine is called by the SQLite trace handler whenever a new
610 ** block of SQL is executed. The TCL script in pDb->zTrace is executed.
612 static void DbTraceHandler(void *cd, const char *zSql){
613 SqliteDb *pDb = (SqliteDb*)cd;
616 Tcl_DStringInit(&str);
617 Tcl_DStringAppend(&str, pDb->zTrace, -1);
618 Tcl_DStringAppendElement(&str, zSql);
619 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
620 Tcl_DStringFree(&str);
621 Tcl_ResetResult(pDb->interp);
625 #ifndef SQLITE_OMIT_TRACE
627 ** This routine is called by the SQLite trace_v2 handler whenever a new
628 ** supported event is generated. Unsupported event types are ignored.
629 ** The TCL script in pDb->zTraceV2 is executed, with the arguments for
630 ** the event appended to it (as list elements).
632 static int DbTraceV2Handler(
633 unsigned type, /* One of the SQLITE_TRACE_* event types. */
634 void *cd, /* The original context data pointer. */
635 void *pd, /* Primary event data, depends on event type. */
636 void *xd /* Extra event data, depends on event type. */
638 SqliteDb *pDb = (SqliteDb*)cd;
642 case SQLITE_TRACE_STMT: {
643 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
644 char *zSql = (char *)xd;
646 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
647 Tcl_IncrRefCount(pCmd);
648 Tcl_ListObjAppendElement(pDb->interp, pCmd,
649 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
650 Tcl_ListObjAppendElement(pDb->interp, pCmd,
651 Tcl_NewStringObj(zSql, -1));
652 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
653 Tcl_DecrRefCount(pCmd);
654 Tcl_ResetResult(pDb->interp);
657 case SQLITE_TRACE_PROFILE: {
658 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
659 sqlite3_int64 ns = *(sqlite3_int64*)xd;
661 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
662 Tcl_IncrRefCount(pCmd);
663 Tcl_ListObjAppendElement(pDb->interp, pCmd,
664 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
665 Tcl_ListObjAppendElement(pDb->interp, pCmd,
666 Tcl_NewWideIntObj((Tcl_WideInt)ns));
667 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
668 Tcl_DecrRefCount(pCmd);
669 Tcl_ResetResult(pDb->interp);
672 case SQLITE_TRACE_ROW: {
673 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
675 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
676 Tcl_IncrRefCount(pCmd);
677 Tcl_ListObjAppendElement(pDb->interp, pCmd,
678 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
679 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
680 Tcl_DecrRefCount(pCmd);
681 Tcl_ResetResult(pDb->interp);
684 case SQLITE_TRACE_CLOSE: {
685 sqlite3 *db = (sqlite3 *)pd;
687 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
688 Tcl_IncrRefCount(pCmd);
689 Tcl_ListObjAppendElement(pDb->interp, pCmd,
690 Tcl_NewWideIntObj((Tcl_WideInt)db));
691 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
692 Tcl_DecrRefCount(pCmd);
693 Tcl_ResetResult(pDb->interp);
701 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
702 !defined(SQLITE_OMIT_DEPRECATED)
704 ** This routine is called by the SQLite profile handler after a statement
705 ** SQL has executed. The TCL script in pDb->zProfile is evaluated.
707 static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
708 SqliteDb *pDb = (SqliteDb*)cd;
712 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
713 Tcl_DStringInit(&str);
714 Tcl_DStringAppend(&str, pDb->zProfile, -1);
715 Tcl_DStringAppendElement(&str, zSql);
716 Tcl_DStringAppendElement(&str, zTm);
717 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
718 Tcl_DStringFree(&str);
719 Tcl_ResetResult(pDb->interp);
724 ** This routine is called when a transaction is committed. The
725 ** TCL script in pDb->zCommit is executed. If it returns non-zero or
726 ** if it throws an exception, the transaction is rolled back instead
727 ** of being committed.
729 static int DbCommitHandler(void *cd){
730 SqliteDb *pDb = (SqliteDb*)cd;
733 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
734 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
740 static void DbRollbackHandler(void *clientData){
741 SqliteDb *pDb = (SqliteDb*)clientData;
742 assert(pDb->pRollbackHook);
743 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
744 Tcl_BackgroundError(pDb->interp);
749 ** This procedure handles wal_hook callbacks.
751 static int DbWalHandler(
759 SqliteDb *pDb = (SqliteDb*)clientData;
760 Tcl_Interp *interp = pDb->interp;
761 assert(pDb->pWalHook);
763 assert( db==pDb->db );
764 p = Tcl_DuplicateObj(pDb->pWalHook);
766 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
767 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
768 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
769 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
771 Tcl_BackgroundError(interp);
778 #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
779 static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
781 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
782 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
783 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
784 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
787 # define setTestUnlockNotifyVars(x,y,z)
790 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
791 static void DbUnlockNotify(void **apArg, int nArg){
793 for(i=0; i<nArg; i++){
794 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
795 SqliteDb *pDb = (SqliteDb *)apArg[i];
796 setTestUnlockNotifyVars(pDb->interp, i, nArg);
797 assert( pDb->pUnlockNotify);
798 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
799 Tcl_DecrRefCount(pDb->pUnlockNotify);
800 pDb->pUnlockNotify = 0;
805 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
807 ** Pre-update hook callback.
809 static void DbPreUpdateHandler(
818 SqliteDb *pDb = (SqliteDb *)p;
820 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
822 assert( (SQLITE_DELETE-1)/9 == 0 );
823 assert( (SQLITE_INSERT-1)/9 == 1 );
824 assert( (SQLITE_UPDATE-1)/9 == 2 );
825 assert( pDb->pPreUpdateHook );
826 assert( db==pDb->db );
827 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
829 pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
830 Tcl_IncrRefCount(pCmd);
831 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
832 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
833 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
834 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
835 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
836 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
837 Tcl_DecrRefCount(pCmd);
839 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
841 static void DbUpdateHandler(
848 SqliteDb *pDb = (SqliteDb *)p;
850 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
852 assert( (SQLITE_DELETE-1)/9 == 0 );
853 assert( (SQLITE_INSERT-1)/9 == 1 );
854 assert( (SQLITE_UPDATE-1)/9 == 2 );
856 assert( pDb->pUpdateHook );
857 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
859 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
860 Tcl_IncrRefCount(pCmd);
861 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
862 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
863 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
864 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
865 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
866 Tcl_DecrRefCount(pCmd);
869 static void tclCollateNeeded(
875 SqliteDb *pDb = (SqliteDb *)pCtx;
876 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
877 Tcl_IncrRefCount(pScript);
878 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
879 Tcl_EvalObjEx(pDb->interp, pScript, 0);
880 Tcl_DecrRefCount(pScript);
884 ** This routine is called to evaluate an SQL collation function implemented
887 static int tclSqlCollate(
894 SqlCollate *p = (SqlCollate *)pCtx;
897 pCmd = Tcl_NewStringObj(p->zScript, -1);
898 Tcl_IncrRefCount(pCmd);
899 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
900 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
901 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
902 Tcl_DecrRefCount(pCmd);
903 return (atoi(Tcl_GetStringResult(p->interp)));
907 ** This routine is called to evaluate an SQL function implemented
910 static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
911 SqlFunc *p = sqlite3_user_data(context);
917 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
918 ** script object directly. This allows the TCL compiler to generate
919 ** bytecode for the command on the first invocation and thus make
920 ** subsequent invocations much faster. */
922 Tcl_IncrRefCount(pCmd);
923 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
924 Tcl_DecrRefCount(pCmd);
926 /* If there are arguments to the function, make a shallow copy of the
927 ** script object, lappend the arguments, then evaluate the copy.
929 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
930 ** The new Tcl_Obj contains pointers to the original list elements.
931 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
932 ** of the list to tclCmdNameType, that alternate representation will
933 ** be preserved and reused on the next invocation.
937 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
938 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
941 pCmd = Tcl_NewListObj(nArg, aArg);
942 Tcl_IncrRefCount(pCmd);
943 for(i=0; i<argc; i++){
944 sqlite3_value *pIn = argv[i];
947 /* Set pVal to contain the i'th column of this row. */
948 switch( sqlite3_value_type(pIn) ){
950 int bytes = sqlite3_value_bytes(pIn);
951 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
954 case SQLITE_INTEGER: {
955 sqlite_int64 v = sqlite3_value_int64(pIn);
956 if( v>=-2147483647 && v<=2147483647 ){
957 pVal = Tcl_NewIntObj((int)v);
959 pVal = Tcl_NewWideIntObj(v);
964 double r = sqlite3_value_double(pIn);
965 pVal = Tcl_NewDoubleObj(r);
969 pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
973 int bytes = sqlite3_value_bytes(pIn);
974 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
978 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
980 Tcl_DecrRefCount(pCmd);
981 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
985 if( !p->useEvalObjv ){
986 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
987 ** is a list without a string representation. To prevent this from
988 ** happening, make sure pCmd has a valid string representation */
991 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
992 Tcl_DecrRefCount(pCmd);
995 if( rc && rc!=TCL_RETURN ){
996 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
998 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
1001 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1003 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
1004 /* Only return a BLOB type if the Tcl variable is a bytearray and
1005 ** has no string representation. */
1006 data = Tcl_GetByteArrayFromObj(pVar, &n);
1007 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
1008 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1009 Tcl_GetIntFromObj(0, pVar, &n);
1010 sqlite3_result_int(context, n);
1011 }else if( c=='d' && strcmp(zType,"double")==0 ){
1013 Tcl_GetDoubleFromObj(0, pVar, &r);
1014 sqlite3_result_double(context, r);
1015 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1016 (c=='i' && strcmp(zType,"int")==0) ){
1018 Tcl_GetWideIntFromObj(0, pVar, &v);
1019 sqlite3_result_int64(context, v);
1021 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1022 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
1027 #ifndef SQLITE_OMIT_AUTHORIZATION
1029 ** This is the authentication function. It appends the authentication
1030 ** type code and the two arguments to zCmd[] then invokes the result
1031 ** on the interpreter. The reply is examined to determine if the
1032 ** authentication fails or succeeds.
1034 static int auth_callback(
1041 #ifdef SQLITE_USER_AUTHENTICATION
1049 /* EVIDENCE-OF: R-38590-62769 The first parameter to the authorizer
1050 ** callback is a copy of the third parameter to the
1051 ** sqlite3_set_authorizer() interface.
1053 SqliteDb *pDb = (SqliteDb*)pArg;
1054 if( pDb->disableAuth ) return SQLITE_OK;
1056 /* EVIDENCE-OF: R-56518-44310 The second parameter to the callback is an
1057 ** integer action code that specifies the particular action to be
1060 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
1061 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
1062 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
1063 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
1064 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
1065 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
1066 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
1067 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
1068 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
1069 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
1070 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
1071 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
1072 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
1073 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
1074 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
1075 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
1076 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
1077 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
1078 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
1079 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
1080 case SQLITE_READ : zCode="SQLITE_READ"; break;
1081 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
1082 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
1083 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
1084 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
1085 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
1086 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
1087 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
1088 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
1089 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
1090 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
1091 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
1092 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
1093 case SQLITE_RECURSIVE : zCode="SQLITE_RECURSIVE"; break;
1094 default : zCode="????"; break;
1096 Tcl_DStringInit(&str);
1097 Tcl_DStringAppend(&str, pDb->zAuth, -1);
1098 Tcl_DStringAppendElement(&str, zCode);
1099 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
1100 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
1101 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
1102 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
1103 #ifdef SQLITE_USER_AUTHENTICATION
1104 Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
1106 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
1107 Tcl_DStringFree(&str);
1108 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
1109 if( strcmp(zReply,"SQLITE_OK")==0 ){
1111 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
1113 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
1120 #endif /* SQLITE_OMIT_AUTHORIZATION */
1123 ** This routine reads a line of text from FILE in, stores
1124 ** the text in memory obtained from malloc() and returns a pointer
1125 ** to the text. NULL is returned at end of file, or if malloc()
1128 ** The interface is like "readline" but no command-line editing
1131 ** copied from shell.c from '.import' command
1133 static char *local_getline(char *zPrompt, FILE *in){
1139 zLine = malloc( nLine );
1140 if( zLine==0 ) return 0;
1144 nLine = nLine*2 + 100;
1145 zLine = realloc(zLine, nLine);
1146 if( zLine==0 ) return 0;
1148 if( fgets(&zLine[n], nLine - n, in)==0 ){
1156 while( zLine[n] ){ n++; }
1157 if( n>0 && zLine[n-1]=='\n' ){
1163 zLine = realloc( zLine, n+1 );
1169 ** This function is part of the implementation of the command:
1171 ** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1173 ** It is invoked after evaluating the script SCRIPT to commit or rollback
1174 ** the transaction or savepoint opened by the [transaction] command.
1176 static int SQLITE_TCLAPI DbTransPostCmd(
1177 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1178 Tcl_Interp *interp, /* Tcl interpreter */
1179 int result /* Result of evaluating SCRIPT */
1181 static const char *const azEnd[] = {
1182 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1183 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1184 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1185 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1187 SqliteDb *pDb = (SqliteDb*)data[0];
1191 pDb->nTransaction--;
1192 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1195 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1196 /* This is a tricky scenario to handle. The most likely cause of an
1197 ** error is that the exec() above was an attempt to commit the
1198 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1199 ** that an IO-error has occurred. In either case, throw a Tcl exception
1200 ** and try to rollback the transaction.
1202 ** But it could also be that the user executed one or more BEGIN,
1203 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1204 ** this method's logic. Not clear how this would be best handled.
1206 if( rc!=TCL_ERROR ){
1207 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
1210 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1218 ** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1219 ** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1220 ** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1221 ** on whether or not the [db_use_legacy_prepare] command has been used to
1222 ** configure the connection.
1224 static int dbPrepare(
1225 SqliteDb *pDb, /* Database object */
1226 const char *zSql, /* SQL to compile */
1227 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1228 const char **pzOut /* OUT: Pointer to next SQL statement */
1230 unsigned int prepFlags = 0;
1232 if( pDb->bLegacyPrepare ){
1233 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1236 /* If the statement cache is large, use the SQLITE_PREPARE_PERSISTENT
1237 ** flags, which uses less lookaside memory. But if the cache is small,
1238 ** omit that flag to make full use of lookaside */
1239 if( pDb->maxStmt>5 ) prepFlags = SQLITE_PREPARE_PERSISTENT;
1241 return sqlite3_prepare_v3(pDb->db, zSql, -1, prepFlags, ppStmt, pzOut);
1245 ** Search the cache for a prepared-statement object that implements the
1246 ** first SQL statement in the buffer pointed to by parameter zIn. If
1247 ** no such prepared-statement can be found, allocate and prepare a new
1248 ** one. In either case, bind the current values of the relevant Tcl
1249 ** variables to any $var, :var or @var variables in the statement. Before
1250 ** returning, set *ppPreStmt to point to the prepared-statement object.
1252 ** Output parameter *pzOut is set to point to the next SQL statement in
1253 ** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1256 ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1257 ** and an error message loaded into interpreter pDb->interp.
1259 static int dbPrepareAndBind(
1260 SqliteDb *pDb, /* Database object */
1261 char const *zIn, /* SQL to compile */
1262 char const **pzOut, /* OUT: Pointer to next SQL statement */
1263 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1265 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
1266 sqlite3_stmt *pStmt = 0; /* Prepared statement object */
1267 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1268 int nSql; /* Length of zSql in bytes */
1269 int nVar = 0; /* Number of variables in statement */
1270 int iParm = 0; /* Next free entry in apParm */
1273 Tcl_Interp *interp = pDb->interp;
1277 /* Trim spaces from the start of zSql and calculate the remaining length. */
1278 while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
1279 nSql = strlen30(zSql);
1281 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1282 int n = pPreStmt->nSql;
1284 && memcmp(pPreStmt->zSql, zSql, n)==0
1285 && (zSql[n]==0 || zSql[n-1]==';')
1287 pStmt = pPreStmt->pStmt;
1288 *pzOut = &zSql[pPreStmt->nSql];
1290 /* When a prepared statement is found, unlink it from the
1291 ** cache list. It will later be added back to the beginning
1292 ** of the cache list in order to implement LRU replacement.
1294 if( pPreStmt->pPrev ){
1295 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1297 pDb->stmtList = pPreStmt->pNext;
1299 if( pPreStmt->pNext ){
1300 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1302 pDb->stmtLast = pPreStmt->pPrev;
1305 nVar = sqlite3_bind_parameter_count(pStmt);
1310 /* If no prepared statement was found. Compile the SQL text. Also allocate
1311 ** a new SqlPreparedStmt structure. */
1315 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
1316 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1320 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1321 /* A compile-time error in the statement. */
1322 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1325 /* The statement was a no-op. Continue to the next statement
1326 ** in the SQL string.
1332 assert( pPreStmt==0 );
1333 nVar = sqlite3_bind_parameter_count(pStmt);
1334 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1335 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1336 memset(pPreStmt, 0, nByte);
1338 pPreStmt->pStmt = pStmt;
1339 pPreStmt->nSql = (int)(*pzOut - zSql);
1340 pPreStmt->zSql = sqlite3_sql(pStmt);
1341 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
1343 if( pPreStmt->zSql==0 ){
1344 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1345 memcpy(zCopy, zSql, pPreStmt->nSql);
1346 zCopy[pPreStmt->nSql] = '\0';
1347 pPreStmt->zSql = zCopy;
1352 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1353 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1355 /* Bind values to parameters that begin with $ or : */
1356 for(i=1; i<=nVar; i++){
1357 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1358 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1359 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1363 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1366 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1367 /* Load a BLOB type if the Tcl variable is a bytearray and
1368 ** it has no string representation or the host
1369 ** parameter name begins with "@". */
1370 data = Tcl_GetByteArrayFromObj(pVar, &n);
1371 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1372 Tcl_IncrRefCount(pVar);
1373 pPreStmt->apParm[iParm++] = pVar;
1374 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1375 Tcl_GetIntFromObj(interp, pVar, &n);
1376 sqlite3_bind_int(pStmt, i, n);
1377 }else if( c=='d' && strcmp(zType,"double")==0 ){
1379 Tcl_GetDoubleFromObj(interp, pVar, &r);
1380 sqlite3_bind_double(pStmt, i, r);
1381 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1382 (c=='i' && strcmp(zType,"int")==0) ){
1384 Tcl_GetWideIntFromObj(interp, pVar, &v);
1385 sqlite3_bind_int64(pStmt, i, v);
1387 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1388 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1389 Tcl_IncrRefCount(pVar);
1390 pPreStmt->apParm[iParm++] = pVar;
1393 sqlite3_bind_null(pStmt, i);
1397 pPreStmt->nParm = iParm;
1398 *ppPreStmt = pPreStmt;
1404 ** Release a statement reference obtained by calling dbPrepareAndBind().
1405 ** There should be exactly one call to this function for each call to
1406 ** dbPrepareAndBind().
1408 ** If the discard parameter is non-zero, then the statement is deleted
1409 ** immediately. Otherwise it is added to the LRU list and may be returned
1410 ** by a subsequent call to dbPrepareAndBind().
1412 static void dbReleaseStmt(
1413 SqliteDb *pDb, /* Database handle */
1414 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1415 int discard /* True to delete (not cache) the pPreStmt */
1419 /* Free the bound string and blob parameters */
1420 for(i=0; i<pPreStmt->nParm; i++){
1421 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1423 pPreStmt->nParm = 0;
1425 if( pDb->maxStmt<=0 || discard ){
1426 /* If the cache is turned off, deallocated the statement */
1427 dbFreeStmt(pPreStmt);
1429 /* Add the prepared statement to the beginning of the cache list. */
1430 pPreStmt->pNext = pDb->stmtList;
1431 pPreStmt->pPrev = 0;
1432 if( pDb->stmtList ){
1433 pDb->stmtList->pPrev = pPreStmt;
1435 pDb->stmtList = pPreStmt;
1436 if( pDb->stmtLast==0 ){
1437 assert( pDb->nStmt==0 );
1438 pDb->stmtLast = pPreStmt;
1440 assert( pDb->nStmt>0 );
1444 /* If we have too many statement in cache, remove the surplus from
1445 ** the end of the cache list. */
1446 while( pDb->nStmt>pDb->maxStmt ){
1447 SqlPreparedStmt *pLast = pDb->stmtLast;
1448 pDb->stmtLast = pLast->pPrev;
1449 pDb->stmtLast->pNext = 0;
1457 ** Structure used with dbEvalXXX() functions:
1463 ** dbEvalColumnValue()
1465 typedef struct DbEvalContext DbEvalContext;
1466 struct DbEvalContext {
1467 SqliteDb *pDb; /* Database handle */
1468 Tcl_Obj *pSql; /* Object holding string zSql */
1469 const char *zSql; /* Remaining SQL to execute */
1470 SqlPreparedStmt *pPreStmt; /* Current statement */
1471 int nCol; /* Number of columns returned by pStmt */
1472 int evalFlags; /* Flags used */
1473 Tcl_Obj *pArray; /* Name of array variable */
1474 Tcl_Obj **apColName; /* Array of column names */
1477 #define SQLITE_EVAL_WITHOUTNULLS 0x00001 /* Unset array(*) for NULL */
1480 ** Release any cache of column names currently held as part of
1481 ** the DbEvalContext structure passed as the first argument.
1483 static void dbReleaseColumnNames(DbEvalContext *p){
1486 for(i=0; i<p->nCol; i++){
1487 Tcl_DecrRefCount(p->apColName[i]);
1489 Tcl_Free((char *)p->apColName);
1496 ** Initialize a DbEvalContext structure.
1498 ** If pArray is not NULL, then it contains the name of a Tcl array
1499 ** variable. The "*" member of this array is set to a list containing
1500 ** the names of the columns returned by the statement as part of each
1501 ** call to dbEvalStep(), in order from left to right. e.g. if the names
1502 ** of the returned columns are a, b and c, it does the equivalent of the
1505 ** set ${pArray}(*) {a b c}
1507 static void dbEvalInit(
1508 DbEvalContext *p, /* Pointer to structure to initialize */
1509 SqliteDb *pDb, /* Database handle */
1510 Tcl_Obj *pSql, /* Object containing SQL script */
1511 Tcl_Obj *pArray, /* Name of Tcl array to set (*) element of */
1512 int evalFlags /* Flags controlling evaluation */
1514 memset(p, 0, sizeof(DbEvalContext));
1516 p->zSql = Tcl_GetString(pSql);
1518 Tcl_IncrRefCount(pSql);
1521 Tcl_IncrRefCount(pArray);
1523 p->evalFlags = evalFlags;
1527 ** Obtain information about the row that the DbEvalContext passed as the
1528 ** first argument currently points to.
1530 static void dbEvalRowInfo(
1531 DbEvalContext *p, /* Evaluation context */
1532 int *pnCol, /* OUT: Number of column names */
1533 Tcl_Obj ***papColName /* OUT: Array of column names */
1535 /* Compute column names */
1536 if( 0==p->apColName ){
1537 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1538 int i; /* Iterator variable */
1539 int nCol; /* Number of columns returned by pStmt */
1540 Tcl_Obj **apColName = 0; /* Array of column names */
1542 p->nCol = nCol = sqlite3_column_count(pStmt);
1543 if( nCol>0 && (papColName || p->pArray) ){
1544 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1545 for(i=0; i<nCol; i++){
1546 apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
1547 Tcl_IncrRefCount(apColName[i]);
1549 p->apColName = apColName;
1552 /* If results are being stored in an array variable, then create
1553 ** the array(*) entry for that array
1556 Tcl_Interp *interp = p->pDb->interp;
1557 Tcl_Obj *pColList = Tcl_NewObj();
1558 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
1560 for(i=0; i<nCol; i++){
1561 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1563 Tcl_IncrRefCount(pStar);
1564 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
1565 Tcl_DecrRefCount(pStar);
1570 *papColName = p->apColName;
1578 ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1579 ** returned, then an error message is stored in the interpreter before
1582 ** A return value of TCL_OK means there is a row of data available. The
1583 ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1584 ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1585 ** is returned, then the SQL script has finished executing and there are
1586 ** no further rows available. This is similar to SQLITE_DONE.
1588 static int dbEvalStep(DbEvalContext *p){
1589 const char *zPrevSql = 0; /* Previous value of p->zSql */
1591 while( p->zSql[0] || p->pPreStmt ){
1593 if( p->pPreStmt==0 ){
1594 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
1595 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1596 if( rc!=TCL_OK ) return rc;
1599 SqliteDb *pDb = p->pDb;
1600 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1601 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1603 rcs = sqlite3_step(pStmt);
1604 if( rcs==SQLITE_ROW ){
1608 dbEvalRowInfo(p, 0, 0);
1610 rcs = sqlite3_reset(pStmt);
1612 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1613 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
1614 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
1615 pDb->nVMStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_VM_STEP,1);
1616 dbReleaseColumnNames(p);
1619 if( rcs!=SQLITE_OK ){
1620 /* If a run-time error occurs, report the error and stop reading
1622 dbReleaseStmt(pDb, pPreStmt, 1);
1624 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1625 /* If the runtime error was an SQLITE_SCHEMA, and the database
1626 ** handle is configured to use the legacy sqlite3_prepare()
1627 ** interface, retry prepare()/step() on the same SQL statement.
1628 ** This only happens once. If there is a second SQLITE_SCHEMA
1629 ** error, the error will be returned to the caller. */
1634 Tcl_SetObjResult(pDb->interp,
1635 Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1638 dbReleaseStmt(pDb, pPreStmt, 0);
1648 ** Free all resources currently held by the DbEvalContext structure passed
1649 ** as the first argument. There should be exactly one call to this function
1650 ** for each call to dbEvalInit().
1652 static void dbEvalFinalize(DbEvalContext *p){
1654 sqlite3_reset(p->pPreStmt->pStmt);
1655 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1659 Tcl_DecrRefCount(p->pArray);
1662 Tcl_DecrRefCount(p->pSql);
1663 dbReleaseColumnNames(p);
1667 ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1668 ** the value for the iCol'th column of the row currently pointed to by
1669 ** the DbEvalContext structure passed as the first argument.
1671 static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1672 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1673 switch( sqlite3_column_type(pStmt, iCol) ){
1675 int bytes = sqlite3_column_bytes(pStmt, iCol);
1676 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1677 if( !zBlob ) bytes = 0;
1678 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1680 case SQLITE_INTEGER: {
1681 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1682 if( v>=-2147483647 && v<=2147483647 ){
1683 return Tcl_NewIntObj((int)v);
1685 return Tcl_NewWideIntObj(v);
1688 case SQLITE_FLOAT: {
1689 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1692 return Tcl_NewStringObj(p->pDb->zNull, -1);
1696 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
1700 ** If using Tcl version 8.6 or greater, use the NR functions to avoid
1701 ** recursive evalution of scripts by the [db eval] and [db trans]
1702 ** commands. Even if the headers used while compiling the extension
1703 ** are 8.6 or newer, the code still tests the Tcl version at runtime.
1704 ** This allows stubs-enabled builds to be used with older Tcl libraries.
1706 #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
1707 # define SQLITE_TCL_NRE 1
1708 static int DbUseNre(void){
1710 Tcl_GetVersion(&major, &minor, 0, 0);
1711 return( (major==8 && minor>=6) || major>8 );
1715 ** Compiling using headers earlier than 8.6. In this case NR cannot be
1716 ** used, so DbUseNre() to always return zero. Add #defines for the other
1717 ** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1718 ** even though the only invocations of them are within conditional blocks
1721 ** if( DbUseNre() ) { ... }
1723 # define SQLITE_TCL_NRE 0
1724 # define DbUseNre() 0
1725 # define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
1726 # define Tcl_NREvalObj(a,b,c) 0
1727 # define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
1731 ** This function is part of the implementation of the command:
1733 ** $db eval SQL ?ARRAYNAME? SCRIPT
1735 static int SQLITE_TCLAPI DbEvalNextCmd(
1736 ClientData data[], /* data[0] is the (DbEvalContext*) */
1737 Tcl_Interp *interp, /* Tcl interpreter */
1738 int result /* Result so far */
1740 int rc = result; /* Return code */
1742 /* The first element of the data[] array is a pointer to a DbEvalContext
1743 ** structure allocated using Tcl_Alloc(). The second element of data[]
1744 ** is a pointer to a Tcl_Obj containing the script to run for each row
1745 ** returned by the queries encapsulated in data[0]. */
1746 DbEvalContext *p = (DbEvalContext *)data[0];
1747 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1748 Tcl_Obj *pArray = p->pArray;
1750 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1753 Tcl_Obj **apColName;
1754 dbEvalRowInfo(p, &nCol, &apColName);
1755 for(i=0; i<nCol; i++){
1757 Tcl_ObjSetVar2(interp, apColName[i], 0, dbEvalColumnValue(p,i), 0);
1758 }else if( (p->evalFlags & SQLITE_EVAL_WITHOUTNULLS)!=0
1759 && sqlite3_column_type(p->pPreStmt->pStmt, i)==SQLITE_NULL
1761 Tcl_UnsetVar2(interp, Tcl_GetString(pArray),
1762 Tcl_GetString(apColName[i]), 0);
1764 Tcl_ObjSetVar2(interp, pArray, apColName[i], dbEvalColumnValue(p,i), 0);
1768 /* The required interpreter variables are now populated with the data
1769 ** from the current row. If using NRE, schedule callbacks to evaluate
1770 ** script pScript, then to invoke this function again to fetch the next
1771 ** row (or clean up if there is no next row or the script throws an
1772 ** exception). After scheduling the callbacks, return control to the
1775 ** If not using NRE, evaluate pScript directly and continue with the
1776 ** next iteration of this while(...) loop. */
1778 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1779 return Tcl_NREvalObj(interp, pScript, 0);
1781 rc = Tcl_EvalObjEx(interp, pScript, 0);
1785 Tcl_DecrRefCount(pScript);
1787 Tcl_Free((char *)p);
1789 if( rc==TCL_OK || rc==TCL_BREAK ){
1790 Tcl_ResetResult(interp);
1797 ** This function is used by the implementations of the following database
1798 ** handle sub-commands:
1800 ** $db update_hook ?SCRIPT?
1801 ** $db wal_hook ?SCRIPT?
1802 ** $db commit_hook ?SCRIPT?
1803 ** $db preupdate hook ?SCRIPT?
1805 static void DbHookCmd(
1806 Tcl_Interp *interp, /* Tcl interpreter */
1807 SqliteDb *pDb, /* Database handle */
1808 Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */
1809 Tcl_Obj **ppHook /* Pointer to member of SqliteDb */
1811 sqlite3 *db = pDb->db;
1814 Tcl_SetObjResult(interp, *ppHook);
1816 Tcl_DecrRefCount(*ppHook);
1821 assert( !(*ppHook) );
1822 if( Tcl_GetCharLength(pArg)>0 ){
1824 Tcl_IncrRefCount(*ppHook);
1828 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1829 sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
1831 sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1832 sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1833 sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
1837 ** The "sqlite" command below creates a new Tcl command for each
1838 ** connection it opens to an SQLite database. This routine is invoked
1839 ** whenever one of those connection-specific commands is executed
1840 ** in Tcl. For example, if you run Tcl code like this:
1842 ** sqlite3 db1 "my_database"
1845 ** The first command opens a connection to the "my_database" database
1846 ** and calls that connection "db1". The second command causes this
1847 ** subroutine to be invoked.
1849 static int SQLITE_TCLAPI DbObjCmd(
1855 SqliteDb *pDb = (SqliteDb*)cd;
1858 static const char *DB_strs[] = {
1859 "authorizer", "backup", "busy",
1860 "cache", "changes", "close",
1861 "collate", "collation_needed", "commit_hook",
1862 "complete", "copy", "deserialize",
1863 "enable_load_extension", "errorcode", "eval",
1864 "exists", "function", "incrblob",
1865 "interrupt", "last_insert_rowid", "nullvalue",
1866 "onecolumn", "preupdate", "profile",
1867 "progress", "rekey", "restore",
1868 "rollback_hook", "serialize", "status",
1869 "timeout", "total_changes", "trace",
1870 "trace_v2", "transaction", "unlock_notify",
1871 "update_hook", "version", "wal_hook",
1875 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1876 DB_CACHE, DB_CHANGES, DB_CLOSE,
1877 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1878 DB_COMPLETE, DB_COPY, DB_DESERIALIZE,
1879 DB_ENABLE_LOAD_EXTENSION, DB_ERRORCODE, DB_EVAL,
1880 DB_EXISTS, DB_FUNCTION, DB_INCRBLOB,
1881 DB_INTERRUPT, DB_LAST_INSERT_ROWID, DB_NULLVALUE,
1882 DB_ONECOLUMN, DB_PREUPDATE, DB_PROFILE,
1883 DB_PROGRESS, DB_REKEY, DB_RESTORE,
1884 DB_ROLLBACK_HOOK, DB_SERIALIZE, DB_STATUS,
1885 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
1886 DB_TRACE_V2, DB_TRANSACTION, DB_UNLOCK_NOTIFY,
1887 DB_UPDATE_HOOK, DB_VERSION, DB_WAL_HOOK
1889 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
1892 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
1895 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
1899 switch( (enum DB_enum)choice ){
1901 /* $db authorizer ?CALLBACK?
1903 ** Invoke the given callback to authorize each SQL operation as it is
1904 ** compiled. 5 arguments are appended to the callback before it is
1907 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1908 ** (2) First descriptive name (depends on authorization type)
1909 ** (3) Second descriptive name
1910 ** (4) Name of the database (ex: "main", "temp")
1911 ** (5) Name of trigger that is doing the access
1913 ** The callback should return on of the following strings: SQLITE_OK,
1914 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1916 ** If this method is invoked with no arguments, the current authorization
1917 ** callback string is returned.
1919 case DB_AUTHORIZER: {
1920 #ifdef SQLITE_OMIT_AUTHORIZATION
1921 Tcl_AppendResult(interp, "authorization not available in this build",
1926 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1928 }else if( objc==2 ){
1930 Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
1936 Tcl_Free(pDb->zAuth);
1938 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1939 if( zAuth && len>0 ){
1940 pDb->zAuth = Tcl_Alloc( len + 1 );
1941 memcpy(pDb->zAuth, zAuth, len+1);
1946 typedef int (*sqlite3_auth_cb)(
1947 void*,int,const char*,const char*,
1948 const char*,const char*);
1949 pDb->interp = interp;
1950 sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
1952 sqlite3_set_authorizer(pDb->db, 0, 0);
1959 /* $db backup ?DATABASE? FILENAME
1961 ** Open or create a database file named FILENAME. Transfer the
1962 ** content of local database DATABASE (default: "main") into the
1963 ** FILENAME database.
1966 const char *zDestFile;
1969 sqlite3_backup *pBackup;
1973 zDestFile = Tcl_GetString(objv[2]);
1974 }else if( objc==4 ){
1975 zSrcDb = Tcl_GetString(objv[2]);
1976 zDestFile = Tcl_GetString(objv[3]);
1978 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1981 rc = sqlite3_open_v2(zDestFile, &pDest,
1982 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
1983 if( rc!=SQLITE_OK ){
1984 Tcl_AppendResult(interp, "cannot open target database: ",
1985 sqlite3_errmsg(pDest), (char*)0);
1986 sqlite3_close(pDest);
1989 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1991 Tcl_AppendResult(interp, "backup failed: ",
1992 sqlite3_errmsg(pDest), (char*)0);
1993 sqlite3_close(pDest);
1996 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1997 sqlite3_backup_finish(pBackup);
1998 if( rc==SQLITE_DONE ){
2001 Tcl_AppendResult(interp, "backup failed: ",
2002 sqlite3_errmsg(pDest), (char*)0);
2005 sqlite3_close(pDest);
2009 /* $db busy ?CALLBACK?
2011 ** Invoke the given callback if an SQL statement attempts to open
2012 ** a locked database file.
2016 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
2018 }else if( objc==2 ){
2020 Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
2026 Tcl_Free(pDb->zBusy);
2028 zBusy = Tcl_GetStringFromObj(objv[2], &len);
2029 if( zBusy && len>0 ){
2030 pDb->zBusy = Tcl_Alloc( len + 1 );
2031 memcpy(pDb->zBusy, zBusy, len+1);
2036 pDb->interp = interp;
2037 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
2039 sqlite3_busy_handler(pDb->db, 0, 0);
2048 ** Flush the prepared statement cache, or set the maximum number of
2049 ** cached statements.
2056 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
2059 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
2060 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
2062 Tcl_WrongNumArgs(interp, 2, objv, "flush");
2065 flushStmtCache( pDb );
2067 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
2069 Tcl_WrongNumArgs(interp, 2, objv, "size n");
2072 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
2073 Tcl_AppendResult( interp, "cannot convert \"",
2074 Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
2078 flushStmtCache( pDb );
2080 }else if( n>MAX_PREPARED_STMTS ){
2081 n = MAX_PREPARED_STMTS;
2087 Tcl_AppendResult( interp, "bad option \"",
2088 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
2097 ** Return the number of rows that were modified, inserted, or deleted by
2098 ** the most recent INSERT, UPDATE or DELETE statement, not including
2099 ** any changes made by trigger programs.
2104 Tcl_WrongNumArgs(interp, 2, objv, "");
2107 pResult = Tcl_GetObjResult(interp);
2108 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
2114 ** Shutdown the database
2117 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
2122 ** $db collate NAME SCRIPT
2124 ** Create a new SQL collation function called NAME. Whenever
2125 ** that function is called, invoke SCRIPT to evaluate the function.
2128 SqlCollate *pCollate;
2133 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
2136 zName = Tcl_GetStringFromObj(objv[2], 0);
2137 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
2138 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
2139 if( pCollate==0 ) return TCL_ERROR;
2140 pCollate->interp = interp;
2141 pCollate->pNext = pDb->pCollate;
2142 pCollate->zScript = (char*)&pCollate[1];
2143 pDb->pCollate = pCollate;
2144 memcpy(pCollate->zScript, zScript, nScript+1);
2145 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
2146 pCollate, tclSqlCollate) ){
2147 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
2154 ** $db collation_needed SCRIPT
2156 ** Create a new SQL collation function called NAME. Whenever
2157 ** that function is called, invoke SCRIPT to evaluate the function.
2159 case DB_COLLATION_NEEDED: {
2161 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
2164 if( pDb->pCollateNeeded ){
2165 Tcl_DecrRefCount(pDb->pCollateNeeded);
2167 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
2168 Tcl_IncrRefCount(pDb->pCollateNeeded);
2169 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
2173 /* $db commit_hook ?CALLBACK?
2175 ** Invoke the given callback just before committing every SQL transaction.
2176 ** If the callback throws an exception or returns non-zero, then the
2177 ** transaction is aborted. If CALLBACK is an empty string, the callback
2180 case DB_COMMIT_HOOK: {
2182 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2184 }else if( objc==2 ){
2186 Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
2189 const char *zCommit;
2192 Tcl_Free(pDb->zCommit);
2194 zCommit = Tcl_GetStringFromObj(objv[2], &len);
2195 if( zCommit && len>0 ){
2196 pDb->zCommit = Tcl_Alloc( len + 1 );
2197 memcpy(pDb->zCommit, zCommit, len+1);
2202 pDb->interp = interp;
2203 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
2205 sqlite3_commit_hook(pDb->db, 0, 0);
2213 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2214 ** additional lines of input are needed. This is similar to the
2215 ** built-in "info complete" command of Tcl.
2218 #ifndef SQLITE_OMIT_COMPLETE
2222 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2225 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
2226 pResult = Tcl_GetObjResult(interp);
2227 Tcl_SetBooleanObj(pResult, isComplete);
2232 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2234 ** Copy data into table from filename, optionally using SEPARATOR
2235 ** as column separators. If a column contains a null string, or the
2236 ** value of NULLINDICATOR, a NULL is inserted for the column.
2237 ** conflict-algorithm is one of the sqlite conflict algorithms:
2238 ** rollback, abort, fail, ignore, replace
2239 ** On success, return the number of lines processed, not necessarily same
2240 ** as 'db changes' due to conflict-algorithm selected.
2242 ** This code is basically an implementation/enhancement of
2243 ** the sqlite3 shell.c ".import" command.
2245 ** This command usage is equivalent to the sqlite2.x COPY statement,
2246 ** which imports file data into a table using the PostgreSQL COPY file format:
2247 ** $db copy $conflit_algo $table_name $filename \t \\N
2250 char *zTable; /* Insert data into this table */
2251 char *zFile; /* The file from which to extract data */
2252 char *zConflict; /* The conflict algorithm to use */
2253 sqlite3_stmt *pStmt; /* A statement */
2254 int nCol; /* Number of columns in the table */
2255 int nByte; /* Number of bytes in an SQL string */
2256 int i, j; /* Loop counters */
2257 int nSep; /* Number of bytes in zSep[] */
2258 int nNull; /* Number of bytes in zNull[] */
2259 char *zSql; /* An SQL statement */
2260 char *zLine; /* A single line of input from the file */
2261 char **azCol; /* zLine[] broken up into columns */
2262 const char *zCommit; /* How to commit changes */
2263 FILE *in; /* The input file */
2264 int lineno = 0; /* Line number of input file */
2265 char zLineNum[80]; /* Line number print buffer */
2266 Tcl_Obj *pResult; /* interp result */
2270 if( objc<5 || objc>7 ){
2271 Tcl_WrongNumArgs(interp, 2, objv,
2272 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2276 zSep = Tcl_GetStringFromObj(objv[5], 0);
2281 zNull = Tcl_GetStringFromObj(objv[6], 0);
2285 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2286 zTable = Tcl_GetStringFromObj(objv[3], 0);
2287 zFile = Tcl_GetStringFromObj(objv[4], 0);
2288 nSep = strlen30(zSep);
2289 nNull = strlen30(zNull);
2291 Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2295 if(strcmp(zConflict, "rollback") != 0 &&
2296 strcmp(zConflict, "abort" ) != 0 &&
2297 strcmp(zConflict, "fail" ) != 0 &&
2298 strcmp(zConflict, "ignore" ) != 0 &&
2299 strcmp(zConflict, "replace" ) != 0 ) {
2300 Tcl_AppendResult(interp, "Error: \"", zConflict,
2301 "\", conflict-algorithm must be one of: rollback, "
2302 "abort, fail, ignore, or replace", (char*)0);
2305 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2307 Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
2310 nByte = strlen30(zSql);
2311 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
2314 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2317 nCol = sqlite3_column_count(pStmt);
2319 sqlite3_finalize(pStmt);
2323 zSql = malloc( nByte + 50 + nCol*2 );
2325 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
2328 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2331 for(i=1; i<nCol; i++){
2337 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
2340 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2341 sqlite3_finalize(pStmt);
2344 in = fopen(zFile, "rb");
2346 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, (char*)0);
2347 sqlite3_finalize(pStmt);
2350 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2352 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
2356 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
2358 while( (zLine = local_getline(0, in))!=0 ){
2362 for(i=0, z=zLine; *z; z++){
2363 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2367 azCol[i] = &z[nSep];
2374 int nErr = strlen30(zFile) + 200;
2375 zErr = malloc(nErr);
2377 sqlite3_snprintf(nErr, zErr,
2378 "Error: %s line %d: expected %d columns of data but found %d",
2379 zFile, lineno, nCol, i+1);
2380 Tcl_AppendResult(interp, zErr, (char*)0);
2383 zCommit = "ROLLBACK";
2386 for(i=0; i<nCol; i++){
2387 /* check for null data, if so, bind as null */
2388 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
2389 || strlen30(azCol[i])==0
2391 sqlite3_bind_null(pStmt, i+1);
2393 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2396 sqlite3_step(pStmt);
2397 rc = sqlite3_reset(pStmt);
2399 if( rc!=SQLITE_OK ){
2400 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2401 zCommit = "ROLLBACK";
2407 sqlite3_finalize(pStmt);
2408 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
2410 if( zCommit[0] == 'C' ){
2411 /* success, set result as number of lines processed */
2412 pResult = Tcl_GetObjResult(interp);
2413 Tcl_SetIntObj(pResult, lineno);
2416 /* failure, append lineno where failed */
2417 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
2418 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2426 ** $db deserialize ?DATABASE? VALUE
2428 ** Reopen DATABASE (default "main") using the content in $VALUE
2430 case DB_DESERIALIZE: {
2431 #ifndef SQLITE_ENABLE_DESERIALIZE
2432 Tcl_AppendResult(interp, "MEMDB not available in this build",
2436 const char *zSchema;
2439 unsigned char *pData;
2445 }else if( objc==4 ){
2446 zSchema = Tcl_GetString(objv[2]);
2449 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? VALUE");
2453 pBA = Tcl_GetByteArrayFromObj(pValue, &len);
2454 pData = sqlite3_malloc64( len );
2455 if( pData==0 && len>0 ){
2456 Tcl_AppendResult(interp, "out of memory", (char*)0);
2459 if( len>0 ) memcpy(pData, pBA, len);
2460 xrc = sqlite3_deserialize(pDb->db, zSchema, pData, len, len,
2461 SQLITE_DESERIALIZE_FREEONCLOSE |
2462 SQLITE_DESERIALIZE_RESIZEABLE);
2464 Tcl_AppendResult(interp, "unable to set MEMDB content", (char*)0);
2473 ** $db enable_load_extension BOOLEAN
2475 ** Turn the extension loading feature on or off. It if off by
2478 case DB_ENABLE_LOAD_EXTENSION: {
2479 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2482 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2485 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2488 sqlite3_enable_load_extension(pDb->db, onoff);
2491 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2500 ** Return the numeric error code that was returned by the most recent
2501 ** call to sqlite3_exec().
2503 case DB_ERRORCODE: {
2504 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
2510 ** $db onecolumn $sql
2512 ** The onecolumn method is the equivalent of:
2513 ** lindex [$db eval $sql] 0
2516 case DB_ONECOLUMN: {
2517 Tcl_Obj *pResult = 0;
2518 DbEvalContext sEval;
2520 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2524 dbEvalInit(&sEval, pDb, objv[2], 0, 0);
2525 rc = dbEvalStep(&sEval);
2526 if( choice==DB_ONECOLUMN ){
2528 pResult = dbEvalColumnValue(&sEval, 0);
2529 }else if( rc==TCL_BREAK ){
2530 Tcl_ResetResult(interp);
2532 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2533 pResult = Tcl_NewBooleanObj(rc==TCL_OK);
2535 dbEvalFinalize(&sEval);
2536 if( pResult ) Tcl_SetObjResult(interp, pResult);
2538 if( rc==TCL_BREAK ){
2545 ** $db eval ?options? $sql ?array? ?{ ...code... }?
2547 ** The SQL statement in $sql is evaluated. For each row, the values are
2548 ** placed in elements of the array named "array" and ...code... is executed.
2549 ** If "array" and "code" are omitted, then no callback is every invoked.
2550 ** If "array" is an empty string, then the values are placed in variables
2551 ** that have the same name as the fields extracted by the query.
2556 while( objc>3 && (zOpt = Tcl_GetString(objv[2]))!=0 && zOpt[0]=='-' ){
2557 if( strcmp(zOpt, "-withoutnulls")==0 ){
2558 evalFlags |= SQLITE_EVAL_WITHOUTNULLS;
2561 Tcl_AppendResult(interp, "unknown option: \"", zOpt, "\"", (void*)0);
2567 if( objc<3 || objc>5 ){
2568 Tcl_WrongNumArgs(interp, 2, objv,
2569 "?OPTIONS? SQL ?ARRAY-NAME? ?SCRIPT?");
2574 DbEvalContext sEval;
2575 Tcl_Obj *pRet = Tcl_NewObj();
2576 Tcl_IncrRefCount(pRet);
2577 dbEvalInit(&sEval, pDb, objv[2], 0, 0);
2578 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2581 dbEvalRowInfo(&sEval, &nCol, 0);
2582 for(i=0; i<nCol; i++){
2583 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
2586 dbEvalFinalize(&sEval);
2587 if( rc==TCL_BREAK ){
2588 Tcl_SetObjResult(interp, pRet);
2591 Tcl_DecrRefCount(pRet);
2595 Tcl_Obj *pArray = 0;
2598 if( objc>=5 && *(char *)Tcl_GetString(objv[3]) ){
2601 pScript = objv[objc-1];
2602 Tcl_IncrRefCount(pScript);
2604 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2605 dbEvalInit(p, pDb, objv[2], pArray, evalFlags);
2608 cd2[1] = (void *)pScript;
2609 rc = DbEvalNextCmd(cd2, interp, TCL_OK);
2615 ** $db function NAME [-argcount N] [-deterministic] SCRIPT
2617 ** Create a new SQL function called NAME. Whenever that function is
2618 ** called, invoke SCRIPT to evaluate the function.
2621 int flags = SQLITE_UTF8;
2628 Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
2631 for(i=3; i<(objc-1); i++){
2632 const char *z = Tcl_GetString(objv[i]);
2633 int n = strlen30(z);
2634 if( n>2 && strncmp(z, "-argcount",n)==0 ){
2636 Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0);
2639 if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
2641 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2647 if( n>2 && strncmp(z, "-deterministic",n)==0 ){
2648 flags |= SQLITE_DETERMINISTIC;
2650 Tcl_AppendResult(interp, "bad option \"", z,
2651 "\": must be -argcount or -deterministic", (char*)0
2657 pScript = objv[objc-1];
2658 zName = Tcl_GetStringFromObj(objv[2], 0);
2659 pFunc = findSqlFunc(pDb, zName);
2660 if( pFunc==0 ) return TCL_ERROR;
2661 if( pFunc->pScript ){
2662 Tcl_DecrRefCount(pFunc->pScript);
2664 pFunc->pScript = pScript;
2665 Tcl_IncrRefCount(pScript);
2666 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
2667 rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
2668 pFunc, tclSqlFunc, 0, 0);
2669 if( rc!=SQLITE_OK ){
2671 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
2677 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
2680 #ifdef SQLITE_OMIT_INCRBLOB
2681 Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
2685 const char *zDb = "main";
2687 const char *zColumn;
2690 /* Check for the -readonly option */
2691 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2695 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2696 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
2700 if( objc==(6+isReadonly) ){
2701 zDb = Tcl_GetString(objv[2]);
2703 zTable = Tcl_GetString(objv[objc-3]);
2704 zColumn = Tcl_GetString(objv[objc-2]);
2705 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2708 rc = createIncrblobChannel(
2709 interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
2719 ** Interrupt the execution of the inner-most SQL interpreter. This
2720 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2722 case DB_INTERRUPT: {
2723 sqlite3_interrupt(pDb->db);
2728 ** $db nullvalue ?STRING?
2730 ** Change text used when a NULL comes back from the database. If ?STRING?
2731 ** is not present, then the current string used for NULL is returned.
2732 ** If STRING is present, then STRING is returned.
2735 case DB_NULLVALUE: {
2736 if( objc!=2 && objc!=3 ){
2737 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2742 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2744 Tcl_Free(pDb->zNull);
2746 if( zNull && len>0 ){
2747 pDb->zNull = Tcl_Alloc( len + 1 );
2748 memcpy(pDb->zNull, zNull, len);
2749 pDb->zNull[len] = '\0';
2754 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
2759 ** $db last_insert_rowid
2761 ** Return an integer which is the ROWID for the most recent insert.
2763 case DB_LAST_INSERT_ROWID: {
2767 Tcl_WrongNumArgs(interp, 2, objv, "");
2770 rowid = sqlite3_last_insert_rowid(pDb->db);
2771 pResult = Tcl_GetObjResult(interp);
2772 Tcl_SetWideIntObj(pResult, rowid);
2777 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
2780 /* $db progress ?N CALLBACK?
2782 ** Invoke the given callback every N virtual machine opcodes while executing
2787 if( pDb->zProgress ){
2788 Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
2790 }else if( objc==4 ){
2794 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
2797 if( pDb->zProgress ){
2798 Tcl_Free(pDb->zProgress);
2800 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2801 if( zProgress && len>0 ){
2802 pDb->zProgress = Tcl_Alloc( len + 1 );
2803 memcpy(pDb->zProgress, zProgress, len+1);
2807 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2808 if( pDb->zProgress ){
2809 pDb->interp = interp;
2810 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2812 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2816 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
2822 /* $db profile ?CALLBACK?
2824 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2825 ** that has run. The text of the SQL and the amount of elapse time are
2826 ** appended to CALLBACK before the script is run.
2830 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2832 }else if( objc==2 ){
2833 if( pDb->zProfile ){
2834 Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
2839 if( pDb->zProfile ){
2840 Tcl_Free(pDb->zProfile);
2842 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2843 if( zProfile && len>0 ){
2844 pDb->zProfile = Tcl_Alloc( len + 1 );
2845 memcpy(pDb->zProfile, zProfile, len+1);
2849 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
2850 !defined(SQLITE_OMIT_DEPRECATED)
2851 if( pDb->zProfile ){
2852 pDb->interp = interp;
2853 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2855 sqlite3_profile(pDb->db, 0, 0);
2865 ** Change the encryption key on the currently open database.
2868 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
2873 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2876 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
2877 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
2878 rc = sqlite3_rekey(pDb->db, pKey, nKey);
2880 Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
2887 /* $db restore ?DATABASE? FILENAME
2889 ** Open a database file named FILENAME. Transfer the content
2890 ** of FILENAME into the local database DATABASE (default: "main").
2893 const char *zSrcFile;
2894 const char *zDestDb;
2896 sqlite3_backup *pBackup;
2901 zSrcFile = Tcl_GetString(objv[2]);
2902 }else if( objc==4 ){
2903 zDestDb = Tcl_GetString(objv[2]);
2904 zSrcFile = Tcl_GetString(objv[3]);
2906 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2909 rc = sqlite3_open_v2(zSrcFile, &pSrc,
2910 SQLITE_OPEN_READONLY | pDb->openFlags, 0);
2911 if( rc!=SQLITE_OK ){
2912 Tcl_AppendResult(interp, "cannot open source database: ",
2913 sqlite3_errmsg(pSrc), (char*)0);
2914 sqlite3_close(pSrc);
2917 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2919 Tcl_AppendResult(interp, "restore failed: ",
2920 sqlite3_errmsg(pDb->db), (char*)0);
2921 sqlite3_close(pSrc);
2924 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2925 || rc==SQLITE_BUSY ){
2926 if( rc==SQLITE_BUSY ){
2927 if( nTimeout++ >= 3 ) break;
2931 sqlite3_backup_finish(pBackup);
2932 if( rc==SQLITE_DONE ){
2934 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2935 Tcl_AppendResult(interp, "restore failed: source database busy",
2939 Tcl_AppendResult(interp, "restore failed: ",
2940 sqlite3_errmsg(pDb->db), (char*)0);
2943 sqlite3_close(pSrc);
2948 ** $db serialize ?DATABASE?
2950 ** Return a serialization of a database.
2952 case DB_SERIALIZE: {
2953 #ifndef SQLITE_ENABLE_DESERIALIZE
2954 Tcl_AppendResult(interp, "MEMDB not available in this build",
2958 const char *zSchema = objc>=3 ? Tcl_GetString(objv[2]) : "main";
2959 sqlite3_int64 sz = 0;
2960 unsigned char *pData;
2961 if( objc!=2 && objc!=3 ){
2962 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE?");
2966 pData = sqlite3_serialize(pDb->db, zSchema, &sz, SQLITE_SERIALIZE_NOCOPY);
2970 pData = sqlite3_serialize(pDb->db, zSchema, &sz, 0);
2973 Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(pData,sz));
2974 if( needFree ) sqlite3_free(pData);
2981 ** $db status (step|sort|autoindex|vmstep)
2983 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2984 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2990 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
2993 zOp = Tcl_GetString(objv[2]);
2994 if( strcmp(zOp, "step")==0 ){
2996 }else if( strcmp(zOp, "sort")==0 ){
2998 }else if( strcmp(zOp, "autoindex")==0 ){
3000 }else if( strcmp(zOp, "vmstep")==0 ){
3003 Tcl_AppendResult(interp,
3004 "bad argument: should be autoindex, step, sort or vmstep",
3008 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
3013 ** $db timeout MILLESECONDS
3015 ** Delay for the number of milliseconds specified when a file is locked.
3020 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
3023 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
3024 sqlite3_busy_timeout(pDb->db, ms);
3029 ** $db total_changes
3031 ** Return the number of rows that were modified, inserted, or deleted
3032 ** since the database handle was created.
3034 case DB_TOTAL_CHANGES: {
3037 Tcl_WrongNumArgs(interp, 2, objv, "");
3040 pResult = Tcl_GetObjResult(interp);
3041 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
3045 /* $db trace ?CALLBACK?
3047 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
3048 ** that is executed. The text of the SQL is appended to CALLBACK before
3053 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
3055 }else if( objc==2 ){
3057 Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
3063 Tcl_Free(pDb->zTrace);
3065 zTrace = Tcl_GetStringFromObj(objv[2], &len);
3066 if( zTrace && len>0 ){
3067 pDb->zTrace = Tcl_Alloc( len + 1 );
3068 memcpy(pDb->zTrace, zTrace, len+1);
3072 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3073 !defined(SQLITE_OMIT_DEPRECATED)
3075 pDb->interp = interp;
3076 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
3078 sqlite3_trace(pDb->db, 0, 0);
3085 /* $db trace_v2 ?CALLBACK? ?MASK?
3087 ** Make arrangements to invoke the CALLBACK routine for each trace event
3088 ** matching the mask that is generated. The parameters are appended to
3089 ** CALLBACK before it is executed.
3093 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK? ?MASK?");
3095 }else if( objc==2 ){
3096 if( pDb->zTraceV2 ){
3097 Tcl_AppendResult(interp, pDb->zTraceV2, (char*)0);
3102 Tcl_WideInt wMask = 0;
3104 static const char *TTYPE_strs[] = {
3105 "statement", "profile", "row", "close", 0
3108 TTYPE_STMT, TTYPE_PROFILE, TTYPE_ROW, TTYPE_CLOSE
3111 if( TCL_OK!=Tcl_ListObjLength(interp, objv[3], &len) ){
3114 for(i=0; i<len; i++){
3117 if( TCL_OK!=Tcl_ListObjIndex(interp, objv[3], i, &pObj) ){
3120 if( Tcl_GetIndexFromObj(interp, pObj, TTYPE_strs, "trace type",
3121 0, &ttype)!=TCL_OK ){
3123 Tcl_Obj *pError = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
3124 Tcl_IncrRefCount(pError);
3125 if( TCL_OK==Tcl_GetWideIntFromObj(interp, pObj, &wType) ){
3126 Tcl_DecrRefCount(pError);
3129 Tcl_SetObjResult(interp, pError);
3130 Tcl_DecrRefCount(pError);
3134 switch( (enum TTYPE_enum)ttype ){
3135 case TTYPE_STMT: wMask |= SQLITE_TRACE_STMT; break;
3136 case TTYPE_PROFILE: wMask |= SQLITE_TRACE_PROFILE; break;
3137 case TTYPE_ROW: wMask |= SQLITE_TRACE_ROW; break;
3138 case TTYPE_CLOSE: wMask |= SQLITE_TRACE_CLOSE; break;
3143 wMask = SQLITE_TRACE_STMT; /* use the "legacy" default */
3145 if( pDb->zTraceV2 ){
3146 Tcl_Free(pDb->zTraceV2);
3148 zTraceV2 = Tcl_GetStringFromObj(objv[2], &len);
3149 if( zTraceV2 && len>0 ){
3150 pDb->zTraceV2 = Tcl_Alloc( len + 1 );
3151 memcpy(pDb->zTraceV2, zTraceV2, len+1);
3155 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3156 if( pDb->zTraceV2 ){
3157 pDb->interp = interp;
3158 sqlite3_trace_v2(pDb->db, (unsigned)wMask, DbTraceV2Handler, pDb);
3160 sqlite3_trace_v2(pDb->db, 0, 0, 0);
3167 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
3169 ** Start a new transaction (if we are not already in the midst of a
3170 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
3171 ** completes, either commit the transaction or roll it back if SCRIPT
3172 ** throws an exception. Or if no new transation was started, do nothing.
3173 ** pass the exception on up the stack.
3175 ** This command was inspired by Dave Thomas's talk on Ruby at the
3176 ** 2005 O'Reilly Open Source Convention (OSCON).
3178 case DB_TRANSACTION: {
3180 const char *zBegin = "SAVEPOINT _tcl_transaction";
3181 if( objc!=3 && objc!=4 ){
3182 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
3186 if( pDb->nTransaction==0 && objc==4 ){
3187 static const char *TTYPE_strs[] = {
3188 "deferred", "exclusive", "immediate", 0
3191 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
3194 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
3198 switch( (enum TTYPE_enum)ttype ){
3199 case TTYPE_DEFERRED: /* no-op */; break;
3200 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
3201 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
3204 pScript = objv[objc-1];
3206 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
3208 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
3210 if( rc!=SQLITE_OK ){
3211 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3214 pDb->nTransaction++;
3216 /* If using NRE, schedule a callback to invoke the script pScript, then
3217 ** a second callback to commit (or rollback) the transaction or savepoint
3218 ** opened above. If not using NRE, evaluate the script directly, then
3219 ** call function DbTransPostCmd() to commit (or rollback) the transaction
3222 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
3223 (void)Tcl_NREvalObj(interp, pScript, 0);
3225 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
3231 ** $db unlock_notify ?script?
3233 case DB_UNLOCK_NOTIFY: {
3234 #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
3235 Tcl_AppendResult(interp, "unlock_notify not available in this build",
3239 if( objc!=2 && objc!=3 ){
3240 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3243 void (*xNotify)(void **, int) = 0;
3244 void *pNotifyArg = 0;
3246 if( pDb->pUnlockNotify ){
3247 Tcl_DecrRefCount(pDb->pUnlockNotify);
3248 pDb->pUnlockNotify = 0;
3252 xNotify = DbUnlockNotify;
3253 pNotifyArg = (void *)pDb;
3254 pDb->pUnlockNotify = objv[2];
3255 Tcl_IncrRefCount(pDb->pUnlockNotify);
3258 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
3259 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3268 ** $db preupdate_hook count
3269 ** $db preupdate_hook hook ?SCRIPT?
3270 ** $db preupdate_hook new INDEX
3271 ** $db preupdate_hook old INDEX
3273 case DB_PREUPDATE: {
3274 #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
3275 Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time",
3279 static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
3280 enum DbPreupdateSubCmd {
3281 PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
3286 Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
3288 if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
3292 switch( (enum DbPreupdateSubCmd)iSub ){
3294 int nCol = sqlite3_preupdate_count(pDb->db);
3295 Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
3301 Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
3304 DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
3311 Tcl_WrongNumArgs(interp, 3, objv, "");
3314 pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
3315 Tcl_SetObjResult(interp, pRet);
3322 sqlite3_value *pValue;
3324 Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
3327 if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
3331 if( iSub==PRE_OLD ){
3332 rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
3334 assert( iSub==PRE_NEW );
3335 rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
3338 if( rc==SQLITE_OK ){
3340 pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
3341 Tcl_SetObjResult(interp, pObj);
3343 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3348 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
3353 ** $db wal_hook ?script?
3354 ** $db update_hook ?script?
3355 ** $db rollback_hook ?script?
3358 case DB_UPDATE_HOOK:
3359 case DB_ROLLBACK_HOOK: {
3360 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
3361 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3363 Tcl_Obj **ppHook = 0;
3364 if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
3365 if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
3366 if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
3368 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3372 DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
3378 ** Return the version string for this database.
3382 for(i=2; i<objc; i++){
3383 const char *zArg = Tcl_GetString(objv[i]);
3384 /* Optional arguments to $db version are used for testing purpose */
3386 /* $db version -use-legacy-prepare BOOLEAN
3388 ** Turn the use of legacy sqlite3_prepare() on or off.
3390 if( strcmp(zArg, "-use-legacy-prepare")==0 && i+1<objc ){
3392 if( Tcl_GetBooleanFromObj(interp, objv[i], &pDb->bLegacyPrepare) ){
3397 /* $db version -last-stmt-ptr
3399 ** Return a string which is a hex encoding of the pointer to the
3400 ** most recent sqlite3_stmt in the statement cache.
3402 if( strcmp(zArg, "-last-stmt-ptr")==0 ){
3404 sqlite3_snprintf(sizeof(zBuf), zBuf, "%p",
3405 pDb->stmtList ? pDb->stmtList->pStmt: 0);
3406 Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
3408 #endif /* SQLITE_TEST */
3410 Tcl_AppendResult(interp, "unknown argument: ", zArg, (char*)0);
3415 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
3421 } /* End of the SWITCH statement */
3427 ** Adaptor that provides an objCmd interface to the NRE-enabled
3428 ** interface implementation.
3430 static int SQLITE_TCLAPI DbObjCmdAdaptor(
3436 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
3438 #endif /* SQLITE_TCL_NRE */
3441 ** Issue the usage message when the "sqlite3" command arguments are
3444 static int sqliteCmdUsage(
3448 Tcl_WrongNumArgs(interp, 1, objv,
3449 "HANDLE ?FILENAME? ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
3450 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
3451 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3459 ** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
3460 ** ?-create BOOLEAN? ?-nomutex BOOLEAN?
3462 ** This is the main Tcl command. When the "sqlite" Tcl command is
3463 ** invoked, this routine runs to process that command.
3465 ** The first argument, DBNAME, is an arbitrary name for a new
3466 ** database connection. This command creates a new command named
3467 ** DBNAME that is used to control that connection. The database
3468 ** connection is deleted when the DBNAME command is deleted.
3470 ** The second argument is the name of the database file.
3473 static int SQLITE_TCLAPI DbMain(
3483 const char *zFile = 0;
3484 const char *zVfs = 0;
3486 Tcl_DString translatedFilename;
3487 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3493 /* In normal use, each TCL interpreter runs in a single thread. So
3494 ** by default, we can turn off mutexing on SQLite database connections.
3495 ** However, for testing purposes it is useful to have mutexes turned
3496 ** on. So, by default, mutexes default off. But if compiled with
3497 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3499 #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3500 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3502 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3505 if( objc==1 ) return sqliteCmdUsage(interp, objv);
3507 zArg = Tcl_GetStringFromObj(objv[1], 0);
3508 if( strcmp(zArg,"-version")==0 ){
3509 Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
3512 if( strcmp(zArg,"-sourceid")==0 ){
3513 Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0);
3516 if( strcmp(zArg,"-has-codec")==0 ){
3517 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3518 Tcl_AppendResult(interp,"1",(char*)0);
3520 Tcl_AppendResult(interp,"0",(char*)0);
3524 if( zArg[0]=='-' ) return sqliteCmdUsage(interp, objv);
3526 for(i=2; i<objc; i++){
3527 zArg = Tcl_GetString(objv[i]);
3529 if( zFile!=0 ) return sqliteCmdUsage(interp, objv);
3533 if( i==objc-1 ) return sqliteCmdUsage(interp, objv);
3535 if( strcmp(zArg,"-key")==0 ){
3536 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3537 pKey = Tcl_GetByteArrayFromObj(objv[i], &nKey);
3539 }else if( strcmp(zArg, "-vfs")==0 ){
3540 zVfs = Tcl_GetString(objv[i]);
3541 }else if( strcmp(zArg, "-readonly")==0 ){
3543 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3545 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
3546 flags |= SQLITE_OPEN_READONLY;
3548 flags &= ~SQLITE_OPEN_READONLY;
3549 flags |= SQLITE_OPEN_READWRITE;
3551 }else if( strcmp(zArg, "-create")==0 ){
3553 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3554 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
3555 flags |= SQLITE_OPEN_CREATE;
3557 flags &= ~SQLITE_OPEN_CREATE;
3559 }else if( strcmp(zArg, "-nomutex")==0 ){
3561 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3563 flags |= SQLITE_OPEN_NOMUTEX;
3564 flags &= ~SQLITE_OPEN_FULLMUTEX;
3566 flags &= ~SQLITE_OPEN_NOMUTEX;
3568 }else if( strcmp(zArg, "-fullmutex")==0 ){
3570 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3572 flags |= SQLITE_OPEN_FULLMUTEX;
3573 flags &= ~SQLITE_OPEN_NOMUTEX;
3575 flags &= ~SQLITE_OPEN_FULLMUTEX;
3577 }else if( strcmp(zArg, "-uri")==0 ){
3579 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3581 flags |= SQLITE_OPEN_URI;
3583 flags &= ~SQLITE_OPEN_URI;
3586 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3591 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
3592 memset(p, 0, sizeof(*p));
3593 if( zFile==0 ) zFile = "";
3594 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
3595 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
3596 Tcl_DStringFree(&translatedFilename);
3598 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3599 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3600 sqlite3_close(p->db);
3604 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
3606 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3608 sqlite3_key(p->db, pKey, nKey);
3612 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
3614 sqlite3_free(zErrMsg);
3617 p->maxStmt = NUM_PREPARED_STMTS;
3618 p->openFlags = flags & SQLITE_OPEN_URI;
3620 zArg = Tcl_GetStringFromObj(objv[1], 0);
3622 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3623 (char*)p, DbDeleteCmd);
3625 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3631 ** Provide a dummy Tcl_InitStubs if we are using this as a static
3634 #ifndef USE_TCL_STUBS
3635 # undef Tcl_InitStubs
3636 # define Tcl_InitStubs(a,b,c) TCL_VERSION
3640 ** Make sure we have a PACKAGE_VERSION macro defined. This will be
3641 ** defined automatically by the TEA makefile. But other makefiles
3642 ** do not define it.
3644 #ifndef PACKAGE_VERSION
3645 # define PACKAGE_VERSION SQLITE_VERSION
3649 ** Initialize this module.
3651 ** This Tcl module contains only a single new Tcl command named "sqlite".
3652 ** (Hence there is no namespace. There is no point in using a namespace
3653 ** if the extension only supplies one new name!) The "sqlite" command is
3654 ** used to open a new SQLite database. See the DbMain() routine above
3655 ** for additional information.
3657 ** The EXTERN macros are required by TCL in order to work on windows.
3659 EXTERN int Sqlite3_Init(Tcl_Interp *interp){
3660 int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
3662 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
3663 #ifndef SQLITE_3_SUFFIX_ONLY
3664 /* The "sqlite" alias is undocumented. It is here only to support
3665 ** legacy scripts. All new scripts should use only the "sqlite3"
3667 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
3669 rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3673 EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3674 EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3675 EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3677 /* Because it accesses the file-system and uses persistent state, SQLite
3678 ** is not considered appropriate for safe interpreters. Hence, we cause
3679 ** the _SafeInit() interfaces return TCL_ERROR.
3681 EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
3682 EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
3686 #ifndef SQLITE_3_SUFFIX_ONLY
3687 int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3688 int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3689 int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3690 int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3694 ** If the TCLSH macro is defined, add code to make a stand-alone program.
3698 /* This is the main routine for an ordinary TCL shell. If there are
3699 ** are arguments, run the first argument as a script. Otherwise,
3700 ** read TCL commands from standard input
3702 static const char *tclsh_main_loop(void){
3703 static const char zMainloop[] =
3704 "if {[llength $argv]>=1} {\n"
3705 "set argv0 [lindex $argv 0]\n"
3706 "set argv [lrange $argv 1 end]\n"
3710 "while {![eof stdin]} {\n"
3711 "if {$line!=\"\"} {\n"
3712 "puts -nonewline \"> \"\n"
3714 "puts -nonewline \"% \"\n"
3717 "append line [gets stdin]\n"
3718 "if {[info complete $line]} {\n"
3719 "if {[catch {uplevel #0 $line} result]} {\n"
3720 "puts stderr \"Error: $result\"\n"
3721 "} elseif {$result!=\"\"} {\n"
3734 #define TCLSH_MAIN main /* Needed to fake out mktclapp */
3735 int SQLITE_CDECL TCLSH_MAIN(int argc, char **argv){
3738 const char *zScript = 0;
3740 #if defined(TCLSH_INIT_PROC)
3741 extern const char *TCLSH_INIT_PROC(Tcl_Interp*);
3744 #if !defined(_WIN32_WCE)
3745 if( getenv("SQLITE_DEBUG_BREAK") ){
3746 if( isatty(0) && isatty(2) ){
3748 "attach debugger to process %d and press any key to continue.\n",
3752 #if defined(_WIN32) || defined(WIN32)
3754 #elif defined(SIGTRAP)
3761 /* Call sqlite3_shutdown() once before doing anything else. This is to
3762 ** test that sqlite3_shutdown() can be safely called by a process before
3763 ** sqlite3_initialize() is. */
3766 Tcl_FindExecutable(argv[0]);
3767 Tcl_SetSystemEncoding(NULL, "utf-8");
3768 interp = Tcl_CreateInterp();
3769 Sqlite3_Init(interp);
3771 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-1);
3772 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
3773 Tcl_SetVar(interp,"argv0",argv[0],TCL_GLOBAL_ONLY);
3774 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
3775 for(i=1; i<argc; i++){
3776 Tcl_SetVar(interp, "argv", argv[i],
3777 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3779 #if defined(TCLSH_INIT_PROC)
3780 zScript = TCLSH_INIT_PROC(interp);
3783 zScript = tclsh_main_loop();
3785 if( Tcl_GlobalEval(interp, zScript)!=TCL_OK ){
3786 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
3787 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
3788 fprintf(stderr,"%s: %s\n", *argv, zInfo);