comparison third_party/sqlite3/tea/generic/tclsqlite3.c @ 173:827c6ac504cd hg-web

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