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 *************************************************************************
13 ** This file contains the implementation of some Tcl commands used to
14 ** test that sqlite3 database handles may be concurrently accessed by
15 ** multiple threads. Right now this only works on unix.
18 #include "sqliteInt.h"
19 #include "tclsqlite.h"
25 #if !defined(_MSC_VER)
30 ** One of these is allocated for each thread created by [sqlthread spawn].
32 typedef struct SqlThread SqlThread
;
34 Tcl_ThreadId parent
; /* Thread id of parent thread */
35 Tcl_Interp
*interp
; /* Parent interpreter */
36 char *zScript
; /* The script to execute. */
37 char *zVarname
; /* Varname in parent script */
41 ** A custom Tcl_Event type used by this module. When the event is
42 ** handled, script zScript is evaluated in interpreter interp. If
43 ** the evaluation throws an exception (returns TCL_ERROR), then the
44 ** error is handled by Tcl_BackgroundError(). If no error occurs,
45 ** the result is simply discarded.
47 typedef struct EvalEvent EvalEvent
;
49 Tcl_Event base
; /* Base class of type Tcl_Event */
50 char *zScript
; /* The script to execute. */
51 Tcl_Interp
*interp
; /* The interpreter to execute it in. */
54 static Tcl_ObjCmdProc sqlthread_proc
;
55 static Tcl_ObjCmdProc clock_seconds_proc
;
56 #if SQLITE_OS_UNIX && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
57 static Tcl_ObjCmdProc blocking_step_proc
;
58 static Tcl_ObjCmdProc blocking_prepare_v2_proc
;
60 int Sqlitetest1_Init(Tcl_Interp
*);
61 int Sqlite3_Init(Tcl_Interp
*);
63 /* Functions from main.c */
64 extern const char *sqlite3ErrName(int);
66 /* Functions from test1.c */
67 extern void *sqlite3TestTextToPtr(const char *);
68 extern int getDbPointer(Tcl_Interp
*, const char *, sqlite3
**);
69 extern int sqlite3TestMakePointerStr(Tcl_Interp
*, char *, void *);
70 extern int sqlite3TestErrCode(Tcl_Interp
*, sqlite3
*, int);
73 ** Handler for events of type EvalEvent.
75 static int SQLITE_TCLAPI
tclScriptEvent(Tcl_Event
*evPtr
, int flags
){
77 EvalEvent
*p
= (EvalEvent
*)evPtr
;
78 rc
= Tcl_Eval(p
->interp
, p
->zScript
);
80 Tcl_BackgroundError(p
->interp
);
82 UNUSED_PARAMETER(flags
);
87 ** Register an EvalEvent to evaluate the script pScript in the
88 ** parent interpreter/thread of SqlThread p.
90 static void postToParent(SqlThread
*p
, Tcl_Obj
*pScript
){
95 zMsg
= Tcl_GetStringFromObj(pScript
, &nMsg
);
96 pEvent
= (EvalEvent
*)ckalloc(sizeof(EvalEvent
)+nMsg
+1);
97 pEvent
->base
.nextPtr
= 0;
98 pEvent
->base
.proc
= tclScriptEvent
;
99 pEvent
->zScript
= (char *)&pEvent
[1];
100 memcpy(pEvent
->zScript
, zMsg
, nMsg
+1);
101 pEvent
->interp
= p
->interp
;
103 Tcl_ThreadQueueEvent(p
->parent
, (Tcl_Event
*)pEvent
, TCL_QUEUE_TAIL
);
104 Tcl_ThreadAlert(p
->parent
);
108 ** The main function for threads created with [sqlthread spawn].
110 static Tcl_ThreadCreateType
tclScriptThread(ClientData pSqlThread
){
115 SqlThread
*p
= (SqlThread
*)pSqlThread
;
116 extern int Sqlitetest_mutex_Init(Tcl_Interp
*);
118 interp
= Tcl_CreateInterp();
119 Tcl_CreateObjCommand(interp
, "clock_seconds", clock_seconds_proc
, 0, 0);
120 Tcl_CreateObjCommand(interp
, "sqlthread", sqlthread_proc
, pSqlThread
, 0);
121 #if SQLITE_OS_UNIX && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
122 Tcl_CreateObjCommand(interp
, "sqlite3_blocking_step", blocking_step_proc
,0,0);
123 Tcl_CreateObjCommand(interp
,
124 "sqlite3_blocking_prepare_v2", blocking_prepare_v2_proc
, (void *)1, 0);
125 Tcl_CreateObjCommand(interp
,
126 "sqlite3_nonblocking_prepare_v2", blocking_prepare_v2_proc
, 0, 0);
128 Sqlitetest1_Init(interp
);
129 Sqlitetest_mutex_Init(interp
);
130 Sqlite3_Init(interp
);
132 rc
= Tcl_Eval(interp
, p
->zScript
);
133 pRes
= Tcl_GetObjResult(interp
);
134 pList
= Tcl_NewObj();
135 Tcl_IncrRefCount(pList
);
136 Tcl_IncrRefCount(pRes
);
139 Tcl_ListObjAppendElement(interp
, pList
, Tcl_NewStringObj("error", -1));
140 Tcl_ListObjAppendElement(interp
, pList
, pRes
);
141 postToParent(p
, pList
);
142 Tcl_DecrRefCount(pList
);
143 pList
= Tcl_NewObj();
146 Tcl_ListObjAppendElement(interp
, pList
, Tcl_NewStringObj("set", -1));
147 Tcl_ListObjAppendElement(interp
, pList
, Tcl_NewStringObj(p
->zVarname
, -1));
148 Tcl_ListObjAppendElement(interp
, pList
, pRes
);
149 postToParent(p
, pList
);
152 Tcl_DecrRefCount(pList
);
153 Tcl_DecrRefCount(pRes
);
154 Tcl_DeleteInterp(interp
);
155 while( Tcl_DoOneEvent(TCL_ALL_EVENTS
|TCL_DONT_WAIT
) );
157 TCL_THREAD_CREATE_RETURN
;
161 ** sqlthread spawn VARNAME SCRIPT
163 ** Spawn a new thread with its own Tcl interpreter and run the
164 ** specified SCRIPT(s) in it. The thread terminates after running
165 ** the script. The result of the script is stored in the variable
168 ** The caller can wait for the script to terminate using [vwait VARNAME].
170 static int SQLITE_TCLAPI
sqlthread_spawn(
171 ClientData clientData
,
174 Tcl_Obj
*CONST objv
[]
180 Tcl_Size nVarname
; char *zVarname
;
181 Tcl_Size nScript
; char *zScript
;
183 /* Parameters for thread creation */
184 const int nStack
= TCL_THREAD_STACK_DEFAULT
;
185 const int flags
= TCL_THREAD_NOFLAGS
;
188 UNUSED_PARAMETER(clientData
);
189 UNUSED_PARAMETER(objc
);
191 zVarname
= Tcl_GetStringFromObj(objv
[2], &nVarname
);
192 zScript
= Tcl_GetStringFromObj(objv
[3], &nScript
);
194 pNew
= (SqlThread
*)ckalloc(sizeof(SqlThread
)+nVarname
+nScript
+2);
195 pNew
->zVarname
= (char *)&pNew
[1];
196 pNew
->zScript
= (char *)&pNew
->zVarname
[nVarname
+1];
197 memcpy(pNew
->zVarname
, zVarname
, nVarname
+1);
198 memcpy(pNew
->zScript
, zScript
, nScript
+1);
199 pNew
->parent
= Tcl_GetCurrentThread();
200 pNew
->interp
= interp
;
202 rc
= Tcl_CreateThread(&x
, tclScriptThread
, (void *)pNew
, nStack
, flags
);
204 Tcl_AppendResult(interp
, "Error in Tcl_CreateThread()", 0);
205 ckfree((char *)pNew
);
213 ** sqlthread parent SCRIPT
215 ** This can be called by spawned threads only. It sends the specified
216 ** script back to the parent thread for execution. The result of
217 ** evaluating the SCRIPT is returned. The parent thread must enter
218 ** the event loop for this to work - otherwise the caller will
219 ** block indefinitely.
221 ** NOTE: At the moment, this doesn't work. FIXME.
223 static int SQLITE_TCLAPI
sqlthread_parent(
224 ClientData clientData
,
227 Tcl_Obj
*CONST objv
[]
232 SqlThread
*p
= (SqlThread
*)clientData
;
235 UNUSED_PARAMETER(objc
);
238 Tcl_AppendResult(interp
, "no parent thread", 0);
242 zMsg
= Tcl_GetStringFromObj(objv
[2], &nMsg
);
243 pEvent
= (EvalEvent
*)ckalloc(sizeof(EvalEvent
)+nMsg
+1);
244 pEvent
->base
.nextPtr
= 0;
245 pEvent
->base
.proc
= tclScriptEvent
;
246 pEvent
->zScript
= (char *)&pEvent
[1];
247 memcpy(pEvent
->zScript
, zMsg
, nMsg
+1);
248 pEvent
->interp
= p
->interp
;
249 Tcl_ThreadQueueEvent(p
->parent
, (Tcl_Event
*)pEvent
, TCL_QUEUE_TAIL
);
250 Tcl_ThreadAlert(p
->parent
);
255 static int xBusy(void *pArg
, int nBusy
){
256 UNUSED_PARAMETER(pArg
);
257 UNUSED_PARAMETER(nBusy
);
259 return 1; /* Try again... */
265 ** Open a database handle and return the string representation of
266 ** the pointer value.
268 static int SQLITE_TCLAPI
sqlthread_open(
269 ClientData clientData
,
272 Tcl_Obj
*CONST objv
[]
274 int sqlite3TestMakePointerStr(Tcl_Interp
*interp
, char *zPtr
, void *p
);
276 const char *zFilename
;
279 extern int Md5_Register(sqlite3
*,char**,const sqlite3_api_routines
*);
281 UNUSED_PARAMETER(clientData
);
282 UNUSED_PARAMETER(objc
);
284 zFilename
= Tcl_GetString(objv
[2]);
285 sqlite3_open(zFilename
, &db
);
286 Md5_Register(db
, 0, 0);
287 sqlite3_busy_handler(db
, xBusy
, 0);
289 if( sqlite3TestMakePointerStr(interp
, zBuf
, db
) ) return TCL_ERROR
;
290 Tcl_AppendResult(interp
, zBuf
, 0);
299 ** Return the current thread-id (Tcl_GetCurrentThread()) cast to
302 static int SQLITE_TCLAPI
sqlthread_id(
303 ClientData clientData
,
306 Tcl_Obj
*CONST objv
[]
308 Tcl_ThreadId id
= Tcl_GetCurrentThread();
309 Tcl_SetObjResult(interp
, Tcl_NewIntObj(SQLITE_PTR_TO_INT(id
)));
310 UNUSED_PARAMETER(clientData
);
311 UNUSED_PARAMETER(objc
);
312 UNUSED_PARAMETER(objv
);
318 ** Dispatch routine for the sub-commands of [sqlthread].
320 static int SQLITE_TCLAPI
sqlthread_proc(
321 ClientData clientData
,
324 Tcl_Obj
*CONST objv
[]
328 Tcl_ObjCmdProc
*xProc
;
332 {"parent", sqlthread_parent
, 1, "SCRIPT"},
333 {"spawn", sqlthread_spawn
, 2, "VARNAME SCRIPT"},
334 {"open", sqlthread_open
, 1, "DBNAME"},
335 {"id", sqlthread_id
, 0, ""},
338 struct SubCommand
*pSub
;
343 Tcl_WrongNumArgs(interp
, 1, objv
, "SUB-COMMAND");
347 rc
= Tcl_GetIndexFromObjStruct(
348 interp
, objv
[1], aSub
, sizeof(aSub
[0]), "sub-command", 0, &iIndex
350 if( rc
!=TCL_OK
) return rc
;
351 pSub
= &aSub
[iIndex
];
353 if( objc
<(pSub
->nArg
+2) ){
354 Tcl_WrongNumArgs(interp
, 2, objv
, pSub
->zUsage
);
358 return pSub
->xProc(clientData
, interp
, objc
, objv
);
362 ** The [clock_seconds] command. This is more or less the same as the
363 ** regular tcl [clock seconds], except that it is available in testfixture
364 ** when linked against both Tcl 8.4 and 8.5. Because [clock seconds] is
365 ** implemented as a script in Tcl 8.5, it is not usually available to
368 static int SQLITE_TCLAPI
clock_seconds_proc(
369 ClientData clientData
,
372 Tcl_Obj
*CONST objv
[]
376 Tcl_SetObjResult(interp
, Tcl_NewIntObj(now
.sec
));
377 UNUSED_PARAMETER(clientData
);
378 UNUSED_PARAMETER(objc
);
379 UNUSED_PARAMETER(objv
);
384 ** The [clock_milliseconds] command. This is more or less the same as the
385 ** regular tcl [clock milliseconds].
387 static int SQLITE_TCLAPI
clock_milliseconds_proc(
388 ClientData clientData
,
391 Tcl_Obj
*CONST objv
[]
395 Tcl_SetObjResult(interp
, Tcl_NewWideIntObj(
396 ((Tcl_WideInt
)now
.sec
* 1000) + (now
.usec
/ 1000)
398 UNUSED_PARAMETER(clientData
);
399 UNUSED_PARAMETER(objc
);
400 UNUSED_PARAMETER(objv
);
404 /*************************************************************************
405 ** This block contains the implementation of the [sqlite3_blocking_step]
406 ** command available to threads created by [sqlthread spawn] commands. It
407 ** is only available on UNIX for now. This is because pthread condition
408 ** variables are used.
410 ** The source code for the C functions sqlite3_blocking_step(),
411 ** blocking_step_notify() and the structure UnlockNotification is
412 ** automatically extracted from this file and used as part of the
413 ** documentation for the sqlite3_unlock_notify() API function. This
414 ** should be considered if these functions are to be extended (i.e. to
415 ** support windows) in the future.
417 #if SQLITE_OS_UNIX && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
419 /* BEGIN_SQLITE_BLOCKING_STEP */
420 /* This example uses the pthreads API */
424 ** A pointer to an instance of this structure is passed as the user-context
425 ** pointer when registering for an unlock-notify callback.
427 typedef struct UnlockNotification UnlockNotification
;
428 struct UnlockNotification
{
429 int fired
; /* True after unlock event has occurred */
430 pthread_cond_t cond
; /* Condition variable to wait on */
431 pthread_mutex_t mutex
; /* Mutex to protect structure */
435 ** This function is an unlock-notify callback registered with SQLite.
437 static void unlock_notify_cb(void **apArg
, int nArg
){
439 for(i
=0; i
<nArg
; i
++){
440 UnlockNotification
*p
= (UnlockNotification
*)apArg
[i
];
441 pthread_mutex_lock(&p
->mutex
);
443 pthread_cond_signal(&p
->cond
);
444 pthread_mutex_unlock(&p
->mutex
);
449 ** This function assumes that an SQLite API call (either sqlite3_prepare_v2()
450 ** or sqlite3_step()) has just returned SQLITE_LOCKED. The argument is the
451 ** associated database connection.
453 ** This function calls sqlite3_unlock_notify() to register for an
454 ** unlock-notify callback, then blocks until that callback is delivered
455 ** and returns SQLITE_OK. The caller should then retry the failed operation.
457 ** Or, if sqlite3_unlock_notify() indicates that to block would deadlock
458 ** the system, then this function returns SQLITE_LOCKED immediately. In
459 ** this case the caller should not retry the operation and should roll
460 ** back the current transaction (if any).
462 static int wait_for_unlock_notify(sqlite3
*db
){
464 UnlockNotification un
;
466 /* Initialize the UnlockNotification structure. */
468 pthread_mutex_init(&un
.mutex
, 0);
469 pthread_cond_init(&un
.cond
, 0);
471 /* Register for an unlock-notify callback. */
472 rc
= sqlite3_unlock_notify(db
, unlock_notify_cb
, (void *)&un
);
473 assert( rc
==SQLITE_LOCKED
|| rc
==SQLITE_OK
);
475 /* The call to sqlite3_unlock_notify() always returns either SQLITE_LOCKED
478 ** If SQLITE_LOCKED was returned, then the system is deadlocked. In this
479 ** case this function needs to return SQLITE_LOCKED to the caller so
480 ** that the current transaction can be rolled back. Otherwise, block
481 ** until the unlock-notify callback is invoked, then return SQLITE_OK.
484 pthread_mutex_lock(&un
.mutex
);
486 pthread_cond_wait(&un
.cond
, &un
.mutex
);
488 pthread_mutex_unlock(&un
.mutex
);
491 /* Destroy the mutex and condition variables. */
492 pthread_cond_destroy(&un
.cond
);
493 pthread_mutex_destroy(&un
.mutex
);
499 ** This function is a wrapper around the SQLite function sqlite3_step().
500 ** It functions in the same way as step(), except that if a required
501 ** shared-cache lock cannot be obtained, this function may block waiting for
502 ** the lock to become available. In this scenario the normal API step()
503 ** function always returns SQLITE_LOCKED.
505 ** If this function returns SQLITE_LOCKED, the caller should rollback
506 ** the current transaction (if any) and try again later. Otherwise, the
507 ** system may become deadlocked.
509 int sqlite3_blocking_step(sqlite3_stmt
*pStmt
){
511 while( SQLITE_LOCKED
==(rc
= sqlite3_step(pStmt
)) ){
512 rc
= wait_for_unlock_notify(sqlite3_db_handle(pStmt
));
513 if( rc
!=SQLITE_OK
) break;
514 sqlite3_reset(pStmt
);
520 ** This function is a wrapper around the SQLite function sqlite3_prepare_v2().
521 ** It functions in the same way as prepare_v2(), except that if a required
522 ** shared-cache lock cannot be obtained, this function may block waiting for
523 ** the lock to become available. In this scenario the normal API prepare_v2()
524 ** function always returns SQLITE_LOCKED.
526 ** If this function returns SQLITE_LOCKED, the caller should rollback
527 ** the current transaction (if any) and try again later. Otherwise, the
528 ** system may become deadlocked.
530 int sqlite3_blocking_prepare_v2(
531 sqlite3
*db
, /* Database handle. */
532 const char *zSql
, /* UTF-8 encoded SQL statement. */
533 int nSql
, /* Length of zSql in bytes. */
534 sqlite3_stmt
**ppStmt
, /* OUT: A pointer to the prepared statement */
535 const char **pz
/* OUT: End of parsed string */
538 while( SQLITE_LOCKED
==(rc
= sqlite3_prepare_v2(db
, zSql
, nSql
, ppStmt
, pz
)) ){
539 rc
= wait_for_unlock_notify(db
);
540 if( rc
!=SQLITE_OK
) break;
544 /* END_SQLITE_BLOCKING_STEP */
547 ** Usage: sqlite3_blocking_step STMT
549 ** Advance the statement to the next row.
551 static int SQLITE_TCLAPI
blocking_step_proc(
555 Tcl_Obj
*CONST objv
[]
562 Tcl_WrongNumArgs(interp
, 1, objv
, "STMT");
566 pStmt
= (sqlite3_stmt
*)sqlite3TestTextToPtr(Tcl_GetString(objv
[1]));
567 rc
= sqlite3_blocking_step(pStmt
);
569 Tcl_SetResult(interp
, (char *)sqlite3ErrName(rc
), 0);
574 ** Usage: sqlite3_blocking_prepare_v2 DB sql bytes ?tailvar?
575 ** Usage: sqlite3_nonblocking_prepare_v2 DB sql bytes ?tailvar?
577 static int SQLITE_TCLAPI
blocking_prepare_v2_proc(
581 Tcl_Obj
*CONST objv
[]
586 const char *zTail
= 0;
587 sqlite3_stmt
*pStmt
= 0;
590 int isBlocking
= !(clientData
==0);
592 if( objc
!=5 && objc
!=4 ){
593 Tcl_AppendResult(interp
, "wrong # args: should be \"",
594 Tcl_GetString(objv
[0]), " DB sql bytes tailvar", 0);
597 if( getDbPointer(interp
, Tcl_GetString(objv
[1]), &db
) ) return TCL_ERROR
;
598 zSql
= Tcl_GetString(objv
[2]);
599 if( Tcl_GetIntFromObj(interp
, objv
[3], &bytes
) ) return TCL_ERROR
;
602 rc
= sqlite3_blocking_prepare_v2(db
, zSql
, bytes
, &pStmt
, &zTail
);
604 rc
= sqlite3_prepare_v2(db
, zSql
, bytes
, &pStmt
, &zTail
);
607 assert(rc
==SQLITE_OK
|| pStmt
==0);
608 if( zTail
&& objc
>=5 ){
610 bytes
= bytes
- (zTail
-zSql
);
612 Tcl_ObjSetVar2(interp
, objv
[4], 0, Tcl_NewStringObj(zTail
, bytes
), 0);
616 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%s ", (char *)sqlite3ErrName(rc
));
617 Tcl_AppendResult(interp
, zBuf
, sqlite3_errmsg(db
), 0);
622 if( sqlite3TestMakePointerStr(interp
, zBuf
, pStmt
) ) return TCL_ERROR
;
623 Tcl_AppendResult(interp
, zBuf
, 0);
628 #endif /* SQLITE_OS_UNIX && SQLITE_ENABLE_UNLOCK_NOTIFY */
630 ** End of implementation of [sqlite3_blocking_step].
631 ************************************************************************/
634 ** Register commands with the TCL interpreter.
636 int SqlitetestThread_Init(Tcl_Interp
*interp
){
638 int (*xProc
)(void*, Tcl_Interp
*, int, Tcl_Obj
*const*);
642 { sqlthread_proc
, "sqlthread", 0 },
643 { clock_seconds_proc
, "clock_second", 0 },
644 { clock_milliseconds_proc
, "clock_milliseconds", 0 },
645 #if SQLITE_OS_UNIX && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
646 { blocking_step_proc
, "sqlite3_blocking_step", 0 },
647 { blocking_prepare_v2_proc
, "sqlite3_blocking_prepare_v2", 1 },
648 { blocking_prepare_v2_proc
, "sqlite3_nonblocking_prepare_v2", 0 },
653 for(ii
=0; ii
<sizeof(aCmd
)/sizeof(aCmd
[0]); ii
++){
654 void *p
= SQLITE_INT_TO_PTR(aCmd
[ii
].iCtx
);
655 Tcl_CreateObjCommand(interp
, aCmd
[ii
].zName
, aCmd
[ii
].xProc
, p
, 0);
660 int SqlitetestThread_Init(Tcl_Interp
*interp
){