blob: 31ad81a18b8b7e11147f79b20d52950e586dc058 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** 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.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
drhbd08af42007-04-05 21:58:33 +000012** 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.
drh57a02272009-10-22 20:52:05 +000014**
15** Compile-time options:
16**
17** -DTCLSH=1 Add a "main()" routine that works as a tclsh.
18**
19** -DSQLITE_TCLMD5 When used in conjuction with -DTCLSH=1, add
20** four new commands to the TCL interpreter for
21** generating MD5 checksums: md5, md5file,
22** md5-10x8, and md5file-10x8.
23**
24** -DSQLITE_TEST When used in conjuction with -DTCLSH=1, add
25** hundreds of new commands used for testing
26** SQLite. This option implies -DSQLITE_TCLMD5.
drh75897232000-05-29 14:26:00 +000027*/
mistachkin27b2f052015-01-12 19:49:46 +000028
29/*
30** If requested, include the SQLite compiler options file for MSVC.
31*/
32#if defined(INCLUDE_MSVC_H)
mistachkin52b1dbb2016-07-28 14:37:04 +000033# include "msvc.h"
mistachkin27b2f052015-01-12 19:49:46 +000034#endif
35
mistachkin52b1dbb2016-07-28 14:37:04 +000036#if defined(INCLUDE_SQLITE_TCL_H)
37# include "sqlite_tcl.h"
38#else
39# include "tcl.h"
mistachkin7617e4a2016-07-28 17:11:20 +000040# ifndef SQLITE_TCLAPI
41# define SQLITE_TCLAPI
42# endif
mistachkin52b1dbb2016-07-28 14:37:04 +000043#endif
danielk1977b4e9af92007-05-01 17:49:49 +000044#include <errno.h>
drhbd08af42007-04-05 21:58:33 +000045
46/*
47** Some additional include files are needed if this file is not
48** appended to the amalgamation.
49*/
50#ifndef SQLITE_AMALGAMATION
drh65e8c822009-12-01 13:57:48 +000051# include "sqlite3.h"
drhbd08af42007-04-05 21:58:33 +000052# include <stdlib.h>
53# include <string.h>
54# include <assert.h>
drh65e8c822009-12-01 13:57:48 +000055 typedef unsigned char u8;
drhbd08af42007-04-05 21:58:33 +000056#endif
drheb206382009-10-24 15:51:33 +000057#include <ctype.h>
drh75897232000-05-29 14:26:00 +000058
mistachkin1f28e072013-08-15 08:06:15 +000059/* Used to get the current process ID */
60#if !defined(_WIN32)
61# include <unistd.h>
62# define GETPID getpid
63#elif !defined(_WIN32_WCE)
64# ifndef SQLITE_AMALGAMATION
65# define WIN32_LEAN_AND_MEAN
66# include <windows.h>
67# endif
68# define GETPID (int)GetCurrentProcessId
69#endif
70
drhad6e1372006-07-10 21:15:51 +000071/*
72 * Windows needs to know which symbols to export. Unix does not.
73 * BUILD_sqlite should be undefined for Unix.
74 */
75#ifdef BUILD_sqlite
76#undef TCL_STORAGE_CLASS
77#define TCL_STORAGE_CLASS DLLEXPORT
78#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000079
danielk1977a21c6b62005-01-24 10:25:59 +000080#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000081#define MAX_PREPARED_STMTS 100
82
drhc45e6712012-10-03 11:02:33 +000083/* Forward declaration */
84typedef struct SqliteDb SqliteDb;
drh98808ba2001-10-18 12:34:46 +000085
86/*
drhcabb0812002-09-14 13:47:32 +000087** New SQL functions can be created as TCL scripts. Each such function
88** is described by an instance of the following structure.
89*/
90typedef struct SqlFunc SqlFunc;
91struct SqlFunc {
92 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000093 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
drhc45e6712012-10-03 11:02:33 +000094 SqliteDb *pDb; /* Database connection that owns this function */
drhd1e47332005-06-26 17:55:33 +000095 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
96 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000097 SqlFunc *pNext; /* Next function on the list of them all */
98};
99
100/*
danielk19770202b292004-06-09 09:55:16 +0000101** New collation sequences function can be created as TCL scripts. Each such
102** function is described by an instance of the following structure.
103*/
104typedef struct SqlCollate SqlCollate;
105struct SqlCollate {
106 Tcl_Interp *interp; /* The TCL interpret to execute the function */
107 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +0000108 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +0000109};
110
111/*
drhfb7e7652005-01-24 00:28:42 +0000112** Prepared statements are cached for faster execution. Each prepared
113** statement is described by an instance of the following structure.
114*/
115typedef struct SqlPreparedStmt SqlPreparedStmt;
116struct SqlPreparedStmt {
117 SqlPreparedStmt *pNext; /* Next in linked list */
118 SqlPreparedStmt *pPrev; /* Previous on the list */
119 sqlite3_stmt *pStmt; /* The prepared statement */
120 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +0000121 const char *zSql; /* Text of the SQL statement */
dan4a4c11a2009-10-06 14:59:02 +0000122 int nParm; /* Size of apParm array */
123 Tcl_Obj **apParm; /* Array of referenced object pointers */
drhfb7e7652005-01-24 00:28:42 +0000124};
125
danielk1977d04417962007-05-02 13:16:30 +0000126typedef struct IncrblobChannel IncrblobChannel;
127
drhfb7e7652005-01-24 00:28:42 +0000128/*
drhbec3f402000-08-04 13:49:02 +0000129** There is one instance of this structure for each SQLite database
130** that has been opened by the SQLite TCL interface.
danc431fd52011-06-27 16:55:50 +0000131**
132** If this module is built with SQLITE_TEST defined (to create the SQLite
133** testfixture executable), then it may be configured to use either
134** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
135** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
drhbec3f402000-08-04 13:49:02 +0000136*/
drhbec3f402000-08-04 13:49:02 +0000137struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000138 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000139 Tcl_Interp *interp; /* The interpreter used for this database */
140 char *zBusy; /* The busy callback routine */
141 char *zCommit; /* The commit hook callback routine */
142 char *zTrace; /* The trace callback routine */
mistachkinb56660f2016-07-14 21:26:09 +0000143 char *zTraceV2; /* The trace_v2 callback routine */
drh19e2d372005-08-29 23:00:03 +0000144 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000145 char *zProgress; /* The progress callback routine */
146 char *zAuth; /* The authorization callback routine */
drh1f1549f2008-08-26 21:33:34 +0000147 int disableAuth; /* Disable the authorizer if it exists */
drhd1e47332005-06-26 17:55:33 +0000148 char *zNull; /* Text to substitute for an SQL NULL value */
149 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000150 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
dan46c47d42011-03-01 18:42:07 +0000151 Tcl_Obj *pPreUpdateHook; /* Pre-update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000152 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drh5def0842010-05-05 20:00:25 +0000153 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000154 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000155 SqlCollate *pCollate; /* List of SQL collation functions */
156 int rc; /* Return code of most recent sqlite3_exec() */
157 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000158 SqlPreparedStmt *stmtList; /* List of prepared statements*/
159 SqlPreparedStmt *stmtLast; /* Last statement in the list */
160 int maxStmt; /* The next maximum number of stmtList */
161 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000162 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh3c379b02010-04-07 19:31:59 +0000163 int nStep, nSort, nIndex; /* Statistics for most recent operation */
danc456a762017-06-22 16:51:16 +0000164 int nVMStep; /* Another statistic for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000165 int nTransaction; /* Number of nested [transaction] methods */
drh147ef392016-01-22 23:17:51 +0000166 int openFlags; /* Flags used to open. (SQLITE_OPEN_URI) */
drh1973ade2017-06-26 16:13:20 +0000167 unsigned int modeFlags; /* Operating mode flags */
danc431fd52011-06-27 16:55:50 +0000168#ifdef SQLITE_TEST
169 int bLegacyPrepare; /* True to use sqlite3_prepare() */
170#endif
drh98808ba2001-10-18 12:34:46 +0000171};
drh297ecf12001-04-05 15:57:13 +0000172
drh1973ade2017-06-26 16:13:20 +0000173/*
174** Valid values for SqliteDb.modeFlags
175*/
176#define SQLITE_TCLMODE_UNSETNULL 0x0001 /* Unset NULL array values in */
177 /* db eval ARRAY SQL */
178
danielk1977b4e9af92007-05-01 17:49:49 +0000179struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000180 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000181 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000182 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000183 Tcl_Channel channel; /* Channel identifier */
184 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
185 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000186};
187
drhea678832008-12-10 19:26:22 +0000188/*
189** Compute a string length that is limited to what can be stored in
190** lower 30 bits of a 32-bit signed integer.
191*/
drh4f21c4a2008-12-10 22:15:00 +0000192static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000193 const char *z2 = z;
194 while( *z2 ){ z2++; }
195 return 0x3fffffff & (int)(z2 - z);
196}
drhea678832008-12-10 19:26:22 +0000197
198
danielk197732a0d8b2007-05-04 19:03:02 +0000199#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000200/*
danielk1977d04417962007-05-02 13:16:30 +0000201** Close all incrblob channels opened using database connection pDb.
202** This is called when shutting down the database connection.
203*/
204static void closeIncrblobChannels(SqliteDb *pDb){
205 IncrblobChannel *p;
206 IncrblobChannel *pNext;
207
208 for(p=pDb->pIncrblob; p; p=pNext){
209 pNext = p->pNext;
210
mistachkinb56660f2016-07-14 21:26:09 +0000211 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
danielk1977d04417962007-05-02 13:16:30 +0000212 ** which deletes the IncrblobChannel structure at *p. So do not
213 ** call Tcl_Free() here.
214 */
215 Tcl_UnregisterChannel(pDb->interp, p->channel);
216 }
217}
218
219/*
danielk1977b4e9af92007-05-01 17:49:49 +0000220** Close an incremental blob channel.
221*/
mistachkin7617e4a2016-07-28 17:11:20 +0000222static int SQLITE_TCLAPI incrblobClose(
223 ClientData instanceData,
224 Tcl_Interp *interp
225){
danielk1977b4e9af92007-05-01 17:49:49 +0000226 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000227 int rc = sqlite3_blob_close(p->pBlob);
228 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000229
230 /* Remove the channel from the SqliteDb.pIncrblob list. */
231 if( p->pNext ){
232 p->pNext->pPrev = p->pPrev;
233 }
234 if( p->pPrev ){
235 p->pPrev->pNext = p->pNext;
236 }
237 if( p->pDb->pIncrblob==p ){
238 p->pDb->pIncrblob = p->pNext;
239 }
240
danielk197792d4d7a2007-05-04 12:05:56 +0000241 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000242 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000243
244 if( rc!=SQLITE_OK ){
245 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
246 return TCL_ERROR;
247 }
danielk1977b4e9af92007-05-01 17:49:49 +0000248 return TCL_OK;
249}
250
251/*
252** Read data from an incremental blob channel.
253*/
mistachkin7617e4a2016-07-28 17:11:20 +0000254static int SQLITE_TCLAPI incrblobInput(
mistachkinb56660f2016-07-14 21:26:09 +0000255 ClientData instanceData,
256 char *buf,
danielk1977b4e9af92007-05-01 17:49:49 +0000257 int bufSize,
258 int *errorCodePtr
259){
260 IncrblobChannel *p = (IncrblobChannel *)instanceData;
261 int nRead = bufSize; /* Number of bytes to read */
262 int nBlob; /* Total size of the blob */
263 int rc; /* sqlite error code */
264
265 nBlob = sqlite3_blob_bytes(p->pBlob);
266 if( (p->iSeek+nRead)>nBlob ){
267 nRead = nBlob-p->iSeek;
268 }
269 if( nRead<=0 ){
270 return 0;
271 }
272
273 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
274 if( rc!=SQLITE_OK ){
275 *errorCodePtr = rc;
276 return -1;
277 }
278
279 p->iSeek += nRead;
280 return nRead;
281}
282
danielk1977d04417962007-05-02 13:16:30 +0000283/*
284** Write data to an incremental blob channel.
285*/
mistachkin7617e4a2016-07-28 17:11:20 +0000286static int SQLITE_TCLAPI incrblobOutput(
mistachkinb56660f2016-07-14 21:26:09 +0000287 ClientData instanceData,
288 CONST char *buf,
danielk1977b4e9af92007-05-01 17:49:49 +0000289 int toWrite,
290 int *errorCodePtr
291){
292 IncrblobChannel *p = (IncrblobChannel *)instanceData;
293 int nWrite = toWrite; /* Number of bytes to write */
294 int nBlob; /* Total size of the blob */
295 int rc; /* sqlite error code */
296
297 nBlob = sqlite3_blob_bytes(p->pBlob);
298 if( (p->iSeek+nWrite)>nBlob ){
299 *errorCodePtr = EINVAL;
300 return -1;
301 }
302 if( nWrite<=0 ){
303 return 0;
304 }
305
306 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
307 if( rc!=SQLITE_OK ){
308 *errorCodePtr = EIO;
309 return -1;
310 }
311
312 p->iSeek += nWrite;
313 return nWrite;
314}
315
316/*
317** Seek an incremental blob channel.
318*/
mistachkin7617e4a2016-07-28 17:11:20 +0000319static int SQLITE_TCLAPI incrblobSeek(
mistachkinb56660f2016-07-14 21:26:09 +0000320 ClientData instanceData,
danielk1977b4e9af92007-05-01 17:49:49 +0000321 long offset,
322 int seekMode,
323 int *errorCodePtr
324){
325 IncrblobChannel *p = (IncrblobChannel *)instanceData;
326
327 switch( seekMode ){
328 case SEEK_SET:
329 p->iSeek = offset;
330 break;
331 case SEEK_CUR:
332 p->iSeek += offset;
333 break;
334 case SEEK_END:
335 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
336 break;
337
338 default: assert(!"Bad seekMode");
339 }
340
341 return p->iSeek;
342}
343
344
mistachkin7617e4a2016-07-28 17:11:20 +0000345static void SQLITE_TCLAPI incrblobWatch(
346 ClientData instanceData,
347 int mode
348){
mistachkinb56660f2016-07-14 21:26:09 +0000349 /* NO-OP */
danielk1977b4e9af92007-05-01 17:49:49 +0000350}
mistachkin7617e4a2016-07-28 17:11:20 +0000351static int SQLITE_TCLAPI incrblobHandle(
352 ClientData instanceData,
353 int dir,
354 ClientData *hPtr
355){
danielk1977b4e9af92007-05-01 17:49:49 +0000356 return TCL_ERROR;
357}
358
359static Tcl_ChannelType IncrblobChannelType = {
360 "incrblob", /* typeName */
361 TCL_CHANNEL_VERSION_2, /* version */
362 incrblobClose, /* closeProc */
363 incrblobInput, /* inputProc */
364 incrblobOutput, /* outputProc */
365 incrblobSeek, /* seekProc */
366 0, /* setOptionProc */
367 0, /* getOptionProc */
368 incrblobWatch, /* watchProc (this is a no-op) */
369 incrblobHandle, /* getHandleProc (always returns error) */
370 0, /* close2Proc */
371 0, /* blockModeProc */
372 0, /* flushProc */
373 0, /* handlerProc */
374 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000375};
376
377/*
378** Create a new incrblob channel.
379*/
380static int createIncrblobChannel(
mistachkinb56660f2016-07-14 21:26:09 +0000381 Tcl_Interp *interp,
382 SqliteDb *pDb,
danielk1977b4e9af92007-05-01 17:49:49 +0000383 const char *zDb,
mistachkinb56660f2016-07-14 21:26:09 +0000384 const char *zTable,
385 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000386 sqlite_int64 iRow,
387 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000388){
389 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000390 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000391 sqlite3_blob *pBlob;
392 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000393 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000394
395 /* This variable is used to name the channels: "incrblob_[incr count]" */
396 static int count = 0;
397 char zChannel[64];
398
danielk19778cbadb02007-05-03 16:31:26 +0000399 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000400 if( rc!=SQLITE_OK ){
401 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
402 return TCL_ERROR;
403 }
404
405 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
406 p->iSeek = 0;
407 p->pBlob = pBlob;
408
drh5bb3eb92007-05-04 13:15:55 +0000409 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000410 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
411 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000412
danielk1977d04417962007-05-02 13:16:30 +0000413 /* Link the new channel into the SqliteDb.pIncrblob list. */
414 p->pNext = pDb->pIncrblob;
415 p->pPrev = 0;
416 if( p->pNext ){
417 p->pNext->pPrev = p;
418 }
419 pDb->pIncrblob = p;
420 p->pDb = pDb;
421
422 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000423 return TCL_OK;
424}
danielk197732a0d8b2007-05-04 19:03:02 +0000425#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
426 #define closeIncrblobChannels(pDb)
427#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000428
drh6d313162000-09-21 13:01:35 +0000429/*
drhd1e47332005-06-26 17:55:33 +0000430** Look at the script prefix in pCmd. We will be executing this script
431** after first appending one or more arguments. This routine analyzes
432** the script to see if it is safe to use Tcl_EvalObjv() on the script
433** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
434** faster.
435**
436** Scripts that are safe to use with Tcl_EvalObjv() consists of a
437** command name followed by zero or more arguments with no [...] or $
438** or {...} or ; to be seen anywhere. Most callback scripts consist
439** of just a single procedure name and they meet this requirement.
440*/
441static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
442 /* We could try to do something with Tcl_Parse(). But we will instead
443 ** just do a search for forbidden characters. If any of the forbidden
444 ** characters appear in pCmd, we will report the string as unsafe.
445 */
446 const char *z;
447 int n;
448 z = Tcl_GetStringFromObj(pCmd, &n);
449 while( n-- > 0 ){
450 int c = *(z++);
451 if( c=='$' || c=='[' || c==';' ) return 0;
452 }
453 return 1;
454}
455
456/*
457** Find an SqlFunc structure with the given name. Or create a new
458** one if an existing one cannot be found. Return a pointer to the
459** structure.
460*/
461static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
462 SqlFunc *p, *pNew;
drh0425f182013-11-26 16:48:04 +0000463 int nName = strlen30(zName);
464 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
drhd1e47332005-06-26 17:55:33 +0000465 pNew->zName = (char*)&pNew[1];
drh0425f182013-11-26 16:48:04 +0000466 memcpy(pNew->zName, zName, nName+1);
mistachkinb56660f2016-07-14 21:26:09 +0000467 for(p=pDb->pFunc; p; p=p->pNext){
drh0425f182013-11-26 16:48:04 +0000468 if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
drhd1e47332005-06-26 17:55:33 +0000469 Tcl_Free((char*)pNew);
470 return p;
471 }
472 }
473 pNew->interp = pDb->interp;
drhc45e6712012-10-03 11:02:33 +0000474 pNew->pDb = pDb;
drhd1e47332005-06-26 17:55:33 +0000475 pNew->pScript = 0;
476 pNew->pNext = pDb->pFunc;
477 pDb->pFunc = pNew;
478 return pNew;
479}
480
481/*
danc431fd52011-06-27 16:55:50 +0000482** Free a single SqlPreparedStmt object.
483*/
484static void dbFreeStmt(SqlPreparedStmt *pStmt){
485#ifdef SQLITE_TEST
486 if( sqlite3_sql(pStmt->pStmt)==0 ){
487 Tcl_Free((char *)pStmt->zSql);
488 }
489#endif
490 sqlite3_finalize(pStmt->pStmt);
491 Tcl_Free((char *)pStmt);
492}
493
494/*
drhfb7e7652005-01-24 00:28:42 +0000495** Finalize and free a list of prepared statements
496*/
danc431fd52011-06-27 16:55:50 +0000497static void flushStmtCache(SqliteDb *pDb){
drhfb7e7652005-01-24 00:28:42 +0000498 SqlPreparedStmt *pPreStmt;
danc431fd52011-06-27 16:55:50 +0000499 SqlPreparedStmt *pNext;
drhfb7e7652005-01-24 00:28:42 +0000500
danc431fd52011-06-27 16:55:50 +0000501 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
502 pNext = pPreStmt->pNext;
503 dbFreeStmt(pPreStmt);
drhfb7e7652005-01-24 00:28:42 +0000504 }
505 pDb->nStmt = 0;
506 pDb->stmtLast = 0;
danc431fd52011-06-27 16:55:50 +0000507 pDb->stmtList = 0;
drhfb7e7652005-01-24 00:28:42 +0000508}
509
510/*
drh895d7472004-08-20 16:02:39 +0000511** TCL calls this procedure when an sqlite3 database command is
512** deleted.
drh75897232000-05-29 14:26:00 +0000513*/
mistachkin7617e4a2016-07-28 17:11:20 +0000514static void SQLITE_TCLAPI DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000515 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000516 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000517 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000518 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000519 while( pDb->pFunc ){
520 SqlFunc *pFunc = pDb->pFunc;
521 pDb->pFunc = pFunc->pNext;
drhc45e6712012-10-03 11:02:33 +0000522 assert( pFunc->pDb==pDb );
drhd1e47332005-06-26 17:55:33 +0000523 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000524 Tcl_Free((char*)pFunc);
525 }
danielk19770202b292004-06-09 09:55:16 +0000526 while( pDb->pCollate ){
527 SqlCollate *pCollate = pDb->pCollate;
528 pDb->pCollate = pCollate->pNext;
529 Tcl_Free((char*)pCollate);
530 }
drhbec3f402000-08-04 13:49:02 +0000531 if( pDb->zBusy ){
532 Tcl_Free(pDb->zBusy);
533 }
drhb5a20d32003-04-23 12:25:23 +0000534 if( pDb->zTrace ){
535 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000536 }
mistachkinb56660f2016-07-14 21:26:09 +0000537 if( pDb->zTraceV2 ){
538 Tcl_Free(pDb->zTraceV2);
539 }
drh19e2d372005-08-29 23:00:03 +0000540 if( pDb->zProfile ){
541 Tcl_Free(pDb->zProfile);
542 }
drhe22a3342003-04-22 20:30:37 +0000543 if( pDb->zAuth ){
544 Tcl_Free(pDb->zAuth);
545 }
danielk197755c45f22005-04-03 23:54:43 +0000546 if( pDb->zNull ){
547 Tcl_Free(pDb->zNull);
548 }
danielk197794eb6a12005-12-15 15:22:08 +0000549 if( pDb->pUpdateHook ){
550 Tcl_DecrRefCount(pDb->pUpdateHook);
551 }
dan46c47d42011-03-01 18:42:07 +0000552 if( pDb->pPreUpdateHook ){
553 Tcl_DecrRefCount(pDb->pPreUpdateHook);
554 }
danielk197771fd80b2005-12-16 06:54:01 +0000555 if( pDb->pRollbackHook ){
556 Tcl_DecrRefCount(pDb->pRollbackHook);
557 }
drh5def0842010-05-05 20:00:25 +0000558 if( pDb->pWalHook ){
559 Tcl_DecrRefCount(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000560 }
danielk197794eb6a12005-12-15 15:22:08 +0000561 if( pDb->pCollateNeeded ){
562 Tcl_DecrRefCount(pDb->pCollateNeeded);
563 }
drhbec3f402000-08-04 13:49:02 +0000564 Tcl_Free((char*)pDb);
565}
566
567/*
568** This routine is called when a database file is locked while trying
569** to execute SQL.
570*/
danielk19772a764eb2004-06-12 01:43:26 +0000571static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000572 SqliteDb *pDb = (SqliteDb*)cd;
573 int rc;
574 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000575
drh5bb3eb92007-05-04 13:15:55 +0000576 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000577 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000578 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
579 return 0;
580 }
581 return 1;
drh75897232000-05-29 14:26:00 +0000582}
583
drh26e4a8b2008-05-01 17:16:52 +0000584#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000585/*
danielk1977348bb5d2003-10-18 09:37:26 +0000586** This routine is invoked as the 'progress callback' for the database.
587*/
588static int DbProgressHandler(void *cd){
589 SqliteDb *pDb = (SqliteDb*)cd;
590 int rc;
591
592 assert( pDb->zProgress );
593 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
594 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
595 return 1;
596 }
597 return 0;
598}
drh26e4a8b2008-05-01 17:16:52 +0000599#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000600
drh2eb22af2016-09-10 19:51:40 +0000601#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
602 !defined(SQLITE_OMIT_DEPRECATED)
danielk1977348bb5d2003-10-18 09:37:26 +0000603/*
drhb5a20d32003-04-23 12:25:23 +0000604** This routine is called by the SQLite trace handler whenever a new
605** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000606*/
drhb5a20d32003-04-23 12:25:23 +0000607static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000608 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000609 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000610
drhb5a20d32003-04-23 12:25:23 +0000611 Tcl_DStringInit(&str);
612 Tcl_DStringAppend(&str, pDb->zTrace, -1);
613 Tcl_DStringAppendElement(&str, zSql);
614 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
615 Tcl_DStringFree(&str);
616 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000617}
drhd1167392006-01-23 13:00:35 +0000618#endif
drh0d1a6432003-04-03 15:46:04 +0000619
drhd1167392006-01-23 13:00:35 +0000620#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000621/*
mistachkinb56660f2016-07-14 21:26:09 +0000622** This routine is called by the SQLite trace_v2 handler whenever a new
623** supported event is generated. Unsupported event types are ignored.
624** The TCL script in pDb->zTraceV2 is executed, with the arguments for
625** the event appended to it (as list elements).
626*/
627static int DbTraceV2Handler(
628 unsigned type, /* One of the SQLITE_TRACE_* event types. */
629 void *cd, /* The original context data pointer. */
630 void *pd, /* Primary event data, depends on event type. */
631 void *xd /* Extra event data, depends on event type. */
632){
633 SqliteDb *pDb = (SqliteDb*)cd;
634 Tcl_Obj *pCmd;
635
636 switch( type ){
637 case SQLITE_TRACE_STMT: {
638 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
639 char *zSql = (char *)xd;
640
641 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
642 Tcl_IncrRefCount(pCmd);
643 Tcl_ListObjAppendElement(pDb->interp, pCmd,
644 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
645 Tcl_ListObjAppendElement(pDb->interp, pCmd,
646 Tcl_NewStringObj(zSql, -1));
647 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
648 Tcl_DecrRefCount(pCmd);
649 Tcl_ResetResult(pDb->interp);
650 break;
651 }
652 case SQLITE_TRACE_PROFILE: {
653 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
654 sqlite3_int64 ns = (sqlite3_int64)xd;
655
656 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
657 Tcl_IncrRefCount(pCmd);
658 Tcl_ListObjAppendElement(pDb->interp, pCmd,
659 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
660 Tcl_ListObjAppendElement(pDb->interp, pCmd,
661 Tcl_NewWideIntObj((Tcl_WideInt)ns));
662 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
663 Tcl_DecrRefCount(pCmd);
664 Tcl_ResetResult(pDb->interp);
665 break;
666 }
667 case SQLITE_TRACE_ROW: {
668 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
669
670 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
671 Tcl_IncrRefCount(pCmd);
672 Tcl_ListObjAppendElement(pDb->interp, pCmd,
673 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
674 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
675 Tcl_DecrRefCount(pCmd);
676 Tcl_ResetResult(pDb->interp);
677 break;
678 }
679 case SQLITE_TRACE_CLOSE: {
680 sqlite3 *db = (sqlite3 *)pd;
681
682 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
683 Tcl_IncrRefCount(pCmd);
684 Tcl_ListObjAppendElement(pDb->interp, pCmd,
685 Tcl_NewWideIntObj((Tcl_WideInt)db));
686 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
687 Tcl_DecrRefCount(pCmd);
688 Tcl_ResetResult(pDb->interp);
689 break;
690 }
691 }
692 return SQLITE_OK;
693}
694#endif
695
drh2eb22af2016-09-10 19:51:40 +0000696#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
697 !defined(SQLITE_OMIT_DEPRECATED)
mistachkinb56660f2016-07-14 21:26:09 +0000698/*
drh19e2d372005-08-29 23:00:03 +0000699** This routine is called by the SQLite profile handler after a statement
700** SQL has executed. The TCL script in pDb->zProfile is evaluated.
701*/
702static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
703 SqliteDb *pDb = (SqliteDb*)cd;
704 Tcl_DString str;
705 char zTm[100];
706
707 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
708 Tcl_DStringInit(&str);
709 Tcl_DStringAppend(&str, pDb->zProfile, -1);
710 Tcl_DStringAppendElement(&str, zSql);
711 Tcl_DStringAppendElement(&str, zTm);
712 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
713 Tcl_DStringFree(&str);
714 Tcl_ResetResult(pDb->interp);
715}
drhd1167392006-01-23 13:00:35 +0000716#endif
drh19e2d372005-08-29 23:00:03 +0000717
718/*
drhaa940ea2004-01-15 02:44:03 +0000719** This routine is called when a transaction is committed. The
720** TCL script in pDb->zCommit is executed. If it returns non-zero or
721** if it throws an exception, the transaction is rolled back instead
722** of being committed.
723*/
724static int DbCommitHandler(void *cd){
725 SqliteDb *pDb = (SqliteDb*)cd;
726 int rc;
727
728 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
729 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
730 return 1;
731 }
732 return 0;
733}
734
danielk197771fd80b2005-12-16 06:54:01 +0000735static void DbRollbackHandler(void *clientData){
736 SqliteDb *pDb = (SqliteDb*)clientData;
737 assert(pDb->pRollbackHook);
738 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
739 Tcl_BackgroundError(pDb->interp);
740 }
741}
742
drh5def0842010-05-05 20:00:25 +0000743/*
744** This procedure handles wal_hook callbacks.
745*/
746static int DbWalHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000747 void *clientData,
748 sqlite3 *db,
749 const char *zDb,
dan8d22a172010-04-19 18:03:51 +0000750 int nEntry
751){
drh5def0842010-05-05 20:00:25 +0000752 int ret = SQLITE_OK;
dan8d22a172010-04-19 18:03:51 +0000753 Tcl_Obj *p;
754 SqliteDb *pDb = (SqliteDb*)clientData;
755 Tcl_Interp *interp = pDb->interp;
drh5def0842010-05-05 20:00:25 +0000756 assert(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000757
dan6e45e0c2014-12-10 20:29:49 +0000758 assert( db==pDb->db );
drh5def0842010-05-05 20:00:25 +0000759 p = Tcl_DuplicateObj(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000760 Tcl_IncrRefCount(p);
761 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
762 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
mistachkinb56660f2016-07-14 21:26:09 +0000763 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
dan8d22a172010-04-19 18:03:51 +0000764 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
765 ){
766 Tcl_BackgroundError(interp);
767 }
768 Tcl_DecrRefCount(p);
769
770 return ret;
771}
772
drhbcf4f482009-03-27 12:44:35 +0000773#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000774static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
775 char zBuf[64];
drh65545b52015-01-19 00:35:53 +0000776 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
danielk1977404ca072009-03-16 13:19:36 +0000777 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
drh65545b52015-01-19 00:35:53 +0000778 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
danielk1977404ca072009-03-16 13:19:36 +0000779 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
780}
781#else
drhbcf4f482009-03-27 12:44:35 +0000782# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000783#endif
784
drh69910da2009-03-27 12:32:54 +0000785#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000786static void DbUnlockNotify(void **apArg, int nArg){
787 int i;
788 for(i=0; i<nArg; i++){
789 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
790 SqliteDb *pDb = (SqliteDb *)apArg[i];
791 setTestUnlockNotifyVars(pDb->interp, i, nArg);
792 assert( pDb->pUnlockNotify);
793 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
794 Tcl_DecrRefCount(pDb->pUnlockNotify);
795 pDb->pUnlockNotify = 0;
796 }
797}
drh69910da2009-03-27 12:32:54 +0000798#endif
danielk1977404ca072009-03-16 13:19:36 +0000799
drh9b1c62d2011-03-30 21:04:43 +0000800#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +0000801/*
802** Pre-update hook callback.
803*/
804static void DbPreUpdateHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000805 void *p,
dan46c47d42011-03-01 18:42:07 +0000806 sqlite3 *db,
807 int op,
mistachkinb56660f2016-07-14 21:26:09 +0000808 const char *zDb,
809 const char *zTbl,
dan46c47d42011-03-01 18:42:07 +0000810 sqlite_int64 iKey1,
811 sqlite_int64 iKey2
812){
813 SqliteDb *pDb = (SqliteDb *)p;
814 Tcl_Obj *pCmd;
815 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
816
817 assert( (SQLITE_DELETE-1)/9 == 0 );
818 assert( (SQLITE_INSERT-1)/9 == 1 );
819 assert( (SQLITE_UPDATE-1)/9 == 2 );
820 assert( pDb->pPreUpdateHook );
821 assert( db==pDb->db );
822 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
823
824 pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
825 Tcl_IncrRefCount(pCmd);
826 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
827 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
828 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
829 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
830 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
831 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
832 Tcl_DecrRefCount(pCmd);
833}
drh9b1c62d2011-03-30 21:04:43 +0000834#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +0000835
danielk197794eb6a12005-12-15 15:22:08 +0000836static void DbUpdateHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000837 void *p,
danielk197794eb6a12005-12-15 15:22:08 +0000838 int op,
mistachkinb56660f2016-07-14 21:26:09 +0000839 const char *zDb,
840 const char *zTbl,
danielk197794eb6a12005-12-15 15:22:08 +0000841 sqlite_int64 rowid
842){
843 SqliteDb *pDb = (SqliteDb *)p;
844 Tcl_Obj *pCmd;
dan46c47d42011-03-01 18:42:07 +0000845 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
846
847 assert( (SQLITE_DELETE-1)/9 == 0 );
848 assert( (SQLITE_INSERT-1)/9 == 1 );
849 assert( (SQLITE_UPDATE-1)/9 == 2 );
danielk197794eb6a12005-12-15 15:22:08 +0000850
851 assert( pDb->pUpdateHook );
852 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
853
854 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
855 Tcl_IncrRefCount(pCmd);
dan46c47d42011-03-01 18:42:07 +0000856 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
danielk197794eb6a12005-12-15 15:22:08 +0000857 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
858 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
859 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
860 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
drhefdde162010-10-27 15:36:21 +0000861 Tcl_DecrRefCount(pCmd);
danielk197794eb6a12005-12-15 15:22:08 +0000862}
863
danielk19777cedc8d2004-06-10 10:50:08 +0000864static void tclCollateNeeded(
865 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000866 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000867 int enc,
868 const char *zName
869){
870 SqliteDb *pDb = (SqliteDb *)pCtx;
871 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
872 Tcl_IncrRefCount(pScript);
873 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
874 Tcl_EvalObjEx(pDb->interp, pScript, 0);
875 Tcl_DecrRefCount(pScript);
876}
877
drhaa940ea2004-01-15 02:44:03 +0000878/*
danielk19770202b292004-06-09 09:55:16 +0000879** This routine is called to evaluate an SQL collation function implemented
880** using TCL script.
881*/
882static int tclSqlCollate(
883 void *pCtx,
884 int nA,
885 const void *zA,
886 int nB,
887 const void *zB
888){
889 SqlCollate *p = (SqlCollate *)pCtx;
890 Tcl_Obj *pCmd;
891
892 pCmd = Tcl_NewStringObj(p->zScript, -1);
893 Tcl_IncrRefCount(pCmd);
894 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
895 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000896 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000897 Tcl_DecrRefCount(pCmd);
898 return (atoi(Tcl_GetStringResult(p->interp)));
899}
900
901/*
drhcabb0812002-09-14 13:47:32 +0000902** This routine is called to evaluate an SQL function implemented
903** using TCL script.
904*/
drhfb7e7652005-01-24 00:28:42 +0000905static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000906 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000907 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000908 int i;
909 int rc;
910
drhd1e47332005-06-26 17:55:33 +0000911 if( argc==0 ){
912 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
913 ** script object directly. This allows the TCL compiler to generate
914 ** bytecode for the command on the first invocation and thus make
915 ** subsequent invocations much faster. */
916 pCmd = p->pScript;
917 Tcl_IncrRefCount(pCmd);
918 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
919 Tcl_DecrRefCount(pCmd);
920 }else{
921 /* If there are arguments to the function, make a shallow copy of the
922 ** script object, lappend the arguments, then evaluate the copy.
923 **
peter.d.reid60ec9142014-09-06 16:39:46 +0000924 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
mistachkinb56660f2016-07-14 21:26:09 +0000925 ** The new Tcl_Obj contains pointers to the original list elements.
drhd1e47332005-06-26 17:55:33 +0000926 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
927 ** of the list to tclCmdNameType, that alternate representation will
928 ** be preserved and reused on the next invocation.
929 */
930 Tcl_Obj **aArg;
931 int nArg;
932 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
mistachkinb56660f2016-07-14 21:26:09 +0000933 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhd1e47332005-06-26 17:55:33 +0000934 return;
mistachkinb56660f2016-07-14 21:26:09 +0000935 }
drhd1e47332005-06-26 17:55:33 +0000936 pCmd = Tcl_NewListObj(nArg, aArg);
937 Tcl_IncrRefCount(pCmd);
938 for(i=0; i<argc; i++){
939 sqlite3_value *pIn = argv[i];
940 Tcl_Obj *pVal;
mistachkinb56660f2016-07-14 21:26:09 +0000941
drhd1e47332005-06-26 17:55:33 +0000942 /* Set pVal to contain the i'th column of this row. */
943 switch( sqlite3_value_type(pIn) ){
944 case SQLITE_BLOB: {
945 int bytes = sqlite3_value_bytes(pIn);
946 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
947 break;
948 }
949 case SQLITE_INTEGER: {
950 sqlite_int64 v = sqlite3_value_int64(pIn);
951 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +0000952 pVal = Tcl_NewIntObj((int)v);
drhd1e47332005-06-26 17:55:33 +0000953 }else{
954 pVal = Tcl_NewWideIntObj(v);
955 }
956 break;
957 }
958 case SQLITE_FLOAT: {
959 double r = sqlite3_value_double(pIn);
960 pVal = Tcl_NewDoubleObj(r);
961 break;
962 }
963 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +0000964 pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
drhd1e47332005-06-26 17:55:33 +0000965 break;
966 }
967 default: {
968 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000969 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000970 break;
971 }
972 }
973 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
974 if( rc ){
975 Tcl_DecrRefCount(pCmd);
mistachkinb56660f2016-07-14 21:26:09 +0000976 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhd1e47332005-06-26 17:55:33 +0000977 return;
978 }
danielk197751ad0ec2004-05-24 12:39:02 +0000979 }
drhd1e47332005-06-26 17:55:33 +0000980 if( !p->useEvalObjv ){
981 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
982 ** is a list without a string representation. To prevent this from
983 ** happening, make sure pCmd has a valid string representation */
984 Tcl_GetString(pCmd);
985 }
986 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
987 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000988 }
danielk1977562e8d32005-05-20 09:40:55 +0000989
drhc7f269d2005-05-05 10:30:29 +0000990 if( rc && rc!=TCL_RETURN ){
mistachkinb56660f2016-07-14 21:26:09 +0000991 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000992 }else{
drhc7f269d2005-05-05 10:30:29 +0000993 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
994 int n;
995 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000996 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000997 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000998 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000999 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +00001000 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +00001001 data = Tcl_GetByteArrayFromObj(pVar, &n);
1002 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +00001003 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +00001004 Tcl_GetIntFromObj(0, pVar, &n);
1005 sqlite3_result_int(context, n);
1006 }else if( c=='d' && strcmp(zType,"double")==0 ){
1007 double r;
1008 Tcl_GetDoubleFromObj(0, pVar, &r);
1009 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +00001010 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1011 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +00001012 Tcl_WideInt v;
1013 Tcl_GetWideIntFromObj(0, pVar, &v);
1014 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +00001015 }else{
danielk197700fd9572005-12-07 06:27:43 +00001016 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1017 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +00001018 }
drhcabb0812002-09-14 13:47:32 +00001019 }
1020}
drh895d7472004-08-20 16:02:39 +00001021
drhe22a3342003-04-22 20:30:37 +00001022#ifndef SQLITE_OMIT_AUTHORIZATION
1023/*
1024** This is the authentication function. It appends the authentication
1025** type code and the two arguments to zCmd[] then invokes the result
1026** on the interpreter. The reply is examined to determine if the
1027** authentication fails or succeeds.
1028*/
1029static int auth_callback(
1030 void *pArg,
1031 int code,
1032 const char *zArg1,
1033 const char *zArg2,
1034 const char *zArg3,
1035 const char *zArg4
drh32c6a482014-09-11 13:44:52 +00001036#ifdef SQLITE_USER_AUTHENTICATION
1037 ,const char *zArg5
1038#endif
drhe22a3342003-04-22 20:30:37 +00001039){
mistachkin6ef5e122014-01-24 17:03:55 +00001040 const char *zCode;
drhe22a3342003-04-22 20:30:37 +00001041 Tcl_DString str;
1042 int rc;
1043 const char *zReply;
drh94189212017-05-11 13:43:57 +00001044 /* EVIDENCE-OF: R-38590-62769 The first parameter to the authorizer
1045 ** callback is a copy of the third parameter to the
1046 ** sqlite3_set_authorizer() interface.
1047 */
drhe22a3342003-04-22 20:30:37 +00001048 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +00001049 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +00001050
drh94189212017-05-11 13:43:57 +00001051 /* EVIDENCE-OF: R-56518-44310 The second parameter to the callback is an
1052 ** integer action code that specifies the particular action to be
1053 ** authorized. */
drhe22a3342003-04-22 20:30:37 +00001054 switch( code ){
1055 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
1056 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
1057 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
1058 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
1059 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
1060 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
1061 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
1062 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
1063 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
1064 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
1065 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
1066 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
1067 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
1068 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
1069 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
1070 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
1071 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
1072 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
1073 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
1074 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
1075 case SQLITE_READ : zCode="SQLITE_READ"; break;
1076 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
1077 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
1078 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +00001079 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
1080 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +00001081 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +00001082 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +00001083 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +00001084 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
1085 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +00001086 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +00001087 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drh65a2aaa2014-01-16 22:40:02 +00001088 case SQLITE_RECURSIVE : zCode="SQLITE_RECURSIVE"; break;
drhe22a3342003-04-22 20:30:37 +00001089 default : zCode="????"; break;
1090 }
1091 Tcl_DStringInit(&str);
1092 Tcl_DStringAppend(&str, pDb->zAuth, -1);
1093 Tcl_DStringAppendElement(&str, zCode);
1094 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
1095 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
1096 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
1097 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
drh32c6a482014-09-11 13:44:52 +00001098#ifdef SQLITE_USER_AUTHENTICATION
1099 Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
mistachkinb56660f2016-07-14 21:26:09 +00001100#endif
drhe22a3342003-04-22 20:30:37 +00001101 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
1102 Tcl_DStringFree(&str);
drhb07028f2011-10-14 21:49:18 +00001103 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
drhe22a3342003-04-22 20:30:37 +00001104 if( strcmp(zReply,"SQLITE_OK")==0 ){
1105 rc = SQLITE_OK;
1106 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
1107 rc = SQLITE_DENY;
1108 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
1109 rc = SQLITE_IGNORE;
1110 }else{
1111 rc = 999;
1112 }
1113 return rc;
1114}
1115#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +00001116
1117/*
tpoindex1067fe12004-12-17 15:41:11 +00001118** This routine reads a line of text from FILE in, stores
1119** the text in memory obtained from malloc() and returns a pointer
1120** to the text. NULL is returned at end of file, or if malloc()
1121** fails.
1122**
1123** The interface is like "readline" but no command-line editing
1124** is done.
1125**
1126** copied from shell.c from '.import' command
1127*/
1128static char *local_getline(char *zPrompt, FILE *in){
1129 char *zLine;
1130 int nLine;
1131 int n;
tpoindex1067fe12004-12-17 15:41:11 +00001132
1133 nLine = 100;
1134 zLine = malloc( nLine );
1135 if( zLine==0 ) return 0;
1136 n = 0;
drhb07028f2011-10-14 21:49:18 +00001137 while( 1 ){
tpoindex1067fe12004-12-17 15:41:11 +00001138 if( n+100>nLine ){
1139 nLine = nLine*2 + 100;
1140 zLine = realloc(zLine, nLine);
1141 if( zLine==0 ) return 0;
1142 }
1143 if( fgets(&zLine[n], nLine - n, in)==0 ){
1144 if( n==0 ){
1145 free(zLine);
1146 return 0;
1147 }
1148 zLine[n] = 0;
tpoindex1067fe12004-12-17 15:41:11 +00001149 break;
1150 }
1151 while( zLine[n] ){ n++; }
1152 if( n>0 && zLine[n-1]=='\n' ){
1153 n--;
1154 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +00001155 break;
tpoindex1067fe12004-12-17 15:41:11 +00001156 }
1157 }
1158 zLine = realloc( zLine, n+1 );
1159 return zLine;
1160}
1161
danielk19778e556522007-11-13 10:30:24 +00001162
1163/*
dan4a4c11a2009-10-06 14:59:02 +00001164** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +00001165**
dan4a4c11a2009-10-06 14:59:02 +00001166** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +00001167**
dan4a4c11a2009-10-06 14:59:02 +00001168** It is invoked after evaluating the script SCRIPT to commit or rollback
1169** the transaction or savepoint opened by the [transaction] command.
1170*/
mistachkina121cc72016-07-28 18:06:52 +00001171static int SQLITE_TCLAPI DbTransPostCmd(
dan4a4c11a2009-10-06 14:59:02 +00001172 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1173 Tcl_Interp *interp, /* Tcl interpreter */
1174 int result /* Result of evaluating SCRIPT */
1175){
mistachkin6ef5e122014-01-24 17:03:55 +00001176 static const char *const azEnd[] = {
dan4a4c11a2009-10-06 14:59:02 +00001177 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1178 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1179 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1180 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1181 };
1182 SqliteDb *pDb = (SqliteDb*)data[0];
1183 int rc = result;
1184 const char *zEnd;
1185
1186 pDb->nTransaction--;
1187 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1188
1189 pDb->disableAuth++;
1190 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1191 /* This is a tricky scenario to handle. The most likely cause of an
mistachkinb56660f2016-07-14 21:26:09 +00001192 ** error is that the exec() above was an attempt to commit the
dan4a4c11a2009-10-06 14:59:02 +00001193 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
mistachkin48864df2013-03-21 21:20:32 +00001194 ** that an IO-error has occurred. In either case, throw a Tcl exception
dan4a4c11a2009-10-06 14:59:02 +00001195 ** and try to rollback the transaction.
1196 **
mistachkinb56660f2016-07-14 21:26:09 +00001197 ** But it could also be that the user executed one or more BEGIN,
dan4a4c11a2009-10-06 14:59:02 +00001198 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1199 ** this method's logic. Not clear how this would be best handled.
1200 */
1201 if( rc!=TCL_ERROR ){
drha198f2b2014-02-07 19:26:13 +00001202 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
dan4a4c11a2009-10-06 14:59:02 +00001203 rc = TCL_ERROR;
1204 }
1205 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1206 }
1207 pDb->disableAuth--;
1208
1209 return rc;
1210}
1211
1212/*
danc431fd52011-06-27 16:55:50 +00001213** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1214** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1215** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
mistachkinb56660f2016-07-14 21:26:09 +00001216** on whether or not the [db_use_legacy_prepare] command has been used to
danc431fd52011-06-27 16:55:50 +00001217** configure the connection.
1218*/
1219static int dbPrepare(
1220 SqliteDb *pDb, /* Database object */
1221 const char *zSql, /* SQL to compile */
1222 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1223 const char **pzOut /* OUT: Pointer to next SQL statement */
1224){
1225#ifdef SQLITE_TEST
1226 if( pDb->bLegacyPrepare ){
1227 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1228 }
1229#endif
1230 return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut);
1231}
1232
1233/*
dan4a4c11a2009-10-06 14:59:02 +00001234** Search the cache for a prepared-statement object that implements the
1235** first SQL statement in the buffer pointed to by parameter zIn. If
1236** no such prepared-statement can be found, allocate and prepare a new
1237** one. In either case, bind the current values of the relevant Tcl
1238** variables to any $var, :var or @var variables in the statement. Before
1239** returning, set *ppPreStmt to point to the prepared-statement object.
1240**
1241** Output parameter *pzOut is set to point to the next SQL statement in
1242** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1243** next statement.
1244**
1245** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1246** and an error message loaded into interpreter pDb->interp.
1247*/
1248static int dbPrepareAndBind(
1249 SqliteDb *pDb, /* Database object */
1250 char const *zIn, /* SQL to compile */
1251 char const **pzOut, /* OUT: Pointer to next SQL statement */
1252 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1253){
1254 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
mistachkin7bb22ac2015-01-12 19:59:12 +00001255 sqlite3_stmt *pStmt = 0; /* Prepared statement object */
dan4a4c11a2009-10-06 14:59:02 +00001256 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1257 int nSql; /* Length of zSql in bytes */
mistachkin7bb22ac2015-01-12 19:59:12 +00001258 int nVar = 0; /* Number of variables in statement */
dan4a4c11a2009-10-06 14:59:02 +00001259 int iParm = 0; /* Next free entry in apParm */
drh0425f182013-11-26 16:48:04 +00001260 char c;
dan4a4c11a2009-10-06 14:59:02 +00001261 int i;
1262 Tcl_Interp *interp = pDb->interp;
1263
1264 *ppPreStmt = 0;
1265
1266 /* Trim spaces from the start of zSql and calculate the remaining length. */
drh0425f182013-11-26 16:48:04 +00001267 while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
dan4a4c11a2009-10-06 14:59:02 +00001268 nSql = strlen30(zSql);
1269
1270 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1271 int n = pPreStmt->nSql;
mistachkinb56660f2016-07-14 21:26:09 +00001272 if( nSql>=n
dan4a4c11a2009-10-06 14:59:02 +00001273 && memcmp(pPreStmt->zSql, zSql, n)==0
1274 && (zSql[n]==0 || zSql[n-1]==';')
1275 ){
1276 pStmt = pPreStmt->pStmt;
1277 *pzOut = &zSql[pPreStmt->nSql];
1278
1279 /* When a prepared statement is found, unlink it from the
1280 ** cache list. It will later be added back to the beginning
1281 ** of the cache list in order to implement LRU replacement.
1282 */
1283 if( pPreStmt->pPrev ){
1284 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1285 }else{
1286 pDb->stmtList = pPreStmt->pNext;
1287 }
1288 if( pPreStmt->pNext ){
1289 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1290 }else{
1291 pDb->stmtLast = pPreStmt->pPrev;
1292 }
1293 pDb->nStmt--;
1294 nVar = sqlite3_bind_parameter_count(pStmt);
1295 break;
1296 }
1297 }
mistachkinb56660f2016-07-14 21:26:09 +00001298
dan4a4c11a2009-10-06 14:59:02 +00001299 /* If no prepared statement was found. Compile the SQL text. Also allocate
1300 ** a new SqlPreparedStmt structure. */
1301 if( pPreStmt==0 ){
1302 int nByte;
1303
danc431fd52011-06-27 16:55:50 +00001304 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
drhc45e6712012-10-03 11:02:33 +00001305 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001306 return TCL_ERROR;
1307 }
1308 if( pStmt==0 ){
1309 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1310 /* A compile-time error in the statement. */
drhc45e6712012-10-03 11:02:33 +00001311 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001312 return TCL_ERROR;
1313 }else{
1314 /* The statement was a no-op. Continue to the next statement
1315 ** in the SQL string.
1316 */
1317 return TCL_OK;
1318 }
1319 }
1320
1321 assert( pPreStmt==0 );
1322 nVar = sqlite3_bind_parameter_count(pStmt);
1323 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1324 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1325 memset(pPreStmt, 0, nByte);
1326
1327 pPreStmt->pStmt = pStmt;
drh7ed243b2012-04-19 17:19:51 +00001328 pPreStmt->nSql = (int)(*pzOut - zSql);
dan4a4c11a2009-10-06 14:59:02 +00001329 pPreStmt->zSql = sqlite3_sql(pStmt);
1330 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
danc431fd52011-06-27 16:55:50 +00001331#ifdef SQLITE_TEST
1332 if( pPreStmt->zSql==0 ){
1333 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1334 memcpy(zCopy, zSql, pPreStmt->nSql);
1335 zCopy[pPreStmt->nSql] = '\0';
1336 pPreStmt->zSql = zCopy;
1337 }
1338#endif
dan4a4c11a2009-10-06 14:59:02 +00001339 }
1340 assert( pPreStmt );
1341 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1342 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1343
mistachkinb56660f2016-07-14 21:26:09 +00001344 /* Bind values to parameters that begin with $ or : */
dan4a4c11a2009-10-06 14:59:02 +00001345 for(i=1; i<=nVar; i++){
1346 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1347 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1348 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1349 if( pVar ){
1350 int n;
1351 u8 *data;
1352 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
mistachkin8e189222015-04-19 21:43:16 +00001353 c = zType[0];
dan4a4c11a2009-10-06 14:59:02 +00001354 if( zVar[0]=='@' ||
1355 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1356 /* Load a BLOB type if the Tcl variable is a bytearray and
1357 ** it has no string representation or the host
1358 ** parameter name begins with "@". */
1359 data = Tcl_GetByteArrayFromObj(pVar, &n);
1360 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1361 Tcl_IncrRefCount(pVar);
1362 pPreStmt->apParm[iParm++] = pVar;
1363 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1364 Tcl_GetIntFromObj(interp, pVar, &n);
1365 sqlite3_bind_int(pStmt, i, n);
1366 }else if( c=='d' && strcmp(zType,"double")==0 ){
1367 double r;
1368 Tcl_GetDoubleFromObj(interp, pVar, &r);
1369 sqlite3_bind_double(pStmt, i, r);
1370 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1371 (c=='i' && strcmp(zType,"int")==0) ){
1372 Tcl_WideInt v;
1373 Tcl_GetWideIntFromObj(interp, pVar, &v);
1374 sqlite3_bind_int64(pStmt, i, v);
1375 }else{
1376 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1377 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1378 Tcl_IncrRefCount(pVar);
1379 pPreStmt->apParm[iParm++] = pVar;
1380 }
1381 }else{
1382 sqlite3_bind_null(pStmt, i);
1383 }
1384 }
1385 }
1386 pPreStmt->nParm = iParm;
1387 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001388
dan4a4c11a2009-10-06 14:59:02 +00001389 return TCL_OK;
1390}
1391
dan4a4c11a2009-10-06 14:59:02 +00001392/*
1393** Release a statement reference obtained by calling dbPrepareAndBind().
1394** There should be exactly one call to this function for each call to
1395** dbPrepareAndBind().
1396**
1397** If the discard parameter is non-zero, then the statement is deleted
1398** immediately. Otherwise it is added to the LRU list and may be returned
1399** by a subsequent call to dbPrepareAndBind().
1400*/
1401static void dbReleaseStmt(
1402 SqliteDb *pDb, /* Database handle */
1403 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1404 int discard /* True to delete (not cache) the pPreStmt */
1405){
1406 int i;
1407
1408 /* Free the bound string and blob parameters */
1409 for(i=0; i<pPreStmt->nParm; i++){
1410 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1411 }
1412 pPreStmt->nParm = 0;
1413
1414 if( pDb->maxStmt<=0 || discard ){
1415 /* If the cache is turned off, deallocated the statement */
danc431fd52011-06-27 16:55:50 +00001416 dbFreeStmt(pPreStmt);
dan4a4c11a2009-10-06 14:59:02 +00001417 }else{
1418 /* Add the prepared statement to the beginning of the cache list. */
1419 pPreStmt->pNext = pDb->stmtList;
1420 pPreStmt->pPrev = 0;
1421 if( pDb->stmtList ){
1422 pDb->stmtList->pPrev = pPreStmt;
1423 }
1424 pDb->stmtList = pPreStmt;
1425 if( pDb->stmtLast==0 ){
1426 assert( pDb->nStmt==0 );
1427 pDb->stmtLast = pPreStmt;
1428 }else{
1429 assert( pDb->nStmt>0 );
1430 }
1431 pDb->nStmt++;
mistachkinb56660f2016-07-14 21:26:09 +00001432
1433 /* If we have too many statement in cache, remove the surplus from
dan4a4c11a2009-10-06 14:59:02 +00001434 ** the end of the cache list. */
1435 while( pDb->nStmt>pDb->maxStmt ){
danc431fd52011-06-27 16:55:50 +00001436 SqlPreparedStmt *pLast = pDb->stmtLast;
1437 pDb->stmtLast = pLast->pPrev;
dan4a4c11a2009-10-06 14:59:02 +00001438 pDb->stmtLast->pNext = 0;
1439 pDb->nStmt--;
danc431fd52011-06-27 16:55:50 +00001440 dbFreeStmt(pLast);
dan4a4c11a2009-10-06 14:59:02 +00001441 }
1442 }
1443}
1444
1445/*
1446** Structure used with dbEvalXXX() functions:
1447**
1448** dbEvalInit()
1449** dbEvalStep()
1450** dbEvalFinalize()
1451** dbEvalRowInfo()
1452** dbEvalColumnValue()
1453*/
1454typedef struct DbEvalContext DbEvalContext;
1455struct DbEvalContext {
1456 SqliteDb *pDb; /* Database handle */
1457 Tcl_Obj *pSql; /* Object holding string zSql */
1458 const char *zSql; /* Remaining SQL to execute */
1459 SqlPreparedStmt *pPreStmt; /* Current statement */
1460 int nCol; /* Number of columns returned by pStmt */
1461 Tcl_Obj *pArray; /* Name of array variable */
1462 Tcl_Obj **apColName; /* Array of column names */
1463};
1464
1465/*
1466** Release any cache of column names currently held as part of
1467** the DbEvalContext structure passed as the first argument.
1468*/
1469static void dbReleaseColumnNames(DbEvalContext *p){
1470 if( p->apColName ){
1471 int i;
1472 for(i=0; i<p->nCol; i++){
1473 Tcl_DecrRefCount(p->apColName[i]);
1474 }
1475 Tcl_Free((char *)p->apColName);
1476 p->apColName = 0;
1477 }
1478 p->nCol = 0;
1479}
1480
1481/*
1482** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001483**
1484** If pArray is not NULL, then it contains the name of a Tcl array
1485** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001486** the names of the columns returned by the statement as part of each
mistachkinb56660f2016-07-14 21:26:09 +00001487** call to dbEvalStep(), in order from left to right. e.g. if the names
1488** of the returned columns are a, b and c, it does the equivalent of the
dan4a4c11a2009-10-06 14:59:02 +00001489** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001490**
1491** set ${pArray}(*) {a b c}
1492*/
dan4a4c11a2009-10-06 14:59:02 +00001493static void dbEvalInit(
1494 DbEvalContext *p, /* Pointer to structure to initialize */
1495 SqliteDb *pDb, /* Database handle */
1496 Tcl_Obj *pSql, /* Object containing SQL script */
1497 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001498){
dan4a4c11a2009-10-06 14:59:02 +00001499 memset(p, 0, sizeof(DbEvalContext));
1500 p->pDb = pDb;
1501 p->zSql = Tcl_GetString(pSql);
1502 p->pSql = pSql;
1503 Tcl_IncrRefCount(pSql);
1504 if( pArray ){
1505 p->pArray = pArray;
1506 Tcl_IncrRefCount(pArray);
1507 }
1508}
danielk19778e556522007-11-13 10:30:24 +00001509
dan4a4c11a2009-10-06 14:59:02 +00001510/*
1511** Obtain information about the row that the DbEvalContext passed as the
1512** first argument currently points to.
1513*/
1514static void dbEvalRowInfo(
1515 DbEvalContext *p, /* Evaluation context */
1516 int *pnCol, /* OUT: Number of column names */
1517 Tcl_Obj ***papColName /* OUT: Array of column names */
1518){
danielk19778e556522007-11-13 10:30:24 +00001519 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001520 if( 0==p->apColName ){
1521 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1522 int i; /* Iterator variable */
1523 int nCol; /* Number of columns returned by pStmt */
1524 Tcl_Obj **apColName = 0; /* Array of column names */
1525
1526 p->nCol = nCol = sqlite3_column_count(pStmt);
1527 if( nCol>0 && (papColName || p->pArray) ){
1528 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1529 for(i=0; i<nCol; i++){
drhc45e6712012-10-03 11:02:33 +00001530 apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
dan4a4c11a2009-10-06 14:59:02 +00001531 Tcl_IncrRefCount(apColName[i]);
1532 }
1533 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001534 }
1535
1536 /* If results are being stored in an array variable, then create
1537 ** the array(*) entry for that array
1538 */
dan4a4c11a2009-10-06 14:59:02 +00001539 if( p->pArray ){
1540 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001541 Tcl_Obj *pColList = Tcl_NewObj();
1542 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001543
danielk19778e556522007-11-13 10:30:24 +00001544 for(i=0; i<nCol; i++){
1545 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1546 }
1547 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001548 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001549 Tcl_DecrRefCount(pStar);
1550 }
danielk19778e556522007-11-13 10:30:24 +00001551 }
1552
dan4a4c11a2009-10-06 14:59:02 +00001553 if( papColName ){
1554 *papColName = p->apColName;
1555 }
1556 if( pnCol ){
1557 *pnCol = p->nCol;
1558 }
1559}
1560
1561/*
1562** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1563** returned, then an error message is stored in the interpreter before
1564** returning.
1565**
1566** A return value of TCL_OK means there is a row of data available. The
1567** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1568** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1569** is returned, then the SQL script has finished executing and there are
1570** no further rows available. This is similar to SQLITE_DONE.
1571*/
1572static int dbEvalStep(DbEvalContext *p){
danc431fd52011-06-27 16:55:50 +00001573 const char *zPrevSql = 0; /* Previous value of p->zSql */
1574
dan4a4c11a2009-10-06 14:59:02 +00001575 while( p->zSql[0] || p->pPreStmt ){
1576 int rc;
1577 if( p->pPreStmt==0 ){
danc431fd52011-06-27 16:55:50 +00001578 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
dan4a4c11a2009-10-06 14:59:02 +00001579 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1580 if( rc!=TCL_OK ) return rc;
1581 }else{
1582 int rcs;
1583 SqliteDb *pDb = p->pDb;
1584 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1585 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1586
1587 rcs = sqlite3_step(pStmt);
1588 if( rcs==SQLITE_ROW ){
1589 return TCL_OK;
1590 }
1591 if( p->pArray ){
1592 dbEvalRowInfo(p, 0, 0);
1593 }
1594 rcs = sqlite3_reset(pStmt);
1595
1596 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1597 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001598 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
danc456a762017-06-22 16:51:16 +00001599 pDb->nVMStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_VM_STEP,1);
dan4a4c11a2009-10-06 14:59:02 +00001600 dbReleaseColumnNames(p);
1601 p->pPreStmt = 0;
1602
1603 if( rcs!=SQLITE_OK ){
1604 /* If a run-time error occurs, report the error and stop reading
1605 ** the SQL. */
dan4a4c11a2009-10-06 14:59:02 +00001606 dbReleaseStmt(pDb, pPreStmt, 1);
danc431fd52011-06-27 16:55:50 +00001607#if SQLITE_TEST
1608 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1609 /* If the runtime error was an SQLITE_SCHEMA, and the database
mistachkinb56660f2016-07-14 21:26:09 +00001610 ** handle is configured to use the legacy sqlite3_prepare()
danc431fd52011-06-27 16:55:50 +00001611 ** interface, retry prepare()/step() on the same SQL statement.
1612 ** This only happens once. If there is a second SQLITE_SCHEMA
1613 ** error, the error will be returned to the caller. */
1614 p->zSql = zPrevSql;
1615 continue;
1616 }
1617#endif
drhc45e6712012-10-03 11:02:33 +00001618 Tcl_SetObjResult(pDb->interp,
1619 Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001620 return TCL_ERROR;
1621 }else{
1622 dbReleaseStmt(pDb, pPreStmt, 0);
1623 }
1624 }
1625 }
1626
1627 /* Finished */
1628 return TCL_BREAK;
1629}
1630
1631/*
1632** Free all resources currently held by the DbEvalContext structure passed
1633** as the first argument. There should be exactly one call to this function
1634** for each call to dbEvalInit().
1635*/
1636static void dbEvalFinalize(DbEvalContext *p){
1637 if( p->pPreStmt ){
1638 sqlite3_reset(p->pPreStmt->pStmt);
1639 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1640 p->pPreStmt = 0;
1641 }
1642 if( p->pArray ){
1643 Tcl_DecrRefCount(p->pArray);
1644 p->pArray = 0;
1645 }
1646 Tcl_DecrRefCount(p->pSql);
1647 dbReleaseColumnNames(p);
1648}
1649
1650/*
1651** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1652** the value for the iCol'th column of the row currently pointed to by
1653** the DbEvalContext structure passed as the first argument.
1654*/
1655static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1656 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1657 switch( sqlite3_column_type(pStmt, iCol) ){
1658 case SQLITE_BLOB: {
1659 int bytes = sqlite3_column_bytes(pStmt, iCol);
1660 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1661 if( !zBlob ) bytes = 0;
1662 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1663 }
1664 case SQLITE_INTEGER: {
1665 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1666 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +00001667 return Tcl_NewIntObj((int)v);
dan4a4c11a2009-10-06 14:59:02 +00001668 }else{
1669 return Tcl_NewWideIntObj(v);
1670 }
1671 }
1672 case SQLITE_FLOAT: {
1673 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1674 }
1675 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +00001676 return Tcl_NewStringObj(p->pDb->zNull, -1);
dan4a4c11a2009-10-06 14:59:02 +00001677 }
1678 }
1679
drh325eff52012-10-03 12:56:18 +00001680 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
dan4a4c11a2009-10-06 14:59:02 +00001681}
1682
1683/*
1684** If using Tcl version 8.6 or greater, use the NR functions to avoid
1685** recursive evalution of scripts by the [db eval] and [db trans]
1686** commands. Even if the headers used while compiling the extension
1687** are 8.6 or newer, the code still tests the Tcl version at runtime.
1688** This allows stubs-enabled builds to be used with older Tcl libraries.
1689*/
1690#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001691# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001692static int DbUseNre(void){
1693 int major, minor;
1694 Tcl_GetVersion(&major, &minor, 0, 0);
1695 return( (major==8 && minor>=6) || major>8 );
1696}
1697#else
mistachkinb56660f2016-07-14 21:26:09 +00001698/*
dan4a4c11a2009-10-06 14:59:02 +00001699** Compiling using headers earlier than 8.6. In this case NR cannot be
1700** used, so DbUseNre() to always return zero. Add #defines for the other
1701** Tcl_NRxxx() functions to prevent them from causing compilation errors,
mistachkinb56660f2016-07-14 21:26:09 +00001702** even though the only invocations of them are within conditional blocks
dan4a4c11a2009-10-06 14:59:02 +00001703** of the form:
1704**
1705** if( DbUseNre() ) { ... }
1706*/
drha2c8a952009-10-13 18:38:34 +00001707# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001708# define DbUseNre() 0
drha47941f2013-12-20 18:57:44 +00001709# define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001710# define Tcl_NREvalObj(a,b,c) 0
drha47941f2013-12-20 18:57:44 +00001711# define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001712#endif
1713
1714/*
1715** This function is part of the implementation of the command:
1716**
1717** $db eval SQL ?ARRAYNAME? SCRIPT
1718*/
mistachkina121cc72016-07-28 18:06:52 +00001719static int SQLITE_TCLAPI DbEvalNextCmd(
dan4a4c11a2009-10-06 14:59:02 +00001720 ClientData data[], /* data[0] is the (DbEvalContext*) */
1721 Tcl_Interp *interp, /* Tcl interpreter */
1722 int result /* Result so far */
1723){
1724 int rc = result; /* Return code */
1725
1726 /* The first element of the data[] array is a pointer to a DbEvalContext
1727 ** structure allocated using Tcl_Alloc(). The second element of data[]
1728 ** is a pointer to a Tcl_Obj containing the script to run for each row
1729 ** returned by the queries encapsulated in data[0]. */
1730 DbEvalContext *p = (DbEvalContext *)data[0];
1731 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1732 Tcl_Obj *pArray = p->pArray;
1733
1734 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1735 int i;
1736 int nCol;
1737 Tcl_Obj **apColName;
1738 dbEvalRowInfo(p, &nCol, &apColName);
1739 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00001740 if( pArray==0 ){
drh1973ade2017-06-26 16:13:20 +00001741 Tcl_ObjSetVar2(interp, apColName[i], 0, dbEvalColumnValue(p,i), 0);
1742 }else if( (p->pDb->modeFlags & SQLITE_TCLMODE_UNSETNULL)!=0
1743 && sqlite3_column_type(p->pPreStmt->pStmt, i)==SQLITE_NULL
1744 ){
1745 Tcl_UnsetVar2(interp, Tcl_GetString(pArray),
1746 Tcl_GetString(apColName[i]), 0);
dan4a4c11a2009-10-06 14:59:02 +00001747 }else{
drh1973ade2017-06-26 16:13:20 +00001748 Tcl_ObjSetVar2(interp, pArray, apColName[i], dbEvalColumnValue(p,i), 0);
dan4a4c11a2009-10-06 14:59:02 +00001749 }
1750 }
1751
mistachkinb56660f2016-07-14 21:26:09 +00001752 /* The required interpreter variables are now populated with the data
dan4a4c11a2009-10-06 14:59:02 +00001753 ** from the current row. If using NRE, schedule callbacks to evaluate
1754 ** script pScript, then to invoke this function again to fetch the next
1755 ** row (or clean up if there is no next row or the script throws an
mistachkinb56660f2016-07-14 21:26:09 +00001756 ** exception). After scheduling the callbacks, return control to the
dan4a4c11a2009-10-06 14:59:02 +00001757 ** caller.
1758 **
1759 ** If not using NRE, evaluate pScript directly and continue with the
1760 ** next iteration of this while(...) loop. */
1761 if( DbUseNre() ){
1762 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1763 return Tcl_NREvalObj(interp, pScript, 0);
1764 }else{
1765 rc = Tcl_EvalObjEx(interp, pScript, 0);
1766 }
1767 }
1768
1769 Tcl_DecrRefCount(pScript);
1770 dbEvalFinalize(p);
1771 Tcl_Free((char *)p);
1772
1773 if( rc==TCL_OK || rc==TCL_BREAK ){
1774 Tcl_ResetResult(interp);
1775 rc = TCL_OK;
1776 }
1777 return rc;
danielk19778e556522007-11-13 10:30:24 +00001778}
1779
tpoindex1067fe12004-12-17 15:41:11 +00001780/*
mistachkinb56660f2016-07-14 21:26:09 +00001781** This function is used by the implementations of the following database
dan46c47d42011-03-01 18:42:07 +00001782** handle sub-commands:
1783**
1784** $db update_hook ?SCRIPT?
1785** $db wal_hook ?SCRIPT?
1786** $db commit_hook ?SCRIPT?
1787** $db preupdate hook ?SCRIPT?
1788*/
1789static void DbHookCmd(
1790 Tcl_Interp *interp, /* Tcl interpreter */
1791 SqliteDb *pDb, /* Database handle */
1792 Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */
1793 Tcl_Obj **ppHook /* Pointer to member of SqliteDb */
1794){
1795 sqlite3 *db = pDb->db;
1796
1797 if( *ppHook ){
1798 Tcl_SetObjResult(interp, *ppHook);
1799 if( pArg ){
1800 Tcl_DecrRefCount(*ppHook);
1801 *ppHook = 0;
1802 }
1803 }
1804 if( pArg ){
1805 assert( !(*ppHook) );
1806 if( Tcl_GetCharLength(pArg)>0 ){
1807 *ppHook = pArg;
1808 Tcl_IncrRefCount(*ppHook);
1809 }
1810 }
1811
drh9b1c62d2011-03-30 21:04:43 +00001812#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +00001813 sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
drh9b1c62d2011-03-30 21:04:43 +00001814#endif
dan46c47d42011-03-01 18:42:07 +00001815 sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1816 sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1817 sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
1818}
1819
1820/*
drh75897232000-05-29 14:26:00 +00001821** The "sqlite" command below creates a new Tcl command for each
1822** connection it opens to an SQLite database. This routine is invoked
1823** whenever one of those connection-specific commands is executed
1824** in Tcl. For example, if you run Tcl code like this:
1825**
drh9bb575f2004-09-06 17:24:11 +00001826** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001827** db1 close
1828**
1829** The first command opens a connection to the "my_database" database
1830** and calls that connection "db1". The second command causes this
1831** subroutine to be invoked.
1832*/
mistachkin7617e4a2016-07-28 17:11:20 +00001833static int SQLITE_TCLAPI DbObjCmd(
1834 void *cd,
1835 Tcl_Interp *interp,
1836 int objc,
1837 Tcl_Obj *const*objv
1838){
drhbec3f402000-08-04 13:49:02 +00001839 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001840 int choice;
drh22fbcb82004-02-01 01:22:50 +00001841 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001842 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001843 "authorizer", "backup", "busy",
1844 "cache", "changes", "close",
1845 "collate", "collation_needed", "commit_hook",
1846 "complete", "copy", "enable_load_extension",
1847 "errorcode", "eval", "exists",
1848 "function", "incrblob", "interrupt",
drh833bf962010-04-28 14:42:19 +00001849 "last_insert_rowid", "nullvalue", "onecolumn",
drh304637c2011-03-18 16:47:27 +00001850 "preupdate", "profile", "progress",
1851 "rekey", "restore", "rollback_hook",
1852 "status", "timeout", "total_changes",
mistachkinb56660f2016-07-14 21:26:09 +00001853 "trace", "trace_v2", "transaction",
1854 "unlock_notify", "update_hook", "version",
1855 "wal_hook",
1856 0
drh6d313162000-09-21 13:01:35 +00001857 };
drh411995d2002-06-25 19:31:18 +00001858 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001859 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1860 DB_CACHE, DB_CHANGES, DB_CLOSE,
1861 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1862 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1863 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1864 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
drh833bf962010-04-28 14:42:19 +00001865 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
drh304637c2011-03-18 16:47:27 +00001866 DB_PREUPDATE, DB_PROFILE, DB_PROGRESS,
1867 DB_REKEY, DB_RESTORE, DB_ROLLBACK_HOOK,
1868 DB_STATUS, DB_TIMEOUT, DB_TOTAL_CHANGES,
mistachkinb56660f2016-07-14 21:26:09 +00001869 DB_TRACE, DB_TRACE_V2, DB_TRANSACTION,
1870 DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK, DB_VERSION,
1871 DB_WAL_HOOK,
drh6d313162000-09-21 13:01:35 +00001872 };
tpoindex1067fe12004-12-17 15:41:11 +00001873 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001874
1875 if( objc<2 ){
1876 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001877 return TCL_ERROR;
1878 }
drh411995d2002-06-25 19:31:18 +00001879 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001880 return TCL_ERROR;
1881 }
1882
drh411995d2002-06-25 19:31:18 +00001883 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001884
drhe22a3342003-04-22 20:30:37 +00001885 /* $db authorizer ?CALLBACK?
1886 **
1887 ** Invoke the given callback to authorize each SQL operation as it is
1888 ** compiled. 5 arguments are appended to the callback before it is
1889 ** invoked:
1890 **
1891 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1892 ** (2) First descriptive name (depends on authorization type)
1893 ** (3) Second descriptive name
1894 ** (4) Name of the database (ex: "main", "temp")
1895 ** (5) Name of trigger that is doing the access
1896 **
1897 ** The callback should return on of the following strings: SQLITE_OK,
1898 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1899 **
1900 ** If this method is invoked with no arguments, the current authorization
1901 ** callback string is returned.
1902 */
1903 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001904#ifdef SQLITE_OMIT_AUTHORIZATION
drha198f2b2014-02-07 19:26:13 +00001905 Tcl_AppendResult(interp, "authorization not available in this build",
1906 (char*)0);
drh1211de32004-07-26 12:24:22 +00001907 return TCL_ERROR;
1908#else
drhe22a3342003-04-22 20:30:37 +00001909 if( objc>3 ){
1910 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001911 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001912 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001913 if( pDb->zAuth ){
drha198f2b2014-02-07 19:26:13 +00001914 Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
drhe22a3342003-04-22 20:30:37 +00001915 }
1916 }else{
1917 char *zAuth;
1918 int len;
1919 if( pDb->zAuth ){
1920 Tcl_Free(pDb->zAuth);
1921 }
1922 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1923 if( zAuth && len>0 ){
1924 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001925 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001926 }else{
1927 pDb->zAuth = 0;
1928 }
drhe22a3342003-04-22 20:30:37 +00001929 if( pDb->zAuth ){
drh32c6a482014-09-11 13:44:52 +00001930 typedef int (*sqlite3_auth_cb)(
1931 void*,int,const char*,const char*,
1932 const char*,const char*);
drhe22a3342003-04-22 20:30:37 +00001933 pDb->interp = interp;
drh32c6a482014-09-11 13:44:52 +00001934 sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
drhe22a3342003-04-22 20:30:37 +00001935 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001936 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001937 }
drhe22a3342003-04-22 20:30:37 +00001938 }
drh1211de32004-07-26 12:24:22 +00001939#endif
drhe22a3342003-04-22 20:30:37 +00001940 break;
1941 }
1942
drhdc2c4912009-02-04 22:46:47 +00001943 /* $db backup ?DATABASE? FILENAME
1944 **
1945 ** Open or create a database file named FILENAME. Transfer the
1946 ** content of local database DATABASE (default: "main") into the
1947 ** FILENAME database.
1948 */
1949 case DB_BACKUP: {
1950 const char *zDestFile;
1951 const char *zSrcDb;
1952 sqlite3 *pDest;
1953 sqlite3_backup *pBackup;
1954
1955 if( objc==3 ){
1956 zSrcDb = "main";
1957 zDestFile = Tcl_GetString(objv[2]);
1958 }else if( objc==4 ){
1959 zSrcDb = Tcl_GetString(objv[2]);
1960 zDestFile = Tcl_GetString(objv[3]);
1961 }else{
1962 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1963 return TCL_ERROR;
1964 }
drh147ef392016-01-22 23:17:51 +00001965 rc = sqlite3_open_v2(zDestFile, &pDest,
1966 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00001967 if( rc!=SQLITE_OK ){
1968 Tcl_AppendResult(interp, "cannot open target database: ",
1969 sqlite3_errmsg(pDest), (char*)0);
1970 sqlite3_close(pDest);
1971 return TCL_ERROR;
1972 }
1973 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1974 if( pBackup==0 ){
1975 Tcl_AppendResult(interp, "backup failed: ",
1976 sqlite3_errmsg(pDest), (char*)0);
1977 sqlite3_close(pDest);
1978 return TCL_ERROR;
1979 }
1980 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1981 sqlite3_backup_finish(pBackup);
1982 if( rc==SQLITE_DONE ){
1983 rc = TCL_OK;
1984 }else{
1985 Tcl_AppendResult(interp, "backup failed: ",
1986 sqlite3_errmsg(pDest), (char*)0);
1987 rc = TCL_ERROR;
1988 }
1989 sqlite3_close(pDest);
1990 break;
1991 }
1992
drhbec3f402000-08-04 13:49:02 +00001993 /* $db busy ?CALLBACK?
1994 **
1995 ** Invoke the given callback if an SQL statement attempts to open
1996 ** a locked database file.
1997 */
drh6d313162000-09-21 13:01:35 +00001998 case DB_BUSY: {
1999 if( objc>3 ){
2000 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00002001 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00002002 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00002003 if( pDb->zBusy ){
drha198f2b2014-02-07 19:26:13 +00002004 Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
drhbec3f402000-08-04 13:49:02 +00002005 }
2006 }else{
drh6d313162000-09-21 13:01:35 +00002007 char *zBusy;
2008 int len;
drhbec3f402000-08-04 13:49:02 +00002009 if( pDb->zBusy ){
2010 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00002011 }
drh6d313162000-09-21 13:01:35 +00002012 zBusy = Tcl_GetStringFromObj(objv[2], &len);
2013 if( zBusy && len>0 ){
2014 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002015 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00002016 }else{
2017 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00002018 }
2019 if( pDb->zBusy ){
2020 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002021 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00002022 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002023 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00002024 }
2025 }
drh6d313162000-09-21 13:01:35 +00002026 break;
2027 }
drhbec3f402000-08-04 13:49:02 +00002028
drhfb7e7652005-01-24 00:28:42 +00002029 /* $db cache flush
2030 ** $db cache size n
2031 **
2032 ** Flush the prepared statement cache, or set the maximum number of
2033 ** cached statements.
2034 */
2035 case DB_CACHE: {
2036 char *subCmd;
2037 int n;
2038
2039 if( objc<=2 ){
2040 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
2041 return TCL_ERROR;
2042 }
2043 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
2044 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
2045 if( objc!=3 ){
2046 Tcl_WrongNumArgs(interp, 2, objv, "flush");
2047 return TCL_ERROR;
2048 }else{
2049 flushStmtCache( pDb );
2050 }
2051 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
2052 if( objc!=4 ){
2053 Tcl_WrongNumArgs(interp, 2, objv, "size n");
2054 return TCL_ERROR;
2055 }else{
2056 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
mistachkinb56660f2016-07-14 21:26:09 +00002057 Tcl_AppendResult( interp, "cannot convert \"",
drha198f2b2014-02-07 19:26:13 +00002058 Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
drhfb7e7652005-01-24 00:28:42 +00002059 return TCL_ERROR;
2060 }else{
2061 if( n<0 ){
2062 flushStmtCache( pDb );
2063 n = 0;
2064 }else if( n>MAX_PREPARED_STMTS ){
2065 n = MAX_PREPARED_STMTS;
2066 }
2067 pDb->maxStmt = n;
2068 }
2069 }
2070 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002071 Tcl_AppendResult( interp, "bad option \"",
drha198f2b2014-02-07 19:26:13 +00002072 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
2073 (char*)0);
drhfb7e7652005-01-24 00:28:42 +00002074 return TCL_ERROR;
2075 }
2076 break;
2077 }
2078
danielk1977b28af712004-06-21 06:50:26 +00002079 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00002080 **
2081 ** Return the number of rows that were modified, inserted, or deleted by
mistachkinb56660f2016-07-14 21:26:09 +00002082 ** the most recent INSERT, UPDATE or DELETE statement, not including
danielk1977b28af712004-06-21 06:50:26 +00002083 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00002084 */
2085 case DB_CHANGES: {
2086 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00002087 if( objc!=2 ){
2088 Tcl_WrongNumArgs(interp, 2, objv, "");
2089 return TCL_ERROR;
2090 }
drhc8d30ac2002-04-12 10:08:59 +00002091 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00002092 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00002093 break;
2094 }
2095
drh75897232000-05-29 14:26:00 +00002096 /* $db close
2097 **
2098 ** Shutdown the database
2099 */
drh6d313162000-09-21 13:01:35 +00002100 case DB_CLOSE: {
2101 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
2102 break;
2103 }
drh75897232000-05-29 14:26:00 +00002104
drh0f14e2e2004-06-29 12:39:08 +00002105 /*
2106 ** $db collate NAME SCRIPT
2107 **
2108 ** Create a new SQL collation function called NAME. Whenever
2109 ** that function is called, invoke SCRIPT to evaluate the function.
2110 */
2111 case DB_COLLATE: {
2112 SqlCollate *pCollate;
2113 char *zName;
2114 char *zScript;
2115 int nScript;
2116 if( objc!=4 ){
2117 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
2118 return TCL_ERROR;
2119 }
2120 zName = Tcl_GetStringFromObj(objv[2], 0);
2121 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
2122 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
2123 if( pCollate==0 ) return TCL_ERROR;
2124 pCollate->interp = interp;
2125 pCollate->pNext = pDb->pCollate;
2126 pCollate->zScript = (char*)&pCollate[1];
2127 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00002128 memcpy(pCollate->zScript, zScript, nScript+1);
mistachkinb56660f2016-07-14 21:26:09 +00002129 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
drh0f14e2e2004-06-29 12:39:08 +00002130 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00002131 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00002132 return TCL_ERROR;
2133 }
2134 break;
2135 }
2136
2137 /*
2138 ** $db collation_needed SCRIPT
2139 **
2140 ** Create a new SQL collation function called NAME. Whenever
2141 ** that function is called, invoke SCRIPT to evaluate the function.
2142 */
2143 case DB_COLLATION_NEEDED: {
2144 if( objc!=3 ){
2145 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
2146 return TCL_ERROR;
2147 }
2148 if( pDb->pCollateNeeded ){
2149 Tcl_DecrRefCount(pDb->pCollateNeeded);
2150 }
2151 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
2152 Tcl_IncrRefCount(pDb->pCollateNeeded);
2153 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
2154 break;
2155 }
2156
drh19e2d372005-08-29 23:00:03 +00002157 /* $db commit_hook ?CALLBACK?
2158 **
2159 ** Invoke the given callback just before committing every SQL transaction.
2160 ** If the callback throws an exception or returns non-zero, then the
2161 ** transaction is aborted. If CALLBACK is an empty string, the callback
2162 ** is disabled.
2163 */
2164 case DB_COMMIT_HOOK: {
2165 if( objc>3 ){
2166 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2167 return TCL_ERROR;
2168 }else if( objc==2 ){
2169 if( pDb->zCommit ){
drha198f2b2014-02-07 19:26:13 +00002170 Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002171 }
2172 }else{
mistachkin6ef5e122014-01-24 17:03:55 +00002173 const char *zCommit;
drh19e2d372005-08-29 23:00:03 +00002174 int len;
2175 if( pDb->zCommit ){
2176 Tcl_Free(pDb->zCommit);
2177 }
2178 zCommit = Tcl_GetStringFromObj(objv[2], &len);
2179 if( zCommit && len>0 ){
2180 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002181 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00002182 }else{
2183 pDb->zCommit = 0;
2184 }
2185 if( pDb->zCommit ){
2186 pDb->interp = interp;
2187 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
2188 }else{
2189 sqlite3_commit_hook(pDb->db, 0, 0);
2190 }
2191 }
2192 break;
2193 }
2194
drh75897232000-05-29 14:26:00 +00002195 /* $db complete SQL
2196 **
2197 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2198 ** additional lines of input are needed. This is similar to the
2199 ** built-in "info complete" command of Tcl.
2200 */
drh6d313162000-09-21 13:01:35 +00002201 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00002202#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00002203 Tcl_Obj *pResult;
2204 int isComplete;
2205 if( objc!=3 ){
2206 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00002207 return TCL_ERROR;
2208 }
danielk19776f8a5032004-05-10 10:34:51 +00002209 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00002210 pResult = Tcl_GetObjResult(interp);
2211 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00002212#endif
drh6d313162000-09-21 13:01:35 +00002213 break;
2214 }
drhdcd997e2003-01-31 17:21:49 +00002215
drh19e2d372005-08-29 23:00:03 +00002216 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2217 **
2218 ** Copy data into table from filename, optionally using SEPARATOR
2219 ** as column separators. If a column contains a null string, or the
2220 ** value of NULLINDICATOR, a NULL is inserted for the column.
2221 ** conflict-algorithm is one of the sqlite conflict algorithms:
2222 ** rollback, abort, fail, ignore, replace
2223 ** On success, return the number of lines processed, not necessarily same
2224 ** as 'db changes' due to conflict-algorithm selected.
2225 **
2226 ** This code is basically an implementation/enhancement of
2227 ** the sqlite3 shell.c ".import" command.
2228 **
2229 ** This command usage is equivalent to the sqlite2.x COPY statement,
2230 ** which imports file data into a table using the PostgreSQL COPY file format:
2231 ** $db copy $conflit_algo $table_name $filename \t \\N
2232 */
2233 case DB_COPY: {
2234 char *zTable; /* Insert data into this table */
2235 char *zFile; /* The file from which to extract data */
2236 char *zConflict; /* The conflict algorithm to use */
2237 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00002238 int nCol; /* Number of columns in the table */
2239 int nByte; /* Number of bytes in an SQL string */
2240 int i, j; /* Loop counters */
2241 int nSep; /* Number of bytes in zSep[] */
2242 int nNull; /* Number of bytes in zNull[] */
2243 char *zSql; /* An SQL statement */
2244 char *zLine; /* A single line of input from the file */
2245 char **azCol; /* zLine[] broken up into columns */
mistachkin6ef5e122014-01-24 17:03:55 +00002246 const char *zCommit; /* How to commit changes */
drh19e2d372005-08-29 23:00:03 +00002247 FILE *in; /* The input file */
2248 int lineno = 0; /* Line number of input file */
2249 char zLineNum[80]; /* Line number print buffer */
2250 Tcl_Obj *pResult; /* interp result */
2251
mistachkin6ef5e122014-01-24 17:03:55 +00002252 const char *zSep;
2253 const char *zNull;
drh19e2d372005-08-29 23:00:03 +00002254 if( objc<5 || objc>7 ){
mistachkinb56660f2016-07-14 21:26:09 +00002255 Tcl_WrongNumArgs(interp, 2, objv,
drh19e2d372005-08-29 23:00:03 +00002256 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2257 return TCL_ERROR;
2258 }
2259 if( objc>=6 ){
2260 zSep = Tcl_GetStringFromObj(objv[5], 0);
2261 }else{
2262 zSep = "\t";
2263 }
2264 if( objc>=7 ){
2265 zNull = Tcl_GetStringFromObj(objv[6], 0);
2266 }else{
2267 zNull = "";
2268 }
2269 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2270 zTable = Tcl_GetStringFromObj(objv[3], 0);
2271 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002272 nSep = strlen30(zSep);
2273 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002274 if( nSep==0 ){
drha198f2b2014-02-07 19:26:13 +00002275 Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2276 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002277 return TCL_ERROR;
2278 }
drh3e59c012008-09-23 10:12:13 +00002279 if(strcmp(zConflict, "rollback") != 0 &&
2280 strcmp(zConflict, "abort" ) != 0 &&
2281 strcmp(zConflict, "fail" ) != 0 &&
2282 strcmp(zConflict, "ignore" ) != 0 &&
2283 strcmp(zConflict, "replace" ) != 0 ) {
mistachkinb56660f2016-07-14 21:26:09 +00002284 Tcl_AppendResult(interp, "Error: \"", zConflict,
drh19e2d372005-08-29 23:00:03 +00002285 "\", conflict-algorithm must be one of: rollback, "
drha198f2b2014-02-07 19:26:13 +00002286 "abort, fail, ignore, or replace", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002287 return TCL_ERROR;
2288 }
2289 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2290 if( zSql==0 ){
drha198f2b2014-02-07 19:26:13 +00002291 Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002292 return TCL_ERROR;
2293 }
drh4f21c4a2008-12-10 22:15:00 +00002294 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002295 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002296 sqlite3_free(zSql);
2297 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002298 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002299 nCol = 0;
2300 }else{
2301 nCol = sqlite3_column_count(pStmt);
2302 }
2303 sqlite3_finalize(pStmt);
2304 if( nCol==0 ) {
2305 return TCL_ERROR;
2306 }
2307 zSql = malloc( nByte + 50 + nCol*2 );
2308 if( zSql==0 ) {
drha198f2b2014-02-07 19:26:13 +00002309 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002310 return TCL_ERROR;
2311 }
2312 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2313 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002314 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002315 for(i=1; i<nCol; i++){
2316 zSql[j++] = ',';
2317 zSql[j++] = '?';
2318 }
2319 zSql[j++] = ')';
2320 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002321 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002322 free(zSql);
2323 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002324 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002325 sqlite3_finalize(pStmt);
2326 return TCL_ERROR;
2327 }
2328 in = fopen(zFile, "rb");
2329 if( in==0 ){
drhea8f0a12017-01-12 11:50:08 +00002330 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002331 sqlite3_finalize(pStmt);
2332 return TCL_ERROR;
2333 }
2334 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2335 if( azCol==0 ) {
drha198f2b2014-02-07 19:26:13 +00002336 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh43617e92006-03-06 20:55:46 +00002337 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002338 return TCL_ERROR;
2339 }
drh37527852006-03-16 16:19:56 +00002340 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002341 zCommit = "COMMIT";
2342 while( (zLine = local_getline(0, in))!=0 ){
2343 char *z;
drh19e2d372005-08-29 23:00:03 +00002344 lineno++;
2345 azCol[0] = zLine;
2346 for(i=0, z=zLine; *z; z++){
2347 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2348 *z = 0;
2349 i++;
2350 if( i<nCol ){
2351 azCol[i] = &z[nSep];
2352 z += nSep-1;
2353 }
2354 }
2355 }
2356 if( i+1!=nCol ){
2357 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002358 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002359 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002360 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002361 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002362 "Error: %s line %d: expected %d columns of data but found %d",
2363 zFile, lineno, nCol, i+1);
drha198f2b2014-02-07 19:26:13 +00002364 Tcl_AppendResult(interp, zErr, (char*)0);
drhc1f44942006-05-10 14:39:13 +00002365 free(zErr);
2366 }
drh19e2d372005-08-29 23:00:03 +00002367 zCommit = "ROLLBACK";
2368 break;
2369 }
2370 for(i=0; i<nCol; i++){
2371 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002372 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
mistachkinb56660f2016-07-14 21:26:09 +00002373 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002374 ){
drh19e2d372005-08-29 23:00:03 +00002375 sqlite3_bind_null(pStmt, i+1);
2376 }else{
2377 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2378 }
2379 }
2380 sqlite3_step(pStmt);
2381 rc = sqlite3_reset(pStmt);
2382 free(zLine);
2383 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00002384 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002385 zCommit = "ROLLBACK";
2386 break;
2387 }
2388 }
2389 free(azCol);
2390 fclose(in);
2391 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002392 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002393
2394 if( zCommit[0] == 'C' ){
2395 /* success, set result as number of lines processed */
2396 pResult = Tcl_GetObjResult(interp);
2397 Tcl_SetIntObj(pResult, lineno);
2398 rc = TCL_OK;
2399 }else{
2400 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002401 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drha198f2b2014-02-07 19:26:13 +00002402 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2403 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002404 rc = TCL_ERROR;
2405 }
2406 break;
2407 }
2408
drhdcd997e2003-01-31 17:21:49 +00002409 /*
drh41449052006-07-06 17:08:48 +00002410 ** $db enable_load_extension BOOLEAN
2411 **
2412 ** Turn the extension loading feature on or off. It if off by
2413 ** default.
2414 */
2415 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002416#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002417 int onoff;
2418 if( objc!=3 ){
2419 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2420 return TCL_ERROR;
2421 }
2422 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2423 return TCL_ERROR;
2424 }
2425 sqlite3_enable_load_extension(pDb->db, onoff);
2426 break;
drhf533acc2006-12-19 18:57:11 +00002427#else
2428 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
drha198f2b2014-02-07 19:26:13 +00002429 (char*)0);
drhf533acc2006-12-19 18:57:11 +00002430 return TCL_ERROR;
2431#endif
drh41449052006-07-06 17:08:48 +00002432 }
2433
2434 /*
drhdcd997e2003-01-31 17:21:49 +00002435 ** $db errorcode
2436 **
2437 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002438 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002439 */
2440 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002441 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002442 break;
2443 }
dan4a4c11a2009-10-06 14:59:02 +00002444
2445 /*
2446 ** $db exists $sql
2447 ** $db onecolumn $sql
2448 **
2449 ** The onecolumn method is the equivalent of:
2450 ** lindex [$db eval $sql] 0
2451 */
mistachkinb56660f2016-07-14 21:26:09 +00002452 case DB_EXISTS:
dan4a4c11a2009-10-06 14:59:02 +00002453 case DB_ONECOLUMN: {
drhedc40242016-06-13 12:34:38 +00002454 Tcl_Obj *pResult = 0;
dan4a4c11a2009-10-06 14:59:02 +00002455 DbEvalContext sEval;
2456 if( objc!=3 ){
2457 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2458 return TCL_ERROR;
2459 }
2460
2461 dbEvalInit(&sEval, pDb, objv[2], 0);
2462 rc = dbEvalStep(&sEval);
2463 if( choice==DB_ONECOLUMN ){
2464 if( rc==TCL_OK ){
drhedc40242016-06-13 12:34:38 +00002465 pResult = dbEvalColumnValue(&sEval, 0);
dand5f12cd2011-08-18 17:47:57 +00002466 }else if( rc==TCL_BREAK ){
2467 Tcl_ResetResult(interp);
dan4a4c11a2009-10-06 14:59:02 +00002468 }
2469 }else if( rc==TCL_BREAK || rc==TCL_OK ){
drhedc40242016-06-13 12:34:38 +00002470 pResult = Tcl_NewBooleanObj(rc==TCL_OK);
dan4a4c11a2009-10-06 14:59:02 +00002471 }
2472 dbEvalFinalize(&sEval);
drhedc40242016-06-13 12:34:38 +00002473 if( pResult ) Tcl_SetObjResult(interp, pResult);
dan4a4c11a2009-10-06 14:59:02 +00002474
2475 if( rc==TCL_BREAK ){
2476 rc = TCL_OK;
2477 }
2478 break;
2479 }
mistachkinb56660f2016-07-14 21:26:09 +00002480
drh75897232000-05-29 14:26:00 +00002481 /*
drh895d7472004-08-20 16:02:39 +00002482 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002483 **
2484 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002485 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002486 ** If "array" and "code" are omitted, then no callback is every invoked.
2487 ** If "array" is an empty string, then the values are placed in variables
2488 ** that have the same name as the fields extracted by the query.
2489 */
dan4a4c11a2009-10-06 14:59:02 +00002490 case DB_EVAL: {
2491 if( objc<3 || objc>5 ){
2492 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2493 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002494 }
dan4a4c11a2009-10-06 14:59:02 +00002495
drh92febd92004-08-20 18:34:20 +00002496 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002497 DbEvalContext sEval;
2498 Tcl_Obj *pRet = Tcl_NewObj();
2499 Tcl_IncrRefCount(pRet);
2500 dbEvalInit(&sEval, pDb, objv[2], 0);
2501 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2502 int i;
2503 int nCol;
2504 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002505 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002506 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002507 }
2508 }
dan4a4c11a2009-10-06 14:59:02 +00002509 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002510 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002511 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002512 rc = TCL_OK;
2513 }
drh1807ce32004-09-07 13:20:35 +00002514 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002515 }else{
mistachkin8e189222015-04-19 21:43:16 +00002516 ClientData cd2[2];
dan4a4c11a2009-10-06 14:59:02 +00002517 DbEvalContext *p;
2518 Tcl_Obj *pArray = 0;
2519 Tcl_Obj *pScript;
2520
2521 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2522 pArray = objv[3];
2523 }
2524 pScript = objv[objc-1];
2525 Tcl_IncrRefCount(pScript);
mistachkinb56660f2016-07-14 21:26:09 +00002526
dan4a4c11a2009-10-06 14:59:02 +00002527 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2528 dbEvalInit(p, pDb, objv[2], pArray);
2529
mistachkin8e189222015-04-19 21:43:16 +00002530 cd2[0] = (void *)p;
2531 cd2[1] = (void *)pScript;
2532 rc = DbEvalNextCmd(cd2, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002533 }
danielk197730ccda12004-05-27 12:11:31 +00002534 break;
2535 }
drhbec3f402000-08-04 13:49:02 +00002536
2537 /*
dan3df30592015-03-13 08:31:54 +00002538 ** $db function NAME [-argcount N] [-deterministic] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002539 **
2540 ** Create a new SQL function called NAME. Whenever that function is
2541 ** called, invoke SCRIPT to evaluate the function.
2542 */
2543 case DB_FUNCTION: {
dan3df30592015-03-13 08:31:54 +00002544 int flags = SQLITE_UTF8;
drhcabb0812002-09-14 13:47:32 +00002545 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002546 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002547 char *zName;
drhe3602be2008-09-09 12:31:33 +00002548 int nArg = -1;
dan3df30592015-03-13 08:31:54 +00002549 int i;
2550 if( objc<4 ){
2551 Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
2552 return TCL_ERROR;
2553 }
2554 for(i=3; i<(objc-1); i++){
2555 const char *z = Tcl_GetString(objv[i]);
drh4f21c4a2008-12-10 22:15:00 +00002556 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002557 if( n>2 && strncmp(z, "-argcount",n)==0 ){
dan3df30592015-03-13 08:31:54 +00002558 if( i==(objc-2) ){
drhea8f0a12017-01-12 11:50:08 +00002559 Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0);
dan3df30592015-03-13 08:31:54 +00002560 return TCL_ERROR;
2561 }
2562 if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002563 if( nArg<0 ){
2564 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2565 (char*)0);
2566 return TCL_ERROR;
2567 }
dan3df30592015-03-13 08:31:54 +00002568 i++;
2569 }else
2570 if( n>2 && strncmp(z, "-deterministic",n)==0 ){
2571 flags |= SQLITE_DETERMINISTIC;
2572 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002573 Tcl_AppendResult(interp, "bad option \"", z,
drhea8f0a12017-01-12 11:50:08 +00002574 "\": must be -argcount or -deterministic", (char*)0
dan3df30592015-03-13 08:31:54 +00002575 );
2576 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002577 }
drhcabb0812002-09-14 13:47:32 +00002578 }
dan3df30592015-03-13 08:31:54 +00002579
2580 pScript = objv[objc-1];
drhcabb0812002-09-14 13:47:32 +00002581 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002582 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002583 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002584 if( pFunc->pScript ){
2585 Tcl_DecrRefCount(pFunc->pScript);
2586 }
2587 pFunc->pScript = pScript;
2588 Tcl_IncrRefCount(pScript);
2589 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
dan3df30592015-03-13 08:31:54 +00002590 rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
danielk1977d8123362004-06-12 09:25:12 +00002591 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002592 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002593 rc = TCL_ERROR;
2594 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002595 }
drhcabb0812002-09-14 13:47:32 +00002596 break;
2597 }
2598
2599 /*
danielk19778cbadb02007-05-03 16:31:26 +00002600 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002601 */
2602 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002603#ifdef SQLITE_OMIT_INCRBLOB
drha198f2b2014-02-07 19:26:13 +00002604 Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
danielk197732a0d8b2007-05-04 19:03:02 +00002605 return TCL_ERROR;
2606#else
danielk19778cbadb02007-05-03 16:31:26 +00002607 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002608 const char *zDb = "main";
2609 const char *zTable;
2610 const char *zColumn;
drhb3f787f2012-09-29 14:45:54 +00002611 Tcl_WideInt iRow;
danielk1977b4e9af92007-05-01 17:49:49 +00002612
danielk19778cbadb02007-05-03 16:31:26 +00002613 /* Check for the -readonly option */
2614 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2615 isReadonly = 1;
2616 }
2617
2618 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2619 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002620 return TCL_ERROR;
2621 }
2622
danielk19778cbadb02007-05-03 16:31:26 +00002623 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002624 zDb = Tcl_GetString(objv[2]);
2625 }
2626 zTable = Tcl_GetString(objv[objc-3]);
2627 zColumn = Tcl_GetString(objv[objc-2]);
2628 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2629
2630 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002631 rc = createIncrblobChannel(
danedf5b162014-08-19 09:15:41 +00002632 interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
danielk19778cbadb02007-05-03 16:31:26 +00002633 );
danielk1977b4e9af92007-05-01 17:49:49 +00002634 }
danielk197732a0d8b2007-05-04 19:03:02 +00002635#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002636 break;
2637 }
2638
2639 /*
drhf11bded2006-07-17 00:02:44 +00002640 ** $db interrupt
2641 **
2642 ** Interrupt the execution of the inner-most SQL interpreter. This
2643 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2644 */
2645 case DB_INTERRUPT: {
2646 sqlite3_interrupt(pDb->db);
2647 break;
2648 }
2649
2650 /*
drh19e2d372005-08-29 23:00:03 +00002651 ** $db nullvalue ?STRING?
2652 **
2653 ** Change text used when a NULL comes back from the database. If ?STRING?
2654 ** is not present, then the current string used for NULL is returned.
2655 ** If STRING is present, then STRING is returned.
2656 **
2657 */
2658 case DB_NULLVALUE: {
2659 if( objc!=2 && objc!=3 ){
2660 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2661 return TCL_ERROR;
2662 }
2663 if( objc==3 ){
2664 int len;
2665 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2666 if( pDb->zNull ){
2667 Tcl_Free(pDb->zNull);
2668 }
2669 if( zNull && len>0 ){
2670 pDb->zNull = Tcl_Alloc( len + 1 );
drh7fd33922011-06-20 19:00:30 +00002671 memcpy(pDb->zNull, zNull, len);
drh19e2d372005-08-29 23:00:03 +00002672 pDb->zNull[len] = '\0';
2673 }else{
2674 pDb->zNull = 0;
2675 }
2676 }
drhc45e6712012-10-03 11:02:33 +00002677 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
drh19e2d372005-08-29 23:00:03 +00002678 break;
2679 }
2680
2681 /*
mistachkinb56660f2016-07-14 21:26:09 +00002682 ** $db last_insert_rowid
drhaf9ff332002-01-16 21:00:27 +00002683 **
2684 ** Return an integer which is the ROWID for the most recent insert.
2685 */
2686 case DB_LAST_INSERT_ROWID: {
2687 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002688 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002689 if( objc!=2 ){
2690 Tcl_WrongNumArgs(interp, 2, objv, "");
2691 return TCL_ERROR;
2692 }
danielk19776f8a5032004-05-10 10:34:51 +00002693 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002694 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002695 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002696 break;
2697 }
2698
2699 /*
dan4a4c11a2009-10-06 14:59:02 +00002700 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002701 */
drh1807ce32004-09-07 13:20:35 +00002702
2703 /* $db progress ?N CALLBACK?
mistachkinb56660f2016-07-14 21:26:09 +00002704 **
drh1807ce32004-09-07 13:20:35 +00002705 ** Invoke the given callback every N virtual machine opcodes while executing
2706 ** queries.
2707 */
2708 case DB_PROGRESS: {
2709 if( objc==2 ){
2710 if( pDb->zProgress ){
drha198f2b2014-02-07 19:26:13 +00002711 Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
drh1807ce32004-09-07 13:20:35 +00002712 }
2713 }else if( objc==4 ){
2714 char *zProgress;
2715 int len;
2716 int N;
2717 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002718 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002719 };
2720 if( pDb->zProgress ){
2721 Tcl_Free(pDb->zProgress);
2722 }
2723 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2724 if( zProgress && len>0 ){
2725 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002726 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002727 }else{
2728 pDb->zProgress = 0;
2729 }
2730#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2731 if( pDb->zProgress ){
2732 pDb->interp = interp;
2733 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2734 }else{
2735 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2736 }
2737#endif
2738 }else{
2739 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002740 return TCL_ERROR;
2741 }
drh5d9d7572003-08-19 14:31:01 +00002742 break;
2743 }
2744
drh19e2d372005-08-29 23:00:03 +00002745 /* $db profile ?CALLBACK?
2746 **
2747 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2748 ** that has run. The text of the SQL and the amount of elapse time are
2749 ** appended to CALLBACK before the script is run.
2750 */
2751 case DB_PROFILE: {
2752 if( objc>3 ){
2753 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2754 return TCL_ERROR;
2755 }else if( objc==2 ){
2756 if( pDb->zProfile ){
drha198f2b2014-02-07 19:26:13 +00002757 Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002758 }
2759 }else{
2760 char *zProfile;
2761 int len;
2762 if( pDb->zProfile ){
2763 Tcl_Free(pDb->zProfile);
2764 }
2765 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2766 if( zProfile && len>0 ){
2767 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002768 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002769 }else{
2770 pDb->zProfile = 0;
2771 }
drh2eb22af2016-09-10 19:51:40 +00002772#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
2773 !defined(SQLITE_OMIT_DEPRECATED)
drh19e2d372005-08-29 23:00:03 +00002774 if( pDb->zProfile ){
2775 pDb->interp = interp;
2776 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2777 }else{
2778 sqlite3_profile(pDb->db, 0, 0);
2779 }
2780#endif
2781 }
2782 break;
2783 }
2784
drh5d9d7572003-08-19 14:31:01 +00002785 /*
drh22fbcb82004-02-01 01:22:50 +00002786 ** $db rekey KEY
2787 **
2788 ** Change the encryption key on the currently open database.
2789 */
2790 case DB_REKEY: {
drh32f57d42016-03-16 01:03:10 +00002791#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh22fbcb82004-02-01 01:22:50 +00002792 int nKey;
2793 void *pKey;
drhb07028f2011-10-14 21:49:18 +00002794#endif
drh22fbcb82004-02-01 01:22:50 +00002795 if( objc!=3 ){
2796 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2797 return TCL_ERROR;
2798 }
drh32f57d42016-03-16 01:03:10 +00002799#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00002800 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh2011d5f2004-07-22 02:40:37 +00002801 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002802 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002803 Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
drh22fbcb82004-02-01 01:22:50 +00002804 rc = TCL_ERROR;
2805 }
2806#endif
2807 break;
2808 }
2809
drhdc2c4912009-02-04 22:46:47 +00002810 /* $db restore ?DATABASE? FILENAME
2811 **
mistachkinb56660f2016-07-14 21:26:09 +00002812 ** Open a database file named FILENAME. Transfer the content
drhdc2c4912009-02-04 22:46:47 +00002813 ** of FILENAME into the local database DATABASE (default: "main").
2814 */
2815 case DB_RESTORE: {
2816 const char *zSrcFile;
2817 const char *zDestDb;
2818 sqlite3 *pSrc;
2819 sqlite3_backup *pBackup;
2820 int nTimeout = 0;
2821
2822 if( objc==3 ){
2823 zDestDb = "main";
2824 zSrcFile = Tcl_GetString(objv[2]);
2825 }else if( objc==4 ){
2826 zDestDb = Tcl_GetString(objv[2]);
2827 zSrcFile = Tcl_GetString(objv[3]);
2828 }else{
2829 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2830 return TCL_ERROR;
2831 }
drh147ef392016-01-22 23:17:51 +00002832 rc = sqlite3_open_v2(zSrcFile, &pSrc,
2833 SQLITE_OPEN_READONLY | pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00002834 if( rc!=SQLITE_OK ){
2835 Tcl_AppendResult(interp, "cannot open source database: ",
2836 sqlite3_errmsg(pSrc), (char*)0);
2837 sqlite3_close(pSrc);
2838 return TCL_ERROR;
2839 }
2840 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2841 if( pBackup==0 ){
2842 Tcl_AppendResult(interp, "restore failed: ",
2843 sqlite3_errmsg(pDb->db), (char*)0);
2844 sqlite3_close(pSrc);
2845 return TCL_ERROR;
2846 }
2847 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2848 || rc==SQLITE_BUSY ){
2849 if( rc==SQLITE_BUSY ){
2850 if( nTimeout++ >= 3 ) break;
2851 sqlite3_sleep(100);
2852 }
2853 }
2854 sqlite3_backup_finish(pBackup);
2855 if( rc==SQLITE_DONE ){
2856 rc = TCL_OK;
2857 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2858 Tcl_AppendResult(interp, "restore failed: source database busy",
2859 (char*)0);
2860 rc = TCL_ERROR;
2861 }else{
2862 Tcl_AppendResult(interp, "restore failed: ",
2863 sqlite3_errmsg(pDb->db), (char*)0);
2864 rc = TCL_ERROR;
2865 }
2866 sqlite3_close(pSrc);
2867 break;
2868 }
2869
drh22fbcb82004-02-01 01:22:50 +00002870 /*
danc456a762017-06-22 16:51:16 +00002871 ** $db status (step|sort|autoindex|vmstep)
drhd1d38482008-10-07 23:46:38 +00002872 **
mistachkinb56660f2016-07-14 21:26:09 +00002873 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
drhd1d38482008-10-07 23:46:38 +00002874 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2875 */
2876 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002877 int v;
2878 const char *zOp;
2879 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00002880 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00002881 return TCL_ERROR;
2882 }
2883 zOp = Tcl_GetString(objv[2]);
2884 if( strcmp(zOp, "step")==0 ){
2885 v = pDb->nStep;
2886 }else if( strcmp(zOp, "sort")==0 ){
2887 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002888 }else if( strcmp(zOp, "autoindex")==0 ){
2889 v = pDb->nIndex;
danc456a762017-06-22 16:51:16 +00002890 }else if( strcmp(zOp, "vmstep")==0 ){
2891 v = pDb->nVMStep;
drhd1d38482008-10-07 23:46:38 +00002892 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002893 Tcl_AppendResult(interp,
danc456a762017-06-22 16:51:16 +00002894 "bad argument: should be autoindex, step, sort or vmstep",
drhd1d38482008-10-07 23:46:38 +00002895 (char*)0);
2896 return TCL_ERROR;
2897 }
2898 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2899 break;
2900 }
mistachkinb56660f2016-07-14 21:26:09 +00002901
drhd1d38482008-10-07 23:46:38 +00002902 /*
drhbec3f402000-08-04 13:49:02 +00002903 ** $db timeout MILLESECONDS
2904 **
2905 ** Delay for the number of milliseconds specified when a file is locked.
2906 */
drh6d313162000-09-21 13:01:35 +00002907 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002908 int ms;
drh6d313162000-09-21 13:01:35 +00002909 if( objc!=3 ){
2910 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002911 return TCL_ERROR;
2912 }
drh6d313162000-09-21 13:01:35 +00002913 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002914 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002915 break;
drh75897232000-05-29 14:26:00 +00002916 }
mistachkinb56660f2016-07-14 21:26:09 +00002917
danielk197755c45f22005-04-03 23:54:43 +00002918 /*
drh0f14e2e2004-06-29 12:39:08 +00002919 ** $db total_changes
2920 **
mistachkinb56660f2016-07-14 21:26:09 +00002921 ** Return the number of rows that were modified, inserted, or deleted
drh0f14e2e2004-06-29 12:39:08 +00002922 ** since the database handle was created.
2923 */
2924 case DB_TOTAL_CHANGES: {
2925 Tcl_Obj *pResult;
2926 if( objc!=2 ){
2927 Tcl_WrongNumArgs(interp, 2, objv, "");
2928 return TCL_ERROR;
2929 }
2930 pResult = Tcl_GetObjResult(interp);
2931 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2932 break;
2933 }
2934
drhb5a20d32003-04-23 12:25:23 +00002935 /* $db trace ?CALLBACK?
2936 **
2937 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2938 ** that is executed. The text of the SQL is appended to CALLBACK before
2939 ** it is executed.
2940 */
2941 case DB_TRACE: {
2942 if( objc>3 ){
2943 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002944 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002945 }else if( objc==2 ){
2946 if( pDb->zTrace ){
drha198f2b2014-02-07 19:26:13 +00002947 Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
drhb5a20d32003-04-23 12:25:23 +00002948 }
2949 }else{
2950 char *zTrace;
2951 int len;
2952 if( pDb->zTrace ){
2953 Tcl_Free(pDb->zTrace);
2954 }
2955 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2956 if( zTrace && len>0 ){
2957 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002958 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002959 }else{
2960 pDb->zTrace = 0;
2961 }
drh2eb22af2016-09-10 19:51:40 +00002962#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
2963 !defined(SQLITE_OMIT_DEPRECATED)
drhb5a20d32003-04-23 12:25:23 +00002964 if( pDb->zTrace ){
2965 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002966 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002967 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002968 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002969 }
drh19e2d372005-08-29 23:00:03 +00002970#endif
drhb5a20d32003-04-23 12:25:23 +00002971 }
2972 break;
2973 }
2974
mistachkinb56660f2016-07-14 21:26:09 +00002975 /* $db trace_v2 ?CALLBACK? ?MASK?
2976 **
2977 ** Make arrangements to invoke the CALLBACK routine for each trace event
2978 ** matching the mask that is generated. The parameters are appended to
2979 ** CALLBACK before it is executed.
2980 */
2981 case DB_TRACE_V2: {
2982 if( objc>4 ){
2983 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK? ?MASK?");
2984 return TCL_ERROR;
2985 }else if( objc==2 ){
2986 if( pDb->zTraceV2 ){
2987 Tcl_AppendResult(interp, pDb->zTraceV2, (char*)0);
2988 }
2989 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002990 char *zTraceV2;
2991 int len;
mistachkinb52dcd82016-07-14 23:17:03 +00002992 Tcl_WideInt wMask = 0;
mistachkinb56660f2016-07-14 21:26:09 +00002993 if( objc==4 ){
mistachkinb52dcd82016-07-14 23:17:03 +00002994 static const char *TTYPE_strs[] = {
2995 "statement", "profile", "row", "close", 0
2996 };
2997 enum TTYPE_enum {
2998 TTYPE_STMT, TTYPE_PROFILE, TTYPE_ROW, TTYPE_CLOSE
2999 };
3000 int i;
3001 if( TCL_OK!=Tcl_ListObjLength(interp, objv[3], &len) ){
mistachkinb56660f2016-07-14 21:26:09 +00003002 return TCL_ERROR;
3003 }
mistachkinb52dcd82016-07-14 23:17:03 +00003004 for(i=0; i<len; i++){
3005 Tcl_Obj *pObj;
3006 int ttype;
3007 if( TCL_OK!=Tcl_ListObjIndex(interp, objv[3], i, &pObj) ){
3008 return TCL_ERROR;
3009 }
3010 if( Tcl_GetIndexFromObj(interp, pObj, TTYPE_strs, "trace type",
3011 0, &ttype)!=TCL_OK ){
3012 Tcl_WideInt wType;
3013 Tcl_Obj *pError = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
3014 Tcl_IncrRefCount(pError);
3015 if( TCL_OK==Tcl_GetWideIntFromObj(interp, pObj, &wType) ){
3016 Tcl_DecrRefCount(pError);
3017 wMask |= wType;
3018 }else{
3019 Tcl_SetObjResult(interp, pError);
3020 Tcl_DecrRefCount(pError);
3021 return TCL_ERROR;
3022 }
3023 }else{
3024 switch( (enum TTYPE_enum)ttype ){
3025 case TTYPE_STMT: wMask |= SQLITE_TRACE_STMT; break;
3026 case TTYPE_PROFILE: wMask |= SQLITE_TRACE_PROFILE; break;
3027 case TTYPE_ROW: wMask |= SQLITE_TRACE_ROW; break;
3028 case TTYPE_CLOSE: wMask |= SQLITE_TRACE_CLOSE; break;
3029 }
3030 }
3031 }
mistachkinb56660f2016-07-14 21:26:09 +00003032 }else{
mistachkinb52dcd82016-07-14 23:17:03 +00003033 wMask = SQLITE_TRACE_STMT; /* use the "legacy" default */
mistachkinb56660f2016-07-14 21:26:09 +00003034 }
3035 if( pDb->zTraceV2 ){
3036 Tcl_Free(pDb->zTraceV2);
3037 }
3038 zTraceV2 = Tcl_GetStringFromObj(objv[2], &len);
3039 if( zTraceV2 && len>0 ){
3040 pDb->zTraceV2 = Tcl_Alloc( len + 1 );
3041 memcpy(pDb->zTraceV2, zTraceV2, len+1);
3042 }else{
3043 pDb->zTraceV2 = 0;
3044 }
3045#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3046 if( pDb->zTraceV2 ){
3047 pDb->interp = interp;
3048 sqlite3_trace_v2(pDb->db, (unsigned)wMask, DbTraceV2Handler, pDb);
3049 }else{
3050 sqlite3_trace_v2(pDb->db, 0, 0, 0);
3051 }
3052#endif
3053 }
3054 break;
3055 }
3056
drh3d214232005-08-02 12:21:08 +00003057 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
3058 **
3059 ** Start a new transaction (if we are not already in the midst of a
3060 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
3061 ** completes, either commit the transaction or roll it back if SCRIPT
3062 ** throws an exception. Or if no new transation was started, do nothing.
3063 ** pass the exception on up the stack.
3064 **
3065 ** This command was inspired by Dave Thomas's talk on Ruby at the
3066 ** 2005 O'Reilly Open Source Convention (OSCON).
3067 */
3068 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00003069 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00003070 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00003071 if( objc!=3 && objc!=4 ){
3072 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
3073 return TCL_ERROR;
3074 }
danielk1977cd38d522009-01-02 17:33:46 +00003075
dan4a4c11a2009-10-06 14:59:02 +00003076 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00003077 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00003078 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00003079 };
3080 enum TTYPE_enum {
3081 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
3082 };
3083 int ttype;
drhb5555e72005-08-02 17:15:14 +00003084 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00003085 0, &ttype) ){
3086 return TCL_ERROR;
3087 }
3088 switch( (enum TTYPE_enum)ttype ){
3089 case TTYPE_DEFERRED: /* no-op */; break;
3090 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
3091 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
3092 }
drh3d214232005-08-02 12:21:08 +00003093 }
danielk1977cd38d522009-01-02 17:33:46 +00003094 pScript = objv[objc-1];
3095
dan4a4c11a2009-10-06 14:59:02 +00003096 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00003097 pDb->disableAuth++;
3098 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
3099 pDb->disableAuth--;
3100 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00003101 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977cd38d522009-01-02 17:33:46 +00003102 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00003103 }
danielk1977cd38d522009-01-02 17:33:46 +00003104 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00003105
dan4a4c11a2009-10-06 14:59:02 +00003106 /* If using NRE, schedule a callback to invoke the script pScript, then
3107 ** a second callback to commit (or rollback) the transaction or savepoint
3108 ** opened above. If not using NRE, evaluate the script directly, then
mistachkinb56660f2016-07-14 21:26:09 +00003109 ** call function DbTransPostCmd() to commit (or rollback) the transaction
dan4a4c11a2009-10-06 14:59:02 +00003110 ** or savepoint. */
3111 if( DbUseNre() ){
3112 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
drha47941f2013-12-20 18:57:44 +00003113 (void)Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00003114 }else{
dan4a4c11a2009-10-06 14:59:02 +00003115 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00003116 }
3117 break;
3118 }
3119
danielk197794eb6a12005-12-15 15:22:08 +00003120 /*
danielk1977404ca072009-03-16 13:19:36 +00003121 ** $db unlock_notify ?script?
3122 */
3123 case DB_UNLOCK_NOTIFY: {
3124#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
drha198f2b2014-02-07 19:26:13 +00003125 Tcl_AppendResult(interp, "unlock_notify not available in this build",
3126 (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00003127 rc = TCL_ERROR;
3128#else
3129 if( objc!=2 && objc!=3 ){
3130 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3131 rc = TCL_ERROR;
3132 }else{
3133 void (*xNotify)(void **, int) = 0;
3134 void *pNotifyArg = 0;
3135
3136 if( pDb->pUnlockNotify ){
3137 Tcl_DecrRefCount(pDb->pUnlockNotify);
3138 pDb->pUnlockNotify = 0;
3139 }
mistachkinb56660f2016-07-14 21:26:09 +00003140
danielk1977404ca072009-03-16 13:19:36 +00003141 if( objc==3 ){
3142 xNotify = DbUnlockNotify;
3143 pNotifyArg = (void *)pDb;
3144 pDb->pUnlockNotify = objv[2];
3145 Tcl_IncrRefCount(pDb->pUnlockNotify);
3146 }
mistachkinb56660f2016-07-14 21:26:09 +00003147
danielk1977404ca072009-03-16 13:19:36 +00003148 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
drha198f2b2014-02-07 19:26:13 +00003149 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00003150 rc = TCL_ERROR;
3151 }
3152 }
3153#endif
3154 break;
3155 }
3156
drh304637c2011-03-18 16:47:27 +00003157 /*
3158 ** $db preupdate_hook count
3159 ** $db preupdate_hook hook ?SCRIPT?
3160 ** $db preupdate_hook new INDEX
3161 ** $db preupdate_hook old INDEX
3162 */
dan46c47d42011-03-01 18:42:07 +00003163 case DB_PREUPDATE: {
drh9b1c62d2011-03-30 21:04:43 +00003164#ifndef SQLITE_ENABLE_PREUPDATE_HOOK
dan2b519ab2016-12-06 19:33:42 +00003165 Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time",
3166 (char*)0);
drh9b1c62d2011-03-30 21:04:43 +00003167 rc = TCL_ERROR;
3168#else
dan1e7a2d42011-03-22 18:45:29 +00003169 static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
dan46c47d42011-03-01 18:42:07 +00003170 enum DbPreupdateSubCmd {
dan1e7a2d42011-03-22 18:45:29 +00003171 PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
dan46c47d42011-03-01 18:42:07 +00003172 };
3173 int iSub;
3174
3175 if( objc<3 ){
3176 Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
3177 }
3178 if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
3179 return TCL_ERROR;
3180 }
3181
3182 switch( (enum DbPreupdateSubCmd)iSub ){
3183 case PRE_COUNT: {
3184 int nCol = sqlite3_preupdate_count(pDb->db);
3185 Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
3186 break;
3187 }
3188
3189 case PRE_HOOK: {
3190 if( objc>4 ){
3191 Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
3192 return TCL_ERROR;
3193 }
3194 DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
3195 break;
3196 }
3197
dan1e7a2d42011-03-22 18:45:29 +00003198 case PRE_DEPTH: {
3199 Tcl_Obj *pRet;
3200 if( objc!=3 ){
3201 Tcl_WrongNumArgs(interp, 3, objv, "");
3202 return TCL_ERROR;
3203 }
3204 pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
3205 Tcl_SetObjResult(interp, pRet);
3206 break;
3207 }
3208
dan37db03b2011-03-16 19:59:18 +00003209 case PRE_NEW:
dan46c47d42011-03-01 18:42:07 +00003210 case PRE_OLD: {
3211 int iIdx;
dan37db03b2011-03-16 19:59:18 +00003212 sqlite3_value *pValue;
dan46c47d42011-03-01 18:42:07 +00003213 if( objc!=4 ){
3214 Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
3215 return TCL_ERROR;
3216 }
3217 if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
3218 return TCL_ERROR;
3219 }
3220
dan37db03b2011-03-16 19:59:18 +00003221 if( iSub==PRE_OLD ){
dan46c47d42011-03-01 18:42:07 +00003222 rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
dan37db03b2011-03-16 19:59:18 +00003223 }else{
3224 assert( iSub==PRE_NEW );
3225 rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
dan46c47d42011-03-01 18:42:07 +00003226 }
3227
dan37db03b2011-03-16 19:59:18 +00003228 if( rc==SQLITE_OK ){
drh304637c2011-03-18 16:47:27 +00003229 Tcl_Obj *pObj;
3230 pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
dan37db03b2011-03-16 19:59:18 +00003231 Tcl_SetObjResult(interp, pObj);
3232 }else{
drhea8f0a12017-01-12 11:50:08 +00003233 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
dan46c47d42011-03-01 18:42:07 +00003234 return TCL_ERROR;
3235 }
3236 }
3237 }
drh9b1c62d2011-03-30 21:04:43 +00003238#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +00003239 break;
3240 }
3241
danielk1977404ca072009-03-16 13:19:36 +00003242 /*
drh833bf962010-04-28 14:42:19 +00003243 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003244 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00003245 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003246 */
mistachkinb56660f2016-07-14 21:26:09 +00003247 case DB_WAL_HOOK:
3248 case DB_UPDATE_HOOK:
dan6566ebe2011-03-16 09:49:14 +00003249 case DB_ROLLBACK_HOOK: {
mistachkinb56660f2016-07-14 21:26:09 +00003250 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
danielk197771fd80b2005-12-16 06:54:01 +00003251 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3252 */
mistachkinb56660f2016-07-14 21:26:09 +00003253 Tcl_Obj **ppHook = 0;
dan46c47d42011-03-01 18:42:07 +00003254 if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
3255 if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
3256 if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
3257 if( objc>3 ){
danielk197794eb6a12005-12-15 15:22:08 +00003258 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3259 return TCL_ERROR;
3260 }
danielk197771fd80b2005-12-16 06:54:01 +00003261
dan46c47d42011-03-01 18:42:07 +00003262 DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00003263 break;
3264 }
3265
danielk19774397de52005-01-12 12:44:03 +00003266 /* $db version
3267 **
3268 ** Return the version string for this database.
3269 */
3270 case DB_VERSION: {
3271 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
3272 break;
3273 }
3274
tpoindex1067fe12004-12-17 15:41:11 +00003275
drh6d313162000-09-21 13:01:35 +00003276 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00003277 return rc;
drh75897232000-05-29 14:26:00 +00003278}
3279
drha2c8a952009-10-13 18:38:34 +00003280#if SQLITE_TCL_NRE
3281/*
3282** Adaptor that provides an objCmd interface to the NRE-enabled
3283** interface implementation.
3284*/
mistachkina121cc72016-07-28 18:06:52 +00003285static int SQLITE_TCLAPI DbObjCmdAdaptor(
drha2c8a952009-10-13 18:38:34 +00003286 void *cd,
3287 Tcl_Interp *interp,
3288 int objc,
3289 Tcl_Obj *const*objv
3290){
3291 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
3292}
3293#endif /* SQLITE_TCL_NRE */
3294
drh75897232000-05-29 14:26:00 +00003295/*
drh3570ad92007-08-31 14:31:44 +00003296** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00003297** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00003298**
3299** This is the main Tcl command. When the "sqlite" Tcl command is
3300** invoked, this routine runs to process that command.
3301**
3302** The first argument, DBNAME, is an arbitrary name for a new
3303** database connection. This command creates a new command named
3304** DBNAME that is used to control that connection. The database
3305** connection is deleted when the DBNAME command is deleted.
3306**
drh3570ad92007-08-31 14:31:44 +00003307** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00003308**
drh75897232000-05-29 14:26:00 +00003309*/
mistachkin7617e4a2016-07-28 17:11:20 +00003310static int SQLITE_TCLAPI DbMain(
3311 void *cd,
3312 Tcl_Interp *interp,
3313 int objc,
3314 Tcl_Obj *const*objv
3315){
drhbec3f402000-08-04 13:49:02 +00003316 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00003317 const char *zArg;
drh75897232000-05-29 14:26:00 +00003318 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00003319 int i;
drh22fbcb82004-02-01 01:22:50 +00003320 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00003321 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00003322 int flags;
drh1973ade2017-06-26 16:13:20 +00003323 unsigned int modeFlags = 0;
drh882e8e42006-08-24 02:42:27 +00003324 Tcl_DString translatedFilename;
drh32f57d42016-03-16 01:03:10 +00003325#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00003326 void *pKey = 0;
3327 int nKey = 0;
3328#endif
mistachkin540ebf82012-09-10 07:29:29 +00003329 int rc;
drhd9da78a2009-03-24 15:08:09 +00003330
3331 /* In normal use, each TCL interpreter runs in a single thread. So
3332 ** by default, we can turn of mutexing on SQLite database connections.
3333 ** However, for testing purposes it is useful to have mutexes turned
3334 ** on. So, by default, mutexes default off. But if compiled with
3335 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3336 */
3337#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3338 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3339#else
3340 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3341#endif
3342
drh22fbcb82004-02-01 01:22:50 +00003343 if( objc==2 ){
3344 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00003345 if( strcmp(zArg,"-version")==0 ){
drha198f2b2014-02-07 19:26:13 +00003346 Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
drh647cb0e2002-11-04 19:32:25 +00003347 return TCL_OK;
3348 }
drh72bf6a32016-01-07 02:06:55 +00003349 if( strcmp(zArg,"-sourceid")==0 ){
3350 Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0);
3351 return TCL_OK;
3352 }
drh9eb9e262004-02-11 02:18:05 +00003353 if( strcmp(zArg,"-has-codec")==0 ){
drh32f57d42016-03-16 01:03:10 +00003354#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drha198f2b2014-02-07 19:26:13 +00003355 Tcl_AppendResult(interp,"1",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003356#else
drha198f2b2014-02-07 19:26:13 +00003357 Tcl_AppendResult(interp,"0",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003358#endif
3359 return TCL_OK;
3360 }
drhfbc3eab2001-04-06 16:13:42 +00003361 }
drh3570ad92007-08-31 14:31:44 +00003362 for(i=3; i+1<objc; i+=2){
3363 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00003364 if( strcmp(zArg,"-key")==0 ){
drh32f57d42016-03-16 01:03:10 +00003365#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh3570ad92007-08-31 14:31:44 +00003366 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
drhb07028f2011-10-14 21:49:18 +00003367#endif
drh3570ad92007-08-31 14:31:44 +00003368 }else if( strcmp(zArg, "-vfs")==0 ){
dan3c3dd7b2010-06-22 11:10:40 +00003369 zVfs = Tcl_GetString(objv[i+1]);
drh3570ad92007-08-31 14:31:44 +00003370 }else if( strcmp(zArg, "-readonly")==0 ){
3371 int b;
3372 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3373 if( b ){
drh33f4e022007-09-03 15:19:34 +00003374 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00003375 flags |= SQLITE_OPEN_READONLY;
3376 }else{
3377 flags &= ~SQLITE_OPEN_READONLY;
3378 flags |= SQLITE_OPEN_READWRITE;
3379 }
3380 }else if( strcmp(zArg, "-create")==0 ){
3381 int b;
3382 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00003383 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00003384 flags |= SQLITE_OPEN_CREATE;
3385 }else{
3386 flags &= ~SQLITE_OPEN_CREATE;
3387 }
danielk19779a6284c2008-07-10 17:52:49 +00003388 }else if( strcmp(zArg, "-nomutex")==0 ){
3389 int b;
3390 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3391 if( b ){
3392 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00003393 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00003394 }else{
3395 flags &= ~SQLITE_OPEN_NOMUTEX;
3396 }
danc431fd52011-06-27 16:55:50 +00003397 }else if( strcmp(zArg, "-fullmutex")==0 ){
drh039963a2008-09-03 00:43:15 +00003398 int b;
3399 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3400 if( b ){
3401 flags |= SQLITE_OPEN_FULLMUTEX;
3402 flags &= ~SQLITE_OPEN_NOMUTEX;
3403 }else{
3404 flags &= ~SQLITE_OPEN_FULLMUTEX;
3405 }
drhf12b3f62011-12-21 14:42:29 +00003406 }else if( strcmp(zArg, "-uri")==0 ){
3407 int b;
3408 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3409 if( b ){
3410 flags |= SQLITE_OPEN_URI;
3411 }else{
3412 flags &= ~SQLITE_OPEN_URI;
3413 }
drh1973ade2017-06-26 16:13:20 +00003414 }else if( strcmp(zArg, "-unsetnull")==0 ){
3415 int b;
3416 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3417 if( b ){
3418 modeFlags |= SQLITE_TCLMODE_UNSETNULL;
3419 }else{
3420 modeFlags &= ~SQLITE_TCLMODE_UNSETNULL;
3421 }
drh3570ad92007-08-31 14:31:44 +00003422 }else{
3423 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3424 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00003425 }
3426 }
drh3570ad92007-08-31 14:31:44 +00003427 if( objc<3 || (objc&1)!=1 ){
mistachkinb56660f2016-07-14 21:26:09 +00003428 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00003429 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh68bd4aa2012-01-13 16:16:10 +00003430 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
drh1973ade2017-06-26 16:13:20 +00003431 " ?-unsetnull BOOLEAN?"
drh32f57d42016-03-16 01:03:10 +00003432#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh3570ad92007-08-31 14:31:44 +00003433 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00003434#endif
3435 );
drh75897232000-05-29 14:26:00 +00003436 return TCL_ERROR;
3437 }
drh75897232000-05-29 14:26:00 +00003438 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003439 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drhbec3f402000-08-04 13:49:02 +00003440 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00003441 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00003442 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003443 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00003444 Tcl_DStringFree(&translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003445 if( p->db ){
3446 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3447 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3448 sqlite3_close(p->db);
3449 p->db = 0;
3450 }
3451 }else{
mistachkin5dac8432012-09-11 02:00:25 +00003452 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
danielk197780290862004-05-22 09:21:21 +00003453 }
drh32f57d42016-03-16 01:03:10 +00003454#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhf3a65f72007-08-22 20:18:21 +00003455 if( p->db ){
3456 sqlite3_key(p->db, pKey, nKey);
3457 }
drheb8ed702004-02-11 10:37:23 +00003458#endif
drhbec3f402000-08-04 13:49:02 +00003459 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003460 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003461 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003462 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003463 return TCL_ERROR;
3464 }
drhfb7e7652005-01-24 00:28:42 +00003465 p->maxStmt = NUM_PREPARED_STMTS;
drh147ef392016-01-22 23:17:51 +00003466 p->openFlags = flags & SQLITE_OPEN_URI;
drh1973ade2017-06-26 16:13:20 +00003467 p->modeFlags = modeFlags;
drh5169bbc2006-08-24 14:59:45 +00003468 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003469 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003470 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003471 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3472 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003473 }else{
3474 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3475 }
drh75897232000-05-29 14:26:00 +00003476 return TCL_OK;
3477}
3478
3479/*
drh90ca9752001-09-28 17:47:14 +00003480** Provide a dummy Tcl_InitStubs if we are using this as a static
3481** library.
3482*/
3483#ifndef USE_TCL_STUBS
3484# undef Tcl_InitStubs
drh0e85ccf2013-06-03 12:34:46 +00003485# define Tcl_InitStubs(a,b,c) TCL_VERSION
drh90ca9752001-09-28 17:47:14 +00003486#endif
3487
3488/*
drh29bc4612005-10-05 10:40:15 +00003489** Make sure we have a PACKAGE_VERSION macro defined. This will be
3490** defined automatically by the TEA makefile. But other makefiles
3491** do not define it.
3492*/
3493#ifndef PACKAGE_VERSION
3494# define PACKAGE_VERSION SQLITE_VERSION
3495#endif
3496
3497/*
drh75897232000-05-29 14:26:00 +00003498** Initialize this module.
3499**
3500** This Tcl module contains only a single new Tcl command named "sqlite".
3501** (Hence there is no namespace. There is no point in using a namespace
3502** if the extension only supplies one new name!) The "sqlite" command is
3503** used to open a new SQLite database. See the DbMain() routine above
3504** for additional information.
drhb652f432010-08-26 16:46:57 +00003505**
3506** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003507*/
drhb652f432010-08-26 16:46:57 +00003508EXTERN int Sqlite3_Init(Tcl_Interp *interp){
mistachkin27b2f052015-01-12 19:49:46 +00003509 int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
drh6dc8cbe2013-05-31 15:36:07 +00003510 if( rc==TCL_OK ){
3511 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh1cca0d22010-08-25 20:35:51 +00003512#ifndef SQLITE_3_SUFFIX_ONLY
drh6dc8cbe2013-05-31 15:36:07 +00003513 /* The "sqlite" alias is undocumented. It is here only to support
3514 ** legacy scripts. All new scripts should use only the "sqlite3"
3515 ** command. */
3516 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003517#endif
drh6dc8cbe2013-05-31 15:36:07 +00003518 rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3519 }
3520 return rc;
drh90ca9752001-09-28 17:47:14 +00003521}
drhb652f432010-08-26 16:46:57 +00003522EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
drhb652f432010-08-26 16:46:57 +00003523EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3524EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00003525
drhd878cab2012-03-20 15:10:42 +00003526/* Because it accesses the file-system and uses persistent state, SQLite
drhe75a9eb2016-02-13 18:54:10 +00003527** is not considered appropriate for safe interpreters. Hence, we cause
3528** the _SafeInit() interfaces return TCL_ERROR.
drhd878cab2012-03-20 15:10:42 +00003529*/
drhe75a9eb2016-02-13 18:54:10 +00003530EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
3531EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
3532
3533
drh49766d62005-01-08 18:42:28 +00003534
3535#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003536int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3537int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
dana3e63c42010-08-20 12:33:59 +00003538int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3539int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00003540#endif
drh75897232000-05-29 14:26:00 +00003541
drh3e27c022004-07-23 00:01:38 +00003542#ifdef TCLSH
3543/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003544** All of the code that follows is used to build standalone TCL interpreters
3545** that are statically linked with SQLite. Enable these by compiling
3546** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3547** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3548** analysis program.
drh75897232000-05-29 14:26:00 +00003549*/
drh348784e2000-05-29 20:41:49 +00003550
drh57a02272009-10-22 20:52:05 +00003551#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3552/*
3553 * This code implements the MD5 message-digest algorithm.
3554 * The algorithm is due to Ron Rivest. This code was
3555 * written by Colin Plumb in 1993, no copyright is claimed.
3556 * This code is in the public domain; do with it what you wish.
3557 *
3558 * Equivalent code is available from RSA Data Security, Inc.
3559 * This code has been tested against that, and is equivalent,
3560 * except that you don't need to include two pages of legalese
3561 * with every copy.
3562 *
3563 * To compute the message digest of a chunk of bytes, declare an
3564 * MD5Context structure, pass it to MD5Init, call MD5Update as
3565 * needed on buffers full of bytes, and then call MD5Final, which
3566 * will fill a supplied 16-byte array with the digest.
3567 */
3568
3569/*
3570 * If compiled on a machine that doesn't have a 32-bit integer,
3571 * you just set "uint32" to the appropriate datatype for an
3572 * unsigned 32-bit integer. For example:
3573 *
3574 * cc -Duint32='unsigned long' md5.c
3575 *
3576 */
3577#ifndef uint32
3578# define uint32 unsigned int
3579#endif
3580
3581struct MD5Context {
3582 int isInit;
3583 uint32 buf[4];
3584 uint32 bits[2];
3585 unsigned char in[64];
3586};
3587typedef struct MD5Context MD5Context;
3588
3589/*
3590 * Note: this code is harmless on little-endian machines.
3591 */
3592static void byteReverse (unsigned char *buf, unsigned longs){
3593 uint32 t;
3594 do {
3595 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3596 ((unsigned)buf[1]<<8 | buf[0]);
3597 *(uint32 *)buf = t;
3598 buf += 4;
3599 } while (--longs);
3600}
3601/* The four core functions - F1 is optimized somewhat */
3602
3603/* #define F1(x, y, z) (x & y | ~x & z) */
3604#define F1(x, y, z) (z ^ (x & (y ^ z)))
3605#define F2(x, y, z) F1(z, x, y)
3606#define F3(x, y, z) (x ^ y ^ z)
3607#define F4(x, y, z) (y ^ (x | ~z))
3608
3609/* This is the central step in the MD5 algorithm. */
3610#define MD5STEP(f, w, x, y, z, data, s) \
3611 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3612
3613/*
3614 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3615 * reflect the addition of 16 longwords of new data. MD5Update blocks
3616 * the data and converts bytes into longwords for this routine.
3617 */
3618static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3619 register uint32 a, b, c, d;
3620
3621 a = buf[0];
3622 b = buf[1];
3623 c = buf[2];
3624 d = buf[3];
3625
3626 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3627 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3628 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3629 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3630 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3631 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3632 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3633 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3634 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3635 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3636 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3637 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3638 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3639 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3640 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3641 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3642
3643 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3644 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3645 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3646 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3647 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3648 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3649 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3650 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3651 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3652 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3653 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3654 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3655 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3656 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3657 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3658 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3659
3660 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3661 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3662 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3663 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3664 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3665 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3666 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3667 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3668 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3669 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3670 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3671 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3672 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3673 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3674 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3675 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3676
3677 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3678 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3679 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3680 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3681 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3682 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3683 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3684 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3685 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3686 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3687 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3688 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3689 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3690 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3691 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3692 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3693
3694 buf[0] += a;
3695 buf[1] += b;
3696 buf[2] += c;
3697 buf[3] += d;
3698}
3699
3700/*
3701 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3702 * initialization constants.
3703 */
3704static void MD5Init(MD5Context *ctx){
3705 ctx->isInit = 1;
3706 ctx->buf[0] = 0x67452301;
3707 ctx->buf[1] = 0xefcdab89;
3708 ctx->buf[2] = 0x98badcfe;
3709 ctx->buf[3] = 0x10325476;
3710 ctx->bits[0] = 0;
3711 ctx->bits[1] = 0;
3712}
3713
3714/*
3715 * Update context to reflect the concatenation of another buffer full
3716 * of bytes.
3717 */
mistachkinb56660f2016-07-14 21:26:09 +00003718static
drh57a02272009-10-22 20:52:05 +00003719void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3720 uint32 t;
3721
3722 /* Update bitcount */
3723
3724 t = ctx->bits[0];
3725 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3726 ctx->bits[1]++; /* Carry from low to high */
3727 ctx->bits[1] += len >> 29;
3728
3729 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3730
3731 /* Handle any leading odd-sized chunks */
3732
3733 if ( t ) {
3734 unsigned char *p = (unsigned char *)ctx->in + t;
3735
3736 t = 64-t;
3737 if (len < t) {
3738 memcpy(p, buf, len);
3739 return;
3740 }
3741 memcpy(p, buf, t);
3742 byteReverse(ctx->in, 16);
3743 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3744 buf += t;
3745 len -= t;
3746 }
3747
3748 /* Process data in 64-byte chunks */
3749
3750 while (len >= 64) {
3751 memcpy(ctx->in, buf, 64);
3752 byteReverse(ctx->in, 16);
3753 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3754 buf += 64;
3755 len -= 64;
3756 }
3757
3758 /* Handle any remaining bytes of data. */
3759
3760 memcpy(ctx->in, buf, len);
3761}
3762
3763/*
mistachkinb56660f2016-07-14 21:26:09 +00003764 * Final wrapup - pad to 64-byte boundary with the bit pattern
drh57a02272009-10-22 20:52:05 +00003765 * 1 0* (64-bit count of bits processed, MSB-first)
3766 */
3767static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3768 unsigned count;
3769 unsigned char *p;
3770
3771 /* Compute number of bytes mod 64 */
3772 count = (ctx->bits[0] >> 3) & 0x3F;
3773
3774 /* Set the first char of padding to 0x80. This is safe since there is
3775 always at least one byte free */
3776 p = ctx->in + count;
3777 *p++ = 0x80;
3778
3779 /* Bytes of padding needed to make 64 bytes */
3780 count = 64 - 1 - count;
3781
3782 /* Pad out to 56 mod 64 */
3783 if (count < 8) {
3784 /* Two lots of padding: Pad the first block to 64 bytes */
3785 memset(p, 0, count);
3786 byteReverse(ctx->in, 16);
3787 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3788
3789 /* Now fill the next block with 56 bytes */
3790 memset(ctx->in, 0, 56);
3791 } else {
3792 /* Pad block to 56 bytes */
3793 memset(p, 0, count-8);
3794 }
3795 byteReverse(ctx->in, 14);
3796
3797 /* Append length in bits and transform */
drha47941f2013-12-20 18:57:44 +00003798 memcpy(ctx->in + 14*4, ctx->bits, 8);
drh57a02272009-10-22 20:52:05 +00003799
3800 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3801 byteReverse((unsigned char *)ctx->buf, 4);
3802 memcpy(digest, ctx->buf, 16);
drh57a02272009-10-22 20:52:05 +00003803}
3804
3805/*
3806** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3807*/
3808static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3809 static char const zEncode[] = "0123456789abcdef";
3810 int i, j;
3811
3812 for(j=i=0; i<16; i++){
3813 int a = digest[i];
3814 zBuf[j++] = zEncode[(a>>4)&0xf];
3815 zBuf[j++] = zEncode[a & 0xf];
3816 }
3817 zBuf[j] = 0;
3818}
3819
3820
3821/*
3822** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3823** each representing 16 bits of the digest and separated from each
3824** other by a "-" character.
3825*/
3826static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3827 int i, j;
3828 unsigned int x;
3829 for(i=j=0; i<16; i+=2){
3830 x = digest[i]*256 + digest[i+1];
3831 if( i>0 ) zDigest[j++] = '-';
drh05f6c672015-02-26 16:32:33 +00003832 sqlite3_snprintf(50-j, &zDigest[j], "%05u", x);
drh57a02272009-10-22 20:52:05 +00003833 j += 5;
3834 }
3835 zDigest[j] = 0;
3836}
3837
3838/*
3839** A TCL command for md5. The argument is the text to be hashed. The
mistachkinb56660f2016-07-14 21:26:09 +00003840** Result is the hash in base64.
drh57a02272009-10-22 20:52:05 +00003841*/
mistachkin44e95d42016-07-28 22:23:26 +00003842static int SQLITE_TCLAPI md5_cmd(
3843 void*cd,
3844 Tcl_Interp *interp,
3845 int argc,
3846 const char **argv
3847){
drh57a02272009-10-22 20:52:05 +00003848 MD5Context ctx;
3849 unsigned char digest[16];
3850 char zBuf[50];
3851 void (*converter)(unsigned char*, char*);
3852
3853 if( argc!=2 ){
mistachkinb56660f2016-07-14 21:26:09 +00003854 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
drha198f2b2014-02-07 19:26:13 +00003855 " TEXT\"", (char*)0);
drh57a02272009-10-22 20:52:05 +00003856 return TCL_ERROR;
3857 }
3858 MD5Init(&ctx);
3859 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3860 MD5Final(digest, &ctx);
3861 converter = (void(*)(unsigned char*,char*))cd;
3862 converter(digest, zBuf);
3863 Tcl_AppendResult(interp, zBuf, (char*)0);
3864 return TCL_OK;
3865}
3866
3867/*
3868** A TCL command to take the md5 hash of a file. The argument is the
3869** name of the file.
3870*/
mistachkin44e95d42016-07-28 22:23:26 +00003871static int SQLITE_TCLAPI md5file_cmd(
3872 void*cd,
3873 Tcl_Interp *interp,
3874 int argc,
3875 const char **argv
3876){
drh57a02272009-10-22 20:52:05 +00003877 FILE *in;
3878 MD5Context ctx;
3879 void (*converter)(unsigned char*, char*);
3880 unsigned char digest[16];
3881 char zBuf[10240];
3882
3883 if( argc!=2 ){
mistachkinb56660f2016-07-14 21:26:09 +00003884 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
drha198f2b2014-02-07 19:26:13 +00003885 " FILENAME\"", (char*)0);
drh57a02272009-10-22 20:52:05 +00003886 return TCL_ERROR;
3887 }
3888 in = fopen(argv[1],"rb");
3889 if( in==0 ){
mistachkinb56660f2016-07-14 21:26:09 +00003890 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
drha198f2b2014-02-07 19:26:13 +00003891 "\" for reading", (char*)0);
drh57a02272009-10-22 20:52:05 +00003892 return TCL_ERROR;
3893 }
3894 MD5Init(&ctx);
3895 for(;;){
3896 int n;
drh83cc1392012-04-19 18:04:28 +00003897 n = (int)fread(zBuf, 1, sizeof(zBuf), in);
drh57a02272009-10-22 20:52:05 +00003898 if( n<=0 ) break;
3899 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3900 }
3901 fclose(in);
3902 MD5Final(digest, &ctx);
3903 converter = (void(*)(unsigned char*,char*))cd;
3904 converter(digest, zBuf);
3905 Tcl_AppendResult(interp, zBuf, (char*)0);
3906 return TCL_OK;
3907}
3908
3909/*
3910** Register the four new TCL commands for generating MD5 checksums
3911** with the TCL interpreter.
3912*/
3913int Md5_Init(Tcl_Interp *interp){
3914 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3915 MD5DigestToBase16, 0);
3916 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3917 MD5DigestToBase10x8, 0);
3918 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3919 MD5DigestToBase16, 0);
3920 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3921 MD5DigestToBase10x8, 0);
3922 return TCL_OK;
3923}
3924#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3925
3926#if defined(SQLITE_TEST)
3927/*
3928** During testing, the special md5sum() aggregate function is available.
3929** inside SQLite. The following routines implement that function.
3930*/
3931static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3932 MD5Context *p;
3933 int i;
3934 if( argc<1 ) return;
3935 p = sqlite3_aggregate_context(context, sizeof(*p));
3936 if( p==0 ) return;
3937 if( !p->isInit ){
3938 MD5Init(p);
3939 }
3940 for(i=0; i<argc; i++){
3941 const char *zData = (char*)sqlite3_value_text(argv[i]);
3942 if( zData ){
drh83cc1392012-04-19 18:04:28 +00003943 MD5Update(p, (unsigned char*)zData, (int)strlen(zData));
drh57a02272009-10-22 20:52:05 +00003944 }
3945 }
3946}
3947static void md5finalize(sqlite3_context *context){
3948 MD5Context *p;
3949 unsigned char digest[16];
3950 char zBuf[33];
3951 p = sqlite3_aggregate_context(context, sizeof(*p));
3952 MD5Final(digest,p);
3953 MD5DigestToBase16(digest, zBuf);
3954 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3955}
mistachkin44e95d42016-07-28 22:23:26 +00003956int Md5_Register(
3957 sqlite3 *db,
3958 char **pzErrMsg,
mistachkin85bd9822016-07-28 22:53:10 +00003959 const sqlite3_api_routines *pThunk
mistachkin44e95d42016-07-28 22:23:26 +00003960){
mistachkinb56660f2016-07-14 21:26:09 +00003961 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
drh57a02272009-10-22 20:52:05 +00003962 md5step, md5finalize);
3963 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3964 return rc;
3965}
3966#endif /* defined(SQLITE_TEST) */
3967
3968
drh348784e2000-05-29 20:41:49 +00003969/*
drh3e27c022004-07-23 00:01:38 +00003970** If the macro TCLSH is one, then put in code this for the
3971** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003972** standard input, or if a file is named on the command line
3973** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003974*/
drh3e27c022004-07-23 00:01:38 +00003975#if TCLSH==1
dan0ae479d2011-09-21 16:43:07 +00003976static const char *tclsh_main_loop(void){
3977 static const char zMainloop[] =
3978 "set line {}\n"
3979 "while {![eof stdin]} {\n"
3980 "if {$line!=\"\"} {\n"
3981 "puts -nonewline \"> \"\n"
3982 "} else {\n"
3983 "puts -nonewline \"% \"\n"
drh348784e2000-05-29 20:41:49 +00003984 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003985 "flush stdout\n"
3986 "append line [gets stdin]\n"
3987 "if {[info complete $line]} {\n"
3988 "if {[catch {uplevel #0 $line} result]} {\n"
3989 "puts stderr \"Error: $result\"\n"
3990 "} elseif {$result!=\"\"} {\n"
3991 "puts $result\n"
3992 "}\n"
3993 "set line {}\n"
3994 "} else {\n"
3995 "append line \\n\n"
3996 "}\n"
drh348784e2000-05-29 20:41:49 +00003997 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003998 ;
3999 return zMainloop;
4000}
drh3e27c022004-07-23 00:01:38 +00004001#endif
drh3a0f13f2010-07-12 16:47:48 +00004002#if TCLSH==2
dan0ae479d2011-09-21 16:43:07 +00004003static const char *tclsh_main_loop(void);
drh3a0f13f2010-07-12 16:47:48 +00004004#endif
drh3e27c022004-07-23 00:01:38 +00004005
danc1a60c52010-06-07 14:28:16 +00004006#ifdef SQLITE_TEST
4007static void init_all(Tcl_Interp *);
mistachkin7617e4a2016-07-28 17:11:20 +00004008static int SQLITE_TCLAPI init_all_cmd(
danc1a60c52010-06-07 14:28:16 +00004009 ClientData cd,
4010 Tcl_Interp *interp,
4011 int objc,
4012 Tcl_Obj *CONST objv[]
4013){
danielk19770a549072009-02-17 16:29:10 +00004014
danc1a60c52010-06-07 14:28:16 +00004015 Tcl_Interp *slave;
4016 if( objc!=2 ){
4017 Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
4018 return TCL_ERROR;
4019 }
4020
4021 slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
4022 if( !slave ){
4023 return TCL_ERROR;
4024 }
4025
4026 init_all(slave);
4027 return TCL_OK;
4028}
danc431fd52011-06-27 16:55:50 +00004029
4030/*
4031** Tclcmd: db_use_legacy_prepare DB BOOLEAN
4032**
4033** The first argument to this command must be a database command created by
4034** [sqlite3]. If the second argument is true, then the handle is configured
4035** to use the sqlite3_prepare_v2() function to prepare statements. If it
4036** is false, sqlite3_prepare().
4037*/
mistachkin7617e4a2016-07-28 17:11:20 +00004038static int SQLITE_TCLAPI db_use_legacy_prepare_cmd(
danc431fd52011-06-27 16:55:50 +00004039 ClientData cd,
4040 Tcl_Interp *interp,
4041 int objc,
4042 Tcl_Obj *CONST objv[]
4043){
4044 Tcl_CmdInfo cmdInfo;
4045 SqliteDb *pDb;
4046 int bPrepare;
4047
4048 if( objc!=3 ){
4049 Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
4050 return TCL_ERROR;
4051 }
4052
4053 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
4054 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
4055 return TCL_ERROR;
4056 }
4057 pDb = (SqliteDb*)cmdInfo.objClientData;
4058 if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
4059 return TCL_ERROR;
4060 }
4061
4062 pDb->bLegacyPrepare = bPrepare;
4063
4064 Tcl_ResetResult(interp);
4065 return TCL_OK;
4066}
dan04489b62014-10-31 20:11:32 +00004067
4068/*
4069** Tclcmd: db_last_stmt_ptr DB
4070**
4071** If the statement cache associated with database DB is not empty,
4072** return the text representation of the most recently used statement
4073** handle.
4074*/
mistachkin7617e4a2016-07-28 17:11:20 +00004075static int SQLITE_TCLAPI db_last_stmt_ptr(
dan04489b62014-10-31 20:11:32 +00004076 ClientData cd,
4077 Tcl_Interp *interp,
4078 int objc,
4079 Tcl_Obj *CONST objv[]
4080){
4081 extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
4082 Tcl_CmdInfo cmdInfo;
4083 SqliteDb *pDb;
4084 sqlite3_stmt *pStmt = 0;
4085 char zBuf[100];
4086
4087 if( objc!=2 ){
4088 Tcl_WrongNumArgs(interp, 1, objv, "DB");
4089 return TCL_ERROR;
4090 }
4091
4092 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
4093 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
4094 return TCL_ERROR;
4095 }
4096 pDb = (SqliteDb*)cmdInfo.objClientData;
4097
4098 if( pDb->stmtList ) pStmt = pDb->stmtList->pStmt;
4099 if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ){
4100 return TCL_ERROR;
4101 }
4102 Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
4103
4104 return TCL_OK;
4105}
drh1a4a6802015-05-04 18:31:09 +00004106#endif /* SQLITE_TEST */
4107
danc1a60c52010-06-07 14:28:16 +00004108/*
4109** Configure the interpreter passed as the first argument to have access
4110** to the commands and linked variables that make up:
4111**
mistachkinb56660f2016-07-14 21:26:09 +00004112** * the [sqlite3] extension itself,
danc1a60c52010-06-07 14:28:16 +00004113**
4114** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
4115**
4116** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
4117** test suite.
4118*/
4119static void init_all(Tcl_Interp *interp){
drh38f82712004-06-18 17:10:16 +00004120 Sqlite3_Init(interp);
danc1a60c52010-06-07 14:28:16 +00004121
drh57a02272009-10-22 20:52:05 +00004122#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
4123 Md5_Init(interp);
4124#endif
danc1a60c52010-06-07 14:28:16 +00004125
drhd9b02572001-04-15 00:37:09 +00004126#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00004127 {
drh2f999a62007-08-15 19:16:43 +00004128 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00004129 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00004130 extern int Sqlitetest2_Init(Tcl_Interp*);
4131 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00004132 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00004133 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00004134 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00004135 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00004136 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00004137 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00004138 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00004139 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
danb391b942014-11-07 14:41:11 +00004140 extern int Sqlitetest_blob_Init(Tcl_Interp*);
dan0a7a9152010-04-07 07:57:38 +00004141 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
drh984bfaa2008-03-19 16:08:53 +00004142 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00004143 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00004144 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00004145 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00004146 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00004147 extern int Sqlitetestschema_Init(Tcl_Interp*);
4148 extern int Sqlitetestsse_Init(Tcl_Interp*);
4149 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
dan9f5ff372013-01-11 09:58:54 +00004150 extern int Sqlitetestfs_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00004151 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00004152 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00004153 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00004154 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh522efc62009-11-10 17:24:37 +00004155 extern int Sqlitetestintarray_Init(Tcl_Interp*);
danc7991bd2010-05-05 19:04:59 +00004156 extern int Sqlitetestvfs_Init(Tcl_Interp *);
dan9508daa2010-08-28 18:58:00 +00004157 extern int Sqlitetestrtree_Init(Tcl_Interp*);
dan8cf35eb2010-09-01 11:40:05 +00004158 extern int Sqlitequota_Init(Tcl_Interp*);
shaneh8a922f72010-11-04 20:50:27 +00004159 extern int Sqlitemultiplex_Init(Tcl_Interp*);
dane336b002010-11-19 18:20:09 +00004160 extern int SqliteSuperlock_Init(Tcl_Interp*);
dan213ca0a2011-03-28 19:10:06 +00004161 extern int SqlitetestSyscall_Init(Tcl_Interp*);
drh9b1c62d2011-03-30 21:04:43 +00004162#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
dan4fccf432011-03-08 19:22:50 +00004163 extern int TestSession_Init(Tcl_Interp*);
4164#endif
dan89a89562014-12-01 20:05:00 +00004165 extern int Fts5tcl_Init(Tcl_Interp *);
drhcfb8f8d2015-07-23 20:44:49 +00004166 extern int SqliteRbu_Init(Tcl_Interp*);
dan8e4251b2016-03-01 18:07:43 +00004167 extern int Sqlitetesttcl_Init(Tcl_Interp*);
dan6764a702011-06-20 11:15:06 +00004168#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00004169 extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
4170#endif
4171
danb29010c2010-12-29 18:24:38 +00004172#ifdef SQLITE_ENABLE_ZIPVFS
4173 extern int Zipvfs_Init(Tcl_Interp*);
4174 Zipvfs_Init(interp);
4175#endif
4176
drh2f999a62007-08-15 19:16:43 +00004177 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00004178 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00004179 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00004180 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00004181 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00004182 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00004183 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00004184 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00004185 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00004186 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00004187 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00004188 Sqlitetest_autoext_Init(interp);
danb391b942014-11-07 14:41:11 +00004189 Sqlitetest_blob_Init(interp);
dan0a7a9152010-04-07 07:57:38 +00004190 Sqlitetest_demovfs_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00004191 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00004192 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00004193 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00004194 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00004195 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00004196 Sqlitetestschema_Init(interp);
4197 Sqlitetesttclvar_Init(interp);
dan9f5ff372013-01-11 09:58:54 +00004198 Sqlitetestfs_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00004199 SqlitetestThread_Init(interp);
mistachkin52b1dbb2016-07-28 14:37:04 +00004200 SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00004201 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00004202 Sqlitetestbackup_Init(interp);
drh522efc62009-11-10 17:24:37 +00004203 Sqlitetestintarray_Init(interp);
danc7991bd2010-05-05 19:04:59 +00004204 Sqlitetestvfs_Init(interp);
dan9508daa2010-08-28 18:58:00 +00004205 Sqlitetestrtree_Init(interp);
dan8cf35eb2010-09-01 11:40:05 +00004206 Sqlitequota_Init(interp);
shaneh8a922f72010-11-04 20:50:27 +00004207 Sqlitemultiplex_Init(interp);
dane336b002010-11-19 18:20:09 +00004208 SqliteSuperlock_Init(interp);
dan213ca0a2011-03-28 19:10:06 +00004209 SqlitetestSyscall_Init(interp);
drh9b1c62d2011-03-30 21:04:43 +00004210#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
dan4fccf432011-03-08 19:22:50 +00004211 TestSession_Init(interp);
4212#endif
dan89a89562014-12-01 20:05:00 +00004213 Fts5tcl_Init(interp);
drhcfb8f8d2015-07-23 20:44:49 +00004214 SqliteRbu_Init(interp);
dan8e4251b2016-03-01 18:07:43 +00004215 Sqlitetesttcl_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00004216
dan6764a702011-06-20 11:15:06 +00004217#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00004218 Sqlitetestfts3_Init(interp);
4219#endif
drh2e66f0b2005-04-28 17:18:48 +00004220
danc431fd52011-06-27 16:55:50 +00004221 Tcl_CreateObjCommand(
4222 interp, "load_testfixture_extensions", init_all_cmd, 0, 0
4223 );
4224 Tcl_CreateObjCommand(
4225 interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
4226 );
dan04489b62014-10-31 20:11:32 +00004227 Tcl_CreateObjCommand(
4228 interp, "db_last_stmt_ptr", db_last_stmt_ptr, 0, 0
4229 );
danc1a60c52010-06-07 14:28:16 +00004230
drh3e27c022004-07-23 00:01:38 +00004231#ifdef SQLITE_SSE
drh348784e2000-05-29 20:41:49 +00004232 Sqlitetestsse_Init(interp);
4233#endif
4234 }
drh61212b62004-12-02 20:17:00 +00004235#endif
danc1a60c52010-06-07 14:28:16 +00004236}
4237
drhdb6bafa2015-01-09 21:54:58 +00004238/* Needed for the setrlimit() system call on unix */
4239#if defined(unix)
4240#include <sys/resource.h>
4241#endif
4242
danc1a60c52010-06-07 14:28:16 +00004243#define TCLSH_MAIN main /* Needed to fake out mktclapp */
mistachkin69def7f2016-07-28 04:14:37 +00004244int SQLITE_CDECL TCLSH_MAIN(int argc, char **argv){
danc1a60c52010-06-07 14:28:16 +00004245 Tcl_Interp *interp;
mistachkin1f28e072013-08-15 08:06:15 +00004246
4247#if !defined(_WIN32_WCE)
4248 if( getenv("BREAK") ){
4249 fprintf(stderr,
4250 "attach debugger to process %d and press any key to continue.\n",
4251 GETPID());
4252 fgetc(stdin);
4253 }
4254#endif
4255
drhdb6bafa2015-01-09 21:54:58 +00004256 /* Since the primary use case for this binary is testing of SQLite,
4257 ** be sure to generate core files if we crash */
4258#if defined(SQLITE_TEST) && defined(unix)
4259 { struct rlimit x;
4260 getrlimit(RLIMIT_CORE, &x);
4261 x.rlim_cur = x.rlim_max;
4262 setrlimit(RLIMIT_CORE, &x);
4263 }
4264#endif /* SQLITE_TEST && unix */
4265
4266
danc1a60c52010-06-07 14:28:16 +00004267 /* Call sqlite3_shutdown() once before doing anything else. This is to
4268 ** test that sqlite3_shutdown() can be safely called by a process before
4269 ** sqlite3_initialize() is. */
4270 sqlite3_shutdown();
4271
dan0ae479d2011-09-21 16:43:07 +00004272 Tcl_FindExecutable(argv[0]);
mistachkin2953ba92014-02-14 00:25:03 +00004273 Tcl_SetSystemEncoding(NULL, "utf-8");
dan0ae479d2011-09-21 16:43:07 +00004274 interp = Tcl_CreateInterp();
4275
drh3a0f13f2010-07-12 16:47:48 +00004276#if TCLSH==2
4277 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
4278#endif
danc1a60c52010-06-07 14:28:16 +00004279
danc1a60c52010-06-07 14:28:16 +00004280 init_all(interp);
drhc7285972009-11-10 01:13:25 +00004281 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00004282 int i;
shessad42c3a2006-08-22 23:53:46 +00004283 char zArgc[32];
4284 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
4285 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00004286 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
4287 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
4288 for(i=3-TCLSH; i<argc; i++){
4289 Tcl_SetVar(interp, "argv", argv[i],
4290 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
4291 }
drh3a0f13f2010-07-12 16:47:48 +00004292 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00004293 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00004294 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00004295 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00004296 return 1;
4297 }
drh3e27c022004-07-23 00:01:38 +00004298 }
drh3a0f13f2010-07-12 16:47:48 +00004299 if( TCLSH==2 || argc<=1 ){
dan0ae479d2011-09-21 16:43:07 +00004300 Tcl_GlobalEval(interp, tclsh_main_loop());
drh348784e2000-05-29 20:41:49 +00004301 }
4302 return 0;
4303}
4304#endif /* TCLSH */