blob: 80a05726224fd99990bce43cf1aa37237136b6af [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)
mistachkin1e8487d2018-07-22 06:25:35 +000063# include <signal.h>
mistachkin1f28e072013-08-15 08:06:15 +000064# include <unistd.h>
65# define GETPID getpid
66#elif !defined(_WIN32_WCE)
67# ifndef SQLITE_AMALGAMATION
mistachkin176b3a02018-01-23 07:11:05 +000068# ifndef WIN32_LEAN_AND_MEAN
69# define WIN32_LEAN_AND_MEAN
70# endif
mistachkin1f28e072013-08-15 08:06:15 +000071# include <windows.h>
72# endif
mistachkin1e8487d2018-07-22 06:25:35 +000073# include <io.h>
74# define isatty(h) _isatty(h)
mistachkin1f28e072013-08-15 08:06:15 +000075# define GETPID (int)GetCurrentProcessId
76#endif
77
drhad6e1372006-07-10 21:15:51 +000078/*
79 * Windows needs to know which symbols to export. Unix does not.
80 * BUILD_sqlite should be undefined for Unix.
81 */
82#ifdef BUILD_sqlite
83#undef TCL_STORAGE_CLASS
84#define TCL_STORAGE_CLASS DLLEXPORT
85#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000086
danielk1977a21c6b62005-01-24 10:25:59 +000087#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000088#define MAX_PREPARED_STMTS 100
89
drhc45e6712012-10-03 11:02:33 +000090/* Forward declaration */
91typedef struct SqliteDb SqliteDb;
drh98808ba2001-10-18 12:34:46 +000092
93/*
drhcabb0812002-09-14 13:47:32 +000094** New SQL functions can be created as TCL scripts. Each such function
95** is described by an instance of the following structure.
dan89d24932019-02-27 16:38:19 +000096**
97** Variable eType may be set to SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT,
98** SQLITE_BLOB or SQLITE_NULL. If it is SQLITE_NULL, then the implementation
99** attempts to determine the type of the result based on the Tcl object.
100** If it is SQLITE_TEXT or SQLITE_BLOB, then a text (sqlite3_result_text())
101** or blob (sqlite3_result_blob()) is returned. If it is SQLITE_INTEGER
102** or SQLITE_FLOAT, then an attempt is made to return an integer or float
103** value, falling back to float and then text if this is not possible.
drhcabb0812002-09-14 13:47:32 +0000104*/
105typedef struct SqlFunc SqlFunc;
106struct SqlFunc {
107 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +0000108 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
drhc45e6712012-10-03 11:02:33 +0000109 SqliteDb *pDb; /* Database connection that owns this function */
drhd1e47332005-06-26 17:55:33 +0000110 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
dan89d24932019-02-27 16:38:19 +0000111 int eType; /* Type of value to return */
drhd1e47332005-06-26 17:55:33 +0000112 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +0000113 SqlFunc *pNext; /* Next function on the list of them all */
114};
115
116/*
danielk19770202b292004-06-09 09:55:16 +0000117** New collation sequences function can be created as TCL scripts. Each such
118** function is described by an instance of the following structure.
119*/
120typedef struct SqlCollate SqlCollate;
121struct SqlCollate {
122 Tcl_Interp *interp; /* The TCL interpret to execute the function */
123 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +0000124 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +0000125};
126
127/*
drhfb7e7652005-01-24 00:28:42 +0000128** Prepared statements are cached for faster execution. Each prepared
129** statement is described by an instance of the following structure.
130*/
131typedef struct SqlPreparedStmt SqlPreparedStmt;
132struct SqlPreparedStmt {
133 SqlPreparedStmt *pNext; /* Next in linked list */
134 SqlPreparedStmt *pPrev; /* Previous on the list */
135 sqlite3_stmt *pStmt; /* The prepared statement */
136 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +0000137 const char *zSql; /* Text of the SQL statement */
dan4a4c11a2009-10-06 14:59:02 +0000138 int nParm; /* Size of apParm array */
139 Tcl_Obj **apParm; /* Array of referenced object pointers */
drhfb7e7652005-01-24 00:28:42 +0000140};
141
danielk1977d04417962007-05-02 13:16:30 +0000142typedef struct IncrblobChannel IncrblobChannel;
143
drhfb7e7652005-01-24 00:28:42 +0000144/*
drhbec3f402000-08-04 13:49:02 +0000145** There is one instance of this structure for each SQLite database
146** that has been opened by the SQLite TCL interface.
danc431fd52011-06-27 16:55:50 +0000147**
148** If this module is built with SQLITE_TEST defined (to create the SQLite
149** testfixture executable), then it may be configured to use either
150** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
151** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
drhbec3f402000-08-04 13:49:02 +0000152*/
drhbec3f402000-08-04 13:49:02 +0000153struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000154 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000155 Tcl_Interp *interp; /* The interpreter used for this database */
156 char *zBusy; /* The busy callback routine */
157 char *zCommit; /* The commit hook callback routine */
158 char *zTrace; /* The trace callback routine */
mistachkinb56660f2016-07-14 21:26:09 +0000159 char *zTraceV2; /* The trace_v2 callback routine */
drh19e2d372005-08-29 23:00:03 +0000160 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000161 char *zProgress; /* The progress callback routine */
drhc06ede12019-02-28 17:29:19 +0000162 char *zBindFallback; /* Callback to invoke on a binding miss */
drhd1e47332005-06-26 17:55:33 +0000163 char *zAuth; /* The authorization callback routine */
drh1f1549f2008-08-26 21:33:34 +0000164 int disableAuth; /* Disable the authorizer if it exists */
drhd1e47332005-06-26 17:55:33 +0000165 char *zNull; /* Text to substitute for an SQL NULL value */
166 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000167 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
dan46c47d42011-03-01 18:42:07 +0000168 Tcl_Obj *pPreUpdateHook; /* Pre-update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000169 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drh5def0842010-05-05 20:00:25 +0000170 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000171 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000172 SqlCollate *pCollate; /* List of SQL collation functions */
173 int rc; /* Return code of most recent sqlite3_exec() */
174 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000175 SqlPreparedStmt *stmtList; /* List of prepared statements*/
176 SqlPreparedStmt *stmtLast; /* Last statement in the list */
177 int maxStmt; /* The next maximum number of stmtList */
178 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000179 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh3c379b02010-04-07 19:31:59 +0000180 int nStep, nSort, nIndex; /* Statistics for most recent operation */
danc456a762017-06-22 16:51:16 +0000181 int nVMStep; /* Another statistic for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000182 int nTransaction; /* Number of nested [transaction] methods */
drh147ef392016-01-22 23:17:51 +0000183 int openFlags; /* Flags used to open. (SQLITE_OPEN_URI) */
danc431fd52011-06-27 16:55:50 +0000184#ifdef SQLITE_TEST
185 int bLegacyPrepare; /* True to use sqlite3_prepare() */
186#endif
drh98808ba2001-10-18 12:34:46 +0000187};
drh297ecf12001-04-05 15:57:13 +0000188
danielk1977b4e9af92007-05-01 17:49:49 +0000189struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000190 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000191 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000192 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000193 Tcl_Channel channel; /* Channel identifier */
194 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
195 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000196};
197
drhea678832008-12-10 19:26:22 +0000198/*
199** Compute a string length that is limited to what can be stored in
200** lower 30 bits of a 32-bit signed integer.
201*/
drh4f21c4a2008-12-10 22:15:00 +0000202static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000203 const char *z2 = z;
204 while( *z2 ){ z2++; }
205 return 0x3fffffff & (int)(z2 - z);
206}
drhea678832008-12-10 19:26:22 +0000207
208
danielk197732a0d8b2007-05-04 19:03:02 +0000209#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000210/*
danielk1977d04417962007-05-02 13:16:30 +0000211** Close all incrblob channels opened using database connection pDb.
212** This is called when shutting down the database connection.
213*/
214static void closeIncrblobChannels(SqliteDb *pDb){
215 IncrblobChannel *p;
216 IncrblobChannel *pNext;
217
218 for(p=pDb->pIncrblob; p; p=pNext){
219 pNext = p->pNext;
220
mistachkinb56660f2016-07-14 21:26:09 +0000221 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
danielk1977d04417962007-05-02 13:16:30 +0000222 ** which deletes the IncrblobChannel structure at *p. So do not
223 ** call Tcl_Free() here.
224 */
225 Tcl_UnregisterChannel(pDb->interp, p->channel);
226 }
227}
228
229/*
danielk1977b4e9af92007-05-01 17:49:49 +0000230** Close an incremental blob channel.
231*/
mistachkin7617e4a2016-07-28 17:11:20 +0000232static int SQLITE_TCLAPI incrblobClose(
233 ClientData instanceData,
234 Tcl_Interp *interp
235){
danielk1977b4e9af92007-05-01 17:49:49 +0000236 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000237 int rc = sqlite3_blob_close(p->pBlob);
238 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000239
240 /* Remove the channel from the SqliteDb.pIncrblob list. */
241 if( p->pNext ){
242 p->pNext->pPrev = p->pPrev;
243 }
244 if( p->pPrev ){
245 p->pPrev->pNext = p->pNext;
246 }
247 if( p->pDb->pIncrblob==p ){
248 p->pDb->pIncrblob = p->pNext;
249 }
250
danielk197792d4d7a2007-05-04 12:05:56 +0000251 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000252 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000253
254 if( rc!=SQLITE_OK ){
255 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
256 return TCL_ERROR;
257 }
danielk1977b4e9af92007-05-01 17:49:49 +0000258 return TCL_OK;
259}
260
261/*
262** Read data from an incremental blob channel.
263*/
mistachkin7617e4a2016-07-28 17:11:20 +0000264static int SQLITE_TCLAPI incrblobInput(
mistachkinb56660f2016-07-14 21:26:09 +0000265 ClientData instanceData,
266 char *buf,
danielk1977b4e9af92007-05-01 17:49:49 +0000267 int bufSize,
268 int *errorCodePtr
269){
270 IncrblobChannel *p = (IncrblobChannel *)instanceData;
271 int nRead = bufSize; /* Number of bytes to read */
272 int nBlob; /* Total size of the blob */
273 int rc; /* sqlite error code */
274
275 nBlob = sqlite3_blob_bytes(p->pBlob);
276 if( (p->iSeek+nRead)>nBlob ){
277 nRead = nBlob-p->iSeek;
278 }
279 if( nRead<=0 ){
280 return 0;
281 }
282
283 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
284 if( rc!=SQLITE_OK ){
285 *errorCodePtr = rc;
286 return -1;
287 }
288
289 p->iSeek += nRead;
290 return nRead;
291}
292
danielk1977d04417962007-05-02 13:16:30 +0000293/*
294** Write data to an incremental blob channel.
295*/
mistachkin7617e4a2016-07-28 17:11:20 +0000296static int SQLITE_TCLAPI incrblobOutput(
mistachkinb56660f2016-07-14 21:26:09 +0000297 ClientData instanceData,
298 CONST char *buf,
danielk1977b4e9af92007-05-01 17:49:49 +0000299 int toWrite,
300 int *errorCodePtr
301){
302 IncrblobChannel *p = (IncrblobChannel *)instanceData;
303 int nWrite = toWrite; /* Number of bytes to write */
304 int nBlob; /* Total size of the blob */
305 int rc; /* sqlite error code */
306
307 nBlob = sqlite3_blob_bytes(p->pBlob);
308 if( (p->iSeek+nWrite)>nBlob ){
309 *errorCodePtr = EINVAL;
310 return -1;
311 }
312 if( nWrite<=0 ){
313 return 0;
314 }
315
316 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
317 if( rc!=SQLITE_OK ){
318 *errorCodePtr = EIO;
319 return -1;
320 }
321
322 p->iSeek += nWrite;
323 return nWrite;
324}
325
326/*
327** Seek an incremental blob channel.
328*/
mistachkin7617e4a2016-07-28 17:11:20 +0000329static int SQLITE_TCLAPI incrblobSeek(
mistachkinb56660f2016-07-14 21:26:09 +0000330 ClientData instanceData,
danielk1977b4e9af92007-05-01 17:49:49 +0000331 long offset,
332 int seekMode,
333 int *errorCodePtr
334){
335 IncrblobChannel *p = (IncrblobChannel *)instanceData;
336
337 switch( seekMode ){
338 case SEEK_SET:
339 p->iSeek = offset;
340 break;
341 case SEEK_CUR:
342 p->iSeek += offset;
343 break;
344 case SEEK_END:
345 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
346 break;
347
348 default: assert(!"Bad seekMode");
349 }
350
351 return p->iSeek;
352}
353
354
mistachkin7617e4a2016-07-28 17:11:20 +0000355static void SQLITE_TCLAPI incrblobWatch(
356 ClientData instanceData,
357 int mode
358){
mistachkinb56660f2016-07-14 21:26:09 +0000359 /* NO-OP */
danielk1977b4e9af92007-05-01 17:49:49 +0000360}
mistachkin7617e4a2016-07-28 17:11:20 +0000361static int SQLITE_TCLAPI incrblobHandle(
362 ClientData instanceData,
363 int dir,
364 ClientData *hPtr
365){
danielk1977b4e9af92007-05-01 17:49:49 +0000366 return TCL_ERROR;
367}
368
369static Tcl_ChannelType IncrblobChannelType = {
370 "incrblob", /* typeName */
371 TCL_CHANNEL_VERSION_2, /* version */
372 incrblobClose, /* closeProc */
373 incrblobInput, /* inputProc */
374 incrblobOutput, /* outputProc */
375 incrblobSeek, /* seekProc */
376 0, /* setOptionProc */
377 0, /* getOptionProc */
378 incrblobWatch, /* watchProc (this is a no-op) */
379 incrblobHandle, /* getHandleProc (always returns error) */
380 0, /* close2Proc */
381 0, /* blockModeProc */
382 0, /* flushProc */
383 0, /* handlerProc */
384 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000385};
386
387/*
388** Create a new incrblob channel.
389*/
390static int createIncrblobChannel(
mistachkinb56660f2016-07-14 21:26:09 +0000391 Tcl_Interp *interp,
392 SqliteDb *pDb,
danielk1977b4e9af92007-05-01 17:49:49 +0000393 const char *zDb,
mistachkinb56660f2016-07-14 21:26:09 +0000394 const char *zTable,
395 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000396 sqlite_int64 iRow,
397 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000398){
399 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000400 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000401 sqlite3_blob *pBlob;
402 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000403 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000404
405 /* This variable is used to name the channels: "incrblob_[incr count]" */
406 static int count = 0;
407 char zChannel[64];
408
danielk19778cbadb02007-05-03 16:31:26 +0000409 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000410 if( rc!=SQLITE_OK ){
411 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
412 return TCL_ERROR;
413 }
414
415 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
416 p->iSeek = 0;
417 p->pBlob = pBlob;
418
drh5bb3eb92007-05-04 13:15:55 +0000419 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000420 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
421 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000422
danielk1977d04417962007-05-02 13:16:30 +0000423 /* Link the new channel into the SqliteDb.pIncrblob list. */
424 p->pNext = pDb->pIncrblob;
425 p->pPrev = 0;
426 if( p->pNext ){
427 p->pNext->pPrev = p;
428 }
429 pDb->pIncrblob = p;
430 p->pDb = pDb;
431
432 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000433 return TCL_OK;
434}
danielk197732a0d8b2007-05-04 19:03:02 +0000435#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
436 #define closeIncrblobChannels(pDb)
437#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000438
drh6d313162000-09-21 13:01:35 +0000439/*
drhd1e47332005-06-26 17:55:33 +0000440** Look at the script prefix in pCmd. We will be executing this script
441** after first appending one or more arguments. This routine analyzes
442** the script to see if it is safe to use Tcl_EvalObjv() on the script
443** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
444** faster.
445**
446** Scripts that are safe to use with Tcl_EvalObjv() consists of a
447** command name followed by zero or more arguments with no [...] or $
448** or {...} or ; to be seen anywhere. Most callback scripts consist
449** of just a single procedure name and they meet this requirement.
450*/
451static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
452 /* We could try to do something with Tcl_Parse(). But we will instead
453 ** just do a search for forbidden characters. If any of the forbidden
454 ** characters appear in pCmd, we will report the string as unsafe.
455 */
456 const char *z;
457 int n;
458 z = Tcl_GetStringFromObj(pCmd, &n);
459 while( n-- > 0 ){
460 int c = *(z++);
461 if( c=='$' || c=='[' || c==';' ) return 0;
462 }
463 return 1;
464}
465
466/*
467** Find an SqlFunc structure with the given name. Or create a new
468** one if an existing one cannot be found. Return a pointer to the
469** structure.
470*/
471static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
472 SqlFunc *p, *pNew;
drh0425f182013-11-26 16:48:04 +0000473 int nName = strlen30(zName);
474 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
drhd1e47332005-06-26 17:55:33 +0000475 pNew->zName = (char*)&pNew[1];
drh0425f182013-11-26 16:48:04 +0000476 memcpy(pNew->zName, zName, nName+1);
mistachkinb56660f2016-07-14 21:26:09 +0000477 for(p=pDb->pFunc; p; p=p->pNext){
drh0425f182013-11-26 16:48:04 +0000478 if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
drhd1e47332005-06-26 17:55:33 +0000479 Tcl_Free((char*)pNew);
480 return p;
481 }
482 }
483 pNew->interp = pDb->interp;
drhc45e6712012-10-03 11:02:33 +0000484 pNew->pDb = pDb;
drhd1e47332005-06-26 17:55:33 +0000485 pNew->pScript = 0;
486 pNew->pNext = pDb->pFunc;
487 pDb->pFunc = pNew;
488 return pNew;
489}
490
491/*
danc431fd52011-06-27 16:55:50 +0000492** Free a single SqlPreparedStmt object.
493*/
494static void dbFreeStmt(SqlPreparedStmt *pStmt){
495#ifdef SQLITE_TEST
496 if( sqlite3_sql(pStmt->pStmt)==0 ){
497 Tcl_Free((char *)pStmt->zSql);
498 }
499#endif
500 sqlite3_finalize(pStmt->pStmt);
501 Tcl_Free((char *)pStmt);
502}
503
504/*
drhfb7e7652005-01-24 00:28:42 +0000505** Finalize and free a list of prepared statements
506*/
danc431fd52011-06-27 16:55:50 +0000507static void flushStmtCache(SqliteDb *pDb){
drhfb7e7652005-01-24 00:28:42 +0000508 SqlPreparedStmt *pPreStmt;
danc431fd52011-06-27 16:55:50 +0000509 SqlPreparedStmt *pNext;
drhfb7e7652005-01-24 00:28:42 +0000510
danc431fd52011-06-27 16:55:50 +0000511 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
512 pNext = pPreStmt->pNext;
513 dbFreeStmt(pPreStmt);
drhfb7e7652005-01-24 00:28:42 +0000514 }
515 pDb->nStmt = 0;
516 pDb->stmtLast = 0;
danc431fd52011-06-27 16:55:50 +0000517 pDb->stmtList = 0;
drhfb7e7652005-01-24 00:28:42 +0000518}
519
520/*
drh895d7472004-08-20 16:02:39 +0000521** TCL calls this procedure when an sqlite3 database command is
522** deleted.
drh75897232000-05-29 14:26:00 +0000523*/
mistachkin7617e4a2016-07-28 17:11:20 +0000524static void SQLITE_TCLAPI DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000525 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000526 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000527 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000528 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000529 while( pDb->pFunc ){
530 SqlFunc *pFunc = pDb->pFunc;
531 pDb->pFunc = pFunc->pNext;
drhc45e6712012-10-03 11:02:33 +0000532 assert( pFunc->pDb==pDb );
drhd1e47332005-06-26 17:55:33 +0000533 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000534 Tcl_Free((char*)pFunc);
535 }
danielk19770202b292004-06-09 09:55:16 +0000536 while( pDb->pCollate ){
537 SqlCollate *pCollate = pDb->pCollate;
538 pDb->pCollate = pCollate->pNext;
539 Tcl_Free((char*)pCollate);
540 }
drhbec3f402000-08-04 13:49:02 +0000541 if( pDb->zBusy ){
542 Tcl_Free(pDb->zBusy);
543 }
drhb5a20d32003-04-23 12:25:23 +0000544 if( pDb->zTrace ){
545 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000546 }
mistachkinb56660f2016-07-14 21:26:09 +0000547 if( pDb->zTraceV2 ){
548 Tcl_Free(pDb->zTraceV2);
549 }
drh19e2d372005-08-29 23:00:03 +0000550 if( pDb->zProfile ){
551 Tcl_Free(pDb->zProfile);
552 }
drhc06ede12019-02-28 17:29:19 +0000553 if( pDb->zBindFallback ){
554 Tcl_Free(pDb->zBindFallback);
555 }
drhe22a3342003-04-22 20:30:37 +0000556 if( pDb->zAuth ){
557 Tcl_Free(pDb->zAuth);
558 }
danielk197755c45f22005-04-03 23:54:43 +0000559 if( pDb->zNull ){
560 Tcl_Free(pDb->zNull);
561 }
danielk197794eb6a12005-12-15 15:22:08 +0000562 if( pDb->pUpdateHook ){
563 Tcl_DecrRefCount(pDb->pUpdateHook);
564 }
dan46c47d42011-03-01 18:42:07 +0000565 if( pDb->pPreUpdateHook ){
566 Tcl_DecrRefCount(pDb->pPreUpdateHook);
567 }
danielk197771fd80b2005-12-16 06:54:01 +0000568 if( pDb->pRollbackHook ){
569 Tcl_DecrRefCount(pDb->pRollbackHook);
570 }
drh5def0842010-05-05 20:00:25 +0000571 if( pDb->pWalHook ){
572 Tcl_DecrRefCount(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000573 }
danielk197794eb6a12005-12-15 15:22:08 +0000574 if( pDb->pCollateNeeded ){
575 Tcl_DecrRefCount(pDb->pCollateNeeded);
576 }
drhbec3f402000-08-04 13:49:02 +0000577 Tcl_Free((char*)pDb);
578}
579
580/*
581** This routine is called when a database file is locked while trying
582** to execute SQL.
583*/
danielk19772a764eb2004-06-12 01:43:26 +0000584static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000585 SqliteDb *pDb = (SqliteDb*)cd;
586 int rc;
587 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000588
drh5bb3eb92007-05-04 13:15:55 +0000589 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000590 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000591 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
592 return 0;
593 }
594 return 1;
drh75897232000-05-29 14:26:00 +0000595}
596
drh26e4a8b2008-05-01 17:16:52 +0000597#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000598/*
danielk1977348bb5d2003-10-18 09:37:26 +0000599** This routine is invoked as the 'progress callback' for the database.
600*/
601static int DbProgressHandler(void *cd){
602 SqliteDb *pDb = (SqliteDb*)cd;
603 int rc;
604
605 assert( pDb->zProgress );
606 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
607 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
608 return 1;
609 }
610 return 0;
611}
drh26e4a8b2008-05-01 17:16:52 +0000612#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000613
drh2eb22af2016-09-10 19:51:40 +0000614#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
615 !defined(SQLITE_OMIT_DEPRECATED)
danielk1977348bb5d2003-10-18 09:37:26 +0000616/*
drhb5a20d32003-04-23 12:25:23 +0000617** This routine is called by the SQLite trace handler whenever a new
618** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000619*/
drhb5a20d32003-04-23 12:25:23 +0000620static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000621 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000622 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000623
drhb5a20d32003-04-23 12:25:23 +0000624 Tcl_DStringInit(&str);
625 Tcl_DStringAppend(&str, pDb->zTrace, -1);
626 Tcl_DStringAppendElement(&str, zSql);
627 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
628 Tcl_DStringFree(&str);
629 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000630}
drhd1167392006-01-23 13:00:35 +0000631#endif
drh0d1a6432003-04-03 15:46:04 +0000632
drhd1167392006-01-23 13:00:35 +0000633#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000634/*
mistachkinb56660f2016-07-14 21:26:09 +0000635** This routine is called by the SQLite trace_v2 handler whenever a new
636** supported event is generated. Unsupported event types are ignored.
637** The TCL script in pDb->zTraceV2 is executed, with the arguments for
638** the event appended to it (as list elements).
639*/
640static int DbTraceV2Handler(
641 unsigned type, /* One of the SQLITE_TRACE_* event types. */
642 void *cd, /* The original context data pointer. */
643 void *pd, /* Primary event data, depends on event type. */
644 void *xd /* Extra event data, depends on event type. */
645){
646 SqliteDb *pDb = (SqliteDb*)cd;
647 Tcl_Obj *pCmd;
648
649 switch( type ){
650 case SQLITE_TRACE_STMT: {
651 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
652 char *zSql = (char *)xd;
653
654 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
655 Tcl_IncrRefCount(pCmd);
656 Tcl_ListObjAppendElement(pDb->interp, pCmd,
657 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
658 Tcl_ListObjAppendElement(pDb->interp, pCmd,
659 Tcl_NewStringObj(zSql, -1));
660 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
661 Tcl_DecrRefCount(pCmd);
662 Tcl_ResetResult(pDb->interp);
663 break;
664 }
665 case SQLITE_TRACE_PROFILE: {
666 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
drhffdab722018-03-10 20:25:08 +0000667 sqlite3_int64 ns = *(sqlite3_int64*)xd;
mistachkinb56660f2016-07-14 21:26:09 +0000668
669 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
670 Tcl_IncrRefCount(pCmd);
671 Tcl_ListObjAppendElement(pDb->interp, pCmd,
672 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
673 Tcl_ListObjAppendElement(pDb->interp, pCmd,
674 Tcl_NewWideIntObj((Tcl_WideInt)ns));
675 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
676 Tcl_DecrRefCount(pCmd);
677 Tcl_ResetResult(pDb->interp);
678 break;
679 }
680 case SQLITE_TRACE_ROW: {
681 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
682
683 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
684 Tcl_IncrRefCount(pCmd);
685 Tcl_ListObjAppendElement(pDb->interp, pCmd,
686 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
687 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
688 Tcl_DecrRefCount(pCmd);
689 Tcl_ResetResult(pDb->interp);
690 break;
691 }
692 case SQLITE_TRACE_CLOSE: {
693 sqlite3 *db = (sqlite3 *)pd;
694
695 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
696 Tcl_IncrRefCount(pCmd);
697 Tcl_ListObjAppendElement(pDb->interp, pCmd,
698 Tcl_NewWideIntObj((Tcl_WideInt)db));
699 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
700 Tcl_DecrRefCount(pCmd);
701 Tcl_ResetResult(pDb->interp);
702 break;
703 }
704 }
705 return SQLITE_OK;
706}
707#endif
708
drh2eb22af2016-09-10 19:51:40 +0000709#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
710 !defined(SQLITE_OMIT_DEPRECATED)
mistachkinb56660f2016-07-14 21:26:09 +0000711/*
drh19e2d372005-08-29 23:00:03 +0000712** This routine is called by the SQLite profile handler after a statement
713** SQL has executed. The TCL script in pDb->zProfile is evaluated.
714*/
715static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
716 SqliteDb *pDb = (SqliteDb*)cd;
717 Tcl_DString str;
718 char zTm[100];
719
720 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
721 Tcl_DStringInit(&str);
722 Tcl_DStringAppend(&str, pDb->zProfile, -1);
723 Tcl_DStringAppendElement(&str, zSql);
724 Tcl_DStringAppendElement(&str, zTm);
725 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
726 Tcl_DStringFree(&str);
727 Tcl_ResetResult(pDb->interp);
728}
drhd1167392006-01-23 13:00:35 +0000729#endif
drh19e2d372005-08-29 23:00:03 +0000730
731/*
drhaa940ea2004-01-15 02:44:03 +0000732** This routine is called when a transaction is committed. The
733** TCL script in pDb->zCommit is executed. If it returns non-zero or
734** if it throws an exception, the transaction is rolled back instead
735** of being committed.
736*/
737static int DbCommitHandler(void *cd){
738 SqliteDb *pDb = (SqliteDb*)cd;
739 int rc;
740
741 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
742 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
743 return 1;
744 }
745 return 0;
746}
747
danielk197771fd80b2005-12-16 06:54:01 +0000748static void DbRollbackHandler(void *clientData){
749 SqliteDb *pDb = (SqliteDb*)clientData;
750 assert(pDb->pRollbackHook);
751 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
752 Tcl_BackgroundError(pDb->interp);
753 }
754}
755
drh5def0842010-05-05 20:00:25 +0000756/*
757** This procedure handles wal_hook callbacks.
758*/
759static int DbWalHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000760 void *clientData,
761 sqlite3 *db,
762 const char *zDb,
dan8d22a172010-04-19 18:03:51 +0000763 int nEntry
764){
drh5def0842010-05-05 20:00:25 +0000765 int ret = SQLITE_OK;
dan8d22a172010-04-19 18:03:51 +0000766 Tcl_Obj *p;
767 SqliteDb *pDb = (SqliteDb*)clientData;
768 Tcl_Interp *interp = pDb->interp;
drh5def0842010-05-05 20:00:25 +0000769 assert(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000770
dan6e45e0c2014-12-10 20:29:49 +0000771 assert( db==pDb->db );
drh5def0842010-05-05 20:00:25 +0000772 p = Tcl_DuplicateObj(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000773 Tcl_IncrRefCount(p);
774 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
775 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
mistachkinb56660f2016-07-14 21:26:09 +0000776 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
dan8d22a172010-04-19 18:03:51 +0000777 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
778 ){
779 Tcl_BackgroundError(interp);
780 }
781 Tcl_DecrRefCount(p);
782
783 return ret;
784}
785
drhbcf4f482009-03-27 12:44:35 +0000786#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000787static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
788 char zBuf[64];
drh65545b52015-01-19 00:35:53 +0000789 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
danielk1977404ca072009-03-16 13:19:36 +0000790 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
drh65545b52015-01-19 00:35:53 +0000791 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
danielk1977404ca072009-03-16 13:19:36 +0000792 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
793}
794#else
drhbcf4f482009-03-27 12:44:35 +0000795# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000796#endif
797
drh69910da2009-03-27 12:32:54 +0000798#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000799static void DbUnlockNotify(void **apArg, int nArg){
800 int i;
801 for(i=0; i<nArg; i++){
802 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
803 SqliteDb *pDb = (SqliteDb *)apArg[i];
804 setTestUnlockNotifyVars(pDb->interp, i, nArg);
805 assert( pDb->pUnlockNotify);
806 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
807 Tcl_DecrRefCount(pDb->pUnlockNotify);
808 pDb->pUnlockNotify = 0;
809 }
810}
drh69910da2009-03-27 12:32:54 +0000811#endif
danielk1977404ca072009-03-16 13:19:36 +0000812
drh9b1c62d2011-03-30 21:04:43 +0000813#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +0000814/*
815** Pre-update hook callback.
816*/
817static void DbPreUpdateHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000818 void *p,
dan46c47d42011-03-01 18:42:07 +0000819 sqlite3 *db,
820 int op,
mistachkinb56660f2016-07-14 21:26:09 +0000821 const char *zDb,
822 const char *zTbl,
dan46c47d42011-03-01 18:42:07 +0000823 sqlite_int64 iKey1,
824 sqlite_int64 iKey2
825){
826 SqliteDb *pDb = (SqliteDb *)p;
827 Tcl_Obj *pCmd;
828 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
829
830 assert( (SQLITE_DELETE-1)/9 == 0 );
831 assert( (SQLITE_INSERT-1)/9 == 1 );
832 assert( (SQLITE_UPDATE-1)/9 == 2 );
833 assert( pDb->pPreUpdateHook );
834 assert( db==pDb->db );
835 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
836
837 pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
838 Tcl_IncrRefCount(pCmd);
839 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
840 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
841 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
842 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
843 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
844 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
845 Tcl_DecrRefCount(pCmd);
846}
drh9b1c62d2011-03-30 21:04:43 +0000847#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +0000848
danielk197794eb6a12005-12-15 15:22:08 +0000849static void DbUpdateHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000850 void *p,
danielk197794eb6a12005-12-15 15:22:08 +0000851 int op,
mistachkinb56660f2016-07-14 21:26:09 +0000852 const char *zDb,
853 const char *zTbl,
danielk197794eb6a12005-12-15 15:22:08 +0000854 sqlite_int64 rowid
855){
856 SqliteDb *pDb = (SqliteDb *)p;
857 Tcl_Obj *pCmd;
dan46c47d42011-03-01 18:42:07 +0000858 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
859
860 assert( (SQLITE_DELETE-1)/9 == 0 );
861 assert( (SQLITE_INSERT-1)/9 == 1 );
862 assert( (SQLITE_UPDATE-1)/9 == 2 );
danielk197794eb6a12005-12-15 15:22:08 +0000863
864 assert( pDb->pUpdateHook );
865 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
866
867 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
868 Tcl_IncrRefCount(pCmd);
dan46c47d42011-03-01 18:42:07 +0000869 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
danielk197794eb6a12005-12-15 15:22:08 +0000870 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
871 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
872 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
873 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
drhefdde162010-10-27 15:36:21 +0000874 Tcl_DecrRefCount(pCmd);
danielk197794eb6a12005-12-15 15:22:08 +0000875}
876
danielk19777cedc8d2004-06-10 10:50:08 +0000877static void tclCollateNeeded(
878 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000879 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000880 int enc,
881 const char *zName
882){
883 SqliteDb *pDb = (SqliteDb *)pCtx;
884 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
885 Tcl_IncrRefCount(pScript);
886 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
887 Tcl_EvalObjEx(pDb->interp, pScript, 0);
888 Tcl_DecrRefCount(pScript);
889}
890
drhaa940ea2004-01-15 02:44:03 +0000891/*
danielk19770202b292004-06-09 09:55:16 +0000892** This routine is called to evaluate an SQL collation function implemented
893** using TCL script.
894*/
895static int tclSqlCollate(
896 void *pCtx,
897 int nA,
898 const void *zA,
899 int nB,
900 const void *zB
901){
902 SqlCollate *p = (SqlCollate *)pCtx;
903 Tcl_Obj *pCmd;
904
905 pCmd = Tcl_NewStringObj(p->zScript, -1);
906 Tcl_IncrRefCount(pCmd);
907 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
908 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000909 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000910 Tcl_DecrRefCount(pCmd);
911 return (atoi(Tcl_GetStringResult(p->interp)));
912}
913
914/*
drhcabb0812002-09-14 13:47:32 +0000915** This routine is called to evaluate an SQL function implemented
916** using TCL script.
917*/
drhfb7e7652005-01-24 00:28:42 +0000918static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000919 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000920 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000921 int i;
922 int rc;
923
drhd1e47332005-06-26 17:55:33 +0000924 if( argc==0 ){
925 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
926 ** script object directly. This allows the TCL compiler to generate
927 ** bytecode for the command on the first invocation and thus make
928 ** subsequent invocations much faster. */
929 pCmd = p->pScript;
930 Tcl_IncrRefCount(pCmd);
931 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
932 Tcl_DecrRefCount(pCmd);
933 }else{
934 /* If there are arguments to the function, make a shallow copy of the
935 ** script object, lappend the arguments, then evaluate the copy.
936 **
peter.d.reid60ec9142014-09-06 16:39:46 +0000937 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
mistachkinb56660f2016-07-14 21:26:09 +0000938 ** The new Tcl_Obj contains pointers to the original list elements.
drhd1e47332005-06-26 17:55:33 +0000939 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
940 ** of the list to tclCmdNameType, that alternate representation will
941 ** be preserved and reused on the next invocation.
942 */
943 Tcl_Obj **aArg;
944 int nArg;
945 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
mistachkinb56660f2016-07-14 21:26:09 +0000946 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhd1e47332005-06-26 17:55:33 +0000947 return;
mistachkinb56660f2016-07-14 21:26:09 +0000948 }
drhd1e47332005-06-26 17:55:33 +0000949 pCmd = Tcl_NewListObj(nArg, aArg);
950 Tcl_IncrRefCount(pCmd);
951 for(i=0; i<argc; i++){
952 sqlite3_value *pIn = argv[i];
953 Tcl_Obj *pVal;
mistachkinb56660f2016-07-14 21:26:09 +0000954
drhd1e47332005-06-26 17:55:33 +0000955 /* Set pVal to contain the i'th column of this row. */
956 switch( sqlite3_value_type(pIn) ){
957 case SQLITE_BLOB: {
958 int bytes = sqlite3_value_bytes(pIn);
959 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
960 break;
961 }
962 case SQLITE_INTEGER: {
963 sqlite_int64 v = sqlite3_value_int64(pIn);
964 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +0000965 pVal = Tcl_NewIntObj((int)v);
drhd1e47332005-06-26 17:55:33 +0000966 }else{
967 pVal = Tcl_NewWideIntObj(v);
968 }
969 break;
970 }
971 case SQLITE_FLOAT: {
972 double r = sqlite3_value_double(pIn);
973 pVal = Tcl_NewDoubleObj(r);
974 break;
975 }
976 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +0000977 pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
drhd1e47332005-06-26 17:55:33 +0000978 break;
979 }
980 default: {
981 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000982 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000983 break;
984 }
985 }
986 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
987 if( rc ){
988 Tcl_DecrRefCount(pCmd);
mistachkinb56660f2016-07-14 21:26:09 +0000989 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhd1e47332005-06-26 17:55:33 +0000990 return;
991 }
danielk197751ad0ec2004-05-24 12:39:02 +0000992 }
drhd1e47332005-06-26 17:55:33 +0000993 if( !p->useEvalObjv ){
994 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
995 ** is a list without a string representation. To prevent this from
996 ** happening, make sure pCmd has a valid string representation */
997 Tcl_GetString(pCmd);
998 }
999 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
1000 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +00001001 }
danielk1977562e8d32005-05-20 09:40:55 +00001002
drhc7f269d2005-05-05 10:30:29 +00001003 if( rc && rc!=TCL_RETURN ){
mistachkinb56660f2016-07-14 21:26:09 +00001004 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +00001005 }else{
drhc7f269d2005-05-05 10:30:29 +00001006 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
1007 int n;
1008 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +00001009 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +00001010 char c = zType[0];
dan89d24932019-02-27 16:38:19 +00001011 int eType = p->eType;
1012
1013 if( eType==SQLITE_NULL ){
1014 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
1015 /* Only return a BLOB type if the Tcl variable is a bytearray and
1016 ** has no string representation. */
1017 eType = SQLITE_BLOB;
1018 }else if( (c=='b' && strcmp(zType,"boolean")==0)
1019 || (c=='w' && strcmp(zType,"wideInt")==0)
1020 || (c=='i' && strcmp(zType,"int")==0)
1021 ){
1022 eType = SQLITE_INTEGER;
1023 }else if( c=='d' && strcmp(zType,"double")==0 ){
1024 eType = SQLITE_FLOAT;
1025 }else{
1026 eType = SQLITE_TEXT;
1027 }
drhc7f269d2005-05-05 10:30:29 +00001028 }
dan89d24932019-02-27 16:38:19 +00001029
1030 switch( eType ){
1031 case SQLITE_BLOB: {
1032 data = Tcl_GetByteArrayFromObj(pVar, &n);
1033 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
1034 break;
1035 }
1036 case SQLITE_INTEGER: {
1037 Tcl_WideInt v;
1038 if( TCL_OK==Tcl_GetWideIntFromObj(0, pVar, &v) ){
1039 sqlite3_result_int64(context, v);
1040 break;
1041 }
1042 /* fall-through */
1043 }
1044 case SQLITE_FLOAT: {
1045 double r;
1046 if( TCL_OK==Tcl_GetDoubleFromObj(0, pVar, &r) ){
1047 sqlite3_result_double(context, r);
1048 break;
1049 }
1050 /* fall-through */
1051 }
1052 default: {
1053 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1054 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
1055 break;
1056 }
1057 }
1058
drhcabb0812002-09-14 13:47:32 +00001059 }
1060}
drh895d7472004-08-20 16:02:39 +00001061
drhe22a3342003-04-22 20:30:37 +00001062#ifndef SQLITE_OMIT_AUTHORIZATION
1063/*
1064** This is the authentication function. It appends the authentication
1065** type code and the two arguments to zCmd[] then invokes the result
1066** on the interpreter. The reply is examined to determine if the
1067** authentication fails or succeeds.
1068*/
1069static int auth_callback(
1070 void *pArg,
1071 int code,
1072 const char *zArg1,
1073 const char *zArg2,
1074 const char *zArg3,
1075 const char *zArg4
drh32c6a482014-09-11 13:44:52 +00001076#ifdef SQLITE_USER_AUTHENTICATION
1077 ,const char *zArg5
1078#endif
drhe22a3342003-04-22 20:30:37 +00001079){
mistachkin6ef5e122014-01-24 17:03:55 +00001080 const char *zCode;
drhe22a3342003-04-22 20:30:37 +00001081 Tcl_DString str;
1082 int rc;
1083 const char *zReply;
drh94189212017-05-11 13:43:57 +00001084 /* EVIDENCE-OF: R-38590-62769 The first parameter to the authorizer
1085 ** callback is a copy of the third parameter to the
1086 ** sqlite3_set_authorizer() interface.
1087 */
drhe22a3342003-04-22 20:30:37 +00001088 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +00001089 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +00001090
drh94189212017-05-11 13:43:57 +00001091 /* EVIDENCE-OF: R-56518-44310 The second parameter to the callback is an
1092 ** integer action code that specifies the particular action to be
1093 ** authorized. */
drhe22a3342003-04-22 20:30:37 +00001094 switch( code ){
1095 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
1096 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
1097 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
1098 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
1099 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
1100 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
1101 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
1102 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
1103 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
1104 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
1105 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
1106 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
1107 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
1108 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
1109 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
1110 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
1111 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
1112 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
1113 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
1114 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
1115 case SQLITE_READ : zCode="SQLITE_READ"; break;
1116 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
1117 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
1118 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +00001119 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
1120 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +00001121 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +00001122 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +00001123 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +00001124 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
1125 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +00001126 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +00001127 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drh65a2aaa2014-01-16 22:40:02 +00001128 case SQLITE_RECURSIVE : zCode="SQLITE_RECURSIVE"; break;
drhe22a3342003-04-22 20:30:37 +00001129 default : zCode="????"; break;
1130 }
1131 Tcl_DStringInit(&str);
1132 Tcl_DStringAppend(&str, pDb->zAuth, -1);
1133 Tcl_DStringAppendElement(&str, zCode);
1134 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
1135 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
1136 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
1137 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
drh32c6a482014-09-11 13:44:52 +00001138#ifdef SQLITE_USER_AUTHENTICATION
1139 Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
mistachkinb56660f2016-07-14 21:26:09 +00001140#endif
drhe22a3342003-04-22 20:30:37 +00001141 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
1142 Tcl_DStringFree(&str);
drhb07028f2011-10-14 21:49:18 +00001143 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
drhe22a3342003-04-22 20:30:37 +00001144 if( strcmp(zReply,"SQLITE_OK")==0 ){
1145 rc = SQLITE_OK;
1146 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
1147 rc = SQLITE_DENY;
1148 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
1149 rc = SQLITE_IGNORE;
1150 }else{
1151 rc = 999;
1152 }
1153 return rc;
1154}
1155#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +00001156
1157/*
tpoindex1067fe12004-12-17 15:41:11 +00001158** This routine reads a line of text from FILE in, stores
1159** the text in memory obtained from malloc() and returns a pointer
1160** to the text. NULL is returned at end of file, or if malloc()
1161** fails.
1162**
1163** The interface is like "readline" but no command-line editing
1164** is done.
1165**
1166** copied from shell.c from '.import' command
1167*/
1168static char *local_getline(char *zPrompt, FILE *in){
1169 char *zLine;
1170 int nLine;
1171 int n;
tpoindex1067fe12004-12-17 15:41:11 +00001172
1173 nLine = 100;
1174 zLine = malloc( nLine );
1175 if( zLine==0 ) return 0;
1176 n = 0;
drhb07028f2011-10-14 21:49:18 +00001177 while( 1 ){
tpoindex1067fe12004-12-17 15:41:11 +00001178 if( n+100>nLine ){
1179 nLine = nLine*2 + 100;
1180 zLine = realloc(zLine, nLine);
1181 if( zLine==0 ) return 0;
1182 }
1183 if( fgets(&zLine[n], nLine - n, in)==0 ){
1184 if( n==0 ){
1185 free(zLine);
1186 return 0;
1187 }
1188 zLine[n] = 0;
tpoindex1067fe12004-12-17 15:41:11 +00001189 break;
1190 }
1191 while( zLine[n] ){ n++; }
1192 if( n>0 && zLine[n-1]=='\n' ){
1193 n--;
1194 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +00001195 break;
tpoindex1067fe12004-12-17 15:41:11 +00001196 }
1197 }
1198 zLine = realloc( zLine, n+1 );
1199 return zLine;
1200}
1201
danielk19778e556522007-11-13 10:30:24 +00001202
1203/*
dan4a4c11a2009-10-06 14:59:02 +00001204** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +00001205**
dan4a4c11a2009-10-06 14:59:02 +00001206** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +00001207**
dan4a4c11a2009-10-06 14:59:02 +00001208** It is invoked after evaluating the script SCRIPT to commit or rollback
1209** the transaction or savepoint opened by the [transaction] command.
1210*/
mistachkina121cc72016-07-28 18:06:52 +00001211static int SQLITE_TCLAPI DbTransPostCmd(
dan4a4c11a2009-10-06 14:59:02 +00001212 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1213 Tcl_Interp *interp, /* Tcl interpreter */
1214 int result /* Result of evaluating SCRIPT */
1215){
mistachkin6ef5e122014-01-24 17:03:55 +00001216 static const char *const azEnd[] = {
dan4a4c11a2009-10-06 14:59:02 +00001217 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1218 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1219 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1220 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1221 };
1222 SqliteDb *pDb = (SqliteDb*)data[0];
1223 int rc = result;
1224 const char *zEnd;
1225
1226 pDb->nTransaction--;
1227 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1228
1229 pDb->disableAuth++;
1230 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1231 /* This is a tricky scenario to handle. The most likely cause of an
mistachkinb56660f2016-07-14 21:26:09 +00001232 ** error is that the exec() above was an attempt to commit the
dan4a4c11a2009-10-06 14:59:02 +00001233 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
mistachkin48864df2013-03-21 21:20:32 +00001234 ** that an IO-error has occurred. In either case, throw a Tcl exception
dan4a4c11a2009-10-06 14:59:02 +00001235 ** and try to rollback the transaction.
1236 **
mistachkinb56660f2016-07-14 21:26:09 +00001237 ** But it could also be that the user executed one or more BEGIN,
dan4a4c11a2009-10-06 14:59:02 +00001238 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1239 ** this method's logic. Not clear how this would be best handled.
1240 */
1241 if( rc!=TCL_ERROR ){
drha198f2b2014-02-07 19:26:13 +00001242 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
dan4a4c11a2009-10-06 14:59:02 +00001243 rc = TCL_ERROR;
1244 }
1245 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1246 }
1247 pDb->disableAuth--;
1248
1249 return rc;
1250}
1251
1252/*
danc431fd52011-06-27 16:55:50 +00001253** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1254** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1255** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
mistachkinb56660f2016-07-14 21:26:09 +00001256** on whether or not the [db_use_legacy_prepare] command has been used to
danc431fd52011-06-27 16:55:50 +00001257** configure the connection.
1258*/
1259static int dbPrepare(
1260 SqliteDb *pDb, /* Database object */
1261 const char *zSql, /* SQL to compile */
1262 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1263 const char **pzOut /* OUT: Pointer to next SQL statement */
1264){
drh2c2f3922017-06-01 00:54:35 +00001265 unsigned int prepFlags = 0;
danc431fd52011-06-27 16:55:50 +00001266#ifdef SQLITE_TEST
1267 if( pDb->bLegacyPrepare ){
1268 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1269 }
1270#endif
drh2c2f3922017-06-01 00:54:35 +00001271 /* If the statement cache is large, use the SQLITE_PREPARE_PERSISTENT
1272 ** flags, which uses less lookaside memory. But if the cache is small,
1273 ** omit that flag to make full use of lookaside */
1274 if( pDb->maxStmt>5 ) prepFlags = SQLITE_PREPARE_PERSISTENT;
1275
1276 return sqlite3_prepare_v3(pDb->db, zSql, -1, prepFlags, ppStmt, pzOut);
danc431fd52011-06-27 16:55:50 +00001277}
1278
1279/*
dan4a4c11a2009-10-06 14:59:02 +00001280** Search the cache for a prepared-statement object that implements the
1281** first SQL statement in the buffer pointed to by parameter zIn. If
1282** no such prepared-statement can be found, allocate and prepare a new
1283** one. In either case, bind the current values of the relevant Tcl
1284** variables to any $var, :var or @var variables in the statement. Before
1285** returning, set *ppPreStmt to point to the prepared-statement object.
1286**
1287** Output parameter *pzOut is set to point to the next SQL statement in
1288** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1289** next statement.
1290**
1291** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1292** and an error message loaded into interpreter pDb->interp.
1293*/
1294static int dbPrepareAndBind(
1295 SqliteDb *pDb, /* Database object */
1296 char const *zIn, /* SQL to compile */
1297 char const **pzOut, /* OUT: Pointer to next SQL statement */
1298 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1299){
1300 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
mistachkin7bb22ac2015-01-12 19:59:12 +00001301 sqlite3_stmt *pStmt = 0; /* Prepared statement object */
dan4a4c11a2009-10-06 14:59:02 +00001302 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1303 int nSql; /* Length of zSql in bytes */
mistachkin7bb22ac2015-01-12 19:59:12 +00001304 int nVar = 0; /* Number of variables in statement */
dan4a4c11a2009-10-06 14:59:02 +00001305 int iParm = 0; /* Next free entry in apParm */
drh0425f182013-11-26 16:48:04 +00001306 char c;
dan4a4c11a2009-10-06 14:59:02 +00001307 int i;
drhc06ede12019-02-28 17:29:19 +00001308 int needResultReset = 0; /* Need to invoke Tcl_ResetResult() */
1309 int rc = SQLITE_OK; /* Value to return */
dan4a4c11a2009-10-06 14:59:02 +00001310 Tcl_Interp *interp = pDb->interp;
1311
1312 *ppPreStmt = 0;
1313
1314 /* Trim spaces from the start of zSql and calculate the remaining length. */
drh0425f182013-11-26 16:48:04 +00001315 while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
dan4a4c11a2009-10-06 14:59:02 +00001316 nSql = strlen30(zSql);
1317
1318 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1319 int n = pPreStmt->nSql;
mistachkinb56660f2016-07-14 21:26:09 +00001320 if( nSql>=n
dan4a4c11a2009-10-06 14:59:02 +00001321 && memcmp(pPreStmt->zSql, zSql, n)==0
1322 && (zSql[n]==0 || zSql[n-1]==';')
1323 ){
1324 pStmt = pPreStmt->pStmt;
1325 *pzOut = &zSql[pPreStmt->nSql];
1326
1327 /* When a prepared statement is found, unlink it from the
1328 ** cache list. It will later be added back to the beginning
1329 ** of the cache list in order to implement LRU replacement.
1330 */
1331 if( pPreStmt->pPrev ){
1332 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1333 }else{
1334 pDb->stmtList = pPreStmt->pNext;
1335 }
1336 if( pPreStmt->pNext ){
1337 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1338 }else{
1339 pDb->stmtLast = pPreStmt->pPrev;
1340 }
1341 pDb->nStmt--;
1342 nVar = sqlite3_bind_parameter_count(pStmt);
1343 break;
1344 }
1345 }
mistachkinb56660f2016-07-14 21:26:09 +00001346
dan4a4c11a2009-10-06 14:59:02 +00001347 /* If no prepared statement was found. Compile the SQL text. Also allocate
1348 ** a new SqlPreparedStmt structure. */
1349 if( pPreStmt==0 ){
1350 int nByte;
1351
danc431fd52011-06-27 16:55:50 +00001352 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
drhc45e6712012-10-03 11:02:33 +00001353 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001354 return TCL_ERROR;
1355 }
1356 if( pStmt==0 ){
1357 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1358 /* A compile-time error in the statement. */
drhc45e6712012-10-03 11:02:33 +00001359 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001360 return TCL_ERROR;
1361 }else{
1362 /* The statement was a no-op. Continue to the next statement
1363 ** in the SQL string.
1364 */
1365 return TCL_OK;
1366 }
1367 }
1368
1369 assert( pPreStmt==0 );
1370 nVar = sqlite3_bind_parameter_count(pStmt);
1371 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1372 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1373 memset(pPreStmt, 0, nByte);
1374
1375 pPreStmt->pStmt = pStmt;
drh7ed243b2012-04-19 17:19:51 +00001376 pPreStmt->nSql = (int)(*pzOut - zSql);
dan4a4c11a2009-10-06 14:59:02 +00001377 pPreStmt->zSql = sqlite3_sql(pStmt);
1378 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
danc431fd52011-06-27 16:55:50 +00001379#ifdef SQLITE_TEST
1380 if( pPreStmt->zSql==0 ){
1381 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1382 memcpy(zCopy, zSql, pPreStmt->nSql);
1383 zCopy[pPreStmt->nSql] = '\0';
1384 pPreStmt->zSql = zCopy;
1385 }
1386#endif
dan4a4c11a2009-10-06 14:59:02 +00001387 }
1388 assert( pPreStmt );
1389 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1390 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1391
mistachkinb56660f2016-07-14 21:26:09 +00001392 /* Bind values to parameters that begin with $ or : */
dan4a4c11a2009-10-06 14:59:02 +00001393 for(i=1; i<=nVar; i++){
1394 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1395 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1396 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
drhc06ede12019-02-28 17:29:19 +00001397 if( pVar==0 && pDb->zBindFallback!=0 ){
1398 Tcl_Obj *pCmd;
1399 int rx;
1400 pCmd = Tcl_NewStringObj(pDb->zBindFallback, -1);
1401 Tcl_IncrRefCount(pCmd);
1402 Tcl_ListObjAppendElement(interp, pCmd, Tcl_NewStringObj(zVar,-1));
1403 if( needResultReset ) Tcl_ResetResult(interp);
1404 needResultReset = 1;
1405 rx = Tcl_EvalObjEx(interp, pCmd, TCL_EVAL_DIRECT);
1406 Tcl_DecrRefCount(pCmd);
1407 if( rx==TCL_OK ){
1408 pVar = Tcl_GetObjResult(interp);
1409 }else if( rx==TCL_ERROR ){
1410 rc = TCL_ERROR;
1411 break;
1412 }else{
1413 pVar = 0;
1414 }
1415 }
dan4a4c11a2009-10-06 14:59:02 +00001416 if( pVar ){
1417 int n;
1418 u8 *data;
1419 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
mistachkin8e189222015-04-19 21:43:16 +00001420 c = zType[0];
dan4a4c11a2009-10-06 14:59:02 +00001421 if( zVar[0]=='@' ||
1422 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1423 /* Load a BLOB type if the Tcl variable is a bytearray and
1424 ** it has no string representation or the host
1425 ** parameter name begins with "@". */
1426 data = Tcl_GetByteArrayFromObj(pVar, &n);
1427 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1428 Tcl_IncrRefCount(pVar);
1429 pPreStmt->apParm[iParm++] = pVar;
1430 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1431 Tcl_GetIntFromObj(interp, pVar, &n);
1432 sqlite3_bind_int(pStmt, i, n);
1433 }else if( c=='d' && strcmp(zType,"double")==0 ){
1434 double r;
1435 Tcl_GetDoubleFromObj(interp, pVar, &r);
1436 sqlite3_bind_double(pStmt, i, r);
1437 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1438 (c=='i' && strcmp(zType,"int")==0) ){
1439 Tcl_WideInt v;
1440 Tcl_GetWideIntFromObj(interp, pVar, &v);
1441 sqlite3_bind_int64(pStmt, i, v);
1442 }else{
1443 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1444 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1445 Tcl_IncrRefCount(pVar);
1446 pPreStmt->apParm[iParm++] = pVar;
1447 }
1448 }else{
1449 sqlite3_bind_null(pStmt, i);
1450 }
drhc06ede12019-02-28 17:29:19 +00001451 if( needResultReset ) Tcl_ResetResult(pDb->interp);
dan4a4c11a2009-10-06 14:59:02 +00001452 }
1453 }
1454 pPreStmt->nParm = iParm;
1455 *ppPreStmt = pPreStmt;
drhc06ede12019-02-28 17:29:19 +00001456 if( needResultReset && rc==TCL_OK ) Tcl_ResetResult(pDb->interp);
dan937d0de2009-10-15 18:35:38 +00001457
drhc06ede12019-02-28 17:29:19 +00001458 return rc;
dan4a4c11a2009-10-06 14:59:02 +00001459}
1460
dan4a4c11a2009-10-06 14:59:02 +00001461/*
1462** Release a statement reference obtained by calling dbPrepareAndBind().
1463** There should be exactly one call to this function for each call to
1464** dbPrepareAndBind().
1465**
1466** If the discard parameter is non-zero, then the statement is deleted
1467** immediately. Otherwise it is added to the LRU list and may be returned
1468** by a subsequent call to dbPrepareAndBind().
1469*/
1470static void dbReleaseStmt(
1471 SqliteDb *pDb, /* Database handle */
1472 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1473 int discard /* True to delete (not cache) the pPreStmt */
1474){
1475 int i;
1476
1477 /* Free the bound string and blob parameters */
1478 for(i=0; i<pPreStmt->nParm; i++){
1479 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1480 }
1481 pPreStmt->nParm = 0;
1482
1483 if( pDb->maxStmt<=0 || discard ){
1484 /* If the cache is turned off, deallocated the statement */
danc431fd52011-06-27 16:55:50 +00001485 dbFreeStmt(pPreStmt);
dan4a4c11a2009-10-06 14:59:02 +00001486 }else{
1487 /* Add the prepared statement to the beginning of the cache list. */
1488 pPreStmt->pNext = pDb->stmtList;
1489 pPreStmt->pPrev = 0;
1490 if( pDb->stmtList ){
1491 pDb->stmtList->pPrev = pPreStmt;
1492 }
1493 pDb->stmtList = pPreStmt;
1494 if( pDb->stmtLast==0 ){
1495 assert( pDb->nStmt==0 );
1496 pDb->stmtLast = pPreStmt;
1497 }else{
1498 assert( pDb->nStmt>0 );
1499 }
1500 pDb->nStmt++;
mistachkinb56660f2016-07-14 21:26:09 +00001501
1502 /* If we have too many statement in cache, remove the surplus from
dan4a4c11a2009-10-06 14:59:02 +00001503 ** the end of the cache list. */
1504 while( pDb->nStmt>pDb->maxStmt ){
danc431fd52011-06-27 16:55:50 +00001505 SqlPreparedStmt *pLast = pDb->stmtLast;
1506 pDb->stmtLast = pLast->pPrev;
dan4a4c11a2009-10-06 14:59:02 +00001507 pDb->stmtLast->pNext = 0;
1508 pDb->nStmt--;
danc431fd52011-06-27 16:55:50 +00001509 dbFreeStmt(pLast);
dan4a4c11a2009-10-06 14:59:02 +00001510 }
1511 }
1512}
1513
1514/*
1515** Structure used with dbEvalXXX() functions:
1516**
1517** dbEvalInit()
1518** dbEvalStep()
1519** dbEvalFinalize()
1520** dbEvalRowInfo()
1521** dbEvalColumnValue()
1522*/
1523typedef struct DbEvalContext DbEvalContext;
1524struct DbEvalContext {
1525 SqliteDb *pDb; /* Database handle */
1526 Tcl_Obj *pSql; /* Object holding string zSql */
1527 const char *zSql; /* Remaining SQL to execute */
1528 SqlPreparedStmt *pPreStmt; /* Current statement */
1529 int nCol; /* Number of columns returned by pStmt */
drhaf38cdb2017-06-26 21:08:32 +00001530 int evalFlags; /* Flags used */
dan4a4c11a2009-10-06 14:59:02 +00001531 Tcl_Obj *pArray; /* Name of array variable */
1532 Tcl_Obj **apColName; /* Array of column names */
1533};
1534
drhaf38cdb2017-06-26 21:08:32 +00001535#define SQLITE_EVAL_WITHOUTNULLS 0x00001 /* Unset array(*) for NULL */
1536
dan4a4c11a2009-10-06 14:59:02 +00001537/*
1538** Release any cache of column names currently held as part of
1539** the DbEvalContext structure passed as the first argument.
1540*/
1541static void dbReleaseColumnNames(DbEvalContext *p){
1542 if( p->apColName ){
1543 int i;
1544 for(i=0; i<p->nCol; i++){
1545 Tcl_DecrRefCount(p->apColName[i]);
1546 }
1547 Tcl_Free((char *)p->apColName);
1548 p->apColName = 0;
1549 }
1550 p->nCol = 0;
1551}
1552
1553/*
1554** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001555**
1556** If pArray is not NULL, then it contains the name of a Tcl array
1557** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001558** the names of the columns returned by the statement as part of each
mistachkinb56660f2016-07-14 21:26:09 +00001559** call to dbEvalStep(), in order from left to right. e.g. if the names
1560** of the returned columns are a, b and c, it does the equivalent of the
dan4a4c11a2009-10-06 14:59:02 +00001561** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001562**
1563** set ${pArray}(*) {a b c}
1564*/
dan4a4c11a2009-10-06 14:59:02 +00001565static void dbEvalInit(
1566 DbEvalContext *p, /* Pointer to structure to initialize */
1567 SqliteDb *pDb, /* Database handle */
1568 Tcl_Obj *pSql, /* Object containing SQL script */
drhaf38cdb2017-06-26 21:08:32 +00001569 Tcl_Obj *pArray, /* Name of Tcl array to set (*) element of */
1570 int evalFlags /* Flags controlling evaluation */
danielk19778e556522007-11-13 10:30:24 +00001571){
dan4a4c11a2009-10-06 14:59:02 +00001572 memset(p, 0, sizeof(DbEvalContext));
1573 p->pDb = pDb;
1574 p->zSql = Tcl_GetString(pSql);
1575 p->pSql = pSql;
1576 Tcl_IncrRefCount(pSql);
1577 if( pArray ){
1578 p->pArray = pArray;
1579 Tcl_IncrRefCount(pArray);
1580 }
drhaf38cdb2017-06-26 21:08:32 +00001581 p->evalFlags = evalFlags;
dan4a4c11a2009-10-06 14:59:02 +00001582}
danielk19778e556522007-11-13 10:30:24 +00001583
dan4a4c11a2009-10-06 14:59:02 +00001584/*
1585** Obtain information about the row that the DbEvalContext passed as the
1586** first argument currently points to.
1587*/
1588static void dbEvalRowInfo(
1589 DbEvalContext *p, /* Evaluation context */
1590 int *pnCol, /* OUT: Number of column names */
1591 Tcl_Obj ***papColName /* OUT: Array of column names */
1592){
danielk19778e556522007-11-13 10:30:24 +00001593 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001594 if( 0==p->apColName ){
1595 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1596 int i; /* Iterator variable */
1597 int nCol; /* Number of columns returned by pStmt */
1598 Tcl_Obj **apColName = 0; /* Array of column names */
1599
1600 p->nCol = nCol = sqlite3_column_count(pStmt);
1601 if( nCol>0 && (papColName || p->pArray) ){
1602 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1603 for(i=0; i<nCol; i++){
drhc45e6712012-10-03 11:02:33 +00001604 apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
dan4a4c11a2009-10-06 14:59:02 +00001605 Tcl_IncrRefCount(apColName[i]);
1606 }
1607 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001608 }
1609
1610 /* If results are being stored in an array variable, then create
1611 ** the array(*) entry for that array
1612 */
dan4a4c11a2009-10-06 14:59:02 +00001613 if( p->pArray ){
1614 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001615 Tcl_Obj *pColList = Tcl_NewObj();
1616 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001617
danielk19778e556522007-11-13 10:30:24 +00001618 for(i=0; i<nCol; i++){
1619 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1620 }
1621 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001622 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001623 Tcl_DecrRefCount(pStar);
1624 }
danielk19778e556522007-11-13 10:30:24 +00001625 }
1626
dan4a4c11a2009-10-06 14:59:02 +00001627 if( papColName ){
1628 *papColName = p->apColName;
1629 }
1630 if( pnCol ){
1631 *pnCol = p->nCol;
1632 }
1633}
1634
1635/*
1636** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1637** returned, then an error message is stored in the interpreter before
1638** returning.
1639**
1640** A return value of TCL_OK means there is a row of data available. The
1641** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1642** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1643** is returned, then the SQL script has finished executing and there are
1644** no further rows available. This is similar to SQLITE_DONE.
1645*/
1646static int dbEvalStep(DbEvalContext *p){
danc431fd52011-06-27 16:55:50 +00001647 const char *zPrevSql = 0; /* Previous value of p->zSql */
1648
dan4a4c11a2009-10-06 14:59:02 +00001649 while( p->zSql[0] || p->pPreStmt ){
1650 int rc;
1651 if( p->pPreStmt==0 ){
danc431fd52011-06-27 16:55:50 +00001652 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
dan4a4c11a2009-10-06 14:59:02 +00001653 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1654 if( rc!=TCL_OK ) return rc;
1655 }else{
1656 int rcs;
1657 SqliteDb *pDb = p->pDb;
1658 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1659 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1660
1661 rcs = sqlite3_step(pStmt);
1662 if( rcs==SQLITE_ROW ){
1663 return TCL_OK;
1664 }
1665 if( p->pArray ){
1666 dbEvalRowInfo(p, 0, 0);
1667 }
1668 rcs = sqlite3_reset(pStmt);
1669
1670 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1671 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001672 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
danc456a762017-06-22 16:51:16 +00001673 pDb->nVMStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_VM_STEP,1);
dan4a4c11a2009-10-06 14:59:02 +00001674 dbReleaseColumnNames(p);
1675 p->pPreStmt = 0;
1676
1677 if( rcs!=SQLITE_OK ){
1678 /* If a run-time error occurs, report the error and stop reading
1679 ** the SQL. */
dan4a4c11a2009-10-06 14:59:02 +00001680 dbReleaseStmt(pDb, pPreStmt, 1);
danc431fd52011-06-27 16:55:50 +00001681#if SQLITE_TEST
1682 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1683 /* If the runtime error was an SQLITE_SCHEMA, and the database
mistachkinb56660f2016-07-14 21:26:09 +00001684 ** handle is configured to use the legacy sqlite3_prepare()
danc431fd52011-06-27 16:55:50 +00001685 ** interface, retry prepare()/step() on the same SQL statement.
1686 ** This only happens once. If there is a second SQLITE_SCHEMA
1687 ** error, the error will be returned to the caller. */
1688 p->zSql = zPrevSql;
1689 continue;
1690 }
1691#endif
drhc45e6712012-10-03 11:02:33 +00001692 Tcl_SetObjResult(pDb->interp,
1693 Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001694 return TCL_ERROR;
1695 }else{
1696 dbReleaseStmt(pDb, pPreStmt, 0);
1697 }
1698 }
1699 }
1700
1701 /* Finished */
1702 return TCL_BREAK;
1703}
1704
1705/*
1706** Free all resources currently held by the DbEvalContext structure passed
1707** as the first argument. There should be exactly one call to this function
1708** for each call to dbEvalInit().
1709*/
1710static void dbEvalFinalize(DbEvalContext *p){
1711 if( p->pPreStmt ){
1712 sqlite3_reset(p->pPreStmt->pStmt);
1713 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1714 p->pPreStmt = 0;
1715 }
1716 if( p->pArray ){
1717 Tcl_DecrRefCount(p->pArray);
1718 p->pArray = 0;
1719 }
1720 Tcl_DecrRefCount(p->pSql);
1721 dbReleaseColumnNames(p);
1722}
1723
1724/*
1725** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1726** the value for the iCol'th column of the row currently pointed to by
1727** the DbEvalContext structure passed as the first argument.
1728*/
1729static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1730 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1731 switch( sqlite3_column_type(pStmt, iCol) ){
1732 case SQLITE_BLOB: {
1733 int bytes = sqlite3_column_bytes(pStmt, iCol);
1734 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1735 if( !zBlob ) bytes = 0;
1736 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1737 }
1738 case SQLITE_INTEGER: {
1739 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1740 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +00001741 return Tcl_NewIntObj((int)v);
dan4a4c11a2009-10-06 14:59:02 +00001742 }else{
1743 return Tcl_NewWideIntObj(v);
1744 }
1745 }
1746 case SQLITE_FLOAT: {
1747 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1748 }
1749 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +00001750 return Tcl_NewStringObj(p->pDb->zNull, -1);
dan4a4c11a2009-10-06 14:59:02 +00001751 }
1752 }
1753
drh325eff52012-10-03 12:56:18 +00001754 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
dan4a4c11a2009-10-06 14:59:02 +00001755}
1756
1757/*
1758** If using Tcl version 8.6 or greater, use the NR functions to avoid
1759** recursive evalution of scripts by the [db eval] and [db trans]
1760** commands. Even if the headers used while compiling the extension
1761** are 8.6 or newer, the code still tests the Tcl version at runtime.
1762** This allows stubs-enabled builds to be used with older Tcl libraries.
1763*/
1764#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001765# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001766static int DbUseNre(void){
1767 int major, minor;
1768 Tcl_GetVersion(&major, &minor, 0, 0);
1769 return( (major==8 && minor>=6) || major>8 );
1770}
1771#else
mistachkinb56660f2016-07-14 21:26:09 +00001772/*
dan4a4c11a2009-10-06 14:59:02 +00001773** Compiling using headers earlier than 8.6. In this case NR cannot be
1774** used, so DbUseNre() to always return zero. Add #defines for the other
1775** Tcl_NRxxx() functions to prevent them from causing compilation errors,
mistachkinb56660f2016-07-14 21:26:09 +00001776** even though the only invocations of them are within conditional blocks
dan4a4c11a2009-10-06 14:59:02 +00001777** of the form:
1778**
1779** if( DbUseNre() ) { ... }
1780*/
drha2c8a952009-10-13 18:38:34 +00001781# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001782# define DbUseNre() 0
drha47941f2013-12-20 18:57:44 +00001783# define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001784# define Tcl_NREvalObj(a,b,c) 0
drha47941f2013-12-20 18:57:44 +00001785# define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001786#endif
1787
1788/*
1789** This function is part of the implementation of the command:
1790**
1791** $db eval SQL ?ARRAYNAME? SCRIPT
1792*/
mistachkina121cc72016-07-28 18:06:52 +00001793static int SQLITE_TCLAPI DbEvalNextCmd(
dan4a4c11a2009-10-06 14:59:02 +00001794 ClientData data[], /* data[0] is the (DbEvalContext*) */
1795 Tcl_Interp *interp, /* Tcl interpreter */
1796 int result /* Result so far */
1797){
1798 int rc = result; /* Return code */
1799
1800 /* The first element of the data[] array is a pointer to a DbEvalContext
1801 ** structure allocated using Tcl_Alloc(). The second element of data[]
1802 ** is a pointer to a Tcl_Obj containing the script to run for each row
1803 ** returned by the queries encapsulated in data[0]. */
1804 DbEvalContext *p = (DbEvalContext *)data[0];
1805 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1806 Tcl_Obj *pArray = p->pArray;
1807
1808 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1809 int i;
1810 int nCol;
1811 Tcl_Obj **apColName;
1812 dbEvalRowInfo(p, &nCol, &apColName);
1813 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00001814 if( pArray==0 ){
drhaf38cdb2017-06-26 21:08:32 +00001815 Tcl_ObjSetVar2(interp, apColName[i], 0, dbEvalColumnValue(p,i), 0);
1816 }else if( (p->evalFlags & SQLITE_EVAL_WITHOUTNULLS)!=0
1817 && sqlite3_column_type(p->pPreStmt->pStmt, i)==SQLITE_NULL
1818 ){
1819 Tcl_UnsetVar2(interp, Tcl_GetString(pArray),
1820 Tcl_GetString(apColName[i]), 0);
dan4a4c11a2009-10-06 14:59:02 +00001821 }else{
drhaf38cdb2017-06-26 21:08:32 +00001822 Tcl_ObjSetVar2(interp, pArray, apColName[i], dbEvalColumnValue(p,i), 0);
dan4a4c11a2009-10-06 14:59:02 +00001823 }
1824 }
1825
mistachkinb56660f2016-07-14 21:26:09 +00001826 /* The required interpreter variables are now populated with the data
dan4a4c11a2009-10-06 14:59:02 +00001827 ** from the current row. If using NRE, schedule callbacks to evaluate
1828 ** script pScript, then to invoke this function again to fetch the next
1829 ** row (or clean up if there is no next row or the script throws an
mistachkinb56660f2016-07-14 21:26:09 +00001830 ** exception). After scheduling the callbacks, return control to the
dan4a4c11a2009-10-06 14:59:02 +00001831 ** caller.
1832 **
1833 ** If not using NRE, evaluate pScript directly and continue with the
1834 ** next iteration of this while(...) loop. */
1835 if( DbUseNre() ){
1836 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1837 return Tcl_NREvalObj(interp, pScript, 0);
1838 }else{
1839 rc = Tcl_EvalObjEx(interp, pScript, 0);
1840 }
1841 }
1842
1843 Tcl_DecrRefCount(pScript);
1844 dbEvalFinalize(p);
1845 Tcl_Free((char *)p);
1846
1847 if( rc==TCL_OK || rc==TCL_BREAK ){
1848 Tcl_ResetResult(interp);
1849 rc = TCL_OK;
1850 }
1851 return rc;
danielk19778e556522007-11-13 10:30:24 +00001852}
1853
tpoindex1067fe12004-12-17 15:41:11 +00001854/*
mistachkinb56660f2016-07-14 21:26:09 +00001855** This function is used by the implementations of the following database
dan46c47d42011-03-01 18:42:07 +00001856** handle sub-commands:
1857**
1858** $db update_hook ?SCRIPT?
1859** $db wal_hook ?SCRIPT?
1860** $db commit_hook ?SCRIPT?
1861** $db preupdate hook ?SCRIPT?
1862*/
1863static void DbHookCmd(
1864 Tcl_Interp *interp, /* Tcl interpreter */
1865 SqliteDb *pDb, /* Database handle */
1866 Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */
1867 Tcl_Obj **ppHook /* Pointer to member of SqliteDb */
1868){
1869 sqlite3 *db = pDb->db;
1870
1871 if( *ppHook ){
1872 Tcl_SetObjResult(interp, *ppHook);
1873 if( pArg ){
1874 Tcl_DecrRefCount(*ppHook);
1875 *ppHook = 0;
1876 }
1877 }
1878 if( pArg ){
1879 assert( !(*ppHook) );
1880 if( Tcl_GetCharLength(pArg)>0 ){
1881 *ppHook = pArg;
1882 Tcl_IncrRefCount(*ppHook);
1883 }
1884 }
1885
drh9b1c62d2011-03-30 21:04:43 +00001886#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +00001887 sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
drh9b1c62d2011-03-30 21:04:43 +00001888#endif
dan46c47d42011-03-01 18:42:07 +00001889 sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1890 sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1891 sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
1892}
1893
1894/*
drh75897232000-05-29 14:26:00 +00001895** The "sqlite" command below creates a new Tcl command for each
1896** connection it opens to an SQLite database. This routine is invoked
1897** whenever one of those connection-specific commands is executed
1898** in Tcl. For example, if you run Tcl code like this:
1899**
drh9bb575f2004-09-06 17:24:11 +00001900** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001901** db1 close
1902**
1903** The first command opens a connection to the "my_database" database
1904** and calls that connection "db1". The second command causes this
1905** subroutine to be invoked.
1906*/
mistachkin7617e4a2016-07-28 17:11:20 +00001907static int SQLITE_TCLAPI DbObjCmd(
1908 void *cd,
1909 Tcl_Interp *interp,
1910 int objc,
1911 Tcl_Obj *const*objv
1912){
drhbec3f402000-08-04 13:49:02 +00001913 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001914 int choice;
drh22fbcb82004-02-01 01:22:50 +00001915 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001916 static const char *DB_strs[] = {
drhc06ede12019-02-28 17:29:19 +00001917 "authorizer", "backup", "bind_fallback",
1918 "busy", "cache", "changes",
1919 "close", "collate", "collation_needed",
drh11d88e62019-08-15 21:27:20 +00001920 "commit_hook", "complete", "config",
1921 "copy", "deserialize", "enable_load_extension",
1922 "errorcode", "eval", "exists",
1923 "function", "incrblob", "interrupt",
1924 "last_insert_rowid", "nullvalue", "onecolumn",
1925 "preupdate", "profile", "progress",
1926 "rekey", "restore", "rollback_hook",
1927 "serialize", "status", "timeout",
1928 "total_changes", "trace", "trace_v2",
1929 "transaction", "unlock_notify", "update_hook",
1930 "version", "wal_hook", 0
drh6d313162000-09-21 13:01:35 +00001931 };
drh411995d2002-06-25 19:31:18 +00001932 enum DB_enum {
drhc06ede12019-02-28 17:29:19 +00001933 DB_AUTHORIZER, DB_BACKUP, DB_BIND_FALLBACK,
1934 DB_BUSY, DB_CACHE, DB_CHANGES,
1935 DB_CLOSE, DB_COLLATE, DB_COLLATION_NEEDED,
drh11d88e62019-08-15 21:27:20 +00001936 DB_COMMIT_HOOK, DB_COMPLETE, DB_CONFIG,
1937 DB_COPY, DB_DESERIALIZE, DB_ENABLE_LOAD_EXTENSION,
1938 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1939 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
1940 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
1941 DB_PREUPDATE, DB_PROFILE, DB_PROGRESS,
1942 DB_REKEY, DB_RESTORE, DB_ROLLBACK_HOOK,
1943 DB_SERIALIZE, DB_STATUS, DB_TIMEOUT,
1944 DB_TOTAL_CHANGES, DB_TRACE, DB_TRACE_V2,
1945 DB_TRANSACTION, DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK,
1946 DB_VERSION, DB_WAL_HOOK
drh6d313162000-09-21 13:01:35 +00001947 };
tpoindex1067fe12004-12-17 15:41:11 +00001948 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001949
1950 if( objc<2 ){
1951 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001952 return TCL_ERROR;
1953 }
drh411995d2002-06-25 19:31:18 +00001954 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001955 return TCL_ERROR;
1956 }
1957
drh411995d2002-06-25 19:31:18 +00001958 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001959
drhe22a3342003-04-22 20:30:37 +00001960 /* $db authorizer ?CALLBACK?
1961 **
1962 ** Invoke the given callback to authorize each SQL operation as it is
1963 ** compiled. 5 arguments are appended to the callback before it is
1964 ** invoked:
1965 **
1966 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1967 ** (2) First descriptive name (depends on authorization type)
1968 ** (3) Second descriptive name
1969 ** (4) Name of the database (ex: "main", "temp")
1970 ** (5) Name of trigger that is doing the access
1971 **
1972 ** The callback should return on of the following strings: SQLITE_OK,
1973 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1974 **
1975 ** If this method is invoked with no arguments, the current authorization
1976 ** callback string is returned.
1977 */
1978 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001979#ifdef SQLITE_OMIT_AUTHORIZATION
drha198f2b2014-02-07 19:26:13 +00001980 Tcl_AppendResult(interp, "authorization not available in this build",
1981 (char*)0);
drh1211de32004-07-26 12:24:22 +00001982 return TCL_ERROR;
1983#else
drhe22a3342003-04-22 20:30:37 +00001984 if( objc>3 ){
1985 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001986 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001987 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001988 if( pDb->zAuth ){
drha198f2b2014-02-07 19:26:13 +00001989 Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
drhe22a3342003-04-22 20:30:37 +00001990 }
1991 }else{
1992 char *zAuth;
1993 int len;
1994 if( pDb->zAuth ){
1995 Tcl_Free(pDb->zAuth);
1996 }
1997 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1998 if( zAuth && len>0 ){
1999 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002000 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00002001 }else{
2002 pDb->zAuth = 0;
2003 }
drhe22a3342003-04-22 20:30:37 +00002004 if( pDb->zAuth ){
drh32c6a482014-09-11 13:44:52 +00002005 typedef int (*sqlite3_auth_cb)(
2006 void*,int,const char*,const char*,
2007 const char*,const char*);
drhe22a3342003-04-22 20:30:37 +00002008 pDb->interp = interp;
drh32c6a482014-09-11 13:44:52 +00002009 sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
drhe22a3342003-04-22 20:30:37 +00002010 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002011 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00002012 }
drhe22a3342003-04-22 20:30:37 +00002013 }
drh1211de32004-07-26 12:24:22 +00002014#endif
drhe22a3342003-04-22 20:30:37 +00002015 break;
2016 }
2017
drhdc2c4912009-02-04 22:46:47 +00002018 /* $db backup ?DATABASE? FILENAME
2019 **
2020 ** Open or create a database file named FILENAME. Transfer the
2021 ** content of local database DATABASE (default: "main") into the
2022 ** FILENAME database.
2023 */
2024 case DB_BACKUP: {
2025 const char *zDestFile;
2026 const char *zSrcDb;
2027 sqlite3 *pDest;
2028 sqlite3_backup *pBackup;
2029
2030 if( objc==3 ){
2031 zSrcDb = "main";
2032 zDestFile = Tcl_GetString(objv[2]);
2033 }else if( objc==4 ){
2034 zSrcDb = Tcl_GetString(objv[2]);
2035 zDestFile = Tcl_GetString(objv[3]);
2036 }else{
2037 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2038 return TCL_ERROR;
2039 }
drh147ef392016-01-22 23:17:51 +00002040 rc = sqlite3_open_v2(zDestFile, &pDest,
2041 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00002042 if( rc!=SQLITE_OK ){
2043 Tcl_AppendResult(interp, "cannot open target database: ",
2044 sqlite3_errmsg(pDest), (char*)0);
2045 sqlite3_close(pDest);
2046 return TCL_ERROR;
2047 }
2048 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
2049 if( pBackup==0 ){
2050 Tcl_AppendResult(interp, "backup failed: ",
2051 sqlite3_errmsg(pDest), (char*)0);
2052 sqlite3_close(pDest);
2053 return TCL_ERROR;
2054 }
2055 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
2056 sqlite3_backup_finish(pBackup);
2057 if( rc==SQLITE_DONE ){
2058 rc = TCL_OK;
2059 }else{
2060 Tcl_AppendResult(interp, "backup failed: ",
2061 sqlite3_errmsg(pDest), (char*)0);
2062 rc = TCL_ERROR;
2063 }
2064 sqlite3_close(pDest);
2065 break;
2066 }
2067
drhc06ede12019-02-28 17:29:19 +00002068 /* $db bind_fallback ?CALLBACK?
2069 **
2070 ** When resolving bind parameters in an SQL statement, if the parameter
2071 ** cannot be associated with a TCL variable then invoke CALLBACK with a
2072 ** single argument that is the name of the parameter and use the return
2073 ** value of the CALLBACK as the binding. If CALLBACK returns something
2074 ** other than TCL_OK or TCL_ERROR then bind a NULL.
2075 **
2076 ** If CALLBACK is an empty string, then revert to the default behavior
2077 ** which is to set the binding to NULL.
2078 **
2079 ** If CALLBACK returns an error, that causes the statement execution to
2080 ** abort. Hence, to configure a connection so that it throws an error
2081 ** on an attempt to bind an unknown variable, do something like this:
2082 **
2083 ** proc bind_error {name} {error "no such variable: $name"}
2084 ** db bind_fallback bind_error
2085 */
2086 case DB_BIND_FALLBACK: {
2087 if( objc>3 ){
2088 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2089 return TCL_ERROR;
2090 }else if( objc==2 ){
2091 if( pDb->zBindFallback ){
2092 Tcl_AppendResult(interp, pDb->zBindFallback, (char*)0);
2093 }
2094 }else{
2095 char *zCallback;
2096 int len;
2097 if( pDb->zBindFallback ){
2098 Tcl_Free(pDb->zBindFallback);
2099 }
2100 zCallback = Tcl_GetStringFromObj(objv[2], &len);
2101 if( zCallback && len>0 ){
2102 pDb->zBindFallback = Tcl_Alloc( len + 1 );
2103 memcpy(pDb->zBindFallback, zCallback, len+1);
2104 }else{
2105 pDb->zBindFallback = 0;
2106 }
2107 }
2108 break;
2109 }
2110
drhbec3f402000-08-04 13:49:02 +00002111 /* $db busy ?CALLBACK?
2112 **
2113 ** Invoke the given callback if an SQL statement attempts to open
2114 ** a locked database file.
2115 */
drh6d313162000-09-21 13:01:35 +00002116 case DB_BUSY: {
2117 if( objc>3 ){
2118 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00002119 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00002120 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00002121 if( pDb->zBusy ){
drha198f2b2014-02-07 19:26:13 +00002122 Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
drhbec3f402000-08-04 13:49:02 +00002123 }
2124 }else{
drh6d313162000-09-21 13:01:35 +00002125 char *zBusy;
2126 int len;
drhbec3f402000-08-04 13:49:02 +00002127 if( pDb->zBusy ){
2128 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00002129 }
drh6d313162000-09-21 13:01:35 +00002130 zBusy = Tcl_GetStringFromObj(objv[2], &len);
2131 if( zBusy && len>0 ){
2132 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002133 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00002134 }else{
2135 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00002136 }
2137 if( pDb->zBusy ){
2138 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002139 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00002140 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002141 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00002142 }
2143 }
drh6d313162000-09-21 13:01:35 +00002144 break;
2145 }
drhbec3f402000-08-04 13:49:02 +00002146
drhfb7e7652005-01-24 00:28:42 +00002147 /* $db cache flush
2148 ** $db cache size n
2149 **
2150 ** Flush the prepared statement cache, or set the maximum number of
2151 ** cached statements.
2152 */
2153 case DB_CACHE: {
2154 char *subCmd;
2155 int n;
2156
2157 if( objc<=2 ){
2158 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
2159 return TCL_ERROR;
2160 }
2161 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
2162 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
2163 if( objc!=3 ){
2164 Tcl_WrongNumArgs(interp, 2, objv, "flush");
2165 return TCL_ERROR;
2166 }else{
2167 flushStmtCache( pDb );
2168 }
2169 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
2170 if( objc!=4 ){
2171 Tcl_WrongNumArgs(interp, 2, objv, "size n");
2172 return TCL_ERROR;
2173 }else{
2174 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
mistachkinb56660f2016-07-14 21:26:09 +00002175 Tcl_AppendResult( interp, "cannot convert \"",
drha198f2b2014-02-07 19:26:13 +00002176 Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
drhfb7e7652005-01-24 00:28:42 +00002177 return TCL_ERROR;
2178 }else{
2179 if( n<0 ){
2180 flushStmtCache( pDb );
2181 n = 0;
2182 }else if( n>MAX_PREPARED_STMTS ){
2183 n = MAX_PREPARED_STMTS;
2184 }
2185 pDb->maxStmt = n;
2186 }
2187 }
2188 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002189 Tcl_AppendResult( interp, "bad option \"",
drha198f2b2014-02-07 19:26:13 +00002190 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
2191 (char*)0);
drhfb7e7652005-01-24 00:28:42 +00002192 return TCL_ERROR;
2193 }
2194 break;
2195 }
2196
danielk1977b28af712004-06-21 06:50:26 +00002197 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00002198 **
2199 ** Return the number of rows that were modified, inserted, or deleted by
mistachkinb56660f2016-07-14 21:26:09 +00002200 ** the most recent INSERT, UPDATE or DELETE statement, not including
danielk1977b28af712004-06-21 06:50:26 +00002201 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00002202 */
2203 case DB_CHANGES: {
2204 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00002205 if( objc!=2 ){
2206 Tcl_WrongNumArgs(interp, 2, objv, "");
2207 return TCL_ERROR;
2208 }
drhc8d30ac2002-04-12 10:08:59 +00002209 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00002210 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00002211 break;
2212 }
2213
drh75897232000-05-29 14:26:00 +00002214 /* $db close
2215 **
2216 ** Shutdown the database
2217 */
drh6d313162000-09-21 13:01:35 +00002218 case DB_CLOSE: {
2219 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
2220 break;
2221 }
drh75897232000-05-29 14:26:00 +00002222
drh0f14e2e2004-06-29 12:39:08 +00002223 /*
2224 ** $db collate NAME SCRIPT
2225 **
2226 ** Create a new SQL collation function called NAME. Whenever
2227 ** that function is called, invoke SCRIPT to evaluate the function.
2228 */
2229 case DB_COLLATE: {
2230 SqlCollate *pCollate;
2231 char *zName;
2232 char *zScript;
2233 int nScript;
2234 if( objc!=4 ){
2235 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
2236 return TCL_ERROR;
2237 }
2238 zName = Tcl_GetStringFromObj(objv[2], 0);
2239 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
2240 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
2241 if( pCollate==0 ) return TCL_ERROR;
2242 pCollate->interp = interp;
2243 pCollate->pNext = pDb->pCollate;
2244 pCollate->zScript = (char*)&pCollate[1];
2245 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00002246 memcpy(pCollate->zScript, zScript, nScript+1);
mistachkinb56660f2016-07-14 21:26:09 +00002247 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
drh0f14e2e2004-06-29 12:39:08 +00002248 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00002249 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00002250 return TCL_ERROR;
2251 }
2252 break;
2253 }
2254
2255 /*
2256 ** $db collation_needed SCRIPT
2257 **
2258 ** Create a new SQL collation function called NAME. Whenever
2259 ** that function is called, invoke SCRIPT to evaluate the function.
2260 */
2261 case DB_COLLATION_NEEDED: {
2262 if( objc!=3 ){
2263 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
2264 return TCL_ERROR;
2265 }
2266 if( pDb->pCollateNeeded ){
2267 Tcl_DecrRefCount(pDb->pCollateNeeded);
2268 }
2269 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
2270 Tcl_IncrRefCount(pDb->pCollateNeeded);
2271 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
2272 break;
2273 }
2274
drh19e2d372005-08-29 23:00:03 +00002275 /* $db commit_hook ?CALLBACK?
2276 **
2277 ** Invoke the given callback just before committing every SQL transaction.
2278 ** If the callback throws an exception or returns non-zero, then the
2279 ** transaction is aborted. If CALLBACK is an empty string, the callback
2280 ** is disabled.
2281 */
2282 case DB_COMMIT_HOOK: {
2283 if( objc>3 ){
2284 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2285 return TCL_ERROR;
2286 }else if( objc==2 ){
2287 if( pDb->zCommit ){
drha198f2b2014-02-07 19:26:13 +00002288 Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002289 }
2290 }else{
mistachkin6ef5e122014-01-24 17:03:55 +00002291 const char *zCommit;
drh19e2d372005-08-29 23:00:03 +00002292 int len;
2293 if( pDb->zCommit ){
2294 Tcl_Free(pDb->zCommit);
2295 }
2296 zCommit = Tcl_GetStringFromObj(objv[2], &len);
2297 if( zCommit && len>0 ){
2298 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002299 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00002300 }else{
2301 pDb->zCommit = 0;
2302 }
2303 if( pDb->zCommit ){
2304 pDb->interp = interp;
2305 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
2306 }else{
2307 sqlite3_commit_hook(pDb->db, 0, 0);
2308 }
2309 }
2310 break;
2311 }
2312
drh75897232000-05-29 14:26:00 +00002313 /* $db complete SQL
2314 **
2315 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2316 ** additional lines of input are needed. This is similar to the
2317 ** built-in "info complete" command of Tcl.
2318 */
drh6d313162000-09-21 13:01:35 +00002319 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00002320#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00002321 Tcl_Obj *pResult;
2322 int isComplete;
2323 if( objc!=3 ){
2324 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00002325 return TCL_ERROR;
2326 }
danielk19776f8a5032004-05-10 10:34:51 +00002327 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00002328 pResult = Tcl_GetObjResult(interp);
2329 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00002330#endif
drh6d313162000-09-21 13:01:35 +00002331 break;
2332 }
drhdcd997e2003-01-31 17:21:49 +00002333
drh11d88e62019-08-15 21:27:20 +00002334 /* $db config ?OPTION? ?BOOLEAN?
2335 **
2336 ** Configure the database connection using the sqlite3_db_config()
2337 ** interface.
2338 */
2339 case DB_CONFIG: {
2340 static const struct DbConfigChoices {
2341 const char *zName;
2342 int op;
2343 } aDbConfig[] = {
2344 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
2345 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
2346 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW },
2347 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
2348 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
2349 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
2350 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
2351 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
2352 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
2353 { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
2354 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA },
2355 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE },
2356 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML },
2357 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL },
2358 };
2359 Tcl_Obj *pResult;
2360 int ii;
2361 if( objc>4 ){
2362 Tcl_WrongNumArgs(interp, 2, objv, "?OPTION? ?BOOLEAN?");
2363 return TCL_ERROR;
2364 }
2365 if( objc==2 ){
2366 /* With no arguments, list all configuration options and with the
2367 ** current value */
2368 pResult = Tcl_NewListObj(0,0);
2369 for(ii=0; ii<sizeof(aDbConfig)/sizeof(aDbConfig[0]); ii++){
2370 int v = 0;
drh4043cfe2019-08-15 23:11:42 +00002371 sqlite3_db_config(pDb->db, aDbConfig[ii].op, -1, &v);
drh11d88e62019-08-15 21:27:20 +00002372 Tcl_ListObjAppendElement(interp, pResult,
2373 Tcl_NewStringObj(aDbConfig[ii].zName,-1));
2374 Tcl_ListObjAppendElement(interp, pResult,
2375 Tcl_NewIntObj(v));
2376 }
2377 }else{
2378 const char *zOpt = Tcl_GetString(objv[2]);
drh11d88e62019-08-15 21:27:20 +00002379 int onoff = -1;
2380 int v = 0;
2381 if( zOpt[0]=='-' ) zOpt++;
2382 for(ii=0; ii<sizeof(aDbConfig)/sizeof(aDbConfig[0]); ii++){
2383 if( strcmp(aDbConfig[ii].zName, zOpt)==0 ) break;
2384 }
2385 if( ii>=sizeof(aDbConfig)/sizeof(aDbConfig[0]) ){
2386 Tcl_AppendResult(interp, "unknown config option: \"", zOpt,
2387 "\"", (void*)0);
2388 return TCL_ERROR;
2389 }
2390 if( objc==4 ){
2391 if( Tcl_GetBooleanFromObj(interp, objv[3], &onoff) ){
2392 return TCL_ERROR;
2393 }
2394 }
drh4043cfe2019-08-15 23:11:42 +00002395 sqlite3_db_config(pDb->db, aDbConfig[ii].op, onoff, &v);
drh11d88e62019-08-15 21:27:20 +00002396 pResult = Tcl_NewIntObj(v);
2397 }
2398 Tcl_SetObjResult(interp, pResult);
2399 break;
2400 }
2401
drh19e2d372005-08-29 23:00:03 +00002402 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2403 **
2404 ** Copy data into table from filename, optionally using SEPARATOR
2405 ** as column separators. If a column contains a null string, or the
2406 ** value of NULLINDICATOR, a NULL is inserted for the column.
2407 ** conflict-algorithm is one of the sqlite conflict algorithms:
2408 ** rollback, abort, fail, ignore, replace
2409 ** On success, return the number of lines processed, not necessarily same
2410 ** as 'db changes' due to conflict-algorithm selected.
2411 **
2412 ** This code is basically an implementation/enhancement of
2413 ** the sqlite3 shell.c ".import" command.
2414 **
2415 ** This command usage is equivalent to the sqlite2.x COPY statement,
2416 ** which imports file data into a table using the PostgreSQL COPY file format:
2417 ** $db copy $conflit_algo $table_name $filename \t \\N
2418 */
2419 case DB_COPY: {
2420 char *zTable; /* Insert data into this table */
2421 char *zFile; /* The file from which to extract data */
2422 char *zConflict; /* The conflict algorithm to use */
2423 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00002424 int nCol; /* Number of columns in the table */
2425 int nByte; /* Number of bytes in an SQL string */
2426 int i, j; /* Loop counters */
2427 int nSep; /* Number of bytes in zSep[] */
2428 int nNull; /* Number of bytes in zNull[] */
2429 char *zSql; /* An SQL statement */
2430 char *zLine; /* A single line of input from the file */
2431 char **azCol; /* zLine[] broken up into columns */
mistachkin6ef5e122014-01-24 17:03:55 +00002432 const char *zCommit; /* How to commit changes */
drh19e2d372005-08-29 23:00:03 +00002433 FILE *in; /* The input file */
2434 int lineno = 0; /* Line number of input file */
2435 char zLineNum[80]; /* Line number print buffer */
2436 Tcl_Obj *pResult; /* interp result */
2437
mistachkin6ef5e122014-01-24 17:03:55 +00002438 const char *zSep;
2439 const char *zNull;
drh19e2d372005-08-29 23:00:03 +00002440 if( objc<5 || objc>7 ){
mistachkinb56660f2016-07-14 21:26:09 +00002441 Tcl_WrongNumArgs(interp, 2, objv,
drh19e2d372005-08-29 23:00:03 +00002442 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2443 return TCL_ERROR;
2444 }
2445 if( objc>=6 ){
2446 zSep = Tcl_GetStringFromObj(objv[5], 0);
2447 }else{
2448 zSep = "\t";
2449 }
2450 if( objc>=7 ){
2451 zNull = Tcl_GetStringFromObj(objv[6], 0);
2452 }else{
2453 zNull = "";
2454 }
2455 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2456 zTable = Tcl_GetStringFromObj(objv[3], 0);
2457 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002458 nSep = strlen30(zSep);
2459 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002460 if( nSep==0 ){
drha198f2b2014-02-07 19:26:13 +00002461 Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2462 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002463 return TCL_ERROR;
2464 }
drh3e59c012008-09-23 10:12:13 +00002465 if(strcmp(zConflict, "rollback") != 0 &&
2466 strcmp(zConflict, "abort" ) != 0 &&
2467 strcmp(zConflict, "fail" ) != 0 &&
2468 strcmp(zConflict, "ignore" ) != 0 &&
2469 strcmp(zConflict, "replace" ) != 0 ) {
mistachkinb56660f2016-07-14 21:26:09 +00002470 Tcl_AppendResult(interp, "Error: \"", zConflict,
drh19e2d372005-08-29 23:00:03 +00002471 "\", conflict-algorithm must be one of: rollback, "
drha198f2b2014-02-07 19:26:13 +00002472 "abort, fail, ignore, or replace", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002473 return TCL_ERROR;
2474 }
2475 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2476 if( zSql==0 ){
drha198f2b2014-02-07 19:26:13 +00002477 Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002478 return TCL_ERROR;
2479 }
drh4f21c4a2008-12-10 22:15:00 +00002480 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002481 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002482 sqlite3_free(zSql);
2483 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002484 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002485 nCol = 0;
2486 }else{
2487 nCol = sqlite3_column_count(pStmt);
2488 }
2489 sqlite3_finalize(pStmt);
2490 if( nCol==0 ) {
2491 return TCL_ERROR;
2492 }
2493 zSql = malloc( nByte + 50 + nCol*2 );
2494 if( zSql==0 ) {
drha198f2b2014-02-07 19:26:13 +00002495 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002496 return TCL_ERROR;
2497 }
2498 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2499 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002500 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002501 for(i=1; i<nCol; i++){
2502 zSql[j++] = ',';
2503 zSql[j++] = '?';
2504 }
2505 zSql[j++] = ')';
2506 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002507 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002508 free(zSql);
2509 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002510 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002511 sqlite3_finalize(pStmt);
2512 return TCL_ERROR;
2513 }
2514 in = fopen(zFile, "rb");
2515 if( in==0 ){
drhea8f0a12017-01-12 11:50:08 +00002516 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002517 sqlite3_finalize(pStmt);
2518 return TCL_ERROR;
2519 }
2520 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2521 if( azCol==0 ) {
drha198f2b2014-02-07 19:26:13 +00002522 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh43617e92006-03-06 20:55:46 +00002523 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002524 return TCL_ERROR;
2525 }
drh37527852006-03-16 16:19:56 +00002526 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002527 zCommit = "COMMIT";
2528 while( (zLine = local_getline(0, in))!=0 ){
2529 char *z;
drh19e2d372005-08-29 23:00:03 +00002530 lineno++;
2531 azCol[0] = zLine;
2532 for(i=0, z=zLine; *z; z++){
2533 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2534 *z = 0;
2535 i++;
2536 if( i<nCol ){
2537 azCol[i] = &z[nSep];
2538 z += nSep-1;
2539 }
2540 }
2541 }
2542 if( i+1!=nCol ){
2543 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002544 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002545 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002546 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002547 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002548 "Error: %s line %d: expected %d columns of data but found %d",
2549 zFile, lineno, nCol, i+1);
drha198f2b2014-02-07 19:26:13 +00002550 Tcl_AppendResult(interp, zErr, (char*)0);
drhc1f44942006-05-10 14:39:13 +00002551 free(zErr);
2552 }
drh19e2d372005-08-29 23:00:03 +00002553 zCommit = "ROLLBACK";
2554 break;
2555 }
2556 for(i=0; i<nCol; i++){
2557 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002558 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
mistachkinb56660f2016-07-14 21:26:09 +00002559 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002560 ){
drh19e2d372005-08-29 23:00:03 +00002561 sqlite3_bind_null(pStmt, i+1);
2562 }else{
2563 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2564 }
2565 }
2566 sqlite3_step(pStmt);
2567 rc = sqlite3_reset(pStmt);
2568 free(zLine);
2569 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00002570 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002571 zCommit = "ROLLBACK";
2572 break;
2573 }
2574 }
2575 free(azCol);
2576 fclose(in);
2577 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002578 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002579
2580 if( zCommit[0] == 'C' ){
2581 /* success, set result as number of lines processed */
2582 pResult = Tcl_GetObjResult(interp);
2583 Tcl_SetIntObj(pResult, lineno);
2584 rc = TCL_OK;
2585 }else{
2586 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002587 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drha198f2b2014-02-07 19:26:13 +00002588 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2589 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002590 rc = TCL_ERROR;
2591 }
2592 break;
2593 }
2594
drhdcd997e2003-01-31 17:21:49 +00002595 /*
drh6ca64482019-01-22 16:06:20 +00002596 ** $db deserialize ?-maxsize N? ?-readonly BOOL? ?DATABASE? VALUE
drhcb7d5412018-01-03 16:49:52 +00002597 **
2598 ** Reopen DATABASE (default "main") using the content in $VALUE
2599 */
2600 case DB_DESERIALIZE: {
drh9c6396e2018-03-06 21:43:19 +00002601#ifndef SQLITE_ENABLE_DESERIALIZE
drh3ec86652018-01-03 19:03:31 +00002602 Tcl_AppendResult(interp, "MEMDB not available in this build",
2603 (char*)0);
2604 rc = TCL_ERROR;
2605#else
drh6ca64482019-01-22 16:06:20 +00002606 const char *zSchema = 0;
2607 Tcl_Obj *pValue = 0;
drh3ec86652018-01-03 19:03:31 +00002608 unsigned char *pBA;
2609 unsigned char *pData;
2610 int len, xrc;
drh6ca64482019-01-22 16:06:20 +00002611 sqlite3_int64 mxSize = 0;
2612 int i;
2613 int isReadonly = 0;
2614
2615
2616 if( objc<3 ){
drh3ec86652018-01-03 19:03:31 +00002617 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? VALUE");
2618 rc = TCL_ERROR;
2619 break;
2620 }
drh6ca64482019-01-22 16:06:20 +00002621 for(i=2; i<objc-1; i++){
2622 const char *z = Tcl_GetString(objv[i]);
2623 if( strcmp(z,"-maxsize")==0 && i<objc-2 ){
2624 rc = Tcl_GetWideIntFromObj(interp, objv[++i], &mxSize);
2625 if( rc ) goto deserialize_error;
2626 continue;
2627 }
2628 if( strcmp(z,"-readonly")==0 && i<objc-2 ){
2629 rc = Tcl_GetBooleanFromObj(interp, objv[++i], &isReadonly);
2630 if( rc ) goto deserialize_error;
2631 continue;
2632 }
2633 if( zSchema==0 && i==objc-2 && z[0]!='-' ){
2634 zSchema = z;
2635 continue;
2636 }
2637 Tcl_AppendResult(interp, "unknown option: ", z, (char*)0);
2638 rc = TCL_ERROR;
2639 goto deserialize_error;
2640 }
2641 pValue = objv[objc-1];
drh3ec86652018-01-03 19:03:31 +00002642 pBA = Tcl_GetByteArrayFromObj(pValue, &len);
2643 pData = sqlite3_malloc64( len );
drha5bb4352018-01-03 23:40:02 +00002644 if( pData==0 && len>0 ){
drh3ec86652018-01-03 19:03:31 +00002645 Tcl_AppendResult(interp, "out of memory", (char*)0);
2646 rc = TCL_ERROR;
2647 }else{
drh6ca64482019-01-22 16:06:20 +00002648 int flags;
drha5bb4352018-01-03 23:40:02 +00002649 if( len>0 ) memcpy(pData, pBA, len);
drh6ca64482019-01-22 16:06:20 +00002650 if( isReadonly ){
2651 flags = SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_READONLY;
2652 }else{
2653 flags = SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_RESIZEABLE;
2654 }
2655 xrc = sqlite3_deserialize(pDb->db, zSchema, pData, len, len, flags);
drh3ec86652018-01-03 19:03:31 +00002656 if( xrc ){
2657 Tcl_AppendResult(interp, "unable to set MEMDB content", (char*)0);
2658 rc = TCL_ERROR;
2659 }
drh6ca64482019-01-22 16:06:20 +00002660 if( mxSize>0 ){
2661 sqlite3_file_control(pDb->db, zSchema,SQLITE_FCNTL_SIZE_LIMIT,&mxSize);
2662 }
drh3ec86652018-01-03 19:03:31 +00002663 }
drh6ca64482019-01-22 16:06:20 +00002664deserialize_error:
drh3ec86652018-01-03 19:03:31 +00002665#endif
drhcb7d5412018-01-03 16:49:52 +00002666 break;
2667 }
2668
2669 /*
drh41449052006-07-06 17:08:48 +00002670 ** $db enable_load_extension BOOLEAN
2671 **
2672 ** Turn the extension loading feature on or off. It if off by
2673 ** default.
2674 */
2675 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002676#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002677 int onoff;
2678 if( objc!=3 ){
2679 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2680 return TCL_ERROR;
2681 }
2682 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2683 return TCL_ERROR;
2684 }
2685 sqlite3_enable_load_extension(pDb->db, onoff);
2686 break;
drhf533acc2006-12-19 18:57:11 +00002687#else
2688 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
drha198f2b2014-02-07 19:26:13 +00002689 (char*)0);
drhf533acc2006-12-19 18:57:11 +00002690 return TCL_ERROR;
2691#endif
drh41449052006-07-06 17:08:48 +00002692 }
2693
2694 /*
drhdcd997e2003-01-31 17:21:49 +00002695 ** $db errorcode
2696 **
2697 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002698 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002699 */
2700 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002701 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002702 break;
2703 }
dan4a4c11a2009-10-06 14:59:02 +00002704
2705 /*
2706 ** $db exists $sql
2707 ** $db onecolumn $sql
2708 **
2709 ** The onecolumn method is the equivalent of:
2710 ** lindex [$db eval $sql] 0
2711 */
mistachkinb56660f2016-07-14 21:26:09 +00002712 case DB_EXISTS:
dan4a4c11a2009-10-06 14:59:02 +00002713 case DB_ONECOLUMN: {
drhedc40242016-06-13 12:34:38 +00002714 Tcl_Obj *pResult = 0;
dan4a4c11a2009-10-06 14:59:02 +00002715 DbEvalContext sEval;
2716 if( objc!=3 ){
2717 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2718 return TCL_ERROR;
2719 }
2720
drhaf38cdb2017-06-26 21:08:32 +00002721 dbEvalInit(&sEval, pDb, objv[2], 0, 0);
dan4a4c11a2009-10-06 14:59:02 +00002722 rc = dbEvalStep(&sEval);
2723 if( choice==DB_ONECOLUMN ){
2724 if( rc==TCL_OK ){
drhedc40242016-06-13 12:34:38 +00002725 pResult = dbEvalColumnValue(&sEval, 0);
dand5f12cd2011-08-18 17:47:57 +00002726 }else if( rc==TCL_BREAK ){
2727 Tcl_ResetResult(interp);
dan4a4c11a2009-10-06 14:59:02 +00002728 }
2729 }else if( rc==TCL_BREAK || rc==TCL_OK ){
drhedc40242016-06-13 12:34:38 +00002730 pResult = Tcl_NewBooleanObj(rc==TCL_OK);
dan4a4c11a2009-10-06 14:59:02 +00002731 }
2732 dbEvalFinalize(&sEval);
drhedc40242016-06-13 12:34:38 +00002733 if( pResult ) Tcl_SetObjResult(interp, pResult);
dan4a4c11a2009-10-06 14:59:02 +00002734
2735 if( rc==TCL_BREAK ){
2736 rc = TCL_OK;
2737 }
2738 break;
2739 }
mistachkinb56660f2016-07-14 21:26:09 +00002740
drh75897232000-05-29 14:26:00 +00002741 /*
drhaf38cdb2017-06-26 21:08:32 +00002742 ** $db eval ?options? $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002743 **
2744 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002745 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002746 ** If "array" and "code" are omitted, then no callback is every invoked.
2747 ** If "array" is an empty string, then the values are placed in variables
2748 ** that have the same name as the fields extracted by the query.
2749 */
dan4a4c11a2009-10-06 14:59:02 +00002750 case DB_EVAL: {
drhaf38cdb2017-06-26 21:08:32 +00002751 int evalFlags = 0;
2752 const char *zOpt;
2753 while( objc>3 && (zOpt = Tcl_GetString(objv[2]))!=0 && zOpt[0]=='-' ){
2754 if( strcmp(zOpt, "-withoutnulls")==0 ){
2755 evalFlags |= SQLITE_EVAL_WITHOUTNULLS;
2756 }
2757 else{
2758 Tcl_AppendResult(interp, "unknown option: \"", zOpt, "\"", (void*)0);
2759 return TCL_ERROR;
2760 }
2761 objc--;
2762 objv++;
2763 }
dan4a4c11a2009-10-06 14:59:02 +00002764 if( objc<3 || objc>5 ){
drhaf38cdb2017-06-26 21:08:32 +00002765 Tcl_WrongNumArgs(interp, 2, objv,
2766 "?OPTIONS? SQL ?ARRAY-NAME? ?SCRIPT?");
dan4a4c11a2009-10-06 14:59:02 +00002767 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002768 }
dan4a4c11a2009-10-06 14:59:02 +00002769
drh92febd92004-08-20 18:34:20 +00002770 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002771 DbEvalContext sEval;
2772 Tcl_Obj *pRet = Tcl_NewObj();
2773 Tcl_IncrRefCount(pRet);
drhaf38cdb2017-06-26 21:08:32 +00002774 dbEvalInit(&sEval, pDb, objv[2], 0, 0);
dan4a4c11a2009-10-06 14:59:02 +00002775 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2776 int i;
2777 int nCol;
2778 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002779 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002780 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002781 }
2782 }
dan4a4c11a2009-10-06 14:59:02 +00002783 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002784 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002785 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002786 rc = TCL_OK;
2787 }
drh1807ce32004-09-07 13:20:35 +00002788 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002789 }else{
mistachkin8e189222015-04-19 21:43:16 +00002790 ClientData cd2[2];
dan4a4c11a2009-10-06 14:59:02 +00002791 DbEvalContext *p;
2792 Tcl_Obj *pArray = 0;
2793 Tcl_Obj *pScript;
2794
drhaf38cdb2017-06-26 21:08:32 +00002795 if( objc>=5 && *(char *)Tcl_GetString(objv[3]) ){
dan4a4c11a2009-10-06 14:59:02 +00002796 pArray = objv[3];
2797 }
2798 pScript = objv[objc-1];
2799 Tcl_IncrRefCount(pScript);
mistachkinb56660f2016-07-14 21:26:09 +00002800
dan4a4c11a2009-10-06 14:59:02 +00002801 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
drhaf38cdb2017-06-26 21:08:32 +00002802 dbEvalInit(p, pDb, objv[2], pArray, evalFlags);
dan4a4c11a2009-10-06 14:59:02 +00002803
mistachkin8e189222015-04-19 21:43:16 +00002804 cd2[0] = (void *)p;
2805 cd2[1] = (void *)pScript;
2806 rc = DbEvalNextCmd(cd2, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002807 }
danielk197730ccda12004-05-27 12:11:31 +00002808 break;
2809 }
drhbec3f402000-08-04 13:49:02 +00002810
2811 /*
drh42d2fce2019-08-15 20:04:09 +00002812 ** $db function NAME [OPTIONS] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002813 **
2814 ** Create a new SQL function called NAME. Whenever that function is
2815 ** called, invoke SCRIPT to evaluate the function.
drh42d2fce2019-08-15 20:04:09 +00002816 **
2817 ** Options:
2818 ** --argcount N Function has exactly N arguments
2819 ** --deterministic The function is pure
2820 ** --directonly Prohibit use inside triggers and views
2821 ** --returntype TYPE Specify the return type of the function
drhcabb0812002-09-14 13:47:32 +00002822 */
2823 case DB_FUNCTION: {
dan3df30592015-03-13 08:31:54 +00002824 int flags = SQLITE_UTF8;
drhcabb0812002-09-14 13:47:32 +00002825 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002826 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002827 char *zName;
drhe3602be2008-09-09 12:31:33 +00002828 int nArg = -1;
dan3df30592015-03-13 08:31:54 +00002829 int i;
dan89d24932019-02-27 16:38:19 +00002830 int eType = SQLITE_NULL;
dan3df30592015-03-13 08:31:54 +00002831 if( objc<4 ){
2832 Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
2833 return TCL_ERROR;
2834 }
2835 for(i=3; i<(objc-1); i++){
2836 const char *z = Tcl_GetString(objv[i]);
drh4f21c4a2008-12-10 22:15:00 +00002837 int n = strlen30(z);
dan89d24932019-02-27 16:38:19 +00002838 if( n>1 && strncmp(z, "-argcount",n)==0 ){
dan3df30592015-03-13 08:31:54 +00002839 if( i==(objc-2) ){
drhea8f0a12017-01-12 11:50:08 +00002840 Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0);
dan3df30592015-03-13 08:31:54 +00002841 return TCL_ERROR;
2842 }
2843 if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002844 if( nArg<0 ){
2845 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2846 (char*)0);
2847 return TCL_ERROR;
2848 }
dan3df30592015-03-13 08:31:54 +00002849 i++;
2850 }else
dan89d24932019-02-27 16:38:19 +00002851 if( n>1 && strncmp(z, "-deterministic",n)==0 ){
dan3df30592015-03-13 08:31:54 +00002852 flags |= SQLITE_DETERMINISTIC;
dan89d24932019-02-27 16:38:19 +00002853 }else
drh42d2fce2019-08-15 20:04:09 +00002854 if( n>1 && strncmp(z, "-directonly",n)==0 ){
2855 flags |= SQLITE_DIRECTONLY;
2856 }else
dan89d24932019-02-27 16:38:19 +00002857 if( n>1 && strncmp(z, "-returntype", n)==0 ){
2858 const char *azType[] = {"integer", "real", "text", "blob", "any", 0};
2859 assert( SQLITE_INTEGER==1 && SQLITE_FLOAT==2 && SQLITE_TEXT==3 );
2860 assert( SQLITE_BLOB==4 && SQLITE_NULL==5 );
2861 if( i==(objc-2) ){
2862 Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0);
2863 return TCL_ERROR;
2864 }
2865 i++;
2866 if( Tcl_GetIndexFromObj(interp, objv[i], azType, "type", 0, &eType) ){
2867 return TCL_ERROR;
2868 }
2869 eType++;
dan3df30592015-03-13 08:31:54 +00002870 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002871 Tcl_AppendResult(interp, "bad option \"", z,
drh42d2fce2019-08-15 20:04:09 +00002872 "\": must be -argcount, -deterministic, -directonly,"
2873 " or -returntype", (char*)0
dan3df30592015-03-13 08:31:54 +00002874 );
2875 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002876 }
drhcabb0812002-09-14 13:47:32 +00002877 }
dan3df30592015-03-13 08:31:54 +00002878
2879 pScript = objv[objc-1];
drhcabb0812002-09-14 13:47:32 +00002880 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002881 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002882 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002883 if( pFunc->pScript ){
2884 Tcl_DecrRefCount(pFunc->pScript);
2885 }
2886 pFunc->pScript = pScript;
2887 Tcl_IncrRefCount(pScript);
2888 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
dan89d24932019-02-27 16:38:19 +00002889 pFunc->eType = eType;
dan3df30592015-03-13 08:31:54 +00002890 rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
danielk1977d8123362004-06-12 09:25:12 +00002891 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002892 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002893 rc = TCL_ERROR;
2894 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002895 }
drhcabb0812002-09-14 13:47:32 +00002896 break;
2897 }
2898
2899 /*
danielk19778cbadb02007-05-03 16:31:26 +00002900 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002901 */
2902 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002903#ifdef SQLITE_OMIT_INCRBLOB
drha198f2b2014-02-07 19:26:13 +00002904 Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
danielk197732a0d8b2007-05-04 19:03:02 +00002905 return TCL_ERROR;
2906#else
danielk19778cbadb02007-05-03 16:31:26 +00002907 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002908 const char *zDb = "main";
2909 const char *zTable;
2910 const char *zColumn;
drhb3f787f2012-09-29 14:45:54 +00002911 Tcl_WideInt iRow;
danielk1977b4e9af92007-05-01 17:49:49 +00002912
danielk19778cbadb02007-05-03 16:31:26 +00002913 /* Check for the -readonly option */
2914 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2915 isReadonly = 1;
2916 }
2917
2918 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2919 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002920 return TCL_ERROR;
2921 }
2922
danielk19778cbadb02007-05-03 16:31:26 +00002923 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002924 zDb = Tcl_GetString(objv[2]);
2925 }
2926 zTable = Tcl_GetString(objv[objc-3]);
2927 zColumn = Tcl_GetString(objv[objc-2]);
2928 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2929
2930 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002931 rc = createIncrblobChannel(
danedf5b162014-08-19 09:15:41 +00002932 interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
danielk19778cbadb02007-05-03 16:31:26 +00002933 );
danielk1977b4e9af92007-05-01 17:49:49 +00002934 }
danielk197732a0d8b2007-05-04 19:03:02 +00002935#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002936 break;
2937 }
2938
2939 /*
drhf11bded2006-07-17 00:02:44 +00002940 ** $db interrupt
2941 **
2942 ** Interrupt the execution of the inner-most SQL interpreter. This
2943 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2944 */
2945 case DB_INTERRUPT: {
2946 sqlite3_interrupt(pDb->db);
2947 break;
2948 }
2949
2950 /*
drh19e2d372005-08-29 23:00:03 +00002951 ** $db nullvalue ?STRING?
2952 **
2953 ** Change text used when a NULL comes back from the database. If ?STRING?
2954 ** is not present, then the current string used for NULL is returned.
2955 ** If STRING is present, then STRING is returned.
2956 **
2957 */
2958 case DB_NULLVALUE: {
2959 if( objc!=2 && objc!=3 ){
2960 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2961 return TCL_ERROR;
2962 }
2963 if( objc==3 ){
2964 int len;
2965 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2966 if( pDb->zNull ){
2967 Tcl_Free(pDb->zNull);
2968 }
2969 if( zNull && len>0 ){
2970 pDb->zNull = Tcl_Alloc( len + 1 );
drh7fd33922011-06-20 19:00:30 +00002971 memcpy(pDb->zNull, zNull, len);
drh19e2d372005-08-29 23:00:03 +00002972 pDb->zNull[len] = '\0';
2973 }else{
2974 pDb->zNull = 0;
2975 }
2976 }
drhc45e6712012-10-03 11:02:33 +00002977 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
drh19e2d372005-08-29 23:00:03 +00002978 break;
2979 }
2980
2981 /*
mistachkinb56660f2016-07-14 21:26:09 +00002982 ** $db last_insert_rowid
drhaf9ff332002-01-16 21:00:27 +00002983 **
2984 ** Return an integer which is the ROWID for the most recent insert.
2985 */
2986 case DB_LAST_INSERT_ROWID: {
2987 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002988 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002989 if( objc!=2 ){
2990 Tcl_WrongNumArgs(interp, 2, objv, "");
2991 return TCL_ERROR;
2992 }
danielk19776f8a5032004-05-10 10:34:51 +00002993 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002994 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002995 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002996 break;
2997 }
2998
2999 /*
dan4a4c11a2009-10-06 14:59:02 +00003000 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00003001 */
drh1807ce32004-09-07 13:20:35 +00003002
3003 /* $db progress ?N CALLBACK?
mistachkinb56660f2016-07-14 21:26:09 +00003004 **
drh1807ce32004-09-07 13:20:35 +00003005 ** Invoke the given callback every N virtual machine opcodes while executing
3006 ** queries.
3007 */
3008 case DB_PROGRESS: {
3009 if( objc==2 ){
3010 if( pDb->zProgress ){
drha198f2b2014-02-07 19:26:13 +00003011 Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
drh1807ce32004-09-07 13:20:35 +00003012 }
3013 }else if( objc==4 ){
3014 char *zProgress;
3015 int len;
3016 int N;
3017 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00003018 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00003019 };
3020 if( pDb->zProgress ){
3021 Tcl_Free(pDb->zProgress);
3022 }
3023 zProgress = Tcl_GetStringFromObj(objv[3], &len);
3024 if( zProgress && len>0 ){
3025 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00003026 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00003027 }else{
3028 pDb->zProgress = 0;
3029 }
3030#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
3031 if( pDb->zProgress ){
3032 pDb->interp = interp;
3033 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
3034 }else{
3035 sqlite3_progress_handler(pDb->db, 0, 0, 0);
3036 }
3037#endif
3038 }else{
3039 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00003040 return TCL_ERROR;
3041 }
drh5d9d7572003-08-19 14:31:01 +00003042 break;
3043 }
3044
drh19e2d372005-08-29 23:00:03 +00003045 /* $db profile ?CALLBACK?
3046 **
3047 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
3048 ** that has run. The text of the SQL and the amount of elapse time are
3049 ** appended to CALLBACK before the script is run.
3050 */
3051 case DB_PROFILE: {
3052 if( objc>3 ){
3053 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
3054 return TCL_ERROR;
3055 }else if( objc==2 ){
3056 if( pDb->zProfile ){
drha198f2b2014-02-07 19:26:13 +00003057 Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
drh19e2d372005-08-29 23:00:03 +00003058 }
3059 }else{
3060 char *zProfile;
3061 int len;
3062 if( pDb->zProfile ){
3063 Tcl_Free(pDb->zProfile);
3064 }
3065 zProfile = Tcl_GetStringFromObj(objv[2], &len);
3066 if( zProfile && len>0 ){
3067 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00003068 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00003069 }else{
3070 pDb->zProfile = 0;
3071 }
drh2eb22af2016-09-10 19:51:40 +00003072#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3073 !defined(SQLITE_OMIT_DEPRECATED)
drh19e2d372005-08-29 23:00:03 +00003074 if( pDb->zProfile ){
3075 pDb->interp = interp;
3076 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
3077 }else{
3078 sqlite3_profile(pDb->db, 0, 0);
3079 }
3080#endif
3081 }
3082 break;
3083 }
3084
drh5d9d7572003-08-19 14:31:01 +00003085 /*
drh22fbcb82004-02-01 01:22:50 +00003086 ** $db rekey KEY
3087 **
3088 ** Change the encryption key on the currently open database.
3089 */
3090 case DB_REKEY: {
drh32f57d42016-03-16 01:03:10 +00003091#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh22fbcb82004-02-01 01:22:50 +00003092 int nKey;
3093 void *pKey;
drhb07028f2011-10-14 21:49:18 +00003094#endif
drh22fbcb82004-02-01 01:22:50 +00003095 if( objc!=3 ){
3096 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
3097 return TCL_ERROR;
3098 }
drh32f57d42016-03-16 01:03:10 +00003099#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00003100 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh2011d5f2004-07-22 02:40:37 +00003101 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00003102 if( rc ){
drha198f2b2014-02-07 19:26:13 +00003103 Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
drh22fbcb82004-02-01 01:22:50 +00003104 rc = TCL_ERROR;
3105 }
3106#endif
3107 break;
3108 }
3109
drhdc2c4912009-02-04 22:46:47 +00003110 /* $db restore ?DATABASE? FILENAME
3111 **
mistachkinb56660f2016-07-14 21:26:09 +00003112 ** Open a database file named FILENAME. Transfer the content
drhdc2c4912009-02-04 22:46:47 +00003113 ** of FILENAME into the local database DATABASE (default: "main").
3114 */
3115 case DB_RESTORE: {
3116 const char *zSrcFile;
3117 const char *zDestDb;
3118 sqlite3 *pSrc;
3119 sqlite3_backup *pBackup;
3120 int nTimeout = 0;
3121
3122 if( objc==3 ){
3123 zDestDb = "main";
3124 zSrcFile = Tcl_GetString(objv[2]);
3125 }else if( objc==4 ){
3126 zDestDb = Tcl_GetString(objv[2]);
3127 zSrcFile = Tcl_GetString(objv[3]);
3128 }else{
3129 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
3130 return TCL_ERROR;
3131 }
drh147ef392016-01-22 23:17:51 +00003132 rc = sqlite3_open_v2(zSrcFile, &pSrc,
3133 SQLITE_OPEN_READONLY | pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00003134 if( rc!=SQLITE_OK ){
3135 Tcl_AppendResult(interp, "cannot open source database: ",
3136 sqlite3_errmsg(pSrc), (char*)0);
3137 sqlite3_close(pSrc);
3138 return TCL_ERROR;
3139 }
3140 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
3141 if( pBackup==0 ){
3142 Tcl_AppendResult(interp, "restore failed: ",
3143 sqlite3_errmsg(pDb->db), (char*)0);
3144 sqlite3_close(pSrc);
3145 return TCL_ERROR;
3146 }
3147 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
3148 || rc==SQLITE_BUSY ){
3149 if( rc==SQLITE_BUSY ){
3150 if( nTimeout++ >= 3 ) break;
3151 sqlite3_sleep(100);
3152 }
3153 }
3154 sqlite3_backup_finish(pBackup);
3155 if( rc==SQLITE_DONE ){
3156 rc = TCL_OK;
3157 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
3158 Tcl_AppendResult(interp, "restore failed: source database busy",
3159 (char*)0);
3160 rc = TCL_ERROR;
3161 }else{
3162 Tcl_AppendResult(interp, "restore failed: ",
3163 sqlite3_errmsg(pDb->db), (char*)0);
3164 rc = TCL_ERROR;
3165 }
3166 sqlite3_close(pSrc);
3167 break;
3168 }
3169
drh22fbcb82004-02-01 01:22:50 +00003170 /*
drhcb7d5412018-01-03 16:49:52 +00003171 ** $db serialize ?DATABASE?
3172 **
3173 ** Return a serialization of a database.
3174 */
3175 case DB_SERIALIZE: {
drh9c6396e2018-03-06 21:43:19 +00003176#ifndef SQLITE_ENABLE_DESERIALIZE
drhcb7d5412018-01-03 16:49:52 +00003177 Tcl_AppendResult(interp, "MEMDB not available in this build",
3178 (char*)0);
3179 rc = TCL_ERROR;
3180#else
3181 const char *zSchema = objc>=3 ? Tcl_GetString(objv[2]) : "main";
3182 sqlite3_int64 sz = 0;
3183 unsigned char *pData;
3184 if( objc!=2 && objc!=3 ){
3185 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE?");
3186 rc = TCL_ERROR;
3187 }else{
3188 int needFree;
3189 pData = sqlite3_serialize(pDb->db, zSchema, &sz, SQLITE_SERIALIZE_NOCOPY);
3190 if( pData ){
3191 needFree = 0;
3192 }else{
3193 pData = sqlite3_serialize(pDb->db, zSchema, &sz, 0);
3194 needFree = 1;
3195 }
3196 Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(pData,sz));
3197 if( needFree ) sqlite3_free(pData);
3198 }
3199#endif
3200 break;
3201 }
3202
3203 /*
danc456a762017-06-22 16:51:16 +00003204 ** $db status (step|sort|autoindex|vmstep)
drhd1d38482008-10-07 23:46:38 +00003205 **
mistachkinb56660f2016-07-14 21:26:09 +00003206 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
drhd1d38482008-10-07 23:46:38 +00003207 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
3208 */
3209 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00003210 int v;
3211 const char *zOp;
3212 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00003213 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00003214 return TCL_ERROR;
3215 }
3216 zOp = Tcl_GetString(objv[2]);
3217 if( strcmp(zOp, "step")==0 ){
3218 v = pDb->nStep;
3219 }else if( strcmp(zOp, "sort")==0 ){
3220 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00003221 }else if( strcmp(zOp, "autoindex")==0 ){
3222 v = pDb->nIndex;
danc456a762017-06-22 16:51:16 +00003223 }else if( strcmp(zOp, "vmstep")==0 ){
3224 v = pDb->nVMStep;
drhd1d38482008-10-07 23:46:38 +00003225 }else{
mistachkinb56660f2016-07-14 21:26:09 +00003226 Tcl_AppendResult(interp,
danc456a762017-06-22 16:51:16 +00003227 "bad argument: should be autoindex, step, sort or vmstep",
drhd1d38482008-10-07 23:46:38 +00003228 (char*)0);
3229 return TCL_ERROR;
3230 }
3231 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
3232 break;
3233 }
mistachkinb56660f2016-07-14 21:26:09 +00003234
drhd1d38482008-10-07 23:46:38 +00003235 /*
drhbec3f402000-08-04 13:49:02 +00003236 ** $db timeout MILLESECONDS
3237 **
3238 ** Delay for the number of milliseconds specified when a file is locked.
3239 */
drh6d313162000-09-21 13:01:35 +00003240 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00003241 int ms;
drh6d313162000-09-21 13:01:35 +00003242 if( objc!=3 ){
3243 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00003244 return TCL_ERROR;
3245 }
drh6d313162000-09-21 13:01:35 +00003246 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00003247 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00003248 break;
drh75897232000-05-29 14:26:00 +00003249 }
mistachkinb56660f2016-07-14 21:26:09 +00003250
danielk197755c45f22005-04-03 23:54:43 +00003251 /*
drh0f14e2e2004-06-29 12:39:08 +00003252 ** $db total_changes
3253 **
mistachkinb56660f2016-07-14 21:26:09 +00003254 ** Return the number of rows that were modified, inserted, or deleted
drh0f14e2e2004-06-29 12:39:08 +00003255 ** since the database handle was created.
3256 */
3257 case DB_TOTAL_CHANGES: {
3258 Tcl_Obj *pResult;
3259 if( objc!=2 ){
3260 Tcl_WrongNumArgs(interp, 2, objv, "");
3261 return TCL_ERROR;
3262 }
3263 pResult = Tcl_GetObjResult(interp);
3264 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
3265 break;
3266 }
3267
drhb5a20d32003-04-23 12:25:23 +00003268 /* $db trace ?CALLBACK?
3269 **
3270 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
3271 ** that is executed. The text of the SQL is appended to CALLBACK before
3272 ** it is executed.
3273 */
3274 case DB_TRACE: {
3275 if( objc>3 ){
3276 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00003277 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00003278 }else if( objc==2 ){
3279 if( pDb->zTrace ){
drha198f2b2014-02-07 19:26:13 +00003280 Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
drhb5a20d32003-04-23 12:25:23 +00003281 }
3282 }else{
3283 char *zTrace;
3284 int len;
3285 if( pDb->zTrace ){
3286 Tcl_Free(pDb->zTrace);
3287 }
3288 zTrace = Tcl_GetStringFromObj(objv[2], &len);
3289 if( zTrace && len>0 ){
3290 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00003291 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00003292 }else{
3293 pDb->zTrace = 0;
3294 }
drh2eb22af2016-09-10 19:51:40 +00003295#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3296 !defined(SQLITE_OMIT_DEPRECATED)
drhb5a20d32003-04-23 12:25:23 +00003297 if( pDb->zTrace ){
3298 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00003299 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00003300 }else{
danielk19776f8a5032004-05-10 10:34:51 +00003301 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00003302 }
drh19e2d372005-08-29 23:00:03 +00003303#endif
drhb5a20d32003-04-23 12:25:23 +00003304 }
3305 break;
3306 }
3307
mistachkinb56660f2016-07-14 21:26:09 +00003308 /* $db trace_v2 ?CALLBACK? ?MASK?
3309 **
3310 ** Make arrangements to invoke the CALLBACK routine for each trace event
3311 ** matching the mask that is generated. The parameters are appended to
3312 ** CALLBACK before it is executed.
3313 */
3314 case DB_TRACE_V2: {
3315 if( objc>4 ){
3316 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK? ?MASK?");
3317 return TCL_ERROR;
3318 }else if( objc==2 ){
3319 if( pDb->zTraceV2 ){
3320 Tcl_AppendResult(interp, pDb->zTraceV2, (char*)0);
3321 }
3322 }else{
mistachkinb56660f2016-07-14 21:26:09 +00003323 char *zTraceV2;
3324 int len;
mistachkinb52dcd82016-07-14 23:17:03 +00003325 Tcl_WideInt wMask = 0;
mistachkinb56660f2016-07-14 21:26:09 +00003326 if( objc==4 ){
mistachkinb52dcd82016-07-14 23:17:03 +00003327 static const char *TTYPE_strs[] = {
3328 "statement", "profile", "row", "close", 0
3329 };
3330 enum TTYPE_enum {
3331 TTYPE_STMT, TTYPE_PROFILE, TTYPE_ROW, TTYPE_CLOSE
3332 };
3333 int i;
3334 if( TCL_OK!=Tcl_ListObjLength(interp, objv[3], &len) ){
mistachkinb56660f2016-07-14 21:26:09 +00003335 return TCL_ERROR;
3336 }
mistachkinb52dcd82016-07-14 23:17:03 +00003337 for(i=0; i<len; i++){
3338 Tcl_Obj *pObj;
3339 int ttype;
3340 if( TCL_OK!=Tcl_ListObjIndex(interp, objv[3], i, &pObj) ){
3341 return TCL_ERROR;
3342 }
3343 if( Tcl_GetIndexFromObj(interp, pObj, TTYPE_strs, "trace type",
3344 0, &ttype)!=TCL_OK ){
3345 Tcl_WideInt wType;
3346 Tcl_Obj *pError = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
3347 Tcl_IncrRefCount(pError);
3348 if( TCL_OK==Tcl_GetWideIntFromObj(interp, pObj, &wType) ){
3349 Tcl_DecrRefCount(pError);
3350 wMask |= wType;
3351 }else{
3352 Tcl_SetObjResult(interp, pError);
3353 Tcl_DecrRefCount(pError);
3354 return TCL_ERROR;
3355 }
3356 }else{
3357 switch( (enum TTYPE_enum)ttype ){
3358 case TTYPE_STMT: wMask |= SQLITE_TRACE_STMT; break;
3359 case TTYPE_PROFILE: wMask |= SQLITE_TRACE_PROFILE; break;
3360 case TTYPE_ROW: wMask |= SQLITE_TRACE_ROW; break;
3361 case TTYPE_CLOSE: wMask |= SQLITE_TRACE_CLOSE; break;
3362 }
3363 }
3364 }
mistachkinb56660f2016-07-14 21:26:09 +00003365 }else{
mistachkinb52dcd82016-07-14 23:17:03 +00003366 wMask = SQLITE_TRACE_STMT; /* use the "legacy" default */
mistachkinb56660f2016-07-14 21:26:09 +00003367 }
3368 if( pDb->zTraceV2 ){
3369 Tcl_Free(pDb->zTraceV2);
3370 }
3371 zTraceV2 = Tcl_GetStringFromObj(objv[2], &len);
3372 if( zTraceV2 && len>0 ){
3373 pDb->zTraceV2 = Tcl_Alloc( len + 1 );
3374 memcpy(pDb->zTraceV2, zTraceV2, len+1);
3375 }else{
3376 pDb->zTraceV2 = 0;
3377 }
3378#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3379 if( pDb->zTraceV2 ){
3380 pDb->interp = interp;
3381 sqlite3_trace_v2(pDb->db, (unsigned)wMask, DbTraceV2Handler, pDb);
3382 }else{
3383 sqlite3_trace_v2(pDb->db, 0, 0, 0);
3384 }
3385#endif
3386 }
3387 break;
3388 }
3389
drh3d214232005-08-02 12:21:08 +00003390 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
3391 **
3392 ** Start a new transaction (if we are not already in the midst of a
3393 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
3394 ** completes, either commit the transaction or roll it back if SCRIPT
3395 ** throws an exception. Or if no new transation was started, do nothing.
3396 ** pass the exception on up the stack.
3397 **
3398 ** This command was inspired by Dave Thomas's talk on Ruby at the
3399 ** 2005 O'Reilly Open Source Convention (OSCON).
3400 */
3401 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00003402 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00003403 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00003404 if( objc!=3 && objc!=4 ){
3405 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
3406 return TCL_ERROR;
3407 }
danielk1977cd38d522009-01-02 17:33:46 +00003408
dan4a4c11a2009-10-06 14:59:02 +00003409 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00003410 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00003411 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00003412 };
3413 enum TTYPE_enum {
3414 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
3415 };
3416 int ttype;
drhb5555e72005-08-02 17:15:14 +00003417 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00003418 0, &ttype) ){
3419 return TCL_ERROR;
3420 }
3421 switch( (enum TTYPE_enum)ttype ){
3422 case TTYPE_DEFERRED: /* no-op */; break;
3423 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
3424 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
3425 }
drh3d214232005-08-02 12:21:08 +00003426 }
danielk1977cd38d522009-01-02 17:33:46 +00003427 pScript = objv[objc-1];
3428
dan4a4c11a2009-10-06 14:59:02 +00003429 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00003430 pDb->disableAuth++;
3431 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
3432 pDb->disableAuth--;
3433 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00003434 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977cd38d522009-01-02 17:33:46 +00003435 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00003436 }
danielk1977cd38d522009-01-02 17:33:46 +00003437 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00003438
dan4a4c11a2009-10-06 14:59:02 +00003439 /* If using NRE, schedule a callback to invoke the script pScript, then
3440 ** a second callback to commit (or rollback) the transaction or savepoint
3441 ** opened above. If not using NRE, evaluate the script directly, then
mistachkinb56660f2016-07-14 21:26:09 +00003442 ** call function DbTransPostCmd() to commit (or rollback) the transaction
dan4a4c11a2009-10-06 14:59:02 +00003443 ** or savepoint. */
3444 if( DbUseNre() ){
3445 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
drha47941f2013-12-20 18:57:44 +00003446 (void)Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00003447 }else{
dan4a4c11a2009-10-06 14:59:02 +00003448 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00003449 }
3450 break;
3451 }
3452
danielk197794eb6a12005-12-15 15:22:08 +00003453 /*
danielk1977404ca072009-03-16 13:19:36 +00003454 ** $db unlock_notify ?script?
3455 */
3456 case DB_UNLOCK_NOTIFY: {
3457#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
drha198f2b2014-02-07 19:26:13 +00003458 Tcl_AppendResult(interp, "unlock_notify not available in this build",
3459 (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00003460 rc = TCL_ERROR;
3461#else
3462 if( objc!=2 && objc!=3 ){
3463 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3464 rc = TCL_ERROR;
3465 }else{
3466 void (*xNotify)(void **, int) = 0;
3467 void *pNotifyArg = 0;
3468
3469 if( pDb->pUnlockNotify ){
3470 Tcl_DecrRefCount(pDb->pUnlockNotify);
3471 pDb->pUnlockNotify = 0;
3472 }
mistachkinb56660f2016-07-14 21:26:09 +00003473
danielk1977404ca072009-03-16 13:19:36 +00003474 if( objc==3 ){
3475 xNotify = DbUnlockNotify;
3476 pNotifyArg = (void *)pDb;
3477 pDb->pUnlockNotify = objv[2];
3478 Tcl_IncrRefCount(pDb->pUnlockNotify);
3479 }
mistachkinb56660f2016-07-14 21:26:09 +00003480
danielk1977404ca072009-03-16 13:19:36 +00003481 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
drha198f2b2014-02-07 19:26:13 +00003482 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00003483 rc = TCL_ERROR;
3484 }
3485 }
3486#endif
3487 break;
3488 }
3489
drh304637c2011-03-18 16:47:27 +00003490 /*
3491 ** $db preupdate_hook count
3492 ** $db preupdate_hook hook ?SCRIPT?
3493 ** $db preupdate_hook new INDEX
3494 ** $db preupdate_hook old INDEX
3495 */
dan46c47d42011-03-01 18:42:07 +00003496 case DB_PREUPDATE: {
drh9b1c62d2011-03-30 21:04:43 +00003497#ifndef SQLITE_ENABLE_PREUPDATE_HOOK
dan2b519ab2016-12-06 19:33:42 +00003498 Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time",
3499 (char*)0);
drh9b1c62d2011-03-30 21:04:43 +00003500 rc = TCL_ERROR;
3501#else
dan1e7a2d42011-03-22 18:45:29 +00003502 static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
dan46c47d42011-03-01 18:42:07 +00003503 enum DbPreupdateSubCmd {
dan1e7a2d42011-03-22 18:45:29 +00003504 PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
dan46c47d42011-03-01 18:42:07 +00003505 };
3506 int iSub;
3507
3508 if( objc<3 ){
3509 Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
3510 }
3511 if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
3512 return TCL_ERROR;
3513 }
3514
3515 switch( (enum DbPreupdateSubCmd)iSub ){
3516 case PRE_COUNT: {
3517 int nCol = sqlite3_preupdate_count(pDb->db);
3518 Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
3519 break;
3520 }
3521
3522 case PRE_HOOK: {
3523 if( objc>4 ){
3524 Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
3525 return TCL_ERROR;
3526 }
3527 DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
3528 break;
3529 }
3530
dan1e7a2d42011-03-22 18:45:29 +00003531 case PRE_DEPTH: {
3532 Tcl_Obj *pRet;
3533 if( objc!=3 ){
3534 Tcl_WrongNumArgs(interp, 3, objv, "");
3535 return TCL_ERROR;
3536 }
3537 pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
3538 Tcl_SetObjResult(interp, pRet);
3539 break;
3540 }
3541
dan37db03b2011-03-16 19:59:18 +00003542 case PRE_NEW:
dan46c47d42011-03-01 18:42:07 +00003543 case PRE_OLD: {
3544 int iIdx;
dan37db03b2011-03-16 19:59:18 +00003545 sqlite3_value *pValue;
dan46c47d42011-03-01 18:42:07 +00003546 if( objc!=4 ){
3547 Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
3548 return TCL_ERROR;
3549 }
3550 if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
3551 return TCL_ERROR;
3552 }
3553
dan37db03b2011-03-16 19:59:18 +00003554 if( iSub==PRE_OLD ){
dan46c47d42011-03-01 18:42:07 +00003555 rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
dan37db03b2011-03-16 19:59:18 +00003556 }else{
3557 assert( iSub==PRE_NEW );
3558 rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
dan46c47d42011-03-01 18:42:07 +00003559 }
3560
dan37db03b2011-03-16 19:59:18 +00003561 if( rc==SQLITE_OK ){
drh304637c2011-03-18 16:47:27 +00003562 Tcl_Obj *pObj;
3563 pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
dan37db03b2011-03-16 19:59:18 +00003564 Tcl_SetObjResult(interp, pObj);
3565 }else{
drhea8f0a12017-01-12 11:50:08 +00003566 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
dan46c47d42011-03-01 18:42:07 +00003567 return TCL_ERROR;
3568 }
3569 }
3570 }
drh9b1c62d2011-03-30 21:04:43 +00003571#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +00003572 break;
3573 }
3574
danielk1977404ca072009-03-16 13:19:36 +00003575 /*
drh833bf962010-04-28 14:42:19 +00003576 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003577 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00003578 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003579 */
mistachkinb56660f2016-07-14 21:26:09 +00003580 case DB_WAL_HOOK:
3581 case DB_UPDATE_HOOK:
dan6566ebe2011-03-16 09:49:14 +00003582 case DB_ROLLBACK_HOOK: {
mistachkinb56660f2016-07-14 21:26:09 +00003583 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
danielk197771fd80b2005-12-16 06:54:01 +00003584 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3585 */
mistachkinb56660f2016-07-14 21:26:09 +00003586 Tcl_Obj **ppHook = 0;
dan46c47d42011-03-01 18:42:07 +00003587 if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
3588 if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
3589 if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
3590 if( objc>3 ){
danielk197794eb6a12005-12-15 15:22:08 +00003591 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3592 return TCL_ERROR;
3593 }
danielk197771fd80b2005-12-16 06:54:01 +00003594
dan46c47d42011-03-01 18:42:07 +00003595 DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00003596 break;
3597 }
3598
danielk19774397de52005-01-12 12:44:03 +00003599 /* $db version
3600 **
3601 ** Return the version string for this database.
3602 */
3603 case DB_VERSION: {
drh1df64702017-10-13 15:56:26 +00003604 int i;
3605 for(i=2; i<objc; i++){
3606 const char *zArg = Tcl_GetString(objv[i]);
3607 /* Optional arguments to $db version are used for testing purpose */
3608#ifdef SQLITE_TEST
3609 /* $db version -use-legacy-prepare BOOLEAN
3610 **
3611 ** Turn the use of legacy sqlite3_prepare() on or off.
3612 */
3613 if( strcmp(zArg, "-use-legacy-prepare")==0 && i+1<objc ){
3614 i++;
3615 if( Tcl_GetBooleanFromObj(interp, objv[i], &pDb->bLegacyPrepare) ){
3616 return TCL_ERROR;
3617 }
3618 }else
3619
3620 /* $db version -last-stmt-ptr
3621 **
3622 ** Return a string which is a hex encoding of the pointer to the
3623 ** most recent sqlite3_stmt in the statement cache.
3624 */
3625 if( strcmp(zArg, "-last-stmt-ptr")==0 ){
3626 char zBuf[100];
3627 sqlite3_snprintf(sizeof(zBuf), zBuf, "%p",
3628 pDb->stmtList ? pDb->stmtList->pStmt: 0);
3629 Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
3630 }else
3631#endif /* SQLITE_TEST */
3632 {
3633 Tcl_AppendResult(interp, "unknown argument: ", zArg, (char*)0);
3634 return TCL_ERROR;
3635 }
3636 }
3637 if( i==2 ){
3638 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
3639 }
danielk19774397de52005-01-12 12:44:03 +00003640 break;
3641 }
3642
tpoindex1067fe12004-12-17 15:41:11 +00003643
drh6d313162000-09-21 13:01:35 +00003644 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00003645 return rc;
drh75897232000-05-29 14:26:00 +00003646}
3647
drha2c8a952009-10-13 18:38:34 +00003648#if SQLITE_TCL_NRE
3649/*
3650** Adaptor that provides an objCmd interface to the NRE-enabled
3651** interface implementation.
3652*/
mistachkina121cc72016-07-28 18:06:52 +00003653static int SQLITE_TCLAPI DbObjCmdAdaptor(
drha2c8a952009-10-13 18:38:34 +00003654 void *cd,
3655 Tcl_Interp *interp,
3656 int objc,
3657 Tcl_Obj *const*objv
3658){
3659 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
3660}
3661#endif /* SQLITE_TCL_NRE */
3662
drh75897232000-05-29 14:26:00 +00003663/*
drh4dcac402018-01-03 13:20:02 +00003664** Issue the usage message when the "sqlite3" command arguments are
3665** incorrect.
3666*/
3667static int sqliteCmdUsage(
3668 Tcl_Interp *interp,
3669 Tcl_Obj *const*objv
3670){
3671 Tcl_WrongNumArgs(interp, 1, objv,
3672 "HANDLE ?FILENAME? ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
3673 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
3674#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3675 " ?-key CODECKEY?"
3676#endif
3677 );
3678 return TCL_ERROR;
3679}
3680
3681/*
drh3570ad92007-08-31 14:31:44 +00003682** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00003683** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00003684**
3685** This is the main Tcl command. When the "sqlite" Tcl command is
3686** invoked, this routine runs to process that command.
3687**
3688** The first argument, DBNAME, is an arbitrary name for a new
3689** database connection. This command creates a new command named
3690** DBNAME that is used to control that connection. The database
3691** connection is deleted when the DBNAME command is deleted.
3692**
drh3570ad92007-08-31 14:31:44 +00003693** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00003694**
drh75897232000-05-29 14:26:00 +00003695*/
mistachkin7617e4a2016-07-28 17:11:20 +00003696static int SQLITE_TCLAPI DbMain(
3697 void *cd,
3698 Tcl_Interp *interp,
3699 int objc,
3700 Tcl_Obj *const*objv
3701){
drhbec3f402000-08-04 13:49:02 +00003702 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00003703 const char *zArg;
drh75897232000-05-29 14:26:00 +00003704 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00003705 int i;
drh4dcac402018-01-03 13:20:02 +00003706 const char *zFile = 0;
drh3570ad92007-08-31 14:31:44 +00003707 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00003708 int flags;
drh882e8e42006-08-24 02:42:27 +00003709 Tcl_DString translatedFilename;
drh32f57d42016-03-16 01:03:10 +00003710#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00003711 void *pKey = 0;
3712 int nKey = 0;
3713#endif
mistachkin540ebf82012-09-10 07:29:29 +00003714 int rc;
drhd9da78a2009-03-24 15:08:09 +00003715
3716 /* In normal use, each TCL interpreter runs in a single thread. So
drh4dcac402018-01-03 13:20:02 +00003717 ** by default, we can turn off mutexing on SQLite database connections.
drhd9da78a2009-03-24 15:08:09 +00003718 ** However, for testing purposes it is useful to have mutexes turned
3719 ** on. So, by default, mutexes default off. But if compiled with
3720 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3721 */
3722#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3723 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3724#else
3725 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3726#endif
3727
drhc6727c82018-09-19 15:08:21 +00003728 if( objc==1 ) return sqliteCmdUsage(interp, objv);
drh22fbcb82004-02-01 01:22:50 +00003729 if( objc==2 ){
3730 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00003731 if( strcmp(zArg,"-version")==0 ){
drha198f2b2014-02-07 19:26:13 +00003732 Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
drh647cb0e2002-11-04 19:32:25 +00003733 return TCL_OK;
3734 }
drh72bf6a32016-01-07 02:06:55 +00003735 if( strcmp(zArg,"-sourceid")==0 ){
3736 Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0);
3737 return TCL_OK;
3738 }
drh9eb9e262004-02-11 02:18:05 +00003739 if( strcmp(zArg,"-has-codec")==0 ){
drh32f57d42016-03-16 01:03:10 +00003740#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drha198f2b2014-02-07 19:26:13 +00003741 Tcl_AppendResult(interp,"1",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003742#else
drha198f2b2014-02-07 19:26:13 +00003743 Tcl_AppendResult(interp,"0",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003744#endif
3745 return TCL_OK;
3746 }
drh4dcac402018-01-03 13:20:02 +00003747 if( zArg[0]=='-' ) return sqliteCmdUsage(interp, objv);
drhfbc3eab2001-04-06 16:13:42 +00003748 }
drh4dcac402018-01-03 13:20:02 +00003749 for(i=2; i<objc; i++){
drh3570ad92007-08-31 14:31:44 +00003750 zArg = Tcl_GetString(objv[i]);
drh4dcac402018-01-03 13:20:02 +00003751 if( zArg[0]!='-' ){
3752 if( zFile!=0 ) return sqliteCmdUsage(interp, objv);
3753 zFile = zArg;
3754 continue;
3755 }
3756 if( i==objc-1 ) return sqliteCmdUsage(interp, objv);
3757 i++;
drh22fbcb82004-02-01 01:22:50 +00003758 if( strcmp(zArg,"-key")==0 ){
drh32f57d42016-03-16 01:03:10 +00003759#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh4dcac402018-01-03 13:20:02 +00003760 pKey = Tcl_GetByteArrayFromObj(objv[i], &nKey);
drhb07028f2011-10-14 21:49:18 +00003761#endif
drh3570ad92007-08-31 14:31:44 +00003762 }else if( strcmp(zArg, "-vfs")==0 ){
drh4dcac402018-01-03 13:20:02 +00003763 zVfs = Tcl_GetString(objv[i]);
drh3570ad92007-08-31 14:31:44 +00003764 }else if( strcmp(zArg, "-readonly")==0 ){
3765 int b;
drh4dcac402018-01-03 13:20:02 +00003766 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
drh3570ad92007-08-31 14:31:44 +00003767 if( b ){
drh33f4e022007-09-03 15:19:34 +00003768 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00003769 flags |= SQLITE_OPEN_READONLY;
3770 }else{
3771 flags &= ~SQLITE_OPEN_READONLY;
3772 flags |= SQLITE_OPEN_READWRITE;
3773 }
3774 }else if( strcmp(zArg, "-create")==0 ){
3775 int b;
drh4dcac402018-01-03 13:20:02 +00003776 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00003777 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00003778 flags |= SQLITE_OPEN_CREATE;
3779 }else{
3780 flags &= ~SQLITE_OPEN_CREATE;
3781 }
danielk19779a6284c2008-07-10 17:52:49 +00003782 }else if( strcmp(zArg, "-nomutex")==0 ){
3783 int b;
drh4dcac402018-01-03 13:20:02 +00003784 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
danielk19779a6284c2008-07-10 17:52:49 +00003785 if( b ){
3786 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00003787 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00003788 }else{
3789 flags &= ~SQLITE_OPEN_NOMUTEX;
3790 }
danc431fd52011-06-27 16:55:50 +00003791 }else if( strcmp(zArg, "-fullmutex")==0 ){
drh039963a2008-09-03 00:43:15 +00003792 int b;
drh4dcac402018-01-03 13:20:02 +00003793 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
drh039963a2008-09-03 00:43:15 +00003794 if( b ){
3795 flags |= SQLITE_OPEN_FULLMUTEX;
3796 flags &= ~SQLITE_OPEN_NOMUTEX;
3797 }else{
3798 flags &= ~SQLITE_OPEN_FULLMUTEX;
3799 }
drhf12b3f62011-12-21 14:42:29 +00003800 }else if( strcmp(zArg, "-uri")==0 ){
3801 int b;
drh4dcac402018-01-03 13:20:02 +00003802 if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
drhf12b3f62011-12-21 14:42:29 +00003803 if( b ){
3804 flags |= SQLITE_OPEN_URI;
3805 }else{
3806 flags &= ~SQLITE_OPEN_URI;
3807 }
drh3570ad92007-08-31 14:31:44 +00003808 }else{
3809 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3810 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00003811 }
3812 }
drh75897232000-05-29 14:26:00 +00003813 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003814 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drhbec3f402000-08-04 13:49:02 +00003815 memset(p, 0, sizeof(*p));
drh3ec86652018-01-03 19:03:31 +00003816 if( zFile==0 ) zFile = "";
3817 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
3818 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
3819 Tcl_DStringFree(&translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003820 if( p->db ){
3821 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3822 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3823 sqlite3_close(p->db);
3824 p->db = 0;
3825 }
3826 }else{
mistachkin5dac8432012-09-11 02:00:25 +00003827 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
danielk197780290862004-05-22 09:21:21 +00003828 }
drh32f57d42016-03-16 01:03:10 +00003829#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhf3a65f72007-08-22 20:18:21 +00003830 if( p->db ){
3831 sqlite3_key(p->db, pKey, nKey);
3832 }
drheb8ed702004-02-11 10:37:23 +00003833#endif
drhbec3f402000-08-04 13:49:02 +00003834 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003835 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003836 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003837 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003838 return TCL_ERROR;
3839 }
drhfb7e7652005-01-24 00:28:42 +00003840 p->maxStmt = NUM_PREPARED_STMTS;
drh147ef392016-01-22 23:17:51 +00003841 p->openFlags = flags & SQLITE_OPEN_URI;
drh5169bbc2006-08-24 14:59:45 +00003842 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003843 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003844 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003845 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3846 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003847 }else{
3848 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3849 }
drh75897232000-05-29 14:26:00 +00003850 return TCL_OK;
3851}
3852
3853/*
drh90ca9752001-09-28 17:47:14 +00003854** Provide a dummy Tcl_InitStubs if we are using this as a static
3855** library.
3856*/
3857#ifndef USE_TCL_STUBS
3858# undef Tcl_InitStubs
drh0e85ccf2013-06-03 12:34:46 +00003859# define Tcl_InitStubs(a,b,c) TCL_VERSION
drh90ca9752001-09-28 17:47:14 +00003860#endif
3861
3862/*
drh29bc4612005-10-05 10:40:15 +00003863** Make sure we have a PACKAGE_VERSION macro defined. This will be
3864** defined automatically by the TEA makefile. But other makefiles
3865** do not define it.
3866*/
3867#ifndef PACKAGE_VERSION
3868# define PACKAGE_VERSION SQLITE_VERSION
3869#endif
3870
3871/*
drh75897232000-05-29 14:26:00 +00003872** Initialize this module.
3873**
3874** This Tcl module contains only a single new Tcl command named "sqlite".
3875** (Hence there is no namespace. There is no point in using a namespace
3876** if the extension only supplies one new name!) The "sqlite" command is
3877** used to open a new SQLite database. See the DbMain() routine above
3878** for additional information.
drhb652f432010-08-26 16:46:57 +00003879**
3880** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003881*/
drhb652f432010-08-26 16:46:57 +00003882EXTERN int Sqlite3_Init(Tcl_Interp *interp){
mistachkin27b2f052015-01-12 19:49:46 +00003883 int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
drh6dc8cbe2013-05-31 15:36:07 +00003884 if( rc==TCL_OK ){
3885 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh1cca0d22010-08-25 20:35:51 +00003886#ifndef SQLITE_3_SUFFIX_ONLY
drh6dc8cbe2013-05-31 15:36:07 +00003887 /* The "sqlite" alias is undocumented. It is here only to support
3888 ** legacy scripts. All new scripts should use only the "sqlite3"
3889 ** command. */
3890 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003891#endif
drh6dc8cbe2013-05-31 15:36:07 +00003892 rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3893 }
3894 return rc;
drh90ca9752001-09-28 17:47:14 +00003895}
drhb652f432010-08-26 16:46:57 +00003896EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
drhb652f432010-08-26 16:46:57 +00003897EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3898EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00003899
drhd878cab2012-03-20 15:10:42 +00003900/* Because it accesses the file-system and uses persistent state, SQLite
drhe75a9eb2016-02-13 18:54:10 +00003901** is not considered appropriate for safe interpreters. Hence, we cause
3902** the _SafeInit() interfaces return TCL_ERROR.
drhd878cab2012-03-20 15:10:42 +00003903*/
drhe75a9eb2016-02-13 18:54:10 +00003904EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
3905EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
3906
3907
drh49766d62005-01-08 18:42:28 +00003908
3909#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003910int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3911int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
dana3e63c42010-08-20 12:33:59 +00003912int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3913int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00003914#endif
drh75897232000-05-29 14:26:00 +00003915
drhc318f732017-10-13 15:06:06 +00003916/*
drh96a206f2017-10-13 20:14:06 +00003917** If the TCLSH macro is defined, add code to make a stand-alone program.
drhc318f732017-10-13 15:06:06 +00003918*/
drh96a206f2017-10-13 20:14:06 +00003919#if defined(TCLSH)
drh57a02272009-10-22 20:52:05 +00003920
drh96a206f2017-10-13 20:14:06 +00003921/* This is the main routine for an ordinary TCL shell. If there are
3922** are arguments, run the first argument as a script. Otherwise,
3923** read TCL commands from standard input
drh348784e2000-05-29 20:41:49 +00003924*/
dan0ae479d2011-09-21 16:43:07 +00003925static const char *tclsh_main_loop(void){
3926 static const char zMainloop[] =
drh96a206f2017-10-13 20:14:06 +00003927 "if {[llength $argv]>=1} {\n"
3928 "set argv0 [lindex $argv 0]\n"
3929 "set argv [lrange $argv 1 end]\n"
3930 "source $argv0\n"
3931 "} else {\n"
3932 "set line {}\n"
3933 "while {![eof stdin]} {\n"
3934 "if {$line!=\"\"} {\n"
3935 "puts -nonewline \"> \"\n"
3936 "} else {\n"
3937 "puts -nonewline \"% \"\n"
dan0ae479d2011-09-21 16:43:07 +00003938 "}\n"
drh96a206f2017-10-13 20:14:06 +00003939 "flush stdout\n"
3940 "append line [gets stdin]\n"
3941 "if {[info complete $line]} {\n"
3942 "if {[catch {uplevel #0 $line} result]} {\n"
3943 "puts stderr \"Error: $result\"\n"
3944 "} elseif {$result!=\"\"} {\n"
3945 "puts $result\n"
3946 "}\n"
3947 "set line {}\n"
3948 "} else {\n"
3949 "append line \\n\n"
3950 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003951 "}\n"
drh348784e2000-05-29 20:41:49 +00003952 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003953 ;
3954 return zMainloop;
3955}
drh3e27c022004-07-23 00:01:38 +00003956
danc1a60c52010-06-07 14:28:16 +00003957#define TCLSH_MAIN main /* Needed to fake out mktclapp */
mistachkin69def7f2016-07-28 04:14:37 +00003958int SQLITE_CDECL TCLSH_MAIN(int argc, char **argv){
danc1a60c52010-06-07 14:28:16 +00003959 Tcl_Interp *interp;
drh96a206f2017-10-13 20:14:06 +00003960 int i;
3961 const char *zScript = 0;
3962 char zArgc[32];
3963#if defined(TCLSH_INIT_PROC)
3964 extern const char *TCLSH_INIT_PROC(Tcl_Interp*);
3965#endif
mistachkin1f28e072013-08-15 08:06:15 +00003966
3967#if !defined(_WIN32_WCE)
mistachkin1e8487d2018-07-22 06:25:35 +00003968 if( getenv("SQLITE_DEBUG_BREAK") ){
3969 if( isatty(0) && isatty(2) ){
3970 fprintf(stderr,
3971 "attach debugger to process %d and press any key to continue.\n",
3972 GETPID());
3973 fgetc(stdin);
3974 }else{
3975#if defined(_WIN32) || defined(WIN32)
3976 DebugBreak();
3977#elif defined(SIGTRAP)
3978 raise(SIGTRAP);
3979#endif
3980 }
mistachkin1f28e072013-08-15 08:06:15 +00003981 }
3982#endif
3983
danc1a60c52010-06-07 14:28:16 +00003984 /* Call sqlite3_shutdown() once before doing anything else. This is to
3985 ** test that sqlite3_shutdown() can be safely called by a process before
3986 ** sqlite3_initialize() is. */
3987 sqlite3_shutdown();
3988
dan0ae479d2011-09-21 16:43:07 +00003989 Tcl_FindExecutable(argv[0]);
mistachkin2953ba92014-02-14 00:25:03 +00003990 Tcl_SetSystemEncoding(NULL, "utf-8");
dan0ae479d2011-09-21 16:43:07 +00003991 interp = Tcl_CreateInterp();
drhc318f732017-10-13 15:06:06 +00003992 Sqlite3_Init(interp);
drh96a206f2017-10-13 20:14:06 +00003993
3994 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-1);
3995 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
3996 Tcl_SetVar(interp,"argv0",argv[0],TCL_GLOBAL_ONLY);
3997 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
3998 for(i=1; i<argc; i++){
3999 Tcl_SetVar(interp, "argv", argv[i],
4000 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
drhc318f732017-10-13 15:06:06 +00004001 }
drh96a206f2017-10-13 20:14:06 +00004002#if defined(TCLSH_INIT_PROC)
4003 zScript = TCLSH_INIT_PROC(interp);
4004#endif
4005 if( zScript==0 ){
4006 zScript = tclsh_main_loop();
drh3e27c022004-07-23 00:01:38 +00004007 }
drh96a206f2017-10-13 20:14:06 +00004008 if( Tcl_GlobalEval(interp, zScript)!=TCL_OK ){
4009 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
4010 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
4011 fprintf(stderr,"%s: %s\n", *argv, zInfo);
4012 return 1;
drh348784e2000-05-29 20:41:49 +00004013 }
4014 return 0;
4015}
4016#endif /* TCLSH */