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) */
184 int nRef
; /* Delete object when this reaches 0 */
186 int bLegacyPrepare
; /* True to use sqlite3_prepare() */
190 struct IncrblobChannel
{
191 sqlite3_blob
*pBlob
; /* sqlite3 blob handle */
192 SqliteDb
*pDb
; /* Associated database connection */
193 int iSeek
; /* Current seek offset */
194 Tcl_Channel channel
; /* Channel identifier */
195 IncrblobChannel
*pNext
; /* Linked list of all open incrblob channels */
196 IncrblobChannel
*pPrev
; /* Linked list of all open incrblob channels */
200 ** Compute a string length that is limited to what can be stored in
201 ** lower 30 bits of a 32-bit signed integer.
203 static int strlen30(const char *z
){
205 while( *z2
){ z2
++; }
206 return 0x3fffffff & (int)(z2
- z
);
210 #ifndef SQLITE_OMIT_INCRBLOB
212 ** Close all incrblob channels opened using database connection pDb.
213 ** This is called when shutting down the database connection.
215 static void closeIncrblobChannels(SqliteDb
*pDb
){
217 IncrblobChannel
*pNext
;
219 for(p
=pDb
->pIncrblob
; p
; p
=pNext
){
222 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
223 ** which deletes the IncrblobChannel structure at *p. So do not
224 ** call Tcl_Free() here.
226 Tcl_UnregisterChannel(pDb
->interp
, p
->channel
);
231 ** Close an incremental blob channel.
233 static int SQLITE_TCLAPI
incrblobClose(
234 ClientData instanceData
,
237 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
238 int rc
= sqlite3_blob_close(p
->pBlob
);
239 sqlite3
*db
= p
->pDb
->db
;
241 /* Remove the channel from the SqliteDb.pIncrblob list. */
243 p
->pNext
->pPrev
= p
->pPrev
;
246 p
->pPrev
->pNext
= p
->pNext
;
248 if( p
->pDb
->pIncrblob
==p
){
249 p
->pDb
->pIncrblob
= p
->pNext
;
252 /* Free the IncrblobChannel structure */
256 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(db
), TCL_VOLATILE
);
263 ** Read data from an incremental blob channel.
265 static int SQLITE_TCLAPI
incrblobInput(
266 ClientData instanceData
,
271 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
272 int nRead
= bufSize
; /* Number of bytes to read */
273 int nBlob
; /* Total size of the blob */
274 int rc
; /* sqlite error code */
276 nBlob
= sqlite3_blob_bytes(p
->pBlob
);
277 if( (p
->iSeek
+nRead
)>nBlob
){
278 nRead
= nBlob
-p
->iSeek
;
284 rc
= sqlite3_blob_read(p
->pBlob
, (void *)buf
, nRead
, p
->iSeek
);
295 ** Write data to an incremental blob channel.
297 static int SQLITE_TCLAPI
incrblobOutput(
298 ClientData instanceData
,
303 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
304 int nWrite
= toWrite
; /* Number of bytes to write */
305 int nBlob
; /* Total size of the blob */
306 int rc
; /* sqlite error code */
308 nBlob
= sqlite3_blob_bytes(p
->pBlob
);
309 if( (p
->iSeek
+nWrite
)>nBlob
){
310 *errorCodePtr
= EINVAL
;
317 rc
= sqlite3_blob_write(p
->pBlob
, (void *)buf
, nWrite
, p
->iSeek
);
328 ** Seek an incremental blob channel.
330 static int SQLITE_TCLAPI
incrblobSeek(
331 ClientData instanceData
,
336 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
346 p
->iSeek
= sqlite3_blob_bytes(p
->pBlob
) + offset
;
349 default: assert(!"Bad seekMode");
356 static void SQLITE_TCLAPI
incrblobWatch(
357 ClientData instanceData
,
362 static int SQLITE_TCLAPI
incrblobHandle(
363 ClientData instanceData
,
370 static Tcl_ChannelType IncrblobChannelType
= {
371 "incrblob", /* typeName */
372 TCL_CHANNEL_VERSION_2
, /* version */
373 incrblobClose
, /* closeProc */
374 incrblobInput
, /* inputProc */
375 incrblobOutput
, /* outputProc */
376 incrblobSeek
, /* seekProc */
377 0, /* setOptionProc */
378 0, /* getOptionProc */
379 incrblobWatch
, /* watchProc (this is a no-op) */
380 incrblobHandle
, /* getHandleProc (always returns error) */
382 0, /* blockModeProc */
385 0, /* wideSeekProc */
389 ** Create a new incrblob channel.
391 static int createIncrblobChannel(
401 sqlite3
*db
= pDb
->db
;
404 int flags
= TCL_READABLE
|(isReadonly
? 0 : TCL_WRITABLE
);
406 /* This variable is used to name the channels: "incrblob_[incr count]" */
407 static int count
= 0;
410 rc
= sqlite3_blob_open(db
, zDb
, zTable
, zColumn
, iRow
, !isReadonly
, &pBlob
);
412 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(pDb
->db
), TCL_VOLATILE
);
416 p
= (IncrblobChannel
*)Tcl_Alloc(sizeof(IncrblobChannel
));
420 sqlite3_snprintf(sizeof(zChannel
), zChannel
, "incrblob_%d", ++count
);
421 p
->channel
= Tcl_CreateChannel(&IncrblobChannelType
, zChannel
, p
, flags
);
422 Tcl_RegisterChannel(interp
, p
->channel
);
424 /* Link the new channel into the SqliteDb.pIncrblob list. */
425 p
->pNext
= pDb
->pIncrblob
;
433 Tcl_SetResult(interp
, (char *)Tcl_GetChannelName(p
->channel
), TCL_VOLATILE
);
436 #else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
437 #define closeIncrblobChannels(pDb)
441 ** Look at the script prefix in pCmd. We will be executing this script
442 ** after first appending one or more arguments. This routine analyzes
443 ** the script to see if it is safe to use Tcl_EvalObjv() on the script
444 ** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
447 ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
448 ** command name followed by zero or more arguments with no [...] or $
449 ** or {...} or ; to be seen anywhere. Most callback scripts consist
450 ** of just a single procedure name and they meet this requirement.
452 static int safeToUseEvalObjv(Tcl_Interp
*interp
, Tcl_Obj
*pCmd
){
453 /* We could try to do something with Tcl_Parse(). But we will instead
454 ** just do a search for forbidden characters. If any of the forbidden
455 ** characters appear in pCmd, we will report the string as unsafe.
459 z
= Tcl_GetStringFromObj(pCmd
, &n
);
462 if( c
=='$' || c
=='[' || c
==';' ) return 0;
468 ** Find an SqlFunc structure with the given name. Or create a new
469 ** one if an existing one cannot be found. Return a pointer to the
472 static SqlFunc
*findSqlFunc(SqliteDb
*pDb
, const char *zName
){
474 int nName
= strlen30(zName
);
475 pNew
= (SqlFunc
*)Tcl_Alloc( sizeof(*pNew
) + nName
+ 1 );
476 pNew
->zName
= (char*)&pNew
[1];
477 memcpy(pNew
->zName
, zName
, nName
+1);
478 for(p
=pDb
->pFunc
; p
; p
=p
->pNext
){
479 if( sqlite3_stricmp(p
->zName
, pNew
->zName
)==0 ){
480 Tcl_Free((char*)pNew
);
484 pNew
->interp
= pDb
->interp
;
487 pNew
->pNext
= pDb
->pFunc
;
493 ** Free a single SqlPreparedStmt object.
495 static void dbFreeStmt(SqlPreparedStmt
*pStmt
){
497 if( sqlite3_sql(pStmt
->pStmt
)==0 ){
498 Tcl_Free((char *)pStmt
->zSql
);
501 sqlite3_finalize(pStmt
->pStmt
);
502 Tcl_Free((char *)pStmt
);
506 ** Finalize and free a list of prepared statements
508 static void flushStmtCache(SqliteDb
*pDb
){
509 SqlPreparedStmt
*pPreStmt
;
510 SqlPreparedStmt
*pNext
;
512 for(pPreStmt
= pDb
->stmtList
; pPreStmt
; pPreStmt
=pNext
){
513 pNext
= pPreStmt
->pNext
;
514 dbFreeStmt(pPreStmt
);
522 ** Increment the reference counter on the SqliteDb object. The reference
523 ** should be released by calling delDatabaseRef().
525 static void addDatabaseRef(SqliteDb
*pDb
){
530 ** Decrement the reference counter associated with the SqliteDb object.
531 ** If it reaches zero, delete the object.
533 static void delDatabaseRef(SqliteDb
*pDb
){
534 assert( pDb
->nRef
>0 );
538 closeIncrblobChannels(pDb
);
539 sqlite3_close(pDb
->db
);
541 SqlFunc
*pFunc
= pDb
->pFunc
;
542 pDb
->pFunc
= pFunc
->pNext
;
543 assert( pFunc
->pDb
==pDb
);
544 Tcl_DecrRefCount(pFunc
->pScript
);
545 Tcl_Free((char*)pFunc
);
547 while( pDb
->pCollate
){
548 SqlCollate
*pCollate
= pDb
->pCollate
;
549 pDb
->pCollate
= pCollate
->pNext
;
550 Tcl_Free((char*)pCollate
);
553 Tcl_Free(pDb
->zBusy
);
556 Tcl_Free(pDb
->zTrace
);
559 Tcl_Free(pDb
->zTraceV2
);
562 Tcl_Free(pDb
->zProfile
);
564 if( pDb
->zBindFallback
){
565 Tcl_Free(pDb
->zBindFallback
);
568 Tcl_Free(pDb
->zAuth
);
571 Tcl_Free(pDb
->zNull
);
573 if( pDb
->pUpdateHook
){
574 Tcl_DecrRefCount(pDb
->pUpdateHook
);
576 if( pDb
->pPreUpdateHook
){
577 Tcl_DecrRefCount(pDb
->pPreUpdateHook
);
579 if( pDb
->pRollbackHook
){
580 Tcl_DecrRefCount(pDb
->pRollbackHook
);
583 Tcl_DecrRefCount(pDb
->pWalHook
);
585 if( pDb
->pCollateNeeded
){
586 Tcl_DecrRefCount(pDb
->pCollateNeeded
);
588 Tcl_Free((char*)pDb
);
593 ** TCL calls this procedure when an sqlite3 database command is
596 static void SQLITE_TCLAPI
DbDeleteCmd(void *db
){
597 SqliteDb
*pDb
= (SqliteDb
*)db
;
602 ** This routine is called when a database file is locked while trying
605 static int DbBusyHandler(void *cd
, int nTries
){
606 SqliteDb
*pDb
= (SqliteDb
*)cd
;
610 sqlite3_snprintf(sizeof(zVal
), zVal
, "%d", nTries
);
611 rc
= Tcl_VarEval(pDb
->interp
, pDb
->zBusy
, " ", zVal
, (char*)0);
612 if( rc
!=TCL_OK
|| atoi(Tcl_GetStringResult(pDb
->interp
)) ){
618 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
620 ** This routine is invoked as the 'progress callback' for the database.
622 static int DbProgressHandler(void *cd
){
623 SqliteDb
*pDb
= (SqliteDb
*)cd
;
626 assert( pDb
->zProgress
);
627 rc
= Tcl_Eval(pDb
->interp
, pDb
->zProgress
);
628 if( rc
!=TCL_OK
|| atoi(Tcl_GetStringResult(pDb
->interp
)) ){
635 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
636 !defined(SQLITE_OMIT_DEPRECATED)
638 ** This routine is called by the SQLite trace handler whenever a new
639 ** block of SQL is executed. The TCL script in pDb->zTrace is executed.
641 static void DbTraceHandler(void *cd
, const char *zSql
){
642 SqliteDb
*pDb
= (SqliteDb
*)cd
;
645 Tcl_DStringInit(&str
);
646 Tcl_DStringAppend(&str
, pDb
->zTrace
, -1);
647 Tcl_DStringAppendElement(&str
, zSql
);
648 Tcl_Eval(pDb
->interp
, Tcl_DStringValue(&str
));
649 Tcl_DStringFree(&str
);
650 Tcl_ResetResult(pDb
->interp
);
654 #ifndef SQLITE_OMIT_TRACE
656 ** This routine is called by the SQLite trace_v2 handler whenever a new
657 ** supported event is generated. Unsupported event types are ignored.
658 ** The TCL script in pDb->zTraceV2 is executed, with the arguments for
659 ** the event appended to it (as list elements).
661 static int DbTraceV2Handler(
662 unsigned type
, /* One of the SQLITE_TRACE_* event types. */
663 void *cd
, /* The original context data pointer. */
664 void *pd
, /* Primary event data, depends on event type. */
665 void *xd
/* Extra event data, depends on event type. */
667 SqliteDb
*pDb
= (SqliteDb
*)cd
;
671 case SQLITE_TRACE_STMT
: {
672 sqlite3_stmt
*pStmt
= (sqlite3_stmt
*)pd
;
673 char *zSql
= (char *)xd
;
675 pCmd
= Tcl_NewStringObj(pDb
->zTraceV2
, -1);
676 Tcl_IncrRefCount(pCmd
);
677 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
678 Tcl_NewWideIntObj((Tcl_WideInt
)pStmt
));
679 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
680 Tcl_NewStringObj(zSql
, -1));
681 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
682 Tcl_DecrRefCount(pCmd
);
683 Tcl_ResetResult(pDb
->interp
);
686 case SQLITE_TRACE_PROFILE
: {
687 sqlite3_stmt
*pStmt
= (sqlite3_stmt
*)pd
;
688 sqlite3_int64 ns
= *(sqlite3_int64
*)xd
;
690 pCmd
= Tcl_NewStringObj(pDb
->zTraceV2
, -1);
691 Tcl_IncrRefCount(pCmd
);
692 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
693 Tcl_NewWideIntObj((Tcl_WideInt
)pStmt
));
694 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
695 Tcl_NewWideIntObj((Tcl_WideInt
)ns
));
696 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
697 Tcl_DecrRefCount(pCmd
);
698 Tcl_ResetResult(pDb
->interp
);
701 case SQLITE_TRACE_ROW
: {
702 sqlite3_stmt
*pStmt
= (sqlite3_stmt
*)pd
;
704 pCmd
= Tcl_NewStringObj(pDb
->zTraceV2
, -1);
705 Tcl_IncrRefCount(pCmd
);
706 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
707 Tcl_NewWideIntObj((Tcl_WideInt
)pStmt
));
708 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
709 Tcl_DecrRefCount(pCmd
);
710 Tcl_ResetResult(pDb
->interp
);
713 case SQLITE_TRACE_CLOSE
: {
714 sqlite3
*db
= (sqlite3
*)pd
;
716 pCmd
= Tcl_NewStringObj(pDb
->zTraceV2
, -1);
717 Tcl_IncrRefCount(pCmd
);
718 Tcl_ListObjAppendElement(pDb
->interp
, pCmd
,
719 Tcl_NewWideIntObj((Tcl_WideInt
)db
));
720 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
721 Tcl_DecrRefCount(pCmd
);
722 Tcl_ResetResult(pDb
->interp
);
730 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
731 !defined(SQLITE_OMIT_DEPRECATED)
733 ** This routine is called by the SQLite profile handler after a statement
734 ** SQL has executed. The TCL script in pDb->zProfile is evaluated.
736 static void DbProfileHandler(void *cd
, const char *zSql
, sqlite_uint64 tm
){
737 SqliteDb
*pDb
= (SqliteDb
*)cd
;
741 sqlite3_snprintf(sizeof(zTm
)-1, zTm
, "%lld", tm
);
742 Tcl_DStringInit(&str
);
743 Tcl_DStringAppend(&str
, pDb
->zProfile
, -1);
744 Tcl_DStringAppendElement(&str
, zSql
);
745 Tcl_DStringAppendElement(&str
, zTm
);
746 Tcl_Eval(pDb
->interp
, Tcl_DStringValue(&str
));
747 Tcl_DStringFree(&str
);
748 Tcl_ResetResult(pDb
->interp
);
753 ** This routine is called when a transaction is committed. The
754 ** TCL script in pDb->zCommit is executed. If it returns non-zero or
755 ** if it throws an exception, the transaction is rolled back instead
756 ** of being committed.
758 static int DbCommitHandler(void *cd
){
759 SqliteDb
*pDb
= (SqliteDb
*)cd
;
762 rc
= Tcl_Eval(pDb
->interp
, pDb
->zCommit
);
763 if( rc
!=TCL_OK
|| atoi(Tcl_GetStringResult(pDb
->interp
)) ){
769 static void DbRollbackHandler(void *clientData
){
770 SqliteDb
*pDb
= (SqliteDb
*)clientData
;
771 assert(pDb
->pRollbackHook
);
772 if( TCL_OK
!=Tcl_EvalObjEx(pDb
->interp
, pDb
->pRollbackHook
, 0) ){
773 Tcl_BackgroundError(pDb
->interp
);
778 ** This procedure handles wal_hook callbacks.
780 static int DbWalHandler(
788 SqliteDb
*pDb
= (SqliteDb
*)clientData
;
789 Tcl_Interp
*interp
= pDb
->interp
;
790 assert(pDb
->pWalHook
);
792 assert( db
==pDb
->db
);
793 p
= Tcl_DuplicateObj(pDb
->pWalHook
);
795 Tcl_ListObjAppendElement(interp
, p
, Tcl_NewStringObj(zDb
, -1));
796 Tcl_ListObjAppendElement(interp
, p
, Tcl_NewIntObj(nEntry
));
797 if( TCL_OK
!=Tcl_EvalObjEx(interp
, p
, 0)
798 || TCL_OK
!=Tcl_GetIntFromObj(interp
, Tcl_GetObjResult(interp
), &ret
)
800 Tcl_BackgroundError(interp
);
807 #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
808 static void setTestUnlockNotifyVars(Tcl_Interp
*interp
, int iArg
, int nArg
){
810 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%d", iArg
);
811 Tcl_SetVar(interp
, "sqlite_unlock_notify_arg", zBuf
, TCL_GLOBAL_ONLY
);
812 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%d", nArg
);
813 Tcl_SetVar(interp
, "sqlite_unlock_notify_argcount", zBuf
, TCL_GLOBAL_ONLY
);
816 # define setTestUnlockNotifyVars(x,y,z)
819 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
820 static void DbUnlockNotify(void **apArg
, int nArg
){
822 for(i
=0; i
<nArg
; i
++){
823 const int flags
= (TCL_EVAL_GLOBAL
|TCL_EVAL_DIRECT
);
824 SqliteDb
*pDb
= (SqliteDb
*)apArg
[i
];
825 setTestUnlockNotifyVars(pDb
->interp
, i
, nArg
);
826 assert( pDb
->pUnlockNotify
);
827 Tcl_EvalObjEx(pDb
->interp
, pDb
->pUnlockNotify
, flags
);
828 Tcl_DecrRefCount(pDb
->pUnlockNotify
);
829 pDb
->pUnlockNotify
= 0;
834 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
836 ** Pre-update hook callback.
838 static void DbPreUpdateHandler(
847 SqliteDb
*pDb
= (SqliteDb
*)p
;
849 static const char *azStr
[] = {"DELETE", "INSERT", "UPDATE"};
851 assert( (SQLITE_DELETE
-1)/9 == 0 );
852 assert( (SQLITE_INSERT
-1)/9 == 1 );
853 assert( (SQLITE_UPDATE
-1)/9 == 2 );
854 assert( pDb
->pPreUpdateHook
);
855 assert( db
==pDb
->db
);
856 assert( op
==SQLITE_INSERT
|| op
==SQLITE_UPDATE
|| op
==SQLITE_DELETE
);
858 pCmd
= Tcl_DuplicateObj(pDb
->pPreUpdateHook
);
859 Tcl_IncrRefCount(pCmd
);
860 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(azStr
[(op
-1)/9], -1));
861 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(zDb
, -1));
862 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(zTbl
, -1));
863 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewWideIntObj(iKey1
));
864 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewWideIntObj(iKey2
));
865 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
866 Tcl_DecrRefCount(pCmd
);
868 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
870 static void DbUpdateHandler(
877 SqliteDb
*pDb
= (SqliteDb
*)p
;
879 static const char *azStr
[] = {"DELETE", "INSERT", "UPDATE"};
881 assert( (SQLITE_DELETE
-1)/9 == 0 );
882 assert( (SQLITE_INSERT
-1)/9 == 1 );
883 assert( (SQLITE_UPDATE
-1)/9 == 2 );
885 assert( pDb
->pUpdateHook
);
886 assert( op
==SQLITE_INSERT
|| op
==SQLITE_UPDATE
|| op
==SQLITE_DELETE
);
888 pCmd
= Tcl_DuplicateObj(pDb
->pUpdateHook
);
889 Tcl_IncrRefCount(pCmd
);
890 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(azStr
[(op
-1)/9], -1));
891 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(zDb
, -1));
892 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(zTbl
, -1));
893 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewWideIntObj(rowid
));
894 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
895 Tcl_DecrRefCount(pCmd
);
898 static void tclCollateNeeded(
904 SqliteDb
*pDb
= (SqliteDb
*)pCtx
;
905 Tcl_Obj
*pScript
= Tcl_DuplicateObj(pDb
->pCollateNeeded
);
906 Tcl_IncrRefCount(pScript
);
907 Tcl_ListObjAppendElement(0, pScript
, Tcl_NewStringObj(zName
, -1));
908 Tcl_EvalObjEx(pDb
->interp
, pScript
, 0);
909 Tcl_DecrRefCount(pScript
);
913 ** This routine is called to evaluate an SQL collation function implemented
916 static int tclSqlCollate(
923 SqlCollate
*p
= (SqlCollate
*)pCtx
;
926 pCmd
= Tcl_NewStringObj(p
->zScript
, -1);
927 Tcl_IncrRefCount(pCmd
);
928 Tcl_ListObjAppendElement(p
->interp
, pCmd
, Tcl_NewStringObj(zA
, nA
));
929 Tcl_ListObjAppendElement(p
->interp
, pCmd
, Tcl_NewStringObj(zB
, nB
));
930 Tcl_EvalObjEx(p
->interp
, pCmd
, TCL_EVAL_DIRECT
);
931 Tcl_DecrRefCount(pCmd
);
932 return (atoi(Tcl_GetStringResult(p
->interp
)));
936 ** This routine is called to evaluate an SQL function implemented
939 static void tclSqlFunc(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
){
940 SqlFunc
*p
= sqlite3_user_data(context
);
946 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
947 ** script object directly. This allows the TCL compiler to generate
948 ** bytecode for the command on the first invocation and thus make
949 ** subsequent invocations much faster. */
951 Tcl_IncrRefCount(pCmd
);
952 rc
= Tcl_EvalObjEx(p
->interp
, pCmd
, 0);
953 Tcl_DecrRefCount(pCmd
);
955 /* If there are arguments to the function, make a shallow copy of the
956 ** script object, lappend the arguments, then evaluate the copy.
958 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
959 ** The new Tcl_Obj contains pointers to the original list elements.
960 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
961 ** of the list to tclCmdNameType, that alternate representation will
962 ** be preserved and reused on the next invocation.
966 if( Tcl_ListObjGetElements(p
->interp
, p
->pScript
, &nArg
, &aArg
) ){
967 sqlite3_result_error(context
, Tcl_GetStringResult(p
->interp
), -1);
970 pCmd
= Tcl_NewListObj(nArg
, aArg
);
971 Tcl_IncrRefCount(pCmd
);
972 for(i
=0; i
<argc
; i
++){
973 sqlite3_value
*pIn
= argv
[i
];
976 /* Set pVal to contain the i'th column of this row. */
977 switch( sqlite3_value_type(pIn
) ){
979 int bytes
= sqlite3_value_bytes(pIn
);
980 pVal
= Tcl_NewByteArrayObj(sqlite3_value_blob(pIn
), bytes
);
983 case SQLITE_INTEGER
: {
984 sqlite_int64 v
= sqlite3_value_int64(pIn
);
985 if( v
>=-2147483647 && v
<=2147483647 ){
986 pVal
= Tcl_NewIntObj((int)v
);
988 pVal
= Tcl_NewWideIntObj(v
);
993 double r
= sqlite3_value_double(pIn
);
994 pVal
= Tcl_NewDoubleObj(r
);
998 pVal
= Tcl_NewStringObj(p
->pDb
->zNull
, -1);
1002 int bytes
= sqlite3_value_bytes(pIn
);
1003 pVal
= Tcl_NewStringObj((char *)sqlite3_value_text(pIn
), bytes
);
1007 rc
= Tcl_ListObjAppendElement(p
->interp
, pCmd
, pVal
);
1009 Tcl_DecrRefCount(pCmd
);
1010 sqlite3_result_error(context
, Tcl_GetStringResult(p
->interp
), -1);
1014 if( !p
->useEvalObjv
){
1015 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
1016 ** is a list without a string representation. To prevent this from
1017 ** happening, make sure pCmd has a valid string representation */
1018 Tcl_GetString(pCmd
);
1020 rc
= Tcl_EvalObjEx(p
->interp
, pCmd
, TCL_EVAL_DIRECT
);
1021 Tcl_DecrRefCount(pCmd
);
1024 if( rc
&& rc
!=TCL_RETURN
){
1025 sqlite3_result_error(context
, Tcl_GetStringResult(p
->interp
), -1);
1027 Tcl_Obj
*pVar
= Tcl_GetObjResult(p
->interp
);
1030 const char *zType
= (pVar
->typePtr
? pVar
->typePtr
->name
: "");
1032 int eType
= p
->eType
;
1034 if( eType
==SQLITE_NULL
){
1035 if( c
=='b' && strcmp(zType
,"bytearray")==0 && pVar
->bytes
==0 ){
1036 /* Only return a BLOB type if the Tcl variable is a bytearray and
1037 ** has no string representation. */
1038 eType
= SQLITE_BLOB
;
1039 }else if( (c
=='b' && strcmp(zType
,"boolean")==0)
1040 || (c
=='w' && strcmp(zType
,"wideInt")==0)
1041 || (c
=='i' && strcmp(zType
,"int")==0)
1043 eType
= SQLITE_INTEGER
;
1044 }else if( c
=='d' && strcmp(zType
,"double")==0 ){
1045 eType
= SQLITE_FLOAT
;
1047 eType
= SQLITE_TEXT
;
1053 data
= Tcl_GetByteArrayFromObj(pVar
, &n
);
1054 sqlite3_result_blob(context
, data
, n
, SQLITE_TRANSIENT
);
1057 case SQLITE_INTEGER
: {
1059 if( TCL_OK
==Tcl_GetWideIntFromObj(0, pVar
, &v
) ){
1060 sqlite3_result_int64(context
, v
);
1065 case SQLITE_FLOAT
: {
1067 if( TCL_OK
==Tcl_GetDoubleFromObj(0, pVar
, &r
) ){
1068 sqlite3_result_double(context
, r
);
1074 data
= (unsigned char *)Tcl_GetStringFromObj(pVar
, &n
);
1075 sqlite3_result_text(context
, (char *)data
, n
, SQLITE_TRANSIENT
);
1083 #ifndef SQLITE_OMIT_AUTHORIZATION
1085 ** This is the authentication function. It appends the authentication
1086 ** type code and the two arguments to zCmd[] then invokes the result
1087 ** on the interpreter. The reply is examined to determine if the
1088 ** authentication fails or succeeds.
1090 static int auth_callback(
1097 #ifdef SQLITE_USER_AUTHENTICATION
1105 /* EVIDENCE-OF: R-38590-62769 The first parameter to the authorizer
1106 ** callback is a copy of the third parameter to the
1107 ** sqlite3_set_authorizer() interface.
1109 SqliteDb
*pDb
= (SqliteDb
*)pArg
;
1110 if( pDb
->disableAuth
) return SQLITE_OK
;
1112 /* EVIDENCE-OF: R-56518-44310 The second parameter to the callback is an
1113 ** integer action code that specifies the particular action to be
1116 case SQLITE_COPY
: zCode
="SQLITE_COPY"; break;
1117 case SQLITE_CREATE_INDEX
: zCode
="SQLITE_CREATE_INDEX"; break;
1118 case SQLITE_CREATE_TABLE
: zCode
="SQLITE_CREATE_TABLE"; break;
1119 case SQLITE_CREATE_TEMP_INDEX
: zCode
="SQLITE_CREATE_TEMP_INDEX"; break;
1120 case SQLITE_CREATE_TEMP_TABLE
: zCode
="SQLITE_CREATE_TEMP_TABLE"; break;
1121 case SQLITE_CREATE_TEMP_TRIGGER
: zCode
="SQLITE_CREATE_TEMP_TRIGGER"; break;
1122 case SQLITE_CREATE_TEMP_VIEW
: zCode
="SQLITE_CREATE_TEMP_VIEW"; break;
1123 case SQLITE_CREATE_TRIGGER
: zCode
="SQLITE_CREATE_TRIGGER"; break;
1124 case SQLITE_CREATE_VIEW
: zCode
="SQLITE_CREATE_VIEW"; break;
1125 case SQLITE_DELETE
: zCode
="SQLITE_DELETE"; break;
1126 case SQLITE_DROP_INDEX
: zCode
="SQLITE_DROP_INDEX"; break;
1127 case SQLITE_DROP_TABLE
: zCode
="SQLITE_DROP_TABLE"; break;
1128 case SQLITE_DROP_TEMP_INDEX
: zCode
="SQLITE_DROP_TEMP_INDEX"; break;
1129 case SQLITE_DROP_TEMP_TABLE
: zCode
="SQLITE_DROP_TEMP_TABLE"; break;
1130 case SQLITE_DROP_TEMP_TRIGGER
: zCode
="SQLITE_DROP_TEMP_TRIGGER"; break;
1131 case SQLITE_DROP_TEMP_VIEW
: zCode
="SQLITE_DROP_TEMP_VIEW"; break;
1132 case SQLITE_DROP_TRIGGER
: zCode
="SQLITE_DROP_TRIGGER"; break;
1133 case SQLITE_DROP_VIEW
: zCode
="SQLITE_DROP_VIEW"; break;
1134 case SQLITE_INSERT
: zCode
="SQLITE_INSERT"; break;
1135 case SQLITE_PRAGMA
: zCode
="SQLITE_PRAGMA"; break;
1136 case SQLITE_READ
: zCode
="SQLITE_READ"; break;
1137 case SQLITE_SELECT
: zCode
="SQLITE_SELECT"; break;
1138 case SQLITE_TRANSACTION
: zCode
="SQLITE_TRANSACTION"; break;
1139 case SQLITE_UPDATE
: zCode
="SQLITE_UPDATE"; break;
1140 case SQLITE_ATTACH
: zCode
="SQLITE_ATTACH"; break;
1141 case SQLITE_DETACH
: zCode
="SQLITE_DETACH"; break;
1142 case SQLITE_ALTER_TABLE
: zCode
="SQLITE_ALTER_TABLE"; break;
1143 case SQLITE_REINDEX
: zCode
="SQLITE_REINDEX"; break;
1144 case SQLITE_ANALYZE
: zCode
="SQLITE_ANALYZE"; break;
1145 case SQLITE_CREATE_VTABLE
: zCode
="SQLITE_CREATE_VTABLE"; break;
1146 case SQLITE_DROP_VTABLE
: zCode
="SQLITE_DROP_VTABLE"; break;
1147 case SQLITE_FUNCTION
: zCode
="SQLITE_FUNCTION"; break;
1148 case SQLITE_SAVEPOINT
: zCode
="SQLITE_SAVEPOINT"; break;
1149 case SQLITE_RECURSIVE
: zCode
="SQLITE_RECURSIVE"; break;
1150 default : zCode
="????"; break;
1152 Tcl_DStringInit(&str
);
1153 Tcl_DStringAppend(&str
, pDb
->zAuth
, -1);
1154 Tcl_DStringAppendElement(&str
, zCode
);
1155 Tcl_DStringAppendElement(&str
, zArg1
? zArg1
: "");
1156 Tcl_DStringAppendElement(&str
, zArg2
? zArg2
: "");
1157 Tcl_DStringAppendElement(&str
, zArg3
? zArg3
: "");
1158 Tcl_DStringAppendElement(&str
, zArg4
? zArg4
: "");
1159 #ifdef SQLITE_USER_AUTHENTICATION
1160 Tcl_DStringAppendElement(&str
, zArg5
? zArg5
: "");
1162 rc
= Tcl_GlobalEval(pDb
->interp
, Tcl_DStringValue(&str
));
1163 Tcl_DStringFree(&str
);
1164 zReply
= rc
==TCL_OK
? Tcl_GetStringResult(pDb
->interp
) : "SQLITE_DENY";
1165 if( strcmp(zReply
,"SQLITE_OK")==0 ){
1167 }else if( strcmp(zReply
,"SQLITE_DENY")==0 ){
1169 }else if( strcmp(zReply
,"SQLITE_IGNORE")==0 ){
1176 #endif /* SQLITE_OMIT_AUTHORIZATION */
1179 ** This routine reads a line of text from FILE in, stores
1180 ** the text in memory obtained from malloc() and returns a pointer
1181 ** to the text. NULL is returned at end of file, or if malloc()
1184 ** The interface is like "readline" but no command-line editing
1187 ** copied from shell.c from '.import' command
1189 static char *local_getline(char *zPrompt
, FILE *in
){
1195 zLine
= malloc( nLine
);
1196 if( zLine
==0 ) return 0;
1200 nLine
= nLine
*2 + 100;
1201 zLine
= realloc(zLine
, nLine
);
1202 if( zLine
==0 ) return 0;
1204 if( fgets(&zLine
[n
], nLine
- n
, in
)==0 ){
1212 while( zLine
[n
] ){ n
++; }
1213 if( n
>0 && zLine
[n
-1]=='\n' ){
1219 zLine
= realloc( zLine
, n
+1 );
1225 ** This function is part of the implementation of the command:
1227 ** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1229 ** It is invoked after evaluating the script SCRIPT to commit or rollback
1230 ** the transaction or savepoint opened by the [transaction] command.
1232 static int SQLITE_TCLAPI
DbTransPostCmd(
1233 ClientData data
[], /* data[0] is the Sqlite3Db* for $db */
1234 Tcl_Interp
*interp
, /* Tcl interpreter */
1235 int result
/* Result of evaluating SCRIPT */
1237 static const char *const azEnd
[] = {
1238 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1239 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1240 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1241 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1243 SqliteDb
*pDb
= (SqliteDb
*)data
[0];
1247 pDb
->nTransaction
--;
1248 zEnd
= azEnd
[(rc
==TCL_ERROR
)*2 + (pDb
->nTransaction
==0)];
1251 if( sqlite3_exec(pDb
->db
, zEnd
, 0, 0, 0) ){
1252 /* This is a tricky scenario to handle. The most likely cause of an
1253 ** error is that the exec() above was an attempt to commit the
1254 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1255 ** that an IO-error has occurred. In either case, throw a Tcl exception
1256 ** and try to rollback the transaction.
1258 ** But it could also be that the user executed one or more BEGIN,
1259 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1260 ** this method's logic. Not clear how this would be best handled.
1262 if( rc
!=TCL_ERROR
){
1263 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
1266 sqlite3_exec(pDb
->db
, "ROLLBACK", 0, 0, 0);
1270 delDatabaseRef(pDb
);
1275 ** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1276 ** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1277 ** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1278 ** on whether or not the [db_use_legacy_prepare] command has been used to
1279 ** configure the connection.
1281 static int dbPrepare(
1282 SqliteDb
*pDb
, /* Database object */
1283 const char *zSql
, /* SQL to compile */
1284 sqlite3_stmt
**ppStmt
, /* OUT: Prepared statement */
1285 const char **pzOut
/* OUT: Pointer to next SQL statement */
1287 unsigned int prepFlags
= 0;
1289 if( pDb
->bLegacyPrepare
){
1290 return sqlite3_prepare(pDb
->db
, zSql
, -1, ppStmt
, pzOut
);
1293 /* If the statement cache is large, use the SQLITE_PREPARE_PERSISTENT
1294 ** flags, which uses less lookaside memory. But if the cache is small,
1295 ** omit that flag to make full use of lookaside */
1296 if( pDb
->maxStmt
>5 ) prepFlags
= SQLITE_PREPARE_PERSISTENT
;
1298 return sqlite3_prepare_v3(pDb
->db
, zSql
, -1, prepFlags
, ppStmt
, pzOut
);
1302 ** Search the cache for a prepared-statement object that implements the
1303 ** first SQL statement in the buffer pointed to by parameter zIn. If
1304 ** no such prepared-statement can be found, allocate and prepare a new
1305 ** one. In either case, bind the current values of the relevant Tcl
1306 ** variables to any $var, :var or @var variables in the statement. Before
1307 ** returning, set *ppPreStmt to point to the prepared-statement object.
1309 ** Output parameter *pzOut is set to point to the next SQL statement in
1310 ** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1313 ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1314 ** and an error message loaded into interpreter pDb->interp.
1316 static int dbPrepareAndBind(
1317 SqliteDb
*pDb
, /* Database object */
1318 char const *zIn
, /* SQL to compile */
1319 char const **pzOut
, /* OUT: Pointer to next SQL statement */
1320 SqlPreparedStmt
**ppPreStmt
/* OUT: Object used to cache statement */
1322 const char *zSql
= zIn
; /* Pointer to first SQL statement in zIn */
1323 sqlite3_stmt
*pStmt
= 0; /* Prepared statement object */
1324 SqlPreparedStmt
*pPreStmt
; /* Pointer to cached statement */
1325 int nSql
; /* Length of zSql in bytes */
1326 int nVar
= 0; /* Number of variables in statement */
1327 int iParm
= 0; /* Next free entry in apParm */
1330 int needResultReset
= 0; /* Need to invoke Tcl_ResetResult() */
1331 int rc
= SQLITE_OK
; /* Value to return */
1332 Tcl_Interp
*interp
= pDb
->interp
;
1336 /* Trim spaces from the start of zSql and calculate the remaining length. */
1337 while( (c
= zSql
[0])==' ' || c
=='\t' || c
=='\r' || c
=='\n' ){ zSql
++; }
1338 nSql
= strlen30(zSql
);
1340 for(pPreStmt
= pDb
->stmtList
; pPreStmt
; pPreStmt
=pPreStmt
->pNext
){
1341 int n
= pPreStmt
->nSql
;
1343 && memcmp(pPreStmt
->zSql
, zSql
, n
)==0
1344 && (zSql
[n
]==0 || zSql
[n
-1]==';')
1346 pStmt
= pPreStmt
->pStmt
;
1347 *pzOut
= &zSql
[pPreStmt
->nSql
];
1349 /* When a prepared statement is found, unlink it from the
1350 ** cache list. It will later be added back to the beginning
1351 ** of the cache list in order to implement LRU replacement.
1353 if( pPreStmt
->pPrev
){
1354 pPreStmt
->pPrev
->pNext
= pPreStmt
->pNext
;
1356 pDb
->stmtList
= pPreStmt
->pNext
;
1358 if( pPreStmt
->pNext
){
1359 pPreStmt
->pNext
->pPrev
= pPreStmt
->pPrev
;
1361 pDb
->stmtLast
= pPreStmt
->pPrev
;
1364 nVar
= sqlite3_bind_parameter_count(pStmt
);
1369 /* If no prepared statement was found. Compile the SQL text. Also allocate
1370 ** a new SqlPreparedStmt structure. */
1374 if( SQLITE_OK
!=dbPrepare(pDb
, zSql
, &pStmt
, pzOut
) ){
1375 Tcl_SetObjResult(interp
, Tcl_NewStringObj(sqlite3_errmsg(pDb
->db
), -1));
1379 if( SQLITE_OK
!=sqlite3_errcode(pDb
->db
) ){
1380 /* A compile-time error in the statement. */
1381 Tcl_SetObjResult(interp
, Tcl_NewStringObj(sqlite3_errmsg(pDb
->db
), -1));
1384 /* The statement was a no-op. Continue to the next statement
1385 ** in the SQL string.
1391 assert( pPreStmt
==0 );
1392 nVar
= sqlite3_bind_parameter_count(pStmt
);
1393 nByte
= sizeof(SqlPreparedStmt
) + nVar
*sizeof(Tcl_Obj
*);
1394 pPreStmt
= (SqlPreparedStmt
*)Tcl_Alloc(nByte
);
1395 memset(pPreStmt
, 0, nByte
);
1397 pPreStmt
->pStmt
= pStmt
;
1398 pPreStmt
->nSql
= (int)(*pzOut
- zSql
);
1399 pPreStmt
->zSql
= sqlite3_sql(pStmt
);
1400 pPreStmt
->apParm
= (Tcl_Obj
**)&pPreStmt
[1];
1402 if( pPreStmt
->zSql
==0 ){
1403 char *zCopy
= Tcl_Alloc(pPreStmt
->nSql
+ 1);
1404 memcpy(zCopy
, zSql
, pPreStmt
->nSql
);
1405 zCopy
[pPreStmt
->nSql
] = '\0';
1406 pPreStmt
->zSql
= zCopy
;
1411 assert( strlen30(pPreStmt
->zSql
)==pPreStmt
->nSql
);
1412 assert( 0==memcmp(pPreStmt
->zSql
, zSql
, pPreStmt
->nSql
) );
1414 /* Bind values to parameters that begin with $ or : */
1415 for(i
=1; i
<=nVar
; i
++){
1416 const char *zVar
= sqlite3_bind_parameter_name(pStmt
, i
);
1417 if( zVar
!=0 && (zVar
[0]=='$' || zVar
[0]==':' || zVar
[0]=='@') ){
1418 Tcl_Obj
*pVar
= Tcl_GetVar2Ex(interp
, &zVar
[1], 0, 0);
1419 if( pVar
==0 && pDb
->zBindFallback
!=0 ){
1422 pCmd
= Tcl_NewStringObj(pDb
->zBindFallback
, -1);
1423 Tcl_IncrRefCount(pCmd
);
1424 Tcl_ListObjAppendElement(interp
, pCmd
, Tcl_NewStringObj(zVar
,-1));
1425 if( needResultReset
) Tcl_ResetResult(interp
);
1426 needResultReset
= 1;
1427 rx
= Tcl_EvalObjEx(interp
, pCmd
, TCL_EVAL_DIRECT
);
1428 Tcl_DecrRefCount(pCmd
);
1430 pVar
= Tcl_GetObjResult(interp
);
1431 }else if( rx
==TCL_ERROR
){
1441 const char *zType
= (pVar
->typePtr
? pVar
->typePtr
->name
: "");
1444 (c
=='b' && strcmp(zType
,"bytearray")==0 && pVar
->bytes
==0) ){
1445 /* Load a BLOB type if the Tcl variable is a bytearray and
1446 ** it has no string representation or the host
1447 ** parameter name begins with "@". */
1448 data
= Tcl_GetByteArrayFromObj(pVar
, &n
);
1449 sqlite3_bind_blob(pStmt
, i
, data
, n
, SQLITE_STATIC
);
1450 Tcl_IncrRefCount(pVar
);
1451 pPreStmt
->apParm
[iParm
++] = pVar
;
1452 }else if( c
=='b' && strcmp(zType
,"boolean")==0 ){
1453 Tcl_GetIntFromObj(interp
, pVar
, &n
);
1454 sqlite3_bind_int(pStmt
, i
, n
);
1455 }else if( c
=='d' && strcmp(zType
,"double")==0 ){
1457 Tcl_GetDoubleFromObj(interp
, pVar
, &r
);
1458 sqlite3_bind_double(pStmt
, i
, r
);
1459 }else if( (c
=='w' && strcmp(zType
,"wideInt")==0) ||
1460 (c
=='i' && strcmp(zType
,"int")==0) ){
1462 Tcl_GetWideIntFromObj(interp
, pVar
, &v
);
1463 sqlite3_bind_int64(pStmt
, i
, v
);
1465 data
= (unsigned char *)Tcl_GetStringFromObj(pVar
, &n
);
1466 sqlite3_bind_text(pStmt
, i
, (char *)data
, n
, SQLITE_STATIC
);
1467 Tcl_IncrRefCount(pVar
);
1468 pPreStmt
->apParm
[iParm
++] = pVar
;
1471 sqlite3_bind_null(pStmt
, i
);
1473 if( needResultReset
) Tcl_ResetResult(pDb
->interp
);
1476 pPreStmt
->nParm
= iParm
;
1477 *ppPreStmt
= pPreStmt
;
1478 if( needResultReset
&& rc
==TCL_OK
) Tcl_ResetResult(pDb
->interp
);
1484 ** Release a statement reference obtained by calling dbPrepareAndBind().
1485 ** There should be exactly one call to this function for each call to
1486 ** dbPrepareAndBind().
1488 ** If the discard parameter is non-zero, then the statement is deleted
1489 ** immediately. Otherwise it is added to the LRU list and may be returned
1490 ** by a subsequent call to dbPrepareAndBind().
1492 static void dbReleaseStmt(
1493 SqliteDb
*pDb
, /* Database handle */
1494 SqlPreparedStmt
*pPreStmt
, /* Prepared statement handle to release */
1495 int discard
/* True to delete (not cache) the pPreStmt */
1499 /* Free the bound string and blob parameters */
1500 for(i
=0; i
<pPreStmt
->nParm
; i
++){
1501 Tcl_DecrRefCount(pPreStmt
->apParm
[i
]);
1503 pPreStmt
->nParm
= 0;
1505 if( pDb
->maxStmt
<=0 || discard
){
1506 /* If the cache is turned off, deallocated the statement */
1507 dbFreeStmt(pPreStmt
);
1509 /* Add the prepared statement to the beginning of the cache list. */
1510 pPreStmt
->pNext
= pDb
->stmtList
;
1511 pPreStmt
->pPrev
= 0;
1512 if( pDb
->stmtList
){
1513 pDb
->stmtList
->pPrev
= pPreStmt
;
1515 pDb
->stmtList
= pPreStmt
;
1516 if( pDb
->stmtLast
==0 ){
1517 assert( pDb
->nStmt
==0 );
1518 pDb
->stmtLast
= pPreStmt
;
1520 assert( pDb
->nStmt
>0 );
1524 /* If we have too many statement in cache, remove the surplus from
1525 ** the end of the cache list. */
1526 while( pDb
->nStmt
>pDb
->maxStmt
){
1527 SqlPreparedStmt
*pLast
= pDb
->stmtLast
;
1528 pDb
->stmtLast
= pLast
->pPrev
;
1529 pDb
->stmtLast
->pNext
= 0;
1537 ** Structure used with dbEvalXXX() functions:
1543 ** dbEvalColumnValue()
1545 typedef struct DbEvalContext DbEvalContext
;
1546 struct DbEvalContext
{
1547 SqliteDb
*pDb
; /* Database handle */
1548 Tcl_Obj
*pSql
; /* Object holding string zSql */
1549 const char *zSql
; /* Remaining SQL to execute */
1550 SqlPreparedStmt
*pPreStmt
; /* Current statement */
1551 int nCol
; /* Number of columns returned by pStmt */
1552 int evalFlags
; /* Flags used */
1553 Tcl_Obj
*pArray
; /* Name of array variable */
1554 Tcl_Obj
**apColName
; /* Array of column names */
1557 #define SQLITE_EVAL_WITHOUTNULLS 0x00001 /* Unset array(*) for NULL */
1560 ** Release any cache of column names currently held as part of
1561 ** the DbEvalContext structure passed as the first argument.
1563 static void dbReleaseColumnNames(DbEvalContext
*p
){
1566 for(i
=0; i
<p
->nCol
; i
++){
1567 Tcl_DecrRefCount(p
->apColName
[i
]);
1569 Tcl_Free((char *)p
->apColName
);
1576 ** Initialize a DbEvalContext structure.
1578 ** If pArray is not NULL, then it contains the name of a Tcl array
1579 ** variable. The "*" member of this array is set to a list containing
1580 ** the names of the columns returned by the statement as part of each
1581 ** call to dbEvalStep(), in order from left to right. e.g. if the names
1582 ** of the returned columns are a, b and c, it does the equivalent of the
1585 ** set ${pArray}(*) {a b c}
1587 static void dbEvalInit(
1588 DbEvalContext
*p
, /* Pointer to structure to initialize */
1589 SqliteDb
*pDb
, /* Database handle */
1590 Tcl_Obj
*pSql
, /* Object containing SQL script */
1591 Tcl_Obj
*pArray
, /* Name of Tcl array to set (*) element of */
1592 int evalFlags
/* Flags controlling evaluation */
1594 memset(p
, 0, sizeof(DbEvalContext
));
1596 p
->zSql
= Tcl_GetString(pSql
);
1598 Tcl_IncrRefCount(pSql
);
1601 Tcl_IncrRefCount(pArray
);
1603 p
->evalFlags
= evalFlags
;
1604 addDatabaseRef(p
->pDb
);
1608 ** Obtain information about the row that the DbEvalContext passed as the
1609 ** first argument currently points to.
1611 static void dbEvalRowInfo(
1612 DbEvalContext
*p
, /* Evaluation context */
1613 int *pnCol
, /* OUT: Number of column names */
1614 Tcl_Obj
***papColName
/* OUT: Array of column names */
1616 /* Compute column names */
1617 if( 0==p
->apColName
){
1618 sqlite3_stmt
*pStmt
= p
->pPreStmt
->pStmt
;
1619 int i
; /* Iterator variable */
1620 int nCol
; /* Number of columns returned by pStmt */
1621 Tcl_Obj
**apColName
= 0; /* Array of column names */
1623 p
->nCol
= nCol
= sqlite3_column_count(pStmt
);
1624 if( nCol
>0 && (papColName
|| p
->pArray
) ){
1625 apColName
= (Tcl_Obj
**)Tcl_Alloc( sizeof(Tcl_Obj
*)*nCol
);
1626 for(i
=0; i
<nCol
; i
++){
1627 apColName
[i
] = Tcl_NewStringObj(sqlite3_column_name(pStmt
,i
), -1);
1628 Tcl_IncrRefCount(apColName
[i
]);
1630 p
->apColName
= apColName
;
1633 /* If results are being stored in an array variable, then create
1634 ** the array(*) entry for that array
1637 Tcl_Interp
*interp
= p
->pDb
->interp
;
1638 Tcl_Obj
*pColList
= Tcl_NewObj();
1639 Tcl_Obj
*pStar
= Tcl_NewStringObj("*", -1);
1641 for(i
=0; i
<nCol
; i
++){
1642 Tcl_ListObjAppendElement(interp
, pColList
, apColName
[i
]);
1644 Tcl_IncrRefCount(pStar
);
1645 Tcl_ObjSetVar2(interp
, p
->pArray
, pStar
, pColList
, 0);
1646 Tcl_DecrRefCount(pStar
);
1651 *papColName
= p
->apColName
;
1659 ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1660 ** returned, then an error message is stored in the interpreter before
1663 ** A return value of TCL_OK means there is a row of data available. The
1664 ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1665 ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1666 ** is returned, then the SQL script has finished executing and there are
1667 ** no further rows available. This is similar to SQLITE_DONE.
1669 static int dbEvalStep(DbEvalContext
*p
){
1670 const char *zPrevSql
= 0; /* Previous value of p->zSql */
1672 while( p
->zSql
[0] || p
->pPreStmt
){
1674 if( p
->pPreStmt
==0 ){
1675 zPrevSql
= (p
->zSql
==zPrevSql
? 0 : p
->zSql
);
1676 rc
= dbPrepareAndBind(p
->pDb
, p
->zSql
, &p
->zSql
, &p
->pPreStmt
);
1677 if( rc
!=TCL_OK
) return rc
;
1680 SqliteDb
*pDb
= p
->pDb
;
1681 SqlPreparedStmt
*pPreStmt
= p
->pPreStmt
;
1682 sqlite3_stmt
*pStmt
= pPreStmt
->pStmt
;
1684 rcs
= sqlite3_step(pStmt
);
1685 if( rcs
==SQLITE_ROW
){
1689 dbEvalRowInfo(p
, 0, 0);
1691 rcs
= sqlite3_reset(pStmt
);
1693 pDb
->nStep
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_FULLSCAN_STEP
,1);
1694 pDb
->nSort
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_SORT
,1);
1695 pDb
->nIndex
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_AUTOINDEX
,1);
1696 pDb
->nVMStep
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_VM_STEP
,1);
1697 dbReleaseColumnNames(p
);
1700 if( rcs
!=SQLITE_OK
){
1701 /* If a run-time error occurs, report the error and stop reading
1703 dbReleaseStmt(pDb
, pPreStmt
, 1);
1705 if( p
->pDb
->bLegacyPrepare
&& rcs
==SQLITE_SCHEMA
&& zPrevSql
){
1706 /* If the runtime error was an SQLITE_SCHEMA, and the database
1707 ** handle is configured to use the legacy sqlite3_prepare()
1708 ** interface, retry prepare()/step() on the same SQL statement.
1709 ** This only happens once. If there is a second SQLITE_SCHEMA
1710 ** error, the error will be returned to the caller. */
1715 Tcl_SetObjResult(pDb
->interp
,
1716 Tcl_NewStringObj(sqlite3_errmsg(pDb
->db
), -1));
1719 dbReleaseStmt(pDb
, pPreStmt
, 0);
1729 ** Free all resources currently held by the DbEvalContext structure passed
1730 ** as the first argument. There should be exactly one call to this function
1731 ** for each call to dbEvalInit().
1733 static void dbEvalFinalize(DbEvalContext
*p
){
1735 sqlite3_reset(p
->pPreStmt
->pStmt
);
1736 dbReleaseStmt(p
->pDb
, p
->pPreStmt
, 0);
1740 Tcl_DecrRefCount(p
->pArray
);
1743 Tcl_DecrRefCount(p
->pSql
);
1744 dbReleaseColumnNames(p
);
1745 delDatabaseRef(p
->pDb
);
1749 ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1750 ** the value for the iCol'th column of the row currently pointed to by
1751 ** the DbEvalContext structure passed as the first argument.
1753 static Tcl_Obj
*dbEvalColumnValue(DbEvalContext
*p
, int iCol
){
1754 sqlite3_stmt
*pStmt
= p
->pPreStmt
->pStmt
;
1755 switch( sqlite3_column_type(pStmt
, iCol
) ){
1757 int bytes
= sqlite3_column_bytes(pStmt
, iCol
);
1758 const char *zBlob
= sqlite3_column_blob(pStmt
, iCol
);
1759 if( !zBlob
) bytes
= 0;
1760 return Tcl_NewByteArrayObj((u8
*)zBlob
, bytes
);
1762 case SQLITE_INTEGER
: {
1763 sqlite_int64 v
= sqlite3_column_int64(pStmt
, iCol
);
1764 if( v
>=-2147483647 && v
<=2147483647 ){
1765 return Tcl_NewIntObj((int)v
);
1767 return Tcl_NewWideIntObj(v
);
1770 case SQLITE_FLOAT
: {
1771 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt
, iCol
));
1774 return Tcl_NewStringObj(p
->pDb
->zNull
, -1);
1778 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt
, iCol
), -1);
1782 ** If using Tcl version 8.6 or greater, use the NR functions to avoid
1783 ** recursive evalution of scripts by the [db eval] and [db trans]
1784 ** commands. Even if the headers used while compiling the extension
1785 ** are 8.6 or newer, the code still tests the Tcl version at runtime.
1786 ** This allows stubs-enabled builds to be used with older Tcl libraries.
1788 #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
1789 # define SQLITE_TCL_NRE 1
1790 static int DbUseNre(void){
1792 Tcl_GetVersion(&major
, &minor
, 0, 0);
1793 return( (major
==8 && minor
>=6) || major
>8 );
1797 ** Compiling using headers earlier than 8.6. In this case NR cannot be
1798 ** used, so DbUseNre() to always return zero. Add #defines for the other
1799 ** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1800 ** even though the only invocations of them are within conditional blocks
1803 ** if( DbUseNre() ) { ... }
1805 # define SQLITE_TCL_NRE 0
1806 # define DbUseNre() 0
1807 # define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
1808 # define Tcl_NREvalObj(a,b,c) 0
1809 # define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
1813 ** This function is part of the implementation of the command:
1815 ** $db eval SQL ?ARRAYNAME? SCRIPT
1817 static int SQLITE_TCLAPI
DbEvalNextCmd(
1818 ClientData data
[], /* data[0] is the (DbEvalContext*) */
1819 Tcl_Interp
*interp
, /* Tcl interpreter */
1820 int result
/* Result so far */
1822 int rc
= result
; /* Return code */
1824 /* The first element of the data[] array is a pointer to a DbEvalContext
1825 ** structure allocated using Tcl_Alloc(). The second element of data[]
1826 ** is a pointer to a Tcl_Obj containing the script to run for each row
1827 ** returned by the queries encapsulated in data[0]. */
1828 DbEvalContext
*p
= (DbEvalContext
*)data
[0];
1829 Tcl_Obj
*pScript
= (Tcl_Obj
*)data
[1];
1830 Tcl_Obj
*pArray
= p
->pArray
;
1832 while( (rc
==TCL_OK
|| rc
==TCL_CONTINUE
) && TCL_OK
==(rc
= dbEvalStep(p
)) ){
1835 Tcl_Obj
**apColName
;
1836 dbEvalRowInfo(p
, &nCol
, &apColName
);
1837 for(i
=0; i
<nCol
; i
++){
1839 Tcl_ObjSetVar2(interp
, apColName
[i
], 0, dbEvalColumnValue(p
,i
), 0);
1840 }else if( (p
->evalFlags
& SQLITE_EVAL_WITHOUTNULLS
)!=0
1841 && sqlite3_column_type(p
->pPreStmt
->pStmt
, i
)==SQLITE_NULL
1843 Tcl_UnsetVar2(interp
, Tcl_GetString(pArray
),
1844 Tcl_GetString(apColName
[i
]), 0);
1846 Tcl_ObjSetVar2(interp
, pArray
, apColName
[i
], dbEvalColumnValue(p
,i
), 0);
1850 /* The required interpreter variables are now populated with the data
1851 ** from the current row. If using NRE, schedule callbacks to evaluate
1852 ** script pScript, then to invoke this function again to fetch the next
1853 ** row (or clean up if there is no next row or the script throws an
1854 ** exception). After scheduling the callbacks, return control to the
1857 ** If not using NRE, evaluate pScript directly and continue with the
1858 ** next iteration of this while(...) loop. */
1860 Tcl_NRAddCallback(interp
, DbEvalNextCmd
, (void*)p
, (void*)pScript
, 0, 0);
1861 return Tcl_NREvalObj(interp
, pScript
, 0);
1863 rc
= Tcl_EvalObjEx(interp
, pScript
, 0);
1867 Tcl_DecrRefCount(pScript
);
1869 Tcl_Free((char *)p
);
1871 if( rc
==TCL_OK
|| rc
==TCL_BREAK
){
1872 Tcl_ResetResult(interp
);
1879 ** This function is used by the implementations of the following database
1880 ** handle sub-commands:
1882 ** $db update_hook ?SCRIPT?
1883 ** $db wal_hook ?SCRIPT?
1884 ** $db commit_hook ?SCRIPT?
1885 ** $db preupdate hook ?SCRIPT?
1887 static void DbHookCmd(
1888 Tcl_Interp
*interp
, /* Tcl interpreter */
1889 SqliteDb
*pDb
, /* Database handle */
1890 Tcl_Obj
*pArg
, /* SCRIPT argument (or NULL) */
1891 Tcl_Obj
**ppHook
/* Pointer to member of SqliteDb */
1893 sqlite3
*db
= pDb
->db
;
1896 Tcl_SetObjResult(interp
, *ppHook
);
1898 Tcl_DecrRefCount(*ppHook
);
1903 assert( !(*ppHook
) );
1904 if( Tcl_GetCharLength(pArg
)>0 ){
1906 Tcl_IncrRefCount(*ppHook
);
1910 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1911 sqlite3_preupdate_hook(db
, (pDb
->pPreUpdateHook
?DbPreUpdateHandler
:0), pDb
);
1913 sqlite3_update_hook(db
, (pDb
->pUpdateHook
?DbUpdateHandler
:0), pDb
);
1914 sqlite3_rollback_hook(db
, (pDb
->pRollbackHook
?DbRollbackHandler
:0), pDb
);
1915 sqlite3_wal_hook(db
, (pDb
->pWalHook
?DbWalHandler
:0), pDb
);
1919 ** The "sqlite" command below creates a new Tcl command for each
1920 ** connection it opens to an SQLite database. This routine is invoked
1921 ** whenever one of those connection-specific commands is executed
1922 ** in Tcl. For example, if you run Tcl code like this:
1924 ** sqlite3 db1 "my_database"
1927 ** The first command opens a connection to the "my_database" database
1928 ** and calls that connection "db1". The second command causes this
1929 ** subroutine to be invoked.
1931 static int SQLITE_TCLAPI
DbObjCmd(
1937 SqliteDb
*pDb
= (SqliteDb
*)cd
;
1940 static const char *DB_strs
[] = {
1941 "authorizer", "backup", "bind_fallback",
1942 "busy", "cache", "changes",
1943 "close", "collate", "collation_needed",
1944 "commit_hook", "complete", "config",
1945 "copy", "deserialize", "enable_load_extension",
1946 "errorcode", "eval", "exists",
1947 "function", "incrblob", "interrupt",
1948 "last_insert_rowid", "nullvalue", "onecolumn",
1949 "preupdate", "profile", "progress",
1950 "rekey", "restore", "rollback_hook",
1951 "serialize", "status", "timeout",
1952 "total_changes", "trace", "trace_v2",
1953 "transaction", "unlock_notify", "update_hook",
1954 "version", "wal_hook", 0
1957 DB_AUTHORIZER
, DB_BACKUP
, DB_BIND_FALLBACK
,
1958 DB_BUSY
, DB_CACHE
, DB_CHANGES
,
1959 DB_CLOSE
, DB_COLLATE
, DB_COLLATION_NEEDED
,
1960 DB_COMMIT_HOOK
, DB_COMPLETE
, DB_CONFIG
,
1961 DB_COPY
, DB_DESERIALIZE
, DB_ENABLE_LOAD_EXTENSION
,
1962 DB_ERRORCODE
, DB_EVAL
, DB_EXISTS
,
1963 DB_FUNCTION
, DB_INCRBLOB
, DB_INTERRUPT
,
1964 DB_LAST_INSERT_ROWID
, DB_NULLVALUE
, DB_ONECOLUMN
,
1965 DB_PREUPDATE
, DB_PROFILE
, DB_PROGRESS
,
1966 DB_REKEY
, DB_RESTORE
, DB_ROLLBACK_HOOK
,
1967 DB_SERIALIZE
, DB_STATUS
, DB_TIMEOUT
,
1968 DB_TOTAL_CHANGES
, DB_TRACE
, DB_TRACE_V2
,
1969 DB_TRANSACTION
, DB_UNLOCK_NOTIFY
, DB_UPDATE_HOOK
,
1970 DB_VERSION
, DB_WAL_HOOK
1972 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
1975 Tcl_WrongNumArgs(interp
, 1, objv
, "SUBCOMMAND ...");
1978 if( Tcl_GetIndexFromObj(interp
, objv
[1], DB_strs
, "option", 0, &choice
) ){
1982 switch( (enum DB_enum
)choice
){
1984 /* $db authorizer ?CALLBACK?
1986 ** Invoke the given callback to authorize each SQL operation as it is
1987 ** compiled. 5 arguments are appended to the callback before it is
1990 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1991 ** (2) First descriptive name (depends on authorization type)
1992 ** (3) Second descriptive name
1993 ** (4) Name of the database (ex: "main", "temp")
1994 ** (5) Name of trigger that is doing the access
1996 ** The callback should return on of the following strings: SQLITE_OK,
1997 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1999 ** If this method is invoked with no arguments, the current authorization
2000 ** callback string is returned.
2002 case DB_AUTHORIZER
: {
2003 #ifdef SQLITE_OMIT_AUTHORIZATION
2004 Tcl_AppendResult(interp
, "authorization not available in this build",
2009 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
2011 }else if( objc
==2 ){
2013 Tcl_AppendResult(interp
, pDb
->zAuth
, (char*)0);
2019 Tcl_Free(pDb
->zAuth
);
2021 zAuth
= Tcl_GetStringFromObj(objv
[2], &len
);
2022 if( zAuth
&& len
>0 ){
2023 pDb
->zAuth
= Tcl_Alloc( len
+ 1 );
2024 memcpy(pDb
->zAuth
, zAuth
, len
+1);
2029 typedef int (*sqlite3_auth_cb
)(
2030 void*,int,const char*,const char*,
2031 const char*,const char*);
2032 pDb
->interp
= interp
;
2033 sqlite3_set_authorizer(pDb
->db
,(sqlite3_auth_cb
)auth_callback
,pDb
);
2035 sqlite3_set_authorizer(pDb
->db
, 0, 0);
2042 /* $db backup ?DATABASE? FILENAME
2044 ** Open or create a database file named FILENAME. Transfer the
2045 ** content of local database DATABASE (default: "main") into the
2046 ** FILENAME database.
2049 const char *zDestFile
;
2052 sqlite3_backup
*pBackup
;
2056 zDestFile
= Tcl_GetString(objv
[2]);
2057 }else if( objc
==4 ){
2058 zSrcDb
= Tcl_GetString(objv
[2]);
2059 zDestFile
= Tcl_GetString(objv
[3]);
2061 Tcl_WrongNumArgs(interp
, 2, objv
, "?DATABASE? FILENAME");
2064 rc
= sqlite3_open_v2(zDestFile
, &pDest
,
2065 SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
| pDb
->openFlags
, 0);
2066 if( rc
!=SQLITE_OK
){
2067 Tcl_AppendResult(interp
, "cannot open target database: ",
2068 sqlite3_errmsg(pDest
), (char*)0);
2069 sqlite3_close(pDest
);
2072 pBackup
= sqlite3_backup_init(pDest
, "main", pDb
->db
, zSrcDb
);
2074 Tcl_AppendResult(interp
, "backup failed: ",
2075 sqlite3_errmsg(pDest
), (char*)0);
2076 sqlite3_close(pDest
);
2079 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
){}
2080 sqlite3_backup_finish(pBackup
);
2081 if( rc
==SQLITE_DONE
){
2084 Tcl_AppendResult(interp
, "backup failed: ",
2085 sqlite3_errmsg(pDest
), (char*)0);
2088 sqlite3_close(pDest
);
2092 /* $db bind_fallback ?CALLBACK?
2094 ** When resolving bind parameters in an SQL statement, if the parameter
2095 ** cannot be associated with a TCL variable then invoke CALLBACK with a
2096 ** single argument that is the name of the parameter and use the return
2097 ** value of the CALLBACK as the binding. If CALLBACK returns something
2098 ** other than TCL_OK or TCL_ERROR then bind a NULL.
2100 ** If CALLBACK is an empty string, then revert to the default behavior
2101 ** which is to set the binding to NULL.
2103 ** If CALLBACK returns an error, that causes the statement execution to
2104 ** abort. Hence, to configure a connection so that it throws an error
2105 ** on an attempt to bind an unknown variable, do something like this:
2107 ** proc bind_error {name} {error "no such variable: $name"}
2108 ** db bind_fallback bind_error
2110 case DB_BIND_FALLBACK
: {
2112 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
2114 }else if( objc
==2 ){
2115 if( pDb
->zBindFallback
){
2116 Tcl_AppendResult(interp
, pDb
->zBindFallback
, (char*)0);
2121 if( pDb
->zBindFallback
){
2122 Tcl_Free(pDb
->zBindFallback
);
2124 zCallback
= Tcl_GetStringFromObj(objv
[2], &len
);
2125 if( zCallback
&& len
>0 ){
2126 pDb
->zBindFallback
= Tcl_Alloc( len
+ 1 );
2127 memcpy(pDb
->zBindFallback
, zCallback
, len
+1);
2129 pDb
->zBindFallback
= 0;
2135 /* $db busy ?CALLBACK?
2137 ** Invoke the given callback if an SQL statement attempts to open
2138 ** a locked database file.
2142 Tcl_WrongNumArgs(interp
, 2, objv
, "CALLBACK");
2144 }else if( objc
==2 ){
2146 Tcl_AppendResult(interp
, pDb
->zBusy
, (char*)0);
2152 Tcl_Free(pDb
->zBusy
);
2154 zBusy
= Tcl_GetStringFromObj(objv
[2], &len
);
2155 if( zBusy
&& len
>0 ){
2156 pDb
->zBusy
= Tcl_Alloc( len
+ 1 );
2157 memcpy(pDb
->zBusy
, zBusy
, len
+1);
2162 pDb
->interp
= interp
;
2163 sqlite3_busy_handler(pDb
->db
, DbBusyHandler
, pDb
);
2165 sqlite3_busy_handler(pDb
->db
, 0, 0);
2174 ** Flush the prepared statement cache, or set the maximum number of
2175 ** cached statements.
2182 Tcl_WrongNumArgs(interp
, 1, objv
, "cache option ?arg?");
2185 subCmd
= Tcl_GetStringFromObj( objv
[2], 0 );
2186 if( *subCmd
=='f' && strcmp(subCmd
,"flush")==0 ){
2188 Tcl_WrongNumArgs(interp
, 2, objv
, "flush");
2191 flushStmtCache( pDb
);
2193 }else if( *subCmd
=='s' && strcmp(subCmd
,"size")==0 ){
2195 Tcl_WrongNumArgs(interp
, 2, objv
, "size n");
2198 if( TCL_ERROR
==Tcl_GetIntFromObj(interp
, objv
[3], &n
) ){
2199 Tcl_AppendResult( interp
, "cannot convert \"",
2200 Tcl_GetStringFromObj(objv
[3],0), "\" to integer", (char*)0);
2204 flushStmtCache( pDb
);
2206 }else if( n
>MAX_PREPARED_STMTS
){
2207 n
= MAX_PREPARED_STMTS
;
2213 Tcl_AppendResult( interp
, "bad option \"",
2214 Tcl_GetStringFromObj(objv
[2],0), "\": must be flush or size",
2223 ** Return the number of rows that were modified, inserted, or deleted by
2224 ** the most recent INSERT, UPDATE or DELETE statement, not including
2225 ** any changes made by trigger programs.
2230 Tcl_WrongNumArgs(interp
, 2, objv
, "");
2233 pResult
= Tcl_GetObjResult(interp
);
2234 Tcl_SetWideIntObj(pResult
, sqlite3_changes64(pDb
->db
));
2240 ** Shutdown the database
2243 Tcl_DeleteCommand(interp
, Tcl_GetStringFromObj(objv
[0], 0));
2248 ** $db collate NAME SCRIPT
2250 ** Create a new SQL collation function called NAME. Whenever
2251 ** that function is called, invoke SCRIPT to evaluate the function.
2254 SqlCollate
*pCollate
;
2259 Tcl_WrongNumArgs(interp
, 2, objv
, "NAME SCRIPT");
2262 zName
= Tcl_GetStringFromObj(objv
[2], 0);
2263 zScript
= Tcl_GetStringFromObj(objv
[3], &nScript
);
2264 pCollate
= (SqlCollate
*)Tcl_Alloc( sizeof(*pCollate
) + nScript
+ 1 );
2265 if( pCollate
==0 ) return TCL_ERROR
;
2266 pCollate
->interp
= interp
;
2267 pCollate
->pNext
= pDb
->pCollate
;
2268 pCollate
->zScript
= (char*)&pCollate
[1];
2269 pDb
->pCollate
= pCollate
;
2270 memcpy(pCollate
->zScript
, zScript
, nScript
+1);
2271 if( sqlite3_create_collation(pDb
->db
, zName
, SQLITE_UTF8
,
2272 pCollate
, tclSqlCollate
) ){
2273 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(pDb
->db
), TCL_VOLATILE
);
2280 ** $db collation_needed SCRIPT
2282 ** Create a new SQL collation function called NAME. Whenever
2283 ** that function is called, invoke SCRIPT to evaluate the function.
2285 case DB_COLLATION_NEEDED
: {
2287 Tcl_WrongNumArgs(interp
, 2, objv
, "SCRIPT");
2290 if( pDb
->pCollateNeeded
){
2291 Tcl_DecrRefCount(pDb
->pCollateNeeded
);
2293 pDb
->pCollateNeeded
= Tcl_DuplicateObj(objv
[2]);
2294 Tcl_IncrRefCount(pDb
->pCollateNeeded
);
2295 sqlite3_collation_needed(pDb
->db
, pDb
, tclCollateNeeded
);
2299 /* $db commit_hook ?CALLBACK?
2301 ** Invoke the given callback just before committing every SQL transaction.
2302 ** If the callback throws an exception or returns non-zero, then the
2303 ** transaction is aborted. If CALLBACK is an empty string, the callback
2306 case DB_COMMIT_HOOK
: {
2308 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
2310 }else if( objc
==2 ){
2312 Tcl_AppendResult(interp
, pDb
->zCommit
, (char*)0);
2315 const char *zCommit
;
2318 Tcl_Free(pDb
->zCommit
);
2320 zCommit
= Tcl_GetStringFromObj(objv
[2], &len
);
2321 if( zCommit
&& len
>0 ){
2322 pDb
->zCommit
= Tcl_Alloc( len
+ 1 );
2323 memcpy(pDb
->zCommit
, zCommit
, len
+1);
2328 pDb
->interp
= interp
;
2329 sqlite3_commit_hook(pDb
->db
, DbCommitHandler
, pDb
);
2331 sqlite3_commit_hook(pDb
->db
, 0, 0);
2339 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2340 ** additional lines of input are needed. This is similar to the
2341 ** built-in "info complete" command of Tcl.
2344 #ifndef SQLITE_OMIT_COMPLETE
2348 Tcl_WrongNumArgs(interp
, 2, objv
, "SQL");
2351 isComplete
= sqlite3_complete( Tcl_GetStringFromObj(objv
[2], 0) );
2352 pResult
= Tcl_GetObjResult(interp
);
2353 Tcl_SetBooleanObj(pResult
, isComplete
);
2358 /* $db config ?OPTION? ?BOOLEAN?
2360 ** Configure the database connection using the sqlite3_db_config()
2364 static const struct DbConfigChoices
{
2368 { "defensive", SQLITE_DBCONFIG_DEFENSIVE
},
2369 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL
},
2370 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML
},
2371 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY
},
2372 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG
},
2373 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER
},
2374 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW
},
2375 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
},
2376 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE
},
2377 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT
},
2378 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
},
2379 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE
},
2380 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE
},
2381 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP
},
2382 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA
},
2383 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA
},
2388 Tcl_WrongNumArgs(interp
, 2, objv
, "?OPTION? ?BOOLEAN?");
2392 /* With no arguments, list all configuration options and with the
2394 pResult
= Tcl_NewListObj(0,0);
2395 for(ii
=0; ii
<sizeof(aDbConfig
)/sizeof(aDbConfig
[0]); ii
++){
2397 sqlite3_db_config(pDb
->db
, aDbConfig
[ii
].op
, -1, &v
);
2398 Tcl_ListObjAppendElement(interp
, pResult
,
2399 Tcl_NewStringObj(aDbConfig
[ii
].zName
,-1));
2400 Tcl_ListObjAppendElement(interp
, pResult
,
2404 const char *zOpt
= Tcl_GetString(objv
[2]);
2407 if( zOpt
[0]=='-' ) zOpt
++;
2408 for(ii
=0; ii
<sizeof(aDbConfig
)/sizeof(aDbConfig
[0]); ii
++){
2409 if( strcmp(aDbConfig
[ii
].zName
, zOpt
)==0 ) break;
2411 if( ii
>=sizeof(aDbConfig
)/sizeof(aDbConfig
[0]) ){
2412 Tcl_AppendResult(interp
, "unknown config option: \"", zOpt
,
2417 if( Tcl_GetBooleanFromObj(interp
, objv
[3], &onoff
) ){
2421 sqlite3_db_config(pDb
->db
, aDbConfig
[ii
].op
, onoff
, &v
);
2422 pResult
= Tcl_NewIntObj(v
);
2424 Tcl_SetObjResult(interp
, pResult
);
2428 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2430 ** Copy data into table from filename, optionally using SEPARATOR
2431 ** as column separators. If a column contains a null string, or the
2432 ** value of NULLINDICATOR, a NULL is inserted for the column.
2433 ** conflict-algorithm is one of the sqlite conflict algorithms:
2434 ** rollback, abort, fail, ignore, replace
2435 ** On success, return the number of lines processed, not necessarily same
2436 ** as 'db changes' due to conflict-algorithm selected.
2438 ** This code is basically an implementation/enhancement of
2439 ** the sqlite3 shell.c ".import" command.
2441 ** This command usage is equivalent to the sqlite2.x COPY statement,
2442 ** which imports file data into a table using the PostgreSQL COPY file format:
2443 ** $db copy $conflit_algo $table_name $filename \t \\N
2446 char *zTable
; /* Insert data into this table */
2447 char *zFile
; /* The file from which to extract data */
2448 char *zConflict
; /* The conflict algorithm to use */
2449 sqlite3_stmt
*pStmt
; /* A statement */
2450 int nCol
; /* Number of columns in the table */
2451 int nByte
; /* Number of bytes in an SQL string */
2452 int i
, j
; /* Loop counters */
2453 int nSep
; /* Number of bytes in zSep[] */
2454 int nNull
; /* Number of bytes in zNull[] */
2455 char *zSql
; /* An SQL statement */
2456 char *zLine
; /* A single line of input from the file */
2457 char **azCol
; /* zLine[] broken up into columns */
2458 const char *zCommit
; /* How to commit changes */
2459 FILE *in
; /* The input file */
2460 int lineno
= 0; /* Line number of input file */
2461 char zLineNum
[80]; /* Line number print buffer */
2462 Tcl_Obj
*pResult
; /* interp result */
2466 if( objc
<5 || objc
>7 ){
2467 Tcl_WrongNumArgs(interp
, 2, objv
,
2468 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2472 zSep
= Tcl_GetStringFromObj(objv
[5], 0);
2477 zNull
= Tcl_GetStringFromObj(objv
[6], 0);
2481 zConflict
= Tcl_GetStringFromObj(objv
[2], 0);
2482 zTable
= Tcl_GetStringFromObj(objv
[3], 0);
2483 zFile
= Tcl_GetStringFromObj(objv
[4], 0);
2484 nSep
= strlen30(zSep
);
2485 nNull
= strlen30(zNull
);
2487 Tcl_AppendResult(interp
,"Error: non-null separator required for copy",
2491 if(strcmp(zConflict
, "rollback") != 0 &&
2492 strcmp(zConflict
, "abort" ) != 0 &&
2493 strcmp(zConflict
, "fail" ) != 0 &&
2494 strcmp(zConflict
, "ignore" ) != 0 &&
2495 strcmp(zConflict
, "replace" ) != 0 ) {
2496 Tcl_AppendResult(interp
, "Error: \"", zConflict
,
2497 "\", conflict-algorithm must be one of: rollback, "
2498 "abort, fail, ignore, or replace", (char*)0);
2501 zSql
= sqlite3_mprintf("SELECT * FROM '%q'", zTable
);
2503 Tcl_AppendResult(interp
, "Error: no such table: ", zTable
, (char*)0);
2506 nByte
= strlen30(zSql
);
2507 rc
= sqlite3_prepare(pDb
->db
, zSql
, -1, &pStmt
, 0);
2510 Tcl_AppendResult(interp
, "Error: ", sqlite3_errmsg(pDb
->db
), (char*)0);
2513 nCol
= sqlite3_column_count(pStmt
);
2515 sqlite3_finalize(pStmt
);
2519 zSql
= malloc( nByte
+ 50 + nCol
*2 );
2521 Tcl_AppendResult(interp
, "Error: can't malloc()", (char*)0);
2524 sqlite3_snprintf(nByte
+50, zSql
, "INSERT OR %q INTO '%q' VALUES(?",
2527 for(i
=1; i
<nCol
; i
++){
2533 rc
= sqlite3_prepare(pDb
->db
, zSql
, -1, &pStmt
, 0);
2536 Tcl_AppendResult(interp
, "Error: ", sqlite3_errmsg(pDb
->db
), (char*)0);
2537 sqlite3_finalize(pStmt
);
2540 in
= fopen(zFile
, "rb");
2542 Tcl_AppendResult(interp
, "Error: cannot open file: ", zFile
, (char*)0);
2543 sqlite3_finalize(pStmt
);
2546 azCol
= malloc( sizeof(azCol
[0])*(nCol
+1) );
2548 Tcl_AppendResult(interp
, "Error: can't malloc()", (char*)0);
2552 (void)sqlite3_exec(pDb
->db
, "BEGIN", 0, 0, 0);
2554 while( (zLine
= local_getline(0, in
))!=0 ){
2558 for(i
=0, z
=zLine
; *z
; z
++){
2559 if( *z
==zSep
[0] && strncmp(z
, zSep
, nSep
)==0 ){
2563 azCol
[i
] = &z
[nSep
];
2570 int nErr
= strlen30(zFile
) + 200;
2571 zErr
= malloc(nErr
);
2573 sqlite3_snprintf(nErr
, zErr
,
2574 "Error: %s line %d: expected %d columns of data but found %d",
2575 zFile
, lineno
, nCol
, i
+1);
2576 Tcl_AppendResult(interp
, zErr
, (char*)0);
2579 zCommit
= "ROLLBACK";
2582 for(i
=0; i
<nCol
; i
++){
2583 /* check for null data, if so, bind as null */
2584 if( (nNull
>0 && strcmp(azCol
[i
], zNull
)==0)
2585 || strlen30(azCol
[i
])==0
2587 sqlite3_bind_null(pStmt
, i
+1);
2589 sqlite3_bind_text(pStmt
, i
+1, azCol
[i
], -1, SQLITE_STATIC
);
2592 sqlite3_step(pStmt
);
2593 rc
= sqlite3_reset(pStmt
);
2595 if( rc
!=SQLITE_OK
){
2596 Tcl_AppendResult(interp
,"Error: ", sqlite3_errmsg(pDb
->db
), (char*)0);
2597 zCommit
= "ROLLBACK";
2603 sqlite3_finalize(pStmt
);
2604 (void)sqlite3_exec(pDb
->db
, zCommit
, 0, 0, 0);
2606 if( zCommit
[0] == 'C' ){
2607 /* success, set result as number of lines processed */
2608 pResult
= Tcl_GetObjResult(interp
);
2609 Tcl_SetIntObj(pResult
, lineno
);
2612 /* failure, append lineno where failed */
2613 sqlite3_snprintf(sizeof(zLineNum
), zLineNum
,"%d",lineno
);
2614 Tcl_AppendResult(interp
,", failed while processing line: ",zLineNum
,
2622 ** $db deserialize ?-maxsize N? ?-readonly BOOL? ?DATABASE? VALUE
2624 ** Reopen DATABASE (default "main") using the content in $VALUE
2626 case DB_DESERIALIZE
: {
2627 #ifdef SQLITE_OMIT_DESERIALIZE
2628 Tcl_AppendResult(interp
, "MEMDB not available in this build",
2632 const char *zSchema
= 0;
2633 Tcl_Obj
*pValue
= 0;
2635 unsigned char *pData
;
2637 sqlite3_int64 mxSize
= 0;
2643 Tcl_WrongNumArgs(interp
, 2, objv
, "?DATABASE? VALUE");
2647 for(i
=2; i
<objc
-1; i
++){
2648 const char *z
= Tcl_GetString(objv
[i
]);
2649 if( strcmp(z
,"-maxsize")==0 && i
<objc
-2 ){
2651 rc
= Tcl_GetWideIntFromObj(interp
, objv
[++i
], &x
);
2652 if( rc
) goto deserialize_error
;
2656 if( strcmp(z
,"-readonly")==0 && i
<objc
-2 ){
2657 rc
= Tcl_GetBooleanFromObj(interp
, objv
[++i
], &isReadonly
);
2658 if( rc
) goto deserialize_error
;
2661 if( zSchema
==0 && i
==objc
-2 && z
[0]!='-' ){
2665 Tcl_AppendResult(interp
, "unknown option: ", z
, (char*)0);
2667 goto deserialize_error
;
2669 pValue
= objv
[objc
-1];
2670 pBA
= Tcl_GetByteArrayFromObj(pValue
, &len
);
2671 pData
= sqlite3_malloc64( len
);
2672 if( pData
==0 && len
>0 ){
2673 Tcl_AppendResult(interp
, "out of memory", (char*)0);
2677 if( len
>0 ) memcpy(pData
, pBA
, len
);
2679 flags
= SQLITE_DESERIALIZE_FREEONCLOSE
| SQLITE_DESERIALIZE_READONLY
;
2681 flags
= SQLITE_DESERIALIZE_FREEONCLOSE
| SQLITE_DESERIALIZE_RESIZEABLE
;
2683 xrc
= sqlite3_deserialize(pDb
->db
, zSchema
, pData
, len
, len
, flags
);
2685 Tcl_AppendResult(interp
, "unable to set MEMDB content", (char*)0);
2689 sqlite3_file_control(pDb
->db
, zSchema
,SQLITE_FCNTL_SIZE_LIMIT
,&mxSize
);
2698 ** $db enable_load_extension BOOLEAN
2700 ** Turn the extension loading feature on or off. It if off by
2703 case DB_ENABLE_LOAD_EXTENSION
: {
2704 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2707 Tcl_WrongNumArgs(interp
, 2, objv
, "BOOLEAN");
2710 if( Tcl_GetBooleanFromObj(interp
, objv
[2], &onoff
) ){
2713 sqlite3_enable_load_extension(pDb
->db
, onoff
);
2716 Tcl_AppendResult(interp
, "extension loading is turned off at compile-time",
2725 ** Return the numeric error code that was returned by the most recent
2726 ** call to sqlite3_exec().
2728 case DB_ERRORCODE
: {
2729 Tcl_SetObjResult(interp
, Tcl_NewIntObj(sqlite3_errcode(pDb
->db
)));
2735 ** $db onecolumn $sql
2737 ** The onecolumn method is the equivalent of:
2738 ** lindex [$db eval $sql] 0
2741 case DB_ONECOLUMN
: {
2742 Tcl_Obj
*pResult
= 0;
2743 DbEvalContext sEval
;
2745 Tcl_WrongNumArgs(interp
, 2, objv
, "SQL");
2749 dbEvalInit(&sEval
, pDb
, objv
[2], 0, 0);
2750 rc
= dbEvalStep(&sEval
);
2751 if( choice
==DB_ONECOLUMN
){
2753 pResult
= dbEvalColumnValue(&sEval
, 0);
2754 }else if( rc
==TCL_BREAK
){
2755 Tcl_ResetResult(interp
);
2757 }else if( rc
==TCL_BREAK
|| rc
==TCL_OK
){
2758 pResult
= Tcl_NewBooleanObj(rc
==TCL_OK
);
2760 dbEvalFinalize(&sEval
);
2761 if( pResult
) Tcl_SetObjResult(interp
, pResult
);
2763 if( rc
==TCL_BREAK
){
2770 ** $db eval ?options? $sql ?array? ?{ ...code... }?
2772 ** The SQL statement in $sql is evaluated. For each row, the values are
2773 ** placed in elements of the array named "array" and ...code... is executed.
2774 ** If "array" and "code" are omitted, then no callback is every invoked.
2775 ** If "array" is an empty string, then the values are placed in variables
2776 ** that have the same name as the fields extracted by the query.
2781 while( objc
>3 && (zOpt
= Tcl_GetString(objv
[2]))!=0 && zOpt
[0]=='-' ){
2782 if( strcmp(zOpt
, "-withoutnulls")==0 ){
2783 evalFlags
|= SQLITE_EVAL_WITHOUTNULLS
;
2786 Tcl_AppendResult(interp
, "unknown option: \"", zOpt
, "\"", (void*)0);
2792 if( objc
<3 || objc
>5 ){
2793 Tcl_WrongNumArgs(interp
, 2, objv
,
2794 "?OPTIONS? SQL ?ARRAY-NAME? ?SCRIPT?");
2799 DbEvalContext sEval
;
2800 Tcl_Obj
*pRet
= Tcl_NewObj();
2801 Tcl_IncrRefCount(pRet
);
2802 dbEvalInit(&sEval
, pDb
, objv
[2], 0, 0);
2803 while( TCL_OK
==(rc
= dbEvalStep(&sEval
)) ){
2806 dbEvalRowInfo(&sEval
, &nCol
, 0);
2807 for(i
=0; i
<nCol
; i
++){
2808 Tcl_ListObjAppendElement(interp
, pRet
, dbEvalColumnValue(&sEval
, i
));
2811 dbEvalFinalize(&sEval
);
2812 if( rc
==TCL_BREAK
){
2813 Tcl_SetObjResult(interp
, pRet
);
2816 Tcl_DecrRefCount(pRet
);
2820 Tcl_Obj
*pArray
= 0;
2823 if( objc
>=5 && *(char *)Tcl_GetString(objv
[3]) ){
2826 pScript
= objv
[objc
-1];
2827 Tcl_IncrRefCount(pScript
);
2829 p
= (DbEvalContext
*)Tcl_Alloc(sizeof(DbEvalContext
));
2830 dbEvalInit(p
, pDb
, objv
[2], pArray
, evalFlags
);
2833 cd2
[1] = (void *)pScript
;
2834 rc
= DbEvalNextCmd(cd2
, interp
, TCL_OK
);
2840 ** $db function NAME [OPTIONS] SCRIPT
2842 ** Create a new SQL function called NAME. Whenever that function is
2843 ** called, invoke SCRIPT to evaluate the function.
2846 ** --argcount N Function has exactly N arguments
2847 ** --deterministic The function is pure
2848 ** --directonly Prohibit use inside triggers and views
2849 ** --innocuous Has no side effects or information leaks
2850 ** --returntype TYPE Specify the return type of the function
2853 int flags
= SQLITE_UTF8
;
2859 int eType
= SQLITE_NULL
;
2861 Tcl_WrongNumArgs(interp
, 2, objv
, "NAME ?SWITCHES? SCRIPT");
2864 for(i
=3; i
<(objc
-1); i
++){
2865 const char *z
= Tcl_GetString(objv
[i
]);
2866 int n
= strlen30(z
);
2867 if( n
>1 && strncmp(z
, "-argcount",n
)==0 ){
2869 Tcl_AppendResult(interp
, "option requires an argument: ", z
,(char*)0);
2872 if( Tcl_GetIntFromObj(interp
, objv
[i
+1], &nArg
) ) return TCL_ERROR
;
2874 Tcl_AppendResult(interp
, "number of arguments must be non-negative",
2880 if( n
>1 && strncmp(z
, "-deterministic",n
)==0 ){
2881 flags
|= SQLITE_DETERMINISTIC
;
2883 if( n
>1 && strncmp(z
, "-directonly",n
)==0 ){
2884 flags
|= SQLITE_DIRECTONLY
;
2886 if( n
>1 && strncmp(z
, "-innocuous",n
)==0 ){
2887 flags
|= SQLITE_INNOCUOUS
;
2889 if( n
>1 && strncmp(z
, "-returntype", n
)==0 ){
2890 const char *azType
[] = {"integer", "real", "text", "blob", "any", 0};
2891 assert( SQLITE_INTEGER
==1 && SQLITE_FLOAT
==2 && SQLITE_TEXT
==3 );
2892 assert( SQLITE_BLOB
==4 && SQLITE_NULL
==5 );
2894 Tcl_AppendResult(interp
, "option requires an argument: ", z
,(char*)0);
2898 if( Tcl_GetIndexFromObj(interp
, objv
[i
], azType
, "type", 0, &eType
) ){
2903 Tcl_AppendResult(interp
, "bad option \"", z
,
2904 "\": must be -argcount, -deterministic, -directonly,"
2905 " -innocuous, or -returntype", (char*)0
2911 pScript
= objv
[objc
-1];
2912 zName
= Tcl_GetStringFromObj(objv
[2], 0);
2913 pFunc
= findSqlFunc(pDb
, zName
);
2914 if( pFunc
==0 ) return TCL_ERROR
;
2915 if( pFunc
->pScript
){
2916 Tcl_DecrRefCount(pFunc
->pScript
);
2918 pFunc
->pScript
= pScript
;
2919 Tcl_IncrRefCount(pScript
);
2920 pFunc
->useEvalObjv
= safeToUseEvalObjv(interp
, pScript
);
2921 pFunc
->eType
= eType
;
2922 rc
= sqlite3_create_function(pDb
->db
, zName
, nArg
, flags
,
2923 pFunc
, tclSqlFunc
, 0, 0);
2924 if( rc
!=SQLITE_OK
){
2926 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(pDb
->db
), TCL_VOLATILE
);
2932 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
2935 #ifdef SQLITE_OMIT_INCRBLOB
2936 Tcl_AppendResult(interp
, "incrblob not available in this build", (char*)0);
2940 const char *zDb
= "main";
2942 const char *zColumn
;
2945 /* Check for the -readonly option */
2946 if( objc
>3 && strcmp(Tcl_GetString(objv
[2]), "-readonly")==0 ){
2950 if( objc
!=(5+isReadonly
) && objc
!=(6+isReadonly
) ){
2951 Tcl_WrongNumArgs(interp
, 2, objv
, "?-readonly? ?DB? TABLE COLUMN ROWID");
2955 if( objc
==(6+isReadonly
) ){
2956 zDb
= Tcl_GetString(objv
[2]);
2958 zTable
= Tcl_GetString(objv
[objc
-3]);
2959 zColumn
= Tcl_GetString(objv
[objc
-2]);
2960 rc
= Tcl_GetWideIntFromObj(interp
, objv
[objc
-1], &iRow
);
2963 rc
= createIncrblobChannel(
2964 interp
, pDb
, zDb
, zTable
, zColumn
, (sqlite3_int64
)iRow
, isReadonly
2974 ** Interrupt the execution of the inner-most SQL interpreter. This
2975 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2977 case DB_INTERRUPT
: {
2978 sqlite3_interrupt(pDb
->db
);
2983 ** $db nullvalue ?STRING?
2985 ** Change text used when a NULL comes back from the database. If ?STRING?
2986 ** is not present, then the current string used for NULL is returned.
2987 ** If STRING is present, then STRING is returned.
2990 case DB_NULLVALUE
: {
2991 if( objc
!=2 && objc
!=3 ){
2992 Tcl_WrongNumArgs(interp
, 2, objv
, "NULLVALUE");
2997 char *zNull
= Tcl_GetStringFromObj(objv
[2], &len
);
2999 Tcl_Free(pDb
->zNull
);
3001 if( zNull
&& len
>0 ){
3002 pDb
->zNull
= Tcl_Alloc( len
+ 1 );
3003 memcpy(pDb
->zNull
, zNull
, len
);
3004 pDb
->zNull
[len
] = '\0';
3009 Tcl_SetObjResult(interp
, Tcl_NewStringObj(pDb
->zNull
, -1));
3014 ** $db last_insert_rowid
3016 ** Return an integer which is the ROWID for the most recent insert.
3018 case DB_LAST_INSERT_ROWID
: {
3022 Tcl_WrongNumArgs(interp
, 2, objv
, "");
3025 rowid
= sqlite3_last_insert_rowid(pDb
->db
);
3026 pResult
= Tcl_GetObjResult(interp
);
3027 Tcl_SetWideIntObj(pResult
, rowid
);
3032 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
3035 /* $db progress ?N CALLBACK?
3037 ** Invoke the given callback every N virtual machine opcodes while executing
3042 if( pDb
->zProgress
){
3043 Tcl_AppendResult(interp
, pDb
->zProgress
, (char*)0);
3045 }else if( objc
==4 ){
3049 if( TCL_OK
!=Tcl_GetIntFromObj(interp
, objv
[2], &N
) ){
3052 if( pDb
->zProgress
){
3053 Tcl_Free(pDb
->zProgress
);
3055 zProgress
= Tcl_GetStringFromObj(objv
[3], &len
);
3056 if( zProgress
&& len
>0 ){
3057 pDb
->zProgress
= Tcl_Alloc( len
+ 1 );
3058 memcpy(pDb
->zProgress
, zProgress
, len
+1);
3062 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
3063 if( pDb
->zProgress
){
3064 pDb
->interp
= interp
;
3065 sqlite3_progress_handler(pDb
->db
, N
, DbProgressHandler
, pDb
);
3067 sqlite3_progress_handler(pDb
->db
, 0, 0, 0);
3071 Tcl_WrongNumArgs(interp
, 2, objv
, "N CALLBACK");
3077 /* $db profile ?CALLBACK?
3079 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
3080 ** that has run. The text of the SQL and the amount of elapse time are
3081 ** appended to CALLBACK before the script is run.
3085 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
3087 }else if( objc
==2 ){
3088 if( pDb
->zProfile
){
3089 Tcl_AppendResult(interp
, pDb
->zProfile
, (char*)0);
3094 if( pDb
->zProfile
){
3095 Tcl_Free(pDb
->zProfile
);
3097 zProfile
= Tcl_GetStringFromObj(objv
[2], &len
);
3098 if( zProfile
&& len
>0 ){
3099 pDb
->zProfile
= Tcl_Alloc( len
+ 1 );
3100 memcpy(pDb
->zProfile
, zProfile
, len
+1);
3104 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3105 !defined(SQLITE_OMIT_DEPRECATED)
3106 if( pDb
->zProfile
){
3107 pDb
->interp
= interp
;
3108 sqlite3_profile(pDb
->db
, DbProfileHandler
, pDb
);
3110 sqlite3_profile(pDb
->db
, 0, 0);
3120 ** Change the encryption key on the currently open database.
3123 /* BEGIN SQLCIPHER */
3124 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3130 Tcl_WrongNumArgs(interp
, 2, objv
, "KEY");
3133 /* BEGIN SQLCIPHER */
3134 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3135 pKey
= Tcl_GetByteArrayFromObj(objv
[2], &nKey
);
3136 rc
= sqlite3_rekey(pDb
->db
, pKey
, nKey
);
3138 Tcl_AppendResult(interp
, sqlite3_errstr(rc
), (char*)0);
3146 /* $db restore ?DATABASE? FILENAME
3148 ** Open a database file named FILENAME. Transfer the content
3149 ** of FILENAME into the local database DATABASE (default: "main").
3152 const char *zSrcFile
;
3153 const char *zDestDb
;
3155 sqlite3_backup
*pBackup
;
3160 zSrcFile
= Tcl_GetString(objv
[2]);
3161 }else if( objc
==4 ){
3162 zDestDb
= Tcl_GetString(objv
[2]);
3163 zSrcFile
= Tcl_GetString(objv
[3]);
3165 Tcl_WrongNumArgs(interp
, 2, objv
, "?DATABASE? FILENAME");
3168 rc
= sqlite3_open_v2(zSrcFile
, &pSrc
,
3169 SQLITE_OPEN_READONLY
| pDb
->openFlags
, 0);
3170 if( rc
!=SQLITE_OK
){
3171 Tcl_AppendResult(interp
, "cannot open source database: ",
3172 sqlite3_errmsg(pSrc
), (char*)0);
3173 sqlite3_close(pSrc
);
3176 pBackup
= sqlite3_backup_init(pDb
->db
, zDestDb
, pSrc
, "main");
3178 Tcl_AppendResult(interp
, "restore failed: ",
3179 sqlite3_errmsg(pDb
->db
), (char*)0);
3180 sqlite3_close(pSrc
);
3183 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
3184 || rc
==SQLITE_BUSY
){
3185 if( rc
==SQLITE_BUSY
){
3186 if( nTimeout
++ >= 3 ) break;
3190 sqlite3_backup_finish(pBackup
);
3191 if( rc
==SQLITE_DONE
){
3193 }else if( rc
==SQLITE_BUSY
|| rc
==SQLITE_LOCKED
){
3194 Tcl_AppendResult(interp
, "restore failed: source database busy",
3198 Tcl_AppendResult(interp
, "restore failed: ",
3199 sqlite3_errmsg(pDb
->db
), (char*)0);
3202 sqlite3_close(pSrc
);
3207 ** $db serialize ?DATABASE?
3209 ** Return a serialization of a database.
3211 case DB_SERIALIZE
: {
3212 #ifdef SQLITE_OMIT_DESERIALIZE
3213 Tcl_AppendResult(interp
, "MEMDB not available in this build",
3217 const char *zSchema
= objc
>=3 ? Tcl_GetString(objv
[2]) : "main";
3218 sqlite3_int64 sz
= 0;
3219 unsigned char *pData
;
3220 if( objc
!=2 && objc
!=3 ){
3221 Tcl_WrongNumArgs(interp
, 2, objv
, "?DATABASE?");
3225 pData
= sqlite3_serialize(pDb
->db
, zSchema
, &sz
, SQLITE_SERIALIZE_NOCOPY
);
3229 pData
= sqlite3_serialize(pDb
->db
, zSchema
, &sz
, 0);
3232 Tcl_SetObjResult(interp
, Tcl_NewByteArrayObj(pData
,sz
));
3233 if( needFree
) sqlite3_free(pData
);
3240 ** $db status (step|sort|autoindex|vmstep)
3242 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
3243 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
3249 Tcl_WrongNumArgs(interp
, 2, objv
, "(step|sort|autoindex)");
3252 zOp
= Tcl_GetString(objv
[2]);
3253 if( strcmp(zOp
, "step")==0 ){
3255 }else if( strcmp(zOp
, "sort")==0 ){
3257 }else if( strcmp(zOp
, "autoindex")==0 ){
3259 }else if( strcmp(zOp
, "vmstep")==0 ){
3262 Tcl_AppendResult(interp
,
3263 "bad argument: should be autoindex, step, sort or vmstep",
3267 Tcl_SetObjResult(interp
, Tcl_NewIntObj(v
));
3272 ** $db timeout MILLESECONDS
3274 ** Delay for the number of milliseconds specified when a file is locked.
3279 Tcl_WrongNumArgs(interp
, 2, objv
, "MILLISECONDS");
3282 if( Tcl_GetIntFromObj(interp
, objv
[2], &ms
) ) return TCL_ERROR
;
3283 sqlite3_busy_timeout(pDb
->db
, ms
);
3288 ** $db total_changes
3290 ** Return the number of rows that were modified, inserted, or deleted
3291 ** since the database handle was created.
3293 case DB_TOTAL_CHANGES
: {
3296 Tcl_WrongNumArgs(interp
, 2, objv
, "");
3299 pResult
= Tcl_GetObjResult(interp
);
3300 Tcl_SetWideIntObj(pResult
, sqlite3_total_changes64(pDb
->db
));
3304 /* $db trace ?CALLBACK?
3306 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
3307 ** that is executed. The text of the SQL is appended to CALLBACK before
3312 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
3314 }else if( objc
==2 ){
3316 Tcl_AppendResult(interp
, pDb
->zTrace
, (char*)0);
3322 Tcl_Free(pDb
->zTrace
);
3324 zTrace
= Tcl_GetStringFromObj(objv
[2], &len
);
3325 if( zTrace
&& len
>0 ){
3326 pDb
->zTrace
= Tcl_Alloc( len
+ 1 );
3327 memcpy(pDb
->zTrace
, zTrace
, len
+1);
3331 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3332 !defined(SQLITE_OMIT_DEPRECATED)
3334 pDb
->interp
= interp
;
3335 sqlite3_trace(pDb
->db
, DbTraceHandler
, pDb
);
3337 sqlite3_trace(pDb
->db
, 0, 0);
3344 /* $db trace_v2 ?CALLBACK? ?MASK?
3346 ** Make arrangements to invoke the CALLBACK routine for each trace event
3347 ** matching the mask that is generated. The parameters are appended to
3348 ** CALLBACK before it is executed.
3352 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK? ?MASK?");
3354 }else if( objc
==2 ){
3355 if( pDb
->zTraceV2
){
3356 Tcl_AppendResult(interp
, pDb
->zTraceV2
, (char*)0);
3361 Tcl_WideInt wMask
= 0;
3363 static const char *TTYPE_strs
[] = {
3364 "statement", "profile", "row", "close", 0
3367 TTYPE_STMT
, TTYPE_PROFILE
, TTYPE_ROW
, TTYPE_CLOSE
3370 if( TCL_OK
!=Tcl_ListObjLength(interp
, objv
[3], &len
) ){
3373 for(i
=0; i
<len
; i
++){
3376 if( TCL_OK
!=Tcl_ListObjIndex(interp
, objv
[3], i
, &pObj
) ){
3379 if( Tcl_GetIndexFromObj(interp
, pObj
, TTYPE_strs
, "trace type",
3380 0, &ttype
)!=TCL_OK
){
3382 Tcl_Obj
*pError
= Tcl_DuplicateObj(Tcl_GetObjResult(interp
));
3383 Tcl_IncrRefCount(pError
);
3384 if( TCL_OK
==Tcl_GetWideIntFromObj(interp
, pObj
, &wType
) ){
3385 Tcl_DecrRefCount(pError
);
3388 Tcl_SetObjResult(interp
, pError
);
3389 Tcl_DecrRefCount(pError
);
3393 switch( (enum TTYPE_enum
)ttype
){
3394 case TTYPE_STMT
: wMask
|= SQLITE_TRACE_STMT
; break;
3395 case TTYPE_PROFILE
: wMask
|= SQLITE_TRACE_PROFILE
; break;
3396 case TTYPE_ROW
: wMask
|= SQLITE_TRACE_ROW
; break;
3397 case TTYPE_CLOSE
: wMask
|= SQLITE_TRACE_CLOSE
; break;
3402 wMask
= SQLITE_TRACE_STMT
; /* use the "legacy" default */
3404 if( pDb
->zTraceV2
){
3405 Tcl_Free(pDb
->zTraceV2
);
3407 zTraceV2
= Tcl_GetStringFromObj(objv
[2], &len
);
3408 if( zTraceV2
&& len
>0 ){
3409 pDb
->zTraceV2
= Tcl_Alloc( len
+ 1 );
3410 memcpy(pDb
->zTraceV2
, zTraceV2
, len
+1);
3414 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3415 if( pDb
->zTraceV2
){
3416 pDb
->interp
= interp
;
3417 sqlite3_trace_v2(pDb
->db
, (unsigned)wMask
, DbTraceV2Handler
, pDb
);
3419 sqlite3_trace_v2(pDb
->db
, 0, 0, 0);
3426 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
3428 ** Start a new transaction (if we are not already in the midst of a
3429 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
3430 ** completes, either commit the transaction or roll it back if SCRIPT
3431 ** throws an exception. Or if no new transation was started, do nothing.
3432 ** pass the exception on up the stack.
3434 ** This command was inspired by Dave Thomas's talk on Ruby at the
3435 ** 2005 O'Reilly Open Source Convention (OSCON).
3437 case DB_TRANSACTION
: {
3439 const char *zBegin
= "SAVEPOINT _tcl_transaction";
3440 if( objc
!=3 && objc
!=4 ){
3441 Tcl_WrongNumArgs(interp
, 2, objv
, "[TYPE] SCRIPT");
3445 if( pDb
->nTransaction
==0 && objc
==4 ){
3446 static const char *TTYPE_strs
[] = {
3447 "deferred", "exclusive", "immediate", 0
3450 TTYPE_DEFERRED
, TTYPE_EXCLUSIVE
, TTYPE_IMMEDIATE
3453 if( Tcl_GetIndexFromObj(interp
, objv
[2], TTYPE_strs
, "transaction type",
3457 switch( (enum TTYPE_enum
)ttype
){
3458 case TTYPE_DEFERRED
: /* no-op */; break;
3459 case TTYPE_EXCLUSIVE
: zBegin
= "BEGIN EXCLUSIVE"; break;
3460 case TTYPE_IMMEDIATE
: zBegin
= "BEGIN IMMEDIATE"; break;
3463 pScript
= objv
[objc
-1];
3465 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
3467 rc
= sqlite3_exec(pDb
->db
, zBegin
, 0, 0, 0);
3469 if( rc
!=SQLITE_OK
){
3470 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
3473 pDb
->nTransaction
++;
3475 /* If using NRE, schedule a callback to invoke the script pScript, then
3476 ** a second callback to commit (or rollback) the transaction or savepoint
3477 ** opened above. If not using NRE, evaluate the script directly, then
3478 ** call function DbTransPostCmd() to commit (or rollback) the transaction
3480 addDatabaseRef(pDb
); /* DbTransPostCmd() calls delDatabaseRef() */
3482 Tcl_NRAddCallback(interp
, DbTransPostCmd
, cd
, 0, 0, 0);
3483 (void)Tcl_NREvalObj(interp
, pScript
, 0);
3485 rc
= DbTransPostCmd(&cd
, interp
, Tcl_EvalObjEx(interp
, pScript
, 0));
3491 ** $db unlock_notify ?script?
3493 case DB_UNLOCK_NOTIFY
: {
3494 #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
3495 Tcl_AppendResult(interp
, "unlock_notify not available in this build",
3499 if( objc
!=2 && objc
!=3 ){
3500 Tcl_WrongNumArgs(interp
, 2, objv
, "?SCRIPT?");
3503 void (*xNotify
)(void **, int) = 0;
3504 void *pNotifyArg
= 0;
3506 if( pDb
->pUnlockNotify
){
3507 Tcl_DecrRefCount(pDb
->pUnlockNotify
);
3508 pDb
->pUnlockNotify
= 0;
3512 xNotify
= DbUnlockNotify
;
3513 pNotifyArg
= (void *)pDb
;
3514 pDb
->pUnlockNotify
= objv
[2];
3515 Tcl_IncrRefCount(pDb
->pUnlockNotify
);
3518 if( sqlite3_unlock_notify(pDb
->db
, xNotify
, pNotifyArg
) ){
3519 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
3528 ** $db preupdate_hook count
3529 ** $db preupdate_hook hook ?SCRIPT?
3530 ** $db preupdate_hook new INDEX
3531 ** $db preupdate_hook old INDEX
3533 case DB_PREUPDATE
: {
3534 #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
3535 Tcl_AppendResult(interp
, "preupdate_hook was omitted at compile-time",
3539 static const char *azSub
[] = {"count", "depth", "hook", "new", "old", 0};
3540 enum DbPreupdateSubCmd
{
3541 PRE_COUNT
, PRE_DEPTH
, PRE_HOOK
, PRE_NEW
, PRE_OLD
3546 Tcl_WrongNumArgs(interp
, 2, objv
, "SUB-COMMAND ?ARGS?");
3548 if( Tcl_GetIndexFromObj(interp
, objv
[2], azSub
, "sub-command", 0, &iSub
) ){
3552 switch( (enum DbPreupdateSubCmd
)iSub
){
3554 int nCol
= sqlite3_preupdate_count(pDb
->db
);
3555 Tcl_SetObjResult(interp
, Tcl_NewIntObj(nCol
));
3561 Tcl_WrongNumArgs(interp
, 2, objv
, "hook ?SCRIPT?");
3564 DbHookCmd(interp
, pDb
, (objc
==4 ? objv
[3] : 0), &pDb
->pPreUpdateHook
);
3571 Tcl_WrongNumArgs(interp
, 3, objv
, "");
3574 pRet
= Tcl_NewIntObj(sqlite3_preupdate_depth(pDb
->db
));
3575 Tcl_SetObjResult(interp
, pRet
);
3582 sqlite3_value
*pValue
;
3584 Tcl_WrongNumArgs(interp
, 3, objv
, "INDEX");
3587 if( Tcl_GetIntFromObj(interp
, objv
[3], &iIdx
) ){
3591 if( iSub
==PRE_OLD
){
3592 rc
= sqlite3_preupdate_old(pDb
->db
, iIdx
, &pValue
);
3594 assert( iSub
==PRE_NEW
);
3595 rc
= sqlite3_preupdate_new(pDb
->db
, iIdx
, &pValue
);
3598 if( rc
==SQLITE_OK
){
3600 pObj
= Tcl_NewStringObj((char*)sqlite3_value_text(pValue
), -1);
3601 Tcl_SetObjResult(interp
, pObj
);
3603 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
3608 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
3613 ** $db wal_hook ?script?
3614 ** $db update_hook ?script?
3615 ** $db rollback_hook ?script?
3618 case DB_UPDATE_HOOK
:
3619 case DB_ROLLBACK_HOOK
: {
3620 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
3621 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3623 Tcl_Obj
**ppHook
= 0;
3624 if( choice
==DB_WAL_HOOK
) ppHook
= &pDb
->pWalHook
;
3625 if( choice
==DB_UPDATE_HOOK
) ppHook
= &pDb
->pUpdateHook
;
3626 if( choice
==DB_ROLLBACK_HOOK
) ppHook
= &pDb
->pRollbackHook
;
3628 Tcl_WrongNumArgs(interp
, 2, objv
, "?SCRIPT?");
3632 DbHookCmd(interp
, pDb
, (objc
==3 ? objv
[2] : 0), ppHook
);
3638 ** Return the version string for this database.
3642 for(i
=2; i
<objc
; i
++){
3643 const char *zArg
= Tcl_GetString(objv
[i
]);
3644 /* Optional arguments to $db version are used for testing purpose */
3646 /* $db version -use-legacy-prepare BOOLEAN
3648 ** Turn the use of legacy sqlite3_prepare() on or off.
3650 if( strcmp(zArg
, "-use-legacy-prepare")==0 && i
+1<objc
){
3652 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &pDb
->bLegacyPrepare
) ){
3657 /* $db version -last-stmt-ptr
3659 ** Return a string which is a hex encoding of the pointer to the
3660 ** most recent sqlite3_stmt in the statement cache.
3662 if( strcmp(zArg
, "-last-stmt-ptr")==0 ){
3664 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%p",
3665 pDb
->stmtList
? pDb
->stmtList
->pStmt
: 0);
3666 Tcl_SetResult(interp
, zBuf
, TCL_VOLATILE
);
3668 #endif /* SQLITE_TEST */
3670 Tcl_AppendResult(interp
, "unknown argument: ", zArg
, (char*)0);
3675 Tcl_SetResult(interp
, (char *)sqlite3_libversion(), TCL_STATIC
);
3681 } /* End of the SWITCH statement */
3687 ** Adaptor that provides an objCmd interface to the NRE-enabled
3688 ** interface implementation.
3690 static int SQLITE_TCLAPI
DbObjCmdAdaptor(
3696 return Tcl_NRCallObjProc(interp
, DbObjCmd
, cd
, objc
, objv
);
3698 #endif /* SQLITE_TCL_NRE */
3701 ** Issue the usage message when the "sqlite3" command arguments are
3704 static int sqliteCmdUsage(
3708 Tcl_WrongNumArgs(interp
, 1, objv
,
3709 "HANDLE ?FILENAME? ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
3710 " ?-nofollow BOOLEAN?"
3711 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
3712 /* BEGIN SQLCIPHER */
3713 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3722 ** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
3723 ** ?-create BOOLEAN? ?-nomutex BOOLEAN?
3724 ** ?-nofollow BOOLEAN?
3726 ** This is the main Tcl command. When the "sqlite" Tcl command is
3727 ** invoked, this routine runs to process that command.
3729 ** The first argument, DBNAME, is an arbitrary name for a new
3730 ** database connection. This command creates a new command named
3731 ** DBNAME that is used to control that connection. The database
3732 ** connection is deleted when the DBNAME command is deleted.
3734 ** The second argument is the name of the database file.
3737 static int SQLITE_TCLAPI
DbMain(
3747 const char *zFile
= 0;
3748 const char *zVfs
= 0;
3750 int bTranslateFileName
= 1;
3751 Tcl_DString translatedFilename
;
3752 /* BEGIN SQLCIPHER */
3753 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3760 /* In normal use, each TCL interpreter runs in a single thread. So
3761 ** by default, we can turn off mutexing on SQLite database connections.
3762 ** However, for testing purposes it is useful to have mutexes turned
3763 ** on. So, by default, mutexes default off. But if compiled with
3764 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3766 #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3767 flags
= SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
| SQLITE_OPEN_FULLMUTEX
;
3769 flags
= SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
| SQLITE_OPEN_NOMUTEX
;
3772 if( objc
==1 ) return sqliteCmdUsage(interp
, objv
);
3774 zArg
= Tcl_GetStringFromObj(objv
[1], 0);
3775 if( strcmp(zArg
,"-version")==0 ){
3776 Tcl_AppendResult(interp
,sqlite3_libversion(), (char*)0);
3779 if( strcmp(zArg
,"-sourceid")==0 ){
3780 Tcl_AppendResult(interp
,sqlite3_sourceid(), (char*)0);
3783 if( strcmp(zArg
,"-has-codec")==0 ){
3784 /* BEGIN SQLCIPHER */
3785 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3786 Tcl_AppendResult(interp
,"1",(char*)0);
3788 Tcl_AppendResult(interp
,"0",(char*)0);
3793 if( zArg
[0]=='-' ) return sqliteCmdUsage(interp
, objv
);
3795 for(i
=2; i
<objc
; i
++){
3796 zArg
= Tcl_GetString(objv
[i
]);
3798 if( zFile
!=0 ) return sqliteCmdUsage(interp
, objv
);
3802 if( i
==objc
-1 ) return sqliteCmdUsage(interp
, objv
);
3804 if( strcmp(zArg
,"-key")==0 ){
3805 /* BEGIN SQLCIPHER */
3806 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3807 pKey
= Tcl_GetByteArrayFromObj(objv
[i
], &nKey
);
3810 }else if( strcmp(zArg
, "-vfs")==0 ){
3811 zVfs
= Tcl_GetString(objv
[i
]);
3812 }else if( strcmp(zArg
, "-readonly")==0 ){
3814 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &b
) ) return TCL_ERROR
;
3816 flags
&= ~(SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
);
3817 flags
|= SQLITE_OPEN_READONLY
;
3819 flags
&= ~SQLITE_OPEN_READONLY
;
3820 flags
|= SQLITE_OPEN_READWRITE
;
3822 }else if( strcmp(zArg
, "-create")==0 ){
3824 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &b
) ) return TCL_ERROR
;
3825 if( b
&& (flags
& SQLITE_OPEN_READONLY
)==0 ){
3826 flags
|= SQLITE_OPEN_CREATE
;
3828 flags
&= ~SQLITE_OPEN_CREATE
;
3830 }else if( strcmp(zArg
, "-nofollow")==0 ){
3832 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &b
) ) return TCL_ERROR
;
3834 flags
|= SQLITE_OPEN_NOFOLLOW
;
3836 flags
&= ~SQLITE_OPEN_NOFOLLOW
;
3838 }else if( strcmp(zArg
, "-nomutex")==0 ){
3840 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &b
) ) return TCL_ERROR
;
3842 flags
|= SQLITE_OPEN_NOMUTEX
;
3843 flags
&= ~SQLITE_OPEN_FULLMUTEX
;
3845 flags
&= ~SQLITE_OPEN_NOMUTEX
;
3847 }else if( strcmp(zArg
, "-fullmutex")==0 ){
3849 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &b
) ) return TCL_ERROR
;
3851 flags
|= SQLITE_OPEN_FULLMUTEX
;
3852 flags
&= ~SQLITE_OPEN_NOMUTEX
;
3854 flags
&= ~SQLITE_OPEN_FULLMUTEX
;
3856 }else if( strcmp(zArg
, "-uri")==0 ){
3858 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &b
) ) return TCL_ERROR
;
3860 flags
|= SQLITE_OPEN_URI
;
3862 flags
&= ~SQLITE_OPEN_URI
;
3864 }else if( strcmp(zArg
, "-translatefilename")==0 ){
3865 if( Tcl_GetBooleanFromObj(interp
, objv
[i
], &bTranslateFileName
) ){
3869 Tcl_AppendResult(interp
, "unknown option: ", zArg
, (char*)0);
3874 p
= (SqliteDb
*)Tcl_Alloc( sizeof(*p
) );
3875 memset(p
, 0, sizeof(*p
));
3876 if( zFile
==0 ) zFile
= "";
3877 if( bTranslateFileName
){
3878 zFile
= Tcl_TranslateFileName(interp
, zFile
, &translatedFilename
);
3880 rc
= sqlite3_open_v2(zFile
, &p
->db
, flags
, zVfs
);
3881 if( bTranslateFileName
){
3882 Tcl_DStringFree(&translatedFilename
);
3885 if( SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
3886 zErrMsg
= sqlite3_mprintf("%s", sqlite3_errmsg(p
->db
));
3887 sqlite3_close(p
->db
);
3891 zErrMsg
= sqlite3_mprintf("%s", sqlite3_errstr(rc
));
3893 /* BEGIN SQLCIPHER */
3894 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3896 sqlite3_key(p
->db
, pKey
, nKey
);
3901 Tcl_SetResult(interp
, zErrMsg
, TCL_VOLATILE
);
3903 sqlite3_free(zErrMsg
);
3906 p
->maxStmt
= NUM_PREPARED_STMTS
;
3907 p
->openFlags
= flags
& SQLITE_OPEN_URI
;
3909 zArg
= Tcl_GetStringFromObj(objv
[1], 0);
3911 Tcl_NRCreateCommand(interp
, zArg
, DbObjCmdAdaptor
, DbObjCmd
,
3912 (char*)p
, DbDeleteCmd
);
3914 Tcl_CreateObjCommand(interp
, zArg
, DbObjCmd
, (char*)p
, DbDeleteCmd
);
3921 ** Provide a dummy Tcl_InitStubs if we are using this as a static
3924 #ifndef USE_TCL_STUBS
3925 # undef Tcl_InitStubs
3926 # define Tcl_InitStubs(a,b,c) TCL_VERSION
3930 ** Make sure we have a PACKAGE_VERSION macro defined. This will be
3931 ** defined automatically by the TEA makefile. But other makefiles
3932 ** do not define it.
3934 #ifndef PACKAGE_VERSION
3935 # define PACKAGE_VERSION SQLITE_VERSION
3939 ** Initialize this module.
3941 ** This Tcl module contains only a single new Tcl command named "sqlite".
3942 ** (Hence there is no namespace. There is no point in using a namespace
3943 ** if the extension only supplies one new name!) The "sqlite" command is
3944 ** used to open a new SQLite database. See the DbMain() routine above
3945 ** for additional information.
3947 ** The EXTERN macros are required by TCL in order to work on windows.
3949 EXTERN
int Sqlite3_Init(Tcl_Interp
*interp
){
3950 int rc
= Tcl_InitStubs(interp
, "8.4", 0) ? TCL_OK
: TCL_ERROR
;
3952 Tcl_CreateObjCommand(interp
, "sqlite3", (Tcl_ObjCmdProc
*)DbMain
, 0, 0);
3953 #ifndef SQLITE_3_SUFFIX_ONLY
3954 /* The "sqlite" alias is undocumented. It is here only to support
3955 ** legacy scripts. All new scripts should use only the "sqlite3"
3957 Tcl_CreateObjCommand(interp
, "sqlite", (Tcl_ObjCmdProc
*)DbMain
, 0, 0);
3959 rc
= Tcl_PkgProvide(interp
, "sqlite3", PACKAGE_VERSION
);
3963 EXTERN
int Tclsqlite3_Init(Tcl_Interp
*interp
){ return Sqlite3_Init(interp
); }
3964 EXTERN
int Sqlite3_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3965 EXTERN
int Tclsqlite3_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3967 /* Because it accesses the file-system and uses persistent state, SQLite
3968 ** is not considered appropriate for safe interpreters. Hence, we cause
3969 ** the _SafeInit() interfaces return TCL_ERROR.
3971 EXTERN
int Sqlite3_SafeInit(Tcl_Interp
*interp
){ return TCL_ERROR
; }
3972 EXTERN
int Sqlite3_SafeUnload(Tcl_Interp
*interp
, int flags
){return TCL_ERROR
;}
3976 #ifndef SQLITE_3_SUFFIX_ONLY
3977 int Sqlite_Init(Tcl_Interp
*interp
){ return Sqlite3_Init(interp
); }
3978 int Tclsqlite_Init(Tcl_Interp
*interp
){ return Sqlite3_Init(interp
); }
3979 int Sqlite_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3980 int Tclsqlite_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3984 ** If the TCLSH macro is defined, add code to make a stand-alone program.
3988 /* This is the main routine for an ordinary TCL shell. If there are
3989 ** are arguments, run the first argument as a script. Otherwise,
3990 ** read TCL commands from standard input
3992 static const char *tclsh_main_loop(void){
3993 static const char zMainloop
[] =
3994 "if {[llength $argv]>=1} {\n"
3995 "set argv0 [lindex $argv 0]\n"
3996 "set argv [lrange $argv 1 end]\n"
4000 "while {![eof stdin]} {\n"
4001 "if {$line!=\"\"} {\n"
4002 "puts -nonewline \"> \"\n"
4004 "puts -nonewline \"% \"\n"
4007 "append line [gets stdin]\n"
4008 "if {[info complete $line]} {\n"
4009 "if {[catch {uplevel #0 $line} result]} {\n"
4010 "puts stderr \"Error: $result\"\n"
4011 "} elseif {$result!=\"\"} {\n"
4025 # define TCLSH_MAIN main
4027 int SQLITE_CDECL
TCLSH_MAIN(int argc
, char **argv
){
4030 const char *zScript
= 0;
4032 #if defined(TCLSH_INIT_PROC)
4033 extern const char *TCLSH_INIT_PROC(Tcl_Interp
*);
4036 #if !defined(_WIN32_WCE)
4037 if( getenv("SQLITE_DEBUG_BREAK") ){
4038 if( isatty(0) && isatty(2) ){
4040 "attach debugger to process %d and press any key to continue.\n",
4044 #if defined(_WIN32) || defined(WIN32)
4046 #elif defined(SIGTRAP)
4053 /* Call sqlite3_shutdown() once before doing anything else. This is to
4054 ** test that sqlite3_shutdown() can be safely called by a process before
4055 ** sqlite3_initialize() is. */
4058 Tcl_FindExecutable(argv
[0]);
4059 Tcl_SetSystemEncoding(NULL
, "utf-8");
4060 interp
= Tcl_CreateInterp();
4061 Sqlite3_Init(interp
);
4063 sqlite3_snprintf(sizeof(zArgc
), zArgc
, "%d", argc
-1);
4064 Tcl_SetVar(interp
,"argc", zArgc
, TCL_GLOBAL_ONLY
);
4065 Tcl_SetVar(interp
,"argv0",argv
[0],TCL_GLOBAL_ONLY
);
4066 Tcl_SetVar(interp
,"argv", "", TCL_GLOBAL_ONLY
);
4067 for(i
=1; i
<argc
; i
++){
4068 Tcl_SetVar(interp
, "argv", argv
[i
],
4069 TCL_GLOBAL_ONLY
| TCL_LIST_ELEMENT
| TCL_APPEND_VALUE
);
4071 #if defined(TCLSH_INIT_PROC)
4072 zScript
= TCLSH_INIT_PROC(interp
);
4075 zScript
= tclsh_main_loop();
4077 if( Tcl_GlobalEval(interp
, zScript
)!=TCL_OK
){
4078 const char *zInfo
= Tcl_GetVar(interp
, "errorInfo", TCL_GLOBAL_ONLY
);
4079 if( zInfo
==0 ) zInfo
= Tcl_GetStringResult(interp
);
4080 fprintf(stderr
,"%s: %s\n", *argv
, zInfo
);