blob: d02d94baf564aa859853358ad29bcdf32c935b3e [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
67# define WIN32_LEAN_AND_MEAN
68# include <windows.h>
69# endif
70# define GETPID (int)GetCurrentProcessId
71#endif
72
drhad6e1372006-07-10 21:15:51 +000073/*
74 * Windows needs to know which symbols to export. Unix does not.
75 * BUILD_sqlite should be undefined for Unix.
76 */
77#ifdef BUILD_sqlite
78#undef TCL_STORAGE_CLASS
79#define TCL_STORAGE_CLASS DLLEXPORT
80#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000081
danielk1977a21c6b62005-01-24 10:25:59 +000082#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000083#define MAX_PREPARED_STMTS 100
84
drhc45e6712012-10-03 11:02:33 +000085/* Forward declaration */
86typedef struct SqliteDb SqliteDb;
drh98808ba2001-10-18 12:34:46 +000087
88/*
drhcabb0812002-09-14 13:47:32 +000089** New SQL functions can be created as TCL scripts. Each such function
90** is described by an instance of the following structure.
91*/
92typedef struct SqlFunc SqlFunc;
93struct SqlFunc {
94 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000095 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
drhc45e6712012-10-03 11:02:33 +000096 SqliteDb *pDb; /* Database connection that owns this function */
drhd1e47332005-06-26 17:55:33 +000097 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
98 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000099 SqlFunc *pNext; /* Next function on the list of them all */
100};
101
102/*
danielk19770202b292004-06-09 09:55:16 +0000103** New collation sequences function can be created as TCL scripts. Each such
104** function is described by an instance of the following structure.
105*/
106typedef struct SqlCollate SqlCollate;
107struct SqlCollate {
108 Tcl_Interp *interp; /* The TCL interpret to execute the function */
109 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +0000110 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +0000111};
112
113/*
drhfb7e7652005-01-24 00:28:42 +0000114** Prepared statements are cached for faster execution. Each prepared
115** statement is described by an instance of the following structure.
116*/
117typedef struct SqlPreparedStmt SqlPreparedStmt;
118struct SqlPreparedStmt {
119 SqlPreparedStmt *pNext; /* Next in linked list */
120 SqlPreparedStmt *pPrev; /* Previous on the list */
121 sqlite3_stmt *pStmt; /* The prepared statement */
122 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +0000123 const char *zSql; /* Text of the SQL statement */
dan4a4c11a2009-10-06 14:59:02 +0000124 int nParm; /* Size of apParm array */
125 Tcl_Obj **apParm; /* Array of referenced object pointers */
drhfb7e7652005-01-24 00:28:42 +0000126};
127
danielk1977d04417962007-05-02 13:16:30 +0000128typedef struct IncrblobChannel IncrblobChannel;
129
drhfb7e7652005-01-24 00:28:42 +0000130/*
drhbec3f402000-08-04 13:49:02 +0000131** There is one instance of this structure for each SQLite database
132** that has been opened by the SQLite TCL interface.
danc431fd52011-06-27 16:55:50 +0000133**
134** If this module is built with SQLITE_TEST defined (to create the SQLite
135** testfixture executable), then it may be configured to use either
136** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
137** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
drhbec3f402000-08-04 13:49:02 +0000138*/
drhbec3f402000-08-04 13:49:02 +0000139struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000140 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000141 Tcl_Interp *interp; /* The interpreter used for this database */
142 char *zBusy; /* The busy callback routine */
143 char *zCommit; /* The commit hook callback routine */
144 char *zTrace; /* The trace callback routine */
mistachkinb56660f2016-07-14 21:26:09 +0000145 char *zTraceV2; /* The trace_v2 callback routine */
drh19e2d372005-08-29 23:00:03 +0000146 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000147 char *zProgress; /* The progress callback routine */
148 char *zAuth; /* The authorization callback routine */
drh1f1549f2008-08-26 21:33:34 +0000149 int disableAuth; /* Disable the authorizer if it exists */
drhd1e47332005-06-26 17:55:33 +0000150 char *zNull; /* Text to substitute for an SQL NULL value */
151 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000152 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
dan46c47d42011-03-01 18:42:07 +0000153 Tcl_Obj *pPreUpdateHook; /* Pre-update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000154 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drh5def0842010-05-05 20:00:25 +0000155 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000156 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000157 SqlCollate *pCollate; /* List of SQL collation functions */
158 int rc; /* Return code of most recent sqlite3_exec() */
159 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000160 SqlPreparedStmt *stmtList; /* List of prepared statements*/
161 SqlPreparedStmt *stmtLast; /* Last statement in the list */
162 int maxStmt; /* The next maximum number of stmtList */
163 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000164 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh3c379b02010-04-07 19:31:59 +0000165 int nStep, nSort, nIndex; /* Statistics for most recent operation */
danc456a762017-06-22 16:51:16 +0000166 int nVMStep; /* Another statistic for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000167 int nTransaction; /* Number of nested [transaction] methods */
drh147ef392016-01-22 23:17:51 +0000168 int openFlags; /* Flags used to open. (SQLITE_OPEN_URI) */
danc431fd52011-06-27 16:55:50 +0000169#ifdef SQLITE_TEST
170 int bLegacyPrepare; /* True to use sqlite3_prepare() */
171#endif
drh98808ba2001-10-18 12:34:46 +0000172};
drh297ecf12001-04-05 15:57:13 +0000173
danielk1977b4e9af92007-05-01 17:49:49 +0000174struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000175 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000176 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000177 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000178 Tcl_Channel channel; /* Channel identifier */
179 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
180 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000181};
182
drhea678832008-12-10 19:26:22 +0000183/*
184** Compute a string length that is limited to what can be stored in
185** lower 30 bits of a 32-bit signed integer.
186*/
drh4f21c4a2008-12-10 22:15:00 +0000187static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000188 const char *z2 = z;
189 while( *z2 ){ z2++; }
190 return 0x3fffffff & (int)(z2 - z);
191}
drhea678832008-12-10 19:26:22 +0000192
193
danielk197732a0d8b2007-05-04 19:03:02 +0000194#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000195/*
danielk1977d04417962007-05-02 13:16:30 +0000196** Close all incrblob channels opened using database connection pDb.
197** This is called when shutting down the database connection.
198*/
199static void closeIncrblobChannels(SqliteDb *pDb){
200 IncrblobChannel *p;
201 IncrblobChannel *pNext;
202
203 for(p=pDb->pIncrblob; p; p=pNext){
204 pNext = p->pNext;
205
mistachkinb56660f2016-07-14 21:26:09 +0000206 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
danielk1977d04417962007-05-02 13:16:30 +0000207 ** which deletes the IncrblobChannel structure at *p. So do not
208 ** call Tcl_Free() here.
209 */
210 Tcl_UnregisterChannel(pDb->interp, p->channel);
211 }
212}
213
214/*
danielk1977b4e9af92007-05-01 17:49:49 +0000215** Close an incremental blob channel.
216*/
mistachkin7617e4a2016-07-28 17:11:20 +0000217static int SQLITE_TCLAPI incrblobClose(
218 ClientData instanceData,
219 Tcl_Interp *interp
220){
danielk1977b4e9af92007-05-01 17:49:49 +0000221 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000222 int rc = sqlite3_blob_close(p->pBlob);
223 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000224
225 /* Remove the channel from the SqliteDb.pIncrblob list. */
226 if( p->pNext ){
227 p->pNext->pPrev = p->pPrev;
228 }
229 if( p->pPrev ){
230 p->pPrev->pNext = p->pNext;
231 }
232 if( p->pDb->pIncrblob==p ){
233 p->pDb->pIncrblob = p->pNext;
234 }
235
danielk197792d4d7a2007-05-04 12:05:56 +0000236 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000237 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000238
239 if( rc!=SQLITE_OK ){
240 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
241 return TCL_ERROR;
242 }
danielk1977b4e9af92007-05-01 17:49:49 +0000243 return TCL_OK;
244}
245
246/*
247** Read data from an incremental blob channel.
248*/
mistachkin7617e4a2016-07-28 17:11:20 +0000249static int SQLITE_TCLAPI incrblobInput(
mistachkinb56660f2016-07-14 21:26:09 +0000250 ClientData instanceData,
251 char *buf,
danielk1977b4e9af92007-05-01 17:49:49 +0000252 int bufSize,
253 int *errorCodePtr
254){
255 IncrblobChannel *p = (IncrblobChannel *)instanceData;
256 int nRead = bufSize; /* Number of bytes to read */
257 int nBlob; /* Total size of the blob */
258 int rc; /* sqlite error code */
259
260 nBlob = sqlite3_blob_bytes(p->pBlob);
261 if( (p->iSeek+nRead)>nBlob ){
262 nRead = nBlob-p->iSeek;
263 }
264 if( nRead<=0 ){
265 return 0;
266 }
267
268 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
269 if( rc!=SQLITE_OK ){
270 *errorCodePtr = rc;
271 return -1;
272 }
273
274 p->iSeek += nRead;
275 return nRead;
276}
277
danielk1977d04417962007-05-02 13:16:30 +0000278/*
279** Write data to an incremental blob channel.
280*/
mistachkin7617e4a2016-07-28 17:11:20 +0000281static int SQLITE_TCLAPI incrblobOutput(
mistachkinb56660f2016-07-14 21:26:09 +0000282 ClientData instanceData,
283 CONST char *buf,
danielk1977b4e9af92007-05-01 17:49:49 +0000284 int toWrite,
285 int *errorCodePtr
286){
287 IncrblobChannel *p = (IncrblobChannel *)instanceData;
288 int nWrite = toWrite; /* Number of bytes to write */
289 int nBlob; /* Total size of the blob */
290 int rc; /* sqlite error code */
291
292 nBlob = sqlite3_blob_bytes(p->pBlob);
293 if( (p->iSeek+nWrite)>nBlob ){
294 *errorCodePtr = EINVAL;
295 return -1;
296 }
297 if( nWrite<=0 ){
298 return 0;
299 }
300
301 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
302 if( rc!=SQLITE_OK ){
303 *errorCodePtr = EIO;
304 return -1;
305 }
306
307 p->iSeek += nWrite;
308 return nWrite;
309}
310
311/*
312** Seek an incremental blob channel.
313*/
mistachkin7617e4a2016-07-28 17:11:20 +0000314static int SQLITE_TCLAPI incrblobSeek(
mistachkinb56660f2016-07-14 21:26:09 +0000315 ClientData instanceData,
danielk1977b4e9af92007-05-01 17:49:49 +0000316 long offset,
317 int seekMode,
318 int *errorCodePtr
319){
320 IncrblobChannel *p = (IncrblobChannel *)instanceData;
321
322 switch( seekMode ){
323 case SEEK_SET:
324 p->iSeek = offset;
325 break;
326 case SEEK_CUR:
327 p->iSeek += offset;
328 break;
329 case SEEK_END:
330 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
331 break;
332
333 default: assert(!"Bad seekMode");
334 }
335
336 return p->iSeek;
337}
338
339
mistachkin7617e4a2016-07-28 17:11:20 +0000340static void SQLITE_TCLAPI incrblobWatch(
341 ClientData instanceData,
342 int mode
343){
mistachkinb56660f2016-07-14 21:26:09 +0000344 /* NO-OP */
danielk1977b4e9af92007-05-01 17:49:49 +0000345}
mistachkin7617e4a2016-07-28 17:11:20 +0000346static int SQLITE_TCLAPI incrblobHandle(
347 ClientData instanceData,
348 int dir,
349 ClientData *hPtr
350){
danielk1977b4e9af92007-05-01 17:49:49 +0000351 return TCL_ERROR;
352}
353
354static Tcl_ChannelType IncrblobChannelType = {
355 "incrblob", /* typeName */
356 TCL_CHANNEL_VERSION_2, /* version */
357 incrblobClose, /* closeProc */
358 incrblobInput, /* inputProc */
359 incrblobOutput, /* outputProc */
360 incrblobSeek, /* seekProc */
361 0, /* setOptionProc */
362 0, /* getOptionProc */
363 incrblobWatch, /* watchProc (this is a no-op) */
364 incrblobHandle, /* getHandleProc (always returns error) */
365 0, /* close2Proc */
366 0, /* blockModeProc */
367 0, /* flushProc */
368 0, /* handlerProc */
369 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000370};
371
372/*
373** Create a new incrblob channel.
374*/
375static int createIncrblobChannel(
mistachkinb56660f2016-07-14 21:26:09 +0000376 Tcl_Interp *interp,
377 SqliteDb *pDb,
danielk1977b4e9af92007-05-01 17:49:49 +0000378 const char *zDb,
mistachkinb56660f2016-07-14 21:26:09 +0000379 const char *zTable,
380 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000381 sqlite_int64 iRow,
382 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000383){
384 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000385 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000386 sqlite3_blob *pBlob;
387 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000388 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000389
390 /* This variable is used to name the channels: "incrblob_[incr count]" */
391 static int count = 0;
392 char zChannel[64];
393
danielk19778cbadb02007-05-03 16:31:26 +0000394 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000395 if( rc!=SQLITE_OK ){
396 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
397 return TCL_ERROR;
398 }
399
400 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
401 p->iSeek = 0;
402 p->pBlob = pBlob;
403
drh5bb3eb92007-05-04 13:15:55 +0000404 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000405 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
406 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000407
danielk1977d04417962007-05-02 13:16:30 +0000408 /* Link the new channel into the SqliteDb.pIncrblob list. */
409 p->pNext = pDb->pIncrblob;
410 p->pPrev = 0;
411 if( p->pNext ){
412 p->pNext->pPrev = p;
413 }
414 pDb->pIncrblob = p;
415 p->pDb = pDb;
416
417 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000418 return TCL_OK;
419}
danielk197732a0d8b2007-05-04 19:03:02 +0000420#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
421 #define closeIncrblobChannels(pDb)
422#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000423
drh6d313162000-09-21 13:01:35 +0000424/*
drhd1e47332005-06-26 17:55:33 +0000425** Look at the script prefix in pCmd. We will be executing this script
426** after first appending one or more arguments. This routine analyzes
427** the script to see if it is safe to use Tcl_EvalObjv() on the script
428** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
429** faster.
430**
431** Scripts that are safe to use with Tcl_EvalObjv() consists of a
432** command name followed by zero or more arguments with no [...] or $
433** or {...} or ; to be seen anywhere. Most callback scripts consist
434** of just a single procedure name and they meet this requirement.
435*/
436static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
437 /* We could try to do something with Tcl_Parse(). But we will instead
438 ** just do a search for forbidden characters. If any of the forbidden
439 ** characters appear in pCmd, we will report the string as unsafe.
440 */
441 const char *z;
442 int n;
443 z = Tcl_GetStringFromObj(pCmd, &n);
444 while( n-- > 0 ){
445 int c = *(z++);
446 if( c=='$' || c=='[' || c==';' ) return 0;
447 }
448 return 1;
449}
450
451/*
452** Find an SqlFunc structure with the given name. Or create a new
453** one if an existing one cannot be found. Return a pointer to the
454** structure.
455*/
456static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
457 SqlFunc *p, *pNew;
drh0425f182013-11-26 16:48:04 +0000458 int nName = strlen30(zName);
459 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
drhd1e47332005-06-26 17:55:33 +0000460 pNew->zName = (char*)&pNew[1];
drh0425f182013-11-26 16:48:04 +0000461 memcpy(pNew->zName, zName, nName+1);
mistachkinb56660f2016-07-14 21:26:09 +0000462 for(p=pDb->pFunc; p; p=p->pNext){
drh0425f182013-11-26 16:48:04 +0000463 if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
drhd1e47332005-06-26 17:55:33 +0000464 Tcl_Free((char*)pNew);
465 return p;
466 }
467 }
468 pNew->interp = pDb->interp;
drhc45e6712012-10-03 11:02:33 +0000469 pNew->pDb = pDb;
drhd1e47332005-06-26 17:55:33 +0000470 pNew->pScript = 0;
471 pNew->pNext = pDb->pFunc;
472 pDb->pFunc = pNew;
473 return pNew;
474}
475
476/*
danc431fd52011-06-27 16:55:50 +0000477** Free a single SqlPreparedStmt object.
478*/
479static void dbFreeStmt(SqlPreparedStmt *pStmt){
480#ifdef SQLITE_TEST
481 if( sqlite3_sql(pStmt->pStmt)==0 ){
482 Tcl_Free((char *)pStmt->zSql);
483 }
484#endif
485 sqlite3_finalize(pStmt->pStmt);
486 Tcl_Free((char *)pStmt);
487}
488
489/*
drhfb7e7652005-01-24 00:28:42 +0000490** Finalize and free a list of prepared statements
491*/
danc431fd52011-06-27 16:55:50 +0000492static void flushStmtCache(SqliteDb *pDb){
drhfb7e7652005-01-24 00:28:42 +0000493 SqlPreparedStmt *pPreStmt;
danc431fd52011-06-27 16:55:50 +0000494 SqlPreparedStmt *pNext;
drhfb7e7652005-01-24 00:28:42 +0000495
danc431fd52011-06-27 16:55:50 +0000496 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
497 pNext = pPreStmt->pNext;
498 dbFreeStmt(pPreStmt);
drhfb7e7652005-01-24 00:28:42 +0000499 }
500 pDb->nStmt = 0;
501 pDb->stmtLast = 0;
danc431fd52011-06-27 16:55:50 +0000502 pDb->stmtList = 0;
drhfb7e7652005-01-24 00:28:42 +0000503}
504
505/*
drh895d7472004-08-20 16:02:39 +0000506** TCL calls this procedure when an sqlite3 database command is
507** deleted.
drh75897232000-05-29 14:26:00 +0000508*/
mistachkin7617e4a2016-07-28 17:11:20 +0000509static void SQLITE_TCLAPI DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000510 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000511 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000512 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000513 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000514 while( pDb->pFunc ){
515 SqlFunc *pFunc = pDb->pFunc;
516 pDb->pFunc = pFunc->pNext;
drhc45e6712012-10-03 11:02:33 +0000517 assert( pFunc->pDb==pDb );
drhd1e47332005-06-26 17:55:33 +0000518 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000519 Tcl_Free((char*)pFunc);
520 }
danielk19770202b292004-06-09 09:55:16 +0000521 while( pDb->pCollate ){
522 SqlCollate *pCollate = pDb->pCollate;
523 pDb->pCollate = pCollate->pNext;
524 Tcl_Free((char*)pCollate);
525 }
drhbec3f402000-08-04 13:49:02 +0000526 if( pDb->zBusy ){
527 Tcl_Free(pDb->zBusy);
528 }
drhb5a20d32003-04-23 12:25:23 +0000529 if( pDb->zTrace ){
530 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000531 }
mistachkinb56660f2016-07-14 21:26:09 +0000532 if( pDb->zTraceV2 ){
533 Tcl_Free(pDb->zTraceV2);
534 }
drh19e2d372005-08-29 23:00:03 +0000535 if( pDb->zProfile ){
536 Tcl_Free(pDb->zProfile);
537 }
drhe22a3342003-04-22 20:30:37 +0000538 if( pDb->zAuth ){
539 Tcl_Free(pDb->zAuth);
540 }
danielk197755c45f22005-04-03 23:54:43 +0000541 if( pDb->zNull ){
542 Tcl_Free(pDb->zNull);
543 }
danielk197794eb6a12005-12-15 15:22:08 +0000544 if( pDb->pUpdateHook ){
545 Tcl_DecrRefCount(pDb->pUpdateHook);
546 }
dan46c47d42011-03-01 18:42:07 +0000547 if( pDb->pPreUpdateHook ){
548 Tcl_DecrRefCount(pDb->pPreUpdateHook);
549 }
danielk197771fd80b2005-12-16 06:54:01 +0000550 if( pDb->pRollbackHook ){
551 Tcl_DecrRefCount(pDb->pRollbackHook);
552 }
drh5def0842010-05-05 20:00:25 +0000553 if( pDb->pWalHook ){
554 Tcl_DecrRefCount(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000555 }
danielk197794eb6a12005-12-15 15:22:08 +0000556 if( pDb->pCollateNeeded ){
557 Tcl_DecrRefCount(pDb->pCollateNeeded);
558 }
drhbec3f402000-08-04 13:49:02 +0000559 Tcl_Free((char*)pDb);
560}
561
562/*
563** This routine is called when a database file is locked while trying
564** to execute SQL.
565*/
danielk19772a764eb2004-06-12 01:43:26 +0000566static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000567 SqliteDb *pDb = (SqliteDb*)cd;
568 int rc;
569 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000570
drh5bb3eb92007-05-04 13:15:55 +0000571 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000572 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000573 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
574 return 0;
575 }
576 return 1;
drh75897232000-05-29 14:26:00 +0000577}
578
drh26e4a8b2008-05-01 17:16:52 +0000579#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000580/*
danielk1977348bb5d2003-10-18 09:37:26 +0000581** This routine is invoked as the 'progress callback' for the database.
582*/
583static int DbProgressHandler(void *cd){
584 SqliteDb *pDb = (SqliteDb*)cd;
585 int rc;
586
587 assert( pDb->zProgress );
588 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
589 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
590 return 1;
591 }
592 return 0;
593}
drh26e4a8b2008-05-01 17:16:52 +0000594#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000595
drh2eb22af2016-09-10 19:51:40 +0000596#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
597 !defined(SQLITE_OMIT_DEPRECATED)
danielk1977348bb5d2003-10-18 09:37:26 +0000598/*
drhb5a20d32003-04-23 12:25:23 +0000599** This routine is called by the SQLite trace handler whenever a new
600** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000601*/
drhb5a20d32003-04-23 12:25:23 +0000602static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000603 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000604 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000605
drhb5a20d32003-04-23 12:25:23 +0000606 Tcl_DStringInit(&str);
607 Tcl_DStringAppend(&str, pDb->zTrace, -1);
608 Tcl_DStringAppendElement(&str, zSql);
609 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
610 Tcl_DStringFree(&str);
611 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000612}
drhd1167392006-01-23 13:00:35 +0000613#endif
drh0d1a6432003-04-03 15:46:04 +0000614
drhd1167392006-01-23 13:00:35 +0000615#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000616/*
mistachkinb56660f2016-07-14 21:26:09 +0000617** This routine is called by the SQLite trace_v2 handler whenever a new
618** supported event is generated. Unsupported event types are ignored.
619** The TCL script in pDb->zTraceV2 is executed, with the arguments for
620** the event appended to it (as list elements).
621*/
622static int DbTraceV2Handler(
623 unsigned type, /* One of the SQLITE_TRACE_* event types. */
624 void *cd, /* The original context data pointer. */
625 void *pd, /* Primary event data, depends on event type. */
626 void *xd /* Extra event data, depends on event type. */
627){
628 SqliteDb *pDb = (SqliteDb*)cd;
629 Tcl_Obj *pCmd;
630
631 switch( type ){
632 case SQLITE_TRACE_STMT: {
633 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
634 char *zSql = (char *)xd;
635
636 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
637 Tcl_IncrRefCount(pCmd);
638 Tcl_ListObjAppendElement(pDb->interp, pCmd,
639 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
640 Tcl_ListObjAppendElement(pDb->interp, pCmd,
641 Tcl_NewStringObj(zSql, -1));
642 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
643 Tcl_DecrRefCount(pCmd);
644 Tcl_ResetResult(pDb->interp);
645 break;
646 }
647 case SQLITE_TRACE_PROFILE: {
648 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
649 sqlite3_int64 ns = (sqlite3_int64)xd;
650
651 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
652 Tcl_IncrRefCount(pCmd);
653 Tcl_ListObjAppendElement(pDb->interp, pCmd,
654 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
655 Tcl_ListObjAppendElement(pDb->interp, pCmd,
656 Tcl_NewWideIntObj((Tcl_WideInt)ns));
657 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
658 Tcl_DecrRefCount(pCmd);
659 Tcl_ResetResult(pDb->interp);
660 break;
661 }
662 case SQLITE_TRACE_ROW: {
663 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
664
665 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
666 Tcl_IncrRefCount(pCmd);
667 Tcl_ListObjAppendElement(pDb->interp, pCmd,
668 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
669 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
670 Tcl_DecrRefCount(pCmd);
671 Tcl_ResetResult(pDb->interp);
672 break;
673 }
674 case SQLITE_TRACE_CLOSE: {
675 sqlite3 *db = (sqlite3 *)pd;
676
677 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
678 Tcl_IncrRefCount(pCmd);
679 Tcl_ListObjAppendElement(pDb->interp, pCmd,
680 Tcl_NewWideIntObj((Tcl_WideInt)db));
681 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
682 Tcl_DecrRefCount(pCmd);
683 Tcl_ResetResult(pDb->interp);
684 break;
685 }
686 }
687 return SQLITE_OK;
688}
689#endif
690
drh2eb22af2016-09-10 19:51:40 +0000691#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
692 !defined(SQLITE_OMIT_DEPRECATED)
mistachkinb56660f2016-07-14 21:26:09 +0000693/*
drh19e2d372005-08-29 23:00:03 +0000694** This routine is called by the SQLite profile handler after a statement
695** SQL has executed. The TCL script in pDb->zProfile is evaluated.
696*/
697static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
698 SqliteDb *pDb = (SqliteDb*)cd;
699 Tcl_DString str;
700 char zTm[100];
701
702 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
703 Tcl_DStringInit(&str);
704 Tcl_DStringAppend(&str, pDb->zProfile, -1);
705 Tcl_DStringAppendElement(&str, zSql);
706 Tcl_DStringAppendElement(&str, zTm);
707 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
708 Tcl_DStringFree(&str);
709 Tcl_ResetResult(pDb->interp);
710}
drhd1167392006-01-23 13:00:35 +0000711#endif
drh19e2d372005-08-29 23:00:03 +0000712
713/*
drhaa940ea2004-01-15 02:44:03 +0000714** This routine is called when a transaction is committed. The
715** TCL script in pDb->zCommit is executed. If it returns non-zero or
716** if it throws an exception, the transaction is rolled back instead
717** of being committed.
718*/
719static int DbCommitHandler(void *cd){
720 SqliteDb *pDb = (SqliteDb*)cd;
721 int rc;
722
723 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
724 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
725 return 1;
726 }
727 return 0;
728}
729
danielk197771fd80b2005-12-16 06:54:01 +0000730static void DbRollbackHandler(void *clientData){
731 SqliteDb *pDb = (SqliteDb*)clientData;
732 assert(pDb->pRollbackHook);
733 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
734 Tcl_BackgroundError(pDb->interp);
735 }
736}
737
drh5def0842010-05-05 20:00:25 +0000738/*
739** This procedure handles wal_hook callbacks.
740*/
741static int DbWalHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000742 void *clientData,
743 sqlite3 *db,
744 const char *zDb,
dan8d22a172010-04-19 18:03:51 +0000745 int nEntry
746){
drh5def0842010-05-05 20:00:25 +0000747 int ret = SQLITE_OK;
dan8d22a172010-04-19 18:03:51 +0000748 Tcl_Obj *p;
749 SqliteDb *pDb = (SqliteDb*)clientData;
750 Tcl_Interp *interp = pDb->interp;
drh5def0842010-05-05 20:00:25 +0000751 assert(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000752
dan6e45e0c2014-12-10 20:29:49 +0000753 assert( db==pDb->db );
drh5def0842010-05-05 20:00:25 +0000754 p = Tcl_DuplicateObj(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000755 Tcl_IncrRefCount(p);
756 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
757 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
mistachkinb56660f2016-07-14 21:26:09 +0000758 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
dan8d22a172010-04-19 18:03:51 +0000759 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
760 ){
761 Tcl_BackgroundError(interp);
762 }
763 Tcl_DecrRefCount(p);
764
765 return ret;
766}
767
drhbcf4f482009-03-27 12:44:35 +0000768#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000769static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
770 char zBuf[64];
drh65545b52015-01-19 00:35:53 +0000771 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
danielk1977404ca072009-03-16 13:19:36 +0000772 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
drh65545b52015-01-19 00:35:53 +0000773 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
danielk1977404ca072009-03-16 13:19:36 +0000774 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
775}
776#else
drhbcf4f482009-03-27 12:44:35 +0000777# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000778#endif
779
drh69910da2009-03-27 12:32:54 +0000780#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000781static void DbUnlockNotify(void **apArg, int nArg){
782 int i;
783 for(i=0; i<nArg; i++){
784 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
785 SqliteDb *pDb = (SqliteDb *)apArg[i];
786 setTestUnlockNotifyVars(pDb->interp, i, nArg);
787 assert( pDb->pUnlockNotify);
788 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
789 Tcl_DecrRefCount(pDb->pUnlockNotify);
790 pDb->pUnlockNotify = 0;
791 }
792}
drh69910da2009-03-27 12:32:54 +0000793#endif
danielk1977404ca072009-03-16 13:19:36 +0000794
drh9b1c62d2011-03-30 21:04:43 +0000795#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +0000796/*
797** Pre-update hook callback.
798*/
799static void DbPreUpdateHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000800 void *p,
dan46c47d42011-03-01 18:42:07 +0000801 sqlite3 *db,
802 int op,
mistachkinb56660f2016-07-14 21:26:09 +0000803 const char *zDb,
804 const char *zTbl,
dan46c47d42011-03-01 18:42:07 +0000805 sqlite_int64 iKey1,
806 sqlite_int64 iKey2
807){
808 SqliteDb *pDb = (SqliteDb *)p;
809 Tcl_Obj *pCmd;
810 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
811
812 assert( (SQLITE_DELETE-1)/9 == 0 );
813 assert( (SQLITE_INSERT-1)/9 == 1 );
814 assert( (SQLITE_UPDATE-1)/9 == 2 );
815 assert( pDb->pPreUpdateHook );
816 assert( db==pDb->db );
817 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
818
819 pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
820 Tcl_IncrRefCount(pCmd);
821 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
822 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
823 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
824 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
825 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
826 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
827 Tcl_DecrRefCount(pCmd);
828}
drh9b1c62d2011-03-30 21:04:43 +0000829#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +0000830
danielk197794eb6a12005-12-15 15:22:08 +0000831static void DbUpdateHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000832 void *p,
danielk197794eb6a12005-12-15 15:22:08 +0000833 int op,
mistachkinb56660f2016-07-14 21:26:09 +0000834 const char *zDb,
835 const char *zTbl,
danielk197794eb6a12005-12-15 15:22:08 +0000836 sqlite_int64 rowid
837){
838 SqliteDb *pDb = (SqliteDb *)p;
839 Tcl_Obj *pCmd;
dan46c47d42011-03-01 18:42:07 +0000840 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
841
842 assert( (SQLITE_DELETE-1)/9 == 0 );
843 assert( (SQLITE_INSERT-1)/9 == 1 );
844 assert( (SQLITE_UPDATE-1)/9 == 2 );
danielk197794eb6a12005-12-15 15:22:08 +0000845
846 assert( pDb->pUpdateHook );
847 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
848
849 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
850 Tcl_IncrRefCount(pCmd);
dan46c47d42011-03-01 18:42:07 +0000851 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
danielk197794eb6a12005-12-15 15:22:08 +0000852 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
853 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
854 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
855 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
drhefdde162010-10-27 15:36:21 +0000856 Tcl_DecrRefCount(pCmd);
danielk197794eb6a12005-12-15 15:22:08 +0000857}
858
danielk19777cedc8d2004-06-10 10:50:08 +0000859static void tclCollateNeeded(
860 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000861 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000862 int enc,
863 const char *zName
864){
865 SqliteDb *pDb = (SqliteDb *)pCtx;
866 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
867 Tcl_IncrRefCount(pScript);
868 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
869 Tcl_EvalObjEx(pDb->interp, pScript, 0);
870 Tcl_DecrRefCount(pScript);
871}
872
drhaa940ea2004-01-15 02:44:03 +0000873/*
danielk19770202b292004-06-09 09:55:16 +0000874** This routine is called to evaluate an SQL collation function implemented
875** using TCL script.
876*/
877static int tclSqlCollate(
878 void *pCtx,
879 int nA,
880 const void *zA,
881 int nB,
882 const void *zB
883){
884 SqlCollate *p = (SqlCollate *)pCtx;
885 Tcl_Obj *pCmd;
886
887 pCmd = Tcl_NewStringObj(p->zScript, -1);
888 Tcl_IncrRefCount(pCmd);
889 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
890 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000891 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000892 Tcl_DecrRefCount(pCmd);
893 return (atoi(Tcl_GetStringResult(p->interp)));
894}
895
896/*
drhcabb0812002-09-14 13:47:32 +0000897** This routine is called to evaluate an SQL function implemented
898** using TCL script.
899*/
drhfb7e7652005-01-24 00:28:42 +0000900static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000901 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000902 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000903 int i;
904 int rc;
905
drhd1e47332005-06-26 17:55:33 +0000906 if( argc==0 ){
907 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
908 ** script object directly. This allows the TCL compiler to generate
909 ** bytecode for the command on the first invocation and thus make
910 ** subsequent invocations much faster. */
911 pCmd = p->pScript;
912 Tcl_IncrRefCount(pCmd);
913 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
914 Tcl_DecrRefCount(pCmd);
915 }else{
916 /* If there are arguments to the function, make a shallow copy of the
917 ** script object, lappend the arguments, then evaluate the copy.
918 **
peter.d.reid60ec9142014-09-06 16:39:46 +0000919 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
mistachkinb56660f2016-07-14 21:26:09 +0000920 ** The new Tcl_Obj contains pointers to the original list elements.
drhd1e47332005-06-26 17:55:33 +0000921 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
922 ** of the list to tclCmdNameType, that alternate representation will
923 ** be preserved and reused on the next invocation.
924 */
925 Tcl_Obj **aArg;
926 int nArg;
927 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
mistachkinb56660f2016-07-14 21:26:09 +0000928 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhd1e47332005-06-26 17:55:33 +0000929 return;
mistachkinb56660f2016-07-14 21:26:09 +0000930 }
drhd1e47332005-06-26 17:55:33 +0000931 pCmd = Tcl_NewListObj(nArg, aArg);
932 Tcl_IncrRefCount(pCmd);
933 for(i=0; i<argc; i++){
934 sqlite3_value *pIn = argv[i];
935 Tcl_Obj *pVal;
mistachkinb56660f2016-07-14 21:26:09 +0000936
drhd1e47332005-06-26 17:55:33 +0000937 /* Set pVal to contain the i'th column of this row. */
938 switch( sqlite3_value_type(pIn) ){
939 case SQLITE_BLOB: {
940 int bytes = sqlite3_value_bytes(pIn);
941 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
942 break;
943 }
944 case SQLITE_INTEGER: {
945 sqlite_int64 v = sqlite3_value_int64(pIn);
946 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +0000947 pVal = Tcl_NewIntObj((int)v);
drhd1e47332005-06-26 17:55:33 +0000948 }else{
949 pVal = Tcl_NewWideIntObj(v);
950 }
951 break;
952 }
953 case SQLITE_FLOAT: {
954 double r = sqlite3_value_double(pIn);
955 pVal = Tcl_NewDoubleObj(r);
956 break;
957 }
958 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +0000959 pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
drhd1e47332005-06-26 17:55:33 +0000960 break;
961 }
962 default: {
963 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000964 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000965 break;
966 }
967 }
968 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
969 if( rc ){
970 Tcl_DecrRefCount(pCmd);
mistachkinb56660f2016-07-14 21:26:09 +0000971 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhd1e47332005-06-26 17:55:33 +0000972 return;
973 }
danielk197751ad0ec2004-05-24 12:39:02 +0000974 }
drhd1e47332005-06-26 17:55:33 +0000975 if( !p->useEvalObjv ){
976 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
977 ** is a list without a string representation. To prevent this from
978 ** happening, make sure pCmd has a valid string representation */
979 Tcl_GetString(pCmd);
980 }
981 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
982 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000983 }
danielk1977562e8d32005-05-20 09:40:55 +0000984
drhc7f269d2005-05-05 10:30:29 +0000985 if( rc && rc!=TCL_RETURN ){
mistachkinb56660f2016-07-14 21:26:09 +0000986 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000987 }else{
drhc7f269d2005-05-05 10:30:29 +0000988 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
989 int n;
990 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000991 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000992 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000993 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000994 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000995 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000996 data = Tcl_GetByteArrayFromObj(pVar, &n);
997 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000998 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000999 Tcl_GetIntFromObj(0, pVar, &n);
1000 sqlite3_result_int(context, n);
1001 }else if( c=='d' && strcmp(zType,"double")==0 ){
1002 double r;
1003 Tcl_GetDoubleFromObj(0, pVar, &r);
1004 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +00001005 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1006 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +00001007 Tcl_WideInt v;
1008 Tcl_GetWideIntFromObj(0, pVar, &v);
1009 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +00001010 }else{
danielk197700fd9572005-12-07 06:27:43 +00001011 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1012 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +00001013 }
drhcabb0812002-09-14 13:47:32 +00001014 }
1015}
drh895d7472004-08-20 16:02:39 +00001016
drhe22a3342003-04-22 20:30:37 +00001017#ifndef SQLITE_OMIT_AUTHORIZATION
1018/*
1019** This is the authentication function. It appends the authentication
1020** type code and the two arguments to zCmd[] then invokes the result
1021** on the interpreter. The reply is examined to determine if the
1022** authentication fails or succeeds.
1023*/
1024static int auth_callback(
1025 void *pArg,
1026 int code,
1027 const char *zArg1,
1028 const char *zArg2,
1029 const char *zArg3,
1030 const char *zArg4
drh32c6a482014-09-11 13:44:52 +00001031#ifdef SQLITE_USER_AUTHENTICATION
1032 ,const char *zArg5
1033#endif
drhe22a3342003-04-22 20:30:37 +00001034){
mistachkin6ef5e122014-01-24 17:03:55 +00001035 const char *zCode;
drhe22a3342003-04-22 20:30:37 +00001036 Tcl_DString str;
1037 int rc;
1038 const char *zReply;
drh94189212017-05-11 13:43:57 +00001039 /* EVIDENCE-OF: R-38590-62769 The first parameter to the authorizer
1040 ** callback is a copy of the third parameter to the
1041 ** sqlite3_set_authorizer() interface.
1042 */
drhe22a3342003-04-22 20:30:37 +00001043 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +00001044 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +00001045
drh94189212017-05-11 13:43:57 +00001046 /* EVIDENCE-OF: R-56518-44310 The second parameter to the callback is an
1047 ** integer action code that specifies the particular action to be
1048 ** authorized. */
drhe22a3342003-04-22 20:30:37 +00001049 switch( code ){
1050 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
1051 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
1052 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
1053 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
1054 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
1055 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
1056 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
1057 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
1058 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
1059 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
1060 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
1061 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
1062 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
1063 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
1064 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
1065 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
1066 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
1067 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
1068 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
1069 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
1070 case SQLITE_READ : zCode="SQLITE_READ"; break;
1071 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
1072 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
1073 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +00001074 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
1075 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +00001076 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +00001077 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +00001078 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +00001079 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
1080 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +00001081 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +00001082 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drh65a2aaa2014-01-16 22:40:02 +00001083 case SQLITE_RECURSIVE : zCode="SQLITE_RECURSIVE"; break;
drhe22a3342003-04-22 20:30:37 +00001084 default : zCode="????"; break;
1085 }
1086 Tcl_DStringInit(&str);
1087 Tcl_DStringAppend(&str, pDb->zAuth, -1);
1088 Tcl_DStringAppendElement(&str, zCode);
1089 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
1090 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
1091 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
1092 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
drh32c6a482014-09-11 13:44:52 +00001093#ifdef SQLITE_USER_AUTHENTICATION
1094 Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
mistachkinb56660f2016-07-14 21:26:09 +00001095#endif
drhe22a3342003-04-22 20:30:37 +00001096 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
1097 Tcl_DStringFree(&str);
drhb07028f2011-10-14 21:49:18 +00001098 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
drhe22a3342003-04-22 20:30:37 +00001099 if( strcmp(zReply,"SQLITE_OK")==0 ){
1100 rc = SQLITE_OK;
1101 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
1102 rc = SQLITE_DENY;
1103 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
1104 rc = SQLITE_IGNORE;
1105 }else{
1106 rc = 999;
1107 }
1108 return rc;
1109}
1110#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +00001111
1112/*
tpoindex1067fe12004-12-17 15:41:11 +00001113** This routine reads a line of text from FILE in, stores
1114** the text in memory obtained from malloc() and returns a pointer
1115** to the text. NULL is returned at end of file, or if malloc()
1116** fails.
1117**
1118** The interface is like "readline" but no command-line editing
1119** is done.
1120**
1121** copied from shell.c from '.import' command
1122*/
1123static char *local_getline(char *zPrompt, FILE *in){
1124 char *zLine;
1125 int nLine;
1126 int n;
tpoindex1067fe12004-12-17 15:41:11 +00001127
1128 nLine = 100;
1129 zLine = malloc( nLine );
1130 if( zLine==0 ) return 0;
1131 n = 0;
drhb07028f2011-10-14 21:49:18 +00001132 while( 1 ){
tpoindex1067fe12004-12-17 15:41:11 +00001133 if( n+100>nLine ){
1134 nLine = nLine*2 + 100;
1135 zLine = realloc(zLine, nLine);
1136 if( zLine==0 ) return 0;
1137 }
1138 if( fgets(&zLine[n], nLine - n, in)==0 ){
1139 if( n==0 ){
1140 free(zLine);
1141 return 0;
1142 }
1143 zLine[n] = 0;
tpoindex1067fe12004-12-17 15:41:11 +00001144 break;
1145 }
1146 while( zLine[n] ){ n++; }
1147 if( n>0 && zLine[n-1]=='\n' ){
1148 n--;
1149 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +00001150 break;
tpoindex1067fe12004-12-17 15:41:11 +00001151 }
1152 }
1153 zLine = realloc( zLine, n+1 );
1154 return zLine;
1155}
1156
danielk19778e556522007-11-13 10:30:24 +00001157
1158/*
dan4a4c11a2009-10-06 14:59:02 +00001159** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +00001160**
dan4a4c11a2009-10-06 14:59:02 +00001161** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +00001162**
dan4a4c11a2009-10-06 14:59:02 +00001163** It is invoked after evaluating the script SCRIPT to commit or rollback
1164** the transaction or savepoint opened by the [transaction] command.
1165*/
mistachkina121cc72016-07-28 18:06:52 +00001166static int SQLITE_TCLAPI DbTransPostCmd(
dan4a4c11a2009-10-06 14:59:02 +00001167 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1168 Tcl_Interp *interp, /* Tcl interpreter */
1169 int result /* Result of evaluating SCRIPT */
1170){
mistachkin6ef5e122014-01-24 17:03:55 +00001171 static const char *const azEnd[] = {
dan4a4c11a2009-10-06 14:59:02 +00001172 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1173 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1174 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1175 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1176 };
1177 SqliteDb *pDb = (SqliteDb*)data[0];
1178 int rc = result;
1179 const char *zEnd;
1180
1181 pDb->nTransaction--;
1182 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1183
1184 pDb->disableAuth++;
1185 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1186 /* This is a tricky scenario to handle. The most likely cause of an
mistachkinb56660f2016-07-14 21:26:09 +00001187 ** error is that the exec() above was an attempt to commit the
dan4a4c11a2009-10-06 14:59:02 +00001188 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
mistachkin48864df2013-03-21 21:20:32 +00001189 ** that an IO-error has occurred. In either case, throw a Tcl exception
dan4a4c11a2009-10-06 14:59:02 +00001190 ** and try to rollback the transaction.
1191 **
mistachkinb56660f2016-07-14 21:26:09 +00001192 ** But it could also be that the user executed one or more BEGIN,
dan4a4c11a2009-10-06 14:59:02 +00001193 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1194 ** this method's logic. Not clear how this would be best handled.
1195 */
1196 if( rc!=TCL_ERROR ){
drha198f2b2014-02-07 19:26:13 +00001197 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
dan4a4c11a2009-10-06 14:59:02 +00001198 rc = TCL_ERROR;
1199 }
1200 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1201 }
1202 pDb->disableAuth--;
1203
1204 return rc;
1205}
1206
1207/*
danc431fd52011-06-27 16:55:50 +00001208** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1209** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1210** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
mistachkinb56660f2016-07-14 21:26:09 +00001211** on whether or not the [db_use_legacy_prepare] command has been used to
danc431fd52011-06-27 16:55:50 +00001212** configure the connection.
1213*/
1214static int dbPrepare(
1215 SqliteDb *pDb, /* Database object */
1216 const char *zSql, /* SQL to compile */
1217 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1218 const char **pzOut /* OUT: Pointer to next SQL statement */
1219){
drh2c2f3922017-06-01 00:54:35 +00001220 unsigned int prepFlags = 0;
danc431fd52011-06-27 16:55:50 +00001221#ifdef SQLITE_TEST
1222 if( pDb->bLegacyPrepare ){
1223 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1224 }
1225#endif
drh2c2f3922017-06-01 00:54:35 +00001226 /* If the statement cache is large, use the SQLITE_PREPARE_PERSISTENT
1227 ** flags, which uses less lookaside memory. But if the cache is small,
1228 ** omit that flag to make full use of lookaside */
1229 if( pDb->maxStmt>5 ) prepFlags = SQLITE_PREPARE_PERSISTENT;
1230
1231 return sqlite3_prepare_v3(pDb->db, zSql, -1, prepFlags, ppStmt, pzOut);
danc431fd52011-06-27 16:55:50 +00001232}
1233
1234/*
dan4a4c11a2009-10-06 14:59:02 +00001235** Search the cache for a prepared-statement object that implements the
1236** first SQL statement in the buffer pointed to by parameter zIn. If
1237** no such prepared-statement can be found, allocate and prepare a new
1238** one. In either case, bind the current values of the relevant Tcl
1239** variables to any $var, :var or @var variables in the statement. Before
1240** returning, set *ppPreStmt to point to the prepared-statement object.
1241**
1242** Output parameter *pzOut is set to point to the next SQL statement in
1243** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1244** next statement.
1245**
1246** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1247** and an error message loaded into interpreter pDb->interp.
1248*/
1249static int dbPrepareAndBind(
1250 SqliteDb *pDb, /* Database object */
1251 char const *zIn, /* SQL to compile */
1252 char const **pzOut, /* OUT: Pointer to next SQL statement */
1253 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1254){
1255 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
mistachkin7bb22ac2015-01-12 19:59:12 +00001256 sqlite3_stmt *pStmt = 0; /* Prepared statement object */
dan4a4c11a2009-10-06 14:59:02 +00001257 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1258 int nSql; /* Length of zSql in bytes */
mistachkin7bb22ac2015-01-12 19:59:12 +00001259 int nVar = 0; /* Number of variables in statement */
dan4a4c11a2009-10-06 14:59:02 +00001260 int iParm = 0; /* Next free entry in apParm */
drh0425f182013-11-26 16:48:04 +00001261 char c;
dan4a4c11a2009-10-06 14:59:02 +00001262 int i;
1263 Tcl_Interp *interp = pDb->interp;
1264
1265 *ppPreStmt = 0;
1266
1267 /* Trim spaces from the start of zSql and calculate the remaining length. */
drh0425f182013-11-26 16:48:04 +00001268 while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
dan4a4c11a2009-10-06 14:59:02 +00001269 nSql = strlen30(zSql);
1270
1271 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1272 int n = pPreStmt->nSql;
mistachkinb56660f2016-07-14 21:26:09 +00001273 if( nSql>=n
dan4a4c11a2009-10-06 14:59:02 +00001274 && memcmp(pPreStmt->zSql, zSql, n)==0
1275 && (zSql[n]==0 || zSql[n-1]==';')
1276 ){
1277 pStmt = pPreStmt->pStmt;
1278 *pzOut = &zSql[pPreStmt->nSql];
1279
1280 /* When a prepared statement is found, unlink it from the
1281 ** cache list. It will later be added back to the beginning
1282 ** of the cache list in order to implement LRU replacement.
1283 */
1284 if( pPreStmt->pPrev ){
1285 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1286 }else{
1287 pDb->stmtList = pPreStmt->pNext;
1288 }
1289 if( pPreStmt->pNext ){
1290 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1291 }else{
1292 pDb->stmtLast = pPreStmt->pPrev;
1293 }
1294 pDb->nStmt--;
1295 nVar = sqlite3_bind_parameter_count(pStmt);
1296 break;
1297 }
1298 }
mistachkinb56660f2016-07-14 21:26:09 +00001299
dan4a4c11a2009-10-06 14:59:02 +00001300 /* If no prepared statement was found. Compile the SQL text. Also allocate
1301 ** a new SqlPreparedStmt structure. */
1302 if( pPreStmt==0 ){
1303 int nByte;
1304
danc431fd52011-06-27 16:55:50 +00001305 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
drhc45e6712012-10-03 11:02:33 +00001306 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001307 return TCL_ERROR;
1308 }
1309 if( pStmt==0 ){
1310 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1311 /* A compile-time error in the statement. */
drhc45e6712012-10-03 11:02:33 +00001312 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001313 return TCL_ERROR;
1314 }else{
1315 /* The statement was a no-op. Continue to the next statement
1316 ** in the SQL string.
1317 */
1318 return TCL_OK;
1319 }
1320 }
1321
1322 assert( pPreStmt==0 );
1323 nVar = sqlite3_bind_parameter_count(pStmt);
1324 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1325 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1326 memset(pPreStmt, 0, nByte);
1327
1328 pPreStmt->pStmt = pStmt;
drh7ed243b2012-04-19 17:19:51 +00001329 pPreStmt->nSql = (int)(*pzOut - zSql);
dan4a4c11a2009-10-06 14:59:02 +00001330 pPreStmt->zSql = sqlite3_sql(pStmt);
1331 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
danc431fd52011-06-27 16:55:50 +00001332#ifdef SQLITE_TEST
1333 if( pPreStmt->zSql==0 ){
1334 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1335 memcpy(zCopy, zSql, pPreStmt->nSql);
1336 zCopy[pPreStmt->nSql] = '\0';
1337 pPreStmt->zSql = zCopy;
1338 }
1339#endif
dan4a4c11a2009-10-06 14:59:02 +00001340 }
1341 assert( pPreStmt );
1342 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1343 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1344
mistachkinb56660f2016-07-14 21:26:09 +00001345 /* Bind values to parameters that begin with $ or : */
dan4a4c11a2009-10-06 14:59:02 +00001346 for(i=1; i<=nVar; i++){
1347 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1348 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1349 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1350 if( pVar ){
1351 int n;
1352 u8 *data;
1353 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
mistachkin8e189222015-04-19 21:43:16 +00001354 c = zType[0];
dan4a4c11a2009-10-06 14:59:02 +00001355 if( zVar[0]=='@' ||
1356 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1357 /* Load a BLOB type if the Tcl variable is a bytearray and
1358 ** it has no string representation or the host
1359 ** parameter name begins with "@". */
1360 data = Tcl_GetByteArrayFromObj(pVar, &n);
1361 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1362 Tcl_IncrRefCount(pVar);
1363 pPreStmt->apParm[iParm++] = pVar;
1364 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1365 Tcl_GetIntFromObj(interp, pVar, &n);
1366 sqlite3_bind_int(pStmt, i, n);
1367 }else if( c=='d' && strcmp(zType,"double")==0 ){
1368 double r;
1369 Tcl_GetDoubleFromObj(interp, pVar, &r);
1370 sqlite3_bind_double(pStmt, i, r);
1371 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1372 (c=='i' && strcmp(zType,"int")==0) ){
1373 Tcl_WideInt v;
1374 Tcl_GetWideIntFromObj(interp, pVar, &v);
1375 sqlite3_bind_int64(pStmt, i, v);
1376 }else{
1377 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1378 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1379 Tcl_IncrRefCount(pVar);
1380 pPreStmt->apParm[iParm++] = pVar;
1381 }
1382 }else{
1383 sqlite3_bind_null(pStmt, i);
1384 }
1385 }
1386 }
1387 pPreStmt->nParm = iParm;
1388 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001389
dan4a4c11a2009-10-06 14:59:02 +00001390 return TCL_OK;
1391}
1392
dan4a4c11a2009-10-06 14:59:02 +00001393/*
1394** Release a statement reference obtained by calling dbPrepareAndBind().
1395** There should be exactly one call to this function for each call to
1396** dbPrepareAndBind().
1397**
1398** If the discard parameter is non-zero, then the statement is deleted
1399** immediately. Otherwise it is added to the LRU list and may be returned
1400** by a subsequent call to dbPrepareAndBind().
1401*/
1402static void dbReleaseStmt(
1403 SqliteDb *pDb, /* Database handle */
1404 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1405 int discard /* True to delete (not cache) the pPreStmt */
1406){
1407 int i;
1408
1409 /* Free the bound string and blob parameters */
1410 for(i=0; i<pPreStmt->nParm; i++){
1411 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1412 }
1413 pPreStmt->nParm = 0;
1414
1415 if( pDb->maxStmt<=0 || discard ){
1416 /* If the cache is turned off, deallocated the statement */
danc431fd52011-06-27 16:55:50 +00001417 dbFreeStmt(pPreStmt);
dan4a4c11a2009-10-06 14:59:02 +00001418 }else{
1419 /* Add the prepared statement to the beginning of the cache list. */
1420 pPreStmt->pNext = pDb->stmtList;
1421 pPreStmt->pPrev = 0;
1422 if( pDb->stmtList ){
1423 pDb->stmtList->pPrev = pPreStmt;
1424 }
1425 pDb->stmtList = pPreStmt;
1426 if( pDb->stmtLast==0 ){
1427 assert( pDb->nStmt==0 );
1428 pDb->stmtLast = pPreStmt;
1429 }else{
1430 assert( pDb->nStmt>0 );
1431 }
1432 pDb->nStmt++;
mistachkinb56660f2016-07-14 21:26:09 +00001433
1434 /* If we have too many statement in cache, remove the surplus from
dan4a4c11a2009-10-06 14:59:02 +00001435 ** the end of the cache list. */
1436 while( pDb->nStmt>pDb->maxStmt ){
danc431fd52011-06-27 16:55:50 +00001437 SqlPreparedStmt *pLast = pDb->stmtLast;
1438 pDb->stmtLast = pLast->pPrev;
dan4a4c11a2009-10-06 14:59:02 +00001439 pDb->stmtLast->pNext = 0;
1440 pDb->nStmt--;
danc431fd52011-06-27 16:55:50 +00001441 dbFreeStmt(pLast);
dan4a4c11a2009-10-06 14:59:02 +00001442 }
1443 }
1444}
1445
1446/*
1447** Structure used with dbEvalXXX() functions:
1448**
1449** dbEvalInit()
1450** dbEvalStep()
1451** dbEvalFinalize()
1452** dbEvalRowInfo()
1453** dbEvalColumnValue()
1454*/
1455typedef struct DbEvalContext DbEvalContext;
1456struct DbEvalContext {
1457 SqliteDb *pDb; /* Database handle */
1458 Tcl_Obj *pSql; /* Object holding string zSql */
1459 const char *zSql; /* Remaining SQL to execute */
1460 SqlPreparedStmt *pPreStmt; /* Current statement */
1461 int nCol; /* Number of columns returned by pStmt */
drhaf38cdb2017-06-26 21:08:32 +00001462 int evalFlags; /* Flags used */
dan4a4c11a2009-10-06 14:59:02 +00001463 Tcl_Obj *pArray; /* Name of array variable */
1464 Tcl_Obj **apColName; /* Array of column names */
1465};
1466
drhaf38cdb2017-06-26 21:08:32 +00001467#define SQLITE_EVAL_WITHOUTNULLS 0x00001 /* Unset array(*) for NULL */
1468
dan4a4c11a2009-10-06 14:59:02 +00001469/*
1470** Release any cache of column names currently held as part of
1471** the DbEvalContext structure passed as the first argument.
1472*/
1473static void dbReleaseColumnNames(DbEvalContext *p){
1474 if( p->apColName ){
1475 int i;
1476 for(i=0; i<p->nCol; i++){
1477 Tcl_DecrRefCount(p->apColName[i]);
1478 }
1479 Tcl_Free((char *)p->apColName);
1480 p->apColName = 0;
1481 }
1482 p->nCol = 0;
1483}
1484
1485/*
1486** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001487**
1488** If pArray is not NULL, then it contains the name of a Tcl array
1489** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001490** the names of the columns returned by the statement as part of each
mistachkinb56660f2016-07-14 21:26:09 +00001491** call to dbEvalStep(), in order from left to right. e.g. if the names
1492** of the returned columns are a, b and c, it does the equivalent of the
dan4a4c11a2009-10-06 14:59:02 +00001493** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001494**
1495** set ${pArray}(*) {a b c}
1496*/
dan4a4c11a2009-10-06 14:59:02 +00001497static void dbEvalInit(
1498 DbEvalContext *p, /* Pointer to structure to initialize */
1499 SqliteDb *pDb, /* Database handle */
1500 Tcl_Obj *pSql, /* Object containing SQL script */
drhaf38cdb2017-06-26 21:08:32 +00001501 Tcl_Obj *pArray, /* Name of Tcl array to set (*) element of */
1502 int evalFlags /* Flags controlling evaluation */
danielk19778e556522007-11-13 10:30:24 +00001503){
dan4a4c11a2009-10-06 14:59:02 +00001504 memset(p, 0, sizeof(DbEvalContext));
1505 p->pDb = pDb;
1506 p->zSql = Tcl_GetString(pSql);
1507 p->pSql = pSql;
1508 Tcl_IncrRefCount(pSql);
1509 if( pArray ){
1510 p->pArray = pArray;
1511 Tcl_IncrRefCount(pArray);
1512 }
drhaf38cdb2017-06-26 21:08:32 +00001513 p->evalFlags = evalFlags;
dan4a4c11a2009-10-06 14:59:02 +00001514}
danielk19778e556522007-11-13 10:30:24 +00001515
dan4a4c11a2009-10-06 14:59:02 +00001516/*
1517** Obtain information about the row that the DbEvalContext passed as the
1518** first argument currently points to.
1519*/
1520static void dbEvalRowInfo(
1521 DbEvalContext *p, /* Evaluation context */
1522 int *pnCol, /* OUT: Number of column names */
1523 Tcl_Obj ***papColName /* OUT: Array of column names */
1524){
danielk19778e556522007-11-13 10:30:24 +00001525 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001526 if( 0==p->apColName ){
1527 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1528 int i; /* Iterator variable */
1529 int nCol; /* Number of columns returned by pStmt */
1530 Tcl_Obj **apColName = 0; /* Array of column names */
1531
1532 p->nCol = nCol = sqlite3_column_count(pStmt);
1533 if( nCol>0 && (papColName || p->pArray) ){
1534 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1535 for(i=0; i<nCol; i++){
drhc45e6712012-10-03 11:02:33 +00001536 apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
dan4a4c11a2009-10-06 14:59:02 +00001537 Tcl_IncrRefCount(apColName[i]);
1538 }
1539 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001540 }
1541
1542 /* If results are being stored in an array variable, then create
1543 ** the array(*) entry for that array
1544 */
dan4a4c11a2009-10-06 14:59:02 +00001545 if( p->pArray ){
1546 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001547 Tcl_Obj *pColList = Tcl_NewObj();
1548 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001549
danielk19778e556522007-11-13 10:30:24 +00001550 for(i=0; i<nCol; i++){
1551 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1552 }
1553 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001554 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001555 Tcl_DecrRefCount(pStar);
1556 }
danielk19778e556522007-11-13 10:30:24 +00001557 }
1558
dan4a4c11a2009-10-06 14:59:02 +00001559 if( papColName ){
1560 *papColName = p->apColName;
1561 }
1562 if( pnCol ){
1563 *pnCol = p->nCol;
1564 }
1565}
1566
1567/*
1568** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1569** returned, then an error message is stored in the interpreter before
1570** returning.
1571**
1572** A return value of TCL_OK means there is a row of data available. The
1573** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1574** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1575** is returned, then the SQL script has finished executing and there are
1576** no further rows available. This is similar to SQLITE_DONE.
1577*/
1578static int dbEvalStep(DbEvalContext *p){
danc431fd52011-06-27 16:55:50 +00001579 const char *zPrevSql = 0; /* Previous value of p->zSql */
1580
dan4a4c11a2009-10-06 14:59:02 +00001581 while( p->zSql[0] || p->pPreStmt ){
1582 int rc;
1583 if( p->pPreStmt==0 ){
danc431fd52011-06-27 16:55:50 +00001584 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
dan4a4c11a2009-10-06 14:59:02 +00001585 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1586 if( rc!=TCL_OK ) return rc;
1587 }else{
1588 int rcs;
1589 SqliteDb *pDb = p->pDb;
1590 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1591 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1592
1593 rcs = sqlite3_step(pStmt);
1594 if( rcs==SQLITE_ROW ){
1595 return TCL_OK;
1596 }
1597 if( p->pArray ){
1598 dbEvalRowInfo(p, 0, 0);
1599 }
1600 rcs = sqlite3_reset(pStmt);
1601
1602 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1603 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001604 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
danc456a762017-06-22 16:51:16 +00001605 pDb->nVMStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_VM_STEP,1);
dan4a4c11a2009-10-06 14:59:02 +00001606 dbReleaseColumnNames(p);
1607 p->pPreStmt = 0;
1608
1609 if( rcs!=SQLITE_OK ){
1610 /* If a run-time error occurs, report the error and stop reading
1611 ** the SQL. */
dan4a4c11a2009-10-06 14:59:02 +00001612 dbReleaseStmt(pDb, pPreStmt, 1);
danc431fd52011-06-27 16:55:50 +00001613#if SQLITE_TEST
1614 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1615 /* If the runtime error was an SQLITE_SCHEMA, and the database
mistachkinb56660f2016-07-14 21:26:09 +00001616 ** handle is configured to use the legacy sqlite3_prepare()
danc431fd52011-06-27 16:55:50 +00001617 ** interface, retry prepare()/step() on the same SQL statement.
1618 ** This only happens once. If there is a second SQLITE_SCHEMA
1619 ** error, the error will be returned to the caller. */
1620 p->zSql = zPrevSql;
1621 continue;
1622 }
1623#endif
drhc45e6712012-10-03 11:02:33 +00001624 Tcl_SetObjResult(pDb->interp,
1625 Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001626 return TCL_ERROR;
1627 }else{
1628 dbReleaseStmt(pDb, pPreStmt, 0);
1629 }
1630 }
1631 }
1632
1633 /* Finished */
1634 return TCL_BREAK;
1635}
1636
1637/*
1638** Free all resources currently held by the DbEvalContext structure passed
1639** as the first argument. There should be exactly one call to this function
1640** for each call to dbEvalInit().
1641*/
1642static void dbEvalFinalize(DbEvalContext *p){
1643 if( p->pPreStmt ){
1644 sqlite3_reset(p->pPreStmt->pStmt);
1645 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1646 p->pPreStmt = 0;
1647 }
1648 if( p->pArray ){
1649 Tcl_DecrRefCount(p->pArray);
1650 p->pArray = 0;
1651 }
1652 Tcl_DecrRefCount(p->pSql);
1653 dbReleaseColumnNames(p);
1654}
1655
1656/*
1657** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1658** the value for the iCol'th column of the row currently pointed to by
1659** the DbEvalContext structure passed as the first argument.
1660*/
1661static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1662 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1663 switch( sqlite3_column_type(pStmt, iCol) ){
1664 case SQLITE_BLOB: {
1665 int bytes = sqlite3_column_bytes(pStmt, iCol);
1666 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1667 if( !zBlob ) bytes = 0;
1668 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1669 }
1670 case SQLITE_INTEGER: {
1671 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1672 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +00001673 return Tcl_NewIntObj((int)v);
dan4a4c11a2009-10-06 14:59:02 +00001674 }else{
1675 return Tcl_NewWideIntObj(v);
1676 }
1677 }
1678 case SQLITE_FLOAT: {
1679 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1680 }
1681 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +00001682 return Tcl_NewStringObj(p->pDb->zNull, -1);
dan4a4c11a2009-10-06 14:59:02 +00001683 }
1684 }
1685
drh325eff52012-10-03 12:56:18 +00001686 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
dan4a4c11a2009-10-06 14:59:02 +00001687}
1688
1689/*
1690** If using Tcl version 8.6 or greater, use the NR functions to avoid
1691** recursive evalution of scripts by the [db eval] and [db trans]
1692** commands. Even if the headers used while compiling the extension
1693** are 8.6 or newer, the code still tests the Tcl version at runtime.
1694** This allows stubs-enabled builds to be used with older Tcl libraries.
1695*/
1696#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001697# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001698static int DbUseNre(void){
1699 int major, minor;
1700 Tcl_GetVersion(&major, &minor, 0, 0);
1701 return( (major==8 && minor>=6) || major>8 );
1702}
1703#else
mistachkinb56660f2016-07-14 21:26:09 +00001704/*
dan4a4c11a2009-10-06 14:59:02 +00001705** Compiling using headers earlier than 8.6. In this case NR cannot be
1706** used, so DbUseNre() to always return zero. Add #defines for the other
1707** Tcl_NRxxx() functions to prevent them from causing compilation errors,
mistachkinb56660f2016-07-14 21:26:09 +00001708** even though the only invocations of them are within conditional blocks
dan4a4c11a2009-10-06 14:59:02 +00001709** of the form:
1710**
1711** if( DbUseNre() ) { ... }
1712*/
drha2c8a952009-10-13 18:38:34 +00001713# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001714# define DbUseNre() 0
drha47941f2013-12-20 18:57:44 +00001715# define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001716# define Tcl_NREvalObj(a,b,c) 0
drha47941f2013-12-20 18:57:44 +00001717# define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001718#endif
1719
1720/*
1721** This function is part of the implementation of the command:
1722**
1723** $db eval SQL ?ARRAYNAME? SCRIPT
1724*/
mistachkina121cc72016-07-28 18:06:52 +00001725static int SQLITE_TCLAPI DbEvalNextCmd(
dan4a4c11a2009-10-06 14:59:02 +00001726 ClientData data[], /* data[0] is the (DbEvalContext*) */
1727 Tcl_Interp *interp, /* Tcl interpreter */
1728 int result /* Result so far */
1729){
1730 int rc = result; /* Return code */
1731
1732 /* The first element of the data[] array is a pointer to a DbEvalContext
1733 ** structure allocated using Tcl_Alloc(). The second element of data[]
1734 ** is a pointer to a Tcl_Obj containing the script to run for each row
1735 ** returned by the queries encapsulated in data[0]. */
1736 DbEvalContext *p = (DbEvalContext *)data[0];
1737 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1738 Tcl_Obj *pArray = p->pArray;
1739
1740 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1741 int i;
1742 int nCol;
1743 Tcl_Obj **apColName;
1744 dbEvalRowInfo(p, &nCol, &apColName);
1745 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00001746 if( pArray==0 ){
drhaf38cdb2017-06-26 21:08:32 +00001747 Tcl_ObjSetVar2(interp, apColName[i], 0, dbEvalColumnValue(p,i), 0);
1748 }else if( (p->evalFlags & SQLITE_EVAL_WITHOUTNULLS)!=0
1749 && sqlite3_column_type(p->pPreStmt->pStmt, i)==SQLITE_NULL
1750 ){
1751 Tcl_UnsetVar2(interp, Tcl_GetString(pArray),
1752 Tcl_GetString(apColName[i]), 0);
dan4a4c11a2009-10-06 14:59:02 +00001753 }else{
drhaf38cdb2017-06-26 21:08:32 +00001754 Tcl_ObjSetVar2(interp, pArray, apColName[i], dbEvalColumnValue(p,i), 0);
dan4a4c11a2009-10-06 14:59:02 +00001755 }
1756 }
1757
mistachkinb56660f2016-07-14 21:26:09 +00001758 /* The required interpreter variables are now populated with the data
dan4a4c11a2009-10-06 14:59:02 +00001759 ** from the current row. If using NRE, schedule callbacks to evaluate
1760 ** script pScript, then to invoke this function again to fetch the next
1761 ** row (or clean up if there is no next row or the script throws an
mistachkinb56660f2016-07-14 21:26:09 +00001762 ** exception). After scheduling the callbacks, return control to the
dan4a4c11a2009-10-06 14:59:02 +00001763 ** caller.
1764 **
1765 ** If not using NRE, evaluate pScript directly and continue with the
1766 ** next iteration of this while(...) loop. */
1767 if( DbUseNre() ){
1768 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1769 return Tcl_NREvalObj(interp, pScript, 0);
1770 }else{
1771 rc = Tcl_EvalObjEx(interp, pScript, 0);
1772 }
1773 }
1774
1775 Tcl_DecrRefCount(pScript);
1776 dbEvalFinalize(p);
1777 Tcl_Free((char *)p);
1778
1779 if( rc==TCL_OK || rc==TCL_BREAK ){
1780 Tcl_ResetResult(interp);
1781 rc = TCL_OK;
1782 }
1783 return rc;
danielk19778e556522007-11-13 10:30:24 +00001784}
1785
tpoindex1067fe12004-12-17 15:41:11 +00001786/*
mistachkinb56660f2016-07-14 21:26:09 +00001787** This function is used by the implementations of the following database
dan46c47d42011-03-01 18:42:07 +00001788** handle sub-commands:
1789**
1790** $db update_hook ?SCRIPT?
1791** $db wal_hook ?SCRIPT?
1792** $db commit_hook ?SCRIPT?
1793** $db preupdate hook ?SCRIPT?
1794*/
1795static void DbHookCmd(
1796 Tcl_Interp *interp, /* Tcl interpreter */
1797 SqliteDb *pDb, /* Database handle */
1798 Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */
1799 Tcl_Obj **ppHook /* Pointer to member of SqliteDb */
1800){
1801 sqlite3 *db = pDb->db;
1802
1803 if( *ppHook ){
1804 Tcl_SetObjResult(interp, *ppHook);
1805 if( pArg ){
1806 Tcl_DecrRefCount(*ppHook);
1807 *ppHook = 0;
1808 }
1809 }
1810 if( pArg ){
1811 assert( !(*ppHook) );
1812 if( Tcl_GetCharLength(pArg)>0 ){
1813 *ppHook = pArg;
1814 Tcl_IncrRefCount(*ppHook);
1815 }
1816 }
1817
drh9b1c62d2011-03-30 21:04:43 +00001818#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +00001819 sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
drh9b1c62d2011-03-30 21:04:43 +00001820#endif
dan46c47d42011-03-01 18:42:07 +00001821 sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1822 sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1823 sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
1824}
1825
1826/*
drh75897232000-05-29 14:26:00 +00001827** The "sqlite" command below creates a new Tcl command for each
1828** connection it opens to an SQLite database. This routine is invoked
1829** whenever one of those connection-specific commands is executed
1830** in Tcl. For example, if you run Tcl code like this:
1831**
drh9bb575f2004-09-06 17:24:11 +00001832** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001833** db1 close
1834**
1835** The first command opens a connection to the "my_database" database
1836** and calls that connection "db1". The second command causes this
1837** subroutine to be invoked.
1838*/
mistachkin7617e4a2016-07-28 17:11:20 +00001839static int SQLITE_TCLAPI DbObjCmd(
1840 void *cd,
1841 Tcl_Interp *interp,
1842 int objc,
1843 Tcl_Obj *const*objv
1844){
drhbec3f402000-08-04 13:49:02 +00001845 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001846 int choice;
drh22fbcb82004-02-01 01:22:50 +00001847 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001848 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001849 "authorizer", "backup", "busy",
1850 "cache", "changes", "close",
1851 "collate", "collation_needed", "commit_hook",
1852 "complete", "copy", "enable_load_extension",
1853 "errorcode", "eval", "exists",
1854 "function", "incrblob", "interrupt",
drhac442f42018-01-03 01:28:46 +00001855 "last_insert_rowid", "memdb", "nullvalue",
1856 "onecolumn", "preupdate", "profile",
1857 "progress", "rekey", "restore",
1858 "rollback_hook", "status", "timeout",
drh4dcac402018-01-03 13:20:02 +00001859 "total_changes", "trace", "trace_v2",
drhac442f42018-01-03 01:28:46 +00001860 "transaction", "unlock_notify", "update_hook",
1861 "version", "wal_hook", 0
drh6d313162000-09-21 13:01:35 +00001862 };
drh411995d2002-06-25 19:31:18 +00001863 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001864 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1865 DB_CACHE, DB_CHANGES, DB_CLOSE,
1866 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1867 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1868 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1869 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
drhac442f42018-01-03 01:28:46 +00001870 DB_LAST_INSERT_ROWID, DB_MEMDB, DB_NULLVALUE,
1871 DB_ONECOLUMN, DB_PREUPDATE, DB_PROFILE,
1872 DB_PROGRESS, DB_REKEY, DB_RESTORE,
1873 DB_ROLLBACK_HOOK, DB_STATUS, DB_TIMEOUT,
1874 DB_TOTAL_CHANGES, DB_TRACE, DB_TRACE_V2,
1875 DB_TRANSACTION, DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK,
1876 DB_VERSION, DB_WAL_HOOK
drh6d313162000-09-21 13:01:35 +00001877 };
tpoindex1067fe12004-12-17 15:41:11 +00001878 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001879
1880 if( objc<2 ){
1881 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001882 return TCL_ERROR;
1883 }
drh411995d2002-06-25 19:31:18 +00001884 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001885 return TCL_ERROR;
1886 }
1887
drh411995d2002-06-25 19:31:18 +00001888 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001889
drhe22a3342003-04-22 20:30:37 +00001890 /* $db authorizer ?CALLBACK?
1891 **
1892 ** Invoke the given callback to authorize each SQL operation as it is
1893 ** compiled. 5 arguments are appended to the callback before it is
1894 ** invoked:
1895 **
1896 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1897 ** (2) First descriptive name (depends on authorization type)
1898 ** (3) Second descriptive name
1899 ** (4) Name of the database (ex: "main", "temp")
1900 ** (5) Name of trigger that is doing the access
1901 **
1902 ** The callback should return on of the following strings: SQLITE_OK,
1903 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1904 **
1905 ** If this method is invoked with no arguments, the current authorization
1906 ** callback string is returned.
1907 */
1908 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001909#ifdef SQLITE_OMIT_AUTHORIZATION
drha198f2b2014-02-07 19:26:13 +00001910 Tcl_AppendResult(interp, "authorization not available in this build",
1911 (char*)0);
drh1211de32004-07-26 12:24:22 +00001912 return TCL_ERROR;
1913#else
drhe22a3342003-04-22 20:30:37 +00001914 if( objc>3 ){
1915 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001916 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001917 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001918 if( pDb->zAuth ){
drha198f2b2014-02-07 19:26:13 +00001919 Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
drhe22a3342003-04-22 20:30:37 +00001920 }
1921 }else{
1922 char *zAuth;
1923 int len;
1924 if( pDb->zAuth ){
1925 Tcl_Free(pDb->zAuth);
1926 }
1927 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1928 if( zAuth && len>0 ){
1929 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001930 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001931 }else{
1932 pDb->zAuth = 0;
1933 }
drhe22a3342003-04-22 20:30:37 +00001934 if( pDb->zAuth ){
drh32c6a482014-09-11 13:44:52 +00001935 typedef int (*sqlite3_auth_cb)(
1936 void*,int,const char*,const char*,
1937 const char*,const char*);
drhe22a3342003-04-22 20:30:37 +00001938 pDb->interp = interp;
drh32c6a482014-09-11 13:44:52 +00001939 sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
drhe22a3342003-04-22 20:30:37 +00001940 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001941 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001942 }
drhe22a3342003-04-22 20:30:37 +00001943 }
drh1211de32004-07-26 12:24:22 +00001944#endif
drhe22a3342003-04-22 20:30:37 +00001945 break;
1946 }
1947
drhdc2c4912009-02-04 22:46:47 +00001948 /* $db backup ?DATABASE? FILENAME
1949 **
1950 ** Open or create a database file named FILENAME. Transfer the
1951 ** content of local database DATABASE (default: "main") into the
1952 ** FILENAME database.
1953 */
1954 case DB_BACKUP: {
1955 const char *zDestFile;
1956 const char *zSrcDb;
1957 sqlite3 *pDest;
1958 sqlite3_backup *pBackup;
1959
1960 if( objc==3 ){
1961 zSrcDb = "main";
1962 zDestFile = Tcl_GetString(objv[2]);
1963 }else if( objc==4 ){
1964 zSrcDb = Tcl_GetString(objv[2]);
1965 zDestFile = Tcl_GetString(objv[3]);
1966 }else{
1967 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1968 return TCL_ERROR;
1969 }
drh147ef392016-01-22 23:17:51 +00001970 rc = sqlite3_open_v2(zDestFile, &pDest,
1971 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00001972 if( rc!=SQLITE_OK ){
1973 Tcl_AppendResult(interp, "cannot open target database: ",
1974 sqlite3_errmsg(pDest), (char*)0);
1975 sqlite3_close(pDest);
1976 return TCL_ERROR;
1977 }
1978 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1979 if( pBackup==0 ){
1980 Tcl_AppendResult(interp, "backup failed: ",
1981 sqlite3_errmsg(pDest), (char*)0);
1982 sqlite3_close(pDest);
1983 return TCL_ERROR;
1984 }
1985 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1986 sqlite3_backup_finish(pBackup);
1987 if( rc==SQLITE_DONE ){
1988 rc = TCL_OK;
1989 }else{
1990 Tcl_AppendResult(interp, "backup failed: ",
1991 sqlite3_errmsg(pDest), (char*)0);
1992 rc = TCL_ERROR;
1993 }
1994 sqlite3_close(pDest);
1995 break;
1996 }
1997
drhbec3f402000-08-04 13:49:02 +00001998 /* $db busy ?CALLBACK?
1999 **
2000 ** Invoke the given callback if an SQL statement attempts to open
2001 ** a locked database file.
2002 */
drh6d313162000-09-21 13:01:35 +00002003 case DB_BUSY: {
2004 if( objc>3 ){
2005 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00002006 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00002007 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00002008 if( pDb->zBusy ){
drha198f2b2014-02-07 19:26:13 +00002009 Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
drhbec3f402000-08-04 13:49:02 +00002010 }
2011 }else{
drh6d313162000-09-21 13:01:35 +00002012 char *zBusy;
2013 int len;
drhbec3f402000-08-04 13:49:02 +00002014 if( pDb->zBusy ){
2015 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00002016 }
drh6d313162000-09-21 13:01:35 +00002017 zBusy = Tcl_GetStringFromObj(objv[2], &len);
2018 if( zBusy && len>0 ){
2019 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002020 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00002021 }else{
2022 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00002023 }
2024 if( pDb->zBusy ){
2025 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002026 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00002027 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002028 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00002029 }
2030 }
drh6d313162000-09-21 13:01:35 +00002031 break;
2032 }
drhbec3f402000-08-04 13:49:02 +00002033
drhfb7e7652005-01-24 00:28:42 +00002034 /* $db cache flush
2035 ** $db cache size n
2036 **
2037 ** Flush the prepared statement cache, or set the maximum number of
2038 ** cached statements.
2039 */
2040 case DB_CACHE: {
2041 char *subCmd;
2042 int n;
2043
2044 if( objc<=2 ){
2045 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
2046 return TCL_ERROR;
2047 }
2048 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
2049 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
2050 if( objc!=3 ){
2051 Tcl_WrongNumArgs(interp, 2, objv, "flush");
2052 return TCL_ERROR;
2053 }else{
2054 flushStmtCache( pDb );
2055 }
2056 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
2057 if( objc!=4 ){
2058 Tcl_WrongNumArgs(interp, 2, objv, "size n");
2059 return TCL_ERROR;
2060 }else{
2061 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
mistachkinb56660f2016-07-14 21:26:09 +00002062 Tcl_AppendResult( interp, "cannot convert \"",
drha198f2b2014-02-07 19:26:13 +00002063 Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
drhfb7e7652005-01-24 00:28:42 +00002064 return TCL_ERROR;
2065 }else{
2066 if( n<0 ){
2067 flushStmtCache( pDb );
2068 n = 0;
2069 }else if( n>MAX_PREPARED_STMTS ){
2070 n = MAX_PREPARED_STMTS;
2071 }
2072 pDb->maxStmt = n;
2073 }
2074 }
2075 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002076 Tcl_AppendResult( interp, "bad option \"",
drha198f2b2014-02-07 19:26:13 +00002077 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
2078 (char*)0);
drhfb7e7652005-01-24 00:28:42 +00002079 return TCL_ERROR;
2080 }
2081 break;
2082 }
2083
danielk1977b28af712004-06-21 06:50:26 +00002084 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00002085 **
2086 ** Return the number of rows that were modified, inserted, or deleted by
mistachkinb56660f2016-07-14 21:26:09 +00002087 ** the most recent INSERT, UPDATE or DELETE statement, not including
danielk1977b28af712004-06-21 06:50:26 +00002088 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00002089 */
2090 case DB_CHANGES: {
2091 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00002092 if( objc!=2 ){
2093 Tcl_WrongNumArgs(interp, 2, objv, "");
2094 return TCL_ERROR;
2095 }
drhc8d30ac2002-04-12 10:08:59 +00002096 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00002097 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00002098 break;
2099 }
2100
drh75897232000-05-29 14:26:00 +00002101 /* $db close
2102 **
2103 ** Shutdown the database
2104 */
drh6d313162000-09-21 13:01:35 +00002105 case DB_CLOSE: {
2106 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
2107 break;
2108 }
drh75897232000-05-29 14:26:00 +00002109
drh0f14e2e2004-06-29 12:39:08 +00002110 /*
2111 ** $db collate NAME SCRIPT
2112 **
2113 ** Create a new SQL collation function called NAME. Whenever
2114 ** that function is called, invoke SCRIPT to evaluate the function.
2115 */
2116 case DB_COLLATE: {
2117 SqlCollate *pCollate;
2118 char *zName;
2119 char *zScript;
2120 int nScript;
2121 if( objc!=4 ){
2122 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
2123 return TCL_ERROR;
2124 }
2125 zName = Tcl_GetStringFromObj(objv[2], 0);
2126 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
2127 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
2128 if( pCollate==0 ) return TCL_ERROR;
2129 pCollate->interp = interp;
2130 pCollate->pNext = pDb->pCollate;
2131 pCollate->zScript = (char*)&pCollate[1];
2132 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00002133 memcpy(pCollate->zScript, zScript, nScript+1);
mistachkinb56660f2016-07-14 21:26:09 +00002134 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
drh0f14e2e2004-06-29 12:39:08 +00002135 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00002136 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00002137 return TCL_ERROR;
2138 }
2139 break;
2140 }
2141
2142 /*
2143 ** $db collation_needed SCRIPT
2144 **
2145 ** Create a new SQL collation function called NAME. Whenever
2146 ** that function is called, invoke SCRIPT to evaluate the function.
2147 */
2148 case DB_COLLATION_NEEDED: {
2149 if( objc!=3 ){
2150 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
2151 return TCL_ERROR;
2152 }
2153 if( pDb->pCollateNeeded ){
2154 Tcl_DecrRefCount(pDb->pCollateNeeded);
2155 }
2156 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
2157 Tcl_IncrRefCount(pDb->pCollateNeeded);
2158 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
2159 break;
2160 }
2161
drh19e2d372005-08-29 23:00:03 +00002162 /* $db commit_hook ?CALLBACK?
2163 **
2164 ** Invoke the given callback just before committing every SQL transaction.
2165 ** If the callback throws an exception or returns non-zero, then the
2166 ** transaction is aborted. If CALLBACK is an empty string, the callback
2167 ** is disabled.
2168 */
2169 case DB_COMMIT_HOOK: {
2170 if( objc>3 ){
2171 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2172 return TCL_ERROR;
2173 }else if( objc==2 ){
2174 if( pDb->zCommit ){
drha198f2b2014-02-07 19:26:13 +00002175 Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002176 }
2177 }else{
mistachkin6ef5e122014-01-24 17:03:55 +00002178 const char *zCommit;
drh19e2d372005-08-29 23:00:03 +00002179 int len;
2180 if( pDb->zCommit ){
2181 Tcl_Free(pDb->zCommit);
2182 }
2183 zCommit = Tcl_GetStringFromObj(objv[2], &len);
2184 if( zCommit && len>0 ){
2185 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002186 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00002187 }else{
2188 pDb->zCommit = 0;
2189 }
2190 if( pDb->zCommit ){
2191 pDb->interp = interp;
2192 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
2193 }else{
2194 sqlite3_commit_hook(pDb->db, 0, 0);
2195 }
2196 }
2197 break;
2198 }
2199
drh75897232000-05-29 14:26:00 +00002200 /* $db complete SQL
2201 **
2202 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2203 ** additional lines of input are needed. This is similar to the
2204 ** built-in "info complete" command of Tcl.
2205 */
drh6d313162000-09-21 13:01:35 +00002206 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00002207#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00002208 Tcl_Obj *pResult;
2209 int isComplete;
2210 if( objc!=3 ){
2211 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00002212 return TCL_ERROR;
2213 }
danielk19776f8a5032004-05-10 10:34:51 +00002214 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00002215 pResult = Tcl_GetObjResult(interp);
2216 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00002217#endif
drh6d313162000-09-21 13:01:35 +00002218 break;
2219 }
drhdcd997e2003-01-31 17:21:49 +00002220
drh19e2d372005-08-29 23:00:03 +00002221 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2222 **
2223 ** Copy data into table from filename, optionally using SEPARATOR
2224 ** as column separators. If a column contains a null string, or the
2225 ** value of NULLINDICATOR, a NULL is inserted for the column.
2226 ** conflict-algorithm is one of the sqlite conflict algorithms:
2227 ** rollback, abort, fail, ignore, replace
2228 ** On success, return the number of lines processed, not necessarily same
2229 ** as 'db changes' due to conflict-algorithm selected.
2230 **
2231 ** This code is basically an implementation/enhancement of
2232 ** the sqlite3 shell.c ".import" command.
2233 **
2234 ** This command usage is equivalent to the sqlite2.x COPY statement,
2235 ** which imports file data into a table using the PostgreSQL COPY file format:
2236 ** $db copy $conflit_algo $table_name $filename \t \\N
2237 */
2238 case DB_COPY: {
2239 char *zTable; /* Insert data into this table */
2240 char *zFile; /* The file from which to extract data */
2241 char *zConflict; /* The conflict algorithm to use */
2242 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00002243 int nCol; /* Number of columns in the table */
2244 int nByte; /* Number of bytes in an SQL string */
2245 int i, j; /* Loop counters */
2246 int nSep; /* Number of bytes in zSep[] */
2247 int nNull; /* Number of bytes in zNull[] */
2248 char *zSql; /* An SQL statement */
2249 char *zLine; /* A single line of input from the file */
2250 char **azCol; /* zLine[] broken up into columns */
mistachkin6ef5e122014-01-24 17:03:55 +00002251 const char *zCommit; /* How to commit changes */
drh19e2d372005-08-29 23:00:03 +00002252 FILE *in; /* The input file */
2253 int lineno = 0; /* Line number of input file */
2254 char zLineNum[80]; /* Line number print buffer */
2255 Tcl_Obj *pResult; /* interp result */
2256
mistachkin6ef5e122014-01-24 17:03:55 +00002257 const char *zSep;
2258 const char *zNull;
drh19e2d372005-08-29 23:00:03 +00002259 if( objc<5 || objc>7 ){
mistachkinb56660f2016-07-14 21:26:09 +00002260 Tcl_WrongNumArgs(interp, 2, objv,
drh19e2d372005-08-29 23:00:03 +00002261 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2262 return TCL_ERROR;
2263 }
2264 if( objc>=6 ){
2265 zSep = Tcl_GetStringFromObj(objv[5], 0);
2266 }else{
2267 zSep = "\t";
2268 }
2269 if( objc>=7 ){
2270 zNull = Tcl_GetStringFromObj(objv[6], 0);
2271 }else{
2272 zNull = "";
2273 }
2274 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2275 zTable = Tcl_GetStringFromObj(objv[3], 0);
2276 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002277 nSep = strlen30(zSep);
2278 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002279 if( nSep==0 ){
drha198f2b2014-02-07 19:26:13 +00002280 Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2281 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002282 return TCL_ERROR;
2283 }
drh3e59c012008-09-23 10:12:13 +00002284 if(strcmp(zConflict, "rollback") != 0 &&
2285 strcmp(zConflict, "abort" ) != 0 &&
2286 strcmp(zConflict, "fail" ) != 0 &&
2287 strcmp(zConflict, "ignore" ) != 0 &&
2288 strcmp(zConflict, "replace" ) != 0 ) {
mistachkinb56660f2016-07-14 21:26:09 +00002289 Tcl_AppendResult(interp, "Error: \"", zConflict,
drh19e2d372005-08-29 23:00:03 +00002290 "\", conflict-algorithm must be one of: rollback, "
drha198f2b2014-02-07 19:26:13 +00002291 "abort, fail, ignore, or replace", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002292 return TCL_ERROR;
2293 }
2294 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2295 if( zSql==0 ){
drha198f2b2014-02-07 19:26:13 +00002296 Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002297 return TCL_ERROR;
2298 }
drh4f21c4a2008-12-10 22:15:00 +00002299 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002300 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002301 sqlite3_free(zSql);
2302 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002303 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002304 nCol = 0;
2305 }else{
2306 nCol = sqlite3_column_count(pStmt);
2307 }
2308 sqlite3_finalize(pStmt);
2309 if( nCol==0 ) {
2310 return TCL_ERROR;
2311 }
2312 zSql = malloc( nByte + 50 + nCol*2 );
2313 if( zSql==0 ) {
drha198f2b2014-02-07 19:26:13 +00002314 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002315 return TCL_ERROR;
2316 }
2317 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2318 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002319 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002320 for(i=1; i<nCol; i++){
2321 zSql[j++] = ',';
2322 zSql[j++] = '?';
2323 }
2324 zSql[j++] = ')';
2325 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002326 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002327 free(zSql);
2328 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002329 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002330 sqlite3_finalize(pStmt);
2331 return TCL_ERROR;
2332 }
2333 in = fopen(zFile, "rb");
2334 if( in==0 ){
drhea8f0a12017-01-12 11:50:08 +00002335 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002336 sqlite3_finalize(pStmt);
2337 return TCL_ERROR;
2338 }
2339 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2340 if( azCol==0 ) {
drha198f2b2014-02-07 19:26:13 +00002341 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh43617e92006-03-06 20:55:46 +00002342 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002343 return TCL_ERROR;
2344 }
drh37527852006-03-16 16:19:56 +00002345 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002346 zCommit = "COMMIT";
2347 while( (zLine = local_getline(0, in))!=0 ){
2348 char *z;
drh19e2d372005-08-29 23:00:03 +00002349 lineno++;
2350 azCol[0] = zLine;
2351 for(i=0, z=zLine; *z; z++){
2352 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2353 *z = 0;
2354 i++;
2355 if( i<nCol ){
2356 azCol[i] = &z[nSep];
2357 z += nSep-1;
2358 }
2359 }
2360 }
2361 if( i+1!=nCol ){
2362 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002363 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002364 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002365 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002366 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002367 "Error: %s line %d: expected %d columns of data but found %d",
2368 zFile, lineno, nCol, i+1);
drha198f2b2014-02-07 19:26:13 +00002369 Tcl_AppendResult(interp, zErr, (char*)0);
drhc1f44942006-05-10 14:39:13 +00002370 free(zErr);
2371 }
drh19e2d372005-08-29 23:00:03 +00002372 zCommit = "ROLLBACK";
2373 break;
2374 }
2375 for(i=0; i<nCol; i++){
2376 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002377 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
mistachkinb56660f2016-07-14 21:26:09 +00002378 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002379 ){
drh19e2d372005-08-29 23:00:03 +00002380 sqlite3_bind_null(pStmt, i+1);
2381 }else{
2382 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2383 }
2384 }
2385 sqlite3_step(pStmt);
2386 rc = sqlite3_reset(pStmt);
2387 free(zLine);
2388 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00002389 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002390 zCommit = "ROLLBACK";
2391 break;
2392 }
2393 }
2394 free(azCol);
2395 fclose(in);
2396 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002397 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002398
2399 if( zCommit[0] == 'C' ){
2400 /* success, set result as number of lines processed */
2401 pResult = Tcl_GetObjResult(interp);
2402 Tcl_SetIntObj(pResult, lineno);
2403 rc = TCL_OK;
2404 }else{
2405 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002406 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drha198f2b2014-02-07 19:26:13 +00002407 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2408 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002409 rc = TCL_ERROR;
2410 }
2411 break;
2412 }
2413
drhdcd997e2003-01-31 17:21:49 +00002414 /*
drh41449052006-07-06 17:08:48 +00002415 ** $db enable_load_extension BOOLEAN
2416 **
2417 ** Turn the extension loading feature on or off. It if off by
2418 ** default.
2419 */
2420 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002421#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002422 int onoff;
2423 if( objc!=3 ){
2424 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2425 return TCL_ERROR;
2426 }
2427 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2428 return TCL_ERROR;
2429 }
2430 sqlite3_enable_load_extension(pDb->db, onoff);
2431 break;
drhf533acc2006-12-19 18:57:11 +00002432#else
2433 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
drha198f2b2014-02-07 19:26:13 +00002434 (char*)0);
drhf533acc2006-12-19 18:57:11 +00002435 return TCL_ERROR;
2436#endif
drh41449052006-07-06 17:08:48 +00002437 }
2438
2439 /*
drhdcd997e2003-01-31 17:21:49 +00002440 ** $db errorcode
2441 **
2442 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002443 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002444 */
2445 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002446 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002447 break;
2448 }
dan4a4c11a2009-10-06 14:59:02 +00002449
2450 /*
2451 ** $db exists $sql
2452 ** $db onecolumn $sql
2453 **
2454 ** The onecolumn method is the equivalent of:
2455 ** lindex [$db eval $sql] 0
2456 */
mistachkinb56660f2016-07-14 21:26:09 +00002457 case DB_EXISTS:
dan4a4c11a2009-10-06 14:59:02 +00002458 case DB_ONECOLUMN: {
drhedc40242016-06-13 12:34:38 +00002459 Tcl_Obj *pResult = 0;
dan4a4c11a2009-10-06 14:59:02 +00002460 DbEvalContext sEval;
2461 if( objc!=3 ){
2462 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2463 return TCL_ERROR;
2464 }
2465
drhaf38cdb2017-06-26 21:08:32 +00002466 dbEvalInit(&sEval, pDb, objv[2], 0, 0);
dan4a4c11a2009-10-06 14:59:02 +00002467 rc = dbEvalStep(&sEval);
2468 if( choice==DB_ONECOLUMN ){
2469 if( rc==TCL_OK ){
drhedc40242016-06-13 12:34:38 +00002470 pResult = dbEvalColumnValue(&sEval, 0);
dand5f12cd2011-08-18 17:47:57 +00002471 }else if( rc==TCL_BREAK ){
2472 Tcl_ResetResult(interp);
dan4a4c11a2009-10-06 14:59:02 +00002473 }
2474 }else if( rc==TCL_BREAK || rc==TCL_OK ){
drhedc40242016-06-13 12:34:38 +00002475 pResult = Tcl_NewBooleanObj(rc==TCL_OK);
dan4a4c11a2009-10-06 14:59:02 +00002476 }
2477 dbEvalFinalize(&sEval);
drhedc40242016-06-13 12:34:38 +00002478 if( pResult ) Tcl_SetObjResult(interp, pResult);
dan4a4c11a2009-10-06 14:59:02 +00002479
2480 if( rc==TCL_BREAK ){
2481 rc = TCL_OK;
2482 }
2483 break;
2484 }
mistachkinb56660f2016-07-14 21:26:09 +00002485
drh75897232000-05-29 14:26:00 +00002486 /*
drhaf38cdb2017-06-26 21:08:32 +00002487 ** $db eval ?options? $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002488 **
2489 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002490 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002491 ** If "array" and "code" are omitted, then no callback is every invoked.
2492 ** If "array" is an empty string, then the values are placed in variables
2493 ** that have the same name as the fields extracted by the query.
2494 */
dan4a4c11a2009-10-06 14:59:02 +00002495 case DB_EVAL: {
drhaf38cdb2017-06-26 21:08:32 +00002496 int evalFlags = 0;
2497 const char *zOpt;
2498 while( objc>3 && (zOpt = Tcl_GetString(objv[2]))!=0 && zOpt[0]=='-' ){
2499 if( strcmp(zOpt, "-withoutnulls")==0 ){
2500 evalFlags |= SQLITE_EVAL_WITHOUTNULLS;
2501 }
2502 else{
2503 Tcl_AppendResult(interp, "unknown option: \"", zOpt, "\"", (void*)0);
2504 return TCL_ERROR;
2505 }
2506 objc--;
2507 objv++;
2508 }
dan4a4c11a2009-10-06 14:59:02 +00002509 if( objc<3 || objc>5 ){
drhaf38cdb2017-06-26 21:08:32 +00002510 Tcl_WrongNumArgs(interp, 2, objv,
2511 "?OPTIONS? SQL ?ARRAY-NAME? ?SCRIPT?");
dan4a4c11a2009-10-06 14:59:02 +00002512 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002513 }
dan4a4c11a2009-10-06 14:59:02 +00002514
drh92febd92004-08-20 18:34:20 +00002515 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002516 DbEvalContext sEval;
2517 Tcl_Obj *pRet = Tcl_NewObj();
2518 Tcl_IncrRefCount(pRet);
drhaf38cdb2017-06-26 21:08:32 +00002519 dbEvalInit(&sEval, pDb, objv[2], 0, 0);
dan4a4c11a2009-10-06 14:59:02 +00002520 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2521 int i;
2522 int nCol;
2523 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002524 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002525 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002526 }
2527 }
dan4a4c11a2009-10-06 14:59:02 +00002528 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002529 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002530 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002531 rc = TCL_OK;
2532 }
drh1807ce32004-09-07 13:20:35 +00002533 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002534 }else{
mistachkin8e189222015-04-19 21:43:16 +00002535 ClientData cd2[2];
dan4a4c11a2009-10-06 14:59:02 +00002536 DbEvalContext *p;
2537 Tcl_Obj *pArray = 0;
2538 Tcl_Obj *pScript;
2539
drhaf38cdb2017-06-26 21:08:32 +00002540 if( objc>=5 && *(char *)Tcl_GetString(objv[3]) ){
dan4a4c11a2009-10-06 14:59:02 +00002541 pArray = objv[3];
2542 }
2543 pScript = objv[objc-1];
2544 Tcl_IncrRefCount(pScript);
mistachkinb56660f2016-07-14 21:26:09 +00002545
dan4a4c11a2009-10-06 14:59:02 +00002546 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
drhaf38cdb2017-06-26 21:08:32 +00002547 dbEvalInit(p, pDb, objv[2], pArray, evalFlags);
dan4a4c11a2009-10-06 14:59:02 +00002548
mistachkin8e189222015-04-19 21:43:16 +00002549 cd2[0] = (void *)p;
2550 cd2[1] = (void *)pScript;
2551 rc = DbEvalNextCmd(cd2, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002552 }
danielk197730ccda12004-05-27 12:11:31 +00002553 break;
2554 }
drhbec3f402000-08-04 13:49:02 +00002555
2556 /*
dan3df30592015-03-13 08:31:54 +00002557 ** $db function NAME [-argcount N] [-deterministic] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002558 **
2559 ** Create a new SQL function called NAME. Whenever that function is
2560 ** called, invoke SCRIPT to evaluate the function.
2561 */
2562 case DB_FUNCTION: {
dan3df30592015-03-13 08:31:54 +00002563 int flags = SQLITE_UTF8;
drhcabb0812002-09-14 13:47:32 +00002564 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002565 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002566 char *zName;
drhe3602be2008-09-09 12:31:33 +00002567 int nArg = -1;
dan3df30592015-03-13 08:31:54 +00002568 int i;
2569 if( objc<4 ){
2570 Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
2571 return TCL_ERROR;
2572 }
2573 for(i=3; i<(objc-1); i++){
2574 const char *z = Tcl_GetString(objv[i]);
drh4f21c4a2008-12-10 22:15:00 +00002575 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002576 if( n>2 && strncmp(z, "-argcount",n)==0 ){
dan3df30592015-03-13 08:31:54 +00002577 if( i==(objc-2) ){
drhea8f0a12017-01-12 11:50:08 +00002578 Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0);
dan3df30592015-03-13 08:31:54 +00002579 return TCL_ERROR;
2580 }
2581 if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002582 if( nArg<0 ){
2583 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2584 (char*)0);
2585 return TCL_ERROR;
2586 }
dan3df30592015-03-13 08:31:54 +00002587 i++;
2588 }else
2589 if( n>2 && strncmp(z, "-deterministic",n)==0 ){
2590 flags |= SQLITE_DETERMINISTIC;
2591 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002592 Tcl_AppendResult(interp, "bad option \"", z,
drhea8f0a12017-01-12 11:50:08 +00002593 "\": must be -argcount or -deterministic", (char*)0
dan3df30592015-03-13 08:31:54 +00002594 );
2595 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002596 }
drhcabb0812002-09-14 13:47:32 +00002597 }
dan3df30592015-03-13 08:31:54 +00002598
2599 pScript = objv[objc-1];
drhcabb0812002-09-14 13:47:32 +00002600 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002601 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002602 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002603 if( pFunc->pScript ){
2604 Tcl_DecrRefCount(pFunc->pScript);
2605 }
2606 pFunc->pScript = pScript;
2607 Tcl_IncrRefCount(pScript);
2608 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
dan3df30592015-03-13 08:31:54 +00002609 rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
danielk1977d8123362004-06-12 09:25:12 +00002610 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002611 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002612 rc = TCL_ERROR;
2613 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002614 }
drhcabb0812002-09-14 13:47:32 +00002615 break;
2616 }
2617
2618 /*
danielk19778cbadb02007-05-03 16:31:26 +00002619 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002620 */
2621 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002622#ifdef SQLITE_OMIT_INCRBLOB
drha198f2b2014-02-07 19:26:13 +00002623 Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
danielk197732a0d8b2007-05-04 19:03:02 +00002624 return TCL_ERROR;
2625#else
danielk19778cbadb02007-05-03 16:31:26 +00002626 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002627 const char *zDb = "main";
2628 const char *zTable;
2629 const char *zColumn;
drhb3f787f2012-09-29 14:45:54 +00002630 Tcl_WideInt iRow;
danielk1977b4e9af92007-05-01 17:49:49 +00002631
danielk19778cbadb02007-05-03 16:31:26 +00002632 /* Check for the -readonly option */
2633 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2634 isReadonly = 1;
2635 }
2636
2637 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2638 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002639 return TCL_ERROR;
2640 }
2641
danielk19778cbadb02007-05-03 16:31:26 +00002642 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002643 zDb = Tcl_GetString(objv[2]);
2644 }
2645 zTable = Tcl_GetString(objv[objc-3]);
2646 zColumn = Tcl_GetString(objv[objc-2]);
2647 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2648
2649 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002650 rc = createIncrblobChannel(
danedf5b162014-08-19 09:15:41 +00002651 interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
danielk19778cbadb02007-05-03 16:31:26 +00002652 );
danielk1977b4e9af92007-05-01 17:49:49 +00002653 }
danielk197732a0d8b2007-05-04 19:03:02 +00002654#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002655 break;
2656 }
2657
2658 /*
drhf11bded2006-07-17 00:02:44 +00002659 ** $db interrupt
2660 **
2661 ** Interrupt the execution of the inner-most SQL interpreter. This
2662 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2663 */
2664 case DB_INTERRUPT: {
2665 sqlite3_interrupt(pDb->db);
2666 break;
2667 }
2668
2669 /*
drhac442f42018-01-03 01:28:46 +00002670 ** $db memdb DATABASE ?BLOB?
2671 **
2672 ** Set or query the content of a MEMDB database.
2673 **
2674 */
2675 case DB_MEMDB: {
2676#ifndef SQLITE_ENABLE_MEMDB
2677 Tcl_AppendResult(interp, "MEMDB not available in this build",
2678 (char*)0);
2679 rc = TCL_ERROR;
2680#else
2681 const char *zSchema = Tcl_GetString(objv[2]);
2682 sqlite3_int64 sz = 0;
2683 unsigned char *pData;
2684 if( objc==3 ){
2685 pData = sqlite3_memdb_ptr(pDb->db, zSchema, &sz);
2686 if( pData==0 ){
2687 Tcl_AppendResult(interp, "not a MEMDB database", (char*)0);
2688 rc = TCL_ERROR;
2689 }else{
2690 Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(pData,sz));
2691 }
2692 }else if( objc==4 ){
2693 int len = 0, xrc;
2694 unsigned char *pBA = Tcl_GetByteArrayFromObj(objv[3], &len);
2695 pData = sqlite3_malloc64( len );
2696 if( pData==0 ){
2697 Tcl_AppendResult(interp, "out of memory", (char*)0);
2698 rc = TCL_ERROR;
2699 }else{
2700 memcpy(pData, pBA, len);
2701 xrc = sqlite3_memdb_config(pDb->db, zSchema, pData, len, len,
2702 SQLITE_MEMDB_FREEONCLOSE|SQLITE_MEMDB_RESIZEABLE);
2703 if( xrc ){
drhac442f42018-01-03 01:28:46 +00002704 Tcl_AppendResult(interp, "unable to set MEMDB content", (char*)0);
2705 rc = TCL_ERROR;
2706 }
2707 }
2708 }else{
2709 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2710 rc = TCL_ERROR;
2711 }
2712#endif
2713 break;
2714 }
2715
2716 /*
drh19e2d372005-08-29 23:00:03 +00002717 ** $db nullvalue ?STRING?
2718 **
2719 ** Change text used when a NULL comes back from the database. If ?STRING?
2720 ** is not present, then the current string used for NULL is returned.
2721 ** If STRING is present, then STRING is returned.
2722 **
2723 */
2724 case DB_NULLVALUE: {
2725 if( objc!=2 && objc!=3 ){
2726 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2727 return TCL_ERROR;
2728 }
2729 if( objc==3 ){
2730 int len;
2731 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2732 if( pDb->zNull ){
2733 Tcl_Free(pDb->zNull);
2734 }
2735 if( zNull && len>0 ){
2736 pDb->zNull = Tcl_Alloc( len + 1 );
drh7fd33922011-06-20 19:00:30 +00002737 memcpy(pDb->zNull, zNull, len);
drh19e2d372005-08-29 23:00:03 +00002738 pDb->zNull[len] = '\0';
2739 }else{
2740 pDb->zNull = 0;
2741 }
2742 }
drhc45e6712012-10-03 11:02:33 +00002743 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
drh19e2d372005-08-29 23:00:03 +00002744 break;
2745 }
2746
2747 /*
mistachkinb56660f2016-07-14 21:26:09 +00002748 ** $db last_insert_rowid
drhaf9ff332002-01-16 21:00:27 +00002749 **
2750 ** Return an integer which is the ROWID for the most recent insert.
2751 */
2752 case DB_LAST_INSERT_ROWID: {
2753 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002754 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002755 if( objc!=2 ){
2756 Tcl_WrongNumArgs(interp, 2, objv, "");
2757 return TCL_ERROR;
2758 }
danielk19776f8a5032004-05-10 10:34:51 +00002759 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002760 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002761 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002762 break;
2763 }
2764
2765 /*
dan4a4c11a2009-10-06 14:59:02 +00002766 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002767 */
drh1807ce32004-09-07 13:20:35 +00002768
2769 /* $db progress ?N CALLBACK?
mistachkinb56660f2016-07-14 21:26:09 +00002770 **
drh1807ce32004-09-07 13:20:35 +00002771 ** Invoke the given callback every N virtual machine opcodes while executing
2772 ** queries.
2773 */
2774 case DB_PROGRESS: {
2775 if( objc==2 ){
2776 if( pDb->zProgress ){
drha198f2b2014-02-07 19:26:13 +00002777 Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
drh1807ce32004-09-07 13:20:35 +00002778 }
2779 }else if( objc==4 ){
2780 char *zProgress;
2781 int len;
2782 int N;
2783 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002784 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002785 };
2786 if( pDb->zProgress ){
2787 Tcl_Free(pDb->zProgress);
2788 }
2789 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2790 if( zProgress && len>0 ){
2791 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002792 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002793 }else{
2794 pDb->zProgress = 0;
2795 }
2796#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2797 if( pDb->zProgress ){
2798 pDb->interp = interp;
2799 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2800 }else{
2801 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2802 }
2803#endif
2804 }else{
2805 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002806 return TCL_ERROR;
2807 }
drh5d9d7572003-08-19 14:31:01 +00002808 break;
2809 }
2810
drh19e2d372005-08-29 23:00:03 +00002811 /* $db profile ?CALLBACK?
2812 **
2813 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2814 ** that has run. The text of the SQL and the amount of elapse time are
2815 ** appended to CALLBACK before the script is run.
2816 */
2817 case DB_PROFILE: {
2818 if( objc>3 ){
2819 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2820 return TCL_ERROR;
2821 }else if( objc==2 ){
2822 if( pDb->zProfile ){
drha198f2b2014-02-07 19:26:13 +00002823 Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002824 }
2825 }else{
2826 char *zProfile;
2827 int len;
2828 if( pDb->zProfile ){
2829 Tcl_Free(pDb->zProfile);
2830 }
2831 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2832 if( zProfile && len>0 ){
2833 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002834 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002835 }else{
2836 pDb->zProfile = 0;
2837 }
drh2eb22af2016-09-10 19:51:40 +00002838#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
2839 !defined(SQLITE_OMIT_DEPRECATED)
drh19e2d372005-08-29 23:00:03 +00002840 if( pDb->zProfile ){
2841 pDb->interp = interp;
2842 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2843 }else{
2844 sqlite3_profile(pDb->db, 0, 0);
2845 }
2846#endif
2847 }
2848 break;
2849 }
2850
drh5d9d7572003-08-19 14:31:01 +00002851 /*
drh22fbcb82004-02-01 01:22:50 +00002852 ** $db rekey KEY
2853 **
2854 ** Change the encryption key on the currently open database.
2855 */
2856 case DB_REKEY: {
drh32f57d42016-03-16 01:03:10 +00002857#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh22fbcb82004-02-01 01:22:50 +00002858 int nKey;
2859 void *pKey;
drhb07028f2011-10-14 21:49:18 +00002860#endif
drh22fbcb82004-02-01 01:22:50 +00002861 if( objc!=3 ){
2862 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2863 return TCL_ERROR;
2864 }
drh32f57d42016-03-16 01:03:10 +00002865#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00002866 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh2011d5f2004-07-22 02:40:37 +00002867 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002868 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002869 Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
drh22fbcb82004-02-01 01:22:50 +00002870 rc = TCL_ERROR;
2871 }
2872#endif
2873 break;
2874 }
2875
drhdc2c4912009-02-04 22:46:47 +00002876 /* $db restore ?DATABASE? FILENAME
2877 **
mistachkinb56660f2016-07-14 21:26:09 +00002878 ** Open a database file named FILENAME. Transfer the content
drhdc2c4912009-02-04 22:46:47 +00002879 ** of FILENAME into the local database DATABASE (default: "main").
2880 */
2881 case DB_RESTORE: {
2882 const char *zSrcFile;
2883 const char *zDestDb;
2884 sqlite3 *pSrc;
2885 sqlite3_backup *pBackup;
2886 int nTimeout = 0;
2887
2888 if( objc==3 ){
2889 zDestDb = "main";
2890 zSrcFile = Tcl_GetString(objv[2]);
2891 }else if( objc==4 ){
2892 zDestDb = Tcl_GetString(objv[2]);
2893 zSrcFile = Tcl_GetString(objv[3]);
2894 }else{
2895 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2896 return TCL_ERROR;
2897 }
drh147ef392016-01-22 23:17:51 +00002898 rc = sqlite3_open_v2(zSrcFile, &pSrc,
2899 SQLITE_OPEN_READONLY | pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00002900 if( rc!=SQLITE_OK ){
2901 Tcl_AppendResult(interp, "cannot open source database: ",
2902 sqlite3_errmsg(pSrc), (char*)0);
2903 sqlite3_close(pSrc);
2904 return TCL_ERROR;
2905 }
2906 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2907 if( pBackup==0 ){
2908 Tcl_AppendResult(interp, "restore failed: ",
2909 sqlite3_errmsg(pDb->db), (char*)0);
2910 sqlite3_close(pSrc);
2911 return TCL_ERROR;
2912 }
2913 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2914 || rc==SQLITE_BUSY ){
2915 if( rc==SQLITE_BUSY ){
2916 if( nTimeout++ >= 3 ) break;
2917 sqlite3_sleep(100);
2918 }
2919 }
2920 sqlite3_backup_finish(pBackup);
2921 if( rc==SQLITE_DONE ){
2922 rc = TCL_OK;
2923 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2924 Tcl_AppendResult(interp, "restore failed: source database busy",
2925 (char*)0);
2926 rc = TCL_ERROR;
2927 }else{
2928 Tcl_AppendResult(interp, "restore failed: ",
2929 sqlite3_errmsg(pDb->db), (char*)0);
2930 rc = TCL_ERROR;
2931 }
2932 sqlite3_close(pSrc);
2933 break;
2934 }
2935
drh22fbcb82004-02-01 01:22:50 +00002936 /*
danc456a762017-06-22 16:51:16 +00002937 ** $db status (step|sort|autoindex|vmstep)
drhd1d38482008-10-07 23:46:38 +00002938 **
mistachkinb56660f2016-07-14 21:26:09 +00002939 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
drhd1d38482008-10-07 23:46:38 +00002940 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2941 */
2942 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002943 int v;
2944 const char *zOp;
2945 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00002946 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00002947 return TCL_ERROR;
2948 }
2949 zOp = Tcl_GetString(objv[2]);
2950 if( strcmp(zOp, "step")==0 ){
2951 v = pDb->nStep;
2952 }else if( strcmp(zOp, "sort")==0 ){
2953 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002954 }else if( strcmp(zOp, "autoindex")==0 ){
2955 v = pDb->nIndex;
danc456a762017-06-22 16:51:16 +00002956 }else if( strcmp(zOp, "vmstep")==0 ){
2957 v = pDb->nVMStep;
drhd1d38482008-10-07 23:46:38 +00002958 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002959 Tcl_AppendResult(interp,
danc456a762017-06-22 16:51:16 +00002960 "bad argument: should be autoindex, step, sort or vmstep",
drhd1d38482008-10-07 23:46:38 +00002961 (char*)0);
2962 return TCL_ERROR;
2963 }
2964 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2965 break;
2966 }
mistachkinb56660f2016-07-14 21:26:09 +00002967
drhd1d38482008-10-07 23:46:38 +00002968 /*
drhbec3f402000-08-04 13:49:02 +00002969 ** $db timeout MILLESECONDS
2970 **
2971 ** Delay for the number of milliseconds specified when a file is locked.
2972 */
drh6d313162000-09-21 13:01:35 +00002973 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002974 int ms;
drh6d313162000-09-21 13:01:35 +00002975 if( objc!=3 ){
2976 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002977 return TCL_ERROR;
2978 }
drh6d313162000-09-21 13:01:35 +00002979 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002980 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002981 break;
drh75897232000-05-29 14:26:00 +00002982 }
mistachkinb56660f2016-07-14 21:26:09 +00002983
danielk197755c45f22005-04-03 23:54:43 +00002984 /*
drh0f14e2e2004-06-29 12:39:08 +00002985 ** $db total_changes
2986 **
mistachkinb56660f2016-07-14 21:26:09 +00002987 ** Return the number of rows that were modified, inserted, or deleted
drh0f14e2e2004-06-29 12:39:08 +00002988 ** since the database handle was created.
2989 */
2990 case DB_TOTAL_CHANGES: {
2991 Tcl_Obj *pResult;
2992 if( objc!=2 ){
2993 Tcl_WrongNumArgs(interp, 2, objv, "");
2994 return TCL_ERROR;
2995 }
2996 pResult = Tcl_GetObjResult(interp);
2997 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2998 break;
2999 }
3000
drhb5a20d32003-04-23 12:25:23 +00003001 /* $db trace ?CALLBACK?
3002 **
3003 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
3004 ** that is executed. The text of the SQL is appended to CALLBACK before
3005 ** it is executed.
3006 */
3007 case DB_TRACE: {
3008 if( objc>3 ){
3009 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00003010 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00003011 }else if( objc==2 ){
3012 if( pDb->zTrace ){
drha198f2b2014-02-07 19:26:13 +00003013 Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
drhb5a20d32003-04-23 12:25:23 +00003014 }
3015 }else{
3016 char *zTrace;
3017 int len;
3018 if( pDb->zTrace ){
3019 Tcl_Free(pDb->zTrace);
3020 }
3021 zTrace = Tcl_GetStringFromObj(objv[2], &len);
3022 if( zTrace && len>0 ){
3023 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00003024 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00003025 }else{
3026 pDb->zTrace = 0;
3027 }
drh2eb22af2016-09-10 19:51:40 +00003028#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3029 !defined(SQLITE_OMIT_DEPRECATED)
drhb5a20d32003-04-23 12:25:23 +00003030 if( pDb->zTrace ){
3031 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00003032 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00003033 }else{
danielk19776f8a5032004-05-10 10:34:51 +00003034 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00003035 }
drh19e2d372005-08-29 23:00:03 +00003036#endif
drhb5a20d32003-04-23 12:25:23 +00003037 }
3038 break;
3039 }
3040
mistachkinb56660f2016-07-14 21:26:09 +00003041 /* $db trace_v2 ?CALLBACK? ?MASK?
3042 **
3043 ** Make arrangements to invoke the CALLBACK routine for each trace event
3044 ** matching the mask that is generated. The parameters are appended to
3045 ** CALLBACK before it is executed.
3046 */
3047 case DB_TRACE_V2: {
3048 if( objc>4 ){
3049 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK? ?MASK?");
3050 return TCL_ERROR;
3051 }else if( objc==2 ){
3052 if( pDb->zTraceV2 ){
3053 Tcl_AppendResult(interp, pDb->zTraceV2, (char*)0);
3054 }
3055 }else{
mistachkinb56660f2016-07-14 21:26:09 +00003056 char *zTraceV2;
3057 int len;
mistachkinb52dcd82016-07-14 23:17:03 +00003058 Tcl_WideInt wMask = 0;
mistachkinb56660f2016-07-14 21:26:09 +00003059 if( objc==4 ){
mistachkinb52dcd82016-07-14 23:17:03 +00003060 static const char *TTYPE_strs[] = {
3061 "statement", "profile", "row", "close", 0
3062 };
3063 enum TTYPE_enum {
3064 TTYPE_STMT, TTYPE_PROFILE, TTYPE_ROW, TTYPE_CLOSE
3065 };
3066 int i;
3067 if( TCL_OK!=Tcl_ListObjLength(interp, objv[3], &len) ){
mistachkinb56660f2016-07-14 21:26:09 +00003068 return TCL_ERROR;
3069 }
mistachkinb52dcd82016-07-14 23:17:03 +00003070 for(i=0; i<len; i++){
3071 Tcl_Obj *pObj;
3072 int ttype;
3073 if( TCL_OK!=Tcl_ListObjIndex(interp, objv[3], i, &pObj) ){
3074 return TCL_ERROR;
3075 }
3076 if( Tcl_GetIndexFromObj(interp, pObj, TTYPE_strs, "trace type",
3077 0, &ttype)!=TCL_OK ){
3078 Tcl_WideInt wType;
3079 Tcl_Obj *pError = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
3080 Tcl_IncrRefCount(pError);
3081 if( TCL_OK==Tcl_GetWideIntFromObj(interp, pObj, &wType) ){
3082 Tcl_DecrRefCount(pError);
3083 wMask |= wType;
3084 }else{
3085 Tcl_SetObjResult(interp, pError);
3086 Tcl_DecrRefCount(pError);
3087 return TCL_ERROR;
3088 }
3089 }else{
3090 switch( (enum TTYPE_enum)ttype ){
3091 case TTYPE_STMT: wMask |= SQLITE_TRACE_STMT; break;
3092 case TTYPE_PROFILE: wMask |= SQLITE_TRACE_PROFILE; break;
3093 case TTYPE_ROW: wMask |= SQLITE_TRACE_ROW; break;
3094 case TTYPE_CLOSE: wMask |= SQLITE_TRACE_CLOSE; break;
3095 }
3096 }
3097 }
mistachkinb56660f2016-07-14 21:26:09 +00003098 }else{
mistachkinb52dcd82016-07-14 23:17:03 +00003099 wMask = SQLITE_TRACE_STMT; /* use the "legacy" default */
mistachkinb56660f2016-07-14 21:26:09 +00003100 }
3101 if( pDb->zTraceV2 ){
3102 Tcl_Free(pDb->zTraceV2);
3103 }
3104 zTraceV2 = Tcl_GetStringFromObj(objv[2], &len);
3105 if( zTraceV2 && len>0 ){
3106 pDb->zTraceV2 = Tcl_Alloc( len + 1 );
3107 memcpy(pDb->zTraceV2, zTraceV2, len+1);
3108 }else{
3109 pDb->zTraceV2 = 0;
3110 }
3111#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3112 if( pDb->zTraceV2 ){
3113 pDb->interp = interp;
3114 sqlite3_trace_v2(pDb->db, (unsigned)wMask, DbTraceV2Handler, pDb);
3115 }else{
3116 sqlite3_trace_v2(pDb->db, 0, 0, 0);
3117 }
3118#endif
3119 }
3120 break;
3121 }
3122
drh3d214232005-08-02 12:21:08 +00003123 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
3124 **
3125 ** Start a new transaction (if we are not already in the midst of a
3126 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
3127 ** completes, either commit the transaction or roll it back if SCRIPT
3128 ** throws an exception. Or if no new transation was started, do nothing.
3129 ** pass the exception on up the stack.
3130 **
3131 ** This command was inspired by Dave Thomas's talk on Ruby at the
3132 ** 2005 O'Reilly Open Source Convention (OSCON).
3133 */
3134 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00003135 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00003136 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00003137 if( objc!=3 && objc!=4 ){
3138 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
3139 return TCL_ERROR;
3140 }
danielk1977cd38d522009-01-02 17:33:46 +00003141
dan4a4c11a2009-10-06 14:59:02 +00003142 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00003143 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00003144 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00003145 };
3146 enum TTYPE_enum {
3147 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
3148 };
3149 int ttype;
drhb5555e72005-08-02 17:15:14 +00003150 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00003151 0, &ttype) ){
3152 return TCL_ERROR;
3153 }
3154 switch( (enum TTYPE_enum)ttype ){
3155 case TTYPE_DEFERRED: /* no-op */; break;
3156 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
3157 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
3158 }
drh3d214232005-08-02 12:21:08 +00003159 }
danielk1977cd38d522009-01-02 17:33:46 +00003160 pScript = objv[objc-1];
3161
dan4a4c11a2009-10-06 14:59:02 +00003162 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00003163 pDb->disableAuth++;
3164 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
3165 pDb->disableAuth--;
3166 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00003167 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977cd38d522009-01-02 17:33:46 +00003168 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00003169 }
danielk1977cd38d522009-01-02 17:33:46 +00003170 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00003171
dan4a4c11a2009-10-06 14:59:02 +00003172 /* If using NRE, schedule a callback to invoke the script pScript, then
3173 ** a second callback to commit (or rollback) the transaction or savepoint
3174 ** opened above. If not using NRE, evaluate the script directly, then
mistachkinb56660f2016-07-14 21:26:09 +00003175 ** call function DbTransPostCmd() to commit (or rollback) the transaction
dan4a4c11a2009-10-06 14:59:02 +00003176 ** or savepoint. */
3177 if( DbUseNre() ){
3178 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
drha47941f2013-12-20 18:57:44 +00003179 (void)Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00003180 }else{
dan4a4c11a2009-10-06 14:59:02 +00003181 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00003182 }
3183 break;
3184 }
3185
danielk197794eb6a12005-12-15 15:22:08 +00003186 /*
danielk1977404ca072009-03-16 13:19:36 +00003187 ** $db unlock_notify ?script?
3188 */
3189 case DB_UNLOCK_NOTIFY: {
3190#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
drha198f2b2014-02-07 19:26:13 +00003191 Tcl_AppendResult(interp, "unlock_notify not available in this build",
3192 (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00003193 rc = TCL_ERROR;
3194#else
3195 if( objc!=2 && objc!=3 ){
3196 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3197 rc = TCL_ERROR;
3198 }else{
3199 void (*xNotify)(void **, int) = 0;
3200 void *pNotifyArg = 0;
3201
3202 if( pDb->pUnlockNotify ){
3203 Tcl_DecrRefCount(pDb->pUnlockNotify);
3204 pDb->pUnlockNotify = 0;
3205 }
mistachkinb56660f2016-07-14 21:26:09 +00003206
danielk1977404ca072009-03-16 13:19:36 +00003207 if( objc==3 ){
3208 xNotify = DbUnlockNotify;
3209 pNotifyArg = (void *)pDb;
3210 pDb->pUnlockNotify = objv[2];
3211 Tcl_IncrRefCount(pDb->pUnlockNotify);
3212 }
mistachkinb56660f2016-07-14 21:26:09 +00003213
danielk1977404ca072009-03-16 13:19:36 +00003214 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
drha198f2b2014-02-07 19:26:13 +00003215 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00003216 rc = TCL_ERROR;
3217 }
3218 }
3219#endif
3220 break;
3221 }
3222
drh304637c2011-03-18 16:47:27 +00003223 /*
3224 ** $db preupdate_hook count
3225 ** $db preupdate_hook hook ?SCRIPT?
3226 ** $db preupdate_hook new INDEX
3227 ** $db preupdate_hook old INDEX
3228 */
dan46c47d42011-03-01 18:42:07 +00003229 case DB_PREUPDATE: {
drh9b1c62d2011-03-30 21:04:43 +00003230#ifndef SQLITE_ENABLE_PREUPDATE_HOOK
dan2b519ab2016-12-06 19:33:42 +00003231 Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time",
3232 (char*)0);
drh9b1c62d2011-03-30 21:04:43 +00003233 rc = TCL_ERROR;
3234#else
dan1e7a2d42011-03-22 18:45:29 +00003235 static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
dan46c47d42011-03-01 18:42:07 +00003236 enum DbPreupdateSubCmd {
dan1e7a2d42011-03-22 18:45:29 +00003237 PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
dan46c47d42011-03-01 18:42:07 +00003238 };
3239 int iSub;
3240
3241 if( objc<3 ){
3242 Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
3243 }
3244 if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
3245 return TCL_ERROR;
3246 }
3247
3248 switch( (enum DbPreupdateSubCmd)iSub ){
3249 case PRE_COUNT: {
3250 int nCol = sqlite3_preupdate_count(pDb->db);
3251 Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
3252 break;
3253 }
3254
3255 case PRE_HOOK: {
3256 if( objc>4 ){
3257 Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
3258 return TCL_ERROR;
3259 }
3260 DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
3261 break;
3262 }
3263
dan1e7a2d42011-03-22 18:45:29 +00003264 case PRE_DEPTH: {
3265 Tcl_Obj *pRet;
3266 if( objc!=3 ){
3267 Tcl_WrongNumArgs(interp, 3, objv, "");
3268 return TCL_ERROR;
3269 }
3270 pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
3271 Tcl_SetObjResult(interp, pRet);
3272 break;
3273 }
3274
dan37db03b2011-03-16 19:59:18 +00003275 case PRE_NEW:
dan46c47d42011-03-01 18:42:07 +00003276 case PRE_OLD: {
3277 int iIdx;
dan37db03b2011-03-16 19:59:18 +00003278 sqlite3_value *pValue;
dan46c47d42011-03-01 18:42:07 +00003279 if( objc!=4 ){
3280 Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
3281 return TCL_ERROR;
3282 }
3283 if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
3284 return TCL_ERROR;
3285 }
3286
dan37db03b2011-03-16 19:59:18 +00003287 if( iSub==PRE_OLD ){
dan46c47d42011-03-01 18:42:07 +00003288 rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
dan37db03b2011-03-16 19:59:18 +00003289 }else{
3290 assert( iSub==PRE_NEW );
3291 rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
dan46c47d42011-03-01 18:42:07 +00003292 }
3293
dan37db03b2011-03-16 19:59:18 +00003294 if( rc==SQLITE_OK ){
drh304637c2011-03-18 16:47:27 +00003295 Tcl_Obj *pObj;
3296 pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
dan37db03b2011-03-16 19:59:18 +00003297 Tcl_SetObjResult(interp, pObj);
3298 }else{
drhea8f0a12017-01-12 11:50:08 +00003299 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
dan46c47d42011-03-01 18:42:07 +00003300 return TCL_ERROR;
3301 }
3302 }
3303 }
drh9b1c62d2011-03-30 21:04:43 +00003304#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +00003305 break;
3306 }
3307
danielk1977404ca072009-03-16 13:19:36 +00003308 /*
drh833bf962010-04-28 14:42:19 +00003309 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003310 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00003311 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003312 */
mistachkinb56660f2016-07-14 21:26:09 +00003313 case DB_WAL_HOOK:
3314 case DB_UPDATE_HOOK:
dan6566ebe2011-03-16 09:49:14 +00003315 case DB_ROLLBACK_HOOK: {
mistachkinb56660f2016-07-14 21:26:09 +00003316 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
danielk197771fd80b2005-12-16 06:54:01 +00003317 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3318 */
mistachkinb56660f2016-07-14 21:26:09 +00003319 Tcl_Obj **ppHook = 0;
dan46c47d42011-03-01 18:42:07 +00003320 if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
3321 if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
3322 if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
3323 if( objc>3 ){
danielk197794eb6a12005-12-15 15:22:08 +00003324 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3325 return TCL_ERROR;
3326 }
danielk197771fd80b2005-12-16 06:54:01 +00003327
dan46c47d42011-03-01 18:42:07 +00003328 DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00003329 break;
3330 }
3331
danielk19774397de52005-01-12 12:44:03 +00003332 /* $db version
3333 **
3334 ** Return the version string for this database.
3335 */
3336 case DB_VERSION: {
drh1df64702017-10-13 15:56:26 +00003337 int i;
3338 for(i=2; i<objc; i++){
3339 const char *zArg = Tcl_GetString(objv[i]);
3340 /* Optional arguments to $db version are used for testing purpose */
3341#ifdef SQLITE_TEST
3342 /* $db version -use-legacy-prepare BOOLEAN
3343 **
3344 ** Turn the use of legacy sqlite3_prepare() on or off.
3345 */
3346 if( strcmp(zArg, "-use-legacy-prepare")==0 && i+1<objc ){
3347 i++;
3348 if( Tcl_GetBooleanFromObj(interp, objv[i], &pDb->bLegacyPrepare) ){
3349 return TCL_ERROR;
3350 }
3351 }else
3352
3353 /* $db version -last-stmt-ptr
3354 **
3355 ** Return a string which is a hex encoding of the pointer to the
3356 ** most recent sqlite3_stmt in the statement cache.
3357 */
3358 if( strcmp(zArg, "-last-stmt-ptr")==0 ){
3359 char zBuf[100];
3360 sqlite3_snprintf(sizeof(zBuf), zBuf, "%p",
3361 pDb->stmtList ? pDb->stmtList->pStmt: 0);
3362 Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
3363 }else
3364#endif /* SQLITE_TEST */
3365 {
3366 Tcl_AppendResult(interp, "unknown argument: ", zArg, (char*)0);
3367 return TCL_ERROR;
3368 }
3369 }
3370 if( i==2 ){
3371 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
3372 }
danielk19774397de52005-01-12 12:44:03 +00003373 break;
3374 }
3375
tpoindex1067fe12004-12-17 15:41:11 +00003376
drh6d313162000-09-21 13:01:35 +00003377 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00003378 return rc;
drh75897232000-05-29 14:26:00 +00003379}
3380
drha2c8a952009-10-13 18:38:34 +00003381#if SQLITE_TCL_NRE
3382/*
3383** Adaptor that provides an objCmd interface to the NRE-enabled
3384** interface implementation.
3385*/
mistachkina121cc72016-07-28 18:06:52 +00003386static int SQLITE_TCLAPI DbObjCmdAdaptor(
drha2c8a952009-10-13 18:38:34 +00003387 void *cd,
3388 Tcl_Interp *interp,
3389 int objc,
3390 Tcl_Obj *const*objv
3391){
3392 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
3393}
3394#endif /* SQLITE_TCL_NRE */
3395
drh75897232000-05-29 14:26:00 +00003396/*
drh4dcac402018-01-03 13:20:02 +00003397** Issue the usage message when the "sqlite3" command arguments are
3398** incorrect.
3399*/
3400static int sqliteCmdUsage(
3401 Tcl_Interp *interp,
3402 Tcl_Obj *const*objv
3403){
3404 Tcl_WrongNumArgs(interp, 1, objv,
3405 "HANDLE ?FILENAME? ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
3406 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
3407#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3408 " ?-key CODECKEY?"
3409#endif
3410 );
3411 return TCL_ERROR;
3412}
3413
3414/*
drh3570ad92007-08-31 14:31:44 +00003415** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00003416** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00003417**
3418** This is the main Tcl command. When the "sqlite" Tcl command is
3419** invoked, this routine runs to process that command.
3420**
3421** The first argument, DBNAME, is an arbitrary name for a new
3422** database connection. This command creates a new command named
3423** DBNAME that is used to control that connection. The database
3424** connection is deleted when the DBNAME command is deleted.
3425**
drh3570ad92007-08-31 14:31:44 +00003426** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00003427**
drh75897232000-05-29 14:26:00 +00003428*/
mistachkin7617e4a2016-07-28 17:11:20 +00003429static int SQLITE_TCLAPI DbMain(
3430 void *cd,
3431 Tcl_Interp *interp,
3432 int objc,
3433 Tcl_Obj *const*objv
3434){
drhbec3f402000-08-04 13:49:02 +00003435 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00003436 const char *zArg;
drh75897232000-05-29 14:26:00 +00003437 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00003438 int i;
drh4dcac402018-01-03 13:20:02 +00003439 const char *zFile = 0;
drh3570ad92007-08-31 14:31:44 +00003440 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00003441 int flags;
drh882e8e42006-08-24 02:42:27 +00003442 Tcl_DString translatedFilename;
drh32f57d42016-03-16 01:03:10 +00003443#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00003444 void *pKey = 0;
3445 int nKey = 0;
3446#endif
mistachkin540ebf82012-09-10 07:29:29 +00003447 int rc;
drh4dcac402018-01-03 13:20:02 +00003448#ifdef SQLITE_ENABLE_MEMDB
3449 Tcl_Obj *pDbObj = 0;
3450#endif
drhd9da78a2009-03-24 15:08:09 +00003451
3452 /* In normal use, each TCL interpreter runs in a single thread. So
drh4dcac402018-01-03 13:20:02 +00003453 ** by default, we can turn off mutexing on SQLite database connections.
drhd9da78a2009-03-24 15:08:09 +00003454 ** However, for testing purposes it is useful to have mutexes turned
3455 ** on. So, by default, mutexes default off. But if compiled with
3456 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3457 */
3458#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3459 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3460#else
3461 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3462#endif
3463
drh22fbcb82004-02-01 01:22:50 +00003464 if( objc==2 ){
3465 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00003466 if( strcmp(zArg,"-version")==0 ){
drha198f2b2014-02-07 19:26:13 +00003467 Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
drh647cb0e2002-11-04 19:32:25 +00003468 return TCL_OK;
3469 }
drh72bf6a32016-01-07 02:06:55 +00003470 if( strcmp(zArg,"-sourceid")==0 ){
3471 Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0);
3472 return TCL_OK;
3473 }
drh9eb9e262004-02-11 02:18:05 +00003474 if( strcmp(zArg,"-has-codec")==0 ){
drh32f57d42016-03-16 01:03:10 +00003475#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drha198f2b2014-02-07 19:26:13 +00003476 Tcl_AppendResult(interp,"1",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003477#else
drha198f2b2014-02-07 19:26:13 +00003478 Tcl_AppendResult(interp,"0",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003479#endif
3480 return TCL_OK;
3481 }
drh4dcac402018-01-03 13:20:02 +00003482 if( zArg[0]=='-' ) return sqliteCmdUsage(interp, objv);
drhfbc3eab2001-04-06 16:13:42 +00003483 }
drh4dcac402018-01-03 13:20:02 +00003484 for(i=2; i<objc; i++){
drh3570ad92007-08-31 14:31:44 +00003485 zArg = Tcl_GetString(objv[i]);
drh4dcac402018-01-03 13:20:02 +00003486 if( zArg[0]!='-' ){
3487 if( zFile!=0 ) return sqliteCmdUsage(interp, objv);
3488 zFile = zArg;
3489 continue;
3490 }
3491 if( i==objc-1 ) return sqliteCmdUsage(interp, objv);
3492 i++;
drh22fbcb82004-02-01 01:22:50 +00003493 if( strcmp(zArg,"-key")==0 ){
drh32f57d42016-03-16 01:03:10 +00003494#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh4dcac402018-01-03 13:20:02 +00003495 pKey = Tcl_GetByteArrayFromObj(objv[i], &nKey);
drhb07028f2011-10-14 21:49:18 +00003496#endif
drh3570ad92007-08-31 14:31:44 +00003497 }else if( strcmp(zArg, "-vfs")==0 ){
drh4dcac402018-01-03 13:20:02 +00003498 zVfs = Tcl_GetString(objv[i]);
drh3570ad92007-08-31 14:31:44 +00003499 }else if( strcmp(zArg, "-readonly")==0 ){
3500 int b;
drh4dcac402018-01-03 13:20:02 +00003501 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
drh3570ad92007-08-31 14:31:44 +00003502 if( b ){
drh33f4e022007-09-03 15:19:34 +00003503 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00003504 flags |= SQLITE_OPEN_READONLY;
3505 }else{
3506 flags &= ~SQLITE_OPEN_READONLY;
3507 flags |= SQLITE_OPEN_READWRITE;
3508 }
3509 }else if( strcmp(zArg, "-create")==0 ){
3510 int b;
drh4dcac402018-01-03 13:20:02 +00003511 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00003512 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00003513 flags |= SQLITE_OPEN_CREATE;
3514 }else{
3515 flags &= ~SQLITE_OPEN_CREATE;
3516 }
danielk19779a6284c2008-07-10 17:52:49 +00003517 }else if( strcmp(zArg, "-nomutex")==0 ){
3518 int b;
drh4dcac402018-01-03 13:20:02 +00003519 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
danielk19779a6284c2008-07-10 17:52:49 +00003520 if( b ){
3521 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00003522 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00003523 }else{
3524 flags &= ~SQLITE_OPEN_NOMUTEX;
3525 }
danc431fd52011-06-27 16:55:50 +00003526 }else if( strcmp(zArg, "-fullmutex")==0 ){
drh039963a2008-09-03 00:43:15 +00003527 int b;
drh4dcac402018-01-03 13:20:02 +00003528 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
drh039963a2008-09-03 00:43:15 +00003529 if( b ){
3530 flags |= SQLITE_OPEN_FULLMUTEX;
3531 flags &= ~SQLITE_OPEN_NOMUTEX;
3532 }else{
3533 flags &= ~SQLITE_OPEN_FULLMUTEX;
3534 }
drhf12b3f62011-12-21 14:42:29 +00003535 }else if( strcmp(zArg, "-uri")==0 ){
3536 int b;
drh4dcac402018-01-03 13:20:02 +00003537 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
drhf12b3f62011-12-21 14:42:29 +00003538 if( b ){
3539 flags |= SQLITE_OPEN_URI;
3540 }else{
3541 flags &= ~SQLITE_OPEN_URI;
3542 }
drh4dcac402018-01-03 13:20:02 +00003543#ifdef SQLITE_ENABLE_MEMDB
3544 }else if( strcmp(zArg, "-memdb")==0 ){
3545 pDbObj = objv[i];
3546#endif
drh3570ad92007-08-31 14:31:44 +00003547 }else{
3548 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3549 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00003550 }
3551 }
drh75897232000-05-29 14:26:00 +00003552 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003553 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drhbec3f402000-08-04 13:49:02 +00003554 memset(p, 0, sizeof(*p));
drh4dcac402018-01-03 13:20:02 +00003555#ifdef SQLITE_ENABLE_MEMDB
3556 if( pDbObj ){
3557 rc = sqlite3_open_v2("x", &p->db, flags, "memdb");
3558 if( rc==SQLITE_OK ){
3559 int len;
3560 unsigned char *aData = Tcl_GetByteArrayFromObj(pDbObj, &len);
3561 unsigned char *a = sqlite3_malloc64( len );
3562 memcpy(a, aData, len);
3563 sqlite3_memdb_config(p->db, "main", a, len, sqlite3_msize(a),
3564 SQLITE_MEMDB_FREEONCLOSE | SQLITE_MEMDB_RESIZEABLE);
3565 }
3566 }else
3567#endif
3568 {
3569 if( zFile==0 ) zFile = ":memory:";
3570 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
3571 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
3572 Tcl_DStringFree(&translatedFilename);
3573 }
mistachkin540ebf82012-09-10 07:29:29 +00003574 if( p->db ){
3575 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3576 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3577 sqlite3_close(p->db);
3578 p->db = 0;
3579 }
3580 }else{
mistachkin5dac8432012-09-11 02:00:25 +00003581 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
danielk197780290862004-05-22 09:21:21 +00003582 }
drh32f57d42016-03-16 01:03:10 +00003583#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhf3a65f72007-08-22 20:18:21 +00003584 if( p->db ){
3585 sqlite3_key(p->db, pKey, nKey);
3586 }
drheb8ed702004-02-11 10:37:23 +00003587#endif
drhbec3f402000-08-04 13:49:02 +00003588 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003589 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003590 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003591 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003592 return TCL_ERROR;
3593 }
drhfb7e7652005-01-24 00:28:42 +00003594 p->maxStmt = NUM_PREPARED_STMTS;
drh147ef392016-01-22 23:17:51 +00003595 p->openFlags = flags & SQLITE_OPEN_URI;
drh5169bbc2006-08-24 14:59:45 +00003596 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003597 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003598 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003599 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3600 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003601 }else{
3602 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3603 }
drh75897232000-05-29 14:26:00 +00003604 return TCL_OK;
3605}
3606
3607/*
drh90ca9752001-09-28 17:47:14 +00003608** Provide a dummy Tcl_InitStubs if we are using this as a static
3609** library.
3610*/
3611#ifndef USE_TCL_STUBS
3612# undef Tcl_InitStubs
drh0e85ccf2013-06-03 12:34:46 +00003613# define Tcl_InitStubs(a,b,c) TCL_VERSION
drh90ca9752001-09-28 17:47:14 +00003614#endif
3615
3616/*
drh29bc4612005-10-05 10:40:15 +00003617** Make sure we have a PACKAGE_VERSION macro defined. This will be
3618** defined automatically by the TEA makefile. But other makefiles
3619** do not define it.
3620*/
3621#ifndef PACKAGE_VERSION
3622# define PACKAGE_VERSION SQLITE_VERSION
3623#endif
3624
3625/*
drh75897232000-05-29 14:26:00 +00003626** Initialize this module.
3627**
3628** This Tcl module contains only a single new Tcl command named "sqlite".
3629** (Hence there is no namespace. There is no point in using a namespace
3630** if the extension only supplies one new name!) The "sqlite" command is
3631** used to open a new SQLite database. See the DbMain() routine above
3632** for additional information.
drhb652f432010-08-26 16:46:57 +00003633**
3634** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003635*/
drhb652f432010-08-26 16:46:57 +00003636EXTERN int Sqlite3_Init(Tcl_Interp *interp){
mistachkin27b2f052015-01-12 19:49:46 +00003637 int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
drh6dc8cbe2013-05-31 15:36:07 +00003638 if( rc==TCL_OK ){
3639 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh1cca0d22010-08-25 20:35:51 +00003640#ifndef SQLITE_3_SUFFIX_ONLY
drh6dc8cbe2013-05-31 15:36:07 +00003641 /* The "sqlite" alias is undocumented. It is here only to support
3642 ** legacy scripts. All new scripts should use only the "sqlite3"
3643 ** command. */
3644 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003645#endif
drh6dc8cbe2013-05-31 15:36:07 +00003646 rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3647 }
3648 return rc;
drh90ca9752001-09-28 17:47:14 +00003649}
drhb652f432010-08-26 16:46:57 +00003650EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
drhb652f432010-08-26 16:46:57 +00003651EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3652EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00003653
drhd878cab2012-03-20 15:10:42 +00003654/* Because it accesses the file-system and uses persistent state, SQLite
drhe75a9eb2016-02-13 18:54:10 +00003655** is not considered appropriate for safe interpreters. Hence, we cause
3656** the _SafeInit() interfaces return TCL_ERROR.
drhd878cab2012-03-20 15:10:42 +00003657*/
drhe75a9eb2016-02-13 18:54:10 +00003658EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
3659EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
3660
3661
drh49766d62005-01-08 18:42:28 +00003662
3663#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003664int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3665int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
dana3e63c42010-08-20 12:33:59 +00003666int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3667int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00003668#endif
drh75897232000-05-29 14:26:00 +00003669
drhc318f732017-10-13 15:06:06 +00003670/*
drh96a206f2017-10-13 20:14:06 +00003671** If the TCLSH macro is defined, add code to make a stand-alone program.
drhc318f732017-10-13 15:06:06 +00003672*/
drh96a206f2017-10-13 20:14:06 +00003673#if defined(TCLSH)
drh57a02272009-10-22 20:52:05 +00003674
drh96a206f2017-10-13 20:14:06 +00003675/* This is the main routine for an ordinary TCL shell. If there are
3676** are arguments, run the first argument as a script. Otherwise,
3677** read TCL commands from standard input
drh348784e2000-05-29 20:41:49 +00003678*/
dan0ae479d2011-09-21 16:43:07 +00003679static const char *tclsh_main_loop(void){
3680 static const char zMainloop[] =
drh96a206f2017-10-13 20:14:06 +00003681 "if {[llength $argv]>=1} {\n"
3682 "set argv0 [lindex $argv 0]\n"
3683 "set argv [lrange $argv 1 end]\n"
3684 "source $argv0\n"
3685 "} else {\n"
3686 "set line {}\n"
3687 "while {![eof stdin]} {\n"
3688 "if {$line!=\"\"} {\n"
3689 "puts -nonewline \"> \"\n"
3690 "} else {\n"
3691 "puts -nonewline \"% \"\n"
dan0ae479d2011-09-21 16:43:07 +00003692 "}\n"
drh96a206f2017-10-13 20:14:06 +00003693 "flush stdout\n"
3694 "append line [gets stdin]\n"
3695 "if {[info complete $line]} {\n"
3696 "if {[catch {uplevel #0 $line} result]} {\n"
3697 "puts stderr \"Error: $result\"\n"
3698 "} elseif {$result!=\"\"} {\n"
3699 "puts $result\n"
3700 "}\n"
3701 "set line {}\n"
3702 "} else {\n"
3703 "append line \\n\n"
3704 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003705 "}\n"
drh348784e2000-05-29 20:41:49 +00003706 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003707 ;
3708 return zMainloop;
3709}
drh3e27c022004-07-23 00:01:38 +00003710
danc1a60c52010-06-07 14:28:16 +00003711#define TCLSH_MAIN main /* Needed to fake out mktclapp */
mistachkin69def7f2016-07-28 04:14:37 +00003712int SQLITE_CDECL TCLSH_MAIN(int argc, char **argv){
danc1a60c52010-06-07 14:28:16 +00003713 Tcl_Interp *interp;
drh96a206f2017-10-13 20:14:06 +00003714 int i;
3715 const char *zScript = 0;
3716 char zArgc[32];
3717#if defined(TCLSH_INIT_PROC)
3718 extern const char *TCLSH_INIT_PROC(Tcl_Interp*);
3719#endif
mistachkin1f28e072013-08-15 08:06:15 +00003720
3721#if !defined(_WIN32_WCE)
3722 if( getenv("BREAK") ){
3723 fprintf(stderr,
3724 "attach debugger to process %d and press any key to continue.\n",
3725 GETPID());
3726 fgetc(stdin);
3727 }
3728#endif
3729
danc1a60c52010-06-07 14:28:16 +00003730 /* Call sqlite3_shutdown() once before doing anything else. This is to
3731 ** test that sqlite3_shutdown() can be safely called by a process before
3732 ** sqlite3_initialize() is. */
3733 sqlite3_shutdown();
3734
dan0ae479d2011-09-21 16:43:07 +00003735 Tcl_FindExecutable(argv[0]);
mistachkin2953ba92014-02-14 00:25:03 +00003736 Tcl_SetSystemEncoding(NULL, "utf-8");
dan0ae479d2011-09-21 16:43:07 +00003737 interp = Tcl_CreateInterp();
drhc318f732017-10-13 15:06:06 +00003738 Sqlite3_Init(interp);
drh96a206f2017-10-13 20:14:06 +00003739
3740 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-1);
3741 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
3742 Tcl_SetVar(interp,"argv0",argv[0],TCL_GLOBAL_ONLY);
3743 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
3744 for(i=1; i<argc; i++){
3745 Tcl_SetVar(interp, "argv", argv[i],
3746 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
drhc318f732017-10-13 15:06:06 +00003747 }
drh96a206f2017-10-13 20:14:06 +00003748#if defined(TCLSH_INIT_PROC)
3749 zScript = TCLSH_INIT_PROC(interp);
3750#endif
3751 if( zScript==0 ){
3752 zScript = tclsh_main_loop();
drh3e27c022004-07-23 00:01:38 +00003753 }
drh96a206f2017-10-13 20:14:06 +00003754 if( Tcl_GlobalEval(interp, zScript)!=TCL_OK ){
3755 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
3756 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
3757 fprintf(stderr,"%s: %s\n", *argv, zInfo);
3758 return 1;
drh348784e2000-05-29 20:41:49 +00003759 }
3760 return 0;
3761}
3762#endif /* TCLSH */