blob: 9fe2316bfc53d1f001dedb00224c482b4f6aeb72 [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 */
danielk1977cd38d522009-01-02 17:33:46 +0000164 int nTransaction; /* Number of nested [transaction] methods */
drh147ef392016-01-22 23:17:51 +0000165 int openFlags; /* Flags used to open. (SQLITE_OPEN_URI) */
danc431fd52011-06-27 16:55:50 +0000166#ifdef SQLITE_TEST
167 int bLegacyPrepare; /* True to use sqlite3_prepare() */
168#endif
drh98808ba2001-10-18 12:34:46 +0000169};
drh297ecf12001-04-05 15:57:13 +0000170
danielk1977b4e9af92007-05-01 17:49:49 +0000171struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000172 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000173 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000174 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000175 Tcl_Channel channel; /* Channel identifier */
176 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
177 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000178};
179
drhea678832008-12-10 19:26:22 +0000180/*
181** Compute a string length that is limited to what can be stored in
182** lower 30 bits of a 32-bit signed integer.
183*/
drh4f21c4a2008-12-10 22:15:00 +0000184static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000185 const char *z2 = z;
186 while( *z2 ){ z2++; }
187 return 0x3fffffff & (int)(z2 - z);
188}
drhea678832008-12-10 19:26:22 +0000189
190
danielk197732a0d8b2007-05-04 19:03:02 +0000191#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000192/*
danielk1977d04417962007-05-02 13:16:30 +0000193** Close all incrblob channels opened using database connection pDb.
194** This is called when shutting down the database connection.
195*/
196static void closeIncrblobChannels(SqliteDb *pDb){
197 IncrblobChannel *p;
198 IncrblobChannel *pNext;
199
200 for(p=pDb->pIncrblob; p; p=pNext){
201 pNext = p->pNext;
202
mistachkinb56660f2016-07-14 21:26:09 +0000203 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
danielk1977d04417962007-05-02 13:16:30 +0000204 ** which deletes the IncrblobChannel structure at *p. So do not
205 ** call Tcl_Free() here.
206 */
207 Tcl_UnregisterChannel(pDb->interp, p->channel);
208 }
209}
210
211/*
danielk1977b4e9af92007-05-01 17:49:49 +0000212** Close an incremental blob channel.
213*/
mistachkin7617e4a2016-07-28 17:11:20 +0000214static int SQLITE_TCLAPI incrblobClose(
215 ClientData instanceData,
216 Tcl_Interp *interp
217){
danielk1977b4e9af92007-05-01 17:49:49 +0000218 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000219 int rc = sqlite3_blob_close(p->pBlob);
220 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000221
222 /* Remove the channel from the SqliteDb.pIncrblob list. */
223 if( p->pNext ){
224 p->pNext->pPrev = p->pPrev;
225 }
226 if( p->pPrev ){
227 p->pPrev->pNext = p->pNext;
228 }
229 if( p->pDb->pIncrblob==p ){
230 p->pDb->pIncrblob = p->pNext;
231 }
232
danielk197792d4d7a2007-05-04 12:05:56 +0000233 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000234 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000235
236 if( rc!=SQLITE_OK ){
237 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
238 return TCL_ERROR;
239 }
danielk1977b4e9af92007-05-01 17:49:49 +0000240 return TCL_OK;
241}
242
243/*
244** Read data from an incremental blob channel.
245*/
mistachkin7617e4a2016-07-28 17:11:20 +0000246static int SQLITE_TCLAPI incrblobInput(
mistachkinb56660f2016-07-14 21:26:09 +0000247 ClientData instanceData,
248 char *buf,
danielk1977b4e9af92007-05-01 17:49:49 +0000249 int bufSize,
250 int *errorCodePtr
251){
252 IncrblobChannel *p = (IncrblobChannel *)instanceData;
253 int nRead = bufSize; /* Number of bytes to read */
254 int nBlob; /* Total size of the blob */
255 int rc; /* sqlite error code */
256
257 nBlob = sqlite3_blob_bytes(p->pBlob);
258 if( (p->iSeek+nRead)>nBlob ){
259 nRead = nBlob-p->iSeek;
260 }
261 if( nRead<=0 ){
262 return 0;
263 }
264
265 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
266 if( rc!=SQLITE_OK ){
267 *errorCodePtr = rc;
268 return -1;
269 }
270
271 p->iSeek += nRead;
272 return nRead;
273}
274
danielk1977d04417962007-05-02 13:16:30 +0000275/*
276** Write data to an incremental blob channel.
277*/
mistachkin7617e4a2016-07-28 17:11:20 +0000278static int SQLITE_TCLAPI incrblobOutput(
mistachkinb56660f2016-07-14 21:26:09 +0000279 ClientData instanceData,
280 CONST char *buf,
danielk1977b4e9af92007-05-01 17:49:49 +0000281 int toWrite,
282 int *errorCodePtr
283){
284 IncrblobChannel *p = (IncrblobChannel *)instanceData;
285 int nWrite = toWrite; /* Number of bytes to write */
286 int nBlob; /* Total size of the blob */
287 int rc; /* sqlite error code */
288
289 nBlob = sqlite3_blob_bytes(p->pBlob);
290 if( (p->iSeek+nWrite)>nBlob ){
291 *errorCodePtr = EINVAL;
292 return -1;
293 }
294 if( nWrite<=0 ){
295 return 0;
296 }
297
298 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
299 if( rc!=SQLITE_OK ){
300 *errorCodePtr = EIO;
301 return -1;
302 }
303
304 p->iSeek += nWrite;
305 return nWrite;
306}
307
308/*
309** Seek an incremental blob channel.
310*/
mistachkin7617e4a2016-07-28 17:11:20 +0000311static int SQLITE_TCLAPI incrblobSeek(
mistachkinb56660f2016-07-14 21:26:09 +0000312 ClientData instanceData,
danielk1977b4e9af92007-05-01 17:49:49 +0000313 long offset,
314 int seekMode,
315 int *errorCodePtr
316){
317 IncrblobChannel *p = (IncrblobChannel *)instanceData;
318
319 switch( seekMode ){
320 case SEEK_SET:
321 p->iSeek = offset;
322 break;
323 case SEEK_CUR:
324 p->iSeek += offset;
325 break;
326 case SEEK_END:
327 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
328 break;
329
330 default: assert(!"Bad seekMode");
331 }
332
333 return p->iSeek;
334}
335
336
mistachkin7617e4a2016-07-28 17:11:20 +0000337static void SQLITE_TCLAPI incrblobWatch(
338 ClientData instanceData,
339 int mode
340){
mistachkinb56660f2016-07-14 21:26:09 +0000341 /* NO-OP */
danielk1977b4e9af92007-05-01 17:49:49 +0000342}
mistachkin7617e4a2016-07-28 17:11:20 +0000343static int SQLITE_TCLAPI incrblobHandle(
344 ClientData instanceData,
345 int dir,
346 ClientData *hPtr
347){
danielk1977b4e9af92007-05-01 17:49:49 +0000348 return TCL_ERROR;
349}
350
351static Tcl_ChannelType IncrblobChannelType = {
352 "incrblob", /* typeName */
353 TCL_CHANNEL_VERSION_2, /* version */
354 incrblobClose, /* closeProc */
355 incrblobInput, /* inputProc */
356 incrblobOutput, /* outputProc */
357 incrblobSeek, /* seekProc */
358 0, /* setOptionProc */
359 0, /* getOptionProc */
360 incrblobWatch, /* watchProc (this is a no-op) */
361 incrblobHandle, /* getHandleProc (always returns error) */
362 0, /* close2Proc */
363 0, /* blockModeProc */
364 0, /* flushProc */
365 0, /* handlerProc */
366 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000367};
368
369/*
370** Create a new incrblob channel.
371*/
372static int createIncrblobChannel(
mistachkinb56660f2016-07-14 21:26:09 +0000373 Tcl_Interp *interp,
374 SqliteDb *pDb,
danielk1977b4e9af92007-05-01 17:49:49 +0000375 const char *zDb,
mistachkinb56660f2016-07-14 21:26:09 +0000376 const char *zTable,
377 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000378 sqlite_int64 iRow,
379 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000380){
381 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000382 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000383 sqlite3_blob *pBlob;
384 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000385 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000386
387 /* This variable is used to name the channels: "incrblob_[incr count]" */
388 static int count = 0;
389 char zChannel[64];
390
danielk19778cbadb02007-05-03 16:31:26 +0000391 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000392 if( rc!=SQLITE_OK ){
393 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
394 return TCL_ERROR;
395 }
396
397 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
398 p->iSeek = 0;
399 p->pBlob = pBlob;
400
drh5bb3eb92007-05-04 13:15:55 +0000401 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000402 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
403 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000404
danielk1977d04417962007-05-02 13:16:30 +0000405 /* Link the new channel into the SqliteDb.pIncrblob list. */
406 p->pNext = pDb->pIncrblob;
407 p->pPrev = 0;
408 if( p->pNext ){
409 p->pNext->pPrev = p;
410 }
411 pDb->pIncrblob = p;
412 p->pDb = pDb;
413
414 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000415 return TCL_OK;
416}
danielk197732a0d8b2007-05-04 19:03:02 +0000417#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
418 #define closeIncrblobChannels(pDb)
419#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000420
drh6d313162000-09-21 13:01:35 +0000421/*
drhd1e47332005-06-26 17:55:33 +0000422** Look at the script prefix in pCmd. We will be executing this script
423** after first appending one or more arguments. This routine analyzes
424** the script to see if it is safe to use Tcl_EvalObjv() on the script
425** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
426** faster.
427**
428** Scripts that are safe to use with Tcl_EvalObjv() consists of a
429** command name followed by zero or more arguments with no [...] or $
430** or {...} or ; to be seen anywhere. Most callback scripts consist
431** of just a single procedure name and they meet this requirement.
432*/
433static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
434 /* We could try to do something with Tcl_Parse(). But we will instead
435 ** just do a search for forbidden characters. If any of the forbidden
436 ** characters appear in pCmd, we will report the string as unsafe.
437 */
438 const char *z;
439 int n;
440 z = Tcl_GetStringFromObj(pCmd, &n);
441 while( n-- > 0 ){
442 int c = *(z++);
443 if( c=='$' || c=='[' || c==';' ) return 0;
444 }
445 return 1;
446}
447
448/*
449** Find an SqlFunc structure with the given name. Or create a new
450** one if an existing one cannot be found. Return a pointer to the
451** structure.
452*/
453static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
454 SqlFunc *p, *pNew;
drh0425f182013-11-26 16:48:04 +0000455 int nName = strlen30(zName);
456 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
drhd1e47332005-06-26 17:55:33 +0000457 pNew->zName = (char*)&pNew[1];
drh0425f182013-11-26 16:48:04 +0000458 memcpy(pNew->zName, zName, nName+1);
mistachkinb56660f2016-07-14 21:26:09 +0000459 for(p=pDb->pFunc; p; p=p->pNext){
drh0425f182013-11-26 16:48:04 +0000460 if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
drhd1e47332005-06-26 17:55:33 +0000461 Tcl_Free((char*)pNew);
462 return p;
463 }
464 }
465 pNew->interp = pDb->interp;
drhc45e6712012-10-03 11:02:33 +0000466 pNew->pDb = pDb;
drhd1e47332005-06-26 17:55:33 +0000467 pNew->pScript = 0;
468 pNew->pNext = pDb->pFunc;
469 pDb->pFunc = pNew;
470 return pNew;
471}
472
473/*
danc431fd52011-06-27 16:55:50 +0000474** Free a single SqlPreparedStmt object.
475*/
476static void dbFreeStmt(SqlPreparedStmt *pStmt){
477#ifdef SQLITE_TEST
478 if( sqlite3_sql(pStmt->pStmt)==0 ){
479 Tcl_Free((char *)pStmt->zSql);
480 }
481#endif
482 sqlite3_finalize(pStmt->pStmt);
483 Tcl_Free((char *)pStmt);
484}
485
486/*
drhfb7e7652005-01-24 00:28:42 +0000487** Finalize and free a list of prepared statements
488*/
danc431fd52011-06-27 16:55:50 +0000489static void flushStmtCache(SqliteDb *pDb){
drhfb7e7652005-01-24 00:28:42 +0000490 SqlPreparedStmt *pPreStmt;
danc431fd52011-06-27 16:55:50 +0000491 SqlPreparedStmt *pNext;
drhfb7e7652005-01-24 00:28:42 +0000492
danc431fd52011-06-27 16:55:50 +0000493 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
494 pNext = pPreStmt->pNext;
495 dbFreeStmt(pPreStmt);
drhfb7e7652005-01-24 00:28:42 +0000496 }
497 pDb->nStmt = 0;
498 pDb->stmtLast = 0;
danc431fd52011-06-27 16:55:50 +0000499 pDb->stmtList = 0;
drhfb7e7652005-01-24 00:28:42 +0000500}
501
502/*
drh895d7472004-08-20 16:02:39 +0000503** TCL calls this procedure when an sqlite3 database command is
504** deleted.
drh75897232000-05-29 14:26:00 +0000505*/
mistachkin7617e4a2016-07-28 17:11:20 +0000506static void SQLITE_TCLAPI DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000507 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000508 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000509 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000510 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000511 while( pDb->pFunc ){
512 SqlFunc *pFunc = pDb->pFunc;
513 pDb->pFunc = pFunc->pNext;
drhc45e6712012-10-03 11:02:33 +0000514 assert( pFunc->pDb==pDb );
drhd1e47332005-06-26 17:55:33 +0000515 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000516 Tcl_Free((char*)pFunc);
517 }
danielk19770202b292004-06-09 09:55:16 +0000518 while( pDb->pCollate ){
519 SqlCollate *pCollate = pDb->pCollate;
520 pDb->pCollate = pCollate->pNext;
521 Tcl_Free((char*)pCollate);
522 }
drhbec3f402000-08-04 13:49:02 +0000523 if( pDb->zBusy ){
524 Tcl_Free(pDb->zBusy);
525 }
drhb5a20d32003-04-23 12:25:23 +0000526 if( pDb->zTrace ){
527 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000528 }
mistachkinb56660f2016-07-14 21:26:09 +0000529 if( pDb->zTraceV2 ){
530 Tcl_Free(pDb->zTraceV2);
531 }
drh19e2d372005-08-29 23:00:03 +0000532 if( pDb->zProfile ){
533 Tcl_Free(pDb->zProfile);
534 }
drhe22a3342003-04-22 20:30:37 +0000535 if( pDb->zAuth ){
536 Tcl_Free(pDb->zAuth);
537 }
danielk197755c45f22005-04-03 23:54:43 +0000538 if( pDb->zNull ){
539 Tcl_Free(pDb->zNull);
540 }
danielk197794eb6a12005-12-15 15:22:08 +0000541 if( pDb->pUpdateHook ){
542 Tcl_DecrRefCount(pDb->pUpdateHook);
543 }
dan46c47d42011-03-01 18:42:07 +0000544 if( pDb->pPreUpdateHook ){
545 Tcl_DecrRefCount(pDb->pPreUpdateHook);
546 }
danielk197771fd80b2005-12-16 06:54:01 +0000547 if( pDb->pRollbackHook ){
548 Tcl_DecrRefCount(pDb->pRollbackHook);
549 }
drh5def0842010-05-05 20:00:25 +0000550 if( pDb->pWalHook ){
551 Tcl_DecrRefCount(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000552 }
danielk197794eb6a12005-12-15 15:22:08 +0000553 if( pDb->pCollateNeeded ){
554 Tcl_DecrRefCount(pDb->pCollateNeeded);
555 }
drhbec3f402000-08-04 13:49:02 +0000556 Tcl_Free((char*)pDb);
557}
558
559/*
560** This routine is called when a database file is locked while trying
561** to execute SQL.
562*/
danielk19772a764eb2004-06-12 01:43:26 +0000563static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000564 SqliteDb *pDb = (SqliteDb*)cd;
565 int rc;
566 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000567
drh5bb3eb92007-05-04 13:15:55 +0000568 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000569 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000570 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
571 return 0;
572 }
573 return 1;
drh75897232000-05-29 14:26:00 +0000574}
575
drh26e4a8b2008-05-01 17:16:52 +0000576#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000577/*
danielk1977348bb5d2003-10-18 09:37:26 +0000578** This routine is invoked as the 'progress callback' for the database.
579*/
580static int DbProgressHandler(void *cd){
581 SqliteDb *pDb = (SqliteDb*)cd;
582 int rc;
583
584 assert( pDb->zProgress );
585 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
586 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
587 return 1;
588 }
589 return 0;
590}
drh26e4a8b2008-05-01 17:16:52 +0000591#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000592
drh2eb22af2016-09-10 19:51:40 +0000593#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
594 !defined(SQLITE_OMIT_DEPRECATED)
danielk1977348bb5d2003-10-18 09:37:26 +0000595/*
drhb5a20d32003-04-23 12:25:23 +0000596** This routine is called by the SQLite trace handler whenever a new
597** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000598*/
drhb5a20d32003-04-23 12:25:23 +0000599static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000600 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000601 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000602
drhb5a20d32003-04-23 12:25:23 +0000603 Tcl_DStringInit(&str);
604 Tcl_DStringAppend(&str, pDb->zTrace, -1);
605 Tcl_DStringAppendElement(&str, zSql);
606 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
607 Tcl_DStringFree(&str);
608 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000609}
drhd1167392006-01-23 13:00:35 +0000610#endif
drh0d1a6432003-04-03 15:46:04 +0000611
drhd1167392006-01-23 13:00:35 +0000612#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000613/*
mistachkinb56660f2016-07-14 21:26:09 +0000614** This routine is called by the SQLite trace_v2 handler whenever a new
615** supported event is generated. Unsupported event types are ignored.
616** The TCL script in pDb->zTraceV2 is executed, with the arguments for
617** the event appended to it (as list elements).
618*/
619static int DbTraceV2Handler(
620 unsigned type, /* One of the SQLITE_TRACE_* event types. */
621 void *cd, /* The original context data pointer. */
622 void *pd, /* Primary event data, depends on event type. */
623 void *xd /* Extra event data, depends on event type. */
624){
625 SqliteDb *pDb = (SqliteDb*)cd;
626 Tcl_Obj *pCmd;
627
628 switch( type ){
629 case SQLITE_TRACE_STMT: {
630 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
631 char *zSql = (char *)xd;
632
633 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
634 Tcl_IncrRefCount(pCmd);
635 Tcl_ListObjAppendElement(pDb->interp, pCmd,
636 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
637 Tcl_ListObjAppendElement(pDb->interp, pCmd,
638 Tcl_NewStringObj(zSql, -1));
639 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
640 Tcl_DecrRefCount(pCmd);
641 Tcl_ResetResult(pDb->interp);
642 break;
643 }
644 case SQLITE_TRACE_PROFILE: {
645 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
646 sqlite3_int64 ns = (sqlite3_int64)xd;
647
648 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
649 Tcl_IncrRefCount(pCmd);
650 Tcl_ListObjAppendElement(pDb->interp, pCmd,
651 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
652 Tcl_ListObjAppendElement(pDb->interp, pCmd,
653 Tcl_NewWideIntObj((Tcl_WideInt)ns));
654 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
655 Tcl_DecrRefCount(pCmd);
656 Tcl_ResetResult(pDb->interp);
657 break;
658 }
659 case SQLITE_TRACE_ROW: {
660 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
661
662 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
663 Tcl_IncrRefCount(pCmd);
664 Tcl_ListObjAppendElement(pDb->interp, pCmd,
665 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
666 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
667 Tcl_DecrRefCount(pCmd);
668 Tcl_ResetResult(pDb->interp);
669 break;
670 }
671 case SQLITE_TRACE_CLOSE: {
672 sqlite3 *db = (sqlite3 *)pd;
673
674 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
675 Tcl_IncrRefCount(pCmd);
676 Tcl_ListObjAppendElement(pDb->interp, pCmd,
677 Tcl_NewWideIntObj((Tcl_WideInt)db));
678 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
679 Tcl_DecrRefCount(pCmd);
680 Tcl_ResetResult(pDb->interp);
681 break;
682 }
683 }
684 return SQLITE_OK;
685}
686#endif
687
drh2eb22af2016-09-10 19:51:40 +0000688#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
689 !defined(SQLITE_OMIT_DEPRECATED)
mistachkinb56660f2016-07-14 21:26:09 +0000690/*
drh19e2d372005-08-29 23:00:03 +0000691** This routine is called by the SQLite profile handler after a statement
692** SQL has executed. The TCL script in pDb->zProfile is evaluated.
693*/
694static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
695 SqliteDb *pDb = (SqliteDb*)cd;
696 Tcl_DString str;
697 char zTm[100];
698
699 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
700 Tcl_DStringInit(&str);
701 Tcl_DStringAppend(&str, pDb->zProfile, -1);
702 Tcl_DStringAppendElement(&str, zSql);
703 Tcl_DStringAppendElement(&str, zTm);
704 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
705 Tcl_DStringFree(&str);
706 Tcl_ResetResult(pDb->interp);
707}
drhd1167392006-01-23 13:00:35 +0000708#endif
drh19e2d372005-08-29 23:00:03 +0000709
710/*
drhaa940ea2004-01-15 02:44:03 +0000711** This routine is called when a transaction is committed. The
712** TCL script in pDb->zCommit is executed. If it returns non-zero or
713** if it throws an exception, the transaction is rolled back instead
714** of being committed.
715*/
716static int DbCommitHandler(void *cd){
717 SqliteDb *pDb = (SqliteDb*)cd;
718 int rc;
719
720 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
721 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
722 return 1;
723 }
724 return 0;
725}
726
danielk197771fd80b2005-12-16 06:54:01 +0000727static void DbRollbackHandler(void *clientData){
728 SqliteDb *pDb = (SqliteDb*)clientData;
729 assert(pDb->pRollbackHook);
730 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
731 Tcl_BackgroundError(pDb->interp);
732 }
733}
734
drh5def0842010-05-05 20:00:25 +0000735/*
736** This procedure handles wal_hook callbacks.
737*/
738static int DbWalHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000739 void *clientData,
740 sqlite3 *db,
741 const char *zDb,
dan8d22a172010-04-19 18:03:51 +0000742 int nEntry
743){
drh5def0842010-05-05 20:00:25 +0000744 int ret = SQLITE_OK;
dan8d22a172010-04-19 18:03:51 +0000745 Tcl_Obj *p;
746 SqliteDb *pDb = (SqliteDb*)clientData;
747 Tcl_Interp *interp = pDb->interp;
drh5def0842010-05-05 20:00:25 +0000748 assert(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000749
dan6e45e0c2014-12-10 20:29:49 +0000750 assert( db==pDb->db );
drh5def0842010-05-05 20:00:25 +0000751 p = Tcl_DuplicateObj(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000752 Tcl_IncrRefCount(p);
753 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
754 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
mistachkinb56660f2016-07-14 21:26:09 +0000755 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
dan8d22a172010-04-19 18:03:51 +0000756 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
757 ){
758 Tcl_BackgroundError(interp);
759 }
760 Tcl_DecrRefCount(p);
761
762 return ret;
763}
764
drhbcf4f482009-03-27 12:44:35 +0000765#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000766static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
767 char zBuf[64];
drh65545b52015-01-19 00:35:53 +0000768 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
danielk1977404ca072009-03-16 13:19:36 +0000769 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
drh65545b52015-01-19 00:35:53 +0000770 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
danielk1977404ca072009-03-16 13:19:36 +0000771 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
772}
773#else
drhbcf4f482009-03-27 12:44:35 +0000774# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000775#endif
776
drh69910da2009-03-27 12:32:54 +0000777#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000778static void DbUnlockNotify(void **apArg, int nArg){
779 int i;
780 for(i=0; i<nArg; i++){
781 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
782 SqliteDb *pDb = (SqliteDb *)apArg[i];
783 setTestUnlockNotifyVars(pDb->interp, i, nArg);
784 assert( pDb->pUnlockNotify);
785 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
786 Tcl_DecrRefCount(pDb->pUnlockNotify);
787 pDb->pUnlockNotify = 0;
788 }
789}
drh69910da2009-03-27 12:32:54 +0000790#endif
danielk1977404ca072009-03-16 13:19:36 +0000791
drh9b1c62d2011-03-30 21:04:43 +0000792#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +0000793/*
794** Pre-update hook callback.
795*/
796static void DbPreUpdateHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000797 void *p,
dan46c47d42011-03-01 18:42:07 +0000798 sqlite3 *db,
799 int op,
mistachkinb56660f2016-07-14 21:26:09 +0000800 const char *zDb,
801 const char *zTbl,
dan46c47d42011-03-01 18:42:07 +0000802 sqlite_int64 iKey1,
803 sqlite_int64 iKey2
804){
805 SqliteDb *pDb = (SqliteDb *)p;
806 Tcl_Obj *pCmd;
807 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
808
809 assert( (SQLITE_DELETE-1)/9 == 0 );
810 assert( (SQLITE_INSERT-1)/9 == 1 );
811 assert( (SQLITE_UPDATE-1)/9 == 2 );
812 assert( pDb->pPreUpdateHook );
813 assert( db==pDb->db );
814 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
815
816 pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
817 Tcl_IncrRefCount(pCmd);
818 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
819 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
820 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
821 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
822 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
823 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
824 Tcl_DecrRefCount(pCmd);
825}
drh9b1c62d2011-03-30 21:04:43 +0000826#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +0000827
danielk197794eb6a12005-12-15 15:22:08 +0000828static void DbUpdateHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000829 void *p,
danielk197794eb6a12005-12-15 15:22:08 +0000830 int op,
mistachkinb56660f2016-07-14 21:26:09 +0000831 const char *zDb,
832 const char *zTbl,
danielk197794eb6a12005-12-15 15:22:08 +0000833 sqlite_int64 rowid
834){
835 SqliteDb *pDb = (SqliteDb *)p;
836 Tcl_Obj *pCmd;
dan46c47d42011-03-01 18:42:07 +0000837 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
838
839 assert( (SQLITE_DELETE-1)/9 == 0 );
840 assert( (SQLITE_INSERT-1)/9 == 1 );
841 assert( (SQLITE_UPDATE-1)/9 == 2 );
danielk197794eb6a12005-12-15 15:22:08 +0000842
843 assert( pDb->pUpdateHook );
844 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
845
846 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
847 Tcl_IncrRefCount(pCmd);
dan46c47d42011-03-01 18:42:07 +0000848 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
danielk197794eb6a12005-12-15 15:22:08 +0000849 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
850 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
851 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
852 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
drhefdde162010-10-27 15:36:21 +0000853 Tcl_DecrRefCount(pCmd);
danielk197794eb6a12005-12-15 15:22:08 +0000854}
855
danielk19777cedc8d2004-06-10 10:50:08 +0000856static void tclCollateNeeded(
857 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000858 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000859 int enc,
860 const char *zName
861){
862 SqliteDb *pDb = (SqliteDb *)pCtx;
863 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
864 Tcl_IncrRefCount(pScript);
865 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
866 Tcl_EvalObjEx(pDb->interp, pScript, 0);
867 Tcl_DecrRefCount(pScript);
868}
869
drhaa940ea2004-01-15 02:44:03 +0000870/*
danielk19770202b292004-06-09 09:55:16 +0000871** This routine is called to evaluate an SQL collation function implemented
872** using TCL script.
873*/
874static int tclSqlCollate(
875 void *pCtx,
876 int nA,
877 const void *zA,
878 int nB,
879 const void *zB
880){
881 SqlCollate *p = (SqlCollate *)pCtx;
882 Tcl_Obj *pCmd;
883
884 pCmd = Tcl_NewStringObj(p->zScript, -1);
885 Tcl_IncrRefCount(pCmd);
886 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
887 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000888 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000889 Tcl_DecrRefCount(pCmd);
890 return (atoi(Tcl_GetStringResult(p->interp)));
891}
892
893/*
drhcabb0812002-09-14 13:47:32 +0000894** This routine is called to evaluate an SQL function implemented
895** using TCL script.
896*/
drhfb7e7652005-01-24 00:28:42 +0000897static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000898 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000899 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000900 int i;
901 int rc;
902
drhd1e47332005-06-26 17:55:33 +0000903 if( argc==0 ){
904 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
905 ** script object directly. This allows the TCL compiler to generate
906 ** bytecode for the command on the first invocation and thus make
907 ** subsequent invocations much faster. */
908 pCmd = p->pScript;
909 Tcl_IncrRefCount(pCmd);
910 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
911 Tcl_DecrRefCount(pCmd);
912 }else{
913 /* If there are arguments to the function, make a shallow copy of the
914 ** script object, lappend the arguments, then evaluate the copy.
915 **
peter.d.reid60ec9142014-09-06 16:39:46 +0000916 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
mistachkinb56660f2016-07-14 21:26:09 +0000917 ** The new Tcl_Obj contains pointers to the original list elements.
drhd1e47332005-06-26 17:55:33 +0000918 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
919 ** of the list to tclCmdNameType, that alternate representation will
920 ** be preserved and reused on the next invocation.
921 */
922 Tcl_Obj **aArg;
923 int nArg;
924 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
mistachkinb56660f2016-07-14 21:26:09 +0000925 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhd1e47332005-06-26 17:55:33 +0000926 return;
mistachkinb56660f2016-07-14 21:26:09 +0000927 }
drhd1e47332005-06-26 17:55:33 +0000928 pCmd = Tcl_NewListObj(nArg, aArg);
929 Tcl_IncrRefCount(pCmd);
930 for(i=0; i<argc; i++){
931 sqlite3_value *pIn = argv[i];
932 Tcl_Obj *pVal;
mistachkinb56660f2016-07-14 21:26:09 +0000933
drhd1e47332005-06-26 17:55:33 +0000934 /* Set pVal to contain the i'th column of this row. */
935 switch( sqlite3_value_type(pIn) ){
936 case SQLITE_BLOB: {
937 int bytes = sqlite3_value_bytes(pIn);
938 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
939 break;
940 }
941 case SQLITE_INTEGER: {
942 sqlite_int64 v = sqlite3_value_int64(pIn);
943 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +0000944 pVal = Tcl_NewIntObj((int)v);
drhd1e47332005-06-26 17:55:33 +0000945 }else{
946 pVal = Tcl_NewWideIntObj(v);
947 }
948 break;
949 }
950 case SQLITE_FLOAT: {
951 double r = sqlite3_value_double(pIn);
952 pVal = Tcl_NewDoubleObj(r);
953 break;
954 }
955 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +0000956 pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
drhd1e47332005-06-26 17:55:33 +0000957 break;
958 }
959 default: {
960 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000961 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000962 break;
963 }
964 }
965 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
966 if( rc ){
967 Tcl_DecrRefCount(pCmd);
mistachkinb56660f2016-07-14 21:26:09 +0000968 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhd1e47332005-06-26 17:55:33 +0000969 return;
970 }
danielk197751ad0ec2004-05-24 12:39:02 +0000971 }
drhd1e47332005-06-26 17:55:33 +0000972 if( !p->useEvalObjv ){
973 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
974 ** is a list without a string representation. To prevent this from
975 ** happening, make sure pCmd has a valid string representation */
976 Tcl_GetString(pCmd);
977 }
978 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
979 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000980 }
danielk1977562e8d32005-05-20 09:40:55 +0000981
drhc7f269d2005-05-05 10:30:29 +0000982 if( rc && rc!=TCL_RETURN ){
mistachkinb56660f2016-07-14 21:26:09 +0000983 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000984 }else{
drhc7f269d2005-05-05 10:30:29 +0000985 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
986 int n;
987 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000988 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000989 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000990 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000991 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000992 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000993 data = Tcl_GetByteArrayFromObj(pVar, &n);
994 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000995 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000996 Tcl_GetIntFromObj(0, pVar, &n);
997 sqlite3_result_int(context, n);
998 }else if( c=='d' && strcmp(zType,"double")==0 ){
999 double r;
1000 Tcl_GetDoubleFromObj(0, pVar, &r);
1001 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +00001002 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1003 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +00001004 Tcl_WideInt v;
1005 Tcl_GetWideIntFromObj(0, pVar, &v);
1006 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +00001007 }else{
danielk197700fd9572005-12-07 06:27:43 +00001008 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1009 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +00001010 }
drhcabb0812002-09-14 13:47:32 +00001011 }
1012}
drh895d7472004-08-20 16:02:39 +00001013
drhe22a3342003-04-22 20:30:37 +00001014#ifndef SQLITE_OMIT_AUTHORIZATION
1015/*
1016** This is the authentication function. It appends the authentication
1017** type code and the two arguments to zCmd[] then invokes the result
1018** on the interpreter. The reply is examined to determine if the
1019** authentication fails or succeeds.
1020*/
1021static int auth_callback(
1022 void *pArg,
1023 int code,
1024 const char *zArg1,
1025 const char *zArg2,
1026 const char *zArg3,
1027 const char *zArg4
drh32c6a482014-09-11 13:44:52 +00001028#ifdef SQLITE_USER_AUTHENTICATION
1029 ,const char *zArg5
1030#endif
drhe22a3342003-04-22 20:30:37 +00001031){
mistachkin6ef5e122014-01-24 17:03:55 +00001032 const char *zCode;
drhe22a3342003-04-22 20:30:37 +00001033 Tcl_DString str;
1034 int rc;
1035 const char *zReply;
drh94189212017-05-11 13:43:57 +00001036 /* EVIDENCE-OF: R-38590-62769 The first parameter to the authorizer
1037 ** callback is a copy of the third parameter to the
1038 ** sqlite3_set_authorizer() interface.
1039 */
drhe22a3342003-04-22 20:30:37 +00001040 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +00001041 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +00001042
drh94189212017-05-11 13:43:57 +00001043 /* EVIDENCE-OF: R-56518-44310 The second parameter to the callback is an
1044 ** integer action code that specifies the particular action to be
1045 ** authorized. */
drhe22a3342003-04-22 20:30:37 +00001046 switch( code ){
1047 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
1048 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
1049 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
1050 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
1051 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
1052 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
1053 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
1054 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
1055 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
1056 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
1057 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
1058 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
1059 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
1060 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
1061 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
1062 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
1063 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
1064 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
1065 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
1066 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
1067 case SQLITE_READ : zCode="SQLITE_READ"; break;
1068 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
1069 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
1070 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +00001071 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
1072 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +00001073 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +00001074 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +00001075 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +00001076 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
1077 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +00001078 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +00001079 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drh65a2aaa2014-01-16 22:40:02 +00001080 case SQLITE_RECURSIVE : zCode="SQLITE_RECURSIVE"; break;
drhe22a3342003-04-22 20:30:37 +00001081 default : zCode="????"; break;
1082 }
1083 Tcl_DStringInit(&str);
1084 Tcl_DStringAppend(&str, pDb->zAuth, -1);
1085 Tcl_DStringAppendElement(&str, zCode);
1086 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
1087 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
1088 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
1089 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
drh32c6a482014-09-11 13:44:52 +00001090#ifdef SQLITE_USER_AUTHENTICATION
1091 Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
mistachkinb56660f2016-07-14 21:26:09 +00001092#endif
drhe22a3342003-04-22 20:30:37 +00001093 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
1094 Tcl_DStringFree(&str);
drhb07028f2011-10-14 21:49:18 +00001095 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
drhe22a3342003-04-22 20:30:37 +00001096 if( strcmp(zReply,"SQLITE_OK")==0 ){
1097 rc = SQLITE_OK;
1098 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
1099 rc = SQLITE_DENY;
1100 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
1101 rc = SQLITE_IGNORE;
1102 }else{
1103 rc = 999;
1104 }
1105 return rc;
1106}
1107#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +00001108
1109/*
tpoindex1067fe12004-12-17 15:41:11 +00001110** This routine reads a line of text from FILE in, stores
1111** the text in memory obtained from malloc() and returns a pointer
1112** to the text. NULL is returned at end of file, or if malloc()
1113** fails.
1114**
1115** The interface is like "readline" but no command-line editing
1116** is done.
1117**
1118** copied from shell.c from '.import' command
1119*/
1120static char *local_getline(char *zPrompt, FILE *in){
1121 char *zLine;
1122 int nLine;
1123 int n;
tpoindex1067fe12004-12-17 15:41:11 +00001124
1125 nLine = 100;
1126 zLine = malloc( nLine );
1127 if( zLine==0 ) return 0;
1128 n = 0;
drhb07028f2011-10-14 21:49:18 +00001129 while( 1 ){
tpoindex1067fe12004-12-17 15:41:11 +00001130 if( n+100>nLine ){
1131 nLine = nLine*2 + 100;
1132 zLine = realloc(zLine, nLine);
1133 if( zLine==0 ) return 0;
1134 }
1135 if( fgets(&zLine[n], nLine - n, in)==0 ){
1136 if( n==0 ){
1137 free(zLine);
1138 return 0;
1139 }
1140 zLine[n] = 0;
tpoindex1067fe12004-12-17 15:41:11 +00001141 break;
1142 }
1143 while( zLine[n] ){ n++; }
1144 if( n>0 && zLine[n-1]=='\n' ){
1145 n--;
1146 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +00001147 break;
tpoindex1067fe12004-12-17 15:41:11 +00001148 }
1149 }
1150 zLine = realloc( zLine, n+1 );
1151 return zLine;
1152}
1153
danielk19778e556522007-11-13 10:30:24 +00001154
1155/*
dan4a4c11a2009-10-06 14:59:02 +00001156** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +00001157**
dan4a4c11a2009-10-06 14:59:02 +00001158** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +00001159**
dan4a4c11a2009-10-06 14:59:02 +00001160** It is invoked after evaluating the script SCRIPT to commit or rollback
1161** the transaction or savepoint opened by the [transaction] command.
1162*/
mistachkina121cc72016-07-28 18:06:52 +00001163static int SQLITE_TCLAPI DbTransPostCmd(
dan4a4c11a2009-10-06 14:59:02 +00001164 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1165 Tcl_Interp *interp, /* Tcl interpreter */
1166 int result /* Result of evaluating SCRIPT */
1167){
mistachkin6ef5e122014-01-24 17:03:55 +00001168 static const char *const azEnd[] = {
dan4a4c11a2009-10-06 14:59:02 +00001169 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1170 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1171 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1172 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1173 };
1174 SqliteDb *pDb = (SqliteDb*)data[0];
1175 int rc = result;
1176 const char *zEnd;
1177
1178 pDb->nTransaction--;
1179 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1180
1181 pDb->disableAuth++;
1182 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1183 /* This is a tricky scenario to handle. The most likely cause of an
mistachkinb56660f2016-07-14 21:26:09 +00001184 ** error is that the exec() above was an attempt to commit the
dan4a4c11a2009-10-06 14:59:02 +00001185 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
mistachkin48864df2013-03-21 21:20:32 +00001186 ** that an IO-error has occurred. In either case, throw a Tcl exception
dan4a4c11a2009-10-06 14:59:02 +00001187 ** and try to rollback the transaction.
1188 **
mistachkinb56660f2016-07-14 21:26:09 +00001189 ** But it could also be that the user executed one or more BEGIN,
dan4a4c11a2009-10-06 14:59:02 +00001190 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1191 ** this method's logic. Not clear how this would be best handled.
1192 */
1193 if( rc!=TCL_ERROR ){
drha198f2b2014-02-07 19:26:13 +00001194 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
dan4a4c11a2009-10-06 14:59:02 +00001195 rc = TCL_ERROR;
1196 }
1197 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1198 }
1199 pDb->disableAuth--;
1200
1201 return rc;
1202}
1203
1204/*
danc431fd52011-06-27 16:55:50 +00001205** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1206** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1207** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
mistachkinb56660f2016-07-14 21:26:09 +00001208** on whether or not the [db_use_legacy_prepare] command has been used to
danc431fd52011-06-27 16:55:50 +00001209** configure the connection.
1210*/
1211static int dbPrepare(
1212 SqliteDb *pDb, /* Database object */
1213 const char *zSql, /* SQL to compile */
1214 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1215 const char **pzOut /* OUT: Pointer to next SQL statement */
1216){
drh2c2f3922017-06-01 00:54:35 +00001217 unsigned int prepFlags = 0;
danc431fd52011-06-27 16:55:50 +00001218#ifdef SQLITE_TEST
1219 if( pDb->bLegacyPrepare ){
1220 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1221 }
1222#endif
drh2c2f3922017-06-01 00:54:35 +00001223 /* If the statement cache is large, use the SQLITE_PREPARE_PERSISTENT
1224 ** flags, which uses less lookaside memory. But if the cache is small,
1225 ** omit that flag to make full use of lookaside */
1226 if( pDb->maxStmt>5 ) prepFlags = SQLITE_PREPARE_PERSISTENT;
1227
1228 return sqlite3_prepare_v3(pDb->db, zSql, -1, prepFlags, ppStmt, pzOut);
danc431fd52011-06-27 16:55:50 +00001229}
1230
1231/*
dan4a4c11a2009-10-06 14:59:02 +00001232** Search the cache for a prepared-statement object that implements the
1233** first SQL statement in the buffer pointed to by parameter zIn. If
1234** no such prepared-statement can be found, allocate and prepare a new
1235** one. In either case, bind the current values of the relevant Tcl
1236** variables to any $var, :var or @var variables in the statement. Before
1237** returning, set *ppPreStmt to point to the prepared-statement object.
1238**
1239** Output parameter *pzOut is set to point to the next SQL statement in
1240** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1241** next statement.
1242**
1243** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1244** and an error message loaded into interpreter pDb->interp.
1245*/
1246static int dbPrepareAndBind(
1247 SqliteDb *pDb, /* Database object */
1248 char const *zIn, /* SQL to compile */
1249 char const **pzOut, /* OUT: Pointer to next SQL statement */
1250 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1251){
1252 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
mistachkin7bb22ac2015-01-12 19:59:12 +00001253 sqlite3_stmt *pStmt = 0; /* Prepared statement object */
dan4a4c11a2009-10-06 14:59:02 +00001254 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1255 int nSql; /* Length of zSql in bytes */
mistachkin7bb22ac2015-01-12 19:59:12 +00001256 int nVar = 0; /* Number of variables in statement */
dan4a4c11a2009-10-06 14:59:02 +00001257 int iParm = 0; /* Next free entry in apParm */
drh0425f182013-11-26 16:48:04 +00001258 char c;
dan4a4c11a2009-10-06 14:59:02 +00001259 int i;
1260 Tcl_Interp *interp = pDb->interp;
1261
1262 *ppPreStmt = 0;
1263
1264 /* Trim spaces from the start of zSql and calculate the remaining length. */
drh0425f182013-11-26 16:48:04 +00001265 while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
dan4a4c11a2009-10-06 14:59:02 +00001266 nSql = strlen30(zSql);
1267
1268 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1269 int n = pPreStmt->nSql;
mistachkinb56660f2016-07-14 21:26:09 +00001270 if( nSql>=n
dan4a4c11a2009-10-06 14:59:02 +00001271 && memcmp(pPreStmt->zSql, zSql, n)==0
1272 && (zSql[n]==0 || zSql[n-1]==';')
1273 ){
1274 pStmt = pPreStmt->pStmt;
1275 *pzOut = &zSql[pPreStmt->nSql];
1276
1277 /* When a prepared statement is found, unlink it from the
1278 ** cache list. It will later be added back to the beginning
1279 ** of the cache list in order to implement LRU replacement.
1280 */
1281 if( pPreStmt->pPrev ){
1282 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1283 }else{
1284 pDb->stmtList = pPreStmt->pNext;
1285 }
1286 if( pPreStmt->pNext ){
1287 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1288 }else{
1289 pDb->stmtLast = pPreStmt->pPrev;
1290 }
1291 pDb->nStmt--;
1292 nVar = sqlite3_bind_parameter_count(pStmt);
1293 break;
1294 }
1295 }
mistachkinb56660f2016-07-14 21:26:09 +00001296
dan4a4c11a2009-10-06 14:59:02 +00001297 /* If no prepared statement was found. Compile the SQL text. Also allocate
1298 ** a new SqlPreparedStmt structure. */
1299 if( pPreStmt==0 ){
1300 int nByte;
1301
danc431fd52011-06-27 16:55:50 +00001302 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
drhc45e6712012-10-03 11:02:33 +00001303 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001304 return TCL_ERROR;
1305 }
1306 if( pStmt==0 ){
1307 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1308 /* A compile-time error in the statement. */
drhc45e6712012-10-03 11:02:33 +00001309 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001310 return TCL_ERROR;
1311 }else{
1312 /* The statement was a no-op. Continue to the next statement
1313 ** in the SQL string.
1314 */
1315 return TCL_OK;
1316 }
1317 }
1318
1319 assert( pPreStmt==0 );
1320 nVar = sqlite3_bind_parameter_count(pStmt);
1321 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1322 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1323 memset(pPreStmt, 0, nByte);
1324
1325 pPreStmt->pStmt = pStmt;
drh7ed243b2012-04-19 17:19:51 +00001326 pPreStmt->nSql = (int)(*pzOut - zSql);
dan4a4c11a2009-10-06 14:59:02 +00001327 pPreStmt->zSql = sqlite3_sql(pStmt);
1328 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
danc431fd52011-06-27 16:55:50 +00001329#ifdef SQLITE_TEST
1330 if( pPreStmt->zSql==0 ){
1331 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1332 memcpy(zCopy, zSql, pPreStmt->nSql);
1333 zCopy[pPreStmt->nSql] = '\0';
1334 pPreStmt->zSql = zCopy;
1335 }
1336#endif
dan4a4c11a2009-10-06 14:59:02 +00001337 }
1338 assert( pPreStmt );
1339 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1340 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1341
mistachkinb56660f2016-07-14 21:26:09 +00001342 /* Bind values to parameters that begin with $ or : */
dan4a4c11a2009-10-06 14:59:02 +00001343 for(i=1; i<=nVar; i++){
1344 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1345 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1346 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1347 if( pVar ){
1348 int n;
1349 u8 *data;
1350 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
mistachkin8e189222015-04-19 21:43:16 +00001351 c = zType[0];
dan4a4c11a2009-10-06 14:59:02 +00001352 if( zVar[0]=='@' ||
1353 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1354 /* Load a BLOB type if the Tcl variable is a bytearray and
1355 ** it has no string representation or the host
1356 ** parameter name begins with "@". */
1357 data = Tcl_GetByteArrayFromObj(pVar, &n);
1358 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1359 Tcl_IncrRefCount(pVar);
1360 pPreStmt->apParm[iParm++] = pVar;
1361 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1362 Tcl_GetIntFromObj(interp, pVar, &n);
1363 sqlite3_bind_int(pStmt, i, n);
1364 }else if( c=='d' && strcmp(zType,"double")==0 ){
1365 double r;
1366 Tcl_GetDoubleFromObj(interp, pVar, &r);
1367 sqlite3_bind_double(pStmt, i, r);
1368 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1369 (c=='i' && strcmp(zType,"int")==0) ){
1370 Tcl_WideInt v;
1371 Tcl_GetWideIntFromObj(interp, pVar, &v);
1372 sqlite3_bind_int64(pStmt, i, v);
1373 }else{
1374 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1375 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1376 Tcl_IncrRefCount(pVar);
1377 pPreStmt->apParm[iParm++] = pVar;
1378 }
1379 }else{
1380 sqlite3_bind_null(pStmt, i);
1381 }
1382 }
1383 }
1384 pPreStmt->nParm = iParm;
1385 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001386
dan4a4c11a2009-10-06 14:59:02 +00001387 return TCL_OK;
1388}
1389
dan4a4c11a2009-10-06 14:59:02 +00001390/*
1391** Release a statement reference obtained by calling dbPrepareAndBind().
1392** There should be exactly one call to this function for each call to
1393** dbPrepareAndBind().
1394**
1395** If the discard parameter is non-zero, then the statement is deleted
1396** immediately. Otherwise it is added to the LRU list and may be returned
1397** by a subsequent call to dbPrepareAndBind().
1398*/
1399static void dbReleaseStmt(
1400 SqliteDb *pDb, /* Database handle */
1401 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1402 int discard /* True to delete (not cache) the pPreStmt */
1403){
1404 int i;
1405
1406 /* Free the bound string and blob parameters */
1407 for(i=0; i<pPreStmt->nParm; i++){
1408 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1409 }
1410 pPreStmt->nParm = 0;
1411
1412 if( pDb->maxStmt<=0 || discard ){
1413 /* If the cache is turned off, deallocated the statement */
danc431fd52011-06-27 16:55:50 +00001414 dbFreeStmt(pPreStmt);
dan4a4c11a2009-10-06 14:59:02 +00001415 }else{
1416 /* Add the prepared statement to the beginning of the cache list. */
1417 pPreStmt->pNext = pDb->stmtList;
1418 pPreStmt->pPrev = 0;
1419 if( pDb->stmtList ){
1420 pDb->stmtList->pPrev = pPreStmt;
1421 }
1422 pDb->stmtList = pPreStmt;
1423 if( pDb->stmtLast==0 ){
1424 assert( pDb->nStmt==0 );
1425 pDb->stmtLast = pPreStmt;
1426 }else{
1427 assert( pDb->nStmt>0 );
1428 }
1429 pDb->nStmt++;
mistachkinb56660f2016-07-14 21:26:09 +00001430
1431 /* If we have too many statement in cache, remove the surplus from
dan4a4c11a2009-10-06 14:59:02 +00001432 ** the end of the cache list. */
1433 while( pDb->nStmt>pDb->maxStmt ){
danc431fd52011-06-27 16:55:50 +00001434 SqlPreparedStmt *pLast = pDb->stmtLast;
1435 pDb->stmtLast = pLast->pPrev;
dan4a4c11a2009-10-06 14:59:02 +00001436 pDb->stmtLast->pNext = 0;
1437 pDb->nStmt--;
danc431fd52011-06-27 16:55:50 +00001438 dbFreeStmt(pLast);
dan4a4c11a2009-10-06 14:59:02 +00001439 }
1440 }
1441}
1442
1443/*
1444** Structure used with dbEvalXXX() functions:
1445**
1446** dbEvalInit()
1447** dbEvalStep()
1448** dbEvalFinalize()
1449** dbEvalRowInfo()
1450** dbEvalColumnValue()
1451*/
1452typedef struct DbEvalContext DbEvalContext;
1453struct DbEvalContext {
1454 SqliteDb *pDb; /* Database handle */
1455 Tcl_Obj *pSql; /* Object holding string zSql */
1456 const char *zSql; /* Remaining SQL to execute */
1457 SqlPreparedStmt *pPreStmt; /* Current statement */
1458 int nCol; /* Number of columns returned by pStmt */
1459 Tcl_Obj *pArray; /* Name of array variable */
1460 Tcl_Obj **apColName; /* Array of column names */
1461};
1462
1463/*
1464** Release any cache of column names currently held as part of
1465** the DbEvalContext structure passed as the first argument.
1466*/
1467static void dbReleaseColumnNames(DbEvalContext *p){
1468 if( p->apColName ){
1469 int i;
1470 for(i=0; i<p->nCol; i++){
1471 Tcl_DecrRefCount(p->apColName[i]);
1472 }
1473 Tcl_Free((char *)p->apColName);
1474 p->apColName = 0;
1475 }
1476 p->nCol = 0;
1477}
1478
1479/*
1480** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001481**
1482** If pArray is not NULL, then it contains the name of a Tcl array
1483** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001484** the names of the columns returned by the statement as part of each
mistachkinb56660f2016-07-14 21:26:09 +00001485** call to dbEvalStep(), in order from left to right. e.g. if the names
1486** of the returned columns are a, b and c, it does the equivalent of the
dan4a4c11a2009-10-06 14:59:02 +00001487** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001488**
1489** set ${pArray}(*) {a b c}
1490*/
dan4a4c11a2009-10-06 14:59:02 +00001491static void dbEvalInit(
1492 DbEvalContext *p, /* Pointer to structure to initialize */
1493 SqliteDb *pDb, /* Database handle */
1494 Tcl_Obj *pSql, /* Object containing SQL script */
1495 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001496){
dan4a4c11a2009-10-06 14:59:02 +00001497 memset(p, 0, sizeof(DbEvalContext));
1498 p->pDb = pDb;
1499 p->zSql = Tcl_GetString(pSql);
1500 p->pSql = pSql;
1501 Tcl_IncrRefCount(pSql);
1502 if( pArray ){
1503 p->pArray = pArray;
1504 Tcl_IncrRefCount(pArray);
1505 }
1506}
danielk19778e556522007-11-13 10:30:24 +00001507
dan4a4c11a2009-10-06 14:59:02 +00001508/*
1509** Obtain information about the row that the DbEvalContext passed as the
1510** first argument currently points to.
1511*/
1512static void dbEvalRowInfo(
1513 DbEvalContext *p, /* Evaluation context */
1514 int *pnCol, /* OUT: Number of column names */
1515 Tcl_Obj ***papColName /* OUT: Array of column names */
1516){
danielk19778e556522007-11-13 10:30:24 +00001517 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001518 if( 0==p->apColName ){
1519 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1520 int i; /* Iterator variable */
1521 int nCol; /* Number of columns returned by pStmt */
1522 Tcl_Obj **apColName = 0; /* Array of column names */
1523
1524 p->nCol = nCol = sqlite3_column_count(pStmt);
1525 if( nCol>0 && (papColName || p->pArray) ){
1526 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1527 for(i=0; i<nCol; i++){
drhc45e6712012-10-03 11:02:33 +00001528 apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
dan4a4c11a2009-10-06 14:59:02 +00001529 Tcl_IncrRefCount(apColName[i]);
1530 }
1531 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001532 }
1533
1534 /* If results are being stored in an array variable, then create
1535 ** the array(*) entry for that array
1536 */
dan4a4c11a2009-10-06 14:59:02 +00001537 if( p->pArray ){
1538 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001539 Tcl_Obj *pColList = Tcl_NewObj();
1540 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001541
danielk19778e556522007-11-13 10:30:24 +00001542 for(i=0; i<nCol; i++){
1543 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1544 }
1545 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001546 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001547 Tcl_DecrRefCount(pStar);
1548 }
danielk19778e556522007-11-13 10:30:24 +00001549 }
1550
dan4a4c11a2009-10-06 14:59:02 +00001551 if( papColName ){
1552 *papColName = p->apColName;
1553 }
1554 if( pnCol ){
1555 *pnCol = p->nCol;
1556 }
1557}
1558
1559/*
1560** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1561** returned, then an error message is stored in the interpreter before
1562** returning.
1563**
1564** A return value of TCL_OK means there is a row of data available. The
1565** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1566** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1567** is returned, then the SQL script has finished executing and there are
1568** no further rows available. This is similar to SQLITE_DONE.
1569*/
1570static int dbEvalStep(DbEvalContext *p){
danc431fd52011-06-27 16:55:50 +00001571 const char *zPrevSql = 0; /* Previous value of p->zSql */
1572
dan4a4c11a2009-10-06 14:59:02 +00001573 while( p->zSql[0] || p->pPreStmt ){
1574 int rc;
1575 if( p->pPreStmt==0 ){
danc431fd52011-06-27 16:55:50 +00001576 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
dan4a4c11a2009-10-06 14:59:02 +00001577 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1578 if( rc!=TCL_OK ) return rc;
1579 }else{
1580 int rcs;
1581 SqliteDb *pDb = p->pDb;
1582 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1583 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1584
1585 rcs = sqlite3_step(pStmt);
1586 if( rcs==SQLITE_ROW ){
1587 return TCL_OK;
1588 }
1589 if( p->pArray ){
1590 dbEvalRowInfo(p, 0, 0);
1591 }
1592 rcs = sqlite3_reset(pStmt);
1593
1594 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1595 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001596 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
dan4a4c11a2009-10-06 14:59:02 +00001597 dbReleaseColumnNames(p);
1598 p->pPreStmt = 0;
1599
1600 if( rcs!=SQLITE_OK ){
1601 /* If a run-time error occurs, report the error and stop reading
1602 ** the SQL. */
dan4a4c11a2009-10-06 14:59:02 +00001603 dbReleaseStmt(pDb, pPreStmt, 1);
danc431fd52011-06-27 16:55:50 +00001604#if SQLITE_TEST
1605 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1606 /* If the runtime error was an SQLITE_SCHEMA, and the database
mistachkinb56660f2016-07-14 21:26:09 +00001607 ** handle is configured to use the legacy sqlite3_prepare()
danc431fd52011-06-27 16:55:50 +00001608 ** interface, retry prepare()/step() on the same SQL statement.
1609 ** This only happens once. If there is a second SQLITE_SCHEMA
1610 ** error, the error will be returned to the caller. */
1611 p->zSql = zPrevSql;
1612 continue;
1613 }
1614#endif
drhc45e6712012-10-03 11:02:33 +00001615 Tcl_SetObjResult(pDb->interp,
1616 Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001617 return TCL_ERROR;
1618 }else{
1619 dbReleaseStmt(pDb, pPreStmt, 0);
1620 }
1621 }
1622 }
1623
1624 /* Finished */
1625 return TCL_BREAK;
1626}
1627
1628/*
1629** Free all resources currently held by the DbEvalContext structure passed
1630** as the first argument. There should be exactly one call to this function
1631** for each call to dbEvalInit().
1632*/
1633static void dbEvalFinalize(DbEvalContext *p){
1634 if( p->pPreStmt ){
1635 sqlite3_reset(p->pPreStmt->pStmt);
1636 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1637 p->pPreStmt = 0;
1638 }
1639 if( p->pArray ){
1640 Tcl_DecrRefCount(p->pArray);
1641 p->pArray = 0;
1642 }
1643 Tcl_DecrRefCount(p->pSql);
1644 dbReleaseColumnNames(p);
1645}
1646
1647/*
1648** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1649** the value for the iCol'th column of the row currently pointed to by
1650** the DbEvalContext structure passed as the first argument.
1651*/
1652static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1653 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1654 switch( sqlite3_column_type(pStmt, iCol) ){
1655 case SQLITE_BLOB: {
1656 int bytes = sqlite3_column_bytes(pStmt, iCol);
1657 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1658 if( !zBlob ) bytes = 0;
1659 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1660 }
1661 case SQLITE_INTEGER: {
1662 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1663 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +00001664 return Tcl_NewIntObj((int)v);
dan4a4c11a2009-10-06 14:59:02 +00001665 }else{
1666 return Tcl_NewWideIntObj(v);
1667 }
1668 }
1669 case SQLITE_FLOAT: {
1670 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1671 }
1672 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +00001673 return Tcl_NewStringObj(p->pDb->zNull, -1);
dan4a4c11a2009-10-06 14:59:02 +00001674 }
1675 }
1676
drh325eff52012-10-03 12:56:18 +00001677 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
dan4a4c11a2009-10-06 14:59:02 +00001678}
1679
1680/*
1681** If using Tcl version 8.6 or greater, use the NR functions to avoid
1682** recursive evalution of scripts by the [db eval] and [db trans]
1683** commands. Even if the headers used while compiling the extension
1684** are 8.6 or newer, the code still tests the Tcl version at runtime.
1685** This allows stubs-enabled builds to be used with older Tcl libraries.
1686*/
1687#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001688# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001689static int DbUseNre(void){
1690 int major, minor;
1691 Tcl_GetVersion(&major, &minor, 0, 0);
1692 return( (major==8 && minor>=6) || major>8 );
1693}
1694#else
mistachkinb56660f2016-07-14 21:26:09 +00001695/*
dan4a4c11a2009-10-06 14:59:02 +00001696** Compiling using headers earlier than 8.6. In this case NR cannot be
1697** used, so DbUseNre() to always return zero. Add #defines for the other
1698** Tcl_NRxxx() functions to prevent them from causing compilation errors,
mistachkinb56660f2016-07-14 21:26:09 +00001699** even though the only invocations of them are within conditional blocks
dan4a4c11a2009-10-06 14:59:02 +00001700** of the form:
1701**
1702** if( DbUseNre() ) { ... }
1703*/
drha2c8a952009-10-13 18:38:34 +00001704# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001705# define DbUseNre() 0
drha47941f2013-12-20 18:57:44 +00001706# define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001707# define Tcl_NREvalObj(a,b,c) 0
drha47941f2013-12-20 18:57:44 +00001708# define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001709#endif
1710
1711/*
1712** This function is part of the implementation of the command:
1713**
1714** $db eval SQL ?ARRAYNAME? SCRIPT
1715*/
mistachkina121cc72016-07-28 18:06:52 +00001716static int SQLITE_TCLAPI DbEvalNextCmd(
dan4a4c11a2009-10-06 14:59:02 +00001717 ClientData data[], /* data[0] is the (DbEvalContext*) */
1718 Tcl_Interp *interp, /* Tcl interpreter */
1719 int result /* Result so far */
1720){
1721 int rc = result; /* Return code */
1722
1723 /* The first element of the data[] array is a pointer to a DbEvalContext
1724 ** structure allocated using Tcl_Alloc(). The second element of data[]
1725 ** is a pointer to a Tcl_Obj containing the script to run for each row
1726 ** returned by the queries encapsulated in data[0]. */
1727 DbEvalContext *p = (DbEvalContext *)data[0];
1728 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1729 Tcl_Obj *pArray = p->pArray;
1730
1731 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1732 int i;
1733 int nCol;
1734 Tcl_Obj **apColName;
1735 dbEvalRowInfo(p, &nCol, &apColName);
1736 for(i=0; i<nCol; i++){
1737 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1738 if( pArray==0 ){
1739 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1740 }else{
1741 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1742 }
1743 }
1744
mistachkinb56660f2016-07-14 21:26:09 +00001745 /* The required interpreter variables are now populated with the data
dan4a4c11a2009-10-06 14:59:02 +00001746 ** from the current row. If using NRE, schedule callbacks to evaluate
1747 ** script pScript, then to invoke this function again to fetch the next
1748 ** row (or clean up if there is no next row or the script throws an
mistachkinb56660f2016-07-14 21:26:09 +00001749 ** exception). After scheduling the callbacks, return control to the
dan4a4c11a2009-10-06 14:59:02 +00001750 ** caller.
1751 **
1752 ** If not using NRE, evaluate pScript directly and continue with the
1753 ** next iteration of this while(...) loop. */
1754 if( DbUseNre() ){
1755 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1756 return Tcl_NREvalObj(interp, pScript, 0);
1757 }else{
1758 rc = Tcl_EvalObjEx(interp, pScript, 0);
1759 }
1760 }
1761
1762 Tcl_DecrRefCount(pScript);
1763 dbEvalFinalize(p);
1764 Tcl_Free((char *)p);
1765
1766 if( rc==TCL_OK || rc==TCL_BREAK ){
1767 Tcl_ResetResult(interp);
1768 rc = TCL_OK;
1769 }
1770 return rc;
danielk19778e556522007-11-13 10:30:24 +00001771}
1772
tpoindex1067fe12004-12-17 15:41:11 +00001773/*
mistachkinb56660f2016-07-14 21:26:09 +00001774** This function is used by the implementations of the following database
dan46c47d42011-03-01 18:42:07 +00001775** handle sub-commands:
1776**
1777** $db update_hook ?SCRIPT?
1778** $db wal_hook ?SCRIPT?
1779** $db commit_hook ?SCRIPT?
1780** $db preupdate hook ?SCRIPT?
1781*/
1782static void DbHookCmd(
1783 Tcl_Interp *interp, /* Tcl interpreter */
1784 SqliteDb *pDb, /* Database handle */
1785 Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */
1786 Tcl_Obj **ppHook /* Pointer to member of SqliteDb */
1787){
1788 sqlite3 *db = pDb->db;
1789
1790 if( *ppHook ){
1791 Tcl_SetObjResult(interp, *ppHook);
1792 if( pArg ){
1793 Tcl_DecrRefCount(*ppHook);
1794 *ppHook = 0;
1795 }
1796 }
1797 if( pArg ){
1798 assert( !(*ppHook) );
1799 if( Tcl_GetCharLength(pArg)>0 ){
1800 *ppHook = pArg;
1801 Tcl_IncrRefCount(*ppHook);
1802 }
1803 }
1804
drh9b1c62d2011-03-30 21:04:43 +00001805#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +00001806 sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
drh9b1c62d2011-03-30 21:04:43 +00001807#endif
dan46c47d42011-03-01 18:42:07 +00001808 sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1809 sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1810 sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
1811}
1812
1813/*
drh75897232000-05-29 14:26:00 +00001814** The "sqlite" command below creates a new Tcl command for each
1815** connection it opens to an SQLite database. This routine is invoked
1816** whenever one of those connection-specific commands is executed
1817** in Tcl. For example, if you run Tcl code like this:
1818**
drh9bb575f2004-09-06 17:24:11 +00001819** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001820** db1 close
1821**
1822** The first command opens a connection to the "my_database" database
1823** and calls that connection "db1". The second command causes this
1824** subroutine to be invoked.
1825*/
mistachkin7617e4a2016-07-28 17:11:20 +00001826static int SQLITE_TCLAPI DbObjCmd(
1827 void *cd,
1828 Tcl_Interp *interp,
1829 int objc,
1830 Tcl_Obj *const*objv
1831){
drhbec3f402000-08-04 13:49:02 +00001832 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001833 int choice;
drh22fbcb82004-02-01 01:22:50 +00001834 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001835 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001836 "authorizer", "backup", "busy",
1837 "cache", "changes", "close",
1838 "collate", "collation_needed", "commit_hook",
1839 "complete", "copy", "enable_load_extension",
1840 "errorcode", "eval", "exists",
1841 "function", "incrblob", "interrupt",
drh833bf962010-04-28 14:42:19 +00001842 "last_insert_rowid", "nullvalue", "onecolumn",
drh304637c2011-03-18 16:47:27 +00001843 "preupdate", "profile", "progress",
1844 "rekey", "restore", "rollback_hook",
1845 "status", "timeout", "total_changes",
mistachkinb56660f2016-07-14 21:26:09 +00001846 "trace", "trace_v2", "transaction",
1847 "unlock_notify", "update_hook", "version",
1848 "wal_hook",
1849 0
drh6d313162000-09-21 13:01:35 +00001850 };
drh411995d2002-06-25 19:31:18 +00001851 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001852 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1853 DB_CACHE, DB_CHANGES, DB_CLOSE,
1854 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1855 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1856 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1857 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
drh833bf962010-04-28 14:42:19 +00001858 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
drh304637c2011-03-18 16:47:27 +00001859 DB_PREUPDATE, DB_PROFILE, DB_PROGRESS,
1860 DB_REKEY, DB_RESTORE, DB_ROLLBACK_HOOK,
1861 DB_STATUS, DB_TIMEOUT, DB_TOTAL_CHANGES,
mistachkinb56660f2016-07-14 21:26:09 +00001862 DB_TRACE, DB_TRACE_V2, DB_TRANSACTION,
1863 DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK, DB_VERSION,
1864 DB_WAL_HOOK,
drh6d313162000-09-21 13:01:35 +00001865 };
tpoindex1067fe12004-12-17 15:41:11 +00001866 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001867
1868 if( objc<2 ){
1869 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001870 return TCL_ERROR;
1871 }
drh411995d2002-06-25 19:31:18 +00001872 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001873 return TCL_ERROR;
1874 }
1875
drh411995d2002-06-25 19:31:18 +00001876 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001877
drhe22a3342003-04-22 20:30:37 +00001878 /* $db authorizer ?CALLBACK?
1879 **
1880 ** Invoke the given callback to authorize each SQL operation as it is
1881 ** compiled. 5 arguments are appended to the callback before it is
1882 ** invoked:
1883 **
1884 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1885 ** (2) First descriptive name (depends on authorization type)
1886 ** (3) Second descriptive name
1887 ** (4) Name of the database (ex: "main", "temp")
1888 ** (5) Name of trigger that is doing the access
1889 **
1890 ** The callback should return on of the following strings: SQLITE_OK,
1891 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1892 **
1893 ** If this method is invoked with no arguments, the current authorization
1894 ** callback string is returned.
1895 */
1896 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001897#ifdef SQLITE_OMIT_AUTHORIZATION
drha198f2b2014-02-07 19:26:13 +00001898 Tcl_AppendResult(interp, "authorization not available in this build",
1899 (char*)0);
drh1211de32004-07-26 12:24:22 +00001900 return TCL_ERROR;
1901#else
drhe22a3342003-04-22 20:30:37 +00001902 if( objc>3 ){
1903 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001904 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001905 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001906 if( pDb->zAuth ){
drha198f2b2014-02-07 19:26:13 +00001907 Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
drhe22a3342003-04-22 20:30:37 +00001908 }
1909 }else{
1910 char *zAuth;
1911 int len;
1912 if( pDb->zAuth ){
1913 Tcl_Free(pDb->zAuth);
1914 }
1915 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1916 if( zAuth && len>0 ){
1917 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001918 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001919 }else{
1920 pDb->zAuth = 0;
1921 }
drhe22a3342003-04-22 20:30:37 +00001922 if( pDb->zAuth ){
drh32c6a482014-09-11 13:44:52 +00001923 typedef int (*sqlite3_auth_cb)(
1924 void*,int,const char*,const char*,
1925 const char*,const char*);
drhe22a3342003-04-22 20:30:37 +00001926 pDb->interp = interp;
drh32c6a482014-09-11 13:44:52 +00001927 sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
drhe22a3342003-04-22 20:30:37 +00001928 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001929 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001930 }
drhe22a3342003-04-22 20:30:37 +00001931 }
drh1211de32004-07-26 12:24:22 +00001932#endif
drhe22a3342003-04-22 20:30:37 +00001933 break;
1934 }
1935
drhdc2c4912009-02-04 22:46:47 +00001936 /* $db backup ?DATABASE? FILENAME
1937 **
1938 ** Open or create a database file named FILENAME. Transfer the
1939 ** content of local database DATABASE (default: "main") into the
1940 ** FILENAME database.
1941 */
1942 case DB_BACKUP: {
1943 const char *zDestFile;
1944 const char *zSrcDb;
1945 sqlite3 *pDest;
1946 sqlite3_backup *pBackup;
1947
1948 if( objc==3 ){
1949 zSrcDb = "main";
1950 zDestFile = Tcl_GetString(objv[2]);
1951 }else if( objc==4 ){
1952 zSrcDb = Tcl_GetString(objv[2]);
1953 zDestFile = Tcl_GetString(objv[3]);
1954 }else{
1955 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1956 return TCL_ERROR;
1957 }
drh147ef392016-01-22 23:17:51 +00001958 rc = sqlite3_open_v2(zDestFile, &pDest,
1959 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00001960 if( rc!=SQLITE_OK ){
1961 Tcl_AppendResult(interp, "cannot open target database: ",
1962 sqlite3_errmsg(pDest), (char*)0);
1963 sqlite3_close(pDest);
1964 return TCL_ERROR;
1965 }
1966 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1967 if( pBackup==0 ){
1968 Tcl_AppendResult(interp, "backup failed: ",
1969 sqlite3_errmsg(pDest), (char*)0);
1970 sqlite3_close(pDest);
1971 return TCL_ERROR;
1972 }
1973 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1974 sqlite3_backup_finish(pBackup);
1975 if( rc==SQLITE_DONE ){
1976 rc = TCL_OK;
1977 }else{
1978 Tcl_AppendResult(interp, "backup failed: ",
1979 sqlite3_errmsg(pDest), (char*)0);
1980 rc = TCL_ERROR;
1981 }
1982 sqlite3_close(pDest);
1983 break;
1984 }
1985
drhbec3f402000-08-04 13:49:02 +00001986 /* $db busy ?CALLBACK?
1987 **
1988 ** Invoke the given callback if an SQL statement attempts to open
1989 ** a locked database file.
1990 */
drh6d313162000-09-21 13:01:35 +00001991 case DB_BUSY: {
1992 if( objc>3 ){
1993 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001994 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001995 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001996 if( pDb->zBusy ){
drha198f2b2014-02-07 19:26:13 +00001997 Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
drhbec3f402000-08-04 13:49:02 +00001998 }
1999 }else{
drh6d313162000-09-21 13:01:35 +00002000 char *zBusy;
2001 int len;
drhbec3f402000-08-04 13:49:02 +00002002 if( pDb->zBusy ){
2003 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00002004 }
drh6d313162000-09-21 13:01:35 +00002005 zBusy = Tcl_GetStringFromObj(objv[2], &len);
2006 if( zBusy && len>0 ){
2007 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002008 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00002009 }else{
2010 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00002011 }
2012 if( pDb->zBusy ){
2013 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002014 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00002015 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002016 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00002017 }
2018 }
drh6d313162000-09-21 13:01:35 +00002019 break;
2020 }
drhbec3f402000-08-04 13:49:02 +00002021
drhfb7e7652005-01-24 00:28:42 +00002022 /* $db cache flush
2023 ** $db cache size n
2024 **
2025 ** Flush the prepared statement cache, or set the maximum number of
2026 ** cached statements.
2027 */
2028 case DB_CACHE: {
2029 char *subCmd;
2030 int n;
2031
2032 if( objc<=2 ){
2033 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
2034 return TCL_ERROR;
2035 }
2036 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
2037 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
2038 if( objc!=3 ){
2039 Tcl_WrongNumArgs(interp, 2, objv, "flush");
2040 return TCL_ERROR;
2041 }else{
2042 flushStmtCache( pDb );
2043 }
2044 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
2045 if( objc!=4 ){
2046 Tcl_WrongNumArgs(interp, 2, objv, "size n");
2047 return TCL_ERROR;
2048 }else{
2049 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
mistachkinb56660f2016-07-14 21:26:09 +00002050 Tcl_AppendResult( interp, "cannot convert \"",
drha198f2b2014-02-07 19:26:13 +00002051 Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
drhfb7e7652005-01-24 00:28:42 +00002052 return TCL_ERROR;
2053 }else{
2054 if( n<0 ){
2055 flushStmtCache( pDb );
2056 n = 0;
2057 }else if( n>MAX_PREPARED_STMTS ){
2058 n = MAX_PREPARED_STMTS;
2059 }
2060 pDb->maxStmt = n;
2061 }
2062 }
2063 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002064 Tcl_AppendResult( interp, "bad option \"",
drha198f2b2014-02-07 19:26:13 +00002065 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
2066 (char*)0);
drhfb7e7652005-01-24 00:28:42 +00002067 return TCL_ERROR;
2068 }
2069 break;
2070 }
2071
danielk1977b28af712004-06-21 06:50:26 +00002072 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00002073 **
2074 ** Return the number of rows that were modified, inserted, or deleted by
mistachkinb56660f2016-07-14 21:26:09 +00002075 ** the most recent INSERT, UPDATE or DELETE statement, not including
danielk1977b28af712004-06-21 06:50:26 +00002076 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00002077 */
2078 case DB_CHANGES: {
2079 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00002080 if( objc!=2 ){
2081 Tcl_WrongNumArgs(interp, 2, objv, "");
2082 return TCL_ERROR;
2083 }
drhc8d30ac2002-04-12 10:08:59 +00002084 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00002085 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00002086 break;
2087 }
2088
drh75897232000-05-29 14:26:00 +00002089 /* $db close
2090 **
2091 ** Shutdown the database
2092 */
drh6d313162000-09-21 13:01:35 +00002093 case DB_CLOSE: {
2094 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
2095 break;
2096 }
drh75897232000-05-29 14:26:00 +00002097
drh0f14e2e2004-06-29 12:39:08 +00002098 /*
2099 ** $db collate NAME SCRIPT
2100 **
2101 ** Create a new SQL collation function called NAME. Whenever
2102 ** that function is called, invoke SCRIPT to evaluate the function.
2103 */
2104 case DB_COLLATE: {
2105 SqlCollate *pCollate;
2106 char *zName;
2107 char *zScript;
2108 int nScript;
2109 if( objc!=4 ){
2110 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
2111 return TCL_ERROR;
2112 }
2113 zName = Tcl_GetStringFromObj(objv[2], 0);
2114 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
2115 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
2116 if( pCollate==0 ) return TCL_ERROR;
2117 pCollate->interp = interp;
2118 pCollate->pNext = pDb->pCollate;
2119 pCollate->zScript = (char*)&pCollate[1];
2120 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00002121 memcpy(pCollate->zScript, zScript, nScript+1);
mistachkinb56660f2016-07-14 21:26:09 +00002122 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
drh0f14e2e2004-06-29 12:39:08 +00002123 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00002124 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00002125 return TCL_ERROR;
2126 }
2127 break;
2128 }
2129
2130 /*
2131 ** $db collation_needed SCRIPT
2132 **
2133 ** Create a new SQL collation function called NAME. Whenever
2134 ** that function is called, invoke SCRIPT to evaluate the function.
2135 */
2136 case DB_COLLATION_NEEDED: {
2137 if( objc!=3 ){
2138 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
2139 return TCL_ERROR;
2140 }
2141 if( pDb->pCollateNeeded ){
2142 Tcl_DecrRefCount(pDb->pCollateNeeded);
2143 }
2144 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
2145 Tcl_IncrRefCount(pDb->pCollateNeeded);
2146 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
2147 break;
2148 }
2149
drh19e2d372005-08-29 23:00:03 +00002150 /* $db commit_hook ?CALLBACK?
2151 **
2152 ** Invoke the given callback just before committing every SQL transaction.
2153 ** If the callback throws an exception or returns non-zero, then the
2154 ** transaction is aborted. If CALLBACK is an empty string, the callback
2155 ** is disabled.
2156 */
2157 case DB_COMMIT_HOOK: {
2158 if( objc>3 ){
2159 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2160 return TCL_ERROR;
2161 }else if( objc==2 ){
2162 if( pDb->zCommit ){
drha198f2b2014-02-07 19:26:13 +00002163 Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002164 }
2165 }else{
mistachkin6ef5e122014-01-24 17:03:55 +00002166 const char *zCommit;
drh19e2d372005-08-29 23:00:03 +00002167 int len;
2168 if( pDb->zCommit ){
2169 Tcl_Free(pDb->zCommit);
2170 }
2171 zCommit = Tcl_GetStringFromObj(objv[2], &len);
2172 if( zCommit && len>0 ){
2173 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002174 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00002175 }else{
2176 pDb->zCommit = 0;
2177 }
2178 if( pDb->zCommit ){
2179 pDb->interp = interp;
2180 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
2181 }else{
2182 sqlite3_commit_hook(pDb->db, 0, 0);
2183 }
2184 }
2185 break;
2186 }
2187
drh75897232000-05-29 14:26:00 +00002188 /* $db complete SQL
2189 **
2190 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2191 ** additional lines of input are needed. This is similar to the
2192 ** built-in "info complete" command of Tcl.
2193 */
drh6d313162000-09-21 13:01:35 +00002194 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00002195#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00002196 Tcl_Obj *pResult;
2197 int isComplete;
2198 if( objc!=3 ){
2199 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00002200 return TCL_ERROR;
2201 }
danielk19776f8a5032004-05-10 10:34:51 +00002202 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00002203 pResult = Tcl_GetObjResult(interp);
2204 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00002205#endif
drh6d313162000-09-21 13:01:35 +00002206 break;
2207 }
drhdcd997e2003-01-31 17:21:49 +00002208
drh19e2d372005-08-29 23:00:03 +00002209 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2210 **
2211 ** Copy data into table from filename, optionally using SEPARATOR
2212 ** as column separators. If a column contains a null string, or the
2213 ** value of NULLINDICATOR, a NULL is inserted for the column.
2214 ** conflict-algorithm is one of the sqlite conflict algorithms:
2215 ** rollback, abort, fail, ignore, replace
2216 ** On success, return the number of lines processed, not necessarily same
2217 ** as 'db changes' due to conflict-algorithm selected.
2218 **
2219 ** This code is basically an implementation/enhancement of
2220 ** the sqlite3 shell.c ".import" command.
2221 **
2222 ** This command usage is equivalent to the sqlite2.x COPY statement,
2223 ** which imports file data into a table using the PostgreSQL COPY file format:
2224 ** $db copy $conflit_algo $table_name $filename \t \\N
2225 */
2226 case DB_COPY: {
2227 char *zTable; /* Insert data into this table */
2228 char *zFile; /* The file from which to extract data */
2229 char *zConflict; /* The conflict algorithm to use */
2230 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00002231 int nCol; /* Number of columns in the table */
2232 int nByte; /* Number of bytes in an SQL string */
2233 int i, j; /* Loop counters */
2234 int nSep; /* Number of bytes in zSep[] */
2235 int nNull; /* Number of bytes in zNull[] */
2236 char *zSql; /* An SQL statement */
2237 char *zLine; /* A single line of input from the file */
2238 char **azCol; /* zLine[] broken up into columns */
mistachkin6ef5e122014-01-24 17:03:55 +00002239 const char *zCommit; /* How to commit changes */
drh19e2d372005-08-29 23:00:03 +00002240 FILE *in; /* The input file */
2241 int lineno = 0; /* Line number of input file */
2242 char zLineNum[80]; /* Line number print buffer */
2243 Tcl_Obj *pResult; /* interp result */
2244
mistachkin6ef5e122014-01-24 17:03:55 +00002245 const char *zSep;
2246 const char *zNull;
drh19e2d372005-08-29 23:00:03 +00002247 if( objc<5 || objc>7 ){
mistachkinb56660f2016-07-14 21:26:09 +00002248 Tcl_WrongNumArgs(interp, 2, objv,
drh19e2d372005-08-29 23:00:03 +00002249 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2250 return TCL_ERROR;
2251 }
2252 if( objc>=6 ){
2253 zSep = Tcl_GetStringFromObj(objv[5], 0);
2254 }else{
2255 zSep = "\t";
2256 }
2257 if( objc>=7 ){
2258 zNull = Tcl_GetStringFromObj(objv[6], 0);
2259 }else{
2260 zNull = "";
2261 }
2262 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2263 zTable = Tcl_GetStringFromObj(objv[3], 0);
2264 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002265 nSep = strlen30(zSep);
2266 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002267 if( nSep==0 ){
drha198f2b2014-02-07 19:26:13 +00002268 Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2269 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002270 return TCL_ERROR;
2271 }
drh3e59c012008-09-23 10:12:13 +00002272 if(strcmp(zConflict, "rollback") != 0 &&
2273 strcmp(zConflict, "abort" ) != 0 &&
2274 strcmp(zConflict, "fail" ) != 0 &&
2275 strcmp(zConflict, "ignore" ) != 0 &&
2276 strcmp(zConflict, "replace" ) != 0 ) {
mistachkinb56660f2016-07-14 21:26:09 +00002277 Tcl_AppendResult(interp, "Error: \"", zConflict,
drh19e2d372005-08-29 23:00:03 +00002278 "\", conflict-algorithm must be one of: rollback, "
drha198f2b2014-02-07 19:26:13 +00002279 "abort, fail, ignore, or replace", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002280 return TCL_ERROR;
2281 }
2282 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2283 if( zSql==0 ){
drha198f2b2014-02-07 19:26:13 +00002284 Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002285 return TCL_ERROR;
2286 }
drh4f21c4a2008-12-10 22:15:00 +00002287 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002288 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002289 sqlite3_free(zSql);
2290 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002291 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002292 nCol = 0;
2293 }else{
2294 nCol = sqlite3_column_count(pStmt);
2295 }
2296 sqlite3_finalize(pStmt);
2297 if( nCol==0 ) {
2298 return TCL_ERROR;
2299 }
2300 zSql = malloc( nByte + 50 + nCol*2 );
2301 if( zSql==0 ) {
drha198f2b2014-02-07 19:26:13 +00002302 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002303 return TCL_ERROR;
2304 }
2305 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2306 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002307 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002308 for(i=1; i<nCol; i++){
2309 zSql[j++] = ',';
2310 zSql[j++] = '?';
2311 }
2312 zSql[j++] = ')';
2313 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002314 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002315 free(zSql);
2316 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002317 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002318 sqlite3_finalize(pStmt);
2319 return TCL_ERROR;
2320 }
2321 in = fopen(zFile, "rb");
2322 if( in==0 ){
drhea8f0a12017-01-12 11:50:08 +00002323 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002324 sqlite3_finalize(pStmt);
2325 return TCL_ERROR;
2326 }
2327 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2328 if( azCol==0 ) {
drha198f2b2014-02-07 19:26:13 +00002329 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh43617e92006-03-06 20:55:46 +00002330 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002331 return TCL_ERROR;
2332 }
drh37527852006-03-16 16:19:56 +00002333 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002334 zCommit = "COMMIT";
2335 while( (zLine = local_getline(0, in))!=0 ){
2336 char *z;
drh19e2d372005-08-29 23:00:03 +00002337 lineno++;
2338 azCol[0] = zLine;
2339 for(i=0, z=zLine; *z; z++){
2340 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2341 *z = 0;
2342 i++;
2343 if( i<nCol ){
2344 azCol[i] = &z[nSep];
2345 z += nSep-1;
2346 }
2347 }
2348 }
2349 if( i+1!=nCol ){
2350 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002351 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002352 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002353 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002354 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002355 "Error: %s line %d: expected %d columns of data but found %d",
2356 zFile, lineno, nCol, i+1);
drha198f2b2014-02-07 19:26:13 +00002357 Tcl_AppendResult(interp, zErr, (char*)0);
drhc1f44942006-05-10 14:39:13 +00002358 free(zErr);
2359 }
drh19e2d372005-08-29 23:00:03 +00002360 zCommit = "ROLLBACK";
2361 break;
2362 }
2363 for(i=0; i<nCol; i++){
2364 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002365 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
mistachkinb56660f2016-07-14 21:26:09 +00002366 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002367 ){
drh19e2d372005-08-29 23:00:03 +00002368 sqlite3_bind_null(pStmt, i+1);
2369 }else{
2370 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2371 }
2372 }
2373 sqlite3_step(pStmt);
2374 rc = sqlite3_reset(pStmt);
2375 free(zLine);
2376 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00002377 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002378 zCommit = "ROLLBACK";
2379 break;
2380 }
2381 }
2382 free(azCol);
2383 fclose(in);
2384 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002385 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002386
2387 if( zCommit[0] == 'C' ){
2388 /* success, set result as number of lines processed */
2389 pResult = Tcl_GetObjResult(interp);
2390 Tcl_SetIntObj(pResult, lineno);
2391 rc = TCL_OK;
2392 }else{
2393 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002394 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drha198f2b2014-02-07 19:26:13 +00002395 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2396 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002397 rc = TCL_ERROR;
2398 }
2399 break;
2400 }
2401
drhdcd997e2003-01-31 17:21:49 +00002402 /*
drh41449052006-07-06 17:08:48 +00002403 ** $db enable_load_extension BOOLEAN
2404 **
2405 ** Turn the extension loading feature on or off. It if off by
2406 ** default.
2407 */
2408 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002409#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002410 int onoff;
2411 if( objc!=3 ){
2412 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2413 return TCL_ERROR;
2414 }
2415 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2416 return TCL_ERROR;
2417 }
2418 sqlite3_enable_load_extension(pDb->db, onoff);
2419 break;
drhf533acc2006-12-19 18:57:11 +00002420#else
2421 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
drha198f2b2014-02-07 19:26:13 +00002422 (char*)0);
drhf533acc2006-12-19 18:57:11 +00002423 return TCL_ERROR;
2424#endif
drh41449052006-07-06 17:08:48 +00002425 }
2426
2427 /*
drhdcd997e2003-01-31 17:21:49 +00002428 ** $db errorcode
2429 **
2430 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002431 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002432 */
2433 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002434 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002435 break;
2436 }
dan4a4c11a2009-10-06 14:59:02 +00002437
2438 /*
2439 ** $db exists $sql
2440 ** $db onecolumn $sql
2441 **
2442 ** The onecolumn method is the equivalent of:
2443 ** lindex [$db eval $sql] 0
2444 */
mistachkinb56660f2016-07-14 21:26:09 +00002445 case DB_EXISTS:
dan4a4c11a2009-10-06 14:59:02 +00002446 case DB_ONECOLUMN: {
drhedc40242016-06-13 12:34:38 +00002447 Tcl_Obj *pResult = 0;
dan4a4c11a2009-10-06 14:59:02 +00002448 DbEvalContext sEval;
2449 if( objc!=3 ){
2450 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2451 return TCL_ERROR;
2452 }
2453
2454 dbEvalInit(&sEval, pDb, objv[2], 0);
2455 rc = dbEvalStep(&sEval);
2456 if( choice==DB_ONECOLUMN ){
2457 if( rc==TCL_OK ){
drhedc40242016-06-13 12:34:38 +00002458 pResult = dbEvalColumnValue(&sEval, 0);
dand5f12cd2011-08-18 17:47:57 +00002459 }else if( rc==TCL_BREAK ){
2460 Tcl_ResetResult(interp);
dan4a4c11a2009-10-06 14:59:02 +00002461 }
2462 }else if( rc==TCL_BREAK || rc==TCL_OK ){
drhedc40242016-06-13 12:34:38 +00002463 pResult = Tcl_NewBooleanObj(rc==TCL_OK);
dan4a4c11a2009-10-06 14:59:02 +00002464 }
2465 dbEvalFinalize(&sEval);
drhedc40242016-06-13 12:34:38 +00002466 if( pResult ) Tcl_SetObjResult(interp, pResult);
dan4a4c11a2009-10-06 14:59:02 +00002467
2468 if( rc==TCL_BREAK ){
2469 rc = TCL_OK;
2470 }
2471 break;
2472 }
mistachkinb56660f2016-07-14 21:26:09 +00002473
drh75897232000-05-29 14:26:00 +00002474 /*
drh895d7472004-08-20 16:02:39 +00002475 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002476 **
2477 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002478 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002479 ** If "array" and "code" are omitted, then no callback is every invoked.
2480 ** If "array" is an empty string, then the values are placed in variables
2481 ** that have the same name as the fields extracted by the query.
2482 */
dan4a4c11a2009-10-06 14:59:02 +00002483 case DB_EVAL: {
2484 if( objc<3 || objc>5 ){
2485 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2486 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002487 }
dan4a4c11a2009-10-06 14:59:02 +00002488
drh92febd92004-08-20 18:34:20 +00002489 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002490 DbEvalContext sEval;
2491 Tcl_Obj *pRet = Tcl_NewObj();
2492 Tcl_IncrRefCount(pRet);
2493 dbEvalInit(&sEval, pDb, objv[2], 0);
2494 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2495 int i;
2496 int nCol;
2497 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002498 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002499 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002500 }
2501 }
dan4a4c11a2009-10-06 14:59:02 +00002502 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002503 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002504 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002505 rc = TCL_OK;
2506 }
drh1807ce32004-09-07 13:20:35 +00002507 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002508 }else{
mistachkin8e189222015-04-19 21:43:16 +00002509 ClientData cd2[2];
dan4a4c11a2009-10-06 14:59:02 +00002510 DbEvalContext *p;
2511 Tcl_Obj *pArray = 0;
2512 Tcl_Obj *pScript;
2513
2514 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2515 pArray = objv[3];
2516 }
2517 pScript = objv[objc-1];
2518 Tcl_IncrRefCount(pScript);
mistachkinb56660f2016-07-14 21:26:09 +00002519
dan4a4c11a2009-10-06 14:59:02 +00002520 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2521 dbEvalInit(p, pDb, objv[2], pArray);
2522
mistachkin8e189222015-04-19 21:43:16 +00002523 cd2[0] = (void *)p;
2524 cd2[1] = (void *)pScript;
2525 rc = DbEvalNextCmd(cd2, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002526 }
danielk197730ccda12004-05-27 12:11:31 +00002527 break;
2528 }
drhbec3f402000-08-04 13:49:02 +00002529
2530 /*
dan3df30592015-03-13 08:31:54 +00002531 ** $db function NAME [-argcount N] [-deterministic] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002532 **
2533 ** Create a new SQL function called NAME. Whenever that function is
2534 ** called, invoke SCRIPT to evaluate the function.
2535 */
2536 case DB_FUNCTION: {
dan3df30592015-03-13 08:31:54 +00002537 int flags = SQLITE_UTF8;
drhcabb0812002-09-14 13:47:32 +00002538 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002539 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002540 char *zName;
drhe3602be2008-09-09 12:31:33 +00002541 int nArg = -1;
dan3df30592015-03-13 08:31:54 +00002542 int i;
2543 if( objc<4 ){
2544 Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
2545 return TCL_ERROR;
2546 }
2547 for(i=3; i<(objc-1); i++){
2548 const char *z = Tcl_GetString(objv[i]);
drh4f21c4a2008-12-10 22:15:00 +00002549 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002550 if( n>2 && strncmp(z, "-argcount",n)==0 ){
dan3df30592015-03-13 08:31:54 +00002551 if( i==(objc-2) ){
drhea8f0a12017-01-12 11:50:08 +00002552 Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0);
dan3df30592015-03-13 08:31:54 +00002553 return TCL_ERROR;
2554 }
2555 if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002556 if( nArg<0 ){
2557 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2558 (char*)0);
2559 return TCL_ERROR;
2560 }
dan3df30592015-03-13 08:31:54 +00002561 i++;
2562 }else
2563 if( n>2 && strncmp(z, "-deterministic",n)==0 ){
2564 flags |= SQLITE_DETERMINISTIC;
2565 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002566 Tcl_AppendResult(interp, "bad option \"", z,
drhea8f0a12017-01-12 11:50:08 +00002567 "\": must be -argcount or -deterministic", (char*)0
dan3df30592015-03-13 08:31:54 +00002568 );
2569 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002570 }
drhcabb0812002-09-14 13:47:32 +00002571 }
dan3df30592015-03-13 08:31:54 +00002572
2573 pScript = objv[objc-1];
drhcabb0812002-09-14 13:47:32 +00002574 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002575 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002576 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002577 if( pFunc->pScript ){
2578 Tcl_DecrRefCount(pFunc->pScript);
2579 }
2580 pFunc->pScript = pScript;
2581 Tcl_IncrRefCount(pScript);
2582 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
dan3df30592015-03-13 08:31:54 +00002583 rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
danielk1977d8123362004-06-12 09:25:12 +00002584 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002585 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002586 rc = TCL_ERROR;
2587 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002588 }
drhcabb0812002-09-14 13:47:32 +00002589 break;
2590 }
2591
2592 /*
danielk19778cbadb02007-05-03 16:31:26 +00002593 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002594 */
2595 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002596#ifdef SQLITE_OMIT_INCRBLOB
drha198f2b2014-02-07 19:26:13 +00002597 Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
danielk197732a0d8b2007-05-04 19:03:02 +00002598 return TCL_ERROR;
2599#else
danielk19778cbadb02007-05-03 16:31:26 +00002600 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002601 const char *zDb = "main";
2602 const char *zTable;
2603 const char *zColumn;
drhb3f787f2012-09-29 14:45:54 +00002604 Tcl_WideInt iRow;
danielk1977b4e9af92007-05-01 17:49:49 +00002605
danielk19778cbadb02007-05-03 16:31:26 +00002606 /* Check for the -readonly option */
2607 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2608 isReadonly = 1;
2609 }
2610
2611 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2612 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002613 return TCL_ERROR;
2614 }
2615
danielk19778cbadb02007-05-03 16:31:26 +00002616 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002617 zDb = Tcl_GetString(objv[2]);
2618 }
2619 zTable = Tcl_GetString(objv[objc-3]);
2620 zColumn = Tcl_GetString(objv[objc-2]);
2621 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2622
2623 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002624 rc = createIncrblobChannel(
danedf5b162014-08-19 09:15:41 +00002625 interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
danielk19778cbadb02007-05-03 16:31:26 +00002626 );
danielk1977b4e9af92007-05-01 17:49:49 +00002627 }
danielk197732a0d8b2007-05-04 19:03:02 +00002628#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002629 break;
2630 }
2631
2632 /*
drhf11bded2006-07-17 00:02:44 +00002633 ** $db interrupt
2634 **
2635 ** Interrupt the execution of the inner-most SQL interpreter. This
2636 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2637 */
2638 case DB_INTERRUPT: {
2639 sqlite3_interrupt(pDb->db);
2640 break;
2641 }
2642
2643 /*
drh19e2d372005-08-29 23:00:03 +00002644 ** $db nullvalue ?STRING?
2645 **
2646 ** Change text used when a NULL comes back from the database. If ?STRING?
2647 ** is not present, then the current string used for NULL is returned.
2648 ** If STRING is present, then STRING is returned.
2649 **
2650 */
2651 case DB_NULLVALUE: {
2652 if( objc!=2 && objc!=3 ){
2653 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2654 return TCL_ERROR;
2655 }
2656 if( objc==3 ){
2657 int len;
2658 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2659 if( pDb->zNull ){
2660 Tcl_Free(pDb->zNull);
2661 }
2662 if( zNull && len>0 ){
2663 pDb->zNull = Tcl_Alloc( len + 1 );
drh7fd33922011-06-20 19:00:30 +00002664 memcpy(pDb->zNull, zNull, len);
drh19e2d372005-08-29 23:00:03 +00002665 pDb->zNull[len] = '\0';
2666 }else{
2667 pDb->zNull = 0;
2668 }
2669 }
drhc45e6712012-10-03 11:02:33 +00002670 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
drh19e2d372005-08-29 23:00:03 +00002671 break;
2672 }
2673
2674 /*
mistachkinb56660f2016-07-14 21:26:09 +00002675 ** $db last_insert_rowid
drhaf9ff332002-01-16 21:00:27 +00002676 **
2677 ** Return an integer which is the ROWID for the most recent insert.
2678 */
2679 case DB_LAST_INSERT_ROWID: {
2680 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002681 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002682 if( objc!=2 ){
2683 Tcl_WrongNumArgs(interp, 2, objv, "");
2684 return TCL_ERROR;
2685 }
danielk19776f8a5032004-05-10 10:34:51 +00002686 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002687 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002688 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002689 break;
2690 }
2691
2692 /*
dan4a4c11a2009-10-06 14:59:02 +00002693 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002694 */
drh1807ce32004-09-07 13:20:35 +00002695
2696 /* $db progress ?N CALLBACK?
mistachkinb56660f2016-07-14 21:26:09 +00002697 **
drh1807ce32004-09-07 13:20:35 +00002698 ** Invoke the given callback every N virtual machine opcodes while executing
2699 ** queries.
2700 */
2701 case DB_PROGRESS: {
2702 if( objc==2 ){
2703 if( pDb->zProgress ){
drha198f2b2014-02-07 19:26:13 +00002704 Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
drh1807ce32004-09-07 13:20:35 +00002705 }
2706 }else if( objc==4 ){
2707 char *zProgress;
2708 int len;
2709 int N;
2710 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002711 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002712 };
2713 if( pDb->zProgress ){
2714 Tcl_Free(pDb->zProgress);
2715 }
2716 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2717 if( zProgress && len>0 ){
2718 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002719 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002720 }else{
2721 pDb->zProgress = 0;
2722 }
2723#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2724 if( pDb->zProgress ){
2725 pDb->interp = interp;
2726 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2727 }else{
2728 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2729 }
2730#endif
2731 }else{
2732 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002733 return TCL_ERROR;
2734 }
drh5d9d7572003-08-19 14:31:01 +00002735 break;
2736 }
2737
drh19e2d372005-08-29 23:00:03 +00002738 /* $db profile ?CALLBACK?
2739 **
2740 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2741 ** that has run. The text of the SQL and the amount of elapse time are
2742 ** appended to CALLBACK before the script is run.
2743 */
2744 case DB_PROFILE: {
2745 if( objc>3 ){
2746 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2747 return TCL_ERROR;
2748 }else if( objc==2 ){
2749 if( pDb->zProfile ){
drha198f2b2014-02-07 19:26:13 +00002750 Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002751 }
2752 }else{
2753 char *zProfile;
2754 int len;
2755 if( pDb->zProfile ){
2756 Tcl_Free(pDb->zProfile);
2757 }
2758 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2759 if( zProfile && len>0 ){
2760 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002761 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002762 }else{
2763 pDb->zProfile = 0;
2764 }
drh2eb22af2016-09-10 19:51:40 +00002765#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
2766 !defined(SQLITE_OMIT_DEPRECATED)
drh19e2d372005-08-29 23:00:03 +00002767 if( pDb->zProfile ){
2768 pDb->interp = interp;
2769 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2770 }else{
2771 sqlite3_profile(pDb->db, 0, 0);
2772 }
2773#endif
2774 }
2775 break;
2776 }
2777
drh5d9d7572003-08-19 14:31:01 +00002778 /*
drh22fbcb82004-02-01 01:22:50 +00002779 ** $db rekey KEY
2780 **
2781 ** Change the encryption key on the currently open database.
2782 */
2783 case DB_REKEY: {
drh32f57d42016-03-16 01:03:10 +00002784#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh22fbcb82004-02-01 01:22:50 +00002785 int nKey;
2786 void *pKey;
drhb07028f2011-10-14 21:49:18 +00002787#endif
drh22fbcb82004-02-01 01:22:50 +00002788 if( objc!=3 ){
2789 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2790 return TCL_ERROR;
2791 }
drh32f57d42016-03-16 01:03:10 +00002792#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00002793 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh2011d5f2004-07-22 02:40:37 +00002794 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002795 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002796 Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
drh22fbcb82004-02-01 01:22:50 +00002797 rc = TCL_ERROR;
2798 }
2799#endif
2800 break;
2801 }
2802
drhdc2c4912009-02-04 22:46:47 +00002803 /* $db restore ?DATABASE? FILENAME
2804 **
mistachkinb56660f2016-07-14 21:26:09 +00002805 ** Open a database file named FILENAME. Transfer the content
drhdc2c4912009-02-04 22:46:47 +00002806 ** of FILENAME into the local database DATABASE (default: "main").
2807 */
2808 case DB_RESTORE: {
2809 const char *zSrcFile;
2810 const char *zDestDb;
2811 sqlite3 *pSrc;
2812 sqlite3_backup *pBackup;
2813 int nTimeout = 0;
2814
2815 if( objc==3 ){
2816 zDestDb = "main";
2817 zSrcFile = Tcl_GetString(objv[2]);
2818 }else if( objc==4 ){
2819 zDestDb = Tcl_GetString(objv[2]);
2820 zSrcFile = Tcl_GetString(objv[3]);
2821 }else{
2822 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2823 return TCL_ERROR;
2824 }
drh147ef392016-01-22 23:17:51 +00002825 rc = sqlite3_open_v2(zSrcFile, &pSrc,
2826 SQLITE_OPEN_READONLY | pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00002827 if( rc!=SQLITE_OK ){
2828 Tcl_AppendResult(interp, "cannot open source database: ",
2829 sqlite3_errmsg(pSrc), (char*)0);
2830 sqlite3_close(pSrc);
2831 return TCL_ERROR;
2832 }
2833 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2834 if( pBackup==0 ){
2835 Tcl_AppendResult(interp, "restore failed: ",
2836 sqlite3_errmsg(pDb->db), (char*)0);
2837 sqlite3_close(pSrc);
2838 return TCL_ERROR;
2839 }
2840 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2841 || rc==SQLITE_BUSY ){
2842 if( rc==SQLITE_BUSY ){
2843 if( nTimeout++ >= 3 ) break;
2844 sqlite3_sleep(100);
2845 }
2846 }
2847 sqlite3_backup_finish(pBackup);
2848 if( rc==SQLITE_DONE ){
2849 rc = TCL_OK;
2850 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2851 Tcl_AppendResult(interp, "restore failed: source database busy",
2852 (char*)0);
2853 rc = TCL_ERROR;
2854 }else{
2855 Tcl_AppendResult(interp, "restore failed: ",
2856 sqlite3_errmsg(pDb->db), (char*)0);
2857 rc = TCL_ERROR;
2858 }
2859 sqlite3_close(pSrc);
2860 break;
2861 }
2862
drh22fbcb82004-02-01 01:22:50 +00002863 /*
drh3c379b02010-04-07 19:31:59 +00002864 ** $db status (step|sort|autoindex)
drhd1d38482008-10-07 23:46:38 +00002865 **
mistachkinb56660f2016-07-14 21:26:09 +00002866 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
drhd1d38482008-10-07 23:46:38 +00002867 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2868 */
2869 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002870 int v;
2871 const char *zOp;
2872 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00002873 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00002874 return TCL_ERROR;
2875 }
2876 zOp = Tcl_GetString(objv[2]);
2877 if( strcmp(zOp, "step")==0 ){
2878 v = pDb->nStep;
2879 }else if( strcmp(zOp, "sort")==0 ){
2880 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002881 }else if( strcmp(zOp, "autoindex")==0 ){
2882 v = pDb->nIndex;
drhd1d38482008-10-07 23:46:38 +00002883 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002884 Tcl_AppendResult(interp,
2885 "bad argument: should be autoindex, step, or sort",
drhd1d38482008-10-07 23:46:38 +00002886 (char*)0);
2887 return TCL_ERROR;
2888 }
2889 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2890 break;
2891 }
mistachkinb56660f2016-07-14 21:26:09 +00002892
drhd1d38482008-10-07 23:46:38 +00002893 /*
drhbec3f402000-08-04 13:49:02 +00002894 ** $db timeout MILLESECONDS
2895 **
2896 ** Delay for the number of milliseconds specified when a file is locked.
2897 */
drh6d313162000-09-21 13:01:35 +00002898 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002899 int ms;
drh6d313162000-09-21 13:01:35 +00002900 if( objc!=3 ){
2901 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002902 return TCL_ERROR;
2903 }
drh6d313162000-09-21 13:01:35 +00002904 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002905 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002906 break;
drh75897232000-05-29 14:26:00 +00002907 }
mistachkinb56660f2016-07-14 21:26:09 +00002908
danielk197755c45f22005-04-03 23:54:43 +00002909 /*
drh0f14e2e2004-06-29 12:39:08 +00002910 ** $db total_changes
2911 **
mistachkinb56660f2016-07-14 21:26:09 +00002912 ** Return the number of rows that were modified, inserted, or deleted
drh0f14e2e2004-06-29 12:39:08 +00002913 ** since the database handle was created.
2914 */
2915 case DB_TOTAL_CHANGES: {
2916 Tcl_Obj *pResult;
2917 if( objc!=2 ){
2918 Tcl_WrongNumArgs(interp, 2, objv, "");
2919 return TCL_ERROR;
2920 }
2921 pResult = Tcl_GetObjResult(interp);
2922 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2923 break;
2924 }
2925
drhb5a20d32003-04-23 12:25:23 +00002926 /* $db trace ?CALLBACK?
2927 **
2928 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2929 ** that is executed. The text of the SQL is appended to CALLBACK before
2930 ** it is executed.
2931 */
2932 case DB_TRACE: {
2933 if( objc>3 ){
2934 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002935 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002936 }else if( objc==2 ){
2937 if( pDb->zTrace ){
drha198f2b2014-02-07 19:26:13 +00002938 Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
drhb5a20d32003-04-23 12:25:23 +00002939 }
2940 }else{
2941 char *zTrace;
2942 int len;
2943 if( pDb->zTrace ){
2944 Tcl_Free(pDb->zTrace);
2945 }
2946 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2947 if( zTrace && len>0 ){
2948 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002949 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002950 }else{
2951 pDb->zTrace = 0;
2952 }
drh2eb22af2016-09-10 19:51:40 +00002953#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
2954 !defined(SQLITE_OMIT_DEPRECATED)
drhb5a20d32003-04-23 12:25:23 +00002955 if( pDb->zTrace ){
2956 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002957 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002958 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002959 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002960 }
drh19e2d372005-08-29 23:00:03 +00002961#endif
drhb5a20d32003-04-23 12:25:23 +00002962 }
2963 break;
2964 }
2965
mistachkinb56660f2016-07-14 21:26:09 +00002966 /* $db trace_v2 ?CALLBACK? ?MASK?
2967 **
2968 ** Make arrangements to invoke the CALLBACK routine for each trace event
2969 ** matching the mask that is generated. The parameters are appended to
2970 ** CALLBACK before it is executed.
2971 */
2972 case DB_TRACE_V2: {
2973 if( objc>4 ){
2974 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK? ?MASK?");
2975 return TCL_ERROR;
2976 }else if( objc==2 ){
2977 if( pDb->zTraceV2 ){
2978 Tcl_AppendResult(interp, pDb->zTraceV2, (char*)0);
2979 }
2980 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002981 char *zTraceV2;
2982 int len;
mistachkinb52dcd82016-07-14 23:17:03 +00002983 Tcl_WideInt wMask = 0;
mistachkinb56660f2016-07-14 21:26:09 +00002984 if( objc==4 ){
mistachkinb52dcd82016-07-14 23:17:03 +00002985 static const char *TTYPE_strs[] = {
2986 "statement", "profile", "row", "close", 0
2987 };
2988 enum TTYPE_enum {
2989 TTYPE_STMT, TTYPE_PROFILE, TTYPE_ROW, TTYPE_CLOSE
2990 };
2991 int i;
2992 if( TCL_OK!=Tcl_ListObjLength(interp, objv[3], &len) ){
mistachkinb56660f2016-07-14 21:26:09 +00002993 return TCL_ERROR;
2994 }
mistachkinb52dcd82016-07-14 23:17:03 +00002995 for(i=0; i<len; i++){
2996 Tcl_Obj *pObj;
2997 int ttype;
2998 if( TCL_OK!=Tcl_ListObjIndex(interp, objv[3], i, &pObj) ){
2999 return TCL_ERROR;
3000 }
3001 if( Tcl_GetIndexFromObj(interp, pObj, TTYPE_strs, "trace type",
3002 0, &ttype)!=TCL_OK ){
3003 Tcl_WideInt wType;
3004 Tcl_Obj *pError = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
3005 Tcl_IncrRefCount(pError);
3006 if( TCL_OK==Tcl_GetWideIntFromObj(interp, pObj, &wType) ){
3007 Tcl_DecrRefCount(pError);
3008 wMask |= wType;
3009 }else{
3010 Tcl_SetObjResult(interp, pError);
3011 Tcl_DecrRefCount(pError);
3012 return TCL_ERROR;
3013 }
3014 }else{
3015 switch( (enum TTYPE_enum)ttype ){
3016 case TTYPE_STMT: wMask |= SQLITE_TRACE_STMT; break;
3017 case TTYPE_PROFILE: wMask |= SQLITE_TRACE_PROFILE; break;
3018 case TTYPE_ROW: wMask |= SQLITE_TRACE_ROW; break;
3019 case TTYPE_CLOSE: wMask |= SQLITE_TRACE_CLOSE; break;
3020 }
3021 }
3022 }
mistachkinb56660f2016-07-14 21:26:09 +00003023 }else{
mistachkinb52dcd82016-07-14 23:17:03 +00003024 wMask = SQLITE_TRACE_STMT; /* use the "legacy" default */
mistachkinb56660f2016-07-14 21:26:09 +00003025 }
3026 if( pDb->zTraceV2 ){
3027 Tcl_Free(pDb->zTraceV2);
3028 }
3029 zTraceV2 = Tcl_GetStringFromObj(objv[2], &len);
3030 if( zTraceV2 && len>0 ){
3031 pDb->zTraceV2 = Tcl_Alloc( len + 1 );
3032 memcpy(pDb->zTraceV2, zTraceV2, len+1);
3033 }else{
3034 pDb->zTraceV2 = 0;
3035 }
3036#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3037 if( pDb->zTraceV2 ){
3038 pDb->interp = interp;
3039 sqlite3_trace_v2(pDb->db, (unsigned)wMask, DbTraceV2Handler, pDb);
3040 }else{
3041 sqlite3_trace_v2(pDb->db, 0, 0, 0);
3042 }
3043#endif
3044 }
3045 break;
3046 }
3047
drh3d214232005-08-02 12:21:08 +00003048 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
3049 **
3050 ** Start a new transaction (if we are not already in the midst of a
3051 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
3052 ** completes, either commit the transaction or roll it back if SCRIPT
3053 ** throws an exception. Or if no new transation was started, do nothing.
3054 ** pass the exception on up the stack.
3055 **
3056 ** This command was inspired by Dave Thomas's talk on Ruby at the
3057 ** 2005 O'Reilly Open Source Convention (OSCON).
3058 */
3059 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00003060 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00003061 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00003062 if( objc!=3 && objc!=4 ){
3063 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
3064 return TCL_ERROR;
3065 }
danielk1977cd38d522009-01-02 17:33:46 +00003066
dan4a4c11a2009-10-06 14:59:02 +00003067 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00003068 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00003069 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00003070 };
3071 enum TTYPE_enum {
3072 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
3073 };
3074 int ttype;
drhb5555e72005-08-02 17:15:14 +00003075 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00003076 0, &ttype) ){
3077 return TCL_ERROR;
3078 }
3079 switch( (enum TTYPE_enum)ttype ){
3080 case TTYPE_DEFERRED: /* no-op */; break;
3081 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
3082 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
3083 }
drh3d214232005-08-02 12:21:08 +00003084 }
danielk1977cd38d522009-01-02 17:33:46 +00003085 pScript = objv[objc-1];
3086
dan4a4c11a2009-10-06 14:59:02 +00003087 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00003088 pDb->disableAuth++;
3089 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
3090 pDb->disableAuth--;
3091 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00003092 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977cd38d522009-01-02 17:33:46 +00003093 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00003094 }
danielk1977cd38d522009-01-02 17:33:46 +00003095 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00003096
dan4a4c11a2009-10-06 14:59:02 +00003097 /* If using NRE, schedule a callback to invoke the script pScript, then
3098 ** a second callback to commit (or rollback) the transaction or savepoint
3099 ** opened above. If not using NRE, evaluate the script directly, then
mistachkinb56660f2016-07-14 21:26:09 +00003100 ** call function DbTransPostCmd() to commit (or rollback) the transaction
dan4a4c11a2009-10-06 14:59:02 +00003101 ** or savepoint. */
3102 if( DbUseNre() ){
3103 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
drha47941f2013-12-20 18:57:44 +00003104 (void)Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00003105 }else{
dan4a4c11a2009-10-06 14:59:02 +00003106 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00003107 }
3108 break;
3109 }
3110
danielk197794eb6a12005-12-15 15:22:08 +00003111 /*
danielk1977404ca072009-03-16 13:19:36 +00003112 ** $db unlock_notify ?script?
3113 */
3114 case DB_UNLOCK_NOTIFY: {
3115#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
drha198f2b2014-02-07 19:26:13 +00003116 Tcl_AppendResult(interp, "unlock_notify not available in this build",
3117 (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00003118 rc = TCL_ERROR;
3119#else
3120 if( objc!=2 && objc!=3 ){
3121 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3122 rc = TCL_ERROR;
3123 }else{
3124 void (*xNotify)(void **, int) = 0;
3125 void *pNotifyArg = 0;
3126
3127 if( pDb->pUnlockNotify ){
3128 Tcl_DecrRefCount(pDb->pUnlockNotify);
3129 pDb->pUnlockNotify = 0;
3130 }
mistachkinb56660f2016-07-14 21:26:09 +00003131
danielk1977404ca072009-03-16 13:19:36 +00003132 if( objc==3 ){
3133 xNotify = DbUnlockNotify;
3134 pNotifyArg = (void *)pDb;
3135 pDb->pUnlockNotify = objv[2];
3136 Tcl_IncrRefCount(pDb->pUnlockNotify);
3137 }
mistachkinb56660f2016-07-14 21:26:09 +00003138
danielk1977404ca072009-03-16 13:19:36 +00003139 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
drha198f2b2014-02-07 19:26:13 +00003140 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00003141 rc = TCL_ERROR;
3142 }
3143 }
3144#endif
3145 break;
3146 }
3147
drh304637c2011-03-18 16:47:27 +00003148 /*
3149 ** $db preupdate_hook count
3150 ** $db preupdate_hook hook ?SCRIPT?
3151 ** $db preupdate_hook new INDEX
3152 ** $db preupdate_hook old INDEX
3153 */
dan46c47d42011-03-01 18:42:07 +00003154 case DB_PREUPDATE: {
drh9b1c62d2011-03-30 21:04:43 +00003155#ifndef SQLITE_ENABLE_PREUPDATE_HOOK
dan2b519ab2016-12-06 19:33:42 +00003156 Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time",
3157 (char*)0);
drh9b1c62d2011-03-30 21:04:43 +00003158 rc = TCL_ERROR;
3159#else
dan1e7a2d42011-03-22 18:45:29 +00003160 static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
dan46c47d42011-03-01 18:42:07 +00003161 enum DbPreupdateSubCmd {
dan1e7a2d42011-03-22 18:45:29 +00003162 PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
dan46c47d42011-03-01 18:42:07 +00003163 };
3164 int iSub;
3165
3166 if( objc<3 ){
3167 Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
3168 }
3169 if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
3170 return TCL_ERROR;
3171 }
3172
3173 switch( (enum DbPreupdateSubCmd)iSub ){
3174 case PRE_COUNT: {
3175 int nCol = sqlite3_preupdate_count(pDb->db);
3176 Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
3177 break;
3178 }
3179
3180 case PRE_HOOK: {
3181 if( objc>4 ){
3182 Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
3183 return TCL_ERROR;
3184 }
3185 DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
3186 break;
3187 }
3188
dan1e7a2d42011-03-22 18:45:29 +00003189 case PRE_DEPTH: {
3190 Tcl_Obj *pRet;
3191 if( objc!=3 ){
3192 Tcl_WrongNumArgs(interp, 3, objv, "");
3193 return TCL_ERROR;
3194 }
3195 pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
3196 Tcl_SetObjResult(interp, pRet);
3197 break;
3198 }
3199
dan37db03b2011-03-16 19:59:18 +00003200 case PRE_NEW:
dan46c47d42011-03-01 18:42:07 +00003201 case PRE_OLD: {
3202 int iIdx;
dan37db03b2011-03-16 19:59:18 +00003203 sqlite3_value *pValue;
dan46c47d42011-03-01 18:42:07 +00003204 if( objc!=4 ){
3205 Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
3206 return TCL_ERROR;
3207 }
3208 if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
3209 return TCL_ERROR;
3210 }
3211
dan37db03b2011-03-16 19:59:18 +00003212 if( iSub==PRE_OLD ){
dan46c47d42011-03-01 18:42:07 +00003213 rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
dan37db03b2011-03-16 19:59:18 +00003214 }else{
3215 assert( iSub==PRE_NEW );
3216 rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
dan46c47d42011-03-01 18:42:07 +00003217 }
3218
dan37db03b2011-03-16 19:59:18 +00003219 if( rc==SQLITE_OK ){
drh304637c2011-03-18 16:47:27 +00003220 Tcl_Obj *pObj;
3221 pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
dan37db03b2011-03-16 19:59:18 +00003222 Tcl_SetObjResult(interp, pObj);
3223 }else{
drhea8f0a12017-01-12 11:50:08 +00003224 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
dan46c47d42011-03-01 18:42:07 +00003225 return TCL_ERROR;
3226 }
3227 }
3228 }
drh9b1c62d2011-03-30 21:04:43 +00003229#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +00003230 break;
3231 }
3232
danielk1977404ca072009-03-16 13:19:36 +00003233 /*
drh833bf962010-04-28 14:42:19 +00003234 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003235 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00003236 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003237 */
mistachkinb56660f2016-07-14 21:26:09 +00003238 case DB_WAL_HOOK:
3239 case DB_UPDATE_HOOK:
dan6566ebe2011-03-16 09:49:14 +00003240 case DB_ROLLBACK_HOOK: {
mistachkinb56660f2016-07-14 21:26:09 +00003241 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
danielk197771fd80b2005-12-16 06:54:01 +00003242 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3243 */
mistachkinb56660f2016-07-14 21:26:09 +00003244 Tcl_Obj **ppHook = 0;
dan46c47d42011-03-01 18:42:07 +00003245 if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
3246 if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
3247 if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
3248 if( objc>3 ){
danielk197794eb6a12005-12-15 15:22:08 +00003249 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3250 return TCL_ERROR;
3251 }
danielk197771fd80b2005-12-16 06:54:01 +00003252
dan46c47d42011-03-01 18:42:07 +00003253 DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00003254 break;
3255 }
3256
danielk19774397de52005-01-12 12:44:03 +00003257 /* $db version
3258 **
3259 ** Return the version string for this database.
3260 */
3261 case DB_VERSION: {
3262 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
3263 break;
3264 }
3265
tpoindex1067fe12004-12-17 15:41:11 +00003266
drh6d313162000-09-21 13:01:35 +00003267 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00003268 return rc;
drh75897232000-05-29 14:26:00 +00003269}
3270
drha2c8a952009-10-13 18:38:34 +00003271#if SQLITE_TCL_NRE
3272/*
3273** Adaptor that provides an objCmd interface to the NRE-enabled
3274** interface implementation.
3275*/
mistachkina121cc72016-07-28 18:06:52 +00003276static int SQLITE_TCLAPI DbObjCmdAdaptor(
drha2c8a952009-10-13 18:38:34 +00003277 void *cd,
3278 Tcl_Interp *interp,
3279 int objc,
3280 Tcl_Obj *const*objv
3281){
3282 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
3283}
3284#endif /* SQLITE_TCL_NRE */
3285
drh75897232000-05-29 14:26:00 +00003286/*
drh3570ad92007-08-31 14:31:44 +00003287** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00003288** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00003289**
3290** This is the main Tcl command. When the "sqlite" Tcl command is
3291** invoked, this routine runs to process that command.
3292**
3293** The first argument, DBNAME, is an arbitrary name for a new
3294** database connection. This command creates a new command named
3295** DBNAME that is used to control that connection. The database
3296** connection is deleted when the DBNAME command is deleted.
3297**
drh3570ad92007-08-31 14:31:44 +00003298** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00003299**
drh75897232000-05-29 14:26:00 +00003300*/
mistachkin7617e4a2016-07-28 17:11:20 +00003301static int SQLITE_TCLAPI DbMain(
3302 void *cd,
3303 Tcl_Interp *interp,
3304 int objc,
3305 Tcl_Obj *const*objv
3306){
drhbec3f402000-08-04 13:49:02 +00003307 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00003308 const char *zArg;
drh75897232000-05-29 14:26:00 +00003309 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00003310 int i;
drh22fbcb82004-02-01 01:22:50 +00003311 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00003312 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00003313 int flags;
drh882e8e42006-08-24 02:42:27 +00003314 Tcl_DString translatedFilename;
drh32f57d42016-03-16 01:03:10 +00003315#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00003316 void *pKey = 0;
3317 int nKey = 0;
3318#endif
mistachkin540ebf82012-09-10 07:29:29 +00003319 int rc;
drhd9da78a2009-03-24 15:08:09 +00003320
3321 /* In normal use, each TCL interpreter runs in a single thread. So
3322 ** by default, we can turn of mutexing on SQLite database connections.
3323 ** However, for testing purposes it is useful to have mutexes turned
3324 ** on. So, by default, mutexes default off. But if compiled with
3325 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3326 */
3327#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3328 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3329#else
3330 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3331#endif
3332
drh22fbcb82004-02-01 01:22:50 +00003333 if( objc==2 ){
3334 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00003335 if( strcmp(zArg,"-version")==0 ){
drha198f2b2014-02-07 19:26:13 +00003336 Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
drh647cb0e2002-11-04 19:32:25 +00003337 return TCL_OK;
3338 }
drh72bf6a32016-01-07 02:06:55 +00003339 if( strcmp(zArg,"-sourceid")==0 ){
3340 Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0);
3341 return TCL_OK;
3342 }
drh9eb9e262004-02-11 02:18:05 +00003343 if( strcmp(zArg,"-has-codec")==0 ){
drh32f57d42016-03-16 01:03:10 +00003344#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drha198f2b2014-02-07 19:26:13 +00003345 Tcl_AppendResult(interp,"1",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003346#else
drha198f2b2014-02-07 19:26:13 +00003347 Tcl_AppendResult(interp,"0",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003348#endif
3349 return TCL_OK;
3350 }
drhfbc3eab2001-04-06 16:13:42 +00003351 }
drh3570ad92007-08-31 14:31:44 +00003352 for(i=3; i+1<objc; i+=2){
3353 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00003354 if( strcmp(zArg,"-key")==0 ){
drh32f57d42016-03-16 01:03:10 +00003355#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh3570ad92007-08-31 14:31:44 +00003356 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
drhb07028f2011-10-14 21:49:18 +00003357#endif
drh3570ad92007-08-31 14:31:44 +00003358 }else if( strcmp(zArg, "-vfs")==0 ){
dan3c3dd7b2010-06-22 11:10:40 +00003359 zVfs = Tcl_GetString(objv[i+1]);
drh3570ad92007-08-31 14:31:44 +00003360 }else if( strcmp(zArg, "-readonly")==0 ){
3361 int b;
3362 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3363 if( b ){
drh33f4e022007-09-03 15:19:34 +00003364 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00003365 flags |= SQLITE_OPEN_READONLY;
3366 }else{
3367 flags &= ~SQLITE_OPEN_READONLY;
3368 flags |= SQLITE_OPEN_READWRITE;
3369 }
3370 }else if( strcmp(zArg, "-create")==0 ){
3371 int b;
3372 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00003373 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00003374 flags |= SQLITE_OPEN_CREATE;
3375 }else{
3376 flags &= ~SQLITE_OPEN_CREATE;
3377 }
danielk19779a6284c2008-07-10 17:52:49 +00003378 }else if( strcmp(zArg, "-nomutex")==0 ){
3379 int b;
3380 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3381 if( b ){
3382 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00003383 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00003384 }else{
3385 flags &= ~SQLITE_OPEN_NOMUTEX;
3386 }
danc431fd52011-06-27 16:55:50 +00003387 }else if( strcmp(zArg, "-fullmutex")==0 ){
drh039963a2008-09-03 00:43:15 +00003388 int b;
3389 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3390 if( b ){
3391 flags |= SQLITE_OPEN_FULLMUTEX;
3392 flags &= ~SQLITE_OPEN_NOMUTEX;
3393 }else{
3394 flags &= ~SQLITE_OPEN_FULLMUTEX;
3395 }
drhf12b3f62011-12-21 14:42:29 +00003396 }else if( strcmp(zArg, "-uri")==0 ){
3397 int b;
3398 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3399 if( b ){
3400 flags |= SQLITE_OPEN_URI;
3401 }else{
3402 flags &= ~SQLITE_OPEN_URI;
3403 }
drh3570ad92007-08-31 14:31:44 +00003404 }else{
3405 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3406 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00003407 }
3408 }
drh3570ad92007-08-31 14:31:44 +00003409 if( objc<3 || (objc&1)!=1 ){
mistachkinb56660f2016-07-14 21:26:09 +00003410 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00003411 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh68bd4aa2012-01-13 16:16:10 +00003412 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
drh32f57d42016-03-16 01:03:10 +00003413#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh3570ad92007-08-31 14:31:44 +00003414 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00003415#endif
3416 );
drh75897232000-05-29 14:26:00 +00003417 return TCL_ERROR;
3418 }
drh75897232000-05-29 14:26:00 +00003419 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003420 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drhbec3f402000-08-04 13:49:02 +00003421 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00003422 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00003423 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003424 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00003425 Tcl_DStringFree(&translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003426 if( p->db ){
3427 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3428 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3429 sqlite3_close(p->db);
3430 p->db = 0;
3431 }
3432 }else{
mistachkin5dac8432012-09-11 02:00:25 +00003433 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
danielk197780290862004-05-22 09:21:21 +00003434 }
drh32f57d42016-03-16 01:03:10 +00003435#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhf3a65f72007-08-22 20:18:21 +00003436 if( p->db ){
3437 sqlite3_key(p->db, pKey, nKey);
3438 }
drheb8ed702004-02-11 10:37:23 +00003439#endif
drhbec3f402000-08-04 13:49:02 +00003440 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003441 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003442 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003443 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003444 return TCL_ERROR;
3445 }
drhfb7e7652005-01-24 00:28:42 +00003446 p->maxStmt = NUM_PREPARED_STMTS;
drh147ef392016-01-22 23:17:51 +00003447 p->openFlags = flags & SQLITE_OPEN_URI;
drh5169bbc2006-08-24 14:59:45 +00003448 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003449 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003450 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003451 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3452 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003453 }else{
3454 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3455 }
drh75897232000-05-29 14:26:00 +00003456 return TCL_OK;
3457}
3458
3459/*
drh90ca9752001-09-28 17:47:14 +00003460** Provide a dummy Tcl_InitStubs if we are using this as a static
3461** library.
3462*/
3463#ifndef USE_TCL_STUBS
3464# undef Tcl_InitStubs
drh0e85ccf2013-06-03 12:34:46 +00003465# define Tcl_InitStubs(a,b,c) TCL_VERSION
drh90ca9752001-09-28 17:47:14 +00003466#endif
3467
3468/*
drh29bc4612005-10-05 10:40:15 +00003469** Make sure we have a PACKAGE_VERSION macro defined. This will be
3470** defined automatically by the TEA makefile. But other makefiles
3471** do not define it.
3472*/
3473#ifndef PACKAGE_VERSION
3474# define PACKAGE_VERSION SQLITE_VERSION
3475#endif
3476
3477/*
drh75897232000-05-29 14:26:00 +00003478** Initialize this module.
3479**
3480** This Tcl module contains only a single new Tcl command named "sqlite".
3481** (Hence there is no namespace. There is no point in using a namespace
3482** if the extension only supplies one new name!) The "sqlite" command is
3483** used to open a new SQLite database. See the DbMain() routine above
3484** for additional information.
drhb652f432010-08-26 16:46:57 +00003485**
3486** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003487*/
drhb652f432010-08-26 16:46:57 +00003488EXTERN int Sqlite3_Init(Tcl_Interp *interp){
mistachkin27b2f052015-01-12 19:49:46 +00003489 int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
drh6dc8cbe2013-05-31 15:36:07 +00003490 if( rc==TCL_OK ){
3491 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh1cca0d22010-08-25 20:35:51 +00003492#ifndef SQLITE_3_SUFFIX_ONLY
drh6dc8cbe2013-05-31 15:36:07 +00003493 /* The "sqlite" alias is undocumented. It is here only to support
3494 ** legacy scripts. All new scripts should use only the "sqlite3"
3495 ** command. */
3496 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003497#endif
drh6dc8cbe2013-05-31 15:36:07 +00003498 rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3499 }
3500 return rc;
drh90ca9752001-09-28 17:47:14 +00003501}
drhb652f432010-08-26 16:46:57 +00003502EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
drhb652f432010-08-26 16:46:57 +00003503EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3504EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00003505
drhd878cab2012-03-20 15:10:42 +00003506/* Because it accesses the file-system and uses persistent state, SQLite
drhe75a9eb2016-02-13 18:54:10 +00003507** is not considered appropriate for safe interpreters. Hence, we cause
3508** the _SafeInit() interfaces return TCL_ERROR.
drhd878cab2012-03-20 15:10:42 +00003509*/
drhe75a9eb2016-02-13 18:54:10 +00003510EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
3511EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
3512
3513
drh49766d62005-01-08 18:42:28 +00003514
3515#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003516int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3517int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
dana3e63c42010-08-20 12:33:59 +00003518int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3519int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00003520#endif
drh75897232000-05-29 14:26:00 +00003521
drh3e27c022004-07-23 00:01:38 +00003522#ifdef TCLSH
3523/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003524** All of the code that follows is used to build standalone TCL interpreters
3525** that are statically linked with SQLite. Enable these by compiling
3526** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3527** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3528** analysis program.
drh75897232000-05-29 14:26:00 +00003529*/
drh348784e2000-05-29 20:41:49 +00003530
drh57a02272009-10-22 20:52:05 +00003531#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3532/*
3533 * This code implements the MD5 message-digest algorithm.
3534 * The algorithm is due to Ron Rivest. This code was
3535 * written by Colin Plumb in 1993, no copyright is claimed.
3536 * This code is in the public domain; do with it what you wish.
3537 *
3538 * Equivalent code is available from RSA Data Security, Inc.
3539 * This code has been tested against that, and is equivalent,
3540 * except that you don't need to include two pages of legalese
3541 * with every copy.
3542 *
3543 * To compute the message digest of a chunk of bytes, declare an
3544 * MD5Context structure, pass it to MD5Init, call MD5Update as
3545 * needed on buffers full of bytes, and then call MD5Final, which
3546 * will fill a supplied 16-byte array with the digest.
3547 */
3548
3549/*
3550 * If compiled on a machine that doesn't have a 32-bit integer,
3551 * you just set "uint32" to the appropriate datatype for an
3552 * unsigned 32-bit integer. For example:
3553 *
3554 * cc -Duint32='unsigned long' md5.c
3555 *
3556 */
3557#ifndef uint32
3558# define uint32 unsigned int
3559#endif
3560
3561struct MD5Context {
3562 int isInit;
3563 uint32 buf[4];
3564 uint32 bits[2];
3565 unsigned char in[64];
3566};
3567typedef struct MD5Context MD5Context;
3568
3569/*
3570 * Note: this code is harmless on little-endian machines.
3571 */
3572static void byteReverse (unsigned char *buf, unsigned longs){
3573 uint32 t;
3574 do {
3575 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3576 ((unsigned)buf[1]<<8 | buf[0]);
3577 *(uint32 *)buf = t;
3578 buf += 4;
3579 } while (--longs);
3580}
3581/* The four core functions - F1 is optimized somewhat */
3582
3583/* #define F1(x, y, z) (x & y | ~x & z) */
3584#define F1(x, y, z) (z ^ (x & (y ^ z)))
3585#define F2(x, y, z) F1(z, x, y)
3586#define F3(x, y, z) (x ^ y ^ z)
3587#define F4(x, y, z) (y ^ (x | ~z))
3588
3589/* This is the central step in the MD5 algorithm. */
3590#define MD5STEP(f, w, x, y, z, data, s) \
3591 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3592
3593/*
3594 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3595 * reflect the addition of 16 longwords of new data. MD5Update blocks
3596 * the data and converts bytes into longwords for this routine.
3597 */
3598static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3599 register uint32 a, b, c, d;
3600
3601 a = buf[0];
3602 b = buf[1];
3603 c = buf[2];
3604 d = buf[3];
3605
3606 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3607 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3608 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3609 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3610 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3611 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3612 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3613 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3614 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3615 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3616 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3617 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3618 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3619 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3620 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3621 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3622
3623 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3624 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3625 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3626 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3627 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3628 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3629 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3630 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3631 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3632 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3633 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3634 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3635 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3636 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3637 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3638 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3639
3640 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3641 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3642 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3643 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3644 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3645 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3646 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3647 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3648 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3649 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3650 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3651 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3652 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3653 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3654 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3655 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3656
3657 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3658 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3659 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3660 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3661 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3662 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3663 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3664 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3665 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3666 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3667 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3668 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3669 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3670 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3671 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3672 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3673
3674 buf[0] += a;
3675 buf[1] += b;
3676 buf[2] += c;
3677 buf[3] += d;
3678}
3679
3680/*
3681 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3682 * initialization constants.
3683 */
3684static void MD5Init(MD5Context *ctx){
3685 ctx->isInit = 1;
3686 ctx->buf[0] = 0x67452301;
3687 ctx->buf[1] = 0xefcdab89;
3688 ctx->buf[2] = 0x98badcfe;
3689 ctx->buf[3] = 0x10325476;
3690 ctx->bits[0] = 0;
3691 ctx->bits[1] = 0;
3692}
3693
3694/*
3695 * Update context to reflect the concatenation of another buffer full
3696 * of bytes.
3697 */
mistachkinb56660f2016-07-14 21:26:09 +00003698static
drh57a02272009-10-22 20:52:05 +00003699void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3700 uint32 t;
3701
3702 /* Update bitcount */
3703
3704 t = ctx->bits[0];
3705 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3706 ctx->bits[1]++; /* Carry from low to high */
3707 ctx->bits[1] += len >> 29;
3708
3709 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3710
3711 /* Handle any leading odd-sized chunks */
3712
3713 if ( t ) {
3714 unsigned char *p = (unsigned char *)ctx->in + t;
3715
3716 t = 64-t;
3717 if (len < t) {
3718 memcpy(p, buf, len);
3719 return;
3720 }
3721 memcpy(p, buf, t);
3722 byteReverse(ctx->in, 16);
3723 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3724 buf += t;
3725 len -= t;
3726 }
3727
3728 /* Process data in 64-byte chunks */
3729
3730 while (len >= 64) {
3731 memcpy(ctx->in, buf, 64);
3732 byteReverse(ctx->in, 16);
3733 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3734 buf += 64;
3735 len -= 64;
3736 }
3737
3738 /* Handle any remaining bytes of data. */
3739
3740 memcpy(ctx->in, buf, len);
3741}
3742
3743/*
mistachkinb56660f2016-07-14 21:26:09 +00003744 * Final wrapup - pad to 64-byte boundary with the bit pattern
drh57a02272009-10-22 20:52:05 +00003745 * 1 0* (64-bit count of bits processed, MSB-first)
3746 */
3747static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3748 unsigned count;
3749 unsigned char *p;
3750
3751 /* Compute number of bytes mod 64 */
3752 count = (ctx->bits[0] >> 3) & 0x3F;
3753
3754 /* Set the first char of padding to 0x80. This is safe since there is
3755 always at least one byte free */
3756 p = ctx->in + count;
3757 *p++ = 0x80;
3758
3759 /* Bytes of padding needed to make 64 bytes */
3760 count = 64 - 1 - count;
3761
3762 /* Pad out to 56 mod 64 */
3763 if (count < 8) {
3764 /* Two lots of padding: Pad the first block to 64 bytes */
3765 memset(p, 0, count);
3766 byteReverse(ctx->in, 16);
3767 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3768
3769 /* Now fill the next block with 56 bytes */
3770 memset(ctx->in, 0, 56);
3771 } else {
3772 /* Pad block to 56 bytes */
3773 memset(p, 0, count-8);
3774 }
3775 byteReverse(ctx->in, 14);
3776
3777 /* Append length in bits and transform */
drha47941f2013-12-20 18:57:44 +00003778 memcpy(ctx->in + 14*4, ctx->bits, 8);
drh57a02272009-10-22 20:52:05 +00003779
3780 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3781 byteReverse((unsigned char *)ctx->buf, 4);
3782 memcpy(digest, ctx->buf, 16);
drh57a02272009-10-22 20:52:05 +00003783}
3784
3785/*
3786** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3787*/
3788static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3789 static char const zEncode[] = "0123456789abcdef";
3790 int i, j;
3791
3792 for(j=i=0; i<16; i++){
3793 int a = digest[i];
3794 zBuf[j++] = zEncode[(a>>4)&0xf];
3795 zBuf[j++] = zEncode[a & 0xf];
3796 }
3797 zBuf[j] = 0;
3798}
3799
3800
3801/*
3802** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3803** each representing 16 bits of the digest and separated from each
3804** other by a "-" character.
3805*/
3806static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3807 int i, j;
3808 unsigned int x;
3809 for(i=j=0; i<16; i+=2){
3810 x = digest[i]*256 + digest[i+1];
3811 if( i>0 ) zDigest[j++] = '-';
drh05f6c672015-02-26 16:32:33 +00003812 sqlite3_snprintf(50-j, &zDigest[j], "%05u", x);
drh57a02272009-10-22 20:52:05 +00003813 j += 5;
3814 }
3815 zDigest[j] = 0;
3816}
3817
3818/*
3819** A TCL command for md5. The argument is the text to be hashed. The
mistachkinb56660f2016-07-14 21:26:09 +00003820** Result is the hash in base64.
drh57a02272009-10-22 20:52:05 +00003821*/
mistachkin44e95d42016-07-28 22:23:26 +00003822static int SQLITE_TCLAPI md5_cmd(
3823 void*cd,
3824 Tcl_Interp *interp,
3825 int argc,
3826 const char **argv
3827){
drh57a02272009-10-22 20:52:05 +00003828 MD5Context ctx;
3829 unsigned char digest[16];
3830 char zBuf[50];
3831 void (*converter)(unsigned char*, char*);
3832
3833 if( argc!=2 ){
mistachkinb56660f2016-07-14 21:26:09 +00003834 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
drha198f2b2014-02-07 19:26:13 +00003835 " TEXT\"", (char*)0);
drh57a02272009-10-22 20:52:05 +00003836 return TCL_ERROR;
3837 }
3838 MD5Init(&ctx);
3839 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3840 MD5Final(digest, &ctx);
3841 converter = (void(*)(unsigned char*,char*))cd;
3842 converter(digest, zBuf);
3843 Tcl_AppendResult(interp, zBuf, (char*)0);
3844 return TCL_OK;
3845}
3846
3847/*
3848** A TCL command to take the md5 hash of a file. The argument is the
3849** name of the file.
3850*/
mistachkin44e95d42016-07-28 22:23:26 +00003851static int SQLITE_TCLAPI md5file_cmd(
3852 void*cd,
3853 Tcl_Interp *interp,
3854 int argc,
3855 const char **argv
3856){
drh57a02272009-10-22 20:52:05 +00003857 FILE *in;
3858 MD5Context ctx;
3859 void (*converter)(unsigned char*, char*);
3860 unsigned char digest[16];
3861 char zBuf[10240];
3862
3863 if( argc!=2 ){
mistachkinb56660f2016-07-14 21:26:09 +00003864 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
drha198f2b2014-02-07 19:26:13 +00003865 " FILENAME\"", (char*)0);
drh57a02272009-10-22 20:52:05 +00003866 return TCL_ERROR;
3867 }
3868 in = fopen(argv[1],"rb");
3869 if( in==0 ){
mistachkinb56660f2016-07-14 21:26:09 +00003870 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
drha198f2b2014-02-07 19:26:13 +00003871 "\" for reading", (char*)0);
drh57a02272009-10-22 20:52:05 +00003872 return TCL_ERROR;
3873 }
3874 MD5Init(&ctx);
3875 for(;;){
3876 int n;
drh83cc1392012-04-19 18:04:28 +00003877 n = (int)fread(zBuf, 1, sizeof(zBuf), in);
drh57a02272009-10-22 20:52:05 +00003878 if( n<=0 ) break;
3879 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3880 }
3881 fclose(in);
3882 MD5Final(digest, &ctx);
3883 converter = (void(*)(unsigned char*,char*))cd;
3884 converter(digest, zBuf);
3885 Tcl_AppendResult(interp, zBuf, (char*)0);
3886 return TCL_OK;
3887}
3888
3889/*
3890** Register the four new TCL commands for generating MD5 checksums
3891** with the TCL interpreter.
3892*/
3893int Md5_Init(Tcl_Interp *interp){
3894 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3895 MD5DigestToBase16, 0);
3896 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3897 MD5DigestToBase10x8, 0);
3898 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3899 MD5DigestToBase16, 0);
3900 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3901 MD5DigestToBase10x8, 0);
3902 return TCL_OK;
3903}
3904#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3905
3906#if defined(SQLITE_TEST)
3907/*
3908** During testing, the special md5sum() aggregate function is available.
3909** inside SQLite. The following routines implement that function.
3910*/
3911static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3912 MD5Context *p;
3913 int i;
3914 if( argc<1 ) return;
3915 p = sqlite3_aggregate_context(context, sizeof(*p));
3916 if( p==0 ) return;
3917 if( !p->isInit ){
3918 MD5Init(p);
3919 }
3920 for(i=0; i<argc; i++){
3921 const char *zData = (char*)sqlite3_value_text(argv[i]);
3922 if( zData ){
drh83cc1392012-04-19 18:04:28 +00003923 MD5Update(p, (unsigned char*)zData, (int)strlen(zData));
drh57a02272009-10-22 20:52:05 +00003924 }
3925 }
3926}
3927static void md5finalize(sqlite3_context *context){
3928 MD5Context *p;
3929 unsigned char digest[16];
3930 char zBuf[33];
3931 p = sqlite3_aggregate_context(context, sizeof(*p));
3932 MD5Final(digest,p);
3933 MD5DigestToBase16(digest, zBuf);
3934 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3935}
mistachkin44e95d42016-07-28 22:23:26 +00003936int Md5_Register(
3937 sqlite3 *db,
3938 char **pzErrMsg,
mistachkin85bd9822016-07-28 22:53:10 +00003939 const sqlite3_api_routines *pThunk
mistachkin44e95d42016-07-28 22:23:26 +00003940){
mistachkinb56660f2016-07-14 21:26:09 +00003941 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
drh57a02272009-10-22 20:52:05 +00003942 md5step, md5finalize);
3943 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3944 return rc;
3945}
3946#endif /* defined(SQLITE_TEST) */
3947
3948
drh348784e2000-05-29 20:41:49 +00003949/*
drh3e27c022004-07-23 00:01:38 +00003950** If the macro TCLSH is one, then put in code this for the
3951** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003952** standard input, or if a file is named on the command line
3953** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003954*/
drh3e27c022004-07-23 00:01:38 +00003955#if TCLSH==1
dan0ae479d2011-09-21 16:43:07 +00003956static const char *tclsh_main_loop(void){
3957 static const char zMainloop[] =
3958 "set line {}\n"
3959 "while {![eof stdin]} {\n"
3960 "if {$line!=\"\"} {\n"
3961 "puts -nonewline \"> \"\n"
3962 "} else {\n"
3963 "puts -nonewline \"% \"\n"
drh348784e2000-05-29 20:41:49 +00003964 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003965 "flush stdout\n"
3966 "append line [gets stdin]\n"
3967 "if {[info complete $line]} {\n"
3968 "if {[catch {uplevel #0 $line} result]} {\n"
3969 "puts stderr \"Error: $result\"\n"
3970 "} elseif {$result!=\"\"} {\n"
3971 "puts $result\n"
3972 "}\n"
3973 "set line {}\n"
3974 "} else {\n"
3975 "append line \\n\n"
3976 "}\n"
drh348784e2000-05-29 20:41:49 +00003977 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003978 ;
3979 return zMainloop;
3980}
drh3e27c022004-07-23 00:01:38 +00003981#endif
drh3a0f13f2010-07-12 16:47:48 +00003982#if TCLSH==2
dan0ae479d2011-09-21 16:43:07 +00003983static const char *tclsh_main_loop(void);
drh3a0f13f2010-07-12 16:47:48 +00003984#endif
drh3e27c022004-07-23 00:01:38 +00003985
danc1a60c52010-06-07 14:28:16 +00003986#ifdef SQLITE_TEST
3987static void init_all(Tcl_Interp *);
mistachkin7617e4a2016-07-28 17:11:20 +00003988static int SQLITE_TCLAPI init_all_cmd(
danc1a60c52010-06-07 14:28:16 +00003989 ClientData cd,
3990 Tcl_Interp *interp,
3991 int objc,
3992 Tcl_Obj *CONST objv[]
3993){
danielk19770a549072009-02-17 16:29:10 +00003994
danc1a60c52010-06-07 14:28:16 +00003995 Tcl_Interp *slave;
3996 if( objc!=2 ){
3997 Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3998 return TCL_ERROR;
3999 }
4000
4001 slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
4002 if( !slave ){
4003 return TCL_ERROR;
4004 }
4005
4006 init_all(slave);
4007 return TCL_OK;
4008}
danc431fd52011-06-27 16:55:50 +00004009
4010/*
4011** Tclcmd: db_use_legacy_prepare DB BOOLEAN
4012**
4013** The first argument to this command must be a database command created by
4014** [sqlite3]. If the second argument is true, then the handle is configured
4015** to use the sqlite3_prepare_v2() function to prepare statements. If it
4016** is false, sqlite3_prepare().
4017*/
mistachkin7617e4a2016-07-28 17:11:20 +00004018static int SQLITE_TCLAPI db_use_legacy_prepare_cmd(
danc431fd52011-06-27 16:55:50 +00004019 ClientData cd,
4020 Tcl_Interp *interp,
4021 int objc,
4022 Tcl_Obj *CONST objv[]
4023){
4024 Tcl_CmdInfo cmdInfo;
4025 SqliteDb *pDb;
4026 int bPrepare;
4027
4028 if( objc!=3 ){
4029 Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
4030 return TCL_ERROR;
4031 }
4032
4033 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
4034 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
4035 return TCL_ERROR;
4036 }
4037 pDb = (SqliteDb*)cmdInfo.objClientData;
4038 if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
4039 return TCL_ERROR;
4040 }
4041
4042 pDb->bLegacyPrepare = bPrepare;
4043
4044 Tcl_ResetResult(interp);
4045 return TCL_OK;
4046}
dan04489b62014-10-31 20:11:32 +00004047
4048/*
4049** Tclcmd: db_last_stmt_ptr DB
4050**
4051** If the statement cache associated with database DB is not empty,
4052** return the text representation of the most recently used statement
4053** handle.
4054*/
mistachkin7617e4a2016-07-28 17:11:20 +00004055static int SQLITE_TCLAPI db_last_stmt_ptr(
dan04489b62014-10-31 20:11:32 +00004056 ClientData cd,
4057 Tcl_Interp *interp,
4058 int objc,
4059 Tcl_Obj *CONST objv[]
4060){
4061 extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
4062 Tcl_CmdInfo cmdInfo;
4063 SqliteDb *pDb;
4064 sqlite3_stmt *pStmt = 0;
4065 char zBuf[100];
4066
4067 if( objc!=2 ){
4068 Tcl_WrongNumArgs(interp, 1, objv, "DB");
4069 return TCL_ERROR;
4070 }
4071
4072 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
4073 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
4074 return TCL_ERROR;
4075 }
4076 pDb = (SqliteDb*)cmdInfo.objClientData;
4077
4078 if( pDb->stmtList ) pStmt = pDb->stmtList->pStmt;
4079 if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ){
4080 return TCL_ERROR;
4081 }
4082 Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
4083
4084 return TCL_OK;
4085}
drh1a4a6802015-05-04 18:31:09 +00004086#endif /* SQLITE_TEST */
4087
danc1a60c52010-06-07 14:28:16 +00004088/*
4089** Configure the interpreter passed as the first argument to have access
4090** to the commands and linked variables that make up:
4091**
mistachkinb56660f2016-07-14 21:26:09 +00004092** * the [sqlite3] extension itself,
danc1a60c52010-06-07 14:28:16 +00004093**
4094** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
4095**
4096** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
4097** test suite.
4098*/
4099static void init_all(Tcl_Interp *interp){
drh38f82712004-06-18 17:10:16 +00004100 Sqlite3_Init(interp);
danc1a60c52010-06-07 14:28:16 +00004101
drh57a02272009-10-22 20:52:05 +00004102#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
4103 Md5_Init(interp);
4104#endif
danc1a60c52010-06-07 14:28:16 +00004105
drhd9b02572001-04-15 00:37:09 +00004106#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00004107 {
drh2f999a62007-08-15 19:16:43 +00004108 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00004109 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00004110 extern int Sqlitetest2_Init(Tcl_Interp*);
4111 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00004112 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00004113 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00004114 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00004115 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00004116 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00004117 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00004118 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00004119 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
danb391b942014-11-07 14:41:11 +00004120 extern int Sqlitetest_blob_Init(Tcl_Interp*);
dan0a7a9152010-04-07 07:57:38 +00004121 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
drh984bfaa2008-03-19 16:08:53 +00004122 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00004123 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00004124 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00004125 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00004126 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00004127 extern int Sqlitetestschema_Init(Tcl_Interp*);
4128 extern int Sqlitetestsse_Init(Tcl_Interp*);
4129 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
dan9f5ff372013-01-11 09:58:54 +00004130 extern int Sqlitetestfs_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00004131 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00004132 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00004133 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00004134 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh522efc62009-11-10 17:24:37 +00004135 extern int Sqlitetestintarray_Init(Tcl_Interp*);
danc7991bd2010-05-05 19:04:59 +00004136 extern int Sqlitetestvfs_Init(Tcl_Interp *);
dan9508daa2010-08-28 18:58:00 +00004137 extern int Sqlitetestrtree_Init(Tcl_Interp*);
dan8cf35eb2010-09-01 11:40:05 +00004138 extern int Sqlitequota_Init(Tcl_Interp*);
shaneh8a922f72010-11-04 20:50:27 +00004139 extern int Sqlitemultiplex_Init(Tcl_Interp*);
dane336b002010-11-19 18:20:09 +00004140 extern int SqliteSuperlock_Init(Tcl_Interp*);
dan213ca0a2011-03-28 19:10:06 +00004141 extern int SqlitetestSyscall_Init(Tcl_Interp*);
drh9b1c62d2011-03-30 21:04:43 +00004142#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
dan4fccf432011-03-08 19:22:50 +00004143 extern int TestSession_Init(Tcl_Interp*);
4144#endif
dan89a89562014-12-01 20:05:00 +00004145 extern int Fts5tcl_Init(Tcl_Interp *);
drhcfb8f8d2015-07-23 20:44:49 +00004146 extern int SqliteRbu_Init(Tcl_Interp*);
dan8e4251b2016-03-01 18:07:43 +00004147 extern int Sqlitetesttcl_Init(Tcl_Interp*);
dan6764a702011-06-20 11:15:06 +00004148#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00004149 extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
4150#endif
4151
danb29010c2010-12-29 18:24:38 +00004152#ifdef SQLITE_ENABLE_ZIPVFS
4153 extern int Zipvfs_Init(Tcl_Interp*);
4154 Zipvfs_Init(interp);
4155#endif
4156
drh2f999a62007-08-15 19:16:43 +00004157 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00004158 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00004159 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00004160 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00004161 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00004162 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00004163 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00004164 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00004165 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00004166 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00004167 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00004168 Sqlitetest_autoext_Init(interp);
danb391b942014-11-07 14:41:11 +00004169 Sqlitetest_blob_Init(interp);
dan0a7a9152010-04-07 07:57:38 +00004170 Sqlitetest_demovfs_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00004171 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00004172 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00004173 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00004174 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00004175 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00004176 Sqlitetestschema_Init(interp);
4177 Sqlitetesttclvar_Init(interp);
dan9f5ff372013-01-11 09:58:54 +00004178 Sqlitetestfs_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00004179 SqlitetestThread_Init(interp);
mistachkin52b1dbb2016-07-28 14:37:04 +00004180 SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00004181 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00004182 Sqlitetestbackup_Init(interp);
drh522efc62009-11-10 17:24:37 +00004183 Sqlitetestintarray_Init(interp);
danc7991bd2010-05-05 19:04:59 +00004184 Sqlitetestvfs_Init(interp);
dan9508daa2010-08-28 18:58:00 +00004185 Sqlitetestrtree_Init(interp);
dan8cf35eb2010-09-01 11:40:05 +00004186 Sqlitequota_Init(interp);
shaneh8a922f72010-11-04 20:50:27 +00004187 Sqlitemultiplex_Init(interp);
dane336b002010-11-19 18:20:09 +00004188 SqliteSuperlock_Init(interp);
dan213ca0a2011-03-28 19:10:06 +00004189 SqlitetestSyscall_Init(interp);
drh9b1c62d2011-03-30 21:04:43 +00004190#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
dan4fccf432011-03-08 19:22:50 +00004191 TestSession_Init(interp);
4192#endif
dan89a89562014-12-01 20:05:00 +00004193 Fts5tcl_Init(interp);
drhcfb8f8d2015-07-23 20:44:49 +00004194 SqliteRbu_Init(interp);
dan8e4251b2016-03-01 18:07:43 +00004195 Sqlitetesttcl_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00004196
dan6764a702011-06-20 11:15:06 +00004197#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00004198 Sqlitetestfts3_Init(interp);
4199#endif
drh2e66f0b2005-04-28 17:18:48 +00004200
danc431fd52011-06-27 16:55:50 +00004201 Tcl_CreateObjCommand(
4202 interp, "load_testfixture_extensions", init_all_cmd, 0, 0
4203 );
4204 Tcl_CreateObjCommand(
4205 interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
4206 );
dan04489b62014-10-31 20:11:32 +00004207 Tcl_CreateObjCommand(
4208 interp, "db_last_stmt_ptr", db_last_stmt_ptr, 0, 0
4209 );
danc1a60c52010-06-07 14:28:16 +00004210
drh3e27c022004-07-23 00:01:38 +00004211#ifdef SQLITE_SSE
drh348784e2000-05-29 20:41:49 +00004212 Sqlitetestsse_Init(interp);
4213#endif
4214 }
drh61212b62004-12-02 20:17:00 +00004215#endif
danc1a60c52010-06-07 14:28:16 +00004216}
4217
drhdb6bafa2015-01-09 21:54:58 +00004218/* Needed for the setrlimit() system call on unix */
4219#if defined(unix)
4220#include <sys/resource.h>
4221#endif
4222
danc1a60c52010-06-07 14:28:16 +00004223#define TCLSH_MAIN main /* Needed to fake out mktclapp */
mistachkin69def7f2016-07-28 04:14:37 +00004224int SQLITE_CDECL TCLSH_MAIN(int argc, char **argv){
danc1a60c52010-06-07 14:28:16 +00004225 Tcl_Interp *interp;
mistachkin1f28e072013-08-15 08:06:15 +00004226
4227#if !defined(_WIN32_WCE)
4228 if( getenv("BREAK") ){
4229 fprintf(stderr,
4230 "attach debugger to process %d and press any key to continue.\n",
4231 GETPID());
4232 fgetc(stdin);
4233 }
4234#endif
4235
drhdb6bafa2015-01-09 21:54:58 +00004236 /* Since the primary use case for this binary is testing of SQLite,
4237 ** be sure to generate core files if we crash */
4238#if defined(SQLITE_TEST) && defined(unix)
4239 { struct rlimit x;
4240 getrlimit(RLIMIT_CORE, &x);
4241 x.rlim_cur = x.rlim_max;
4242 setrlimit(RLIMIT_CORE, &x);
4243 }
4244#endif /* SQLITE_TEST && unix */
4245
4246
danc1a60c52010-06-07 14:28:16 +00004247 /* Call sqlite3_shutdown() once before doing anything else. This is to
4248 ** test that sqlite3_shutdown() can be safely called by a process before
4249 ** sqlite3_initialize() is. */
4250 sqlite3_shutdown();
4251
dan0ae479d2011-09-21 16:43:07 +00004252 Tcl_FindExecutable(argv[0]);
mistachkin2953ba92014-02-14 00:25:03 +00004253 Tcl_SetSystemEncoding(NULL, "utf-8");
dan0ae479d2011-09-21 16:43:07 +00004254 interp = Tcl_CreateInterp();
4255
drh3a0f13f2010-07-12 16:47:48 +00004256#if TCLSH==2
4257 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
4258#endif
danc1a60c52010-06-07 14:28:16 +00004259
danc1a60c52010-06-07 14:28:16 +00004260 init_all(interp);
drhc7285972009-11-10 01:13:25 +00004261 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00004262 int i;
shessad42c3a2006-08-22 23:53:46 +00004263 char zArgc[32];
4264 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
4265 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00004266 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
4267 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
4268 for(i=3-TCLSH; i<argc; i++){
4269 Tcl_SetVar(interp, "argv", argv[i],
4270 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
4271 }
drh3a0f13f2010-07-12 16:47:48 +00004272 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00004273 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00004274 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00004275 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00004276 return 1;
4277 }
drh3e27c022004-07-23 00:01:38 +00004278 }
drh3a0f13f2010-07-12 16:47:48 +00004279 if( TCLSH==2 || argc<=1 ){
dan0ae479d2011-09-21 16:43:07 +00004280 Tcl_GlobalEval(interp, tclsh_main_loop());
drh348784e2000-05-29 20:41:49 +00004281 }
4282 return 0;
4283}
4284#endif /* TCLSH */