New #ifdefs to omit code that is unused when SQLITE_USE_LONG DOUBLE is defined.
[sqlite.git] / src / tclsqlite.c
blob0c8888fd48d33d3ef0a444aca2eee880f959c0d6
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** A TCL Interface to SQLite. Append this file to sqlite3.c and
13 ** compile the whole thing to build a TCL-enabled version of SQLite.
15 ** Compile-time options:
17 ** -DTCLSH Add a "main()" routine that works as a tclsh.
19 ** -DTCLSH_INIT_PROC=name
21 ** Invoke name(interp) to initialize the Tcl interpreter.
22 ** If name(interp) returns a non-NULL string, then run
23 ** that string as a Tcl script to launch the application.
24 ** If name(interp) returns NULL, then run the regular
25 ** tclsh-emulator code.
27 #ifdef TCLSH_INIT_PROC
28 # define TCLSH 1
29 #endif
32 ** If requested, include the SQLite compiler options file for MSVC.
34 #if defined(INCLUDE_MSVC_H)
35 # include "msvc.h"
36 #endif
38 /****** Copy of tclsqlite.h ******/
39 #if defined(INCLUDE_SQLITE_TCL_H)
40 # include "sqlite_tcl.h" /* Special case for Windows using STDCALL */
41 #else
42 # include <tcl.h> /* All normal cases */
43 # ifndef SQLITE_TCLAPI
44 # define SQLITE_TCLAPI
45 # endif
46 #endif
47 /* Compatability between Tcl8.6 and Tcl9.0 */
48 #if TCL_MAJOR_VERSION==9
49 # define CONST const
50 #else
51 typedef int Tcl_Size;
52 #endif
53 /**** End copy of tclsqlite.h ****/
55 #include <errno.h>
58 ** Some additional include files are needed if this file is not
59 ** appended to the amalgamation.
61 #ifndef SQLITE_AMALGAMATION
62 # include "sqlite3.h"
63 # include <stdlib.h>
64 # include <string.h>
65 # include <assert.h>
66 typedef unsigned char u8;
67 # ifndef SQLITE_PTRSIZE
68 # if defined(__SIZEOF_POINTER__)
69 # define SQLITE_PTRSIZE __SIZEOF_POINTER__
70 # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
71 defined(_M_ARM) || defined(__arm__) || defined(__x86) || \
72 (defined(__APPLE__) && defined(__POWERPC__)) || \
73 (defined(__TOS_AIX__) && !defined(__64BIT__))
74 # define SQLITE_PTRSIZE 4
75 # else
76 # define SQLITE_PTRSIZE 8
77 # endif
78 # endif /* SQLITE_PTRSIZE */
79 # if defined(HAVE_STDINT_H)
80 typedef uintptr_t uptr;
81 # elif SQLITE_PTRSIZE==4
82 typedef unsigned int uptr;
83 # else
84 typedef sqlite3_uint64 uptr;
85 # endif
86 #endif
87 #include <ctype.h>
89 /* Used to get the current process ID */
90 #if !defined(_WIN32)
91 # include <signal.h>
92 # include <unistd.h>
93 # define GETPID getpid
94 #elif !defined(_WIN32_WCE)
95 # ifndef SQLITE_AMALGAMATION
96 # ifndef WIN32_LEAN_AND_MEAN
97 # define WIN32_LEAN_AND_MEAN
98 # endif
99 # include <windows.h>
100 # endif
101 # include <io.h>
102 # define isatty(h) _isatty(h)
103 # define GETPID (int)GetCurrentProcessId
104 #endif
107 * Windows needs to know which symbols to export. Unix does not.
108 * BUILD_sqlite should be undefined for Unix.
110 #ifdef BUILD_sqlite
111 #undef TCL_STORAGE_CLASS
112 #define TCL_STORAGE_CLASS DLLEXPORT
113 #endif /* BUILD_sqlite */
115 #define NUM_PREPARED_STMTS 10
116 #define MAX_PREPARED_STMTS 100
118 /* Forward declaration */
119 typedef struct SqliteDb SqliteDb;
122 ** New SQL functions can be created as TCL scripts. Each such function
123 ** is described by an instance of the following structure.
125 ** Variable eType may be set to SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT,
126 ** SQLITE_BLOB or SQLITE_NULL. If it is SQLITE_NULL, then the implementation
127 ** attempts to determine the type of the result based on the Tcl object.
128 ** If it is SQLITE_TEXT or SQLITE_BLOB, then a text (sqlite3_result_text())
129 ** or blob (sqlite3_result_blob()) is returned. If it is SQLITE_INTEGER
130 ** or SQLITE_FLOAT, then an attempt is made to return an integer or float
131 ** value, falling back to float and then text if this is not possible.
133 typedef struct SqlFunc SqlFunc;
134 struct SqlFunc {
135 Tcl_Interp *interp; /* The TCL interpret to execute the function */
136 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
137 SqliteDb *pDb; /* Database connection that owns this function */
138 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
139 int eType; /* Type of value to return */
140 char *zName; /* Name of this function */
141 SqlFunc *pNext; /* Next function on the list of them all */
145 ** New collation sequences function can be created as TCL scripts. Each such
146 ** function is described by an instance of the following structure.
148 typedef struct SqlCollate SqlCollate;
149 struct SqlCollate {
150 Tcl_Interp *interp; /* The TCL interpret to execute the function */
151 char *zScript; /* The script to be run */
152 SqlCollate *pNext; /* Next function on the list of them all */
156 ** Prepared statements are cached for faster execution. Each prepared
157 ** statement is described by an instance of the following structure.
159 typedef struct SqlPreparedStmt SqlPreparedStmt;
160 struct SqlPreparedStmt {
161 SqlPreparedStmt *pNext; /* Next in linked list */
162 SqlPreparedStmt *pPrev; /* Previous on the list */
163 sqlite3_stmt *pStmt; /* The prepared statement */
164 int nSql; /* chars in zSql[] */
165 const char *zSql; /* Text of the SQL statement */
166 int nParm; /* Size of apParm array */
167 Tcl_Obj **apParm; /* Array of referenced object pointers */
170 typedef struct IncrblobChannel IncrblobChannel;
173 ** There is one instance of this structure for each SQLite database
174 ** that has been opened by the SQLite TCL interface.
176 ** If this module is built with SQLITE_TEST defined (to create the SQLite
177 ** testfixture executable), then it may be configured to use either
178 ** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
179 ** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
181 struct SqliteDb {
182 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
183 Tcl_Interp *interp; /* The interpreter used for this database */
184 char *zBusy; /* The busy callback routine */
185 char *zCommit; /* The commit hook callback routine */
186 char *zTrace; /* The trace callback routine */
187 char *zTraceV2; /* The trace_v2 callback routine */
188 char *zProfile; /* The profile callback routine */
189 char *zProgress; /* The progress callback routine */
190 char *zBindFallback; /* Callback to invoke on a binding miss */
191 char *zAuth; /* The authorization callback routine */
192 int disableAuth; /* Disable the authorizer if it exists */
193 char *zNull; /* Text to substitute for an SQL NULL value */
194 SqlFunc *pFunc; /* List of SQL functions */
195 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
196 Tcl_Obj *pPreUpdateHook; /* Pre-update hook script (if any) */
197 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
198 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
199 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
200 SqlCollate *pCollate; /* List of SQL collation functions */
201 int rc; /* Return code of most recent sqlite3_exec() */
202 Tcl_Obj *pCollateNeeded; /* Collation needed script */
203 SqlPreparedStmt *stmtList; /* List of prepared statements*/
204 SqlPreparedStmt *stmtLast; /* Last statement in the list */
205 int maxStmt; /* The next maximum number of stmtList */
206 int nStmt; /* Number of statements in stmtList */
207 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
208 int nStep, nSort, nIndex; /* Statistics for most recent operation */
209 int nVMStep; /* Another statistic for most recent operation */
210 int nTransaction; /* Number of nested [transaction] methods */
211 int openFlags; /* Flags used to open. (SQLITE_OPEN_URI) */
212 int nRef; /* Delete object when this reaches 0 */
213 #ifdef SQLITE_TEST
214 int bLegacyPrepare; /* True to use sqlite3_prepare() */
215 #endif
218 struct IncrblobChannel {
219 sqlite3_blob *pBlob; /* sqlite3 blob handle */
220 SqliteDb *pDb; /* Associated database connection */
221 sqlite3_int64 iSeek; /* Current seek offset */
222 unsigned int isClosed; /* TCL_CLOSE_READ or TCL_CLOSE_WRITE */
223 Tcl_Channel channel; /* Channel identifier */
224 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
225 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
229 ** Compute a string length that is limited to what can be stored in
230 ** lower 30 bits of a 32-bit signed integer.
232 static int strlen30(const char *z){
233 const char *z2 = z;
234 while( *z2 ){ z2++; }
235 return 0x3fffffff & (int)(z2 - z);
239 #ifndef SQLITE_OMIT_INCRBLOB
241 ** Close all incrblob channels opened using database connection pDb.
242 ** This is called when shutting down the database connection.
244 static void closeIncrblobChannels(SqliteDb *pDb){
245 IncrblobChannel *p;
246 IncrblobChannel *pNext;
248 for(p=pDb->pIncrblob; p; p=pNext){
249 pNext = p->pNext;
251 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
252 ** which deletes the IncrblobChannel structure at *p. So do not
253 ** call Tcl_Free() here.
255 Tcl_UnregisterChannel(pDb->interp, p->channel);
260 ** Close an incremental blob channel.
262 static int SQLITE_TCLAPI incrblobClose2(
263 ClientData instanceData,
264 Tcl_Interp *interp,
265 int flags
267 IncrblobChannel *p = (IncrblobChannel *)instanceData;
268 int rc;
269 sqlite3 *db = p->pDb->db;
271 if( flags ){
272 p->isClosed |= flags;
273 return TCL_OK;
276 /* If we reach this point, then we really do need to close the channel */
277 rc = sqlite3_blob_close(p->pBlob);
279 /* Remove the channel from the SqliteDb.pIncrblob list. */
280 if( p->pNext ){
281 p->pNext->pPrev = p->pPrev;
283 if( p->pPrev ){
284 p->pPrev->pNext = p->pNext;
286 if( p->pDb->pIncrblob==p ){
287 p->pDb->pIncrblob = p->pNext;
290 /* Free the IncrblobChannel structure */
291 Tcl_Free((char *)p);
293 if( rc!=SQLITE_OK ){
294 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
295 return TCL_ERROR;
297 return TCL_OK;
299 static int SQLITE_TCLAPI incrblobClose(
300 ClientData instanceData,
301 Tcl_Interp *interp
303 return incrblobClose2(instanceData, interp, 0);
308 ** Read data from an incremental blob channel.
310 static int SQLITE_TCLAPI incrblobInput(
311 ClientData instanceData,
312 char *buf,
313 int bufSize,
314 int *errorCodePtr
316 IncrblobChannel *p = (IncrblobChannel *)instanceData;
317 sqlite3_int64 nRead = bufSize; /* Number of bytes to read */
318 sqlite3_int64 nBlob; /* Total size of the blob */
319 int rc; /* sqlite error code */
321 nBlob = sqlite3_blob_bytes(p->pBlob);
322 if( (p->iSeek+nRead)>nBlob ){
323 nRead = nBlob-p->iSeek;
325 if( nRead<=0 ){
326 return 0;
329 rc = sqlite3_blob_read(p->pBlob, (void *)buf, (int)nRead, (int)p->iSeek);
330 if( rc!=SQLITE_OK ){
331 *errorCodePtr = rc;
332 return -1;
335 p->iSeek += nRead;
336 return nRead;
340 ** Write data to an incremental blob channel.
342 static int SQLITE_TCLAPI incrblobOutput(
343 ClientData instanceData,
344 CONST char *buf,
345 int toWrite,
346 int *errorCodePtr
348 IncrblobChannel *p = (IncrblobChannel *)instanceData;
349 sqlite3_int64 nWrite = toWrite; /* Number of bytes to write */
350 sqlite3_int64 nBlob; /* Total size of the blob */
351 int rc; /* sqlite error code */
353 nBlob = sqlite3_blob_bytes(p->pBlob);
354 if( (p->iSeek+nWrite)>nBlob ){
355 *errorCodePtr = EINVAL;
356 return -1;
358 if( nWrite<=0 ){
359 return 0;
362 rc = sqlite3_blob_write(p->pBlob, (void*)buf,(int)nWrite, (int)p->iSeek);
363 if( rc!=SQLITE_OK ){
364 *errorCodePtr = EIO;
365 return -1;
368 p->iSeek += nWrite;
369 return nWrite;
372 /* The datatype of Tcl_DriverWideSeekProc changes between tcl8.6 and tcl9.0 */
373 #if TCL_MAJOR_VERSION==9
374 # define WideSeekProcType long long
375 #else
376 # define WideSeekProcType Tcl_WideInt
377 #endif
380 ** Seek an incremental blob channel.
382 static WideSeekProcType SQLITE_TCLAPI incrblobWideSeek(
383 ClientData instanceData,
384 WideSeekProcType offset,
385 int seekMode,
386 int *errorCodePtr
388 IncrblobChannel *p = (IncrblobChannel *)instanceData;
390 switch( seekMode ){
391 case SEEK_SET:
392 p->iSeek = offset;
393 break;
394 case SEEK_CUR:
395 p->iSeek += offset;
396 break;
397 case SEEK_END:
398 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
399 break;
401 default: assert(!"Bad seekMode");
404 return p->iSeek;
406 static int SQLITE_TCLAPI incrblobSeek(
407 ClientData instanceData,
408 long offset,
409 int seekMode,
410 int *errorCodePtr
412 return incrblobWideSeek(instanceData,offset,seekMode,errorCodePtr);
416 static void SQLITE_TCLAPI incrblobWatch(
417 ClientData instanceData,
418 int mode
420 /* NO-OP */
422 static int SQLITE_TCLAPI incrblobHandle(
423 ClientData instanceData,
424 int dir,
425 ClientData *hPtr
427 return TCL_ERROR;
430 static Tcl_ChannelType IncrblobChannelType = {
431 "incrblob", /* typeName */
432 TCL_CHANNEL_VERSION_5, /* version */
433 incrblobClose, /* closeProc */
434 incrblobInput, /* inputProc */
435 incrblobOutput, /* outputProc */
436 incrblobSeek, /* seekProc */
437 0, /* setOptionProc */
438 0, /* getOptionProc */
439 incrblobWatch, /* watchProc (this is a no-op) */
440 incrblobHandle, /* getHandleProc (always returns error) */
441 incrblobClose2, /* close2Proc */
442 0, /* blockModeProc */
443 0, /* flushProc */
444 0, /* handlerProc */
445 incrblobWideSeek, /* wideSeekProc */
449 ** Create a new incrblob channel.
451 static int createIncrblobChannel(
452 Tcl_Interp *interp,
453 SqliteDb *pDb,
454 const char *zDb,
455 const char *zTable,
456 const char *zColumn,
457 sqlite_int64 iRow,
458 int isReadonly
460 IncrblobChannel *p;
461 sqlite3 *db = pDb->db;
462 sqlite3_blob *pBlob;
463 int rc;
464 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
466 /* This variable is used to name the channels: "incrblob_[incr count]" */
467 static int count = 0;
468 char zChannel[64];
470 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
471 if( rc!=SQLITE_OK ){
472 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
473 return TCL_ERROR;
476 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
477 memset(p, 0, sizeof(*p));
478 p->pBlob = pBlob;
479 if( (flags & TCL_WRITABLE)==0 ) p->isClosed |= TCL_CLOSE_WRITE;
481 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
482 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
483 Tcl_RegisterChannel(interp, p->channel);
485 /* Link the new channel into the SqliteDb.pIncrblob list. */
486 p->pNext = pDb->pIncrblob;
487 p->pPrev = 0;
488 if( p->pNext ){
489 p->pNext->pPrev = p;
491 pDb->pIncrblob = p;
492 p->pDb = pDb;
494 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
495 return TCL_OK;
497 #else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
498 #define closeIncrblobChannels(pDb)
499 #endif
502 ** Look at the script prefix in pCmd. We will be executing this script
503 ** after first appending one or more arguments. This routine analyzes
504 ** the script to see if it is safe to use Tcl_EvalObjv() on the script
505 ** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
506 ** faster.
508 ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
509 ** command name followed by zero or more arguments with no [...] or $
510 ** or {...} or ; to be seen anywhere. Most callback scripts consist
511 ** of just a single procedure name and they meet this requirement.
513 static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
514 /* We could try to do something with Tcl_Parse(). But we will instead
515 ** just do a search for forbidden characters. If any of the forbidden
516 ** characters appear in pCmd, we will report the string as unsafe.
518 const char *z;
519 Tcl_Size n;
520 z = Tcl_GetStringFromObj(pCmd, &n);
521 while( n-- > 0 ){
522 int c = *(z++);
523 if( c=='$' || c=='[' || c==';' ) return 0;
525 return 1;
529 ** Find an SqlFunc structure with the given name. Or create a new
530 ** one if an existing one cannot be found. Return a pointer to the
531 ** structure.
533 static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
534 SqlFunc *p, *pNew;
535 int nName = strlen30(zName);
536 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
537 pNew->zName = (char*)&pNew[1];
538 memcpy(pNew->zName, zName, nName+1);
539 for(p=pDb->pFunc; p; p=p->pNext){
540 if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
541 Tcl_Free((char*)pNew);
542 return p;
545 pNew->interp = pDb->interp;
546 pNew->pDb = pDb;
547 pNew->pScript = 0;
548 pNew->pNext = pDb->pFunc;
549 pDb->pFunc = pNew;
550 return pNew;
554 ** Free a single SqlPreparedStmt object.
556 static void dbFreeStmt(SqlPreparedStmt *pStmt){
557 #ifdef SQLITE_TEST
558 if( sqlite3_sql(pStmt->pStmt)==0 ){
559 Tcl_Free((char *)pStmt->zSql);
561 #endif
562 sqlite3_finalize(pStmt->pStmt);
563 Tcl_Free((char *)pStmt);
567 ** Finalize and free a list of prepared statements
569 static void flushStmtCache(SqliteDb *pDb){
570 SqlPreparedStmt *pPreStmt;
571 SqlPreparedStmt *pNext;
573 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
574 pNext = pPreStmt->pNext;
575 dbFreeStmt(pPreStmt);
577 pDb->nStmt = 0;
578 pDb->stmtLast = 0;
579 pDb->stmtList = 0;
583 ** Increment the reference counter on the SqliteDb object. The reference
584 ** should be released by calling delDatabaseRef().
586 static void addDatabaseRef(SqliteDb *pDb){
587 pDb->nRef++;
591 ** Decrement the reference counter associated with the SqliteDb object.
592 ** If it reaches zero, delete the object.
594 static void delDatabaseRef(SqliteDb *pDb){
595 assert( pDb->nRef>0 );
596 pDb->nRef--;
597 if( pDb->nRef==0 ){
598 flushStmtCache(pDb);
599 closeIncrblobChannels(pDb);
600 sqlite3_close(pDb->db);
601 while( pDb->pFunc ){
602 SqlFunc *pFunc = pDb->pFunc;
603 pDb->pFunc = pFunc->pNext;
604 assert( pFunc->pDb==pDb );
605 Tcl_DecrRefCount(pFunc->pScript);
606 Tcl_Free((char*)pFunc);
608 while( pDb->pCollate ){
609 SqlCollate *pCollate = pDb->pCollate;
610 pDb->pCollate = pCollate->pNext;
611 Tcl_Free((char*)pCollate);
613 if( pDb->zBusy ){
614 Tcl_Free(pDb->zBusy);
616 if( pDb->zTrace ){
617 Tcl_Free(pDb->zTrace);
619 if( pDb->zTraceV2 ){
620 Tcl_Free(pDb->zTraceV2);
622 if( pDb->zProfile ){
623 Tcl_Free(pDb->zProfile);
625 if( pDb->zBindFallback ){
626 Tcl_Free(pDb->zBindFallback);
628 if( pDb->zAuth ){
629 Tcl_Free(pDb->zAuth);
631 if( pDb->zNull ){
632 Tcl_Free(pDb->zNull);
634 if( pDb->pUpdateHook ){
635 Tcl_DecrRefCount(pDb->pUpdateHook);
637 if( pDb->pPreUpdateHook ){
638 Tcl_DecrRefCount(pDb->pPreUpdateHook);
640 if( pDb->pRollbackHook ){
641 Tcl_DecrRefCount(pDb->pRollbackHook);
643 if( pDb->pWalHook ){
644 Tcl_DecrRefCount(pDb->pWalHook);
646 if( pDb->pCollateNeeded ){
647 Tcl_DecrRefCount(pDb->pCollateNeeded);
649 Tcl_Free((char*)pDb);
654 ** TCL calls this procedure when an sqlite3 database command is
655 ** deleted.
657 static void SQLITE_TCLAPI DbDeleteCmd(void *db){
658 SqliteDb *pDb = (SqliteDb*)db;
659 delDatabaseRef(pDb);
663 ** This routine is called when a database file is locked while trying
664 ** to execute SQL.
666 static int DbBusyHandler(void *cd, int nTries){
667 SqliteDb *pDb = (SqliteDb*)cd;
668 int rc;
669 char zVal[30];
671 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
672 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
673 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
674 return 0;
676 return 1;
679 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
681 ** This routine is invoked as the 'progress callback' for the database.
683 static int DbProgressHandler(void *cd){
684 SqliteDb *pDb = (SqliteDb*)cd;
685 int rc;
687 assert( pDb->zProgress );
688 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
689 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
690 return 1;
692 return 0;
694 #endif
696 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
697 !defined(SQLITE_OMIT_DEPRECATED)
699 ** This routine is called by the SQLite trace handler whenever a new
700 ** block of SQL is executed. The TCL script in pDb->zTrace is executed.
702 static void DbTraceHandler(void *cd, const char *zSql){
703 SqliteDb *pDb = (SqliteDb*)cd;
704 Tcl_DString str;
706 Tcl_DStringInit(&str);
707 Tcl_DStringAppend(&str, pDb->zTrace, -1);
708 Tcl_DStringAppendElement(&str, zSql);
709 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
710 Tcl_DStringFree(&str);
711 Tcl_ResetResult(pDb->interp);
713 #endif
715 #ifndef SQLITE_OMIT_TRACE
717 ** This routine is called by the SQLite trace_v2 handler whenever a new
718 ** supported event is generated. Unsupported event types are ignored.
719 ** The TCL script in pDb->zTraceV2 is executed, with the arguments for
720 ** the event appended to it (as list elements).
722 static int DbTraceV2Handler(
723 unsigned type, /* One of the SQLITE_TRACE_* event types. */
724 void *cd, /* The original context data pointer. */
725 void *pd, /* Primary event data, depends on event type. */
726 void *xd /* Extra event data, depends on event type. */
728 SqliteDb *pDb = (SqliteDb*)cd;
729 Tcl_Obj *pCmd;
731 switch( type ){
732 case SQLITE_TRACE_STMT: {
733 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
734 char *zSql = (char *)xd;
736 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
737 Tcl_IncrRefCount(pCmd);
738 Tcl_ListObjAppendElement(pDb->interp, pCmd,
739 Tcl_NewWideIntObj((Tcl_WideInt)(uptr)pStmt));
740 Tcl_ListObjAppendElement(pDb->interp, pCmd,
741 Tcl_NewStringObj(zSql, -1));
742 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
743 Tcl_DecrRefCount(pCmd);
744 Tcl_ResetResult(pDb->interp);
745 break;
747 case SQLITE_TRACE_PROFILE: {
748 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
749 sqlite3_int64 ns = *(sqlite3_int64*)xd;
751 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
752 Tcl_IncrRefCount(pCmd);
753 Tcl_ListObjAppendElement(pDb->interp, pCmd,
754 Tcl_NewWideIntObj((Tcl_WideInt)(uptr)pStmt));
755 Tcl_ListObjAppendElement(pDb->interp, pCmd,
756 Tcl_NewWideIntObj((Tcl_WideInt)ns));
757 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
758 Tcl_DecrRefCount(pCmd);
759 Tcl_ResetResult(pDb->interp);
760 break;
762 case SQLITE_TRACE_ROW: {
763 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
765 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
766 Tcl_IncrRefCount(pCmd);
767 Tcl_ListObjAppendElement(pDb->interp, pCmd,
768 Tcl_NewWideIntObj((Tcl_WideInt)(uptr)pStmt));
769 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
770 Tcl_DecrRefCount(pCmd);
771 Tcl_ResetResult(pDb->interp);
772 break;
774 case SQLITE_TRACE_CLOSE: {
775 sqlite3 *db = (sqlite3 *)pd;
777 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
778 Tcl_IncrRefCount(pCmd);
779 Tcl_ListObjAppendElement(pDb->interp, pCmd,
780 Tcl_NewWideIntObj((Tcl_WideInt)(uptr)db));
781 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
782 Tcl_DecrRefCount(pCmd);
783 Tcl_ResetResult(pDb->interp);
784 break;
787 return SQLITE_OK;
789 #endif
791 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
792 !defined(SQLITE_OMIT_DEPRECATED)
794 ** This routine is called by the SQLite profile handler after a statement
795 ** SQL has executed. The TCL script in pDb->zProfile is evaluated.
797 static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
798 SqliteDb *pDb = (SqliteDb*)cd;
799 Tcl_DString str;
800 char zTm[100];
802 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
803 Tcl_DStringInit(&str);
804 Tcl_DStringAppend(&str, pDb->zProfile, -1);
805 Tcl_DStringAppendElement(&str, zSql);
806 Tcl_DStringAppendElement(&str, zTm);
807 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
808 Tcl_DStringFree(&str);
809 Tcl_ResetResult(pDb->interp);
811 #endif
814 ** This routine is called when a transaction is committed. The
815 ** TCL script in pDb->zCommit is executed. If it returns non-zero or
816 ** if it throws an exception, the transaction is rolled back instead
817 ** of being committed.
819 static int DbCommitHandler(void *cd){
820 SqliteDb *pDb = (SqliteDb*)cd;
821 int rc;
823 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
824 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
825 return 1;
827 return 0;
830 static void DbRollbackHandler(void *clientData){
831 SqliteDb *pDb = (SqliteDb*)clientData;
832 assert(pDb->pRollbackHook);
833 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
834 Tcl_BackgroundError(pDb->interp);
839 ** This procedure handles wal_hook callbacks.
841 static int DbWalHandler(
842 void *clientData,
843 sqlite3 *db,
844 const char *zDb,
845 int nEntry
847 int ret = SQLITE_OK;
848 Tcl_Obj *p;
849 SqliteDb *pDb = (SqliteDb*)clientData;
850 Tcl_Interp *interp = pDb->interp;
851 assert(pDb->pWalHook);
853 assert( db==pDb->db );
854 p = Tcl_DuplicateObj(pDb->pWalHook);
855 Tcl_IncrRefCount(p);
856 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
857 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
858 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
859 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
861 Tcl_BackgroundError(interp);
863 Tcl_DecrRefCount(p);
865 return ret;
868 #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
869 static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
870 char zBuf[64];
871 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
872 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
873 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
874 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
876 #else
877 # define setTestUnlockNotifyVars(x,y,z)
878 #endif
880 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
881 static void DbUnlockNotify(void **apArg, int nArg){
882 int i;
883 for(i=0; i<nArg; i++){
884 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
885 SqliteDb *pDb = (SqliteDb *)apArg[i];
886 setTestUnlockNotifyVars(pDb->interp, i, nArg);
887 assert( pDb->pUnlockNotify);
888 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
889 Tcl_DecrRefCount(pDb->pUnlockNotify);
890 pDb->pUnlockNotify = 0;
893 #endif
895 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
897 ** Pre-update hook callback.
899 static void DbPreUpdateHandler(
900 void *p,
901 sqlite3 *db,
902 int op,
903 const char *zDb,
904 const char *zTbl,
905 sqlite_int64 iKey1,
906 sqlite_int64 iKey2
908 SqliteDb *pDb = (SqliteDb *)p;
909 Tcl_Obj *pCmd;
910 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
912 assert( (SQLITE_DELETE-1)/9 == 0 );
913 assert( (SQLITE_INSERT-1)/9 == 1 );
914 assert( (SQLITE_UPDATE-1)/9 == 2 );
915 assert( pDb->pPreUpdateHook );
916 assert( db==pDb->db );
917 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
919 pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
920 Tcl_IncrRefCount(pCmd);
921 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
922 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
923 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
924 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
925 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
926 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
927 Tcl_DecrRefCount(pCmd);
929 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
931 static void DbUpdateHandler(
932 void *p,
933 int op,
934 const char *zDb,
935 const char *zTbl,
936 sqlite_int64 rowid
938 SqliteDb *pDb = (SqliteDb *)p;
939 Tcl_Obj *pCmd;
940 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
942 assert( (SQLITE_DELETE-1)/9 == 0 );
943 assert( (SQLITE_INSERT-1)/9 == 1 );
944 assert( (SQLITE_UPDATE-1)/9 == 2 );
946 assert( pDb->pUpdateHook );
947 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
949 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
950 Tcl_IncrRefCount(pCmd);
951 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
952 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
953 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
954 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
955 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
956 Tcl_DecrRefCount(pCmd);
959 static void tclCollateNeeded(
960 void *pCtx,
961 sqlite3 *db,
962 int enc,
963 const char *zName
965 SqliteDb *pDb = (SqliteDb *)pCtx;
966 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
967 Tcl_IncrRefCount(pScript);
968 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
969 Tcl_EvalObjEx(pDb->interp, pScript, 0);
970 Tcl_DecrRefCount(pScript);
974 ** This routine is called to evaluate an SQL collation function implemented
975 ** using TCL script.
977 static int tclSqlCollate(
978 void *pCtx,
979 int nA,
980 const void *zA,
981 int nB,
982 const void *zB
984 SqlCollate *p = (SqlCollate *)pCtx;
985 Tcl_Obj *pCmd;
987 pCmd = Tcl_NewStringObj(p->zScript, -1);
988 Tcl_IncrRefCount(pCmd);
989 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
990 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
991 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
992 Tcl_DecrRefCount(pCmd);
993 return (atoi(Tcl_GetStringResult(p->interp)));
997 ** This routine is called to evaluate an SQL function implemented
998 ** using TCL script.
1000 static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
1001 SqlFunc *p = sqlite3_user_data(context);
1002 Tcl_Obj *pCmd;
1003 int i;
1004 int rc;
1006 if( argc==0 ){
1007 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
1008 ** script object directly. This allows the TCL compiler to generate
1009 ** bytecode for the command on the first invocation and thus make
1010 ** subsequent invocations much faster. */
1011 pCmd = p->pScript;
1012 Tcl_IncrRefCount(pCmd);
1013 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
1014 Tcl_DecrRefCount(pCmd);
1015 }else{
1016 /* If there are arguments to the function, make a shallow copy of the
1017 ** script object, lappend the arguments, then evaluate the copy.
1019 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
1020 ** The new Tcl_Obj contains pointers to the original list elements.
1021 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
1022 ** of the list to tclCmdNameType, that alternate representation will
1023 ** be preserved and reused on the next invocation.
1025 Tcl_Obj **aArg;
1026 Tcl_Size nArg;
1027 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
1028 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
1029 return;
1031 pCmd = Tcl_NewListObj(nArg, aArg);
1032 Tcl_IncrRefCount(pCmd);
1033 for(i=0; i<argc; i++){
1034 sqlite3_value *pIn = argv[i];
1035 Tcl_Obj *pVal;
1037 /* Set pVal to contain the i'th column of this row. */
1038 switch( sqlite3_value_type(pIn) ){
1039 case SQLITE_BLOB: {
1040 int bytes = sqlite3_value_bytes(pIn);
1041 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
1042 break;
1044 case SQLITE_INTEGER: {
1045 sqlite_int64 v = sqlite3_value_int64(pIn);
1046 if( v>=-2147483647 && v<=2147483647 ){
1047 pVal = Tcl_NewIntObj((int)v);
1048 }else{
1049 pVal = Tcl_NewWideIntObj(v);
1051 break;
1053 case SQLITE_FLOAT: {
1054 double r = sqlite3_value_double(pIn);
1055 pVal = Tcl_NewDoubleObj(r);
1056 break;
1058 case SQLITE_NULL: {
1059 pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
1060 break;
1062 default: {
1063 int bytes = sqlite3_value_bytes(pIn);
1064 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
1065 break;
1068 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
1069 if( rc ){
1070 Tcl_DecrRefCount(pCmd);
1071 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
1072 return;
1075 if( !p->useEvalObjv ){
1076 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
1077 ** is a list without a string representation. To prevent this from
1078 ** happening, make sure pCmd has a valid string representation */
1079 Tcl_GetString(pCmd);
1081 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
1082 Tcl_DecrRefCount(pCmd);
1085 if( rc && rc!=TCL_RETURN ){
1086 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
1087 }else{
1088 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
1089 Tcl_Size n;
1090 u8 *data;
1091 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1092 char c = zType[0];
1093 int eType = p->eType;
1095 if( eType==SQLITE_NULL ){
1096 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
1097 /* Only return a BLOB type if the Tcl variable is a bytearray and
1098 ** has no string representation. */
1099 eType = SQLITE_BLOB;
1100 }else if( (c=='b' && strcmp(zType,"boolean")==0)
1101 || (c=='w' && strcmp(zType,"wideInt")==0)
1102 || (c=='i' && strcmp(zType,"int")==0)
1104 eType = SQLITE_INTEGER;
1105 }else if( c=='d' && strcmp(zType,"double")==0 ){
1106 eType = SQLITE_FLOAT;
1107 }else{
1108 eType = SQLITE_TEXT;
1112 switch( eType ){
1113 case SQLITE_BLOB: {
1114 data = Tcl_GetByteArrayFromObj(pVar, &n);
1115 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
1116 break;
1118 case SQLITE_INTEGER: {
1119 Tcl_WideInt v;
1120 if( TCL_OK==Tcl_GetWideIntFromObj(0, pVar, &v) ){
1121 sqlite3_result_int64(context, v);
1122 break;
1124 /* fall-through */
1126 case SQLITE_FLOAT: {
1127 double r;
1128 if( TCL_OK==Tcl_GetDoubleFromObj(0, pVar, &r) ){
1129 sqlite3_result_double(context, r);
1130 break;
1132 /* fall-through */
1134 default: {
1135 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1136 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
1137 break;
1144 #ifndef SQLITE_OMIT_AUTHORIZATION
1146 ** This is the authentication function. It appends the authentication
1147 ** type code and the two arguments to zCmd[] then invokes the result
1148 ** on the interpreter. The reply is examined to determine if the
1149 ** authentication fails or succeeds.
1151 static int auth_callback(
1152 void *pArg,
1153 int code,
1154 const char *zArg1,
1155 const char *zArg2,
1156 const char *zArg3,
1157 const char *zArg4
1158 #ifdef SQLITE_USER_AUTHENTICATION
1159 ,const char *zArg5
1160 #endif
1162 const char *zCode;
1163 Tcl_DString str;
1164 int rc;
1165 const char *zReply;
1166 /* EVIDENCE-OF: R-38590-62769 The first parameter to the authorizer
1167 ** callback is a copy of the third parameter to the
1168 ** sqlite3_set_authorizer() interface.
1170 SqliteDb *pDb = (SqliteDb*)pArg;
1171 if( pDb->disableAuth ) return SQLITE_OK;
1173 /* EVIDENCE-OF: R-56518-44310 The second parameter to the callback is an
1174 ** integer action code that specifies the particular action to be
1175 ** authorized. */
1176 switch( code ){
1177 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
1178 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
1179 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
1180 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
1181 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
1182 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
1183 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
1184 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
1185 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
1186 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
1187 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
1188 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
1189 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
1190 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
1191 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
1192 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
1193 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
1194 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
1195 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
1196 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
1197 case SQLITE_READ : zCode="SQLITE_READ"; break;
1198 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
1199 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
1200 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
1201 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
1202 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
1203 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
1204 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
1205 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
1206 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
1207 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
1208 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
1209 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
1210 case SQLITE_RECURSIVE : zCode="SQLITE_RECURSIVE"; break;
1211 default : zCode="????"; break;
1213 Tcl_DStringInit(&str);
1214 Tcl_DStringAppend(&str, pDb->zAuth, -1);
1215 Tcl_DStringAppendElement(&str, zCode);
1216 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
1217 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
1218 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
1219 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
1220 #ifdef SQLITE_USER_AUTHENTICATION
1221 Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
1222 #endif
1223 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
1224 Tcl_DStringFree(&str);
1225 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
1226 if( strcmp(zReply,"SQLITE_OK")==0 ){
1227 rc = SQLITE_OK;
1228 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
1229 rc = SQLITE_DENY;
1230 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
1231 rc = SQLITE_IGNORE;
1232 }else{
1233 rc = 999;
1235 return rc;
1237 #endif /* SQLITE_OMIT_AUTHORIZATION */
1240 ** This routine reads a line of text from FILE in, stores
1241 ** the text in memory obtained from malloc() and returns a pointer
1242 ** to the text. NULL is returned at end of file, or if malloc()
1243 ** fails.
1245 ** The interface is like "readline" but no command-line editing
1246 ** is done.
1248 ** copied from shell.c from '.import' command
1250 static char *local_getline(char *zPrompt, FILE *in){
1251 char *zLine;
1252 int nLine;
1253 int n;
1255 nLine = 100;
1256 zLine = malloc( nLine );
1257 if( zLine==0 ) return 0;
1258 n = 0;
1259 while( 1 ){
1260 if( n+100>nLine ){
1261 nLine = nLine*2 + 100;
1262 zLine = realloc(zLine, nLine);
1263 if( zLine==0 ) return 0;
1265 if( fgets(&zLine[n], nLine - n, in)==0 ){
1266 if( n==0 ){
1267 free(zLine);
1268 return 0;
1270 zLine[n] = 0;
1271 break;
1273 while( zLine[n] ){ n++; }
1274 if( n>0 && zLine[n-1]=='\n' ){
1275 n--;
1276 zLine[n] = 0;
1277 break;
1280 zLine = realloc( zLine, n+1 );
1281 return zLine;
1286 ** This function is part of the implementation of the command:
1288 ** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1290 ** It is invoked after evaluating the script SCRIPT to commit or rollback
1291 ** the transaction or savepoint opened by the [transaction] command.
1293 static int SQLITE_TCLAPI DbTransPostCmd(
1294 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1295 Tcl_Interp *interp, /* Tcl interpreter */
1296 int result /* Result of evaluating SCRIPT */
1298 static const char *const azEnd[] = {
1299 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1300 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1301 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1302 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1304 SqliteDb *pDb = (SqliteDb*)data[0];
1305 int rc = result;
1306 const char *zEnd;
1308 pDb->nTransaction--;
1309 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1311 pDb->disableAuth++;
1312 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1313 /* This is a tricky scenario to handle. The most likely cause of an
1314 ** error is that the exec() above was an attempt to commit the
1315 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1316 ** that an IO-error has occurred. In either case, throw a Tcl exception
1317 ** and try to rollback the transaction.
1319 ** But it could also be that the user executed one or more BEGIN,
1320 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1321 ** this method's logic. Not clear how this would be best handled.
1323 if( rc!=TCL_ERROR ){
1324 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
1325 rc = TCL_ERROR;
1327 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1329 pDb->disableAuth--;
1331 delDatabaseRef(pDb);
1332 return rc;
1336 ** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1337 ** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1338 ** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1339 ** on whether or not the [db_use_legacy_prepare] command has been used to
1340 ** configure the connection.
1342 static int dbPrepare(
1343 SqliteDb *pDb, /* Database object */
1344 const char *zSql, /* SQL to compile */
1345 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1346 const char **pzOut /* OUT: Pointer to next SQL statement */
1348 unsigned int prepFlags = 0;
1349 #ifdef SQLITE_TEST
1350 if( pDb->bLegacyPrepare ){
1351 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1353 #endif
1354 /* If the statement cache is large, use the SQLITE_PREPARE_PERSISTENT
1355 ** flags, which uses less lookaside memory. But if the cache is small,
1356 ** omit that flag to make full use of lookaside */
1357 if( pDb->maxStmt>5 ) prepFlags = SQLITE_PREPARE_PERSISTENT;
1359 return sqlite3_prepare_v3(pDb->db, zSql, -1, prepFlags, ppStmt, pzOut);
1363 ** Search the cache for a prepared-statement object that implements the
1364 ** first SQL statement in the buffer pointed to by parameter zIn. If
1365 ** no such prepared-statement can be found, allocate and prepare a new
1366 ** one. In either case, bind the current values of the relevant Tcl
1367 ** variables to any $var, :var or @var variables in the statement. Before
1368 ** returning, set *ppPreStmt to point to the prepared-statement object.
1370 ** Output parameter *pzOut is set to point to the next SQL statement in
1371 ** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1372 ** next statement.
1374 ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1375 ** and an error message loaded into interpreter pDb->interp.
1377 static int dbPrepareAndBind(
1378 SqliteDb *pDb, /* Database object */
1379 char const *zIn, /* SQL to compile */
1380 char const **pzOut, /* OUT: Pointer to next SQL statement */
1381 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1383 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
1384 sqlite3_stmt *pStmt = 0; /* Prepared statement object */
1385 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1386 int nSql; /* Length of zSql in bytes */
1387 int nVar = 0; /* Number of variables in statement */
1388 int iParm = 0; /* Next free entry in apParm */
1389 char c;
1390 int i;
1391 int needResultReset = 0; /* Need to invoke Tcl_ResetResult() */
1392 int rc = SQLITE_OK; /* Value to return */
1393 Tcl_Interp *interp = pDb->interp;
1395 *ppPreStmt = 0;
1397 /* Trim spaces from the start of zSql and calculate the remaining length. */
1398 while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
1399 nSql = strlen30(zSql);
1401 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1402 int n = pPreStmt->nSql;
1403 if( nSql>=n
1404 && memcmp(pPreStmt->zSql, zSql, n)==0
1405 && (zSql[n]==0 || zSql[n-1]==';')
1407 pStmt = pPreStmt->pStmt;
1408 *pzOut = &zSql[pPreStmt->nSql];
1410 /* When a prepared statement is found, unlink it from the
1411 ** cache list. It will later be added back to the beginning
1412 ** of the cache list in order to implement LRU replacement.
1414 if( pPreStmt->pPrev ){
1415 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1416 }else{
1417 pDb->stmtList = pPreStmt->pNext;
1419 if( pPreStmt->pNext ){
1420 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1421 }else{
1422 pDb->stmtLast = pPreStmt->pPrev;
1424 pDb->nStmt--;
1425 nVar = sqlite3_bind_parameter_count(pStmt);
1426 break;
1430 /* If no prepared statement was found. Compile the SQL text. Also allocate
1431 ** a new SqlPreparedStmt structure. */
1432 if( pPreStmt==0 ){
1433 int nByte;
1435 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
1436 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1437 return TCL_ERROR;
1439 if( pStmt==0 ){
1440 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1441 /* A compile-time error in the statement. */
1442 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1443 return TCL_ERROR;
1444 }else{
1445 /* The statement was a no-op. Continue to the next statement
1446 ** in the SQL string.
1448 return TCL_OK;
1452 assert( pPreStmt==0 );
1453 nVar = sqlite3_bind_parameter_count(pStmt);
1454 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1455 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1456 memset(pPreStmt, 0, nByte);
1458 pPreStmt->pStmt = pStmt;
1459 pPreStmt->nSql = (int)(*pzOut - zSql);
1460 pPreStmt->zSql = sqlite3_sql(pStmt);
1461 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
1462 #ifdef SQLITE_TEST
1463 if( pPreStmt->zSql==0 ){
1464 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1465 memcpy(zCopy, zSql, pPreStmt->nSql);
1466 zCopy[pPreStmt->nSql] = '\0';
1467 pPreStmt->zSql = zCopy;
1469 #endif
1471 assert( pPreStmt );
1472 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1473 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1475 /* Bind values to parameters that begin with $ or : */
1476 for(i=1; i<=nVar; i++){
1477 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1478 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1479 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1480 if( pVar==0 && pDb->zBindFallback!=0 ){
1481 Tcl_Obj *pCmd;
1482 int rx;
1483 pCmd = Tcl_NewStringObj(pDb->zBindFallback, -1);
1484 Tcl_IncrRefCount(pCmd);
1485 Tcl_ListObjAppendElement(interp, pCmd, Tcl_NewStringObj(zVar,-1));
1486 if( needResultReset ) Tcl_ResetResult(interp);
1487 needResultReset = 1;
1488 rx = Tcl_EvalObjEx(interp, pCmd, TCL_EVAL_DIRECT);
1489 Tcl_DecrRefCount(pCmd);
1490 if( rx==TCL_OK ){
1491 pVar = Tcl_GetObjResult(interp);
1492 }else if( rx==TCL_ERROR ){
1493 rc = TCL_ERROR;
1494 break;
1495 }else{
1496 pVar = 0;
1499 if( pVar ){
1500 Tcl_Size n;
1501 u8 *data;
1502 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1503 c = zType[0];
1504 if( zVar[0]=='@' ||
1505 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1506 /* Load a BLOB type if the Tcl variable is a bytearray and
1507 ** it has no string representation or the host
1508 ** parameter name begins with "@". */
1509 data = Tcl_GetByteArrayFromObj(pVar, &n);
1510 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1511 Tcl_IncrRefCount(pVar);
1512 pPreStmt->apParm[iParm++] = pVar;
1513 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1514 int nn;
1515 Tcl_GetIntFromObj(interp, pVar, &nn);
1516 sqlite3_bind_int(pStmt, i, nn);
1517 }else if( c=='d' && strcmp(zType,"double")==0 ){
1518 double r;
1519 Tcl_GetDoubleFromObj(interp, pVar, &r);
1520 sqlite3_bind_double(pStmt, i, r);
1521 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1522 (c=='i' && strcmp(zType,"int")==0) ){
1523 Tcl_WideInt v;
1524 Tcl_GetWideIntFromObj(interp, pVar, &v);
1525 sqlite3_bind_int64(pStmt, i, v);
1526 }else{
1527 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1528 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1529 Tcl_IncrRefCount(pVar);
1530 pPreStmt->apParm[iParm++] = pVar;
1532 }else{
1533 sqlite3_bind_null(pStmt, i);
1535 if( needResultReset ) Tcl_ResetResult(pDb->interp);
1538 pPreStmt->nParm = iParm;
1539 *ppPreStmt = pPreStmt;
1540 if( needResultReset && rc==TCL_OK ) Tcl_ResetResult(pDb->interp);
1542 return rc;
1546 ** Release a statement reference obtained by calling dbPrepareAndBind().
1547 ** There should be exactly one call to this function for each call to
1548 ** dbPrepareAndBind().
1550 ** If the discard parameter is non-zero, then the statement is deleted
1551 ** immediately. Otherwise it is added to the LRU list and may be returned
1552 ** by a subsequent call to dbPrepareAndBind().
1554 static void dbReleaseStmt(
1555 SqliteDb *pDb, /* Database handle */
1556 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1557 int discard /* True to delete (not cache) the pPreStmt */
1559 int i;
1561 /* Free the bound string and blob parameters */
1562 for(i=0; i<pPreStmt->nParm; i++){
1563 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1565 pPreStmt->nParm = 0;
1567 if( pDb->maxStmt<=0 || discard ){
1568 /* If the cache is turned off, deallocated the statement */
1569 dbFreeStmt(pPreStmt);
1570 }else{
1571 /* Add the prepared statement to the beginning of the cache list. */
1572 pPreStmt->pNext = pDb->stmtList;
1573 pPreStmt->pPrev = 0;
1574 if( pDb->stmtList ){
1575 pDb->stmtList->pPrev = pPreStmt;
1577 pDb->stmtList = pPreStmt;
1578 if( pDb->stmtLast==0 ){
1579 assert( pDb->nStmt==0 );
1580 pDb->stmtLast = pPreStmt;
1581 }else{
1582 assert( pDb->nStmt>0 );
1584 pDb->nStmt++;
1586 /* If we have too many statement in cache, remove the surplus from
1587 ** the end of the cache list. */
1588 while( pDb->nStmt>pDb->maxStmt ){
1589 SqlPreparedStmt *pLast = pDb->stmtLast;
1590 pDb->stmtLast = pLast->pPrev;
1591 pDb->stmtLast->pNext = 0;
1592 pDb->nStmt--;
1593 dbFreeStmt(pLast);
1599 ** Structure used with dbEvalXXX() functions:
1601 ** dbEvalInit()
1602 ** dbEvalStep()
1603 ** dbEvalFinalize()
1604 ** dbEvalRowInfo()
1605 ** dbEvalColumnValue()
1607 typedef struct DbEvalContext DbEvalContext;
1608 struct DbEvalContext {
1609 SqliteDb *pDb; /* Database handle */
1610 Tcl_Obj *pSql; /* Object holding string zSql */
1611 const char *zSql; /* Remaining SQL to execute */
1612 SqlPreparedStmt *pPreStmt; /* Current statement */
1613 int nCol; /* Number of columns returned by pStmt */
1614 int evalFlags; /* Flags used */
1615 Tcl_Obj *pArray; /* Name of array variable */
1616 Tcl_Obj **apColName; /* Array of column names */
1619 #define SQLITE_EVAL_WITHOUTNULLS 0x00001 /* Unset array(*) for NULL */
1622 ** Release any cache of column names currently held as part of
1623 ** the DbEvalContext structure passed as the first argument.
1625 static void dbReleaseColumnNames(DbEvalContext *p){
1626 if( p->apColName ){
1627 int i;
1628 for(i=0; i<p->nCol; i++){
1629 Tcl_DecrRefCount(p->apColName[i]);
1631 Tcl_Free((char *)p->apColName);
1632 p->apColName = 0;
1634 p->nCol = 0;
1638 ** Initialize a DbEvalContext structure.
1640 ** If pArray is not NULL, then it contains the name of a Tcl array
1641 ** variable. The "*" member of this array is set to a list containing
1642 ** the names of the columns returned by the statement as part of each
1643 ** call to dbEvalStep(), in order from left to right. e.g. if the names
1644 ** of the returned columns are a, b and c, it does the equivalent of the
1645 ** tcl command:
1647 ** set ${pArray}(*) {a b c}
1649 static void dbEvalInit(
1650 DbEvalContext *p, /* Pointer to structure to initialize */
1651 SqliteDb *pDb, /* Database handle */
1652 Tcl_Obj *pSql, /* Object containing SQL script */
1653 Tcl_Obj *pArray, /* Name of Tcl array to set (*) element of */
1654 int evalFlags /* Flags controlling evaluation */
1656 memset(p, 0, sizeof(DbEvalContext));
1657 p->pDb = pDb;
1658 p->zSql = Tcl_GetString(pSql);
1659 p->pSql = pSql;
1660 Tcl_IncrRefCount(pSql);
1661 if( pArray ){
1662 p->pArray = pArray;
1663 Tcl_IncrRefCount(pArray);
1665 p->evalFlags = evalFlags;
1666 addDatabaseRef(p->pDb);
1670 ** Obtain information about the row that the DbEvalContext passed as the
1671 ** first argument currently points to.
1673 static void dbEvalRowInfo(
1674 DbEvalContext *p, /* Evaluation context */
1675 int *pnCol, /* OUT: Number of column names */
1676 Tcl_Obj ***papColName /* OUT: Array of column names */
1678 /* Compute column names */
1679 if( 0==p->apColName ){
1680 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1681 int i; /* Iterator variable */
1682 int nCol; /* Number of columns returned by pStmt */
1683 Tcl_Obj **apColName = 0; /* Array of column names */
1685 p->nCol = nCol = sqlite3_column_count(pStmt);
1686 if( nCol>0 && (papColName || p->pArray) ){
1687 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1688 for(i=0; i<nCol; i++){
1689 apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
1690 Tcl_IncrRefCount(apColName[i]);
1692 p->apColName = apColName;
1695 /* If results are being stored in an array variable, then create
1696 ** the array(*) entry for that array
1698 if( p->pArray ){
1699 Tcl_Interp *interp = p->pDb->interp;
1700 Tcl_Obj *pColList = Tcl_NewObj();
1701 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
1703 for(i=0; i<nCol; i++){
1704 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1706 Tcl_IncrRefCount(pStar);
1707 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
1708 Tcl_DecrRefCount(pStar);
1712 if( papColName ){
1713 *papColName = p->apColName;
1715 if( pnCol ){
1716 *pnCol = p->nCol;
1721 ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1722 ** returned, then an error message is stored in the interpreter before
1723 ** returning.
1725 ** A return value of TCL_OK means there is a row of data available. The
1726 ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1727 ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1728 ** is returned, then the SQL script has finished executing and there are
1729 ** no further rows available. This is similar to SQLITE_DONE.
1731 static int dbEvalStep(DbEvalContext *p){
1732 const char *zPrevSql = 0; /* Previous value of p->zSql */
1734 while( p->zSql[0] || p->pPreStmt ){
1735 int rc;
1736 if( p->pPreStmt==0 ){
1737 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
1738 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1739 if( rc!=TCL_OK ) return rc;
1740 }else{
1741 int rcs;
1742 SqliteDb *pDb = p->pDb;
1743 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1744 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1746 rcs = sqlite3_step(pStmt);
1747 if( rcs==SQLITE_ROW ){
1748 return TCL_OK;
1750 if( p->pArray ){
1751 dbEvalRowInfo(p, 0, 0);
1753 rcs = sqlite3_reset(pStmt);
1755 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1756 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
1757 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
1758 pDb->nVMStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_VM_STEP,1);
1759 dbReleaseColumnNames(p);
1760 p->pPreStmt = 0;
1762 if( rcs!=SQLITE_OK ){
1763 /* If a run-time error occurs, report the error and stop reading
1764 ** the SQL. */
1765 dbReleaseStmt(pDb, pPreStmt, 1);
1766 #if SQLITE_TEST
1767 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1768 /* If the runtime error was an SQLITE_SCHEMA, and the database
1769 ** handle is configured to use the legacy sqlite3_prepare()
1770 ** interface, retry prepare()/step() on the same SQL statement.
1771 ** This only happens once. If there is a second SQLITE_SCHEMA
1772 ** error, the error will be returned to the caller. */
1773 p->zSql = zPrevSql;
1774 continue;
1776 #endif
1777 Tcl_SetObjResult(pDb->interp,
1778 Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1779 return TCL_ERROR;
1780 }else{
1781 dbReleaseStmt(pDb, pPreStmt, 0);
1786 /* Finished */
1787 return TCL_BREAK;
1791 ** Free all resources currently held by the DbEvalContext structure passed
1792 ** as the first argument. There should be exactly one call to this function
1793 ** for each call to dbEvalInit().
1795 static void dbEvalFinalize(DbEvalContext *p){
1796 if( p->pPreStmt ){
1797 sqlite3_reset(p->pPreStmt->pStmt);
1798 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1799 p->pPreStmt = 0;
1801 if( p->pArray ){
1802 Tcl_DecrRefCount(p->pArray);
1803 p->pArray = 0;
1805 Tcl_DecrRefCount(p->pSql);
1806 dbReleaseColumnNames(p);
1807 delDatabaseRef(p->pDb);
1811 ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1812 ** the value for the iCol'th column of the row currently pointed to by
1813 ** the DbEvalContext structure passed as the first argument.
1815 static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1816 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1817 switch( sqlite3_column_type(pStmt, iCol) ){
1818 case SQLITE_BLOB: {
1819 int bytes = sqlite3_column_bytes(pStmt, iCol);
1820 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1821 if( !zBlob ) bytes = 0;
1822 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1824 case SQLITE_INTEGER: {
1825 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1826 if( v>=-2147483647 && v<=2147483647 ){
1827 return Tcl_NewIntObj((int)v);
1828 }else{
1829 return Tcl_NewWideIntObj(v);
1832 case SQLITE_FLOAT: {
1833 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1835 case SQLITE_NULL: {
1836 return Tcl_NewStringObj(p->pDb->zNull, -1);
1840 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
1844 ** If using Tcl version 8.6 or greater, use the NR functions to avoid
1845 ** recursive evaluation of scripts by the [db eval] and [db trans]
1846 ** commands. Even if the headers used while compiling the extension
1847 ** are 8.6 or newer, the code still tests the Tcl version at runtime.
1848 ** This allows stubs-enabled builds to be used with older Tcl libraries.
1850 #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
1851 # define SQLITE_TCL_NRE 1
1852 static int DbUseNre(void){
1853 int major, minor;
1854 Tcl_GetVersion(&major, &minor, 0, 0);
1855 return( (major==8 && minor>=6) || major>8 );
1857 #else
1859 ** Compiling using headers earlier than 8.6. In this case NR cannot be
1860 ** used, so DbUseNre() to always return zero. Add #defines for the other
1861 ** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1862 ** even though the only invocations of them are within conditional blocks
1863 ** of the form:
1865 ** if( DbUseNre() ) { ... }
1867 # define SQLITE_TCL_NRE 0
1868 # define DbUseNre() 0
1869 # define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
1870 # define Tcl_NREvalObj(a,b,c) 0
1871 # define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
1872 #endif
1875 ** This function is part of the implementation of the command:
1877 ** $db eval SQL ?ARRAYNAME? SCRIPT
1879 static int SQLITE_TCLAPI DbEvalNextCmd(
1880 ClientData data[], /* data[0] is the (DbEvalContext*) */
1881 Tcl_Interp *interp, /* Tcl interpreter */
1882 int result /* Result so far */
1884 int rc = result; /* Return code */
1886 /* The first element of the data[] array is a pointer to a DbEvalContext
1887 ** structure allocated using Tcl_Alloc(). The second element of data[]
1888 ** is a pointer to a Tcl_Obj containing the script to run for each row
1889 ** returned by the queries encapsulated in data[0]. */
1890 DbEvalContext *p = (DbEvalContext *)data[0];
1891 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1892 Tcl_Obj *pArray = p->pArray;
1894 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1895 int i;
1896 int nCol;
1897 Tcl_Obj **apColName;
1898 dbEvalRowInfo(p, &nCol, &apColName);
1899 for(i=0; i<nCol; i++){
1900 if( pArray==0 ){
1901 Tcl_ObjSetVar2(interp, apColName[i], 0, dbEvalColumnValue(p,i), 0);
1902 }else if( (p->evalFlags & SQLITE_EVAL_WITHOUTNULLS)!=0
1903 && sqlite3_column_type(p->pPreStmt->pStmt, i)==SQLITE_NULL
1905 Tcl_UnsetVar2(interp, Tcl_GetString(pArray),
1906 Tcl_GetString(apColName[i]), 0);
1907 }else{
1908 Tcl_ObjSetVar2(interp, pArray, apColName[i], dbEvalColumnValue(p,i), 0);
1912 /* The required interpreter variables are now populated with the data
1913 ** from the current row. If using NRE, schedule callbacks to evaluate
1914 ** script pScript, then to invoke this function again to fetch the next
1915 ** row (or clean up if there is no next row or the script throws an
1916 ** exception). After scheduling the callbacks, return control to the
1917 ** caller.
1919 ** If not using NRE, evaluate pScript directly and continue with the
1920 ** next iteration of this while(...) loop. */
1921 if( DbUseNre() ){
1922 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1923 return Tcl_NREvalObj(interp, pScript, 0);
1924 }else{
1925 rc = Tcl_EvalObjEx(interp, pScript, 0);
1929 Tcl_DecrRefCount(pScript);
1930 dbEvalFinalize(p);
1931 Tcl_Free((char *)p);
1933 if( rc==TCL_OK || rc==TCL_BREAK ){
1934 Tcl_ResetResult(interp);
1935 rc = TCL_OK;
1937 return rc;
1941 ** This function is used by the implementations of the following database
1942 ** handle sub-commands:
1944 ** $db update_hook ?SCRIPT?
1945 ** $db wal_hook ?SCRIPT?
1946 ** $db commit_hook ?SCRIPT?
1947 ** $db preupdate hook ?SCRIPT?
1949 static void DbHookCmd(
1950 Tcl_Interp *interp, /* Tcl interpreter */
1951 SqliteDb *pDb, /* Database handle */
1952 Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */
1953 Tcl_Obj **ppHook /* Pointer to member of SqliteDb */
1955 sqlite3 *db = pDb->db;
1957 if( *ppHook ){
1958 Tcl_SetObjResult(interp, *ppHook);
1959 if( pArg ){
1960 Tcl_DecrRefCount(*ppHook);
1961 *ppHook = 0;
1964 if( pArg ){
1965 assert( !(*ppHook) );
1966 if( Tcl_GetCharLength(pArg)>0 ){
1967 *ppHook = pArg;
1968 Tcl_IncrRefCount(*ppHook);
1972 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1973 sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
1974 #endif
1975 sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1976 sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1977 sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
1981 ** The "sqlite" command below creates a new Tcl command for each
1982 ** connection it opens to an SQLite database. This routine is invoked
1983 ** whenever one of those connection-specific commands is executed
1984 ** in Tcl. For example, if you run Tcl code like this:
1986 ** sqlite3 db1 "my_database"
1987 ** db1 close
1989 ** The first command opens a connection to the "my_database" database
1990 ** and calls that connection "db1". The second command causes this
1991 ** subroutine to be invoked.
1993 static int SQLITE_TCLAPI DbObjCmd(
1994 void *cd,
1995 Tcl_Interp *interp,
1996 int objc,
1997 Tcl_Obj *const*objv
1999 SqliteDb *pDb = (SqliteDb*)cd;
2000 int choice;
2001 int rc = TCL_OK;
2002 static const char *DB_strs[] = {
2003 "authorizer", "backup", "bind_fallback",
2004 "busy", "cache", "changes",
2005 "close", "collate", "collation_needed",
2006 "commit_hook", "complete", "config",
2007 "copy", "deserialize", "enable_load_extension",
2008 "errorcode", "erroroffset", "eval",
2009 "exists", "function", "incrblob",
2010 "interrupt", "last_insert_rowid", "nullvalue",
2011 "onecolumn", "preupdate", "profile",
2012 "progress", "rekey", "restore",
2013 "rollback_hook", "serialize", "status",
2014 "timeout", "total_changes", "trace",
2015 "trace_v2", "transaction", "unlock_notify",
2016 "update_hook", "version", "wal_hook",
2019 enum DB_enum {
2020 DB_AUTHORIZER, DB_BACKUP, DB_BIND_FALLBACK,
2021 DB_BUSY, DB_CACHE, DB_CHANGES,
2022 DB_CLOSE, DB_COLLATE, DB_COLLATION_NEEDED,
2023 DB_COMMIT_HOOK, DB_COMPLETE, DB_CONFIG,
2024 DB_COPY, DB_DESERIALIZE, DB_ENABLE_LOAD_EXTENSION,
2025 DB_ERRORCODE, DB_ERROROFFSET, DB_EVAL,
2026 DB_EXISTS, DB_FUNCTION, DB_INCRBLOB,
2027 DB_INTERRUPT, DB_LAST_INSERT_ROWID, DB_NULLVALUE,
2028 DB_ONECOLUMN, DB_PREUPDATE, DB_PROFILE,
2029 DB_PROGRESS, DB_REKEY, DB_RESTORE,
2030 DB_ROLLBACK_HOOK, DB_SERIALIZE, DB_STATUS,
2031 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
2032 DB_TRACE_V2, DB_TRANSACTION, DB_UNLOCK_NOTIFY,
2033 DB_UPDATE_HOOK, DB_VERSION, DB_WAL_HOOK,
2035 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
2037 if( objc<2 ){
2038 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
2039 return TCL_ERROR;
2041 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
2042 return TCL_ERROR;
2045 switch( (enum DB_enum)choice ){
2047 /* $db authorizer ?CALLBACK?
2049 ** Invoke the given callback to authorize each SQL operation as it is
2050 ** compiled. 5 arguments are appended to the callback before it is
2051 ** invoked:
2053 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
2054 ** (2) First descriptive name (depends on authorization type)
2055 ** (3) Second descriptive name
2056 ** (4) Name of the database (ex: "main", "temp")
2057 ** (5) Name of trigger that is doing the access
2059 ** The callback should return on of the following strings: SQLITE_OK,
2060 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
2062 ** If this method is invoked with no arguments, the current authorization
2063 ** callback string is returned.
2065 case DB_AUTHORIZER: {
2066 #ifdef SQLITE_OMIT_AUTHORIZATION
2067 Tcl_AppendResult(interp, "authorization not available in this build",
2068 (char*)0);
2069 return TCL_ERROR;
2070 #else
2071 if( objc>3 ){
2072 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2073 return TCL_ERROR;
2074 }else if( objc==2 ){
2075 if( pDb->zAuth ){
2076 Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
2078 }else{
2079 char *zAuth;
2080 Tcl_Size len;
2081 if( pDb->zAuth ){
2082 Tcl_Free(pDb->zAuth);
2084 zAuth = Tcl_GetStringFromObj(objv[2], &len);
2085 if( zAuth && len>0 ){
2086 pDb->zAuth = Tcl_Alloc( len + 1 );
2087 memcpy(pDb->zAuth, zAuth, len+1);
2088 }else{
2089 pDb->zAuth = 0;
2091 if( pDb->zAuth ){
2092 typedef int (*sqlite3_auth_cb)(
2093 void*,int,const char*,const char*,
2094 const char*,const char*);
2095 pDb->interp = interp;
2096 sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
2097 }else{
2098 sqlite3_set_authorizer(pDb->db, 0, 0);
2101 #endif
2102 break;
2105 /* $db backup ?DATABASE? FILENAME
2107 ** Open or create a database file named FILENAME. Transfer the
2108 ** content of local database DATABASE (default: "main") into the
2109 ** FILENAME database.
2111 case DB_BACKUP: {
2112 const char *zDestFile;
2113 const char *zSrcDb;
2114 sqlite3 *pDest;
2115 sqlite3_backup *pBackup;
2117 if( objc==3 ){
2118 zSrcDb = "main";
2119 zDestFile = Tcl_GetString(objv[2]);
2120 }else if( objc==4 ){
2121 zSrcDb = Tcl_GetString(objv[2]);
2122 zDestFile = Tcl_GetString(objv[3]);
2123 }else{
2124 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2125 return TCL_ERROR;
2127 rc = sqlite3_open_v2(zDestFile, &pDest,
2128 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
2129 if( rc!=SQLITE_OK ){
2130 Tcl_AppendResult(interp, "cannot open target database: ",
2131 sqlite3_errmsg(pDest), (char*)0);
2132 sqlite3_close(pDest);
2133 return TCL_ERROR;
2135 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
2136 if( pBackup==0 ){
2137 Tcl_AppendResult(interp, "backup failed: ",
2138 sqlite3_errmsg(pDest), (char*)0);
2139 sqlite3_close(pDest);
2140 return TCL_ERROR;
2142 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
2143 sqlite3_backup_finish(pBackup);
2144 if( rc==SQLITE_DONE ){
2145 rc = TCL_OK;
2146 }else{
2147 Tcl_AppendResult(interp, "backup failed: ",
2148 sqlite3_errmsg(pDest), (char*)0);
2149 rc = TCL_ERROR;
2151 sqlite3_close(pDest);
2152 break;
2155 /* $db bind_fallback ?CALLBACK?
2157 ** When resolving bind parameters in an SQL statement, if the parameter
2158 ** cannot be associated with a TCL variable then invoke CALLBACK with a
2159 ** single argument that is the name of the parameter and use the return
2160 ** value of the CALLBACK as the binding. If CALLBACK returns something
2161 ** other than TCL_OK or TCL_ERROR then bind a NULL.
2163 ** If CALLBACK is an empty string, then revert to the default behavior
2164 ** which is to set the binding to NULL.
2166 ** If CALLBACK returns an error, that causes the statement execution to
2167 ** abort. Hence, to configure a connection so that it throws an error
2168 ** on an attempt to bind an unknown variable, do something like this:
2170 ** proc bind_error {name} {error "no such variable: $name"}
2171 ** db bind_fallback bind_error
2173 case DB_BIND_FALLBACK: {
2174 if( objc>3 ){
2175 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2176 return TCL_ERROR;
2177 }else if( objc==2 ){
2178 if( pDb->zBindFallback ){
2179 Tcl_AppendResult(interp, pDb->zBindFallback, (char*)0);
2181 }else{
2182 char *zCallback;
2183 Tcl_Size len;
2184 if( pDb->zBindFallback ){
2185 Tcl_Free(pDb->zBindFallback);
2187 zCallback = Tcl_GetStringFromObj(objv[2], &len);
2188 if( zCallback && len>0 ){
2189 pDb->zBindFallback = Tcl_Alloc( len + 1 );
2190 memcpy(pDb->zBindFallback, zCallback, len+1);
2191 }else{
2192 pDb->zBindFallback = 0;
2195 break;
2198 /* $db busy ?CALLBACK?
2200 ** Invoke the given callback if an SQL statement attempts to open
2201 ** a locked database file.
2203 case DB_BUSY: {
2204 if( objc>3 ){
2205 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
2206 return TCL_ERROR;
2207 }else if( objc==2 ){
2208 if( pDb->zBusy ){
2209 Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
2211 }else{
2212 char *zBusy;
2213 Tcl_Size len;
2214 if( pDb->zBusy ){
2215 Tcl_Free(pDb->zBusy);
2217 zBusy = Tcl_GetStringFromObj(objv[2], &len);
2218 if( zBusy && len>0 ){
2219 pDb->zBusy = Tcl_Alloc( len + 1 );
2220 memcpy(pDb->zBusy, zBusy, len+1);
2221 }else{
2222 pDb->zBusy = 0;
2224 if( pDb->zBusy ){
2225 pDb->interp = interp;
2226 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
2227 }else{
2228 sqlite3_busy_handler(pDb->db, 0, 0);
2231 break;
2234 /* $db cache flush
2235 ** $db cache size n
2237 ** Flush the prepared statement cache, or set the maximum number of
2238 ** cached statements.
2240 case DB_CACHE: {
2241 char *subCmd;
2242 int n;
2244 if( objc<=2 ){
2245 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
2246 return TCL_ERROR;
2248 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
2249 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
2250 if( objc!=3 ){
2251 Tcl_WrongNumArgs(interp, 2, objv, "flush");
2252 return TCL_ERROR;
2253 }else{
2254 flushStmtCache( pDb );
2256 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
2257 if( objc!=4 ){
2258 Tcl_WrongNumArgs(interp, 2, objv, "size n");
2259 return TCL_ERROR;
2260 }else{
2261 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
2262 Tcl_AppendResult( interp, "cannot convert \"",
2263 Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
2264 return TCL_ERROR;
2265 }else{
2266 if( n<0 ){
2267 flushStmtCache( pDb );
2268 n = 0;
2269 }else if( n>MAX_PREPARED_STMTS ){
2270 n = MAX_PREPARED_STMTS;
2272 pDb->maxStmt = n;
2275 }else{
2276 Tcl_AppendResult( interp, "bad option \"",
2277 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
2278 (char*)0);
2279 return TCL_ERROR;
2281 break;
2284 /* $db changes
2286 ** Return the number of rows that were modified, inserted, or deleted by
2287 ** the most recent INSERT, UPDATE or DELETE statement, not including
2288 ** any changes made by trigger programs.
2290 case DB_CHANGES: {
2291 Tcl_Obj *pResult;
2292 if( objc!=2 ){
2293 Tcl_WrongNumArgs(interp, 2, objv, "");
2294 return TCL_ERROR;
2296 pResult = Tcl_GetObjResult(interp);
2297 Tcl_SetWideIntObj(pResult, sqlite3_changes64(pDb->db));
2298 break;
2301 /* $db close
2303 ** Shutdown the database
2305 case DB_CLOSE: {
2306 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
2307 break;
2311 ** $db collate NAME SCRIPT
2313 ** Create a new SQL collation function called NAME. Whenever
2314 ** that function is called, invoke SCRIPT to evaluate the function.
2316 case DB_COLLATE: {
2317 SqlCollate *pCollate;
2318 char *zName;
2319 char *zScript;
2320 Tcl_Size nScript;
2321 if( objc!=4 ){
2322 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
2323 return TCL_ERROR;
2325 zName = Tcl_GetStringFromObj(objv[2], 0);
2326 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
2327 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
2328 if( pCollate==0 ) return TCL_ERROR;
2329 pCollate->interp = interp;
2330 pCollate->pNext = pDb->pCollate;
2331 pCollate->zScript = (char*)&pCollate[1];
2332 pDb->pCollate = pCollate;
2333 memcpy(pCollate->zScript, zScript, nScript+1);
2334 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
2335 pCollate, tclSqlCollate) ){
2336 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
2337 return TCL_ERROR;
2339 break;
2343 ** $db collation_needed SCRIPT
2345 ** Create a new SQL collation function called NAME. Whenever
2346 ** that function is called, invoke SCRIPT to evaluate the function.
2348 case DB_COLLATION_NEEDED: {
2349 if( objc!=3 ){
2350 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
2351 return TCL_ERROR;
2353 if( pDb->pCollateNeeded ){
2354 Tcl_DecrRefCount(pDb->pCollateNeeded);
2356 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
2357 Tcl_IncrRefCount(pDb->pCollateNeeded);
2358 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
2359 break;
2362 /* $db commit_hook ?CALLBACK?
2364 ** Invoke the given callback just before committing every SQL transaction.
2365 ** If the callback throws an exception or returns non-zero, then the
2366 ** transaction is aborted. If CALLBACK is an empty string, the callback
2367 ** is disabled.
2369 case DB_COMMIT_HOOK: {
2370 if( objc>3 ){
2371 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2372 return TCL_ERROR;
2373 }else if( objc==2 ){
2374 if( pDb->zCommit ){
2375 Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
2377 }else{
2378 const char *zCommit;
2379 Tcl_Size len;
2380 if( pDb->zCommit ){
2381 Tcl_Free(pDb->zCommit);
2383 zCommit = Tcl_GetStringFromObj(objv[2], &len);
2384 if( zCommit && len>0 ){
2385 pDb->zCommit = Tcl_Alloc( len + 1 );
2386 memcpy(pDb->zCommit, zCommit, len+1);
2387 }else{
2388 pDb->zCommit = 0;
2390 if( pDb->zCommit ){
2391 pDb->interp = interp;
2392 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
2393 }else{
2394 sqlite3_commit_hook(pDb->db, 0, 0);
2397 break;
2400 /* $db complete SQL
2402 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2403 ** additional lines of input are needed. This is similar to the
2404 ** built-in "info complete" command of Tcl.
2406 case DB_COMPLETE: {
2407 #ifndef SQLITE_OMIT_COMPLETE
2408 Tcl_Obj *pResult;
2409 int isComplete;
2410 if( objc!=3 ){
2411 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2412 return TCL_ERROR;
2414 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
2415 pResult = Tcl_GetObjResult(interp);
2416 Tcl_SetBooleanObj(pResult, isComplete);
2417 #endif
2418 break;
2421 /* $db config ?OPTION? ?BOOLEAN?
2423 ** Configure the database connection using the sqlite3_db_config()
2424 ** interface.
2426 case DB_CONFIG: {
2427 static const struct DbConfigChoices {
2428 const char *zName;
2429 int op;
2430 } aDbConfig[] = {
2431 { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
2432 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL },
2433 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML },
2434 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
2435 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
2436 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
2437 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW },
2438 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
2439 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE },
2440 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT },
2441 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
2442 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
2443 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
2444 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
2445 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA },
2446 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA },
2448 Tcl_Obj *pResult;
2449 int ii;
2450 if( objc>4 ){
2451 Tcl_WrongNumArgs(interp, 2, objv, "?OPTION? ?BOOLEAN?");
2452 return TCL_ERROR;
2454 if( objc==2 ){
2455 /* With no arguments, list all configuration options and with the
2456 ** current value */
2457 pResult = Tcl_NewListObj(0,0);
2458 for(ii=0; ii<sizeof(aDbConfig)/sizeof(aDbConfig[0]); ii++){
2459 int v = 0;
2460 sqlite3_db_config(pDb->db, aDbConfig[ii].op, -1, &v);
2461 Tcl_ListObjAppendElement(interp, pResult,
2462 Tcl_NewStringObj(aDbConfig[ii].zName,-1));
2463 Tcl_ListObjAppendElement(interp, pResult,
2464 Tcl_NewIntObj(v));
2466 }else{
2467 const char *zOpt = Tcl_GetString(objv[2]);
2468 int onoff = -1;
2469 int v = 0;
2470 if( zOpt[0]=='-' ) zOpt++;
2471 for(ii=0; ii<sizeof(aDbConfig)/sizeof(aDbConfig[0]); ii++){
2472 if( strcmp(aDbConfig[ii].zName, zOpt)==0 ) break;
2474 if( ii>=sizeof(aDbConfig)/sizeof(aDbConfig[0]) ){
2475 Tcl_AppendResult(interp, "unknown config option: \"", zOpt,
2476 "\"", (void*)0);
2477 return TCL_ERROR;
2479 if( objc==4 ){
2480 if( Tcl_GetBooleanFromObj(interp, objv[3], &onoff) ){
2481 return TCL_ERROR;
2484 sqlite3_db_config(pDb->db, aDbConfig[ii].op, onoff, &v);
2485 pResult = Tcl_NewIntObj(v);
2487 Tcl_SetObjResult(interp, pResult);
2488 break;
2491 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2493 ** Copy data into table from filename, optionally using SEPARATOR
2494 ** as column separators. If a column contains a null string, or the
2495 ** value of NULLINDICATOR, a NULL is inserted for the column.
2496 ** conflict-algorithm is one of the sqlite conflict algorithms:
2497 ** rollback, abort, fail, ignore, replace
2498 ** On success, return the number of lines processed, not necessarily same
2499 ** as 'db changes' due to conflict-algorithm selected.
2501 ** This code is basically an implementation/enhancement of
2502 ** the sqlite3 shell.c ".import" command.
2504 ** This command usage is equivalent to the sqlite2.x COPY statement,
2505 ** which imports file data into a table using the PostgreSQL COPY file format:
2506 ** $db copy $conflict_algorithm $table_name $filename \t \\N
2508 case DB_COPY: {
2509 char *zTable; /* Insert data into this table */
2510 char *zFile; /* The file from which to extract data */
2511 char *zConflict; /* The conflict algorithm to use */
2512 sqlite3_stmt *pStmt; /* A statement */
2513 int nCol; /* Number of columns in the table */
2514 int nByte; /* Number of bytes in an SQL string */
2515 int i, j; /* Loop counters */
2516 int nSep; /* Number of bytes in zSep[] */
2517 int nNull; /* Number of bytes in zNull[] */
2518 char *zSql; /* An SQL statement */
2519 char *zLine; /* A single line of input from the file */
2520 char **azCol; /* zLine[] broken up into columns */
2521 const char *zCommit; /* How to commit changes */
2522 FILE *in; /* The input file */
2523 int lineno = 0; /* Line number of input file */
2524 char zLineNum[80]; /* Line number print buffer */
2525 Tcl_Obj *pResult; /* interp result */
2527 const char *zSep;
2528 const char *zNull;
2529 if( objc<5 || objc>7 ){
2530 Tcl_WrongNumArgs(interp, 2, objv,
2531 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2532 return TCL_ERROR;
2534 if( objc>=6 ){
2535 zSep = Tcl_GetStringFromObj(objv[5], 0);
2536 }else{
2537 zSep = "\t";
2539 if( objc>=7 ){
2540 zNull = Tcl_GetStringFromObj(objv[6], 0);
2541 }else{
2542 zNull = "";
2544 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2545 zTable = Tcl_GetStringFromObj(objv[3], 0);
2546 zFile = Tcl_GetStringFromObj(objv[4], 0);
2547 nSep = strlen30(zSep);
2548 nNull = strlen30(zNull);
2549 if( nSep==0 ){
2550 Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2551 (char*)0);
2552 return TCL_ERROR;
2554 if(strcmp(zConflict, "rollback") != 0 &&
2555 strcmp(zConflict, "abort" ) != 0 &&
2556 strcmp(zConflict, "fail" ) != 0 &&
2557 strcmp(zConflict, "ignore" ) != 0 &&
2558 strcmp(zConflict, "replace" ) != 0 ) {
2559 Tcl_AppendResult(interp, "Error: \"", zConflict,
2560 "\", conflict-algorithm must be one of: rollback, "
2561 "abort, fail, ignore, or replace", (char*)0);
2562 return TCL_ERROR;
2564 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2565 if( zSql==0 ){
2566 Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
2567 return TCL_ERROR;
2569 nByte = strlen30(zSql);
2570 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
2571 sqlite3_free(zSql);
2572 if( rc ){
2573 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2574 nCol = 0;
2575 }else{
2576 nCol = sqlite3_column_count(pStmt);
2578 sqlite3_finalize(pStmt);
2579 if( nCol==0 ) {
2580 return TCL_ERROR;
2582 zSql = malloc( nByte + 50 + nCol*2 );
2583 if( zSql==0 ) {
2584 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
2585 return TCL_ERROR;
2587 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2588 zConflict, zTable);
2589 j = strlen30(zSql);
2590 for(i=1; i<nCol; i++){
2591 zSql[j++] = ',';
2592 zSql[j++] = '?';
2594 zSql[j++] = ')';
2595 zSql[j] = 0;
2596 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
2597 free(zSql);
2598 if( rc ){
2599 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2600 sqlite3_finalize(pStmt);
2601 return TCL_ERROR;
2603 in = fopen(zFile, "rb");
2604 if( in==0 ){
2605 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, (char*)0);
2606 sqlite3_finalize(pStmt);
2607 return TCL_ERROR;
2609 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2610 if( azCol==0 ) {
2611 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
2612 fclose(in);
2613 return TCL_ERROR;
2615 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
2616 zCommit = "COMMIT";
2617 while( (zLine = local_getline(0, in))!=0 ){
2618 char *z;
2619 lineno++;
2620 azCol[0] = zLine;
2621 for(i=0, z=zLine; *z; z++){
2622 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2623 *z = 0;
2624 i++;
2625 if( i<nCol ){
2626 azCol[i] = &z[nSep];
2627 z += nSep-1;
2631 if( i+1!=nCol ){
2632 char *zErr;
2633 int nErr = strlen30(zFile) + 200;
2634 zErr = malloc(nErr);
2635 if( zErr ){
2636 sqlite3_snprintf(nErr, zErr,
2637 "Error: %s line %d: expected %d columns of data but found %d",
2638 zFile, lineno, nCol, i+1);
2639 Tcl_AppendResult(interp, zErr, (char*)0);
2640 free(zErr);
2642 zCommit = "ROLLBACK";
2643 break;
2645 for(i=0; i<nCol; i++){
2646 /* check for null data, if so, bind as null */
2647 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
2648 || strlen30(azCol[i])==0
2650 sqlite3_bind_null(pStmt, i+1);
2651 }else{
2652 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2655 sqlite3_step(pStmt);
2656 rc = sqlite3_reset(pStmt);
2657 free(zLine);
2658 if( rc!=SQLITE_OK ){
2659 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2660 zCommit = "ROLLBACK";
2661 break;
2664 free(azCol);
2665 fclose(in);
2666 sqlite3_finalize(pStmt);
2667 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
2669 if( zCommit[0] == 'C' ){
2670 /* success, set result as number of lines processed */
2671 pResult = Tcl_GetObjResult(interp);
2672 Tcl_SetIntObj(pResult, lineno);
2673 rc = TCL_OK;
2674 }else{
2675 /* failure, append lineno where failed */
2676 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
2677 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2678 (char*)0);
2679 rc = TCL_ERROR;
2681 break;
2685 ** $db deserialize ?-maxsize N? ?-readonly BOOL? ?DATABASE? VALUE
2687 ** Reopen DATABASE (default "main") using the content in $VALUE
2689 case DB_DESERIALIZE: {
2690 #ifdef SQLITE_OMIT_DESERIALIZE
2691 Tcl_AppendResult(interp, "MEMDB not available in this build",
2692 (char*)0);
2693 rc = TCL_ERROR;
2694 #else
2695 const char *zSchema = 0;
2696 Tcl_Obj *pValue = 0;
2697 unsigned char *pBA;
2698 unsigned char *pData;
2699 Tcl_Size len;
2700 int xrc;
2701 sqlite3_int64 mxSize = 0;
2702 int i;
2703 int isReadonly = 0;
2706 if( objc<3 ){
2707 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? VALUE");
2708 rc = TCL_ERROR;
2709 break;
2711 for(i=2; i<objc-1; i++){
2712 const char *z = Tcl_GetString(objv[i]);
2713 if( strcmp(z,"-maxsize")==0 && i<objc-2 ){
2714 Tcl_WideInt x;
2715 rc = Tcl_GetWideIntFromObj(interp, objv[++i], &x);
2716 if( rc ) goto deserialize_error;
2717 mxSize = x;
2718 continue;
2720 if( strcmp(z,"-readonly")==0 && i<objc-2 ){
2721 rc = Tcl_GetBooleanFromObj(interp, objv[++i], &isReadonly);
2722 if( rc ) goto deserialize_error;
2723 continue;
2725 if( zSchema==0 && i==objc-2 && z[0]!='-' ){
2726 zSchema = z;
2727 continue;
2729 Tcl_AppendResult(interp, "unknown option: ", z, (char*)0);
2730 rc = TCL_ERROR;
2731 goto deserialize_error;
2733 pValue = objv[objc-1];
2734 pBA = Tcl_GetByteArrayFromObj(pValue, &len);
2735 pData = sqlite3_malloc64( len );
2736 if( pData==0 && len>0 ){
2737 Tcl_AppendResult(interp, "out of memory", (char*)0);
2738 rc = TCL_ERROR;
2739 }else{
2740 int flags;
2741 if( len>0 ) memcpy(pData, pBA, len);
2742 if( isReadonly ){
2743 flags = SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_READONLY;
2744 }else{
2745 flags = SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_RESIZEABLE;
2747 xrc = sqlite3_deserialize(pDb->db, zSchema, pData, len, len, flags);
2748 if( xrc ){
2749 Tcl_AppendResult(interp, "unable to set MEMDB content", (char*)0);
2750 rc = TCL_ERROR;
2752 if( mxSize>0 ){
2753 sqlite3_file_control(pDb->db, zSchema,SQLITE_FCNTL_SIZE_LIMIT,&mxSize);
2756 deserialize_error:
2757 #endif
2758 break;
2762 ** $db enable_load_extension BOOLEAN
2764 ** Turn the extension loading feature on or off. It if off by
2765 ** default.
2767 case DB_ENABLE_LOAD_EXTENSION: {
2768 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2769 int onoff;
2770 if( objc!=3 ){
2771 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2772 return TCL_ERROR;
2774 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2775 return TCL_ERROR;
2777 sqlite3_enable_load_extension(pDb->db, onoff);
2778 break;
2779 #else
2780 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2781 (char*)0);
2782 return TCL_ERROR;
2783 #endif
2787 ** $db errorcode
2789 ** Return the numeric error code that was returned by the most recent
2790 ** call to sqlite3_exec().
2792 case DB_ERRORCODE: {
2793 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
2794 break;
2798 ** $db erroroffset
2800 ** Return the numeric error code that was returned by the most recent
2801 ** call to sqlite3_exec().
2803 case DB_ERROROFFSET: {
2804 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_error_offset(pDb->db)));
2805 break;
2809 ** $db exists $sql
2810 ** $db onecolumn $sql
2812 ** The onecolumn method is the equivalent of:
2813 ** lindex [$db eval $sql] 0
2815 case DB_EXISTS:
2816 case DB_ONECOLUMN: {
2817 Tcl_Obj *pResult = 0;
2818 DbEvalContext sEval;
2819 if( objc!=3 ){
2820 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2821 return TCL_ERROR;
2824 dbEvalInit(&sEval, pDb, objv[2], 0, 0);
2825 rc = dbEvalStep(&sEval);
2826 if( choice==DB_ONECOLUMN ){
2827 if( rc==TCL_OK ){
2828 pResult = dbEvalColumnValue(&sEval, 0);
2829 }else if( rc==TCL_BREAK ){
2830 Tcl_ResetResult(interp);
2832 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2833 pResult = Tcl_NewBooleanObj(rc==TCL_OK);
2835 dbEvalFinalize(&sEval);
2836 if( pResult ) Tcl_SetObjResult(interp, pResult);
2838 if( rc==TCL_BREAK ){
2839 rc = TCL_OK;
2841 break;
2845 ** $db eval ?options? $sql ?array? ?{ ...code... }?
2847 ** The SQL statement in $sql is evaluated. For each row, the values are
2848 ** placed in elements of the array named "array" and ...code... is executed.
2849 ** If "array" and "code" are omitted, then no callback is every invoked.
2850 ** If "array" is an empty string, then the values are placed in variables
2851 ** that have the same name as the fields extracted by the query.
2853 case DB_EVAL: {
2854 int evalFlags = 0;
2855 const char *zOpt;
2856 while( objc>3 && (zOpt = Tcl_GetString(objv[2]))!=0 && zOpt[0]=='-' ){
2857 if( strcmp(zOpt, "-withoutnulls")==0 ){
2858 evalFlags |= SQLITE_EVAL_WITHOUTNULLS;
2860 else{
2861 Tcl_AppendResult(interp, "unknown option: \"", zOpt, "\"", (void*)0);
2862 return TCL_ERROR;
2864 objc--;
2865 objv++;
2867 if( objc<3 || objc>5 ){
2868 Tcl_WrongNumArgs(interp, 2, objv,
2869 "?OPTIONS? SQL ?ARRAY-NAME? ?SCRIPT?");
2870 return TCL_ERROR;
2873 if( objc==3 ){
2874 DbEvalContext sEval;
2875 Tcl_Obj *pRet = Tcl_NewObj();
2876 Tcl_IncrRefCount(pRet);
2877 dbEvalInit(&sEval, pDb, objv[2], 0, 0);
2878 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2879 int i;
2880 int nCol;
2881 dbEvalRowInfo(&sEval, &nCol, 0);
2882 for(i=0; i<nCol; i++){
2883 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
2886 dbEvalFinalize(&sEval);
2887 if( rc==TCL_BREAK ){
2888 Tcl_SetObjResult(interp, pRet);
2889 rc = TCL_OK;
2891 Tcl_DecrRefCount(pRet);
2892 }else{
2893 ClientData cd2[2];
2894 DbEvalContext *p;
2895 Tcl_Obj *pArray = 0;
2896 Tcl_Obj *pScript;
2898 if( objc>=5 && *(char *)Tcl_GetString(objv[3]) ){
2899 pArray = objv[3];
2901 pScript = objv[objc-1];
2902 Tcl_IncrRefCount(pScript);
2904 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2905 dbEvalInit(p, pDb, objv[2], pArray, evalFlags);
2907 cd2[0] = (void *)p;
2908 cd2[1] = (void *)pScript;
2909 rc = DbEvalNextCmd(cd2, interp, TCL_OK);
2911 break;
2915 ** $db function NAME [OPTIONS] SCRIPT
2917 ** Create a new SQL function called NAME. Whenever that function is
2918 ** called, invoke SCRIPT to evaluate the function.
2920 ** Options:
2921 ** --argcount N Function has exactly N arguments
2922 ** --deterministic The function is pure
2923 ** --directonly Prohibit use inside triggers and views
2924 ** --innocuous Has no side effects or information leaks
2925 ** --returntype TYPE Specify the return type of the function
2927 case DB_FUNCTION: {
2928 int flags = SQLITE_UTF8;
2929 SqlFunc *pFunc;
2930 Tcl_Obj *pScript;
2931 char *zName;
2932 int nArg = -1;
2933 int i;
2934 int eType = SQLITE_NULL;
2935 if( objc<4 ){
2936 Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
2937 return TCL_ERROR;
2939 for(i=3; i<(objc-1); i++){
2940 const char *z = Tcl_GetString(objv[i]);
2941 int n = strlen30(z);
2942 if( n>1 && strncmp(z, "-argcount",n)==0 ){
2943 if( i==(objc-2) ){
2944 Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0);
2945 return TCL_ERROR;
2947 if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
2948 if( nArg<0 ){
2949 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2950 (char*)0);
2951 return TCL_ERROR;
2953 i++;
2954 }else
2955 if( n>1 && strncmp(z, "-deterministic",n)==0 ){
2956 flags |= SQLITE_DETERMINISTIC;
2957 }else
2958 if( n>1 && strncmp(z, "-directonly",n)==0 ){
2959 flags |= SQLITE_DIRECTONLY;
2960 }else
2961 if( n>1 && strncmp(z, "-innocuous",n)==0 ){
2962 flags |= SQLITE_INNOCUOUS;
2963 }else
2964 if( n>1 && strncmp(z, "-returntype", n)==0 ){
2965 const char *azType[] = {"integer", "real", "text", "blob", "any", 0};
2966 assert( SQLITE_INTEGER==1 && SQLITE_FLOAT==2 && SQLITE_TEXT==3 );
2967 assert( SQLITE_BLOB==4 && SQLITE_NULL==5 );
2968 if( i==(objc-2) ){
2969 Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0);
2970 return TCL_ERROR;
2972 i++;
2973 if( Tcl_GetIndexFromObj(interp, objv[i], azType, "type", 0, &eType) ){
2974 return TCL_ERROR;
2976 eType++;
2977 }else{
2978 Tcl_AppendResult(interp, "bad option \"", z,
2979 "\": must be -argcount, -deterministic, -directonly,"
2980 " -innocuous, or -returntype", (char*)0
2982 return TCL_ERROR;
2986 pScript = objv[objc-1];
2987 zName = Tcl_GetStringFromObj(objv[2], 0);
2988 pFunc = findSqlFunc(pDb, zName);
2989 if( pFunc==0 ) return TCL_ERROR;
2990 if( pFunc->pScript ){
2991 Tcl_DecrRefCount(pFunc->pScript);
2993 pFunc->pScript = pScript;
2994 Tcl_IncrRefCount(pScript);
2995 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
2996 pFunc->eType = eType;
2997 rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
2998 pFunc, tclSqlFunc, 0, 0);
2999 if( rc!=SQLITE_OK ){
3000 rc = TCL_ERROR;
3001 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
3003 break;
3007 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
3009 case DB_INCRBLOB: {
3010 #ifdef SQLITE_OMIT_INCRBLOB
3011 Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
3012 return TCL_ERROR;
3013 #else
3014 int isReadonly = 0;
3015 const char *zDb = "main";
3016 const char *zTable;
3017 const char *zColumn;
3018 Tcl_WideInt iRow;
3020 /* Check for the -readonly option */
3021 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
3022 isReadonly = 1;
3025 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
3026 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
3027 return TCL_ERROR;
3030 if( objc==(6+isReadonly) ){
3031 zDb = Tcl_GetString(objv[2+isReadonly]);
3033 zTable = Tcl_GetString(objv[objc-3]);
3034 zColumn = Tcl_GetString(objv[objc-2]);
3035 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
3037 if( rc==TCL_OK ){
3038 rc = createIncrblobChannel(
3039 interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
3042 #endif
3043 break;
3047 ** $db interrupt
3049 ** Interrupt the execution of the inner-most SQL interpreter. This
3050 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
3052 case DB_INTERRUPT: {
3053 sqlite3_interrupt(pDb->db);
3054 break;
3058 ** $db nullvalue ?STRING?
3060 ** Change text used when a NULL comes back from the database. If ?STRING?
3061 ** is not present, then the current string used for NULL is returned.
3062 ** If STRING is present, then STRING is returned.
3065 case DB_NULLVALUE: {
3066 if( objc!=2 && objc!=3 ){
3067 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
3068 return TCL_ERROR;
3070 if( objc==3 ){
3071 Tcl_Size len;
3072 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
3073 if( pDb->zNull ){
3074 Tcl_Free(pDb->zNull);
3076 if( zNull && len>0 ){
3077 pDb->zNull = Tcl_Alloc( len + 1 );
3078 memcpy(pDb->zNull, zNull, len);
3079 pDb->zNull[len] = '\0';
3080 }else{
3081 pDb->zNull = 0;
3084 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
3085 break;
3089 ** $db last_insert_rowid
3091 ** Return an integer which is the ROWID for the most recent insert.
3093 case DB_LAST_INSERT_ROWID: {
3094 Tcl_Obj *pResult;
3095 Tcl_WideInt rowid;
3096 if( objc!=2 ){
3097 Tcl_WrongNumArgs(interp, 2, objv, "");
3098 return TCL_ERROR;
3100 rowid = sqlite3_last_insert_rowid(pDb->db);
3101 pResult = Tcl_GetObjResult(interp);
3102 Tcl_SetWideIntObj(pResult, rowid);
3103 break;
3107 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
3110 /* $db progress ?N CALLBACK?
3112 ** Invoke the given callback every N virtual machine opcodes while executing
3113 ** queries.
3115 case DB_PROGRESS: {
3116 if( objc==2 ){
3117 if( pDb->zProgress ){
3118 Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
3120 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
3121 sqlite3_progress_handler(pDb->db, 0, 0, 0);
3122 #endif
3123 }else if( objc==4 ){
3124 char *zProgress;
3125 Tcl_Size len;
3126 int N;
3127 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
3128 return TCL_ERROR;
3130 if( pDb->zProgress ){
3131 Tcl_Free(pDb->zProgress);
3133 zProgress = Tcl_GetStringFromObj(objv[3], &len);
3134 if( zProgress && len>0 ){
3135 pDb->zProgress = Tcl_Alloc( len + 1 );
3136 memcpy(pDb->zProgress, zProgress, len+1);
3137 }else{
3138 pDb->zProgress = 0;
3140 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
3141 if( pDb->zProgress ){
3142 pDb->interp = interp;
3143 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
3144 }else{
3145 sqlite3_progress_handler(pDb->db, 0, 0, 0);
3147 #endif
3148 }else{
3149 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
3150 return TCL_ERROR;
3152 break;
3155 /* $db profile ?CALLBACK?
3157 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
3158 ** that has run. The text of the SQL and the amount of elapse time are
3159 ** appended to CALLBACK before the script is run.
3161 case DB_PROFILE: {
3162 if( objc>3 ){
3163 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
3164 return TCL_ERROR;
3165 }else if( objc==2 ){
3166 if( pDb->zProfile ){
3167 Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
3169 }else{
3170 char *zProfile;
3171 Tcl_Size len;
3172 if( pDb->zProfile ){
3173 Tcl_Free(pDb->zProfile);
3175 zProfile = Tcl_GetStringFromObj(objv[2], &len);
3176 if( zProfile && len>0 ){
3177 pDb->zProfile = Tcl_Alloc( len + 1 );
3178 memcpy(pDb->zProfile, zProfile, len+1);
3179 }else{
3180 pDb->zProfile = 0;
3182 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3183 !defined(SQLITE_OMIT_DEPRECATED)
3184 if( pDb->zProfile ){
3185 pDb->interp = interp;
3186 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
3187 }else{
3188 sqlite3_profile(pDb->db, 0, 0);
3190 #endif
3192 break;
3196 ** $db rekey KEY
3198 ** Change the encryption key on the currently open database.
3200 case DB_REKEY: {
3201 if( objc!=3 ){
3202 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
3203 return TCL_ERROR;
3205 break;
3208 /* $db restore ?DATABASE? FILENAME
3210 ** Open a database file named FILENAME. Transfer the content
3211 ** of FILENAME into the local database DATABASE (default: "main").
3213 case DB_RESTORE: {
3214 const char *zSrcFile;
3215 const char *zDestDb;
3216 sqlite3 *pSrc;
3217 sqlite3_backup *pBackup;
3218 int nTimeout = 0;
3220 if( objc==3 ){
3221 zDestDb = "main";
3222 zSrcFile = Tcl_GetString(objv[2]);
3223 }else if( objc==4 ){
3224 zDestDb = Tcl_GetString(objv[2]);
3225 zSrcFile = Tcl_GetString(objv[3]);
3226 }else{
3227 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
3228 return TCL_ERROR;
3230 rc = sqlite3_open_v2(zSrcFile, &pSrc,
3231 SQLITE_OPEN_READONLY | pDb->openFlags, 0);
3232 if( rc!=SQLITE_OK ){
3233 Tcl_AppendResult(interp, "cannot open source database: ",
3234 sqlite3_errmsg(pSrc), (char*)0);
3235 sqlite3_close(pSrc);
3236 return TCL_ERROR;
3238 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
3239 if( pBackup==0 ){
3240 Tcl_AppendResult(interp, "restore failed: ",
3241 sqlite3_errmsg(pDb->db), (char*)0);
3242 sqlite3_close(pSrc);
3243 return TCL_ERROR;
3245 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
3246 || rc==SQLITE_BUSY ){
3247 if( rc==SQLITE_BUSY ){
3248 if( nTimeout++ >= 3 ) break;
3249 sqlite3_sleep(100);
3252 sqlite3_backup_finish(pBackup);
3253 if( rc==SQLITE_DONE ){
3254 rc = TCL_OK;
3255 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
3256 Tcl_AppendResult(interp, "restore failed: source database busy",
3257 (char*)0);
3258 rc = TCL_ERROR;
3259 }else{
3260 Tcl_AppendResult(interp, "restore failed: ",
3261 sqlite3_errmsg(pDb->db), (char*)0);
3262 rc = TCL_ERROR;
3264 sqlite3_close(pSrc);
3265 break;
3269 ** $db serialize ?DATABASE?
3271 ** Return a serialization of a database.
3273 case DB_SERIALIZE: {
3274 #ifdef SQLITE_OMIT_DESERIALIZE
3275 Tcl_AppendResult(interp, "MEMDB not available in this build",
3276 (char*)0);
3277 rc = TCL_ERROR;
3278 #else
3279 const char *zSchema = objc>=3 ? Tcl_GetString(objv[2]) : "main";
3280 sqlite3_int64 sz = 0;
3281 unsigned char *pData;
3282 if( objc!=2 && objc!=3 ){
3283 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE?");
3284 rc = TCL_ERROR;
3285 }else{
3286 int needFree;
3287 pData = sqlite3_serialize(pDb->db, zSchema, &sz, SQLITE_SERIALIZE_NOCOPY);
3288 if( pData ){
3289 needFree = 0;
3290 }else{
3291 pData = sqlite3_serialize(pDb->db, zSchema, &sz, 0);
3292 needFree = 1;
3294 Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(pData,sz));
3295 if( needFree ) sqlite3_free(pData);
3297 #endif
3298 break;
3302 ** $db status (step|sort|autoindex|vmstep)
3304 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
3305 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
3307 case DB_STATUS: {
3308 int v;
3309 const char *zOp;
3310 if( objc!=3 ){
3311 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
3312 return TCL_ERROR;
3314 zOp = Tcl_GetString(objv[2]);
3315 if( strcmp(zOp, "step")==0 ){
3316 v = pDb->nStep;
3317 }else if( strcmp(zOp, "sort")==0 ){
3318 v = pDb->nSort;
3319 }else if( strcmp(zOp, "autoindex")==0 ){
3320 v = pDb->nIndex;
3321 }else if( strcmp(zOp, "vmstep")==0 ){
3322 v = pDb->nVMStep;
3323 }else{
3324 Tcl_AppendResult(interp,
3325 "bad argument: should be autoindex, step, sort or vmstep",
3326 (char*)0);
3327 return TCL_ERROR;
3329 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
3330 break;
3334 ** $db timeout MILLESECONDS
3336 ** Delay for the number of milliseconds specified when a file is locked.
3338 case DB_TIMEOUT: {
3339 int ms;
3340 if( objc!=3 ){
3341 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
3342 return TCL_ERROR;
3344 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
3345 sqlite3_busy_timeout(pDb->db, ms);
3346 break;
3350 ** $db total_changes
3352 ** Return the number of rows that were modified, inserted, or deleted
3353 ** since the database handle was created.
3355 case DB_TOTAL_CHANGES: {
3356 Tcl_Obj *pResult;
3357 if( objc!=2 ){
3358 Tcl_WrongNumArgs(interp, 2, objv, "");
3359 return TCL_ERROR;
3361 pResult = Tcl_GetObjResult(interp);
3362 Tcl_SetWideIntObj(pResult, sqlite3_total_changes64(pDb->db));
3363 break;
3366 /* $db trace ?CALLBACK?
3368 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
3369 ** that is executed. The text of the SQL is appended to CALLBACK before
3370 ** it is executed.
3372 case DB_TRACE: {
3373 if( objc>3 ){
3374 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
3375 return TCL_ERROR;
3376 }else if( objc==2 ){
3377 if( pDb->zTrace ){
3378 Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
3380 }else{
3381 char *zTrace;
3382 Tcl_Size len;
3383 if( pDb->zTrace ){
3384 Tcl_Free(pDb->zTrace);
3386 zTrace = Tcl_GetStringFromObj(objv[2], &len);
3387 if( zTrace && len>0 ){
3388 pDb->zTrace = Tcl_Alloc( len + 1 );
3389 memcpy(pDb->zTrace, zTrace, len+1);
3390 }else{
3391 pDb->zTrace = 0;
3393 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3394 !defined(SQLITE_OMIT_DEPRECATED)
3395 if( pDb->zTrace ){
3396 pDb->interp = interp;
3397 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
3398 }else{
3399 sqlite3_trace(pDb->db, 0, 0);
3401 #endif
3403 break;
3406 /* $db trace_v2 ?CALLBACK? ?MASK?
3408 ** Make arrangements to invoke the CALLBACK routine for each trace event
3409 ** matching the mask that is generated. The parameters are appended to
3410 ** CALLBACK before it is executed.
3412 case DB_TRACE_V2: {
3413 if( objc>4 ){
3414 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK? ?MASK?");
3415 return TCL_ERROR;
3416 }else if( objc==2 ){
3417 if( pDb->zTraceV2 ){
3418 Tcl_AppendResult(interp, pDb->zTraceV2, (char*)0);
3420 }else{
3421 char *zTraceV2;
3422 Tcl_Size len;
3423 Tcl_WideInt wMask = 0;
3424 if( objc==4 ){
3425 static const char *TTYPE_strs[] = {
3426 "statement", "profile", "row", "close", 0
3428 enum TTYPE_enum {
3429 TTYPE_STMT, TTYPE_PROFILE, TTYPE_ROW, TTYPE_CLOSE
3431 int i;
3432 if( TCL_OK!=Tcl_ListObjLength(interp, objv[3], &len) ){
3433 return TCL_ERROR;
3435 for(i=0; i<len; i++){
3436 Tcl_Obj *pObj;
3437 int ttype;
3438 if( TCL_OK!=Tcl_ListObjIndex(interp, objv[3], i, &pObj) ){
3439 return TCL_ERROR;
3441 if( Tcl_GetIndexFromObj(interp, pObj, TTYPE_strs, "trace type",
3442 0, &ttype)!=TCL_OK ){
3443 Tcl_WideInt wType;
3444 Tcl_Obj *pError = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
3445 Tcl_IncrRefCount(pError);
3446 if( TCL_OK==Tcl_GetWideIntFromObj(interp, pObj, &wType) ){
3447 Tcl_DecrRefCount(pError);
3448 wMask |= wType;
3449 }else{
3450 Tcl_SetObjResult(interp, pError);
3451 Tcl_DecrRefCount(pError);
3452 return TCL_ERROR;
3454 }else{
3455 switch( (enum TTYPE_enum)ttype ){
3456 case TTYPE_STMT: wMask |= SQLITE_TRACE_STMT; break;
3457 case TTYPE_PROFILE: wMask |= SQLITE_TRACE_PROFILE; break;
3458 case TTYPE_ROW: wMask |= SQLITE_TRACE_ROW; break;
3459 case TTYPE_CLOSE: wMask |= SQLITE_TRACE_CLOSE; break;
3463 }else{
3464 wMask = SQLITE_TRACE_STMT; /* use the "legacy" default */
3466 if( pDb->zTraceV2 ){
3467 Tcl_Free(pDb->zTraceV2);
3469 zTraceV2 = Tcl_GetStringFromObj(objv[2], &len);
3470 if( zTraceV2 && len>0 ){
3471 pDb->zTraceV2 = Tcl_Alloc( len + 1 );
3472 memcpy(pDb->zTraceV2, zTraceV2, len+1);
3473 }else{
3474 pDb->zTraceV2 = 0;
3476 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3477 if( pDb->zTraceV2 ){
3478 pDb->interp = interp;
3479 sqlite3_trace_v2(pDb->db, (unsigned)wMask, DbTraceV2Handler, pDb);
3480 }else{
3481 sqlite3_trace_v2(pDb->db, 0, 0, 0);
3483 #endif
3485 break;
3488 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
3490 ** Start a new transaction (if we are not already in the midst of a
3491 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
3492 ** completes, either commit the transaction or roll it back if SCRIPT
3493 ** throws an exception. Or if no new transaction was started, do nothing.
3494 ** pass the exception on up the stack.
3496 ** This command was inspired by Dave Thomas's talk on Ruby at the
3497 ** 2005 O'Reilly Open Source Convention (OSCON).
3499 case DB_TRANSACTION: {
3500 Tcl_Obj *pScript;
3501 const char *zBegin = "SAVEPOINT _tcl_transaction";
3502 if( objc!=3 && objc!=4 ){
3503 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
3504 return TCL_ERROR;
3507 if( pDb->nTransaction==0 && objc==4 ){
3508 static const char *TTYPE_strs[] = {
3509 "deferred", "exclusive", "immediate", 0
3511 enum TTYPE_enum {
3512 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
3514 int ttype;
3515 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
3516 0, &ttype) ){
3517 return TCL_ERROR;
3519 switch( (enum TTYPE_enum)ttype ){
3520 case TTYPE_DEFERRED: /* no-op */; break;
3521 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
3522 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
3525 pScript = objv[objc-1];
3527 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
3528 pDb->disableAuth++;
3529 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
3530 pDb->disableAuth--;
3531 if( rc!=SQLITE_OK ){
3532 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3533 return TCL_ERROR;
3535 pDb->nTransaction++;
3537 /* If using NRE, schedule a callback to invoke the script pScript, then
3538 ** a second callback to commit (or rollback) the transaction or savepoint
3539 ** opened above. If not using NRE, evaluate the script directly, then
3540 ** call function DbTransPostCmd() to commit (or rollback) the transaction
3541 ** or savepoint. */
3542 addDatabaseRef(pDb); /* DbTransPostCmd() calls delDatabaseRef() */
3543 if( DbUseNre() ){
3544 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
3545 (void)Tcl_NREvalObj(interp, pScript, 0);
3546 }else{
3547 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
3549 break;
3553 ** $db unlock_notify ?script?
3555 case DB_UNLOCK_NOTIFY: {
3556 #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
3557 Tcl_AppendResult(interp, "unlock_notify not available in this build",
3558 (char*)0);
3559 rc = TCL_ERROR;
3560 #else
3561 if( objc!=2 && objc!=3 ){
3562 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3563 rc = TCL_ERROR;
3564 }else{
3565 void (*xNotify)(void **, int) = 0;
3566 void *pNotifyArg = 0;
3568 if( pDb->pUnlockNotify ){
3569 Tcl_DecrRefCount(pDb->pUnlockNotify);
3570 pDb->pUnlockNotify = 0;
3573 if( objc==3 ){
3574 xNotify = DbUnlockNotify;
3575 pNotifyArg = (void *)pDb;
3576 pDb->pUnlockNotify = objv[2];
3577 Tcl_IncrRefCount(pDb->pUnlockNotify);
3580 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
3581 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3582 rc = TCL_ERROR;
3585 #endif
3586 break;
3590 ** $db preupdate_hook count
3591 ** $db preupdate_hook hook ?SCRIPT?
3592 ** $db preupdate_hook new INDEX
3593 ** $db preupdate_hook old INDEX
3595 case DB_PREUPDATE: {
3596 #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
3597 Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time",
3598 (char*)0);
3599 rc = TCL_ERROR;
3600 #else
3601 static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
3602 enum DbPreupdateSubCmd {
3603 PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
3605 int iSub;
3607 if( objc<3 ){
3608 Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
3610 if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
3611 return TCL_ERROR;
3614 switch( (enum DbPreupdateSubCmd)iSub ){
3615 case PRE_COUNT: {
3616 int nCol = sqlite3_preupdate_count(pDb->db);
3617 Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
3618 break;
3621 case PRE_HOOK: {
3622 if( objc>4 ){
3623 Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
3624 return TCL_ERROR;
3626 DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
3627 break;
3630 case PRE_DEPTH: {
3631 Tcl_Obj *pRet;
3632 if( objc!=3 ){
3633 Tcl_WrongNumArgs(interp, 3, objv, "");
3634 return TCL_ERROR;
3636 pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
3637 Tcl_SetObjResult(interp, pRet);
3638 break;
3641 case PRE_NEW:
3642 case PRE_OLD: {
3643 int iIdx;
3644 sqlite3_value *pValue;
3645 if( objc!=4 ){
3646 Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
3647 return TCL_ERROR;
3649 if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
3650 return TCL_ERROR;
3653 if( iSub==PRE_OLD ){
3654 rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
3655 }else{
3656 assert( iSub==PRE_NEW );
3657 rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
3660 if( rc==SQLITE_OK ){
3661 Tcl_Obj *pObj;
3662 pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
3663 Tcl_SetObjResult(interp, pObj);
3664 }else{
3665 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3666 return TCL_ERROR;
3670 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
3671 break;
3675 ** $db wal_hook ?script?
3676 ** $db update_hook ?script?
3677 ** $db rollback_hook ?script?
3679 case DB_WAL_HOOK:
3680 case DB_UPDATE_HOOK:
3681 case DB_ROLLBACK_HOOK: {
3682 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
3683 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3685 Tcl_Obj **ppHook = 0;
3686 if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
3687 if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
3688 if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
3689 if( objc>3 ){
3690 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3691 return TCL_ERROR;
3694 DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
3695 break;
3698 /* $db version
3700 ** Return the version string for this database.
3702 case DB_VERSION: {
3703 int i;
3704 for(i=2; i<objc; i++){
3705 const char *zArg = Tcl_GetString(objv[i]);
3706 /* Optional arguments to $db version are used for testing purpose */
3707 #ifdef SQLITE_TEST
3708 /* $db version -use-legacy-prepare BOOLEAN
3710 ** Turn the use of legacy sqlite3_prepare() on or off.
3712 if( strcmp(zArg, "-use-legacy-prepare")==0 && i+1<objc ){
3713 i++;
3714 if( Tcl_GetBooleanFromObj(interp, objv[i], &pDb->bLegacyPrepare) ){
3715 return TCL_ERROR;
3717 }else
3719 /* $db version -last-stmt-ptr
3721 ** Return a string which is a hex encoding of the pointer to the
3722 ** most recent sqlite3_stmt in the statement cache.
3724 if( strcmp(zArg, "-last-stmt-ptr")==0 ){
3725 char zBuf[100];
3726 sqlite3_snprintf(sizeof(zBuf), zBuf, "%p",
3727 pDb->stmtList ? pDb->stmtList->pStmt: 0);
3728 Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
3729 }else
3730 #endif /* SQLITE_TEST */
3732 Tcl_AppendResult(interp, "unknown argument: ", zArg, (char*)0);
3733 return TCL_ERROR;
3736 if( i==2 ){
3737 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
3739 break;
3743 } /* End of the SWITCH statement */
3744 return rc;
3747 #if SQLITE_TCL_NRE
3749 ** Adaptor that provides an objCmd interface to the NRE-enabled
3750 ** interface implementation.
3752 static int SQLITE_TCLAPI DbObjCmdAdaptor(
3753 void *cd,
3754 Tcl_Interp *interp,
3755 int objc,
3756 Tcl_Obj *const*objv
3758 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
3760 #endif /* SQLITE_TCL_NRE */
3763 ** Issue the usage message when the "sqlite3" command arguments are
3764 ** incorrect.
3766 static int sqliteCmdUsage(
3767 Tcl_Interp *interp,
3768 Tcl_Obj *const*objv
3770 Tcl_WrongNumArgs(interp, 1, objv,
3771 "HANDLE ?FILENAME? ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
3772 " ?-nofollow BOOLEAN?"
3773 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
3775 return TCL_ERROR;
3779 ** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
3780 ** ?-create BOOLEAN? ?-nomutex BOOLEAN?
3781 ** ?-nofollow BOOLEAN?
3783 ** This is the main Tcl command. When the "sqlite" Tcl command is
3784 ** invoked, this routine runs to process that command.
3786 ** The first argument, DBNAME, is an arbitrary name for a new
3787 ** database connection. This command creates a new command named
3788 ** DBNAME that is used to control that connection. The database
3789 ** connection is deleted when the DBNAME command is deleted.
3791 ** The second argument is the name of the database file.
3794 static int SQLITE_TCLAPI DbMain(
3795 void *cd,
3796 Tcl_Interp *interp,
3797 int objc,
3798 Tcl_Obj *const*objv
3800 SqliteDb *p;
3801 const char *zArg;
3802 char *zErrMsg;
3803 int i;
3804 const char *zFile = 0;
3805 const char *zVfs = 0;
3806 int flags;
3807 int bTranslateFileName = 1;
3808 Tcl_DString translatedFilename;
3809 int rc;
3811 /* In normal use, each TCL interpreter runs in a single thread. So
3812 ** by default, we can turn off mutexing on SQLite database connections.
3813 ** However, for testing purposes it is useful to have mutexes turned
3814 ** on. So, by default, mutexes default off. But if compiled with
3815 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3817 #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3818 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3819 #else
3820 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3821 #endif
3823 if( objc==1 ) return sqliteCmdUsage(interp, objv);
3824 if( objc==2 ){
3825 zArg = Tcl_GetStringFromObj(objv[1], 0);
3826 if( strcmp(zArg,"-version")==0 ){
3827 Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
3828 return TCL_OK;
3830 if( strcmp(zArg,"-sourceid")==0 ){
3831 Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0);
3832 return TCL_OK;
3834 if( strcmp(zArg,"-has-codec")==0 ){
3835 Tcl_AppendResult(interp,"0",(char*)0);
3836 return TCL_OK;
3838 if( zArg[0]=='-' ) return sqliteCmdUsage(interp, objv);
3840 for(i=2; i<objc; i++){
3841 zArg = Tcl_GetString(objv[i]);
3842 if( zArg[0]!='-' ){
3843 if( zFile!=0 ) return sqliteCmdUsage(interp, objv);
3844 zFile = zArg;
3845 continue;
3847 if( i==objc-1 ) return sqliteCmdUsage(interp, objv);
3848 i++;
3849 if( strcmp(zArg,"-key")==0 ){
3850 /* no-op */
3851 }else if( strcmp(zArg, "-vfs")==0 ){
3852 zVfs = Tcl_GetString(objv[i]);
3853 }else if( strcmp(zArg, "-readonly")==0 ){
3854 int b;
3855 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3856 if( b ){
3857 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
3858 flags |= SQLITE_OPEN_READONLY;
3859 }else{
3860 flags &= ~SQLITE_OPEN_READONLY;
3861 flags |= SQLITE_OPEN_READWRITE;
3863 }else if( strcmp(zArg, "-create")==0 ){
3864 int b;
3865 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3866 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
3867 flags |= SQLITE_OPEN_CREATE;
3868 }else{
3869 flags &= ~SQLITE_OPEN_CREATE;
3871 }else if( strcmp(zArg, "-nofollow")==0 ){
3872 int b;
3873 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3874 if( b ){
3875 flags |= SQLITE_OPEN_NOFOLLOW;
3876 }else{
3877 flags &= ~SQLITE_OPEN_NOFOLLOW;
3879 }else if( strcmp(zArg, "-nomutex")==0 ){
3880 int b;
3881 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3882 if( b ){
3883 flags |= SQLITE_OPEN_NOMUTEX;
3884 flags &= ~SQLITE_OPEN_FULLMUTEX;
3885 }else{
3886 flags &= ~SQLITE_OPEN_NOMUTEX;
3888 }else if( strcmp(zArg, "-fullmutex")==0 ){
3889 int b;
3890 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3891 if( b ){
3892 flags |= SQLITE_OPEN_FULLMUTEX;
3893 flags &= ~SQLITE_OPEN_NOMUTEX;
3894 }else{
3895 flags &= ~SQLITE_OPEN_FULLMUTEX;
3897 }else if( strcmp(zArg, "-uri")==0 ){
3898 int b;
3899 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3900 if( b ){
3901 flags |= SQLITE_OPEN_URI;
3902 }else{
3903 flags &= ~SQLITE_OPEN_URI;
3905 }else if( strcmp(zArg, "-translatefilename")==0 ){
3906 if( Tcl_GetBooleanFromObj(interp, objv[i], &bTranslateFileName) ){
3907 return TCL_ERROR;
3909 }else{
3910 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3911 return TCL_ERROR;
3914 zErrMsg = 0;
3915 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
3916 memset(p, 0, sizeof(*p));
3917 if( zFile==0 ) zFile = "";
3918 if( bTranslateFileName ){
3919 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
3921 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
3922 if( bTranslateFileName ){
3923 Tcl_DStringFree(&translatedFilename);
3925 if( p->db ){
3926 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3927 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3928 sqlite3_close(p->db);
3929 p->db = 0;
3931 }else{
3932 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
3934 if( p->db==0 ){
3935 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
3936 Tcl_Free((char*)p);
3937 sqlite3_free(zErrMsg);
3938 return TCL_ERROR;
3940 p->maxStmt = NUM_PREPARED_STMTS;
3941 p->openFlags = flags & SQLITE_OPEN_URI;
3942 p->interp = interp;
3943 zArg = Tcl_GetStringFromObj(objv[1], 0);
3944 if( DbUseNre() ){
3945 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3946 (char*)p, DbDeleteCmd);
3947 }else{
3948 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3950 p->nRef = 1;
3951 return TCL_OK;
3955 ** Provide a dummy Tcl_InitStubs if we are using this as a static
3956 ** library.
3958 #ifndef USE_TCL_STUBS
3959 # undef Tcl_InitStubs
3960 # define Tcl_InitStubs(a,b,c) TCL_VERSION
3961 #endif
3964 ** Make sure we have a PACKAGE_VERSION macro defined. This will be
3965 ** defined automatically by the TEA makefile. But other makefiles
3966 ** do not define it.
3968 #ifndef PACKAGE_VERSION
3969 # define PACKAGE_VERSION SQLITE_VERSION
3970 #endif
3973 ** Initialize this module.
3975 ** This Tcl module contains only a single new Tcl command named "sqlite".
3976 ** (Hence there is no namespace. There is no point in using a namespace
3977 ** if the extension only supplies one new name!) The "sqlite" command is
3978 ** used to open a new SQLite database. See the DbMain() routine above
3979 ** for additional information.
3981 ** The EXTERN macros are required by TCL in order to work on windows.
3983 EXTERN int Sqlite3_Init(Tcl_Interp *interp){
3984 int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
3985 if( rc==TCL_OK ){
3986 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
3987 #ifndef SQLITE_3_SUFFIX_ONLY
3988 /* The "sqlite" alias is undocumented. It is here only to support
3989 ** legacy scripts. All new scripts should use only the "sqlite3"
3990 ** command. */
3991 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
3992 #endif
3993 rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3995 return rc;
3997 EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3998 EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3999 EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
4001 /* Because it accesses the file-system and uses persistent state, SQLite
4002 ** is not considered appropriate for safe interpreters. Hence, we cause
4003 ** the _SafeInit() interfaces return TCL_ERROR.
4005 EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
4006 EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
4009 ** Versions of all of the above entry points that omit the "3" at the end
4010 ** of the name. Years ago (circa 2004) the "3" was necessary to distinguish
4011 ** SQLite version 3 from Sqlite version 2. But two decades have elapsed.
4012 ** SQLite2 is not longer a conflict. So it is ok to omit the "3".
4014 ** Omitting the "3" helps TCL find the entry point.
4016 EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp);}
4017 EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
4018 EXTERN int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
4019 EXTERN int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
4020 EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
4021 EXTERN int Sqlite_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
4023 /* Also variants with a lowercase "s" */
4024 EXTERN int sqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp);}
4025 EXTERN int sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp);}
4029 ** If the TCLSH macro is defined, add code to make a stand-alone program.
4031 #if defined(TCLSH)
4033 /* This is the main routine for an ordinary TCL shell. If there are
4034 ** are arguments, run the first argument as a script. Otherwise,
4035 ** read TCL commands from standard input
4037 static const char *tclsh_main_loop(void){
4038 static const char zMainloop[] =
4039 "if {[llength $argv]>=1} {\n"
4040 "set argv0 [lindex $argv 0]\n"
4041 "set argv [lrange $argv 1 end]\n"
4042 "source $argv0\n"
4043 "} else {\n"
4044 "set line {}\n"
4045 "while {![eof stdin]} {\n"
4046 "if {$line!=\"\"} {\n"
4047 "puts -nonewline \"> \"\n"
4048 "} else {\n"
4049 "puts -nonewline \"% \"\n"
4050 "}\n"
4051 "flush stdout\n"
4052 "append line [gets stdin]\n"
4053 "if {[info complete $line]} {\n"
4054 "if {[catch {uplevel #0 $line} result]} {\n"
4055 "puts stderr \"Error: $result\"\n"
4056 "} elseif {$result!=\"\"} {\n"
4057 "puts $result\n"
4058 "}\n"
4059 "set line {}\n"
4060 "} else {\n"
4061 "append line \\n\n"
4062 "}\n"
4063 "}\n"
4064 "}\n"
4066 return zMainloop;
4069 #ifndef TCLSH_MAIN
4070 # define TCLSH_MAIN main
4071 #endif
4072 int SQLITE_CDECL TCLSH_MAIN(int argc, char **argv){
4073 Tcl_Interp *interp;
4074 int i;
4075 const char *zScript = 0;
4076 char zArgc[32];
4077 #if defined(TCLSH_INIT_PROC)
4078 extern const char *TCLSH_INIT_PROC(Tcl_Interp*);
4079 #endif
4081 #if !defined(_WIN32_WCE)
4082 if( getenv("SQLITE_DEBUG_BREAK") ){
4083 if( isatty(0) && isatty(2) ){
4084 fprintf(stderr,
4085 "attach debugger to process %d and press any key to continue.\n",
4086 GETPID());
4087 fgetc(stdin);
4088 }else{
4089 #if defined(_WIN32) || defined(WIN32)
4090 DebugBreak();
4091 #elif defined(SIGTRAP)
4092 raise(SIGTRAP);
4093 #endif
4096 #endif
4098 /* Call sqlite3_shutdown() once before doing anything else. This is to
4099 ** test that sqlite3_shutdown() can be safely called by a process before
4100 ** sqlite3_initialize() is. */
4101 sqlite3_shutdown();
4103 Tcl_FindExecutable(argv[0]);
4104 Tcl_SetSystemEncoding(NULL, "utf-8");
4105 interp = Tcl_CreateInterp();
4106 Sqlite3_Init(interp);
4108 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-1);
4109 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
4110 Tcl_SetVar(interp,"argv0",argv[0],TCL_GLOBAL_ONLY);
4111 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
4112 for(i=1; i<argc; i++){
4113 Tcl_SetVar(interp, "argv", argv[i],
4114 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
4116 #if defined(TCLSH_INIT_PROC)
4117 zScript = TCLSH_INIT_PROC(interp);
4118 #endif
4119 if( zScript==0 ){
4120 zScript = tclsh_main_loop();
4122 if( Tcl_GlobalEval(interp, zScript)!=TCL_OK ){
4123 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
4124 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
4125 fprintf(stderr,"%s: %s\n", *argv, zInfo);
4126 return 1;
4128 return 0;
4130 #endif /* TCLSH */