4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** A TCL Interface to SQLite. Append this file to sqlite3.c and
13 ** compile the whole thing to build a TCL-enabled version of SQLite.
15 ** Compile-time options:
17 ** -DTCLSH=1 Add a "main()" routine that works as a tclsh.
19 ** -DSQLITE_TCLMD5 When used in conjuction with -DTCLSH=1, add
20 ** four new commands to the TCL interpreter for
21 ** generating MD5 checksums: md5, md5file,
22 ** md5-10x8, and md5file-10x8.
24 ** -DSQLITE_TEST When used in conjuction with -DTCLSH=1, add
25 ** hundreds of new commands used for testing
26 ** SQLite. This option implies -DSQLITE_TCLMD5.
32 ** Some additional include files are needed if this file is not
33 ** appended to the amalgamation.
35 #ifndef SQLITE_AMALGAMATION
40 typedef unsigned char u8
;
44 /* Used to get the current process ID */
47 # define GETPID getpid
48 #elif !defined(_WIN32_WCE)
49 # ifndef SQLITE_AMALGAMATION
50 # define WIN32_LEAN_AND_MEAN
53 # define GETPID (int)GetCurrentProcessId
57 * Windows needs to know which symbols to export. Unix does not.
58 * BUILD_sqlite should be undefined for Unix.
61 #undef TCL_STORAGE_CLASS
62 #define TCL_STORAGE_CLASS DLLEXPORT
63 #endif /* BUILD_sqlite */
65 #define NUM_PREPARED_STMTS 10
66 #define MAX_PREPARED_STMTS 100
68 /* Forward declaration */
69 typedef struct SqliteDb SqliteDb
;
72 ** New SQL functions can be created as TCL scripts. Each such function
73 ** is described by an instance of the following structure.
75 typedef struct SqlFunc SqlFunc
;
77 Tcl_Interp
*interp
; /* The TCL interpret to execute the function */
78 Tcl_Obj
*pScript
; /* The Tcl_Obj representation of the script */
79 SqliteDb
*pDb
; /* Database connection that owns this function */
80 int useEvalObjv
; /* True if it is safe to use Tcl_EvalObjv */
81 char *zName
; /* Name of this function */
82 SqlFunc
*pNext
; /* Next function on the list of them all */
86 ** New collation sequences function can be created as TCL scripts. Each such
87 ** function is described by an instance of the following structure.
89 typedef struct SqlCollate SqlCollate
;
91 Tcl_Interp
*interp
; /* The TCL interpret to execute the function */
92 char *zScript
; /* The script to be run */
93 SqlCollate
*pNext
; /* Next function on the list of them all */
97 ** Prepared statements are cached for faster execution. Each prepared
98 ** statement is described by an instance of the following structure.
100 typedef struct SqlPreparedStmt SqlPreparedStmt
;
101 struct SqlPreparedStmt
{
102 SqlPreparedStmt
*pNext
; /* Next in linked list */
103 SqlPreparedStmt
*pPrev
; /* Previous on the list */
104 sqlite3_stmt
*pStmt
; /* The prepared statement */
105 int nSql
; /* chars in zSql[] */
106 const char *zSql
; /* Text of the SQL statement */
107 int nParm
; /* Size of apParm array */
108 Tcl_Obj
**apParm
; /* Array of referenced object pointers */
111 typedef struct IncrblobChannel IncrblobChannel
;
114 ** There is one instance of this structure for each SQLite database
115 ** that has been opened by the SQLite TCL interface.
117 ** If this module is built with SQLITE_TEST defined (to create the SQLite
118 ** testfixture executable), then it may be configured to use either
119 ** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
120 ** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
123 sqlite3
*db
; /* The "real" database structure. MUST BE FIRST */
124 Tcl_Interp
*interp
; /* The interpreter used for this database */
125 char *zBusy
; /* The busy callback routine */
126 char *zCommit
; /* The commit hook callback routine */
127 char *zTrace
; /* The trace callback routine */
128 char *zProfile
; /* The profile callback routine */
129 char *zProgress
; /* The progress callback routine */
130 char *zAuth
; /* The authorization callback routine */
131 int disableAuth
; /* Disable the authorizer if it exists */
132 char *zNull
; /* Text to substitute for an SQL NULL value */
133 SqlFunc
*pFunc
; /* List of SQL functions */
134 Tcl_Obj
*pUpdateHook
; /* Update hook script (if any) */
135 Tcl_Obj
*pRollbackHook
; /* Rollback hook script (if any) */
136 Tcl_Obj
*pWalHook
; /* WAL hook script (if any) */
137 Tcl_Obj
*pUnlockNotify
; /* Unlock notify script (if any) */
138 SqlCollate
*pCollate
; /* List of SQL collation functions */
139 int rc
; /* Return code of most recent sqlite3_exec() */
140 Tcl_Obj
*pCollateNeeded
; /* Collation needed script */
141 SqlPreparedStmt
*stmtList
; /* List of prepared statements*/
142 SqlPreparedStmt
*stmtLast
; /* Last statement in the list */
143 int maxStmt
; /* The next maximum number of stmtList */
144 int nStmt
; /* Number of statements in stmtList */
145 IncrblobChannel
*pIncrblob
;/* Linked list of open incrblob channels */
146 int nStep
, nSort
, nIndex
; /* Statistics for most recent operation */
147 int nTransaction
; /* Number of nested [transaction] methods */
149 int bLegacyPrepare
; /* True to use sqlite3_prepare() */
153 struct IncrblobChannel
{
154 sqlite3_blob
*pBlob
; /* sqlite3 blob handle */
155 SqliteDb
*pDb
; /* Associated database connection */
156 int iSeek
; /* Current seek offset */
157 Tcl_Channel channel
; /* Channel identifier */
158 IncrblobChannel
*pNext
; /* Linked list of all open incrblob channels */
159 IncrblobChannel
*pPrev
; /* Linked list of all open incrblob channels */
163 ** Compute a string length that is limited to what can be stored in
164 ** lower 30 bits of a 32-bit signed integer.
166 static int strlen30(const char *z
){
168 while( *z2
){ z2
++; }
169 return 0x3fffffff & (int)(z2
- z
);
173 #ifndef SQLITE_OMIT_INCRBLOB
175 ** Close all incrblob channels opened using database connection pDb.
176 ** This is called when shutting down the database connection.
178 static void closeIncrblobChannels(SqliteDb
*pDb
){
180 IncrblobChannel
*pNext
;
182 for(p
=pDb
->pIncrblob
; p
; p
=pNext
){
185 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
186 ** which deletes the IncrblobChannel structure at *p. So do not
187 ** call Tcl_Free() here.
189 Tcl_UnregisterChannel(pDb
->interp
, p
->channel
);
194 ** Close an incremental blob channel.
196 static int incrblobClose(ClientData instanceData
, Tcl_Interp
*interp
){
197 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
198 int rc
= sqlite3_blob_close(p
->pBlob
);
199 sqlite3
*db
= p
->pDb
->db
;
201 /* Remove the channel from the SqliteDb.pIncrblob list. */
203 p
->pNext
->pPrev
= p
->pPrev
;
206 p
->pPrev
->pNext
= p
->pNext
;
208 if( p
->pDb
->pIncrblob
==p
){
209 p
->pDb
->pIncrblob
= p
->pNext
;
212 /* Free the IncrblobChannel structure */
216 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(db
), TCL_VOLATILE
);
223 ** Read data from an incremental blob channel.
225 static int incrblobInput(
226 ClientData instanceData
,
231 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
232 int nRead
= bufSize
; /* Number of bytes to read */
233 int nBlob
; /* Total size of the blob */
234 int rc
; /* sqlite error code */
236 nBlob
= sqlite3_blob_bytes(p
->pBlob
);
237 if( (p
->iSeek
+nRead
)>nBlob
){
238 nRead
= nBlob
-p
->iSeek
;
244 rc
= sqlite3_blob_read(p
->pBlob
, (void *)buf
, nRead
, p
->iSeek
);
255 ** Write data to an incremental blob channel.
257 static int incrblobOutput(
258 ClientData instanceData
,
263 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
264 int nWrite
= toWrite
; /* Number of bytes to write */
265 int nBlob
; /* Total size of the blob */
266 int rc
; /* sqlite error code */
268 nBlob
= sqlite3_blob_bytes(p
->pBlob
);
269 if( (p
->iSeek
+nWrite
)>nBlob
){
270 *errorCodePtr
= EINVAL
;
277 rc
= sqlite3_blob_write(p
->pBlob
, (void *)buf
, nWrite
, p
->iSeek
);
288 ** Seek an incremental blob channel.
290 static int incrblobSeek(
291 ClientData instanceData
,
296 IncrblobChannel
*p
= (IncrblobChannel
*)instanceData
;
306 p
->iSeek
= sqlite3_blob_bytes(p
->pBlob
) + offset
;
309 default: assert(!"Bad seekMode");
316 static void incrblobWatch(ClientData instanceData
, int mode
){
319 static int incrblobHandle(ClientData instanceData
, int dir
, ClientData
*hPtr
){
323 static Tcl_ChannelType IncrblobChannelType
= {
324 "incrblob", /* typeName */
325 TCL_CHANNEL_VERSION_2
, /* version */
326 incrblobClose
, /* closeProc */
327 incrblobInput
, /* inputProc */
328 incrblobOutput
, /* outputProc */
329 incrblobSeek
, /* seekProc */
330 0, /* setOptionProc */
331 0, /* getOptionProc */
332 incrblobWatch
, /* watchProc (this is a no-op) */
333 incrblobHandle
, /* getHandleProc (always returns error) */
335 0, /* blockModeProc */
338 0, /* wideSeekProc */
342 ** Create a new incrblob channel.
344 static int createIncrblobChannel(
354 sqlite3
*db
= pDb
->db
;
357 int flags
= TCL_READABLE
|(isReadonly
? 0 : TCL_WRITABLE
);
359 /* This variable is used to name the channels: "incrblob_[incr count]" */
360 static int count
= 0;
363 rc
= sqlite3_blob_open(db
, zDb
, zTable
, zColumn
, iRow
, !isReadonly
, &pBlob
);
365 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(pDb
->db
), TCL_VOLATILE
);
369 p
= (IncrblobChannel
*)Tcl_Alloc(sizeof(IncrblobChannel
));
373 sqlite3_snprintf(sizeof(zChannel
), zChannel
, "incrblob_%d", ++count
);
374 p
->channel
= Tcl_CreateChannel(&IncrblobChannelType
, zChannel
, p
, flags
);
375 Tcl_RegisterChannel(interp
, p
->channel
);
377 /* Link the new channel into the SqliteDb.pIncrblob list. */
378 p
->pNext
= pDb
->pIncrblob
;
386 Tcl_SetResult(interp
, (char *)Tcl_GetChannelName(p
->channel
), TCL_VOLATILE
);
389 #else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
390 #define closeIncrblobChannels(pDb)
394 ** Look at the script prefix in pCmd. We will be executing this script
395 ** after first appending one or more arguments. This routine analyzes
396 ** the script to see if it is safe to use Tcl_EvalObjv() on the script
397 ** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
400 ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
401 ** command name followed by zero or more arguments with no [...] or $
402 ** or {...} or ; to be seen anywhere. Most callback scripts consist
403 ** of just a single procedure name and they meet this requirement.
405 static int safeToUseEvalObjv(Tcl_Interp
*interp
, Tcl_Obj
*pCmd
){
406 /* We could try to do something with Tcl_Parse(). But we will instead
407 ** just do a search for forbidden characters. If any of the forbidden
408 ** characters appear in pCmd, we will report the string as unsafe.
412 z
= Tcl_GetStringFromObj(pCmd
, &n
);
415 if( c
=='$' || c
=='[' || c
==';' ) return 0;
421 ** Find an SqlFunc structure with the given name. Or create a new
422 ** one if an existing one cannot be found. Return a pointer to the
425 static SqlFunc
*findSqlFunc(SqliteDb
*pDb
, const char *zName
){
427 int nName
= strlen30(zName
);
428 pNew
= (SqlFunc
*)Tcl_Alloc( sizeof(*pNew
) + nName
+ 1 );
429 pNew
->zName
= (char*)&pNew
[1];
430 memcpy(pNew
->zName
, zName
, nName
+1);
431 for(p
=pDb
->pFunc
; p
; p
=p
->pNext
){
432 if( sqlite3_stricmp(p
->zName
, pNew
->zName
)==0 ){
433 Tcl_Free((char*)pNew
);
437 pNew
->interp
= pDb
->interp
;
440 pNew
->pNext
= pDb
->pFunc
;
446 ** Free a single SqlPreparedStmt object.
448 static void dbFreeStmt(SqlPreparedStmt
*pStmt
){
450 if( sqlite3_sql(pStmt
->pStmt
)==0 ){
451 Tcl_Free((char *)pStmt
->zSql
);
454 sqlite3_finalize(pStmt
->pStmt
);
455 Tcl_Free((char *)pStmt
);
459 ** Finalize and free a list of prepared statements
461 static void flushStmtCache(SqliteDb
*pDb
){
462 SqlPreparedStmt
*pPreStmt
;
463 SqlPreparedStmt
*pNext
;
465 for(pPreStmt
= pDb
->stmtList
; pPreStmt
; pPreStmt
=pNext
){
466 pNext
= pPreStmt
->pNext
;
467 dbFreeStmt(pPreStmt
);
475 ** TCL calls this procedure when an sqlite3 database command is
478 static void DbDeleteCmd(void *db
){
479 SqliteDb
*pDb
= (SqliteDb
*)db
;
481 closeIncrblobChannels(pDb
);
482 sqlite3_close(pDb
->db
);
484 SqlFunc
*pFunc
= pDb
->pFunc
;
485 pDb
->pFunc
= pFunc
->pNext
;
486 assert( pFunc
->pDb
==pDb
);
487 Tcl_DecrRefCount(pFunc
->pScript
);
488 Tcl_Free((char*)pFunc
);
490 while( pDb
->pCollate
){
491 SqlCollate
*pCollate
= pDb
->pCollate
;
492 pDb
->pCollate
= pCollate
->pNext
;
493 Tcl_Free((char*)pCollate
);
496 Tcl_Free(pDb
->zBusy
);
499 Tcl_Free(pDb
->zTrace
);
502 Tcl_Free(pDb
->zProfile
);
505 Tcl_Free(pDb
->zAuth
);
508 Tcl_Free(pDb
->zNull
);
510 if( pDb
->pUpdateHook
){
511 Tcl_DecrRefCount(pDb
->pUpdateHook
);
513 if( pDb
->pRollbackHook
){
514 Tcl_DecrRefCount(pDb
->pRollbackHook
);
517 Tcl_DecrRefCount(pDb
->pWalHook
);
519 if( pDb
->pCollateNeeded
){
520 Tcl_DecrRefCount(pDb
->pCollateNeeded
);
522 Tcl_Free((char*)pDb
);
526 ** This routine is called when a database file is locked while trying
529 static int DbBusyHandler(void *cd
, int nTries
){
530 SqliteDb
*pDb
= (SqliteDb
*)cd
;
534 sqlite3_snprintf(sizeof(zVal
), zVal
, "%d", nTries
);
535 rc
= Tcl_VarEval(pDb
->interp
, pDb
->zBusy
, " ", zVal
, (char*)0);
536 if( rc
!=TCL_OK
|| atoi(Tcl_GetStringResult(pDb
->interp
)) ){
542 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
544 ** This routine is invoked as the 'progress callback' for the database.
546 static int DbProgressHandler(void *cd
){
547 SqliteDb
*pDb
= (SqliteDb
*)cd
;
550 assert( pDb
->zProgress
);
551 rc
= Tcl_Eval(pDb
->interp
, pDb
->zProgress
);
552 if( rc
!=TCL_OK
|| atoi(Tcl_GetStringResult(pDb
->interp
)) ){
559 #ifndef SQLITE_OMIT_TRACE
561 ** This routine is called by the SQLite trace handler whenever a new
562 ** block of SQL is executed. The TCL script in pDb->zTrace is executed.
564 static void DbTraceHandler(void *cd
, const char *zSql
){
565 SqliteDb
*pDb
= (SqliteDb
*)cd
;
568 Tcl_DStringInit(&str
);
569 Tcl_DStringAppend(&str
, pDb
->zTrace
, -1);
570 Tcl_DStringAppendElement(&str
, zSql
);
571 Tcl_Eval(pDb
->interp
, Tcl_DStringValue(&str
));
572 Tcl_DStringFree(&str
);
573 Tcl_ResetResult(pDb
->interp
);
577 #ifndef SQLITE_OMIT_TRACE
579 ** This routine is called by the SQLite profile handler after a statement
580 ** SQL has executed. The TCL script in pDb->zProfile is evaluated.
582 static void DbProfileHandler(void *cd
, const char *zSql
, sqlite_uint64 tm
){
583 SqliteDb
*pDb
= (SqliteDb
*)cd
;
587 sqlite3_snprintf(sizeof(zTm
)-1, zTm
, "%lld", tm
);
588 Tcl_DStringInit(&str
);
589 Tcl_DStringAppend(&str
, pDb
->zProfile
, -1);
590 Tcl_DStringAppendElement(&str
, zSql
);
591 Tcl_DStringAppendElement(&str
, zTm
);
592 Tcl_Eval(pDb
->interp
, Tcl_DStringValue(&str
));
593 Tcl_DStringFree(&str
);
594 Tcl_ResetResult(pDb
->interp
);
599 ** This routine is called when a transaction is committed. The
600 ** TCL script in pDb->zCommit is executed. If it returns non-zero or
601 ** if it throws an exception, the transaction is rolled back instead
602 ** of being committed.
604 static int DbCommitHandler(void *cd
){
605 SqliteDb
*pDb
= (SqliteDb
*)cd
;
608 rc
= Tcl_Eval(pDb
->interp
, pDb
->zCommit
);
609 if( rc
!=TCL_OK
|| atoi(Tcl_GetStringResult(pDb
->interp
)) ){
615 static void DbRollbackHandler(void *clientData
){
616 SqliteDb
*pDb
= (SqliteDb
*)clientData
;
617 assert(pDb
->pRollbackHook
);
618 if( TCL_OK
!=Tcl_EvalObjEx(pDb
->interp
, pDb
->pRollbackHook
, 0) ){
619 Tcl_BackgroundError(pDb
->interp
);
624 ** This procedure handles wal_hook callbacks.
626 static int DbWalHandler(
634 SqliteDb
*pDb
= (SqliteDb
*)clientData
;
635 Tcl_Interp
*interp
= pDb
->interp
;
636 assert(pDb
->pWalHook
);
638 p
= Tcl_DuplicateObj(pDb
->pWalHook
);
640 Tcl_ListObjAppendElement(interp
, p
, Tcl_NewStringObj(zDb
, -1));
641 Tcl_ListObjAppendElement(interp
, p
, Tcl_NewIntObj(nEntry
));
642 if( TCL_OK
!=Tcl_EvalObjEx(interp
, p
, 0)
643 || TCL_OK
!=Tcl_GetIntFromObj(interp
, Tcl_GetObjResult(interp
), &ret
)
645 Tcl_BackgroundError(interp
);
652 #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
653 static void setTestUnlockNotifyVars(Tcl_Interp
*interp
, int iArg
, int nArg
){
655 sprintf(zBuf
, "%d", iArg
);
656 Tcl_SetVar(interp
, "sqlite_unlock_notify_arg", zBuf
, TCL_GLOBAL_ONLY
);
657 sprintf(zBuf
, "%d", nArg
);
658 Tcl_SetVar(interp
, "sqlite_unlock_notify_argcount", zBuf
, TCL_GLOBAL_ONLY
);
661 # define setTestUnlockNotifyVars(x,y,z)
664 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
665 static void DbUnlockNotify(void **apArg
, int nArg
){
667 for(i
=0; i
<nArg
; i
++){
668 const int flags
= (TCL_EVAL_GLOBAL
|TCL_EVAL_DIRECT
);
669 SqliteDb
*pDb
= (SqliteDb
*)apArg
[i
];
670 setTestUnlockNotifyVars(pDb
->interp
, i
, nArg
);
671 assert( pDb
->pUnlockNotify
);
672 Tcl_EvalObjEx(pDb
->interp
, pDb
->pUnlockNotify
, flags
);
673 Tcl_DecrRefCount(pDb
->pUnlockNotify
);
674 pDb
->pUnlockNotify
= 0;
679 static void DbUpdateHandler(
686 SqliteDb
*pDb
= (SqliteDb
*)p
;
689 assert( pDb
->pUpdateHook
);
690 assert( op
==SQLITE_INSERT
|| op
==SQLITE_UPDATE
|| op
==SQLITE_DELETE
);
692 pCmd
= Tcl_DuplicateObj(pDb
->pUpdateHook
);
693 Tcl_IncrRefCount(pCmd
);
694 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(
695 ( (op
==SQLITE_INSERT
)?"INSERT":(op
==SQLITE_UPDATE
)?"UPDATE":"DELETE"), -1));
696 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(zDb
, -1));
697 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewStringObj(zTbl
, -1));
698 Tcl_ListObjAppendElement(0, pCmd
, Tcl_NewWideIntObj(rowid
));
699 Tcl_EvalObjEx(pDb
->interp
, pCmd
, TCL_EVAL_DIRECT
);
700 Tcl_DecrRefCount(pCmd
);
703 static void tclCollateNeeded(
709 SqliteDb
*pDb
= (SqliteDb
*)pCtx
;
710 Tcl_Obj
*pScript
= Tcl_DuplicateObj(pDb
->pCollateNeeded
);
711 Tcl_IncrRefCount(pScript
);
712 Tcl_ListObjAppendElement(0, pScript
, Tcl_NewStringObj(zName
, -1));
713 Tcl_EvalObjEx(pDb
->interp
, pScript
, 0);
714 Tcl_DecrRefCount(pScript
);
718 ** This routine is called to evaluate an SQL collation function implemented
721 static int tclSqlCollate(
728 SqlCollate
*p
= (SqlCollate
*)pCtx
;
731 pCmd
= Tcl_NewStringObj(p
->zScript
, -1);
732 Tcl_IncrRefCount(pCmd
);
733 Tcl_ListObjAppendElement(p
->interp
, pCmd
, Tcl_NewStringObj(zA
, nA
));
734 Tcl_ListObjAppendElement(p
->interp
, pCmd
, Tcl_NewStringObj(zB
, nB
));
735 Tcl_EvalObjEx(p
->interp
, pCmd
, TCL_EVAL_DIRECT
);
736 Tcl_DecrRefCount(pCmd
);
737 return (atoi(Tcl_GetStringResult(p
->interp
)));
741 ** This routine is called to evaluate an SQL function implemented
744 static void tclSqlFunc(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
){
745 SqlFunc
*p
= sqlite3_user_data(context
);
751 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
752 ** script object directly. This allows the TCL compiler to generate
753 ** bytecode for the command on the first invocation and thus make
754 ** subsequent invocations much faster. */
756 Tcl_IncrRefCount(pCmd
);
757 rc
= Tcl_EvalObjEx(p
->interp
, pCmd
, 0);
758 Tcl_DecrRefCount(pCmd
);
760 /* If there are arguments to the function, make a shallow copy of the
761 ** script object, lappend the arguments, then evaluate the copy.
763 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
764 ** The new Tcl_Obj contains pointers to the original list elements.
765 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
766 ** of the list to tclCmdNameType, that alternate representation will
767 ** be preserved and reused on the next invocation.
771 if( Tcl_ListObjGetElements(p
->interp
, p
->pScript
, &nArg
, &aArg
) ){
772 sqlite3_result_error(context
, Tcl_GetStringResult(p
->interp
), -1);
775 pCmd
= Tcl_NewListObj(nArg
, aArg
);
776 Tcl_IncrRefCount(pCmd
);
777 for(i
=0; i
<argc
; i
++){
778 sqlite3_value
*pIn
= argv
[i
];
781 /* Set pVal to contain the i'th column of this row. */
782 switch( sqlite3_value_type(pIn
) ){
784 int bytes
= sqlite3_value_bytes(pIn
);
785 pVal
= Tcl_NewByteArrayObj(sqlite3_value_blob(pIn
), bytes
);
788 case SQLITE_INTEGER
: {
789 sqlite_int64 v
= sqlite3_value_int64(pIn
);
790 if( v
>=-2147483647 && v
<=2147483647 ){
791 pVal
= Tcl_NewIntObj((int)v
);
793 pVal
= Tcl_NewWideIntObj(v
);
798 double r
= sqlite3_value_double(pIn
);
799 pVal
= Tcl_NewDoubleObj(r
);
803 pVal
= Tcl_NewStringObj(p
->pDb
->zNull
, -1);
807 int bytes
= sqlite3_value_bytes(pIn
);
808 pVal
= Tcl_NewStringObj((char *)sqlite3_value_text(pIn
), bytes
);
812 rc
= Tcl_ListObjAppendElement(p
->interp
, pCmd
, pVal
);
814 Tcl_DecrRefCount(pCmd
);
815 sqlite3_result_error(context
, Tcl_GetStringResult(p
->interp
), -1);
819 if( !p
->useEvalObjv
){
820 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
821 ** is a list without a string representation. To prevent this from
822 ** happening, make sure pCmd has a valid string representation */
825 rc
= Tcl_EvalObjEx(p
->interp
, pCmd
, TCL_EVAL_DIRECT
);
826 Tcl_DecrRefCount(pCmd
);
829 if( rc
&& rc
!=TCL_RETURN
){
830 sqlite3_result_error(context
, Tcl_GetStringResult(p
->interp
), -1);
832 Tcl_Obj
*pVar
= Tcl_GetObjResult(p
->interp
);
835 const char *zType
= (pVar
->typePtr
? pVar
->typePtr
->name
: "");
837 if( c
=='b' && strcmp(zType
,"bytearray")==0 && pVar
->bytes
==0 ){
838 /* Only return a BLOB type if the Tcl variable is a bytearray and
839 ** has no string representation. */
840 data
= Tcl_GetByteArrayFromObj(pVar
, &n
);
841 sqlite3_result_blob(context
, data
, n
, SQLITE_TRANSIENT
);
842 }else if( c
=='b' && strcmp(zType
,"boolean")==0 ){
843 Tcl_GetIntFromObj(0, pVar
, &n
);
844 sqlite3_result_int(context
, n
);
845 }else if( c
=='d' && strcmp(zType
,"double")==0 ){
847 Tcl_GetDoubleFromObj(0, pVar
, &r
);
848 sqlite3_result_double(context
, r
);
849 }else if( (c
=='w' && strcmp(zType
,"wideInt")==0) ||
850 (c
=='i' && strcmp(zType
,"int")==0) ){
852 Tcl_GetWideIntFromObj(0, pVar
, &v
);
853 sqlite3_result_int64(context
, v
);
855 data
= (unsigned char *)Tcl_GetStringFromObj(pVar
, &n
);
856 sqlite3_result_text(context
, (char *)data
, n
, SQLITE_TRANSIENT
);
861 #ifndef SQLITE_OMIT_AUTHORIZATION
863 ** This is the authentication function. It appends the authentication
864 ** type code and the two arguments to zCmd[] then invokes the result
865 ** on the interpreter. The reply is examined to determine if the
866 ** authentication fails or succeeds.
868 static int auth_callback(
875 #ifdef SQLITE_USER_AUTHENTICATION
883 SqliteDb
*pDb
= (SqliteDb
*)pArg
;
884 if( pDb
->disableAuth
) return SQLITE_OK
;
887 case SQLITE_COPY
: zCode
="SQLITE_COPY"; break;
888 case SQLITE_CREATE_INDEX
: zCode
="SQLITE_CREATE_INDEX"; break;
889 case SQLITE_CREATE_TABLE
: zCode
="SQLITE_CREATE_TABLE"; break;
890 case SQLITE_CREATE_TEMP_INDEX
: zCode
="SQLITE_CREATE_TEMP_INDEX"; break;
891 case SQLITE_CREATE_TEMP_TABLE
: zCode
="SQLITE_CREATE_TEMP_TABLE"; break;
892 case SQLITE_CREATE_TEMP_TRIGGER
: zCode
="SQLITE_CREATE_TEMP_TRIGGER"; break;
893 case SQLITE_CREATE_TEMP_VIEW
: zCode
="SQLITE_CREATE_TEMP_VIEW"; break;
894 case SQLITE_CREATE_TRIGGER
: zCode
="SQLITE_CREATE_TRIGGER"; break;
895 case SQLITE_CREATE_VIEW
: zCode
="SQLITE_CREATE_VIEW"; break;
896 case SQLITE_DELETE
: zCode
="SQLITE_DELETE"; break;
897 case SQLITE_DROP_INDEX
: zCode
="SQLITE_DROP_INDEX"; break;
898 case SQLITE_DROP_TABLE
: zCode
="SQLITE_DROP_TABLE"; break;
899 case SQLITE_DROP_TEMP_INDEX
: zCode
="SQLITE_DROP_TEMP_INDEX"; break;
900 case SQLITE_DROP_TEMP_TABLE
: zCode
="SQLITE_DROP_TEMP_TABLE"; break;
901 case SQLITE_DROP_TEMP_TRIGGER
: zCode
="SQLITE_DROP_TEMP_TRIGGER"; break;
902 case SQLITE_DROP_TEMP_VIEW
: zCode
="SQLITE_DROP_TEMP_VIEW"; break;
903 case SQLITE_DROP_TRIGGER
: zCode
="SQLITE_DROP_TRIGGER"; break;
904 case SQLITE_DROP_VIEW
: zCode
="SQLITE_DROP_VIEW"; break;
905 case SQLITE_INSERT
: zCode
="SQLITE_INSERT"; break;
906 case SQLITE_PRAGMA
: zCode
="SQLITE_PRAGMA"; break;
907 case SQLITE_READ
: zCode
="SQLITE_READ"; break;
908 case SQLITE_SELECT
: zCode
="SQLITE_SELECT"; break;
909 case SQLITE_TRANSACTION
: zCode
="SQLITE_TRANSACTION"; break;
910 case SQLITE_UPDATE
: zCode
="SQLITE_UPDATE"; break;
911 case SQLITE_ATTACH
: zCode
="SQLITE_ATTACH"; break;
912 case SQLITE_DETACH
: zCode
="SQLITE_DETACH"; break;
913 case SQLITE_ALTER_TABLE
: zCode
="SQLITE_ALTER_TABLE"; break;
914 case SQLITE_REINDEX
: zCode
="SQLITE_REINDEX"; break;
915 case SQLITE_ANALYZE
: zCode
="SQLITE_ANALYZE"; break;
916 case SQLITE_CREATE_VTABLE
: zCode
="SQLITE_CREATE_VTABLE"; break;
917 case SQLITE_DROP_VTABLE
: zCode
="SQLITE_DROP_VTABLE"; break;
918 case SQLITE_FUNCTION
: zCode
="SQLITE_FUNCTION"; break;
919 case SQLITE_SAVEPOINT
: zCode
="SQLITE_SAVEPOINT"; break;
920 case SQLITE_RECURSIVE
: zCode
="SQLITE_RECURSIVE"; break;
921 default : zCode
="????"; break;
923 Tcl_DStringInit(&str
);
924 Tcl_DStringAppend(&str
, pDb
->zAuth
, -1);
925 Tcl_DStringAppendElement(&str
, zCode
);
926 Tcl_DStringAppendElement(&str
, zArg1
? zArg1
: "");
927 Tcl_DStringAppendElement(&str
, zArg2
? zArg2
: "");
928 Tcl_DStringAppendElement(&str
, zArg3
? zArg3
: "");
929 Tcl_DStringAppendElement(&str
, zArg4
? zArg4
: "");
930 #ifdef SQLITE_USER_AUTHENTICATION
931 Tcl_DStringAppendElement(&str
, zArg5
? zArg5
: "");
933 rc
= Tcl_GlobalEval(pDb
->interp
, Tcl_DStringValue(&str
));
934 Tcl_DStringFree(&str
);
935 zReply
= rc
==TCL_OK
? Tcl_GetStringResult(pDb
->interp
) : "SQLITE_DENY";
936 if( strcmp(zReply
,"SQLITE_OK")==0 ){
938 }else if( strcmp(zReply
,"SQLITE_DENY")==0 ){
940 }else if( strcmp(zReply
,"SQLITE_IGNORE")==0 ){
947 #endif /* SQLITE_OMIT_AUTHORIZATION */
950 ** This routine reads a line of text from FILE in, stores
951 ** the text in memory obtained from malloc() and returns a pointer
952 ** to the text. NULL is returned at end of file, or if malloc()
955 ** The interface is like "readline" but no command-line editing
958 ** copied from shell.c from '.import' command
960 static char *local_getline(char *zPrompt
, FILE *in
){
966 zLine
= malloc( nLine
);
967 if( zLine
==0 ) return 0;
971 nLine
= nLine
*2 + 100;
972 zLine
= realloc(zLine
, nLine
);
973 if( zLine
==0 ) return 0;
975 if( fgets(&zLine
[n
], nLine
- n
, in
)==0 ){
983 while( zLine
[n
] ){ n
++; }
984 if( n
>0 && zLine
[n
-1]=='\n' ){
990 zLine
= realloc( zLine
, n
+1 );
996 ** This function is part of the implementation of the command:
998 ** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1000 ** It is invoked after evaluating the script SCRIPT to commit or rollback
1001 ** the transaction or savepoint opened by the [transaction] command.
1003 static int DbTransPostCmd(
1004 ClientData data
[], /* data[0] is the Sqlite3Db* for $db */
1005 Tcl_Interp
*interp
, /* Tcl interpreter */
1006 int result
/* Result of evaluating SCRIPT */
1008 static const char *const azEnd
[] = {
1009 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1010 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1011 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1012 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1014 SqliteDb
*pDb
= (SqliteDb
*)data
[0];
1018 pDb
->nTransaction
--;
1019 zEnd
= azEnd
[(rc
==TCL_ERROR
)*2 + (pDb
->nTransaction
==0)];
1022 if( sqlite3_exec(pDb
->db
, zEnd
, 0, 0, 0) ){
1023 /* This is a tricky scenario to handle. The most likely cause of an
1024 ** error is that the exec() above was an attempt to commit the
1025 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1026 ** that an IO-error has occurred. In either case, throw a Tcl exception
1027 ** and try to rollback the transaction.
1029 ** But it could also be that the user executed one or more BEGIN,
1030 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1031 ** this method's logic. Not clear how this would be best handled.
1033 if( rc
!=TCL_ERROR
){
1034 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
1037 sqlite3_exec(pDb
->db
, "ROLLBACK", 0, 0, 0);
1045 ** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1046 ** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1047 ** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1048 ** on whether or not the [db_use_legacy_prepare] command has been used to
1049 ** configure the connection.
1051 static int dbPrepare(
1052 SqliteDb
*pDb
, /* Database object */
1053 const char *zSql
, /* SQL to compile */
1054 sqlite3_stmt
**ppStmt
, /* OUT: Prepared statement */
1055 const char **pzOut
/* OUT: Pointer to next SQL statement */
1058 if( pDb
->bLegacyPrepare
){
1059 return sqlite3_prepare(pDb
->db
, zSql
, -1, ppStmt
, pzOut
);
1062 return sqlite3_prepare_v2(pDb
->db
, zSql
, -1, ppStmt
, pzOut
);
1066 ** Search the cache for a prepared-statement object that implements the
1067 ** first SQL statement in the buffer pointed to by parameter zIn. If
1068 ** no such prepared-statement can be found, allocate and prepare a new
1069 ** one. In either case, bind the current values of the relevant Tcl
1070 ** variables to any $var, :var or @var variables in the statement. Before
1071 ** returning, set *ppPreStmt to point to the prepared-statement object.
1073 ** Output parameter *pzOut is set to point to the next SQL statement in
1074 ** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1077 ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1078 ** and an error message loaded into interpreter pDb->interp.
1080 static int dbPrepareAndBind(
1081 SqliteDb
*pDb
, /* Database object */
1082 char const *zIn
, /* SQL to compile */
1083 char const **pzOut
, /* OUT: Pointer to next SQL statement */
1084 SqlPreparedStmt
**ppPreStmt
/* OUT: Object used to cache statement */
1086 const char *zSql
= zIn
; /* Pointer to first SQL statement in zIn */
1087 sqlite3_stmt
*pStmt
; /* Prepared statement object */
1088 SqlPreparedStmt
*pPreStmt
; /* Pointer to cached statement */
1089 int nSql
; /* Length of zSql in bytes */
1090 int nVar
; /* Number of variables in statement */
1091 int iParm
= 0; /* Next free entry in apParm */
1094 Tcl_Interp
*interp
= pDb
->interp
;
1098 /* Trim spaces from the start of zSql and calculate the remaining length. */
1099 while( (c
= zSql
[0])==' ' || c
=='\t' || c
=='\r' || c
=='\n' ){ zSql
++; }
1100 nSql
= strlen30(zSql
);
1102 for(pPreStmt
= pDb
->stmtList
; pPreStmt
; pPreStmt
=pPreStmt
->pNext
){
1103 int n
= pPreStmt
->nSql
;
1105 && memcmp(pPreStmt
->zSql
, zSql
, n
)==0
1106 && (zSql
[n
]==0 || zSql
[n
-1]==';')
1108 pStmt
= pPreStmt
->pStmt
;
1109 *pzOut
= &zSql
[pPreStmt
->nSql
];
1111 /* When a prepared statement is found, unlink it from the
1112 ** cache list. It will later be added back to the beginning
1113 ** of the cache list in order to implement LRU replacement.
1115 if( pPreStmt
->pPrev
){
1116 pPreStmt
->pPrev
->pNext
= pPreStmt
->pNext
;
1118 pDb
->stmtList
= pPreStmt
->pNext
;
1120 if( pPreStmt
->pNext
){
1121 pPreStmt
->pNext
->pPrev
= pPreStmt
->pPrev
;
1123 pDb
->stmtLast
= pPreStmt
->pPrev
;
1126 nVar
= sqlite3_bind_parameter_count(pStmt
);
1131 /* If no prepared statement was found. Compile the SQL text. Also allocate
1132 ** a new SqlPreparedStmt structure. */
1136 if( SQLITE_OK
!=dbPrepare(pDb
, zSql
, &pStmt
, pzOut
) ){
1137 Tcl_SetObjResult(interp
, Tcl_NewStringObj(sqlite3_errmsg(pDb
->db
), -1));
1141 if( SQLITE_OK
!=sqlite3_errcode(pDb
->db
) ){
1142 /* A compile-time error in the statement. */
1143 Tcl_SetObjResult(interp
, Tcl_NewStringObj(sqlite3_errmsg(pDb
->db
), -1));
1146 /* The statement was a no-op. Continue to the next statement
1147 ** in the SQL string.
1153 assert( pPreStmt
==0 );
1154 nVar
= sqlite3_bind_parameter_count(pStmt
);
1155 nByte
= sizeof(SqlPreparedStmt
) + nVar
*sizeof(Tcl_Obj
*);
1156 pPreStmt
= (SqlPreparedStmt
*)Tcl_Alloc(nByte
);
1157 memset(pPreStmt
, 0, nByte
);
1159 pPreStmt
->pStmt
= pStmt
;
1160 pPreStmt
->nSql
= (int)(*pzOut
- zSql
);
1161 pPreStmt
->zSql
= sqlite3_sql(pStmt
);
1162 pPreStmt
->apParm
= (Tcl_Obj
**)&pPreStmt
[1];
1164 if( pPreStmt
->zSql
==0 ){
1165 char *zCopy
= Tcl_Alloc(pPreStmt
->nSql
+ 1);
1166 memcpy(zCopy
, zSql
, pPreStmt
->nSql
);
1167 zCopy
[pPreStmt
->nSql
] = '\0';
1168 pPreStmt
->zSql
= zCopy
;
1173 assert( strlen30(pPreStmt
->zSql
)==pPreStmt
->nSql
);
1174 assert( 0==memcmp(pPreStmt
->zSql
, zSql
, pPreStmt
->nSql
) );
1176 /* Bind values to parameters that begin with $ or : */
1177 for(i
=1; i
<=nVar
; i
++){
1178 const char *zVar
= sqlite3_bind_parameter_name(pStmt
, i
);
1179 if( zVar
!=0 && (zVar
[0]=='$' || zVar
[0]==':' || zVar
[0]=='@') ){
1180 Tcl_Obj
*pVar
= Tcl_GetVar2Ex(interp
, &zVar
[1], 0, 0);
1184 const char *zType
= (pVar
->typePtr
? pVar
->typePtr
->name
: "");
1187 (c
=='b' && strcmp(zType
,"bytearray")==0 && pVar
->bytes
==0) ){
1188 /* Load a BLOB type if the Tcl variable is a bytearray and
1189 ** it has no string representation or the host
1190 ** parameter name begins with "@". */
1191 data
= Tcl_GetByteArrayFromObj(pVar
, &n
);
1192 sqlite3_bind_blob(pStmt
, i
, data
, n
, SQLITE_STATIC
);
1193 Tcl_IncrRefCount(pVar
);
1194 pPreStmt
->apParm
[iParm
++] = pVar
;
1195 }else if( c
=='b' && strcmp(zType
,"boolean")==0 ){
1196 Tcl_GetIntFromObj(interp
, pVar
, &n
);
1197 sqlite3_bind_int(pStmt
, i
, n
);
1198 }else if( c
=='d' && strcmp(zType
,"double")==0 ){
1200 Tcl_GetDoubleFromObj(interp
, pVar
, &r
);
1201 sqlite3_bind_double(pStmt
, i
, r
);
1202 }else if( (c
=='w' && strcmp(zType
,"wideInt")==0) ||
1203 (c
=='i' && strcmp(zType
,"int")==0) ){
1205 Tcl_GetWideIntFromObj(interp
, pVar
, &v
);
1206 sqlite3_bind_int64(pStmt
, i
, v
);
1208 data
= (unsigned char *)Tcl_GetStringFromObj(pVar
, &n
);
1209 sqlite3_bind_text(pStmt
, i
, (char *)data
, n
, SQLITE_STATIC
);
1210 Tcl_IncrRefCount(pVar
);
1211 pPreStmt
->apParm
[iParm
++] = pVar
;
1214 sqlite3_bind_null(pStmt
, i
);
1218 pPreStmt
->nParm
= iParm
;
1219 *ppPreStmt
= pPreStmt
;
1225 ** Release a statement reference obtained by calling dbPrepareAndBind().
1226 ** There should be exactly one call to this function for each call to
1227 ** dbPrepareAndBind().
1229 ** If the discard parameter is non-zero, then the statement is deleted
1230 ** immediately. Otherwise it is added to the LRU list and may be returned
1231 ** by a subsequent call to dbPrepareAndBind().
1233 static void dbReleaseStmt(
1234 SqliteDb
*pDb
, /* Database handle */
1235 SqlPreparedStmt
*pPreStmt
, /* Prepared statement handle to release */
1236 int discard
/* True to delete (not cache) the pPreStmt */
1240 /* Free the bound string and blob parameters */
1241 for(i
=0; i
<pPreStmt
->nParm
; i
++){
1242 Tcl_DecrRefCount(pPreStmt
->apParm
[i
]);
1244 pPreStmt
->nParm
= 0;
1246 if( pDb
->maxStmt
<=0 || discard
){
1247 /* If the cache is turned off, deallocated the statement */
1248 dbFreeStmt(pPreStmt
);
1250 /* Add the prepared statement to the beginning of the cache list. */
1251 pPreStmt
->pNext
= pDb
->stmtList
;
1252 pPreStmt
->pPrev
= 0;
1253 if( pDb
->stmtList
){
1254 pDb
->stmtList
->pPrev
= pPreStmt
;
1256 pDb
->stmtList
= pPreStmt
;
1257 if( pDb
->stmtLast
==0 ){
1258 assert( pDb
->nStmt
==0 );
1259 pDb
->stmtLast
= pPreStmt
;
1261 assert( pDb
->nStmt
>0 );
1265 /* If we have too many statement in cache, remove the surplus from
1266 ** the end of the cache list. */
1267 while( pDb
->nStmt
>pDb
->maxStmt
){
1268 SqlPreparedStmt
*pLast
= pDb
->stmtLast
;
1269 pDb
->stmtLast
= pLast
->pPrev
;
1270 pDb
->stmtLast
->pNext
= 0;
1278 ** Structure used with dbEvalXXX() functions:
1284 ** dbEvalColumnValue()
1286 typedef struct DbEvalContext DbEvalContext
;
1287 struct DbEvalContext
{
1288 SqliteDb
*pDb
; /* Database handle */
1289 Tcl_Obj
*pSql
; /* Object holding string zSql */
1290 const char *zSql
; /* Remaining SQL to execute */
1291 SqlPreparedStmt
*pPreStmt
; /* Current statement */
1292 int nCol
; /* Number of columns returned by pStmt */
1293 Tcl_Obj
*pArray
; /* Name of array variable */
1294 Tcl_Obj
**apColName
; /* Array of column names */
1298 ** Release any cache of column names currently held as part of
1299 ** the DbEvalContext structure passed as the first argument.
1301 static void dbReleaseColumnNames(DbEvalContext
*p
){
1304 for(i
=0; i
<p
->nCol
; i
++){
1305 Tcl_DecrRefCount(p
->apColName
[i
]);
1307 Tcl_Free((char *)p
->apColName
);
1314 ** Initialize a DbEvalContext structure.
1316 ** If pArray is not NULL, then it contains the name of a Tcl array
1317 ** variable. The "*" member of this array is set to a list containing
1318 ** the names of the columns returned by the statement as part of each
1319 ** call to dbEvalStep(), in order from left to right. e.g. if the names
1320 ** of the returned columns are a, b and c, it does the equivalent of the
1323 ** set ${pArray}(*) {a b c}
1325 static void dbEvalInit(
1326 DbEvalContext
*p
, /* Pointer to structure to initialize */
1327 SqliteDb
*pDb
, /* Database handle */
1328 Tcl_Obj
*pSql
, /* Object containing SQL script */
1329 Tcl_Obj
*pArray
/* Name of Tcl array to set (*) element of */
1331 memset(p
, 0, sizeof(DbEvalContext
));
1333 p
->zSql
= Tcl_GetString(pSql
);
1335 Tcl_IncrRefCount(pSql
);
1338 Tcl_IncrRefCount(pArray
);
1343 ** Obtain information about the row that the DbEvalContext passed as the
1344 ** first argument currently points to.
1346 static void dbEvalRowInfo(
1347 DbEvalContext
*p
, /* Evaluation context */
1348 int *pnCol
, /* OUT: Number of column names */
1349 Tcl_Obj
***papColName
/* OUT: Array of column names */
1351 /* Compute column names */
1352 if( 0==p
->apColName
){
1353 sqlite3_stmt
*pStmt
= p
->pPreStmt
->pStmt
;
1354 int i
; /* Iterator variable */
1355 int nCol
; /* Number of columns returned by pStmt */
1356 Tcl_Obj
**apColName
= 0; /* Array of column names */
1358 p
->nCol
= nCol
= sqlite3_column_count(pStmt
);
1359 if( nCol
>0 && (papColName
|| p
->pArray
) ){
1360 apColName
= (Tcl_Obj
**)Tcl_Alloc( sizeof(Tcl_Obj
*)*nCol
);
1361 for(i
=0; i
<nCol
; i
++){
1362 apColName
[i
] = Tcl_NewStringObj(sqlite3_column_name(pStmt
,i
), -1);
1363 Tcl_IncrRefCount(apColName
[i
]);
1365 p
->apColName
= apColName
;
1368 /* If results are being stored in an array variable, then create
1369 ** the array(*) entry for that array
1372 Tcl_Interp
*interp
= p
->pDb
->interp
;
1373 Tcl_Obj
*pColList
= Tcl_NewObj();
1374 Tcl_Obj
*pStar
= Tcl_NewStringObj("*", -1);
1376 for(i
=0; i
<nCol
; i
++){
1377 Tcl_ListObjAppendElement(interp
, pColList
, apColName
[i
]);
1379 Tcl_IncrRefCount(pStar
);
1380 Tcl_ObjSetVar2(interp
, p
->pArray
, pStar
, pColList
, 0);
1381 Tcl_DecrRefCount(pStar
);
1386 *papColName
= p
->apColName
;
1394 ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1395 ** returned, then an error message is stored in the interpreter before
1398 ** A return value of TCL_OK means there is a row of data available. The
1399 ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1400 ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1401 ** is returned, then the SQL script has finished executing and there are
1402 ** no further rows available. This is similar to SQLITE_DONE.
1404 static int dbEvalStep(DbEvalContext
*p
){
1405 const char *zPrevSql
= 0; /* Previous value of p->zSql */
1407 while( p
->zSql
[0] || p
->pPreStmt
){
1409 if( p
->pPreStmt
==0 ){
1410 zPrevSql
= (p
->zSql
==zPrevSql
? 0 : p
->zSql
);
1411 rc
= dbPrepareAndBind(p
->pDb
, p
->zSql
, &p
->zSql
, &p
->pPreStmt
);
1412 if( rc
!=TCL_OK
) return rc
;
1415 SqliteDb
*pDb
= p
->pDb
;
1416 SqlPreparedStmt
*pPreStmt
= p
->pPreStmt
;
1417 sqlite3_stmt
*pStmt
= pPreStmt
->pStmt
;
1419 rcs
= sqlite3_step(pStmt
);
1420 if( rcs
==SQLITE_ROW
){
1424 dbEvalRowInfo(p
, 0, 0);
1426 rcs
= sqlite3_reset(pStmt
);
1428 pDb
->nStep
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_FULLSCAN_STEP
,1);
1429 pDb
->nSort
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_SORT
,1);
1430 pDb
->nIndex
= sqlite3_stmt_status(pStmt
,SQLITE_STMTSTATUS_AUTOINDEX
,1);
1431 dbReleaseColumnNames(p
);
1434 if( rcs
!=SQLITE_OK
){
1435 /* If a run-time error occurs, report the error and stop reading
1437 dbReleaseStmt(pDb
, pPreStmt
, 1);
1439 if( p
->pDb
->bLegacyPrepare
&& rcs
==SQLITE_SCHEMA
&& zPrevSql
){
1440 /* If the runtime error was an SQLITE_SCHEMA, and the database
1441 ** handle is configured to use the legacy sqlite3_prepare()
1442 ** interface, retry prepare()/step() on the same SQL statement.
1443 ** This only happens once. If there is a second SQLITE_SCHEMA
1444 ** error, the error will be returned to the caller. */
1449 Tcl_SetObjResult(pDb
->interp
,
1450 Tcl_NewStringObj(sqlite3_errmsg(pDb
->db
), -1));
1453 dbReleaseStmt(pDb
, pPreStmt
, 0);
1463 ** Free all resources currently held by the DbEvalContext structure passed
1464 ** as the first argument. There should be exactly one call to this function
1465 ** for each call to dbEvalInit().
1467 static void dbEvalFinalize(DbEvalContext
*p
){
1469 sqlite3_reset(p
->pPreStmt
->pStmt
);
1470 dbReleaseStmt(p
->pDb
, p
->pPreStmt
, 0);
1474 Tcl_DecrRefCount(p
->pArray
);
1477 Tcl_DecrRefCount(p
->pSql
);
1478 dbReleaseColumnNames(p
);
1482 ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1483 ** the value for the iCol'th column of the row currently pointed to by
1484 ** the DbEvalContext structure passed as the first argument.
1486 static Tcl_Obj
*dbEvalColumnValue(DbEvalContext
*p
, int iCol
){
1487 sqlite3_stmt
*pStmt
= p
->pPreStmt
->pStmt
;
1488 switch( sqlite3_column_type(pStmt
, iCol
) ){
1490 int bytes
= sqlite3_column_bytes(pStmt
, iCol
);
1491 const char *zBlob
= sqlite3_column_blob(pStmt
, iCol
);
1492 if( !zBlob
) bytes
= 0;
1493 return Tcl_NewByteArrayObj((u8
*)zBlob
, bytes
);
1495 case SQLITE_INTEGER
: {
1496 sqlite_int64 v
= sqlite3_column_int64(pStmt
, iCol
);
1497 if( v
>=-2147483647 && v
<=2147483647 ){
1498 return Tcl_NewIntObj((int)v
);
1500 return Tcl_NewWideIntObj(v
);
1503 case SQLITE_FLOAT
: {
1504 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt
, iCol
));
1507 return Tcl_NewStringObj(p
->pDb
->zNull
, -1);
1511 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt
, iCol
), -1);
1515 ** If using Tcl version 8.6 or greater, use the NR functions to avoid
1516 ** recursive evalution of scripts by the [db eval] and [db trans]
1517 ** commands. Even if the headers used while compiling the extension
1518 ** are 8.6 or newer, the code still tests the Tcl version at runtime.
1519 ** This allows stubs-enabled builds to be used with older Tcl libraries.
1521 #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
1522 # define SQLITE_TCL_NRE 1
1523 static int DbUseNre(void){
1525 Tcl_GetVersion(&major
, &minor
, 0, 0);
1526 return( (major
==8 && minor
>=6) || major
>8 );
1530 ** Compiling using headers earlier than 8.6. In this case NR cannot be
1531 ** used, so DbUseNre() to always return zero. Add #defines for the other
1532 ** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1533 ** even though the only invocations of them are within conditional blocks
1536 ** if( DbUseNre() ) { ... }
1538 # define SQLITE_TCL_NRE 0
1539 # define DbUseNre() 0
1540 # define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
1541 # define Tcl_NREvalObj(a,b,c) 0
1542 # define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
1546 ** This function is part of the implementation of the command:
1548 ** $db eval SQL ?ARRAYNAME? SCRIPT
1550 static int DbEvalNextCmd(
1551 ClientData data
[], /* data[0] is the (DbEvalContext*) */
1552 Tcl_Interp
*interp
, /* Tcl interpreter */
1553 int result
/* Result so far */
1555 int rc
= result
; /* Return code */
1557 /* The first element of the data[] array is a pointer to a DbEvalContext
1558 ** structure allocated using Tcl_Alloc(). The second element of data[]
1559 ** is a pointer to a Tcl_Obj containing the script to run for each row
1560 ** returned by the queries encapsulated in data[0]. */
1561 DbEvalContext
*p
= (DbEvalContext
*)data
[0];
1562 Tcl_Obj
*pScript
= (Tcl_Obj
*)data
[1];
1563 Tcl_Obj
*pArray
= p
->pArray
;
1565 while( (rc
==TCL_OK
|| rc
==TCL_CONTINUE
) && TCL_OK
==(rc
= dbEvalStep(p
)) ){
1568 Tcl_Obj
**apColName
;
1569 dbEvalRowInfo(p
, &nCol
, &apColName
);
1570 for(i
=0; i
<nCol
; i
++){
1571 Tcl_Obj
*pVal
= dbEvalColumnValue(p
, i
);
1573 Tcl_ObjSetVar2(interp
, apColName
[i
], 0, pVal
, 0);
1575 Tcl_ObjSetVar2(interp
, pArray
, apColName
[i
], pVal
, 0);
1579 /* The required interpreter variables are now populated with the data
1580 ** from the current row. If using NRE, schedule callbacks to evaluate
1581 ** script pScript, then to invoke this function again to fetch the next
1582 ** row (or clean up if there is no next row or the script throws an
1583 ** exception). After scheduling the callbacks, return control to the
1586 ** If not using NRE, evaluate pScript directly and continue with the
1587 ** next iteration of this while(...) loop. */
1589 Tcl_NRAddCallback(interp
, DbEvalNextCmd
, (void*)p
, (void*)pScript
, 0, 0);
1590 return Tcl_NREvalObj(interp
, pScript
, 0);
1592 rc
= Tcl_EvalObjEx(interp
, pScript
, 0);
1596 Tcl_DecrRefCount(pScript
);
1598 Tcl_Free((char *)p
);
1600 if( rc
==TCL_OK
|| rc
==TCL_BREAK
){
1601 Tcl_ResetResult(interp
);
1608 ** The "sqlite" command below creates a new Tcl command for each
1609 ** connection it opens to an SQLite database. This routine is invoked
1610 ** whenever one of those connection-specific commands is executed
1611 ** in Tcl. For example, if you run Tcl code like this:
1613 ** sqlite3 db1 "my_database"
1616 ** The first command opens a connection to the "my_database" database
1617 ** and calls that connection "db1". The second command causes this
1618 ** subroutine to be invoked.
1620 static int DbObjCmd(void *cd
, Tcl_Interp
*interp
, int objc
,Tcl_Obj
*const*objv
){
1621 SqliteDb
*pDb
= (SqliteDb
*)cd
;
1624 static const char *DB_strs
[] = {
1625 "authorizer", "backup", "busy",
1626 "cache", "changes", "close",
1627 "collate", "collation_needed", "commit_hook",
1628 "complete", "copy", "enable_load_extension",
1629 "errorcode", "eval", "exists",
1630 "function", "incrblob", "interrupt",
1631 "last_insert_rowid", "nullvalue", "onecolumn",
1632 "profile", "progress", "rekey",
1633 "restore", "rollback_hook", "status",
1634 "timeout", "total_changes", "trace",
1635 "transaction", "unlock_notify", "update_hook",
1636 "version", "wal_hook", 0
1639 DB_AUTHORIZER
, DB_BACKUP
, DB_BUSY
,
1640 DB_CACHE
, DB_CHANGES
, DB_CLOSE
,
1641 DB_COLLATE
, DB_COLLATION_NEEDED
, DB_COMMIT_HOOK
,
1642 DB_COMPLETE
, DB_COPY
, DB_ENABLE_LOAD_EXTENSION
,
1643 DB_ERRORCODE
, DB_EVAL
, DB_EXISTS
,
1644 DB_FUNCTION
, DB_INCRBLOB
, DB_INTERRUPT
,
1645 DB_LAST_INSERT_ROWID
, DB_NULLVALUE
, DB_ONECOLUMN
,
1646 DB_PROFILE
, DB_PROGRESS
, DB_REKEY
,
1647 DB_RESTORE
, DB_ROLLBACK_HOOK
, DB_STATUS
,
1648 DB_TIMEOUT
, DB_TOTAL_CHANGES
, DB_TRACE
,
1649 DB_TRANSACTION
, DB_UNLOCK_NOTIFY
, DB_UPDATE_HOOK
,
1650 DB_VERSION
, DB_WAL_HOOK
1652 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
1655 Tcl_WrongNumArgs(interp
, 1, objv
, "SUBCOMMAND ...");
1658 if( Tcl_GetIndexFromObj(interp
, objv
[1], DB_strs
, "option", 0, &choice
) ){
1662 switch( (enum DB_enum
)choice
){
1664 /* $db authorizer ?CALLBACK?
1666 ** Invoke the given callback to authorize each SQL operation as it is
1667 ** compiled. 5 arguments are appended to the callback before it is
1670 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1671 ** (2) First descriptive name (depends on authorization type)
1672 ** (3) Second descriptive name
1673 ** (4) Name of the database (ex: "main", "temp")
1674 ** (5) Name of trigger that is doing the access
1676 ** The callback should return on of the following strings: SQLITE_OK,
1677 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1679 ** If this method is invoked with no arguments, the current authorization
1680 ** callback string is returned.
1682 case DB_AUTHORIZER
: {
1683 #ifdef SQLITE_OMIT_AUTHORIZATION
1684 Tcl_AppendResult(interp
, "authorization not available in this build",
1689 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
1691 }else if( objc
==2 ){
1693 Tcl_AppendResult(interp
, pDb
->zAuth
, (char*)0);
1699 Tcl_Free(pDb
->zAuth
);
1701 zAuth
= Tcl_GetStringFromObj(objv
[2], &len
);
1702 if( zAuth
&& len
>0 ){
1703 pDb
->zAuth
= Tcl_Alloc( len
+ 1 );
1704 memcpy(pDb
->zAuth
, zAuth
, len
+1);
1709 typedef int (*sqlite3_auth_cb
)(
1710 void*,int,const char*,const char*,
1711 const char*,const char*);
1712 pDb
->interp
= interp
;
1713 sqlite3_set_authorizer(pDb
->db
,(sqlite3_auth_cb
)auth_callback
,pDb
);
1715 sqlite3_set_authorizer(pDb
->db
, 0, 0);
1722 /* $db backup ?DATABASE? FILENAME
1724 ** Open or create a database file named FILENAME. Transfer the
1725 ** content of local database DATABASE (default: "main") into the
1726 ** FILENAME database.
1729 const char *zDestFile
;
1732 sqlite3_backup
*pBackup
;
1736 zDestFile
= Tcl_GetString(objv
[2]);
1737 }else if( objc
==4 ){
1738 zSrcDb
= Tcl_GetString(objv
[2]);
1739 zDestFile
= Tcl_GetString(objv
[3]);
1741 Tcl_WrongNumArgs(interp
, 2, objv
, "?DATABASE? FILENAME");
1744 rc
= sqlite3_open(zDestFile
, &pDest
);
1745 if( rc
!=SQLITE_OK
){
1746 Tcl_AppendResult(interp
, "cannot open target database: ",
1747 sqlite3_errmsg(pDest
), (char*)0);
1748 sqlite3_close(pDest
);
1751 pBackup
= sqlite3_backup_init(pDest
, "main", pDb
->db
, zSrcDb
);
1753 Tcl_AppendResult(interp
, "backup failed: ",
1754 sqlite3_errmsg(pDest
), (char*)0);
1755 sqlite3_close(pDest
);
1758 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
){}
1759 sqlite3_backup_finish(pBackup
);
1760 if( rc
==SQLITE_DONE
){
1763 Tcl_AppendResult(interp
, "backup failed: ",
1764 sqlite3_errmsg(pDest
), (char*)0);
1767 sqlite3_close(pDest
);
1771 /* $db busy ?CALLBACK?
1773 ** Invoke the given callback if an SQL statement attempts to open
1774 ** a locked database file.
1778 Tcl_WrongNumArgs(interp
, 2, objv
, "CALLBACK");
1780 }else if( objc
==2 ){
1782 Tcl_AppendResult(interp
, pDb
->zBusy
, (char*)0);
1788 Tcl_Free(pDb
->zBusy
);
1790 zBusy
= Tcl_GetStringFromObj(objv
[2], &len
);
1791 if( zBusy
&& len
>0 ){
1792 pDb
->zBusy
= Tcl_Alloc( len
+ 1 );
1793 memcpy(pDb
->zBusy
, zBusy
, len
+1);
1798 pDb
->interp
= interp
;
1799 sqlite3_busy_handler(pDb
->db
, DbBusyHandler
, pDb
);
1801 sqlite3_busy_handler(pDb
->db
, 0, 0);
1810 ** Flush the prepared statement cache, or set the maximum number of
1811 ** cached statements.
1818 Tcl_WrongNumArgs(interp
, 1, objv
, "cache option ?arg?");
1821 subCmd
= Tcl_GetStringFromObj( objv
[2], 0 );
1822 if( *subCmd
=='f' && strcmp(subCmd
,"flush")==0 ){
1824 Tcl_WrongNumArgs(interp
, 2, objv
, "flush");
1827 flushStmtCache( pDb
);
1829 }else if( *subCmd
=='s' && strcmp(subCmd
,"size")==0 ){
1831 Tcl_WrongNumArgs(interp
, 2, objv
, "size n");
1834 if( TCL_ERROR
==Tcl_GetIntFromObj(interp
, objv
[3], &n
) ){
1835 Tcl_AppendResult( interp
, "cannot convert \"",
1836 Tcl_GetStringFromObj(objv
[3],0), "\" to integer", (char*)0);
1840 flushStmtCache( pDb
);
1842 }else if( n
>MAX_PREPARED_STMTS
){
1843 n
= MAX_PREPARED_STMTS
;
1849 Tcl_AppendResult( interp
, "bad option \"",
1850 Tcl_GetStringFromObj(objv
[2],0), "\": must be flush or size",
1859 ** Return the number of rows that were modified, inserted, or deleted by
1860 ** the most recent INSERT, UPDATE or DELETE statement, not including
1861 ** any changes made by trigger programs.
1866 Tcl_WrongNumArgs(interp
, 2, objv
, "");
1869 pResult
= Tcl_GetObjResult(interp
);
1870 Tcl_SetIntObj(pResult
, sqlite3_changes(pDb
->db
));
1876 ** Shutdown the database
1879 Tcl_DeleteCommand(interp
, Tcl_GetStringFromObj(objv
[0], 0));
1884 ** $db collate NAME SCRIPT
1886 ** Create a new SQL collation function called NAME. Whenever
1887 ** that function is called, invoke SCRIPT to evaluate the function.
1890 SqlCollate
*pCollate
;
1895 Tcl_WrongNumArgs(interp
, 2, objv
, "NAME SCRIPT");
1898 zName
= Tcl_GetStringFromObj(objv
[2], 0);
1899 zScript
= Tcl_GetStringFromObj(objv
[3], &nScript
);
1900 pCollate
= (SqlCollate
*)Tcl_Alloc( sizeof(*pCollate
) + nScript
+ 1 );
1901 if( pCollate
==0 ) return TCL_ERROR
;
1902 pCollate
->interp
= interp
;
1903 pCollate
->pNext
= pDb
->pCollate
;
1904 pCollate
->zScript
= (char*)&pCollate
[1];
1905 pDb
->pCollate
= pCollate
;
1906 memcpy(pCollate
->zScript
, zScript
, nScript
+1);
1907 if( sqlite3_create_collation(pDb
->db
, zName
, SQLITE_UTF8
,
1908 pCollate
, tclSqlCollate
) ){
1909 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(pDb
->db
), TCL_VOLATILE
);
1916 ** $db collation_needed SCRIPT
1918 ** Create a new SQL collation function called NAME. Whenever
1919 ** that function is called, invoke SCRIPT to evaluate the function.
1921 case DB_COLLATION_NEEDED
: {
1923 Tcl_WrongNumArgs(interp
, 2, objv
, "SCRIPT");
1926 if( pDb
->pCollateNeeded
){
1927 Tcl_DecrRefCount(pDb
->pCollateNeeded
);
1929 pDb
->pCollateNeeded
= Tcl_DuplicateObj(objv
[2]);
1930 Tcl_IncrRefCount(pDb
->pCollateNeeded
);
1931 sqlite3_collation_needed(pDb
->db
, pDb
, tclCollateNeeded
);
1935 /* $db commit_hook ?CALLBACK?
1937 ** Invoke the given callback just before committing every SQL transaction.
1938 ** If the callback throws an exception or returns non-zero, then the
1939 ** transaction is aborted. If CALLBACK is an empty string, the callback
1942 case DB_COMMIT_HOOK
: {
1944 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
1946 }else if( objc
==2 ){
1948 Tcl_AppendResult(interp
, pDb
->zCommit
, (char*)0);
1951 const char *zCommit
;
1954 Tcl_Free(pDb
->zCommit
);
1956 zCommit
= Tcl_GetStringFromObj(objv
[2], &len
);
1957 if( zCommit
&& len
>0 ){
1958 pDb
->zCommit
= Tcl_Alloc( len
+ 1 );
1959 memcpy(pDb
->zCommit
, zCommit
, len
+1);
1964 pDb
->interp
= interp
;
1965 sqlite3_commit_hook(pDb
->db
, DbCommitHandler
, pDb
);
1967 sqlite3_commit_hook(pDb
->db
, 0, 0);
1975 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1976 ** additional lines of input are needed. This is similar to the
1977 ** built-in "info complete" command of Tcl.
1980 #ifndef SQLITE_OMIT_COMPLETE
1984 Tcl_WrongNumArgs(interp
, 2, objv
, "SQL");
1987 isComplete
= sqlite3_complete( Tcl_GetStringFromObj(objv
[2], 0) );
1988 pResult
= Tcl_GetObjResult(interp
);
1989 Tcl_SetBooleanObj(pResult
, isComplete
);
1994 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1996 ** Copy data into table from filename, optionally using SEPARATOR
1997 ** as column separators. If a column contains a null string, or the
1998 ** value of NULLINDICATOR, a NULL is inserted for the column.
1999 ** conflict-algorithm is one of the sqlite conflict algorithms:
2000 ** rollback, abort, fail, ignore, replace
2001 ** On success, return the number of lines processed, not necessarily same
2002 ** as 'db changes' due to conflict-algorithm selected.
2004 ** This code is basically an implementation/enhancement of
2005 ** the sqlite3 shell.c ".import" command.
2007 ** This command usage is equivalent to the sqlite2.x COPY statement,
2008 ** which imports file data into a table using the PostgreSQL COPY file format:
2009 ** $db copy $conflit_algo $table_name $filename \t \\N
2012 char *zTable
; /* Insert data into this table */
2013 char *zFile
; /* The file from which to extract data */
2014 char *zConflict
; /* The conflict algorithm to use */
2015 sqlite3_stmt
*pStmt
; /* A statement */
2016 int nCol
; /* Number of columns in the table */
2017 int nByte
; /* Number of bytes in an SQL string */
2018 int i
, j
; /* Loop counters */
2019 int nSep
; /* Number of bytes in zSep[] */
2020 int nNull
; /* Number of bytes in zNull[] */
2021 char *zSql
; /* An SQL statement */
2022 char *zLine
; /* A single line of input from the file */
2023 char **azCol
; /* zLine[] broken up into columns */
2024 const char *zCommit
; /* How to commit changes */
2025 FILE *in
; /* The input file */
2026 int lineno
= 0; /* Line number of input file */
2027 char zLineNum
[80]; /* Line number print buffer */
2028 Tcl_Obj
*pResult
; /* interp result */
2032 if( objc
<5 || objc
>7 ){
2033 Tcl_WrongNumArgs(interp
, 2, objv
,
2034 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2038 zSep
= Tcl_GetStringFromObj(objv
[5], 0);
2043 zNull
= Tcl_GetStringFromObj(objv
[6], 0);
2047 zConflict
= Tcl_GetStringFromObj(objv
[2], 0);
2048 zTable
= Tcl_GetStringFromObj(objv
[3], 0);
2049 zFile
= Tcl_GetStringFromObj(objv
[4], 0);
2050 nSep
= strlen30(zSep
);
2051 nNull
= strlen30(zNull
);
2053 Tcl_AppendResult(interp
,"Error: non-null separator required for copy",
2057 if(strcmp(zConflict
, "rollback") != 0 &&
2058 strcmp(zConflict
, "abort" ) != 0 &&
2059 strcmp(zConflict
, "fail" ) != 0 &&
2060 strcmp(zConflict
, "ignore" ) != 0 &&
2061 strcmp(zConflict
, "replace" ) != 0 ) {
2062 Tcl_AppendResult(interp
, "Error: \"", zConflict
,
2063 "\", conflict-algorithm must be one of: rollback, "
2064 "abort, fail, ignore, or replace", (char*)0);
2067 zSql
= sqlite3_mprintf("SELECT * FROM '%q'", zTable
);
2069 Tcl_AppendResult(interp
, "Error: no such table: ", zTable
, (char*)0);
2072 nByte
= strlen30(zSql
);
2073 rc
= sqlite3_prepare(pDb
->db
, zSql
, -1, &pStmt
, 0);
2076 Tcl_AppendResult(interp
, "Error: ", sqlite3_errmsg(pDb
->db
), (char*)0);
2079 nCol
= sqlite3_column_count(pStmt
);
2081 sqlite3_finalize(pStmt
);
2085 zSql
= malloc( nByte
+ 50 + nCol
*2 );
2087 Tcl_AppendResult(interp
, "Error: can't malloc()", (char*)0);
2090 sqlite3_snprintf(nByte
+50, zSql
, "INSERT OR %q INTO '%q' VALUES(?",
2093 for(i
=1; i
<nCol
; i
++){
2099 rc
= sqlite3_prepare(pDb
->db
, zSql
, -1, &pStmt
, 0);
2102 Tcl_AppendResult(interp
, "Error: ", sqlite3_errmsg(pDb
->db
), (char*)0);
2103 sqlite3_finalize(pStmt
);
2106 in
= fopen(zFile
, "rb");
2108 Tcl_AppendResult(interp
, "Error: cannot open file: ", zFile
, NULL
);
2109 sqlite3_finalize(pStmt
);
2112 azCol
= malloc( sizeof(azCol
[0])*(nCol
+1) );
2114 Tcl_AppendResult(interp
, "Error: can't malloc()", (char*)0);
2118 (void)sqlite3_exec(pDb
->db
, "BEGIN", 0, 0, 0);
2120 while( (zLine
= local_getline(0, in
))!=0 ){
2124 for(i
=0, z
=zLine
; *z
; z
++){
2125 if( *z
==zSep
[0] && strncmp(z
, zSep
, nSep
)==0 ){
2129 azCol
[i
] = &z
[nSep
];
2136 int nErr
= strlen30(zFile
) + 200;
2137 zErr
= malloc(nErr
);
2139 sqlite3_snprintf(nErr
, zErr
,
2140 "Error: %s line %d: expected %d columns of data but found %d",
2141 zFile
, lineno
, nCol
, i
+1);
2142 Tcl_AppendResult(interp
, zErr
, (char*)0);
2145 zCommit
= "ROLLBACK";
2148 for(i
=0; i
<nCol
; i
++){
2149 /* check for null data, if so, bind as null */
2150 if( (nNull
>0 && strcmp(azCol
[i
], zNull
)==0)
2151 || strlen30(azCol
[i
])==0
2153 sqlite3_bind_null(pStmt
, i
+1);
2155 sqlite3_bind_text(pStmt
, i
+1, azCol
[i
], -1, SQLITE_STATIC
);
2158 sqlite3_step(pStmt
);
2159 rc
= sqlite3_reset(pStmt
);
2161 if( rc
!=SQLITE_OK
){
2162 Tcl_AppendResult(interp
,"Error: ", sqlite3_errmsg(pDb
->db
), (char*)0);
2163 zCommit
= "ROLLBACK";
2169 sqlite3_finalize(pStmt
);
2170 (void)sqlite3_exec(pDb
->db
, zCommit
, 0, 0, 0);
2172 if( zCommit
[0] == 'C' ){
2173 /* success, set result as number of lines processed */
2174 pResult
= Tcl_GetObjResult(interp
);
2175 Tcl_SetIntObj(pResult
, lineno
);
2178 /* failure, append lineno where failed */
2179 sqlite3_snprintf(sizeof(zLineNum
), zLineNum
,"%d",lineno
);
2180 Tcl_AppendResult(interp
,", failed while processing line: ",zLineNum
,
2188 ** $db enable_load_extension BOOLEAN
2190 ** Turn the extension loading feature on or off. It if off by
2193 case DB_ENABLE_LOAD_EXTENSION
: {
2194 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2197 Tcl_WrongNumArgs(interp
, 2, objv
, "BOOLEAN");
2200 if( Tcl_GetBooleanFromObj(interp
, objv
[2], &onoff
) ){
2203 sqlite3_enable_load_extension(pDb
->db
, onoff
);
2206 Tcl_AppendResult(interp
, "extension loading is turned off at compile-time",
2215 ** Return the numeric error code that was returned by the most recent
2216 ** call to sqlite3_exec().
2218 case DB_ERRORCODE
: {
2219 Tcl_SetObjResult(interp
, Tcl_NewIntObj(sqlite3_errcode(pDb
->db
)));
2225 ** $db onecolumn $sql
2227 ** The onecolumn method is the equivalent of:
2228 ** lindex [$db eval $sql] 0
2231 case DB_ONECOLUMN
: {
2232 DbEvalContext sEval
;
2234 Tcl_WrongNumArgs(interp
, 2, objv
, "SQL");
2238 dbEvalInit(&sEval
, pDb
, objv
[2], 0);
2239 rc
= dbEvalStep(&sEval
);
2240 if( choice
==DB_ONECOLUMN
){
2242 Tcl_SetObjResult(interp
, dbEvalColumnValue(&sEval
, 0));
2243 }else if( rc
==TCL_BREAK
){
2244 Tcl_ResetResult(interp
);
2246 }else if( rc
==TCL_BREAK
|| rc
==TCL_OK
){
2247 Tcl_SetObjResult(interp
, Tcl_NewBooleanObj(rc
==TCL_OK
));
2249 dbEvalFinalize(&sEval
);
2251 if( rc
==TCL_BREAK
){
2258 ** $db eval $sql ?array? ?{ ...code... }?
2260 ** The SQL statement in $sql is evaluated. For each row, the values are
2261 ** placed in elements of the array named "array" and ...code... is executed.
2262 ** If "array" and "code" are omitted, then no callback is every invoked.
2263 ** If "array" is an empty string, then the values are placed in variables
2264 ** that have the same name as the fields extracted by the query.
2267 if( objc
<3 || objc
>5 ){
2268 Tcl_WrongNumArgs(interp
, 2, objv
, "SQL ?ARRAY-NAME? ?SCRIPT?");
2273 DbEvalContext sEval
;
2274 Tcl_Obj
*pRet
= Tcl_NewObj();
2275 Tcl_IncrRefCount(pRet
);
2276 dbEvalInit(&sEval
, pDb
, objv
[2], 0);
2277 while( TCL_OK
==(rc
= dbEvalStep(&sEval
)) ){
2280 dbEvalRowInfo(&sEval
, &nCol
, 0);
2281 for(i
=0; i
<nCol
; i
++){
2282 Tcl_ListObjAppendElement(interp
, pRet
, dbEvalColumnValue(&sEval
, i
));
2285 dbEvalFinalize(&sEval
);
2286 if( rc
==TCL_BREAK
){
2287 Tcl_SetObjResult(interp
, pRet
);
2290 Tcl_DecrRefCount(pRet
);
2294 Tcl_Obj
*pArray
= 0;
2297 if( objc
==5 && *(char *)Tcl_GetString(objv
[3]) ){
2300 pScript
= objv
[objc
-1];
2301 Tcl_IncrRefCount(pScript
);
2303 p
= (DbEvalContext
*)Tcl_Alloc(sizeof(DbEvalContext
));
2304 dbEvalInit(p
, pDb
, objv
[2], pArray
);
2307 cd
[1] = (void *)pScript
;
2308 rc
= DbEvalNextCmd(cd
, interp
, TCL_OK
);
2314 ** $db function NAME [-argcount N] SCRIPT
2316 ** Create a new SQL function called NAME. Whenever that function is
2317 ** called, invoke SCRIPT to evaluate the function.
2325 const char *z
= Tcl_GetString(objv
[3]);
2326 int n
= strlen30(z
);
2327 if( n
>2 && strncmp(z
, "-argcount",n
)==0 ){
2328 if( Tcl_GetIntFromObj(interp
, objv
[4], &nArg
) ) return TCL_ERROR
;
2330 Tcl_AppendResult(interp
, "number of arguments must be non-negative",
2336 }else if( objc
!=4 ){
2337 Tcl_WrongNumArgs(interp
, 2, objv
, "NAME [-argcount N] SCRIPT");
2342 zName
= Tcl_GetStringFromObj(objv
[2], 0);
2343 pFunc
= findSqlFunc(pDb
, zName
);
2344 if( pFunc
==0 ) return TCL_ERROR
;
2345 if( pFunc
->pScript
){
2346 Tcl_DecrRefCount(pFunc
->pScript
);
2348 pFunc
->pScript
= pScript
;
2349 Tcl_IncrRefCount(pScript
);
2350 pFunc
->useEvalObjv
= safeToUseEvalObjv(interp
, pScript
);
2351 rc
= sqlite3_create_function(pDb
->db
, zName
, nArg
, SQLITE_UTF8
,
2352 pFunc
, tclSqlFunc
, 0, 0);
2353 if( rc
!=SQLITE_OK
){
2355 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(pDb
->db
), TCL_VOLATILE
);
2361 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
2364 #ifdef SQLITE_OMIT_INCRBLOB
2365 Tcl_AppendResult(interp
, "incrblob not available in this build", (char*)0);
2369 const char *zDb
= "main";
2371 const char *zColumn
;
2374 /* Check for the -readonly option */
2375 if( objc
>3 && strcmp(Tcl_GetString(objv
[2]), "-readonly")==0 ){
2379 if( objc
!=(5+isReadonly
) && objc
!=(6+isReadonly
) ){
2380 Tcl_WrongNumArgs(interp
, 2, objv
, "?-readonly? ?DB? TABLE COLUMN ROWID");
2384 if( objc
==(6+isReadonly
) ){
2385 zDb
= Tcl_GetString(objv
[2]);
2387 zTable
= Tcl_GetString(objv
[objc
-3]);
2388 zColumn
= Tcl_GetString(objv
[objc
-2]);
2389 rc
= Tcl_GetWideIntFromObj(interp
, objv
[objc
-1], &iRow
);
2392 rc
= createIncrblobChannel(
2393 interp
, pDb
, zDb
, zTable
, zColumn
, (sqlite3_int64
)iRow
, isReadonly
2403 ** Interrupt the execution of the inner-most SQL interpreter. This
2404 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2406 case DB_INTERRUPT
: {
2407 sqlite3_interrupt(pDb
->db
);
2412 ** $db nullvalue ?STRING?
2414 ** Change text used when a NULL comes back from the database. If ?STRING?
2415 ** is not present, then the current string used for NULL is returned.
2416 ** If STRING is present, then STRING is returned.
2419 case DB_NULLVALUE
: {
2420 if( objc
!=2 && objc
!=3 ){
2421 Tcl_WrongNumArgs(interp
, 2, objv
, "NULLVALUE");
2426 char *zNull
= Tcl_GetStringFromObj(objv
[2], &len
);
2428 Tcl_Free(pDb
->zNull
);
2430 if( zNull
&& len
>0 ){
2431 pDb
->zNull
= Tcl_Alloc( len
+ 1 );
2432 memcpy(pDb
->zNull
, zNull
, len
);
2433 pDb
->zNull
[len
] = '\0';
2438 Tcl_SetObjResult(interp
, Tcl_NewStringObj(pDb
->zNull
, -1));
2443 ** $db last_insert_rowid
2445 ** Return an integer which is the ROWID for the most recent insert.
2447 case DB_LAST_INSERT_ROWID
: {
2451 Tcl_WrongNumArgs(interp
, 2, objv
, "");
2454 rowid
= sqlite3_last_insert_rowid(pDb
->db
);
2455 pResult
= Tcl_GetObjResult(interp
);
2456 Tcl_SetWideIntObj(pResult
, rowid
);
2461 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
2464 /* $db progress ?N CALLBACK?
2466 ** Invoke the given callback every N virtual machine opcodes while executing
2471 if( pDb
->zProgress
){
2472 Tcl_AppendResult(interp
, pDb
->zProgress
, (char*)0);
2474 }else if( objc
==4 ){
2478 if( TCL_OK
!=Tcl_GetIntFromObj(interp
, objv
[2], &N
) ){
2481 if( pDb
->zProgress
){
2482 Tcl_Free(pDb
->zProgress
);
2484 zProgress
= Tcl_GetStringFromObj(objv
[3], &len
);
2485 if( zProgress
&& len
>0 ){
2486 pDb
->zProgress
= Tcl_Alloc( len
+ 1 );
2487 memcpy(pDb
->zProgress
, zProgress
, len
+1);
2491 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2492 if( pDb
->zProgress
){
2493 pDb
->interp
= interp
;
2494 sqlite3_progress_handler(pDb
->db
, N
, DbProgressHandler
, pDb
);
2496 sqlite3_progress_handler(pDb
->db
, 0, 0, 0);
2500 Tcl_WrongNumArgs(interp
, 2, objv
, "N CALLBACK");
2506 /* $db profile ?CALLBACK?
2508 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2509 ** that has run. The text of the SQL and the amount of elapse time are
2510 ** appended to CALLBACK before the script is run.
2514 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
2516 }else if( objc
==2 ){
2517 if( pDb
->zProfile
){
2518 Tcl_AppendResult(interp
, pDb
->zProfile
, (char*)0);
2523 if( pDb
->zProfile
){
2524 Tcl_Free(pDb
->zProfile
);
2526 zProfile
= Tcl_GetStringFromObj(objv
[2], &len
);
2527 if( zProfile
&& len
>0 ){
2528 pDb
->zProfile
= Tcl_Alloc( len
+ 1 );
2529 memcpy(pDb
->zProfile
, zProfile
, len
+1);
2533 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
2534 if( pDb
->zProfile
){
2535 pDb
->interp
= interp
;
2536 sqlite3_profile(pDb
->db
, DbProfileHandler
, pDb
);
2538 sqlite3_profile(pDb
->db
, 0, 0);
2548 ** Change the encryption key on the currently open database.
2551 #ifdef SQLITE_HAS_CODEC
2556 Tcl_WrongNumArgs(interp
, 2, objv
, "KEY");
2559 #ifdef SQLITE_HAS_CODEC
2560 pKey
= Tcl_GetByteArrayFromObj(objv
[2], &nKey
);
2561 rc
= sqlite3_rekey(pDb
->db
, pKey
, nKey
);
2563 Tcl_AppendResult(interp
, sqlite3_errstr(rc
), (char*)0);
2570 /* $db restore ?DATABASE? FILENAME
2572 ** Open a database file named FILENAME. Transfer the content
2573 ** of FILENAME into the local database DATABASE (default: "main").
2576 const char *zSrcFile
;
2577 const char *zDestDb
;
2579 sqlite3_backup
*pBackup
;
2584 zSrcFile
= Tcl_GetString(objv
[2]);
2585 }else if( objc
==4 ){
2586 zDestDb
= Tcl_GetString(objv
[2]);
2587 zSrcFile
= Tcl_GetString(objv
[3]);
2589 Tcl_WrongNumArgs(interp
, 2, objv
, "?DATABASE? FILENAME");
2592 rc
= sqlite3_open_v2(zSrcFile
, &pSrc
, SQLITE_OPEN_READONLY
, 0);
2593 if( rc
!=SQLITE_OK
){
2594 Tcl_AppendResult(interp
, "cannot open source database: ",
2595 sqlite3_errmsg(pSrc
), (char*)0);
2596 sqlite3_close(pSrc
);
2599 pBackup
= sqlite3_backup_init(pDb
->db
, zDestDb
, pSrc
, "main");
2601 Tcl_AppendResult(interp
, "restore failed: ",
2602 sqlite3_errmsg(pDb
->db
), (char*)0);
2603 sqlite3_close(pSrc
);
2606 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
2607 || rc
==SQLITE_BUSY
){
2608 if( rc
==SQLITE_BUSY
){
2609 if( nTimeout
++ >= 3 ) break;
2613 sqlite3_backup_finish(pBackup
);
2614 if( rc
==SQLITE_DONE
){
2616 }else if( rc
==SQLITE_BUSY
|| rc
==SQLITE_LOCKED
){
2617 Tcl_AppendResult(interp
, "restore failed: source database busy",
2621 Tcl_AppendResult(interp
, "restore failed: ",
2622 sqlite3_errmsg(pDb
->db
), (char*)0);
2625 sqlite3_close(pSrc
);
2630 ** $db status (step|sort|autoindex)
2632 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2633 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2639 Tcl_WrongNumArgs(interp
, 2, objv
, "(step|sort|autoindex)");
2642 zOp
= Tcl_GetString(objv
[2]);
2643 if( strcmp(zOp
, "step")==0 ){
2645 }else if( strcmp(zOp
, "sort")==0 ){
2647 }else if( strcmp(zOp
, "autoindex")==0 ){
2650 Tcl_AppendResult(interp
,
2651 "bad argument: should be autoindex, step, or sort",
2655 Tcl_SetObjResult(interp
, Tcl_NewIntObj(v
));
2660 ** $db timeout MILLESECONDS
2662 ** Delay for the number of milliseconds specified when a file is locked.
2667 Tcl_WrongNumArgs(interp
, 2, objv
, "MILLISECONDS");
2670 if( Tcl_GetIntFromObj(interp
, objv
[2], &ms
) ) return TCL_ERROR
;
2671 sqlite3_busy_timeout(pDb
->db
, ms
);
2676 ** $db total_changes
2678 ** Return the number of rows that were modified, inserted, or deleted
2679 ** since the database handle was created.
2681 case DB_TOTAL_CHANGES
: {
2684 Tcl_WrongNumArgs(interp
, 2, objv
, "");
2687 pResult
= Tcl_GetObjResult(interp
);
2688 Tcl_SetIntObj(pResult
, sqlite3_total_changes(pDb
->db
));
2692 /* $db trace ?CALLBACK?
2694 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2695 ** that is executed. The text of the SQL is appended to CALLBACK before
2700 Tcl_WrongNumArgs(interp
, 2, objv
, "?CALLBACK?");
2702 }else if( objc
==2 ){
2704 Tcl_AppendResult(interp
, pDb
->zTrace
, (char*)0);
2710 Tcl_Free(pDb
->zTrace
);
2712 zTrace
= Tcl_GetStringFromObj(objv
[2], &len
);
2713 if( zTrace
&& len
>0 ){
2714 pDb
->zTrace
= Tcl_Alloc( len
+ 1 );
2715 memcpy(pDb
->zTrace
, zTrace
, len
+1);
2719 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
2721 pDb
->interp
= interp
;
2722 sqlite3_trace(pDb
->db
, DbTraceHandler
, pDb
);
2724 sqlite3_trace(pDb
->db
, 0, 0);
2731 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2733 ** Start a new transaction (if we are not already in the midst of a
2734 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2735 ** completes, either commit the transaction or roll it back if SCRIPT
2736 ** throws an exception. Or if no new transation was started, do nothing.
2737 ** pass the exception on up the stack.
2739 ** This command was inspired by Dave Thomas's talk on Ruby at the
2740 ** 2005 O'Reilly Open Source Convention (OSCON).
2742 case DB_TRANSACTION
: {
2744 const char *zBegin
= "SAVEPOINT _tcl_transaction";
2745 if( objc
!=3 && objc
!=4 ){
2746 Tcl_WrongNumArgs(interp
, 2, objv
, "[TYPE] SCRIPT");
2750 if( pDb
->nTransaction
==0 && objc
==4 ){
2751 static const char *TTYPE_strs
[] = {
2752 "deferred", "exclusive", "immediate", 0
2755 TTYPE_DEFERRED
, TTYPE_EXCLUSIVE
, TTYPE_IMMEDIATE
2758 if( Tcl_GetIndexFromObj(interp
, objv
[2], TTYPE_strs
, "transaction type",
2762 switch( (enum TTYPE_enum
)ttype
){
2763 case TTYPE_DEFERRED
: /* no-op */; break;
2764 case TTYPE_EXCLUSIVE
: zBegin
= "BEGIN EXCLUSIVE"; break;
2765 case TTYPE_IMMEDIATE
: zBegin
= "BEGIN IMMEDIATE"; break;
2768 pScript
= objv
[objc
-1];
2770 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
2772 rc
= sqlite3_exec(pDb
->db
, zBegin
, 0, 0, 0);
2774 if( rc
!=SQLITE_OK
){
2775 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
2778 pDb
->nTransaction
++;
2780 /* If using NRE, schedule a callback to invoke the script pScript, then
2781 ** a second callback to commit (or rollback) the transaction or savepoint
2782 ** opened above. If not using NRE, evaluate the script directly, then
2783 ** call function DbTransPostCmd() to commit (or rollback) the transaction
2786 Tcl_NRAddCallback(interp
, DbTransPostCmd
, cd
, 0, 0, 0);
2787 (void)Tcl_NREvalObj(interp
, pScript
, 0);
2789 rc
= DbTransPostCmd(&cd
, interp
, Tcl_EvalObjEx(interp
, pScript
, 0));
2795 ** $db unlock_notify ?script?
2797 case DB_UNLOCK_NOTIFY
: {
2798 #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2799 Tcl_AppendResult(interp
, "unlock_notify not available in this build",
2803 if( objc
!=2 && objc
!=3 ){
2804 Tcl_WrongNumArgs(interp
, 2, objv
, "?SCRIPT?");
2807 void (*xNotify
)(void **, int) = 0;
2808 void *pNotifyArg
= 0;
2810 if( pDb
->pUnlockNotify
){
2811 Tcl_DecrRefCount(pDb
->pUnlockNotify
);
2812 pDb
->pUnlockNotify
= 0;
2816 xNotify
= DbUnlockNotify
;
2817 pNotifyArg
= (void *)pDb
;
2818 pDb
->pUnlockNotify
= objv
[2];
2819 Tcl_IncrRefCount(pDb
->pUnlockNotify
);
2822 if( sqlite3_unlock_notify(pDb
->db
, xNotify
, pNotifyArg
) ){
2823 Tcl_AppendResult(interp
, sqlite3_errmsg(pDb
->db
), (char*)0);
2832 ** $db wal_hook ?script?
2833 ** $db update_hook ?script?
2834 ** $db rollback_hook ?script?
2837 case DB_UPDATE_HOOK
:
2838 case DB_ROLLBACK_HOOK
: {
2840 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2841 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2844 if( choice
==DB_UPDATE_HOOK
){
2845 ppHook
= &pDb
->pUpdateHook
;
2846 }else if( choice
==DB_WAL_HOOK
){
2847 ppHook
= &pDb
->pWalHook
;
2849 ppHook
= &pDb
->pRollbackHook
;
2852 if( objc
!=2 && objc
!=3 ){
2853 Tcl_WrongNumArgs(interp
, 2, objv
, "?SCRIPT?");
2857 Tcl_SetObjResult(interp
, *ppHook
);
2859 Tcl_DecrRefCount(*ppHook
);
2864 assert( !(*ppHook
) );
2865 if( Tcl_GetCharLength(objv
[2])>0 ){
2867 Tcl_IncrRefCount(*ppHook
);
2871 sqlite3_update_hook(pDb
->db
, (pDb
->pUpdateHook
?DbUpdateHandler
:0), pDb
);
2872 sqlite3_rollback_hook(pDb
->db
,(pDb
->pRollbackHook
?DbRollbackHandler
:0),pDb
);
2873 sqlite3_wal_hook(pDb
->db
,(pDb
->pWalHook
?DbWalHandler
:0),pDb
);
2880 ** Return the version string for this database.
2883 Tcl_SetResult(interp
, (char *)sqlite3_libversion(), TCL_STATIC
);
2888 } /* End of the SWITCH statement */
2894 ** Adaptor that provides an objCmd interface to the NRE-enabled
2895 ** interface implementation.
2897 static int DbObjCmdAdaptor(
2903 return Tcl_NRCallObjProc(interp
, DbObjCmd
, cd
, objc
, objv
);
2905 #endif /* SQLITE_TCL_NRE */
2908 ** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
2909 ** ?-create BOOLEAN? ?-nomutex BOOLEAN?
2911 ** This is the main Tcl command. When the "sqlite" Tcl command is
2912 ** invoked, this routine runs to process that command.
2914 ** The first argument, DBNAME, is an arbitrary name for a new
2915 ** database connection. This command creates a new command named
2916 ** DBNAME that is used to control that connection. The database
2917 ** connection is deleted when the DBNAME command is deleted.
2919 ** The second argument is the name of the database file.
2922 static int DbMain(void *cd
, Tcl_Interp
*interp
, int objc
,Tcl_Obj
*const*objv
){
2928 const char *zVfs
= 0;
2930 Tcl_DString translatedFilename
;
2931 #ifdef SQLITE_HAS_CODEC
2937 /* In normal use, each TCL interpreter runs in a single thread. So
2938 ** by default, we can turn of mutexing on SQLite database connections.
2939 ** However, for testing purposes it is useful to have mutexes turned
2940 ** on. So, by default, mutexes default off. But if compiled with
2941 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
2943 #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
2944 flags
= SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
| SQLITE_OPEN_FULLMUTEX
;
2946 flags
= SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
| SQLITE_OPEN_NOMUTEX
;
2950 zArg
= Tcl_GetStringFromObj(objv
[1], 0);
2951 if( strcmp(zArg
,"-version")==0 ){
2952 Tcl_AppendResult(interp
,sqlite3_libversion(), (char*)0);
2955 if( strcmp(zArg
,"-has-codec")==0 ){
2956 #ifdef SQLITE_HAS_CODEC
2957 Tcl_AppendResult(interp
,"1",(char*)0);
2959 Tcl_AppendResult(interp
,"0",(char*)0);
2964 for(i
=3; i
+1<objc
; i
+=2){
2965 zArg
= Tcl_GetString(objv
[i
]);
2966 if( strcmp(zArg
,"-key")==0 ){
2967 #ifdef SQLITE_HAS_CODEC
2968 pKey
= Tcl_GetByteArrayFromObj(objv
[i
+1], &nKey
);
2970 }else if( strcmp(zArg
, "-vfs")==0 ){
2971 zVfs
= Tcl_GetString(objv
[i
+1]);
2972 }else if( strcmp(zArg
, "-readonly")==0 ){
2974 if( Tcl_GetBooleanFromObj(interp
, objv
[i
+1], &b
) ) return TCL_ERROR
;
2976 flags
&= ~(SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
);
2977 flags
|= SQLITE_OPEN_READONLY
;
2979 flags
&= ~SQLITE_OPEN_READONLY
;
2980 flags
|= SQLITE_OPEN_READWRITE
;
2982 }else if( strcmp(zArg
, "-create")==0 ){
2984 if( Tcl_GetBooleanFromObj(interp
, objv
[i
+1], &b
) ) return TCL_ERROR
;
2985 if( b
&& (flags
& SQLITE_OPEN_READONLY
)==0 ){
2986 flags
|= SQLITE_OPEN_CREATE
;
2988 flags
&= ~SQLITE_OPEN_CREATE
;
2990 }else if( strcmp(zArg
, "-nomutex")==0 ){
2992 if( Tcl_GetBooleanFromObj(interp
, objv
[i
+1], &b
) ) return TCL_ERROR
;
2994 flags
|= SQLITE_OPEN_NOMUTEX
;
2995 flags
&= ~SQLITE_OPEN_FULLMUTEX
;
2997 flags
&= ~SQLITE_OPEN_NOMUTEX
;
2999 }else if( strcmp(zArg
, "-fullmutex")==0 ){
3001 if( Tcl_GetBooleanFromObj(interp
, objv
[i
+1], &b
) ) return TCL_ERROR
;
3003 flags
|= SQLITE_OPEN_FULLMUTEX
;
3004 flags
&= ~SQLITE_OPEN_NOMUTEX
;
3006 flags
&= ~SQLITE_OPEN_FULLMUTEX
;
3008 }else if( strcmp(zArg
, "-uri")==0 ){
3010 if( Tcl_GetBooleanFromObj(interp
, objv
[i
+1], &b
) ) return TCL_ERROR
;
3012 flags
|= SQLITE_OPEN_URI
;
3014 flags
&= ~SQLITE_OPEN_URI
;
3017 Tcl_AppendResult(interp
, "unknown option: ", zArg
, (char*)0);
3021 if( objc
<3 || (objc
&1)!=1 ){
3022 Tcl_WrongNumArgs(interp
, 1, objv
,
3023 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
3024 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
3025 #ifdef SQLITE_HAS_CODEC
3032 p
= (SqliteDb
*)Tcl_Alloc( sizeof(*p
) );
3034 Tcl_SetResult(interp
, (char *)"malloc failed", TCL_STATIC
);
3037 memset(p
, 0, sizeof(*p
));
3038 zFile
= Tcl_GetStringFromObj(objv
[2], 0);
3039 zFile
= Tcl_TranslateFileName(interp
, zFile
, &translatedFilename
);
3040 rc
= sqlite3_open_v2(zFile
, &p
->db
, flags
, zVfs
);
3041 Tcl_DStringFree(&translatedFilename
);
3043 if( SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
3044 zErrMsg
= sqlite3_mprintf("%s", sqlite3_errmsg(p
->db
));
3045 sqlite3_close(p
->db
);
3049 zErrMsg
= sqlite3_mprintf("%s", sqlite3_errstr(rc
));
3051 #ifdef SQLITE_HAS_CODEC
3053 sqlite3_key(p
->db
, pKey
, nKey
);
3057 Tcl_SetResult(interp
, zErrMsg
, TCL_VOLATILE
);
3059 sqlite3_free(zErrMsg
);
3062 p
->maxStmt
= NUM_PREPARED_STMTS
;
3064 zArg
= Tcl_GetStringFromObj(objv
[1], 0);
3066 Tcl_NRCreateCommand(interp
, zArg
, DbObjCmdAdaptor
, DbObjCmd
,
3067 (char*)p
, DbDeleteCmd
);
3069 Tcl_CreateObjCommand(interp
, zArg
, DbObjCmd
, (char*)p
, DbDeleteCmd
);
3075 ** Provide a dummy Tcl_InitStubs if we are using this as a static
3078 #ifndef USE_TCL_STUBS
3079 # undef Tcl_InitStubs
3080 # define Tcl_InitStubs(a,b,c) TCL_VERSION
3084 ** Make sure we have a PACKAGE_VERSION macro defined. This will be
3085 ** defined automatically by the TEA makefile. But other makefiles
3086 ** do not define it.
3088 #ifndef PACKAGE_VERSION
3089 # define PACKAGE_VERSION SQLITE_VERSION
3093 ** Initialize this module.
3095 ** This Tcl module contains only a single new Tcl command named "sqlite".
3096 ** (Hence there is no namespace. There is no point in using a namespace
3097 ** if the extension only supplies one new name!) The "sqlite" command is
3098 ** used to open a new SQLite database. See the DbMain() routine above
3099 ** for additional information.
3101 ** The EXTERN macros are required by TCL in order to work on windows.
3103 EXTERN
int Sqlite3_Init(Tcl_Interp
*interp
){
3104 int rc
= Tcl_InitStubs(interp
, "8.4", 0)==0 ? TCL_ERROR
: TCL_OK
;
3106 Tcl_CreateObjCommand(interp
, "sqlite3", (Tcl_ObjCmdProc
*)DbMain
, 0, 0);
3107 #ifndef SQLITE_3_SUFFIX_ONLY
3108 /* The "sqlite" alias is undocumented. It is here only to support
3109 ** legacy scripts. All new scripts should use only the "sqlite3"
3111 Tcl_CreateObjCommand(interp
, "sqlite", (Tcl_ObjCmdProc
*)DbMain
, 0, 0);
3113 rc
= Tcl_PkgProvide(interp
, "sqlite3", PACKAGE_VERSION
);
3117 EXTERN
int Tclsqlite3_Init(Tcl_Interp
*interp
){ return Sqlite3_Init(interp
); }
3118 EXTERN
int Sqlite3_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3119 EXTERN
int Tclsqlite3_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3121 /* Because it accesses the file-system and uses persistent state, SQLite
3122 ** is not considered appropriate for safe interpreters. Hence, we deliberately
3123 ** omit the _SafeInit() interfaces.
3126 #ifndef SQLITE_3_SUFFIX_ONLY
3127 int Sqlite_Init(Tcl_Interp
*interp
){ return Sqlite3_Init(interp
); }
3128 int Tclsqlite_Init(Tcl_Interp
*interp
){ return Sqlite3_Init(interp
); }
3129 int Sqlite_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3130 int Tclsqlite_Unload(Tcl_Interp
*interp
, int flags
){ return TCL_OK
; }
3134 /*****************************************************************************
3135 ** All of the code that follows is used to build standalone TCL interpreters
3136 ** that are statically linked with SQLite. Enable these by compiling
3137 ** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3138 ** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3139 ** analysis program.
3142 #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3144 * This code implements the MD5 message-digest algorithm.
3145 * The algorithm is due to Ron Rivest. This code was
3146 * written by Colin Plumb in 1993, no copyright is claimed.
3147 * This code is in the public domain; do with it what you wish.
3149 * Equivalent code is available from RSA Data Security, Inc.
3150 * This code has been tested against that, and is equivalent,
3151 * except that you don't need to include two pages of legalese
3154 * To compute the message digest of a chunk of bytes, declare an
3155 * MD5Context structure, pass it to MD5Init, call MD5Update as
3156 * needed on buffers full of bytes, and then call MD5Final, which
3157 * will fill a supplied 16-byte array with the digest.
3161 * If compiled on a machine that doesn't have a 32-bit integer,
3162 * you just set "uint32" to the appropriate datatype for an
3163 * unsigned 32-bit integer. For example:
3165 * cc -Duint32='unsigned long' md5.c
3169 # define uint32 unsigned int
3176 unsigned char in
[64];
3178 typedef struct MD5Context MD5Context
;
3181 * Note: this code is harmless on little-endian machines.
3183 static void byteReverse (unsigned char *buf
, unsigned longs
){
3186 t
= (uint32
)((unsigned)buf
[3]<<8 | buf
[2]) << 16 |
3187 ((unsigned)buf
[1]<<8 | buf
[0]);
3192 /* The four core functions - F1 is optimized somewhat */
3194 /* #define F1(x, y, z) (x & y | ~x & z) */
3195 #define F1(x, y, z) (z ^ (x & (y ^ z)))
3196 #define F2(x, y, z) F1(z, x, y)
3197 #define F3(x, y, z) (x ^ y ^ z)
3198 #define F4(x, y, z) (y ^ (x | ~z))
3200 /* This is the central step in the MD5 algorithm. */
3201 #define MD5STEP(f, w, x, y, z, data, s) \
3202 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3205 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3206 * reflect the addition of 16 longwords of new data. MD5Update blocks
3207 * the data and converts bytes into longwords for this routine.
3209 static void MD5Transform(uint32 buf
[4], const uint32 in
[16]){
3210 register uint32 a
, b
, c
, d
;
3217 MD5STEP(F1
, a
, b
, c
, d
, in
[ 0]+0xd76aa478, 7);
3218 MD5STEP(F1
, d
, a
, b
, c
, in
[ 1]+0xe8c7b756, 12);
3219 MD5STEP(F1
, c
, d
, a
, b
, in
[ 2]+0x242070db, 17);
3220 MD5STEP(F1
, b
, c
, d
, a
, in
[ 3]+0xc1bdceee, 22);
3221 MD5STEP(F1
, a
, b
, c
, d
, in
[ 4]+0xf57c0faf, 7);
3222 MD5STEP(F1
, d
, a
, b
, c
, in
[ 5]+0x4787c62a, 12);
3223 MD5STEP(F1
, c
, d
, a
, b
, in
[ 6]+0xa8304613, 17);
3224 MD5STEP(F1
, b
, c
, d
, a
, in
[ 7]+0xfd469501, 22);
3225 MD5STEP(F1
, a
, b
, c
, d
, in
[ 8]+0x698098d8, 7);
3226 MD5STEP(F1
, d
, a
, b
, c
, in
[ 9]+0x8b44f7af, 12);
3227 MD5STEP(F1
, c
, d
, a
, b
, in
[10]+0xffff5bb1, 17);
3228 MD5STEP(F1
, b
, c
, d
, a
, in
[11]+0x895cd7be, 22);
3229 MD5STEP(F1
, a
, b
, c
, d
, in
[12]+0x6b901122, 7);
3230 MD5STEP(F1
, d
, a
, b
, c
, in
[13]+0xfd987193, 12);
3231 MD5STEP(F1
, c
, d
, a
, b
, in
[14]+0xa679438e, 17);
3232 MD5STEP(F1
, b
, c
, d
, a
, in
[15]+0x49b40821, 22);
3234 MD5STEP(F2
, a
, b
, c
, d
, in
[ 1]+0xf61e2562, 5);
3235 MD5STEP(F2
, d
, a
, b
, c
, in
[ 6]+0xc040b340, 9);
3236 MD5STEP(F2
, c
, d
, a
, b
, in
[11]+0x265e5a51, 14);
3237 MD5STEP(F2
, b
, c
, d
, a
, in
[ 0]+0xe9b6c7aa, 20);
3238 MD5STEP(F2
, a
, b
, c
, d
, in
[ 5]+0xd62f105d, 5);
3239 MD5STEP(F2
, d
, a
, b
, c
, in
[10]+0x02441453, 9);
3240 MD5STEP(F2
, c
, d
, a
, b
, in
[15]+0xd8a1e681, 14);
3241 MD5STEP(F2
, b
, c
, d
, a
, in
[ 4]+0xe7d3fbc8, 20);
3242 MD5STEP(F2
, a
, b
, c
, d
, in
[ 9]+0x21e1cde6, 5);
3243 MD5STEP(F2
, d
, a
, b
, c
, in
[14]+0xc33707d6, 9);
3244 MD5STEP(F2
, c
, d
, a
, b
, in
[ 3]+0xf4d50d87, 14);
3245 MD5STEP(F2
, b
, c
, d
, a
, in
[ 8]+0x455a14ed, 20);
3246 MD5STEP(F2
, a
, b
, c
, d
, in
[13]+0xa9e3e905, 5);
3247 MD5STEP(F2
, d
, a
, b
, c
, in
[ 2]+0xfcefa3f8, 9);
3248 MD5STEP(F2
, c
, d
, a
, b
, in
[ 7]+0x676f02d9, 14);
3249 MD5STEP(F2
, b
, c
, d
, a
, in
[12]+0x8d2a4c8a, 20);
3251 MD5STEP(F3
, a
, b
, c
, d
, in
[ 5]+0xfffa3942, 4);
3252 MD5STEP(F3
, d
, a
, b
, c
, in
[ 8]+0x8771f681, 11);
3253 MD5STEP(F3
, c
, d
, a
, b
, in
[11]+0x6d9d6122, 16);
3254 MD5STEP(F3
, b
, c
, d
, a
, in
[14]+0xfde5380c, 23);
3255 MD5STEP(F3
, a
, b
, c
, d
, in
[ 1]+0xa4beea44, 4);
3256 MD5STEP(F3
, d
, a
, b
, c
, in
[ 4]+0x4bdecfa9, 11);
3257 MD5STEP(F3
, c
, d
, a
, b
, in
[ 7]+0xf6bb4b60, 16);
3258 MD5STEP(F3
, b
, c
, d
, a
, in
[10]+0xbebfbc70, 23);
3259 MD5STEP(F3
, a
, b
, c
, d
, in
[13]+0x289b7ec6, 4);
3260 MD5STEP(F3
, d
, a
, b
, c
, in
[ 0]+0xeaa127fa, 11);
3261 MD5STEP(F3
, c
, d
, a
, b
, in
[ 3]+0xd4ef3085, 16);
3262 MD5STEP(F3
, b
, c
, d
, a
, in
[ 6]+0x04881d05, 23);
3263 MD5STEP(F3
, a
, b
, c
, d
, in
[ 9]+0xd9d4d039, 4);
3264 MD5STEP(F3
, d
, a
, b
, c
, in
[12]+0xe6db99e5, 11);
3265 MD5STEP(F3
, c
, d
, a
, b
, in
[15]+0x1fa27cf8, 16);
3266 MD5STEP(F3
, b
, c
, d
, a
, in
[ 2]+0xc4ac5665, 23);
3268 MD5STEP(F4
, a
, b
, c
, d
, in
[ 0]+0xf4292244, 6);
3269 MD5STEP(F4
, d
, a
, b
, c
, in
[ 7]+0x432aff97, 10);
3270 MD5STEP(F4
, c
, d
, a
, b
, in
[14]+0xab9423a7, 15);
3271 MD5STEP(F4
, b
, c
, d
, a
, in
[ 5]+0xfc93a039, 21);
3272 MD5STEP(F4
, a
, b
, c
, d
, in
[12]+0x655b59c3, 6);
3273 MD5STEP(F4
, d
, a
, b
, c
, in
[ 3]+0x8f0ccc92, 10);
3274 MD5STEP(F4
, c
, d
, a
, b
, in
[10]+0xffeff47d, 15);
3275 MD5STEP(F4
, b
, c
, d
, a
, in
[ 1]+0x85845dd1, 21);
3276 MD5STEP(F4
, a
, b
, c
, d
, in
[ 8]+0x6fa87e4f, 6);
3277 MD5STEP(F4
, d
, a
, b
, c
, in
[15]+0xfe2ce6e0, 10);
3278 MD5STEP(F4
, c
, d
, a
, b
, in
[ 6]+0xa3014314, 15);
3279 MD5STEP(F4
, b
, c
, d
, a
, in
[13]+0x4e0811a1, 21);
3280 MD5STEP(F4
, a
, b
, c
, d
, in
[ 4]+0xf7537e82, 6);
3281 MD5STEP(F4
, d
, a
, b
, c
, in
[11]+0xbd3af235, 10);
3282 MD5STEP(F4
, c
, d
, a
, b
, in
[ 2]+0x2ad7d2bb, 15);
3283 MD5STEP(F4
, b
, c
, d
, a
, in
[ 9]+0xeb86d391, 21);
3292 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3293 * initialization constants.
3295 static void MD5Init(MD5Context
*ctx
){
3297 ctx
->buf
[0] = 0x67452301;
3298 ctx
->buf
[1] = 0xefcdab89;
3299 ctx
->buf
[2] = 0x98badcfe;
3300 ctx
->buf
[3] = 0x10325476;
3306 * Update context to reflect the concatenation of another buffer full
3310 void MD5Update(MD5Context
*ctx
, const unsigned char *buf
, unsigned int len
){
3313 /* Update bitcount */
3316 if ((ctx
->bits
[0] = t
+ ((uint32
)len
<< 3)) < t
)
3317 ctx
->bits
[1]++; /* Carry from low to high */
3318 ctx
->bits
[1] += len
>> 29;
3320 t
= (t
>> 3) & 0x3f; /* Bytes already in shsInfo->data */
3322 /* Handle any leading odd-sized chunks */
3325 unsigned char *p
= (unsigned char *)ctx
->in
+ t
;
3329 memcpy(p
, buf
, len
);
3333 byteReverse(ctx
->in
, 16);
3334 MD5Transform(ctx
->buf
, (uint32
*)ctx
->in
);
3339 /* Process data in 64-byte chunks */
3342 memcpy(ctx
->in
, buf
, 64);
3343 byteReverse(ctx
->in
, 16);
3344 MD5Transform(ctx
->buf
, (uint32
*)ctx
->in
);
3349 /* Handle any remaining bytes of data. */
3351 memcpy(ctx
->in
, buf
, len
);
3355 * Final wrapup - pad to 64-byte boundary with the bit pattern
3356 * 1 0* (64-bit count of bits processed, MSB-first)
3358 static void MD5Final(unsigned char digest
[16], MD5Context
*ctx
){
3362 /* Compute number of bytes mod 64 */
3363 count
= (ctx
->bits
[0] >> 3) & 0x3F;
3365 /* Set the first char of padding to 0x80. This is safe since there is
3366 always at least one byte free */
3367 p
= ctx
->in
+ count
;
3370 /* Bytes of padding needed to make 64 bytes */
3371 count
= 64 - 1 - count
;
3373 /* Pad out to 56 mod 64 */
3375 /* Two lots of padding: Pad the first block to 64 bytes */
3376 memset(p
, 0, count
);
3377 byteReverse(ctx
->in
, 16);
3378 MD5Transform(ctx
->buf
, (uint32
*)ctx
->in
);
3380 /* Now fill the next block with 56 bytes */
3381 memset(ctx
->in
, 0, 56);
3383 /* Pad block to 56 bytes */
3384 memset(p
, 0, count
-8);
3386 byteReverse(ctx
->in
, 14);
3388 /* Append length in bits and transform */
3389 memcpy(ctx
->in
+ 14*4, ctx
->bits
, 8);
3391 MD5Transform(ctx
->buf
, (uint32
*)ctx
->in
);
3392 byteReverse((unsigned char *)ctx
->buf
, 4);
3393 memcpy(digest
, ctx
->buf
, 16);
3397 ** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3399 static void MD5DigestToBase16(unsigned char *digest
, char *zBuf
){
3400 static char const zEncode
[] = "0123456789abcdef";
3403 for(j
=i
=0; i
<16; i
++){
3405 zBuf
[j
++] = zEncode
[(a
>>4)&0xf];
3406 zBuf
[j
++] = zEncode
[a
& 0xf];
3413 ** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3414 ** each representing 16 bits of the digest and separated from each
3415 ** other by a "-" character.
3417 static void MD5DigestToBase10x8(unsigned char digest
[16], char zDigest
[50]){
3420 for(i
=j
=0; i
<16; i
+=2){
3421 x
= digest
[i
]*256 + digest
[i
+1];
3422 if( i
>0 ) zDigest
[j
++] = '-';
3423 sprintf(&zDigest
[j
], "%05u", x
);
3430 ** A TCL command for md5. The argument is the text to be hashed. The
3431 ** Result is the hash in base64.
3433 static int md5_cmd(void*cd
, Tcl_Interp
*interp
, int argc
, const char **argv
){
3435 unsigned char digest
[16];
3437 void (*converter
)(unsigned char*, char*);
3440 Tcl_AppendResult(interp
,"wrong # args: should be \"", argv
[0],
3441 " TEXT\"", (char*)0);
3445 MD5Update(&ctx
, (unsigned char*)argv
[1], (unsigned)strlen(argv
[1]));
3446 MD5Final(digest
, &ctx
);
3447 converter
= (void(*)(unsigned char*,char*))cd
;
3448 converter(digest
, zBuf
);
3449 Tcl_AppendResult(interp
, zBuf
, (char*)0);
3454 ** A TCL command to take the md5 hash of a file. The argument is the
3455 ** name of the file.
3457 static int md5file_cmd(void*cd
, Tcl_Interp
*interp
, int argc
, const char **argv
){
3460 void (*converter
)(unsigned char*, char*);
3461 unsigned char digest
[16];
3465 Tcl_AppendResult(interp
,"wrong # args: should be \"", argv
[0],
3466 " FILENAME\"", (char*)0);
3469 in
= fopen(argv
[1],"rb");
3471 Tcl_AppendResult(interp
,"unable to open file \"", argv
[1],
3472 "\" for reading", (char*)0);
3478 n
= (int)fread(zBuf
, 1, sizeof(zBuf
), in
);
3480 MD5Update(&ctx
, (unsigned char*)zBuf
, (unsigned)n
);
3483 MD5Final(digest
, &ctx
);
3484 converter
= (void(*)(unsigned char*,char*))cd
;
3485 converter(digest
, zBuf
);
3486 Tcl_AppendResult(interp
, zBuf
, (char*)0);
3491 ** Register the four new TCL commands for generating MD5 checksums
3492 ** with the TCL interpreter.
3494 int Md5_Init(Tcl_Interp
*interp
){
3495 Tcl_CreateCommand(interp
, "md5", (Tcl_CmdProc
*)md5_cmd
,
3496 MD5DigestToBase16
, 0);
3497 Tcl_CreateCommand(interp
, "md5-10x8", (Tcl_CmdProc
*)md5_cmd
,
3498 MD5DigestToBase10x8
, 0);
3499 Tcl_CreateCommand(interp
, "md5file", (Tcl_CmdProc
*)md5file_cmd
,
3500 MD5DigestToBase16
, 0);
3501 Tcl_CreateCommand(interp
, "md5file-10x8", (Tcl_CmdProc
*)md5file_cmd
,
3502 MD5DigestToBase10x8
, 0);
3505 #endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3507 #if defined(SQLITE_TEST)
3509 ** During testing, the special md5sum() aggregate function is available.
3510 ** inside SQLite. The following routines implement that function.
3512 static void md5step(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
){
3515 if( argc
<1 ) return;
3516 p
= sqlite3_aggregate_context(context
, sizeof(*p
));
3521 for(i
=0; i
<argc
; i
++){
3522 const char *zData
= (char*)sqlite3_value_text(argv
[i
]);
3524 MD5Update(p
, (unsigned char*)zData
, (int)strlen(zData
));
3528 static void md5finalize(sqlite3_context
*context
){
3530 unsigned char digest
[16];
3532 p
= sqlite3_aggregate_context(context
, sizeof(*p
));
3534 MD5DigestToBase16(digest
, zBuf
);
3535 sqlite3_result_text(context
, zBuf
, -1, SQLITE_TRANSIENT
);
3537 int Md5_Register(sqlite3
*db
){
3538 int rc
= sqlite3_create_function(db
, "md5sum", -1, SQLITE_UTF8
, 0, 0,
3539 md5step
, md5finalize
);
3540 sqlite3_overload_function(db
, "md5sum", -1); /* To exercise this API */
3543 #endif /* defined(SQLITE_TEST) */
3547 ** If the macro TCLSH is one, then put in code this for the
3548 ** "main" routine that will initialize Tcl and take input from
3549 ** standard input, or if a file is named on the command line
3550 ** the TCL interpreter reads and evaluates that file.
3553 static const char *tclsh_main_loop(void){
3554 static const char zMainloop
[] =
3556 "while {![eof stdin]} {\n"
3557 "if {$line!=\"\"} {\n"
3558 "puts -nonewline \"> \"\n"
3560 "puts -nonewline \"% \"\n"
3563 "append line [gets stdin]\n"
3564 "if {[info complete $line]} {\n"
3565 "if {[catch {uplevel #0 $line} result]} {\n"
3566 "puts stderr \"Error: $result\"\n"
3567 "} elseif {$result!=\"\"} {\n"
3580 static const char *tclsh_main_loop(void);
3584 static void init_all(Tcl_Interp
*);
3585 static int init_all_cmd(
3589 Tcl_Obj
*CONST objv
[]
3594 Tcl_WrongNumArgs(interp
, 1, objv
, "SLAVE");
3598 slave
= Tcl_GetSlave(interp
, Tcl_GetString(objv
[1]));
3608 ** Tclcmd: db_use_legacy_prepare DB BOOLEAN
3610 ** The first argument to this command must be a database command created by
3611 ** [sqlite3]. If the second argument is true, then the handle is configured
3612 ** to use the sqlite3_prepare_v2() function to prepare statements. If it
3613 ** is false, sqlite3_prepare().
3615 static int db_use_legacy_prepare_cmd(
3619 Tcl_Obj
*CONST objv
[]
3621 Tcl_CmdInfo cmdInfo
;
3626 Tcl_WrongNumArgs(interp
, 1, objv
, "DB BOOLEAN");
3630 if( !Tcl_GetCommandInfo(interp
, Tcl_GetString(objv
[1]), &cmdInfo
) ){
3631 Tcl_AppendResult(interp
, "no such db: ", Tcl_GetString(objv
[1]), (char*)0);
3634 pDb
= (SqliteDb
*)cmdInfo
.objClientData
;
3635 if( Tcl_GetBooleanFromObj(interp
, objv
[2], &bPrepare
) ){
3639 pDb
->bLegacyPrepare
= bPrepare
;
3641 Tcl_ResetResult(interp
);
3647 ** Configure the interpreter passed as the first argument to have access
3648 ** to the commands and linked variables that make up:
3650 ** * the [sqlite3] extension itself,
3652 ** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
3654 ** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
3657 static void init_all(Tcl_Interp
*interp
){
3658 Sqlite3_Init(interp
);
3660 #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3664 /* Install the [register_dbstat_vtab] command to access the implementation
3665 ** of virtual table dbstat (source file test_stat.c). This command is
3666 ** required for testfixture and sqlite3_analyzer, but not by the production
3667 ** Tcl extension. */
3668 #if defined(SQLITE_TEST) || TCLSH==2
3670 extern int SqlitetestStat_Init(Tcl_Interp
*);
3671 SqlitetestStat_Init(interp
);
3677 extern int Sqliteconfig_Init(Tcl_Interp
*);
3678 extern int Sqlitetest1_Init(Tcl_Interp
*);
3679 extern int Sqlitetest2_Init(Tcl_Interp
*);
3680 extern int Sqlitetest3_Init(Tcl_Interp
*);
3681 extern int Sqlitetest4_Init(Tcl_Interp
*);
3682 extern int Sqlitetest5_Init(Tcl_Interp
*);
3683 extern int Sqlitetest6_Init(Tcl_Interp
*);
3684 extern int Sqlitetest7_Init(Tcl_Interp
*);
3685 extern int Sqlitetest8_Init(Tcl_Interp
*);
3686 extern int Sqlitetest9_Init(Tcl_Interp
*);
3687 extern int Sqlitetestasync_Init(Tcl_Interp
*);
3688 extern int Sqlitetest_autoext_Init(Tcl_Interp
*);
3689 extern int Sqlitetest_demovfs_Init(Tcl_Interp
*);
3690 extern int Sqlitetest_func_Init(Tcl_Interp
*);
3691 extern int Sqlitetest_hexio_Init(Tcl_Interp
*);
3692 extern int Sqlitetest_init_Init(Tcl_Interp
*);
3693 extern int Sqlitetest_malloc_Init(Tcl_Interp
*);
3694 extern int Sqlitetest_mutex_Init(Tcl_Interp
*);
3695 extern int Sqlitetestschema_Init(Tcl_Interp
*);
3696 extern int Sqlitetestsse_Init(Tcl_Interp
*);
3697 extern int Sqlitetesttclvar_Init(Tcl_Interp
*);
3698 extern int Sqlitetestfs_Init(Tcl_Interp
*);
3699 extern int SqlitetestThread_Init(Tcl_Interp
*);
3700 extern int SqlitetestOnefile_Init();
3701 extern int SqlitetestOsinst_Init(Tcl_Interp
*);
3702 extern int Sqlitetestbackup_Init(Tcl_Interp
*);
3703 extern int Sqlitetestintarray_Init(Tcl_Interp
*);
3704 extern int Sqlitetestvfs_Init(Tcl_Interp
*);
3705 extern int Sqlitetestrtree_Init(Tcl_Interp
*);
3706 extern int Sqlitequota_Init(Tcl_Interp
*);
3707 extern int Sqlitemultiplex_Init(Tcl_Interp
*);
3708 extern int SqliteSuperlock_Init(Tcl_Interp
*);
3709 extern int SqlitetestSyscall_Init(Tcl_Interp
*);
3711 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
3712 extern int Sqlitetestfts3_Init(Tcl_Interp
*interp
);
3715 #ifdef SQLITE_ENABLE_ZIPVFS
3716 extern int Zipvfs_Init(Tcl_Interp
*);
3717 Zipvfs_Init(interp
);
3720 Sqliteconfig_Init(interp
);
3721 Sqlitetest1_Init(interp
);
3722 Sqlitetest2_Init(interp
);
3723 Sqlitetest3_Init(interp
);
3724 Sqlitetest4_Init(interp
);
3725 Sqlitetest5_Init(interp
);
3726 Sqlitetest6_Init(interp
);
3727 Sqlitetest7_Init(interp
);
3728 Sqlitetest8_Init(interp
);
3729 Sqlitetest9_Init(interp
);
3730 Sqlitetestasync_Init(interp
);
3731 Sqlitetest_autoext_Init(interp
);
3732 Sqlitetest_demovfs_Init(interp
);
3733 Sqlitetest_func_Init(interp
);
3734 Sqlitetest_hexio_Init(interp
);
3735 Sqlitetest_init_Init(interp
);
3736 Sqlitetest_malloc_Init(interp
);
3737 Sqlitetest_mutex_Init(interp
);
3738 Sqlitetestschema_Init(interp
);
3739 Sqlitetesttclvar_Init(interp
);
3740 Sqlitetestfs_Init(interp
);
3741 SqlitetestThread_Init(interp
);
3742 SqlitetestOnefile_Init(interp
);
3743 SqlitetestOsinst_Init(interp
);
3744 Sqlitetestbackup_Init(interp
);
3745 Sqlitetestintarray_Init(interp
);
3746 Sqlitetestvfs_Init(interp
);
3747 Sqlitetestrtree_Init(interp
);
3748 Sqlitequota_Init(interp
);
3749 Sqlitemultiplex_Init(interp
);
3750 SqliteSuperlock_Init(interp
);
3751 SqlitetestSyscall_Init(interp
);
3753 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
3754 Sqlitetestfts3_Init(interp
);
3757 Tcl_CreateObjCommand(
3758 interp
, "load_testfixture_extensions", init_all_cmd
, 0, 0
3760 Tcl_CreateObjCommand(
3761 interp
, "db_use_legacy_prepare", db_use_legacy_prepare_cmd
, 0, 0
3765 Sqlitetestsse_Init(interp
);
3771 #define TCLSH_MAIN main /* Needed to fake out mktclapp */
3772 int TCLSH_MAIN(int argc
, char **argv
){
3775 #if !defined(_WIN32_WCE)
3776 if( getenv("BREAK") ){
3778 "attach debugger to process %d and press any key to continue.\n",
3784 /* Call sqlite3_shutdown() once before doing anything else. This is to
3785 ** test that sqlite3_shutdown() can be safely called by a process before
3786 ** sqlite3_initialize() is. */
3789 Tcl_FindExecutable(argv
[0]);
3790 Tcl_SetSystemEncoding(NULL
, "utf-8");
3791 interp
= Tcl_CreateInterp();
3794 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD
);
3801 sqlite3_snprintf(sizeof(zArgc
), zArgc
, "%d", argc
-(3-TCLSH
));
3802 Tcl_SetVar(interp
,"argc", zArgc
, TCL_GLOBAL_ONLY
);
3803 Tcl_SetVar(interp
,"argv0",argv
[1],TCL_GLOBAL_ONLY
);
3804 Tcl_SetVar(interp
,"argv", "", TCL_GLOBAL_ONLY
);
3805 for(i
=3-TCLSH
; i
<argc
; i
++){
3806 Tcl_SetVar(interp
, "argv", argv
[i
],
3807 TCL_GLOBAL_ONLY
| TCL_LIST_ELEMENT
| TCL_APPEND_VALUE
);
3809 if( TCLSH
==1 && Tcl_EvalFile(interp
, argv
[1])!=TCL_OK
){
3810 const char *zInfo
= Tcl_GetVar(interp
, "errorInfo", TCL_GLOBAL_ONLY
);
3811 if( zInfo
==0 ) zInfo
= Tcl_GetStringResult(interp
);
3812 fprintf(stderr
,"%s: %s\n", *argv
, zInfo
);
3816 if( TCLSH
==2 || argc
<=1 ){
3817 Tcl_GlobalEval(interp
, tclsh_main_loop());