4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** A TCL Interface to SQLite. Append this file to sqlite3.c and
13 ** compile the whole thing to build a TCL-enabled version of SQLite.
15 ** Compile-time options:
17 ** -DTCLSH Add a "main()" routine that works as a tclsh.
19 ** -DTCLSH_INIT_PROC=name
21 ** Invoke name(interp) to initialize the Tcl interpreter.
22 ** If name(interp) returns a non-NULL string, then run
23 ** that string as a Tcl script to launch the application.
24 ** If name(interp) returns NULL, then run the regular
25 ** tclsh-emulator code.
27 #ifdef TCLSH_INIT_PROC
32 ** If requested, include the SQLite compiler options file for MSVC.
34 #if defined(INCLUDE_MSVC_H)
38 #if defined(INCLUDE_SQLITE_TCL_H)
39 # include "sqlite_tcl.h"
42 # ifndef SQLITE_TCLAPI
43 # define SQLITE_TCLAPI
49 ** Some additional include files are needed if this file is not
50 ** appended to the amalgamation.
52 #ifndef SQLITE_AMALGAMATION
57 typedef unsigned char u8
;
61 /* Used to get the current process ID */
65 # define GETPID getpid
66 #elif !defined(_WIN32_WCE)
67 # ifndef SQLITE_AMALGAMATION
68 # ifndef WIN32_LEAN_AND_MEAN
69 # define WIN32_LEAN_AND_MEAN
74 # define isatty(h) _isatty(h)
75 # define GETPID (int)GetCurrentProcessId
79 * Windows needs to know which symbols to export. Unix does not.
80 * BUILD_sqlite should be undefined for Unix.
83 #undef TCL_STORAGE_CLASS
84 #define TCL_STORAGE_CLASS DLLEXPORT
85 #endif /* BUILD_sqlite */
87 #define NUM_PREPARED_STMTS 10
88 #define MAX_PREPARED_STMTS 100
90 /* Forward declaration */
91 typedef struct SqliteDb SqliteDb
;
94 ** New SQL functions can be created as TCL scripts. Each such function
95 ** is described by an instance of the following structure.
97 ** Variable eType may be set to SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT,
98 ** SQLITE_BLOB or SQLITE_NULL. If it is SQLITE_NULL, then the implementation
99 ** attempts to determine the type of the result based on the Tcl object.
100 ** If it is SQLITE_TEXT or SQLITE_BLOB, then a text (sqlite3_result_text())
101 ** or blob (sqlite3_result_blob()) is returned. If it is SQLITE_INTEGER
102 ** or SQLITE_FLOAT, then an attempt is made to return an integer or float
103 ** value, falling back to float and then text if this is not possible.
105 typedef struct SqlFunc SqlFunc
;
107 Tcl_Interp
*interp
; /* The TCL interpret to execute the function */
108 Tcl_Obj
*pScript
; /* The Tcl_Obj representation of the script */
109 SqliteDb
*pDb
; /* Database connection that owns this function */
110 int useEvalObjv
; /* True if it is safe to use Tcl_EvalObjv */
111 int eType
; /* Type of value to return */
112 char *zName
; /* Name of this function */
113 SqlFunc
*pNext
; /* Next function on the list of them all */
117 ** New collation sequences function can be created as TCL scripts. Each such
118 ** function is described by an instance of the following structure.
120 typedef struct SqlCollate SqlCollate
;
122 Tcl_Interp
*interp
; /* The TCL interpret to execute the function */
123 char *zScript
; /* The script to be run */
124 SqlCollate
*pNext
; /* Next function on the list of them all */
128 ** Prepared statements are cached for faster execution. Each prepared
129 ** statement is described by an instance of the following structure.
131 typedef struct SqlPreparedStmt SqlPreparedStmt
;
132 struct SqlPreparedStmt
{
133 SqlPreparedStmt
*pNext
; /* Next in linked list */
134 SqlPreparedStmt
*pPrev
; /* Previous on the list */
135 sqlite3_stmt
*pStmt
; /* The prepared statement */
136 int nSql
; /* chars in zSql[] */
137 const char *zSql
; /* Text of the SQL statement */
138 int nParm
; /* Size of apParm array */
139 Tcl_Obj
**apParm
; /* Array of referenced object pointers */
142 typedef struct IncrblobChannel IncrblobChannel
;
145 ** There is one instance of this structure for each SQLite database
146 ** that has been opened by the SQLite TCL interface.
148 ** If this module is built with SQLITE_TEST defined (to create the SQLite
149 ** testfixture executable), then it may be configured to use either
150 ** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
151 ** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
154 sqlite3
*db
; /* The "real" database structure. MUST BE FIRST */
155 Tcl_Interp
*interp
; /* The interpreter used for this database */
156 char *zBusy
; /* The busy callback routine */
157 char *zCommit
; /* The commit hook callback routine */
158 char *zTrace
; /* The trace callback routine */
159 char *zTraceV2
; /* The trace_v2 callback routine */
160 char *zProfile
; /* The profile callback routine */
161 char *zProgress
; /* The progress callback routine */
162 char *zBindFallback
; /* Callback to invoke on a binding miss */
163 char *zAuth
; /* The authorization callback routine */
164 int disableAuth
; /* Disable the authorizer if it exists */
165 char *zNull
; /* Text to substitute for an SQL NULL value */
166 SqlFunc
*pFunc
; /* List of SQL functions */
167 Tcl_Obj
*pUpdateHook
; /* Update hook script (if any) */
168 Tcl_Obj
*pPreUpdateHook
; /* Pre-update hook script (if any) */
169 Tcl_Obj
*pRollbackHook
; /* Rollback hook script (if any) */
170 Tcl_Obj
*pWalHook
; /* WAL hook script (if any) */
171 Tcl_Obj
*pUnlockNotify
; /* Unlock notify script (if any) */
172 SqlCollate
*pCollate
; /* List of SQL collation functions */
173 int rc
; /* Return code of most recent sqlite3_exec() */
174 Tcl_Obj
*pCollateNeeded
; /* Collation needed script */
175 SqlPreparedStmt
*stmtList
; /* List of prepared statements*/
176 SqlPreparedStmt
*stmtLast
; /* Last statement in the list */
177 int maxStmt
; /* The next maximum number of stmtList */
178 int nStmt
; /* Number of statements in stmtList */
179 IncrblobChannel
*pIncrblob
;/* Linked list of open incrblob channels */
180 int nStep
, nSort
, nIndex
; /* Statistics for most recent operation */
181 int nVMStep
; /* Another statistic for most recent operation */
182 int nTransaction
; /* Number of nested [transaction] methods */
183 int openFlags
; /* Flags used to open. (SQLITE_OPEN_URI) */
185 int bLegacyPrepare
; /* True to use sqlite3_prepare() */
189 struct IncrblobChannel
{
190 sqlite3_blob
*pBlob
; /* sqlite3 blob handle */
191 SqliteDb
*pDb
; /* Associated database connection */
192 int iSeek
; /* Current seek offset */
193 Tcl_Channel channel
; /* Channel identifier */
194 IncrblobChannel
*pNext
; /* Linked list of all open incrblob channels */
195 IncrblobChannel
*pPrev
; /* Linked list of all open incrblob channels */
199 ** Compute a string length that is limited to what can be stored in
200 ** lower 30 bits of a 32-bit signed integer.
202 static int strlen30(const char *z
){
204 while( *z2
){ z2
++; }
205 return 0x3fffffff & (int)(z2
- z
);
209 #ifndef SQLITE_OMIT_INCRBLOB
211 ** Close all incrblob channels opened using database connection pDb.
212 ** This is called when shutting down the database connection.
214 static void closeIncrblobChannels(SqliteDb
*pDb
){
216 IncrblobChannel
*pNext
;
218 for(p
=pDb
->pIncrblob
; p
; p
=pNext
){
221 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
222 ** which deletes the IncrblobChannel structure at *p. So do not
223 ** call Tcl_Free() here.
225 Tcl_UnregisterChannel(pDb
->interp
, p
->channel
);
230 ** Close an incremental blob channel.
232 static int SQLITE_TCLAPI
incrblobClose(
233 ClientData instanceData
,
236 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
237 int rc
= sqlite3_blob_close(p
->pBlob
);
238 sqlite3
*db
= p
->pDb
->db
;
240 /* Remove the channel from the SqliteDb.pIncrblob list. */
242 p
->pNext
->pPrev
= p
->pPrev
;
245 p
->pPrev
->pNext
= p
->pNext
;
247 if( p
->pDb
->pIncrblob
==p
){
248 p
->pDb
->pIncrblob
= p
->pNext
;
251 /* Free the IncrblobChannel structure */
255 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(db
), TCL_VOLATILE
);
262 ** Read data from an incremental blob channel.
264 static int SQLITE_TCLAPI
incrblobInput(
265 ClientData instanceData
,
270 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
271 int nRead
= bufSize
; /* Number of bytes to read */
272 int nBlob
; /* Total size of the blob */
273 int rc
; /* sqlite error code */
275 nBlob
= sqlite3_blob_bytes(p
->pBlob
);
276 if( (p
->iSeek
+nRead
)>nBlob
){
277 nRead
= nBlob
-p
->iSeek
;
283 rc
= sqlite3_blob_read(p
->pBlob
, (void *)buf
, nRead
, p
->iSeek
);
294 ** Write data to an incremental blob channel.
296 static int SQLITE_TCLAPI
incrblobOutput(
297 ClientData instanceData
,
302 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
303 int nWrite
= toWrite
; /* Number of bytes to write */
304 int nBlob
; /* Total size of the blob */
305 int rc
; /* sqlite error code */
307 nBlob
= sqlite3_blob_bytes(p
->pBlob
);
308 if( (p
->iSeek
+nWrite
)>nBlob
){
309 *errorCodePtr
= EINVAL
;
316 rc
= sqlite3_blob_write(p
->pBlob
, (void *)buf
, nWrite
, p
->iSeek
);
327 ** Seek an incremental blob channel.
329 static int SQLITE_TCLAPI
incrblobSeek(
330 ClientData instanceData
,
335 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
345 p
->iSeek
= sqlite3_blob_bytes(p
->pBlob
) + offset
;
348 default: assert(!"Bad seekMode");
355 static void SQLITE_TCLAPI
incrblobWatch(
356 ClientData instanceData
,
361 static int SQLITE_TCLAPI
incrblobHandle(
362 ClientData instanceData
,
369 static Tcl_ChannelType IncrblobChannelType
= {
370 "incrblob", /* typeName */
371 TCL_CHANNEL_VERSION_2
, /* version */
372 incrblobClose
, /* closeProc */
373 incrblobInput
, /* inputProc */
374 incrblobOutput
, /* outputProc */
375 incrblobSeek
, /* seekProc */
376 0, /* setOptionProc */
377 0, /* getOptionProc */
378 incrblobWatch
, /* watchProc (this is a no-op) */
379 incrblobHandle
, /* getHandleProc (always returns error) */
381 0, /* blockModeProc */
384 0, /* wideSeekProc */
388 ** Create a new incrblob channel.
390 static int createIncrblobChannel(
400 sqlite3
*db
= pDb
->db
;
403 int flags
= TCL_READABLE
|(isReadonly
? 0 : TCL_WRITABLE
);
405 /* This variable is used to name the channels: "incrblob_[incr count]" */
406 static int count
= 0;
409 rc
= sqlite3_blob_open(db
, zDb
, zTable
, zColumn
, iRow
, !isReadonly
, &pBlob
);
411 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(pDb
->db
), TCL_VOLATILE
);
415 p
= (IncrblobChannel
*)Tcl_Alloc(sizeof(IncrblobChannel
));
419 sqlite3_snprintf(sizeof(zChannel
), zChannel
, "incrblob_%d", ++count
);
420 p
->channel
= Tcl_CreateChannel(&IncrblobChannelType
, zChannel
, p
, flags
);
421 Tcl_RegisterChannel(interp
, p
->channel
);
423 /* Link the new channel into the SqliteDb.pIncrblob list. */
424 p
->pNext
= pDb
->pIncrblob
;
432 Tcl_SetResult(interp
, (char *)Tcl_GetChannelName(p
->channel
), TCL_VOLATILE
);
435 #else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
436 #define closeIncrblobChannels(pDb)
440 ** Look at the script prefix in pCmd. We will be executing this script
441 ** after first appending one or more arguments. This routine analyzes
442 ** the script to see if it is safe to use Tcl_EvalObjv() on the script
443 ** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
446 ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
447 ** command name followed by zero or more arguments with no [...] or $
448 ** or {...} or ; to be seen anywhere. Most callback scripts consist
449 ** of just a single procedure name and they meet this requirement.
451 static int safeToUseEvalObjv(Tcl_Interp
*interp
, Tcl_Obj
*pCmd
){
452 /* We could try to do something with Tcl_Parse(). But we will instead
453 ** just do a search for forbidden characters. If any of the forbidden
454 ** characters appear in pCmd, we will report the string as unsafe.
458 z
= Tcl_GetStringFromObj(pCmd
, &n
);
461 if( c
=='$' || c
=='[' || c
==';' ) return 0;
467 ** Find an SqlFunc structure with the given name. Or create a new
468 ** one if an existing one cannot be found. Return a pointer to the
471 static SqlFunc
*findSqlFunc(SqliteDb
*pDb
, const char *zName
){
473 int nName
= strlen30(zName
);
474 pNew
= (SqlFunc
*)Tcl_Alloc( sizeof(*pNew
) + nName
+ 1 );
475 pNew
->zName
= (char*)&pNew
[1];
476 memcpy(pNew
->zName
, zName
, nName
+1);
477 for(p
=pDb
->pFunc
; p
; p
=p
->pNext
){
478 if( sqlite3_stricmp(p
->zName
, pNew
->zName
)==0 ){
479 Tcl_Free((char*)pNew
);
483 pNew
->interp
= pDb
->interp
;
486 pNew
->pNext
= pDb
->pFunc
;
492 ** Free a single SqlPreparedStmt object.
494 static void dbFreeStmt(SqlPreparedStmt
*pStmt
){
496 if( sqlite3_sql(pStmt
->pStmt
)==0 ){
497 Tcl_Free((char *)pStmt
->zSql
);
500 sqlite3_finalize(pStmt
->pStmt
);
501 Tcl_Free((char *)pStmt
);
505 ** Finalize and free a list of prepared statements
507 static void flushStmtCache(SqliteDb
*pDb
){
508 SqlPreparedStmt
*pPreStmt
;
509 SqlPreparedStmt
*pNext
;
511 for(pPreStmt
= pDb
->stmtList
; pPreStmt
; pPreStmt
=pNext
){
512 pNext
= pPreStmt
->pNext
;
513 dbFreeStmt(pPreStmt
);
521 ** TCL calls this procedure when an sqlite3 database command is
524 static void SQLITE_TCLAPI
DbDeleteCmd(void *db
){
525 SqliteDb
*pDb
= (SqliteDb
*)db
;
527 closeIncrblobChannels(pDb
);
528 sqlite3_close(pDb
->db
);
530 SqlFunc
*pFunc
= pDb
->pFunc
;
531 pDb
->pFunc
= pFunc
->pNext
;
532 assert( pFunc
->pDb
==pDb
);
533 Tcl_DecrRefCount(pFunc
->pScript
);
534 Tcl_Free((char*)pFunc
);
536 while( pDb
->pCollate
){
537 SqlCollate
*pCollate
= pDb
->pCollate
;
538 pDb
->pCollate
= pCollate
->pNext
;
539 Tcl_Free((char*)pCollate
);
542 Tcl_Free(pDb
->zBusy
);
545 Tcl_Free(pDb
->zTrace
);
548 Tcl_Free(pDb
->zTraceV2
);
551 Tcl_Free(pDb
->zProfile
);
553 if( pDb
->zBindFallback
){
554 Tcl_Free(pDb
->zBindFallback
);
557 Tcl_Free(pDb
->zAuth
);
560 Tcl_Free(pDb
->zNull
);
562 if( pDb
->pUpdateHook
){
563 Tcl_DecrRefCount(pDb
->pUpdateHook
);
565 if( pDb
->pPreUpdateHook
){
566 Tcl_DecrRefCount(pDb
->pPreUpdateHook
);
568 if( pDb
->pRollbackHook
){
569 Tcl_DecrRefCount(pDb
->pRollbackHook
);
572 Tcl_DecrRefCount(pDb
->pWalHook
);
574 if( pDb
->pCollateNeeded
){
575 Tcl_DecrRefCount(pDb
->pCollateNeeded
);
577 Tcl_Free((char*)pDb
);
581 ** This routine is called when a database file is locked while trying
584 static int DbBusyHandler(void *cd
, int nTries
){
585 SqliteDb
*pDb
= (SqliteDb
*)cd
;
589 sqlite3_snprintf(sizeof(zVal
), zVal
, "%d", nTries
);
590 rc
= Tcl_VarEval(pDb
->interp
, pDb
->zBusy
, " ", zVal
, (char*)0);
591 if( rc
!=TCL_OK
|| atoi(Tcl_GetStringResult(pDb
->interp
)) ){
597 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
599 ** This routine is invoked as the 'progress callback' for the database.
601 static int DbProgressHandler(void *cd
){
602 SqliteDb
*pDb
= (SqliteDb
*)cd
;
605 assert( pDb
->zProgress
);
606 rc
= Tcl_Eval(pDb
->interp
, pDb
->zProgress
);
607 if( rc
!=TCL_OK
|| atoi(Tcl_GetStringResult(pDb
->interp
)) ){
614 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
615 !defined(SQLITE_OMIT_DEPRECATED)
617 ** This routine is called by the SQLite trace handler whenever a new
618 ** block of SQL is executed. The TCL script in pDb->zTrace is executed.
620 static void DbTraceHandler(void *cd
, const char *zSql
){
621 SqliteDb
*pDb
= (SqliteDb
*)cd
;
624 Tcl_DStringInit(&str
);
625 Tcl_DStringAppend(&str
, pDb
->zTrace
, -1);
626 Tcl_DStringAppendElement(&str
, zSql
);
627 Tcl_Eval(pDb
->interp
, Tcl_DStringValue(&str
));
628 Tcl_DStringFree(&str
);
629 Tcl_ResetResult(pDb
->interp
);
633 #ifndef SQLITE_OMIT_TRACE
635 ** This routine is called by the SQLite trace_v2 handler whenever a new
636 ** supported event is generated. Unsupported event types are ignored.
637 ** The TCL script in pDb->zTraceV2 is executed, with the arguments for
638 ** the event appended to it (as list elements).
640 static int DbTraceV2Handler(
641 unsigned type
, /* One of the SQLITE_TRACE_* event types. */
642 void *cd
, /* The original context data pointer. */
643 void *pd
, /* Primary event data, depends on event type. */
644 void *xd
/* Extra event data, depends on event type. */
646 SqliteDb
*pDb
= (SqliteDb
*)cd
;
650 case SQLITE_TRACE_STMT
: {
651 sqlite3_stmt
*pStmt
= (sqlite3_stmt
*)pd
;
652 char *zSql
= (char *)xd
;
654 pCmd
= Tcl_NewStringObj(pDb
->zTraceV2
, -1);
655 Tcl_IncrRefCount(pCmd
);
656 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
657 Tcl_NewWideIntObj((Tcl_WideInt
)pStmt
));
658 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
659 Tcl_NewStringObj(zSql
, -1));
660 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
661 Tcl_DecrRefCount(pCmd
);
662 Tcl_ResetResult(pDb
->interp
);
665 case SQLITE_TRACE_PROFILE
: {
666 sqlite3_stmt
*pStmt
= (sqlite3_stmt
*)pd
;
667 sqlite3_int64 ns
= *(sqlite3_int64
*)xd
;
669 pCmd
= Tcl_NewStringObj(pDb
->zTraceV2
, -1);
670 Tcl_IncrRefCount(pCmd
);
671 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
672 Tcl_NewWideIntObj((Tcl_WideInt
)pStmt
));
673 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
674 Tcl_NewWideIntObj((Tcl_WideInt
)ns
));
675 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
676 Tcl_DecrRefCount(pCmd
);
677 Tcl_ResetResult(pDb
->interp
);
680 case SQLITE_TRACE_ROW
: {
681 sqlite3_stmt
*pStmt
= (sqlite3_stmt
*)pd
;
683 pCmd
= Tcl_NewStringObj(pDb
->zTraceV2
, -1);
684 Tcl_IncrRefCount(pCmd
);
685 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
686 Tcl_NewWideIntObj((Tcl_WideInt
)pStmt
));
687 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
688 Tcl_DecrRefCount(pCmd
);
689 Tcl_ResetResult(pDb
->interp
);
692 case SQLITE_TRACE_CLOSE
: {
693 sqlite3
*db
= (sqlite3
*)pd
;
695 pCmd
= Tcl_NewStringObj(pDb
->zTraceV2
, -1);
696 Tcl_IncrRefCount(pCmd
);
697 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
698 Tcl_NewWideIntObj((Tcl_WideInt
)db
));
699 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
700 Tcl_DecrRefCount(pCmd
);
701 Tcl_ResetResult(pDb
->interp
);
709 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
710 !defined(SQLITE_OMIT_DEPRECATED)
712 ** This routine is called by the SQLite profile handler after a statement
713 ** SQL has executed. The TCL script in pDb->zProfile is evaluated.
715 static void DbProfileHandler(void *cd
, const char *zSql
, sqlite_uint64 tm
){
716 SqliteDb
*pDb
= (SqliteDb
*)cd
;
720 sqlite3_snprintf(sizeof(zTm
)-1, zTm
, "%lld", tm
);
721 Tcl_DStringInit(&str
);
722 Tcl_DStringAppend(&str
, pDb
->zProfile
, -1);
723 Tcl_DStringAppendElement(&str
, zSql
);
724 Tcl_DStringAppendElement(&str
, zTm
);
725 Tcl_Eval(pDb
->interp
, Tcl_DStringValue(&str
));
726 Tcl_DStringFree(&str
);
727 Tcl_ResetResult(pDb
->interp
);
732 ** This routine is called when a transaction is committed. The
733 ** TCL script in pDb->zCommit is executed. If it returns non-zero or
734 ** if it throws an exception, the transaction is rolled back instead
735 ** of being committed.
737 static int DbCommitHandler(void *cd
){
738 SqliteDb
*pDb
= (SqliteDb
*)cd
;
741 rc
= Tcl_Eval(pDb
->interp
, pDb
->zCommit
);
742 if( rc
!=TCL_OK
|| atoi(Tcl_GetStringResult(pDb
->interp
)) ){
748 static void DbRollbackHandler(void *clientData
){
749 SqliteDb
*pDb
= (SqliteDb
*)clientData
;
750 assert(pDb
->pRollbackHook
);
751 if( TCL_OK
!=Tcl_EvalObjEx(pDb
->interp
, pDb
->pRollbackHook
, 0) ){
752 Tcl_BackgroundError(pDb
->interp
);
757 ** This procedure handles wal_hook callbacks.
759 static int DbWalHandler(
767 SqliteDb
*pDb
= (SqliteDb
*)clientData
;
768 Tcl_Interp
*interp
= pDb
->interp
;
769 assert(pDb
->pWalHook
);
771 assert( db
==pDb
->db
);
772 p
= Tcl_DuplicateObj(pDb
->pWalHook
);
774 Tcl_ListObjAppendElement(interp
, p
, Tcl_NewStringObj(zDb
, -1));
775 Tcl_ListObjAppendElement(interp
, p
, Tcl_NewIntObj(nEntry
));
776 if( TCL_OK
!=Tcl_EvalObjEx(interp
, p
, 0)
777 || TCL_OK
!=Tcl_GetIntFromObj(interp
, Tcl_GetObjResult(interp
), &ret
)
779 Tcl_BackgroundError(interp
);
786 #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
787 static void setTestUnlockNotifyVars(Tcl_Interp
*interp
, int iArg
, int nArg
){
789 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%d", iArg
);
790 Tcl_SetVar(interp
, "sqlite_unlock_notify_arg", zBuf
, TCL_GLOBAL_ONLY
);
791 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%d", nArg
);
792 Tcl_SetVar(interp
, "sqlite_unlock_notify_argcount", zBuf
, TCL_GLOBAL_ONLY
);
795 # define setTestUnlockNotifyVars(x,y,z)
798 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
799 static void DbUnlockNotify(void **apArg
, int nArg
){
801 for(i
=0; i
<nArg
; i
++){
802 const int flags
= (TCL_EVAL_GLOBAL
|TCL_EVAL_DIRECT
);
803 SqliteDb
*pDb
= (SqliteDb
*)apArg
[i
];
804 setTestUnlockNotifyVars(pDb
->interp
, i
, nArg
);
805 assert( pDb
->pUnlockNotify
);
806 Tcl_EvalObjEx(pDb
->interp
, pDb
->pUnlockNotify
, flags
);
807 Tcl_DecrRefCount(pDb
->pUnlockNotify
);
808 pDb
->pUnlockNotify
= 0;
813 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
815 ** Pre-update hook callback.
817 static void DbPreUpdateHandler(
826 SqliteDb
*pDb
= (SqliteDb
*)p
;
828 static const char *azStr
[] = {"DELETE", "INSERT", "UPDATE"};
830 assert( (SQLITE_DELETE
-1)/9 == 0 );
831 assert( (SQLITE_INSERT
-1)/9 == 1 );
832 assert( (SQLITE_UPDATE
-1)/9 == 2 );
833 assert( pDb
->pPreUpdateHook
);
834 assert( db
==pDb
->db
);
835 assert( op
==SQLITE_INSERT
|| op
==SQLITE_UPDATE
|| op
==SQLITE_DELETE
);
837 pCmd
= Tcl_DuplicateObj(pDb
->pPreUpdateHook
);
838 Tcl_IncrRefCount(pCmd
);
839 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(azStr
[(op
-1)/9], -1));
840 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(zDb
, -1));
841 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(zTbl
, -1));
842 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewWideIntObj(iKey1
));
843 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewWideIntObj(iKey2
));
844 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
845 Tcl_DecrRefCount(pCmd
);
847 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
849 static void DbUpdateHandler(
856 SqliteDb
*pDb
= (SqliteDb
*)p
;
858 static const char *azStr
[] = {"DELETE", "INSERT", "UPDATE"};
860 assert( (SQLITE_DELETE
-1)/9 == 0 );
861 assert( (SQLITE_INSERT
-1)/9 == 1 );
862 assert( (SQLITE_UPDATE
-1)/9 == 2 );
864 assert( pDb
->pUpdateHook
);
865 assert( op
==SQLITE_INSERT
|| op
==SQLITE_UPDATE
|| op
==SQLITE_DELETE
);
867 pCmd
= Tcl_DuplicateObj(pDb
->pUpdateHook
);
868 Tcl_IncrRefCount(pCmd
);
869 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(azStr
[(op
-1)/9], -1));
870 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(zDb
, -1));
871 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(zTbl
, -1));
872 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewWideIntObj(rowid
));
873 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
874 Tcl_DecrRefCount(pCmd
);
877 static void tclCollateNeeded(
883 SqliteDb
*pDb
= (SqliteDb
*)pCtx
;
884 Tcl_Obj
*pScript
= Tcl_DuplicateObj(pDb
->pCollateNeeded
);
885 Tcl_IncrRefCount(pScript
);
886 Tcl_ListObjAppendElement(0, pScript
, Tcl_NewStringObj(zName
, -1));
887 Tcl_EvalObjEx(pDb
->interp
, pScript
, 0);
888 Tcl_DecrRefCount(pScript
);
892 ** This routine is called to evaluate an SQL collation function implemented
895 static int tclSqlCollate(
902 SqlCollate
*p
= (SqlCollate
*)pCtx
;
905 pCmd
= Tcl_NewStringObj(p
->zScript
, -1);
906 Tcl_IncrRefCount(pCmd
);
907 Tcl_ListObjAppendElement(p
->interp
, pCmd
, Tcl_NewStringObj(zA
, nA
));
908 Tcl_ListObjAppendElement(p
->interp
, pCmd
, Tcl_NewStringObj(zB
, nB
));
909 Tcl_EvalObjEx(p
->interp
, pCmd
, TCL_EVAL_DIRECT
);
910 Tcl_DecrRefCount(pCmd
);
911 return (atoi(Tcl_GetStringResult(p
->interp
)));
915 ** This routine is called to evaluate an SQL function implemented
918 static void tclSqlFunc(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
){
919 SqlFunc
*p
= sqlite3_user_data(context
);
925 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
926 ** script object directly. This allows the TCL compiler to generate
927 ** bytecode for the command on the first invocation and thus make
928 ** subsequent invocations much faster. */
930 Tcl_IncrRefCount(pCmd
);
931 rc
= Tcl_EvalObjEx(p
->interp
, pCmd
, 0);
932 Tcl_DecrRefCount(pCmd
);
934 /* If there are arguments to the function, make a shallow copy of the
935 ** script object, lappend the arguments, then evaluate the copy.
937 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
938 ** The new Tcl_Obj contains pointers to the original list elements.
939 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
940 ** of the list to tclCmdNameType, that alternate representation will
941 ** be preserved and reused on the next invocation.
945 if( Tcl_ListObjGetElements(p
->interp
, p
->pScript
, &nArg
, &aArg
) ){
946 sqlite3_result_error(context
, Tcl_GetStringResult(p
->interp
), -1);
949 pCmd
= Tcl_NewListObj(nArg
, aArg
);
950 Tcl_IncrRefCount(pCmd
);
951 for(i
=0; i
<argc
; i
++){
952 sqlite3_value
*pIn
= argv
[i
];
955 /* Set pVal to contain the i'th column of this row. */
956 switch( sqlite3_value_type(pIn
) ){
958 int bytes
= sqlite3_value_bytes(pIn
);
959 pVal
= Tcl_NewByteArrayObj(sqlite3_value_blob(pIn
), bytes
);
962 case SQLITE_INTEGER
: {
963 sqlite_int64 v
= sqlite3_value_int64(pIn
);
964 if( v
>=-2147483647 && v
<=2147483647 ){
965 pVal
= Tcl_NewIntObj((int)v
);
967 pVal
= Tcl_NewWideIntObj(v
);
972 double r
= sqlite3_value_double(pIn
);
973 pVal
= Tcl_NewDoubleObj(r
);
977 pVal
= Tcl_NewStringObj(p
->pDb
->zNull
, -1);
981 int bytes
= sqlite3_value_bytes(pIn
);
982 pVal
= Tcl_NewStringObj((char *)sqlite3_value_text(pIn
), bytes
);
986 rc
= Tcl_ListObjAppendElement(p
->interp
, pCmd
, pVal
);
988 Tcl_DecrRefCount(pCmd
);
989 sqlite3_result_error(context
, Tcl_GetStringResult(p
->interp
), -1);
993 if( !p
->useEvalObjv
){
994 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
995 ** is a list without a string representation. To prevent this from
996 ** happening, make sure pCmd has a valid string representation */
999 rc
= Tcl_EvalObjEx(p
->interp
, pCmd
, TCL_EVAL_DIRECT
);
1000 Tcl_DecrRefCount(pCmd
);
1003 if( rc
&& rc
!=TCL_RETURN
){
1004 sqlite3_result_error(context
, Tcl_GetStringResult(p
->interp
), -1);
1006 Tcl_Obj
*pVar
= Tcl_GetObjResult(p
->interp
);
1009 const char *zType
= (pVar
->typePtr
? pVar
->typePtr
->name
: "");
1011 int eType
= p
->eType
;
1013 if( eType
==SQLITE_NULL
){
1014 if( c
=='b' && strcmp(zType
,"bytearray")==0 && pVar
->bytes
==0 ){
1015 /* Only return a BLOB type if the Tcl variable is a bytearray and
1016 ** has no string representation. */
1017 eType
= SQLITE_BLOB
;
1018 }else if( (c
=='b' && strcmp(zType
,"boolean")==0)
1019 || (c
=='w' && strcmp(zType
,"wideInt")==0)
1020 || (c
=='i' && strcmp(zType
,"int")==0)
1022 eType
= SQLITE_INTEGER
;
1023 }else if( c
=='d' && strcmp(zType
,"double")==0 ){
1024 eType
= SQLITE_FLOAT
;
1026 eType
= SQLITE_TEXT
;
1032 data
= Tcl_GetByteArrayFromObj(pVar
, &n
);
1033 sqlite3_result_blob(context
, data
, n
, SQLITE_TRANSIENT
);
1036 case SQLITE_INTEGER
: {
1038 if( TCL_OK
==Tcl_GetWideIntFromObj(0, pVar
, &v
) ){
1039 sqlite3_result_int64(context
, v
);
1044 case SQLITE_FLOAT
: {
1046 if( TCL_OK
==Tcl_GetDoubleFromObj(0, pVar
, &r
) ){
1047 sqlite3_result_double(context
, r
);
1053 data
= (unsigned char *)Tcl_GetStringFromObj(pVar
, &n
);
1054 sqlite3_result_text(context
, (char *)data
, n
, SQLITE_TRANSIENT
);
1062 #ifndef SQLITE_OMIT_AUTHORIZATION
1064 ** This is the authentication function. It appends the authentication
1065 ** type code and the two arguments to zCmd[] then invokes the result
1066 ** on the interpreter. The reply is examined to determine if the
1067 ** authentication fails or succeeds.
1069 static int auth_callback(
1076 #ifdef SQLITE_USER_AUTHENTICATION
1084 /* EVIDENCE-OF: R-38590-62769 The first parameter to the authorizer
1085 ** callback is a copy of the third parameter to the
1086 ** sqlite3_set_authorizer() interface.
1088 SqliteDb
*pDb
= (SqliteDb
*)pArg
;
1089 if( pDb
->disableAuth
) return SQLITE_OK
;
1091 /* EVIDENCE-OF: R-56518-44310 The second parameter to the callback is an
1092 ** integer action code that specifies the particular action to be
1095 case SQLITE_COPY
: zCode
="SQLITE_COPY"; break;
1096 case SQLITE_CREATE_INDEX
: zCode
="SQLITE_CREATE_INDEX"; break;
1097 case SQLITE_CREATE_TABLE
: zCode
="SQLITE_CREATE_TABLE"; break;
1098 case SQLITE_CREATE_TEMP_INDEX
: zCode
="SQLITE_CREATE_TEMP_INDEX"; break;
1099 case SQLITE_CREATE_TEMP_TABLE
: zCode
="SQLITE_CREATE_TEMP_TABLE"; break;
1100 case SQLITE_CREATE_TEMP_TRIGGER
: zCode
="SQLITE_CREATE_TEMP_TRIGGER"; break;
1101 case SQLITE_CREATE_TEMP_VIEW
: zCode
="SQLITE_CREATE_TEMP_VIEW"; break;
1102 case SQLITE_CREATE_TRIGGER
: zCode
="SQLITE_CREATE_TRIGGER"; break;
1103 case SQLITE_CREATE_VIEW
: zCode
="SQLITE_CREATE_VIEW"; break;
1104 case SQLITE_DELETE
: zCode
="SQLITE_DELETE"; break;
1105 case SQLITE_DROP_INDEX
: zCode
="SQLITE_DROP_INDEX"; break;
1106 case SQLITE_DROP_TABLE
: zCode
="SQLITE_DROP_TABLE"; break;
1107 case SQLITE_DROP_TEMP_INDEX
: zCode
="SQLITE_DROP_TEMP_INDEX"; break;
1108 case SQLITE_DROP_TEMP_TABLE
: zCode
="SQLITE_DROP_TEMP_TABLE"; break;
1109 case SQLITE_DROP_TEMP_TRIGGER
: zCode
="SQLITE_DROP_TEMP_TRIGGER"; break;
1110 case SQLITE_DROP_TEMP_VIEW
: zCode
="SQLITE_DROP_TEMP_VIEW"; break;
1111 case SQLITE_DROP_TRIGGER
: zCode
="SQLITE_DROP_TRIGGER"; break;
1112 case SQLITE_DROP_VIEW
: zCode
="SQLITE_DROP_VIEW"; break;
1113 case SQLITE_INSERT
: zCode
="SQLITE_INSERT"; break;
1114 case SQLITE_PRAGMA
: zCode
="SQLITE_PRAGMA"; break;
1115 case SQLITE_READ
: zCode
="SQLITE_READ"; break;
1116 case SQLITE_SELECT
: zCode
="SQLITE_SELECT"; break;
1117 case SQLITE_TRANSACTION
: zCode
="SQLITE_TRANSACTION"; break;
1118 case SQLITE_UPDATE
: zCode
="SQLITE_UPDATE"; break;
1119 case SQLITE_ATTACH
: zCode
="SQLITE_ATTACH"; break;
1120 case SQLITE_DETACH
: zCode
="SQLITE_DETACH"; break;
1121 case SQLITE_ALTER_TABLE
: zCode
="SQLITE_ALTER_TABLE"; break;
1122 case SQLITE_REINDEX
: zCode
="SQLITE_REINDEX"; break;
1123 case SQLITE_ANALYZE
: zCode
="SQLITE_ANALYZE"; break;
1124 case SQLITE_CREATE_VTABLE
: zCode
="SQLITE_CREATE_VTABLE"; break;
1125 case SQLITE_DROP_VTABLE
: zCode
="SQLITE_DROP_VTABLE"; break;
1126 case SQLITE_FUNCTION
: zCode
="SQLITE_FUNCTION"; break;
1127 case SQLITE_SAVEPOINT
: zCode
="SQLITE_SAVEPOINT"; break;
1128 case SQLITE_RECURSIVE
: zCode
="SQLITE_RECURSIVE"; break;
1129 default : zCode
="????"; break;
1131 Tcl_DStringInit(&str
);
1132 Tcl_DStringAppend(&str
, pDb
->zAuth
, -1);
1133 Tcl_DStringAppendElement(&str
, zCode
);
1134 Tcl_DStringAppendElement(&str
, zArg1
? zArg1
: "");
1135 Tcl_DStringAppendElement(&str
, zArg2
? zArg2
: "");
1136 Tcl_DStringAppendElement(&str
, zArg3
? zArg3
: "");
1137 Tcl_DStringAppendElement(&str
, zArg4
? zArg4
: "");
1138 #ifdef SQLITE_USER_AUTHENTICATION
1139 Tcl_DStringAppendElement(&str
, zArg5
? zArg5
: "");
1141 rc
= Tcl_GlobalEval(pDb
->interp
, Tcl_DStringValue(&str
));
1142 Tcl_DStringFree(&str
);
1143 zReply
= rc
==TCL_OK
? Tcl_GetStringResult(pDb
->interp
) : "SQLITE_DENY";
1144 if( strcmp(zReply
,"SQLITE_OK")==0 ){
1146 }else if( strcmp(zReply
,"SQLITE_DENY")==0 ){
1148 }else if( strcmp(zReply
,"SQLITE_IGNORE")==0 ){
1155 #endif /* SQLITE_OMIT_AUTHORIZATION */
1158 ** This routine reads a line of text from FILE in, stores
1159 ** the text in memory obtained from malloc() and returns a pointer
1160 ** to the text. NULL is returned at end of file, or if malloc()
1163 ** The interface is like "readline" but no command-line editing
1166 ** copied from shell.c from '.import' command
1168 static char *local_getline(char *zPrompt
, FILE *in
){
1174 zLine
= malloc( nLine
);
1175 if( zLine
==0 ) return 0;
1179 nLine
= nLine
*2 + 100;
1180 zLine
= realloc(zLine
, nLine
);
1181 if( zLine
==0 ) return 0;
1183 if( fgets(&zLine
[n
], nLine
- n
, in
)==0 ){
1191 while( zLine
[n
] ){ n
++; }
1192 if( n
>0 && zLine
[n
-1]=='\n' ){
1198 zLine
= realloc( zLine
, n
+1 );
1204 ** This function is part of the implementation of the command:
1206 ** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1208 ** It is invoked after evaluating the script SCRIPT to commit or rollback
1209 ** the transaction or savepoint opened by the [transaction] command.
1211 static int SQLITE_TCLAPI
DbTransPostCmd(
1212 ClientData data
[], /* data[0] is the Sqlite3Db* for $db */
1213 Tcl_Interp
*interp
, /* Tcl interpreter */
1214 int result
/* Result of evaluating SCRIPT */
1216 static const char *const azEnd
[] = {
1217 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1218 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1219 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1220 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1222 SqliteDb
*pDb
= (SqliteDb
*)data
[0];
1226 pDb
->nTransaction
--;
1227 zEnd
= azEnd
[(rc
==TCL_ERROR
)*2 + (pDb
->nTransaction
==0)];
1230 if( sqlite3_exec(pDb
->db
, zEnd
, 0, 0, 0) ){
1231 /* This is a tricky scenario to handle. The most likely cause of an
1232 ** error is that the exec() above was an attempt to commit the
1233 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1234 ** that an IO-error has occurred. In either case, throw a Tcl exception
1235 ** and try to rollback the transaction.
1237 ** But it could also be that the user executed one or more BEGIN,
1238 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1239 ** this method's logic. Not clear how this would be best handled.
1241 if( rc
!=TCL_ERROR
){
1242 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
1245 sqlite3_exec(pDb
->db
, "ROLLBACK", 0, 0, 0);
1253 ** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1254 ** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1255 ** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1256 ** on whether or not the [db_use_legacy_prepare] command has been used to
1257 ** configure the connection.
1259 static int dbPrepare(
1260 SqliteDb
*pDb
, /* Database object */
1261 const char *zSql
, /* SQL to compile */
1262 sqlite3_stmt
**ppStmt
, /* OUT: Prepared statement */
1263 const char **pzOut
/* OUT: Pointer to next SQL statement */
1265 unsigned int prepFlags
= 0;
1267 if( pDb
->bLegacyPrepare
){
1268 return sqlite3_prepare(pDb
->db
, zSql
, -1, ppStmt
, pzOut
);
1271 /* If the statement cache is large, use the SQLITE_PREPARE_PERSISTENT
1272 ** flags, which uses less lookaside memory. But if the cache is small,
1273 ** omit that flag to make full use of lookaside */
1274 if( pDb
->maxStmt
>5 ) prepFlags
= SQLITE_PREPARE_PERSISTENT
;
1276 return sqlite3_prepare_v3(pDb
->db
, zSql
, -1, prepFlags
, ppStmt
, pzOut
);
1280 ** Search the cache for a prepared-statement object that implements the
1281 ** first SQL statement in the buffer pointed to by parameter zIn. If
1282 ** no such prepared-statement can be found, allocate and prepare a new
1283 ** one. In either case, bind the current values of the relevant Tcl
1284 ** variables to any $var, :var or @var variables in the statement. Before
1285 ** returning, set *ppPreStmt to point to the prepared-statement object.
1287 ** Output parameter *pzOut is set to point to the next SQL statement in
1288 ** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1291 ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1292 ** and an error message loaded into interpreter pDb->interp.
1294 static int dbPrepareAndBind(
1295 SqliteDb
*pDb
, /* Database object */
1296 char const *zIn
, /* SQL to compile */
1297 char const **pzOut
, /* OUT: Pointer to next SQL statement */
1298 SqlPreparedStmt
**ppPreStmt
/* OUT: Object used to cache statement */
1300 const char *zSql
= zIn
; /* Pointer to first SQL statement in zIn */
1301 sqlite3_stmt
*pStmt
= 0; /* Prepared statement object */
1302 SqlPreparedStmt
*pPreStmt
; /* Pointer to cached statement */
1303 int nSql
; /* Length of zSql in bytes */
1304 int nVar
= 0; /* Number of variables in statement */
1305 int iParm
= 0; /* Next free entry in apParm */
1308 int needResultReset
= 0; /* Need to invoke Tcl_ResetResult() */
1309 int rc
= SQLITE_OK
; /* Value to return */
1310 Tcl_Interp
*interp
= pDb
->interp
;
1314 /* Trim spaces from the start of zSql and calculate the remaining length. */
1315 while( (c
= zSql
[0])==' ' || c
=='\t' || c
=='\r' || c
=='\n' ){ zSql
++; }
1316 nSql
= strlen30(zSql
);
1318 for(pPreStmt
= pDb
->stmtList
; pPreStmt
; pPreStmt
=pPreStmt
->pNext
){
1319 int n
= pPreStmt
->nSql
;
1321 && memcmp(pPreStmt
->zSql
, zSql
, n
)==0
1322 && (zSql
[n
]==0 || zSql
[n
-1]==';')
1324 pStmt
= pPreStmt
->pStmt
;
1325 *pzOut
= &zSql
[pPreStmt
->nSql
];
1327 /* When a prepared statement is found, unlink it from the
1328 ** cache list. It will later be added back to the beginning
1329 ** of the cache list in order to implement LRU replacement.
1331 if( pPreStmt
->pPrev
){
1332 pPreStmt
->pPrev
->pNext
= pPreStmt
->pNext
;
1334 pDb
->stmtList
= pPreStmt
->pNext
;
1336 if( pPreStmt
->pNext
){
1337 pPreStmt
->pNext
->pPrev
= pPreStmt
->pPrev
;
1339 pDb
->stmtLast
= pPreStmt
->pPrev
;
1342 nVar
= sqlite3_bind_parameter_count(pStmt
);
1347 /* If no prepared statement was found. Compile the SQL text. Also allocate
1348 ** a new SqlPreparedStmt structure. */
1352 if( SQLITE_OK
!=dbPrepare(pDb
, zSql
, &pStmt
, pzOut
) ){
1353 Tcl_SetObjResult(interp
, Tcl_NewStringObj(sqlite3_errmsg(pDb
->db
), -1));
1357 if( SQLITE_OK
!=sqlite3_errcode(pDb
->db
) ){
1358 /* A compile-time error in the statement. */
1359 Tcl_SetObjResult(interp
, Tcl_NewStringObj(sqlite3_errmsg(pDb
->db
), -1));
1362 /* The statement was a no-op. Continue to the next statement
1363 ** in the SQL string.
1369 assert( pPreStmt
==0 );
1370 nVar
= sqlite3_bind_parameter_count(pStmt
);
1371 nByte
= sizeof(SqlPreparedStmt
) + nVar
*sizeof(Tcl_Obj
*);
1372 pPreStmt
= (SqlPreparedStmt
*)Tcl_Alloc(nByte
);
1373 memset(pPreStmt
, 0, nByte
);
1375 pPreStmt
->pStmt
= pStmt
;
1376 pPreStmt
->nSql
= (int)(*pzOut
- zSql
);
1377 pPreStmt
->zSql
= sqlite3_sql(pStmt
);
1378 pPreStmt
->apParm
= (Tcl_Obj
**)&pPreStmt
[1];
1380 if( pPreStmt
->zSql
==0 ){
1381 char *zCopy
= Tcl_Alloc(pPreStmt
->nSql
+ 1);
1382 memcpy(zCopy
, zSql
, pPreStmt
->nSql
);
1383 zCopy
[pPreStmt
->nSql
] = '\0';
1384 pPreStmt
->zSql
= zCopy
;
1389 assert( strlen30(pPreStmt
->zSql
)==pPreStmt
->nSql
);
1390 assert( 0==memcmp(pPreStmt
->zSql
, zSql
, pPreStmt
->nSql
) );
1392 /* Bind values to parameters that begin with $ or : */
1393 for(i
=1; i
<=nVar
; i
++){
1394 const char *zVar
= sqlite3_bind_parameter_name(pStmt
, i
);
1395 if( zVar
!=0 && (zVar
[0]=='$' || zVar
[0]==':' || zVar
[0]=='@') ){
1396 Tcl_Obj
*pVar
= Tcl_GetVar2Ex(interp
, &zVar
[1], 0, 0);
1397 if( pVar
==0 && pDb
->zBindFallback
!=0 ){
1400 pCmd
= Tcl_NewStringObj(pDb
->zBindFallback
, -1);
1401 Tcl_IncrRefCount(pCmd
);
1402 Tcl_ListObjAppendElement(interp
, pCmd
, Tcl_NewStringObj(zVar
,-1));
1403 if( needResultReset
) Tcl_ResetResult(interp
);
1404 needResultReset
= 1;
1405 rx
= Tcl_EvalObjEx(interp
, pCmd
, TCL_EVAL_DIRECT
);
1406 Tcl_DecrRefCount(pCmd
);
1408 pVar
= Tcl_GetObjResult(interp
);
1409 }else if( rx
==TCL_ERROR
){
1419 const char *zType
= (pVar
->typePtr
? pVar
->typePtr
->name
: "");
1422 (c
=='b' && strcmp(zType
,"bytearray")==0 && pVar
->bytes
==0) ){
1423 /* Load a BLOB type if the Tcl variable is a bytearray and
1424 ** it has no string representation or the host
1425 ** parameter name begins with "@". */
1426 data
= Tcl_GetByteArrayFromObj(pVar
, &n
);
1427 sqlite3_bind_blob(pStmt
, i
, data
, n
, SQLITE_STATIC
);
1428 Tcl_IncrRefCount(pVar
);
1429 pPreStmt
->apParm
[iParm
++] = pVar
;
1430 }else if( c
=='b' && strcmp(zType
,"boolean")==0 ){
1431 Tcl_GetIntFromObj(interp
, pVar
, &n
);
1432 sqlite3_bind_int(pStmt
, i
, n
);
1433 }else if( c
=='d' && strcmp(zType
,"double")==0 ){
1435 Tcl_GetDoubleFromObj(interp
, pVar
, &r
);
1436 sqlite3_bind_double(pStmt
, i
, r
);
1437 }else if( (c
=='w' && strcmp(zType
,"wideInt")==0) ||
1438 (c
=='i' && strcmp(zType
,"int")==0) ){
1440 Tcl_GetWideIntFromObj(interp
, pVar
, &v
);
1441 sqlite3_bind_int64(pStmt
, i
, v
);
1443 data
= (unsigned char *)Tcl_GetStringFromObj(pVar
, &n
);
1444 sqlite3_bind_text(pStmt
, i
, (char *)data
, n
, SQLITE_STATIC
);
1445 Tcl_IncrRefCount(pVar
);
1446 pPreStmt
->apParm
[iParm
++] = pVar
;
1449 sqlite3_bind_null(pStmt
, i
);
1451 if( needResultReset
) Tcl_ResetResult(pDb
->interp
);
1454 pPreStmt
->nParm
= iParm
;
1455 *ppPreStmt
= pPreStmt
;
1456 if( needResultReset
&& rc
==TCL_OK
) Tcl_ResetResult(pDb
->interp
);
1462 ** Release a statement reference obtained by calling dbPrepareAndBind().
1463 ** There should be exactly one call to this function for each call to
1464 ** dbPrepareAndBind().
1466 ** If the discard parameter is non-zero, then the statement is deleted
1467 ** immediately. Otherwise it is added to the LRU list and may be returned
1468 ** by a subsequent call to dbPrepareAndBind().
1470 static void dbReleaseStmt(
1471 SqliteDb
*pDb
, /* Database handle */
1472 SqlPreparedStmt
*pPreStmt
, /* Prepared statement handle to release */
1473 int discard
/* True to delete (not cache) the pPreStmt */
1477 /* Free the bound string and blob parameters */
1478 for(i
=0; i
<pPreStmt
->nParm
; i
++){
1479 Tcl_DecrRefCount(pPreStmt
->apParm
[i
]);
1481 pPreStmt
->nParm
= 0;
1483 if( pDb
->maxStmt
<=0 || discard
){
1484 /* If the cache is turned off, deallocated the statement */
1485 dbFreeStmt(pPreStmt
);
1487 /* Add the prepared statement to the beginning of the cache list. */
1488 pPreStmt
->pNext
= pDb
->stmtList
;
1489 pPreStmt
->pPrev
= 0;
1490 if( pDb
->stmtList
){
1491 pDb
->stmtList
->pPrev
= pPreStmt
;
1493 pDb
->stmtList
= pPreStmt
;
1494 if( pDb
->stmtLast
==0 ){
1495 assert( pDb
->nStmt
==0 );
1496 pDb
->stmtLast
= pPreStmt
;
1498 assert( pDb
->nStmt
>0 );
1502 /* If we have too many statement in cache, remove the surplus from
1503 ** the end of the cache list. */
1504 while( pDb
->nStmt
>pDb
->maxStmt
){
1505 SqlPreparedStmt
*pLast
= pDb
->stmtLast
;
1506 pDb
->stmtLast
= pLast
->pPrev
;
1507 pDb
->stmtLast
->pNext
= 0;
1515 ** Structure used with dbEvalXXX() functions:
1521 ** dbEvalColumnValue()
1523 typedef struct DbEvalContext DbEvalContext
;
1524 struct DbEvalContext
{
1525 SqliteDb
*pDb
; /* Database handle */
1526 Tcl_Obj
*pSql
; /* Object holding string zSql */
1527 const char *zSql
; /* Remaining SQL to execute */
1528 SqlPreparedStmt
*pPreStmt
; /* Current statement */
1529 int nCol
; /* Number of columns returned by pStmt */
1530 int evalFlags
; /* Flags used */
1531 Tcl_Obj
*pArray
; /* Name of array variable */
1532 Tcl_Obj
**apColName
; /* Array of column names */
1535 #define SQLITE_EVAL_WITHOUTNULLS 0x00001 /* Unset array(*) for NULL */
1538 ** Release any cache of column names currently held as part of
1539 ** the DbEvalContext structure passed as the first argument.
1541 static void dbReleaseColumnNames(DbEvalContext
*p
){
1544 for(i
=0; i
<p
->nCol
; i
++){
1545 Tcl_DecrRefCount(p
->apColName
[i
]);
1547 Tcl_Free((char *)p
->apColName
);
1554 ** Initialize a DbEvalContext structure.
1556 ** If pArray is not NULL, then it contains the name of a Tcl array
1557 ** variable. The "*" member of this array is set to a list containing
1558 ** the names of the columns returned by the statement as part of each
1559 ** call to dbEvalStep(), in order from left to right. e.g. if the names
1560 ** of the returned columns are a, b and c, it does the equivalent of the
1563 ** set ${pArray}(*) {a b c}
1565 static void dbEvalInit(
1566 DbEvalContext
*p
, /* Pointer to structure to initialize */
1567 SqliteDb
*pDb
, /* Database handle */
1568 Tcl_Obj
*pSql
, /* Object containing SQL script */
1569 Tcl_Obj
*pArray
, /* Name of Tcl array to set (*) element of */
1570 int evalFlags
/* Flags controlling evaluation */
1572 memset(p
, 0, sizeof(DbEvalContext
));
1574 p
->zSql
= Tcl_GetString(pSql
);
1576 Tcl_IncrRefCount(pSql
);
1579 Tcl_IncrRefCount(pArray
);
1581 p
->evalFlags
= evalFlags
;
1585 ** Obtain information about the row that the DbEvalContext passed as the
1586 ** first argument currently points to.
1588 static void dbEvalRowInfo(
1589 DbEvalContext
*p
, /* Evaluation context */
1590 int *pnCol
, /* OUT: Number of column names */
1591 Tcl_Obj
***papColName
/* OUT: Array of column names */
1593 /* Compute column names */
1594 if( 0==p
->apColName
){
1595 sqlite3_stmt
*pStmt
= p
->pPreStmt
->pStmt
;
1596 int i
; /* Iterator variable */
1597 int nCol
; /* Number of columns returned by pStmt */
1598 Tcl_Obj
**apColName
= 0; /* Array of column names */
1600 p
->nCol
= nCol
= sqlite3_column_count(pStmt
);
1601 if( nCol
>0 && (papColName
|| p
->pArray
) ){
1602 apColName
= (Tcl_Obj
**)Tcl_Alloc( sizeof(Tcl_Obj
*)*nCol
);
1603 for(i
=0; i
<nCol
; i
++){
1604 apColName
[i
] = Tcl_NewStringObj(sqlite3_column_name(pStmt
,i
), -1);
1605 Tcl_IncrRefCount(apColName
[i
]);
1607 p
->apColName
= apColName
;
1610 /* If results are being stored in an array variable, then create
1611 ** the array(*) entry for that array
1614 Tcl_Interp
*interp
= p
->pDb
->interp
;
1615 Tcl_Obj
*pColList
= Tcl_NewObj();
1616 Tcl_Obj
*pStar
= Tcl_NewStringObj("*", -1);
1618 for(i
=0; i
<nCol
; i
++){
1619 Tcl_ListObjAppendElement(interp
, pColList
, apColName
[i
]);
1621 Tcl_IncrRefCount(pStar
);
1622 Tcl_ObjSetVar2(interp
, p
->pArray
, pStar
, pColList
, 0);
1623 Tcl_DecrRefCount(pStar
);
1628 *papColName
= p
->apColName
;
1636 ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1637 ** returned, then an error message is stored in the interpreter before
1640 ** A return value of TCL_OK means there is a row of data available. The
1641 ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1642 ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1643 ** is returned, then the SQL script has finished executing and there are
1644 ** no further rows available. This is similar to SQLITE_DONE.
1646 static int dbEvalStep(DbEvalContext
*p
){
1647 const char *zPrevSql
= 0; /* Previous value of p->zSql */
1649 while( p
->zSql
[0] || p
->pPreStmt
){
1651 if( p
->pPreStmt
==0 ){
1652 zPrevSql
= (p
->zSql
==zPrevSql
? 0 : p
->zSql
);
1653 rc
= dbPrepareAndBind(p
->pDb
, p
->zSql
, &p
->zSql
, &p
->pPreStmt
);
1654 if( rc
!=TCL_OK
) return rc
;
1657 SqliteDb
*pDb
= p
->pDb
;
1658 SqlPreparedStmt
*pPreStmt
= p
->pPreStmt
;
1659 sqlite3_stmt
*pStmt
= pPreStmt
->pStmt
;
1661 rcs
= sqlite3_step(pStmt
);
1662 if( rcs
==SQLITE_ROW
){
1666 dbEvalRowInfo(p
, 0, 0);
1668 rcs
= sqlite3_reset(pStmt
);
1670 pDb
->nStep
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_FULLSCAN_STEP
,1);
1671 pDb
->nSort
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_SORT
,1);
1672 pDb
->nIndex
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_AUTOINDEX
,1);
1673 pDb
->nVMStep
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_VM_STEP
,1);
1674 dbReleaseColumnNames(p
);
1677 if( rcs
!=SQLITE_OK
){
1678 /* If a run-time error occurs, report the error and stop reading
1680 dbReleaseStmt(pDb
, pPreStmt
, 1);
1682 if( p
->pDb
->bLegacyPrepare
&& rcs
==SQLITE_SCHEMA
&& zPrevSql
){
1683 /* If the runtime error was an SQLITE_SCHEMA, and the database
1684 ** handle is configured to use the legacy sqlite3_prepare()
1685 ** interface, retry prepare()/step() on the same SQL statement.
1686 ** This only happens once. If there is a second SQLITE_SCHEMA
1687 ** error, the error will be returned to the caller. */
1692 Tcl_SetObjResult(pDb
->interp
,
1693 Tcl_NewStringObj(sqlite3_errmsg(pDb
->db
), -1));
1696 dbReleaseStmt(pDb
, pPreStmt
, 0);
1706 ** Free all resources currently held by the DbEvalContext structure passed
1707 ** as the first argument. There should be exactly one call to this function
1708 ** for each call to dbEvalInit().
1710 static void dbEvalFinalize(DbEvalContext
*p
){
1712 sqlite3_reset(p
->pPreStmt
->pStmt
);
1713 dbReleaseStmt(p
->pDb
, p
->pPreStmt
, 0);
1717 Tcl_DecrRefCount(p
->pArray
);
1720 Tcl_DecrRefCount(p
->pSql
);
1721 dbReleaseColumnNames(p
);
1725 ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1726 ** the value for the iCol'th column of the row currently pointed to by
1727 ** the DbEvalContext structure passed as the first argument.
1729 static Tcl_Obj
*dbEvalColumnValue(DbEvalContext
*p
, int iCol
){
1730 sqlite3_stmt
*pStmt
= p
->pPreStmt
->pStmt
;
1731 switch( sqlite3_column_type(pStmt
, iCol
) ){
1733 int bytes
= sqlite3_column_bytes(pStmt
, iCol
);
1734 const char *zBlob
= sqlite3_column_blob(pStmt
, iCol
);
1735 if( !zBlob
) bytes
= 0;
1736 return Tcl_NewByteArrayObj((u8
*)zBlob
, bytes
);
1738 case SQLITE_INTEGER
: {
1739 sqlite_int64 v
= sqlite3_column_int64(pStmt
, iCol
);
1740 if( v
>=-2147483647 && v
<=2147483647 ){
1741 return Tcl_NewIntObj((int)v
);
1743 return Tcl_NewWideIntObj(v
);
1746 case SQLITE_FLOAT
: {
1747 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt
, iCol
));
1750 return Tcl_NewStringObj(p
->pDb
->zNull
, -1);
1754 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt
, iCol
), -1);
1758 ** If using Tcl version 8.6 or greater, use the NR functions to avoid
1759 ** recursive evalution of scripts by the [db eval] and [db trans]
1760 ** commands. Even if the headers used while compiling the extension
1761 ** are 8.6 or newer, the code still tests the Tcl version at runtime.
1762 ** This allows stubs-enabled builds to be used with older Tcl libraries.
1764 #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
1765 # define SQLITE_TCL_NRE 1
1766 static int DbUseNre(void){
1768 Tcl_GetVersion(&major
, &minor
, 0, 0);
1769 return( (major
==8 && minor
>=6) || major
>8 );
1773 ** Compiling using headers earlier than 8.6. In this case NR cannot be
1774 ** used, so DbUseNre() to always return zero. Add #defines for the other
1775 ** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1776 ** even though the only invocations of them are within conditional blocks
1779 ** if( DbUseNre() ) { ... }
1781 # define SQLITE_TCL_NRE 0
1782 # define DbUseNre() 0
1783 # define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
1784 # define Tcl_NREvalObj(a,b,c) 0
1785 # define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
1789 ** This function is part of the implementation of the command:
1791 ** $db eval SQL ?ARRAYNAME? SCRIPT
1793 static int SQLITE_TCLAPI
DbEvalNextCmd(
1794 ClientData data
[], /* data[0] is the (DbEvalContext*) */
1795 Tcl_Interp
*interp
, /* Tcl interpreter */
1796 int result
/* Result so far */
1798 int rc
= result
; /* Return code */
1800 /* The first element of the data[] array is a pointer to a DbEvalContext
1801 ** structure allocated using Tcl_Alloc(). The second element of data[]
1802 ** is a pointer to a Tcl_Obj containing the script to run for each row
1803 ** returned by the queries encapsulated in data[0]. */
1804 DbEvalContext
*p
= (DbEvalContext
*)data
[0];
1805 Tcl_Obj
*pScript
= (Tcl_Obj
*)data
[1];
1806 Tcl_Obj
*pArray
= p
->pArray
;
1808 while( (rc
==TCL_OK
|| rc
==TCL_CONTINUE
) && TCL_OK
==(rc
= dbEvalStep(p
)) ){
1811 Tcl_Obj
**apColName
;
1812 dbEvalRowInfo(p
, &nCol
, &apColName
);
1813 for(i
=0; i
<nCol
; i
++){
1815 Tcl_ObjSetVar2(interp
, apColName
[i
], 0, dbEvalColumnValue(p
,i
), 0);
1816 }else if( (p
->evalFlags
& SQLITE_EVAL_WITHOUTNULLS
)!=0
1817 && sqlite3_column_type(p
->pPreStmt
->pStmt
, i
)==SQLITE_NULL
1819 Tcl_UnsetVar2(interp
, Tcl_GetString(pArray
),
1820 Tcl_GetString(apColName
[i
]), 0);
1822 Tcl_ObjSetVar2(interp
, pArray
, apColName
[i
], dbEvalColumnValue(p
,i
), 0);
1826 /* The required interpreter variables are now populated with the data
1827 ** from the current row. If using NRE, schedule callbacks to evaluate
1828 ** script pScript, then to invoke this function again to fetch the next
1829 ** row (or clean up if there is no next row or the script throws an
1830 ** exception). After scheduling the callbacks, return control to the
1833 ** If not using NRE, evaluate pScript directly and continue with the
1834 ** next iteration of this while(...) loop. */
1836 Tcl_NRAddCallback(interp
, DbEvalNextCmd
, (void*)p
, (void*)pScript
, 0, 0);
1837 return Tcl_NREvalObj(interp
, pScript
, 0);
1839 rc
= Tcl_EvalObjEx(interp
, pScript
, 0);
1843 Tcl_DecrRefCount(pScript
);
1845 Tcl_Free((char *)p
);
1847 if( rc
==TCL_OK
|| rc
==TCL_BREAK
){
1848 Tcl_ResetResult(interp
);
1855 ** This function is used by the implementations of the following database
1856 ** handle sub-commands:
1858 ** $db update_hook ?SCRIPT?
1859 ** $db wal_hook ?SCRIPT?
1860 ** $db commit_hook ?SCRIPT?
1861 ** $db preupdate hook ?SCRIPT?
1863 static void DbHookCmd(
1864 Tcl_Interp
*interp
, /* Tcl interpreter */
1865 SqliteDb
*pDb
, /* Database handle */
1866 Tcl_Obj
*pArg
, /* SCRIPT argument (or NULL) */
1867 Tcl_Obj
**ppHook
/* Pointer to member of SqliteDb */
1869 sqlite3
*db
= pDb
->db
;
1872 Tcl_SetObjResult(interp
, *ppHook
);
1874 Tcl_DecrRefCount(*ppHook
);
1879 assert( !(*ppHook
) );
1880 if( Tcl_GetCharLength(pArg
)>0 ){
1882 Tcl_IncrRefCount(*ppHook
);
1886 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1887 sqlite3_preupdate_hook(db
, (pDb
->pPreUpdateHook
?DbPreUpdateHandler
:0), pDb
);
1889 sqlite3_update_hook(db
, (pDb
->pUpdateHook
?DbUpdateHandler
:0), pDb
);
1890 sqlite3_rollback_hook(db
, (pDb
->pRollbackHook
?DbRollbackHandler
:0), pDb
);
1891 sqlite3_wal_hook(db
, (pDb
->pWalHook
?DbWalHandler
:0), pDb
);
1895 ** The "sqlite" command below creates a new Tcl command for each
1896 ** connection it opens to an SQLite database. This routine is invoked
1897 ** whenever one of those connection-specific commands is executed
1898 ** in Tcl. For example, if you run Tcl code like this:
1900 ** sqlite3 db1 "my_database"
1903 ** The first command opens a connection to the "my_database" database
1904 ** and calls that connection "db1". The second command causes this
1905 ** subroutine to be invoked.
1907 static int SQLITE_TCLAPI
DbObjCmd(
1913 SqliteDb
*pDb
= (SqliteDb
*)cd
;
1916 static const char *DB_strs
[] = {
1917 "authorizer", "backup", "bind_fallback",
1918 "busy", "cache", "changes",
1919 "close", "collate", "collation_needed",
1920 "commit_hook", "complete", "config",
1921 "copy", "deserialize", "enable_load_extension",
1922 "errorcode", "eval", "exists",
1923 "function", "incrblob", "interrupt",
1924 "last_insert_rowid", "nullvalue", "onecolumn",
1925 "preupdate", "profile", "progress",
1926 "rekey", "restore", "rollback_hook",
1927 "serialize", "status", "timeout",
1928 "total_changes", "trace", "trace_v2",
1929 "transaction", "unlock_notify", "update_hook",
1930 "version", "wal_hook", 0
1933 DB_AUTHORIZER
, DB_BACKUP
, DB_BIND_FALLBACK
,
1934 DB_BUSY
, DB_CACHE
, DB_CHANGES
,
1935 DB_CLOSE
, DB_COLLATE
, DB_COLLATION_NEEDED
,
1936 DB_COMMIT_HOOK
, DB_COMPLETE
, DB_CONFIG
,
1937 DB_COPY
, DB_DESERIALIZE
, DB_ENABLE_LOAD_EXTENSION
,
1938 DB_ERRORCODE
, DB_EVAL
, DB_EXISTS
,
1939 DB_FUNCTION
, DB_INCRBLOB
, DB_INTERRUPT
,
1940 DB_LAST_INSERT_ROWID
, DB_NULLVALUE
, DB_ONECOLUMN
,
1941 DB_PREUPDATE
, DB_PROFILE
, DB_PROGRESS
,
1942 DB_REKEY
, DB_RESTORE
, DB_ROLLBACK_HOOK
,
1943 DB_SERIALIZE
, DB_STATUS
, DB_TIMEOUT
,
1944 DB_TOTAL_CHANGES
, DB_TRACE
, DB_TRACE_V2
,
1945 DB_TRANSACTION
, DB_UNLOCK_NOTIFY
, DB_UPDATE_HOOK
,
1946 DB_VERSION
, DB_WAL_HOOK
1948 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
1951 Tcl_WrongNumArgs(interp
, 1, objv
, "SUBCOMMAND ...");
1954 if( Tcl_GetIndexFromObj(interp
, objv
[1], DB_strs
, "option", 0, &choice
) ){
1958 switch( (enum DB_enum
)choice
){
1960 /* $db authorizer ?CALLBACK?
1962 ** Invoke the given callback to authorize each SQL operation as it is
1963 ** compiled. 5 arguments are appended to the callback before it is
1966 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1967 ** (2) First descriptive name (depends on authorization type)
1968 ** (3) Second descriptive name
1969 ** (4) Name of the database (ex: "main", "temp")
1970 ** (5) Name of trigger that is doing the access
1972 ** The callback should return on of the following strings: SQLITE_OK,
1973 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1975 ** If this method is invoked with no arguments, the current authorization
1976 ** callback string is returned.
1978 case DB_AUTHORIZER
: {
1979 #ifdef SQLITE_OMIT_AUTHORIZATION
1980 Tcl_AppendResult(interp
, "authorization not available in this build",
1985 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
1987 }else if( objc
==2 ){
1989 Tcl_AppendResult(interp
, pDb
->zAuth
, (char*)0);
1995 Tcl_Free(pDb
->zAuth
);
1997 zAuth
= Tcl_GetStringFromObj(objv
[2], &len
);
1998 if( zAuth
&& len
>0 ){
1999 pDb
->zAuth
= Tcl_Alloc( len
+ 1 );
2000 memcpy(pDb
->zAuth
, zAuth
, len
+1);
2005 typedef int (*sqlite3_auth_cb
)(
2006 void*,int,const char*,const char*,
2007 const char*,const char*);
2008 pDb
->interp
= interp
;
2009 sqlite3_set_authorizer(pDb
->db
,(sqlite3_auth_cb
)auth_callback
,pDb
);
2011 sqlite3_set_authorizer(pDb
->db
, 0, 0);
2018 /* $db backup ?DATABASE? FILENAME
2020 ** Open or create a database file named FILENAME. Transfer the
2021 ** content of local database DATABASE (default: "main") into the
2022 ** FILENAME database.
2025 const char *zDestFile
;
2028 sqlite3_backup
*pBackup
;
2032 zDestFile
= Tcl_GetString(objv
[2]);
2033 }else if( objc
==4 ){
2034 zSrcDb
= Tcl_GetString(objv
[2]);
2035 zDestFile
= Tcl_GetString(objv
[3]);
2037 Tcl_WrongNumArgs(interp
, 2, objv
, "?DATABASE? FILENAME");
2040 rc
= sqlite3_open_v2(zDestFile
, &pDest
,
2041 SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
| pDb
->openFlags
, 0);
2042 if( rc
!=SQLITE_OK
){
2043 Tcl_AppendResult(interp
, "cannot open target database: ",
2044 sqlite3_errmsg(pDest
), (char*)0);
2045 sqlite3_close(pDest
);
2048 pBackup
= sqlite3_backup_init(pDest
, "main", pDb
->db
, zSrcDb
);
2050 Tcl_AppendResult(interp
, "backup failed: ",
2051 sqlite3_errmsg(pDest
), (char*)0);
2052 sqlite3_close(pDest
);
2055 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
){}
2056 sqlite3_backup_finish(pBackup
);
2057 if( rc
==SQLITE_DONE
){
2060 Tcl_AppendResult(interp
, "backup failed: ",
2061 sqlite3_errmsg(pDest
), (char*)0);
2064 sqlite3_close(pDest
);
2068 /* $db bind_fallback ?CALLBACK?
2070 ** When resolving bind parameters in an SQL statement, if the parameter
2071 ** cannot be associated with a TCL variable then invoke CALLBACK with a
2072 ** single argument that is the name of the parameter and use the return
2073 ** value of the CALLBACK as the binding. If CALLBACK returns something
2074 ** other than TCL_OK or TCL_ERROR then bind a NULL.
2076 ** If CALLBACK is an empty string, then revert to the default behavior
2077 ** which is to set the binding to NULL.
2079 ** If CALLBACK returns an error, that causes the statement execution to
2080 ** abort. Hence, to configure a connection so that it throws an error
2081 ** on an attempt to bind an unknown variable, do something like this:
2083 ** proc bind_error {name} {error "no such variable: $name"}
2084 ** db bind_fallback bind_error
2086 case DB_BIND_FALLBACK
: {
2088 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
2090 }else if( objc
==2 ){
2091 if( pDb
->zBindFallback
){
2092 Tcl_AppendResult(interp
, pDb
->zBindFallback
, (char*)0);
2097 if( pDb
->zBindFallback
){
2098 Tcl_Free(pDb
->zBindFallback
);
2100 zCallback
= Tcl_GetStringFromObj(objv
[2], &len
);
2101 if( zCallback
&& len
>0 ){
2102 pDb
->zBindFallback
= Tcl_Alloc( len
+ 1 );
2103 memcpy(pDb
->zBindFallback
, zCallback
, len
+1);
2105 pDb
->zBindFallback
= 0;
2111 /* $db busy ?CALLBACK?
2113 ** Invoke the given callback if an SQL statement attempts to open
2114 ** a locked database file.
2118 Tcl_WrongNumArgs(interp
, 2, objv
, "CALLBACK");
2120 }else if( objc
==2 ){
2122 Tcl_AppendResult(interp
, pDb
->zBusy
, (char*)0);
2128 Tcl_Free(pDb
->zBusy
);
2130 zBusy
= Tcl_GetStringFromObj(objv
[2], &len
);
2131 if( zBusy
&& len
>0 ){
2132 pDb
->zBusy
= Tcl_Alloc( len
+ 1 );
2133 memcpy(pDb
->zBusy
, zBusy
, len
+1);
2138 pDb
->interp
= interp
;
2139 sqlite3_busy_handler(pDb
->db
, DbBusyHandler
, pDb
);
2141 sqlite3_busy_handler(pDb
->db
, 0, 0);
2150 ** Flush the prepared statement cache, or set the maximum number of
2151 ** cached statements.
2158 Tcl_WrongNumArgs(interp
, 1, objv
, "cache option ?arg?");
2161 subCmd
= Tcl_GetStringFromObj( objv
[2], 0 );
2162 if( *subCmd
=='f' && strcmp(subCmd
,"flush")==0 ){
2164 Tcl_WrongNumArgs(interp
, 2, objv
, "flush");
2167 flushStmtCache( pDb
);
2169 }else if( *subCmd
=='s' && strcmp(subCmd
,"size")==0 ){
2171 Tcl_WrongNumArgs(interp
, 2, objv
, "size n");
2174 if( TCL_ERROR
==Tcl_GetIntFromObj(interp
, objv
[3], &n
) ){
2175 Tcl_AppendResult( interp
, "cannot convert \"",
2176 Tcl_GetStringFromObj(objv
[3],0), "\" to integer", (char*)0);
2180 flushStmtCache( pDb
);
2182 }else if( n
>MAX_PREPARED_STMTS
){
2183 n
= MAX_PREPARED_STMTS
;
2189 Tcl_AppendResult( interp
, "bad option \"",
2190 Tcl_GetStringFromObj(objv
[2],0), "\": must be flush or size",
2199 ** Return the number of rows that were modified, inserted, or deleted by
2200 ** the most recent INSERT, UPDATE or DELETE statement, not including
2201 ** any changes made by trigger programs.
2206 Tcl_WrongNumArgs(interp
, 2, objv
, "");
2209 pResult
= Tcl_GetObjResult(interp
);
2210 Tcl_SetIntObj(pResult
, sqlite3_changes(pDb
->db
));
2216 ** Shutdown the database
2219 Tcl_DeleteCommand(interp
, Tcl_GetStringFromObj(objv
[0], 0));
2224 ** $db collate NAME SCRIPT
2226 ** Create a new SQL collation function called NAME. Whenever
2227 ** that function is called, invoke SCRIPT to evaluate the function.
2230 SqlCollate
*pCollate
;
2235 Tcl_WrongNumArgs(interp
, 2, objv
, "NAME SCRIPT");
2238 zName
= Tcl_GetStringFromObj(objv
[2], 0);
2239 zScript
= Tcl_GetStringFromObj(objv
[3], &nScript
);
2240 pCollate
= (SqlCollate
*)Tcl_Alloc( sizeof(*pCollate
) + nScript
+ 1 );
2241 if( pCollate
==0 ) return TCL_ERROR
;
2242 pCollate
->interp
= interp
;
2243 pCollate
->pNext
= pDb
->pCollate
;
2244 pCollate
->zScript
= (char*)&pCollate
[1];
2245 pDb
->pCollate
= pCollate
;
2246 memcpy(pCollate
->zScript
, zScript
, nScript
+1);
2247 if( sqlite3_create_collation(pDb
->db
, zName
, SQLITE_UTF8
,
2248 pCollate
, tclSqlCollate
) ){
2249 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(pDb
->db
), TCL_VOLATILE
);
2256 ** $db collation_needed SCRIPT
2258 ** Create a new SQL collation function called NAME. Whenever
2259 ** that function is called, invoke SCRIPT to evaluate the function.
2261 case DB_COLLATION_NEEDED
: {
2263 Tcl_WrongNumArgs(interp
, 2, objv
, "SCRIPT");
2266 if( pDb
->pCollateNeeded
){
2267 Tcl_DecrRefCount(pDb
->pCollateNeeded
);
2269 pDb
->pCollateNeeded
= Tcl_DuplicateObj(objv
[2]);
2270 Tcl_IncrRefCount(pDb
->pCollateNeeded
);
2271 sqlite3_collation_needed(pDb
->db
, pDb
, tclCollateNeeded
);
2275 /* $db commit_hook ?CALLBACK?
2277 ** Invoke the given callback just before committing every SQL transaction.
2278 ** If the callback throws an exception or returns non-zero, then the
2279 ** transaction is aborted. If CALLBACK is an empty string, the callback
2282 case DB_COMMIT_HOOK
: {
2284 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
2286 }else if( objc
==2 ){
2288 Tcl_AppendResult(interp
, pDb
->zCommit
, (char*)0);
2291 const char *zCommit
;
2294 Tcl_Free(pDb
->zCommit
);
2296 zCommit
= Tcl_GetStringFromObj(objv
[2], &len
);
2297 if( zCommit
&& len
>0 ){
2298 pDb
->zCommit
= Tcl_Alloc( len
+ 1 );
2299 memcpy(pDb
->zCommit
, zCommit
, len
+1);
2304 pDb
->interp
= interp
;
2305 sqlite3_commit_hook(pDb
->db
, DbCommitHandler
, pDb
);
2307 sqlite3_commit_hook(pDb
->db
, 0, 0);
2315 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2316 ** additional lines of input are needed. This is similar to the
2317 ** built-in "info complete" command of Tcl.
2320 #ifndef SQLITE_OMIT_COMPLETE
2324 Tcl_WrongNumArgs(interp
, 2, objv
, "SQL");
2327 isComplete
= sqlite3_complete( Tcl_GetStringFromObj(objv
[2], 0) );
2328 pResult
= Tcl_GetObjResult(interp
);
2329 Tcl_SetBooleanObj(pResult
, isComplete
);
2334 /* $db config ?OPTION? ?BOOLEAN?
2336 ** Configure the database connection using the sqlite3_db_config()
2340 static const struct DbConfigChoices
{
2344 { "defensive", SQLITE_DBCONFIG_DEFENSIVE
},
2345 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL
},
2346 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML
},
2347 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY
},
2348 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG
},
2349 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER
},
2350 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW
},
2351 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
},
2352 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE
},
2353 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT
},
2354 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
},
2355 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE
},
2356 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE
},
2357 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP
},
2358 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA
},
2359 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA
},
2364 Tcl_WrongNumArgs(interp
, 2, objv
, "?OPTION? ?BOOLEAN?");
2368 /* With no arguments, list all configuration options and with the
2370 pResult
= Tcl_NewListObj(0,0);
2371 for(ii
=0; ii
<sizeof(aDbConfig
)/sizeof(aDbConfig
[0]); ii
++){
2373 sqlite3_db_config(pDb
->db
, aDbConfig
[ii
].op
, -1, &v
);
2374 Tcl_ListObjAppendElement(interp
, pResult
,
2375 Tcl_NewStringObj(aDbConfig
[ii
].zName
,-1));
2376 Tcl_ListObjAppendElement(interp
, pResult
,
2380 const char *zOpt
= Tcl_GetString(objv
[2]);
2383 if( zOpt
[0]=='-' ) zOpt
++;
2384 for(ii
=0; ii
<sizeof(aDbConfig
)/sizeof(aDbConfig
[0]); ii
++){
2385 if( strcmp(aDbConfig
[ii
].zName
, zOpt
)==0 ) break;
2387 if( ii
>=sizeof(aDbConfig
)/sizeof(aDbConfig
[0]) ){
2388 Tcl_AppendResult(interp
, "unknown config option: \"", zOpt
,
2393 if( Tcl_GetBooleanFromObj(interp
, objv
[3], &onoff
) ){
2397 sqlite3_db_config(pDb
->db
, aDbConfig
[ii
].op
, onoff
, &v
);
2398 pResult
= Tcl_NewIntObj(v
);
2400 Tcl_SetObjResult(interp
, pResult
);
2404 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2406 ** Copy data into table from filename, optionally using SEPARATOR
2407 ** as column separators. If a column contains a null string, or the
2408 ** value of NULLINDICATOR, a NULL is inserted for the column.
2409 ** conflict-algorithm is one of the sqlite conflict algorithms:
2410 ** rollback, abort, fail, ignore, replace
2411 ** On success, return the number of lines processed, not necessarily same
2412 ** as 'db changes' due to conflict-algorithm selected.
2414 ** This code is basically an implementation/enhancement of
2415 ** the sqlite3 shell.c ".import" command.
2417 ** This command usage is equivalent to the sqlite2.x COPY statement,
2418 ** which imports file data into a table using the PostgreSQL COPY file format:
2419 ** $db copy $conflit_algo $table_name $filename \t \\N
2422 char *zTable
; /* Insert data into this table */
2423 char *zFile
; /* The file from which to extract data */
2424 char *zConflict
; /* The conflict algorithm to use */
2425 sqlite3_stmt
*pStmt
; /* A statement */
2426 int nCol
; /* Number of columns in the table */
2427 int nByte
; /* Number of bytes in an SQL string */
2428 int i
, j
; /* Loop counters */
2429 int nSep
; /* Number of bytes in zSep[] */
2430 int nNull
; /* Number of bytes in zNull[] */
2431 char *zSql
; /* An SQL statement */
2432 char *zLine
; /* A single line of input from the file */
2433 char **azCol
; /* zLine[] broken up into columns */
2434 const char *zCommit
; /* How to commit changes */
2435 FILE *in
; /* The input file */
2436 int lineno
= 0; /* Line number of input file */
2437 char zLineNum
[80]; /* Line number print buffer */
2438 Tcl_Obj
*pResult
; /* interp result */
2442 if( objc
<5 || objc
>7 ){
2443 Tcl_WrongNumArgs(interp
, 2, objv
,
2444 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2448 zSep
= Tcl_GetStringFromObj(objv
[5], 0);
2453 zNull
= Tcl_GetStringFromObj(objv
[6], 0);
2457 zConflict
= Tcl_GetStringFromObj(objv
[2], 0);
2458 zTable
= Tcl_GetStringFromObj(objv
[3], 0);
2459 zFile
= Tcl_GetStringFromObj(objv
[4], 0);
2460 nSep
= strlen30(zSep
);
2461 nNull
= strlen30(zNull
);
2463 Tcl_AppendResult(interp
,"Error: non-null separator required for copy",
2467 if(strcmp(zConflict
, "rollback") != 0 &&
2468 strcmp(zConflict
, "abort" ) != 0 &&
2469 strcmp(zConflict
, "fail" ) != 0 &&
2470 strcmp(zConflict
, "ignore" ) != 0 &&
2471 strcmp(zConflict
, "replace" ) != 0 ) {
2472 Tcl_AppendResult(interp
, "Error: \"", zConflict
,
2473 "\", conflict-algorithm must be one of: rollback, "
2474 "abort, fail, ignore, or replace", (char*)0);
2477 zSql
= sqlite3_mprintf("SELECT * FROM '%q'", zTable
);
2479 Tcl_AppendResult(interp
, "Error: no such table: ", zTable
, (char*)0);
2482 nByte
= strlen30(zSql
);
2483 rc
= sqlite3_prepare(pDb
->db
, zSql
, -1, &pStmt
, 0);
2486 Tcl_AppendResult(interp
, "Error: ", sqlite3_errmsg(pDb
->db
), (char*)0);
2489 nCol
= sqlite3_column_count(pStmt
);
2491 sqlite3_finalize(pStmt
);
2495 zSql
= malloc( nByte
+ 50 + nCol
*2 );
2497 Tcl_AppendResult(interp
, "Error: can't malloc()", (char*)0);
2500 sqlite3_snprintf(nByte
+50, zSql
, "INSERT OR %q INTO '%q' VALUES(?",
2503 for(i
=1; i
<nCol
; i
++){
2509 rc
= sqlite3_prepare(pDb
->db
, zSql
, -1, &pStmt
, 0);
2512 Tcl_AppendResult(interp
, "Error: ", sqlite3_errmsg(pDb
->db
), (char*)0);
2513 sqlite3_finalize(pStmt
);
2516 in
= fopen(zFile
, "rb");
2518 Tcl_AppendResult(interp
, "Error: cannot open file: ", zFile
, (char*)0);
2519 sqlite3_finalize(pStmt
);
2522 azCol
= malloc( sizeof(azCol
[0])*(nCol
+1) );
2524 Tcl_AppendResult(interp
, "Error: can't malloc()", (char*)0);
2528 (void)sqlite3_exec(pDb
->db
, "BEGIN", 0, 0, 0);
2530 while( (zLine
= local_getline(0, in
))!=0 ){
2534 for(i
=0, z
=zLine
; *z
; z
++){
2535 if( *z
==zSep
[0] && strncmp(z
, zSep
, nSep
)==0 ){
2539 azCol
[i
] = &z
[nSep
];
2546 int nErr
= strlen30(zFile
) + 200;
2547 zErr
= malloc(nErr
);
2549 sqlite3_snprintf(nErr
, zErr
,
2550 "Error: %s line %d: expected %d columns of data but found %d",
2551 zFile
, lineno
, nCol
, i
+1);
2552 Tcl_AppendResult(interp
, zErr
, (char*)0);
2555 zCommit
= "ROLLBACK";
2558 for(i
=0; i
<nCol
; i
++){
2559 /* check for null data, if so, bind as null */
2560 if( (nNull
>0 && strcmp(azCol
[i
], zNull
)==0)
2561 || strlen30(azCol
[i
])==0
2563 sqlite3_bind_null(pStmt
, i
+1);
2565 sqlite3_bind_text(pStmt
, i
+1, azCol
[i
], -1, SQLITE_STATIC
);
2568 sqlite3_step(pStmt
);
2569 rc
= sqlite3_reset(pStmt
);
2571 if( rc
!=SQLITE_OK
){
2572 Tcl_AppendResult(interp
,"Error: ", sqlite3_errmsg(pDb
->db
), (char*)0);
2573 zCommit
= "ROLLBACK";
2579 sqlite3_finalize(pStmt
);
2580 (void)sqlite3_exec(pDb
->db
, zCommit
, 0, 0, 0);
2582 if( zCommit
[0] == 'C' ){
2583 /* success, set result as number of lines processed */
2584 pResult
= Tcl_GetObjResult(interp
);
2585 Tcl_SetIntObj(pResult
, lineno
);
2588 /* failure, append lineno where failed */
2589 sqlite3_snprintf(sizeof(zLineNum
), zLineNum
,"%d",lineno
);
2590 Tcl_AppendResult(interp
,", failed while processing line: ",zLineNum
,
2598 ** $db deserialize ?-maxsize N? ?-readonly BOOL? ?DATABASE? VALUE
2600 ** Reopen DATABASE (default "main") using the content in $VALUE
2602 case DB_DESERIALIZE
: {
2603 #ifdef SQLITE_OMIT_DESERIALIZE
2604 Tcl_AppendResult(interp
, "MEMDB not available in this build",
2608 const char *zSchema
= 0;
2609 Tcl_Obj
*pValue
= 0;
2611 unsigned char *pData
;
2613 sqlite3_int64 mxSize
= 0;
2619 Tcl_WrongNumArgs(interp
, 2, objv
, "?DATABASE? VALUE");
2623 for(i
=2; i
<objc
-1; i
++){
2624 const char *z
= Tcl_GetString(objv
[i
]);
2625 if( strcmp(z
,"-maxsize")==0 && i
<objc
-2 ){
2626 rc
= Tcl_GetWideIntFromObj(interp
, objv
[++i
], &mxSize
);
2627 if( rc
) goto deserialize_error
;
2630 if( strcmp(z
,"-readonly")==0 && i
<objc
-2 ){
2631 rc
= Tcl_GetBooleanFromObj(interp
, objv
[++i
], &isReadonly
);
2632 if( rc
) goto deserialize_error
;
2635 if( zSchema
==0 && i
==objc
-2 && z
[0]!='-' ){
2639 Tcl_AppendResult(interp
, "unknown option: ", z
, (char*)0);
2641 goto deserialize_error
;
2643 pValue
= objv
[objc
-1];
2644 pBA
= Tcl_GetByteArrayFromObj(pValue
, &len
);
2645 pData
= sqlite3_malloc64( len
);
2646 if( pData
==0 && len
>0 ){
2647 Tcl_AppendResult(interp
, "out of memory", (char*)0);
2651 if( len
>0 ) memcpy(pData
, pBA
, len
);
2653 flags
= SQLITE_DESERIALIZE_FREEONCLOSE
| SQLITE_DESERIALIZE_READONLY
;
2655 flags
= SQLITE_DESERIALIZE_FREEONCLOSE
| SQLITE_DESERIALIZE_RESIZEABLE
;
2657 xrc
= sqlite3_deserialize(pDb
->db
, zSchema
, pData
, len
, len
, flags
);
2659 Tcl_AppendResult(interp
, "unable to set MEMDB content", (char*)0);
2663 sqlite3_file_control(pDb
->db
, zSchema
,SQLITE_FCNTL_SIZE_LIMIT
,&mxSize
);
2672 ** $db enable_load_extension BOOLEAN
2674 ** Turn the extension loading feature on or off. It if off by
2677 case DB_ENABLE_LOAD_EXTENSION
: {
2678 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2681 Tcl_WrongNumArgs(interp
, 2, objv
, "BOOLEAN");
2684 if( Tcl_GetBooleanFromObj(interp
, objv
[2], &onoff
) ){
2687 sqlite3_enable_load_extension(pDb
->db
, onoff
);
2690 Tcl_AppendResult(interp
, "extension loading is turned off at compile-time",
2699 ** Return the numeric error code that was returned by the most recent
2700 ** call to sqlite3_exec().
2702 case DB_ERRORCODE
: {
2703 Tcl_SetObjResult(interp
, Tcl_NewIntObj(sqlite3_errcode(pDb
->db
)));
2709 ** $db onecolumn $sql
2711 ** The onecolumn method is the equivalent of:
2712 ** lindex [$db eval $sql] 0
2715 case DB_ONECOLUMN
: {
2716 Tcl_Obj
*pResult
= 0;
2717 DbEvalContext sEval
;
2719 Tcl_WrongNumArgs(interp
, 2, objv
, "SQL");
2723 dbEvalInit(&sEval
, pDb
, objv
[2], 0, 0);
2724 rc
= dbEvalStep(&sEval
);
2725 if( choice
==DB_ONECOLUMN
){
2727 pResult
= dbEvalColumnValue(&sEval
, 0);
2728 }else if( rc
==TCL_BREAK
){
2729 Tcl_ResetResult(interp
);
2731 }else if( rc
==TCL_BREAK
|| rc
==TCL_OK
){
2732 pResult
= Tcl_NewBooleanObj(rc
==TCL_OK
);
2734 dbEvalFinalize(&sEval
);
2735 if( pResult
) Tcl_SetObjResult(interp
, pResult
);
2737 if( rc
==TCL_BREAK
){
2744 ** $db eval ?options? $sql ?array? ?{ ...code... }?
2746 ** The SQL statement in $sql is evaluated. For each row, the values are
2747 ** placed in elements of the array named "array" and ...code... is executed.
2748 ** If "array" and "code" are omitted, then no callback is every invoked.
2749 ** If "array" is an empty string, then the values are placed in variables
2750 ** that have the same name as the fields extracted by the query.
2755 while( objc
>3 && (zOpt
= Tcl_GetString(objv
[2]))!=0 && zOpt
[0]=='-' ){
2756 if( strcmp(zOpt
, "-withoutnulls")==0 ){
2757 evalFlags
|= SQLITE_EVAL_WITHOUTNULLS
;
2760 Tcl_AppendResult(interp
, "unknown option: \"", zOpt
, "\"", (void*)0);
2766 if( objc
<3 || objc
>5 ){
2767 Tcl_WrongNumArgs(interp
, 2, objv
,
2768 "?OPTIONS? SQL ?ARRAY-NAME? ?SCRIPT?");
2773 DbEvalContext sEval
;
2774 Tcl_Obj
*pRet
= Tcl_NewObj();
2775 Tcl_IncrRefCount(pRet
);
2776 dbEvalInit(&sEval
, pDb
, objv
[2], 0, 0);
2777 while( TCL_OK
==(rc
= dbEvalStep(&sEval
)) ){
2780 dbEvalRowInfo(&sEval
, &nCol
, 0);
2781 for(i
=0; i
<nCol
; i
++){
2782 Tcl_ListObjAppendElement(interp
, pRet
, dbEvalColumnValue(&sEval
, i
));
2785 dbEvalFinalize(&sEval
);
2786 if( rc
==TCL_BREAK
){
2787 Tcl_SetObjResult(interp
, pRet
);
2790 Tcl_DecrRefCount(pRet
);
2794 Tcl_Obj
*pArray
= 0;
2797 if( objc
>=5 && *(char *)Tcl_GetString(objv
[3]) ){
2800 pScript
= objv
[objc
-1];
2801 Tcl_IncrRefCount(pScript
);
2803 p
= (DbEvalContext
*)Tcl_Alloc(sizeof(DbEvalContext
));
2804 dbEvalInit(p
, pDb
, objv
[2], pArray
, evalFlags
);
2807 cd2
[1] = (void *)pScript
;
2808 rc
= DbEvalNextCmd(cd2
, interp
, TCL_OK
);
2814 ** $db function NAME [OPTIONS] SCRIPT
2816 ** Create a new SQL function called NAME. Whenever that function is
2817 ** called, invoke SCRIPT to evaluate the function.
2820 ** --argcount N Function has exactly N arguments
2821 ** --deterministic The function is pure
2822 ** --directonly Prohibit use inside triggers and views
2823 ** --innocuous Has no side effects or information leaks
2824 ** --returntype TYPE Specify the return type of the function
2827 int flags
= SQLITE_UTF8
;
2833 int eType
= SQLITE_NULL
;
2835 Tcl_WrongNumArgs(interp
, 2, objv
, "NAME ?SWITCHES? SCRIPT");
2838 for(i
=3; i
<(objc
-1); i
++){
2839 const char *z
= Tcl_GetString(objv
[i
]);
2840 int n
= strlen30(z
);
2841 if( n
>1 && strncmp(z
, "-argcount",n
)==0 ){
2843 Tcl_AppendResult(interp
, "option requires an argument: ", z
,(char*)0);
2846 if( Tcl_GetIntFromObj(interp
, objv
[i
+1], &nArg
) ) return TCL_ERROR
;
2848 Tcl_AppendResult(interp
, "number of arguments must be non-negative",
2854 if( n
>1 && strncmp(z
, "-deterministic",n
)==0 ){
2855 flags
|= SQLITE_DETERMINISTIC
;
2857 if( n
>1 && strncmp(z
, "-directonly",n
)==0 ){
2858 flags
|= SQLITE_DIRECTONLY
;
2860 if( n
>1 && strncmp(z
, "-innocuous",n
)==0 ){
2861 flags
|= SQLITE_INNOCUOUS
;
2863 if( n
>1 && strncmp(z
, "-returntype", n
)==0 ){
2864 const char *azType
[] = {"integer", "real", "text", "blob", "any", 0};
2865 assert( SQLITE_INTEGER
==1 && SQLITE_FLOAT
==2 && SQLITE_TEXT
==3 );
2866 assert( SQLITE_BLOB
==4 && SQLITE_NULL
==5 );
2868 Tcl_AppendResult(interp
, "option requires an argument: ", z
,(char*)0);
2872 if( Tcl_GetIndexFromObj(interp
, objv
[i
], azType
, "type", 0, &eType
) ){
2877 Tcl_AppendResult(interp
, "bad option \"", z
,
2878 "\": must be -argcount, -deterministic, -directonly,"
2879 " -innocuous, or -returntype", (char*)0
2885 pScript
= objv
[objc
-1];
2886 zName
= Tcl_GetStringFromObj(objv
[2], 0);
2887 pFunc
= findSqlFunc(pDb
, zName
);
2888 if( pFunc
==0 ) return TCL_ERROR
;
2889 if( pFunc
->pScript
){
2890 Tcl_DecrRefCount(pFunc
->pScript
);
2892 pFunc
->pScript
= pScript
;
2893 Tcl_IncrRefCount(pScript
);
2894 pFunc
->useEvalObjv
= safeToUseEvalObjv(interp
, pScript
);
2895 pFunc
->eType
= eType
;
2896 rc
= sqlite3_create_function(pDb
->db
, zName
, nArg
, flags
,
2897 pFunc
, tclSqlFunc
, 0, 0);
2898 if( rc
!=SQLITE_OK
){
2900 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(pDb
->db
), TCL_VOLATILE
);
2906 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
2909 #ifdef SQLITE_OMIT_INCRBLOB
2910 Tcl_AppendResult(interp
, "incrblob not available in this build", (char*)0);
2914 const char *zDb
= "main";
2916 const char *zColumn
;
2919 /* Check for the -readonly option */
2920 if( objc
>3 && strcmp(Tcl_GetString(objv
[2]), "-readonly")==0 ){
2924 if( objc
!=(5+isReadonly
) && objc
!=(6+isReadonly
) ){
2925 Tcl_WrongNumArgs(interp
, 2, objv
, "?-readonly? ?DB? TABLE COLUMN ROWID");
2929 if( objc
==(6+isReadonly
) ){
2930 zDb
= Tcl_GetString(objv
[2]);
2932 zTable
= Tcl_GetString(objv
[objc
-3]);
2933 zColumn
= Tcl_GetString(objv
[objc
-2]);
2934 rc
= Tcl_GetWideIntFromObj(interp
, objv
[objc
-1], &iRow
);
2937 rc
= createIncrblobChannel(
2938 interp
, pDb
, zDb
, zTable
, zColumn
, (sqlite3_int64
)iRow
, isReadonly
2948 ** Interrupt the execution of the inner-most SQL interpreter. This
2949 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2951 case DB_INTERRUPT
: {
2952 sqlite3_interrupt(pDb
->db
);
2957 ** $db nullvalue ?STRING?
2959 ** Change text used when a NULL comes back from the database. If ?STRING?
2960 ** is not present, then the current string used for NULL is returned.
2961 ** If STRING is present, then STRING is returned.
2964 case DB_NULLVALUE
: {
2965 if( objc
!=2 && objc
!=3 ){
2966 Tcl_WrongNumArgs(interp
, 2, objv
, "NULLVALUE");
2971 char *zNull
= Tcl_GetStringFromObj(objv
[2], &len
);
2973 Tcl_Free(pDb
->zNull
);
2975 if( zNull
&& len
>0 ){
2976 pDb
->zNull
= Tcl_Alloc( len
+ 1 );
2977 memcpy(pDb
->zNull
, zNull
, len
);
2978 pDb
->zNull
[len
] = '\0';
2983 Tcl_SetObjResult(interp
, Tcl_NewStringObj(pDb
->zNull
, -1));
2988 ** $db last_insert_rowid
2990 ** Return an integer which is the ROWID for the most recent insert.
2992 case DB_LAST_INSERT_ROWID
: {
2996 Tcl_WrongNumArgs(interp
, 2, objv
, "");
2999 rowid
= sqlite3_last_insert_rowid(pDb
->db
);
3000 pResult
= Tcl_GetObjResult(interp
);
3001 Tcl_SetWideIntObj(pResult
, rowid
);
3006 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
3009 /* $db progress ?N CALLBACK?
3011 ** Invoke the given callback every N virtual machine opcodes while executing
3016 if( pDb
->zProgress
){
3017 Tcl_AppendResult(interp
, pDb
->zProgress
, (char*)0);
3019 }else if( objc
==4 ){
3023 if( TCL_OK
!=Tcl_GetIntFromObj(interp
, objv
[2], &N
) ){
3026 if( pDb
->zProgress
){
3027 Tcl_Free(pDb
->zProgress
);
3029 zProgress
= Tcl_GetStringFromObj(objv
[3], &len
);
3030 if( zProgress
&& len
>0 ){
3031 pDb
->zProgress
= Tcl_Alloc( len
+ 1 );
3032 memcpy(pDb
->zProgress
, zProgress
, len
+1);
3036 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
3037 if( pDb
->zProgress
){
3038 pDb
->interp
= interp
;
3039 sqlite3_progress_handler(pDb
->db
, N
, DbProgressHandler
, pDb
);
3041 sqlite3_progress_handler(pDb
->db
, 0, 0, 0);
3045 Tcl_WrongNumArgs(interp
, 2, objv
, "N CALLBACK");
3051 /* $db profile ?CALLBACK?
3053 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
3054 ** that has run. The text of the SQL and the amount of elapse time are
3055 ** appended to CALLBACK before the script is run.
3059 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
3061 }else if( objc
==2 ){
3062 if( pDb
->zProfile
){
3063 Tcl_AppendResult(interp
, pDb
->zProfile
, (char*)0);
3068 if( pDb
->zProfile
){
3069 Tcl_Free(pDb
->zProfile
);
3071 zProfile
= Tcl_GetStringFromObj(objv
[2], &len
);
3072 if( zProfile
&& len
>0 ){
3073 pDb
->zProfile
= Tcl_Alloc( len
+ 1 );
3074 memcpy(pDb
->zProfile
, zProfile
, len
+1);
3078 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3079 !defined(SQLITE_OMIT_DEPRECATED)
3080 if( pDb
->zProfile
){
3081 pDb
->interp
= interp
;
3082 sqlite3_profile(pDb
->db
, DbProfileHandler
, pDb
);
3084 sqlite3_profile(pDb
->db
, 0, 0);
3094 ** Change the encryption key on the currently open database.
3097 /* BEGIN SQLCIPHER */
3098 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3104 Tcl_WrongNumArgs(interp
, 2, objv
, "KEY");
3107 /* BEGIN SQLCIPHER */
3108 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3109 pKey
= Tcl_GetByteArrayFromObj(objv
[2], &nKey
);
3110 rc
= sqlite3_rekey(pDb
->db
, pKey
, nKey
);
3112 Tcl_AppendResult(interp
, sqlite3_errstr(rc
), (char*)0);
3120 /* $db restore ?DATABASE? FILENAME
3122 ** Open a database file named FILENAME. Transfer the content
3123 ** of FILENAME into the local database DATABASE (default: "main").
3126 const char *zSrcFile
;
3127 const char *zDestDb
;
3129 sqlite3_backup
*pBackup
;
3134 zSrcFile
= Tcl_GetString(objv
[2]);
3135 }else if( objc
==4 ){
3136 zDestDb
= Tcl_GetString(objv
[2]);
3137 zSrcFile
= Tcl_GetString(objv
[3]);
3139 Tcl_WrongNumArgs(interp
, 2, objv
, "?DATABASE? FILENAME");
3142 rc
= sqlite3_open_v2(zSrcFile
, &pSrc
,
3143 SQLITE_OPEN_READONLY
| pDb
->openFlags
, 0);
3144 if( rc
!=SQLITE_OK
){
3145 Tcl_AppendResult(interp
, "cannot open source database: ",
3146 sqlite3_errmsg(pSrc
), (char*)0);
3147 sqlite3_close(pSrc
);
3150 pBackup
= sqlite3_backup_init(pDb
->db
, zDestDb
, pSrc
, "main");
3152 Tcl_AppendResult(interp
, "restore failed: ",
3153 sqlite3_errmsg(pDb
->db
), (char*)0);
3154 sqlite3_close(pSrc
);
3157 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
3158 || rc
==SQLITE_BUSY
){
3159 if( rc
==SQLITE_BUSY
){
3160 if( nTimeout
++ >= 3 ) break;
3164 sqlite3_backup_finish(pBackup
);
3165 if( rc
==SQLITE_DONE
){
3167 }else if( rc
==SQLITE_BUSY
|| rc
==SQLITE_LOCKED
){
3168 Tcl_AppendResult(interp
, "restore failed: source database busy",
3172 Tcl_AppendResult(interp
, "restore failed: ",
3173 sqlite3_errmsg(pDb
->db
), (char*)0);
3176 sqlite3_close(pSrc
);
3181 ** $db serialize ?DATABASE?
3183 ** Return a serialization of a database.
3185 case DB_SERIALIZE
: {
3186 #ifdef SQLITE_OMIT_DESERIALIZE
3187 Tcl_AppendResult(interp
, "MEMDB not available in this build",
3191 const char *zSchema
= objc
>=3 ? Tcl_GetString(objv
[2]) : "main";
3192 sqlite3_int64 sz
= 0;
3193 unsigned char *pData
;
3194 if( objc
!=2 && objc
!=3 ){
3195 Tcl_WrongNumArgs(interp
, 2, objv
, "?DATABASE?");
3199 pData
= sqlite3_serialize(pDb
->db
, zSchema
, &sz
, SQLITE_SERIALIZE_NOCOPY
);
3203 pData
= sqlite3_serialize(pDb
->db
, zSchema
, &sz
, 0);
3206 Tcl_SetObjResult(interp
, Tcl_NewByteArrayObj(pData
,sz
));
3207 if( needFree
) sqlite3_free(pData
);
3214 ** $db status (step|sort|autoindex|vmstep)
3216 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
3217 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
3223 Tcl_WrongNumArgs(interp
, 2, objv
, "(step|sort|autoindex)");
3226 zOp
= Tcl_GetString(objv
[2]);
3227 if( strcmp(zOp
, "step")==0 ){
3229 }else if( strcmp(zOp
, "sort")==0 ){
3231 }else if( strcmp(zOp
, "autoindex")==0 ){
3233 }else if( strcmp(zOp
, "vmstep")==0 ){
3236 Tcl_AppendResult(interp
,
3237 "bad argument: should be autoindex, step, sort or vmstep",
3241 Tcl_SetObjResult(interp
, Tcl_NewIntObj(v
));
3246 ** $db timeout MILLESECONDS
3248 ** Delay for the number of milliseconds specified when a file is locked.
3253 Tcl_WrongNumArgs(interp
, 2, objv
, "MILLISECONDS");
3256 if( Tcl_GetIntFromObj(interp
, objv
[2], &ms
) ) return TCL_ERROR
;
3257 sqlite3_busy_timeout(pDb
->db
, ms
);
3262 ** $db total_changes
3264 ** Return the number of rows that were modified, inserted, or deleted
3265 ** since the database handle was created.
3267 case DB_TOTAL_CHANGES
: {
3270 Tcl_WrongNumArgs(interp
, 2, objv
, "");
3273 pResult
= Tcl_GetObjResult(interp
);
3274 Tcl_SetIntObj(pResult
, sqlite3_total_changes(pDb
->db
));
3278 /* $db trace ?CALLBACK?
3280 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
3281 ** that is executed. The text of the SQL is appended to CALLBACK before
3286 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
3288 }else if( objc
==2 ){
3290 Tcl_AppendResult(interp
, pDb
->zTrace
, (char*)0);
3296 Tcl_Free(pDb
->zTrace
);
3298 zTrace
= Tcl_GetStringFromObj(objv
[2], &len
);
3299 if( zTrace
&& len
>0 ){
3300 pDb
->zTrace
= Tcl_Alloc( len
+ 1 );
3301 memcpy(pDb
->zTrace
, zTrace
, len
+1);
3305 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3306 !defined(SQLITE_OMIT_DEPRECATED)
3308 pDb
->interp
= interp
;
3309 sqlite3_trace(pDb
->db
, DbTraceHandler
, pDb
);
3311 sqlite3_trace(pDb
->db
, 0, 0);
3318 /* $db trace_v2 ?CALLBACK? ?MASK?
3320 ** Make arrangements to invoke the CALLBACK routine for each trace event
3321 ** matching the mask that is generated. The parameters are appended to
3322 ** CALLBACK before it is executed.
3326 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK? ?MASK?");
3328 }else if( objc
==2 ){
3329 if( pDb
->zTraceV2
){
3330 Tcl_AppendResult(interp
, pDb
->zTraceV2
, (char*)0);
3335 Tcl_WideInt wMask
= 0;
3337 static const char *TTYPE_strs
[] = {
3338 "statement", "profile", "row", "close", 0
3341 TTYPE_STMT
, TTYPE_PROFILE
, TTYPE_ROW
, TTYPE_CLOSE
3344 if( TCL_OK
!=Tcl_ListObjLength(interp
, objv
[3], &len
) ){
3347 for(i
=0; i
<len
; i
++){
3350 if( TCL_OK
!=Tcl_ListObjIndex(interp
, objv
[3], i
, &pObj
) ){
3353 if( Tcl_GetIndexFromObj(interp
, pObj
, TTYPE_strs
, "trace type",
3354 0, &ttype
)!=TCL_OK
){
3356 Tcl_Obj
*pError
= Tcl_DuplicateObj(Tcl_GetObjResult(interp
));
3357 Tcl_IncrRefCount(pError
);
3358 if( TCL_OK
==Tcl_GetWideIntFromObj(interp
, pObj
, &wType
) ){
3359 Tcl_DecrRefCount(pError
);
3362 Tcl_SetObjResult(interp
, pError
);
3363 Tcl_DecrRefCount(pError
);
3367 switch( (enum TTYPE_enum
)ttype
){
3368 case TTYPE_STMT
: wMask
|= SQLITE_TRACE_STMT
; break;
3369 case TTYPE_PROFILE
: wMask
|= SQLITE_TRACE_PROFILE
; break;
3370 case TTYPE_ROW
: wMask
|= SQLITE_TRACE_ROW
; break;
3371 case TTYPE_CLOSE
: wMask
|= SQLITE_TRACE_CLOSE
; break;
3376 wMask
= SQLITE_TRACE_STMT
; /* use the "legacy" default */
3378 if( pDb
->zTraceV2
){
3379 Tcl_Free(pDb
->zTraceV2
);
3381 zTraceV2
= Tcl_GetStringFromObj(objv
[2], &len
);
3382 if( zTraceV2
&& len
>0 ){
3383 pDb
->zTraceV2
= Tcl_Alloc( len
+ 1 );
3384 memcpy(pDb
->zTraceV2
, zTraceV2
, len
+1);
3388 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3389 if( pDb
->zTraceV2
){
3390 pDb
->interp
= interp
;
3391 sqlite3_trace_v2(pDb
->db
, (unsigned)wMask
, DbTraceV2Handler
, pDb
);
3393 sqlite3_trace_v2(pDb
->db
, 0, 0, 0);
3400 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
3402 ** Start a new transaction (if we are not already in the midst of a
3403 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
3404 ** completes, either commit the transaction or roll it back if SCRIPT
3405 ** throws an exception. Or if no new transation was started, do nothing.
3406 ** pass the exception on up the stack.
3408 ** This command was inspired by Dave Thomas's talk on Ruby at the
3409 ** 2005 O'Reilly Open Source Convention (OSCON).
3411 case DB_TRANSACTION
: {
3413 const char *zBegin
= "SAVEPOINT _tcl_transaction";
3414 if( objc
!=3 && objc
!=4 ){
3415 Tcl_WrongNumArgs(interp
, 2, objv
, "[TYPE] SCRIPT");
3419 if( pDb
->nTransaction
==0 && objc
==4 ){
3420 static const char *TTYPE_strs
[] = {
3421 "deferred", "exclusive", "immediate", 0
3424 TTYPE_DEFERRED
, TTYPE_EXCLUSIVE
, TTYPE_IMMEDIATE
3427 if( Tcl_GetIndexFromObj(interp
, objv
[2], TTYPE_strs
, "transaction type",
3431 switch( (enum TTYPE_enum
)ttype
){
3432 case TTYPE_DEFERRED
: /* no-op */; break;
3433 case TTYPE_EXCLUSIVE
: zBegin
= "BEGIN EXCLUSIVE"; break;
3434 case TTYPE_IMMEDIATE
: zBegin
= "BEGIN IMMEDIATE"; break;
3437 pScript
= objv
[objc
-1];
3439 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
3441 rc
= sqlite3_exec(pDb
->db
, zBegin
, 0, 0, 0);
3443 if( rc
!=SQLITE_OK
){
3444 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
3447 pDb
->nTransaction
++;
3449 /* If using NRE, schedule a callback to invoke the script pScript, then
3450 ** a second callback to commit (or rollback) the transaction or savepoint
3451 ** opened above. If not using NRE, evaluate the script directly, then
3452 ** call function DbTransPostCmd() to commit (or rollback) the transaction
3455 Tcl_NRAddCallback(interp
, DbTransPostCmd
, cd
, 0, 0, 0);
3456 (void)Tcl_NREvalObj(interp
, pScript
, 0);
3458 rc
= DbTransPostCmd(&cd
, interp
, Tcl_EvalObjEx(interp
, pScript
, 0));
3464 ** $db unlock_notify ?script?
3466 case DB_UNLOCK_NOTIFY
: {
3467 #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
3468 Tcl_AppendResult(interp
, "unlock_notify not available in this build",
3472 if( objc
!=2 && objc
!=3 ){
3473 Tcl_WrongNumArgs(interp
, 2, objv
, "?SCRIPT?");
3476 void (*xNotify
)(void **, int) = 0;
3477 void *pNotifyArg
= 0;
3479 if( pDb
->pUnlockNotify
){
3480 Tcl_DecrRefCount(pDb
->pUnlockNotify
);
3481 pDb
->pUnlockNotify
= 0;
3485 xNotify
= DbUnlockNotify
;
3486 pNotifyArg
= (void *)pDb
;
3487 pDb
->pUnlockNotify
= objv
[2];
3488 Tcl_IncrRefCount(pDb
->pUnlockNotify
);
3491 if( sqlite3_unlock_notify(pDb
->db
, xNotify
, pNotifyArg
) ){
3492 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
3501 ** $db preupdate_hook count
3502 ** $db preupdate_hook hook ?SCRIPT?
3503 ** $db preupdate_hook new INDEX
3504 ** $db preupdate_hook old INDEX
3506 case DB_PREUPDATE
: {
3507 #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
3508 Tcl_AppendResult(interp
, "preupdate_hook was omitted at compile-time",
3512 static const char *azSub
[] = {"count", "depth", "hook", "new", "old", 0};
3513 enum DbPreupdateSubCmd
{
3514 PRE_COUNT
, PRE_DEPTH
, PRE_HOOK
, PRE_NEW
, PRE_OLD
3519 Tcl_WrongNumArgs(interp
, 2, objv
, "SUB-COMMAND ?ARGS?");
3521 if( Tcl_GetIndexFromObj(interp
, objv
[2], azSub
, "sub-command", 0, &iSub
) ){
3525 switch( (enum DbPreupdateSubCmd
)iSub
){
3527 int nCol
= sqlite3_preupdate_count(pDb
->db
);
3528 Tcl_SetObjResult(interp
, Tcl_NewIntObj(nCol
));
3534 Tcl_WrongNumArgs(interp
, 2, objv
, "hook ?SCRIPT?");
3537 DbHookCmd(interp
, pDb
, (objc
==4 ? objv
[3] : 0), &pDb
->pPreUpdateHook
);
3544 Tcl_WrongNumArgs(interp
, 3, objv
, "");
3547 pRet
= Tcl_NewIntObj(sqlite3_preupdate_depth(pDb
->db
));
3548 Tcl_SetObjResult(interp
, pRet
);
3555 sqlite3_value
*pValue
;
3557 Tcl_WrongNumArgs(interp
, 3, objv
, "INDEX");
3560 if( Tcl_GetIntFromObj(interp
, objv
[3], &iIdx
) ){
3564 if( iSub
==PRE_OLD
){
3565 rc
= sqlite3_preupdate_old(pDb
->db
, iIdx
, &pValue
);
3567 assert( iSub
==PRE_NEW
);
3568 rc
= sqlite3_preupdate_new(pDb
->db
, iIdx
, &pValue
);
3571 if( rc
==SQLITE_OK
){
3573 pObj
= Tcl_NewStringObj((char*)sqlite3_value_text(pValue
), -1);
3574 Tcl_SetObjResult(interp
, pObj
);
3576 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
3581 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
3586 ** $db wal_hook ?script?
3587 ** $db update_hook ?script?
3588 ** $db rollback_hook ?script?
3591 case DB_UPDATE_HOOK
:
3592 case DB_ROLLBACK_HOOK
: {
3593 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
3594 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3596 Tcl_Obj
**ppHook
= 0;
3597 if( choice
==DB_WAL_HOOK
) ppHook
= &pDb
->pWalHook
;
3598 if( choice
==DB_UPDATE_HOOK
) ppHook
= &pDb
->pUpdateHook
;
3599 if( choice
==DB_ROLLBACK_HOOK
) ppHook
= &pDb
->pRollbackHook
;
3601 Tcl_WrongNumArgs(interp
, 2, objv
, "?SCRIPT?");
3605 DbHookCmd(interp
, pDb
, (objc
==3 ? objv
[2] : 0), ppHook
);
3611 ** Return the version string for this database.
3615 for(i
=2; i
<objc
; i
++){
3616 const char *zArg
= Tcl_GetString(objv
[i
]);
3617 /* Optional arguments to $db version are used for testing purpose */
3619 /* $db version -use-legacy-prepare BOOLEAN
3621 ** Turn the use of legacy sqlite3_prepare() on or off.
3623 if( strcmp(zArg
, "-use-legacy-prepare")==0 && i
+1<objc
){
3625 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &pDb
->bLegacyPrepare
) ){
3630 /* $db version -last-stmt-ptr
3632 ** Return a string which is a hex encoding of the pointer to the
3633 ** most recent sqlite3_stmt in the statement cache.
3635 if( strcmp(zArg
, "-last-stmt-ptr")==0 ){
3637 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%p",
3638 pDb
->stmtList
? pDb
->stmtList
->pStmt
: 0);
3639 Tcl_SetResult(interp
, zBuf
, TCL_VOLATILE
);
3641 #endif /* SQLITE_TEST */
3643 Tcl_AppendResult(interp
, "unknown argument: ", zArg
, (char*)0);
3648 Tcl_SetResult(interp
, (char *)sqlite3_libversion(), TCL_STATIC
);
3654 } /* End of the SWITCH statement */
3660 ** Adaptor that provides an objCmd interface to the NRE-enabled
3661 ** interface implementation.
3663 static int SQLITE_TCLAPI
DbObjCmdAdaptor(
3669 return Tcl_NRCallObjProc(interp
, DbObjCmd
, cd
, objc
, objv
);
3671 #endif /* SQLITE_TCL_NRE */
3674 ** Issue the usage message when the "sqlite3" command arguments are
3677 static int sqliteCmdUsage(
3681 Tcl_WrongNumArgs(interp
, 1, objv
,
3682 "HANDLE ?FILENAME? ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
3683 " ?-nofollow BOOLEAN?"
3684 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
3685 /* BEGIN SQLCIPHER */
3686 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3695 ** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
3696 ** ?-create BOOLEAN? ?-nomutex BOOLEAN?
3697 ** ?-nofollow BOOLEAN?
3699 ** This is the main Tcl command. When the "sqlite" Tcl command is
3700 ** invoked, this routine runs to process that command.
3702 ** The first argument, DBNAME, is an arbitrary name for a new
3703 ** database connection. This command creates a new command named
3704 ** DBNAME that is used to control that connection. The database
3705 ** connection is deleted when the DBNAME command is deleted.
3707 ** The second argument is the name of the database file.
3710 static int SQLITE_TCLAPI
DbMain(
3720 const char *zFile
= 0;
3721 const char *zVfs
= 0;
3723 int bTranslateFileName
= 1;
3724 Tcl_DString translatedFilename
;
3725 /* BEGIN SQLCIPHER */
3726 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3733 /* In normal use, each TCL interpreter runs in a single thread. So
3734 ** by default, we can turn off mutexing on SQLite database connections.
3735 ** However, for testing purposes it is useful to have mutexes turned
3736 ** on. So, by default, mutexes default off. But if compiled with
3737 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3739 #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3740 flags
= SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
| SQLITE_OPEN_FULLMUTEX
;
3742 flags
= SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
| SQLITE_OPEN_NOMUTEX
;
3745 if( objc
==1 ) return sqliteCmdUsage(interp
, objv
);
3747 zArg
= Tcl_GetStringFromObj(objv
[1], 0);
3748 if( strcmp(zArg
,"-version")==0 ){
3749 Tcl_AppendResult(interp
,sqlite3_libversion(), (char*)0);
3752 if( strcmp(zArg
,"-sourceid")==0 ){
3753 Tcl_AppendResult(interp
,sqlite3_sourceid(), (char*)0);
3756 if( strcmp(zArg
,"-has-codec")==0 ){
3757 /* BEGIN SQLCIPHER */
3758 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3759 Tcl_AppendResult(interp
,"1",(char*)0);
3761 Tcl_AppendResult(interp
,"0",(char*)0);
3766 if( zArg
[0]=='-' ) return sqliteCmdUsage(interp
, objv
);
3768 for(i
=2; i
<objc
; i
++){
3769 zArg
= Tcl_GetString(objv
[i
]);
3771 if( zFile
!=0 ) return sqliteCmdUsage(interp
, objv
);
3775 if( i
==objc
-1 ) return sqliteCmdUsage(interp
, objv
);
3777 if( strcmp(zArg
,"-key")==0 ){
3778 /* BEGIN SQLCIPHER */
3779 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3780 pKey
= Tcl_GetByteArrayFromObj(objv
[i
], &nKey
);
3783 }else if( strcmp(zArg
, "-vfs")==0 ){
3784 zVfs
= Tcl_GetString(objv
[i
]);
3785 }else if( strcmp(zArg
, "-readonly")==0 ){
3787 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &b
) ) return TCL_ERROR
;
3789 flags
&= ~(SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
);
3790 flags
|= SQLITE_OPEN_READONLY
;
3792 flags
&= ~SQLITE_OPEN_READONLY
;
3793 flags
|= SQLITE_OPEN_READWRITE
;
3795 }else if( strcmp(zArg
, "-create")==0 ){
3797 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &b
) ) return TCL_ERROR
;
3798 if( b
&& (flags
& SQLITE_OPEN_READONLY
)==0 ){
3799 flags
|= SQLITE_OPEN_CREATE
;
3801 flags
&= ~SQLITE_OPEN_CREATE
;
3803 }else if( strcmp(zArg
, "-nofollow")==0 ){
3805 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &b
) ) return TCL_ERROR
;
3807 flags
|= SQLITE_OPEN_NOFOLLOW
;
3809 flags
&= ~SQLITE_OPEN_NOFOLLOW
;
3811 }else if( strcmp(zArg
, "-nomutex")==0 ){
3813 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &b
) ) return TCL_ERROR
;
3815 flags
|= SQLITE_OPEN_NOMUTEX
;
3816 flags
&= ~SQLITE_OPEN_FULLMUTEX
;
3818 flags
&= ~SQLITE_OPEN_NOMUTEX
;
3820 }else if( strcmp(zArg
, "-fullmutex")==0 ){
3822 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &b
) ) return TCL_ERROR
;
3824 flags
|= SQLITE_OPEN_FULLMUTEX
;
3825 flags
&= ~SQLITE_OPEN_NOMUTEX
;
3827 flags
&= ~SQLITE_OPEN_FULLMUTEX
;
3829 }else if( strcmp(zArg
, "-uri")==0 ){
3831 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &b
) ) return TCL_ERROR
;
3833 flags
|= SQLITE_OPEN_URI
;
3835 flags
&= ~SQLITE_OPEN_URI
;
3837 }else if( strcmp(zArg
, "-translatefilename")==0 ){
3838 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &bTranslateFileName
) ){
3842 Tcl_AppendResult(interp
, "unknown option: ", zArg
, (char*)0);
3847 p
= (SqliteDb
*)Tcl_Alloc( sizeof(*p
) );
3848 memset(p
, 0, sizeof(*p
));
3849 if( zFile
==0 ) zFile
= "";
3850 if( bTranslateFileName
){
3851 zFile
= Tcl_TranslateFileName(interp
, zFile
, &translatedFilename
);
3853 rc
= sqlite3_open_v2(zFile
, &p
->db
, flags
, zVfs
);
3854 if( bTranslateFileName
){
3855 Tcl_DStringFree(&translatedFilename
);
3858 if( SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
3859 zErrMsg
= sqlite3_mprintf("%s", sqlite3_errmsg(p
->db
));
3860 sqlite3_close(p
->db
);
3864 zErrMsg
= sqlite3_mprintf("%s", sqlite3_errstr(rc
));
3866 /* BEGIN SQLCIPHER */
3867 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3869 sqlite3_key(p
->db
, pKey
, nKey
);
3874 Tcl_SetResult(interp
, zErrMsg
, TCL_VOLATILE
);
3876 sqlite3_free(zErrMsg
);
3879 p
->maxStmt
= NUM_PREPARED_STMTS
;
3880 p
->openFlags
= flags
& SQLITE_OPEN_URI
;
3882 zArg
= Tcl_GetStringFromObj(objv
[1], 0);
3884 Tcl_NRCreateCommand(interp
, zArg
, DbObjCmdAdaptor
, DbObjCmd
,
3885 (char*)p
, DbDeleteCmd
);
3887 Tcl_CreateObjCommand(interp
, zArg
, DbObjCmd
, (char*)p
, DbDeleteCmd
);
3893 ** Provide a dummy Tcl_InitStubs if we are using this as a static
3896 #ifndef USE_TCL_STUBS
3897 # undef Tcl_InitStubs
3898 # define Tcl_InitStubs(a,b,c) TCL_VERSION
3902 ** Make sure we have a PACKAGE_VERSION macro defined. This will be
3903 ** defined automatically by the TEA makefile. But other makefiles
3904 ** do not define it.
3906 #ifndef PACKAGE_VERSION
3907 # define PACKAGE_VERSION SQLITE_VERSION
3911 ** Initialize this module.
3913 ** This Tcl module contains only a single new Tcl command named "sqlite".
3914 ** (Hence there is no namespace. There is no point in using a namespace
3915 ** if the extension only supplies one new name!) The "sqlite" command is
3916 ** used to open a new SQLite database. See the DbMain() routine above
3917 ** for additional information.
3919 ** The EXTERN macros are required by TCL in order to work on windows.
3921 EXTERN
int Sqlite3_Init(Tcl_Interp
*interp
){
3922 int rc
= Tcl_InitStubs(interp
, "8.4", 0) ? TCL_OK
: TCL_ERROR
;
3924 Tcl_CreateObjCommand(interp
, "sqlite3", (Tcl_ObjCmdProc
*)DbMain
, 0, 0);
3925 #ifndef SQLITE_3_SUFFIX_ONLY
3926 /* The "sqlite" alias is undocumented. It is here only to support
3927 ** legacy scripts. All new scripts should use only the "sqlite3"
3929 Tcl_CreateObjCommand(interp
, "sqlite", (Tcl_ObjCmdProc
*)DbMain
, 0, 0);
3931 rc
= Tcl_PkgProvide(interp
, "sqlite3", PACKAGE_VERSION
);
3935 EXTERN
int Tclsqlite3_Init(Tcl_Interp
*interp
){ return Sqlite3_Init(interp
); }
3936 EXTERN
int Sqlite3_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3937 EXTERN
int Tclsqlite3_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3939 /* Because it accesses the file-system and uses persistent state, SQLite
3940 ** is not considered appropriate for safe interpreters. Hence, we cause
3941 ** the _SafeInit() interfaces return TCL_ERROR.
3943 EXTERN
int Sqlite3_SafeInit(Tcl_Interp
*interp
){ return TCL_ERROR
; }
3944 EXTERN
int Sqlite3_SafeUnload(Tcl_Interp
*interp
, int flags
){return TCL_ERROR
;}
3948 #ifndef SQLITE_3_SUFFIX_ONLY
3949 int Sqlite_Init(Tcl_Interp
*interp
){ return Sqlite3_Init(interp
); }
3950 int Tclsqlite_Init(Tcl_Interp
*interp
){ return Sqlite3_Init(interp
); }
3951 int Sqlite_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3952 int Tclsqlite_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3956 ** If the TCLSH macro is defined, add code to make a stand-alone program.
3960 /* This is the main routine for an ordinary TCL shell. If there are
3961 ** are arguments, run the first argument as a script. Otherwise,
3962 ** read TCL commands from standard input
3964 static const char *tclsh_main_loop(void){
3965 static const char zMainloop
[] =
3966 "if {[llength $argv]>=1} {\n"
3967 "set argv0 [lindex $argv 0]\n"
3968 "set argv [lrange $argv 1 end]\n"
3972 "while {![eof stdin]} {\n"
3973 "if {$line!=\"\"} {\n"
3974 "puts -nonewline \"> \"\n"
3976 "puts -nonewline \"% \"\n"
3979 "append line [gets stdin]\n"
3980 "if {[info complete $line]} {\n"
3981 "if {[catch {uplevel #0 $line} result]} {\n"
3982 "puts stderr \"Error: $result\"\n"
3983 "} elseif {$result!=\"\"} {\n"
3996 #define TCLSH_MAIN main /* Needed to fake out mktclapp */
3997 int SQLITE_CDECL
TCLSH_MAIN(int argc
, char **argv
){
4000 const char *zScript
= 0;
4002 #if defined(TCLSH_INIT_PROC)
4003 extern const char *TCLSH_INIT_PROC(Tcl_Interp
*);
4006 #if !defined(_WIN32_WCE)
4007 if( getenv("SQLITE_DEBUG_BREAK") ){
4008 if( isatty(0) && isatty(2) ){
4010 "attach debugger to process %d and press any key to continue.\n",
4014 #if defined(_WIN32) || defined(WIN32)
4016 #elif defined(SIGTRAP)
4023 /* Call sqlite3_shutdown() once before doing anything else. This is to
4024 ** test that sqlite3_shutdown() can be safely called by a process before
4025 ** sqlite3_initialize() is. */
4028 Tcl_FindExecutable(argv
[0]);
4029 Tcl_SetSystemEncoding(NULL
, "utf-8");
4030 interp
= Tcl_CreateInterp();
4031 Sqlite3_Init(interp
);
4033 sqlite3_snprintf(sizeof(zArgc
), zArgc
, "%d", argc
-1);
4034 Tcl_SetVar(interp
,"argc", zArgc
, TCL_GLOBAL_ONLY
);
4035 Tcl_SetVar(interp
,"argv0",argv
[0],TCL_GLOBAL_ONLY
);
4036 Tcl_SetVar(interp
,"argv", "", TCL_GLOBAL_ONLY
);
4037 for(i
=1; i
<argc
; i
++){
4038 Tcl_SetVar(interp
, "argv", argv
[i
],
4039 TCL_GLOBAL_ONLY
| TCL_LIST_ELEMENT
| TCL_APPEND_VALUE
);
4041 #if defined(TCLSH_INIT_PROC)
4042 zScript
= TCLSH_INIT_PROC(interp
);
4045 zScript
= tclsh_main_loop();
4047 if( Tcl_GlobalEval(interp
, zScript
)!=TCL_OK
){
4048 const char *zInfo
= Tcl_GetVar(interp
, "errorInfo", TCL_GLOBAL_ONLY
);
4049 if( zInfo
==0 ) zInfo
= Tcl_GetStringResult(interp
);
4050 fprintf(stderr
,"%s: %s\n", *argv
, zInfo
);