blob: e5984ec804ce507117197c39bbf083687b82d3a5 [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**
drh96a206f2017-10-13 20:14:06 +000017** -DTCLSH Add a "main()" routine that works as a tclsh.
drh57a02272009-10-22 20:52:05 +000018**
drh96a206f2017-10-13 20:14:06 +000019** -DTCLSH_INIT_PROC=name
drh57a02272009-10-22 20:52:05 +000020**
drh96a206f2017-10-13 20:14:06 +000021** Invoke name(interp) to initialize the Tcl interpreter.
22** If name(interp) returns a non-NULL string, then run
23** that string as a Tcl script to launch the application.
24** If name(interp) returns NULL, then run the regular
25** tclsh-emulator code.
drh75897232000-05-29 14:26:00 +000026*/
drh96a206f2017-10-13 20:14:06 +000027#ifdef TCLSH_INIT_PROC
28# define TCLSH 1
29#endif
mistachkin27b2f052015-01-12 19:49:46 +000030
31/*
32** If requested, include the SQLite compiler options file for MSVC.
33*/
34#if defined(INCLUDE_MSVC_H)
mistachkin52b1dbb2016-07-28 14:37:04 +000035# include "msvc.h"
mistachkin27b2f052015-01-12 19:49:46 +000036#endif
37
mistachkin52b1dbb2016-07-28 14:37:04 +000038#if defined(INCLUDE_SQLITE_TCL_H)
39# include "sqlite_tcl.h"
40#else
41# include "tcl.h"
mistachkin7617e4a2016-07-28 17:11:20 +000042# ifndef SQLITE_TCLAPI
43# define SQLITE_TCLAPI
44# endif
mistachkin52b1dbb2016-07-28 14:37:04 +000045#endif
danielk1977b4e9af92007-05-01 17:49:49 +000046#include <errno.h>
drhbd08af42007-04-05 21:58:33 +000047
48/*
49** Some additional include files are needed if this file is not
50** appended to the amalgamation.
51*/
52#ifndef SQLITE_AMALGAMATION
drh65e8c822009-12-01 13:57:48 +000053# include "sqlite3.h"
drhbd08af42007-04-05 21:58:33 +000054# include <stdlib.h>
55# include <string.h>
56# include <assert.h>
drh65e8c822009-12-01 13:57:48 +000057 typedef unsigned char u8;
drhbd08af42007-04-05 21:58:33 +000058#endif
drheb206382009-10-24 15:51:33 +000059#include <ctype.h>
drh75897232000-05-29 14:26:00 +000060
mistachkin1f28e072013-08-15 08:06:15 +000061/* Used to get the current process ID */
62#if !defined(_WIN32)
63# include <unistd.h>
64# define GETPID getpid
65#elif !defined(_WIN32_WCE)
66# ifndef SQLITE_AMALGAMATION
mistachkin176b3a02018-01-23 07:11:05 +000067# ifndef WIN32_LEAN_AND_MEAN
68# define WIN32_LEAN_AND_MEAN
69# endif
mistachkin1f28e072013-08-15 08:06:15 +000070# include <windows.h>
71# endif
72# define GETPID (int)GetCurrentProcessId
73#endif
74
drhad6e1372006-07-10 21:15:51 +000075/*
76 * Windows needs to know which symbols to export. Unix does not.
77 * BUILD_sqlite should be undefined for Unix.
78 */
79#ifdef BUILD_sqlite
80#undef TCL_STORAGE_CLASS
81#define TCL_STORAGE_CLASS DLLEXPORT
82#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000083
danielk1977a21c6b62005-01-24 10:25:59 +000084#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000085#define MAX_PREPARED_STMTS 100
86
drhc45e6712012-10-03 11:02:33 +000087/* Forward declaration */
88typedef struct SqliteDb SqliteDb;
drh98808ba2001-10-18 12:34:46 +000089
90/*
drhcabb0812002-09-14 13:47:32 +000091** New SQL functions can be created as TCL scripts. Each such function
92** is described by an instance of the following structure.
93*/
94typedef struct SqlFunc SqlFunc;
95struct SqlFunc {
96 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000097 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
drhc45e6712012-10-03 11:02:33 +000098 SqliteDb *pDb; /* Database connection that owns this function */
drhd1e47332005-06-26 17:55:33 +000099 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
100 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +0000101 SqlFunc *pNext; /* Next function on the list of them all */
102};
103
104/*
danielk19770202b292004-06-09 09:55:16 +0000105** New collation sequences function can be created as TCL scripts. Each such
106** function is described by an instance of the following structure.
107*/
108typedef struct SqlCollate SqlCollate;
109struct SqlCollate {
110 Tcl_Interp *interp; /* The TCL interpret to execute the function */
111 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +0000112 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +0000113};
114
115/*
drhfb7e7652005-01-24 00:28:42 +0000116** Prepared statements are cached for faster execution. Each prepared
117** statement is described by an instance of the following structure.
118*/
119typedef struct SqlPreparedStmt SqlPreparedStmt;
120struct SqlPreparedStmt {
121 SqlPreparedStmt *pNext; /* Next in linked list */
122 SqlPreparedStmt *pPrev; /* Previous on the list */
123 sqlite3_stmt *pStmt; /* The prepared statement */
124 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +0000125 const char *zSql; /* Text of the SQL statement */
dan4a4c11a2009-10-06 14:59:02 +0000126 int nParm; /* Size of apParm array */
127 Tcl_Obj **apParm; /* Array of referenced object pointers */
drhfb7e7652005-01-24 00:28:42 +0000128};
129
danielk1977d04417962007-05-02 13:16:30 +0000130typedef struct IncrblobChannel IncrblobChannel;
131
drhfb7e7652005-01-24 00:28:42 +0000132/*
drhbec3f402000-08-04 13:49:02 +0000133** There is one instance of this structure for each SQLite database
134** that has been opened by the SQLite TCL interface.
danc431fd52011-06-27 16:55:50 +0000135**
136** If this module is built with SQLITE_TEST defined (to create the SQLite
137** testfixture executable), then it may be configured to use either
138** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
139** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
drhbec3f402000-08-04 13:49:02 +0000140*/
drhbec3f402000-08-04 13:49:02 +0000141struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000142 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000143 Tcl_Interp *interp; /* The interpreter used for this database */
144 char *zBusy; /* The busy callback routine */
145 char *zCommit; /* The commit hook callback routine */
146 char *zTrace; /* The trace callback routine */
mistachkinb56660f2016-07-14 21:26:09 +0000147 char *zTraceV2; /* The trace_v2 callback routine */
drh19e2d372005-08-29 23:00:03 +0000148 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000149 char *zProgress; /* The progress callback routine */
150 char *zAuth; /* The authorization callback routine */
drh1f1549f2008-08-26 21:33:34 +0000151 int disableAuth; /* Disable the authorizer if it exists */
drhd1e47332005-06-26 17:55:33 +0000152 char *zNull; /* Text to substitute for an SQL NULL value */
153 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000154 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
dan46c47d42011-03-01 18:42:07 +0000155 Tcl_Obj *pPreUpdateHook; /* Pre-update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000156 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drh5def0842010-05-05 20:00:25 +0000157 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000158 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000159 SqlCollate *pCollate; /* List of SQL collation functions */
160 int rc; /* Return code of most recent sqlite3_exec() */
161 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000162 SqlPreparedStmt *stmtList; /* List of prepared statements*/
163 SqlPreparedStmt *stmtLast; /* Last statement in the list */
164 int maxStmt; /* The next maximum number of stmtList */
165 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000166 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh3c379b02010-04-07 19:31:59 +0000167 int nStep, nSort, nIndex; /* Statistics for most recent operation */
danc456a762017-06-22 16:51:16 +0000168 int nVMStep; /* Another statistic for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000169 int nTransaction; /* Number of nested [transaction] methods */
drh147ef392016-01-22 23:17:51 +0000170 int openFlags; /* Flags used to open. (SQLITE_OPEN_URI) */
danc431fd52011-06-27 16:55:50 +0000171#ifdef SQLITE_TEST
172 int bLegacyPrepare; /* True to use sqlite3_prepare() */
173#endif
drh98808ba2001-10-18 12:34:46 +0000174};
drh297ecf12001-04-05 15:57:13 +0000175
danielk1977b4e9af92007-05-01 17:49:49 +0000176struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000177 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000178 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000179 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000180 Tcl_Channel channel; /* Channel identifier */
181 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
182 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000183};
184
drhea678832008-12-10 19:26:22 +0000185/*
186** Compute a string length that is limited to what can be stored in
187** lower 30 bits of a 32-bit signed integer.
188*/
drh4f21c4a2008-12-10 22:15:00 +0000189static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000190 const char *z2 = z;
191 while( *z2 ){ z2++; }
192 return 0x3fffffff & (int)(z2 - z);
193}
drhea678832008-12-10 19:26:22 +0000194
195
danielk197732a0d8b2007-05-04 19:03:02 +0000196#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000197/*
danielk1977d04417962007-05-02 13:16:30 +0000198** Close all incrblob channels opened using database connection pDb.
199** This is called when shutting down the database connection.
200*/
201static void closeIncrblobChannels(SqliteDb *pDb){
202 IncrblobChannel *p;
203 IncrblobChannel *pNext;
204
205 for(p=pDb->pIncrblob; p; p=pNext){
206 pNext = p->pNext;
207
mistachkinb56660f2016-07-14 21:26:09 +0000208 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
danielk1977d04417962007-05-02 13:16:30 +0000209 ** which deletes the IncrblobChannel structure at *p. So do not
210 ** call Tcl_Free() here.
211 */
212 Tcl_UnregisterChannel(pDb->interp, p->channel);
213 }
214}
215
216/*
danielk1977b4e9af92007-05-01 17:49:49 +0000217** Close an incremental blob channel.
218*/
mistachkin7617e4a2016-07-28 17:11:20 +0000219static int SQLITE_TCLAPI incrblobClose(
220 ClientData instanceData,
221 Tcl_Interp *interp
222){
danielk1977b4e9af92007-05-01 17:49:49 +0000223 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000224 int rc = sqlite3_blob_close(p->pBlob);
225 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000226
227 /* Remove the channel from the SqliteDb.pIncrblob list. */
228 if( p->pNext ){
229 p->pNext->pPrev = p->pPrev;
230 }
231 if( p->pPrev ){
232 p->pPrev->pNext = p->pNext;
233 }
234 if( p->pDb->pIncrblob==p ){
235 p->pDb->pIncrblob = p->pNext;
236 }
237
danielk197792d4d7a2007-05-04 12:05:56 +0000238 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000239 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000240
241 if( rc!=SQLITE_OK ){
242 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
243 return TCL_ERROR;
244 }
danielk1977b4e9af92007-05-01 17:49:49 +0000245 return TCL_OK;
246}
247
248/*
249** Read data from an incremental blob channel.
250*/
mistachkin7617e4a2016-07-28 17:11:20 +0000251static int SQLITE_TCLAPI incrblobInput(
mistachkinb56660f2016-07-14 21:26:09 +0000252 ClientData instanceData,
253 char *buf,
danielk1977b4e9af92007-05-01 17:49:49 +0000254 int bufSize,
255 int *errorCodePtr
256){
257 IncrblobChannel *p = (IncrblobChannel *)instanceData;
258 int nRead = bufSize; /* Number of bytes to read */
259 int nBlob; /* Total size of the blob */
260 int rc; /* sqlite error code */
261
262 nBlob = sqlite3_blob_bytes(p->pBlob);
263 if( (p->iSeek+nRead)>nBlob ){
264 nRead = nBlob-p->iSeek;
265 }
266 if( nRead<=0 ){
267 return 0;
268 }
269
270 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
271 if( rc!=SQLITE_OK ){
272 *errorCodePtr = rc;
273 return -1;
274 }
275
276 p->iSeek += nRead;
277 return nRead;
278}
279
danielk1977d04417962007-05-02 13:16:30 +0000280/*
281** Write data to an incremental blob channel.
282*/
mistachkin7617e4a2016-07-28 17:11:20 +0000283static int SQLITE_TCLAPI incrblobOutput(
mistachkinb56660f2016-07-14 21:26:09 +0000284 ClientData instanceData,
285 CONST char *buf,
danielk1977b4e9af92007-05-01 17:49:49 +0000286 int toWrite,
287 int *errorCodePtr
288){
289 IncrblobChannel *p = (IncrblobChannel *)instanceData;
290 int nWrite = toWrite; /* Number of bytes to write */
291 int nBlob; /* Total size of the blob */
292 int rc; /* sqlite error code */
293
294 nBlob = sqlite3_blob_bytes(p->pBlob);
295 if( (p->iSeek+nWrite)>nBlob ){
296 *errorCodePtr = EINVAL;
297 return -1;
298 }
299 if( nWrite<=0 ){
300 return 0;
301 }
302
303 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
304 if( rc!=SQLITE_OK ){
305 *errorCodePtr = EIO;
306 return -1;
307 }
308
309 p->iSeek += nWrite;
310 return nWrite;
311}
312
313/*
314** Seek an incremental blob channel.
315*/
mistachkin7617e4a2016-07-28 17:11:20 +0000316static int SQLITE_TCLAPI incrblobSeek(
mistachkinb56660f2016-07-14 21:26:09 +0000317 ClientData instanceData,
danielk1977b4e9af92007-05-01 17:49:49 +0000318 long offset,
319 int seekMode,
320 int *errorCodePtr
321){
322 IncrblobChannel *p = (IncrblobChannel *)instanceData;
323
324 switch( seekMode ){
325 case SEEK_SET:
326 p->iSeek = offset;
327 break;
328 case SEEK_CUR:
329 p->iSeek += offset;
330 break;
331 case SEEK_END:
332 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
333 break;
334
335 default: assert(!"Bad seekMode");
336 }
337
338 return p->iSeek;
339}
340
341
mistachkin7617e4a2016-07-28 17:11:20 +0000342static void SQLITE_TCLAPI incrblobWatch(
343 ClientData instanceData,
344 int mode
345){
mistachkinb56660f2016-07-14 21:26:09 +0000346 /* NO-OP */
danielk1977b4e9af92007-05-01 17:49:49 +0000347}
mistachkin7617e4a2016-07-28 17:11:20 +0000348static int SQLITE_TCLAPI incrblobHandle(
349 ClientData instanceData,
350 int dir,
351 ClientData *hPtr
352){
danielk1977b4e9af92007-05-01 17:49:49 +0000353 return TCL_ERROR;
354}
355
356static Tcl_ChannelType IncrblobChannelType = {
357 "incrblob", /* typeName */
358 TCL_CHANNEL_VERSION_2, /* version */
359 incrblobClose, /* closeProc */
360 incrblobInput, /* inputProc */
361 incrblobOutput, /* outputProc */
362 incrblobSeek, /* seekProc */
363 0, /* setOptionProc */
364 0, /* getOptionProc */
365 incrblobWatch, /* watchProc (this is a no-op) */
366 incrblobHandle, /* getHandleProc (always returns error) */
367 0, /* close2Proc */
368 0, /* blockModeProc */
369 0, /* flushProc */
370 0, /* handlerProc */
371 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000372};
373
374/*
375** Create a new incrblob channel.
376*/
377static int createIncrblobChannel(
mistachkinb56660f2016-07-14 21:26:09 +0000378 Tcl_Interp *interp,
379 SqliteDb *pDb,
danielk1977b4e9af92007-05-01 17:49:49 +0000380 const char *zDb,
mistachkinb56660f2016-07-14 21:26:09 +0000381 const char *zTable,
382 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000383 sqlite_int64 iRow,
384 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000385){
386 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000387 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000388 sqlite3_blob *pBlob;
389 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000390 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000391
392 /* This variable is used to name the channels: "incrblob_[incr count]" */
393 static int count = 0;
394 char zChannel[64];
395
danielk19778cbadb02007-05-03 16:31:26 +0000396 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000397 if( rc!=SQLITE_OK ){
398 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
399 return TCL_ERROR;
400 }
401
402 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
403 p->iSeek = 0;
404 p->pBlob = pBlob;
405
drh5bb3eb92007-05-04 13:15:55 +0000406 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000407 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
408 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000409
danielk1977d04417962007-05-02 13:16:30 +0000410 /* Link the new channel into the SqliteDb.pIncrblob list. */
411 p->pNext = pDb->pIncrblob;
412 p->pPrev = 0;
413 if( p->pNext ){
414 p->pNext->pPrev = p;
415 }
416 pDb->pIncrblob = p;
417 p->pDb = pDb;
418
419 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000420 return TCL_OK;
421}
danielk197732a0d8b2007-05-04 19:03:02 +0000422#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
423 #define closeIncrblobChannels(pDb)
424#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000425
drh6d313162000-09-21 13:01:35 +0000426/*
drhd1e47332005-06-26 17:55:33 +0000427** Look at the script prefix in pCmd. We will be executing this script
428** after first appending one or more arguments. This routine analyzes
429** the script to see if it is safe to use Tcl_EvalObjv() on the script
430** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
431** faster.
432**
433** Scripts that are safe to use with Tcl_EvalObjv() consists of a
434** command name followed by zero or more arguments with no [...] or $
435** or {...} or ; to be seen anywhere. Most callback scripts consist
436** of just a single procedure name and they meet this requirement.
437*/
438static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
439 /* We could try to do something with Tcl_Parse(). But we will instead
440 ** just do a search for forbidden characters. If any of the forbidden
441 ** characters appear in pCmd, we will report the string as unsafe.
442 */
443 const char *z;
444 int n;
445 z = Tcl_GetStringFromObj(pCmd, &n);
446 while( n-- > 0 ){
447 int c = *(z++);
448 if( c=='$' || c=='[' || c==';' ) return 0;
449 }
450 return 1;
451}
452
453/*
454** Find an SqlFunc structure with the given name. Or create a new
455** one if an existing one cannot be found. Return a pointer to the
456** structure.
457*/
458static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
459 SqlFunc *p, *pNew;
drh0425f182013-11-26 16:48:04 +0000460 int nName = strlen30(zName);
461 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
drhd1e47332005-06-26 17:55:33 +0000462 pNew->zName = (char*)&pNew[1];
drh0425f182013-11-26 16:48:04 +0000463 memcpy(pNew->zName, zName, nName+1);
mistachkinb56660f2016-07-14 21:26:09 +0000464 for(p=pDb->pFunc; p; p=p->pNext){
drh0425f182013-11-26 16:48:04 +0000465 if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
drhd1e47332005-06-26 17:55:33 +0000466 Tcl_Free((char*)pNew);
467 return p;
468 }
469 }
470 pNew->interp = pDb->interp;
drhc45e6712012-10-03 11:02:33 +0000471 pNew->pDb = pDb;
drhd1e47332005-06-26 17:55:33 +0000472 pNew->pScript = 0;
473 pNew->pNext = pDb->pFunc;
474 pDb->pFunc = pNew;
475 return pNew;
476}
477
478/*
danc431fd52011-06-27 16:55:50 +0000479** Free a single SqlPreparedStmt object.
480*/
481static void dbFreeStmt(SqlPreparedStmt *pStmt){
482#ifdef SQLITE_TEST
483 if( sqlite3_sql(pStmt->pStmt)==0 ){
484 Tcl_Free((char *)pStmt->zSql);
485 }
486#endif
487 sqlite3_finalize(pStmt->pStmt);
488 Tcl_Free((char *)pStmt);
489}
490
491/*
drhfb7e7652005-01-24 00:28:42 +0000492** Finalize and free a list of prepared statements
493*/
danc431fd52011-06-27 16:55:50 +0000494static void flushStmtCache(SqliteDb *pDb){
drhfb7e7652005-01-24 00:28:42 +0000495 SqlPreparedStmt *pPreStmt;
danc431fd52011-06-27 16:55:50 +0000496 SqlPreparedStmt *pNext;
drhfb7e7652005-01-24 00:28:42 +0000497
danc431fd52011-06-27 16:55:50 +0000498 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
499 pNext = pPreStmt->pNext;
500 dbFreeStmt(pPreStmt);
drhfb7e7652005-01-24 00:28:42 +0000501 }
502 pDb->nStmt = 0;
503 pDb->stmtLast = 0;
danc431fd52011-06-27 16:55:50 +0000504 pDb->stmtList = 0;
drhfb7e7652005-01-24 00:28:42 +0000505}
506
507/*
drh895d7472004-08-20 16:02:39 +0000508** TCL calls this procedure when an sqlite3 database command is
509** deleted.
drh75897232000-05-29 14:26:00 +0000510*/
mistachkin7617e4a2016-07-28 17:11:20 +0000511static void SQLITE_TCLAPI DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000512 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000513 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000514 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000515 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000516 while( pDb->pFunc ){
517 SqlFunc *pFunc = pDb->pFunc;
518 pDb->pFunc = pFunc->pNext;
drhc45e6712012-10-03 11:02:33 +0000519 assert( pFunc->pDb==pDb );
drhd1e47332005-06-26 17:55:33 +0000520 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000521 Tcl_Free((char*)pFunc);
522 }
danielk19770202b292004-06-09 09:55:16 +0000523 while( pDb->pCollate ){
524 SqlCollate *pCollate = pDb->pCollate;
525 pDb->pCollate = pCollate->pNext;
526 Tcl_Free((char*)pCollate);
527 }
drhbec3f402000-08-04 13:49:02 +0000528 if( pDb->zBusy ){
529 Tcl_Free(pDb->zBusy);
530 }
drhb5a20d32003-04-23 12:25:23 +0000531 if( pDb->zTrace ){
532 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000533 }
mistachkinb56660f2016-07-14 21:26:09 +0000534 if( pDb->zTraceV2 ){
535 Tcl_Free(pDb->zTraceV2);
536 }
drh19e2d372005-08-29 23:00:03 +0000537 if( pDb->zProfile ){
538 Tcl_Free(pDb->zProfile);
539 }
drhe22a3342003-04-22 20:30:37 +0000540 if( pDb->zAuth ){
541 Tcl_Free(pDb->zAuth);
542 }
danielk197755c45f22005-04-03 23:54:43 +0000543 if( pDb->zNull ){
544 Tcl_Free(pDb->zNull);
545 }
danielk197794eb6a12005-12-15 15:22:08 +0000546 if( pDb->pUpdateHook ){
547 Tcl_DecrRefCount(pDb->pUpdateHook);
548 }
dan46c47d42011-03-01 18:42:07 +0000549 if( pDb->pPreUpdateHook ){
550 Tcl_DecrRefCount(pDb->pPreUpdateHook);
551 }
danielk197771fd80b2005-12-16 06:54:01 +0000552 if( pDb->pRollbackHook ){
553 Tcl_DecrRefCount(pDb->pRollbackHook);
554 }
drh5def0842010-05-05 20:00:25 +0000555 if( pDb->pWalHook ){
556 Tcl_DecrRefCount(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000557 }
danielk197794eb6a12005-12-15 15:22:08 +0000558 if( pDb->pCollateNeeded ){
559 Tcl_DecrRefCount(pDb->pCollateNeeded);
560 }
drhbec3f402000-08-04 13:49:02 +0000561 Tcl_Free((char*)pDb);
562}
563
564/*
565** This routine is called when a database file is locked while trying
566** to execute SQL.
567*/
danielk19772a764eb2004-06-12 01:43:26 +0000568static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000569 SqliteDb *pDb = (SqliteDb*)cd;
570 int rc;
571 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000572
drh5bb3eb92007-05-04 13:15:55 +0000573 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000574 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000575 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
576 return 0;
577 }
578 return 1;
drh75897232000-05-29 14:26:00 +0000579}
580
drh26e4a8b2008-05-01 17:16:52 +0000581#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000582/*
danielk1977348bb5d2003-10-18 09:37:26 +0000583** This routine is invoked as the 'progress callback' for the database.
584*/
585static int DbProgressHandler(void *cd){
586 SqliteDb *pDb = (SqliteDb*)cd;
587 int rc;
588
589 assert( pDb->zProgress );
590 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
591 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
592 return 1;
593 }
594 return 0;
595}
drh26e4a8b2008-05-01 17:16:52 +0000596#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000597
drh2eb22af2016-09-10 19:51:40 +0000598#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
599 !defined(SQLITE_OMIT_DEPRECATED)
danielk1977348bb5d2003-10-18 09:37:26 +0000600/*
drhb5a20d32003-04-23 12:25:23 +0000601** This routine is called by the SQLite trace handler whenever a new
602** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000603*/
drhb5a20d32003-04-23 12:25:23 +0000604static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000605 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000606 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000607
drhb5a20d32003-04-23 12:25:23 +0000608 Tcl_DStringInit(&str);
609 Tcl_DStringAppend(&str, pDb->zTrace, -1);
610 Tcl_DStringAppendElement(&str, zSql);
611 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
612 Tcl_DStringFree(&str);
613 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000614}
drhd1167392006-01-23 13:00:35 +0000615#endif
drh0d1a6432003-04-03 15:46:04 +0000616
drhd1167392006-01-23 13:00:35 +0000617#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000618/*
mistachkinb56660f2016-07-14 21:26:09 +0000619** This routine is called by the SQLite trace_v2 handler whenever a new
620** supported event is generated. Unsupported event types are ignored.
621** The TCL script in pDb->zTraceV2 is executed, with the arguments for
622** the event appended to it (as list elements).
623*/
624static int DbTraceV2Handler(
625 unsigned type, /* One of the SQLITE_TRACE_* event types. */
626 void *cd, /* The original context data pointer. */
627 void *pd, /* Primary event data, depends on event type. */
628 void *xd /* Extra event data, depends on event type. */
629){
630 SqliteDb *pDb = (SqliteDb*)cd;
631 Tcl_Obj *pCmd;
632
633 switch( type ){
634 case SQLITE_TRACE_STMT: {
635 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
636 char *zSql = (char *)xd;
637
638 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
639 Tcl_IncrRefCount(pCmd);
640 Tcl_ListObjAppendElement(pDb->interp, pCmd,
641 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
642 Tcl_ListObjAppendElement(pDb->interp, pCmd,
643 Tcl_NewStringObj(zSql, -1));
644 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
645 Tcl_DecrRefCount(pCmd);
646 Tcl_ResetResult(pDb->interp);
647 break;
648 }
649 case SQLITE_TRACE_PROFILE: {
650 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
drhffdab722018-03-10 20:25:08 +0000651 sqlite3_int64 ns = *(sqlite3_int64*)xd;
mistachkinb56660f2016-07-14 21:26:09 +0000652
653 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
654 Tcl_IncrRefCount(pCmd);
655 Tcl_ListObjAppendElement(pDb->interp, pCmd,
656 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
657 Tcl_ListObjAppendElement(pDb->interp, pCmd,
658 Tcl_NewWideIntObj((Tcl_WideInt)ns));
659 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
660 Tcl_DecrRefCount(pCmd);
661 Tcl_ResetResult(pDb->interp);
662 break;
663 }
664 case SQLITE_TRACE_ROW: {
665 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
666
667 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
668 Tcl_IncrRefCount(pCmd);
669 Tcl_ListObjAppendElement(pDb->interp, pCmd,
670 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
671 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
672 Tcl_DecrRefCount(pCmd);
673 Tcl_ResetResult(pDb->interp);
674 break;
675 }
676 case SQLITE_TRACE_CLOSE: {
677 sqlite3 *db = (sqlite3 *)pd;
678
679 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
680 Tcl_IncrRefCount(pCmd);
681 Tcl_ListObjAppendElement(pDb->interp, pCmd,
682 Tcl_NewWideIntObj((Tcl_WideInt)db));
683 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
684 Tcl_DecrRefCount(pCmd);
685 Tcl_ResetResult(pDb->interp);
686 break;
687 }
688 }
689 return SQLITE_OK;
690}
691#endif
692
drh2eb22af2016-09-10 19:51:40 +0000693#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
694 !defined(SQLITE_OMIT_DEPRECATED)
mistachkinb56660f2016-07-14 21:26:09 +0000695/*
drh19e2d372005-08-29 23:00:03 +0000696** This routine is called by the SQLite profile handler after a statement
697** SQL has executed. The TCL script in pDb->zProfile is evaluated.
698*/
699static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
700 SqliteDb *pDb = (SqliteDb*)cd;
701 Tcl_DString str;
702 char zTm[100];
703
704 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
705 Tcl_DStringInit(&str);
706 Tcl_DStringAppend(&str, pDb->zProfile, -1);
707 Tcl_DStringAppendElement(&str, zSql);
708 Tcl_DStringAppendElement(&str, zTm);
709 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
710 Tcl_DStringFree(&str);
711 Tcl_ResetResult(pDb->interp);
712}
drhd1167392006-01-23 13:00:35 +0000713#endif
drh19e2d372005-08-29 23:00:03 +0000714
715/*
drhaa940ea2004-01-15 02:44:03 +0000716** This routine is called when a transaction is committed. The
717** TCL script in pDb->zCommit is executed. If it returns non-zero or
718** if it throws an exception, the transaction is rolled back instead
719** of being committed.
720*/
721static int DbCommitHandler(void *cd){
722 SqliteDb *pDb = (SqliteDb*)cd;
723 int rc;
724
725 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
726 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
727 return 1;
728 }
729 return 0;
730}
731
danielk197771fd80b2005-12-16 06:54:01 +0000732static void DbRollbackHandler(void *clientData){
733 SqliteDb *pDb = (SqliteDb*)clientData;
734 assert(pDb->pRollbackHook);
735 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
736 Tcl_BackgroundError(pDb->interp);
737 }
738}
739
drh5def0842010-05-05 20:00:25 +0000740/*
741** This procedure handles wal_hook callbacks.
742*/
743static int DbWalHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000744 void *clientData,
745 sqlite3 *db,
746 const char *zDb,
dan8d22a172010-04-19 18:03:51 +0000747 int nEntry
748){
drh5def0842010-05-05 20:00:25 +0000749 int ret = SQLITE_OK;
dan8d22a172010-04-19 18:03:51 +0000750 Tcl_Obj *p;
751 SqliteDb *pDb = (SqliteDb*)clientData;
752 Tcl_Interp *interp = pDb->interp;
drh5def0842010-05-05 20:00:25 +0000753 assert(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000754
dan6e45e0c2014-12-10 20:29:49 +0000755 assert( db==pDb->db );
drh5def0842010-05-05 20:00:25 +0000756 p = Tcl_DuplicateObj(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000757 Tcl_IncrRefCount(p);
758 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
759 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
mistachkinb56660f2016-07-14 21:26:09 +0000760 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
dan8d22a172010-04-19 18:03:51 +0000761 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
762 ){
763 Tcl_BackgroundError(interp);
764 }
765 Tcl_DecrRefCount(p);
766
767 return ret;
768}
769
drhbcf4f482009-03-27 12:44:35 +0000770#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000771static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
772 char zBuf[64];
drh65545b52015-01-19 00:35:53 +0000773 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
danielk1977404ca072009-03-16 13:19:36 +0000774 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
drh65545b52015-01-19 00:35:53 +0000775 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
danielk1977404ca072009-03-16 13:19:36 +0000776 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
777}
778#else
drhbcf4f482009-03-27 12:44:35 +0000779# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000780#endif
781
drh69910da2009-03-27 12:32:54 +0000782#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000783static void DbUnlockNotify(void **apArg, int nArg){
784 int i;
785 for(i=0; i<nArg; i++){
786 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
787 SqliteDb *pDb = (SqliteDb *)apArg[i];
788 setTestUnlockNotifyVars(pDb->interp, i, nArg);
789 assert( pDb->pUnlockNotify);
790 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
791 Tcl_DecrRefCount(pDb->pUnlockNotify);
792 pDb->pUnlockNotify = 0;
793 }
794}
drh69910da2009-03-27 12:32:54 +0000795#endif
danielk1977404ca072009-03-16 13:19:36 +0000796
drh9b1c62d2011-03-30 21:04:43 +0000797#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +0000798/*
799** Pre-update hook callback.
800*/
801static void DbPreUpdateHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000802 void *p,
dan46c47d42011-03-01 18:42:07 +0000803 sqlite3 *db,
804 int op,
mistachkinb56660f2016-07-14 21:26:09 +0000805 const char *zDb,
806 const char *zTbl,
dan46c47d42011-03-01 18:42:07 +0000807 sqlite_int64 iKey1,
808 sqlite_int64 iKey2
809){
810 SqliteDb *pDb = (SqliteDb *)p;
811 Tcl_Obj *pCmd;
812 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
813
814 assert( (SQLITE_DELETE-1)/9 == 0 );
815 assert( (SQLITE_INSERT-1)/9 == 1 );
816 assert( (SQLITE_UPDATE-1)/9 == 2 );
817 assert( pDb->pPreUpdateHook );
818 assert( db==pDb->db );
819 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
820
821 pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
822 Tcl_IncrRefCount(pCmd);
823 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
824 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
825 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
826 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
827 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
828 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
829 Tcl_DecrRefCount(pCmd);
830}
drh9b1c62d2011-03-30 21:04:43 +0000831#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +0000832
danielk197794eb6a12005-12-15 15:22:08 +0000833static void DbUpdateHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000834 void *p,
danielk197794eb6a12005-12-15 15:22:08 +0000835 int op,
mistachkinb56660f2016-07-14 21:26:09 +0000836 const char *zDb,
837 const char *zTbl,
danielk197794eb6a12005-12-15 15:22:08 +0000838 sqlite_int64 rowid
839){
840 SqliteDb *pDb = (SqliteDb *)p;
841 Tcl_Obj *pCmd;
dan46c47d42011-03-01 18:42:07 +0000842 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
843
844 assert( (SQLITE_DELETE-1)/9 == 0 );
845 assert( (SQLITE_INSERT-1)/9 == 1 );
846 assert( (SQLITE_UPDATE-1)/9 == 2 );
danielk197794eb6a12005-12-15 15:22:08 +0000847
848 assert( pDb->pUpdateHook );
849 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
850
851 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
852 Tcl_IncrRefCount(pCmd);
dan46c47d42011-03-01 18:42:07 +0000853 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
danielk197794eb6a12005-12-15 15:22:08 +0000854 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
855 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
856 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
857 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
drhefdde162010-10-27 15:36:21 +0000858 Tcl_DecrRefCount(pCmd);
danielk197794eb6a12005-12-15 15:22:08 +0000859}
860
danielk19777cedc8d2004-06-10 10:50:08 +0000861static void tclCollateNeeded(
862 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000863 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000864 int enc,
865 const char *zName
866){
867 SqliteDb *pDb = (SqliteDb *)pCtx;
868 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
869 Tcl_IncrRefCount(pScript);
870 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
871 Tcl_EvalObjEx(pDb->interp, pScript, 0);
872 Tcl_DecrRefCount(pScript);
873}
874
drhaa940ea2004-01-15 02:44:03 +0000875/*
danielk19770202b292004-06-09 09:55:16 +0000876** This routine is called to evaluate an SQL collation function implemented
877** using TCL script.
878*/
879static int tclSqlCollate(
880 void *pCtx,
881 int nA,
882 const void *zA,
883 int nB,
884 const void *zB
885){
886 SqlCollate *p = (SqlCollate *)pCtx;
887 Tcl_Obj *pCmd;
888
889 pCmd = Tcl_NewStringObj(p->zScript, -1);
890 Tcl_IncrRefCount(pCmd);
891 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
892 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000893 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000894 Tcl_DecrRefCount(pCmd);
895 return (atoi(Tcl_GetStringResult(p->interp)));
896}
897
898/*
drhcabb0812002-09-14 13:47:32 +0000899** This routine is called to evaluate an SQL function implemented
900** using TCL script.
901*/
drhfb7e7652005-01-24 00:28:42 +0000902static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000903 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000904 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000905 int i;
906 int rc;
907
drhd1e47332005-06-26 17:55:33 +0000908 if( argc==0 ){
909 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
910 ** script object directly. This allows the TCL compiler to generate
911 ** bytecode for the command on the first invocation and thus make
912 ** subsequent invocations much faster. */
913 pCmd = p->pScript;
914 Tcl_IncrRefCount(pCmd);
915 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
916 Tcl_DecrRefCount(pCmd);
917 }else{
918 /* If there are arguments to the function, make a shallow copy of the
919 ** script object, lappend the arguments, then evaluate the copy.
920 **
peter.d.reid60ec9142014-09-06 16:39:46 +0000921 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
mistachkinb56660f2016-07-14 21:26:09 +0000922 ** The new Tcl_Obj contains pointers to the original list elements.
drhd1e47332005-06-26 17:55:33 +0000923 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
924 ** of the list to tclCmdNameType, that alternate representation will
925 ** be preserved and reused on the next invocation.
926 */
927 Tcl_Obj **aArg;
928 int nArg;
929 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
mistachkinb56660f2016-07-14 21:26:09 +0000930 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhd1e47332005-06-26 17:55:33 +0000931 return;
mistachkinb56660f2016-07-14 21:26:09 +0000932 }
drhd1e47332005-06-26 17:55:33 +0000933 pCmd = Tcl_NewListObj(nArg, aArg);
934 Tcl_IncrRefCount(pCmd);
935 for(i=0; i<argc; i++){
936 sqlite3_value *pIn = argv[i];
937 Tcl_Obj *pVal;
mistachkinb56660f2016-07-14 21:26:09 +0000938
drhd1e47332005-06-26 17:55:33 +0000939 /* Set pVal to contain the i'th column of this row. */
940 switch( sqlite3_value_type(pIn) ){
941 case SQLITE_BLOB: {
942 int bytes = sqlite3_value_bytes(pIn);
943 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
944 break;
945 }
946 case SQLITE_INTEGER: {
947 sqlite_int64 v = sqlite3_value_int64(pIn);
948 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +0000949 pVal = Tcl_NewIntObj((int)v);
drhd1e47332005-06-26 17:55:33 +0000950 }else{
951 pVal = Tcl_NewWideIntObj(v);
952 }
953 break;
954 }
955 case SQLITE_FLOAT: {
956 double r = sqlite3_value_double(pIn);
957 pVal = Tcl_NewDoubleObj(r);
958 break;
959 }
960 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +0000961 pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
drhd1e47332005-06-26 17:55:33 +0000962 break;
963 }
964 default: {
965 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000966 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000967 break;
968 }
969 }
970 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
971 if( rc ){
972 Tcl_DecrRefCount(pCmd);
mistachkinb56660f2016-07-14 21:26:09 +0000973 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhd1e47332005-06-26 17:55:33 +0000974 return;
975 }
danielk197751ad0ec2004-05-24 12:39:02 +0000976 }
drhd1e47332005-06-26 17:55:33 +0000977 if( !p->useEvalObjv ){
978 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
979 ** is a list without a string representation. To prevent this from
980 ** happening, make sure pCmd has a valid string representation */
981 Tcl_GetString(pCmd);
982 }
983 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
984 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000985 }
danielk1977562e8d32005-05-20 09:40:55 +0000986
drhc7f269d2005-05-05 10:30:29 +0000987 if( rc && rc!=TCL_RETURN ){
mistachkinb56660f2016-07-14 21:26:09 +0000988 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000989 }else{
drhc7f269d2005-05-05 10:30:29 +0000990 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
991 int n;
992 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000993 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000994 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000995 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000996 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000997 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000998 data = Tcl_GetByteArrayFromObj(pVar, &n);
999 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +00001000 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +00001001 Tcl_GetIntFromObj(0, pVar, &n);
1002 sqlite3_result_int(context, n);
1003 }else if( c=='d' && strcmp(zType,"double")==0 ){
1004 double r;
1005 Tcl_GetDoubleFromObj(0, pVar, &r);
1006 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +00001007 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1008 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +00001009 Tcl_WideInt v;
1010 Tcl_GetWideIntFromObj(0, pVar, &v);
1011 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +00001012 }else{
danielk197700fd9572005-12-07 06:27:43 +00001013 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1014 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +00001015 }
drhcabb0812002-09-14 13:47:32 +00001016 }
1017}
drh895d7472004-08-20 16:02:39 +00001018
drhe22a3342003-04-22 20:30:37 +00001019#ifndef SQLITE_OMIT_AUTHORIZATION
1020/*
1021** This is the authentication function. It appends the authentication
1022** type code and the two arguments to zCmd[] then invokes the result
1023** on the interpreter. The reply is examined to determine if the
1024** authentication fails or succeeds.
1025*/
1026static int auth_callback(
1027 void *pArg,
1028 int code,
1029 const char *zArg1,
1030 const char *zArg2,
1031 const char *zArg3,
1032 const char *zArg4
drh32c6a482014-09-11 13:44:52 +00001033#ifdef SQLITE_USER_AUTHENTICATION
1034 ,const char *zArg5
1035#endif
drhe22a3342003-04-22 20:30:37 +00001036){
mistachkin6ef5e122014-01-24 17:03:55 +00001037 const char *zCode;
drhe22a3342003-04-22 20:30:37 +00001038 Tcl_DString str;
1039 int rc;
1040 const char *zReply;
drh94189212017-05-11 13:43:57 +00001041 /* EVIDENCE-OF: R-38590-62769 The first parameter to the authorizer
1042 ** callback is a copy of the third parameter to the
1043 ** sqlite3_set_authorizer() interface.
1044 */
drhe22a3342003-04-22 20:30:37 +00001045 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +00001046 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +00001047
drh94189212017-05-11 13:43:57 +00001048 /* EVIDENCE-OF: R-56518-44310 The second parameter to the callback is an
1049 ** integer action code that specifies the particular action to be
1050 ** authorized. */
drhe22a3342003-04-22 20:30:37 +00001051 switch( code ){
1052 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
1053 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
1054 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
1055 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
1056 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
1057 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
1058 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
1059 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
1060 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
1061 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
1062 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
1063 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
1064 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
1065 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
1066 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
1067 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
1068 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
1069 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
1070 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
1071 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
1072 case SQLITE_READ : zCode="SQLITE_READ"; break;
1073 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
1074 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
1075 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +00001076 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
1077 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +00001078 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +00001079 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +00001080 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +00001081 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
1082 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +00001083 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +00001084 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drh65a2aaa2014-01-16 22:40:02 +00001085 case SQLITE_RECURSIVE : zCode="SQLITE_RECURSIVE"; break;
drhe22a3342003-04-22 20:30:37 +00001086 default : zCode="????"; break;
1087 }
1088 Tcl_DStringInit(&str);
1089 Tcl_DStringAppend(&str, pDb->zAuth, -1);
1090 Tcl_DStringAppendElement(&str, zCode);
1091 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
1092 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
1093 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
1094 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
drh32c6a482014-09-11 13:44:52 +00001095#ifdef SQLITE_USER_AUTHENTICATION
1096 Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
mistachkinb56660f2016-07-14 21:26:09 +00001097#endif
drhe22a3342003-04-22 20:30:37 +00001098 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
1099 Tcl_DStringFree(&str);
drhb07028f2011-10-14 21:49:18 +00001100 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
drhe22a3342003-04-22 20:30:37 +00001101 if( strcmp(zReply,"SQLITE_OK")==0 ){
1102 rc = SQLITE_OK;
1103 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
1104 rc = SQLITE_DENY;
1105 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
1106 rc = SQLITE_IGNORE;
1107 }else{
1108 rc = 999;
1109 }
1110 return rc;
1111}
1112#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +00001113
1114/*
tpoindex1067fe12004-12-17 15:41:11 +00001115** This routine reads a line of text from FILE in, stores
1116** the text in memory obtained from malloc() and returns a pointer
1117** to the text. NULL is returned at end of file, or if malloc()
1118** fails.
1119**
1120** The interface is like "readline" but no command-line editing
1121** is done.
1122**
1123** copied from shell.c from '.import' command
1124*/
1125static char *local_getline(char *zPrompt, FILE *in){
1126 char *zLine;
1127 int nLine;
1128 int n;
tpoindex1067fe12004-12-17 15:41:11 +00001129
1130 nLine = 100;
1131 zLine = malloc( nLine );
1132 if( zLine==0 ) return 0;
1133 n = 0;
drhb07028f2011-10-14 21:49:18 +00001134 while( 1 ){
tpoindex1067fe12004-12-17 15:41:11 +00001135 if( n+100>nLine ){
1136 nLine = nLine*2 + 100;
1137 zLine = realloc(zLine, nLine);
1138 if( zLine==0 ) return 0;
1139 }
1140 if( fgets(&zLine[n], nLine - n, in)==0 ){
1141 if( n==0 ){
1142 free(zLine);
1143 return 0;
1144 }
1145 zLine[n] = 0;
tpoindex1067fe12004-12-17 15:41:11 +00001146 break;
1147 }
1148 while( zLine[n] ){ n++; }
1149 if( n>0 && zLine[n-1]=='\n' ){
1150 n--;
1151 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +00001152 break;
tpoindex1067fe12004-12-17 15:41:11 +00001153 }
1154 }
1155 zLine = realloc( zLine, n+1 );
1156 return zLine;
1157}
1158
danielk19778e556522007-11-13 10:30:24 +00001159
1160/*
dan4a4c11a2009-10-06 14:59:02 +00001161** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +00001162**
dan4a4c11a2009-10-06 14:59:02 +00001163** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +00001164**
dan4a4c11a2009-10-06 14:59:02 +00001165** It is invoked after evaluating the script SCRIPT to commit or rollback
1166** the transaction or savepoint opened by the [transaction] command.
1167*/
mistachkina121cc72016-07-28 18:06:52 +00001168static int SQLITE_TCLAPI DbTransPostCmd(
dan4a4c11a2009-10-06 14:59:02 +00001169 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1170 Tcl_Interp *interp, /* Tcl interpreter */
1171 int result /* Result of evaluating SCRIPT */
1172){
mistachkin6ef5e122014-01-24 17:03:55 +00001173 static const char *const azEnd[] = {
dan4a4c11a2009-10-06 14:59:02 +00001174 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1175 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1176 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1177 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1178 };
1179 SqliteDb *pDb = (SqliteDb*)data[0];
1180 int rc = result;
1181 const char *zEnd;
1182
1183 pDb->nTransaction--;
1184 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1185
1186 pDb->disableAuth++;
1187 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1188 /* This is a tricky scenario to handle. The most likely cause of an
mistachkinb56660f2016-07-14 21:26:09 +00001189 ** error is that the exec() above was an attempt to commit the
dan4a4c11a2009-10-06 14:59:02 +00001190 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
mistachkin48864df2013-03-21 21:20:32 +00001191 ** that an IO-error has occurred. In either case, throw a Tcl exception
dan4a4c11a2009-10-06 14:59:02 +00001192 ** and try to rollback the transaction.
1193 **
mistachkinb56660f2016-07-14 21:26:09 +00001194 ** But it could also be that the user executed one or more BEGIN,
dan4a4c11a2009-10-06 14:59:02 +00001195 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1196 ** this method's logic. Not clear how this would be best handled.
1197 */
1198 if( rc!=TCL_ERROR ){
drha198f2b2014-02-07 19:26:13 +00001199 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
dan4a4c11a2009-10-06 14:59:02 +00001200 rc = TCL_ERROR;
1201 }
1202 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1203 }
1204 pDb->disableAuth--;
1205
1206 return rc;
1207}
1208
1209/*
danc431fd52011-06-27 16:55:50 +00001210** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1211** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1212** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
mistachkinb56660f2016-07-14 21:26:09 +00001213** on whether or not the [db_use_legacy_prepare] command has been used to
danc431fd52011-06-27 16:55:50 +00001214** configure the connection.
1215*/
1216static int dbPrepare(
1217 SqliteDb *pDb, /* Database object */
1218 const char *zSql, /* SQL to compile */
1219 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1220 const char **pzOut /* OUT: Pointer to next SQL statement */
1221){
drh2c2f3922017-06-01 00:54:35 +00001222 unsigned int prepFlags = 0;
danc431fd52011-06-27 16:55:50 +00001223#ifdef SQLITE_TEST
1224 if( pDb->bLegacyPrepare ){
1225 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1226 }
1227#endif
drh2c2f3922017-06-01 00:54:35 +00001228 /* If the statement cache is large, use the SQLITE_PREPARE_PERSISTENT
1229 ** flags, which uses less lookaside memory. But if the cache is small,
1230 ** omit that flag to make full use of lookaside */
1231 if( pDb->maxStmt>5 ) prepFlags = SQLITE_PREPARE_PERSISTENT;
1232
1233 return sqlite3_prepare_v3(pDb->db, zSql, -1, prepFlags, ppStmt, pzOut);
danc431fd52011-06-27 16:55:50 +00001234}
1235
1236/*
dan4a4c11a2009-10-06 14:59:02 +00001237** Search the cache for a prepared-statement object that implements the
1238** first SQL statement in the buffer pointed to by parameter zIn. If
1239** no such prepared-statement can be found, allocate and prepare a new
1240** one. In either case, bind the current values of the relevant Tcl
1241** variables to any $var, :var or @var variables in the statement. Before
1242** returning, set *ppPreStmt to point to the prepared-statement object.
1243**
1244** Output parameter *pzOut is set to point to the next SQL statement in
1245** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1246** next statement.
1247**
1248** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1249** and an error message loaded into interpreter pDb->interp.
1250*/
1251static int dbPrepareAndBind(
1252 SqliteDb *pDb, /* Database object */
1253 char const *zIn, /* SQL to compile */
1254 char const **pzOut, /* OUT: Pointer to next SQL statement */
1255 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1256){
1257 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
mistachkin7bb22ac2015-01-12 19:59:12 +00001258 sqlite3_stmt *pStmt = 0; /* Prepared statement object */
dan4a4c11a2009-10-06 14:59:02 +00001259 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1260 int nSql; /* Length of zSql in bytes */
mistachkin7bb22ac2015-01-12 19:59:12 +00001261 int nVar = 0; /* Number of variables in statement */
dan4a4c11a2009-10-06 14:59:02 +00001262 int iParm = 0; /* Next free entry in apParm */
drh0425f182013-11-26 16:48:04 +00001263 char c;
dan4a4c11a2009-10-06 14:59:02 +00001264 int i;
1265 Tcl_Interp *interp = pDb->interp;
1266
1267 *ppPreStmt = 0;
1268
1269 /* Trim spaces from the start of zSql and calculate the remaining length. */
drh0425f182013-11-26 16:48:04 +00001270 while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
dan4a4c11a2009-10-06 14:59:02 +00001271 nSql = strlen30(zSql);
1272
1273 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1274 int n = pPreStmt->nSql;
mistachkinb56660f2016-07-14 21:26:09 +00001275 if( nSql>=n
dan4a4c11a2009-10-06 14:59:02 +00001276 && memcmp(pPreStmt->zSql, zSql, n)==0
1277 && (zSql[n]==0 || zSql[n-1]==';')
1278 ){
1279 pStmt = pPreStmt->pStmt;
1280 *pzOut = &zSql[pPreStmt->nSql];
1281
1282 /* When a prepared statement is found, unlink it from the
1283 ** cache list. It will later be added back to the beginning
1284 ** of the cache list in order to implement LRU replacement.
1285 */
1286 if( pPreStmt->pPrev ){
1287 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1288 }else{
1289 pDb->stmtList = pPreStmt->pNext;
1290 }
1291 if( pPreStmt->pNext ){
1292 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1293 }else{
1294 pDb->stmtLast = pPreStmt->pPrev;
1295 }
1296 pDb->nStmt--;
1297 nVar = sqlite3_bind_parameter_count(pStmt);
1298 break;
1299 }
1300 }
mistachkinb56660f2016-07-14 21:26:09 +00001301
dan4a4c11a2009-10-06 14:59:02 +00001302 /* If no prepared statement was found. Compile the SQL text. Also allocate
1303 ** a new SqlPreparedStmt structure. */
1304 if( pPreStmt==0 ){
1305 int nByte;
1306
danc431fd52011-06-27 16:55:50 +00001307 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
drhc45e6712012-10-03 11:02:33 +00001308 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001309 return TCL_ERROR;
1310 }
1311 if( pStmt==0 ){
1312 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1313 /* A compile-time error in the statement. */
drhc45e6712012-10-03 11:02:33 +00001314 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001315 return TCL_ERROR;
1316 }else{
1317 /* The statement was a no-op. Continue to the next statement
1318 ** in the SQL string.
1319 */
1320 return TCL_OK;
1321 }
1322 }
1323
1324 assert( pPreStmt==0 );
1325 nVar = sqlite3_bind_parameter_count(pStmt);
1326 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1327 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1328 memset(pPreStmt, 0, nByte);
1329
1330 pPreStmt->pStmt = pStmt;
drh7ed243b2012-04-19 17:19:51 +00001331 pPreStmt->nSql = (int)(*pzOut - zSql);
dan4a4c11a2009-10-06 14:59:02 +00001332 pPreStmt->zSql = sqlite3_sql(pStmt);
1333 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
danc431fd52011-06-27 16:55:50 +00001334#ifdef SQLITE_TEST
1335 if( pPreStmt->zSql==0 ){
1336 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1337 memcpy(zCopy, zSql, pPreStmt->nSql);
1338 zCopy[pPreStmt->nSql] = '\0';
1339 pPreStmt->zSql = zCopy;
1340 }
1341#endif
dan4a4c11a2009-10-06 14:59:02 +00001342 }
1343 assert( pPreStmt );
1344 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1345 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1346
mistachkinb56660f2016-07-14 21:26:09 +00001347 /* Bind values to parameters that begin with $ or : */
dan4a4c11a2009-10-06 14:59:02 +00001348 for(i=1; i<=nVar; i++){
1349 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1350 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1351 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1352 if( pVar ){
1353 int n;
1354 u8 *data;
1355 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
mistachkin8e189222015-04-19 21:43:16 +00001356 c = zType[0];
dan4a4c11a2009-10-06 14:59:02 +00001357 if( zVar[0]=='@' ||
1358 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1359 /* Load a BLOB type if the Tcl variable is a bytearray and
1360 ** it has no string representation or the host
1361 ** parameter name begins with "@". */
1362 data = Tcl_GetByteArrayFromObj(pVar, &n);
1363 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1364 Tcl_IncrRefCount(pVar);
1365 pPreStmt->apParm[iParm++] = pVar;
1366 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1367 Tcl_GetIntFromObj(interp, pVar, &n);
1368 sqlite3_bind_int(pStmt, i, n);
1369 }else if( c=='d' && strcmp(zType,"double")==0 ){
1370 double r;
1371 Tcl_GetDoubleFromObj(interp, pVar, &r);
1372 sqlite3_bind_double(pStmt, i, r);
1373 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1374 (c=='i' && strcmp(zType,"int")==0) ){
1375 Tcl_WideInt v;
1376 Tcl_GetWideIntFromObj(interp, pVar, &v);
1377 sqlite3_bind_int64(pStmt, i, v);
1378 }else{
1379 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1380 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1381 Tcl_IncrRefCount(pVar);
1382 pPreStmt->apParm[iParm++] = pVar;
1383 }
1384 }else{
1385 sqlite3_bind_null(pStmt, i);
1386 }
1387 }
1388 }
1389 pPreStmt->nParm = iParm;
1390 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001391
dan4a4c11a2009-10-06 14:59:02 +00001392 return TCL_OK;
1393}
1394
dan4a4c11a2009-10-06 14:59:02 +00001395/*
1396** Release a statement reference obtained by calling dbPrepareAndBind().
1397** There should be exactly one call to this function for each call to
1398** dbPrepareAndBind().
1399**
1400** If the discard parameter is non-zero, then the statement is deleted
1401** immediately. Otherwise it is added to the LRU list and may be returned
1402** by a subsequent call to dbPrepareAndBind().
1403*/
1404static void dbReleaseStmt(
1405 SqliteDb *pDb, /* Database handle */
1406 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1407 int discard /* True to delete (not cache) the pPreStmt */
1408){
1409 int i;
1410
1411 /* Free the bound string and blob parameters */
1412 for(i=0; i<pPreStmt->nParm; i++){
1413 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1414 }
1415 pPreStmt->nParm = 0;
1416
1417 if( pDb->maxStmt<=0 || discard ){
1418 /* If the cache is turned off, deallocated the statement */
danc431fd52011-06-27 16:55:50 +00001419 dbFreeStmt(pPreStmt);
dan4a4c11a2009-10-06 14:59:02 +00001420 }else{
1421 /* Add the prepared statement to the beginning of the cache list. */
1422 pPreStmt->pNext = pDb->stmtList;
1423 pPreStmt->pPrev = 0;
1424 if( pDb->stmtList ){
1425 pDb->stmtList->pPrev = pPreStmt;
1426 }
1427 pDb->stmtList = pPreStmt;
1428 if( pDb->stmtLast==0 ){
1429 assert( pDb->nStmt==0 );
1430 pDb->stmtLast = pPreStmt;
1431 }else{
1432 assert( pDb->nStmt>0 );
1433 }
1434 pDb->nStmt++;
mistachkinb56660f2016-07-14 21:26:09 +00001435
1436 /* If we have too many statement in cache, remove the surplus from
dan4a4c11a2009-10-06 14:59:02 +00001437 ** the end of the cache list. */
1438 while( pDb->nStmt>pDb->maxStmt ){
danc431fd52011-06-27 16:55:50 +00001439 SqlPreparedStmt *pLast = pDb->stmtLast;
1440 pDb->stmtLast = pLast->pPrev;
dan4a4c11a2009-10-06 14:59:02 +00001441 pDb->stmtLast->pNext = 0;
1442 pDb->nStmt--;
danc431fd52011-06-27 16:55:50 +00001443 dbFreeStmt(pLast);
dan4a4c11a2009-10-06 14:59:02 +00001444 }
1445 }
1446}
1447
1448/*
1449** Structure used with dbEvalXXX() functions:
1450**
1451** dbEvalInit()
1452** dbEvalStep()
1453** dbEvalFinalize()
1454** dbEvalRowInfo()
1455** dbEvalColumnValue()
1456*/
1457typedef struct DbEvalContext DbEvalContext;
1458struct DbEvalContext {
1459 SqliteDb *pDb; /* Database handle */
1460 Tcl_Obj *pSql; /* Object holding string zSql */
1461 const char *zSql; /* Remaining SQL to execute */
1462 SqlPreparedStmt *pPreStmt; /* Current statement */
1463 int nCol; /* Number of columns returned by pStmt */
drhaf38cdb2017-06-26 21:08:32 +00001464 int evalFlags; /* Flags used */
dan4a4c11a2009-10-06 14:59:02 +00001465 Tcl_Obj *pArray; /* Name of array variable */
1466 Tcl_Obj **apColName; /* Array of column names */
1467};
1468
drhaf38cdb2017-06-26 21:08:32 +00001469#define SQLITE_EVAL_WITHOUTNULLS 0x00001 /* Unset array(*) for NULL */
1470
dan4a4c11a2009-10-06 14:59:02 +00001471/*
1472** Release any cache of column names currently held as part of
1473** the DbEvalContext structure passed as the first argument.
1474*/
1475static void dbReleaseColumnNames(DbEvalContext *p){
1476 if( p->apColName ){
1477 int i;
1478 for(i=0; i<p->nCol; i++){
1479 Tcl_DecrRefCount(p->apColName[i]);
1480 }
1481 Tcl_Free((char *)p->apColName);
1482 p->apColName = 0;
1483 }
1484 p->nCol = 0;
1485}
1486
1487/*
1488** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001489**
1490** If pArray is not NULL, then it contains the name of a Tcl array
1491** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001492** the names of the columns returned by the statement as part of each
mistachkinb56660f2016-07-14 21:26:09 +00001493** call to dbEvalStep(), in order from left to right. e.g. if the names
1494** of the returned columns are a, b and c, it does the equivalent of the
dan4a4c11a2009-10-06 14:59:02 +00001495** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001496**
1497** set ${pArray}(*) {a b c}
1498*/
dan4a4c11a2009-10-06 14:59:02 +00001499static void dbEvalInit(
1500 DbEvalContext *p, /* Pointer to structure to initialize */
1501 SqliteDb *pDb, /* Database handle */
1502 Tcl_Obj *pSql, /* Object containing SQL script */
drhaf38cdb2017-06-26 21:08:32 +00001503 Tcl_Obj *pArray, /* Name of Tcl array to set (*) element of */
1504 int evalFlags /* Flags controlling evaluation */
danielk19778e556522007-11-13 10:30:24 +00001505){
dan4a4c11a2009-10-06 14:59:02 +00001506 memset(p, 0, sizeof(DbEvalContext));
1507 p->pDb = pDb;
1508 p->zSql = Tcl_GetString(pSql);
1509 p->pSql = pSql;
1510 Tcl_IncrRefCount(pSql);
1511 if( pArray ){
1512 p->pArray = pArray;
1513 Tcl_IncrRefCount(pArray);
1514 }
drhaf38cdb2017-06-26 21:08:32 +00001515 p->evalFlags = evalFlags;
dan4a4c11a2009-10-06 14:59:02 +00001516}
danielk19778e556522007-11-13 10:30:24 +00001517
dan4a4c11a2009-10-06 14:59:02 +00001518/*
1519** Obtain information about the row that the DbEvalContext passed as the
1520** first argument currently points to.
1521*/
1522static void dbEvalRowInfo(
1523 DbEvalContext *p, /* Evaluation context */
1524 int *pnCol, /* OUT: Number of column names */
1525 Tcl_Obj ***papColName /* OUT: Array of column names */
1526){
danielk19778e556522007-11-13 10:30:24 +00001527 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001528 if( 0==p->apColName ){
1529 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1530 int i; /* Iterator variable */
1531 int nCol; /* Number of columns returned by pStmt */
1532 Tcl_Obj **apColName = 0; /* Array of column names */
1533
1534 p->nCol = nCol = sqlite3_column_count(pStmt);
1535 if( nCol>0 && (papColName || p->pArray) ){
1536 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1537 for(i=0; i<nCol; i++){
drhc45e6712012-10-03 11:02:33 +00001538 apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
dan4a4c11a2009-10-06 14:59:02 +00001539 Tcl_IncrRefCount(apColName[i]);
1540 }
1541 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001542 }
1543
1544 /* If results are being stored in an array variable, then create
1545 ** the array(*) entry for that array
1546 */
dan4a4c11a2009-10-06 14:59:02 +00001547 if( p->pArray ){
1548 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001549 Tcl_Obj *pColList = Tcl_NewObj();
1550 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001551
danielk19778e556522007-11-13 10:30:24 +00001552 for(i=0; i<nCol; i++){
1553 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1554 }
1555 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001556 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001557 Tcl_DecrRefCount(pStar);
1558 }
danielk19778e556522007-11-13 10:30:24 +00001559 }
1560
dan4a4c11a2009-10-06 14:59:02 +00001561 if( papColName ){
1562 *papColName = p->apColName;
1563 }
1564 if( pnCol ){
1565 *pnCol = p->nCol;
1566 }
1567}
1568
1569/*
1570** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1571** returned, then an error message is stored in the interpreter before
1572** returning.
1573**
1574** A return value of TCL_OK means there is a row of data available. The
1575** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1576** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1577** is returned, then the SQL script has finished executing and there are
1578** no further rows available. This is similar to SQLITE_DONE.
1579*/
1580static int dbEvalStep(DbEvalContext *p){
danc431fd52011-06-27 16:55:50 +00001581 const char *zPrevSql = 0; /* Previous value of p->zSql */
1582
dan4a4c11a2009-10-06 14:59:02 +00001583 while( p->zSql[0] || p->pPreStmt ){
1584 int rc;
1585 if( p->pPreStmt==0 ){
danc431fd52011-06-27 16:55:50 +00001586 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
dan4a4c11a2009-10-06 14:59:02 +00001587 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1588 if( rc!=TCL_OK ) return rc;
1589 }else{
1590 int rcs;
1591 SqliteDb *pDb = p->pDb;
1592 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1593 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1594
1595 rcs = sqlite3_step(pStmt);
1596 if( rcs==SQLITE_ROW ){
1597 return TCL_OK;
1598 }
1599 if( p->pArray ){
1600 dbEvalRowInfo(p, 0, 0);
1601 }
1602 rcs = sqlite3_reset(pStmt);
1603
1604 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1605 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001606 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
danc456a762017-06-22 16:51:16 +00001607 pDb->nVMStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_VM_STEP,1);
dan4a4c11a2009-10-06 14:59:02 +00001608 dbReleaseColumnNames(p);
1609 p->pPreStmt = 0;
1610
1611 if( rcs!=SQLITE_OK ){
1612 /* If a run-time error occurs, report the error and stop reading
1613 ** the SQL. */
dan4a4c11a2009-10-06 14:59:02 +00001614 dbReleaseStmt(pDb, pPreStmt, 1);
danc431fd52011-06-27 16:55:50 +00001615#if SQLITE_TEST
1616 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1617 /* If the runtime error was an SQLITE_SCHEMA, and the database
mistachkinb56660f2016-07-14 21:26:09 +00001618 ** handle is configured to use the legacy sqlite3_prepare()
danc431fd52011-06-27 16:55:50 +00001619 ** interface, retry prepare()/step() on the same SQL statement.
1620 ** This only happens once. If there is a second SQLITE_SCHEMA
1621 ** error, the error will be returned to the caller. */
1622 p->zSql = zPrevSql;
1623 continue;
1624 }
1625#endif
drhc45e6712012-10-03 11:02:33 +00001626 Tcl_SetObjResult(pDb->interp,
1627 Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001628 return TCL_ERROR;
1629 }else{
1630 dbReleaseStmt(pDb, pPreStmt, 0);
1631 }
1632 }
1633 }
1634
1635 /* Finished */
1636 return TCL_BREAK;
1637}
1638
1639/*
1640** Free all resources currently held by the DbEvalContext structure passed
1641** as the first argument. There should be exactly one call to this function
1642** for each call to dbEvalInit().
1643*/
1644static void dbEvalFinalize(DbEvalContext *p){
1645 if( p->pPreStmt ){
1646 sqlite3_reset(p->pPreStmt->pStmt);
1647 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1648 p->pPreStmt = 0;
1649 }
1650 if( p->pArray ){
1651 Tcl_DecrRefCount(p->pArray);
1652 p->pArray = 0;
1653 }
1654 Tcl_DecrRefCount(p->pSql);
1655 dbReleaseColumnNames(p);
1656}
1657
1658/*
1659** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1660** the value for the iCol'th column of the row currently pointed to by
1661** the DbEvalContext structure passed as the first argument.
1662*/
1663static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1664 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1665 switch( sqlite3_column_type(pStmt, iCol) ){
1666 case SQLITE_BLOB: {
1667 int bytes = sqlite3_column_bytes(pStmt, iCol);
1668 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1669 if( !zBlob ) bytes = 0;
1670 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1671 }
1672 case SQLITE_INTEGER: {
1673 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1674 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +00001675 return Tcl_NewIntObj((int)v);
dan4a4c11a2009-10-06 14:59:02 +00001676 }else{
1677 return Tcl_NewWideIntObj(v);
1678 }
1679 }
1680 case SQLITE_FLOAT: {
1681 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1682 }
1683 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +00001684 return Tcl_NewStringObj(p->pDb->zNull, -1);
dan4a4c11a2009-10-06 14:59:02 +00001685 }
1686 }
1687
drh325eff52012-10-03 12:56:18 +00001688 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
dan4a4c11a2009-10-06 14:59:02 +00001689}
1690
1691/*
1692** If using Tcl version 8.6 or greater, use the NR functions to avoid
1693** recursive evalution of scripts by the [db eval] and [db trans]
1694** commands. Even if the headers used while compiling the extension
1695** are 8.6 or newer, the code still tests the Tcl version at runtime.
1696** This allows stubs-enabled builds to be used with older Tcl libraries.
1697*/
1698#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001699# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001700static int DbUseNre(void){
1701 int major, minor;
1702 Tcl_GetVersion(&major, &minor, 0, 0);
1703 return( (major==8 && minor>=6) || major>8 );
1704}
1705#else
mistachkinb56660f2016-07-14 21:26:09 +00001706/*
dan4a4c11a2009-10-06 14:59:02 +00001707** Compiling using headers earlier than 8.6. In this case NR cannot be
1708** used, so DbUseNre() to always return zero. Add #defines for the other
1709** Tcl_NRxxx() functions to prevent them from causing compilation errors,
mistachkinb56660f2016-07-14 21:26:09 +00001710** even though the only invocations of them are within conditional blocks
dan4a4c11a2009-10-06 14:59:02 +00001711** of the form:
1712**
1713** if( DbUseNre() ) { ... }
1714*/
drha2c8a952009-10-13 18:38:34 +00001715# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001716# define DbUseNre() 0
drha47941f2013-12-20 18:57:44 +00001717# define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001718# define Tcl_NREvalObj(a,b,c) 0
drha47941f2013-12-20 18:57:44 +00001719# define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001720#endif
1721
1722/*
1723** This function is part of the implementation of the command:
1724**
1725** $db eval SQL ?ARRAYNAME? SCRIPT
1726*/
mistachkina121cc72016-07-28 18:06:52 +00001727static int SQLITE_TCLAPI DbEvalNextCmd(
dan4a4c11a2009-10-06 14:59:02 +00001728 ClientData data[], /* data[0] is the (DbEvalContext*) */
1729 Tcl_Interp *interp, /* Tcl interpreter */
1730 int result /* Result so far */
1731){
1732 int rc = result; /* Return code */
1733
1734 /* The first element of the data[] array is a pointer to a DbEvalContext
1735 ** structure allocated using Tcl_Alloc(). The second element of data[]
1736 ** is a pointer to a Tcl_Obj containing the script to run for each row
1737 ** returned by the queries encapsulated in data[0]. */
1738 DbEvalContext *p = (DbEvalContext *)data[0];
1739 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1740 Tcl_Obj *pArray = p->pArray;
1741
1742 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1743 int i;
1744 int nCol;
1745 Tcl_Obj **apColName;
1746 dbEvalRowInfo(p, &nCol, &apColName);
1747 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00001748 if( pArray==0 ){
drhaf38cdb2017-06-26 21:08:32 +00001749 Tcl_ObjSetVar2(interp, apColName[i], 0, dbEvalColumnValue(p,i), 0);
1750 }else if( (p->evalFlags & SQLITE_EVAL_WITHOUTNULLS)!=0
1751 && sqlite3_column_type(p->pPreStmt->pStmt, i)==SQLITE_NULL
1752 ){
1753 Tcl_UnsetVar2(interp, Tcl_GetString(pArray),
1754 Tcl_GetString(apColName[i]), 0);
dan4a4c11a2009-10-06 14:59:02 +00001755 }else{
drhaf38cdb2017-06-26 21:08:32 +00001756 Tcl_ObjSetVar2(interp, pArray, apColName[i], dbEvalColumnValue(p,i), 0);
dan4a4c11a2009-10-06 14:59:02 +00001757 }
1758 }
1759
mistachkinb56660f2016-07-14 21:26:09 +00001760 /* The required interpreter variables are now populated with the data
dan4a4c11a2009-10-06 14:59:02 +00001761 ** from the current row. If using NRE, schedule callbacks to evaluate
1762 ** script pScript, then to invoke this function again to fetch the next
1763 ** row (or clean up if there is no next row or the script throws an
mistachkinb56660f2016-07-14 21:26:09 +00001764 ** exception). After scheduling the callbacks, return control to the
dan4a4c11a2009-10-06 14:59:02 +00001765 ** caller.
1766 **
1767 ** If not using NRE, evaluate pScript directly and continue with the
1768 ** next iteration of this while(...) loop. */
1769 if( DbUseNre() ){
1770 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1771 return Tcl_NREvalObj(interp, pScript, 0);
1772 }else{
1773 rc = Tcl_EvalObjEx(interp, pScript, 0);
1774 }
1775 }
1776
1777 Tcl_DecrRefCount(pScript);
1778 dbEvalFinalize(p);
1779 Tcl_Free((char *)p);
1780
1781 if( rc==TCL_OK || rc==TCL_BREAK ){
1782 Tcl_ResetResult(interp);
1783 rc = TCL_OK;
1784 }
1785 return rc;
danielk19778e556522007-11-13 10:30:24 +00001786}
1787
tpoindex1067fe12004-12-17 15:41:11 +00001788/*
mistachkinb56660f2016-07-14 21:26:09 +00001789** This function is used by the implementations of the following database
dan46c47d42011-03-01 18:42:07 +00001790** handle sub-commands:
1791**
1792** $db update_hook ?SCRIPT?
1793** $db wal_hook ?SCRIPT?
1794** $db commit_hook ?SCRIPT?
1795** $db preupdate hook ?SCRIPT?
1796*/
1797static void DbHookCmd(
1798 Tcl_Interp *interp, /* Tcl interpreter */
1799 SqliteDb *pDb, /* Database handle */
1800 Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */
1801 Tcl_Obj **ppHook /* Pointer to member of SqliteDb */
1802){
1803 sqlite3 *db = pDb->db;
1804
1805 if( *ppHook ){
1806 Tcl_SetObjResult(interp, *ppHook);
1807 if( pArg ){
1808 Tcl_DecrRefCount(*ppHook);
1809 *ppHook = 0;
1810 }
1811 }
1812 if( pArg ){
1813 assert( !(*ppHook) );
1814 if( Tcl_GetCharLength(pArg)>0 ){
1815 *ppHook = pArg;
1816 Tcl_IncrRefCount(*ppHook);
1817 }
1818 }
1819
drh9b1c62d2011-03-30 21:04:43 +00001820#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +00001821 sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
drh9b1c62d2011-03-30 21:04:43 +00001822#endif
dan46c47d42011-03-01 18:42:07 +00001823 sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1824 sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1825 sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
1826}
1827
1828/*
drh75897232000-05-29 14:26:00 +00001829** The "sqlite" command below creates a new Tcl command for each
1830** connection it opens to an SQLite database. This routine is invoked
1831** whenever one of those connection-specific commands is executed
1832** in Tcl. For example, if you run Tcl code like this:
1833**
drh9bb575f2004-09-06 17:24:11 +00001834** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001835** db1 close
1836**
1837** The first command opens a connection to the "my_database" database
1838** and calls that connection "db1". The second command causes this
1839** subroutine to be invoked.
1840*/
mistachkin7617e4a2016-07-28 17:11:20 +00001841static int SQLITE_TCLAPI DbObjCmd(
1842 void *cd,
1843 Tcl_Interp *interp,
1844 int objc,
1845 Tcl_Obj *const*objv
1846){
drhbec3f402000-08-04 13:49:02 +00001847 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001848 int choice;
drh22fbcb82004-02-01 01:22:50 +00001849 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001850 static const char *DB_strs[] = {
drhcb7d5412018-01-03 16:49:52 +00001851 "authorizer", "backup", "busy",
1852 "cache", "changes", "close",
1853 "collate", "collation_needed", "commit_hook",
1854 "complete", "copy", "deserialize",
1855 "enable_load_extension", "errorcode", "eval",
1856 "exists", "function", "incrblob",
drh3ec86652018-01-03 19:03:31 +00001857 "interrupt", "last_insert_rowid", "nullvalue",
1858 "onecolumn", "preupdate", "profile",
1859 "progress", "rekey", "restore",
1860 "rollback_hook", "serialize", "status",
1861 "timeout", "total_changes", "trace",
1862 "trace_v2", "transaction", "unlock_notify",
1863 "update_hook", "version", "wal_hook",
1864 0
drh6d313162000-09-21 13:01:35 +00001865 };
drh411995d2002-06-25 19:31:18 +00001866 enum DB_enum {
drhcb7d5412018-01-03 16:49:52 +00001867 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1868 DB_CACHE, DB_CHANGES, DB_CLOSE,
1869 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1870 DB_COMPLETE, DB_COPY, DB_DESERIALIZE,
1871 DB_ENABLE_LOAD_EXTENSION, DB_ERRORCODE, DB_EVAL,
1872 DB_EXISTS, DB_FUNCTION, DB_INCRBLOB,
drh3ec86652018-01-03 19:03:31 +00001873 DB_INTERRUPT, DB_LAST_INSERT_ROWID, DB_NULLVALUE,
1874 DB_ONECOLUMN, DB_PREUPDATE, DB_PROFILE,
1875 DB_PROGRESS, DB_REKEY, DB_RESTORE,
1876 DB_ROLLBACK_HOOK, DB_SERIALIZE, DB_STATUS,
1877 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
1878 DB_TRACE_V2, DB_TRANSACTION, DB_UNLOCK_NOTIFY,
1879 DB_UPDATE_HOOK, DB_VERSION, DB_WAL_HOOK
drh6d313162000-09-21 13:01:35 +00001880 };
tpoindex1067fe12004-12-17 15:41:11 +00001881 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001882
1883 if( objc<2 ){
1884 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001885 return TCL_ERROR;
1886 }
drh411995d2002-06-25 19:31:18 +00001887 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001888 return TCL_ERROR;
1889 }
1890
drh411995d2002-06-25 19:31:18 +00001891 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001892
drhe22a3342003-04-22 20:30:37 +00001893 /* $db authorizer ?CALLBACK?
1894 **
1895 ** Invoke the given callback to authorize each SQL operation as it is
1896 ** compiled. 5 arguments are appended to the callback before it is
1897 ** invoked:
1898 **
1899 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1900 ** (2) First descriptive name (depends on authorization type)
1901 ** (3) Second descriptive name
1902 ** (4) Name of the database (ex: "main", "temp")
1903 ** (5) Name of trigger that is doing the access
1904 **
1905 ** The callback should return on of the following strings: SQLITE_OK,
1906 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1907 **
1908 ** If this method is invoked with no arguments, the current authorization
1909 ** callback string is returned.
1910 */
1911 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001912#ifdef SQLITE_OMIT_AUTHORIZATION
drha198f2b2014-02-07 19:26:13 +00001913 Tcl_AppendResult(interp, "authorization not available in this build",
1914 (char*)0);
drh1211de32004-07-26 12:24:22 +00001915 return TCL_ERROR;
1916#else
drhe22a3342003-04-22 20:30:37 +00001917 if( objc>3 ){
1918 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001919 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001920 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001921 if( pDb->zAuth ){
drha198f2b2014-02-07 19:26:13 +00001922 Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
drhe22a3342003-04-22 20:30:37 +00001923 }
1924 }else{
1925 char *zAuth;
1926 int len;
1927 if( pDb->zAuth ){
1928 Tcl_Free(pDb->zAuth);
1929 }
1930 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1931 if( zAuth && len>0 ){
1932 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001933 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001934 }else{
1935 pDb->zAuth = 0;
1936 }
drhe22a3342003-04-22 20:30:37 +00001937 if( pDb->zAuth ){
drh32c6a482014-09-11 13:44:52 +00001938 typedef int (*sqlite3_auth_cb)(
1939 void*,int,const char*,const char*,
1940 const char*,const char*);
drhe22a3342003-04-22 20:30:37 +00001941 pDb->interp = interp;
drh32c6a482014-09-11 13:44:52 +00001942 sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
drhe22a3342003-04-22 20:30:37 +00001943 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001944 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001945 }
drhe22a3342003-04-22 20:30:37 +00001946 }
drh1211de32004-07-26 12:24:22 +00001947#endif
drhe22a3342003-04-22 20:30:37 +00001948 break;
1949 }
1950
drhdc2c4912009-02-04 22:46:47 +00001951 /* $db backup ?DATABASE? FILENAME
1952 **
1953 ** Open or create a database file named FILENAME. Transfer the
1954 ** content of local database DATABASE (default: "main") into the
1955 ** FILENAME database.
1956 */
1957 case DB_BACKUP: {
1958 const char *zDestFile;
1959 const char *zSrcDb;
1960 sqlite3 *pDest;
1961 sqlite3_backup *pBackup;
1962
1963 if( objc==3 ){
1964 zSrcDb = "main";
1965 zDestFile = Tcl_GetString(objv[2]);
1966 }else if( objc==4 ){
1967 zSrcDb = Tcl_GetString(objv[2]);
1968 zDestFile = Tcl_GetString(objv[3]);
1969 }else{
1970 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1971 return TCL_ERROR;
1972 }
drh147ef392016-01-22 23:17:51 +00001973 rc = sqlite3_open_v2(zDestFile, &pDest,
1974 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00001975 if( rc!=SQLITE_OK ){
1976 Tcl_AppendResult(interp, "cannot open target database: ",
1977 sqlite3_errmsg(pDest), (char*)0);
1978 sqlite3_close(pDest);
1979 return TCL_ERROR;
1980 }
1981 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1982 if( pBackup==0 ){
1983 Tcl_AppendResult(interp, "backup failed: ",
1984 sqlite3_errmsg(pDest), (char*)0);
1985 sqlite3_close(pDest);
1986 return TCL_ERROR;
1987 }
1988 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1989 sqlite3_backup_finish(pBackup);
1990 if( rc==SQLITE_DONE ){
1991 rc = TCL_OK;
1992 }else{
1993 Tcl_AppendResult(interp, "backup failed: ",
1994 sqlite3_errmsg(pDest), (char*)0);
1995 rc = TCL_ERROR;
1996 }
1997 sqlite3_close(pDest);
1998 break;
1999 }
2000
drhbec3f402000-08-04 13:49:02 +00002001 /* $db busy ?CALLBACK?
2002 **
2003 ** Invoke the given callback if an SQL statement attempts to open
2004 ** a locked database file.
2005 */
drh6d313162000-09-21 13:01:35 +00002006 case DB_BUSY: {
2007 if( objc>3 ){
2008 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00002009 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00002010 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00002011 if( pDb->zBusy ){
drha198f2b2014-02-07 19:26:13 +00002012 Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
drhbec3f402000-08-04 13:49:02 +00002013 }
2014 }else{
drh6d313162000-09-21 13:01:35 +00002015 char *zBusy;
2016 int len;
drhbec3f402000-08-04 13:49:02 +00002017 if( pDb->zBusy ){
2018 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00002019 }
drh6d313162000-09-21 13:01:35 +00002020 zBusy = Tcl_GetStringFromObj(objv[2], &len);
2021 if( zBusy && len>0 ){
2022 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002023 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00002024 }else{
2025 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00002026 }
2027 if( pDb->zBusy ){
2028 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002029 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00002030 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002031 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00002032 }
2033 }
drh6d313162000-09-21 13:01:35 +00002034 break;
2035 }
drhbec3f402000-08-04 13:49:02 +00002036
drhfb7e7652005-01-24 00:28:42 +00002037 /* $db cache flush
2038 ** $db cache size n
2039 **
2040 ** Flush the prepared statement cache, or set the maximum number of
2041 ** cached statements.
2042 */
2043 case DB_CACHE: {
2044 char *subCmd;
2045 int n;
2046
2047 if( objc<=2 ){
2048 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
2049 return TCL_ERROR;
2050 }
2051 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
2052 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
2053 if( objc!=3 ){
2054 Tcl_WrongNumArgs(interp, 2, objv, "flush");
2055 return TCL_ERROR;
2056 }else{
2057 flushStmtCache( pDb );
2058 }
2059 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
2060 if( objc!=4 ){
2061 Tcl_WrongNumArgs(interp, 2, objv, "size n");
2062 return TCL_ERROR;
2063 }else{
2064 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
mistachkinb56660f2016-07-14 21:26:09 +00002065 Tcl_AppendResult( interp, "cannot convert \"",
drha198f2b2014-02-07 19:26:13 +00002066 Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
drhfb7e7652005-01-24 00:28:42 +00002067 return TCL_ERROR;
2068 }else{
2069 if( n<0 ){
2070 flushStmtCache( pDb );
2071 n = 0;
2072 }else if( n>MAX_PREPARED_STMTS ){
2073 n = MAX_PREPARED_STMTS;
2074 }
2075 pDb->maxStmt = n;
2076 }
2077 }
2078 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002079 Tcl_AppendResult( interp, "bad option \"",
drha198f2b2014-02-07 19:26:13 +00002080 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
2081 (char*)0);
drhfb7e7652005-01-24 00:28:42 +00002082 return TCL_ERROR;
2083 }
2084 break;
2085 }
2086
danielk1977b28af712004-06-21 06:50:26 +00002087 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00002088 **
2089 ** Return the number of rows that were modified, inserted, or deleted by
mistachkinb56660f2016-07-14 21:26:09 +00002090 ** the most recent INSERT, UPDATE or DELETE statement, not including
danielk1977b28af712004-06-21 06:50:26 +00002091 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00002092 */
2093 case DB_CHANGES: {
2094 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00002095 if( objc!=2 ){
2096 Tcl_WrongNumArgs(interp, 2, objv, "");
2097 return TCL_ERROR;
2098 }
drhc8d30ac2002-04-12 10:08:59 +00002099 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00002100 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00002101 break;
2102 }
2103
drh75897232000-05-29 14:26:00 +00002104 /* $db close
2105 **
2106 ** Shutdown the database
2107 */
drh6d313162000-09-21 13:01:35 +00002108 case DB_CLOSE: {
2109 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
2110 break;
2111 }
drh75897232000-05-29 14:26:00 +00002112
drh0f14e2e2004-06-29 12:39:08 +00002113 /*
2114 ** $db collate NAME SCRIPT
2115 **
2116 ** Create a new SQL collation function called NAME. Whenever
2117 ** that function is called, invoke SCRIPT to evaluate the function.
2118 */
2119 case DB_COLLATE: {
2120 SqlCollate *pCollate;
2121 char *zName;
2122 char *zScript;
2123 int nScript;
2124 if( objc!=4 ){
2125 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
2126 return TCL_ERROR;
2127 }
2128 zName = Tcl_GetStringFromObj(objv[2], 0);
2129 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
2130 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
2131 if( pCollate==0 ) return TCL_ERROR;
2132 pCollate->interp = interp;
2133 pCollate->pNext = pDb->pCollate;
2134 pCollate->zScript = (char*)&pCollate[1];
2135 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00002136 memcpy(pCollate->zScript, zScript, nScript+1);
mistachkinb56660f2016-07-14 21:26:09 +00002137 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
drh0f14e2e2004-06-29 12:39:08 +00002138 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00002139 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00002140 return TCL_ERROR;
2141 }
2142 break;
2143 }
2144
2145 /*
2146 ** $db collation_needed SCRIPT
2147 **
2148 ** Create a new SQL collation function called NAME. Whenever
2149 ** that function is called, invoke SCRIPT to evaluate the function.
2150 */
2151 case DB_COLLATION_NEEDED: {
2152 if( objc!=3 ){
2153 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
2154 return TCL_ERROR;
2155 }
2156 if( pDb->pCollateNeeded ){
2157 Tcl_DecrRefCount(pDb->pCollateNeeded);
2158 }
2159 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
2160 Tcl_IncrRefCount(pDb->pCollateNeeded);
2161 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
2162 break;
2163 }
2164
drh19e2d372005-08-29 23:00:03 +00002165 /* $db commit_hook ?CALLBACK?
2166 **
2167 ** Invoke the given callback just before committing every SQL transaction.
2168 ** If the callback throws an exception or returns non-zero, then the
2169 ** transaction is aborted. If CALLBACK is an empty string, the callback
2170 ** is disabled.
2171 */
2172 case DB_COMMIT_HOOK: {
2173 if( objc>3 ){
2174 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2175 return TCL_ERROR;
2176 }else if( objc==2 ){
2177 if( pDb->zCommit ){
drha198f2b2014-02-07 19:26:13 +00002178 Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002179 }
2180 }else{
mistachkin6ef5e122014-01-24 17:03:55 +00002181 const char *zCommit;
drh19e2d372005-08-29 23:00:03 +00002182 int len;
2183 if( pDb->zCommit ){
2184 Tcl_Free(pDb->zCommit);
2185 }
2186 zCommit = Tcl_GetStringFromObj(objv[2], &len);
2187 if( zCommit && len>0 ){
2188 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002189 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00002190 }else{
2191 pDb->zCommit = 0;
2192 }
2193 if( pDb->zCommit ){
2194 pDb->interp = interp;
2195 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
2196 }else{
2197 sqlite3_commit_hook(pDb->db, 0, 0);
2198 }
2199 }
2200 break;
2201 }
2202
drh75897232000-05-29 14:26:00 +00002203 /* $db complete SQL
2204 **
2205 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2206 ** additional lines of input are needed. This is similar to the
2207 ** built-in "info complete" command of Tcl.
2208 */
drh6d313162000-09-21 13:01:35 +00002209 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00002210#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00002211 Tcl_Obj *pResult;
2212 int isComplete;
2213 if( objc!=3 ){
2214 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00002215 return TCL_ERROR;
2216 }
danielk19776f8a5032004-05-10 10:34:51 +00002217 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00002218 pResult = Tcl_GetObjResult(interp);
2219 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00002220#endif
drh6d313162000-09-21 13:01:35 +00002221 break;
2222 }
drhdcd997e2003-01-31 17:21:49 +00002223
drh19e2d372005-08-29 23:00:03 +00002224 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2225 **
2226 ** Copy data into table from filename, optionally using SEPARATOR
2227 ** as column separators. If a column contains a null string, or the
2228 ** value of NULLINDICATOR, a NULL is inserted for the column.
2229 ** conflict-algorithm is one of the sqlite conflict algorithms:
2230 ** rollback, abort, fail, ignore, replace
2231 ** On success, return the number of lines processed, not necessarily same
2232 ** as 'db changes' due to conflict-algorithm selected.
2233 **
2234 ** This code is basically an implementation/enhancement of
2235 ** the sqlite3 shell.c ".import" command.
2236 **
2237 ** This command usage is equivalent to the sqlite2.x COPY statement,
2238 ** which imports file data into a table using the PostgreSQL COPY file format:
2239 ** $db copy $conflit_algo $table_name $filename \t \\N
2240 */
2241 case DB_COPY: {
2242 char *zTable; /* Insert data into this table */
2243 char *zFile; /* The file from which to extract data */
2244 char *zConflict; /* The conflict algorithm to use */
2245 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00002246 int nCol; /* Number of columns in the table */
2247 int nByte; /* Number of bytes in an SQL string */
2248 int i, j; /* Loop counters */
2249 int nSep; /* Number of bytes in zSep[] */
2250 int nNull; /* Number of bytes in zNull[] */
2251 char *zSql; /* An SQL statement */
2252 char *zLine; /* A single line of input from the file */
2253 char **azCol; /* zLine[] broken up into columns */
mistachkin6ef5e122014-01-24 17:03:55 +00002254 const char *zCommit; /* How to commit changes */
drh19e2d372005-08-29 23:00:03 +00002255 FILE *in; /* The input file */
2256 int lineno = 0; /* Line number of input file */
2257 char zLineNum[80]; /* Line number print buffer */
2258 Tcl_Obj *pResult; /* interp result */
2259
mistachkin6ef5e122014-01-24 17:03:55 +00002260 const char *zSep;
2261 const char *zNull;
drh19e2d372005-08-29 23:00:03 +00002262 if( objc<5 || objc>7 ){
mistachkinb56660f2016-07-14 21:26:09 +00002263 Tcl_WrongNumArgs(interp, 2, objv,
drh19e2d372005-08-29 23:00:03 +00002264 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2265 return TCL_ERROR;
2266 }
2267 if( objc>=6 ){
2268 zSep = Tcl_GetStringFromObj(objv[5], 0);
2269 }else{
2270 zSep = "\t";
2271 }
2272 if( objc>=7 ){
2273 zNull = Tcl_GetStringFromObj(objv[6], 0);
2274 }else{
2275 zNull = "";
2276 }
2277 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2278 zTable = Tcl_GetStringFromObj(objv[3], 0);
2279 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002280 nSep = strlen30(zSep);
2281 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002282 if( nSep==0 ){
drha198f2b2014-02-07 19:26:13 +00002283 Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2284 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002285 return TCL_ERROR;
2286 }
drh3e59c012008-09-23 10:12:13 +00002287 if(strcmp(zConflict, "rollback") != 0 &&
2288 strcmp(zConflict, "abort" ) != 0 &&
2289 strcmp(zConflict, "fail" ) != 0 &&
2290 strcmp(zConflict, "ignore" ) != 0 &&
2291 strcmp(zConflict, "replace" ) != 0 ) {
mistachkinb56660f2016-07-14 21:26:09 +00002292 Tcl_AppendResult(interp, "Error: \"", zConflict,
drh19e2d372005-08-29 23:00:03 +00002293 "\", conflict-algorithm must be one of: rollback, "
drha198f2b2014-02-07 19:26:13 +00002294 "abort, fail, ignore, or replace", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002295 return TCL_ERROR;
2296 }
2297 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2298 if( zSql==0 ){
drha198f2b2014-02-07 19:26:13 +00002299 Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002300 return TCL_ERROR;
2301 }
drh4f21c4a2008-12-10 22:15:00 +00002302 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002303 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002304 sqlite3_free(zSql);
2305 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002306 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002307 nCol = 0;
2308 }else{
2309 nCol = sqlite3_column_count(pStmt);
2310 }
2311 sqlite3_finalize(pStmt);
2312 if( nCol==0 ) {
2313 return TCL_ERROR;
2314 }
2315 zSql = malloc( nByte + 50 + nCol*2 );
2316 if( zSql==0 ) {
drha198f2b2014-02-07 19:26:13 +00002317 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002318 return TCL_ERROR;
2319 }
2320 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2321 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002322 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002323 for(i=1; i<nCol; i++){
2324 zSql[j++] = ',';
2325 zSql[j++] = '?';
2326 }
2327 zSql[j++] = ')';
2328 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002329 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002330 free(zSql);
2331 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002332 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002333 sqlite3_finalize(pStmt);
2334 return TCL_ERROR;
2335 }
2336 in = fopen(zFile, "rb");
2337 if( in==0 ){
drhea8f0a12017-01-12 11:50:08 +00002338 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002339 sqlite3_finalize(pStmt);
2340 return TCL_ERROR;
2341 }
2342 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2343 if( azCol==0 ) {
drha198f2b2014-02-07 19:26:13 +00002344 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh43617e92006-03-06 20:55:46 +00002345 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002346 return TCL_ERROR;
2347 }
drh37527852006-03-16 16:19:56 +00002348 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002349 zCommit = "COMMIT";
2350 while( (zLine = local_getline(0, in))!=0 ){
2351 char *z;
drh19e2d372005-08-29 23:00:03 +00002352 lineno++;
2353 azCol[0] = zLine;
2354 for(i=0, z=zLine; *z; z++){
2355 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2356 *z = 0;
2357 i++;
2358 if( i<nCol ){
2359 azCol[i] = &z[nSep];
2360 z += nSep-1;
2361 }
2362 }
2363 }
2364 if( i+1!=nCol ){
2365 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002366 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002367 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002368 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002369 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002370 "Error: %s line %d: expected %d columns of data but found %d",
2371 zFile, lineno, nCol, i+1);
drha198f2b2014-02-07 19:26:13 +00002372 Tcl_AppendResult(interp, zErr, (char*)0);
drhc1f44942006-05-10 14:39:13 +00002373 free(zErr);
2374 }
drh19e2d372005-08-29 23:00:03 +00002375 zCommit = "ROLLBACK";
2376 break;
2377 }
2378 for(i=0; i<nCol; i++){
2379 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002380 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
mistachkinb56660f2016-07-14 21:26:09 +00002381 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002382 ){
drh19e2d372005-08-29 23:00:03 +00002383 sqlite3_bind_null(pStmt, i+1);
2384 }else{
2385 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2386 }
2387 }
2388 sqlite3_step(pStmt);
2389 rc = sqlite3_reset(pStmt);
2390 free(zLine);
2391 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00002392 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002393 zCommit = "ROLLBACK";
2394 break;
2395 }
2396 }
2397 free(azCol);
2398 fclose(in);
2399 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002400 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002401
2402 if( zCommit[0] == 'C' ){
2403 /* success, set result as number of lines processed */
2404 pResult = Tcl_GetObjResult(interp);
2405 Tcl_SetIntObj(pResult, lineno);
2406 rc = TCL_OK;
2407 }else{
2408 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002409 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drha198f2b2014-02-07 19:26:13 +00002410 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2411 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002412 rc = TCL_ERROR;
2413 }
2414 break;
2415 }
2416
drhdcd997e2003-01-31 17:21:49 +00002417 /*
drhcb7d5412018-01-03 16:49:52 +00002418 ** $db deserialize ?DATABASE? VALUE
2419 **
2420 ** Reopen DATABASE (default "main") using the content in $VALUE
2421 */
2422 case DB_DESERIALIZE: {
drh9c6396e2018-03-06 21:43:19 +00002423#ifndef SQLITE_ENABLE_DESERIALIZE
drh3ec86652018-01-03 19:03:31 +00002424 Tcl_AppendResult(interp, "MEMDB not available in this build",
2425 (char*)0);
2426 rc = TCL_ERROR;
2427#else
2428 const char *zSchema;
2429 Tcl_Obj *pValue;
2430 unsigned char *pBA;
2431 unsigned char *pData;
2432 int len, xrc;
2433
2434 if( objc==3 ){
2435 zSchema = 0;
2436 pValue = objv[2];
2437 }else if( objc==4 ){
2438 zSchema = Tcl_GetString(objv[2]);
2439 pValue = objv[3];
2440 }else{
2441 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? VALUE");
2442 rc = TCL_ERROR;
2443 break;
2444 }
2445 pBA = Tcl_GetByteArrayFromObj(pValue, &len);
2446 pData = sqlite3_malloc64( len );
drha5bb4352018-01-03 23:40:02 +00002447 if( pData==0 && len>0 ){
drh3ec86652018-01-03 19:03:31 +00002448 Tcl_AppendResult(interp, "out of memory", (char*)0);
2449 rc = TCL_ERROR;
2450 }else{
drha5bb4352018-01-03 23:40:02 +00002451 if( len>0 ) memcpy(pData, pBA, len);
drh3ec86652018-01-03 19:03:31 +00002452 xrc = sqlite3_deserialize(pDb->db, zSchema, pData, len, len,
2453 SQLITE_DESERIALIZE_FREEONCLOSE |
2454 SQLITE_DESERIALIZE_RESIZEABLE);
2455 if( xrc ){
2456 Tcl_AppendResult(interp, "unable to set MEMDB content", (char*)0);
2457 rc = TCL_ERROR;
2458 }
2459 }
2460#endif
drhcb7d5412018-01-03 16:49:52 +00002461 break;
2462 }
2463
2464 /*
drh41449052006-07-06 17:08:48 +00002465 ** $db enable_load_extension BOOLEAN
2466 **
2467 ** Turn the extension loading feature on or off. It if off by
2468 ** default.
2469 */
2470 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002471#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002472 int onoff;
2473 if( objc!=3 ){
2474 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2475 return TCL_ERROR;
2476 }
2477 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2478 return TCL_ERROR;
2479 }
2480 sqlite3_enable_load_extension(pDb->db, onoff);
2481 break;
drhf533acc2006-12-19 18:57:11 +00002482#else
2483 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
drha198f2b2014-02-07 19:26:13 +00002484 (char*)0);
drhf533acc2006-12-19 18:57:11 +00002485 return TCL_ERROR;
2486#endif
drh41449052006-07-06 17:08:48 +00002487 }
2488
2489 /*
drhdcd997e2003-01-31 17:21:49 +00002490 ** $db errorcode
2491 **
2492 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002493 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002494 */
2495 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002496 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002497 break;
2498 }
dan4a4c11a2009-10-06 14:59:02 +00002499
2500 /*
2501 ** $db exists $sql
2502 ** $db onecolumn $sql
2503 **
2504 ** The onecolumn method is the equivalent of:
2505 ** lindex [$db eval $sql] 0
2506 */
mistachkinb56660f2016-07-14 21:26:09 +00002507 case DB_EXISTS:
dan4a4c11a2009-10-06 14:59:02 +00002508 case DB_ONECOLUMN: {
drhedc40242016-06-13 12:34:38 +00002509 Tcl_Obj *pResult = 0;
dan4a4c11a2009-10-06 14:59:02 +00002510 DbEvalContext sEval;
2511 if( objc!=3 ){
2512 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2513 return TCL_ERROR;
2514 }
2515
drhaf38cdb2017-06-26 21:08:32 +00002516 dbEvalInit(&sEval, pDb, objv[2], 0, 0);
dan4a4c11a2009-10-06 14:59:02 +00002517 rc = dbEvalStep(&sEval);
2518 if( choice==DB_ONECOLUMN ){
2519 if( rc==TCL_OK ){
drhedc40242016-06-13 12:34:38 +00002520 pResult = dbEvalColumnValue(&sEval, 0);
dand5f12cd2011-08-18 17:47:57 +00002521 }else if( rc==TCL_BREAK ){
2522 Tcl_ResetResult(interp);
dan4a4c11a2009-10-06 14:59:02 +00002523 }
2524 }else if( rc==TCL_BREAK || rc==TCL_OK ){
drhedc40242016-06-13 12:34:38 +00002525 pResult = Tcl_NewBooleanObj(rc==TCL_OK);
dan4a4c11a2009-10-06 14:59:02 +00002526 }
2527 dbEvalFinalize(&sEval);
drhedc40242016-06-13 12:34:38 +00002528 if( pResult ) Tcl_SetObjResult(interp, pResult);
dan4a4c11a2009-10-06 14:59:02 +00002529
2530 if( rc==TCL_BREAK ){
2531 rc = TCL_OK;
2532 }
2533 break;
2534 }
mistachkinb56660f2016-07-14 21:26:09 +00002535
drh75897232000-05-29 14:26:00 +00002536 /*
drhaf38cdb2017-06-26 21:08:32 +00002537 ** $db eval ?options? $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002538 **
2539 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002540 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002541 ** If "array" and "code" are omitted, then no callback is every invoked.
2542 ** If "array" is an empty string, then the values are placed in variables
2543 ** that have the same name as the fields extracted by the query.
2544 */
dan4a4c11a2009-10-06 14:59:02 +00002545 case DB_EVAL: {
drhaf38cdb2017-06-26 21:08:32 +00002546 int evalFlags = 0;
2547 const char *zOpt;
2548 while( objc>3 && (zOpt = Tcl_GetString(objv[2]))!=0 && zOpt[0]=='-' ){
2549 if( strcmp(zOpt, "-withoutnulls")==0 ){
2550 evalFlags |= SQLITE_EVAL_WITHOUTNULLS;
2551 }
2552 else{
2553 Tcl_AppendResult(interp, "unknown option: \"", zOpt, "\"", (void*)0);
2554 return TCL_ERROR;
2555 }
2556 objc--;
2557 objv++;
2558 }
dan4a4c11a2009-10-06 14:59:02 +00002559 if( objc<3 || objc>5 ){
drhaf38cdb2017-06-26 21:08:32 +00002560 Tcl_WrongNumArgs(interp, 2, objv,
2561 "?OPTIONS? SQL ?ARRAY-NAME? ?SCRIPT?");
dan4a4c11a2009-10-06 14:59:02 +00002562 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002563 }
dan4a4c11a2009-10-06 14:59:02 +00002564
drh92febd92004-08-20 18:34:20 +00002565 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002566 DbEvalContext sEval;
2567 Tcl_Obj *pRet = Tcl_NewObj();
2568 Tcl_IncrRefCount(pRet);
drhaf38cdb2017-06-26 21:08:32 +00002569 dbEvalInit(&sEval, pDb, objv[2], 0, 0);
dan4a4c11a2009-10-06 14:59:02 +00002570 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2571 int i;
2572 int nCol;
2573 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002574 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002575 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002576 }
2577 }
dan4a4c11a2009-10-06 14:59:02 +00002578 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002579 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002580 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002581 rc = TCL_OK;
2582 }
drh1807ce32004-09-07 13:20:35 +00002583 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002584 }else{
mistachkin8e189222015-04-19 21:43:16 +00002585 ClientData cd2[2];
dan4a4c11a2009-10-06 14:59:02 +00002586 DbEvalContext *p;
2587 Tcl_Obj *pArray = 0;
2588 Tcl_Obj *pScript;
2589
drhaf38cdb2017-06-26 21:08:32 +00002590 if( objc>=5 && *(char *)Tcl_GetString(objv[3]) ){
dan4a4c11a2009-10-06 14:59:02 +00002591 pArray = objv[3];
2592 }
2593 pScript = objv[objc-1];
2594 Tcl_IncrRefCount(pScript);
mistachkinb56660f2016-07-14 21:26:09 +00002595
dan4a4c11a2009-10-06 14:59:02 +00002596 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
drhaf38cdb2017-06-26 21:08:32 +00002597 dbEvalInit(p, pDb, objv[2], pArray, evalFlags);
dan4a4c11a2009-10-06 14:59:02 +00002598
mistachkin8e189222015-04-19 21:43:16 +00002599 cd2[0] = (void *)p;
2600 cd2[1] = (void *)pScript;
2601 rc = DbEvalNextCmd(cd2, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002602 }
danielk197730ccda12004-05-27 12:11:31 +00002603 break;
2604 }
drhbec3f402000-08-04 13:49:02 +00002605
2606 /*
dan3df30592015-03-13 08:31:54 +00002607 ** $db function NAME [-argcount N] [-deterministic] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002608 **
2609 ** Create a new SQL function called NAME. Whenever that function is
2610 ** called, invoke SCRIPT to evaluate the function.
2611 */
2612 case DB_FUNCTION: {
dan3df30592015-03-13 08:31:54 +00002613 int flags = SQLITE_UTF8;
drhcabb0812002-09-14 13:47:32 +00002614 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002615 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002616 char *zName;
drhe3602be2008-09-09 12:31:33 +00002617 int nArg = -1;
dan3df30592015-03-13 08:31:54 +00002618 int i;
2619 if( objc<4 ){
2620 Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
2621 return TCL_ERROR;
2622 }
2623 for(i=3; i<(objc-1); i++){
2624 const char *z = Tcl_GetString(objv[i]);
drh4f21c4a2008-12-10 22:15:00 +00002625 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002626 if( n>2 && strncmp(z, "-argcount",n)==0 ){
dan3df30592015-03-13 08:31:54 +00002627 if( i==(objc-2) ){
drhea8f0a12017-01-12 11:50:08 +00002628 Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0);
dan3df30592015-03-13 08:31:54 +00002629 return TCL_ERROR;
2630 }
2631 if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002632 if( nArg<0 ){
2633 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2634 (char*)0);
2635 return TCL_ERROR;
2636 }
dan3df30592015-03-13 08:31:54 +00002637 i++;
2638 }else
2639 if( n>2 && strncmp(z, "-deterministic",n)==0 ){
2640 flags |= SQLITE_DETERMINISTIC;
2641 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002642 Tcl_AppendResult(interp, "bad option \"", z,
drhea8f0a12017-01-12 11:50:08 +00002643 "\": must be -argcount or -deterministic", (char*)0
dan3df30592015-03-13 08:31:54 +00002644 );
2645 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002646 }
drhcabb0812002-09-14 13:47:32 +00002647 }
dan3df30592015-03-13 08:31:54 +00002648
2649 pScript = objv[objc-1];
drhcabb0812002-09-14 13:47:32 +00002650 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002651 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002652 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002653 if( pFunc->pScript ){
2654 Tcl_DecrRefCount(pFunc->pScript);
2655 }
2656 pFunc->pScript = pScript;
2657 Tcl_IncrRefCount(pScript);
2658 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
dan3df30592015-03-13 08:31:54 +00002659 rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
danielk1977d8123362004-06-12 09:25:12 +00002660 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002661 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002662 rc = TCL_ERROR;
2663 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002664 }
drhcabb0812002-09-14 13:47:32 +00002665 break;
2666 }
2667
2668 /*
danielk19778cbadb02007-05-03 16:31:26 +00002669 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002670 */
2671 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002672#ifdef SQLITE_OMIT_INCRBLOB
drha198f2b2014-02-07 19:26:13 +00002673 Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
danielk197732a0d8b2007-05-04 19:03:02 +00002674 return TCL_ERROR;
2675#else
danielk19778cbadb02007-05-03 16:31:26 +00002676 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002677 const char *zDb = "main";
2678 const char *zTable;
2679 const char *zColumn;
drhb3f787f2012-09-29 14:45:54 +00002680 Tcl_WideInt iRow;
danielk1977b4e9af92007-05-01 17:49:49 +00002681
danielk19778cbadb02007-05-03 16:31:26 +00002682 /* Check for the -readonly option */
2683 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2684 isReadonly = 1;
2685 }
2686
2687 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2688 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002689 return TCL_ERROR;
2690 }
2691
danielk19778cbadb02007-05-03 16:31:26 +00002692 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002693 zDb = Tcl_GetString(objv[2]);
2694 }
2695 zTable = Tcl_GetString(objv[objc-3]);
2696 zColumn = Tcl_GetString(objv[objc-2]);
2697 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2698
2699 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002700 rc = createIncrblobChannel(
danedf5b162014-08-19 09:15:41 +00002701 interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
danielk19778cbadb02007-05-03 16:31:26 +00002702 );
danielk1977b4e9af92007-05-01 17:49:49 +00002703 }
danielk197732a0d8b2007-05-04 19:03:02 +00002704#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002705 break;
2706 }
2707
2708 /*
drhf11bded2006-07-17 00:02:44 +00002709 ** $db interrupt
2710 **
2711 ** Interrupt the execution of the inner-most SQL interpreter. This
2712 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2713 */
2714 case DB_INTERRUPT: {
2715 sqlite3_interrupt(pDb->db);
2716 break;
2717 }
2718
2719 /*
drh19e2d372005-08-29 23:00:03 +00002720 ** $db nullvalue ?STRING?
2721 **
2722 ** Change text used when a NULL comes back from the database. If ?STRING?
2723 ** is not present, then the current string used for NULL is returned.
2724 ** If STRING is present, then STRING is returned.
2725 **
2726 */
2727 case DB_NULLVALUE: {
2728 if( objc!=2 && objc!=3 ){
2729 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2730 return TCL_ERROR;
2731 }
2732 if( objc==3 ){
2733 int len;
2734 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2735 if( pDb->zNull ){
2736 Tcl_Free(pDb->zNull);
2737 }
2738 if( zNull && len>0 ){
2739 pDb->zNull = Tcl_Alloc( len + 1 );
drh7fd33922011-06-20 19:00:30 +00002740 memcpy(pDb->zNull, zNull, len);
drh19e2d372005-08-29 23:00:03 +00002741 pDb->zNull[len] = '\0';
2742 }else{
2743 pDb->zNull = 0;
2744 }
2745 }
drhc45e6712012-10-03 11:02:33 +00002746 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
drh19e2d372005-08-29 23:00:03 +00002747 break;
2748 }
2749
2750 /*
mistachkinb56660f2016-07-14 21:26:09 +00002751 ** $db last_insert_rowid
drhaf9ff332002-01-16 21:00:27 +00002752 **
2753 ** Return an integer which is the ROWID for the most recent insert.
2754 */
2755 case DB_LAST_INSERT_ROWID: {
2756 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002757 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002758 if( objc!=2 ){
2759 Tcl_WrongNumArgs(interp, 2, objv, "");
2760 return TCL_ERROR;
2761 }
danielk19776f8a5032004-05-10 10:34:51 +00002762 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002763 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002764 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002765 break;
2766 }
2767
2768 /*
dan4a4c11a2009-10-06 14:59:02 +00002769 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002770 */
drh1807ce32004-09-07 13:20:35 +00002771
2772 /* $db progress ?N CALLBACK?
mistachkinb56660f2016-07-14 21:26:09 +00002773 **
drh1807ce32004-09-07 13:20:35 +00002774 ** Invoke the given callback every N virtual machine opcodes while executing
2775 ** queries.
2776 */
2777 case DB_PROGRESS: {
2778 if( objc==2 ){
2779 if( pDb->zProgress ){
drha198f2b2014-02-07 19:26:13 +00002780 Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
drh1807ce32004-09-07 13:20:35 +00002781 }
2782 }else if( objc==4 ){
2783 char *zProgress;
2784 int len;
2785 int N;
2786 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002787 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002788 };
2789 if( pDb->zProgress ){
2790 Tcl_Free(pDb->zProgress);
2791 }
2792 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2793 if( zProgress && len>0 ){
2794 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002795 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002796 }else{
2797 pDb->zProgress = 0;
2798 }
2799#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2800 if( pDb->zProgress ){
2801 pDb->interp = interp;
2802 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2803 }else{
2804 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2805 }
2806#endif
2807 }else{
2808 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002809 return TCL_ERROR;
2810 }
drh5d9d7572003-08-19 14:31:01 +00002811 break;
2812 }
2813
drh19e2d372005-08-29 23:00:03 +00002814 /* $db profile ?CALLBACK?
2815 **
2816 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2817 ** that has run. The text of the SQL and the amount of elapse time are
2818 ** appended to CALLBACK before the script is run.
2819 */
2820 case DB_PROFILE: {
2821 if( objc>3 ){
2822 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2823 return TCL_ERROR;
2824 }else if( objc==2 ){
2825 if( pDb->zProfile ){
drha198f2b2014-02-07 19:26:13 +00002826 Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002827 }
2828 }else{
2829 char *zProfile;
2830 int len;
2831 if( pDb->zProfile ){
2832 Tcl_Free(pDb->zProfile);
2833 }
2834 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2835 if( zProfile && len>0 ){
2836 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002837 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002838 }else{
2839 pDb->zProfile = 0;
2840 }
drh2eb22af2016-09-10 19:51:40 +00002841#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
2842 !defined(SQLITE_OMIT_DEPRECATED)
drh19e2d372005-08-29 23:00:03 +00002843 if( pDb->zProfile ){
2844 pDb->interp = interp;
2845 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2846 }else{
2847 sqlite3_profile(pDb->db, 0, 0);
2848 }
2849#endif
2850 }
2851 break;
2852 }
2853
drh5d9d7572003-08-19 14:31:01 +00002854 /*
drh22fbcb82004-02-01 01:22:50 +00002855 ** $db rekey KEY
2856 **
2857 ** Change the encryption key on the currently open database.
2858 */
2859 case DB_REKEY: {
drh32f57d42016-03-16 01:03:10 +00002860#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh22fbcb82004-02-01 01:22:50 +00002861 int nKey;
2862 void *pKey;
drhb07028f2011-10-14 21:49:18 +00002863#endif
drh22fbcb82004-02-01 01:22:50 +00002864 if( objc!=3 ){
2865 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2866 return TCL_ERROR;
2867 }
drh32f57d42016-03-16 01:03:10 +00002868#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00002869 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh2011d5f2004-07-22 02:40:37 +00002870 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002871 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002872 Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
drh22fbcb82004-02-01 01:22:50 +00002873 rc = TCL_ERROR;
2874 }
2875#endif
2876 break;
2877 }
2878
drhdc2c4912009-02-04 22:46:47 +00002879 /* $db restore ?DATABASE? FILENAME
2880 **
mistachkinb56660f2016-07-14 21:26:09 +00002881 ** Open a database file named FILENAME. Transfer the content
drhdc2c4912009-02-04 22:46:47 +00002882 ** of FILENAME into the local database DATABASE (default: "main").
2883 */
2884 case DB_RESTORE: {
2885 const char *zSrcFile;
2886 const char *zDestDb;
2887 sqlite3 *pSrc;
2888 sqlite3_backup *pBackup;
2889 int nTimeout = 0;
2890
2891 if( objc==3 ){
2892 zDestDb = "main";
2893 zSrcFile = Tcl_GetString(objv[2]);
2894 }else if( objc==4 ){
2895 zDestDb = Tcl_GetString(objv[2]);
2896 zSrcFile = Tcl_GetString(objv[3]);
2897 }else{
2898 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2899 return TCL_ERROR;
2900 }
drh147ef392016-01-22 23:17:51 +00002901 rc = sqlite3_open_v2(zSrcFile, &pSrc,
2902 SQLITE_OPEN_READONLY | pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00002903 if( rc!=SQLITE_OK ){
2904 Tcl_AppendResult(interp, "cannot open source database: ",
2905 sqlite3_errmsg(pSrc), (char*)0);
2906 sqlite3_close(pSrc);
2907 return TCL_ERROR;
2908 }
2909 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2910 if( pBackup==0 ){
2911 Tcl_AppendResult(interp, "restore failed: ",
2912 sqlite3_errmsg(pDb->db), (char*)0);
2913 sqlite3_close(pSrc);
2914 return TCL_ERROR;
2915 }
2916 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2917 || rc==SQLITE_BUSY ){
2918 if( rc==SQLITE_BUSY ){
2919 if( nTimeout++ >= 3 ) break;
2920 sqlite3_sleep(100);
2921 }
2922 }
2923 sqlite3_backup_finish(pBackup);
2924 if( rc==SQLITE_DONE ){
2925 rc = TCL_OK;
2926 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2927 Tcl_AppendResult(interp, "restore failed: source database busy",
2928 (char*)0);
2929 rc = TCL_ERROR;
2930 }else{
2931 Tcl_AppendResult(interp, "restore failed: ",
2932 sqlite3_errmsg(pDb->db), (char*)0);
2933 rc = TCL_ERROR;
2934 }
2935 sqlite3_close(pSrc);
2936 break;
2937 }
2938
drh22fbcb82004-02-01 01:22:50 +00002939 /*
drhcb7d5412018-01-03 16:49:52 +00002940 ** $db serialize ?DATABASE?
2941 **
2942 ** Return a serialization of a database.
2943 */
2944 case DB_SERIALIZE: {
drh9c6396e2018-03-06 21:43:19 +00002945#ifndef SQLITE_ENABLE_DESERIALIZE
drhcb7d5412018-01-03 16:49:52 +00002946 Tcl_AppendResult(interp, "MEMDB not available in this build",
2947 (char*)0);
2948 rc = TCL_ERROR;
2949#else
2950 const char *zSchema = objc>=3 ? Tcl_GetString(objv[2]) : "main";
2951 sqlite3_int64 sz = 0;
2952 unsigned char *pData;
2953 if( objc!=2 && objc!=3 ){
2954 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE?");
2955 rc = TCL_ERROR;
2956 }else{
2957 int needFree;
2958 pData = sqlite3_serialize(pDb->db, zSchema, &sz, SQLITE_SERIALIZE_NOCOPY);
2959 if( pData ){
2960 needFree = 0;
2961 }else{
2962 pData = sqlite3_serialize(pDb->db, zSchema, &sz, 0);
2963 needFree = 1;
2964 }
2965 Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(pData,sz));
2966 if( needFree ) sqlite3_free(pData);
2967 }
2968#endif
2969 break;
2970 }
2971
2972 /*
danc456a762017-06-22 16:51:16 +00002973 ** $db status (step|sort|autoindex|vmstep)
drhd1d38482008-10-07 23:46:38 +00002974 **
mistachkinb56660f2016-07-14 21:26:09 +00002975 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
drhd1d38482008-10-07 23:46:38 +00002976 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2977 */
2978 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002979 int v;
2980 const char *zOp;
2981 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00002982 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00002983 return TCL_ERROR;
2984 }
2985 zOp = Tcl_GetString(objv[2]);
2986 if( strcmp(zOp, "step")==0 ){
2987 v = pDb->nStep;
2988 }else if( strcmp(zOp, "sort")==0 ){
2989 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002990 }else if( strcmp(zOp, "autoindex")==0 ){
2991 v = pDb->nIndex;
danc456a762017-06-22 16:51:16 +00002992 }else if( strcmp(zOp, "vmstep")==0 ){
2993 v = pDb->nVMStep;
drhd1d38482008-10-07 23:46:38 +00002994 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002995 Tcl_AppendResult(interp,
danc456a762017-06-22 16:51:16 +00002996 "bad argument: should be autoindex, step, sort or vmstep",
drhd1d38482008-10-07 23:46:38 +00002997 (char*)0);
2998 return TCL_ERROR;
2999 }
3000 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
3001 break;
3002 }
mistachkinb56660f2016-07-14 21:26:09 +00003003
drhd1d38482008-10-07 23:46:38 +00003004 /*
drhbec3f402000-08-04 13:49:02 +00003005 ** $db timeout MILLESECONDS
3006 **
3007 ** Delay for the number of milliseconds specified when a file is locked.
3008 */
drh6d313162000-09-21 13:01:35 +00003009 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00003010 int ms;
drh6d313162000-09-21 13:01:35 +00003011 if( objc!=3 ){
3012 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00003013 return TCL_ERROR;
3014 }
drh6d313162000-09-21 13:01:35 +00003015 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00003016 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00003017 break;
drh75897232000-05-29 14:26:00 +00003018 }
mistachkinb56660f2016-07-14 21:26:09 +00003019
danielk197755c45f22005-04-03 23:54:43 +00003020 /*
drh0f14e2e2004-06-29 12:39:08 +00003021 ** $db total_changes
3022 **
mistachkinb56660f2016-07-14 21:26:09 +00003023 ** Return the number of rows that were modified, inserted, or deleted
drh0f14e2e2004-06-29 12:39:08 +00003024 ** since the database handle was created.
3025 */
3026 case DB_TOTAL_CHANGES: {
3027 Tcl_Obj *pResult;
3028 if( objc!=2 ){
3029 Tcl_WrongNumArgs(interp, 2, objv, "");
3030 return TCL_ERROR;
3031 }
3032 pResult = Tcl_GetObjResult(interp);
3033 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
3034 break;
3035 }
3036
drhb5a20d32003-04-23 12:25:23 +00003037 /* $db trace ?CALLBACK?
3038 **
3039 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
3040 ** that is executed. The text of the SQL is appended to CALLBACK before
3041 ** it is executed.
3042 */
3043 case DB_TRACE: {
3044 if( objc>3 ){
3045 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00003046 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00003047 }else if( objc==2 ){
3048 if( pDb->zTrace ){
drha198f2b2014-02-07 19:26:13 +00003049 Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
drhb5a20d32003-04-23 12:25:23 +00003050 }
3051 }else{
3052 char *zTrace;
3053 int len;
3054 if( pDb->zTrace ){
3055 Tcl_Free(pDb->zTrace);
3056 }
3057 zTrace = Tcl_GetStringFromObj(objv[2], &len);
3058 if( zTrace && len>0 ){
3059 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00003060 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00003061 }else{
3062 pDb->zTrace = 0;
3063 }
drh2eb22af2016-09-10 19:51:40 +00003064#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3065 !defined(SQLITE_OMIT_DEPRECATED)
drhb5a20d32003-04-23 12:25:23 +00003066 if( pDb->zTrace ){
3067 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00003068 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00003069 }else{
danielk19776f8a5032004-05-10 10:34:51 +00003070 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00003071 }
drh19e2d372005-08-29 23:00:03 +00003072#endif
drhb5a20d32003-04-23 12:25:23 +00003073 }
3074 break;
3075 }
3076
mistachkinb56660f2016-07-14 21:26:09 +00003077 /* $db trace_v2 ?CALLBACK? ?MASK?
3078 **
3079 ** Make arrangements to invoke the CALLBACK routine for each trace event
3080 ** matching the mask that is generated. The parameters are appended to
3081 ** CALLBACK before it is executed.
3082 */
3083 case DB_TRACE_V2: {
3084 if( objc>4 ){
3085 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK? ?MASK?");
3086 return TCL_ERROR;
3087 }else if( objc==2 ){
3088 if( pDb->zTraceV2 ){
3089 Tcl_AppendResult(interp, pDb->zTraceV2, (char*)0);
3090 }
3091 }else{
mistachkinb56660f2016-07-14 21:26:09 +00003092 char *zTraceV2;
3093 int len;
mistachkinb52dcd82016-07-14 23:17:03 +00003094 Tcl_WideInt wMask = 0;
mistachkinb56660f2016-07-14 21:26:09 +00003095 if( objc==4 ){
mistachkinb52dcd82016-07-14 23:17:03 +00003096 static const char *TTYPE_strs[] = {
3097 "statement", "profile", "row", "close", 0
3098 };
3099 enum TTYPE_enum {
3100 TTYPE_STMT, TTYPE_PROFILE, TTYPE_ROW, TTYPE_CLOSE
3101 };
3102 int i;
3103 if( TCL_OK!=Tcl_ListObjLength(interp, objv[3], &len) ){
mistachkinb56660f2016-07-14 21:26:09 +00003104 return TCL_ERROR;
3105 }
mistachkinb52dcd82016-07-14 23:17:03 +00003106 for(i=0; i<len; i++){
3107 Tcl_Obj *pObj;
3108 int ttype;
3109 if( TCL_OK!=Tcl_ListObjIndex(interp, objv[3], i, &pObj) ){
3110 return TCL_ERROR;
3111 }
3112 if( Tcl_GetIndexFromObj(interp, pObj, TTYPE_strs, "trace type",
3113 0, &ttype)!=TCL_OK ){
3114 Tcl_WideInt wType;
3115 Tcl_Obj *pError = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
3116 Tcl_IncrRefCount(pError);
3117 if( TCL_OK==Tcl_GetWideIntFromObj(interp, pObj, &wType) ){
3118 Tcl_DecrRefCount(pError);
3119 wMask |= wType;
3120 }else{
3121 Tcl_SetObjResult(interp, pError);
3122 Tcl_DecrRefCount(pError);
3123 return TCL_ERROR;
3124 }
3125 }else{
3126 switch( (enum TTYPE_enum)ttype ){
3127 case TTYPE_STMT: wMask |= SQLITE_TRACE_STMT; break;
3128 case TTYPE_PROFILE: wMask |= SQLITE_TRACE_PROFILE; break;
3129 case TTYPE_ROW: wMask |= SQLITE_TRACE_ROW; break;
3130 case TTYPE_CLOSE: wMask |= SQLITE_TRACE_CLOSE; break;
3131 }
3132 }
3133 }
mistachkinb56660f2016-07-14 21:26:09 +00003134 }else{
mistachkinb52dcd82016-07-14 23:17:03 +00003135 wMask = SQLITE_TRACE_STMT; /* use the "legacy" default */
mistachkinb56660f2016-07-14 21:26:09 +00003136 }
3137 if( pDb->zTraceV2 ){
3138 Tcl_Free(pDb->zTraceV2);
3139 }
3140 zTraceV2 = Tcl_GetStringFromObj(objv[2], &len);
3141 if( zTraceV2 && len>0 ){
3142 pDb->zTraceV2 = Tcl_Alloc( len + 1 );
3143 memcpy(pDb->zTraceV2, zTraceV2, len+1);
3144 }else{
3145 pDb->zTraceV2 = 0;
3146 }
3147#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3148 if( pDb->zTraceV2 ){
3149 pDb->interp = interp;
3150 sqlite3_trace_v2(pDb->db, (unsigned)wMask, DbTraceV2Handler, pDb);
3151 }else{
3152 sqlite3_trace_v2(pDb->db, 0, 0, 0);
3153 }
3154#endif
3155 }
3156 break;
3157 }
3158
drh3d214232005-08-02 12:21:08 +00003159 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
3160 **
3161 ** Start a new transaction (if we are not already in the midst of a
3162 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
3163 ** completes, either commit the transaction or roll it back if SCRIPT
3164 ** throws an exception. Or if no new transation was started, do nothing.
3165 ** pass the exception on up the stack.
3166 **
3167 ** This command was inspired by Dave Thomas's talk on Ruby at the
3168 ** 2005 O'Reilly Open Source Convention (OSCON).
3169 */
3170 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00003171 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00003172 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00003173 if( objc!=3 && objc!=4 ){
3174 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
3175 return TCL_ERROR;
3176 }
danielk1977cd38d522009-01-02 17:33:46 +00003177
dan4a4c11a2009-10-06 14:59:02 +00003178 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00003179 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00003180 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00003181 };
3182 enum TTYPE_enum {
3183 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
3184 };
3185 int ttype;
drhb5555e72005-08-02 17:15:14 +00003186 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00003187 0, &ttype) ){
3188 return TCL_ERROR;
3189 }
3190 switch( (enum TTYPE_enum)ttype ){
3191 case TTYPE_DEFERRED: /* no-op */; break;
3192 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
3193 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
3194 }
drh3d214232005-08-02 12:21:08 +00003195 }
danielk1977cd38d522009-01-02 17:33:46 +00003196 pScript = objv[objc-1];
3197
dan4a4c11a2009-10-06 14:59:02 +00003198 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00003199 pDb->disableAuth++;
3200 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
3201 pDb->disableAuth--;
3202 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00003203 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977cd38d522009-01-02 17:33:46 +00003204 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00003205 }
danielk1977cd38d522009-01-02 17:33:46 +00003206 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00003207
dan4a4c11a2009-10-06 14:59:02 +00003208 /* If using NRE, schedule a callback to invoke the script pScript, then
3209 ** a second callback to commit (or rollback) the transaction or savepoint
3210 ** opened above. If not using NRE, evaluate the script directly, then
mistachkinb56660f2016-07-14 21:26:09 +00003211 ** call function DbTransPostCmd() to commit (or rollback) the transaction
dan4a4c11a2009-10-06 14:59:02 +00003212 ** or savepoint. */
3213 if( DbUseNre() ){
3214 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
drha47941f2013-12-20 18:57:44 +00003215 (void)Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00003216 }else{
dan4a4c11a2009-10-06 14:59:02 +00003217 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00003218 }
3219 break;
3220 }
3221
danielk197794eb6a12005-12-15 15:22:08 +00003222 /*
danielk1977404ca072009-03-16 13:19:36 +00003223 ** $db unlock_notify ?script?
3224 */
3225 case DB_UNLOCK_NOTIFY: {
3226#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
drha198f2b2014-02-07 19:26:13 +00003227 Tcl_AppendResult(interp, "unlock_notify not available in this build",
3228 (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00003229 rc = TCL_ERROR;
3230#else
3231 if( objc!=2 && objc!=3 ){
3232 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3233 rc = TCL_ERROR;
3234 }else{
3235 void (*xNotify)(void **, int) = 0;
3236 void *pNotifyArg = 0;
3237
3238 if( pDb->pUnlockNotify ){
3239 Tcl_DecrRefCount(pDb->pUnlockNotify);
3240 pDb->pUnlockNotify = 0;
3241 }
mistachkinb56660f2016-07-14 21:26:09 +00003242
danielk1977404ca072009-03-16 13:19:36 +00003243 if( objc==3 ){
3244 xNotify = DbUnlockNotify;
3245 pNotifyArg = (void *)pDb;
3246 pDb->pUnlockNotify = objv[2];
3247 Tcl_IncrRefCount(pDb->pUnlockNotify);
3248 }
mistachkinb56660f2016-07-14 21:26:09 +00003249
danielk1977404ca072009-03-16 13:19:36 +00003250 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
drha198f2b2014-02-07 19:26:13 +00003251 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00003252 rc = TCL_ERROR;
3253 }
3254 }
3255#endif
3256 break;
3257 }
3258
drh304637c2011-03-18 16:47:27 +00003259 /*
3260 ** $db preupdate_hook count
3261 ** $db preupdate_hook hook ?SCRIPT?
3262 ** $db preupdate_hook new INDEX
3263 ** $db preupdate_hook old INDEX
3264 */
dan46c47d42011-03-01 18:42:07 +00003265 case DB_PREUPDATE: {
drh9b1c62d2011-03-30 21:04:43 +00003266#ifndef SQLITE_ENABLE_PREUPDATE_HOOK
dan2b519ab2016-12-06 19:33:42 +00003267 Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time",
3268 (char*)0);
drh9b1c62d2011-03-30 21:04:43 +00003269 rc = TCL_ERROR;
3270#else
dan1e7a2d42011-03-22 18:45:29 +00003271 static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
dan46c47d42011-03-01 18:42:07 +00003272 enum DbPreupdateSubCmd {
dan1e7a2d42011-03-22 18:45:29 +00003273 PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
dan46c47d42011-03-01 18:42:07 +00003274 };
3275 int iSub;
3276
3277 if( objc<3 ){
3278 Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
3279 }
3280 if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
3281 return TCL_ERROR;
3282 }
3283
3284 switch( (enum DbPreupdateSubCmd)iSub ){
3285 case PRE_COUNT: {
3286 int nCol = sqlite3_preupdate_count(pDb->db);
3287 Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
3288 break;
3289 }
3290
3291 case PRE_HOOK: {
3292 if( objc>4 ){
3293 Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
3294 return TCL_ERROR;
3295 }
3296 DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
3297 break;
3298 }
3299
dan1e7a2d42011-03-22 18:45:29 +00003300 case PRE_DEPTH: {
3301 Tcl_Obj *pRet;
3302 if( objc!=3 ){
3303 Tcl_WrongNumArgs(interp, 3, objv, "");
3304 return TCL_ERROR;
3305 }
3306 pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
3307 Tcl_SetObjResult(interp, pRet);
3308 break;
3309 }
3310
dan37db03b2011-03-16 19:59:18 +00003311 case PRE_NEW:
dan46c47d42011-03-01 18:42:07 +00003312 case PRE_OLD: {
3313 int iIdx;
dan37db03b2011-03-16 19:59:18 +00003314 sqlite3_value *pValue;
dan46c47d42011-03-01 18:42:07 +00003315 if( objc!=4 ){
3316 Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
3317 return TCL_ERROR;
3318 }
3319 if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
3320 return TCL_ERROR;
3321 }
3322
dan37db03b2011-03-16 19:59:18 +00003323 if( iSub==PRE_OLD ){
dan46c47d42011-03-01 18:42:07 +00003324 rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
dan37db03b2011-03-16 19:59:18 +00003325 }else{
3326 assert( iSub==PRE_NEW );
3327 rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
dan46c47d42011-03-01 18:42:07 +00003328 }
3329
dan37db03b2011-03-16 19:59:18 +00003330 if( rc==SQLITE_OK ){
drh304637c2011-03-18 16:47:27 +00003331 Tcl_Obj *pObj;
3332 pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
dan37db03b2011-03-16 19:59:18 +00003333 Tcl_SetObjResult(interp, pObj);
3334 }else{
drhea8f0a12017-01-12 11:50:08 +00003335 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
dan46c47d42011-03-01 18:42:07 +00003336 return TCL_ERROR;
3337 }
3338 }
3339 }
drh9b1c62d2011-03-30 21:04:43 +00003340#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +00003341 break;
3342 }
3343
danielk1977404ca072009-03-16 13:19:36 +00003344 /*
drh833bf962010-04-28 14:42:19 +00003345 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003346 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00003347 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003348 */
mistachkinb56660f2016-07-14 21:26:09 +00003349 case DB_WAL_HOOK:
3350 case DB_UPDATE_HOOK:
dan6566ebe2011-03-16 09:49:14 +00003351 case DB_ROLLBACK_HOOK: {
mistachkinb56660f2016-07-14 21:26:09 +00003352 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
danielk197771fd80b2005-12-16 06:54:01 +00003353 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3354 */
mistachkinb56660f2016-07-14 21:26:09 +00003355 Tcl_Obj **ppHook = 0;
dan46c47d42011-03-01 18:42:07 +00003356 if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
3357 if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
3358 if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
3359 if( objc>3 ){
danielk197794eb6a12005-12-15 15:22:08 +00003360 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3361 return TCL_ERROR;
3362 }
danielk197771fd80b2005-12-16 06:54:01 +00003363
dan46c47d42011-03-01 18:42:07 +00003364 DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00003365 break;
3366 }
3367
danielk19774397de52005-01-12 12:44:03 +00003368 /* $db version
3369 **
3370 ** Return the version string for this database.
3371 */
3372 case DB_VERSION: {
drh1df64702017-10-13 15:56:26 +00003373 int i;
3374 for(i=2; i<objc; i++){
3375 const char *zArg = Tcl_GetString(objv[i]);
3376 /* Optional arguments to $db version are used for testing purpose */
3377#ifdef SQLITE_TEST
3378 /* $db version -use-legacy-prepare BOOLEAN
3379 **
3380 ** Turn the use of legacy sqlite3_prepare() on or off.
3381 */
3382 if( strcmp(zArg, "-use-legacy-prepare")==0 && i+1<objc ){
3383 i++;
3384 if( Tcl_GetBooleanFromObj(interp, objv[i], &pDb->bLegacyPrepare) ){
3385 return TCL_ERROR;
3386 }
3387 }else
3388
3389 /* $db version -last-stmt-ptr
3390 **
3391 ** Return a string which is a hex encoding of the pointer to the
3392 ** most recent sqlite3_stmt in the statement cache.
3393 */
3394 if( strcmp(zArg, "-last-stmt-ptr")==0 ){
3395 char zBuf[100];
3396 sqlite3_snprintf(sizeof(zBuf), zBuf, "%p",
3397 pDb->stmtList ? pDb->stmtList->pStmt: 0);
3398 Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
3399 }else
3400#endif /* SQLITE_TEST */
3401 {
3402 Tcl_AppendResult(interp, "unknown argument: ", zArg, (char*)0);
3403 return TCL_ERROR;
3404 }
3405 }
3406 if( i==2 ){
3407 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
3408 }
danielk19774397de52005-01-12 12:44:03 +00003409 break;
3410 }
3411
tpoindex1067fe12004-12-17 15:41:11 +00003412
drh6d313162000-09-21 13:01:35 +00003413 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00003414 return rc;
drh75897232000-05-29 14:26:00 +00003415}
3416
drha2c8a952009-10-13 18:38:34 +00003417#if SQLITE_TCL_NRE
3418/*
3419** Adaptor that provides an objCmd interface to the NRE-enabled
3420** interface implementation.
3421*/
mistachkina121cc72016-07-28 18:06:52 +00003422static int SQLITE_TCLAPI DbObjCmdAdaptor(
drha2c8a952009-10-13 18:38:34 +00003423 void *cd,
3424 Tcl_Interp *interp,
3425 int objc,
3426 Tcl_Obj *const*objv
3427){
3428 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
3429}
3430#endif /* SQLITE_TCL_NRE */
3431
drh75897232000-05-29 14:26:00 +00003432/*
drh4dcac402018-01-03 13:20:02 +00003433** Issue the usage message when the "sqlite3" command arguments are
3434** incorrect.
3435*/
3436static int sqliteCmdUsage(
3437 Tcl_Interp *interp,
3438 Tcl_Obj *const*objv
3439){
3440 Tcl_WrongNumArgs(interp, 1, objv,
3441 "HANDLE ?FILENAME? ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
3442 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
3443#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3444 " ?-key CODECKEY?"
3445#endif
3446 );
3447 return TCL_ERROR;
3448}
3449
3450/*
drh3570ad92007-08-31 14:31:44 +00003451** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00003452** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00003453**
3454** This is the main Tcl command. When the "sqlite" Tcl command is
3455** invoked, this routine runs to process that command.
3456**
3457** The first argument, DBNAME, is an arbitrary name for a new
3458** database connection. This command creates a new command named
3459** DBNAME that is used to control that connection. The database
3460** connection is deleted when the DBNAME command is deleted.
3461**
drh3570ad92007-08-31 14:31:44 +00003462** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00003463**
drh75897232000-05-29 14:26:00 +00003464*/
mistachkin7617e4a2016-07-28 17:11:20 +00003465static int SQLITE_TCLAPI DbMain(
3466 void *cd,
3467 Tcl_Interp *interp,
3468 int objc,
3469 Tcl_Obj *const*objv
3470){
drhbec3f402000-08-04 13:49:02 +00003471 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00003472 const char *zArg;
drh75897232000-05-29 14:26:00 +00003473 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00003474 int i;
drh4dcac402018-01-03 13:20:02 +00003475 const char *zFile = 0;
drh3570ad92007-08-31 14:31:44 +00003476 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00003477 int flags;
drh882e8e42006-08-24 02:42:27 +00003478 Tcl_DString translatedFilename;
drh32f57d42016-03-16 01:03:10 +00003479#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00003480 void *pKey = 0;
3481 int nKey = 0;
3482#endif
mistachkin540ebf82012-09-10 07:29:29 +00003483 int rc;
drhd9da78a2009-03-24 15:08:09 +00003484
3485 /* In normal use, each TCL interpreter runs in a single thread. So
drh4dcac402018-01-03 13:20:02 +00003486 ** by default, we can turn off mutexing on SQLite database connections.
drhd9da78a2009-03-24 15:08:09 +00003487 ** However, for testing purposes it is useful to have mutexes turned
3488 ** on. So, by default, mutexes default off. But if compiled with
3489 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3490 */
3491#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3492 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3493#else
3494 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3495#endif
3496
drh22fbcb82004-02-01 01:22:50 +00003497 if( objc==2 ){
3498 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00003499 if( strcmp(zArg,"-version")==0 ){
drha198f2b2014-02-07 19:26:13 +00003500 Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
drh647cb0e2002-11-04 19:32:25 +00003501 return TCL_OK;
3502 }
drh72bf6a32016-01-07 02:06:55 +00003503 if( strcmp(zArg,"-sourceid")==0 ){
3504 Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0);
3505 return TCL_OK;
3506 }
drh9eb9e262004-02-11 02:18:05 +00003507 if( strcmp(zArg,"-has-codec")==0 ){
drh32f57d42016-03-16 01:03:10 +00003508#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drha198f2b2014-02-07 19:26:13 +00003509 Tcl_AppendResult(interp,"1",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003510#else
drha198f2b2014-02-07 19:26:13 +00003511 Tcl_AppendResult(interp,"0",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003512#endif
3513 return TCL_OK;
3514 }
drh4dcac402018-01-03 13:20:02 +00003515 if( zArg[0]=='-' ) return sqliteCmdUsage(interp, objv);
drhfbc3eab2001-04-06 16:13:42 +00003516 }
drh4dcac402018-01-03 13:20:02 +00003517 for(i=2; i<objc; i++){
drh3570ad92007-08-31 14:31:44 +00003518 zArg = Tcl_GetString(objv[i]);
drh4dcac402018-01-03 13:20:02 +00003519 if( zArg[0]!='-' ){
3520 if( zFile!=0 ) return sqliteCmdUsage(interp, objv);
3521 zFile = zArg;
3522 continue;
3523 }
3524 if( i==objc-1 ) return sqliteCmdUsage(interp, objv);
3525 i++;
drh22fbcb82004-02-01 01:22:50 +00003526 if( strcmp(zArg,"-key")==0 ){
drh32f57d42016-03-16 01:03:10 +00003527#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh4dcac402018-01-03 13:20:02 +00003528 pKey = Tcl_GetByteArrayFromObj(objv[i], &nKey);
drhb07028f2011-10-14 21:49:18 +00003529#endif
drh3570ad92007-08-31 14:31:44 +00003530 }else if( strcmp(zArg, "-vfs")==0 ){
drh4dcac402018-01-03 13:20:02 +00003531 zVfs = Tcl_GetString(objv[i]);
drh3570ad92007-08-31 14:31:44 +00003532 }else if( strcmp(zArg, "-readonly")==0 ){
3533 int b;
drh4dcac402018-01-03 13:20:02 +00003534 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
drh3570ad92007-08-31 14:31:44 +00003535 if( b ){
drh33f4e022007-09-03 15:19:34 +00003536 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00003537 flags |= SQLITE_OPEN_READONLY;
3538 }else{
3539 flags &= ~SQLITE_OPEN_READONLY;
3540 flags |= SQLITE_OPEN_READWRITE;
3541 }
3542 }else if( strcmp(zArg, "-create")==0 ){
3543 int b;
drh4dcac402018-01-03 13:20:02 +00003544 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00003545 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00003546 flags |= SQLITE_OPEN_CREATE;
3547 }else{
3548 flags &= ~SQLITE_OPEN_CREATE;
3549 }
danielk19779a6284c2008-07-10 17:52:49 +00003550 }else if( strcmp(zArg, "-nomutex")==0 ){
3551 int b;
drh4dcac402018-01-03 13:20:02 +00003552 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
danielk19779a6284c2008-07-10 17:52:49 +00003553 if( b ){
3554 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00003555 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00003556 }else{
3557 flags &= ~SQLITE_OPEN_NOMUTEX;
3558 }
danc431fd52011-06-27 16:55:50 +00003559 }else if( strcmp(zArg, "-fullmutex")==0 ){
drh039963a2008-09-03 00:43:15 +00003560 int b;
drh4dcac402018-01-03 13:20:02 +00003561 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
drh039963a2008-09-03 00:43:15 +00003562 if( b ){
3563 flags |= SQLITE_OPEN_FULLMUTEX;
3564 flags &= ~SQLITE_OPEN_NOMUTEX;
3565 }else{
3566 flags &= ~SQLITE_OPEN_FULLMUTEX;
3567 }
drhf12b3f62011-12-21 14:42:29 +00003568 }else if( strcmp(zArg, "-uri")==0 ){
3569 int b;
drh4dcac402018-01-03 13:20:02 +00003570 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
drhf12b3f62011-12-21 14:42:29 +00003571 if( b ){
3572 flags |= SQLITE_OPEN_URI;
3573 }else{
3574 flags &= ~SQLITE_OPEN_URI;
3575 }
drh3570ad92007-08-31 14:31:44 +00003576 }else{
3577 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3578 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00003579 }
3580 }
drh75897232000-05-29 14:26:00 +00003581 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003582 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drhbec3f402000-08-04 13:49:02 +00003583 memset(p, 0, sizeof(*p));
drh3ec86652018-01-03 19:03:31 +00003584 if( zFile==0 ) zFile = "";
3585 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
3586 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
3587 Tcl_DStringFree(&translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003588 if( p->db ){
3589 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3590 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3591 sqlite3_close(p->db);
3592 p->db = 0;
3593 }
3594 }else{
mistachkin5dac8432012-09-11 02:00:25 +00003595 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
danielk197780290862004-05-22 09:21:21 +00003596 }
drh32f57d42016-03-16 01:03:10 +00003597#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhf3a65f72007-08-22 20:18:21 +00003598 if( p->db ){
3599 sqlite3_key(p->db, pKey, nKey);
3600 }
drheb8ed702004-02-11 10:37:23 +00003601#endif
drhbec3f402000-08-04 13:49:02 +00003602 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003603 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003604 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003605 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003606 return TCL_ERROR;
3607 }
drhfb7e7652005-01-24 00:28:42 +00003608 p->maxStmt = NUM_PREPARED_STMTS;
drh147ef392016-01-22 23:17:51 +00003609 p->openFlags = flags & SQLITE_OPEN_URI;
drh5169bbc2006-08-24 14:59:45 +00003610 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003611 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003612 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003613 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3614 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003615 }else{
3616 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3617 }
drh75897232000-05-29 14:26:00 +00003618 return TCL_OK;
3619}
3620
3621/*
drh90ca9752001-09-28 17:47:14 +00003622** Provide a dummy Tcl_InitStubs if we are using this as a static
3623** library.
3624*/
3625#ifndef USE_TCL_STUBS
3626# undef Tcl_InitStubs
drh0e85ccf2013-06-03 12:34:46 +00003627# define Tcl_InitStubs(a,b,c) TCL_VERSION
drh90ca9752001-09-28 17:47:14 +00003628#endif
3629
3630/*
drh29bc4612005-10-05 10:40:15 +00003631** Make sure we have a PACKAGE_VERSION macro defined. This will be
3632** defined automatically by the TEA makefile. But other makefiles
3633** do not define it.
3634*/
3635#ifndef PACKAGE_VERSION
3636# define PACKAGE_VERSION SQLITE_VERSION
3637#endif
3638
3639/*
drh75897232000-05-29 14:26:00 +00003640** Initialize this module.
3641**
3642** This Tcl module contains only a single new Tcl command named "sqlite".
3643** (Hence there is no namespace. There is no point in using a namespace
3644** if the extension only supplies one new name!) The "sqlite" command is
3645** used to open a new SQLite database. See the DbMain() routine above
3646** for additional information.
drhb652f432010-08-26 16:46:57 +00003647**
3648** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003649*/
drhb652f432010-08-26 16:46:57 +00003650EXTERN int Sqlite3_Init(Tcl_Interp *interp){
mistachkin27b2f052015-01-12 19:49:46 +00003651 int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
drh6dc8cbe2013-05-31 15:36:07 +00003652 if( rc==TCL_OK ){
3653 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh1cca0d22010-08-25 20:35:51 +00003654#ifndef SQLITE_3_SUFFIX_ONLY
drh6dc8cbe2013-05-31 15:36:07 +00003655 /* The "sqlite" alias is undocumented. It is here only to support
3656 ** legacy scripts. All new scripts should use only the "sqlite3"
3657 ** command. */
3658 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003659#endif
drh6dc8cbe2013-05-31 15:36:07 +00003660 rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3661 }
3662 return rc;
drh90ca9752001-09-28 17:47:14 +00003663}
drhb652f432010-08-26 16:46:57 +00003664EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
drhb652f432010-08-26 16:46:57 +00003665EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3666EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00003667
drhd878cab2012-03-20 15:10:42 +00003668/* Because it accesses the file-system and uses persistent state, SQLite
drhe75a9eb2016-02-13 18:54:10 +00003669** is not considered appropriate for safe interpreters. Hence, we cause
3670** the _SafeInit() interfaces return TCL_ERROR.
drhd878cab2012-03-20 15:10:42 +00003671*/
drhe75a9eb2016-02-13 18:54:10 +00003672EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
3673EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
3674
3675
drh49766d62005-01-08 18:42:28 +00003676
3677#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003678int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3679int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
dana3e63c42010-08-20 12:33:59 +00003680int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3681int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00003682#endif
drh75897232000-05-29 14:26:00 +00003683
drhc318f732017-10-13 15:06:06 +00003684/*
drh96a206f2017-10-13 20:14:06 +00003685** If the TCLSH macro is defined, add code to make a stand-alone program.
drhc318f732017-10-13 15:06:06 +00003686*/
drh96a206f2017-10-13 20:14:06 +00003687#if defined(TCLSH)
drh57a02272009-10-22 20:52:05 +00003688
drh96a206f2017-10-13 20:14:06 +00003689/* This is the main routine for an ordinary TCL shell. If there are
3690** are arguments, run the first argument as a script. Otherwise,
3691** read TCL commands from standard input
drh348784e2000-05-29 20:41:49 +00003692*/
dan0ae479d2011-09-21 16:43:07 +00003693static const char *tclsh_main_loop(void){
3694 static const char zMainloop[] =
drh96a206f2017-10-13 20:14:06 +00003695 "if {[llength $argv]>=1} {\n"
3696 "set argv0 [lindex $argv 0]\n"
3697 "set argv [lrange $argv 1 end]\n"
3698 "source $argv0\n"
3699 "} else {\n"
3700 "set line {}\n"
3701 "while {![eof stdin]} {\n"
3702 "if {$line!=\"\"} {\n"
3703 "puts -nonewline \"> \"\n"
3704 "} else {\n"
3705 "puts -nonewline \"% \"\n"
dan0ae479d2011-09-21 16:43:07 +00003706 "}\n"
drh96a206f2017-10-13 20:14:06 +00003707 "flush stdout\n"
3708 "append line [gets stdin]\n"
3709 "if {[info complete $line]} {\n"
3710 "if {[catch {uplevel #0 $line} result]} {\n"
3711 "puts stderr \"Error: $result\"\n"
3712 "} elseif {$result!=\"\"} {\n"
3713 "puts $result\n"
3714 "}\n"
3715 "set line {}\n"
3716 "} else {\n"
3717 "append line \\n\n"
3718 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003719 "}\n"
drh348784e2000-05-29 20:41:49 +00003720 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003721 ;
3722 return zMainloop;
3723}
drh3e27c022004-07-23 00:01:38 +00003724
danc1a60c52010-06-07 14:28:16 +00003725#define TCLSH_MAIN main /* Needed to fake out mktclapp */
mistachkin69def7f2016-07-28 04:14:37 +00003726int SQLITE_CDECL TCLSH_MAIN(int argc, char **argv){
danc1a60c52010-06-07 14:28:16 +00003727 Tcl_Interp *interp;
drh96a206f2017-10-13 20:14:06 +00003728 int i;
3729 const char *zScript = 0;
3730 char zArgc[32];
3731#if defined(TCLSH_INIT_PROC)
3732 extern const char *TCLSH_INIT_PROC(Tcl_Interp*);
3733#endif
mistachkin1f28e072013-08-15 08:06:15 +00003734
3735#if !defined(_WIN32_WCE)
3736 if( getenv("BREAK") ){
3737 fprintf(stderr,
3738 "attach debugger to process %d and press any key to continue.\n",
3739 GETPID());
3740 fgetc(stdin);
3741 }
3742#endif
3743
danc1a60c52010-06-07 14:28:16 +00003744 /* Call sqlite3_shutdown() once before doing anything else. This is to
3745 ** test that sqlite3_shutdown() can be safely called by a process before
3746 ** sqlite3_initialize() is. */
3747 sqlite3_shutdown();
3748
dan0ae479d2011-09-21 16:43:07 +00003749 Tcl_FindExecutable(argv[0]);
mistachkin2953ba92014-02-14 00:25:03 +00003750 Tcl_SetSystemEncoding(NULL, "utf-8");
dan0ae479d2011-09-21 16:43:07 +00003751 interp = Tcl_CreateInterp();
drhc318f732017-10-13 15:06:06 +00003752 Sqlite3_Init(interp);
drh96a206f2017-10-13 20:14:06 +00003753
3754 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-1);
3755 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
3756 Tcl_SetVar(interp,"argv0",argv[0],TCL_GLOBAL_ONLY);
3757 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
3758 for(i=1; i<argc; i++){
3759 Tcl_SetVar(interp, "argv", argv[i],
3760 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
drhc318f732017-10-13 15:06:06 +00003761 }
drh96a206f2017-10-13 20:14:06 +00003762#if defined(TCLSH_INIT_PROC)
3763 zScript = TCLSH_INIT_PROC(interp);
3764#endif
3765 if( zScript==0 ){
3766 zScript = tclsh_main_loop();
drh3e27c022004-07-23 00:01:38 +00003767 }
drh96a206f2017-10-13 20:14:06 +00003768 if( Tcl_GlobalEval(interp, zScript)!=TCL_OK ){
3769 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
3770 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
3771 fprintf(stderr,"%s: %s\n", *argv, zInfo);
3772 return 1;
drh348784e2000-05-29 20:41:49 +00003773 }
3774 return 0;
3775}
3776#endif /* TCLSH */