4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** A TCL Interface to SQLite. Append this file to sqlite3.c and
13 ** compile the whole thing to build a TCL-enabled version of SQLite.
15 ** Compile-time options:
17 ** -DTCLSH Add a "main()" routine that works as a tclsh.
19 ** -DTCLSH_INIT_PROC=name
21 ** Invoke name(interp) to initialize the Tcl interpreter.
22 ** If name(interp) returns a non-NULL string, then run
23 ** that string as a Tcl script to launch the application.
24 ** If name(interp) returns NULL, then run the regular
25 ** tclsh-emulator code.
27 #ifdef TCLSH_INIT_PROC
32 ** If requested, include the SQLite compiler options file for MSVC.
34 #if defined(INCLUDE_MSVC_H)
38 #if defined(INCLUDE_SQLITE_TCL_H)
39 # include "sqlite_tcl.h"
42 # ifndef SQLITE_TCLAPI
43 # define SQLITE_TCLAPI
49 ** Some additional include files are needed if this file is not
50 ** appended to the amalgamation.
52 #ifndef SQLITE_AMALGAMATION
57 typedef unsigned char u8
;
58 # ifndef SQLITE_PTRSIZE
59 # if defined(__SIZEOF_POINTER__)
60 # define SQLITE_PTRSIZE __SIZEOF_POINTER__
61 # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
62 defined(_M_ARM) || defined(__arm__) || defined(__x86) || \
63 (defined(__APPLE__) && defined(__POWERPC__)) || \
64 (defined(__TOS_AIX__) && !defined(__64BIT__))
65 # define SQLITE_PTRSIZE 4
67 # define SQLITE_PTRSIZE 8
69 # endif /* SQLITE_PTRSIZE */
70 # if defined(HAVE_STDINT_H)
71 typedef uintptr_t uptr
;
72 # elif SQLITE_PTRSIZE==4
73 typedef unsigned int uptr
;
75 typedef sqlite3_uint64 uptr
;
80 /* Used to get the current process ID */
84 # define GETPID getpid
85 #elif !defined(_WIN32_WCE)
86 # ifndef SQLITE_AMALGAMATION
87 # ifndef WIN32_LEAN_AND_MEAN
88 # define WIN32_LEAN_AND_MEAN
93 # define isatty(h) _isatty(h)
94 # define GETPID (int)GetCurrentProcessId
98 * Windows needs to know which symbols to export. Unix does not.
99 * BUILD_sqlite should be undefined for Unix.
102 #undef TCL_STORAGE_CLASS
103 #define TCL_STORAGE_CLASS DLLEXPORT
104 #endif /* BUILD_sqlite */
106 #define NUM_PREPARED_STMTS 10
107 #define MAX_PREPARED_STMTS 100
109 /* Forward declaration */
110 typedef struct SqliteDb SqliteDb
;
113 ** New SQL functions can be created as TCL scripts. Each such function
114 ** is described by an instance of the following structure.
116 ** Variable eType may be set to SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT,
117 ** SQLITE_BLOB or SQLITE_NULL. If it is SQLITE_NULL, then the implementation
118 ** attempts to determine the type of the result based on the Tcl object.
119 ** If it is SQLITE_TEXT or SQLITE_BLOB, then a text (sqlite3_result_text())
120 ** or blob (sqlite3_result_blob()) is returned. If it is SQLITE_INTEGER
121 ** or SQLITE_FLOAT, then an attempt is made to return an integer or float
122 ** value, falling back to float and then text if this is not possible.
124 typedef struct SqlFunc SqlFunc
;
126 Tcl_Interp
*interp
; /* The TCL interpret to execute the function */
127 Tcl_Obj
*pScript
; /* The Tcl_Obj representation of the script */
128 SqliteDb
*pDb
; /* Database connection that owns this function */
129 int useEvalObjv
; /* True if it is safe to use Tcl_EvalObjv */
130 int eType
; /* Type of value to return */
131 char *zName
; /* Name of this function */
132 SqlFunc
*pNext
; /* Next function on the list of them all */
136 ** New collation sequences function can be created as TCL scripts. Each such
137 ** function is described by an instance of the following structure.
139 typedef struct SqlCollate SqlCollate
;
141 Tcl_Interp
*interp
; /* The TCL interpret to execute the function */
142 char *zScript
; /* The script to be run */
143 SqlCollate
*pNext
; /* Next function on the list of them all */
147 ** Prepared statements are cached for faster execution. Each prepared
148 ** statement is described by an instance of the following structure.
150 typedef struct SqlPreparedStmt SqlPreparedStmt
;
151 struct SqlPreparedStmt
{
152 SqlPreparedStmt
*pNext
; /* Next in linked list */
153 SqlPreparedStmt
*pPrev
; /* Previous on the list */
154 sqlite3_stmt
*pStmt
; /* The prepared statement */
155 int nSql
; /* chars in zSql[] */
156 const char *zSql
; /* Text of the SQL statement */
157 int nParm
; /* Size of apParm array */
158 Tcl_Obj
**apParm
; /* Array of referenced object pointers */
161 typedef struct IncrblobChannel IncrblobChannel
;
164 ** There is one instance of this structure for each SQLite database
165 ** that has been opened by the SQLite TCL interface.
167 ** If this module is built with SQLITE_TEST defined (to create the SQLite
168 ** testfixture executable), then it may be configured to use either
169 ** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
170 ** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
173 sqlite3
*db
; /* The "real" database structure. MUST BE FIRST */
174 Tcl_Interp
*interp
; /* The interpreter used for this database */
175 char *zBusy
; /* The busy callback routine */
176 char *zCommit
; /* The commit hook callback routine */
177 char *zTrace
; /* The trace callback routine */
178 char *zTraceV2
; /* The trace_v2 callback routine */
179 char *zProfile
; /* The profile callback routine */
180 char *zProgress
; /* The progress callback routine */
181 char *zBindFallback
; /* Callback to invoke on a binding miss */
182 char *zAuth
; /* The authorization callback routine */
183 int disableAuth
; /* Disable the authorizer if it exists */
184 char *zNull
; /* Text to substitute for an SQL NULL value */
185 SqlFunc
*pFunc
; /* List of SQL functions */
186 Tcl_Obj
*pUpdateHook
; /* Update hook script (if any) */
187 Tcl_Obj
*pPreUpdateHook
; /* Pre-update hook script (if any) */
188 Tcl_Obj
*pRollbackHook
; /* Rollback hook script (if any) */
189 Tcl_Obj
*pWalHook
; /* WAL hook script (if any) */
190 Tcl_Obj
*pUnlockNotify
; /* Unlock notify script (if any) */
191 SqlCollate
*pCollate
; /* List of SQL collation functions */
192 int rc
; /* Return code of most recent sqlite3_exec() */
193 Tcl_Obj
*pCollateNeeded
; /* Collation needed script */
194 SqlPreparedStmt
*stmtList
; /* List of prepared statements*/
195 SqlPreparedStmt
*stmtLast
; /* Last statement in the list */
196 int maxStmt
; /* The next maximum number of stmtList */
197 int nStmt
; /* Number of statements in stmtList */
198 IncrblobChannel
*pIncrblob
;/* Linked list of open incrblob channels */
199 int nStep
, nSort
, nIndex
; /* Statistics for most recent operation */
200 int nVMStep
; /* Another statistic for most recent operation */
201 int nTransaction
; /* Number of nested [transaction] methods */
202 int openFlags
; /* Flags used to open. (SQLITE_OPEN_URI) */
203 int nRef
; /* Delete object when this reaches 0 */
205 int bLegacyPrepare
; /* True to use sqlite3_prepare() */
209 struct IncrblobChannel
{
210 sqlite3_blob
*pBlob
; /* sqlite3 blob handle */
211 SqliteDb
*pDb
; /* Associated database connection */
212 int iSeek
; /* Current seek offset */
213 Tcl_Channel channel
; /* Channel identifier */
214 IncrblobChannel
*pNext
; /* Linked list of all open incrblob channels */
215 IncrblobChannel
*pPrev
; /* Linked list of all open incrblob channels */
219 ** Compute a string length that is limited to what can be stored in
220 ** lower 30 bits of a 32-bit signed integer.
222 static int strlen30(const char *z
){
224 while( *z2
){ z2
++; }
225 return 0x3fffffff & (int)(z2
- z
);
229 #ifndef SQLITE_OMIT_INCRBLOB
231 ** Close all incrblob channels opened using database connection pDb.
232 ** This is called when shutting down the database connection.
234 static void closeIncrblobChannels(SqliteDb
*pDb
){
236 IncrblobChannel
*pNext
;
238 for(p
=pDb
->pIncrblob
; p
; p
=pNext
){
241 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
242 ** which deletes the IncrblobChannel structure at *p. So do not
243 ** call Tcl_Free() here.
245 Tcl_UnregisterChannel(pDb
->interp
, p
->channel
);
250 ** Close an incremental blob channel.
252 static int SQLITE_TCLAPI
incrblobClose(
253 ClientData instanceData
,
256 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
257 int rc
= sqlite3_blob_close(p
->pBlob
);
258 sqlite3
*db
= p
->pDb
->db
;
260 /* Remove the channel from the SqliteDb.pIncrblob list. */
262 p
->pNext
->pPrev
= p
->pPrev
;
265 p
->pPrev
->pNext
= p
->pNext
;
267 if( p
->pDb
->pIncrblob
==p
){
268 p
->pDb
->pIncrblob
= p
->pNext
;
271 /* Free the IncrblobChannel structure */
275 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(db
), TCL_VOLATILE
);
282 ** Read data from an incremental blob channel.
284 static int SQLITE_TCLAPI
incrblobInput(
285 ClientData instanceData
,
290 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
291 int nRead
= bufSize
; /* Number of bytes to read */
292 int nBlob
; /* Total size of the blob */
293 int rc
; /* sqlite error code */
295 nBlob
= sqlite3_blob_bytes(p
->pBlob
);
296 if( (p
->iSeek
+nRead
)>nBlob
){
297 nRead
= nBlob
-p
->iSeek
;
303 rc
= sqlite3_blob_read(p
->pBlob
, (void *)buf
, nRead
, p
->iSeek
);
314 ** Write data to an incremental blob channel.
316 static int SQLITE_TCLAPI
incrblobOutput(
317 ClientData instanceData
,
322 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
323 int nWrite
= toWrite
; /* Number of bytes to write */
324 int nBlob
; /* Total size of the blob */
325 int rc
; /* sqlite error code */
327 nBlob
= sqlite3_blob_bytes(p
->pBlob
);
328 if( (p
->iSeek
+nWrite
)>nBlob
){
329 *errorCodePtr
= EINVAL
;
336 rc
= sqlite3_blob_write(p
->pBlob
, (void *)buf
, nWrite
, p
->iSeek
);
347 ** Seek an incremental blob channel.
349 static int SQLITE_TCLAPI
incrblobSeek(
350 ClientData instanceData
,
355 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
365 p
->iSeek
= sqlite3_blob_bytes(p
->pBlob
) + offset
;
368 default: assert(!"Bad seekMode");
375 static void SQLITE_TCLAPI
incrblobWatch(
376 ClientData instanceData
,
381 static int SQLITE_TCLAPI
incrblobHandle(
382 ClientData instanceData
,
389 static Tcl_ChannelType IncrblobChannelType
= {
390 "incrblob", /* typeName */
391 TCL_CHANNEL_VERSION_2
, /* version */
392 incrblobClose
, /* closeProc */
393 incrblobInput
, /* inputProc */
394 incrblobOutput
, /* outputProc */
395 incrblobSeek
, /* seekProc */
396 0, /* setOptionProc */
397 0, /* getOptionProc */
398 incrblobWatch
, /* watchProc (this is a no-op) */
399 incrblobHandle
, /* getHandleProc (always returns error) */
401 0, /* blockModeProc */
404 0, /* wideSeekProc */
408 ** Create a new incrblob channel.
410 static int createIncrblobChannel(
420 sqlite3
*db
= pDb
->db
;
423 int flags
= TCL_READABLE
|(isReadonly
? 0 : TCL_WRITABLE
);
425 /* This variable is used to name the channels: "incrblob_[incr count]" */
426 static int count
= 0;
429 rc
= sqlite3_blob_open(db
, zDb
, zTable
, zColumn
, iRow
, !isReadonly
, &pBlob
);
431 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(pDb
->db
), TCL_VOLATILE
);
435 p
= (IncrblobChannel
*)Tcl_Alloc(sizeof(IncrblobChannel
));
439 sqlite3_snprintf(sizeof(zChannel
), zChannel
, "incrblob_%d", ++count
);
440 p
->channel
= Tcl_CreateChannel(&IncrblobChannelType
, zChannel
, p
, flags
);
441 Tcl_RegisterChannel(interp
, p
->channel
);
443 /* Link the new channel into the SqliteDb.pIncrblob list. */
444 p
->pNext
= pDb
->pIncrblob
;
452 Tcl_SetResult(interp
, (char *)Tcl_GetChannelName(p
->channel
), TCL_VOLATILE
);
455 #else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
456 #define closeIncrblobChannels(pDb)
460 ** Look at the script prefix in pCmd. We will be executing this script
461 ** after first appending one or more arguments. This routine analyzes
462 ** the script to see if it is safe to use Tcl_EvalObjv() on the script
463 ** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
466 ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
467 ** command name followed by zero or more arguments with no [...] or $
468 ** or {...} or ; to be seen anywhere. Most callback scripts consist
469 ** of just a single procedure name and they meet this requirement.
471 static int safeToUseEvalObjv(Tcl_Interp
*interp
, Tcl_Obj
*pCmd
){
472 /* We could try to do something with Tcl_Parse(). But we will instead
473 ** just do a search for forbidden characters. If any of the forbidden
474 ** characters appear in pCmd, we will report the string as unsafe.
478 z
= Tcl_GetStringFromObj(pCmd
, &n
);
481 if( c
=='$' || c
=='[' || c
==';' ) return 0;
487 ** Find an SqlFunc structure with the given name. Or create a new
488 ** one if an existing one cannot be found. Return a pointer to the
491 static SqlFunc
*findSqlFunc(SqliteDb
*pDb
, const char *zName
){
493 int nName
= strlen30(zName
);
494 pNew
= (SqlFunc
*)Tcl_Alloc( sizeof(*pNew
) + nName
+ 1 );
495 pNew
->zName
= (char*)&pNew
[1];
496 memcpy(pNew
->zName
, zName
, nName
+1);
497 for(p
=pDb
->pFunc
; p
; p
=p
->pNext
){
498 if( sqlite3_stricmp(p
->zName
, pNew
->zName
)==0 ){
499 Tcl_Free((char*)pNew
);
503 pNew
->interp
= pDb
->interp
;
506 pNew
->pNext
= pDb
->pFunc
;
512 ** Free a single SqlPreparedStmt object.
514 static void dbFreeStmt(SqlPreparedStmt
*pStmt
){
516 if( sqlite3_sql(pStmt
->pStmt
)==0 ){
517 Tcl_Free((char *)pStmt
->zSql
);
520 sqlite3_finalize(pStmt
->pStmt
);
521 Tcl_Free((char *)pStmt
);
525 ** Finalize and free a list of prepared statements
527 static void flushStmtCache(SqliteDb
*pDb
){
528 SqlPreparedStmt
*pPreStmt
;
529 SqlPreparedStmt
*pNext
;
531 for(pPreStmt
= pDb
->stmtList
; pPreStmt
; pPreStmt
=pNext
){
532 pNext
= pPreStmt
->pNext
;
533 dbFreeStmt(pPreStmt
);
541 ** Increment the reference counter on the SqliteDb object. The reference
542 ** should be released by calling delDatabaseRef().
544 static void addDatabaseRef(SqliteDb
*pDb
){
549 ** Decrement the reference counter associated with the SqliteDb object.
550 ** If it reaches zero, delete the object.
552 static void delDatabaseRef(SqliteDb
*pDb
){
553 assert( pDb
->nRef
>0 );
557 closeIncrblobChannels(pDb
);
558 sqlite3_close(pDb
->db
);
560 SqlFunc
*pFunc
= pDb
->pFunc
;
561 pDb
->pFunc
= pFunc
->pNext
;
562 assert( pFunc
->pDb
==pDb
);
563 Tcl_DecrRefCount(pFunc
->pScript
);
564 Tcl_Free((char*)pFunc
);
566 while( pDb
->pCollate
){
567 SqlCollate
*pCollate
= pDb
->pCollate
;
568 pDb
->pCollate
= pCollate
->pNext
;
569 Tcl_Free((char*)pCollate
);
572 Tcl_Free(pDb
->zBusy
);
575 Tcl_Free(pDb
->zTrace
);
578 Tcl_Free(pDb
->zTraceV2
);
581 Tcl_Free(pDb
->zProfile
);
583 if( pDb
->zBindFallback
){
584 Tcl_Free(pDb
->zBindFallback
);
587 Tcl_Free(pDb
->zAuth
);
590 Tcl_Free(pDb
->zNull
);
592 if( pDb
->pUpdateHook
){
593 Tcl_DecrRefCount(pDb
->pUpdateHook
);
595 if( pDb
->pPreUpdateHook
){
596 Tcl_DecrRefCount(pDb
->pPreUpdateHook
);
598 if( pDb
->pRollbackHook
){
599 Tcl_DecrRefCount(pDb
->pRollbackHook
);
602 Tcl_DecrRefCount(pDb
->pWalHook
);
604 if( pDb
->pCollateNeeded
){
605 Tcl_DecrRefCount(pDb
->pCollateNeeded
);
607 Tcl_Free((char*)pDb
);
612 ** TCL calls this procedure when an sqlite3 database command is
615 static void SQLITE_TCLAPI
DbDeleteCmd(void *db
){
616 SqliteDb
*pDb
= (SqliteDb
*)db
;
621 ** This routine is called when a database file is locked while trying
624 static int DbBusyHandler(void *cd
, int nTries
){
625 SqliteDb
*pDb
= (SqliteDb
*)cd
;
629 sqlite3_snprintf(sizeof(zVal
), zVal
, "%d", nTries
);
630 rc
= Tcl_VarEval(pDb
->interp
, pDb
->zBusy
, " ", zVal
, (char*)0);
631 if( rc
!=TCL_OK
|| atoi(Tcl_GetStringResult(pDb
->interp
)) ){
637 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
639 ** This routine is invoked as the 'progress callback' for the database.
641 static int DbProgressHandler(void *cd
){
642 SqliteDb
*pDb
= (SqliteDb
*)cd
;
645 assert( pDb
->zProgress
);
646 rc
= Tcl_Eval(pDb
->interp
, pDb
->zProgress
);
647 if( rc
!=TCL_OK
|| atoi(Tcl_GetStringResult(pDb
->interp
)) ){
654 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
655 !defined(SQLITE_OMIT_DEPRECATED)
657 ** This routine is called by the SQLite trace handler whenever a new
658 ** block of SQL is executed. The TCL script in pDb->zTrace is executed.
660 static void DbTraceHandler(void *cd
, const char *zSql
){
661 SqliteDb
*pDb
= (SqliteDb
*)cd
;
664 Tcl_DStringInit(&str
);
665 Tcl_DStringAppend(&str
, pDb
->zTrace
, -1);
666 Tcl_DStringAppendElement(&str
, zSql
);
667 Tcl_Eval(pDb
->interp
, Tcl_DStringValue(&str
));
668 Tcl_DStringFree(&str
);
669 Tcl_ResetResult(pDb
->interp
);
673 #ifndef SQLITE_OMIT_TRACE
675 ** This routine is called by the SQLite trace_v2 handler whenever a new
676 ** supported event is generated. Unsupported event types are ignored.
677 ** The TCL script in pDb->zTraceV2 is executed, with the arguments for
678 ** the event appended to it (as list elements).
680 static int DbTraceV2Handler(
681 unsigned type
, /* One of the SQLITE_TRACE_* event types. */
682 void *cd
, /* The original context data pointer. */
683 void *pd
, /* Primary event data, depends on event type. */
684 void *xd
/* Extra event data, depends on event type. */
686 SqliteDb
*pDb
= (SqliteDb
*)cd
;
690 case SQLITE_TRACE_STMT
: {
691 sqlite3_stmt
*pStmt
= (sqlite3_stmt
*)pd
;
692 char *zSql
= (char *)xd
;
694 pCmd
= Tcl_NewStringObj(pDb
->zTraceV2
, -1);
695 Tcl_IncrRefCount(pCmd
);
696 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
697 Tcl_NewWideIntObj((Tcl_WideInt
)(uptr
)pStmt
));
698 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
699 Tcl_NewStringObj(zSql
, -1));
700 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
701 Tcl_DecrRefCount(pCmd
);
702 Tcl_ResetResult(pDb
->interp
);
705 case SQLITE_TRACE_PROFILE
: {
706 sqlite3_stmt
*pStmt
= (sqlite3_stmt
*)pd
;
707 sqlite3_int64 ns
= *(sqlite3_int64
*)xd
;
709 pCmd
= Tcl_NewStringObj(pDb
->zTraceV2
, -1);
710 Tcl_IncrRefCount(pCmd
);
711 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
712 Tcl_NewWideIntObj((Tcl_WideInt
)(uptr
)pStmt
));
713 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
714 Tcl_NewWideIntObj((Tcl_WideInt
)ns
));
715 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
716 Tcl_DecrRefCount(pCmd
);
717 Tcl_ResetResult(pDb
->interp
);
720 case SQLITE_TRACE_ROW
: {
721 sqlite3_stmt
*pStmt
= (sqlite3_stmt
*)pd
;
723 pCmd
= Tcl_NewStringObj(pDb
->zTraceV2
, -1);
724 Tcl_IncrRefCount(pCmd
);
725 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
726 Tcl_NewWideIntObj((Tcl_WideInt
)(uptr
)pStmt
));
727 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
728 Tcl_DecrRefCount(pCmd
);
729 Tcl_ResetResult(pDb
->interp
);
732 case SQLITE_TRACE_CLOSE
: {
733 sqlite3
*db
= (sqlite3
*)pd
;
735 pCmd
= Tcl_NewStringObj(pDb
->zTraceV2
, -1);
736 Tcl_IncrRefCount(pCmd
);
737 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
738 Tcl_NewWideIntObj((Tcl_WideInt
)(uptr
)db
));
739 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
740 Tcl_DecrRefCount(pCmd
);
741 Tcl_ResetResult(pDb
->interp
);
749 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
750 !defined(SQLITE_OMIT_DEPRECATED)
752 ** This routine is called by the SQLite profile handler after a statement
753 ** SQL has executed. The TCL script in pDb->zProfile is evaluated.
755 static void DbProfileHandler(void *cd
, const char *zSql
, sqlite_uint64 tm
){
756 SqliteDb
*pDb
= (SqliteDb
*)cd
;
760 sqlite3_snprintf(sizeof(zTm
)-1, zTm
, "%lld", tm
);
761 Tcl_DStringInit(&str
);
762 Tcl_DStringAppend(&str
, pDb
->zProfile
, -1);
763 Tcl_DStringAppendElement(&str
, zSql
);
764 Tcl_DStringAppendElement(&str
, zTm
);
765 Tcl_Eval(pDb
->interp
, Tcl_DStringValue(&str
));
766 Tcl_DStringFree(&str
);
767 Tcl_ResetResult(pDb
->interp
);
772 ** This routine is called when a transaction is committed. The
773 ** TCL script in pDb->zCommit is executed. If it returns non-zero or
774 ** if it throws an exception, the transaction is rolled back instead
775 ** of being committed.
777 static int DbCommitHandler(void *cd
){
778 SqliteDb
*pDb
= (SqliteDb
*)cd
;
781 rc
= Tcl_Eval(pDb
->interp
, pDb
->zCommit
);
782 if( rc
!=TCL_OK
|| atoi(Tcl_GetStringResult(pDb
->interp
)) ){
788 static void DbRollbackHandler(void *clientData
){
789 SqliteDb
*pDb
= (SqliteDb
*)clientData
;
790 assert(pDb
->pRollbackHook
);
791 if( TCL_OK
!=Tcl_EvalObjEx(pDb
->interp
, pDb
->pRollbackHook
, 0) ){
792 Tcl_BackgroundError(pDb
->interp
);
797 ** This procedure handles wal_hook callbacks.
799 static int DbWalHandler(
807 SqliteDb
*pDb
= (SqliteDb
*)clientData
;
808 Tcl_Interp
*interp
= pDb
->interp
;
809 assert(pDb
->pWalHook
);
811 assert( db
==pDb
->db
);
812 p
= Tcl_DuplicateObj(pDb
->pWalHook
);
814 Tcl_ListObjAppendElement(interp
, p
, Tcl_NewStringObj(zDb
, -1));
815 Tcl_ListObjAppendElement(interp
, p
, Tcl_NewIntObj(nEntry
));
816 if( TCL_OK
!=Tcl_EvalObjEx(interp
, p
, 0)
817 || TCL_OK
!=Tcl_GetIntFromObj(interp
, Tcl_GetObjResult(interp
), &ret
)
819 Tcl_BackgroundError(interp
);
826 #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
827 static void setTestUnlockNotifyVars(Tcl_Interp
*interp
, int iArg
, int nArg
){
829 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%d", iArg
);
830 Tcl_SetVar(interp
, "sqlite_unlock_notify_arg", zBuf
, TCL_GLOBAL_ONLY
);
831 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%d", nArg
);
832 Tcl_SetVar(interp
, "sqlite_unlock_notify_argcount", zBuf
, TCL_GLOBAL_ONLY
);
835 # define setTestUnlockNotifyVars(x,y,z)
838 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
839 static void DbUnlockNotify(void **apArg
, int nArg
){
841 for(i
=0; i
<nArg
; i
++){
842 const int flags
= (TCL_EVAL_GLOBAL
|TCL_EVAL_DIRECT
);
843 SqliteDb
*pDb
= (SqliteDb
*)apArg
[i
];
844 setTestUnlockNotifyVars(pDb
->interp
, i
, nArg
);
845 assert( pDb
->pUnlockNotify
);
846 Tcl_EvalObjEx(pDb
->interp
, pDb
->pUnlockNotify
, flags
);
847 Tcl_DecrRefCount(pDb
->pUnlockNotify
);
848 pDb
->pUnlockNotify
= 0;
853 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
855 ** Pre-update hook callback.
857 static void DbPreUpdateHandler(
866 SqliteDb
*pDb
= (SqliteDb
*)p
;
868 static const char *azStr
[] = {"DELETE", "INSERT", "UPDATE"};
870 assert( (SQLITE_DELETE
-1)/9 == 0 );
871 assert( (SQLITE_INSERT
-1)/9 == 1 );
872 assert( (SQLITE_UPDATE
-1)/9 == 2 );
873 assert( pDb
->pPreUpdateHook
);
874 assert( db
==pDb
->db
);
875 assert( op
==SQLITE_INSERT
|| op
==SQLITE_UPDATE
|| op
==SQLITE_DELETE
);
877 pCmd
= Tcl_DuplicateObj(pDb
->pPreUpdateHook
);
878 Tcl_IncrRefCount(pCmd
);
879 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(azStr
[(op
-1)/9], -1));
880 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(zDb
, -1));
881 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(zTbl
, -1));
882 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewWideIntObj(iKey1
));
883 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewWideIntObj(iKey2
));
884 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
885 Tcl_DecrRefCount(pCmd
);
887 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
889 static void DbUpdateHandler(
896 SqliteDb
*pDb
= (SqliteDb
*)p
;
898 static const char *azStr
[] = {"DELETE", "INSERT", "UPDATE"};
900 assert( (SQLITE_DELETE
-1)/9 == 0 );
901 assert( (SQLITE_INSERT
-1)/9 == 1 );
902 assert( (SQLITE_UPDATE
-1)/9 == 2 );
904 assert( pDb
->pUpdateHook
);
905 assert( op
==SQLITE_INSERT
|| op
==SQLITE_UPDATE
|| op
==SQLITE_DELETE
);
907 pCmd
= Tcl_DuplicateObj(pDb
->pUpdateHook
);
908 Tcl_IncrRefCount(pCmd
);
909 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(azStr
[(op
-1)/9], -1));
910 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(zDb
, -1));
911 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(zTbl
, -1));
912 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewWideIntObj(rowid
));
913 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
914 Tcl_DecrRefCount(pCmd
);
917 static void tclCollateNeeded(
923 SqliteDb
*pDb
= (SqliteDb
*)pCtx
;
924 Tcl_Obj
*pScript
= Tcl_DuplicateObj(pDb
->pCollateNeeded
);
925 Tcl_IncrRefCount(pScript
);
926 Tcl_ListObjAppendElement(0, pScript
, Tcl_NewStringObj(zName
, -1));
927 Tcl_EvalObjEx(pDb
->interp
, pScript
, 0);
928 Tcl_DecrRefCount(pScript
);
932 ** This routine is called to evaluate an SQL collation function implemented
935 static int tclSqlCollate(
942 SqlCollate
*p
= (SqlCollate
*)pCtx
;
945 pCmd
= Tcl_NewStringObj(p
->zScript
, -1);
946 Tcl_IncrRefCount(pCmd
);
947 Tcl_ListObjAppendElement(p
->interp
, pCmd
, Tcl_NewStringObj(zA
, nA
));
948 Tcl_ListObjAppendElement(p
->interp
, pCmd
, Tcl_NewStringObj(zB
, nB
));
949 Tcl_EvalObjEx(p
->interp
, pCmd
, TCL_EVAL_DIRECT
);
950 Tcl_DecrRefCount(pCmd
);
951 return (atoi(Tcl_GetStringResult(p
->interp
)));
955 ** This routine is called to evaluate an SQL function implemented
958 static void tclSqlFunc(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
){
959 SqlFunc
*p
= sqlite3_user_data(context
);
965 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
966 ** script object directly. This allows the TCL compiler to generate
967 ** bytecode for the command on the first invocation and thus make
968 ** subsequent invocations much faster. */
970 Tcl_IncrRefCount(pCmd
);
971 rc
= Tcl_EvalObjEx(p
->interp
, pCmd
, 0);
972 Tcl_DecrRefCount(pCmd
);
974 /* If there are arguments to the function, make a shallow copy of the
975 ** script object, lappend the arguments, then evaluate the copy.
977 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
978 ** The new Tcl_Obj contains pointers to the original list elements.
979 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
980 ** of the list to tclCmdNameType, that alternate representation will
981 ** be preserved and reused on the next invocation.
985 if( Tcl_ListObjGetElements(p
->interp
, p
->pScript
, &nArg
, &aArg
) ){
986 sqlite3_result_error(context
, Tcl_GetStringResult(p
->interp
), -1);
989 pCmd
= Tcl_NewListObj(nArg
, aArg
);
990 Tcl_IncrRefCount(pCmd
);
991 for(i
=0; i
<argc
; i
++){
992 sqlite3_value
*pIn
= argv
[i
];
995 /* Set pVal to contain the i'th column of this row. */
996 switch( sqlite3_value_type(pIn
) ){
998 int bytes
= sqlite3_value_bytes(pIn
);
999 pVal
= Tcl_NewByteArrayObj(sqlite3_value_blob(pIn
), bytes
);
1002 case SQLITE_INTEGER
: {
1003 sqlite_int64 v
= sqlite3_value_int64(pIn
);
1004 if( v
>=-2147483647 && v
<=2147483647 ){
1005 pVal
= Tcl_NewIntObj((int)v
);
1007 pVal
= Tcl_NewWideIntObj(v
);
1011 case SQLITE_FLOAT
: {
1012 double r
= sqlite3_value_double(pIn
);
1013 pVal
= Tcl_NewDoubleObj(r
);
1017 pVal
= Tcl_NewStringObj(p
->pDb
->zNull
, -1);
1021 int bytes
= sqlite3_value_bytes(pIn
);
1022 pVal
= Tcl_NewStringObj((char *)sqlite3_value_text(pIn
), bytes
);
1026 rc
= Tcl_ListObjAppendElement(p
->interp
, pCmd
, pVal
);
1028 Tcl_DecrRefCount(pCmd
);
1029 sqlite3_result_error(context
, Tcl_GetStringResult(p
->interp
), -1);
1033 if( !p
->useEvalObjv
){
1034 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
1035 ** is a list without a string representation. To prevent this from
1036 ** happening, make sure pCmd has a valid string representation */
1037 Tcl_GetString(pCmd
);
1039 rc
= Tcl_EvalObjEx(p
->interp
, pCmd
, TCL_EVAL_DIRECT
);
1040 Tcl_DecrRefCount(pCmd
);
1043 if( rc
&& rc
!=TCL_RETURN
){
1044 sqlite3_result_error(context
, Tcl_GetStringResult(p
->interp
), -1);
1046 Tcl_Obj
*pVar
= Tcl_GetObjResult(p
->interp
);
1049 const char *zType
= (pVar
->typePtr
? pVar
->typePtr
->name
: "");
1051 int eType
= p
->eType
;
1053 if( eType
==SQLITE_NULL
){
1054 if( c
=='b' && strcmp(zType
,"bytearray")==0 && pVar
->bytes
==0 ){
1055 /* Only return a BLOB type if the Tcl variable is a bytearray and
1056 ** has no string representation. */
1057 eType
= SQLITE_BLOB
;
1058 }else if( (c
=='b' && strcmp(zType
,"boolean")==0)
1059 || (c
=='w' && strcmp(zType
,"wideInt")==0)
1060 || (c
=='i' && strcmp(zType
,"int")==0)
1062 eType
= SQLITE_INTEGER
;
1063 }else if( c
=='d' && strcmp(zType
,"double")==0 ){
1064 eType
= SQLITE_FLOAT
;
1066 eType
= SQLITE_TEXT
;
1072 data
= Tcl_GetByteArrayFromObj(pVar
, &n
);
1073 sqlite3_result_blob(context
, data
, n
, SQLITE_TRANSIENT
);
1076 case SQLITE_INTEGER
: {
1078 if( TCL_OK
==Tcl_GetWideIntFromObj(0, pVar
, &v
) ){
1079 sqlite3_result_int64(context
, v
);
1084 case SQLITE_FLOAT
: {
1086 if( TCL_OK
==Tcl_GetDoubleFromObj(0, pVar
, &r
) ){
1087 sqlite3_result_double(context
, r
);
1093 data
= (unsigned char *)Tcl_GetStringFromObj(pVar
, &n
);
1094 sqlite3_result_text(context
, (char *)data
, n
, SQLITE_TRANSIENT
);
1102 #ifndef SQLITE_OMIT_AUTHORIZATION
1104 ** This is the authentication function. It appends the authentication
1105 ** type code and the two arguments to zCmd[] then invokes the result
1106 ** on the interpreter. The reply is examined to determine if the
1107 ** authentication fails or succeeds.
1109 static int auth_callback(
1116 #ifdef SQLITE_USER_AUTHENTICATION
1124 /* EVIDENCE-OF: R-38590-62769 The first parameter to the authorizer
1125 ** callback is a copy of the third parameter to the
1126 ** sqlite3_set_authorizer() interface.
1128 SqliteDb
*pDb
= (SqliteDb
*)pArg
;
1129 if( pDb
->disableAuth
) return SQLITE_OK
;
1131 /* EVIDENCE-OF: R-56518-44310 The second parameter to the callback is an
1132 ** integer action code that specifies the particular action to be
1135 case SQLITE_COPY
: zCode
="SQLITE_COPY"; break;
1136 case SQLITE_CREATE_INDEX
: zCode
="SQLITE_CREATE_INDEX"; break;
1137 case SQLITE_CREATE_TABLE
: zCode
="SQLITE_CREATE_TABLE"; break;
1138 case SQLITE_CREATE_TEMP_INDEX
: zCode
="SQLITE_CREATE_TEMP_INDEX"; break;
1139 case SQLITE_CREATE_TEMP_TABLE
: zCode
="SQLITE_CREATE_TEMP_TABLE"; break;
1140 case SQLITE_CREATE_TEMP_TRIGGER
: zCode
="SQLITE_CREATE_TEMP_TRIGGER"; break;
1141 case SQLITE_CREATE_TEMP_VIEW
: zCode
="SQLITE_CREATE_TEMP_VIEW"; break;
1142 case SQLITE_CREATE_TRIGGER
: zCode
="SQLITE_CREATE_TRIGGER"; break;
1143 case SQLITE_CREATE_VIEW
: zCode
="SQLITE_CREATE_VIEW"; break;
1144 case SQLITE_DELETE
: zCode
="SQLITE_DELETE"; break;
1145 case SQLITE_DROP_INDEX
: zCode
="SQLITE_DROP_INDEX"; break;
1146 case SQLITE_DROP_TABLE
: zCode
="SQLITE_DROP_TABLE"; break;
1147 case SQLITE_DROP_TEMP_INDEX
: zCode
="SQLITE_DROP_TEMP_INDEX"; break;
1148 case SQLITE_DROP_TEMP_TABLE
: zCode
="SQLITE_DROP_TEMP_TABLE"; break;
1149 case SQLITE_DROP_TEMP_TRIGGER
: zCode
="SQLITE_DROP_TEMP_TRIGGER"; break;
1150 case SQLITE_DROP_TEMP_VIEW
: zCode
="SQLITE_DROP_TEMP_VIEW"; break;
1151 case SQLITE_DROP_TRIGGER
: zCode
="SQLITE_DROP_TRIGGER"; break;
1152 case SQLITE_DROP_VIEW
: zCode
="SQLITE_DROP_VIEW"; break;
1153 case SQLITE_INSERT
: zCode
="SQLITE_INSERT"; break;
1154 case SQLITE_PRAGMA
: zCode
="SQLITE_PRAGMA"; break;
1155 case SQLITE_READ
: zCode
="SQLITE_READ"; break;
1156 case SQLITE_SELECT
: zCode
="SQLITE_SELECT"; break;
1157 case SQLITE_TRANSACTION
: zCode
="SQLITE_TRANSACTION"; break;
1158 case SQLITE_UPDATE
: zCode
="SQLITE_UPDATE"; break;
1159 case SQLITE_ATTACH
: zCode
="SQLITE_ATTACH"; break;
1160 case SQLITE_DETACH
: zCode
="SQLITE_DETACH"; break;
1161 case SQLITE_ALTER_TABLE
: zCode
="SQLITE_ALTER_TABLE"; break;
1162 case SQLITE_REINDEX
: zCode
="SQLITE_REINDEX"; break;
1163 case SQLITE_ANALYZE
: zCode
="SQLITE_ANALYZE"; break;
1164 case SQLITE_CREATE_VTABLE
: zCode
="SQLITE_CREATE_VTABLE"; break;
1165 case SQLITE_DROP_VTABLE
: zCode
="SQLITE_DROP_VTABLE"; break;
1166 case SQLITE_FUNCTION
: zCode
="SQLITE_FUNCTION"; break;
1167 case SQLITE_SAVEPOINT
: zCode
="SQLITE_SAVEPOINT"; break;
1168 case SQLITE_RECURSIVE
: zCode
="SQLITE_RECURSIVE"; break;
1169 default : zCode
="????"; break;
1171 Tcl_DStringInit(&str
);
1172 Tcl_DStringAppend(&str
, pDb
->zAuth
, -1);
1173 Tcl_DStringAppendElement(&str
, zCode
);
1174 Tcl_DStringAppendElement(&str
, zArg1
? zArg1
: "");
1175 Tcl_DStringAppendElement(&str
, zArg2
? zArg2
: "");
1176 Tcl_DStringAppendElement(&str
, zArg3
? zArg3
: "");
1177 Tcl_DStringAppendElement(&str
, zArg4
? zArg4
: "");
1178 #ifdef SQLITE_USER_AUTHENTICATION
1179 Tcl_DStringAppendElement(&str
, zArg5
? zArg5
: "");
1181 rc
= Tcl_GlobalEval(pDb
->interp
, Tcl_DStringValue(&str
));
1182 Tcl_DStringFree(&str
);
1183 zReply
= rc
==TCL_OK
? Tcl_GetStringResult(pDb
->interp
) : "SQLITE_DENY";
1184 if( strcmp(zReply
,"SQLITE_OK")==0 ){
1186 }else if( strcmp(zReply
,"SQLITE_DENY")==0 ){
1188 }else if( strcmp(zReply
,"SQLITE_IGNORE")==0 ){
1195 #endif /* SQLITE_OMIT_AUTHORIZATION */
1198 ** This routine reads a line of text from FILE in, stores
1199 ** the text in memory obtained from malloc() and returns a pointer
1200 ** to the text. NULL is returned at end of file, or if malloc()
1203 ** The interface is like "readline" but no command-line editing
1206 ** copied from shell.c from '.import' command
1208 static char *local_getline(char *zPrompt
, FILE *in
){
1214 zLine
= malloc( nLine
);
1215 if( zLine
==0 ) return 0;
1219 nLine
= nLine
*2 + 100;
1220 zLine
= realloc(zLine
, nLine
);
1221 if( zLine
==0 ) return 0;
1223 if( fgets(&zLine
[n
], nLine
- n
, in
)==0 ){
1231 while( zLine
[n
] ){ n
++; }
1232 if( n
>0 && zLine
[n
-1]=='\n' ){
1238 zLine
= realloc( zLine
, n
+1 );
1244 ** This function is part of the implementation of the command:
1246 ** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1248 ** It is invoked after evaluating the script SCRIPT to commit or rollback
1249 ** the transaction or savepoint opened by the [transaction] command.
1251 static int SQLITE_TCLAPI
DbTransPostCmd(
1252 ClientData data
[], /* data[0] is the Sqlite3Db* for $db */
1253 Tcl_Interp
*interp
, /* Tcl interpreter */
1254 int result
/* Result of evaluating SCRIPT */
1256 static const char *const azEnd
[] = {
1257 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1258 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1259 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1260 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1262 SqliteDb
*pDb
= (SqliteDb
*)data
[0];
1266 pDb
->nTransaction
--;
1267 zEnd
= azEnd
[(rc
==TCL_ERROR
)*2 + (pDb
->nTransaction
==0)];
1270 if( sqlite3_exec(pDb
->db
, zEnd
, 0, 0, 0) ){
1271 /* This is a tricky scenario to handle. The most likely cause of an
1272 ** error is that the exec() above was an attempt to commit the
1273 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1274 ** that an IO-error has occurred. In either case, throw a Tcl exception
1275 ** and try to rollback the transaction.
1277 ** But it could also be that the user executed one or more BEGIN,
1278 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1279 ** this method's logic. Not clear how this would be best handled.
1281 if( rc
!=TCL_ERROR
){
1282 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
1285 sqlite3_exec(pDb
->db
, "ROLLBACK", 0, 0, 0);
1289 delDatabaseRef(pDb
);
1294 ** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1295 ** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1296 ** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1297 ** on whether or not the [db_use_legacy_prepare] command has been used to
1298 ** configure the connection.
1300 static int dbPrepare(
1301 SqliteDb
*pDb
, /* Database object */
1302 const char *zSql
, /* SQL to compile */
1303 sqlite3_stmt
**ppStmt
, /* OUT: Prepared statement */
1304 const char **pzOut
/* OUT: Pointer to next SQL statement */
1306 unsigned int prepFlags
= 0;
1308 if( pDb
->bLegacyPrepare
){
1309 return sqlite3_prepare(pDb
->db
, zSql
, -1, ppStmt
, pzOut
);
1312 /* If the statement cache is large, use the SQLITE_PREPARE_PERSISTENT
1313 ** flags, which uses less lookaside memory. But if the cache is small,
1314 ** omit that flag to make full use of lookaside */
1315 if( pDb
->maxStmt
>5 ) prepFlags
= SQLITE_PREPARE_PERSISTENT
;
1317 return sqlite3_prepare_v3(pDb
->db
, zSql
, -1, prepFlags
, ppStmt
, pzOut
);
1321 ** Search the cache for a prepared-statement object that implements the
1322 ** first SQL statement in the buffer pointed to by parameter zIn. If
1323 ** no such prepared-statement can be found, allocate and prepare a new
1324 ** one. In either case, bind the current values of the relevant Tcl
1325 ** variables to any $var, :var or @var variables in the statement. Before
1326 ** returning, set *ppPreStmt to point to the prepared-statement object.
1328 ** Output parameter *pzOut is set to point to the next SQL statement in
1329 ** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1332 ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1333 ** and an error message loaded into interpreter pDb->interp.
1335 static int dbPrepareAndBind(
1336 SqliteDb
*pDb
, /* Database object */
1337 char const *zIn
, /* SQL to compile */
1338 char const **pzOut
, /* OUT: Pointer to next SQL statement */
1339 SqlPreparedStmt
**ppPreStmt
/* OUT: Object used to cache statement */
1341 const char *zSql
= zIn
; /* Pointer to first SQL statement in zIn */
1342 sqlite3_stmt
*pStmt
= 0; /* Prepared statement object */
1343 SqlPreparedStmt
*pPreStmt
; /* Pointer to cached statement */
1344 int nSql
; /* Length of zSql in bytes */
1345 int nVar
= 0; /* Number of variables in statement */
1346 int iParm
= 0; /* Next free entry in apParm */
1349 int needResultReset
= 0; /* Need to invoke Tcl_ResetResult() */
1350 int rc
= SQLITE_OK
; /* Value to return */
1351 Tcl_Interp
*interp
= pDb
->interp
;
1355 /* Trim spaces from the start of zSql and calculate the remaining length. */
1356 while( (c
= zSql
[0])==' ' || c
=='\t' || c
=='\r' || c
=='\n' ){ zSql
++; }
1357 nSql
= strlen30(zSql
);
1359 for(pPreStmt
= pDb
->stmtList
; pPreStmt
; pPreStmt
=pPreStmt
->pNext
){
1360 int n
= pPreStmt
->nSql
;
1362 && memcmp(pPreStmt
->zSql
, zSql
, n
)==0
1363 && (zSql
[n
]==0 || zSql
[n
-1]==';')
1365 pStmt
= pPreStmt
->pStmt
;
1366 *pzOut
= &zSql
[pPreStmt
->nSql
];
1368 /* When a prepared statement is found, unlink it from the
1369 ** cache list. It will later be added back to the beginning
1370 ** of the cache list in order to implement LRU replacement.
1372 if( pPreStmt
->pPrev
){
1373 pPreStmt
->pPrev
->pNext
= pPreStmt
->pNext
;
1375 pDb
->stmtList
= pPreStmt
->pNext
;
1377 if( pPreStmt
->pNext
){
1378 pPreStmt
->pNext
->pPrev
= pPreStmt
->pPrev
;
1380 pDb
->stmtLast
= pPreStmt
->pPrev
;
1383 nVar
= sqlite3_bind_parameter_count(pStmt
);
1388 /* If no prepared statement was found. Compile the SQL text. Also allocate
1389 ** a new SqlPreparedStmt structure. */
1393 if( SQLITE_OK
!=dbPrepare(pDb
, zSql
, &pStmt
, pzOut
) ){
1394 Tcl_SetObjResult(interp
, Tcl_NewStringObj(sqlite3_errmsg(pDb
->db
), -1));
1398 if( SQLITE_OK
!=sqlite3_errcode(pDb
->db
) ){
1399 /* A compile-time error in the statement. */
1400 Tcl_SetObjResult(interp
, Tcl_NewStringObj(sqlite3_errmsg(pDb
->db
), -1));
1403 /* The statement was a no-op. Continue to the next statement
1404 ** in the SQL string.
1410 assert( pPreStmt
==0 );
1411 nVar
= sqlite3_bind_parameter_count(pStmt
);
1412 nByte
= sizeof(SqlPreparedStmt
) + nVar
*sizeof(Tcl_Obj
*);
1413 pPreStmt
= (SqlPreparedStmt
*)Tcl_Alloc(nByte
);
1414 memset(pPreStmt
, 0, nByte
);
1416 pPreStmt
->pStmt
= pStmt
;
1417 pPreStmt
->nSql
= (int)(*pzOut
- zSql
);
1418 pPreStmt
->zSql
= sqlite3_sql(pStmt
);
1419 pPreStmt
->apParm
= (Tcl_Obj
**)&pPreStmt
[1];
1421 if( pPreStmt
->zSql
==0 ){
1422 char *zCopy
= Tcl_Alloc(pPreStmt
->nSql
+ 1);
1423 memcpy(zCopy
, zSql
, pPreStmt
->nSql
);
1424 zCopy
[pPreStmt
->nSql
] = '\0';
1425 pPreStmt
->zSql
= zCopy
;
1430 assert( strlen30(pPreStmt
->zSql
)==pPreStmt
->nSql
);
1431 assert( 0==memcmp(pPreStmt
->zSql
, zSql
, pPreStmt
->nSql
) );
1433 /* Bind values to parameters that begin with $ or : */
1434 for(i
=1; i
<=nVar
; i
++){
1435 const char *zVar
= sqlite3_bind_parameter_name(pStmt
, i
);
1436 if( zVar
!=0 && (zVar
[0]=='$' || zVar
[0]==':' || zVar
[0]=='@') ){
1437 Tcl_Obj
*pVar
= Tcl_GetVar2Ex(interp
, &zVar
[1], 0, 0);
1438 if( pVar
==0 && pDb
->zBindFallback
!=0 ){
1441 pCmd
= Tcl_NewStringObj(pDb
->zBindFallback
, -1);
1442 Tcl_IncrRefCount(pCmd
);
1443 Tcl_ListObjAppendElement(interp
, pCmd
, Tcl_NewStringObj(zVar
,-1));
1444 if( needResultReset
) Tcl_ResetResult(interp
);
1445 needResultReset
= 1;
1446 rx
= Tcl_EvalObjEx(interp
, pCmd
, TCL_EVAL_DIRECT
);
1447 Tcl_DecrRefCount(pCmd
);
1449 pVar
= Tcl_GetObjResult(interp
);
1450 }else if( rx
==TCL_ERROR
){
1460 const char *zType
= (pVar
->typePtr
? pVar
->typePtr
->name
: "");
1463 (c
=='b' && strcmp(zType
,"bytearray")==0 && pVar
->bytes
==0) ){
1464 /* Load a BLOB type if the Tcl variable is a bytearray and
1465 ** it has no string representation or the host
1466 ** parameter name begins with "@". */
1467 data
= Tcl_GetByteArrayFromObj(pVar
, &n
);
1468 sqlite3_bind_blob(pStmt
, i
, data
, n
, SQLITE_STATIC
);
1469 Tcl_IncrRefCount(pVar
);
1470 pPreStmt
->apParm
[iParm
++] = pVar
;
1471 }else if( c
=='b' && strcmp(zType
,"boolean")==0 ){
1472 Tcl_GetIntFromObj(interp
, pVar
, &n
);
1473 sqlite3_bind_int(pStmt
, i
, n
);
1474 }else if( c
=='d' && strcmp(zType
,"double")==0 ){
1476 Tcl_GetDoubleFromObj(interp
, pVar
, &r
);
1477 sqlite3_bind_double(pStmt
, i
, r
);
1478 }else if( (c
=='w' && strcmp(zType
,"wideInt")==0) ||
1479 (c
=='i' && strcmp(zType
,"int")==0) ){
1481 Tcl_GetWideIntFromObj(interp
, pVar
, &v
);
1482 sqlite3_bind_int64(pStmt
, i
, v
);
1484 data
= (unsigned char *)Tcl_GetStringFromObj(pVar
, &n
);
1485 sqlite3_bind_text(pStmt
, i
, (char *)data
, n
, SQLITE_STATIC
);
1486 Tcl_IncrRefCount(pVar
);
1487 pPreStmt
->apParm
[iParm
++] = pVar
;
1490 sqlite3_bind_null(pStmt
, i
);
1492 if( needResultReset
) Tcl_ResetResult(pDb
->interp
);
1495 pPreStmt
->nParm
= iParm
;
1496 *ppPreStmt
= pPreStmt
;
1497 if( needResultReset
&& rc
==TCL_OK
) Tcl_ResetResult(pDb
->interp
);
1503 ** Release a statement reference obtained by calling dbPrepareAndBind().
1504 ** There should be exactly one call to this function for each call to
1505 ** dbPrepareAndBind().
1507 ** If the discard parameter is non-zero, then the statement is deleted
1508 ** immediately. Otherwise it is added to the LRU list and may be returned
1509 ** by a subsequent call to dbPrepareAndBind().
1511 static void dbReleaseStmt(
1512 SqliteDb
*pDb
, /* Database handle */
1513 SqlPreparedStmt
*pPreStmt
, /* Prepared statement handle to release */
1514 int discard
/* True to delete (not cache) the pPreStmt */
1518 /* Free the bound string and blob parameters */
1519 for(i
=0; i
<pPreStmt
->nParm
; i
++){
1520 Tcl_DecrRefCount(pPreStmt
->apParm
[i
]);
1522 pPreStmt
->nParm
= 0;
1524 if( pDb
->maxStmt
<=0 || discard
){
1525 /* If the cache is turned off, deallocated the statement */
1526 dbFreeStmt(pPreStmt
);
1528 /* Add the prepared statement to the beginning of the cache list. */
1529 pPreStmt
->pNext
= pDb
->stmtList
;
1530 pPreStmt
->pPrev
= 0;
1531 if( pDb
->stmtList
){
1532 pDb
->stmtList
->pPrev
= pPreStmt
;
1534 pDb
->stmtList
= pPreStmt
;
1535 if( pDb
->stmtLast
==0 ){
1536 assert( pDb
->nStmt
==0 );
1537 pDb
->stmtLast
= pPreStmt
;
1539 assert( pDb
->nStmt
>0 );
1543 /* If we have too many statement in cache, remove the surplus from
1544 ** the end of the cache list. */
1545 while( pDb
->nStmt
>pDb
->maxStmt
){
1546 SqlPreparedStmt
*pLast
= pDb
->stmtLast
;
1547 pDb
->stmtLast
= pLast
->pPrev
;
1548 pDb
->stmtLast
->pNext
= 0;
1556 ** Structure used with dbEvalXXX() functions:
1562 ** dbEvalColumnValue()
1564 typedef struct DbEvalContext DbEvalContext
;
1565 struct DbEvalContext
{
1566 SqliteDb
*pDb
; /* Database handle */
1567 Tcl_Obj
*pSql
; /* Object holding string zSql */
1568 const char *zSql
; /* Remaining SQL to execute */
1569 SqlPreparedStmt
*pPreStmt
; /* Current statement */
1570 int nCol
; /* Number of columns returned by pStmt */
1571 int evalFlags
; /* Flags used */
1572 Tcl_Obj
*pArray
; /* Name of array variable */
1573 Tcl_Obj
**apColName
; /* Array of column names */
1576 #define SQLITE_EVAL_WITHOUTNULLS 0x00001 /* Unset array(*) for NULL */
1579 ** Release any cache of column names currently held as part of
1580 ** the DbEvalContext structure passed as the first argument.
1582 static void dbReleaseColumnNames(DbEvalContext
*p
){
1585 for(i
=0; i
<p
->nCol
; i
++){
1586 Tcl_DecrRefCount(p
->apColName
[i
]);
1588 Tcl_Free((char *)p
->apColName
);
1595 ** Initialize a DbEvalContext structure.
1597 ** If pArray is not NULL, then it contains the name of a Tcl array
1598 ** variable. The "*" member of this array is set to a list containing
1599 ** the names of the columns returned by the statement as part of each
1600 ** call to dbEvalStep(), in order from left to right. e.g. if the names
1601 ** of the returned columns are a, b and c, it does the equivalent of the
1604 ** set ${pArray}(*) {a b c}
1606 static void dbEvalInit(
1607 DbEvalContext
*p
, /* Pointer to structure to initialize */
1608 SqliteDb
*pDb
, /* Database handle */
1609 Tcl_Obj
*pSql
, /* Object containing SQL script */
1610 Tcl_Obj
*pArray
, /* Name of Tcl array to set (*) element of */
1611 int evalFlags
/* Flags controlling evaluation */
1613 memset(p
, 0, sizeof(DbEvalContext
));
1615 p
->zSql
= Tcl_GetString(pSql
);
1617 Tcl_IncrRefCount(pSql
);
1620 Tcl_IncrRefCount(pArray
);
1622 p
->evalFlags
= evalFlags
;
1623 addDatabaseRef(p
->pDb
);
1627 ** Obtain information about the row that the DbEvalContext passed as the
1628 ** first argument currently points to.
1630 static void dbEvalRowInfo(
1631 DbEvalContext
*p
, /* Evaluation context */
1632 int *pnCol
, /* OUT: Number of column names */
1633 Tcl_Obj
***papColName
/* OUT: Array of column names */
1635 /* Compute column names */
1636 if( 0==p
->apColName
){
1637 sqlite3_stmt
*pStmt
= p
->pPreStmt
->pStmt
;
1638 int i
; /* Iterator variable */
1639 int nCol
; /* Number of columns returned by pStmt */
1640 Tcl_Obj
**apColName
= 0; /* Array of column names */
1642 p
->nCol
= nCol
= sqlite3_column_count(pStmt
);
1643 if( nCol
>0 && (papColName
|| p
->pArray
) ){
1644 apColName
= (Tcl_Obj
**)Tcl_Alloc( sizeof(Tcl_Obj
*)*nCol
);
1645 for(i
=0; i
<nCol
; i
++){
1646 apColName
[i
] = Tcl_NewStringObj(sqlite3_column_name(pStmt
,i
), -1);
1647 Tcl_IncrRefCount(apColName
[i
]);
1649 p
->apColName
= apColName
;
1652 /* If results are being stored in an array variable, then create
1653 ** the array(*) entry for that array
1656 Tcl_Interp
*interp
= p
->pDb
->interp
;
1657 Tcl_Obj
*pColList
= Tcl_NewObj();
1658 Tcl_Obj
*pStar
= Tcl_NewStringObj("*", -1);
1660 for(i
=0; i
<nCol
; i
++){
1661 Tcl_ListObjAppendElement(interp
, pColList
, apColName
[i
]);
1663 Tcl_IncrRefCount(pStar
);
1664 Tcl_ObjSetVar2(interp
, p
->pArray
, pStar
, pColList
, 0);
1665 Tcl_DecrRefCount(pStar
);
1670 *papColName
= p
->apColName
;
1678 ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1679 ** returned, then an error message is stored in the interpreter before
1682 ** A return value of TCL_OK means there is a row of data available. The
1683 ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1684 ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1685 ** is returned, then the SQL script has finished executing and there are
1686 ** no further rows available. This is similar to SQLITE_DONE.
1688 static int dbEvalStep(DbEvalContext
*p
){
1689 const char *zPrevSql
= 0; /* Previous value of p->zSql */
1691 while( p
->zSql
[0] || p
->pPreStmt
){
1693 if( p
->pPreStmt
==0 ){
1694 zPrevSql
= (p
->zSql
==zPrevSql
? 0 : p
->zSql
);
1695 rc
= dbPrepareAndBind(p
->pDb
, p
->zSql
, &p
->zSql
, &p
->pPreStmt
);
1696 if( rc
!=TCL_OK
) return rc
;
1699 SqliteDb
*pDb
= p
->pDb
;
1700 SqlPreparedStmt
*pPreStmt
= p
->pPreStmt
;
1701 sqlite3_stmt
*pStmt
= pPreStmt
->pStmt
;
1703 rcs
= sqlite3_step(pStmt
);
1704 if( rcs
==SQLITE_ROW
){
1708 dbEvalRowInfo(p
, 0, 0);
1710 rcs
= sqlite3_reset(pStmt
);
1712 pDb
->nStep
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_FULLSCAN_STEP
,1);
1713 pDb
->nSort
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_SORT
,1);
1714 pDb
->nIndex
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_AUTOINDEX
,1);
1715 pDb
->nVMStep
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_VM_STEP
,1);
1716 dbReleaseColumnNames(p
);
1719 if( rcs
!=SQLITE_OK
){
1720 /* If a run-time error occurs, report the error and stop reading
1722 dbReleaseStmt(pDb
, pPreStmt
, 1);
1724 if( p
->pDb
->bLegacyPrepare
&& rcs
==SQLITE_SCHEMA
&& zPrevSql
){
1725 /* If the runtime error was an SQLITE_SCHEMA, and the database
1726 ** handle is configured to use the legacy sqlite3_prepare()
1727 ** interface, retry prepare()/step() on the same SQL statement.
1728 ** This only happens once. If there is a second SQLITE_SCHEMA
1729 ** error, the error will be returned to the caller. */
1734 Tcl_SetObjResult(pDb
->interp
,
1735 Tcl_NewStringObj(sqlite3_errmsg(pDb
->db
), -1));
1738 dbReleaseStmt(pDb
, pPreStmt
, 0);
1748 ** Free all resources currently held by the DbEvalContext structure passed
1749 ** as the first argument. There should be exactly one call to this function
1750 ** for each call to dbEvalInit().
1752 static void dbEvalFinalize(DbEvalContext
*p
){
1754 sqlite3_reset(p
->pPreStmt
->pStmt
);
1755 dbReleaseStmt(p
->pDb
, p
->pPreStmt
, 0);
1759 Tcl_DecrRefCount(p
->pArray
);
1762 Tcl_DecrRefCount(p
->pSql
);
1763 dbReleaseColumnNames(p
);
1764 delDatabaseRef(p
->pDb
);
1768 ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1769 ** the value for the iCol'th column of the row currently pointed to by
1770 ** the DbEvalContext structure passed as the first argument.
1772 static Tcl_Obj
*dbEvalColumnValue(DbEvalContext
*p
, int iCol
){
1773 sqlite3_stmt
*pStmt
= p
->pPreStmt
->pStmt
;
1774 switch( sqlite3_column_type(pStmt
, iCol
) ){
1776 int bytes
= sqlite3_column_bytes(pStmt
, iCol
);
1777 const char *zBlob
= sqlite3_column_blob(pStmt
, iCol
);
1778 if( !zBlob
) bytes
= 0;
1779 return Tcl_NewByteArrayObj((u8
*)zBlob
, bytes
);
1781 case SQLITE_INTEGER
: {
1782 sqlite_int64 v
= sqlite3_column_int64(pStmt
, iCol
);
1783 if( v
>=-2147483647 && v
<=2147483647 ){
1784 return Tcl_NewIntObj((int)v
);
1786 return Tcl_NewWideIntObj(v
);
1789 case SQLITE_FLOAT
: {
1790 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt
, iCol
));
1793 return Tcl_NewStringObj(p
->pDb
->zNull
, -1);
1797 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt
, iCol
), -1);
1801 ** If using Tcl version 8.6 or greater, use the NR functions to avoid
1802 ** recursive evaluation of scripts by the [db eval] and [db trans]
1803 ** commands. Even if the headers used while compiling the extension
1804 ** are 8.6 or newer, the code still tests the Tcl version at runtime.
1805 ** This allows stubs-enabled builds to be used with older Tcl libraries.
1807 #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
1808 # define SQLITE_TCL_NRE 1
1809 static int DbUseNre(void){
1811 Tcl_GetVersion(&major
, &minor
, 0, 0);
1812 return( (major
==8 && minor
>=6) || major
>8 );
1816 ** Compiling using headers earlier than 8.6. In this case NR cannot be
1817 ** used, so DbUseNre() to always return zero. Add #defines for the other
1818 ** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1819 ** even though the only invocations of them are within conditional blocks
1822 ** if( DbUseNre() ) { ... }
1824 # define SQLITE_TCL_NRE 0
1825 # define DbUseNre() 0
1826 # define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
1827 # define Tcl_NREvalObj(a,b,c) 0
1828 # define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
1832 ** This function is part of the implementation of the command:
1834 ** $db eval SQL ?ARRAYNAME? SCRIPT
1836 static int SQLITE_TCLAPI
DbEvalNextCmd(
1837 ClientData data
[], /* data[0] is the (DbEvalContext*) */
1838 Tcl_Interp
*interp
, /* Tcl interpreter */
1839 int result
/* Result so far */
1841 int rc
= result
; /* Return code */
1843 /* The first element of the data[] array is a pointer to a DbEvalContext
1844 ** structure allocated using Tcl_Alloc(). The second element of data[]
1845 ** is a pointer to a Tcl_Obj containing the script to run for each row
1846 ** returned by the queries encapsulated in data[0]. */
1847 DbEvalContext
*p
= (DbEvalContext
*)data
[0];
1848 Tcl_Obj
*pScript
= (Tcl_Obj
*)data
[1];
1849 Tcl_Obj
*pArray
= p
->pArray
;
1851 while( (rc
==TCL_OK
|| rc
==TCL_CONTINUE
) && TCL_OK
==(rc
= dbEvalStep(p
)) ){
1854 Tcl_Obj
**apColName
;
1855 dbEvalRowInfo(p
, &nCol
, &apColName
);
1856 for(i
=0; i
<nCol
; i
++){
1858 Tcl_ObjSetVar2(interp
, apColName
[i
], 0, dbEvalColumnValue(p
,i
), 0);
1859 }else if( (p
->evalFlags
& SQLITE_EVAL_WITHOUTNULLS
)!=0
1860 && sqlite3_column_type(p
->pPreStmt
->pStmt
, i
)==SQLITE_NULL
1862 Tcl_UnsetVar2(interp
, Tcl_GetString(pArray
),
1863 Tcl_GetString(apColName
[i
]), 0);
1865 Tcl_ObjSetVar2(interp
, pArray
, apColName
[i
], dbEvalColumnValue(p
,i
), 0);
1869 /* The required interpreter variables are now populated with the data
1870 ** from the current row. If using NRE, schedule callbacks to evaluate
1871 ** script pScript, then to invoke this function again to fetch the next
1872 ** row (or clean up if there is no next row or the script throws an
1873 ** exception). After scheduling the callbacks, return control to the
1876 ** If not using NRE, evaluate pScript directly and continue with the
1877 ** next iteration of this while(...) loop. */
1879 Tcl_NRAddCallback(interp
, DbEvalNextCmd
, (void*)p
, (void*)pScript
, 0, 0);
1880 return Tcl_NREvalObj(interp
, pScript
, 0);
1882 rc
= Tcl_EvalObjEx(interp
, pScript
, 0);
1886 Tcl_DecrRefCount(pScript
);
1888 Tcl_Free((char *)p
);
1890 if( rc
==TCL_OK
|| rc
==TCL_BREAK
){
1891 Tcl_ResetResult(interp
);
1898 ** This function is used by the implementations of the following database
1899 ** handle sub-commands:
1901 ** $db update_hook ?SCRIPT?
1902 ** $db wal_hook ?SCRIPT?
1903 ** $db commit_hook ?SCRIPT?
1904 ** $db preupdate hook ?SCRIPT?
1906 static void DbHookCmd(
1907 Tcl_Interp
*interp
, /* Tcl interpreter */
1908 SqliteDb
*pDb
, /* Database handle */
1909 Tcl_Obj
*pArg
, /* SCRIPT argument (or NULL) */
1910 Tcl_Obj
**ppHook
/* Pointer to member of SqliteDb */
1912 sqlite3
*db
= pDb
->db
;
1915 Tcl_SetObjResult(interp
, *ppHook
);
1917 Tcl_DecrRefCount(*ppHook
);
1922 assert( !(*ppHook
) );
1923 if( Tcl_GetCharLength(pArg
)>0 ){
1925 Tcl_IncrRefCount(*ppHook
);
1929 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1930 sqlite3_preupdate_hook(db
, (pDb
->pPreUpdateHook
?DbPreUpdateHandler
:0), pDb
);
1932 sqlite3_update_hook(db
, (pDb
->pUpdateHook
?DbUpdateHandler
:0), pDb
);
1933 sqlite3_rollback_hook(db
, (pDb
->pRollbackHook
?DbRollbackHandler
:0), pDb
);
1934 sqlite3_wal_hook(db
, (pDb
->pWalHook
?DbWalHandler
:0), pDb
);
1938 ** The "sqlite" command below creates a new Tcl command for each
1939 ** connection it opens to an SQLite database. This routine is invoked
1940 ** whenever one of those connection-specific commands is executed
1941 ** in Tcl. For example, if you run Tcl code like this:
1943 ** sqlite3 db1 "my_database"
1946 ** The first command opens a connection to the "my_database" database
1947 ** and calls that connection "db1". The second command causes this
1948 ** subroutine to be invoked.
1950 static int SQLITE_TCLAPI
DbObjCmd(
1956 SqliteDb
*pDb
= (SqliteDb
*)cd
;
1959 static const char *DB_strs
[] = {
1960 "authorizer", "backup", "bind_fallback",
1961 "busy", "cache", "changes",
1962 "close", "collate", "collation_needed",
1963 "commit_hook", "complete", "config",
1964 "copy", "deserialize", "enable_load_extension",
1965 "errorcode", "erroroffset", "eval",
1966 "exists", "function", "incrblob",
1967 "interrupt", "last_insert_rowid", "nullvalue",
1968 "onecolumn", "preupdate", "profile",
1969 "progress", "rekey", "restore",
1970 "rollback_hook", "serialize", "status",
1971 "timeout", "total_changes", "trace",
1972 "trace_v2", "transaction", "unlock_notify",
1973 "update_hook", "version", "wal_hook",
1977 DB_AUTHORIZER
, DB_BACKUP
, DB_BIND_FALLBACK
,
1978 DB_BUSY
, DB_CACHE
, DB_CHANGES
,
1979 DB_CLOSE
, DB_COLLATE
, DB_COLLATION_NEEDED
,
1980 DB_COMMIT_HOOK
, DB_COMPLETE
, DB_CONFIG
,
1981 DB_COPY
, DB_DESERIALIZE
, DB_ENABLE_LOAD_EXTENSION
,
1982 DB_ERRORCODE
, DB_ERROROFFSET
, DB_EVAL
,
1983 DB_EXISTS
, DB_FUNCTION
, DB_INCRBLOB
,
1984 DB_INTERRUPT
, DB_LAST_INSERT_ROWID
, DB_NULLVALUE
,
1985 DB_ONECOLUMN
, DB_PREUPDATE
, DB_PROFILE
,
1986 DB_PROGRESS
, DB_REKEY
, DB_RESTORE
,
1987 DB_ROLLBACK_HOOK
, DB_SERIALIZE
, DB_STATUS
,
1988 DB_TIMEOUT
, DB_TOTAL_CHANGES
, DB_TRACE
,
1989 DB_TRACE_V2
, DB_TRANSACTION
, DB_UNLOCK_NOTIFY
,
1990 DB_UPDATE_HOOK
, DB_VERSION
, DB_WAL_HOOK
,
1992 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
1995 Tcl_WrongNumArgs(interp
, 1, objv
, "SUBCOMMAND ...");
1998 if( Tcl_GetIndexFromObj(interp
, objv
[1], DB_strs
, "option", 0, &choice
) ){
2002 switch( (enum DB_enum
)choice
){
2004 /* $db authorizer ?CALLBACK?
2006 ** Invoke the given callback to authorize each SQL operation as it is
2007 ** compiled. 5 arguments are appended to the callback before it is
2010 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
2011 ** (2) First descriptive name (depends on authorization type)
2012 ** (3) Second descriptive name
2013 ** (4) Name of the database (ex: "main", "temp")
2014 ** (5) Name of trigger that is doing the access
2016 ** The callback should return on of the following strings: SQLITE_OK,
2017 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
2019 ** If this method is invoked with no arguments, the current authorization
2020 ** callback string is returned.
2022 case DB_AUTHORIZER
: {
2023 #ifdef SQLITE_OMIT_AUTHORIZATION
2024 Tcl_AppendResult(interp
, "authorization not available in this build",
2029 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
2031 }else if( objc
==2 ){
2033 Tcl_AppendResult(interp
, pDb
->zAuth
, (char*)0);
2039 Tcl_Free(pDb
->zAuth
);
2041 zAuth
= Tcl_GetStringFromObj(objv
[2], &len
);
2042 if( zAuth
&& len
>0 ){
2043 pDb
->zAuth
= Tcl_Alloc( len
+ 1 );
2044 memcpy(pDb
->zAuth
, zAuth
, len
+1);
2049 typedef int (*sqlite3_auth_cb
)(
2050 void*,int,const char*,const char*,
2051 const char*,const char*);
2052 pDb
->interp
= interp
;
2053 sqlite3_set_authorizer(pDb
->db
,(sqlite3_auth_cb
)auth_callback
,pDb
);
2055 sqlite3_set_authorizer(pDb
->db
, 0, 0);
2062 /* $db backup ?DATABASE? FILENAME
2064 ** Open or create a database file named FILENAME. Transfer the
2065 ** content of local database DATABASE (default: "main") into the
2066 ** FILENAME database.
2069 const char *zDestFile
;
2072 sqlite3_backup
*pBackup
;
2076 zDestFile
= Tcl_GetString(objv
[2]);
2077 }else if( objc
==4 ){
2078 zSrcDb
= Tcl_GetString(objv
[2]);
2079 zDestFile
= Tcl_GetString(objv
[3]);
2081 Tcl_WrongNumArgs(interp
, 2, objv
, "?DATABASE? FILENAME");
2084 rc
= sqlite3_open_v2(zDestFile
, &pDest
,
2085 SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
| pDb
->openFlags
, 0);
2086 if( rc
!=SQLITE_OK
){
2087 Tcl_AppendResult(interp
, "cannot open target database: ",
2088 sqlite3_errmsg(pDest
), (char*)0);
2089 sqlite3_close(pDest
);
2092 pBackup
= sqlite3_backup_init(pDest
, "main", pDb
->db
, zSrcDb
);
2094 Tcl_AppendResult(interp
, "backup failed: ",
2095 sqlite3_errmsg(pDest
), (char*)0);
2096 sqlite3_close(pDest
);
2099 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
){}
2100 sqlite3_backup_finish(pBackup
);
2101 if( rc
==SQLITE_DONE
){
2104 Tcl_AppendResult(interp
, "backup failed: ",
2105 sqlite3_errmsg(pDest
), (char*)0);
2108 sqlite3_close(pDest
);
2112 /* $db bind_fallback ?CALLBACK?
2114 ** When resolving bind parameters in an SQL statement, if the parameter
2115 ** cannot be associated with a TCL variable then invoke CALLBACK with a
2116 ** single argument that is the name of the parameter and use the return
2117 ** value of the CALLBACK as the binding. If CALLBACK returns something
2118 ** other than TCL_OK or TCL_ERROR then bind a NULL.
2120 ** If CALLBACK is an empty string, then revert to the default behavior
2121 ** which is to set the binding to NULL.
2123 ** If CALLBACK returns an error, that causes the statement execution to
2124 ** abort. Hence, to configure a connection so that it throws an error
2125 ** on an attempt to bind an unknown variable, do something like this:
2127 ** proc bind_error {name} {error "no such variable: $name"}
2128 ** db bind_fallback bind_error
2130 case DB_BIND_FALLBACK
: {
2132 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
2134 }else if( objc
==2 ){
2135 if( pDb
->zBindFallback
){
2136 Tcl_AppendResult(interp
, pDb
->zBindFallback
, (char*)0);
2141 if( pDb
->zBindFallback
){
2142 Tcl_Free(pDb
->zBindFallback
);
2144 zCallback
= Tcl_GetStringFromObj(objv
[2], &len
);
2145 if( zCallback
&& len
>0 ){
2146 pDb
->zBindFallback
= Tcl_Alloc( len
+ 1 );
2147 memcpy(pDb
->zBindFallback
, zCallback
, len
+1);
2149 pDb
->zBindFallback
= 0;
2155 /* $db busy ?CALLBACK?
2157 ** Invoke the given callback if an SQL statement attempts to open
2158 ** a locked database file.
2162 Tcl_WrongNumArgs(interp
, 2, objv
, "CALLBACK");
2164 }else if( objc
==2 ){
2166 Tcl_AppendResult(interp
, pDb
->zBusy
, (char*)0);
2172 Tcl_Free(pDb
->zBusy
);
2174 zBusy
= Tcl_GetStringFromObj(objv
[2], &len
);
2175 if( zBusy
&& len
>0 ){
2176 pDb
->zBusy
= Tcl_Alloc( len
+ 1 );
2177 memcpy(pDb
->zBusy
, zBusy
, len
+1);
2182 pDb
->interp
= interp
;
2183 sqlite3_busy_handler(pDb
->db
, DbBusyHandler
, pDb
);
2185 sqlite3_busy_handler(pDb
->db
, 0, 0);
2194 ** Flush the prepared statement cache, or set the maximum number of
2195 ** cached statements.
2202 Tcl_WrongNumArgs(interp
, 1, objv
, "cache option ?arg?");
2205 subCmd
= Tcl_GetStringFromObj( objv
[2], 0 );
2206 if( *subCmd
=='f' && strcmp(subCmd
,"flush")==0 ){
2208 Tcl_WrongNumArgs(interp
, 2, objv
, "flush");
2211 flushStmtCache( pDb
);
2213 }else if( *subCmd
=='s' && strcmp(subCmd
,"size")==0 ){
2215 Tcl_WrongNumArgs(interp
, 2, objv
, "size n");
2218 if( TCL_ERROR
==Tcl_GetIntFromObj(interp
, objv
[3], &n
) ){
2219 Tcl_AppendResult( interp
, "cannot convert \"",
2220 Tcl_GetStringFromObj(objv
[3],0), "\" to integer", (char*)0);
2224 flushStmtCache( pDb
);
2226 }else if( n
>MAX_PREPARED_STMTS
){
2227 n
= MAX_PREPARED_STMTS
;
2233 Tcl_AppendResult( interp
, "bad option \"",
2234 Tcl_GetStringFromObj(objv
[2],0), "\": must be flush or size",
2243 ** Return the number of rows that were modified, inserted, or deleted by
2244 ** the most recent INSERT, UPDATE or DELETE statement, not including
2245 ** any changes made by trigger programs.
2250 Tcl_WrongNumArgs(interp
, 2, objv
, "");
2253 pResult
= Tcl_GetObjResult(interp
);
2254 Tcl_SetWideIntObj(pResult
, sqlite3_changes64(pDb
->db
));
2260 ** Shutdown the database
2263 Tcl_DeleteCommand(interp
, Tcl_GetStringFromObj(objv
[0], 0));
2268 ** $db collate NAME SCRIPT
2270 ** Create a new SQL collation function called NAME. Whenever
2271 ** that function is called, invoke SCRIPT to evaluate the function.
2274 SqlCollate
*pCollate
;
2279 Tcl_WrongNumArgs(interp
, 2, objv
, "NAME SCRIPT");
2282 zName
= Tcl_GetStringFromObj(objv
[2], 0);
2283 zScript
= Tcl_GetStringFromObj(objv
[3], &nScript
);
2284 pCollate
= (SqlCollate
*)Tcl_Alloc( sizeof(*pCollate
) + nScript
+ 1 );
2285 if( pCollate
==0 ) return TCL_ERROR
;
2286 pCollate
->interp
= interp
;
2287 pCollate
->pNext
= pDb
->pCollate
;
2288 pCollate
->zScript
= (char*)&pCollate
[1];
2289 pDb
->pCollate
= pCollate
;
2290 memcpy(pCollate
->zScript
, zScript
, nScript
+1);
2291 if( sqlite3_create_collation(pDb
->db
, zName
, SQLITE_UTF8
,
2292 pCollate
, tclSqlCollate
) ){
2293 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(pDb
->db
), TCL_VOLATILE
);
2300 ** $db collation_needed SCRIPT
2302 ** Create a new SQL collation function called NAME. Whenever
2303 ** that function is called, invoke SCRIPT to evaluate the function.
2305 case DB_COLLATION_NEEDED
: {
2307 Tcl_WrongNumArgs(interp
, 2, objv
, "SCRIPT");
2310 if( pDb
->pCollateNeeded
){
2311 Tcl_DecrRefCount(pDb
->pCollateNeeded
);
2313 pDb
->pCollateNeeded
= Tcl_DuplicateObj(objv
[2]);
2314 Tcl_IncrRefCount(pDb
->pCollateNeeded
);
2315 sqlite3_collation_needed(pDb
->db
, pDb
, tclCollateNeeded
);
2319 /* $db commit_hook ?CALLBACK?
2321 ** Invoke the given callback just before committing every SQL transaction.
2322 ** If the callback throws an exception or returns non-zero, then the
2323 ** transaction is aborted. If CALLBACK is an empty string, the callback
2326 case DB_COMMIT_HOOK
: {
2328 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
2330 }else if( objc
==2 ){
2332 Tcl_AppendResult(interp
, pDb
->zCommit
, (char*)0);
2335 const char *zCommit
;
2338 Tcl_Free(pDb
->zCommit
);
2340 zCommit
= Tcl_GetStringFromObj(objv
[2], &len
);
2341 if( zCommit
&& len
>0 ){
2342 pDb
->zCommit
= Tcl_Alloc( len
+ 1 );
2343 memcpy(pDb
->zCommit
, zCommit
, len
+1);
2348 pDb
->interp
= interp
;
2349 sqlite3_commit_hook(pDb
->db
, DbCommitHandler
, pDb
);
2351 sqlite3_commit_hook(pDb
->db
, 0, 0);
2359 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2360 ** additional lines of input are needed. This is similar to the
2361 ** built-in "info complete" command of Tcl.
2364 #ifndef SQLITE_OMIT_COMPLETE
2368 Tcl_WrongNumArgs(interp
, 2, objv
, "SQL");
2371 isComplete
= sqlite3_complete( Tcl_GetStringFromObj(objv
[2], 0) );
2372 pResult
= Tcl_GetObjResult(interp
);
2373 Tcl_SetBooleanObj(pResult
, isComplete
);
2378 /* $db config ?OPTION? ?BOOLEAN?
2380 ** Configure the database connection using the sqlite3_db_config()
2384 static const struct DbConfigChoices
{
2388 { "defensive", SQLITE_DBCONFIG_DEFENSIVE
},
2389 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL
},
2390 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML
},
2391 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY
},
2392 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG
},
2393 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER
},
2394 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW
},
2395 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
},
2396 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE
},
2397 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT
},
2398 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
},
2399 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE
},
2400 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE
},
2401 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP
},
2402 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA
},
2403 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA
},
2408 Tcl_WrongNumArgs(interp
, 2, objv
, "?OPTION? ?BOOLEAN?");
2412 /* With no arguments, list all configuration options and with the
2414 pResult
= Tcl_NewListObj(0,0);
2415 for(ii
=0; ii
<sizeof(aDbConfig
)/sizeof(aDbConfig
[0]); ii
++){
2417 sqlite3_db_config(pDb
->db
, aDbConfig
[ii
].op
, -1, &v
);
2418 Tcl_ListObjAppendElement(interp
, pResult
,
2419 Tcl_NewStringObj(aDbConfig
[ii
].zName
,-1));
2420 Tcl_ListObjAppendElement(interp
, pResult
,
2424 const char *zOpt
= Tcl_GetString(objv
[2]);
2427 if( zOpt
[0]=='-' ) zOpt
++;
2428 for(ii
=0; ii
<sizeof(aDbConfig
)/sizeof(aDbConfig
[0]); ii
++){
2429 if( strcmp(aDbConfig
[ii
].zName
, zOpt
)==0 ) break;
2431 if( ii
>=sizeof(aDbConfig
)/sizeof(aDbConfig
[0]) ){
2432 Tcl_AppendResult(interp
, "unknown config option: \"", zOpt
,
2437 if( Tcl_GetBooleanFromObj(interp
, objv
[3], &onoff
) ){
2441 sqlite3_db_config(pDb
->db
, aDbConfig
[ii
].op
, onoff
, &v
);
2442 pResult
= Tcl_NewIntObj(v
);
2444 Tcl_SetObjResult(interp
, pResult
);
2448 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2450 ** Copy data into table from filename, optionally using SEPARATOR
2451 ** as column separators. If a column contains a null string, or the
2452 ** value of NULLINDICATOR, a NULL is inserted for the column.
2453 ** conflict-algorithm is one of the sqlite conflict algorithms:
2454 ** rollback, abort, fail, ignore, replace
2455 ** On success, return the number of lines processed, not necessarily same
2456 ** as 'db changes' due to conflict-algorithm selected.
2458 ** This code is basically an implementation/enhancement of
2459 ** the sqlite3 shell.c ".import" command.
2461 ** This command usage is equivalent to the sqlite2.x COPY statement,
2462 ** which imports file data into a table using the PostgreSQL COPY file format:
2463 ** $db copy $conflict_algorithm $table_name $filename \t \\N
2466 char *zTable
; /* Insert data into this table */
2467 char *zFile
; /* The file from which to extract data */
2468 char *zConflict
; /* The conflict algorithm to use */
2469 sqlite3_stmt
*pStmt
; /* A statement */
2470 int nCol
; /* Number of columns in the table */
2471 int nByte
; /* Number of bytes in an SQL string */
2472 int i
, j
; /* Loop counters */
2473 int nSep
; /* Number of bytes in zSep[] */
2474 int nNull
; /* Number of bytes in zNull[] */
2475 char *zSql
; /* An SQL statement */
2476 char *zLine
; /* A single line of input from the file */
2477 char **azCol
; /* zLine[] broken up into columns */
2478 const char *zCommit
; /* How to commit changes */
2479 FILE *in
; /* The input file */
2480 int lineno
= 0; /* Line number of input file */
2481 char zLineNum
[80]; /* Line number print buffer */
2482 Tcl_Obj
*pResult
; /* interp result */
2486 if( objc
<5 || objc
>7 ){
2487 Tcl_WrongNumArgs(interp
, 2, objv
,
2488 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2492 zSep
= Tcl_GetStringFromObj(objv
[5], 0);
2497 zNull
= Tcl_GetStringFromObj(objv
[6], 0);
2501 zConflict
= Tcl_GetStringFromObj(objv
[2], 0);
2502 zTable
= Tcl_GetStringFromObj(objv
[3], 0);
2503 zFile
= Tcl_GetStringFromObj(objv
[4], 0);
2504 nSep
= strlen30(zSep
);
2505 nNull
= strlen30(zNull
);
2507 Tcl_AppendResult(interp
,"Error: non-null separator required for copy",
2511 if(strcmp(zConflict
, "rollback") != 0 &&
2512 strcmp(zConflict
, "abort" ) != 0 &&
2513 strcmp(zConflict
, "fail" ) != 0 &&
2514 strcmp(zConflict
, "ignore" ) != 0 &&
2515 strcmp(zConflict
, "replace" ) != 0 ) {
2516 Tcl_AppendResult(interp
, "Error: \"", zConflict
,
2517 "\", conflict-algorithm must be one of: rollback, "
2518 "abort, fail, ignore, or replace", (char*)0);
2521 zSql
= sqlite3_mprintf("SELECT * FROM '%q'", zTable
);
2523 Tcl_AppendResult(interp
, "Error: no such table: ", zTable
, (char*)0);
2526 nByte
= strlen30(zSql
);
2527 rc
= sqlite3_prepare(pDb
->db
, zSql
, -1, &pStmt
, 0);
2530 Tcl_AppendResult(interp
, "Error: ", sqlite3_errmsg(pDb
->db
), (char*)0);
2533 nCol
= sqlite3_column_count(pStmt
);
2535 sqlite3_finalize(pStmt
);
2539 zSql
= malloc( nByte
+ 50 + nCol
*2 );
2541 Tcl_AppendResult(interp
, "Error: can't malloc()", (char*)0);
2544 sqlite3_snprintf(nByte
+50, zSql
, "INSERT OR %q INTO '%q' VALUES(?",
2547 for(i
=1; i
<nCol
; i
++){
2553 rc
= sqlite3_prepare(pDb
->db
, zSql
, -1, &pStmt
, 0);
2556 Tcl_AppendResult(interp
, "Error: ", sqlite3_errmsg(pDb
->db
), (char*)0);
2557 sqlite3_finalize(pStmt
);
2560 in
= fopen(zFile
, "rb");
2562 Tcl_AppendResult(interp
, "Error: cannot open file: ", zFile
, (char*)0);
2563 sqlite3_finalize(pStmt
);
2566 azCol
= malloc( sizeof(azCol
[0])*(nCol
+1) );
2568 Tcl_AppendResult(interp
, "Error: can't malloc()", (char*)0);
2572 (void)sqlite3_exec(pDb
->db
, "BEGIN", 0, 0, 0);
2574 while( (zLine
= local_getline(0, in
))!=0 ){
2578 for(i
=0, z
=zLine
; *z
; z
++){
2579 if( *z
==zSep
[0] && strncmp(z
, zSep
, nSep
)==0 ){
2583 azCol
[i
] = &z
[nSep
];
2590 int nErr
= strlen30(zFile
) + 200;
2591 zErr
= malloc(nErr
);
2593 sqlite3_snprintf(nErr
, zErr
,
2594 "Error: %s line %d: expected %d columns of data but found %d",
2595 zFile
, lineno
, nCol
, i
+1);
2596 Tcl_AppendResult(interp
, zErr
, (char*)0);
2599 zCommit
= "ROLLBACK";
2602 for(i
=0; i
<nCol
; i
++){
2603 /* check for null data, if so, bind as null */
2604 if( (nNull
>0 && strcmp(azCol
[i
], zNull
)==0)
2605 || strlen30(azCol
[i
])==0
2607 sqlite3_bind_null(pStmt
, i
+1);
2609 sqlite3_bind_text(pStmt
, i
+1, azCol
[i
], -1, SQLITE_STATIC
);
2612 sqlite3_step(pStmt
);
2613 rc
= sqlite3_reset(pStmt
);
2615 if( rc
!=SQLITE_OK
){
2616 Tcl_AppendResult(interp
,"Error: ", sqlite3_errmsg(pDb
->db
), (char*)0);
2617 zCommit
= "ROLLBACK";
2623 sqlite3_finalize(pStmt
);
2624 (void)sqlite3_exec(pDb
->db
, zCommit
, 0, 0, 0);
2626 if( zCommit
[0] == 'C' ){
2627 /* success, set result as number of lines processed */
2628 pResult
= Tcl_GetObjResult(interp
);
2629 Tcl_SetIntObj(pResult
, lineno
);
2632 /* failure, append lineno where failed */
2633 sqlite3_snprintf(sizeof(zLineNum
), zLineNum
,"%d",lineno
);
2634 Tcl_AppendResult(interp
,", failed while processing line: ",zLineNum
,
2642 ** $db deserialize ?-maxsize N? ?-readonly BOOL? ?DATABASE? VALUE
2644 ** Reopen DATABASE (default "main") using the content in $VALUE
2646 case DB_DESERIALIZE
: {
2647 #ifdef SQLITE_OMIT_DESERIALIZE
2648 Tcl_AppendResult(interp
, "MEMDB not available in this build",
2652 const char *zSchema
= 0;
2653 Tcl_Obj
*pValue
= 0;
2655 unsigned char *pData
;
2657 sqlite3_int64 mxSize
= 0;
2663 Tcl_WrongNumArgs(interp
, 2, objv
, "?DATABASE? VALUE");
2667 for(i
=2; i
<objc
-1; i
++){
2668 const char *z
= Tcl_GetString(objv
[i
]);
2669 if( strcmp(z
,"-maxsize")==0 && i
<objc
-2 ){
2671 rc
= Tcl_GetWideIntFromObj(interp
, objv
[++i
], &x
);
2672 if( rc
) goto deserialize_error
;
2676 if( strcmp(z
,"-readonly")==0 && i
<objc
-2 ){
2677 rc
= Tcl_GetBooleanFromObj(interp
, objv
[++i
], &isReadonly
);
2678 if( rc
) goto deserialize_error
;
2681 if( zSchema
==0 && i
==objc
-2 && z
[0]!='-' ){
2685 Tcl_AppendResult(interp
, "unknown option: ", z
, (char*)0);
2687 goto deserialize_error
;
2689 pValue
= objv
[objc
-1];
2690 pBA
= Tcl_GetByteArrayFromObj(pValue
, &len
);
2691 pData
= sqlite3_malloc64( len
);
2692 if( pData
==0 && len
>0 ){
2693 Tcl_AppendResult(interp
, "out of memory", (char*)0);
2697 if( len
>0 ) memcpy(pData
, pBA
, len
);
2699 flags
= SQLITE_DESERIALIZE_FREEONCLOSE
| SQLITE_DESERIALIZE_READONLY
;
2701 flags
= SQLITE_DESERIALIZE_FREEONCLOSE
| SQLITE_DESERIALIZE_RESIZEABLE
;
2703 xrc
= sqlite3_deserialize(pDb
->db
, zSchema
, pData
, len
, len
, flags
);
2705 Tcl_AppendResult(interp
, "unable to set MEMDB content", (char*)0);
2709 sqlite3_file_control(pDb
->db
, zSchema
,SQLITE_FCNTL_SIZE_LIMIT
,&mxSize
);
2718 ** $db enable_load_extension BOOLEAN
2720 ** Turn the extension loading feature on or off. It if off by
2723 case DB_ENABLE_LOAD_EXTENSION
: {
2724 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2727 Tcl_WrongNumArgs(interp
, 2, objv
, "BOOLEAN");
2730 if( Tcl_GetBooleanFromObj(interp
, objv
[2], &onoff
) ){
2733 sqlite3_enable_load_extension(pDb
->db
, onoff
);
2736 Tcl_AppendResult(interp
, "extension loading is turned off at compile-time",
2745 ** Return the numeric error code that was returned by the most recent
2746 ** call to sqlite3_exec().
2748 case DB_ERRORCODE
: {
2749 Tcl_SetObjResult(interp
, Tcl_NewIntObj(sqlite3_errcode(pDb
->db
)));
2756 ** Return the numeric error code that was returned by the most recent
2757 ** call to sqlite3_exec().
2759 case DB_ERROROFFSET
: {
2760 Tcl_SetObjResult(interp
, Tcl_NewIntObj(sqlite3_error_offset(pDb
->db
)));
2766 ** $db onecolumn $sql
2768 ** The onecolumn method is the equivalent of:
2769 ** lindex [$db eval $sql] 0
2772 case DB_ONECOLUMN
: {
2773 Tcl_Obj
*pResult
= 0;
2774 DbEvalContext sEval
;
2776 Tcl_WrongNumArgs(interp
, 2, objv
, "SQL");
2780 dbEvalInit(&sEval
, pDb
, objv
[2], 0, 0);
2781 rc
= dbEvalStep(&sEval
);
2782 if( choice
==DB_ONECOLUMN
){
2784 pResult
= dbEvalColumnValue(&sEval
, 0);
2785 }else if( rc
==TCL_BREAK
){
2786 Tcl_ResetResult(interp
);
2788 }else if( rc
==TCL_BREAK
|| rc
==TCL_OK
){
2789 pResult
= Tcl_NewBooleanObj(rc
==TCL_OK
);
2791 dbEvalFinalize(&sEval
);
2792 if( pResult
) Tcl_SetObjResult(interp
, pResult
);
2794 if( rc
==TCL_BREAK
){
2801 ** $db eval ?options? $sql ?array? ?{ ...code... }?
2803 ** The SQL statement in $sql is evaluated. For each row, the values are
2804 ** placed in elements of the array named "array" and ...code... is executed.
2805 ** If "array" and "code" are omitted, then no callback is every invoked.
2806 ** If "array" is an empty string, then the values are placed in variables
2807 ** that have the same name as the fields extracted by the query.
2812 while( objc
>3 && (zOpt
= Tcl_GetString(objv
[2]))!=0 && zOpt
[0]=='-' ){
2813 if( strcmp(zOpt
, "-withoutnulls")==0 ){
2814 evalFlags
|= SQLITE_EVAL_WITHOUTNULLS
;
2817 Tcl_AppendResult(interp
, "unknown option: \"", zOpt
, "\"", (void*)0);
2823 if( objc
<3 || objc
>5 ){
2824 Tcl_WrongNumArgs(interp
, 2, objv
,
2825 "?OPTIONS? SQL ?ARRAY-NAME? ?SCRIPT?");
2830 DbEvalContext sEval
;
2831 Tcl_Obj
*pRet
= Tcl_NewObj();
2832 Tcl_IncrRefCount(pRet
);
2833 dbEvalInit(&sEval
, pDb
, objv
[2], 0, 0);
2834 while( TCL_OK
==(rc
= dbEvalStep(&sEval
)) ){
2837 dbEvalRowInfo(&sEval
, &nCol
, 0);
2838 for(i
=0; i
<nCol
; i
++){
2839 Tcl_ListObjAppendElement(interp
, pRet
, dbEvalColumnValue(&sEval
, i
));
2842 dbEvalFinalize(&sEval
);
2843 if( rc
==TCL_BREAK
){
2844 Tcl_SetObjResult(interp
, pRet
);
2847 Tcl_DecrRefCount(pRet
);
2851 Tcl_Obj
*pArray
= 0;
2854 if( objc
>=5 && *(char *)Tcl_GetString(objv
[3]) ){
2857 pScript
= objv
[objc
-1];
2858 Tcl_IncrRefCount(pScript
);
2860 p
= (DbEvalContext
*)Tcl_Alloc(sizeof(DbEvalContext
));
2861 dbEvalInit(p
, pDb
, objv
[2], pArray
, evalFlags
);
2864 cd2
[1] = (void *)pScript
;
2865 rc
= DbEvalNextCmd(cd2
, interp
, TCL_OK
);
2871 ** $db function NAME [OPTIONS] SCRIPT
2873 ** Create a new SQL function called NAME. Whenever that function is
2874 ** called, invoke SCRIPT to evaluate the function.
2877 ** --argcount N Function has exactly N arguments
2878 ** --deterministic The function is pure
2879 ** --directonly Prohibit use inside triggers and views
2880 ** --innocuous Has no side effects or information leaks
2881 ** --returntype TYPE Specify the return type of the function
2884 int flags
= SQLITE_UTF8
;
2890 int eType
= SQLITE_NULL
;
2892 Tcl_WrongNumArgs(interp
, 2, objv
, "NAME ?SWITCHES? SCRIPT");
2895 for(i
=3; i
<(objc
-1); i
++){
2896 const char *z
= Tcl_GetString(objv
[i
]);
2897 int n
= strlen30(z
);
2898 if( n
>1 && strncmp(z
, "-argcount",n
)==0 ){
2900 Tcl_AppendResult(interp
, "option requires an argument: ", z
,(char*)0);
2903 if( Tcl_GetIntFromObj(interp
, objv
[i
+1], &nArg
) ) return TCL_ERROR
;
2905 Tcl_AppendResult(interp
, "number of arguments must be non-negative",
2911 if( n
>1 && strncmp(z
, "-deterministic",n
)==0 ){
2912 flags
|= SQLITE_DETERMINISTIC
;
2914 if( n
>1 && strncmp(z
, "-directonly",n
)==0 ){
2915 flags
|= SQLITE_DIRECTONLY
;
2917 if( n
>1 && strncmp(z
, "-innocuous",n
)==0 ){
2918 flags
|= SQLITE_INNOCUOUS
;
2920 if( n
>1 && strncmp(z
, "-returntype", n
)==0 ){
2921 const char *azType
[] = {"integer", "real", "text", "blob", "any", 0};
2922 assert( SQLITE_INTEGER
==1 && SQLITE_FLOAT
==2 && SQLITE_TEXT
==3 );
2923 assert( SQLITE_BLOB
==4 && SQLITE_NULL
==5 );
2925 Tcl_AppendResult(interp
, "option requires an argument: ", z
,(char*)0);
2929 if( Tcl_GetIndexFromObj(interp
, objv
[i
], azType
, "type", 0, &eType
) ){
2934 Tcl_AppendResult(interp
, "bad option \"", z
,
2935 "\": must be -argcount, -deterministic, -directonly,"
2936 " -innocuous, or -returntype", (char*)0
2942 pScript
= objv
[objc
-1];
2943 zName
= Tcl_GetStringFromObj(objv
[2], 0);
2944 pFunc
= findSqlFunc(pDb
, zName
);
2945 if( pFunc
==0 ) return TCL_ERROR
;
2946 if( pFunc
->pScript
){
2947 Tcl_DecrRefCount(pFunc
->pScript
);
2949 pFunc
->pScript
= pScript
;
2950 Tcl_IncrRefCount(pScript
);
2951 pFunc
->useEvalObjv
= safeToUseEvalObjv(interp
, pScript
);
2952 pFunc
->eType
= eType
;
2953 rc
= sqlite3_create_function(pDb
->db
, zName
, nArg
, flags
,
2954 pFunc
, tclSqlFunc
, 0, 0);
2955 if( rc
!=SQLITE_OK
){
2957 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(pDb
->db
), TCL_VOLATILE
);
2963 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
2966 #ifdef SQLITE_OMIT_INCRBLOB
2967 Tcl_AppendResult(interp
, "incrblob not available in this build", (char*)0);
2971 const char *zDb
= "main";
2973 const char *zColumn
;
2976 /* Check for the -readonly option */
2977 if( objc
>3 && strcmp(Tcl_GetString(objv
[2]), "-readonly")==0 ){
2981 if( objc
!=(5+isReadonly
) && objc
!=(6+isReadonly
) ){
2982 Tcl_WrongNumArgs(interp
, 2, objv
, "?-readonly? ?DB? TABLE COLUMN ROWID");
2986 if( objc
==(6+isReadonly
) ){
2987 zDb
= Tcl_GetString(objv
[2+isReadonly
]);
2989 zTable
= Tcl_GetString(objv
[objc
-3]);
2990 zColumn
= Tcl_GetString(objv
[objc
-2]);
2991 rc
= Tcl_GetWideIntFromObj(interp
, objv
[objc
-1], &iRow
);
2994 rc
= createIncrblobChannel(
2995 interp
, pDb
, zDb
, zTable
, zColumn
, (sqlite3_int64
)iRow
, isReadonly
3005 ** Interrupt the execution of the inner-most SQL interpreter. This
3006 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
3008 case DB_INTERRUPT
: {
3009 sqlite3_interrupt(pDb
->db
);
3014 ** $db nullvalue ?STRING?
3016 ** Change text used when a NULL comes back from the database. If ?STRING?
3017 ** is not present, then the current string used for NULL is returned.
3018 ** If STRING is present, then STRING is returned.
3021 case DB_NULLVALUE
: {
3022 if( objc
!=2 && objc
!=3 ){
3023 Tcl_WrongNumArgs(interp
, 2, objv
, "NULLVALUE");
3028 char *zNull
= Tcl_GetStringFromObj(objv
[2], &len
);
3030 Tcl_Free(pDb
->zNull
);
3032 if( zNull
&& len
>0 ){
3033 pDb
->zNull
= Tcl_Alloc( len
+ 1 );
3034 memcpy(pDb
->zNull
, zNull
, len
);
3035 pDb
->zNull
[len
] = '\0';
3040 Tcl_SetObjResult(interp
, Tcl_NewStringObj(pDb
->zNull
, -1));
3045 ** $db last_insert_rowid
3047 ** Return an integer which is the ROWID for the most recent insert.
3049 case DB_LAST_INSERT_ROWID
: {
3053 Tcl_WrongNumArgs(interp
, 2, objv
, "");
3056 rowid
= sqlite3_last_insert_rowid(pDb
->db
);
3057 pResult
= Tcl_GetObjResult(interp
);
3058 Tcl_SetWideIntObj(pResult
, rowid
);
3063 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
3066 /* $db progress ?N CALLBACK?
3068 ** Invoke the given callback every N virtual machine opcodes while executing
3073 if( pDb
->zProgress
){
3074 Tcl_AppendResult(interp
, pDb
->zProgress
, (char*)0);
3076 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
3077 sqlite3_progress_handler(pDb
->db
, 0, 0, 0);
3079 }else if( objc
==4 ){
3083 if( TCL_OK
!=Tcl_GetIntFromObj(interp
, objv
[2], &N
) ){
3086 if( pDb
->zProgress
){
3087 Tcl_Free(pDb
->zProgress
);
3089 zProgress
= Tcl_GetStringFromObj(objv
[3], &len
);
3090 if( zProgress
&& len
>0 ){
3091 pDb
->zProgress
= Tcl_Alloc( len
+ 1 );
3092 memcpy(pDb
->zProgress
, zProgress
, len
+1);
3096 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
3097 if( pDb
->zProgress
){
3098 pDb
->interp
= interp
;
3099 sqlite3_progress_handler(pDb
->db
, N
, DbProgressHandler
, pDb
);
3101 sqlite3_progress_handler(pDb
->db
, 0, 0, 0);
3105 Tcl_WrongNumArgs(interp
, 2, objv
, "N CALLBACK");
3111 /* $db profile ?CALLBACK?
3113 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
3114 ** that has run. The text of the SQL and the amount of elapse time are
3115 ** appended to CALLBACK before the script is run.
3119 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
3121 }else if( objc
==2 ){
3122 if( pDb
->zProfile
){
3123 Tcl_AppendResult(interp
, pDb
->zProfile
, (char*)0);
3128 if( pDb
->zProfile
){
3129 Tcl_Free(pDb
->zProfile
);
3131 zProfile
= Tcl_GetStringFromObj(objv
[2], &len
);
3132 if( zProfile
&& len
>0 ){
3133 pDb
->zProfile
= Tcl_Alloc( len
+ 1 );
3134 memcpy(pDb
->zProfile
, zProfile
, len
+1);
3138 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3139 !defined(SQLITE_OMIT_DEPRECATED)
3140 if( pDb
->zProfile
){
3141 pDb
->interp
= interp
;
3142 sqlite3_profile(pDb
->db
, DbProfileHandler
, pDb
);
3144 sqlite3_profile(pDb
->db
, 0, 0);
3154 ** Change the encryption key on the currently open database.
3158 Tcl_WrongNumArgs(interp
, 2, objv
, "KEY");
3164 /* $db restore ?DATABASE? FILENAME
3166 ** Open a database file named FILENAME. Transfer the content
3167 ** of FILENAME into the local database DATABASE (default: "main").
3170 const char *zSrcFile
;
3171 const char *zDestDb
;
3173 sqlite3_backup
*pBackup
;
3178 zSrcFile
= Tcl_GetString(objv
[2]);
3179 }else if( objc
==4 ){
3180 zDestDb
= Tcl_GetString(objv
[2]);
3181 zSrcFile
= Tcl_GetString(objv
[3]);
3183 Tcl_WrongNumArgs(interp
, 2, objv
, "?DATABASE? FILENAME");
3186 rc
= sqlite3_open_v2(zSrcFile
, &pSrc
,
3187 SQLITE_OPEN_READONLY
| pDb
->openFlags
, 0);
3188 if( rc
!=SQLITE_OK
){
3189 Tcl_AppendResult(interp
, "cannot open source database: ",
3190 sqlite3_errmsg(pSrc
), (char*)0);
3191 sqlite3_close(pSrc
);
3194 pBackup
= sqlite3_backup_init(pDb
->db
, zDestDb
, pSrc
, "main");
3196 Tcl_AppendResult(interp
, "restore failed: ",
3197 sqlite3_errmsg(pDb
->db
), (char*)0);
3198 sqlite3_close(pSrc
);
3201 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
3202 || rc
==SQLITE_BUSY
){
3203 if( rc
==SQLITE_BUSY
){
3204 if( nTimeout
++ >= 3 ) break;
3208 sqlite3_backup_finish(pBackup
);
3209 if( rc
==SQLITE_DONE
){
3211 }else if( rc
==SQLITE_BUSY
|| rc
==SQLITE_LOCKED
){
3212 Tcl_AppendResult(interp
, "restore failed: source database busy",
3216 Tcl_AppendResult(interp
, "restore failed: ",
3217 sqlite3_errmsg(pDb
->db
), (char*)0);
3220 sqlite3_close(pSrc
);
3225 ** $db serialize ?DATABASE?
3227 ** Return a serialization of a database.
3229 case DB_SERIALIZE
: {
3230 #ifdef SQLITE_OMIT_DESERIALIZE
3231 Tcl_AppendResult(interp
, "MEMDB not available in this build",
3235 const char *zSchema
= objc
>=3 ? Tcl_GetString(objv
[2]) : "main";
3236 sqlite3_int64 sz
= 0;
3237 unsigned char *pData
;
3238 if( objc
!=2 && objc
!=3 ){
3239 Tcl_WrongNumArgs(interp
, 2, objv
, "?DATABASE?");
3243 pData
= sqlite3_serialize(pDb
->db
, zSchema
, &sz
, SQLITE_SERIALIZE_NOCOPY
);
3247 pData
= sqlite3_serialize(pDb
->db
, zSchema
, &sz
, 0);
3250 Tcl_SetObjResult(interp
, Tcl_NewByteArrayObj(pData
,sz
));
3251 if( needFree
) sqlite3_free(pData
);
3258 ** $db status (step|sort|autoindex|vmstep)
3260 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
3261 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
3267 Tcl_WrongNumArgs(interp
, 2, objv
, "(step|sort|autoindex)");
3270 zOp
= Tcl_GetString(objv
[2]);
3271 if( strcmp(zOp
, "step")==0 ){
3273 }else if( strcmp(zOp
, "sort")==0 ){
3275 }else if( strcmp(zOp
, "autoindex")==0 ){
3277 }else if( strcmp(zOp
, "vmstep")==0 ){
3280 Tcl_AppendResult(interp
,
3281 "bad argument: should be autoindex, step, sort or vmstep",
3285 Tcl_SetObjResult(interp
, Tcl_NewIntObj(v
));
3290 ** $db timeout MILLESECONDS
3292 ** Delay for the number of milliseconds specified when a file is locked.
3297 Tcl_WrongNumArgs(interp
, 2, objv
, "MILLISECONDS");
3300 if( Tcl_GetIntFromObj(interp
, objv
[2], &ms
) ) return TCL_ERROR
;
3301 sqlite3_busy_timeout(pDb
->db
, ms
);
3306 ** $db total_changes
3308 ** Return the number of rows that were modified, inserted, or deleted
3309 ** since the database handle was created.
3311 case DB_TOTAL_CHANGES
: {
3314 Tcl_WrongNumArgs(interp
, 2, objv
, "");
3317 pResult
= Tcl_GetObjResult(interp
);
3318 Tcl_SetWideIntObj(pResult
, sqlite3_total_changes64(pDb
->db
));
3322 /* $db trace ?CALLBACK?
3324 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
3325 ** that is executed. The text of the SQL is appended to CALLBACK before
3330 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
3332 }else if( objc
==2 ){
3334 Tcl_AppendResult(interp
, pDb
->zTrace
, (char*)0);
3340 Tcl_Free(pDb
->zTrace
);
3342 zTrace
= Tcl_GetStringFromObj(objv
[2], &len
);
3343 if( zTrace
&& len
>0 ){
3344 pDb
->zTrace
= Tcl_Alloc( len
+ 1 );
3345 memcpy(pDb
->zTrace
, zTrace
, len
+1);
3349 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3350 !defined(SQLITE_OMIT_DEPRECATED)
3352 pDb
->interp
= interp
;
3353 sqlite3_trace(pDb
->db
, DbTraceHandler
, pDb
);
3355 sqlite3_trace(pDb
->db
, 0, 0);
3362 /* $db trace_v2 ?CALLBACK? ?MASK?
3364 ** Make arrangements to invoke the CALLBACK routine for each trace event
3365 ** matching the mask that is generated. The parameters are appended to
3366 ** CALLBACK before it is executed.
3370 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK? ?MASK?");
3372 }else if( objc
==2 ){
3373 if( pDb
->zTraceV2
){
3374 Tcl_AppendResult(interp
, pDb
->zTraceV2
, (char*)0);
3379 Tcl_WideInt wMask
= 0;
3381 static const char *TTYPE_strs
[] = {
3382 "statement", "profile", "row", "close", 0
3385 TTYPE_STMT
, TTYPE_PROFILE
, TTYPE_ROW
, TTYPE_CLOSE
3388 if( TCL_OK
!=Tcl_ListObjLength(interp
, objv
[3], &len
) ){
3391 for(i
=0; i
<len
; i
++){
3394 if( TCL_OK
!=Tcl_ListObjIndex(interp
, objv
[3], i
, &pObj
) ){
3397 if( Tcl_GetIndexFromObj(interp
, pObj
, TTYPE_strs
, "trace type",
3398 0, &ttype
)!=TCL_OK
){
3400 Tcl_Obj
*pError
= Tcl_DuplicateObj(Tcl_GetObjResult(interp
));
3401 Tcl_IncrRefCount(pError
);
3402 if( TCL_OK
==Tcl_GetWideIntFromObj(interp
, pObj
, &wType
) ){
3403 Tcl_DecrRefCount(pError
);
3406 Tcl_SetObjResult(interp
, pError
);
3407 Tcl_DecrRefCount(pError
);
3411 switch( (enum TTYPE_enum
)ttype
){
3412 case TTYPE_STMT
: wMask
|= SQLITE_TRACE_STMT
; break;
3413 case TTYPE_PROFILE
: wMask
|= SQLITE_TRACE_PROFILE
; break;
3414 case TTYPE_ROW
: wMask
|= SQLITE_TRACE_ROW
; break;
3415 case TTYPE_CLOSE
: wMask
|= SQLITE_TRACE_CLOSE
; break;
3420 wMask
= SQLITE_TRACE_STMT
; /* use the "legacy" default */
3422 if( pDb
->zTraceV2
){
3423 Tcl_Free(pDb
->zTraceV2
);
3425 zTraceV2
= Tcl_GetStringFromObj(objv
[2], &len
);
3426 if( zTraceV2
&& len
>0 ){
3427 pDb
->zTraceV2
= Tcl_Alloc( len
+ 1 );
3428 memcpy(pDb
->zTraceV2
, zTraceV2
, len
+1);
3432 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3433 if( pDb
->zTraceV2
){
3434 pDb
->interp
= interp
;
3435 sqlite3_trace_v2(pDb
->db
, (unsigned)wMask
, DbTraceV2Handler
, pDb
);
3437 sqlite3_trace_v2(pDb
->db
, 0, 0, 0);
3444 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
3446 ** Start a new transaction (if we are not already in the midst of a
3447 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
3448 ** completes, either commit the transaction or roll it back if SCRIPT
3449 ** throws an exception. Or if no new transaction was started, do nothing.
3450 ** pass the exception on up the stack.
3452 ** This command was inspired by Dave Thomas's talk on Ruby at the
3453 ** 2005 O'Reilly Open Source Convention (OSCON).
3455 case DB_TRANSACTION
: {
3457 const char *zBegin
= "SAVEPOINT _tcl_transaction";
3458 if( objc
!=3 && objc
!=4 ){
3459 Tcl_WrongNumArgs(interp
, 2, objv
, "[TYPE] SCRIPT");
3463 if( pDb
->nTransaction
==0 && objc
==4 ){
3464 static const char *TTYPE_strs
[] = {
3465 "deferred", "exclusive", "immediate", 0
3468 TTYPE_DEFERRED
, TTYPE_EXCLUSIVE
, TTYPE_IMMEDIATE
3471 if( Tcl_GetIndexFromObj(interp
, objv
[2], TTYPE_strs
, "transaction type",
3475 switch( (enum TTYPE_enum
)ttype
){
3476 case TTYPE_DEFERRED
: /* no-op */; break;
3477 case TTYPE_EXCLUSIVE
: zBegin
= "BEGIN EXCLUSIVE"; break;
3478 case TTYPE_IMMEDIATE
: zBegin
= "BEGIN IMMEDIATE"; break;
3481 pScript
= objv
[objc
-1];
3483 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
3485 rc
= sqlite3_exec(pDb
->db
, zBegin
, 0, 0, 0);
3487 if( rc
!=SQLITE_OK
){
3488 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
3491 pDb
->nTransaction
++;
3493 /* If using NRE, schedule a callback to invoke the script pScript, then
3494 ** a second callback to commit (or rollback) the transaction or savepoint
3495 ** opened above. If not using NRE, evaluate the script directly, then
3496 ** call function DbTransPostCmd() to commit (or rollback) the transaction
3498 addDatabaseRef(pDb
); /* DbTransPostCmd() calls delDatabaseRef() */
3500 Tcl_NRAddCallback(interp
, DbTransPostCmd
, cd
, 0, 0, 0);
3501 (void)Tcl_NREvalObj(interp
, pScript
, 0);
3503 rc
= DbTransPostCmd(&cd
, interp
, Tcl_EvalObjEx(interp
, pScript
, 0));
3509 ** $db unlock_notify ?script?
3511 case DB_UNLOCK_NOTIFY
: {
3512 #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
3513 Tcl_AppendResult(interp
, "unlock_notify not available in this build",
3517 if( objc
!=2 && objc
!=3 ){
3518 Tcl_WrongNumArgs(interp
, 2, objv
, "?SCRIPT?");
3521 void (*xNotify
)(void **, int) = 0;
3522 void *pNotifyArg
= 0;
3524 if( pDb
->pUnlockNotify
){
3525 Tcl_DecrRefCount(pDb
->pUnlockNotify
);
3526 pDb
->pUnlockNotify
= 0;
3530 xNotify
= DbUnlockNotify
;
3531 pNotifyArg
= (void *)pDb
;
3532 pDb
->pUnlockNotify
= objv
[2];
3533 Tcl_IncrRefCount(pDb
->pUnlockNotify
);
3536 if( sqlite3_unlock_notify(pDb
->db
, xNotify
, pNotifyArg
) ){
3537 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
3546 ** $db preupdate_hook count
3547 ** $db preupdate_hook hook ?SCRIPT?
3548 ** $db preupdate_hook new INDEX
3549 ** $db preupdate_hook old INDEX
3551 case DB_PREUPDATE
: {
3552 #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
3553 Tcl_AppendResult(interp
, "preupdate_hook was omitted at compile-time",
3557 static const char *azSub
[] = {"count", "depth", "hook", "new", "old", 0};
3558 enum DbPreupdateSubCmd
{
3559 PRE_COUNT
, PRE_DEPTH
, PRE_HOOK
, PRE_NEW
, PRE_OLD
3564 Tcl_WrongNumArgs(interp
, 2, objv
, "SUB-COMMAND ?ARGS?");
3566 if( Tcl_GetIndexFromObj(interp
, objv
[2], azSub
, "sub-command", 0, &iSub
) ){
3570 switch( (enum DbPreupdateSubCmd
)iSub
){
3572 int nCol
= sqlite3_preupdate_count(pDb
->db
);
3573 Tcl_SetObjResult(interp
, Tcl_NewIntObj(nCol
));
3579 Tcl_WrongNumArgs(interp
, 2, objv
, "hook ?SCRIPT?");
3582 DbHookCmd(interp
, pDb
, (objc
==4 ? objv
[3] : 0), &pDb
->pPreUpdateHook
);
3589 Tcl_WrongNumArgs(interp
, 3, objv
, "");
3592 pRet
= Tcl_NewIntObj(sqlite3_preupdate_depth(pDb
->db
));
3593 Tcl_SetObjResult(interp
, pRet
);
3600 sqlite3_value
*pValue
;
3602 Tcl_WrongNumArgs(interp
, 3, objv
, "INDEX");
3605 if( Tcl_GetIntFromObj(interp
, objv
[3], &iIdx
) ){
3609 if( iSub
==PRE_OLD
){
3610 rc
= sqlite3_preupdate_old(pDb
->db
, iIdx
, &pValue
);
3612 assert( iSub
==PRE_NEW
);
3613 rc
= sqlite3_preupdate_new(pDb
->db
, iIdx
, &pValue
);
3616 if( rc
==SQLITE_OK
){
3618 pObj
= Tcl_NewStringObj((char*)sqlite3_value_text(pValue
), -1);
3619 Tcl_SetObjResult(interp
, pObj
);
3621 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
3626 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
3631 ** $db wal_hook ?script?
3632 ** $db update_hook ?script?
3633 ** $db rollback_hook ?script?
3636 case DB_UPDATE_HOOK
:
3637 case DB_ROLLBACK_HOOK
: {
3638 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
3639 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3641 Tcl_Obj
**ppHook
= 0;
3642 if( choice
==DB_WAL_HOOK
) ppHook
= &pDb
->pWalHook
;
3643 if( choice
==DB_UPDATE_HOOK
) ppHook
= &pDb
->pUpdateHook
;
3644 if( choice
==DB_ROLLBACK_HOOK
) ppHook
= &pDb
->pRollbackHook
;
3646 Tcl_WrongNumArgs(interp
, 2, objv
, "?SCRIPT?");
3650 DbHookCmd(interp
, pDb
, (objc
==3 ? objv
[2] : 0), ppHook
);
3656 ** Return the version string for this database.
3660 for(i
=2; i
<objc
; i
++){
3661 const char *zArg
= Tcl_GetString(objv
[i
]);
3662 /* Optional arguments to $db version are used for testing purpose */
3664 /* $db version -use-legacy-prepare BOOLEAN
3666 ** Turn the use of legacy sqlite3_prepare() on or off.
3668 if( strcmp(zArg
, "-use-legacy-prepare")==0 && i
+1<objc
){
3670 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &pDb
->bLegacyPrepare
) ){
3675 /* $db version -last-stmt-ptr
3677 ** Return a string which is a hex encoding of the pointer to the
3678 ** most recent sqlite3_stmt in the statement cache.
3680 if( strcmp(zArg
, "-last-stmt-ptr")==0 ){
3682 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%p",
3683 pDb
->stmtList
? pDb
->stmtList
->pStmt
: 0);
3684 Tcl_SetResult(interp
, zBuf
, TCL_VOLATILE
);
3686 #endif /* SQLITE_TEST */
3688 Tcl_AppendResult(interp
, "unknown argument: ", zArg
, (char*)0);
3693 Tcl_SetResult(interp
, (char *)sqlite3_libversion(), TCL_STATIC
);
3699 } /* End of the SWITCH statement */
3705 ** Adaptor that provides an objCmd interface to the NRE-enabled
3706 ** interface implementation.
3708 static int SQLITE_TCLAPI
DbObjCmdAdaptor(
3714 return Tcl_NRCallObjProc(interp
, DbObjCmd
, cd
, objc
, objv
);
3716 #endif /* SQLITE_TCL_NRE */
3719 ** Issue the usage message when the "sqlite3" command arguments are
3722 static int sqliteCmdUsage(
3726 Tcl_WrongNumArgs(interp
, 1, objv
,
3727 "HANDLE ?FILENAME? ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
3728 " ?-nofollow BOOLEAN?"
3729 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
3735 ** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
3736 ** ?-create BOOLEAN? ?-nomutex BOOLEAN?
3737 ** ?-nofollow BOOLEAN?
3739 ** This is the main Tcl command. When the "sqlite" Tcl command is
3740 ** invoked, this routine runs to process that command.
3742 ** The first argument, DBNAME, is an arbitrary name for a new
3743 ** database connection. This command creates a new command named
3744 ** DBNAME that is used to control that connection. The database
3745 ** connection is deleted when the DBNAME command is deleted.
3747 ** The second argument is the name of the database file.
3750 static int SQLITE_TCLAPI
DbMain(
3760 const char *zFile
= 0;
3761 const char *zVfs
= 0;
3763 int bTranslateFileName
= 1;
3764 Tcl_DString translatedFilename
;
3767 /* In normal use, each TCL interpreter runs in a single thread. So
3768 ** by default, we can turn off mutexing on SQLite database connections.
3769 ** However, for testing purposes it is useful to have mutexes turned
3770 ** on. So, by default, mutexes default off. But if compiled with
3771 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3773 #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3774 flags
= SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
| SQLITE_OPEN_FULLMUTEX
;
3776 flags
= SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
| SQLITE_OPEN_NOMUTEX
;
3779 if( objc
==1 ) return sqliteCmdUsage(interp
, objv
);
3781 zArg
= Tcl_GetStringFromObj(objv
[1], 0);
3782 if( strcmp(zArg
,"-version")==0 ){
3783 Tcl_AppendResult(interp
,sqlite3_libversion(), (char*)0);
3786 if( strcmp(zArg
,"-sourceid")==0 ){
3787 Tcl_AppendResult(interp
,sqlite3_sourceid(), (char*)0);
3790 if( strcmp(zArg
,"-has-codec")==0 ){
3791 Tcl_AppendResult(interp
,"0",(char*)0);
3794 if( zArg
[0]=='-' ) return sqliteCmdUsage(interp
, objv
);
3796 for(i
=2; i
<objc
; i
++){
3797 zArg
= Tcl_GetString(objv
[i
]);
3799 if( zFile
!=0 ) return sqliteCmdUsage(interp
, objv
);
3803 if( i
==objc
-1 ) return sqliteCmdUsage(interp
, objv
);
3805 if( strcmp(zArg
,"-key")==0 ){
3807 }else if( strcmp(zArg
, "-vfs")==0 ){
3808 zVfs
= Tcl_GetString(objv
[i
]);
3809 }else if( strcmp(zArg
, "-readonly")==0 ){
3811 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &b
) ) return TCL_ERROR
;
3813 flags
&= ~(SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
);
3814 flags
|= SQLITE_OPEN_READONLY
;
3816 flags
&= ~SQLITE_OPEN_READONLY
;
3817 flags
|= SQLITE_OPEN_READWRITE
;
3819 }else if( strcmp(zArg
, "-create")==0 ){
3821 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &b
) ) return TCL_ERROR
;
3822 if( b
&& (flags
& SQLITE_OPEN_READONLY
)==0 ){
3823 flags
|= SQLITE_OPEN_CREATE
;
3825 flags
&= ~SQLITE_OPEN_CREATE
;
3827 }else if( strcmp(zArg
, "-nofollow")==0 ){
3829 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &b
) ) return TCL_ERROR
;
3831 flags
|= SQLITE_OPEN_NOFOLLOW
;
3833 flags
&= ~SQLITE_OPEN_NOFOLLOW
;
3835 }else if( strcmp(zArg
, "-nomutex")==0 ){
3837 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &b
) ) return TCL_ERROR
;
3839 flags
|= SQLITE_OPEN_NOMUTEX
;
3840 flags
&= ~SQLITE_OPEN_FULLMUTEX
;
3842 flags
&= ~SQLITE_OPEN_NOMUTEX
;
3844 }else if( strcmp(zArg
, "-fullmutex")==0 ){
3846 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &b
) ) return TCL_ERROR
;
3848 flags
|= SQLITE_OPEN_FULLMUTEX
;
3849 flags
&= ~SQLITE_OPEN_NOMUTEX
;
3851 flags
&= ~SQLITE_OPEN_FULLMUTEX
;
3853 }else if( strcmp(zArg
, "-uri")==0 ){
3855 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &b
) ) return TCL_ERROR
;
3857 flags
|= SQLITE_OPEN_URI
;
3859 flags
&= ~SQLITE_OPEN_URI
;
3861 }else if( strcmp(zArg
, "-translatefilename")==0 ){
3862 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &bTranslateFileName
) ){
3866 Tcl_AppendResult(interp
, "unknown option: ", zArg
, (char*)0);
3871 p
= (SqliteDb
*)Tcl_Alloc( sizeof(*p
) );
3872 memset(p
, 0, sizeof(*p
));
3873 if( zFile
==0 ) zFile
= "";
3874 if( bTranslateFileName
){
3875 zFile
= Tcl_TranslateFileName(interp
, zFile
, &translatedFilename
);
3877 rc
= sqlite3_open_v2(zFile
, &p
->db
, flags
, zVfs
);
3878 if( bTranslateFileName
){
3879 Tcl_DStringFree(&translatedFilename
);
3882 if( SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
3883 zErrMsg
= sqlite3_mprintf("%s", sqlite3_errmsg(p
->db
));
3884 sqlite3_close(p
->db
);
3888 zErrMsg
= sqlite3_mprintf("%s", sqlite3_errstr(rc
));
3891 Tcl_SetResult(interp
, zErrMsg
, TCL_VOLATILE
);
3893 sqlite3_free(zErrMsg
);
3896 p
->maxStmt
= NUM_PREPARED_STMTS
;
3897 p
->openFlags
= flags
& SQLITE_OPEN_URI
;
3899 zArg
= Tcl_GetStringFromObj(objv
[1], 0);
3901 Tcl_NRCreateCommand(interp
, zArg
, DbObjCmdAdaptor
, DbObjCmd
,
3902 (char*)p
, DbDeleteCmd
);
3904 Tcl_CreateObjCommand(interp
, zArg
, DbObjCmd
, (char*)p
, DbDeleteCmd
);
3911 ** Provide a dummy Tcl_InitStubs if we are using this as a static
3914 #ifndef USE_TCL_STUBS
3915 # undef Tcl_InitStubs
3916 # define Tcl_InitStubs(a,b,c) TCL_VERSION
3920 ** Make sure we have a PACKAGE_VERSION macro defined. This will be
3921 ** defined automatically by the TEA makefile. But other makefiles
3922 ** do not define it.
3924 #ifndef PACKAGE_VERSION
3925 # define PACKAGE_VERSION SQLITE_VERSION
3929 ** Initialize this module.
3931 ** This Tcl module contains only a single new Tcl command named "sqlite".
3932 ** (Hence there is no namespace. There is no point in using a namespace
3933 ** if the extension only supplies one new name!) The "sqlite" command is
3934 ** used to open a new SQLite database. See the DbMain() routine above
3935 ** for additional information.
3937 ** The EXTERN macros are required by TCL in order to work on windows.
3939 EXTERN
int Sqlite3_Init(Tcl_Interp
*interp
){
3940 int rc
= Tcl_InitStubs(interp
, "8.4", 0) ? TCL_OK
: TCL_ERROR
;
3942 Tcl_CreateObjCommand(interp
, "sqlite3", (Tcl_ObjCmdProc
*)DbMain
, 0, 0);
3943 #ifndef SQLITE_3_SUFFIX_ONLY
3944 /* The "sqlite" alias is undocumented. It is here only to support
3945 ** legacy scripts. All new scripts should use only the "sqlite3"
3947 Tcl_CreateObjCommand(interp
, "sqlite", (Tcl_ObjCmdProc
*)DbMain
, 0, 0);
3949 rc
= Tcl_PkgProvide(interp
, "sqlite3", PACKAGE_VERSION
);
3953 EXTERN
int Tclsqlite3_Init(Tcl_Interp
*interp
){ return Sqlite3_Init(interp
); }
3954 EXTERN
int Sqlite3_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3955 EXTERN
int Tclsqlite3_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3957 /* Because it accesses the file-system and uses persistent state, SQLite
3958 ** is not considered appropriate for safe interpreters. Hence, we cause
3959 ** the _SafeInit() interfaces return TCL_ERROR.
3961 EXTERN
int Sqlite3_SafeInit(Tcl_Interp
*interp
){ return TCL_ERROR
; }
3962 EXTERN
int Sqlite3_SafeUnload(Tcl_Interp
*interp
, int flags
){return TCL_ERROR
;}
3966 #ifndef SQLITE_3_SUFFIX_ONLY
3967 int Sqlite_Init(Tcl_Interp
*interp
){ return Sqlite3_Init(interp
); }
3968 int Tclsqlite_Init(Tcl_Interp
*interp
){ return Sqlite3_Init(interp
); }
3969 int Sqlite_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3970 int Tclsqlite_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3974 ** If the TCLSH macro is defined, add code to make a stand-alone program.
3978 /* This is the main routine for an ordinary TCL shell. If there are
3979 ** are arguments, run the first argument as a script. Otherwise,
3980 ** read TCL commands from standard input
3982 static const char *tclsh_main_loop(void){
3983 static const char zMainloop
[] =
3984 "if {[llength $argv]>=1} {\n"
3985 "set argv0 [lindex $argv 0]\n"
3986 "set argv [lrange $argv 1 end]\n"
3990 "while {![eof stdin]} {\n"
3991 "if {$line!=\"\"} {\n"
3992 "puts -nonewline \"> \"\n"
3994 "puts -nonewline \"% \"\n"
3997 "append line [gets stdin]\n"
3998 "if {[info complete $line]} {\n"
3999 "if {[catch {uplevel #0 $line} result]} {\n"
4000 "puts stderr \"Error: $result\"\n"
4001 "} elseif {$result!=\"\"} {\n"
4015 # define TCLSH_MAIN main
4017 int SQLITE_CDECL
TCLSH_MAIN(int argc
, char **argv
){
4020 const char *zScript
= 0;
4022 #if defined(TCLSH_INIT_PROC)
4023 extern const char *TCLSH_INIT_PROC(Tcl_Interp
*);
4026 #if !defined(_WIN32_WCE)
4027 if( getenv("SQLITE_DEBUG_BREAK") ){
4028 if( isatty(0) && isatty(2) ){
4030 "attach debugger to process %d and press any key to continue.\n",
4034 #if defined(_WIN32) || defined(WIN32)
4036 #elif defined(SIGTRAP)
4043 /* Call sqlite3_shutdown() once before doing anything else. This is to
4044 ** test that sqlite3_shutdown() can be safely called by a process before
4045 ** sqlite3_initialize() is. */
4048 Tcl_FindExecutable(argv
[0]);
4049 Tcl_SetSystemEncoding(NULL
, "utf-8");
4050 interp
= Tcl_CreateInterp();
4051 Sqlite3_Init(interp
);
4053 sqlite3_snprintf(sizeof(zArgc
), zArgc
, "%d", argc
-1);
4054 Tcl_SetVar(interp
,"argc", zArgc
, TCL_GLOBAL_ONLY
);
4055 Tcl_SetVar(interp
,"argv0",argv
[0],TCL_GLOBAL_ONLY
);
4056 Tcl_SetVar(interp
,"argv", "", TCL_GLOBAL_ONLY
);
4057 for(i
=1; i
<argc
; i
++){
4058 Tcl_SetVar(interp
, "argv", argv
[i
],
4059 TCL_GLOBAL_ONLY
| TCL_LIST_ELEMENT
| TCL_APPEND_VALUE
);
4061 #if defined(TCLSH_INIT_PROC)
4062 zScript
= TCLSH_INIT_PROC(interp
);
4065 zScript
= tclsh_main_loop();
4067 if( Tcl_GlobalEval(interp
, zScript
)!=TCL_OK
){
4068 const char *zInfo
= Tcl_GetVar(interp
, "errorInfo", TCL_GLOBAL_ONLY
);
4069 if( zInfo
==0 ) zInfo
= Tcl_GetStringResult(interp
);
4070 fprintf(stderr
,"%s: %s\n", *argv
, zInfo
);