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=1 Add a "main()" routine that works as a tclsh.
19 ** -DSQLITE_TCLMD5 When used in conjuction with -DTCLSH=1, add
20 ** four new commands to the TCL interpreter for
21 ** generating MD5 checksums: md5, md5file,
22 ** md5-10x8, and md5file-10x8.
24 ** -DSQLITE_TEST When used in conjuction with -DTCLSH=1, add
25 ** hundreds of new commands used for testing
26 ** SQLite. This option implies -DSQLITE_TCLMD5.
30 ** If requested, include the SQLite compiler options file for MSVC.
32 #if defined(INCLUDE_MSVC_H)
36 #if defined(INCLUDE_SQLITE_TCL_H)
37 # include "sqlite_tcl.h"
40 # ifndef SQLITE_TCLAPI
41 # define SQLITE_TCLAPI
47 ** Some additional include files are needed if this file is not
48 ** appended to the amalgamation.
50 #ifndef SQLITE_AMALGAMATION
55 typedef unsigned char u8
;
59 /* Used to get the current process ID */
62 # define GETPID getpid
63 #elif !defined(_WIN32_WCE)
64 # ifndef SQLITE_AMALGAMATION
65 # define WIN32_LEAN_AND_MEAN
68 # define GETPID (int)GetCurrentProcessId
72 * Windows needs to know which symbols to export. Unix does not.
73 * BUILD_sqlite should be undefined for Unix.
76 #undef TCL_STORAGE_CLASS
77 #define TCL_STORAGE_CLASS DLLEXPORT
78 #endif /* BUILD_sqlite */
80 #define NUM_PREPARED_STMTS 10
81 #define MAX_PREPARED_STMTS 100
83 /* Forward declaration */
84 typedef struct SqliteDb SqliteDb
;
87 ** New SQL functions can be created as TCL scripts. Each such function
88 ** is described by an instance of the following structure.
90 typedef struct SqlFunc SqlFunc
;
92 Tcl_Interp
*interp
; /* The TCL interpret to execute the function */
93 Tcl_Obj
*pScript
; /* The Tcl_Obj representation of the script */
94 SqliteDb
*pDb
; /* Database connection that owns this function */
95 int useEvalObjv
; /* True if it is safe to use Tcl_EvalObjv */
96 char *zName
; /* Name of this function */
97 SqlFunc
*pNext
; /* Next function on the list of them all */
101 ** New collation sequences function can be created as TCL scripts. Each such
102 ** function is described by an instance of the following structure.
104 typedef struct SqlCollate SqlCollate
;
106 Tcl_Interp
*interp
; /* The TCL interpret to execute the function */
107 char *zScript
; /* The script to be run */
108 SqlCollate
*pNext
; /* Next function on the list of them all */
112 ** Prepared statements are cached for faster execution. Each prepared
113 ** statement is described by an instance of the following structure.
115 typedef struct SqlPreparedStmt SqlPreparedStmt
;
116 struct SqlPreparedStmt
{
117 SqlPreparedStmt
*pNext
; /* Next in linked list */
118 SqlPreparedStmt
*pPrev
; /* Previous on the list */
119 sqlite3_stmt
*pStmt
; /* The prepared statement */
120 int nSql
; /* chars in zSql[] */
121 const char *zSql
; /* Text of the SQL statement */
122 int nParm
; /* Size of apParm array */
123 Tcl_Obj
**apParm
; /* Array of referenced object pointers */
126 typedef struct IncrblobChannel IncrblobChannel
;
129 ** There is one instance of this structure for each SQLite database
130 ** that has been opened by the SQLite TCL interface.
132 ** If this module is built with SQLITE_TEST defined (to create the SQLite
133 ** testfixture executable), then it may be configured to use either
134 ** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
135 ** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
138 sqlite3
*db
; /* The "real" database structure. MUST BE FIRST */
139 Tcl_Interp
*interp
; /* The interpreter used for this database */
140 char *zBusy
; /* The busy callback routine */
141 char *zCommit
; /* The commit hook callback routine */
142 char *zTrace
; /* The trace callback routine */
143 char *zTraceV2
; /* The trace_v2 callback routine */
144 char *zProfile
; /* The profile callback routine */
145 char *zProgress
; /* The progress callback routine */
146 char *zAuth
; /* The authorization callback routine */
147 int disableAuth
; /* Disable the authorizer if it exists */
148 char *zNull
; /* Text to substitute for an SQL NULL value */
149 SqlFunc
*pFunc
; /* List of SQL functions */
150 Tcl_Obj
*pUpdateHook
; /* Update hook script (if any) */
151 Tcl_Obj
*pPreUpdateHook
; /* Pre-update hook script (if any) */
152 Tcl_Obj
*pRollbackHook
; /* Rollback hook script (if any) */
153 Tcl_Obj
*pWalHook
; /* WAL hook script (if any) */
154 Tcl_Obj
*pUnlockNotify
; /* Unlock notify script (if any) */
155 SqlCollate
*pCollate
; /* List of SQL collation functions */
156 int rc
; /* Return code of most recent sqlite3_exec() */
157 Tcl_Obj
*pCollateNeeded
; /* Collation needed script */
158 SqlPreparedStmt
*stmtList
; /* List of prepared statements*/
159 SqlPreparedStmt
*stmtLast
; /* Last statement in the list */
160 int maxStmt
; /* The next maximum number of stmtList */
161 int nStmt
; /* Number of statements in stmtList */
162 IncrblobChannel
*pIncrblob
;/* Linked list of open incrblob channels */
163 int nStep
, nSort
, nIndex
; /* Statistics for most recent operation */
164 int nVMStep
; /* Another statistic for most recent operation */
165 int nTransaction
; /* Number of nested [transaction] methods */
166 int openFlags
; /* Flags used to open. (SQLITE_OPEN_URI) */
168 int bLegacyPrepare
; /* True to use sqlite3_prepare() */
172 struct IncrblobChannel
{
173 sqlite3_blob
*pBlob
; /* sqlite3 blob handle */
174 SqliteDb
*pDb
; /* Associated database connection */
175 int iSeek
; /* Current seek offset */
176 Tcl_Channel channel
; /* Channel identifier */
177 IncrblobChannel
*pNext
; /* Linked list of all open incrblob channels */
178 IncrblobChannel
*pPrev
; /* Linked list of all open incrblob channels */
182 ** Compute a string length that is limited to what can be stored in
183 ** lower 30 bits of a 32-bit signed integer.
185 static int strlen30(const char *z
){
187 while( *z2
){ z2
++; }
188 return 0x3fffffff & (int)(z2
- z
);
192 #ifndef SQLITE_OMIT_INCRBLOB
194 ** Close all incrblob channels opened using database connection pDb.
195 ** This is called when shutting down the database connection.
197 static void closeIncrblobChannels(SqliteDb
*pDb
){
199 IncrblobChannel
*pNext
;
201 for(p
=pDb
->pIncrblob
; p
; p
=pNext
){
204 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
205 ** which deletes the IncrblobChannel structure at *p. So do not
206 ** call Tcl_Free() here.
208 Tcl_UnregisterChannel(pDb
->interp
, p
->channel
);
213 ** Close an incremental blob channel.
215 static int SQLITE_TCLAPI
incrblobClose(
216 ClientData instanceData
,
219 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
220 int rc
= sqlite3_blob_close(p
->pBlob
);
221 sqlite3
*db
= p
->pDb
->db
;
223 /* Remove the channel from the SqliteDb.pIncrblob list. */
225 p
->pNext
->pPrev
= p
->pPrev
;
228 p
->pPrev
->pNext
= p
->pNext
;
230 if( p
->pDb
->pIncrblob
==p
){
231 p
->pDb
->pIncrblob
= p
->pNext
;
234 /* Free the IncrblobChannel structure */
238 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(db
), TCL_VOLATILE
);
245 ** Read data from an incremental blob channel.
247 static int SQLITE_TCLAPI
incrblobInput(
248 ClientData instanceData
,
253 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
254 int nRead
= bufSize
; /* Number of bytes to read */
255 int nBlob
; /* Total size of the blob */
256 int rc
; /* sqlite error code */
258 nBlob
= sqlite3_blob_bytes(p
->pBlob
);
259 if( (p
->iSeek
+nRead
)>nBlob
){
260 nRead
= nBlob
-p
->iSeek
;
266 rc
= sqlite3_blob_read(p
->pBlob
, (void *)buf
, nRead
, p
->iSeek
);
277 ** Write data to an incremental blob channel.
279 static int SQLITE_TCLAPI
incrblobOutput(
280 ClientData instanceData
,
285 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
286 int nWrite
= toWrite
; /* Number of bytes to write */
287 int nBlob
; /* Total size of the blob */
288 int rc
; /* sqlite error code */
290 nBlob
= sqlite3_blob_bytes(p
->pBlob
);
291 if( (p
->iSeek
+nWrite
)>nBlob
){
292 *errorCodePtr
= EINVAL
;
299 rc
= sqlite3_blob_write(p
->pBlob
, (void *)buf
, nWrite
, p
->iSeek
);
310 ** Seek an incremental blob channel.
312 static int SQLITE_TCLAPI
incrblobSeek(
313 ClientData instanceData
,
318 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
328 p
->iSeek
= sqlite3_blob_bytes(p
->pBlob
) + offset
;
331 default: assert(!"Bad seekMode");
338 static void SQLITE_TCLAPI
incrblobWatch(
339 ClientData instanceData
,
344 static int SQLITE_TCLAPI
incrblobHandle(
345 ClientData instanceData
,
352 static Tcl_ChannelType IncrblobChannelType
= {
353 "incrblob", /* typeName */
354 TCL_CHANNEL_VERSION_2
, /* version */
355 incrblobClose
, /* closeProc */
356 incrblobInput
, /* inputProc */
357 incrblobOutput
, /* outputProc */
358 incrblobSeek
, /* seekProc */
359 0, /* setOptionProc */
360 0, /* getOptionProc */
361 incrblobWatch
, /* watchProc (this is a no-op) */
362 incrblobHandle
, /* getHandleProc (always returns error) */
364 0, /* blockModeProc */
367 0, /* wideSeekProc */
371 ** Create a new incrblob channel.
373 static int createIncrblobChannel(
383 sqlite3
*db
= pDb
->db
;
386 int flags
= TCL_READABLE
|(isReadonly
? 0 : TCL_WRITABLE
);
388 /* This variable is used to name the channels: "incrblob_[incr count]" */
389 static int count
= 0;
392 rc
= sqlite3_blob_open(db
, zDb
, zTable
, zColumn
, iRow
, !isReadonly
, &pBlob
);
394 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(pDb
->db
), TCL_VOLATILE
);
398 p
= (IncrblobChannel
*)Tcl_Alloc(sizeof(IncrblobChannel
));
402 sqlite3_snprintf(sizeof(zChannel
), zChannel
, "incrblob_%d", ++count
);
403 p
->channel
= Tcl_CreateChannel(&IncrblobChannelType
, zChannel
, p
, flags
);
404 Tcl_RegisterChannel(interp
, p
->channel
);
406 /* Link the new channel into the SqliteDb.pIncrblob list. */
407 p
->pNext
= pDb
->pIncrblob
;
415 Tcl_SetResult(interp
, (char *)Tcl_GetChannelName(p
->channel
), TCL_VOLATILE
);
418 #else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
419 #define closeIncrblobChannels(pDb)
423 ** Look at the script prefix in pCmd. We will be executing this script
424 ** after first appending one or more arguments. This routine analyzes
425 ** the script to see if it is safe to use Tcl_EvalObjv() on the script
426 ** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
429 ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
430 ** command name followed by zero or more arguments with no [...] or $
431 ** or {...} or ; to be seen anywhere. Most callback scripts consist
432 ** of just a single procedure name and they meet this requirement.
434 static int safeToUseEvalObjv(Tcl_Interp
*interp
, Tcl_Obj
*pCmd
){
435 /* We could try to do something with Tcl_Parse(). But we will instead
436 ** just do a search for forbidden characters. If any of the forbidden
437 ** characters appear in pCmd, we will report the string as unsafe.
441 z
= Tcl_GetStringFromObj(pCmd
, &n
);
444 if( c
=='$' || c
=='[' || c
==';' ) return 0;
450 ** Find an SqlFunc structure with the given name. Or create a new
451 ** one if an existing one cannot be found. Return a pointer to the
454 static SqlFunc
*findSqlFunc(SqliteDb
*pDb
, const char *zName
){
456 int nName
= strlen30(zName
);
457 pNew
= (SqlFunc
*)Tcl_Alloc( sizeof(*pNew
) + nName
+ 1 );
458 pNew
->zName
= (char*)&pNew
[1];
459 memcpy(pNew
->zName
, zName
, nName
+1);
460 for(p
=pDb
->pFunc
; p
; p
=p
->pNext
){
461 if( sqlite3_stricmp(p
->zName
, pNew
->zName
)==0 ){
462 Tcl_Free((char*)pNew
);
466 pNew
->interp
= pDb
->interp
;
469 pNew
->pNext
= pDb
->pFunc
;
475 ** Free a single SqlPreparedStmt object.
477 static void dbFreeStmt(SqlPreparedStmt
*pStmt
){
479 if( sqlite3_sql(pStmt
->pStmt
)==0 ){
480 Tcl_Free((char *)pStmt
->zSql
);
483 sqlite3_finalize(pStmt
->pStmt
);
484 Tcl_Free((char *)pStmt
);
488 ** Finalize and free a list of prepared statements
490 static void flushStmtCache(SqliteDb
*pDb
){
491 SqlPreparedStmt
*pPreStmt
;
492 SqlPreparedStmt
*pNext
;
494 for(pPreStmt
= pDb
->stmtList
; pPreStmt
; pPreStmt
=pNext
){
495 pNext
= pPreStmt
->pNext
;
496 dbFreeStmt(pPreStmt
);
504 ** TCL calls this procedure when an sqlite3 database command is
507 static void SQLITE_TCLAPI
DbDeleteCmd(void *db
){
508 SqliteDb
*pDb
= (SqliteDb
*)db
;
510 closeIncrblobChannels(pDb
);
511 sqlite3_close(pDb
->db
);
513 SqlFunc
*pFunc
= pDb
->pFunc
;
514 pDb
->pFunc
= pFunc
->pNext
;
515 assert( pFunc
->pDb
==pDb
);
516 Tcl_DecrRefCount(pFunc
->pScript
);
517 Tcl_Free((char*)pFunc
);
519 while( pDb
->pCollate
){
520 SqlCollate
*pCollate
= pDb
->pCollate
;
521 pDb
->pCollate
= pCollate
->pNext
;
522 Tcl_Free((char*)pCollate
);
525 Tcl_Free(pDb
->zBusy
);
528 Tcl_Free(pDb
->zTrace
);
531 Tcl_Free(pDb
->zTraceV2
);
534 Tcl_Free(pDb
->zProfile
);
537 Tcl_Free(pDb
->zAuth
);
540 Tcl_Free(pDb
->zNull
);
542 if( pDb
->pUpdateHook
){
543 Tcl_DecrRefCount(pDb
->pUpdateHook
);
545 if( pDb
->pPreUpdateHook
){
546 Tcl_DecrRefCount(pDb
->pPreUpdateHook
);
548 if( pDb
->pRollbackHook
){
549 Tcl_DecrRefCount(pDb
->pRollbackHook
);
552 Tcl_DecrRefCount(pDb
->pWalHook
);
554 if( pDb
->pCollateNeeded
){
555 Tcl_DecrRefCount(pDb
->pCollateNeeded
);
557 Tcl_Free((char*)pDb
);
561 ** This routine is called when a database file is locked while trying
564 static int DbBusyHandler(void *cd
, int nTries
){
565 SqliteDb
*pDb
= (SqliteDb
*)cd
;
569 sqlite3_snprintf(sizeof(zVal
), zVal
, "%d", nTries
);
570 rc
= Tcl_VarEval(pDb
->interp
, pDb
->zBusy
, " ", zVal
, (char*)0);
571 if( rc
!=TCL_OK
|| atoi(Tcl_GetStringResult(pDb
->interp
)) ){
577 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
579 ** This routine is invoked as the 'progress callback' for the database.
581 static int DbProgressHandler(void *cd
){
582 SqliteDb
*pDb
= (SqliteDb
*)cd
;
585 assert( pDb
->zProgress
);
586 rc
= Tcl_Eval(pDb
->interp
, pDb
->zProgress
);
587 if( rc
!=TCL_OK
|| atoi(Tcl_GetStringResult(pDb
->interp
)) ){
594 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
595 !defined(SQLITE_OMIT_DEPRECATED)
597 ** This routine is called by the SQLite trace handler whenever a new
598 ** block of SQL is executed. The TCL script in pDb->zTrace is executed.
600 static void DbTraceHandler(void *cd
, const char *zSql
){
601 SqliteDb
*pDb
= (SqliteDb
*)cd
;
604 Tcl_DStringInit(&str
);
605 Tcl_DStringAppend(&str
, pDb
->zTrace
, -1);
606 Tcl_DStringAppendElement(&str
, zSql
);
607 Tcl_Eval(pDb
->interp
, Tcl_DStringValue(&str
));
608 Tcl_DStringFree(&str
);
609 Tcl_ResetResult(pDb
->interp
);
613 #ifndef SQLITE_OMIT_TRACE
615 ** This routine is called by the SQLite trace_v2 handler whenever a new
616 ** supported event is generated. Unsupported event types are ignored.
617 ** The TCL script in pDb->zTraceV2 is executed, with the arguments for
618 ** the event appended to it (as list elements).
620 static int DbTraceV2Handler(
621 unsigned type
, /* One of the SQLITE_TRACE_* event types. */
622 void *cd
, /* The original context data pointer. */
623 void *pd
, /* Primary event data, depends on event type. */
624 void *xd
/* Extra event data, depends on event type. */
626 SqliteDb
*pDb
= (SqliteDb
*)cd
;
630 case SQLITE_TRACE_STMT
: {
631 sqlite3_stmt
*pStmt
= (sqlite3_stmt
*)pd
;
632 char *zSql
= (char *)xd
;
634 pCmd
= Tcl_NewStringObj(pDb
->zTraceV2
, -1);
635 Tcl_IncrRefCount(pCmd
);
636 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
637 Tcl_NewWideIntObj((Tcl_WideInt
)pStmt
));
638 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
639 Tcl_NewStringObj(zSql
, -1));
640 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
641 Tcl_DecrRefCount(pCmd
);
642 Tcl_ResetResult(pDb
->interp
);
645 case SQLITE_TRACE_PROFILE
: {
646 sqlite3_stmt
*pStmt
= (sqlite3_stmt
*)pd
;
647 sqlite3_int64 ns
= (sqlite3_int64
)xd
;
649 pCmd
= Tcl_NewStringObj(pDb
->zTraceV2
, -1);
650 Tcl_IncrRefCount(pCmd
);
651 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
652 Tcl_NewWideIntObj((Tcl_WideInt
)pStmt
));
653 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
654 Tcl_NewWideIntObj((Tcl_WideInt
)ns
));
655 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
656 Tcl_DecrRefCount(pCmd
);
657 Tcl_ResetResult(pDb
->interp
);
660 case SQLITE_TRACE_ROW
: {
661 sqlite3_stmt
*pStmt
= (sqlite3_stmt
*)pd
;
663 pCmd
= Tcl_NewStringObj(pDb
->zTraceV2
, -1);
664 Tcl_IncrRefCount(pCmd
);
665 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
666 Tcl_NewWideIntObj((Tcl_WideInt
)pStmt
));
667 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
668 Tcl_DecrRefCount(pCmd
);
669 Tcl_ResetResult(pDb
->interp
);
672 case SQLITE_TRACE_CLOSE
: {
673 sqlite3
*db
= (sqlite3
*)pd
;
675 pCmd
= Tcl_NewStringObj(pDb
->zTraceV2
, -1);
676 Tcl_IncrRefCount(pCmd
);
677 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
678 Tcl_NewWideIntObj((Tcl_WideInt
)db
));
679 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
680 Tcl_DecrRefCount(pCmd
);
681 Tcl_ResetResult(pDb
->interp
);
689 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
690 !defined(SQLITE_OMIT_DEPRECATED)
692 ** This routine is called by the SQLite profile handler after a statement
693 ** SQL has executed. The TCL script in pDb->zProfile is evaluated.
695 static void DbProfileHandler(void *cd
, const char *zSql
, sqlite_uint64 tm
){
696 SqliteDb
*pDb
= (SqliteDb
*)cd
;
700 sqlite3_snprintf(sizeof(zTm
)-1, zTm
, "%lld", tm
);
701 Tcl_DStringInit(&str
);
702 Tcl_DStringAppend(&str
, pDb
->zProfile
, -1);
703 Tcl_DStringAppendElement(&str
, zSql
);
704 Tcl_DStringAppendElement(&str
, zTm
);
705 Tcl_Eval(pDb
->interp
, Tcl_DStringValue(&str
));
706 Tcl_DStringFree(&str
);
707 Tcl_ResetResult(pDb
->interp
);
712 ** This routine is called when a transaction is committed. The
713 ** TCL script in pDb->zCommit is executed. If it returns non-zero or
714 ** if it throws an exception, the transaction is rolled back instead
715 ** of being committed.
717 static int DbCommitHandler(void *cd
){
718 SqliteDb
*pDb
= (SqliteDb
*)cd
;
721 rc
= Tcl_Eval(pDb
->interp
, pDb
->zCommit
);
722 if( rc
!=TCL_OK
|| atoi(Tcl_GetStringResult(pDb
->interp
)) ){
728 static void DbRollbackHandler(void *clientData
){
729 SqliteDb
*pDb
= (SqliteDb
*)clientData
;
730 assert(pDb
->pRollbackHook
);
731 if( TCL_OK
!=Tcl_EvalObjEx(pDb
->interp
, pDb
->pRollbackHook
, 0) ){
732 Tcl_BackgroundError(pDb
->interp
);
737 ** This procedure handles wal_hook callbacks.
739 static int DbWalHandler(
747 SqliteDb
*pDb
= (SqliteDb
*)clientData
;
748 Tcl_Interp
*interp
= pDb
->interp
;
749 assert(pDb
->pWalHook
);
751 assert( db
==pDb
->db
);
752 p
= Tcl_DuplicateObj(pDb
->pWalHook
);
754 Tcl_ListObjAppendElement(interp
, p
, Tcl_NewStringObj(zDb
, -1));
755 Tcl_ListObjAppendElement(interp
, p
, Tcl_NewIntObj(nEntry
));
756 if( TCL_OK
!=Tcl_EvalObjEx(interp
, p
, 0)
757 || TCL_OK
!=Tcl_GetIntFromObj(interp
, Tcl_GetObjResult(interp
), &ret
)
759 Tcl_BackgroundError(interp
);
766 #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
767 static void setTestUnlockNotifyVars(Tcl_Interp
*interp
, int iArg
, int nArg
){
769 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%d", iArg
);
770 Tcl_SetVar(interp
, "sqlite_unlock_notify_arg", zBuf
, TCL_GLOBAL_ONLY
);
771 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%d", nArg
);
772 Tcl_SetVar(interp
, "sqlite_unlock_notify_argcount", zBuf
, TCL_GLOBAL_ONLY
);
775 # define setTestUnlockNotifyVars(x,y,z)
778 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
779 static void DbUnlockNotify(void **apArg
, int nArg
){
781 for(i
=0; i
<nArg
; i
++){
782 const int flags
= (TCL_EVAL_GLOBAL
|TCL_EVAL_DIRECT
);
783 SqliteDb
*pDb
= (SqliteDb
*)apArg
[i
];
784 setTestUnlockNotifyVars(pDb
->interp
, i
, nArg
);
785 assert( pDb
->pUnlockNotify
);
786 Tcl_EvalObjEx(pDb
->interp
, pDb
->pUnlockNotify
, flags
);
787 Tcl_DecrRefCount(pDb
->pUnlockNotify
);
788 pDb
->pUnlockNotify
= 0;
793 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
795 ** Pre-update hook callback.
797 static void DbPreUpdateHandler(
806 SqliteDb
*pDb
= (SqliteDb
*)p
;
808 static const char *azStr
[] = {"DELETE", "INSERT", "UPDATE"};
810 assert( (SQLITE_DELETE
-1)/9 == 0 );
811 assert( (SQLITE_INSERT
-1)/9 == 1 );
812 assert( (SQLITE_UPDATE
-1)/9 == 2 );
813 assert( pDb
->pPreUpdateHook
);
814 assert( db
==pDb
->db
);
815 assert( op
==SQLITE_INSERT
|| op
==SQLITE_UPDATE
|| op
==SQLITE_DELETE
);
817 pCmd
= Tcl_DuplicateObj(pDb
->pPreUpdateHook
);
818 Tcl_IncrRefCount(pCmd
);
819 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(azStr
[(op
-1)/9], -1));
820 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(zDb
, -1));
821 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(zTbl
, -1));
822 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewWideIntObj(iKey1
));
823 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewWideIntObj(iKey2
));
824 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
825 Tcl_DecrRefCount(pCmd
);
827 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
829 static void DbUpdateHandler(
836 SqliteDb
*pDb
= (SqliteDb
*)p
;
838 static const char *azStr
[] = {"DELETE", "INSERT", "UPDATE"};
840 assert( (SQLITE_DELETE
-1)/9 == 0 );
841 assert( (SQLITE_INSERT
-1)/9 == 1 );
842 assert( (SQLITE_UPDATE
-1)/9 == 2 );
844 assert( pDb
->pUpdateHook
);
845 assert( op
==SQLITE_INSERT
|| op
==SQLITE_UPDATE
|| op
==SQLITE_DELETE
);
847 pCmd
= Tcl_DuplicateObj(pDb
->pUpdateHook
);
848 Tcl_IncrRefCount(pCmd
);
849 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(azStr
[(op
-1)/9], -1));
850 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(zDb
, -1));
851 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(zTbl
, -1));
852 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewWideIntObj(rowid
));
853 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
854 Tcl_DecrRefCount(pCmd
);
857 static void tclCollateNeeded(
863 SqliteDb
*pDb
= (SqliteDb
*)pCtx
;
864 Tcl_Obj
*pScript
= Tcl_DuplicateObj(pDb
->pCollateNeeded
);
865 Tcl_IncrRefCount(pScript
);
866 Tcl_ListObjAppendElement(0, pScript
, Tcl_NewStringObj(zName
, -1));
867 Tcl_EvalObjEx(pDb
->interp
, pScript
, 0);
868 Tcl_DecrRefCount(pScript
);
872 ** This routine is called to evaluate an SQL collation function implemented
875 static int tclSqlCollate(
882 SqlCollate
*p
= (SqlCollate
*)pCtx
;
885 pCmd
= Tcl_NewStringObj(p
->zScript
, -1);
886 Tcl_IncrRefCount(pCmd
);
887 Tcl_ListObjAppendElement(p
->interp
, pCmd
, Tcl_NewStringObj(zA
, nA
));
888 Tcl_ListObjAppendElement(p
->interp
, pCmd
, Tcl_NewStringObj(zB
, nB
));
889 Tcl_EvalObjEx(p
->interp
, pCmd
, TCL_EVAL_DIRECT
);
890 Tcl_DecrRefCount(pCmd
);
891 return (atoi(Tcl_GetStringResult(p
->interp
)));
895 ** This routine is called to evaluate an SQL function implemented
898 static void tclSqlFunc(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
){
899 SqlFunc
*p
= sqlite3_user_data(context
);
905 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
906 ** script object directly. This allows the TCL compiler to generate
907 ** bytecode for the command on the first invocation and thus make
908 ** subsequent invocations much faster. */
910 Tcl_IncrRefCount(pCmd
);
911 rc
= Tcl_EvalObjEx(p
->interp
, pCmd
, 0);
912 Tcl_DecrRefCount(pCmd
);
914 /* If there are arguments to the function, make a shallow copy of the
915 ** script object, lappend the arguments, then evaluate the copy.
917 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
918 ** The new Tcl_Obj contains pointers to the original list elements.
919 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
920 ** of the list to tclCmdNameType, that alternate representation will
921 ** be preserved and reused on the next invocation.
925 if( Tcl_ListObjGetElements(p
->interp
, p
->pScript
, &nArg
, &aArg
) ){
926 sqlite3_result_error(context
, Tcl_GetStringResult(p
->interp
), -1);
929 pCmd
= Tcl_NewListObj(nArg
, aArg
);
930 Tcl_IncrRefCount(pCmd
);
931 for(i
=0; i
<argc
; i
++){
932 sqlite3_value
*pIn
= argv
[i
];
935 /* Set pVal to contain the i'th column of this row. */
936 switch( sqlite3_value_type(pIn
) ){
938 int bytes
= sqlite3_value_bytes(pIn
);
939 pVal
= Tcl_NewByteArrayObj(sqlite3_value_blob(pIn
), bytes
);
942 case SQLITE_INTEGER
: {
943 sqlite_int64 v
= sqlite3_value_int64(pIn
);
944 if( v
>=-2147483647 && v
<=2147483647 ){
945 pVal
= Tcl_NewIntObj((int)v
);
947 pVal
= Tcl_NewWideIntObj(v
);
952 double r
= sqlite3_value_double(pIn
);
953 pVal
= Tcl_NewDoubleObj(r
);
957 pVal
= Tcl_NewStringObj(p
->pDb
->zNull
, -1);
961 int bytes
= sqlite3_value_bytes(pIn
);
962 pVal
= Tcl_NewStringObj((char *)sqlite3_value_text(pIn
), bytes
);
966 rc
= Tcl_ListObjAppendElement(p
->interp
, pCmd
, pVal
);
968 Tcl_DecrRefCount(pCmd
);
969 sqlite3_result_error(context
, Tcl_GetStringResult(p
->interp
), -1);
973 if( !p
->useEvalObjv
){
974 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
975 ** is a list without a string representation. To prevent this from
976 ** happening, make sure pCmd has a valid string representation */
979 rc
= Tcl_EvalObjEx(p
->interp
, pCmd
, TCL_EVAL_DIRECT
);
980 Tcl_DecrRefCount(pCmd
);
983 if( rc
&& rc
!=TCL_RETURN
){
984 sqlite3_result_error(context
, Tcl_GetStringResult(p
->interp
), -1);
986 Tcl_Obj
*pVar
= Tcl_GetObjResult(p
->interp
);
989 const char *zType
= (pVar
->typePtr
? pVar
->typePtr
->name
: "");
991 if( c
=='b' && strcmp(zType
,"bytearray")==0 && pVar
->bytes
==0 ){
992 /* Only return a BLOB type if the Tcl variable is a bytearray and
993 ** has no string representation. */
994 data
= Tcl_GetByteArrayFromObj(pVar
, &n
);
995 sqlite3_result_blob(context
, data
, n
, SQLITE_TRANSIENT
);
996 }else if( c
=='b' && strcmp(zType
,"boolean")==0 ){
997 Tcl_GetIntFromObj(0, pVar
, &n
);
998 sqlite3_result_int(context
, n
);
999 }else if( c
=='d' && strcmp(zType
,"double")==0 ){
1001 Tcl_GetDoubleFromObj(0, pVar
, &r
);
1002 sqlite3_result_double(context
, r
);
1003 }else if( (c
=='w' && strcmp(zType
,"wideInt")==0) ||
1004 (c
=='i' && strcmp(zType
,"int")==0) ){
1006 Tcl_GetWideIntFromObj(0, pVar
, &v
);
1007 sqlite3_result_int64(context
, v
);
1009 data
= (unsigned char *)Tcl_GetStringFromObj(pVar
, &n
);
1010 sqlite3_result_text(context
, (char *)data
, n
, SQLITE_TRANSIENT
);
1015 #ifndef SQLITE_OMIT_AUTHORIZATION
1017 ** This is the authentication function. It appends the authentication
1018 ** type code and the two arguments to zCmd[] then invokes the result
1019 ** on the interpreter. The reply is examined to determine if the
1020 ** authentication fails or succeeds.
1022 static int auth_callback(
1029 #ifdef SQLITE_USER_AUTHENTICATION
1037 /* EVIDENCE-OF: R-38590-62769 The first parameter to the authorizer
1038 ** callback is a copy of the third parameter to the
1039 ** sqlite3_set_authorizer() interface.
1041 SqliteDb
*pDb
= (SqliteDb
*)pArg
;
1042 if( pDb
->disableAuth
) return SQLITE_OK
;
1044 /* EVIDENCE-OF: R-56518-44310 The second parameter to the callback is an
1045 ** integer action code that specifies the particular action to be
1048 case SQLITE_COPY
: zCode
="SQLITE_COPY"; break;
1049 case SQLITE_CREATE_INDEX
: zCode
="SQLITE_CREATE_INDEX"; break;
1050 case SQLITE_CREATE_TABLE
: zCode
="SQLITE_CREATE_TABLE"; break;
1051 case SQLITE_CREATE_TEMP_INDEX
: zCode
="SQLITE_CREATE_TEMP_INDEX"; break;
1052 case SQLITE_CREATE_TEMP_TABLE
: zCode
="SQLITE_CREATE_TEMP_TABLE"; break;
1053 case SQLITE_CREATE_TEMP_TRIGGER
: zCode
="SQLITE_CREATE_TEMP_TRIGGER"; break;
1054 case SQLITE_CREATE_TEMP_VIEW
: zCode
="SQLITE_CREATE_TEMP_VIEW"; break;
1055 case SQLITE_CREATE_TRIGGER
: zCode
="SQLITE_CREATE_TRIGGER"; break;
1056 case SQLITE_CREATE_VIEW
: zCode
="SQLITE_CREATE_VIEW"; break;
1057 case SQLITE_DELETE
: zCode
="SQLITE_DELETE"; break;
1058 case SQLITE_DROP_INDEX
: zCode
="SQLITE_DROP_INDEX"; break;
1059 case SQLITE_DROP_TABLE
: zCode
="SQLITE_DROP_TABLE"; break;
1060 case SQLITE_DROP_TEMP_INDEX
: zCode
="SQLITE_DROP_TEMP_INDEX"; break;
1061 case SQLITE_DROP_TEMP_TABLE
: zCode
="SQLITE_DROP_TEMP_TABLE"; break;
1062 case SQLITE_DROP_TEMP_TRIGGER
: zCode
="SQLITE_DROP_TEMP_TRIGGER"; break;
1063 case SQLITE_DROP_TEMP_VIEW
: zCode
="SQLITE_DROP_TEMP_VIEW"; break;
1064 case SQLITE_DROP_TRIGGER
: zCode
="SQLITE_DROP_TRIGGER"; break;
1065 case SQLITE_DROP_VIEW
: zCode
="SQLITE_DROP_VIEW"; break;
1066 case SQLITE_INSERT
: zCode
="SQLITE_INSERT"; break;
1067 case SQLITE_PRAGMA
: zCode
="SQLITE_PRAGMA"; break;
1068 case SQLITE_READ
: zCode
="SQLITE_READ"; break;
1069 case SQLITE_SELECT
: zCode
="SQLITE_SELECT"; break;
1070 case SQLITE_TRANSACTION
: zCode
="SQLITE_TRANSACTION"; break;
1071 case SQLITE_UPDATE
: zCode
="SQLITE_UPDATE"; break;
1072 case SQLITE_ATTACH
: zCode
="SQLITE_ATTACH"; break;
1073 case SQLITE_DETACH
: zCode
="SQLITE_DETACH"; break;
1074 case SQLITE_ALTER_TABLE
: zCode
="SQLITE_ALTER_TABLE"; break;
1075 case SQLITE_REINDEX
: zCode
="SQLITE_REINDEX"; break;
1076 case SQLITE_ANALYZE
: zCode
="SQLITE_ANALYZE"; break;
1077 case SQLITE_CREATE_VTABLE
: zCode
="SQLITE_CREATE_VTABLE"; break;
1078 case SQLITE_DROP_VTABLE
: zCode
="SQLITE_DROP_VTABLE"; break;
1079 case SQLITE_FUNCTION
: zCode
="SQLITE_FUNCTION"; break;
1080 case SQLITE_SAVEPOINT
: zCode
="SQLITE_SAVEPOINT"; break;
1081 case SQLITE_RECURSIVE
: zCode
="SQLITE_RECURSIVE"; break;
1082 default : zCode
="????"; break;
1084 Tcl_DStringInit(&str
);
1085 Tcl_DStringAppend(&str
, pDb
->zAuth
, -1);
1086 Tcl_DStringAppendElement(&str
, zCode
);
1087 Tcl_DStringAppendElement(&str
, zArg1
? zArg1
: "");
1088 Tcl_DStringAppendElement(&str
, zArg2
? zArg2
: "");
1089 Tcl_DStringAppendElement(&str
, zArg3
? zArg3
: "");
1090 Tcl_DStringAppendElement(&str
, zArg4
? zArg4
: "");
1091 #ifdef SQLITE_USER_AUTHENTICATION
1092 Tcl_DStringAppendElement(&str
, zArg5
? zArg5
: "");
1094 rc
= Tcl_GlobalEval(pDb
->interp
, Tcl_DStringValue(&str
));
1095 Tcl_DStringFree(&str
);
1096 zReply
= rc
==TCL_OK
? Tcl_GetStringResult(pDb
->interp
) : "SQLITE_DENY";
1097 if( strcmp(zReply
,"SQLITE_OK")==0 ){
1099 }else if( strcmp(zReply
,"SQLITE_DENY")==0 ){
1101 }else if( strcmp(zReply
,"SQLITE_IGNORE")==0 ){
1108 #endif /* SQLITE_OMIT_AUTHORIZATION */
1111 ** This routine reads a line of text from FILE in, stores
1112 ** the text in memory obtained from malloc() and returns a pointer
1113 ** to the text. NULL is returned at end of file, or if malloc()
1116 ** The interface is like "readline" but no command-line editing
1119 ** copied from shell.c from '.import' command
1121 static char *local_getline(char *zPrompt
, FILE *in
){
1127 zLine
= malloc( nLine
);
1128 if( zLine
==0 ) return 0;
1132 nLine
= nLine
*2 + 100;
1133 zLine
= realloc(zLine
, nLine
);
1134 if( zLine
==0 ) return 0;
1136 if( fgets(&zLine
[n
], nLine
- n
, in
)==0 ){
1144 while( zLine
[n
] ){ n
++; }
1145 if( n
>0 && zLine
[n
-1]=='\n' ){
1151 zLine
= realloc( zLine
, n
+1 );
1157 ** This function is part of the implementation of the command:
1159 ** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1161 ** It is invoked after evaluating the script SCRIPT to commit or rollback
1162 ** the transaction or savepoint opened by the [transaction] command.
1164 static int SQLITE_TCLAPI
DbTransPostCmd(
1165 ClientData data
[], /* data[0] is the Sqlite3Db* for $db */
1166 Tcl_Interp
*interp
, /* Tcl interpreter */
1167 int result
/* Result of evaluating SCRIPT */
1169 static const char *const azEnd
[] = {
1170 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1171 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1172 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1173 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1175 SqliteDb
*pDb
= (SqliteDb
*)data
[0];
1179 pDb
->nTransaction
--;
1180 zEnd
= azEnd
[(rc
==TCL_ERROR
)*2 + (pDb
->nTransaction
==0)];
1183 if( sqlite3_exec(pDb
->db
, zEnd
, 0, 0, 0) ){
1184 /* This is a tricky scenario to handle. The most likely cause of an
1185 ** error is that the exec() above was an attempt to commit the
1186 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1187 ** that an IO-error has occurred. In either case, throw a Tcl exception
1188 ** and try to rollback the transaction.
1190 ** But it could also be that the user executed one or more BEGIN,
1191 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1192 ** this method's logic. Not clear how this would be best handled.
1194 if( rc
!=TCL_ERROR
){
1195 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
1198 sqlite3_exec(pDb
->db
, "ROLLBACK", 0, 0, 0);
1206 ** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1207 ** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1208 ** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1209 ** on whether or not the [db_use_legacy_prepare] command has been used to
1210 ** configure the connection.
1212 static int dbPrepare(
1213 SqliteDb
*pDb
, /* Database object */
1214 const char *zSql
, /* SQL to compile */
1215 sqlite3_stmt
**ppStmt
, /* OUT: Prepared statement */
1216 const char **pzOut
/* OUT: Pointer to next SQL statement */
1218 unsigned int prepFlags
= 0;
1220 if( pDb
->bLegacyPrepare
){
1221 return sqlite3_prepare(pDb
->db
, zSql
, -1, ppStmt
, pzOut
);
1224 /* If the statement cache is large, use the SQLITE_PREPARE_PERSISTENT
1225 ** flags, which uses less lookaside memory. But if the cache is small,
1226 ** omit that flag to make full use of lookaside */
1227 if( pDb
->maxStmt
>5 ) prepFlags
= SQLITE_PREPARE_PERSISTENT
;
1229 return sqlite3_prepare_v3(pDb
->db
, zSql
, -1, prepFlags
, ppStmt
, pzOut
);
1233 ** Search the cache for a prepared-statement object that implements the
1234 ** first SQL statement in the buffer pointed to by parameter zIn. If
1235 ** no such prepared-statement can be found, allocate and prepare a new
1236 ** one. In either case, bind the current values of the relevant Tcl
1237 ** variables to any $var, :var or @var variables in the statement. Before
1238 ** returning, set *ppPreStmt to point to the prepared-statement object.
1240 ** Output parameter *pzOut is set to point to the next SQL statement in
1241 ** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1244 ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1245 ** and an error message loaded into interpreter pDb->interp.
1247 static int dbPrepareAndBind(
1248 SqliteDb
*pDb
, /* Database object */
1249 char const *zIn
, /* SQL to compile */
1250 char const **pzOut
, /* OUT: Pointer to next SQL statement */
1251 SqlPreparedStmt
**ppPreStmt
/* OUT: Object used to cache statement */
1253 const char *zSql
= zIn
; /* Pointer to first SQL statement in zIn */
1254 sqlite3_stmt
*pStmt
= 0; /* Prepared statement object */
1255 SqlPreparedStmt
*pPreStmt
; /* Pointer to cached statement */
1256 int nSql
; /* Length of zSql in bytes */
1257 int nVar
= 0; /* Number of variables in statement */
1258 int iParm
= 0; /* Next free entry in apParm */
1261 Tcl_Interp
*interp
= pDb
->interp
;
1265 /* Trim spaces from the start of zSql and calculate the remaining length. */
1266 while( (c
= zSql
[0])==' ' || c
=='\t' || c
=='\r' || c
=='\n' ){ zSql
++; }
1267 nSql
= strlen30(zSql
);
1269 for(pPreStmt
= pDb
->stmtList
; pPreStmt
; pPreStmt
=pPreStmt
->pNext
){
1270 int n
= pPreStmt
->nSql
;
1272 && memcmp(pPreStmt
->zSql
, zSql
, n
)==0
1273 && (zSql
[n
]==0 || zSql
[n
-1]==';')
1275 pStmt
= pPreStmt
->pStmt
;
1276 *pzOut
= &zSql
[pPreStmt
->nSql
];
1278 /* When a prepared statement is found, unlink it from the
1279 ** cache list. It will later be added back to the beginning
1280 ** of the cache list in order to implement LRU replacement.
1282 if( pPreStmt
->pPrev
){
1283 pPreStmt
->pPrev
->pNext
= pPreStmt
->pNext
;
1285 pDb
->stmtList
= pPreStmt
->pNext
;
1287 if( pPreStmt
->pNext
){
1288 pPreStmt
->pNext
->pPrev
= pPreStmt
->pPrev
;
1290 pDb
->stmtLast
= pPreStmt
->pPrev
;
1293 nVar
= sqlite3_bind_parameter_count(pStmt
);
1298 /* If no prepared statement was found. Compile the SQL text. Also allocate
1299 ** a new SqlPreparedStmt structure. */
1303 if( SQLITE_OK
!=dbPrepare(pDb
, zSql
, &pStmt
, pzOut
) ){
1304 Tcl_SetObjResult(interp
, Tcl_NewStringObj(sqlite3_errmsg(pDb
->db
), -1));
1308 if( SQLITE_OK
!=sqlite3_errcode(pDb
->db
) ){
1309 /* A compile-time error in the statement. */
1310 Tcl_SetObjResult(interp
, Tcl_NewStringObj(sqlite3_errmsg(pDb
->db
), -1));
1313 /* The statement was a no-op. Continue to the next statement
1314 ** in the SQL string.
1320 assert( pPreStmt
==0 );
1321 nVar
= sqlite3_bind_parameter_count(pStmt
);
1322 nByte
= sizeof(SqlPreparedStmt
) + nVar
*sizeof(Tcl_Obj
*);
1323 pPreStmt
= (SqlPreparedStmt
*)Tcl_Alloc(nByte
);
1324 memset(pPreStmt
, 0, nByte
);
1326 pPreStmt
->pStmt
= pStmt
;
1327 pPreStmt
->nSql
= (int)(*pzOut
- zSql
);
1328 pPreStmt
->zSql
= sqlite3_sql(pStmt
);
1329 pPreStmt
->apParm
= (Tcl_Obj
**)&pPreStmt
[1];
1331 if( pPreStmt
->zSql
==0 ){
1332 char *zCopy
= Tcl_Alloc(pPreStmt
->nSql
+ 1);
1333 memcpy(zCopy
, zSql
, pPreStmt
->nSql
);
1334 zCopy
[pPreStmt
->nSql
] = '\0';
1335 pPreStmt
->zSql
= zCopy
;
1340 assert( strlen30(pPreStmt
->zSql
)==pPreStmt
->nSql
);
1341 assert( 0==memcmp(pPreStmt
->zSql
, zSql
, pPreStmt
->nSql
) );
1343 /* Bind values to parameters that begin with $ or : */
1344 for(i
=1; i
<=nVar
; i
++){
1345 const char *zVar
= sqlite3_bind_parameter_name(pStmt
, i
);
1346 if( zVar
!=0 && (zVar
[0]=='$' || zVar
[0]==':' || zVar
[0]=='@') ){
1347 Tcl_Obj
*pVar
= Tcl_GetVar2Ex(interp
, &zVar
[1], 0, 0);
1351 const char *zType
= (pVar
->typePtr
? pVar
->typePtr
->name
: "");
1354 (c
=='b' && strcmp(zType
,"bytearray")==0 && pVar
->bytes
==0) ){
1355 /* Load a BLOB type if the Tcl variable is a bytearray and
1356 ** it has no string representation or the host
1357 ** parameter name begins with "@". */
1358 data
= Tcl_GetByteArrayFromObj(pVar
, &n
);
1359 sqlite3_bind_blob(pStmt
, i
, data
, n
, SQLITE_STATIC
);
1360 Tcl_IncrRefCount(pVar
);
1361 pPreStmt
->apParm
[iParm
++] = pVar
;
1362 }else if( c
=='b' && strcmp(zType
,"boolean")==0 ){
1363 Tcl_GetIntFromObj(interp
, pVar
, &n
);
1364 sqlite3_bind_int(pStmt
, i
, n
);
1365 }else if( c
=='d' && strcmp(zType
,"double")==0 ){
1367 Tcl_GetDoubleFromObj(interp
, pVar
, &r
);
1368 sqlite3_bind_double(pStmt
, i
, r
);
1369 }else if( (c
=='w' && strcmp(zType
,"wideInt")==0) ||
1370 (c
=='i' && strcmp(zType
,"int")==0) ){
1372 Tcl_GetWideIntFromObj(interp
, pVar
, &v
);
1373 sqlite3_bind_int64(pStmt
, i
, v
);
1375 data
= (unsigned char *)Tcl_GetStringFromObj(pVar
, &n
);
1376 sqlite3_bind_text(pStmt
, i
, (char *)data
, n
, SQLITE_STATIC
);
1377 Tcl_IncrRefCount(pVar
);
1378 pPreStmt
->apParm
[iParm
++] = pVar
;
1381 sqlite3_bind_null(pStmt
, i
);
1385 pPreStmt
->nParm
= iParm
;
1386 *ppPreStmt
= pPreStmt
;
1392 ** Release a statement reference obtained by calling dbPrepareAndBind().
1393 ** There should be exactly one call to this function for each call to
1394 ** dbPrepareAndBind().
1396 ** If the discard parameter is non-zero, then the statement is deleted
1397 ** immediately. Otherwise it is added to the LRU list and may be returned
1398 ** by a subsequent call to dbPrepareAndBind().
1400 static void dbReleaseStmt(
1401 SqliteDb
*pDb
, /* Database handle */
1402 SqlPreparedStmt
*pPreStmt
, /* Prepared statement handle to release */
1403 int discard
/* True to delete (not cache) the pPreStmt */
1407 /* Free the bound string and blob parameters */
1408 for(i
=0; i
<pPreStmt
->nParm
; i
++){
1409 Tcl_DecrRefCount(pPreStmt
->apParm
[i
]);
1411 pPreStmt
->nParm
= 0;
1413 if( pDb
->maxStmt
<=0 || discard
){
1414 /* If the cache is turned off, deallocated the statement */
1415 dbFreeStmt(pPreStmt
);
1417 /* Add the prepared statement to the beginning of the cache list. */
1418 pPreStmt
->pNext
= pDb
->stmtList
;
1419 pPreStmt
->pPrev
= 0;
1420 if( pDb
->stmtList
){
1421 pDb
->stmtList
->pPrev
= pPreStmt
;
1423 pDb
->stmtList
= pPreStmt
;
1424 if( pDb
->stmtLast
==0 ){
1425 assert( pDb
->nStmt
==0 );
1426 pDb
->stmtLast
= pPreStmt
;
1428 assert( pDb
->nStmt
>0 );
1432 /* If we have too many statement in cache, remove the surplus from
1433 ** the end of the cache list. */
1434 while( pDb
->nStmt
>pDb
->maxStmt
){
1435 SqlPreparedStmt
*pLast
= pDb
->stmtLast
;
1436 pDb
->stmtLast
= pLast
->pPrev
;
1437 pDb
->stmtLast
->pNext
= 0;
1445 ** Structure used with dbEvalXXX() functions:
1451 ** dbEvalColumnValue()
1453 typedef struct DbEvalContext DbEvalContext
;
1454 struct DbEvalContext
{
1455 SqliteDb
*pDb
; /* Database handle */
1456 Tcl_Obj
*pSql
; /* Object holding string zSql */
1457 const char *zSql
; /* Remaining SQL to execute */
1458 SqlPreparedStmt
*pPreStmt
; /* Current statement */
1459 int nCol
; /* Number of columns returned by pStmt */
1460 int evalFlags
; /* Flags used */
1461 Tcl_Obj
*pArray
; /* Name of array variable */
1462 Tcl_Obj
**apColName
; /* Array of column names */
1465 #define SQLITE_EVAL_WITHOUTNULLS 0x00001 /* Unset array(*) for NULL */
1468 ** Release any cache of column names currently held as part of
1469 ** the DbEvalContext structure passed as the first argument.
1471 static void dbReleaseColumnNames(DbEvalContext
*p
){
1474 for(i
=0; i
<p
->nCol
; i
++){
1475 Tcl_DecrRefCount(p
->apColName
[i
]);
1477 Tcl_Free((char *)p
->apColName
);
1484 ** Initialize a DbEvalContext structure.
1486 ** If pArray is not NULL, then it contains the name of a Tcl array
1487 ** variable. The "*" member of this array is set to a list containing
1488 ** the names of the columns returned by the statement as part of each
1489 ** call to dbEvalStep(), in order from left to right. e.g. if the names
1490 ** of the returned columns are a, b and c, it does the equivalent of the
1493 ** set ${pArray}(*) {a b c}
1495 static void dbEvalInit(
1496 DbEvalContext
*p
, /* Pointer to structure to initialize */
1497 SqliteDb
*pDb
, /* Database handle */
1498 Tcl_Obj
*pSql
, /* Object containing SQL script */
1499 Tcl_Obj
*pArray
, /* Name of Tcl array to set (*) element of */
1500 int evalFlags
/* Flags controlling evaluation */
1502 memset(p
, 0, sizeof(DbEvalContext
));
1504 p
->zSql
= Tcl_GetString(pSql
);
1506 Tcl_IncrRefCount(pSql
);
1509 Tcl_IncrRefCount(pArray
);
1511 p
->evalFlags
= evalFlags
;
1515 ** Obtain information about the row that the DbEvalContext passed as the
1516 ** first argument currently points to.
1518 static void dbEvalRowInfo(
1519 DbEvalContext
*p
, /* Evaluation context */
1520 int *pnCol
, /* OUT: Number of column names */
1521 Tcl_Obj
***papColName
/* OUT: Array of column names */
1523 /* Compute column names */
1524 if( 0==p
->apColName
){
1525 sqlite3_stmt
*pStmt
= p
->pPreStmt
->pStmt
;
1526 int i
; /* Iterator variable */
1527 int nCol
; /* Number of columns returned by pStmt */
1528 Tcl_Obj
**apColName
= 0; /* Array of column names */
1530 p
->nCol
= nCol
= sqlite3_column_count(pStmt
);
1531 if( nCol
>0 && (papColName
|| p
->pArray
) ){
1532 apColName
= (Tcl_Obj
**)Tcl_Alloc( sizeof(Tcl_Obj
*)*nCol
);
1533 for(i
=0; i
<nCol
; i
++){
1534 apColName
[i
] = Tcl_NewStringObj(sqlite3_column_name(pStmt
,i
), -1);
1535 Tcl_IncrRefCount(apColName
[i
]);
1537 p
->apColName
= apColName
;
1540 /* If results are being stored in an array variable, then create
1541 ** the array(*) entry for that array
1544 Tcl_Interp
*interp
= p
->pDb
->interp
;
1545 Tcl_Obj
*pColList
= Tcl_NewObj();
1546 Tcl_Obj
*pStar
= Tcl_NewStringObj("*", -1);
1548 for(i
=0; i
<nCol
; i
++){
1549 Tcl_ListObjAppendElement(interp
, pColList
, apColName
[i
]);
1551 Tcl_IncrRefCount(pStar
);
1552 Tcl_ObjSetVar2(interp
, p
->pArray
, pStar
, pColList
, 0);
1553 Tcl_DecrRefCount(pStar
);
1558 *papColName
= p
->apColName
;
1566 ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1567 ** returned, then an error message is stored in the interpreter before
1570 ** A return value of TCL_OK means there is a row of data available. The
1571 ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1572 ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1573 ** is returned, then the SQL script has finished executing and there are
1574 ** no further rows available. This is similar to SQLITE_DONE.
1576 static int dbEvalStep(DbEvalContext
*p
){
1577 const char *zPrevSql
= 0; /* Previous value of p->zSql */
1579 while( p
->zSql
[0] || p
->pPreStmt
){
1581 if( p
->pPreStmt
==0 ){
1582 zPrevSql
= (p
->zSql
==zPrevSql
? 0 : p
->zSql
);
1583 rc
= dbPrepareAndBind(p
->pDb
, p
->zSql
, &p
->zSql
, &p
->pPreStmt
);
1584 if( rc
!=TCL_OK
) return rc
;
1587 SqliteDb
*pDb
= p
->pDb
;
1588 SqlPreparedStmt
*pPreStmt
= p
->pPreStmt
;
1589 sqlite3_stmt
*pStmt
= pPreStmt
->pStmt
;
1591 rcs
= sqlite3_step(pStmt
);
1592 if( rcs
==SQLITE_ROW
){
1596 dbEvalRowInfo(p
, 0, 0);
1598 rcs
= sqlite3_reset(pStmt
);
1600 pDb
->nStep
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_FULLSCAN_STEP
,1);
1601 pDb
->nSort
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_SORT
,1);
1602 pDb
->nIndex
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_AUTOINDEX
,1);
1603 pDb
->nVMStep
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_VM_STEP
,1);
1604 dbReleaseColumnNames(p
);
1607 if( rcs
!=SQLITE_OK
){
1608 /* If a run-time error occurs, report the error and stop reading
1610 dbReleaseStmt(pDb
, pPreStmt
, 1);
1612 if( p
->pDb
->bLegacyPrepare
&& rcs
==SQLITE_SCHEMA
&& zPrevSql
){
1613 /* If the runtime error was an SQLITE_SCHEMA, and the database
1614 ** handle is configured to use the legacy sqlite3_prepare()
1615 ** interface, retry prepare()/step() on the same SQL statement.
1616 ** This only happens once. If there is a second SQLITE_SCHEMA
1617 ** error, the error will be returned to the caller. */
1622 Tcl_SetObjResult(pDb
->interp
,
1623 Tcl_NewStringObj(sqlite3_errmsg(pDb
->db
), -1));
1626 dbReleaseStmt(pDb
, pPreStmt
, 0);
1636 ** Free all resources currently held by the DbEvalContext structure passed
1637 ** as the first argument. There should be exactly one call to this function
1638 ** for each call to dbEvalInit().
1640 static void dbEvalFinalize(DbEvalContext
*p
){
1642 sqlite3_reset(p
->pPreStmt
->pStmt
);
1643 dbReleaseStmt(p
->pDb
, p
->pPreStmt
, 0);
1647 Tcl_DecrRefCount(p
->pArray
);
1650 Tcl_DecrRefCount(p
->pSql
);
1651 dbReleaseColumnNames(p
);
1655 ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1656 ** the value for the iCol'th column of the row currently pointed to by
1657 ** the DbEvalContext structure passed as the first argument.
1659 static Tcl_Obj
*dbEvalColumnValue(DbEvalContext
*p
, int iCol
){
1660 sqlite3_stmt
*pStmt
= p
->pPreStmt
->pStmt
;
1661 switch( sqlite3_column_type(pStmt
, iCol
) ){
1663 int bytes
= sqlite3_column_bytes(pStmt
, iCol
);
1664 const char *zBlob
= sqlite3_column_blob(pStmt
, iCol
);
1665 if( !zBlob
) bytes
= 0;
1666 return Tcl_NewByteArrayObj((u8
*)zBlob
, bytes
);
1668 case SQLITE_INTEGER
: {
1669 sqlite_int64 v
= sqlite3_column_int64(pStmt
, iCol
);
1670 if( v
>=-2147483647 && v
<=2147483647 ){
1671 return Tcl_NewIntObj((int)v
);
1673 return Tcl_NewWideIntObj(v
);
1676 case SQLITE_FLOAT
: {
1677 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt
, iCol
));
1680 return Tcl_NewStringObj(p
->pDb
->zNull
, -1);
1684 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt
, iCol
), -1);
1688 ** If using Tcl version 8.6 or greater, use the NR functions to avoid
1689 ** recursive evalution of scripts by the [db eval] and [db trans]
1690 ** commands. Even if the headers used while compiling the extension
1691 ** are 8.6 or newer, the code still tests the Tcl version at runtime.
1692 ** This allows stubs-enabled builds to be used with older Tcl libraries.
1694 #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
1695 # define SQLITE_TCL_NRE 1
1696 static int DbUseNre(void){
1698 Tcl_GetVersion(&major
, &minor
, 0, 0);
1699 return( (major
==8 && minor
>=6) || major
>8 );
1703 ** Compiling using headers earlier than 8.6. In this case NR cannot be
1704 ** used, so DbUseNre() to always return zero. Add #defines for the other
1705 ** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1706 ** even though the only invocations of them are within conditional blocks
1709 ** if( DbUseNre() ) { ... }
1711 # define SQLITE_TCL_NRE 0
1712 # define DbUseNre() 0
1713 # define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
1714 # define Tcl_NREvalObj(a,b,c) 0
1715 # define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
1719 ** This function is part of the implementation of the command:
1721 ** $db eval SQL ?ARRAYNAME? SCRIPT
1723 static int SQLITE_TCLAPI
DbEvalNextCmd(
1724 ClientData data
[], /* data[0] is the (DbEvalContext*) */
1725 Tcl_Interp
*interp
, /* Tcl interpreter */
1726 int result
/* Result so far */
1728 int rc
= result
; /* Return code */
1730 /* The first element of the data[] array is a pointer to a DbEvalContext
1731 ** structure allocated using Tcl_Alloc(). The second element of data[]
1732 ** is a pointer to a Tcl_Obj containing the script to run for each row
1733 ** returned by the queries encapsulated in data[0]. */
1734 DbEvalContext
*p
= (DbEvalContext
*)data
[0];
1735 Tcl_Obj
*pScript
= (Tcl_Obj
*)data
[1];
1736 Tcl_Obj
*pArray
= p
->pArray
;
1738 while( (rc
==TCL_OK
|| rc
==TCL_CONTINUE
) && TCL_OK
==(rc
= dbEvalStep(p
)) ){
1741 Tcl_Obj
**apColName
;
1742 dbEvalRowInfo(p
, &nCol
, &apColName
);
1743 for(i
=0; i
<nCol
; i
++){
1745 Tcl_ObjSetVar2(interp
, apColName
[i
], 0, dbEvalColumnValue(p
,i
), 0);
1746 }else if( (p
->evalFlags
& SQLITE_EVAL_WITHOUTNULLS
)!=0
1747 && sqlite3_column_type(p
->pPreStmt
->pStmt
, i
)==SQLITE_NULL
1749 Tcl_UnsetVar2(interp
, Tcl_GetString(pArray
),
1750 Tcl_GetString(apColName
[i
]), 0);
1752 Tcl_ObjSetVar2(interp
, pArray
, apColName
[i
], dbEvalColumnValue(p
,i
), 0);
1756 /* The required interpreter variables are now populated with the data
1757 ** from the current row. If using NRE, schedule callbacks to evaluate
1758 ** script pScript, then to invoke this function again to fetch the next
1759 ** row (or clean up if there is no next row or the script throws an
1760 ** exception). After scheduling the callbacks, return control to the
1763 ** If not using NRE, evaluate pScript directly and continue with the
1764 ** next iteration of this while(...) loop. */
1766 Tcl_NRAddCallback(interp
, DbEvalNextCmd
, (void*)p
, (void*)pScript
, 0, 0);
1767 return Tcl_NREvalObj(interp
, pScript
, 0);
1769 rc
= Tcl_EvalObjEx(interp
, pScript
, 0);
1773 Tcl_DecrRefCount(pScript
);
1775 Tcl_Free((char *)p
);
1777 if( rc
==TCL_OK
|| rc
==TCL_BREAK
){
1778 Tcl_ResetResult(interp
);
1785 ** This function is used by the implementations of the following database
1786 ** handle sub-commands:
1788 ** $db update_hook ?SCRIPT?
1789 ** $db wal_hook ?SCRIPT?
1790 ** $db commit_hook ?SCRIPT?
1791 ** $db preupdate hook ?SCRIPT?
1793 static void DbHookCmd(
1794 Tcl_Interp
*interp
, /* Tcl interpreter */
1795 SqliteDb
*pDb
, /* Database handle */
1796 Tcl_Obj
*pArg
, /* SCRIPT argument (or NULL) */
1797 Tcl_Obj
**ppHook
/* Pointer to member of SqliteDb */
1799 sqlite3
*db
= pDb
->db
;
1802 Tcl_SetObjResult(interp
, *ppHook
);
1804 Tcl_DecrRefCount(*ppHook
);
1809 assert( !(*ppHook
) );
1810 if( Tcl_GetCharLength(pArg
)>0 ){
1812 Tcl_IncrRefCount(*ppHook
);
1816 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1817 sqlite3_preupdate_hook(db
, (pDb
->pPreUpdateHook
?DbPreUpdateHandler
:0), pDb
);
1819 sqlite3_update_hook(db
, (pDb
->pUpdateHook
?DbUpdateHandler
:0), pDb
);
1820 sqlite3_rollback_hook(db
, (pDb
->pRollbackHook
?DbRollbackHandler
:0), pDb
);
1821 sqlite3_wal_hook(db
, (pDb
->pWalHook
?DbWalHandler
:0), pDb
);
1825 ** The "sqlite" command below creates a new Tcl command for each
1826 ** connection it opens to an SQLite database. This routine is invoked
1827 ** whenever one of those connection-specific commands is executed
1828 ** in Tcl. For example, if you run Tcl code like this:
1830 ** sqlite3 db1 "my_database"
1833 ** The first command opens a connection to the "my_database" database
1834 ** and calls that connection "db1". The second command causes this
1835 ** subroutine to be invoked.
1837 static int SQLITE_TCLAPI
DbObjCmd(
1843 SqliteDb
*pDb
= (SqliteDb
*)cd
;
1846 static const char *DB_strs
[] = {
1847 "authorizer", "backup", "busy",
1848 "cache", "changes", "close",
1849 "collate", "collation_needed", "commit_hook",
1850 "complete", "copy", "enable_load_extension",
1851 "errorcode", "eval", "exists",
1852 "function", "incrblob", "interrupt",
1853 "last_insert_rowid", "nullvalue", "onecolumn",
1854 "preupdate", "profile", "progress",
1855 "rekey", "restore", "rollback_hook",
1856 "status", "timeout", "total_changes",
1857 "trace", "trace_v2", "transaction",
1858 "unlock_notify", "update_hook", "version",
1863 DB_AUTHORIZER
, DB_BACKUP
, DB_BUSY
,
1864 DB_CACHE
, DB_CHANGES
, DB_CLOSE
,
1865 DB_COLLATE
, DB_COLLATION_NEEDED
, DB_COMMIT_HOOK
,
1866 DB_COMPLETE
, DB_COPY
, DB_ENABLE_LOAD_EXTENSION
,
1867 DB_ERRORCODE
, DB_EVAL
, DB_EXISTS
,
1868 DB_FUNCTION
, DB_INCRBLOB
, DB_INTERRUPT
,
1869 DB_LAST_INSERT_ROWID
, DB_NULLVALUE
, DB_ONECOLUMN
,
1870 DB_PREUPDATE
, DB_PROFILE
, DB_PROGRESS
,
1871 DB_REKEY
, DB_RESTORE
, DB_ROLLBACK_HOOK
,
1872 DB_STATUS
, DB_TIMEOUT
, DB_TOTAL_CHANGES
,
1873 DB_TRACE
, DB_TRACE_V2
, DB_TRANSACTION
,
1874 DB_UNLOCK_NOTIFY
, DB_UPDATE_HOOK
, DB_VERSION
,
1877 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
1880 Tcl_WrongNumArgs(interp
, 1, objv
, "SUBCOMMAND ...");
1883 if( Tcl_GetIndexFromObj(interp
, objv
[1], DB_strs
, "option", 0, &choice
) ){
1887 switch( (enum DB_enum
)choice
){
1889 /* $db authorizer ?CALLBACK?
1891 ** Invoke the given callback to authorize each SQL operation as it is
1892 ** compiled. 5 arguments are appended to the callback before it is
1895 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1896 ** (2) First descriptive name (depends on authorization type)
1897 ** (3) Second descriptive name
1898 ** (4) Name of the database (ex: "main", "temp")
1899 ** (5) Name of trigger that is doing the access
1901 ** The callback should return on of the following strings: SQLITE_OK,
1902 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1904 ** If this method is invoked with no arguments, the current authorization
1905 ** callback string is returned.
1907 case DB_AUTHORIZER
: {
1908 #ifdef SQLITE_OMIT_AUTHORIZATION
1909 Tcl_AppendResult(interp
, "authorization not available in this build",
1914 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
1916 }else if( objc
==2 ){
1918 Tcl_AppendResult(interp
, pDb
->zAuth
, (char*)0);
1924 Tcl_Free(pDb
->zAuth
);
1926 zAuth
= Tcl_GetStringFromObj(objv
[2], &len
);
1927 if( zAuth
&& len
>0 ){
1928 pDb
->zAuth
= Tcl_Alloc( len
+ 1 );
1929 memcpy(pDb
->zAuth
, zAuth
, len
+1);
1934 typedef int (*sqlite3_auth_cb
)(
1935 void*,int,const char*,const char*,
1936 const char*,const char*);
1937 pDb
->interp
= interp
;
1938 sqlite3_set_authorizer(pDb
->db
,(sqlite3_auth_cb
)auth_callback
,pDb
);
1940 sqlite3_set_authorizer(pDb
->db
, 0, 0);
1947 /* $db backup ?DATABASE? FILENAME
1949 ** Open or create a database file named FILENAME. Transfer the
1950 ** content of local database DATABASE (default: "main") into the
1951 ** FILENAME database.
1954 const char *zDestFile
;
1957 sqlite3_backup
*pBackup
;
1961 zDestFile
= Tcl_GetString(objv
[2]);
1962 }else if( objc
==4 ){
1963 zSrcDb
= Tcl_GetString(objv
[2]);
1964 zDestFile
= Tcl_GetString(objv
[3]);
1966 Tcl_WrongNumArgs(interp
, 2, objv
, "?DATABASE? FILENAME");
1969 rc
= sqlite3_open_v2(zDestFile
, &pDest
,
1970 SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
| pDb
->openFlags
, 0);
1971 if( rc
!=SQLITE_OK
){
1972 Tcl_AppendResult(interp
, "cannot open target database: ",
1973 sqlite3_errmsg(pDest
), (char*)0);
1974 sqlite3_close(pDest
);
1977 pBackup
= sqlite3_backup_init(pDest
, "main", pDb
->db
, zSrcDb
);
1979 Tcl_AppendResult(interp
, "backup failed: ",
1980 sqlite3_errmsg(pDest
), (char*)0);
1981 sqlite3_close(pDest
);
1984 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
){}
1985 sqlite3_backup_finish(pBackup
);
1986 if( rc
==SQLITE_DONE
){
1989 Tcl_AppendResult(interp
, "backup failed: ",
1990 sqlite3_errmsg(pDest
), (char*)0);
1993 sqlite3_close(pDest
);
1997 /* $db busy ?CALLBACK?
1999 ** Invoke the given callback if an SQL statement attempts to open
2000 ** a locked database file.
2004 Tcl_WrongNumArgs(interp
, 2, objv
, "CALLBACK");
2006 }else if( objc
==2 ){
2008 Tcl_AppendResult(interp
, pDb
->zBusy
, (char*)0);
2014 Tcl_Free(pDb
->zBusy
);
2016 zBusy
= Tcl_GetStringFromObj(objv
[2], &len
);
2017 if( zBusy
&& len
>0 ){
2018 pDb
->zBusy
= Tcl_Alloc( len
+ 1 );
2019 memcpy(pDb
->zBusy
, zBusy
, len
+1);
2024 pDb
->interp
= interp
;
2025 sqlite3_busy_handler(pDb
->db
, DbBusyHandler
, pDb
);
2027 sqlite3_busy_handler(pDb
->db
, 0, 0);
2036 ** Flush the prepared statement cache, or set the maximum number of
2037 ** cached statements.
2044 Tcl_WrongNumArgs(interp
, 1, objv
, "cache option ?arg?");
2047 subCmd
= Tcl_GetStringFromObj( objv
[2], 0 );
2048 if( *subCmd
=='f' && strcmp(subCmd
,"flush")==0 ){
2050 Tcl_WrongNumArgs(interp
, 2, objv
, "flush");
2053 flushStmtCache( pDb
);
2055 }else if( *subCmd
=='s' && strcmp(subCmd
,"size")==0 ){
2057 Tcl_WrongNumArgs(interp
, 2, objv
, "size n");
2060 if( TCL_ERROR
==Tcl_GetIntFromObj(interp
, objv
[3], &n
) ){
2061 Tcl_AppendResult( interp
, "cannot convert \"",
2062 Tcl_GetStringFromObj(objv
[3],0), "\" to integer", (char*)0);
2066 flushStmtCache( pDb
);
2068 }else if( n
>MAX_PREPARED_STMTS
){
2069 n
= MAX_PREPARED_STMTS
;
2075 Tcl_AppendResult( interp
, "bad option \"",
2076 Tcl_GetStringFromObj(objv
[2],0), "\": must be flush or size",
2085 ** Return the number of rows that were modified, inserted, or deleted by
2086 ** the most recent INSERT, UPDATE or DELETE statement, not including
2087 ** any changes made by trigger programs.
2092 Tcl_WrongNumArgs(interp
, 2, objv
, "");
2095 pResult
= Tcl_GetObjResult(interp
);
2096 Tcl_SetIntObj(pResult
, sqlite3_changes(pDb
->db
));
2102 ** Shutdown the database
2105 Tcl_DeleteCommand(interp
, Tcl_GetStringFromObj(objv
[0], 0));
2110 ** $db collate NAME SCRIPT
2112 ** Create a new SQL collation function called NAME. Whenever
2113 ** that function is called, invoke SCRIPT to evaluate the function.
2116 SqlCollate
*pCollate
;
2121 Tcl_WrongNumArgs(interp
, 2, objv
, "NAME SCRIPT");
2124 zName
= Tcl_GetStringFromObj(objv
[2], 0);
2125 zScript
= Tcl_GetStringFromObj(objv
[3], &nScript
);
2126 pCollate
= (SqlCollate
*)Tcl_Alloc( sizeof(*pCollate
) + nScript
+ 1 );
2127 if( pCollate
==0 ) return TCL_ERROR
;
2128 pCollate
->interp
= interp
;
2129 pCollate
->pNext
= pDb
->pCollate
;
2130 pCollate
->zScript
= (char*)&pCollate
[1];
2131 pDb
->pCollate
= pCollate
;
2132 memcpy(pCollate
->zScript
, zScript
, nScript
+1);
2133 if( sqlite3_create_collation(pDb
->db
, zName
, SQLITE_UTF8
,
2134 pCollate
, tclSqlCollate
) ){
2135 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(pDb
->db
), TCL_VOLATILE
);
2142 ** $db collation_needed SCRIPT
2144 ** Create a new SQL collation function called NAME. Whenever
2145 ** that function is called, invoke SCRIPT to evaluate the function.
2147 case DB_COLLATION_NEEDED
: {
2149 Tcl_WrongNumArgs(interp
, 2, objv
, "SCRIPT");
2152 if( pDb
->pCollateNeeded
){
2153 Tcl_DecrRefCount(pDb
->pCollateNeeded
);
2155 pDb
->pCollateNeeded
= Tcl_DuplicateObj(objv
[2]);
2156 Tcl_IncrRefCount(pDb
->pCollateNeeded
);
2157 sqlite3_collation_needed(pDb
->db
, pDb
, tclCollateNeeded
);
2161 /* $db commit_hook ?CALLBACK?
2163 ** Invoke the given callback just before committing every SQL transaction.
2164 ** If the callback throws an exception or returns non-zero, then the
2165 ** transaction is aborted. If CALLBACK is an empty string, the callback
2168 case DB_COMMIT_HOOK
: {
2170 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
2172 }else if( objc
==2 ){
2174 Tcl_AppendResult(interp
, pDb
->zCommit
, (char*)0);
2177 const char *zCommit
;
2180 Tcl_Free(pDb
->zCommit
);
2182 zCommit
= Tcl_GetStringFromObj(objv
[2], &len
);
2183 if( zCommit
&& len
>0 ){
2184 pDb
->zCommit
= Tcl_Alloc( len
+ 1 );
2185 memcpy(pDb
->zCommit
, zCommit
, len
+1);
2190 pDb
->interp
= interp
;
2191 sqlite3_commit_hook(pDb
->db
, DbCommitHandler
, pDb
);
2193 sqlite3_commit_hook(pDb
->db
, 0, 0);
2201 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2202 ** additional lines of input are needed. This is similar to the
2203 ** built-in "info complete" command of Tcl.
2206 #ifndef SQLITE_OMIT_COMPLETE
2210 Tcl_WrongNumArgs(interp
, 2, objv
, "SQL");
2213 isComplete
= sqlite3_complete( Tcl_GetStringFromObj(objv
[2], 0) );
2214 pResult
= Tcl_GetObjResult(interp
);
2215 Tcl_SetBooleanObj(pResult
, isComplete
);
2220 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2222 ** Copy data into table from filename, optionally using SEPARATOR
2223 ** as column separators. If a column contains a null string, or the
2224 ** value of NULLINDICATOR, a NULL is inserted for the column.
2225 ** conflict-algorithm is one of the sqlite conflict algorithms:
2226 ** rollback, abort, fail, ignore, replace
2227 ** On success, return the number of lines processed, not necessarily same
2228 ** as 'db changes' due to conflict-algorithm selected.
2230 ** This code is basically an implementation/enhancement of
2231 ** the sqlite3 shell.c ".import" command.
2233 ** This command usage is equivalent to the sqlite2.x COPY statement,
2234 ** which imports file data into a table using the PostgreSQL COPY file format:
2235 ** $db copy $conflit_algo $table_name $filename \t \\N
2238 char *zTable
; /* Insert data into this table */
2239 char *zFile
; /* The file from which to extract data */
2240 char *zConflict
; /* The conflict algorithm to use */
2241 sqlite3_stmt
*pStmt
; /* A statement */
2242 int nCol
; /* Number of columns in the table */
2243 int nByte
; /* Number of bytes in an SQL string */
2244 int i
, j
; /* Loop counters */
2245 int nSep
; /* Number of bytes in zSep[] */
2246 int nNull
; /* Number of bytes in zNull[] */
2247 char *zSql
; /* An SQL statement */
2248 char *zLine
; /* A single line of input from the file */
2249 char **azCol
; /* zLine[] broken up into columns */
2250 const char *zCommit
; /* How to commit changes */
2251 FILE *in
; /* The input file */
2252 int lineno
= 0; /* Line number of input file */
2253 char zLineNum
[80]; /* Line number print buffer */
2254 Tcl_Obj
*pResult
; /* interp result */
2258 if( objc
<5 || objc
>7 ){
2259 Tcl_WrongNumArgs(interp
, 2, objv
,
2260 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2264 zSep
= Tcl_GetStringFromObj(objv
[5], 0);
2269 zNull
= Tcl_GetStringFromObj(objv
[6], 0);
2273 zConflict
= Tcl_GetStringFromObj(objv
[2], 0);
2274 zTable
= Tcl_GetStringFromObj(objv
[3], 0);
2275 zFile
= Tcl_GetStringFromObj(objv
[4], 0);
2276 nSep
= strlen30(zSep
);
2277 nNull
= strlen30(zNull
);
2279 Tcl_AppendResult(interp
,"Error: non-null separator required for copy",
2283 if(strcmp(zConflict
, "rollback") != 0 &&
2284 strcmp(zConflict
, "abort" ) != 0 &&
2285 strcmp(zConflict
, "fail" ) != 0 &&
2286 strcmp(zConflict
, "ignore" ) != 0 &&
2287 strcmp(zConflict
, "replace" ) != 0 ) {
2288 Tcl_AppendResult(interp
, "Error: \"", zConflict
,
2289 "\", conflict-algorithm must be one of: rollback, "
2290 "abort, fail, ignore, or replace", (char*)0);
2293 zSql
= sqlite3_mprintf("SELECT * FROM '%q'", zTable
);
2295 Tcl_AppendResult(interp
, "Error: no such table: ", zTable
, (char*)0);
2298 nByte
= strlen30(zSql
);
2299 rc
= sqlite3_prepare(pDb
->db
, zSql
, -1, &pStmt
, 0);
2302 Tcl_AppendResult(interp
, "Error: ", sqlite3_errmsg(pDb
->db
), (char*)0);
2305 nCol
= sqlite3_column_count(pStmt
);
2307 sqlite3_finalize(pStmt
);
2311 zSql
= malloc( nByte
+ 50 + nCol
*2 );
2313 Tcl_AppendResult(interp
, "Error: can't malloc()", (char*)0);
2316 sqlite3_snprintf(nByte
+50, zSql
, "INSERT OR %q INTO '%q' VALUES(?",
2319 for(i
=1; i
<nCol
; i
++){
2325 rc
= sqlite3_prepare(pDb
->db
, zSql
, -1, &pStmt
, 0);
2328 Tcl_AppendResult(interp
, "Error: ", sqlite3_errmsg(pDb
->db
), (char*)0);
2329 sqlite3_finalize(pStmt
);
2332 in
= fopen(zFile
, "rb");
2334 Tcl_AppendResult(interp
, "Error: cannot open file: ", zFile
, (char*)0);
2335 sqlite3_finalize(pStmt
);
2338 azCol
= malloc( sizeof(azCol
[0])*(nCol
+1) );
2340 Tcl_AppendResult(interp
, "Error: can't malloc()", (char*)0);
2344 (void)sqlite3_exec(pDb
->db
, "BEGIN", 0, 0, 0);
2346 while( (zLine
= local_getline(0, in
))!=0 ){
2350 for(i
=0, z
=zLine
; *z
; z
++){
2351 if( *z
==zSep
[0] && strncmp(z
, zSep
, nSep
)==0 ){
2355 azCol
[i
] = &z
[nSep
];
2362 int nErr
= strlen30(zFile
) + 200;
2363 zErr
= malloc(nErr
);
2365 sqlite3_snprintf(nErr
, zErr
,
2366 "Error: %s line %d: expected %d columns of data but found %d",
2367 zFile
, lineno
, nCol
, i
+1);
2368 Tcl_AppendResult(interp
, zErr
, (char*)0);
2371 zCommit
= "ROLLBACK";
2374 for(i
=0; i
<nCol
; i
++){
2375 /* check for null data, if so, bind as null */
2376 if( (nNull
>0 && strcmp(azCol
[i
], zNull
)==0)
2377 || strlen30(azCol
[i
])==0
2379 sqlite3_bind_null(pStmt
, i
+1);
2381 sqlite3_bind_text(pStmt
, i
+1, azCol
[i
], -1, SQLITE_STATIC
);
2384 sqlite3_step(pStmt
);
2385 rc
= sqlite3_reset(pStmt
);
2387 if( rc
!=SQLITE_OK
){
2388 Tcl_AppendResult(interp
,"Error: ", sqlite3_errmsg(pDb
->db
), (char*)0);
2389 zCommit
= "ROLLBACK";
2395 sqlite3_finalize(pStmt
);
2396 (void)sqlite3_exec(pDb
->db
, zCommit
, 0, 0, 0);
2398 if( zCommit
[0] == 'C' ){
2399 /* success, set result as number of lines processed */
2400 pResult
= Tcl_GetObjResult(interp
);
2401 Tcl_SetIntObj(pResult
, lineno
);
2404 /* failure, append lineno where failed */
2405 sqlite3_snprintf(sizeof(zLineNum
), zLineNum
,"%d",lineno
);
2406 Tcl_AppendResult(interp
,", failed while processing line: ",zLineNum
,
2414 ** $db enable_load_extension BOOLEAN
2416 ** Turn the extension loading feature on or off. It if off by
2419 case DB_ENABLE_LOAD_EXTENSION
: {
2420 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2423 Tcl_WrongNumArgs(interp
, 2, objv
, "BOOLEAN");
2426 if( Tcl_GetBooleanFromObj(interp
, objv
[2], &onoff
) ){
2429 sqlite3_enable_load_extension(pDb
->db
, onoff
);
2432 Tcl_AppendResult(interp
, "extension loading is turned off at compile-time",
2441 ** Return the numeric error code that was returned by the most recent
2442 ** call to sqlite3_exec().
2444 case DB_ERRORCODE
: {
2445 Tcl_SetObjResult(interp
, Tcl_NewIntObj(sqlite3_errcode(pDb
->db
)));
2451 ** $db onecolumn $sql
2453 ** The onecolumn method is the equivalent of:
2454 ** lindex [$db eval $sql] 0
2457 case DB_ONECOLUMN
: {
2458 Tcl_Obj
*pResult
= 0;
2459 DbEvalContext sEval
;
2461 Tcl_WrongNumArgs(interp
, 2, objv
, "SQL");
2465 dbEvalInit(&sEval
, pDb
, objv
[2], 0, 0);
2466 rc
= dbEvalStep(&sEval
);
2467 if( choice
==DB_ONECOLUMN
){
2469 pResult
= dbEvalColumnValue(&sEval
, 0);
2470 }else if( rc
==TCL_BREAK
){
2471 Tcl_ResetResult(interp
);
2473 }else if( rc
==TCL_BREAK
|| rc
==TCL_OK
){
2474 pResult
= Tcl_NewBooleanObj(rc
==TCL_OK
);
2476 dbEvalFinalize(&sEval
);
2477 if( pResult
) Tcl_SetObjResult(interp
, pResult
);
2479 if( rc
==TCL_BREAK
){
2486 ** $db eval ?options? $sql ?array? ?{ ...code... }?
2488 ** The SQL statement in $sql is evaluated. For each row, the values are
2489 ** placed in elements of the array named "array" and ...code... is executed.
2490 ** If "array" and "code" are omitted, then no callback is every invoked.
2491 ** If "array" is an empty string, then the values are placed in variables
2492 ** that have the same name as the fields extracted by the query.
2497 while( objc
>3 && (zOpt
= Tcl_GetString(objv
[2]))!=0 && zOpt
[0]=='-' ){
2498 if( strcmp(zOpt
, "-withoutnulls")==0 ){
2499 evalFlags
|= SQLITE_EVAL_WITHOUTNULLS
;
2502 Tcl_AppendResult(interp
, "unknown option: \"", zOpt
, "\"", (void*)0);
2508 if( objc
<3 || objc
>5 ){
2509 Tcl_WrongNumArgs(interp
, 2, objv
,
2510 "?OPTIONS? SQL ?ARRAY-NAME? ?SCRIPT?");
2515 DbEvalContext sEval
;
2516 Tcl_Obj
*pRet
= Tcl_NewObj();
2517 Tcl_IncrRefCount(pRet
);
2518 dbEvalInit(&sEval
, pDb
, objv
[2], 0, 0);
2519 while( TCL_OK
==(rc
= dbEvalStep(&sEval
)) ){
2522 dbEvalRowInfo(&sEval
, &nCol
, 0);
2523 for(i
=0; i
<nCol
; i
++){
2524 Tcl_ListObjAppendElement(interp
, pRet
, dbEvalColumnValue(&sEval
, i
));
2527 dbEvalFinalize(&sEval
);
2528 if( rc
==TCL_BREAK
){
2529 Tcl_SetObjResult(interp
, pRet
);
2532 Tcl_DecrRefCount(pRet
);
2536 Tcl_Obj
*pArray
= 0;
2539 if( objc
>=5 && *(char *)Tcl_GetString(objv
[3]) ){
2542 pScript
= objv
[objc
-1];
2543 Tcl_IncrRefCount(pScript
);
2545 p
= (DbEvalContext
*)Tcl_Alloc(sizeof(DbEvalContext
));
2546 dbEvalInit(p
, pDb
, objv
[2], pArray
, evalFlags
);
2549 cd2
[1] = (void *)pScript
;
2550 rc
= DbEvalNextCmd(cd2
, interp
, TCL_OK
);
2556 ** $db function NAME [-argcount N] [-deterministic] SCRIPT
2558 ** Create a new SQL function called NAME. Whenever that function is
2559 ** called, invoke SCRIPT to evaluate the function.
2562 int flags
= SQLITE_UTF8
;
2569 Tcl_WrongNumArgs(interp
, 2, objv
, "NAME ?SWITCHES? SCRIPT");
2572 for(i
=3; i
<(objc
-1); i
++){
2573 const char *z
= Tcl_GetString(objv
[i
]);
2574 int n
= strlen30(z
);
2575 if( n
>2 && strncmp(z
, "-argcount",n
)==0 ){
2577 Tcl_AppendResult(interp
, "option requires an argument: ", z
,(char*)0);
2580 if( Tcl_GetIntFromObj(interp
, objv
[i
+1], &nArg
) ) return TCL_ERROR
;
2582 Tcl_AppendResult(interp
, "number of arguments must be non-negative",
2588 if( n
>2 && strncmp(z
, "-deterministic",n
)==0 ){
2589 flags
|= SQLITE_DETERMINISTIC
;
2591 Tcl_AppendResult(interp
, "bad option \"", z
,
2592 "\": must be -argcount or -deterministic", (char*)0
2598 pScript
= objv
[objc
-1];
2599 zName
= Tcl_GetStringFromObj(objv
[2], 0);
2600 pFunc
= findSqlFunc(pDb
, zName
);
2601 if( pFunc
==0 ) return TCL_ERROR
;
2602 if( pFunc
->pScript
){
2603 Tcl_DecrRefCount(pFunc
->pScript
);
2605 pFunc
->pScript
= pScript
;
2606 Tcl_IncrRefCount(pScript
);
2607 pFunc
->useEvalObjv
= safeToUseEvalObjv(interp
, pScript
);
2608 rc
= sqlite3_create_function(pDb
->db
, zName
, nArg
, flags
,
2609 pFunc
, tclSqlFunc
, 0, 0);
2610 if( rc
!=SQLITE_OK
){
2612 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(pDb
->db
), TCL_VOLATILE
);
2618 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
2621 #ifdef SQLITE_OMIT_INCRBLOB
2622 Tcl_AppendResult(interp
, "incrblob not available in this build", (char*)0);
2626 const char *zDb
= "main";
2628 const char *zColumn
;
2631 /* Check for the -readonly option */
2632 if( objc
>3 && strcmp(Tcl_GetString(objv
[2]), "-readonly")==0 ){
2636 if( objc
!=(5+isReadonly
) && objc
!=(6+isReadonly
) ){
2637 Tcl_WrongNumArgs(interp
, 2, objv
, "?-readonly? ?DB? TABLE COLUMN ROWID");
2641 if( objc
==(6+isReadonly
) ){
2642 zDb
= Tcl_GetString(objv
[2]);
2644 zTable
= Tcl_GetString(objv
[objc
-3]);
2645 zColumn
= Tcl_GetString(objv
[objc
-2]);
2646 rc
= Tcl_GetWideIntFromObj(interp
, objv
[objc
-1], &iRow
);
2649 rc
= createIncrblobChannel(
2650 interp
, pDb
, zDb
, zTable
, zColumn
, (sqlite3_int64
)iRow
, isReadonly
2660 ** Interrupt the execution of the inner-most SQL interpreter. This
2661 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2663 case DB_INTERRUPT
: {
2664 sqlite3_interrupt(pDb
->db
);
2669 ** $db nullvalue ?STRING?
2671 ** Change text used when a NULL comes back from the database. If ?STRING?
2672 ** is not present, then the current string used for NULL is returned.
2673 ** If STRING is present, then STRING is returned.
2676 case DB_NULLVALUE
: {
2677 if( objc
!=2 && objc
!=3 ){
2678 Tcl_WrongNumArgs(interp
, 2, objv
, "NULLVALUE");
2683 char *zNull
= Tcl_GetStringFromObj(objv
[2], &len
);
2685 Tcl_Free(pDb
->zNull
);
2687 if( zNull
&& len
>0 ){
2688 pDb
->zNull
= Tcl_Alloc( len
+ 1 );
2689 memcpy(pDb
->zNull
, zNull
, len
);
2690 pDb
->zNull
[len
] = '\0';
2695 Tcl_SetObjResult(interp
, Tcl_NewStringObj(pDb
->zNull
, -1));
2700 ** $db last_insert_rowid
2702 ** Return an integer which is the ROWID for the most recent insert.
2704 case DB_LAST_INSERT_ROWID
: {
2708 Tcl_WrongNumArgs(interp
, 2, objv
, "");
2711 rowid
= sqlite3_last_insert_rowid(pDb
->db
);
2712 pResult
= Tcl_GetObjResult(interp
);
2713 Tcl_SetWideIntObj(pResult
, rowid
);
2718 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
2721 /* $db progress ?N CALLBACK?
2723 ** Invoke the given callback every N virtual machine opcodes while executing
2728 if( pDb
->zProgress
){
2729 Tcl_AppendResult(interp
, pDb
->zProgress
, (char*)0);
2731 }else if( objc
==4 ){
2735 if( TCL_OK
!=Tcl_GetIntFromObj(interp
, objv
[2], &N
) ){
2738 if( pDb
->zProgress
){
2739 Tcl_Free(pDb
->zProgress
);
2741 zProgress
= Tcl_GetStringFromObj(objv
[3], &len
);
2742 if( zProgress
&& len
>0 ){
2743 pDb
->zProgress
= Tcl_Alloc( len
+ 1 );
2744 memcpy(pDb
->zProgress
, zProgress
, len
+1);
2748 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2749 if( pDb
->zProgress
){
2750 pDb
->interp
= interp
;
2751 sqlite3_progress_handler(pDb
->db
, N
, DbProgressHandler
, pDb
);
2753 sqlite3_progress_handler(pDb
->db
, 0, 0, 0);
2757 Tcl_WrongNumArgs(interp
, 2, objv
, "N CALLBACK");
2763 /* $db profile ?CALLBACK?
2765 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2766 ** that has run. The text of the SQL and the amount of elapse time are
2767 ** appended to CALLBACK before the script is run.
2771 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
2773 }else if( objc
==2 ){
2774 if( pDb
->zProfile
){
2775 Tcl_AppendResult(interp
, pDb
->zProfile
, (char*)0);
2780 if( pDb
->zProfile
){
2781 Tcl_Free(pDb
->zProfile
);
2783 zProfile
= Tcl_GetStringFromObj(objv
[2], &len
);
2784 if( zProfile
&& len
>0 ){
2785 pDb
->zProfile
= Tcl_Alloc( len
+ 1 );
2786 memcpy(pDb
->zProfile
, zProfile
, len
+1);
2790 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
2791 !defined(SQLITE_OMIT_DEPRECATED)
2792 if( pDb
->zProfile
){
2793 pDb
->interp
= interp
;
2794 sqlite3_profile(pDb
->db
, DbProfileHandler
, pDb
);
2796 sqlite3_profile(pDb
->db
, 0, 0);
2806 ** Change the encryption key on the currently open database.
2809 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
2814 Tcl_WrongNumArgs(interp
, 2, objv
, "KEY");
2817 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
2818 pKey
= Tcl_GetByteArrayFromObj(objv
[2], &nKey
);
2819 rc
= sqlite3_rekey(pDb
->db
, pKey
, nKey
);
2821 Tcl_AppendResult(interp
, sqlite3_errstr(rc
), (char*)0);
2828 /* $db restore ?DATABASE? FILENAME
2830 ** Open a database file named FILENAME. Transfer the content
2831 ** of FILENAME into the local database DATABASE (default: "main").
2834 const char *zSrcFile
;
2835 const char *zDestDb
;
2837 sqlite3_backup
*pBackup
;
2842 zSrcFile
= Tcl_GetString(objv
[2]);
2843 }else if( objc
==4 ){
2844 zDestDb
= Tcl_GetString(objv
[2]);
2845 zSrcFile
= Tcl_GetString(objv
[3]);
2847 Tcl_WrongNumArgs(interp
, 2, objv
, "?DATABASE? FILENAME");
2850 rc
= sqlite3_open_v2(zSrcFile
, &pSrc
,
2851 SQLITE_OPEN_READONLY
| pDb
->openFlags
, 0);
2852 if( rc
!=SQLITE_OK
){
2853 Tcl_AppendResult(interp
, "cannot open source database: ",
2854 sqlite3_errmsg(pSrc
), (char*)0);
2855 sqlite3_close(pSrc
);
2858 pBackup
= sqlite3_backup_init(pDb
->db
, zDestDb
, pSrc
, "main");
2860 Tcl_AppendResult(interp
, "restore failed: ",
2861 sqlite3_errmsg(pDb
->db
), (char*)0);
2862 sqlite3_close(pSrc
);
2865 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
2866 || rc
==SQLITE_BUSY
){
2867 if( rc
==SQLITE_BUSY
){
2868 if( nTimeout
++ >= 3 ) break;
2872 sqlite3_backup_finish(pBackup
);
2873 if( rc
==SQLITE_DONE
){
2875 }else if( rc
==SQLITE_BUSY
|| rc
==SQLITE_LOCKED
){
2876 Tcl_AppendResult(interp
, "restore failed: source database busy",
2880 Tcl_AppendResult(interp
, "restore failed: ",
2881 sqlite3_errmsg(pDb
->db
), (char*)0);
2884 sqlite3_close(pSrc
);
2889 ** $db status (step|sort|autoindex|vmstep)
2891 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2892 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2898 Tcl_WrongNumArgs(interp
, 2, objv
, "(step|sort|autoindex)");
2901 zOp
= Tcl_GetString(objv
[2]);
2902 if( strcmp(zOp
, "step")==0 ){
2904 }else if( strcmp(zOp
, "sort")==0 ){
2906 }else if( strcmp(zOp
, "autoindex")==0 ){
2908 }else if( strcmp(zOp
, "vmstep")==0 ){
2911 Tcl_AppendResult(interp
,
2912 "bad argument: should be autoindex, step, sort or vmstep",
2916 Tcl_SetObjResult(interp
, Tcl_NewIntObj(v
));
2921 ** $db timeout MILLESECONDS
2923 ** Delay for the number of milliseconds specified when a file is locked.
2928 Tcl_WrongNumArgs(interp
, 2, objv
, "MILLISECONDS");
2931 if( Tcl_GetIntFromObj(interp
, objv
[2], &ms
) ) return TCL_ERROR
;
2932 sqlite3_busy_timeout(pDb
->db
, ms
);
2937 ** $db total_changes
2939 ** Return the number of rows that were modified, inserted, or deleted
2940 ** since the database handle was created.
2942 case DB_TOTAL_CHANGES
: {
2945 Tcl_WrongNumArgs(interp
, 2, objv
, "");
2948 pResult
= Tcl_GetObjResult(interp
);
2949 Tcl_SetIntObj(pResult
, sqlite3_total_changes(pDb
->db
));
2953 /* $db trace ?CALLBACK?
2955 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2956 ** that is executed. The text of the SQL is appended to CALLBACK before
2961 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
2963 }else if( objc
==2 ){
2965 Tcl_AppendResult(interp
, pDb
->zTrace
, (char*)0);
2971 Tcl_Free(pDb
->zTrace
);
2973 zTrace
= Tcl_GetStringFromObj(objv
[2], &len
);
2974 if( zTrace
&& len
>0 ){
2975 pDb
->zTrace
= Tcl_Alloc( len
+ 1 );
2976 memcpy(pDb
->zTrace
, zTrace
, len
+1);
2980 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
2981 !defined(SQLITE_OMIT_DEPRECATED)
2983 pDb
->interp
= interp
;
2984 sqlite3_trace(pDb
->db
, DbTraceHandler
, pDb
);
2986 sqlite3_trace(pDb
->db
, 0, 0);
2993 /* $db trace_v2 ?CALLBACK? ?MASK?
2995 ** Make arrangements to invoke the CALLBACK routine for each trace event
2996 ** matching the mask that is generated. The parameters are appended to
2997 ** CALLBACK before it is executed.
3001 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK? ?MASK?");
3003 }else if( objc
==2 ){
3004 if( pDb
->zTraceV2
){
3005 Tcl_AppendResult(interp
, pDb
->zTraceV2
, (char*)0);
3010 Tcl_WideInt wMask
= 0;
3012 static const char *TTYPE_strs
[] = {
3013 "statement", "profile", "row", "close", 0
3016 TTYPE_STMT
, TTYPE_PROFILE
, TTYPE_ROW
, TTYPE_CLOSE
3019 if( TCL_OK
!=Tcl_ListObjLength(interp
, objv
[3], &len
) ){
3022 for(i
=0; i
<len
; i
++){
3025 if( TCL_OK
!=Tcl_ListObjIndex(interp
, objv
[3], i
, &pObj
) ){
3028 if( Tcl_GetIndexFromObj(interp
, pObj
, TTYPE_strs
, "trace type",
3029 0, &ttype
)!=TCL_OK
){
3031 Tcl_Obj
*pError
= Tcl_DuplicateObj(Tcl_GetObjResult(interp
));
3032 Tcl_IncrRefCount(pError
);
3033 if( TCL_OK
==Tcl_GetWideIntFromObj(interp
, pObj
, &wType
) ){
3034 Tcl_DecrRefCount(pError
);
3037 Tcl_SetObjResult(interp
, pError
);
3038 Tcl_DecrRefCount(pError
);
3042 switch( (enum TTYPE_enum
)ttype
){
3043 case TTYPE_STMT
: wMask
|= SQLITE_TRACE_STMT
; break;
3044 case TTYPE_PROFILE
: wMask
|= SQLITE_TRACE_PROFILE
; break;
3045 case TTYPE_ROW
: wMask
|= SQLITE_TRACE_ROW
; break;
3046 case TTYPE_CLOSE
: wMask
|= SQLITE_TRACE_CLOSE
; break;
3051 wMask
= SQLITE_TRACE_STMT
; /* use the "legacy" default */
3053 if( pDb
->zTraceV2
){
3054 Tcl_Free(pDb
->zTraceV2
);
3056 zTraceV2
= Tcl_GetStringFromObj(objv
[2], &len
);
3057 if( zTraceV2
&& len
>0 ){
3058 pDb
->zTraceV2
= Tcl_Alloc( len
+ 1 );
3059 memcpy(pDb
->zTraceV2
, zTraceV2
, len
+1);
3063 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3064 if( pDb
->zTraceV2
){
3065 pDb
->interp
= interp
;
3066 sqlite3_trace_v2(pDb
->db
, (unsigned)wMask
, DbTraceV2Handler
, pDb
);
3068 sqlite3_trace_v2(pDb
->db
, 0, 0, 0);
3075 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
3077 ** Start a new transaction (if we are not already in the midst of a
3078 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
3079 ** completes, either commit the transaction or roll it back if SCRIPT
3080 ** throws an exception. Or if no new transation was started, do nothing.
3081 ** pass the exception on up the stack.
3083 ** This command was inspired by Dave Thomas's talk on Ruby at the
3084 ** 2005 O'Reilly Open Source Convention (OSCON).
3086 case DB_TRANSACTION
: {
3088 const char *zBegin
= "SAVEPOINT _tcl_transaction";
3089 if( objc
!=3 && objc
!=4 ){
3090 Tcl_WrongNumArgs(interp
, 2, objv
, "[TYPE] SCRIPT");
3094 if( pDb
->nTransaction
==0 && objc
==4 ){
3095 static const char *TTYPE_strs
[] = {
3096 "deferred", "exclusive", "immediate", 0
3099 TTYPE_DEFERRED
, TTYPE_EXCLUSIVE
, TTYPE_IMMEDIATE
3102 if( Tcl_GetIndexFromObj(interp
, objv
[2], TTYPE_strs
, "transaction type",
3106 switch( (enum TTYPE_enum
)ttype
){
3107 case TTYPE_DEFERRED
: /* no-op */; break;
3108 case TTYPE_EXCLUSIVE
: zBegin
= "BEGIN EXCLUSIVE"; break;
3109 case TTYPE_IMMEDIATE
: zBegin
= "BEGIN IMMEDIATE"; break;
3112 pScript
= objv
[objc
-1];
3114 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
3116 rc
= sqlite3_exec(pDb
->db
, zBegin
, 0, 0, 0);
3118 if( rc
!=SQLITE_OK
){
3119 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
3122 pDb
->nTransaction
++;
3124 /* If using NRE, schedule a callback to invoke the script pScript, then
3125 ** a second callback to commit (or rollback) the transaction or savepoint
3126 ** opened above. If not using NRE, evaluate the script directly, then
3127 ** call function DbTransPostCmd() to commit (or rollback) the transaction
3130 Tcl_NRAddCallback(interp
, DbTransPostCmd
, cd
, 0, 0, 0);
3131 (void)Tcl_NREvalObj(interp
, pScript
, 0);
3133 rc
= DbTransPostCmd(&cd
, interp
, Tcl_EvalObjEx(interp
, pScript
, 0));
3139 ** $db unlock_notify ?script?
3141 case DB_UNLOCK_NOTIFY
: {
3142 #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
3143 Tcl_AppendResult(interp
, "unlock_notify not available in this build",
3147 if( objc
!=2 && objc
!=3 ){
3148 Tcl_WrongNumArgs(interp
, 2, objv
, "?SCRIPT?");
3151 void (*xNotify
)(void **, int) = 0;
3152 void *pNotifyArg
= 0;
3154 if( pDb
->pUnlockNotify
){
3155 Tcl_DecrRefCount(pDb
->pUnlockNotify
);
3156 pDb
->pUnlockNotify
= 0;
3160 xNotify
= DbUnlockNotify
;
3161 pNotifyArg
= (void *)pDb
;
3162 pDb
->pUnlockNotify
= objv
[2];
3163 Tcl_IncrRefCount(pDb
->pUnlockNotify
);
3166 if( sqlite3_unlock_notify(pDb
->db
, xNotify
, pNotifyArg
) ){
3167 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
3176 ** $db preupdate_hook count
3177 ** $db preupdate_hook hook ?SCRIPT?
3178 ** $db preupdate_hook new INDEX
3179 ** $db preupdate_hook old INDEX
3181 case DB_PREUPDATE
: {
3182 #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
3183 Tcl_AppendResult(interp
, "preupdate_hook was omitted at compile-time",
3187 static const char *azSub
[] = {"count", "depth", "hook", "new", "old", 0};
3188 enum DbPreupdateSubCmd
{
3189 PRE_COUNT
, PRE_DEPTH
, PRE_HOOK
, PRE_NEW
, PRE_OLD
3194 Tcl_WrongNumArgs(interp
, 2, objv
, "SUB-COMMAND ?ARGS?");
3196 if( Tcl_GetIndexFromObj(interp
, objv
[2], azSub
, "sub-command", 0, &iSub
) ){
3200 switch( (enum DbPreupdateSubCmd
)iSub
){
3202 int nCol
= sqlite3_preupdate_count(pDb
->db
);
3203 Tcl_SetObjResult(interp
, Tcl_NewIntObj(nCol
));
3209 Tcl_WrongNumArgs(interp
, 2, objv
, "hook ?SCRIPT?");
3212 DbHookCmd(interp
, pDb
, (objc
==4 ? objv
[3] : 0), &pDb
->pPreUpdateHook
);
3219 Tcl_WrongNumArgs(interp
, 3, objv
, "");
3222 pRet
= Tcl_NewIntObj(sqlite3_preupdate_depth(pDb
->db
));
3223 Tcl_SetObjResult(interp
, pRet
);
3230 sqlite3_value
*pValue
;
3232 Tcl_WrongNumArgs(interp
, 3, objv
, "INDEX");
3235 if( Tcl_GetIntFromObj(interp
, objv
[3], &iIdx
) ){
3239 if( iSub
==PRE_OLD
){
3240 rc
= sqlite3_preupdate_old(pDb
->db
, iIdx
, &pValue
);
3242 assert( iSub
==PRE_NEW
);
3243 rc
= sqlite3_preupdate_new(pDb
->db
, iIdx
, &pValue
);
3246 if( rc
==SQLITE_OK
){
3248 pObj
= Tcl_NewStringObj((char*)sqlite3_value_text(pValue
), -1);
3249 Tcl_SetObjResult(interp
, pObj
);
3251 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
3256 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
3261 ** $db wal_hook ?script?
3262 ** $db update_hook ?script?
3263 ** $db rollback_hook ?script?
3266 case DB_UPDATE_HOOK
:
3267 case DB_ROLLBACK_HOOK
: {
3268 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
3269 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3271 Tcl_Obj
**ppHook
= 0;
3272 if( choice
==DB_WAL_HOOK
) ppHook
= &pDb
->pWalHook
;
3273 if( choice
==DB_UPDATE_HOOK
) ppHook
= &pDb
->pUpdateHook
;
3274 if( choice
==DB_ROLLBACK_HOOK
) ppHook
= &pDb
->pRollbackHook
;
3276 Tcl_WrongNumArgs(interp
, 2, objv
, "?SCRIPT?");
3280 DbHookCmd(interp
, pDb
, (objc
==3 ? objv
[2] : 0), ppHook
);
3286 ** Return the version string for this database.
3289 Tcl_SetResult(interp
, (char *)sqlite3_libversion(), TCL_STATIC
);
3294 } /* End of the SWITCH statement */
3300 ** Adaptor that provides an objCmd interface to the NRE-enabled
3301 ** interface implementation.
3303 static int SQLITE_TCLAPI
DbObjCmdAdaptor(
3309 return Tcl_NRCallObjProc(interp
, DbObjCmd
, cd
, objc
, objv
);
3311 #endif /* SQLITE_TCL_NRE */
3314 ** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
3315 ** ?-create BOOLEAN? ?-nomutex BOOLEAN?
3317 ** This is the main Tcl command. When the "sqlite" Tcl command is
3318 ** invoked, this routine runs to process that command.
3320 ** The first argument, DBNAME, is an arbitrary name for a new
3321 ** database connection. This command creates a new command named
3322 ** DBNAME that is used to control that connection. The database
3323 ** connection is deleted when the DBNAME command is deleted.
3325 ** The second argument is the name of the database file.
3328 static int SQLITE_TCLAPI
DbMain(
3339 const char *zVfs
= 0;
3341 Tcl_DString translatedFilename
;
3342 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3348 /* In normal use, each TCL interpreter runs in a single thread. So
3349 ** by default, we can turn of mutexing on SQLite database connections.
3350 ** However, for testing purposes it is useful to have mutexes turned
3351 ** on. So, by default, mutexes default off. But if compiled with
3352 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3354 #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3355 flags
= SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
| SQLITE_OPEN_FULLMUTEX
;
3357 flags
= SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
| SQLITE_OPEN_NOMUTEX
;
3361 zArg
= Tcl_GetStringFromObj(objv
[1], 0);
3362 if( strcmp(zArg
,"-version")==0 ){
3363 Tcl_AppendResult(interp
,sqlite3_libversion(), (char*)0);
3366 if( strcmp(zArg
,"-sourceid")==0 ){
3367 Tcl_AppendResult(interp
,sqlite3_sourceid(), (char*)0);
3370 if( strcmp(zArg
,"-has-codec")==0 ){
3371 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3372 Tcl_AppendResult(interp
,"1",(char*)0);
3374 Tcl_AppendResult(interp
,"0",(char*)0);
3379 for(i
=3; i
+1<objc
; i
+=2){
3380 zArg
= Tcl_GetString(objv
[i
]);
3381 if( strcmp(zArg
,"-key")==0 ){
3382 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3383 pKey
= Tcl_GetByteArrayFromObj(objv
[i
+1], &nKey
);
3385 }else if( strcmp(zArg
, "-vfs")==0 ){
3386 zVfs
= Tcl_GetString(objv
[i
+1]);
3387 }else if( strcmp(zArg
, "-readonly")==0 ){
3389 if( Tcl_GetBooleanFromObj(interp
, objv
[i
+1], &b
) ) return TCL_ERROR
;
3391 flags
&= ~(SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
);
3392 flags
|= SQLITE_OPEN_READONLY
;
3394 flags
&= ~SQLITE_OPEN_READONLY
;
3395 flags
|= SQLITE_OPEN_READWRITE
;
3397 }else if( strcmp(zArg
, "-create")==0 ){
3399 if( Tcl_GetBooleanFromObj(interp
, objv
[i
+1], &b
) ) return TCL_ERROR
;
3400 if( b
&& (flags
& SQLITE_OPEN_READONLY
)==0 ){
3401 flags
|= SQLITE_OPEN_CREATE
;
3403 flags
&= ~SQLITE_OPEN_CREATE
;
3405 }else if( strcmp(zArg
, "-nomutex")==0 ){
3407 if( Tcl_GetBooleanFromObj(interp
, objv
[i
+1], &b
) ) return TCL_ERROR
;
3409 flags
|= SQLITE_OPEN_NOMUTEX
;
3410 flags
&= ~SQLITE_OPEN_FULLMUTEX
;
3412 flags
&= ~SQLITE_OPEN_NOMUTEX
;
3414 }else if( strcmp(zArg
, "-fullmutex")==0 ){
3416 if( Tcl_GetBooleanFromObj(interp
, objv
[i
+1], &b
) ) return TCL_ERROR
;
3418 flags
|= SQLITE_OPEN_FULLMUTEX
;
3419 flags
&= ~SQLITE_OPEN_NOMUTEX
;
3421 flags
&= ~SQLITE_OPEN_FULLMUTEX
;
3423 }else if( strcmp(zArg
, "-uri")==0 ){
3425 if( Tcl_GetBooleanFromObj(interp
, objv
[i
+1], &b
) ) return TCL_ERROR
;
3427 flags
|= SQLITE_OPEN_URI
;
3429 flags
&= ~SQLITE_OPEN_URI
;
3432 Tcl_AppendResult(interp
, "unknown option: ", zArg
, (char*)0);
3436 if( objc
<3 || (objc
&1)!=1 ){
3437 Tcl_WrongNumArgs(interp
, 1, objv
,
3438 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
3439 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
3440 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3447 p
= (SqliteDb
*)Tcl_Alloc( sizeof(*p
) );
3448 memset(p
, 0, sizeof(*p
));
3449 zFile
= Tcl_GetStringFromObj(objv
[2], 0);
3450 zFile
= Tcl_TranslateFileName(interp
, zFile
, &translatedFilename
);
3451 rc
= sqlite3_open_v2(zFile
, &p
->db
, flags
, zVfs
);
3452 Tcl_DStringFree(&translatedFilename
);
3454 if( SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
3455 zErrMsg
= sqlite3_mprintf("%s", sqlite3_errmsg(p
->db
));
3456 sqlite3_close(p
->db
);
3460 zErrMsg
= sqlite3_mprintf("%s", sqlite3_errstr(rc
));
3462 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3464 sqlite3_key(p
->db
, pKey
, nKey
);
3468 Tcl_SetResult(interp
, zErrMsg
, TCL_VOLATILE
);
3470 sqlite3_free(zErrMsg
);
3473 p
->maxStmt
= NUM_PREPARED_STMTS
;
3474 p
->openFlags
= flags
& SQLITE_OPEN_URI
;
3476 zArg
= Tcl_GetStringFromObj(objv
[1], 0);
3478 Tcl_NRCreateCommand(interp
, zArg
, DbObjCmdAdaptor
, DbObjCmd
,
3479 (char*)p
, DbDeleteCmd
);
3481 Tcl_CreateObjCommand(interp
, zArg
, DbObjCmd
, (char*)p
, DbDeleteCmd
);
3487 ** Provide a dummy Tcl_InitStubs if we are using this as a static
3490 #ifndef USE_TCL_STUBS
3491 # undef Tcl_InitStubs
3492 # define Tcl_InitStubs(a,b,c) TCL_VERSION
3496 ** Make sure we have a PACKAGE_VERSION macro defined. This will be
3497 ** defined automatically by the TEA makefile. But other makefiles
3498 ** do not define it.
3500 #ifndef PACKAGE_VERSION
3501 # define PACKAGE_VERSION SQLITE_VERSION
3505 ** Initialize this module.
3507 ** This Tcl module contains only a single new Tcl command named "sqlite".
3508 ** (Hence there is no namespace. There is no point in using a namespace
3509 ** if the extension only supplies one new name!) The "sqlite" command is
3510 ** used to open a new SQLite database. See the DbMain() routine above
3511 ** for additional information.
3513 ** The EXTERN macros are required by TCL in order to work on windows.
3515 EXTERN
int Sqlite3_Init(Tcl_Interp
*interp
){
3516 int rc
= Tcl_InitStubs(interp
, "8.4", 0) ? TCL_OK
: TCL_ERROR
;
3518 Tcl_CreateObjCommand(interp
, "sqlite3", (Tcl_ObjCmdProc
*)DbMain
, 0, 0);
3519 #ifndef SQLITE_3_SUFFIX_ONLY
3520 /* The "sqlite" alias is undocumented. It is here only to support
3521 ** legacy scripts. All new scripts should use only the "sqlite3"
3523 Tcl_CreateObjCommand(interp
, "sqlite", (Tcl_ObjCmdProc
*)DbMain
, 0, 0);
3525 rc
= Tcl_PkgProvide(interp
, "sqlite3", PACKAGE_VERSION
);
3529 EXTERN
int Tclsqlite3_Init(Tcl_Interp
*interp
){ return Sqlite3_Init(interp
); }
3530 EXTERN
int Sqlite3_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3531 EXTERN
int Tclsqlite3_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3533 /* Because it accesses the file-system and uses persistent state, SQLite
3534 ** is not considered appropriate for safe interpreters. Hence, we cause
3535 ** the _SafeInit() interfaces return TCL_ERROR.
3537 EXTERN
int Sqlite3_SafeInit(Tcl_Interp
*interp
){ return TCL_ERROR
; }
3538 EXTERN
int Sqlite3_SafeUnload(Tcl_Interp
*interp
, int flags
){return TCL_ERROR
;}
3542 #ifndef SQLITE_3_SUFFIX_ONLY
3543 int Sqlite_Init(Tcl_Interp
*interp
){ return Sqlite3_Init(interp
); }
3544 int Tclsqlite_Init(Tcl_Interp
*interp
){ return Sqlite3_Init(interp
); }
3545 int Sqlite_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3546 int Tclsqlite_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3550 /*****************************************************************************
3551 ** All of the code that follows is used to build standalone TCL interpreters
3552 ** that are statically linked with SQLite. Enable these by compiling
3553 ** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3554 ** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3555 ** analysis program.
3558 #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3560 * This code implements the MD5 message-digest algorithm.
3561 * The algorithm is due to Ron Rivest. This code was
3562 * written by Colin Plumb in 1993, no copyright is claimed.
3563 * This code is in the public domain; do with it what you wish.
3565 * Equivalent code is available from RSA Data Security, Inc.
3566 * This code has been tested against that, and is equivalent,
3567 * except that you don't need to include two pages of legalese
3570 * To compute the message digest of a chunk of bytes, declare an
3571 * MD5Context structure, pass it to MD5Init, call MD5Update as
3572 * needed on buffers full of bytes, and then call MD5Final, which
3573 * will fill a supplied 16-byte array with the digest.
3577 * If compiled on a machine that doesn't have a 32-bit integer,
3578 * you just set "uint32" to the appropriate datatype for an
3579 * unsigned 32-bit integer. For example:
3581 * cc -Duint32='unsigned long' md5.c
3585 # define uint32 unsigned int
3592 unsigned char in
[64];
3594 typedef struct MD5Context MD5Context
;
3597 * Note: this code is harmless on little-endian machines.
3599 static void byteReverse (unsigned char *buf
, unsigned longs
){
3602 t
= (uint32
)((unsigned)buf
[3]<<8 | buf
[2]) << 16 |
3603 ((unsigned)buf
[1]<<8 | buf
[0]);
3608 /* The four core functions - F1 is optimized somewhat */
3610 /* #define F1(x, y, z) (x & y | ~x & z) */
3611 #define F1(x, y, z) (z ^ (x & (y ^ z)))
3612 #define F2(x, y, z) F1(z, x, y)
3613 #define F3(x, y, z) (x ^ y ^ z)
3614 #define F4(x, y, z) (y ^ (x | ~z))
3616 /* This is the central step in the MD5 algorithm. */
3617 #define MD5STEP(f, w, x, y, z, data, s) \
3618 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3621 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3622 * reflect the addition of 16 longwords of new data. MD5Update blocks
3623 * the data and converts bytes into longwords for this routine.
3625 static void MD5Transform(uint32 buf
[4], const uint32 in
[16]){
3626 register uint32 a
, b
, c
, d
;
3633 MD5STEP(F1
, a
, b
, c
, d
, in
[ 0]+0xd76aa478, 7);
3634 MD5STEP(F1
, d
, a
, b
, c
, in
[ 1]+0xe8c7b756, 12);
3635 MD5STEP(F1
, c
, d
, a
, b
, in
[ 2]+0x242070db, 17);
3636 MD5STEP(F1
, b
, c
, d
, a
, in
[ 3]+0xc1bdceee, 22);
3637 MD5STEP(F1
, a
, b
, c
, d
, in
[ 4]+0xf57c0faf, 7);
3638 MD5STEP(F1
, d
, a
, b
, c
, in
[ 5]+0x4787c62a, 12);
3639 MD5STEP(F1
, c
, d
, a
, b
, in
[ 6]+0xa8304613, 17);
3640 MD5STEP(F1
, b
, c
, d
, a
, in
[ 7]+0xfd469501, 22);
3641 MD5STEP(F1
, a
, b
, c
, d
, in
[ 8]+0x698098d8, 7);
3642 MD5STEP(F1
, d
, a
, b
, c
, in
[ 9]+0x8b44f7af, 12);
3643 MD5STEP(F1
, c
, d
, a
, b
, in
[10]+0xffff5bb1, 17);
3644 MD5STEP(F1
, b
, c
, d
, a
, in
[11]+0x895cd7be, 22);
3645 MD5STEP(F1
, a
, b
, c
, d
, in
[12]+0x6b901122, 7);
3646 MD5STEP(F1
, d
, a
, b
, c
, in
[13]+0xfd987193, 12);
3647 MD5STEP(F1
, c
, d
, a
, b
, in
[14]+0xa679438e, 17);
3648 MD5STEP(F1
, b
, c
, d
, a
, in
[15]+0x49b40821, 22);
3650 MD5STEP(F2
, a
, b
, c
, d
, in
[ 1]+0xf61e2562, 5);
3651 MD5STEP(F2
, d
, a
, b
, c
, in
[ 6]+0xc040b340, 9);
3652 MD5STEP(F2
, c
, d
, a
, b
, in
[11]+0x265e5a51, 14);
3653 MD5STEP(F2
, b
, c
, d
, a
, in
[ 0]+0xe9b6c7aa, 20);
3654 MD5STEP(F2
, a
, b
, c
, d
, in
[ 5]+0xd62f105d, 5);
3655 MD5STEP(F2
, d
, a
, b
, c
, in
[10]+0x02441453, 9);
3656 MD5STEP(F2
, c
, d
, a
, b
, in
[15]+0xd8a1e681, 14);
3657 MD5STEP(F2
, b
, c
, d
, a
, in
[ 4]+0xe7d3fbc8, 20);
3658 MD5STEP(F2
, a
, b
, c
, d
, in
[ 9]+0x21e1cde6, 5);
3659 MD5STEP(F2
, d
, a
, b
, c
, in
[14]+0xc33707d6, 9);
3660 MD5STEP(F2
, c
, d
, a
, b
, in
[ 3]+0xf4d50d87, 14);
3661 MD5STEP(F2
, b
, c
, d
, a
, in
[ 8]+0x455a14ed, 20);
3662 MD5STEP(F2
, a
, b
, c
, d
, in
[13]+0xa9e3e905, 5);
3663 MD5STEP(F2
, d
, a
, b
, c
, in
[ 2]+0xfcefa3f8, 9);
3664 MD5STEP(F2
, c
, d
, a
, b
, in
[ 7]+0x676f02d9, 14);
3665 MD5STEP(F2
, b
, c
, d
, a
, in
[12]+0x8d2a4c8a, 20);
3667 MD5STEP(F3
, a
, b
, c
, d
, in
[ 5]+0xfffa3942, 4);
3668 MD5STEP(F3
, d
, a
, b
, c
, in
[ 8]+0x8771f681, 11);
3669 MD5STEP(F3
, c
, d
, a
, b
, in
[11]+0x6d9d6122, 16);
3670 MD5STEP(F3
, b
, c
, d
, a
, in
[14]+0xfde5380c, 23);
3671 MD5STEP(F3
, a
, b
, c
, d
, in
[ 1]+0xa4beea44, 4);
3672 MD5STEP(F3
, d
, a
, b
, c
, in
[ 4]+0x4bdecfa9, 11);
3673 MD5STEP(F3
, c
, d
, a
, b
, in
[ 7]+0xf6bb4b60, 16);
3674 MD5STEP(F3
, b
, c
, d
, a
, in
[10]+0xbebfbc70, 23);
3675 MD5STEP(F3
, a
, b
, c
, d
, in
[13]+0x289b7ec6, 4);
3676 MD5STEP(F3
, d
, a
, b
, c
, in
[ 0]+0xeaa127fa, 11);
3677 MD5STEP(F3
, c
, d
, a
, b
, in
[ 3]+0xd4ef3085, 16);
3678 MD5STEP(F3
, b
, c
, d
, a
, in
[ 6]+0x04881d05, 23);
3679 MD5STEP(F3
, a
, b
, c
, d
, in
[ 9]+0xd9d4d039, 4);
3680 MD5STEP(F3
, d
, a
, b
, c
, in
[12]+0xe6db99e5, 11);
3681 MD5STEP(F3
, c
, d
, a
, b
, in
[15]+0x1fa27cf8, 16);
3682 MD5STEP(F3
, b
, c
, d
, a
, in
[ 2]+0xc4ac5665, 23);
3684 MD5STEP(F4
, a
, b
, c
, d
, in
[ 0]+0xf4292244, 6);
3685 MD5STEP(F4
, d
, a
, b
, c
, in
[ 7]+0x432aff97, 10);
3686 MD5STEP(F4
, c
, d
, a
, b
, in
[14]+0xab9423a7, 15);
3687 MD5STEP(F4
, b
, c
, d
, a
, in
[ 5]+0xfc93a039, 21);
3688 MD5STEP(F4
, a
, b
, c
, d
, in
[12]+0x655b59c3, 6);
3689 MD5STEP(F4
, d
, a
, b
, c
, in
[ 3]+0x8f0ccc92, 10);
3690 MD5STEP(F4
, c
, d
, a
, b
, in
[10]+0xffeff47d, 15);
3691 MD5STEP(F4
, b
, c
, d
, a
, in
[ 1]+0x85845dd1, 21);
3692 MD5STEP(F4
, a
, b
, c
, d
, in
[ 8]+0x6fa87e4f, 6);
3693 MD5STEP(F4
, d
, a
, b
, c
, in
[15]+0xfe2ce6e0, 10);
3694 MD5STEP(F4
, c
, d
, a
, b
, in
[ 6]+0xa3014314, 15);
3695 MD5STEP(F4
, b
, c
, d
, a
, in
[13]+0x4e0811a1, 21);
3696 MD5STEP(F4
, a
, b
, c
, d
, in
[ 4]+0xf7537e82, 6);
3697 MD5STEP(F4
, d
, a
, b
, c
, in
[11]+0xbd3af235, 10);
3698 MD5STEP(F4
, c
, d
, a
, b
, in
[ 2]+0x2ad7d2bb, 15);
3699 MD5STEP(F4
, b
, c
, d
, a
, in
[ 9]+0xeb86d391, 21);
3708 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3709 * initialization constants.
3711 static void MD5Init(MD5Context
*ctx
){
3713 ctx
->buf
[0] = 0x67452301;
3714 ctx
->buf
[1] = 0xefcdab89;
3715 ctx
->buf
[2] = 0x98badcfe;
3716 ctx
->buf
[3] = 0x10325476;
3722 * Update context to reflect the concatenation of another buffer full
3726 void MD5Update(MD5Context
*ctx
, const unsigned char *buf
, unsigned int len
){
3729 /* Update bitcount */
3732 if ((ctx
->bits
[0] = t
+ ((uint32
)len
<< 3)) < t
)
3733 ctx
->bits
[1]++; /* Carry from low to high */
3734 ctx
->bits
[1] += len
>> 29;
3736 t
= (t
>> 3) & 0x3f; /* Bytes already in shsInfo->data */
3738 /* Handle any leading odd-sized chunks */
3741 unsigned char *p
= (unsigned char *)ctx
->in
+ t
;
3745 memcpy(p
, buf
, len
);
3749 byteReverse(ctx
->in
, 16);
3750 MD5Transform(ctx
->buf
, (uint32
*)ctx
->in
);
3755 /* Process data in 64-byte chunks */
3758 memcpy(ctx
->in
, buf
, 64);
3759 byteReverse(ctx
->in
, 16);
3760 MD5Transform(ctx
->buf
, (uint32
*)ctx
->in
);
3765 /* Handle any remaining bytes of data. */
3767 memcpy(ctx
->in
, buf
, len
);
3771 * Final wrapup - pad to 64-byte boundary with the bit pattern
3772 * 1 0* (64-bit count of bits processed, MSB-first)
3774 static void MD5Final(unsigned char digest
[16], MD5Context
*ctx
){
3778 /* Compute number of bytes mod 64 */
3779 count
= (ctx
->bits
[0] >> 3) & 0x3F;
3781 /* Set the first char of padding to 0x80. This is safe since there is
3782 always at least one byte free */
3783 p
= ctx
->in
+ count
;
3786 /* Bytes of padding needed to make 64 bytes */
3787 count
= 64 - 1 - count
;
3789 /* Pad out to 56 mod 64 */
3791 /* Two lots of padding: Pad the first block to 64 bytes */
3792 memset(p
, 0, count
);
3793 byteReverse(ctx
->in
, 16);
3794 MD5Transform(ctx
->buf
, (uint32
*)ctx
->in
);
3796 /* Now fill the next block with 56 bytes */
3797 memset(ctx
->in
, 0, 56);
3799 /* Pad block to 56 bytes */
3800 memset(p
, 0, count
-8);
3802 byteReverse(ctx
->in
, 14);
3804 /* Append length in bits and transform */
3805 memcpy(ctx
->in
+ 14*4, ctx
->bits
, 8);
3807 MD5Transform(ctx
->buf
, (uint32
*)ctx
->in
);
3808 byteReverse((unsigned char *)ctx
->buf
, 4);
3809 memcpy(digest
, ctx
->buf
, 16);
3813 ** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3815 static void MD5DigestToBase16(unsigned char *digest
, char *zBuf
){
3816 static char const zEncode
[] = "0123456789abcdef";
3819 for(j
=i
=0; i
<16; i
++){
3821 zBuf
[j
++] = zEncode
[(a
>>4)&0xf];
3822 zBuf
[j
++] = zEncode
[a
& 0xf];
3829 ** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3830 ** each representing 16 bits of the digest and separated from each
3831 ** other by a "-" character.
3833 static void MD5DigestToBase10x8(unsigned char digest
[16], char zDigest
[50]){
3836 for(i
=j
=0; i
<16; i
+=2){
3837 x
= digest
[i
]*256 + digest
[i
+1];
3838 if( i
>0 ) zDigest
[j
++] = '-';
3839 sqlite3_snprintf(50-j
, &zDigest
[j
], "%05u", x
);
3846 ** A TCL command for md5. The argument is the text to be hashed. The
3847 ** Result is the hash in base64.
3849 static int SQLITE_TCLAPI
md5_cmd(
3856 unsigned char digest
[16];
3858 void (*converter
)(unsigned char*, char*);
3861 Tcl_AppendResult(interp
,"wrong # args: should be \"", argv
[0],
3862 " TEXT\"", (char*)0);
3866 MD5Update(&ctx
, (unsigned char*)argv
[1], (unsigned)strlen(argv
[1]));
3867 MD5Final(digest
, &ctx
);
3868 converter
= (void(*)(unsigned char*,char*))cd
;
3869 converter(digest
, zBuf
);
3870 Tcl_AppendResult(interp
, zBuf
, (char*)0);
3875 ** A TCL command to take the md5 hash of a file. The argument is the
3876 ** name of the file.
3878 static int SQLITE_TCLAPI
md5file_cmd(
3888 void (*converter
)(unsigned char*, char*);
3889 unsigned char digest
[16];
3892 if( argc
!=2 && argc
!=4 ){
3893 Tcl_AppendResult(interp
,"wrong # args: should be \"", argv
[0],
3894 " FILENAME [OFFSET AMT]\"", (char*)0);
3898 ofst
= atoi(argv
[2]);
3899 amt
= atoi(argv
[3]);
3904 in
= fopen(argv
[1],"rb");
3906 Tcl_AppendResult(interp
,"unable to open file \"", argv
[1],
3907 "\" for reading", (char*)0);
3910 fseek(in
, ofst
, SEEK_SET
);
3914 n
= (int)fread(zBuf
, 1, sizeof(zBuf
)<=amt
? sizeof(zBuf
) : amt
, in
);
3916 MD5Update(&ctx
, (unsigned char*)zBuf
, (unsigned)n
);
3920 MD5Final(digest
, &ctx
);
3921 converter
= (void(*)(unsigned char*,char*))cd
;
3922 converter(digest
, zBuf
);
3923 Tcl_AppendResult(interp
, zBuf
, (char*)0);
3928 ** Register the four new TCL commands for generating MD5 checksums
3929 ** with the TCL interpreter.
3931 int Md5_Init(Tcl_Interp
*interp
){
3932 Tcl_CreateCommand(interp
, "md5", (Tcl_CmdProc
*)md5_cmd
,
3933 MD5DigestToBase16
, 0);
3934 Tcl_CreateCommand(interp
, "md5-10x8", (Tcl_CmdProc
*)md5_cmd
,
3935 MD5DigestToBase10x8
, 0);
3936 Tcl_CreateCommand(interp
, "md5file", (Tcl_CmdProc
*)md5file_cmd
,
3937 MD5DigestToBase16
, 0);
3938 Tcl_CreateCommand(interp
, "md5file-10x8", (Tcl_CmdProc
*)md5file_cmd
,
3939 MD5DigestToBase10x8
, 0);
3942 #endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3944 #if defined(SQLITE_TEST)
3946 ** During testing, the special md5sum() aggregate function is available.
3947 ** inside SQLite. The following routines implement that function.
3949 static void md5step(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
){
3952 if( argc
<1 ) return;
3953 p
= sqlite3_aggregate_context(context
, sizeof(*p
));
3958 for(i
=0; i
<argc
; i
++){
3959 const char *zData
= (char*)sqlite3_value_text(argv
[i
]);
3961 MD5Update(p
, (unsigned char*)zData
, (int)strlen(zData
));
3965 static void md5finalize(sqlite3_context
*context
){
3967 unsigned char digest
[16];
3969 p
= sqlite3_aggregate_context(context
, sizeof(*p
));
3971 MD5DigestToBase16(digest
, zBuf
);
3972 sqlite3_result_text(context
, zBuf
, -1, SQLITE_TRANSIENT
);
3977 const sqlite3_api_routines
*pThunk
3979 int rc
= sqlite3_create_function(db
, "md5sum", -1, SQLITE_UTF8
, 0, 0,
3980 md5step
, md5finalize
);
3981 sqlite3_overload_function(db
, "md5sum", -1); /* To exercise this API */
3984 #endif /* defined(SQLITE_TEST) */
3988 ** If the macro TCLSH is one, then put in code this for the
3989 ** "main" routine that will initialize Tcl and take input from
3990 ** standard input, or if a file is named on the command line
3991 ** the TCL interpreter reads and evaluates that file.
3994 static const char *tclsh_main_loop(void){
3995 static const char zMainloop
[] =
3997 "while {![eof stdin]} {\n"
3998 "if {$line!=\"\"} {\n"
3999 "puts -nonewline \"> \"\n"
4001 "puts -nonewline \"% \"\n"
4004 "append line [gets stdin]\n"
4005 "if {[info complete $line]} {\n"
4006 "if {[catch {uplevel #0 $line} result]} {\n"
4007 "puts stderr \"Error: $result\"\n"
4008 "} elseif {$result!=\"\"} {\n"
4021 static const char *tclsh_main_loop(void);
4025 static void init_all(Tcl_Interp
*);
4026 static int SQLITE_TCLAPI
init_all_cmd(
4030 Tcl_Obj
*CONST objv
[]
4035 Tcl_WrongNumArgs(interp
, 1, objv
, "SLAVE");
4039 slave
= Tcl_GetSlave(interp
, Tcl_GetString(objv
[1]));
4049 ** Tclcmd: db_use_legacy_prepare DB BOOLEAN
4051 ** The first argument to this command must be a database command created by
4052 ** [sqlite3]. If the second argument is true, then the handle is configured
4053 ** to use the sqlite3_prepare_v2() function to prepare statements. If it
4054 ** is false, sqlite3_prepare().
4056 static int SQLITE_TCLAPI
db_use_legacy_prepare_cmd(
4060 Tcl_Obj
*CONST objv
[]
4062 Tcl_CmdInfo cmdInfo
;
4067 Tcl_WrongNumArgs(interp
, 1, objv
, "DB BOOLEAN");
4071 if( !Tcl_GetCommandInfo(interp
, Tcl_GetString(objv
[1]), &cmdInfo
) ){
4072 Tcl_AppendResult(interp
, "no such db: ", Tcl_GetString(objv
[1]), (char*)0);
4075 pDb
= (SqliteDb
*)cmdInfo
.objClientData
;
4076 if( Tcl_GetBooleanFromObj(interp
, objv
[2], &bPrepare
) ){
4080 pDb
->bLegacyPrepare
= bPrepare
;
4082 Tcl_ResetResult(interp
);
4087 ** Tclcmd: db_last_stmt_ptr DB
4089 ** If the statement cache associated with database DB is not empty,
4090 ** return the text representation of the most recently used statement
4093 static int SQLITE_TCLAPI
db_last_stmt_ptr(
4097 Tcl_Obj
*CONST objv
[]
4099 extern int sqlite3TestMakePointerStr(Tcl_Interp
*, char*, void*);
4100 Tcl_CmdInfo cmdInfo
;
4102 sqlite3_stmt
*pStmt
= 0;
4106 Tcl_WrongNumArgs(interp
, 1, objv
, "DB");
4110 if( !Tcl_GetCommandInfo(interp
, Tcl_GetString(objv
[1]), &cmdInfo
) ){
4111 Tcl_AppendResult(interp
, "no such db: ", Tcl_GetString(objv
[1]), (char*)0);
4114 pDb
= (SqliteDb
*)cmdInfo
.objClientData
;
4116 if( pDb
->stmtList
) pStmt
= pDb
->stmtList
->pStmt
;
4117 if( sqlite3TestMakePointerStr(interp
, zBuf
, pStmt
) ){
4120 Tcl_SetResult(interp
, zBuf
, TCL_VOLATILE
);
4124 #endif /* SQLITE_TEST */
4127 ** Configure the interpreter passed as the first argument to have access
4128 ** to the commands and linked variables that make up:
4130 ** * the [sqlite3] extension itself,
4132 ** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
4134 ** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
4137 static void init_all(Tcl_Interp
*interp
){
4138 Sqlite3_Init(interp
);
4140 #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
4146 extern int Sqliteconfig_Init(Tcl_Interp
*);
4147 extern int Sqlitetest1_Init(Tcl_Interp
*);
4148 extern int Sqlitetest2_Init(Tcl_Interp
*);
4149 extern int Sqlitetest3_Init(Tcl_Interp
*);
4150 extern int Sqlitetest4_Init(Tcl_Interp
*);
4151 extern int Sqlitetest5_Init(Tcl_Interp
*);
4152 extern int Sqlitetest6_Init(Tcl_Interp
*);
4153 extern int Sqlitetest7_Init(Tcl_Interp
*);
4154 extern int Sqlitetest8_Init(Tcl_Interp
*);
4155 extern int Sqlitetest9_Init(Tcl_Interp
*);
4156 extern int Sqlitetestasync_Init(Tcl_Interp
*);
4157 extern int Sqlitetest_autoext_Init(Tcl_Interp
*);
4158 extern int Sqlitetest_blob_Init(Tcl_Interp
*);
4159 extern int Sqlitetest_demovfs_Init(Tcl_Interp
*);
4160 extern int Sqlitetest_func_Init(Tcl_Interp
*);
4161 extern int Sqlitetest_hexio_Init(Tcl_Interp
*);
4162 extern int Sqlitetest_init_Init(Tcl_Interp
*);
4163 extern int Sqlitetest_malloc_Init(Tcl_Interp
*);
4164 extern int Sqlitetest_mutex_Init(Tcl_Interp
*);
4165 extern int Sqlitetestschema_Init(Tcl_Interp
*);
4166 extern int Sqlitetestsse_Init(Tcl_Interp
*);
4167 extern int Sqlitetesttclvar_Init(Tcl_Interp
*);
4168 extern int Sqlitetestfs_Init(Tcl_Interp
*);
4169 extern int SqlitetestThread_Init(Tcl_Interp
*);
4170 extern int SqlitetestOnefile_Init();
4171 extern int SqlitetestOsinst_Init(Tcl_Interp
*);
4172 extern int Sqlitetestbackup_Init(Tcl_Interp
*);
4173 extern int Sqlitetestintarray_Init(Tcl_Interp
*);
4174 extern int Sqlitetestvfs_Init(Tcl_Interp
*);
4175 extern int Sqlitetestrtree_Init(Tcl_Interp
*);
4176 extern int Sqlitequota_Init(Tcl_Interp
*);
4177 extern int Sqlitemultiplex_Init(Tcl_Interp
*);
4178 extern int SqliteSuperlock_Init(Tcl_Interp
*);
4179 extern int SqlitetestSyscall_Init(Tcl_Interp
*);
4180 #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
4181 extern int TestSession_Init(Tcl_Interp
*);
4183 extern int Fts5tcl_Init(Tcl_Interp
*);
4184 extern int SqliteRbu_Init(Tcl_Interp
*);
4185 extern int Sqlitetesttcl_Init(Tcl_Interp
*);
4186 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
4187 extern int Sqlitetestfts3_Init(Tcl_Interp
*interp
);
4190 #ifdef SQLITE_ENABLE_ZIPVFS
4191 extern int Zipvfs_Init(Tcl_Interp
*);
4192 Zipvfs_Init(interp
);
4195 Sqliteconfig_Init(interp
);
4196 Sqlitetest1_Init(interp
);
4197 Sqlitetest2_Init(interp
);
4198 Sqlitetest3_Init(interp
);
4199 Sqlitetest4_Init(interp
);
4200 Sqlitetest5_Init(interp
);
4201 Sqlitetest6_Init(interp
);
4202 Sqlitetest7_Init(interp
);
4203 Sqlitetest8_Init(interp
);
4204 Sqlitetest9_Init(interp
);
4205 Sqlitetestasync_Init(interp
);
4206 Sqlitetest_autoext_Init(interp
);
4207 Sqlitetest_blob_Init(interp
);
4208 Sqlitetest_demovfs_Init(interp
);
4209 Sqlitetest_func_Init(interp
);
4210 Sqlitetest_hexio_Init(interp
);
4211 Sqlitetest_init_Init(interp
);
4212 Sqlitetest_malloc_Init(interp
);
4213 Sqlitetest_mutex_Init(interp
);
4214 Sqlitetestschema_Init(interp
);
4215 Sqlitetesttclvar_Init(interp
);
4216 Sqlitetestfs_Init(interp
);
4217 SqlitetestThread_Init(interp
);
4218 SqlitetestOnefile_Init();
4219 SqlitetestOsinst_Init(interp
);
4220 Sqlitetestbackup_Init(interp
);
4221 Sqlitetestintarray_Init(interp
);
4222 Sqlitetestvfs_Init(interp
);
4223 Sqlitetestrtree_Init(interp
);
4224 Sqlitequota_Init(interp
);
4225 Sqlitemultiplex_Init(interp
);
4226 SqliteSuperlock_Init(interp
);
4227 SqlitetestSyscall_Init(interp
);
4228 #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
4229 TestSession_Init(interp
);
4231 Fts5tcl_Init(interp
);
4232 SqliteRbu_Init(interp
);
4233 Sqlitetesttcl_Init(interp
);
4235 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
4236 Sqlitetestfts3_Init(interp
);
4239 Tcl_CreateObjCommand(
4240 interp
, "load_testfixture_extensions", init_all_cmd
, 0, 0
4242 Tcl_CreateObjCommand(
4243 interp
, "db_use_legacy_prepare", db_use_legacy_prepare_cmd
, 0, 0
4245 Tcl_CreateObjCommand(
4246 interp
, "db_last_stmt_ptr", db_last_stmt_ptr
, 0, 0
4250 Sqlitetestsse_Init(interp
);
4256 /* Needed for the setrlimit() system call on unix */
4258 #include <sys/resource.h>
4261 #define TCLSH_MAIN main /* Needed to fake out mktclapp */
4262 int SQLITE_CDECL
TCLSH_MAIN(int argc
, char **argv
){
4265 #if !defined(_WIN32_WCE)
4266 if( getenv("BREAK") ){
4268 "attach debugger to process %d and press any key to continue.\n",
4274 /* Since the primary use case for this binary is testing of SQLite,
4275 ** be sure to generate core files if we crash */
4276 #if defined(SQLITE_TEST) && defined(unix)
4278 getrlimit(RLIMIT_CORE
, &x
);
4279 x
.rlim_cur
= x
.rlim_max
;
4280 setrlimit(RLIMIT_CORE
, &x
);
4282 #endif /* SQLITE_TEST && unix */
4285 /* Call sqlite3_shutdown() once before doing anything else. This is to
4286 ** test that sqlite3_shutdown() can be safely called by a process before
4287 ** sqlite3_initialize() is. */
4290 Tcl_FindExecutable(argv
[0]);
4291 Tcl_SetSystemEncoding(NULL
, "utf-8");
4292 interp
= Tcl_CreateInterp();
4295 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD
);
4302 sqlite3_snprintf(sizeof(zArgc
), zArgc
, "%d", argc
-(3-TCLSH
));
4303 Tcl_SetVar(interp
,"argc", zArgc
, TCL_GLOBAL_ONLY
);
4304 Tcl_SetVar(interp
,"argv0",argv
[1],TCL_GLOBAL_ONLY
);
4305 Tcl_SetVar(interp
,"argv", "", TCL_GLOBAL_ONLY
);
4306 for(i
=3-TCLSH
; i
<argc
; i
++){
4307 Tcl_SetVar(interp
, "argv", argv
[i
],
4308 TCL_GLOBAL_ONLY
| TCL_LIST_ELEMENT
| TCL_APPEND_VALUE
);
4310 if( TCLSH
==1 && Tcl_EvalFile(interp
, argv
[1])!=TCL_OK
){
4311 const char *zInfo
= Tcl_GetVar(interp
, "errorInfo", TCL_GLOBAL_ONLY
);
4312 if( zInfo
==0 ) zInfo
= Tcl_GetStringResult(interp
);
4313 fprintf(stderr
,"%s: %s\n", *argv
, zInfo
);
4317 if( TCLSH
==2 || argc
<=1 ){
4318 Tcl_GlobalEval(interp
, tclsh_main_loop());