interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / src / tclsqlite.c

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