blob: 2de88f41f44a00087a59e94f802fe49b14159cb2 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
drhbd08af42007-04-05 21:58:33 +000012** A TCL Interface to SQLite. Append this file to sqlite3.c and
13** compile the whole thing to build a TCL-enabled version of SQLite.
drh57a02272009-10-22 20:52:05 +000014**
15** Compile-time options:
16**
17** -DTCLSH=1 Add a "main()" routine that works as a tclsh.
18**
19** -DSQLITE_TCLMD5 When used in conjuction with -DTCLSH=1, add
20** four new commands to the TCL interpreter for
21** generating MD5 checksums: md5, md5file,
22** md5-10x8, and md5file-10x8.
23**
24** -DSQLITE_TEST When used in conjuction with -DTCLSH=1, add
25** hundreds of new commands used for testing
26** SQLite. This option implies -DSQLITE_TCLMD5.
drh75897232000-05-29 14:26:00 +000027*/
mistachkin27b2f052015-01-12 19:49:46 +000028
29/*
30** If requested, include the SQLite compiler options file for MSVC.
31*/
32#if defined(INCLUDE_MSVC_H)
33#include "msvc.h"
34#endif
35
drh17a68932001-01-31 13:28:08 +000036#include "tcl.h"
danielk1977b4e9af92007-05-01 17:49:49 +000037#include <errno.h>
drhbd08af42007-04-05 21:58:33 +000038
39/*
40** Some additional include files are needed if this file is not
41** appended to the amalgamation.
42*/
43#ifndef SQLITE_AMALGAMATION
drh65e8c822009-12-01 13:57:48 +000044# include "sqlite3.h"
drhbd08af42007-04-05 21:58:33 +000045# include <stdlib.h>
46# include <string.h>
47# include <assert.h>
drh65e8c822009-12-01 13:57:48 +000048 typedef unsigned char u8;
drhbd08af42007-04-05 21:58:33 +000049#endif
drheb206382009-10-24 15:51:33 +000050#include <ctype.h>
drh75897232000-05-29 14:26:00 +000051
mistachkin1f28e072013-08-15 08:06:15 +000052/* Used to get the current process ID */
53#if !defined(_WIN32)
54# include <unistd.h>
55# define GETPID getpid
56#elif !defined(_WIN32_WCE)
57# ifndef SQLITE_AMALGAMATION
58# define WIN32_LEAN_AND_MEAN
59# include <windows.h>
60# endif
61# define GETPID (int)GetCurrentProcessId
62#endif
63
drhad6e1372006-07-10 21:15:51 +000064/*
65 * Windows needs to know which symbols to export. Unix does not.
66 * BUILD_sqlite should be undefined for Unix.
67 */
68#ifdef BUILD_sqlite
69#undef TCL_STORAGE_CLASS
70#define TCL_STORAGE_CLASS DLLEXPORT
71#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000072
danielk1977a21c6b62005-01-24 10:25:59 +000073#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000074#define MAX_PREPARED_STMTS 100
75
drhc45e6712012-10-03 11:02:33 +000076/* Forward declaration */
77typedef struct SqliteDb SqliteDb;
drh98808ba2001-10-18 12:34:46 +000078
79/*
drhcabb0812002-09-14 13:47:32 +000080** New SQL functions can be created as TCL scripts. Each such function
81** is described by an instance of the following structure.
82*/
83typedef struct SqlFunc SqlFunc;
84struct SqlFunc {
85 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000086 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
drhc45e6712012-10-03 11:02:33 +000087 SqliteDb *pDb; /* Database connection that owns this function */
drhd1e47332005-06-26 17:55:33 +000088 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
89 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000090 SqlFunc *pNext; /* Next function on the list of them all */
91};
92
93/*
danielk19770202b292004-06-09 09:55:16 +000094** New collation sequences function can be created as TCL scripts. Each such
95** function is described by an instance of the following structure.
96*/
97typedef struct SqlCollate SqlCollate;
98struct SqlCollate {
99 Tcl_Interp *interp; /* The TCL interpret to execute the function */
100 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +0000101 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +0000102};
103
104/*
drhfb7e7652005-01-24 00:28:42 +0000105** Prepared statements are cached for faster execution. Each prepared
106** statement is described by an instance of the following structure.
107*/
108typedef struct SqlPreparedStmt SqlPreparedStmt;
109struct SqlPreparedStmt {
110 SqlPreparedStmt *pNext; /* Next in linked list */
111 SqlPreparedStmt *pPrev; /* Previous on the list */
112 sqlite3_stmt *pStmt; /* The prepared statement */
113 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +0000114 const char *zSql; /* Text of the SQL statement */
dan4a4c11a2009-10-06 14:59:02 +0000115 int nParm; /* Size of apParm array */
116 Tcl_Obj **apParm; /* Array of referenced object pointers */
drhfb7e7652005-01-24 00:28:42 +0000117};
118
danielk1977d04417962007-05-02 13:16:30 +0000119typedef struct IncrblobChannel IncrblobChannel;
120
drhfb7e7652005-01-24 00:28:42 +0000121/*
drhbec3f402000-08-04 13:49:02 +0000122** There is one instance of this structure for each SQLite database
123** that has been opened by the SQLite TCL interface.
danc431fd52011-06-27 16:55:50 +0000124**
125** If this module is built with SQLITE_TEST defined (to create the SQLite
126** testfixture executable), then it may be configured to use either
127** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
128** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
drhbec3f402000-08-04 13:49:02 +0000129*/
drhbec3f402000-08-04 13:49:02 +0000130struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000131 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000132 Tcl_Interp *interp; /* The interpreter used for this database */
133 char *zBusy; /* The busy callback routine */
134 char *zCommit; /* The commit hook callback routine */
135 char *zTrace; /* The trace callback routine */
mistachkinb56660f2016-07-14 21:26:09 +0000136 char *zTraceV2; /* The trace_v2 callback routine */
drh19e2d372005-08-29 23:00:03 +0000137 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000138 char *zProgress; /* The progress callback routine */
139 char *zAuth; /* The authorization callback routine */
drh1f1549f2008-08-26 21:33:34 +0000140 int disableAuth; /* Disable the authorizer if it exists */
drhd1e47332005-06-26 17:55:33 +0000141 char *zNull; /* Text to substitute for an SQL NULL value */
142 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000143 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
dan46c47d42011-03-01 18:42:07 +0000144 Tcl_Obj *pPreUpdateHook; /* Pre-update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000145 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drh5def0842010-05-05 20:00:25 +0000146 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000147 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000148 SqlCollate *pCollate; /* List of SQL collation functions */
149 int rc; /* Return code of most recent sqlite3_exec() */
150 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000151 SqlPreparedStmt *stmtList; /* List of prepared statements*/
152 SqlPreparedStmt *stmtLast; /* Last statement in the list */
153 int maxStmt; /* The next maximum number of stmtList */
154 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000155 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh3c379b02010-04-07 19:31:59 +0000156 int nStep, nSort, nIndex; /* Statistics for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000157 int nTransaction; /* Number of nested [transaction] methods */
drh147ef392016-01-22 23:17:51 +0000158 int openFlags; /* Flags used to open. (SQLITE_OPEN_URI) */
danc431fd52011-06-27 16:55:50 +0000159#ifdef SQLITE_TEST
160 int bLegacyPrepare; /* True to use sqlite3_prepare() */
161#endif
drh98808ba2001-10-18 12:34:46 +0000162};
drh297ecf12001-04-05 15:57:13 +0000163
danielk1977b4e9af92007-05-01 17:49:49 +0000164struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000165 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000166 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000167 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000168 Tcl_Channel channel; /* Channel identifier */
169 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
170 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000171};
172
drhea678832008-12-10 19:26:22 +0000173/*
174** Compute a string length that is limited to what can be stored in
175** lower 30 bits of a 32-bit signed integer.
176*/
drh4f21c4a2008-12-10 22:15:00 +0000177static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000178 const char *z2 = z;
179 while( *z2 ){ z2++; }
180 return 0x3fffffff & (int)(z2 - z);
181}
drhea678832008-12-10 19:26:22 +0000182
183
danielk197732a0d8b2007-05-04 19:03:02 +0000184#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000185/*
danielk1977d04417962007-05-02 13:16:30 +0000186** Close all incrblob channels opened using database connection pDb.
187** This is called when shutting down the database connection.
188*/
189static void closeIncrblobChannels(SqliteDb *pDb){
190 IncrblobChannel *p;
191 IncrblobChannel *pNext;
192
193 for(p=pDb->pIncrblob; p; p=pNext){
194 pNext = p->pNext;
195
mistachkinb56660f2016-07-14 21:26:09 +0000196 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
danielk1977d04417962007-05-02 13:16:30 +0000197 ** which deletes the IncrblobChannel structure at *p. So do not
198 ** call Tcl_Free() here.
199 */
200 Tcl_UnregisterChannel(pDb->interp, p->channel);
201 }
202}
203
204/*
danielk1977b4e9af92007-05-01 17:49:49 +0000205** Close an incremental blob channel.
206*/
207static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
208 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000209 int rc = sqlite3_blob_close(p->pBlob);
210 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000211
212 /* Remove the channel from the SqliteDb.pIncrblob list. */
213 if( p->pNext ){
214 p->pNext->pPrev = p->pPrev;
215 }
216 if( p->pPrev ){
217 p->pPrev->pNext = p->pNext;
218 }
219 if( p->pDb->pIncrblob==p ){
220 p->pDb->pIncrblob = p->pNext;
221 }
222
danielk197792d4d7a2007-05-04 12:05:56 +0000223 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000224 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000225
226 if( rc!=SQLITE_OK ){
227 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
228 return TCL_ERROR;
229 }
danielk1977b4e9af92007-05-01 17:49:49 +0000230 return TCL_OK;
231}
232
233/*
234** Read data from an incremental blob channel.
235*/
236static int incrblobInput(
mistachkinb56660f2016-07-14 21:26:09 +0000237 ClientData instanceData,
238 char *buf,
danielk1977b4e9af92007-05-01 17:49:49 +0000239 int bufSize,
240 int *errorCodePtr
241){
242 IncrblobChannel *p = (IncrblobChannel *)instanceData;
243 int nRead = bufSize; /* Number of bytes to read */
244 int nBlob; /* Total size of the blob */
245 int rc; /* sqlite error code */
246
247 nBlob = sqlite3_blob_bytes(p->pBlob);
248 if( (p->iSeek+nRead)>nBlob ){
249 nRead = nBlob-p->iSeek;
250 }
251 if( nRead<=0 ){
252 return 0;
253 }
254
255 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
256 if( rc!=SQLITE_OK ){
257 *errorCodePtr = rc;
258 return -1;
259 }
260
261 p->iSeek += nRead;
262 return nRead;
263}
264
danielk1977d04417962007-05-02 13:16:30 +0000265/*
266** Write data to an incremental blob channel.
267*/
danielk1977b4e9af92007-05-01 17:49:49 +0000268static int incrblobOutput(
mistachkinb56660f2016-07-14 21:26:09 +0000269 ClientData instanceData,
270 CONST char *buf,
danielk1977b4e9af92007-05-01 17:49:49 +0000271 int toWrite,
272 int *errorCodePtr
273){
274 IncrblobChannel *p = (IncrblobChannel *)instanceData;
275 int nWrite = toWrite; /* Number of bytes to write */
276 int nBlob; /* Total size of the blob */
277 int rc; /* sqlite error code */
278
279 nBlob = sqlite3_blob_bytes(p->pBlob);
280 if( (p->iSeek+nWrite)>nBlob ){
281 *errorCodePtr = EINVAL;
282 return -1;
283 }
284 if( nWrite<=0 ){
285 return 0;
286 }
287
288 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
289 if( rc!=SQLITE_OK ){
290 *errorCodePtr = EIO;
291 return -1;
292 }
293
294 p->iSeek += nWrite;
295 return nWrite;
296}
297
298/*
299** Seek an incremental blob channel.
300*/
301static int incrblobSeek(
mistachkinb56660f2016-07-14 21:26:09 +0000302 ClientData instanceData,
danielk1977b4e9af92007-05-01 17:49:49 +0000303 long offset,
304 int seekMode,
305 int *errorCodePtr
306){
307 IncrblobChannel *p = (IncrblobChannel *)instanceData;
308
309 switch( seekMode ){
310 case SEEK_SET:
311 p->iSeek = offset;
312 break;
313 case SEEK_CUR:
314 p->iSeek += offset;
315 break;
316 case SEEK_END:
317 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
318 break;
319
320 default: assert(!"Bad seekMode");
321 }
322
323 return p->iSeek;
324}
325
326
mistachkinb56660f2016-07-14 21:26:09 +0000327static void incrblobWatch(ClientData instanceData, int mode){
328 /* NO-OP */
danielk1977b4e9af92007-05-01 17:49:49 +0000329}
330static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
331 return TCL_ERROR;
332}
333
334static Tcl_ChannelType IncrblobChannelType = {
335 "incrblob", /* typeName */
336 TCL_CHANNEL_VERSION_2, /* version */
337 incrblobClose, /* closeProc */
338 incrblobInput, /* inputProc */
339 incrblobOutput, /* outputProc */
340 incrblobSeek, /* seekProc */
341 0, /* setOptionProc */
342 0, /* getOptionProc */
343 incrblobWatch, /* watchProc (this is a no-op) */
344 incrblobHandle, /* getHandleProc (always returns error) */
345 0, /* close2Proc */
346 0, /* blockModeProc */
347 0, /* flushProc */
348 0, /* handlerProc */
349 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000350};
351
352/*
353** Create a new incrblob channel.
354*/
355static int createIncrblobChannel(
mistachkinb56660f2016-07-14 21:26:09 +0000356 Tcl_Interp *interp,
357 SqliteDb *pDb,
danielk1977b4e9af92007-05-01 17:49:49 +0000358 const char *zDb,
mistachkinb56660f2016-07-14 21:26:09 +0000359 const char *zTable,
360 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000361 sqlite_int64 iRow,
362 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000363){
364 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000365 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000366 sqlite3_blob *pBlob;
367 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000368 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000369
370 /* This variable is used to name the channels: "incrblob_[incr count]" */
371 static int count = 0;
372 char zChannel[64];
373
danielk19778cbadb02007-05-03 16:31:26 +0000374 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000375 if( rc!=SQLITE_OK ){
376 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
377 return TCL_ERROR;
378 }
379
380 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
381 p->iSeek = 0;
382 p->pBlob = pBlob;
383
drh5bb3eb92007-05-04 13:15:55 +0000384 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000385 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
386 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000387
danielk1977d04417962007-05-02 13:16:30 +0000388 /* Link the new channel into the SqliteDb.pIncrblob list. */
389 p->pNext = pDb->pIncrblob;
390 p->pPrev = 0;
391 if( p->pNext ){
392 p->pNext->pPrev = p;
393 }
394 pDb->pIncrblob = p;
395 p->pDb = pDb;
396
397 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000398 return TCL_OK;
399}
danielk197732a0d8b2007-05-04 19:03:02 +0000400#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
401 #define closeIncrblobChannels(pDb)
402#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000403
drh6d313162000-09-21 13:01:35 +0000404/*
drhd1e47332005-06-26 17:55:33 +0000405** Look at the script prefix in pCmd. We will be executing this script
406** after first appending one or more arguments. This routine analyzes
407** the script to see if it is safe to use Tcl_EvalObjv() on the script
408** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
409** faster.
410**
411** Scripts that are safe to use with Tcl_EvalObjv() consists of a
412** command name followed by zero or more arguments with no [...] or $
413** or {...} or ; to be seen anywhere. Most callback scripts consist
414** of just a single procedure name and they meet this requirement.
415*/
416static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
417 /* We could try to do something with Tcl_Parse(). But we will instead
418 ** just do a search for forbidden characters. If any of the forbidden
419 ** characters appear in pCmd, we will report the string as unsafe.
420 */
421 const char *z;
422 int n;
423 z = Tcl_GetStringFromObj(pCmd, &n);
424 while( n-- > 0 ){
425 int c = *(z++);
426 if( c=='$' || c=='[' || c==';' ) return 0;
427 }
428 return 1;
429}
430
431/*
432** Find an SqlFunc structure with the given name. Or create a new
433** one if an existing one cannot be found. Return a pointer to the
434** structure.
435*/
436static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
437 SqlFunc *p, *pNew;
drh0425f182013-11-26 16:48:04 +0000438 int nName = strlen30(zName);
439 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
drhd1e47332005-06-26 17:55:33 +0000440 pNew->zName = (char*)&pNew[1];
drh0425f182013-11-26 16:48:04 +0000441 memcpy(pNew->zName, zName, nName+1);
mistachkinb56660f2016-07-14 21:26:09 +0000442 for(p=pDb->pFunc; p; p=p->pNext){
drh0425f182013-11-26 16:48:04 +0000443 if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
drhd1e47332005-06-26 17:55:33 +0000444 Tcl_Free((char*)pNew);
445 return p;
446 }
447 }
448 pNew->interp = pDb->interp;
drhc45e6712012-10-03 11:02:33 +0000449 pNew->pDb = pDb;
drhd1e47332005-06-26 17:55:33 +0000450 pNew->pScript = 0;
451 pNew->pNext = pDb->pFunc;
452 pDb->pFunc = pNew;
453 return pNew;
454}
455
456/*
danc431fd52011-06-27 16:55:50 +0000457** Free a single SqlPreparedStmt object.
458*/
459static void dbFreeStmt(SqlPreparedStmt *pStmt){
460#ifdef SQLITE_TEST
461 if( sqlite3_sql(pStmt->pStmt)==0 ){
462 Tcl_Free((char *)pStmt->zSql);
463 }
464#endif
465 sqlite3_finalize(pStmt->pStmt);
466 Tcl_Free((char *)pStmt);
467}
468
469/*
drhfb7e7652005-01-24 00:28:42 +0000470** Finalize and free a list of prepared statements
471*/
danc431fd52011-06-27 16:55:50 +0000472static void flushStmtCache(SqliteDb *pDb){
drhfb7e7652005-01-24 00:28:42 +0000473 SqlPreparedStmt *pPreStmt;
danc431fd52011-06-27 16:55:50 +0000474 SqlPreparedStmt *pNext;
drhfb7e7652005-01-24 00:28:42 +0000475
danc431fd52011-06-27 16:55:50 +0000476 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
477 pNext = pPreStmt->pNext;
478 dbFreeStmt(pPreStmt);
drhfb7e7652005-01-24 00:28:42 +0000479 }
480 pDb->nStmt = 0;
481 pDb->stmtLast = 0;
danc431fd52011-06-27 16:55:50 +0000482 pDb->stmtList = 0;
drhfb7e7652005-01-24 00:28:42 +0000483}
484
485/*
drh895d7472004-08-20 16:02:39 +0000486** TCL calls this procedure when an sqlite3 database command is
487** deleted.
drh75897232000-05-29 14:26:00 +0000488*/
489static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000490 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000491 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000492 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000493 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000494 while( pDb->pFunc ){
495 SqlFunc *pFunc = pDb->pFunc;
496 pDb->pFunc = pFunc->pNext;
drhc45e6712012-10-03 11:02:33 +0000497 assert( pFunc->pDb==pDb );
drhd1e47332005-06-26 17:55:33 +0000498 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000499 Tcl_Free((char*)pFunc);
500 }
danielk19770202b292004-06-09 09:55:16 +0000501 while( pDb->pCollate ){
502 SqlCollate *pCollate = pDb->pCollate;
503 pDb->pCollate = pCollate->pNext;
504 Tcl_Free((char*)pCollate);
505 }
drhbec3f402000-08-04 13:49:02 +0000506 if( pDb->zBusy ){
507 Tcl_Free(pDb->zBusy);
508 }
drhb5a20d32003-04-23 12:25:23 +0000509 if( pDb->zTrace ){
510 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000511 }
mistachkinb56660f2016-07-14 21:26:09 +0000512 if( pDb->zTraceV2 ){
513 Tcl_Free(pDb->zTraceV2);
514 }
drh19e2d372005-08-29 23:00:03 +0000515 if( pDb->zProfile ){
516 Tcl_Free(pDb->zProfile);
517 }
drhe22a3342003-04-22 20:30:37 +0000518 if( pDb->zAuth ){
519 Tcl_Free(pDb->zAuth);
520 }
danielk197755c45f22005-04-03 23:54:43 +0000521 if( pDb->zNull ){
522 Tcl_Free(pDb->zNull);
523 }
danielk197794eb6a12005-12-15 15:22:08 +0000524 if( pDb->pUpdateHook ){
525 Tcl_DecrRefCount(pDb->pUpdateHook);
526 }
dan46c47d42011-03-01 18:42:07 +0000527 if( pDb->pPreUpdateHook ){
528 Tcl_DecrRefCount(pDb->pPreUpdateHook);
529 }
danielk197771fd80b2005-12-16 06:54:01 +0000530 if( pDb->pRollbackHook ){
531 Tcl_DecrRefCount(pDb->pRollbackHook);
532 }
drh5def0842010-05-05 20:00:25 +0000533 if( pDb->pWalHook ){
534 Tcl_DecrRefCount(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000535 }
danielk197794eb6a12005-12-15 15:22:08 +0000536 if( pDb->pCollateNeeded ){
537 Tcl_DecrRefCount(pDb->pCollateNeeded);
538 }
drhbec3f402000-08-04 13:49:02 +0000539 Tcl_Free((char*)pDb);
540}
541
542/*
543** This routine is called when a database file is locked while trying
544** to execute SQL.
545*/
danielk19772a764eb2004-06-12 01:43:26 +0000546static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000547 SqliteDb *pDb = (SqliteDb*)cd;
548 int rc;
549 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000550
drh5bb3eb92007-05-04 13:15:55 +0000551 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000552 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000553 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
554 return 0;
555 }
556 return 1;
drh75897232000-05-29 14:26:00 +0000557}
558
drh26e4a8b2008-05-01 17:16:52 +0000559#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000560/*
danielk1977348bb5d2003-10-18 09:37:26 +0000561** This routine is invoked as the 'progress callback' for the database.
562*/
563static int DbProgressHandler(void *cd){
564 SqliteDb *pDb = (SqliteDb*)cd;
565 int rc;
566
567 assert( pDb->zProgress );
568 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
569 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
570 return 1;
571 }
572 return 0;
573}
drh26e4a8b2008-05-01 17:16:52 +0000574#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000575
drhd1167392006-01-23 13:00:35 +0000576#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000577/*
drhb5a20d32003-04-23 12:25:23 +0000578** This routine is called by the SQLite trace handler whenever a new
579** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000580*/
drhb5a20d32003-04-23 12:25:23 +0000581static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000582 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000583 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000584
drhb5a20d32003-04-23 12:25:23 +0000585 Tcl_DStringInit(&str);
586 Tcl_DStringAppend(&str, pDb->zTrace, -1);
587 Tcl_DStringAppendElement(&str, zSql);
588 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
589 Tcl_DStringFree(&str);
590 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000591}
drhd1167392006-01-23 13:00:35 +0000592#endif
drh0d1a6432003-04-03 15:46:04 +0000593
drhd1167392006-01-23 13:00:35 +0000594#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000595/*
mistachkinb56660f2016-07-14 21:26:09 +0000596** This routine is called by the SQLite trace_v2 handler whenever a new
597** supported event is generated. Unsupported event types are ignored.
598** The TCL script in pDb->zTraceV2 is executed, with the arguments for
599** the event appended to it (as list elements).
600*/
601static int DbTraceV2Handler(
602 unsigned type, /* One of the SQLITE_TRACE_* event types. */
603 void *cd, /* The original context data pointer. */
604 void *pd, /* Primary event data, depends on event type. */
605 void *xd /* Extra event data, depends on event type. */
606){
607 SqliteDb *pDb = (SqliteDb*)cd;
608 Tcl_Obj *pCmd;
609
610 switch( type ){
611 case SQLITE_TRACE_STMT: {
612 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
613 char *zSql = (char *)xd;
614
615 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
616 Tcl_IncrRefCount(pCmd);
617 Tcl_ListObjAppendElement(pDb->interp, pCmd,
618 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
619 Tcl_ListObjAppendElement(pDb->interp, pCmd,
620 Tcl_NewStringObj(zSql, -1));
621 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
622 Tcl_DecrRefCount(pCmd);
623 Tcl_ResetResult(pDb->interp);
624 break;
625 }
626 case SQLITE_TRACE_PROFILE: {
627 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
628 sqlite3_int64 ns = (sqlite3_int64)xd;
629
630 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
631 Tcl_IncrRefCount(pCmd);
632 Tcl_ListObjAppendElement(pDb->interp, pCmd,
633 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
634 Tcl_ListObjAppendElement(pDb->interp, pCmd,
635 Tcl_NewWideIntObj((Tcl_WideInt)ns));
636 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
637 Tcl_DecrRefCount(pCmd);
638 Tcl_ResetResult(pDb->interp);
639 break;
640 }
641 case SQLITE_TRACE_ROW: {
642 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
643
644 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
645 Tcl_IncrRefCount(pCmd);
646 Tcl_ListObjAppendElement(pDb->interp, pCmd,
647 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
648 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
649 Tcl_DecrRefCount(pCmd);
650 Tcl_ResetResult(pDb->interp);
651 break;
652 }
653 case SQLITE_TRACE_CLOSE: {
654 sqlite3 *db = (sqlite3 *)pd;
655
656 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
657 Tcl_IncrRefCount(pCmd);
658 Tcl_ListObjAppendElement(pDb->interp, pCmd,
659 Tcl_NewWideIntObj((Tcl_WideInt)db));
660 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
661 Tcl_DecrRefCount(pCmd);
662 Tcl_ResetResult(pDb->interp);
663 break;
664 }
665 }
666 return SQLITE_OK;
667}
668#endif
669
670#ifndef SQLITE_OMIT_TRACE
671/*
drh19e2d372005-08-29 23:00:03 +0000672** This routine is called by the SQLite profile handler after a statement
673** SQL has executed. The TCL script in pDb->zProfile is evaluated.
674*/
675static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
676 SqliteDb *pDb = (SqliteDb*)cd;
677 Tcl_DString str;
678 char zTm[100];
679
680 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
681 Tcl_DStringInit(&str);
682 Tcl_DStringAppend(&str, pDb->zProfile, -1);
683 Tcl_DStringAppendElement(&str, zSql);
684 Tcl_DStringAppendElement(&str, zTm);
685 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
686 Tcl_DStringFree(&str);
687 Tcl_ResetResult(pDb->interp);
688}
drhd1167392006-01-23 13:00:35 +0000689#endif
drh19e2d372005-08-29 23:00:03 +0000690
691/*
drhaa940ea2004-01-15 02:44:03 +0000692** This routine is called when a transaction is committed. The
693** TCL script in pDb->zCommit is executed. If it returns non-zero or
694** if it throws an exception, the transaction is rolled back instead
695** of being committed.
696*/
697static int DbCommitHandler(void *cd){
698 SqliteDb *pDb = (SqliteDb*)cd;
699 int rc;
700
701 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
702 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
703 return 1;
704 }
705 return 0;
706}
707
danielk197771fd80b2005-12-16 06:54:01 +0000708static void DbRollbackHandler(void *clientData){
709 SqliteDb *pDb = (SqliteDb*)clientData;
710 assert(pDb->pRollbackHook);
711 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
712 Tcl_BackgroundError(pDb->interp);
713 }
714}
715
drh5def0842010-05-05 20:00:25 +0000716/*
717** This procedure handles wal_hook callbacks.
718*/
719static int DbWalHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000720 void *clientData,
721 sqlite3 *db,
722 const char *zDb,
dan8d22a172010-04-19 18:03:51 +0000723 int nEntry
724){
drh5def0842010-05-05 20:00:25 +0000725 int ret = SQLITE_OK;
dan8d22a172010-04-19 18:03:51 +0000726 Tcl_Obj *p;
727 SqliteDb *pDb = (SqliteDb*)clientData;
728 Tcl_Interp *interp = pDb->interp;
drh5def0842010-05-05 20:00:25 +0000729 assert(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000730
dan6e45e0c2014-12-10 20:29:49 +0000731 assert( db==pDb->db );
drh5def0842010-05-05 20:00:25 +0000732 p = Tcl_DuplicateObj(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000733 Tcl_IncrRefCount(p);
734 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
735 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
mistachkinb56660f2016-07-14 21:26:09 +0000736 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
dan8d22a172010-04-19 18:03:51 +0000737 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
738 ){
739 Tcl_BackgroundError(interp);
740 }
741 Tcl_DecrRefCount(p);
742
743 return ret;
744}
745
drhbcf4f482009-03-27 12:44:35 +0000746#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000747static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
748 char zBuf[64];
drh65545b52015-01-19 00:35:53 +0000749 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
danielk1977404ca072009-03-16 13:19:36 +0000750 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
drh65545b52015-01-19 00:35:53 +0000751 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
danielk1977404ca072009-03-16 13:19:36 +0000752 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
753}
754#else
drhbcf4f482009-03-27 12:44:35 +0000755# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000756#endif
757
drh69910da2009-03-27 12:32:54 +0000758#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000759static void DbUnlockNotify(void **apArg, int nArg){
760 int i;
761 for(i=0; i<nArg; i++){
762 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
763 SqliteDb *pDb = (SqliteDb *)apArg[i];
764 setTestUnlockNotifyVars(pDb->interp, i, nArg);
765 assert( pDb->pUnlockNotify);
766 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
767 Tcl_DecrRefCount(pDb->pUnlockNotify);
768 pDb->pUnlockNotify = 0;
769 }
770}
drh69910da2009-03-27 12:32:54 +0000771#endif
danielk1977404ca072009-03-16 13:19:36 +0000772
drh9b1c62d2011-03-30 21:04:43 +0000773#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +0000774/*
775** Pre-update hook callback.
776*/
777static void DbPreUpdateHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000778 void *p,
dan46c47d42011-03-01 18:42:07 +0000779 sqlite3 *db,
780 int op,
mistachkinb56660f2016-07-14 21:26:09 +0000781 const char *zDb,
782 const char *zTbl,
dan46c47d42011-03-01 18:42:07 +0000783 sqlite_int64 iKey1,
784 sqlite_int64 iKey2
785){
786 SqliteDb *pDb = (SqliteDb *)p;
787 Tcl_Obj *pCmd;
788 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
789
790 assert( (SQLITE_DELETE-1)/9 == 0 );
791 assert( (SQLITE_INSERT-1)/9 == 1 );
792 assert( (SQLITE_UPDATE-1)/9 == 2 );
793 assert( pDb->pPreUpdateHook );
794 assert( db==pDb->db );
795 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
796
797 pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
798 Tcl_IncrRefCount(pCmd);
799 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
800 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
801 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
802 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
803 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
804 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
805 Tcl_DecrRefCount(pCmd);
806}
drh9b1c62d2011-03-30 21:04:43 +0000807#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +0000808
danielk197794eb6a12005-12-15 15:22:08 +0000809static void DbUpdateHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000810 void *p,
danielk197794eb6a12005-12-15 15:22:08 +0000811 int op,
mistachkinb56660f2016-07-14 21:26:09 +0000812 const char *zDb,
813 const char *zTbl,
danielk197794eb6a12005-12-15 15:22:08 +0000814 sqlite_int64 rowid
815){
816 SqliteDb *pDb = (SqliteDb *)p;
817 Tcl_Obj *pCmd;
dan46c47d42011-03-01 18:42:07 +0000818 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
819
820 assert( (SQLITE_DELETE-1)/9 == 0 );
821 assert( (SQLITE_INSERT-1)/9 == 1 );
822 assert( (SQLITE_UPDATE-1)/9 == 2 );
danielk197794eb6a12005-12-15 15:22:08 +0000823
824 assert( pDb->pUpdateHook );
825 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
826
827 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
828 Tcl_IncrRefCount(pCmd);
dan46c47d42011-03-01 18:42:07 +0000829 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
danielk197794eb6a12005-12-15 15:22:08 +0000830 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
831 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
832 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
833 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
drhefdde162010-10-27 15:36:21 +0000834 Tcl_DecrRefCount(pCmd);
danielk197794eb6a12005-12-15 15:22:08 +0000835}
836
danielk19777cedc8d2004-06-10 10:50:08 +0000837static void tclCollateNeeded(
838 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000839 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000840 int enc,
841 const char *zName
842){
843 SqliteDb *pDb = (SqliteDb *)pCtx;
844 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
845 Tcl_IncrRefCount(pScript);
846 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
847 Tcl_EvalObjEx(pDb->interp, pScript, 0);
848 Tcl_DecrRefCount(pScript);
849}
850
drhaa940ea2004-01-15 02:44:03 +0000851/*
danielk19770202b292004-06-09 09:55:16 +0000852** This routine is called to evaluate an SQL collation function implemented
853** using TCL script.
854*/
855static int tclSqlCollate(
856 void *pCtx,
857 int nA,
858 const void *zA,
859 int nB,
860 const void *zB
861){
862 SqlCollate *p = (SqlCollate *)pCtx;
863 Tcl_Obj *pCmd;
864
865 pCmd = Tcl_NewStringObj(p->zScript, -1);
866 Tcl_IncrRefCount(pCmd);
867 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
868 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000869 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000870 Tcl_DecrRefCount(pCmd);
871 return (atoi(Tcl_GetStringResult(p->interp)));
872}
873
874/*
drhcabb0812002-09-14 13:47:32 +0000875** This routine is called to evaluate an SQL function implemented
876** using TCL script.
877*/
drhfb7e7652005-01-24 00:28:42 +0000878static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000879 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000880 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000881 int i;
882 int rc;
883
drhd1e47332005-06-26 17:55:33 +0000884 if( argc==0 ){
885 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
886 ** script object directly. This allows the TCL compiler to generate
887 ** bytecode for the command on the first invocation and thus make
888 ** subsequent invocations much faster. */
889 pCmd = p->pScript;
890 Tcl_IncrRefCount(pCmd);
891 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
892 Tcl_DecrRefCount(pCmd);
893 }else{
894 /* If there are arguments to the function, make a shallow copy of the
895 ** script object, lappend the arguments, then evaluate the copy.
896 **
peter.d.reid60ec9142014-09-06 16:39:46 +0000897 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
mistachkinb56660f2016-07-14 21:26:09 +0000898 ** The new Tcl_Obj contains pointers to the original list elements.
drhd1e47332005-06-26 17:55:33 +0000899 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
900 ** of the list to tclCmdNameType, that alternate representation will
901 ** be preserved and reused on the next invocation.
902 */
903 Tcl_Obj **aArg;
904 int nArg;
905 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
mistachkinb56660f2016-07-14 21:26:09 +0000906 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhd1e47332005-06-26 17:55:33 +0000907 return;
mistachkinb56660f2016-07-14 21:26:09 +0000908 }
drhd1e47332005-06-26 17:55:33 +0000909 pCmd = Tcl_NewListObj(nArg, aArg);
910 Tcl_IncrRefCount(pCmd);
911 for(i=0; i<argc; i++){
912 sqlite3_value *pIn = argv[i];
913 Tcl_Obj *pVal;
mistachkinb56660f2016-07-14 21:26:09 +0000914
drhd1e47332005-06-26 17:55:33 +0000915 /* Set pVal to contain the i'th column of this row. */
916 switch( sqlite3_value_type(pIn) ){
917 case SQLITE_BLOB: {
918 int bytes = sqlite3_value_bytes(pIn);
919 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
920 break;
921 }
922 case SQLITE_INTEGER: {
923 sqlite_int64 v = sqlite3_value_int64(pIn);
924 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +0000925 pVal = Tcl_NewIntObj((int)v);
drhd1e47332005-06-26 17:55:33 +0000926 }else{
927 pVal = Tcl_NewWideIntObj(v);
928 }
929 break;
930 }
931 case SQLITE_FLOAT: {
932 double r = sqlite3_value_double(pIn);
933 pVal = Tcl_NewDoubleObj(r);
934 break;
935 }
936 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +0000937 pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
drhd1e47332005-06-26 17:55:33 +0000938 break;
939 }
940 default: {
941 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000942 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000943 break;
944 }
945 }
946 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
947 if( rc ){
948 Tcl_DecrRefCount(pCmd);
mistachkinb56660f2016-07-14 21:26:09 +0000949 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhd1e47332005-06-26 17:55:33 +0000950 return;
951 }
danielk197751ad0ec2004-05-24 12:39:02 +0000952 }
drhd1e47332005-06-26 17:55:33 +0000953 if( !p->useEvalObjv ){
954 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
955 ** is a list without a string representation. To prevent this from
956 ** happening, make sure pCmd has a valid string representation */
957 Tcl_GetString(pCmd);
958 }
959 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
960 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000961 }
danielk1977562e8d32005-05-20 09:40:55 +0000962
drhc7f269d2005-05-05 10:30:29 +0000963 if( rc && rc!=TCL_RETURN ){
mistachkinb56660f2016-07-14 21:26:09 +0000964 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000965 }else{
drhc7f269d2005-05-05 10:30:29 +0000966 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
967 int n;
968 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000969 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000970 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000971 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000972 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000973 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000974 data = Tcl_GetByteArrayFromObj(pVar, &n);
975 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000976 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000977 Tcl_GetIntFromObj(0, pVar, &n);
978 sqlite3_result_int(context, n);
979 }else if( c=='d' && strcmp(zType,"double")==0 ){
980 double r;
981 Tcl_GetDoubleFromObj(0, pVar, &r);
982 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +0000983 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
984 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000985 Tcl_WideInt v;
986 Tcl_GetWideIntFromObj(0, pVar, &v);
987 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000988 }else{
danielk197700fd9572005-12-07 06:27:43 +0000989 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
990 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000991 }
drhcabb0812002-09-14 13:47:32 +0000992 }
993}
drh895d7472004-08-20 16:02:39 +0000994
drhe22a3342003-04-22 20:30:37 +0000995#ifndef SQLITE_OMIT_AUTHORIZATION
996/*
997** This is the authentication function. It appends the authentication
998** type code and the two arguments to zCmd[] then invokes the result
999** on the interpreter. The reply is examined to determine if the
1000** authentication fails or succeeds.
1001*/
1002static int auth_callback(
1003 void *pArg,
1004 int code,
1005 const char *zArg1,
1006 const char *zArg2,
1007 const char *zArg3,
1008 const char *zArg4
drh32c6a482014-09-11 13:44:52 +00001009#ifdef SQLITE_USER_AUTHENTICATION
1010 ,const char *zArg5
1011#endif
drhe22a3342003-04-22 20:30:37 +00001012){
mistachkin6ef5e122014-01-24 17:03:55 +00001013 const char *zCode;
drhe22a3342003-04-22 20:30:37 +00001014 Tcl_DString str;
1015 int rc;
1016 const char *zReply;
1017 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +00001018 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +00001019
1020 switch( code ){
1021 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
1022 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
1023 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
1024 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
1025 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
1026 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
1027 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
1028 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
1029 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
1030 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
1031 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
1032 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
1033 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
1034 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
1035 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
1036 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
1037 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
1038 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
1039 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
1040 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
1041 case SQLITE_READ : zCode="SQLITE_READ"; break;
1042 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
1043 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
1044 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +00001045 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
1046 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +00001047 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +00001048 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +00001049 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +00001050 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
1051 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +00001052 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +00001053 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drh65a2aaa2014-01-16 22:40:02 +00001054 case SQLITE_RECURSIVE : zCode="SQLITE_RECURSIVE"; break;
drhe22a3342003-04-22 20:30:37 +00001055 default : zCode="????"; break;
1056 }
1057 Tcl_DStringInit(&str);
1058 Tcl_DStringAppend(&str, pDb->zAuth, -1);
1059 Tcl_DStringAppendElement(&str, zCode);
1060 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
1061 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
1062 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
1063 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
drh32c6a482014-09-11 13:44:52 +00001064#ifdef SQLITE_USER_AUTHENTICATION
1065 Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
mistachkinb56660f2016-07-14 21:26:09 +00001066#endif
drhe22a3342003-04-22 20:30:37 +00001067 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
1068 Tcl_DStringFree(&str);
drhb07028f2011-10-14 21:49:18 +00001069 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
drhe22a3342003-04-22 20:30:37 +00001070 if( strcmp(zReply,"SQLITE_OK")==0 ){
1071 rc = SQLITE_OK;
1072 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
1073 rc = SQLITE_DENY;
1074 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
1075 rc = SQLITE_IGNORE;
1076 }else{
1077 rc = 999;
1078 }
1079 return rc;
1080}
1081#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +00001082
1083/*
tpoindex1067fe12004-12-17 15:41:11 +00001084** This routine reads a line of text from FILE in, stores
1085** the text in memory obtained from malloc() and returns a pointer
1086** to the text. NULL is returned at end of file, or if malloc()
1087** fails.
1088**
1089** The interface is like "readline" but no command-line editing
1090** is done.
1091**
1092** copied from shell.c from '.import' command
1093*/
1094static char *local_getline(char *zPrompt, FILE *in){
1095 char *zLine;
1096 int nLine;
1097 int n;
tpoindex1067fe12004-12-17 15:41:11 +00001098
1099 nLine = 100;
1100 zLine = malloc( nLine );
1101 if( zLine==0 ) return 0;
1102 n = 0;
drhb07028f2011-10-14 21:49:18 +00001103 while( 1 ){
tpoindex1067fe12004-12-17 15:41:11 +00001104 if( n+100>nLine ){
1105 nLine = nLine*2 + 100;
1106 zLine = realloc(zLine, nLine);
1107 if( zLine==0 ) return 0;
1108 }
1109 if( fgets(&zLine[n], nLine - n, in)==0 ){
1110 if( n==0 ){
1111 free(zLine);
1112 return 0;
1113 }
1114 zLine[n] = 0;
tpoindex1067fe12004-12-17 15:41:11 +00001115 break;
1116 }
1117 while( zLine[n] ){ n++; }
1118 if( n>0 && zLine[n-1]=='\n' ){
1119 n--;
1120 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +00001121 break;
tpoindex1067fe12004-12-17 15:41:11 +00001122 }
1123 }
1124 zLine = realloc( zLine, n+1 );
1125 return zLine;
1126}
1127
danielk19778e556522007-11-13 10:30:24 +00001128
1129/*
dan4a4c11a2009-10-06 14:59:02 +00001130** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +00001131**
dan4a4c11a2009-10-06 14:59:02 +00001132** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +00001133**
dan4a4c11a2009-10-06 14:59:02 +00001134** It is invoked after evaluating the script SCRIPT to commit or rollback
1135** the transaction or savepoint opened by the [transaction] command.
1136*/
1137static int DbTransPostCmd(
1138 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1139 Tcl_Interp *interp, /* Tcl interpreter */
1140 int result /* Result of evaluating SCRIPT */
1141){
mistachkin6ef5e122014-01-24 17:03:55 +00001142 static const char *const azEnd[] = {
dan4a4c11a2009-10-06 14:59:02 +00001143 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1144 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1145 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1146 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1147 };
1148 SqliteDb *pDb = (SqliteDb*)data[0];
1149 int rc = result;
1150 const char *zEnd;
1151
1152 pDb->nTransaction--;
1153 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1154
1155 pDb->disableAuth++;
1156 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1157 /* This is a tricky scenario to handle. The most likely cause of an
mistachkinb56660f2016-07-14 21:26:09 +00001158 ** error is that the exec() above was an attempt to commit the
dan4a4c11a2009-10-06 14:59:02 +00001159 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
mistachkin48864df2013-03-21 21:20:32 +00001160 ** that an IO-error has occurred. In either case, throw a Tcl exception
dan4a4c11a2009-10-06 14:59:02 +00001161 ** and try to rollback the transaction.
1162 **
mistachkinb56660f2016-07-14 21:26:09 +00001163 ** But it could also be that the user executed one or more BEGIN,
dan4a4c11a2009-10-06 14:59:02 +00001164 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1165 ** this method's logic. Not clear how this would be best handled.
1166 */
1167 if( rc!=TCL_ERROR ){
drha198f2b2014-02-07 19:26:13 +00001168 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
dan4a4c11a2009-10-06 14:59:02 +00001169 rc = TCL_ERROR;
1170 }
1171 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1172 }
1173 pDb->disableAuth--;
1174
1175 return rc;
1176}
1177
1178/*
danc431fd52011-06-27 16:55:50 +00001179** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1180** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1181** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
mistachkinb56660f2016-07-14 21:26:09 +00001182** on whether or not the [db_use_legacy_prepare] command has been used to
danc431fd52011-06-27 16:55:50 +00001183** configure the connection.
1184*/
1185static int dbPrepare(
1186 SqliteDb *pDb, /* Database object */
1187 const char *zSql, /* SQL to compile */
1188 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1189 const char **pzOut /* OUT: Pointer to next SQL statement */
1190){
1191#ifdef SQLITE_TEST
1192 if( pDb->bLegacyPrepare ){
1193 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1194 }
1195#endif
1196 return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut);
1197}
1198
1199/*
dan4a4c11a2009-10-06 14:59:02 +00001200** Search the cache for a prepared-statement object that implements the
1201** first SQL statement in the buffer pointed to by parameter zIn. If
1202** no such prepared-statement can be found, allocate and prepare a new
1203** one. In either case, bind the current values of the relevant Tcl
1204** variables to any $var, :var or @var variables in the statement. Before
1205** returning, set *ppPreStmt to point to the prepared-statement object.
1206**
1207** Output parameter *pzOut is set to point to the next SQL statement in
1208** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1209** next statement.
1210**
1211** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1212** and an error message loaded into interpreter pDb->interp.
1213*/
1214static int dbPrepareAndBind(
1215 SqliteDb *pDb, /* Database object */
1216 char const *zIn, /* SQL to compile */
1217 char const **pzOut, /* OUT: Pointer to next SQL statement */
1218 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1219){
1220 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
mistachkin7bb22ac2015-01-12 19:59:12 +00001221 sqlite3_stmt *pStmt = 0; /* Prepared statement object */
dan4a4c11a2009-10-06 14:59:02 +00001222 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1223 int nSql; /* Length of zSql in bytes */
mistachkin7bb22ac2015-01-12 19:59:12 +00001224 int nVar = 0; /* Number of variables in statement */
dan4a4c11a2009-10-06 14:59:02 +00001225 int iParm = 0; /* Next free entry in apParm */
drh0425f182013-11-26 16:48:04 +00001226 char c;
dan4a4c11a2009-10-06 14:59:02 +00001227 int i;
1228 Tcl_Interp *interp = pDb->interp;
1229
1230 *ppPreStmt = 0;
1231
1232 /* Trim spaces from the start of zSql and calculate the remaining length. */
drh0425f182013-11-26 16:48:04 +00001233 while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
dan4a4c11a2009-10-06 14:59:02 +00001234 nSql = strlen30(zSql);
1235
1236 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1237 int n = pPreStmt->nSql;
mistachkinb56660f2016-07-14 21:26:09 +00001238 if( nSql>=n
dan4a4c11a2009-10-06 14:59:02 +00001239 && memcmp(pPreStmt->zSql, zSql, n)==0
1240 && (zSql[n]==0 || zSql[n-1]==';')
1241 ){
1242 pStmt = pPreStmt->pStmt;
1243 *pzOut = &zSql[pPreStmt->nSql];
1244
1245 /* When a prepared statement is found, unlink it from the
1246 ** cache list. It will later be added back to the beginning
1247 ** of the cache list in order to implement LRU replacement.
1248 */
1249 if( pPreStmt->pPrev ){
1250 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1251 }else{
1252 pDb->stmtList = pPreStmt->pNext;
1253 }
1254 if( pPreStmt->pNext ){
1255 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1256 }else{
1257 pDb->stmtLast = pPreStmt->pPrev;
1258 }
1259 pDb->nStmt--;
1260 nVar = sqlite3_bind_parameter_count(pStmt);
1261 break;
1262 }
1263 }
mistachkinb56660f2016-07-14 21:26:09 +00001264
dan4a4c11a2009-10-06 14:59:02 +00001265 /* If no prepared statement was found. Compile the SQL text. Also allocate
1266 ** a new SqlPreparedStmt structure. */
1267 if( pPreStmt==0 ){
1268 int nByte;
1269
danc431fd52011-06-27 16:55:50 +00001270 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
drhc45e6712012-10-03 11:02:33 +00001271 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001272 return TCL_ERROR;
1273 }
1274 if( pStmt==0 ){
1275 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1276 /* A compile-time error in the statement. */
drhc45e6712012-10-03 11:02:33 +00001277 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001278 return TCL_ERROR;
1279 }else{
1280 /* The statement was a no-op. Continue to the next statement
1281 ** in the SQL string.
1282 */
1283 return TCL_OK;
1284 }
1285 }
1286
1287 assert( pPreStmt==0 );
1288 nVar = sqlite3_bind_parameter_count(pStmt);
1289 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1290 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1291 memset(pPreStmt, 0, nByte);
1292
1293 pPreStmt->pStmt = pStmt;
drh7ed243b2012-04-19 17:19:51 +00001294 pPreStmt->nSql = (int)(*pzOut - zSql);
dan4a4c11a2009-10-06 14:59:02 +00001295 pPreStmt->zSql = sqlite3_sql(pStmt);
1296 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
danc431fd52011-06-27 16:55:50 +00001297#ifdef SQLITE_TEST
1298 if( pPreStmt->zSql==0 ){
1299 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1300 memcpy(zCopy, zSql, pPreStmt->nSql);
1301 zCopy[pPreStmt->nSql] = '\0';
1302 pPreStmt->zSql = zCopy;
1303 }
1304#endif
dan4a4c11a2009-10-06 14:59:02 +00001305 }
1306 assert( pPreStmt );
1307 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1308 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1309
mistachkinb56660f2016-07-14 21:26:09 +00001310 /* Bind values to parameters that begin with $ or : */
dan4a4c11a2009-10-06 14:59:02 +00001311 for(i=1; i<=nVar; i++){
1312 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1313 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1314 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1315 if( pVar ){
1316 int n;
1317 u8 *data;
1318 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
mistachkin8e189222015-04-19 21:43:16 +00001319 c = zType[0];
dan4a4c11a2009-10-06 14:59:02 +00001320 if( zVar[0]=='@' ||
1321 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1322 /* Load a BLOB type if the Tcl variable is a bytearray and
1323 ** it has no string representation or the host
1324 ** parameter name begins with "@". */
1325 data = Tcl_GetByteArrayFromObj(pVar, &n);
1326 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1327 Tcl_IncrRefCount(pVar);
1328 pPreStmt->apParm[iParm++] = pVar;
1329 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1330 Tcl_GetIntFromObj(interp, pVar, &n);
1331 sqlite3_bind_int(pStmt, i, n);
1332 }else if( c=='d' && strcmp(zType,"double")==0 ){
1333 double r;
1334 Tcl_GetDoubleFromObj(interp, pVar, &r);
1335 sqlite3_bind_double(pStmt, i, r);
1336 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1337 (c=='i' && strcmp(zType,"int")==0) ){
1338 Tcl_WideInt v;
1339 Tcl_GetWideIntFromObj(interp, pVar, &v);
1340 sqlite3_bind_int64(pStmt, i, v);
1341 }else{
1342 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1343 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1344 Tcl_IncrRefCount(pVar);
1345 pPreStmt->apParm[iParm++] = pVar;
1346 }
1347 }else{
1348 sqlite3_bind_null(pStmt, i);
1349 }
1350 }
1351 }
1352 pPreStmt->nParm = iParm;
1353 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001354
dan4a4c11a2009-10-06 14:59:02 +00001355 return TCL_OK;
1356}
1357
dan4a4c11a2009-10-06 14:59:02 +00001358/*
1359** Release a statement reference obtained by calling dbPrepareAndBind().
1360** There should be exactly one call to this function for each call to
1361** dbPrepareAndBind().
1362**
1363** If the discard parameter is non-zero, then the statement is deleted
1364** immediately. Otherwise it is added to the LRU list and may be returned
1365** by a subsequent call to dbPrepareAndBind().
1366*/
1367static void dbReleaseStmt(
1368 SqliteDb *pDb, /* Database handle */
1369 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1370 int discard /* True to delete (not cache) the pPreStmt */
1371){
1372 int i;
1373
1374 /* Free the bound string and blob parameters */
1375 for(i=0; i<pPreStmt->nParm; i++){
1376 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1377 }
1378 pPreStmt->nParm = 0;
1379
1380 if( pDb->maxStmt<=0 || discard ){
1381 /* If the cache is turned off, deallocated the statement */
danc431fd52011-06-27 16:55:50 +00001382 dbFreeStmt(pPreStmt);
dan4a4c11a2009-10-06 14:59:02 +00001383 }else{
1384 /* Add the prepared statement to the beginning of the cache list. */
1385 pPreStmt->pNext = pDb->stmtList;
1386 pPreStmt->pPrev = 0;
1387 if( pDb->stmtList ){
1388 pDb->stmtList->pPrev = pPreStmt;
1389 }
1390 pDb->stmtList = pPreStmt;
1391 if( pDb->stmtLast==0 ){
1392 assert( pDb->nStmt==0 );
1393 pDb->stmtLast = pPreStmt;
1394 }else{
1395 assert( pDb->nStmt>0 );
1396 }
1397 pDb->nStmt++;
mistachkinb56660f2016-07-14 21:26:09 +00001398
1399 /* If we have too many statement in cache, remove the surplus from
dan4a4c11a2009-10-06 14:59:02 +00001400 ** the end of the cache list. */
1401 while( pDb->nStmt>pDb->maxStmt ){
danc431fd52011-06-27 16:55:50 +00001402 SqlPreparedStmt *pLast = pDb->stmtLast;
1403 pDb->stmtLast = pLast->pPrev;
dan4a4c11a2009-10-06 14:59:02 +00001404 pDb->stmtLast->pNext = 0;
1405 pDb->nStmt--;
danc431fd52011-06-27 16:55:50 +00001406 dbFreeStmt(pLast);
dan4a4c11a2009-10-06 14:59:02 +00001407 }
1408 }
1409}
1410
1411/*
1412** Structure used with dbEvalXXX() functions:
1413**
1414** dbEvalInit()
1415** dbEvalStep()
1416** dbEvalFinalize()
1417** dbEvalRowInfo()
1418** dbEvalColumnValue()
1419*/
1420typedef struct DbEvalContext DbEvalContext;
1421struct DbEvalContext {
1422 SqliteDb *pDb; /* Database handle */
1423 Tcl_Obj *pSql; /* Object holding string zSql */
1424 const char *zSql; /* Remaining SQL to execute */
1425 SqlPreparedStmt *pPreStmt; /* Current statement */
1426 int nCol; /* Number of columns returned by pStmt */
1427 Tcl_Obj *pArray; /* Name of array variable */
1428 Tcl_Obj **apColName; /* Array of column names */
1429};
1430
1431/*
1432** Release any cache of column names currently held as part of
1433** the DbEvalContext structure passed as the first argument.
1434*/
1435static void dbReleaseColumnNames(DbEvalContext *p){
1436 if( p->apColName ){
1437 int i;
1438 for(i=0; i<p->nCol; i++){
1439 Tcl_DecrRefCount(p->apColName[i]);
1440 }
1441 Tcl_Free((char *)p->apColName);
1442 p->apColName = 0;
1443 }
1444 p->nCol = 0;
1445}
1446
1447/*
1448** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001449**
1450** If pArray is not NULL, then it contains the name of a Tcl array
1451** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001452** the names of the columns returned by the statement as part of each
mistachkinb56660f2016-07-14 21:26:09 +00001453** call to dbEvalStep(), in order from left to right. e.g. if the names
1454** of the returned columns are a, b and c, it does the equivalent of the
dan4a4c11a2009-10-06 14:59:02 +00001455** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001456**
1457** set ${pArray}(*) {a b c}
1458*/
dan4a4c11a2009-10-06 14:59:02 +00001459static void dbEvalInit(
1460 DbEvalContext *p, /* Pointer to structure to initialize */
1461 SqliteDb *pDb, /* Database handle */
1462 Tcl_Obj *pSql, /* Object containing SQL script */
1463 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001464){
dan4a4c11a2009-10-06 14:59:02 +00001465 memset(p, 0, sizeof(DbEvalContext));
1466 p->pDb = pDb;
1467 p->zSql = Tcl_GetString(pSql);
1468 p->pSql = pSql;
1469 Tcl_IncrRefCount(pSql);
1470 if( pArray ){
1471 p->pArray = pArray;
1472 Tcl_IncrRefCount(pArray);
1473 }
1474}
danielk19778e556522007-11-13 10:30:24 +00001475
dan4a4c11a2009-10-06 14:59:02 +00001476/*
1477** Obtain information about the row that the DbEvalContext passed as the
1478** first argument currently points to.
1479*/
1480static void dbEvalRowInfo(
1481 DbEvalContext *p, /* Evaluation context */
1482 int *pnCol, /* OUT: Number of column names */
1483 Tcl_Obj ***papColName /* OUT: Array of column names */
1484){
danielk19778e556522007-11-13 10:30:24 +00001485 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001486 if( 0==p->apColName ){
1487 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1488 int i; /* Iterator variable */
1489 int nCol; /* Number of columns returned by pStmt */
1490 Tcl_Obj **apColName = 0; /* Array of column names */
1491
1492 p->nCol = nCol = sqlite3_column_count(pStmt);
1493 if( nCol>0 && (papColName || p->pArray) ){
1494 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1495 for(i=0; i<nCol; i++){
drhc45e6712012-10-03 11:02:33 +00001496 apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
dan4a4c11a2009-10-06 14:59:02 +00001497 Tcl_IncrRefCount(apColName[i]);
1498 }
1499 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001500 }
1501
1502 /* If results are being stored in an array variable, then create
1503 ** the array(*) entry for that array
1504 */
dan4a4c11a2009-10-06 14:59:02 +00001505 if( p->pArray ){
1506 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001507 Tcl_Obj *pColList = Tcl_NewObj();
1508 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001509
danielk19778e556522007-11-13 10:30:24 +00001510 for(i=0; i<nCol; i++){
1511 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1512 }
1513 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001514 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001515 Tcl_DecrRefCount(pStar);
1516 }
danielk19778e556522007-11-13 10:30:24 +00001517 }
1518
dan4a4c11a2009-10-06 14:59:02 +00001519 if( papColName ){
1520 *papColName = p->apColName;
1521 }
1522 if( pnCol ){
1523 *pnCol = p->nCol;
1524 }
1525}
1526
1527/*
1528** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1529** returned, then an error message is stored in the interpreter before
1530** returning.
1531**
1532** A return value of TCL_OK means there is a row of data available. The
1533** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1534** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1535** is returned, then the SQL script has finished executing and there are
1536** no further rows available. This is similar to SQLITE_DONE.
1537*/
1538static int dbEvalStep(DbEvalContext *p){
danc431fd52011-06-27 16:55:50 +00001539 const char *zPrevSql = 0; /* Previous value of p->zSql */
1540
dan4a4c11a2009-10-06 14:59:02 +00001541 while( p->zSql[0] || p->pPreStmt ){
1542 int rc;
1543 if( p->pPreStmt==0 ){
danc431fd52011-06-27 16:55:50 +00001544 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
dan4a4c11a2009-10-06 14:59:02 +00001545 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1546 if( rc!=TCL_OK ) return rc;
1547 }else{
1548 int rcs;
1549 SqliteDb *pDb = p->pDb;
1550 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1551 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1552
1553 rcs = sqlite3_step(pStmt);
1554 if( rcs==SQLITE_ROW ){
1555 return TCL_OK;
1556 }
1557 if( p->pArray ){
1558 dbEvalRowInfo(p, 0, 0);
1559 }
1560 rcs = sqlite3_reset(pStmt);
1561
1562 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1563 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001564 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
dan4a4c11a2009-10-06 14:59:02 +00001565 dbReleaseColumnNames(p);
1566 p->pPreStmt = 0;
1567
1568 if( rcs!=SQLITE_OK ){
1569 /* If a run-time error occurs, report the error and stop reading
1570 ** the SQL. */
dan4a4c11a2009-10-06 14:59:02 +00001571 dbReleaseStmt(pDb, pPreStmt, 1);
danc431fd52011-06-27 16:55:50 +00001572#if SQLITE_TEST
1573 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1574 /* If the runtime error was an SQLITE_SCHEMA, and the database
mistachkinb56660f2016-07-14 21:26:09 +00001575 ** handle is configured to use the legacy sqlite3_prepare()
danc431fd52011-06-27 16:55:50 +00001576 ** interface, retry prepare()/step() on the same SQL statement.
1577 ** This only happens once. If there is a second SQLITE_SCHEMA
1578 ** error, the error will be returned to the caller. */
1579 p->zSql = zPrevSql;
1580 continue;
1581 }
1582#endif
drhc45e6712012-10-03 11:02:33 +00001583 Tcl_SetObjResult(pDb->interp,
1584 Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001585 return TCL_ERROR;
1586 }else{
1587 dbReleaseStmt(pDb, pPreStmt, 0);
1588 }
1589 }
1590 }
1591
1592 /* Finished */
1593 return TCL_BREAK;
1594}
1595
1596/*
1597** Free all resources currently held by the DbEvalContext structure passed
1598** as the first argument. There should be exactly one call to this function
1599** for each call to dbEvalInit().
1600*/
1601static void dbEvalFinalize(DbEvalContext *p){
1602 if( p->pPreStmt ){
1603 sqlite3_reset(p->pPreStmt->pStmt);
1604 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1605 p->pPreStmt = 0;
1606 }
1607 if( p->pArray ){
1608 Tcl_DecrRefCount(p->pArray);
1609 p->pArray = 0;
1610 }
1611 Tcl_DecrRefCount(p->pSql);
1612 dbReleaseColumnNames(p);
1613}
1614
1615/*
1616** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1617** the value for the iCol'th column of the row currently pointed to by
1618** the DbEvalContext structure passed as the first argument.
1619*/
1620static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1621 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1622 switch( sqlite3_column_type(pStmt, iCol) ){
1623 case SQLITE_BLOB: {
1624 int bytes = sqlite3_column_bytes(pStmt, iCol);
1625 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1626 if( !zBlob ) bytes = 0;
1627 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1628 }
1629 case SQLITE_INTEGER: {
1630 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1631 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +00001632 return Tcl_NewIntObj((int)v);
dan4a4c11a2009-10-06 14:59:02 +00001633 }else{
1634 return Tcl_NewWideIntObj(v);
1635 }
1636 }
1637 case SQLITE_FLOAT: {
1638 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1639 }
1640 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +00001641 return Tcl_NewStringObj(p->pDb->zNull, -1);
dan4a4c11a2009-10-06 14:59:02 +00001642 }
1643 }
1644
drh325eff52012-10-03 12:56:18 +00001645 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
dan4a4c11a2009-10-06 14:59:02 +00001646}
1647
1648/*
1649** If using Tcl version 8.6 or greater, use the NR functions to avoid
1650** recursive evalution of scripts by the [db eval] and [db trans]
1651** commands. Even if the headers used while compiling the extension
1652** are 8.6 or newer, the code still tests the Tcl version at runtime.
1653** This allows stubs-enabled builds to be used with older Tcl libraries.
1654*/
1655#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001656# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001657static int DbUseNre(void){
1658 int major, minor;
1659 Tcl_GetVersion(&major, &minor, 0, 0);
1660 return( (major==8 && minor>=6) || major>8 );
1661}
1662#else
mistachkinb56660f2016-07-14 21:26:09 +00001663/*
dan4a4c11a2009-10-06 14:59:02 +00001664** Compiling using headers earlier than 8.6. In this case NR cannot be
1665** used, so DbUseNre() to always return zero. Add #defines for the other
1666** Tcl_NRxxx() functions to prevent them from causing compilation errors,
mistachkinb56660f2016-07-14 21:26:09 +00001667** even though the only invocations of them are within conditional blocks
dan4a4c11a2009-10-06 14:59:02 +00001668** of the form:
1669**
1670** if( DbUseNre() ) { ... }
1671*/
drha2c8a952009-10-13 18:38:34 +00001672# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001673# define DbUseNre() 0
drha47941f2013-12-20 18:57:44 +00001674# define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001675# define Tcl_NREvalObj(a,b,c) 0
drha47941f2013-12-20 18:57:44 +00001676# define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001677#endif
1678
1679/*
1680** This function is part of the implementation of the command:
1681**
1682** $db eval SQL ?ARRAYNAME? SCRIPT
1683*/
1684static int DbEvalNextCmd(
1685 ClientData data[], /* data[0] is the (DbEvalContext*) */
1686 Tcl_Interp *interp, /* Tcl interpreter */
1687 int result /* Result so far */
1688){
1689 int rc = result; /* Return code */
1690
1691 /* The first element of the data[] array is a pointer to a DbEvalContext
1692 ** structure allocated using Tcl_Alloc(). The second element of data[]
1693 ** is a pointer to a Tcl_Obj containing the script to run for each row
1694 ** returned by the queries encapsulated in data[0]. */
1695 DbEvalContext *p = (DbEvalContext *)data[0];
1696 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1697 Tcl_Obj *pArray = p->pArray;
1698
1699 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1700 int i;
1701 int nCol;
1702 Tcl_Obj **apColName;
1703 dbEvalRowInfo(p, &nCol, &apColName);
1704 for(i=0; i<nCol; i++){
1705 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1706 if( pArray==0 ){
1707 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1708 }else{
1709 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1710 }
1711 }
1712
mistachkinb56660f2016-07-14 21:26:09 +00001713 /* The required interpreter variables are now populated with the data
dan4a4c11a2009-10-06 14:59:02 +00001714 ** from the current row. If using NRE, schedule callbacks to evaluate
1715 ** script pScript, then to invoke this function again to fetch the next
1716 ** row (or clean up if there is no next row or the script throws an
mistachkinb56660f2016-07-14 21:26:09 +00001717 ** exception). After scheduling the callbacks, return control to the
dan4a4c11a2009-10-06 14:59:02 +00001718 ** caller.
1719 **
1720 ** If not using NRE, evaluate pScript directly and continue with the
1721 ** next iteration of this while(...) loop. */
1722 if( DbUseNre() ){
1723 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1724 return Tcl_NREvalObj(interp, pScript, 0);
1725 }else{
1726 rc = Tcl_EvalObjEx(interp, pScript, 0);
1727 }
1728 }
1729
1730 Tcl_DecrRefCount(pScript);
1731 dbEvalFinalize(p);
1732 Tcl_Free((char *)p);
1733
1734 if( rc==TCL_OK || rc==TCL_BREAK ){
1735 Tcl_ResetResult(interp);
1736 rc = TCL_OK;
1737 }
1738 return rc;
danielk19778e556522007-11-13 10:30:24 +00001739}
1740
tpoindex1067fe12004-12-17 15:41:11 +00001741/*
mistachkinb56660f2016-07-14 21:26:09 +00001742** This function is used by the implementations of the following database
dan46c47d42011-03-01 18:42:07 +00001743** handle sub-commands:
1744**
1745** $db update_hook ?SCRIPT?
1746** $db wal_hook ?SCRIPT?
1747** $db commit_hook ?SCRIPT?
1748** $db preupdate hook ?SCRIPT?
1749*/
1750static void DbHookCmd(
1751 Tcl_Interp *interp, /* Tcl interpreter */
1752 SqliteDb *pDb, /* Database handle */
1753 Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */
1754 Tcl_Obj **ppHook /* Pointer to member of SqliteDb */
1755){
1756 sqlite3 *db = pDb->db;
1757
1758 if( *ppHook ){
1759 Tcl_SetObjResult(interp, *ppHook);
1760 if( pArg ){
1761 Tcl_DecrRefCount(*ppHook);
1762 *ppHook = 0;
1763 }
1764 }
1765 if( pArg ){
1766 assert( !(*ppHook) );
1767 if( Tcl_GetCharLength(pArg)>0 ){
1768 *ppHook = pArg;
1769 Tcl_IncrRefCount(*ppHook);
1770 }
1771 }
1772
drh9b1c62d2011-03-30 21:04:43 +00001773#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +00001774 sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
drh9b1c62d2011-03-30 21:04:43 +00001775#endif
dan46c47d42011-03-01 18:42:07 +00001776 sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1777 sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1778 sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
1779}
1780
1781/*
drh75897232000-05-29 14:26:00 +00001782** The "sqlite" command below creates a new Tcl command for each
1783** connection it opens to an SQLite database. This routine is invoked
1784** whenever one of those connection-specific commands is executed
1785** in Tcl. For example, if you run Tcl code like this:
1786**
drh9bb575f2004-09-06 17:24:11 +00001787** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001788** db1 close
1789**
1790** The first command opens a connection to the "my_database" database
1791** and calls that connection "db1". The second command causes this
1792** subroutine to be invoked.
1793*/
drh6d313162000-09-21 13:01:35 +00001794static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001795 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001796 int choice;
drh22fbcb82004-02-01 01:22:50 +00001797 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001798 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001799 "authorizer", "backup", "busy",
1800 "cache", "changes", "close",
1801 "collate", "collation_needed", "commit_hook",
1802 "complete", "copy", "enable_load_extension",
1803 "errorcode", "eval", "exists",
1804 "function", "incrblob", "interrupt",
drh833bf962010-04-28 14:42:19 +00001805 "last_insert_rowid", "nullvalue", "onecolumn",
drh304637c2011-03-18 16:47:27 +00001806 "preupdate", "profile", "progress",
1807 "rekey", "restore", "rollback_hook",
1808 "status", "timeout", "total_changes",
mistachkinb56660f2016-07-14 21:26:09 +00001809 "trace", "trace_v2", "transaction",
1810 "unlock_notify", "update_hook", "version",
1811 "wal_hook",
1812 0
drh6d313162000-09-21 13:01:35 +00001813 };
drh411995d2002-06-25 19:31:18 +00001814 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001815 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1816 DB_CACHE, DB_CHANGES, DB_CLOSE,
1817 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1818 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1819 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1820 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
drh833bf962010-04-28 14:42:19 +00001821 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
drh304637c2011-03-18 16:47:27 +00001822 DB_PREUPDATE, DB_PROFILE, DB_PROGRESS,
1823 DB_REKEY, DB_RESTORE, DB_ROLLBACK_HOOK,
1824 DB_STATUS, DB_TIMEOUT, DB_TOTAL_CHANGES,
mistachkinb56660f2016-07-14 21:26:09 +00001825 DB_TRACE, DB_TRACE_V2, DB_TRANSACTION,
1826 DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK, DB_VERSION,
1827 DB_WAL_HOOK,
drh6d313162000-09-21 13:01:35 +00001828 };
tpoindex1067fe12004-12-17 15:41:11 +00001829 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001830
1831 if( objc<2 ){
1832 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001833 return TCL_ERROR;
1834 }
drh411995d2002-06-25 19:31:18 +00001835 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001836 return TCL_ERROR;
1837 }
1838
drh411995d2002-06-25 19:31:18 +00001839 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001840
drhe22a3342003-04-22 20:30:37 +00001841 /* $db authorizer ?CALLBACK?
1842 **
1843 ** Invoke the given callback to authorize each SQL operation as it is
1844 ** compiled. 5 arguments are appended to the callback before it is
1845 ** invoked:
1846 **
1847 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1848 ** (2) First descriptive name (depends on authorization type)
1849 ** (3) Second descriptive name
1850 ** (4) Name of the database (ex: "main", "temp")
1851 ** (5) Name of trigger that is doing the access
1852 **
1853 ** The callback should return on of the following strings: SQLITE_OK,
1854 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1855 **
1856 ** If this method is invoked with no arguments, the current authorization
1857 ** callback string is returned.
1858 */
1859 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001860#ifdef SQLITE_OMIT_AUTHORIZATION
drha198f2b2014-02-07 19:26:13 +00001861 Tcl_AppendResult(interp, "authorization not available in this build",
1862 (char*)0);
drh1211de32004-07-26 12:24:22 +00001863 return TCL_ERROR;
1864#else
drhe22a3342003-04-22 20:30:37 +00001865 if( objc>3 ){
1866 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001867 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001868 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001869 if( pDb->zAuth ){
drha198f2b2014-02-07 19:26:13 +00001870 Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
drhe22a3342003-04-22 20:30:37 +00001871 }
1872 }else{
1873 char *zAuth;
1874 int len;
1875 if( pDb->zAuth ){
1876 Tcl_Free(pDb->zAuth);
1877 }
1878 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1879 if( zAuth && len>0 ){
1880 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001881 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001882 }else{
1883 pDb->zAuth = 0;
1884 }
drhe22a3342003-04-22 20:30:37 +00001885 if( pDb->zAuth ){
drh32c6a482014-09-11 13:44:52 +00001886 typedef int (*sqlite3_auth_cb)(
1887 void*,int,const char*,const char*,
1888 const char*,const char*);
drhe22a3342003-04-22 20:30:37 +00001889 pDb->interp = interp;
drh32c6a482014-09-11 13:44:52 +00001890 sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
drhe22a3342003-04-22 20:30:37 +00001891 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001892 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001893 }
drhe22a3342003-04-22 20:30:37 +00001894 }
drh1211de32004-07-26 12:24:22 +00001895#endif
drhe22a3342003-04-22 20:30:37 +00001896 break;
1897 }
1898
drhdc2c4912009-02-04 22:46:47 +00001899 /* $db backup ?DATABASE? FILENAME
1900 **
1901 ** Open or create a database file named FILENAME. Transfer the
1902 ** content of local database DATABASE (default: "main") into the
1903 ** FILENAME database.
1904 */
1905 case DB_BACKUP: {
1906 const char *zDestFile;
1907 const char *zSrcDb;
1908 sqlite3 *pDest;
1909 sqlite3_backup *pBackup;
1910
1911 if( objc==3 ){
1912 zSrcDb = "main";
1913 zDestFile = Tcl_GetString(objv[2]);
1914 }else if( objc==4 ){
1915 zSrcDb = Tcl_GetString(objv[2]);
1916 zDestFile = Tcl_GetString(objv[3]);
1917 }else{
1918 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1919 return TCL_ERROR;
1920 }
drh147ef392016-01-22 23:17:51 +00001921 rc = sqlite3_open_v2(zDestFile, &pDest,
1922 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00001923 if( rc!=SQLITE_OK ){
1924 Tcl_AppendResult(interp, "cannot open target database: ",
1925 sqlite3_errmsg(pDest), (char*)0);
1926 sqlite3_close(pDest);
1927 return TCL_ERROR;
1928 }
1929 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1930 if( pBackup==0 ){
1931 Tcl_AppendResult(interp, "backup failed: ",
1932 sqlite3_errmsg(pDest), (char*)0);
1933 sqlite3_close(pDest);
1934 return TCL_ERROR;
1935 }
1936 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1937 sqlite3_backup_finish(pBackup);
1938 if( rc==SQLITE_DONE ){
1939 rc = TCL_OK;
1940 }else{
1941 Tcl_AppendResult(interp, "backup failed: ",
1942 sqlite3_errmsg(pDest), (char*)0);
1943 rc = TCL_ERROR;
1944 }
1945 sqlite3_close(pDest);
1946 break;
1947 }
1948
drhbec3f402000-08-04 13:49:02 +00001949 /* $db busy ?CALLBACK?
1950 **
1951 ** Invoke the given callback if an SQL statement attempts to open
1952 ** a locked database file.
1953 */
drh6d313162000-09-21 13:01:35 +00001954 case DB_BUSY: {
1955 if( objc>3 ){
1956 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001957 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001958 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001959 if( pDb->zBusy ){
drha198f2b2014-02-07 19:26:13 +00001960 Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
drhbec3f402000-08-04 13:49:02 +00001961 }
1962 }else{
drh6d313162000-09-21 13:01:35 +00001963 char *zBusy;
1964 int len;
drhbec3f402000-08-04 13:49:02 +00001965 if( pDb->zBusy ){
1966 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001967 }
drh6d313162000-09-21 13:01:35 +00001968 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1969 if( zBusy && len>0 ){
1970 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001971 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001972 }else{
1973 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001974 }
1975 if( pDb->zBusy ){
1976 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001977 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001978 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001979 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001980 }
1981 }
drh6d313162000-09-21 13:01:35 +00001982 break;
1983 }
drhbec3f402000-08-04 13:49:02 +00001984
drhfb7e7652005-01-24 00:28:42 +00001985 /* $db cache flush
1986 ** $db cache size n
1987 **
1988 ** Flush the prepared statement cache, or set the maximum number of
1989 ** cached statements.
1990 */
1991 case DB_CACHE: {
1992 char *subCmd;
1993 int n;
1994
1995 if( objc<=2 ){
1996 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1997 return TCL_ERROR;
1998 }
1999 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
2000 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
2001 if( objc!=3 ){
2002 Tcl_WrongNumArgs(interp, 2, objv, "flush");
2003 return TCL_ERROR;
2004 }else{
2005 flushStmtCache( pDb );
2006 }
2007 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
2008 if( objc!=4 ){
2009 Tcl_WrongNumArgs(interp, 2, objv, "size n");
2010 return TCL_ERROR;
2011 }else{
2012 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
mistachkinb56660f2016-07-14 21:26:09 +00002013 Tcl_AppendResult( interp, "cannot convert \"",
drha198f2b2014-02-07 19:26:13 +00002014 Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
drhfb7e7652005-01-24 00:28:42 +00002015 return TCL_ERROR;
2016 }else{
2017 if( n<0 ){
2018 flushStmtCache( pDb );
2019 n = 0;
2020 }else if( n>MAX_PREPARED_STMTS ){
2021 n = MAX_PREPARED_STMTS;
2022 }
2023 pDb->maxStmt = n;
2024 }
2025 }
2026 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002027 Tcl_AppendResult( interp, "bad option \"",
drha198f2b2014-02-07 19:26:13 +00002028 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
2029 (char*)0);
drhfb7e7652005-01-24 00:28:42 +00002030 return TCL_ERROR;
2031 }
2032 break;
2033 }
2034
danielk1977b28af712004-06-21 06:50:26 +00002035 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00002036 **
2037 ** Return the number of rows that were modified, inserted, or deleted by
mistachkinb56660f2016-07-14 21:26:09 +00002038 ** the most recent INSERT, UPDATE or DELETE statement, not including
danielk1977b28af712004-06-21 06:50:26 +00002039 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00002040 */
2041 case DB_CHANGES: {
2042 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00002043 if( objc!=2 ){
2044 Tcl_WrongNumArgs(interp, 2, objv, "");
2045 return TCL_ERROR;
2046 }
drhc8d30ac2002-04-12 10:08:59 +00002047 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00002048 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00002049 break;
2050 }
2051
drh75897232000-05-29 14:26:00 +00002052 /* $db close
2053 **
2054 ** Shutdown the database
2055 */
drh6d313162000-09-21 13:01:35 +00002056 case DB_CLOSE: {
2057 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
2058 break;
2059 }
drh75897232000-05-29 14:26:00 +00002060
drh0f14e2e2004-06-29 12:39:08 +00002061 /*
2062 ** $db collate NAME SCRIPT
2063 **
2064 ** Create a new SQL collation function called NAME. Whenever
2065 ** that function is called, invoke SCRIPT to evaluate the function.
2066 */
2067 case DB_COLLATE: {
2068 SqlCollate *pCollate;
2069 char *zName;
2070 char *zScript;
2071 int nScript;
2072 if( objc!=4 ){
2073 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
2074 return TCL_ERROR;
2075 }
2076 zName = Tcl_GetStringFromObj(objv[2], 0);
2077 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
2078 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
2079 if( pCollate==0 ) return TCL_ERROR;
2080 pCollate->interp = interp;
2081 pCollate->pNext = pDb->pCollate;
2082 pCollate->zScript = (char*)&pCollate[1];
2083 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00002084 memcpy(pCollate->zScript, zScript, nScript+1);
mistachkinb56660f2016-07-14 21:26:09 +00002085 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
drh0f14e2e2004-06-29 12:39:08 +00002086 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00002087 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00002088 return TCL_ERROR;
2089 }
2090 break;
2091 }
2092
2093 /*
2094 ** $db collation_needed SCRIPT
2095 **
2096 ** Create a new SQL collation function called NAME. Whenever
2097 ** that function is called, invoke SCRIPT to evaluate the function.
2098 */
2099 case DB_COLLATION_NEEDED: {
2100 if( objc!=3 ){
2101 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
2102 return TCL_ERROR;
2103 }
2104 if( pDb->pCollateNeeded ){
2105 Tcl_DecrRefCount(pDb->pCollateNeeded);
2106 }
2107 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
2108 Tcl_IncrRefCount(pDb->pCollateNeeded);
2109 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
2110 break;
2111 }
2112
drh19e2d372005-08-29 23:00:03 +00002113 /* $db commit_hook ?CALLBACK?
2114 **
2115 ** Invoke the given callback just before committing every SQL transaction.
2116 ** If the callback throws an exception or returns non-zero, then the
2117 ** transaction is aborted. If CALLBACK is an empty string, the callback
2118 ** is disabled.
2119 */
2120 case DB_COMMIT_HOOK: {
2121 if( objc>3 ){
2122 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2123 return TCL_ERROR;
2124 }else if( objc==2 ){
2125 if( pDb->zCommit ){
drha198f2b2014-02-07 19:26:13 +00002126 Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002127 }
2128 }else{
mistachkin6ef5e122014-01-24 17:03:55 +00002129 const char *zCommit;
drh19e2d372005-08-29 23:00:03 +00002130 int len;
2131 if( pDb->zCommit ){
2132 Tcl_Free(pDb->zCommit);
2133 }
2134 zCommit = Tcl_GetStringFromObj(objv[2], &len);
2135 if( zCommit && len>0 ){
2136 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002137 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00002138 }else{
2139 pDb->zCommit = 0;
2140 }
2141 if( pDb->zCommit ){
2142 pDb->interp = interp;
2143 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
2144 }else{
2145 sqlite3_commit_hook(pDb->db, 0, 0);
2146 }
2147 }
2148 break;
2149 }
2150
drh75897232000-05-29 14:26:00 +00002151 /* $db complete SQL
2152 **
2153 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2154 ** additional lines of input are needed. This is similar to the
2155 ** built-in "info complete" command of Tcl.
2156 */
drh6d313162000-09-21 13:01:35 +00002157 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00002158#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00002159 Tcl_Obj *pResult;
2160 int isComplete;
2161 if( objc!=3 ){
2162 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00002163 return TCL_ERROR;
2164 }
danielk19776f8a5032004-05-10 10:34:51 +00002165 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00002166 pResult = Tcl_GetObjResult(interp);
2167 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00002168#endif
drh6d313162000-09-21 13:01:35 +00002169 break;
2170 }
drhdcd997e2003-01-31 17:21:49 +00002171
drh19e2d372005-08-29 23:00:03 +00002172 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2173 **
2174 ** Copy data into table from filename, optionally using SEPARATOR
2175 ** as column separators. If a column contains a null string, or the
2176 ** value of NULLINDICATOR, a NULL is inserted for the column.
2177 ** conflict-algorithm is one of the sqlite conflict algorithms:
2178 ** rollback, abort, fail, ignore, replace
2179 ** On success, return the number of lines processed, not necessarily same
2180 ** as 'db changes' due to conflict-algorithm selected.
2181 **
2182 ** This code is basically an implementation/enhancement of
2183 ** the sqlite3 shell.c ".import" command.
2184 **
2185 ** This command usage is equivalent to the sqlite2.x COPY statement,
2186 ** which imports file data into a table using the PostgreSQL COPY file format:
2187 ** $db copy $conflit_algo $table_name $filename \t \\N
2188 */
2189 case DB_COPY: {
2190 char *zTable; /* Insert data into this table */
2191 char *zFile; /* The file from which to extract data */
2192 char *zConflict; /* The conflict algorithm to use */
2193 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00002194 int nCol; /* Number of columns in the table */
2195 int nByte; /* Number of bytes in an SQL string */
2196 int i, j; /* Loop counters */
2197 int nSep; /* Number of bytes in zSep[] */
2198 int nNull; /* Number of bytes in zNull[] */
2199 char *zSql; /* An SQL statement */
2200 char *zLine; /* A single line of input from the file */
2201 char **azCol; /* zLine[] broken up into columns */
mistachkin6ef5e122014-01-24 17:03:55 +00002202 const char *zCommit; /* How to commit changes */
drh19e2d372005-08-29 23:00:03 +00002203 FILE *in; /* The input file */
2204 int lineno = 0; /* Line number of input file */
2205 char zLineNum[80]; /* Line number print buffer */
2206 Tcl_Obj *pResult; /* interp result */
2207
mistachkin6ef5e122014-01-24 17:03:55 +00002208 const char *zSep;
2209 const char *zNull;
drh19e2d372005-08-29 23:00:03 +00002210 if( objc<5 || objc>7 ){
mistachkinb56660f2016-07-14 21:26:09 +00002211 Tcl_WrongNumArgs(interp, 2, objv,
drh19e2d372005-08-29 23:00:03 +00002212 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2213 return TCL_ERROR;
2214 }
2215 if( objc>=6 ){
2216 zSep = Tcl_GetStringFromObj(objv[5], 0);
2217 }else{
2218 zSep = "\t";
2219 }
2220 if( objc>=7 ){
2221 zNull = Tcl_GetStringFromObj(objv[6], 0);
2222 }else{
2223 zNull = "";
2224 }
2225 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2226 zTable = Tcl_GetStringFromObj(objv[3], 0);
2227 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002228 nSep = strlen30(zSep);
2229 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002230 if( nSep==0 ){
drha198f2b2014-02-07 19:26:13 +00002231 Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2232 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002233 return TCL_ERROR;
2234 }
drh3e59c012008-09-23 10:12:13 +00002235 if(strcmp(zConflict, "rollback") != 0 &&
2236 strcmp(zConflict, "abort" ) != 0 &&
2237 strcmp(zConflict, "fail" ) != 0 &&
2238 strcmp(zConflict, "ignore" ) != 0 &&
2239 strcmp(zConflict, "replace" ) != 0 ) {
mistachkinb56660f2016-07-14 21:26:09 +00002240 Tcl_AppendResult(interp, "Error: \"", zConflict,
drh19e2d372005-08-29 23:00:03 +00002241 "\", conflict-algorithm must be one of: rollback, "
drha198f2b2014-02-07 19:26:13 +00002242 "abort, fail, ignore, or replace", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002243 return TCL_ERROR;
2244 }
2245 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2246 if( zSql==0 ){
drha198f2b2014-02-07 19:26:13 +00002247 Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002248 return TCL_ERROR;
2249 }
drh4f21c4a2008-12-10 22:15:00 +00002250 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002251 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002252 sqlite3_free(zSql);
2253 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002254 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002255 nCol = 0;
2256 }else{
2257 nCol = sqlite3_column_count(pStmt);
2258 }
2259 sqlite3_finalize(pStmt);
2260 if( nCol==0 ) {
2261 return TCL_ERROR;
2262 }
2263 zSql = malloc( nByte + 50 + nCol*2 );
2264 if( zSql==0 ) {
drha198f2b2014-02-07 19:26:13 +00002265 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002266 return TCL_ERROR;
2267 }
2268 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2269 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002270 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002271 for(i=1; i<nCol; i++){
2272 zSql[j++] = ',';
2273 zSql[j++] = '?';
2274 }
2275 zSql[j++] = ')';
2276 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002277 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002278 free(zSql);
2279 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002280 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002281 sqlite3_finalize(pStmt);
2282 return TCL_ERROR;
2283 }
2284 in = fopen(zFile, "rb");
2285 if( in==0 ){
2286 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2287 sqlite3_finalize(pStmt);
2288 return TCL_ERROR;
2289 }
2290 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2291 if( azCol==0 ) {
drha198f2b2014-02-07 19:26:13 +00002292 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh43617e92006-03-06 20:55:46 +00002293 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002294 return TCL_ERROR;
2295 }
drh37527852006-03-16 16:19:56 +00002296 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002297 zCommit = "COMMIT";
2298 while( (zLine = local_getline(0, in))!=0 ){
2299 char *z;
drh19e2d372005-08-29 23:00:03 +00002300 lineno++;
2301 azCol[0] = zLine;
2302 for(i=0, z=zLine; *z; z++){
2303 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2304 *z = 0;
2305 i++;
2306 if( i<nCol ){
2307 azCol[i] = &z[nSep];
2308 z += nSep-1;
2309 }
2310 }
2311 }
2312 if( i+1!=nCol ){
2313 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002314 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002315 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002316 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002317 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002318 "Error: %s line %d: expected %d columns of data but found %d",
2319 zFile, lineno, nCol, i+1);
drha198f2b2014-02-07 19:26:13 +00002320 Tcl_AppendResult(interp, zErr, (char*)0);
drhc1f44942006-05-10 14:39:13 +00002321 free(zErr);
2322 }
drh19e2d372005-08-29 23:00:03 +00002323 zCommit = "ROLLBACK";
2324 break;
2325 }
2326 for(i=0; i<nCol; i++){
2327 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002328 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
mistachkinb56660f2016-07-14 21:26:09 +00002329 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002330 ){
drh19e2d372005-08-29 23:00:03 +00002331 sqlite3_bind_null(pStmt, i+1);
2332 }else{
2333 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2334 }
2335 }
2336 sqlite3_step(pStmt);
2337 rc = sqlite3_reset(pStmt);
2338 free(zLine);
2339 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00002340 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002341 zCommit = "ROLLBACK";
2342 break;
2343 }
2344 }
2345 free(azCol);
2346 fclose(in);
2347 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002348 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002349
2350 if( zCommit[0] == 'C' ){
2351 /* success, set result as number of lines processed */
2352 pResult = Tcl_GetObjResult(interp);
2353 Tcl_SetIntObj(pResult, lineno);
2354 rc = TCL_OK;
2355 }else{
2356 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002357 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drha198f2b2014-02-07 19:26:13 +00002358 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2359 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002360 rc = TCL_ERROR;
2361 }
2362 break;
2363 }
2364
drhdcd997e2003-01-31 17:21:49 +00002365 /*
drh41449052006-07-06 17:08:48 +00002366 ** $db enable_load_extension BOOLEAN
2367 **
2368 ** Turn the extension loading feature on or off. It if off by
2369 ** default.
2370 */
2371 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002372#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002373 int onoff;
2374 if( objc!=3 ){
2375 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2376 return TCL_ERROR;
2377 }
2378 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2379 return TCL_ERROR;
2380 }
2381 sqlite3_enable_load_extension(pDb->db, onoff);
2382 break;
drhf533acc2006-12-19 18:57:11 +00002383#else
2384 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
drha198f2b2014-02-07 19:26:13 +00002385 (char*)0);
drhf533acc2006-12-19 18:57:11 +00002386 return TCL_ERROR;
2387#endif
drh41449052006-07-06 17:08:48 +00002388 }
2389
2390 /*
drhdcd997e2003-01-31 17:21:49 +00002391 ** $db errorcode
2392 **
2393 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002394 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002395 */
2396 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002397 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002398 break;
2399 }
dan4a4c11a2009-10-06 14:59:02 +00002400
2401 /*
2402 ** $db exists $sql
2403 ** $db onecolumn $sql
2404 **
2405 ** The onecolumn method is the equivalent of:
2406 ** lindex [$db eval $sql] 0
2407 */
mistachkinb56660f2016-07-14 21:26:09 +00002408 case DB_EXISTS:
dan4a4c11a2009-10-06 14:59:02 +00002409 case DB_ONECOLUMN: {
drhedc40242016-06-13 12:34:38 +00002410 Tcl_Obj *pResult = 0;
dan4a4c11a2009-10-06 14:59:02 +00002411 DbEvalContext sEval;
2412 if( objc!=3 ){
2413 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2414 return TCL_ERROR;
2415 }
2416
2417 dbEvalInit(&sEval, pDb, objv[2], 0);
2418 rc = dbEvalStep(&sEval);
2419 if( choice==DB_ONECOLUMN ){
2420 if( rc==TCL_OK ){
drhedc40242016-06-13 12:34:38 +00002421 pResult = dbEvalColumnValue(&sEval, 0);
dand5f12cd2011-08-18 17:47:57 +00002422 }else if( rc==TCL_BREAK ){
2423 Tcl_ResetResult(interp);
dan4a4c11a2009-10-06 14:59:02 +00002424 }
2425 }else if( rc==TCL_BREAK || rc==TCL_OK ){
drhedc40242016-06-13 12:34:38 +00002426 pResult = Tcl_NewBooleanObj(rc==TCL_OK);
dan4a4c11a2009-10-06 14:59:02 +00002427 }
2428 dbEvalFinalize(&sEval);
drhedc40242016-06-13 12:34:38 +00002429 if( pResult ) Tcl_SetObjResult(interp, pResult);
dan4a4c11a2009-10-06 14:59:02 +00002430
2431 if( rc==TCL_BREAK ){
2432 rc = TCL_OK;
2433 }
2434 break;
2435 }
mistachkinb56660f2016-07-14 21:26:09 +00002436
drh75897232000-05-29 14:26:00 +00002437 /*
drh895d7472004-08-20 16:02:39 +00002438 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002439 **
2440 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002441 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002442 ** If "array" and "code" are omitted, then no callback is every invoked.
2443 ** If "array" is an empty string, then the values are placed in variables
2444 ** that have the same name as the fields extracted by the query.
2445 */
dan4a4c11a2009-10-06 14:59:02 +00002446 case DB_EVAL: {
2447 if( objc<3 || objc>5 ){
2448 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2449 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002450 }
dan4a4c11a2009-10-06 14:59:02 +00002451
drh92febd92004-08-20 18:34:20 +00002452 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002453 DbEvalContext sEval;
2454 Tcl_Obj *pRet = Tcl_NewObj();
2455 Tcl_IncrRefCount(pRet);
2456 dbEvalInit(&sEval, pDb, objv[2], 0);
2457 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2458 int i;
2459 int nCol;
2460 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002461 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002462 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002463 }
2464 }
dan4a4c11a2009-10-06 14:59:02 +00002465 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002466 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002467 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002468 rc = TCL_OK;
2469 }
drh1807ce32004-09-07 13:20:35 +00002470 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002471 }else{
mistachkin8e189222015-04-19 21:43:16 +00002472 ClientData cd2[2];
dan4a4c11a2009-10-06 14:59:02 +00002473 DbEvalContext *p;
2474 Tcl_Obj *pArray = 0;
2475 Tcl_Obj *pScript;
2476
2477 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2478 pArray = objv[3];
2479 }
2480 pScript = objv[objc-1];
2481 Tcl_IncrRefCount(pScript);
mistachkinb56660f2016-07-14 21:26:09 +00002482
dan4a4c11a2009-10-06 14:59:02 +00002483 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2484 dbEvalInit(p, pDb, objv[2], pArray);
2485
mistachkin8e189222015-04-19 21:43:16 +00002486 cd2[0] = (void *)p;
2487 cd2[1] = (void *)pScript;
2488 rc = DbEvalNextCmd(cd2, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002489 }
danielk197730ccda12004-05-27 12:11:31 +00002490 break;
2491 }
drhbec3f402000-08-04 13:49:02 +00002492
2493 /*
dan3df30592015-03-13 08:31:54 +00002494 ** $db function NAME [-argcount N] [-deterministic] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002495 **
2496 ** Create a new SQL function called NAME. Whenever that function is
2497 ** called, invoke SCRIPT to evaluate the function.
2498 */
2499 case DB_FUNCTION: {
dan3df30592015-03-13 08:31:54 +00002500 int flags = SQLITE_UTF8;
drhcabb0812002-09-14 13:47:32 +00002501 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002502 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002503 char *zName;
drhe3602be2008-09-09 12:31:33 +00002504 int nArg = -1;
dan3df30592015-03-13 08:31:54 +00002505 int i;
2506 if( objc<4 ){
2507 Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
2508 return TCL_ERROR;
2509 }
2510 for(i=3; i<(objc-1); i++){
2511 const char *z = Tcl_GetString(objv[i]);
drh4f21c4a2008-12-10 22:15:00 +00002512 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002513 if( n>2 && strncmp(z, "-argcount",n)==0 ){
dan3df30592015-03-13 08:31:54 +00002514 if( i==(objc-2) ){
2515 Tcl_AppendResult(interp, "option requires an argument: ", z, 0);
2516 return TCL_ERROR;
2517 }
2518 if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002519 if( nArg<0 ){
2520 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2521 (char*)0);
2522 return TCL_ERROR;
2523 }
dan3df30592015-03-13 08:31:54 +00002524 i++;
2525 }else
2526 if( n>2 && strncmp(z, "-deterministic",n)==0 ){
2527 flags |= SQLITE_DETERMINISTIC;
2528 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002529 Tcl_AppendResult(interp, "bad option \"", z,
dan3df30592015-03-13 08:31:54 +00002530 "\": must be -argcount or -deterministic", 0
2531 );
2532 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002533 }
drhcabb0812002-09-14 13:47:32 +00002534 }
dan3df30592015-03-13 08:31:54 +00002535
2536 pScript = objv[objc-1];
drhcabb0812002-09-14 13:47:32 +00002537 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002538 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002539 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002540 if( pFunc->pScript ){
2541 Tcl_DecrRefCount(pFunc->pScript);
2542 }
2543 pFunc->pScript = pScript;
2544 Tcl_IncrRefCount(pScript);
2545 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
dan3df30592015-03-13 08:31:54 +00002546 rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
danielk1977d8123362004-06-12 09:25:12 +00002547 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002548 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002549 rc = TCL_ERROR;
2550 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002551 }
drhcabb0812002-09-14 13:47:32 +00002552 break;
2553 }
2554
2555 /*
danielk19778cbadb02007-05-03 16:31:26 +00002556 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002557 */
2558 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002559#ifdef SQLITE_OMIT_INCRBLOB
drha198f2b2014-02-07 19:26:13 +00002560 Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
danielk197732a0d8b2007-05-04 19:03:02 +00002561 return TCL_ERROR;
2562#else
danielk19778cbadb02007-05-03 16:31:26 +00002563 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002564 const char *zDb = "main";
2565 const char *zTable;
2566 const char *zColumn;
drhb3f787f2012-09-29 14:45:54 +00002567 Tcl_WideInt iRow;
danielk1977b4e9af92007-05-01 17:49:49 +00002568
danielk19778cbadb02007-05-03 16:31:26 +00002569 /* Check for the -readonly option */
2570 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2571 isReadonly = 1;
2572 }
2573
2574 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2575 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002576 return TCL_ERROR;
2577 }
2578
danielk19778cbadb02007-05-03 16:31:26 +00002579 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002580 zDb = Tcl_GetString(objv[2]);
2581 }
2582 zTable = Tcl_GetString(objv[objc-3]);
2583 zColumn = Tcl_GetString(objv[objc-2]);
2584 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2585
2586 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002587 rc = createIncrblobChannel(
danedf5b162014-08-19 09:15:41 +00002588 interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
danielk19778cbadb02007-05-03 16:31:26 +00002589 );
danielk1977b4e9af92007-05-01 17:49:49 +00002590 }
danielk197732a0d8b2007-05-04 19:03:02 +00002591#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002592 break;
2593 }
2594
2595 /*
drhf11bded2006-07-17 00:02:44 +00002596 ** $db interrupt
2597 **
2598 ** Interrupt the execution of the inner-most SQL interpreter. This
2599 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2600 */
2601 case DB_INTERRUPT: {
2602 sqlite3_interrupt(pDb->db);
2603 break;
2604 }
2605
2606 /*
drh19e2d372005-08-29 23:00:03 +00002607 ** $db nullvalue ?STRING?
2608 **
2609 ** Change text used when a NULL comes back from the database. If ?STRING?
2610 ** is not present, then the current string used for NULL is returned.
2611 ** If STRING is present, then STRING is returned.
2612 **
2613 */
2614 case DB_NULLVALUE: {
2615 if( objc!=2 && objc!=3 ){
2616 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2617 return TCL_ERROR;
2618 }
2619 if( objc==3 ){
2620 int len;
2621 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2622 if( pDb->zNull ){
2623 Tcl_Free(pDb->zNull);
2624 }
2625 if( zNull && len>0 ){
2626 pDb->zNull = Tcl_Alloc( len + 1 );
drh7fd33922011-06-20 19:00:30 +00002627 memcpy(pDb->zNull, zNull, len);
drh19e2d372005-08-29 23:00:03 +00002628 pDb->zNull[len] = '\0';
2629 }else{
2630 pDb->zNull = 0;
2631 }
2632 }
drhc45e6712012-10-03 11:02:33 +00002633 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
drh19e2d372005-08-29 23:00:03 +00002634 break;
2635 }
2636
2637 /*
mistachkinb56660f2016-07-14 21:26:09 +00002638 ** $db last_insert_rowid
drhaf9ff332002-01-16 21:00:27 +00002639 **
2640 ** Return an integer which is the ROWID for the most recent insert.
2641 */
2642 case DB_LAST_INSERT_ROWID: {
2643 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002644 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002645 if( objc!=2 ){
2646 Tcl_WrongNumArgs(interp, 2, objv, "");
2647 return TCL_ERROR;
2648 }
danielk19776f8a5032004-05-10 10:34:51 +00002649 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002650 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002651 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002652 break;
2653 }
2654
2655 /*
dan4a4c11a2009-10-06 14:59:02 +00002656 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002657 */
drh1807ce32004-09-07 13:20:35 +00002658
2659 /* $db progress ?N CALLBACK?
mistachkinb56660f2016-07-14 21:26:09 +00002660 **
drh1807ce32004-09-07 13:20:35 +00002661 ** Invoke the given callback every N virtual machine opcodes while executing
2662 ** queries.
2663 */
2664 case DB_PROGRESS: {
2665 if( objc==2 ){
2666 if( pDb->zProgress ){
drha198f2b2014-02-07 19:26:13 +00002667 Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
drh1807ce32004-09-07 13:20:35 +00002668 }
2669 }else if( objc==4 ){
2670 char *zProgress;
2671 int len;
2672 int N;
2673 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002674 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002675 };
2676 if( pDb->zProgress ){
2677 Tcl_Free(pDb->zProgress);
2678 }
2679 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2680 if( zProgress && len>0 ){
2681 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002682 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002683 }else{
2684 pDb->zProgress = 0;
2685 }
2686#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2687 if( pDb->zProgress ){
2688 pDb->interp = interp;
2689 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2690 }else{
2691 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2692 }
2693#endif
2694 }else{
2695 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002696 return TCL_ERROR;
2697 }
drh5d9d7572003-08-19 14:31:01 +00002698 break;
2699 }
2700
drh19e2d372005-08-29 23:00:03 +00002701 /* $db profile ?CALLBACK?
2702 **
2703 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2704 ** that has run. The text of the SQL and the amount of elapse time are
2705 ** appended to CALLBACK before the script is run.
2706 */
2707 case DB_PROFILE: {
2708 if( objc>3 ){
2709 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2710 return TCL_ERROR;
2711 }else if( objc==2 ){
2712 if( pDb->zProfile ){
drha198f2b2014-02-07 19:26:13 +00002713 Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002714 }
2715 }else{
2716 char *zProfile;
2717 int len;
2718 if( pDb->zProfile ){
2719 Tcl_Free(pDb->zProfile);
2720 }
2721 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2722 if( zProfile && len>0 ){
2723 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002724 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002725 }else{
2726 pDb->zProfile = 0;
2727 }
shanehbb201342011-02-09 19:55:20 +00002728#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh19e2d372005-08-29 23:00:03 +00002729 if( pDb->zProfile ){
2730 pDb->interp = interp;
2731 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2732 }else{
2733 sqlite3_profile(pDb->db, 0, 0);
2734 }
2735#endif
2736 }
2737 break;
2738 }
2739
drh5d9d7572003-08-19 14:31:01 +00002740 /*
drh22fbcb82004-02-01 01:22:50 +00002741 ** $db rekey KEY
2742 **
2743 ** Change the encryption key on the currently open database.
2744 */
2745 case DB_REKEY: {
drh32f57d42016-03-16 01:03:10 +00002746#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh22fbcb82004-02-01 01:22:50 +00002747 int nKey;
2748 void *pKey;
drhb07028f2011-10-14 21:49:18 +00002749#endif
drh22fbcb82004-02-01 01:22:50 +00002750 if( objc!=3 ){
2751 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2752 return TCL_ERROR;
2753 }
drh32f57d42016-03-16 01:03:10 +00002754#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00002755 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh2011d5f2004-07-22 02:40:37 +00002756 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002757 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002758 Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
drh22fbcb82004-02-01 01:22:50 +00002759 rc = TCL_ERROR;
2760 }
2761#endif
2762 break;
2763 }
2764
drhdc2c4912009-02-04 22:46:47 +00002765 /* $db restore ?DATABASE? FILENAME
2766 **
mistachkinb56660f2016-07-14 21:26:09 +00002767 ** Open a database file named FILENAME. Transfer the content
drhdc2c4912009-02-04 22:46:47 +00002768 ** of FILENAME into the local database DATABASE (default: "main").
2769 */
2770 case DB_RESTORE: {
2771 const char *zSrcFile;
2772 const char *zDestDb;
2773 sqlite3 *pSrc;
2774 sqlite3_backup *pBackup;
2775 int nTimeout = 0;
2776
2777 if( objc==3 ){
2778 zDestDb = "main";
2779 zSrcFile = Tcl_GetString(objv[2]);
2780 }else if( objc==4 ){
2781 zDestDb = Tcl_GetString(objv[2]);
2782 zSrcFile = Tcl_GetString(objv[3]);
2783 }else{
2784 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2785 return TCL_ERROR;
2786 }
drh147ef392016-01-22 23:17:51 +00002787 rc = sqlite3_open_v2(zSrcFile, &pSrc,
2788 SQLITE_OPEN_READONLY | pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00002789 if( rc!=SQLITE_OK ){
2790 Tcl_AppendResult(interp, "cannot open source database: ",
2791 sqlite3_errmsg(pSrc), (char*)0);
2792 sqlite3_close(pSrc);
2793 return TCL_ERROR;
2794 }
2795 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2796 if( pBackup==0 ){
2797 Tcl_AppendResult(interp, "restore failed: ",
2798 sqlite3_errmsg(pDb->db), (char*)0);
2799 sqlite3_close(pSrc);
2800 return TCL_ERROR;
2801 }
2802 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2803 || rc==SQLITE_BUSY ){
2804 if( rc==SQLITE_BUSY ){
2805 if( nTimeout++ >= 3 ) break;
2806 sqlite3_sleep(100);
2807 }
2808 }
2809 sqlite3_backup_finish(pBackup);
2810 if( rc==SQLITE_DONE ){
2811 rc = TCL_OK;
2812 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2813 Tcl_AppendResult(interp, "restore failed: source database busy",
2814 (char*)0);
2815 rc = TCL_ERROR;
2816 }else{
2817 Tcl_AppendResult(interp, "restore failed: ",
2818 sqlite3_errmsg(pDb->db), (char*)0);
2819 rc = TCL_ERROR;
2820 }
2821 sqlite3_close(pSrc);
2822 break;
2823 }
2824
drh22fbcb82004-02-01 01:22:50 +00002825 /*
drh3c379b02010-04-07 19:31:59 +00002826 ** $db status (step|sort|autoindex)
drhd1d38482008-10-07 23:46:38 +00002827 **
mistachkinb56660f2016-07-14 21:26:09 +00002828 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
drhd1d38482008-10-07 23:46:38 +00002829 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2830 */
2831 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002832 int v;
2833 const char *zOp;
2834 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00002835 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00002836 return TCL_ERROR;
2837 }
2838 zOp = Tcl_GetString(objv[2]);
2839 if( strcmp(zOp, "step")==0 ){
2840 v = pDb->nStep;
2841 }else if( strcmp(zOp, "sort")==0 ){
2842 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002843 }else if( strcmp(zOp, "autoindex")==0 ){
2844 v = pDb->nIndex;
drhd1d38482008-10-07 23:46:38 +00002845 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002846 Tcl_AppendResult(interp,
2847 "bad argument: should be autoindex, step, or sort",
drhd1d38482008-10-07 23:46:38 +00002848 (char*)0);
2849 return TCL_ERROR;
2850 }
2851 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2852 break;
2853 }
mistachkinb56660f2016-07-14 21:26:09 +00002854
drhd1d38482008-10-07 23:46:38 +00002855 /*
drhbec3f402000-08-04 13:49:02 +00002856 ** $db timeout MILLESECONDS
2857 **
2858 ** Delay for the number of milliseconds specified when a file is locked.
2859 */
drh6d313162000-09-21 13:01:35 +00002860 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002861 int ms;
drh6d313162000-09-21 13:01:35 +00002862 if( objc!=3 ){
2863 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002864 return TCL_ERROR;
2865 }
drh6d313162000-09-21 13:01:35 +00002866 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002867 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002868 break;
drh75897232000-05-29 14:26:00 +00002869 }
mistachkinb56660f2016-07-14 21:26:09 +00002870
danielk197755c45f22005-04-03 23:54:43 +00002871 /*
drh0f14e2e2004-06-29 12:39:08 +00002872 ** $db total_changes
2873 **
mistachkinb56660f2016-07-14 21:26:09 +00002874 ** Return the number of rows that were modified, inserted, or deleted
drh0f14e2e2004-06-29 12:39:08 +00002875 ** since the database handle was created.
2876 */
2877 case DB_TOTAL_CHANGES: {
2878 Tcl_Obj *pResult;
2879 if( objc!=2 ){
2880 Tcl_WrongNumArgs(interp, 2, objv, "");
2881 return TCL_ERROR;
2882 }
2883 pResult = Tcl_GetObjResult(interp);
2884 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2885 break;
2886 }
2887
drhb5a20d32003-04-23 12:25:23 +00002888 /* $db trace ?CALLBACK?
2889 **
2890 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2891 ** that is executed. The text of the SQL is appended to CALLBACK before
2892 ** it is executed.
2893 */
2894 case DB_TRACE: {
2895 if( objc>3 ){
2896 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002897 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002898 }else if( objc==2 ){
2899 if( pDb->zTrace ){
drha198f2b2014-02-07 19:26:13 +00002900 Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
drhb5a20d32003-04-23 12:25:23 +00002901 }
2902 }else{
2903 char *zTrace;
2904 int len;
2905 if( pDb->zTrace ){
2906 Tcl_Free(pDb->zTrace);
2907 }
2908 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2909 if( zTrace && len>0 ){
2910 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002911 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002912 }else{
2913 pDb->zTrace = 0;
2914 }
drh087ec072016-07-25 00:05:56 +00002915#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) \
2916 && !defined(SQLITE_OMIT_DEPRECATED)
drhb5a20d32003-04-23 12:25:23 +00002917 if( pDb->zTrace ){
2918 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002919 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002920 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002921 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002922 }
drh19e2d372005-08-29 23:00:03 +00002923#endif
drhb5a20d32003-04-23 12:25:23 +00002924 }
2925 break;
2926 }
2927
mistachkinb56660f2016-07-14 21:26:09 +00002928 /* $db trace_v2 ?CALLBACK? ?MASK?
2929 **
2930 ** Make arrangements to invoke the CALLBACK routine for each trace event
2931 ** matching the mask that is generated. The parameters are appended to
2932 ** CALLBACK before it is executed.
2933 */
2934 case DB_TRACE_V2: {
2935 if( objc>4 ){
2936 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK? ?MASK?");
2937 return TCL_ERROR;
2938 }else if( objc==2 ){
2939 if( pDb->zTraceV2 ){
2940 Tcl_AppendResult(interp, pDb->zTraceV2, (char*)0);
2941 }
2942 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002943 char *zTraceV2;
2944 int len;
mistachkinb52dcd82016-07-14 23:17:03 +00002945 Tcl_WideInt wMask = 0;
mistachkinb56660f2016-07-14 21:26:09 +00002946 if( objc==4 ){
mistachkinb52dcd82016-07-14 23:17:03 +00002947 static const char *TTYPE_strs[] = {
2948 "statement", "profile", "row", "close", 0
2949 };
2950 enum TTYPE_enum {
2951 TTYPE_STMT, TTYPE_PROFILE, TTYPE_ROW, TTYPE_CLOSE
2952 };
2953 int i;
2954 if( TCL_OK!=Tcl_ListObjLength(interp, objv[3], &len) ){
mistachkinb56660f2016-07-14 21:26:09 +00002955 return TCL_ERROR;
2956 }
mistachkinb52dcd82016-07-14 23:17:03 +00002957 for(i=0; i<len; i++){
2958 Tcl_Obj *pObj;
2959 int ttype;
2960 if( TCL_OK!=Tcl_ListObjIndex(interp, objv[3], i, &pObj) ){
2961 return TCL_ERROR;
2962 }
2963 if( Tcl_GetIndexFromObj(interp, pObj, TTYPE_strs, "trace type",
2964 0, &ttype)!=TCL_OK ){
2965 Tcl_WideInt wType;
2966 Tcl_Obj *pError = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
2967 Tcl_IncrRefCount(pError);
2968 if( TCL_OK==Tcl_GetWideIntFromObj(interp, pObj, &wType) ){
2969 Tcl_DecrRefCount(pError);
2970 wMask |= wType;
2971 }else{
2972 Tcl_SetObjResult(interp, pError);
2973 Tcl_DecrRefCount(pError);
2974 return TCL_ERROR;
2975 }
2976 }else{
2977 switch( (enum TTYPE_enum)ttype ){
2978 case TTYPE_STMT: wMask |= SQLITE_TRACE_STMT; break;
2979 case TTYPE_PROFILE: wMask |= SQLITE_TRACE_PROFILE; break;
2980 case TTYPE_ROW: wMask |= SQLITE_TRACE_ROW; break;
2981 case TTYPE_CLOSE: wMask |= SQLITE_TRACE_CLOSE; break;
2982 }
2983 }
2984 }
mistachkinb56660f2016-07-14 21:26:09 +00002985 }else{
mistachkinb52dcd82016-07-14 23:17:03 +00002986 wMask = SQLITE_TRACE_STMT; /* use the "legacy" default */
mistachkinb56660f2016-07-14 21:26:09 +00002987 }
2988 if( pDb->zTraceV2 ){
2989 Tcl_Free(pDb->zTraceV2);
2990 }
2991 zTraceV2 = Tcl_GetStringFromObj(objv[2], &len);
2992 if( zTraceV2 && len>0 ){
2993 pDb->zTraceV2 = Tcl_Alloc( len + 1 );
2994 memcpy(pDb->zTraceV2, zTraceV2, len+1);
2995 }else{
2996 pDb->zTraceV2 = 0;
2997 }
2998#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
2999 if( pDb->zTraceV2 ){
3000 pDb->interp = interp;
3001 sqlite3_trace_v2(pDb->db, (unsigned)wMask, DbTraceV2Handler, pDb);
3002 }else{
3003 sqlite3_trace_v2(pDb->db, 0, 0, 0);
3004 }
3005#endif
3006 }
3007 break;
3008 }
3009
drh3d214232005-08-02 12:21:08 +00003010 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
3011 **
3012 ** Start a new transaction (if we are not already in the midst of a
3013 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
3014 ** completes, either commit the transaction or roll it back if SCRIPT
3015 ** throws an exception. Or if no new transation was started, do nothing.
3016 ** pass the exception on up the stack.
3017 **
3018 ** This command was inspired by Dave Thomas's talk on Ruby at the
3019 ** 2005 O'Reilly Open Source Convention (OSCON).
3020 */
3021 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00003022 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00003023 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00003024 if( objc!=3 && objc!=4 ){
3025 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
3026 return TCL_ERROR;
3027 }
danielk1977cd38d522009-01-02 17:33:46 +00003028
dan4a4c11a2009-10-06 14:59:02 +00003029 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00003030 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00003031 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00003032 };
3033 enum TTYPE_enum {
3034 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
3035 };
3036 int ttype;
drhb5555e72005-08-02 17:15:14 +00003037 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00003038 0, &ttype) ){
3039 return TCL_ERROR;
3040 }
3041 switch( (enum TTYPE_enum)ttype ){
3042 case TTYPE_DEFERRED: /* no-op */; break;
3043 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
3044 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
3045 }
drh3d214232005-08-02 12:21:08 +00003046 }
danielk1977cd38d522009-01-02 17:33:46 +00003047 pScript = objv[objc-1];
3048
dan4a4c11a2009-10-06 14:59:02 +00003049 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00003050 pDb->disableAuth++;
3051 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
3052 pDb->disableAuth--;
3053 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00003054 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977cd38d522009-01-02 17:33:46 +00003055 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00003056 }
danielk1977cd38d522009-01-02 17:33:46 +00003057 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00003058
dan4a4c11a2009-10-06 14:59:02 +00003059 /* If using NRE, schedule a callback to invoke the script pScript, then
3060 ** a second callback to commit (or rollback) the transaction or savepoint
3061 ** opened above. If not using NRE, evaluate the script directly, then
mistachkinb56660f2016-07-14 21:26:09 +00003062 ** call function DbTransPostCmd() to commit (or rollback) the transaction
dan4a4c11a2009-10-06 14:59:02 +00003063 ** or savepoint. */
3064 if( DbUseNre() ){
3065 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
drha47941f2013-12-20 18:57:44 +00003066 (void)Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00003067 }else{
dan4a4c11a2009-10-06 14:59:02 +00003068 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00003069 }
3070 break;
3071 }
3072
danielk197794eb6a12005-12-15 15:22:08 +00003073 /*
danielk1977404ca072009-03-16 13:19:36 +00003074 ** $db unlock_notify ?script?
3075 */
3076 case DB_UNLOCK_NOTIFY: {
3077#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
drha198f2b2014-02-07 19:26:13 +00003078 Tcl_AppendResult(interp, "unlock_notify not available in this build",
3079 (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00003080 rc = TCL_ERROR;
3081#else
3082 if( objc!=2 && objc!=3 ){
3083 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3084 rc = TCL_ERROR;
3085 }else{
3086 void (*xNotify)(void **, int) = 0;
3087 void *pNotifyArg = 0;
3088
3089 if( pDb->pUnlockNotify ){
3090 Tcl_DecrRefCount(pDb->pUnlockNotify);
3091 pDb->pUnlockNotify = 0;
3092 }
mistachkinb56660f2016-07-14 21:26:09 +00003093
danielk1977404ca072009-03-16 13:19:36 +00003094 if( objc==3 ){
3095 xNotify = DbUnlockNotify;
3096 pNotifyArg = (void *)pDb;
3097 pDb->pUnlockNotify = objv[2];
3098 Tcl_IncrRefCount(pDb->pUnlockNotify);
3099 }
mistachkinb56660f2016-07-14 21:26:09 +00003100
danielk1977404ca072009-03-16 13:19:36 +00003101 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
drha198f2b2014-02-07 19:26:13 +00003102 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00003103 rc = TCL_ERROR;
3104 }
3105 }
3106#endif
3107 break;
3108 }
3109
drh304637c2011-03-18 16:47:27 +00003110 /*
3111 ** $db preupdate_hook count
3112 ** $db preupdate_hook hook ?SCRIPT?
3113 ** $db preupdate_hook new INDEX
3114 ** $db preupdate_hook old INDEX
3115 */
dan46c47d42011-03-01 18:42:07 +00003116 case DB_PREUPDATE: {
drh9b1c62d2011-03-30 21:04:43 +00003117#ifndef SQLITE_ENABLE_PREUPDATE_HOOK
3118 Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time");
3119 rc = TCL_ERROR;
3120#else
dan1e7a2d42011-03-22 18:45:29 +00003121 static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
dan46c47d42011-03-01 18:42:07 +00003122 enum DbPreupdateSubCmd {
dan1e7a2d42011-03-22 18:45:29 +00003123 PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
dan46c47d42011-03-01 18:42:07 +00003124 };
3125 int iSub;
3126
3127 if( objc<3 ){
3128 Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
3129 }
3130 if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
3131 return TCL_ERROR;
3132 }
3133
3134 switch( (enum DbPreupdateSubCmd)iSub ){
3135 case PRE_COUNT: {
3136 int nCol = sqlite3_preupdate_count(pDb->db);
3137 Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
3138 break;
3139 }
3140
3141 case PRE_HOOK: {
3142 if( objc>4 ){
3143 Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
3144 return TCL_ERROR;
3145 }
3146 DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
3147 break;
3148 }
3149
dan1e7a2d42011-03-22 18:45:29 +00003150 case PRE_DEPTH: {
3151 Tcl_Obj *pRet;
3152 if( objc!=3 ){
3153 Tcl_WrongNumArgs(interp, 3, objv, "");
3154 return TCL_ERROR;
3155 }
3156 pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
3157 Tcl_SetObjResult(interp, pRet);
3158 break;
3159 }
3160
dan37db03b2011-03-16 19:59:18 +00003161 case PRE_NEW:
dan46c47d42011-03-01 18:42:07 +00003162 case PRE_OLD: {
3163 int iIdx;
dan37db03b2011-03-16 19:59:18 +00003164 sqlite3_value *pValue;
dan46c47d42011-03-01 18:42:07 +00003165 if( objc!=4 ){
3166 Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
3167 return TCL_ERROR;
3168 }
3169 if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
3170 return TCL_ERROR;
3171 }
3172
dan37db03b2011-03-16 19:59:18 +00003173 if( iSub==PRE_OLD ){
dan46c47d42011-03-01 18:42:07 +00003174 rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
dan37db03b2011-03-16 19:59:18 +00003175 }else{
3176 assert( iSub==PRE_NEW );
3177 rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
dan46c47d42011-03-01 18:42:07 +00003178 }
3179
dan37db03b2011-03-16 19:59:18 +00003180 if( rc==SQLITE_OK ){
drh304637c2011-03-18 16:47:27 +00003181 Tcl_Obj *pObj;
3182 pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
dan37db03b2011-03-16 19:59:18 +00003183 Tcl_SetObjResult(interp, pObj);
3184 }else{
dan46c47d42011-03-01 18:42:07 +00003185 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
3186 return TCL_ERROR;
3187 }
3188 }
3189 }
drh9b1c62d2011-03-30 21:04:43 +00003190#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +00003191 break;
3192 }
3193
danielk1977404ca072009-03-16 13:19:36 +00003194 /*
drh833bf962010-04-28 14:42:19 +00003195 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003196 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00003197 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003198 */
mistachkinb56660f2016-07-14 21:26:09 +00003199 case DB_WAL_HOOK:
3200 case DB_UPDATE_HOOK:
dan6566ebe2011-03-16 09:49:14 +00003201 case DB_ROLLBACK_HOOK: {
mistachkinb56660f2016-07-14 21:26:09 +00003202 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
danielk197771fd80b2005-12-16 06:54:01 +00003203 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3204 */
mistachkinb56660f2016-07-14 21:26:09 +00003205 Tcl_Obj **ppHook = 0;
dan46c47d42011-03-01 18:42:07 +00003206 if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
3207 if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
3208 if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
3209 if( objc>3 ){
danielk197794eb6a12005-12-15 15:22:08 +00003210 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3211 return TCL_ERROR;
3212 }
danielk197771fd80b2005-12-16 06:54:01 +00003213
dan46c47d42011-03-01 18:42:07 +00003214 DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00003215 break;
3216 }
3217
danielk19774397de52005-01-12 12:44:03 +00003218 /* $db version
3219 **
3220 ** Return the version string for this database.
3221 */
3222 case DB_VERSION: {
3223 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
3224 break;
3225 }
3226
tpoindex1067fe12004-12-17 15:41:11 +00003227
drh6d313162000-09-21 13:01:35 +00003228 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00003229 return rc;
drh75897232000-05-29 14:26:00 +00003230}
3231
drha2c8a952009-10-13 18:38:34 +00003232#if SQLITE_TCL_NRE
3233/*
3234** Adaptor that provides an objCmd interface to the NRE-enabled
3235** interface implementation.
3236*/
3237static int DbObjCmdAdaptor(
3238 void *cd,
3239 Tcl_Interp *interp,
3240 int objc,
3241 Tcl_Obj *const*objv
3242){
3243 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
3244}
3245#endif /* SQLITE_TCL_NRE */
3246
drh75897232000-05-29 14:26:00 +00003247/*
drh3570ad92007-08-31 14:31:44 +00003248** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00003249** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00003250**
3251** This is the main Tcl command. When the "sqlite" Tcl command is
3252** invoked, this routine runs to process that command.
3253**
3254** The first argument, DBNAME, is an arbitrary name for a new
3255** database connection. This command creates a new command named
3256** DBNAME that is used to control that connection. The database
3257** connection is deleted when the DBNAME command is deleted.
3258**
drh3570ad92007-08-31 14:31:44 +00003259** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00003260**
drh75897232000-05-29 14:26:00 +00003261*/
drh22fbcb82004-02-01 01:22:50 +00003262static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00003263 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00003264 const char *zArg;
drh75897232000-05-29 14:26:00 +00003265 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00003266 int i;
drh22fbcb82004-02-01 01:22:50 +00003267 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00003268 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00003269 int flags;
drh882e8e42006-08-24 02:42:27 +00003270 Tcl_DString translatedFilename;
drh32f57d42016-03-16 01:03:10 +00003271#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00003272 void *pKey = 0;
3273 int nKey = 0;
3274#endif
mistachkin540ebf82012-09-10 07:29:29 +00003275 int rc;
drhd9da78a2009-03-24 15:08:09 +00003276
3277 /* In normal use, each TCL interpreter runs in a single thread. So
3278 ** by default, we can turn of mutexing on SQLite database connections.
3279 ** However, for testing purposes it is useful to have mutexes turned
3280 ** on. So, by default, mutexes default off. But if compiled with
3281 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3282 */
3283#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3284 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3285#else
3286 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3287#endif
3288
drh22fbcb82004-02-01 01:22:50 +00003289 if( objc==2 ){
3290 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00003291 if( strcmp(zArg,"-version")==0 ){
drha198f2b2014-02-07 19:26:13 +00003292 Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
drh647cb0e2002-11-04 19:32:25 +00003293 return TCL_OK;
3294 }
drh72bf6a32016-01-07 02:06:55 +00003295 if( strcmp(zArg,"-sourceid")==0 ){
3296 Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0);
3297 return TCL_OK;
3298 }
drh9eb9e262004-02-11 02:18:05 +00003299 if( strcmp(zArg,"-has-codec")==0 ){
drh32f57d42016-03-16 01:03:10 +00003300#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drha198f2b2014-02-07 19:26:13 +00003301 Tcl_AppendResult(interp,"1",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003302#else
drha198f2b2014-02-07 19:26:13 +00003303 Tcl_AppendResult(interp,"0",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003304#endif
3305 return TCL_OK;
3306 }
drhfbc3eab2001-04-06 16:13:42 +00003307 }
drh3570ad92007-08-31 14:31:44 +00003308 for(i=3; i+1<objc; i+=2){
3309 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00003310 if( strcmp(zArg,"-key")==0 ){
drh32f57d42016-03-16 01:03:10 +00003311#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh3570ad92007-08-31 14:31:44 +00003312 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
drhb07028f2011-10-14 21:49:18 +00003313#endif
drh3570ad92007-08-31 14:31:44 +00003314 }else if( strcmp(zArg, "-vfs")==0 ){
dan3c3dd7b2010-06-22 11:10:40 +00003315 zVfs = Tcl_GetString(objv[i+1]);
drh3570ad92007-08-31 14:31:44 +00003316 }else if( strcmp(zArg, "-readonly")==0 ){
3317 int b;
3318 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3319 if( b ){
drh33f4e022007-09-03 15:19:34 +00003320 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00003321 flags |= SQLITE_OPEN_READONLY;
3322 }else{
3323 flags &= ~SQLITE_OPEN_READONLY;
3324 flags |= SQLITE_OPEN_READWRITE;
3325 }
3326 }else if( strcmp(zArg, "-create")==0 ){
3327 int b;
3328 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00003329 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00003330 flags |= SQLITE_OPEN_CREATE;
3331 }else{
3332 flags &= ~SQLITE_OPEN_CREATE;
3333 }
danielk19779a6284c2008-07-10 17:52:49 +00003334 }else if( strcmp(zArg, "-nomutex")==0 ){
3335 int b;
3336 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3337 if( b ){
3338 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00003339 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00003340 }else{
3341 flags &= ~SQLITE_OPEN_NOMUTEX;
3342 }
danc431fd52011-06-27 16:55:50 +00003343 }else if( strcmp(zArg, "-fullmutex")==0 ){
drh039963a2008-09-03 00:43:15 +00003344 int b;
3345 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3346 if( b ){
3347 flags |= SQLITE_OPEN_FULLMUTEX;
3348 flags &= ~SQLITE_OPEN_NOMUTEX;
3349 }else{
3350 flags &= ~SQLITE_OPEN_FULLMUTEX;
3351 }
drhf12b3f62011-12-21 14:42:29 +00003352 }else if( strcmp(zArg, "-uri")==0 ){
3353 int b;
3354 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3355 if( b ){
3356 flags |= SQLITE_OPEN_URI;
3357 }else{
3358 flags &= ~SQLITE_OPEN_URI;
3359 }
drh3570ad92007-08-31 14:31:44 +00003360 }else{
3361 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3362 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00003363 }
3364 }
drh3570ad92007-08-31 14:31:44 +00003365 if( objc<3 || (objc&1)!=1 ){
mistachkinb56660f2016-07-14 21:26:09 +00003366 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00003367 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh68bd4aa2012-01-13 16:16:10 +00003368 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
drh32f57d42016-03-16 01:03:10 +00003369#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh3570ad92007-08-31 14:31:44 +00003370 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00003371#endif
3372 );
drh75897232000-05-29 14:26:00 +00003373 return TCL_ERROR;
3374 }
drh75897232000-05-29 14:26:00 +00003375 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003376 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00003377 if( p==0 ){
mistachkin6ef5e122014-01-24 17:03:55 +00003378 Tcl_SetResult(interp, (char *)"malloc failed", TCL_STATIC);
drhbec3f402000-08-04 13:49:02 +00003379 return TCL_ERROR;
3380 }
3381 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00003382 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00003383 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003384 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00003385 Tcl_DStringFree(&translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003386 if( p->db ){
3387 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3388 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3389 sqlite3_close(p->db);
3390 p->db = 0;
3391 }
3392 }else{
mistachkin5dac8432012-09-11 02:00:25 +00003393 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
danielk197780290862004-05-22 09:21:21 +00003394 }
drh32f57d42016-03-16 01:03:10 +00003395#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhf3a65f72007-08-22 20:18:21 +00003396 if( p->db ){
3397 sqlite3_key(p->db, pKey, nKey);
3398 }
drheb8ed702004-02-11 10:37:23 +00003399#endif
drhbec3f402000-08-04 13:49:02 +00003400 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003401 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003402 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003403 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003404 return TCL_ERROR;
3405 }
drhfb7e7652005-01-24 00:28:42 +00003406 p->maxStmt = NUM_PREPARED_STMTS;
drh147ef392016-01-22 23:17:51 +00003407 p->openFlags = flags & SQLITE_OPEN_URI;
drh5169bbc2006-08-24 14:59:45 +00003408 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003409 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003410 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003411 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3412 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003413 }else{
3414 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3415 }
drh75897232000-05-29 14:26:00 +00003416 return TCL_OK;
3417}
3418
3419/*
drh90ca9752001-09-28 17:47:14 +00003420** Provide a dummy Tcl_InitStubs if we are using this as a static
3421** library.
3422*/
3423#ifndef USE_TCL_STUBS
3424# undef Tcl_InitStubs
drh0e85ccf2013-06-03 12:34:46 +00003425# define Tcl_InitStubs(a,b,c) TCL_VERSION
drh90ca9752001-09-28 17:47:14 +00003426#endif
3427
3428/*
drh29bc4612005-10-05 10:40:15 +00003429** Make sure we have a PACKAGE_VERSION macro defined. This will be
3430** defined automatically by the TEA makefile. But other makefiles
3431** do not define it.
3432*/
3433#ifndef PACKAGE_VERSION
3434# define PACKAGE_VERSION SQLITE_VERSION
3435#endif
3436
3437/*
drh75897232000-05-29 14:26:00 +00003438** Initialize this module.
3439**
3440** This Tcl module contains only a single new Tcl command named "sqlite".
3441** (Hence there is no namespace. There is no point in using a namespace
3442** if the extension only supplies one new name!) The "sqlite" command is
3443** used to open a new SQLite database. See the DbMain() routine above
3444** for additional information.
drhb652f432010-08-26 16:46:57 +00003445**
3446** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003447*/
drhb652f432010-08-26 16:46:57 +00003448EXTERN int Sqlite3_Init(Tcl_Interp *interp){
mistachkin27b2f052015-01-12 19:49:46 +00003449 int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
drh6dc8cbe2013-05-31 15:36:07 +00003450 if( rc==TCL_OK ){
3451 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh1cca0d22010-08-25 20:35:51 +00003452#ifndef SQLITE_3_SUFFIX_ONLY
drh6dc8cbe2013-05-31 15:36:07 +00003453 /* The "sqlite" alias is undocumented. It is here only to support
3454 ** legacy scripts. All new scripts should use only the "sqlite3"
3455 ** command. */
3456 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003457#endif
drh6dc8cbe2013-05-31 15:36:07 +00003458 rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3459 }
3460 return rc;
drh90ca9752001-09-28 17:47:14 +00003461}
drhb652f432010-08-26 16:46:57 +00003462EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
drhb652f432010-08-26 16:46:57 +00003463EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3464EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00003465
drhd878cab2012-03-20 15:10:42 +00003466/* Because it accesses the file-system and uses persistent state, SQLite
drhe75a9eb2016-02-13 18:54:10 +00003467** is not considered appropriate for safe interpreters. Hence, we cause
3468** the _SafeInit() interfaces return TCL_ERROR.
drhd878cab2012-03-20 15:10:42 +00003469*/
drhe75a9eb2016-02-13 18:54:10 +00003470EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
3471EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
3472
3473
drh49766d62005-01-08 18:42:28 +00003474
3475#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003476int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3477int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
dana3e63c42010-08-20 12:33:59 +00003478int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3479int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00003480#endif
drh75897232000-05-29 14:26:00 +00003481
drh3e27c022004-07-23 00:01:38 +00003482#ifdef TCLSH
3483/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003484** All of the code that follows is used to build standalone TCL interpreters
3485** that are statically linked with SQLite. Enable these by compiling
3486** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3487** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3488** analysis program.
drh75897232000-05-29 14:26:00 +00003489*/
drh348784e2000-05-29 20:41:49 +00003490
drh57a02272009-10-22 20:52:05 +00003491#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3492/*
3493 * This code implements the MD5 message-digest algorithm.
3494 * The algorithm is due to Ron Rivest. This code was
3495 * written by Colin Plumb in 1993, no copyright is claimed.
3496 * This code is in the public domain; do with it what you wish.
3497 *
3498 * Equivalent code is available from RSA Data Security, Inc.
3499 * This code has been tested against that, and is equivalent,
3500 * except that you don't need to include two pages of legalese
3501 * with every copy.
3502 *
3503 * To compute the message digest of a chunk of bytes, declare an
3504 * MD5Context structure, pass it to MD5Init, call MD5Update as
3505 * needed on buffers full of bytes, and then call MD5Final, which
3506 * will fill a supplied 16-byte array with the digest.
3507 */
3508
3509/*
3510 * If compiled on a machine that doesn't have a 32-bit integer,
3511 * you just set "uint32" to the appropriate datatype for an
3512 * unsigned 32-bit integer. For example:
3513 *
3514 * cc -Duint32='unsigned long' md5.c
3515 *
3516 */
3517#ifndef uint32
3518# define uint32 unsigned int
3519#endif
3520
3521struct MD5Context {
3522 int isInit;
3523 uint32 buf[4];
3524 uint32 bits[2];
3525 unsigned char in[64];
3526};
3527typedef struct MD5Context MD5Context;
3528
3529/*
3530 * Note: this code is harmless on little-endian machines.
3531 */
3532static void byteReverse (unsigned char *buf, unsigned longs){
3533 uint32 t;
3534 do {
3535 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3536 ((unsigned)buf[1]<<8 | buf[0]);
3537 *(uint32 *)buf = t;
3538 buf += 4;
3539 } while (--longs);
3540}
3541/* The four core functions - F1 is optimized somewhat */
3542
3543/* #define F1(x, y, z) (x & y | ~x & z) */
3544#define F1(x, y, z) (z ^ (x & (y ^ z)))
3545#define F2(x, y, z) F1(z, x, y)
3546#define F3(x, y, z) (x ^ y ^ z)
3547#define F4(x, y, z) (y ^ (x | ~z))
3548
3549/* This is the central step in the MD5 algorithm. */
3550#define MD5STEP(f, w, x, y, z, data, s) \
3551 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3552
3553/*
3554 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3555 * reflect the addition of 16 longwords of new data. MD5Update blocks
3556 * the data and converts bytes into longwords for this routine.
3557 */
3558static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3559 register uint32 a, b, c, d;
3560
3561 a = buf[0];
3562 b = buf[1];
3563 c = buf[2];
3564 d = buf[3];
3565
3566 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3567 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3568 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3569 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3570 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3571 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3572 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3573 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3574 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3575 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3576 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3577 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3578 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3579 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3580 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3581 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3582
3583 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3584 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3585 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3586 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3587 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3588 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3589 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3590 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3591 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3592 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3593 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3594 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3595 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3596 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3597 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3598 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3599
3600 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3601 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3602 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3603 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3604 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3605 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3606 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3607 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3608 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3609 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3610 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3611 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3612 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3613 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3614 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3615 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3616
3617 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3618 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3619 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3620 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3621 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3622 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3623 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3624 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3625 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3626 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3627 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3628 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3629 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3630 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3631 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3632 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3633
3634 buf[0] += a;
3635 buf[1] += b;
3636 buf[2] += c;
3637 buf[3] += d;
3638}
3639
3640/*
3641 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3642 * initialization constants.
3643 */
3644static void MD5Init(MD5Context *ctx){
3645 ctx->isInit = 1;
3646 ctx->buf[0] = 0x67452301;
3647 ctx->buf[1] = 0xefcdab89;
3648 ctx->buf[2] = 0x98badcfe;
3649 ctx->buf[3] = 0x10325476;
3650 ctx->bits[0] = 0;
3651 ctx->bits[1] = 0;
3652}
3653
3654/*
3655 * Update context to reflect the concatenation of another buffer full
3656 * of bytes.
3657 */
mistachkinb56660f2016-07-14 21:26:09 +00003658static
drh57a02272009-10-22 20:52:05 +00003659void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3660 uint32 t;
3661
3662 /* Update bitcount */
3663
3664 t = ctx->bits[0];
3665 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3666 ctx->bits[1]++; /* Carry from low to high */
3667 ctx->bits[1] += len >> 29;
3668
3669 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3670
3671 /* Handle any leading odd-sized chunks */
3672
3673 if ( t ) {
3674 unsigned char *p = (unsigned char *)ctx->in + t;
3675
3676 t = 64-t;
3677 if (len < t) {
3678 memcpy(p, buf, len);
3679 return;
3680 }
3681 memcpy(p, buf, t);
3682 byteReverse(ctx->in, 16);
3683 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3684 buf += t;
3685 len -= t;
3686 }
3687
3688 /* Process data in 64-byte chunks */
3689
3690 while (len >= 64) {
3691 memcpy(ctx->in, buf, 64);
3692 byteReverse(ctx->in, 16);
3693 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3694 buf += 64;
3695 len -= 64;
3696 }
3697
3698 /* Handle any remaining bytes of data. */
3699
3700 memcpy(ctx->in, buf, len);
3701}
3702
3703/*
mistachkinb56660f2016-07-14 21:26:09 +00003704 * Final wrapup - pad to 64-byte boundary with the bit pattern
drh57a02272009-10-22 20:52:05 +00003705 * 1 0* (64-bit count of bits processed, MSB-first)
3706 */
3707static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3708 unsigned count;
3709 unsigned char *p;
3710
3711 /* Compute number of bytes mod 64 */
3712 count = (ctx->bits[0] >> 3) & 0x3F;
3713
3714 /* Set the first char of padding to 0x80. This is safe since there is
3715 always at least one byte free */
3716 p = ctx->in + count;
3717 *p++ = 0x80;
3718
3719 /* Bytes of padding needed to make 64 bytes */
3720 count = 64 - 1 - count;
3721
3722 /* Pad out to 56 mod 64 */
3723 if (count < 8) {
3724 /* Two lots of padding: Pad the first block to 64 bytes */
3725 memset(p, 0, count);
3726 byteReverse(ctx->in, 16);
3727 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3728
3729 /* Now fill the next block with 56 bytes */
3730 memset(ctx->in, 0, 56);
3731 } else {
3732 /* Pad block to 56 bytes */
3733 memset(p, 0, count-8);
3734 }
3735 byteReverse(ctx->in, 14);
3736
3737 /* Append length in bits and transform */
drha47941f2013-12-20 18:57:44 +00003738 memcpy(ctx->in + 14*4, ctx->bits, 8);
drh57a02272009-10-22 20:52:05 +00003739
3740 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3741 byteReverse((unsigned char *)ctx->buf, 4);
3742 memcpy(digest, ctx->buf, 16);
drh57a02272009-10-22 20:52:05 +00003743}
3744
3745/*
3746** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3747*/
3748static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3749 static char const zEncode[] = "0123456789abcdef";
3750 int i, j;
3751
3752 for(j=i=0; i<16; i++){
3753 int a = digest[i];
3754 zBuf[j++] = zEncode[(a>>4)&0xf];
3755 zBuf[j++] = zEncode[a & 0xf];
3756 }
3757 zBuf[j] = 0;
3758}
3759
3760
3761/*
3762** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3763** each representing 16 bits of the digest and separated from each
3764** other by a "-" character.
3765*/
3766static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3767 int i, j;
3768 unsigned int x;
3769 for(i=j=0; i<16; i+=2){
3770 x = digest[i]*256 + digest[i+1];
3771 if( i>0 ) zDigest[j++] = '-';
drh05f6c672015-02-26 16:32:33 +00003772 sqlite3_snprintf(50-j, &zDigest[j], "%05u", x);
drh57a02272009-10-22 20:52:05 +00003773 j += 5;
3774 }
3775 zDigest[j] = 0;
3776}
3777
3778/*
3779** A TCL command for md5. The argument is the text to be hashed. The
mistachkinb56660f2016-07-14 21:26:09 +00003780** Result is the hash in base64.
drh57a02272009-10-22 20:52:05 +00003781*/
3782static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3783 MD5Context ctx;
3784 unsigned char digest[16];
3785 char zBuf[50];
3786 void (*converter)(unsigned char*, char*);
3787
3788 if( argc!=2 ){
mistachkinb56660f2016-07-14 21:26:09 +00003789 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
drha198f2b2014-02-07 19:26:13 +00003790 " TEXT\"", (char*)0);
drh57a02272009-10-22 20:52:05 +00003791 return TCL_ERROR;
3792 }
3793 MD5Init(&ctx);
3794 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3795 MD5Final(digest, &ctx);
3796 converter = (void(*)(unsigned char*,char*))cd;
3797 converter(digest, zBuf);
3798 Tcl_AppendResult(interp, zBuf, (char*)0);
3799 return TCL_OK;
3800}
3801
3802/*
3803** A TCL command to take the md5 hash of a file. The argument is the
3804** name of the file.
3805*/
3806static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3807 FILE *in;
3808 MD5Context ctx;
3809 void (*converter)(unsigned char*, char*);
3810 unsigned char digest[16];
3811 char zBuf[10240];
3812
3813 if( argc!=2 ){
mistachkinb56660f2016-07-14 21:26:09 +00003814 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
drha198f2b2014-02-07 19:26:13 +00003815 " FILENAME\"", (char*)0);
drh57a02272009-10-22 20:52:05 +00003816 return TCL_ERROR;
3817 }
3818 in = fopen(argv[1],"rb");
3819 if( in==0 ){
mistachkinb56660f2016-07-14 21:26:09 +00003820 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
drha198f2b2014-02-07 19:26:13 +00003821 "\" for reading", (char*)0);
drh57a02272009-10-22 20:52:05 +00003822 return TCL_ERROR;
3823 }
3824 MD5Init(&ctx);
3825 for(;;){
3826 int n;
drh83cc1392012-04-19 18:04:28 +00003827 n = (int)fread(zBuf, 1, sizeof(zBuf), in);
drh57a02272009-10-22 20:52:05 +00003828 if( n<=0 ) break;
3829 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3830 }
3831 fclose(in);
3832 MD5Final(digest, &ctx);
3833 converter = (void(*)(unsigned char*,char*))cd;
3834 converter(digest, zBuf);
3835 Tcl_AppendResult(interp, zBuf, (char*)0);
3836 return TCL_OK;
3837}
3838
3839/*
3840** Register the four new TCL commands for generating MD5 checksums
3841** with the TCL interpreter.
3842*/
3843int Md5_Init(Tcl_Interp *interp){
3844 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3845 MD5DigestToBase16, 0);
3846 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3847 MD5DigestToBase10x8, 0);
3848 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3849 MD5DigestToBase16, 0);
3850 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3851 MD5DigestToBase10x8, 0);
3852 return TCL_OK;
3853}
3854#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3855
3856#if defined(SQLITE_TEST)
3857/*
3858** During testing, the special md5sum() aggregate function is available.
3859** inside SQLite. The following routines implement that function.
3860*/
3861static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3862 MD5Context *p;
3863 int i;
3864 if( argc<1 ) return;
3865 p = sqlite3_aggregate_context(context, sizeof(*p));
3866 if( p==0 ) return;
3867 if( !p->isInit ){
3868 MD5Init(p);
3869 }
3870 for(i=0; i<argc; i++){
3871 const char *zData = (char*)sqlite3_value_text(argv[i]);
3872 if( zData ){
drh83cc1392012-04-19 18:04:28 +00003873 MD5Update(p, (unsigned char*)zData, (int)strlen(zData));
drh57a02272009-10-22 20:52:05 +00003874 }
3875 }
3876}
3877static void md5finalize(sqlite3_context *context){
3878 MD5Context *p;
3879 unsigned char digest[16];
3880 char zBuf[33];
3881 p = sqlite3_aggregate_context(context, sizeof(*p));
3882 MD5Final(digest,p);
3883 MD5DigestToBase16(digest, zBuf);
3884 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3885}
3886int Md5_Register(sqlite3 *db){
mistachkinb56660f2016-07-14 21:26:09 +00003887 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
drh57a02272009-10-22 20:52:05 +00003888 md5step, md5finalize);
3889 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3890 return rc;
3891}
3892#endif /* defined(SQLITE_TEST) */
3893
3894
drh348784e2000-05-29 20:41:49 +00003895/*
drh3e27c022004-07-23 00:01:38 +00003896** If the macro TCLSH is one, then put in code this for the
3897** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003898** standard input, or if a file is named on the command line
3899** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003900*/
drh3e27c022004-07-23 00:01:38 +00003901#if TCLSH==1
dan0ae479d2011-09-21 16:43:07 +00003902static const char *tclsh_main_loop(void){
3903 static const char zMainloop[] =
3904 "set line {}\n"
3905 "while {![eof stdin]} {\n"
3906 "if {$line!=\"\"} {\n"
3907 "puts -nonewline \"> \"\n"
3908 "} else {\n"
3909 "puts -nonewline \"% \"\n"
drh348784e2000-05-29 20:41:49 +00003910 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003911 "flush stdout\n"
3912 "append line [gets stdin]\n"
3913 "if {[info complete $line]} {\n"
3914 "if {[catch {uplevel #0 $line} result]} {\n"
3915 "puts stderr \"Error: $result\"\n"
3916 "} elseif {$result!=\"\"} {\n"
3917 "puts $result\n"
3918 "}\n"
3919 "set line {}\n"
3920 "} else {\n"
3921 "append line \\n\n"
3922 "}\n"
drh348784e2000-05-29 20:41:49 +00003923 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003924 ;
3925 return zMainloop;
3926}
drh3e27c022004-07-23 00:01:38 +00003927#endif
drh3a0f13f2010-07-12 16:47:48 +00003928#if TCLSH==2
dan0ae479d2011-09-21 16:43:07 +00003929static const char *tclsh_main_loop(void);
drh3a0f13f2010-07-12 16:47:48 +00003930#endif
drh3e27c022004-07-23 00:01:38 +00003931
danc1a60c52010-06-07 14:28:16 +00003932#ifdef SQLITE_TEST
3933static void init_all(Tcl_Interp *);
3934static int init_all_cmd(
3935 ClientData cd,
3936 Tcl_Interp *interp,
3937 int objc,
3938 Tcl_Obj *CONST objv[]
3939){
danielk19770a549072009-02-17 16:29:10 +00003940
danc1a60c52010-06-07 14:28:16 +00003941 Tcl_Interp *slave;
3942 if( objc!=2 ){
3943 Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3944 return TCL_ERROR;
3945 }
3946
3947 slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3948 if( !slave ){
3949 return TCL_ERROR;
3950 }
3951
3952 init_all(slave);
3953 return TCL_OK;
3954}
danc431fd52011-06-27 16:55:50 +00003955
3956/*
3957** Tclcmd: db_use_legacy_prepare DB BOOLEAN
3958**
3959** The first argument to this command must be a database command created by
3960** [sqlite3]. If the second argument is true, then the handle is configured
3961** to use the sqlite3_prepare_v2() function to prepare statements. If it
3962** is false, sqlite3_prepare().
3963*/
3964static int db_use_legacy_prepare_cmd(
3965 ClientData cd,
3966 Tcl_Interp *interp,
3967 int objc,
3968 Tcl_Obj *CONST objv[]
3969){
3970 Tcl_CmdInfo cmdInfo;
3971 SqliteDb *pDb;
3972 int bPrepare;
3973
3974 if( objc!=3 ){
3975 Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
3976 return TCL_ERROR;
3977 }
3978
3979 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3980 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3981 return TCL_ERROR;
3982 }
3983 pDb = (SqliteDb*)cmdInfo.objClientData;
3984 if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
3985 return TCL_ERROR;
3986 }
3987
3988 pDb->bLegacyPrepare = bPrepare;
3989
3990 Tcl_ResetResult(interp);
3991 return TCL_OK;
3992}
dan04489b62014-10-31 20:11:32 +00003993
3994/*
3995** Tclcmd: db_last_stmt_ptr DB
3996**
3997** If the statement cache associated with database DB is not empty,
3998** return the text representation of the most recently used statement
3999** handle.
4000*/
4001static int db_last_stmt_ptr(
4002 ClientData cd,
4003 Tcl_Interp *interp,
4004 int objc,
4005 Tcl_Obj *CONST objv[]
4006){
4007 extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
4008 Tcl_CmdInfo cmdInfo;
4009 SqliteDb *pDb;
4010 sqlite3_stmt *pStmt = 0;
4011 char zBuf[100];
4012
4013 if( objc!=2 ){
4014 Tcl_WrongNumArgs(interp, 1, objv, "DB");
4015 return TCL_ERROR;
4016 }
4017
4018 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
4019 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
4020 return TCL_ERROR;
4021 }
4022 pDb = (SqliteDb*)cmdInfo.objClientData;
4023
4024 if( pDb->stmtList ) pStmt = pDb->stmtList->pStmt;
4025 if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ){
4026 return TCL_ERROR;
4027 }
4028 Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
4029
4030 return TCL_OK;
4031}
drh1a4a6802015-05-04 18:31:09 +00004032#endif /* SQLITE_TEST */
4033
danc1a60c52010-06-07 14:28:16 +00004034/*
4035** Configure the interpreter passed as the first argument to have access
4036** to the commands and linked variables that make up:
4037**
mistachkinb56660f2016-07-14 21:26:09 +00004038** * the [sqlite3] extension itself,
danc1a60c52010-06-07 14:28:16 +00004039**
4040** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
4041**
4042** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
4043** test suite.
4044*/
4045static void init_all(Tcl_Interp *interp){
drh38f82712004-06-18 17:10:16 +00004046 Sqlite3_Init(interp);
danc1a60c52010-06-07 14:28:16 +00004047
drh57a02272009-10-22 20:52:05 +00004048#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
4049 Md5_Init(interp);
4050#endif
danc1a60c52010-06-07 14:28:16 +00004051
drhd9b02572001-04-15 00:37:09 +00004052#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00004053 {
drh2f999a62007-08-15 19:16:43 +00004054 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00004055 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00004056 extern int Sqlitetest2_Init(Tcl_Interp*);
4057 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00004058 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00004059 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00004060 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00004061 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00004062 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00004063 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00004064 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00004065 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
danb391b942014-11-07 14:41:11 +00004066 extern int Sqlitetest_blob_Init(Tcl_Interp*);
dan0a7a9152010-04-07 07:57:38 +00004067 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
drh984bfaa2008-03-19 16:08:53 +00004068 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00004069 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00004070 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00004071 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00004072 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00004073 extern int Sqlitetestschema_Init(Tcl_Interp*);
4074 extern int Sqlitetestsse_Init(Tcl_Interp*);
4075 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
dan9f5ff372013-01-11 09:58:54 +00004076 extern int Sqlitetestfs_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00004077 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00004078 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00004079 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00004080 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh522efc62009-11-10 17:24:37 +00004081 extern int Sqlitetestintarray_Init(Tcl_Interp*);
danc7991bd2010-05-05 19:04:59 +00004082 extern int Sqlitetestvfs_Init(Tcl_Interp *);
dan9508daa2010-08-28 18:58:00 +00004083 extern int Sqlitetestrtree_Init(Tcl_Interp*);
dan8cf35eb2010-09-01 11:40:05 +00004084 extern int Sqlitequota_Init(Tcl_Interp*);
shaneh8a922f72010-11-04 20:50:27 +00004085 extern int Sqlitemultiplex_Init(Tcl_Interp*);
dane336b002010-11-19 18:20:09 +00004086 extern int SqliteSuperlock_Init(Tcl_Interp*);
dan213ca0a2011-03-28 19:10:06 +00004087 extern int SqlitetestSyscall_Init(Tcl_Interp*);
drh9b1c62d2011-03-30 21:04:43 +00004088#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
dan4fccf432011-03-08 19:22:50 +00004089 extern int TestSession_Init(Tcl_Interp*);
4090#endif
dan89a89562014-12-01 20:05:00 +00004091 extern int Fts5tcl_Init(Tcl_Interp *);
drhcfb8f8d2015-07-23 20:44:49 +00004092 extern int SqliteRbu_Init(Tcl_Interp*);
dan8e4251b2016-03-01 18:07:43 +00004093 extern int Sqlitetesttcl_Init(Tcl_Interp*);
dan6764a702011-06-20 11:15:06 +00004094#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00004095 extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
4096#endif
4097
danb29010c2010-12-29 18:24:38 +00004098#ifdef SQLITE_ENABLE_ZIPVFS
4099 extern int Zipvfs_Init(Tcl_Interp*);
4100 Zipvfs_Init(interp);
4101#endif
4102
drh2f999a62007-08-15 19:16:43 +00004103 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00004104 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00004105 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00004106 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00004107 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00004108 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00004109 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00004110 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00004111 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00004112 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00004113 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00004114 Sqlitetest_autoext_Init(interp);
danb391b942014-11-07 14:41:11 +00004115 Sqlitetest_blob_Init(interp);
dan0a7a9152010-04-07 07:57:38 +00004116 Sqlitetest_demovfs_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00004117 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00004118 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00004119 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00004120 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00004121 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00004122 Sqlitetestschema_Init(interp);
4123 Sqlitetesttclvar_Init(interp);
dan9f5ff372013-01-11 09:58:54 +00004124 Sqlitetestfs_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00004125 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00004126 SqlitetestOnefile_Init(interp);
danielk19775d1f5aa2008-04-10 14:51:00 +00004127 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00004128 Sqlitetestbackup_Init(interp);
drh522efc62009-11-10 17:24:37 +00004129 Sqlitetestintarray_Init(interp);
danc7991bd2010-05-05 19:04:59 +00004130 Sqlitetestvfs_Init(interp);
dan9508daa2010-08-28 18:58:00 +00004131 Sqlitetestrtree_Init(interp);
dan8cf35eb2010-09-01 11:40:05 +00004132 Sqlitequota_Init(interp);
shaneh8a922f72010-11-04 20:50:27 +00004133 Sqlitemultiplex_Init(interp);
dane336b002010-11-19 18:20:09 +00004134 SqliteSuperlock_Init(interp);
dan213ca0a2011-03-28 19:10:06 +00004135 SqlitetestSyscall_Init(interp);
drh9b1c62d2011-03-30 21:04:43 +00004136#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
dan4fccf432011-03-08 19:22:50 +00004137 TestSession_Init(interp);
4138#endif
dan89a89562014-12-01 20:05:00 +00004139 Fts5tcl_Init(interp);
drhcfb8f8d2015-07-23 20:44:49 +00004140 SqliteRbu_Init(interp);
dan8e4251b2016-03-01 18:07:43 +00004141 Sqlitetesttcl_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00004142
dan6764a702011-06-20 11:15:06 +00004143#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00004144 Sqlitetestfts3_Init(interp);
4145#endif
drh2e66f0b2005-04-28 17:18:48 +00004146
danc431fd52011-06-27 16:55:50 +00004147 Tcl_CreateObjCommand(
4148 interp, "load_testfixture_extensions", init_all_cmd, 0, 0
4149 );
4150 Tcl_CreateObjCommand(
4151 interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
4152 );
dan04489b62014-10-31 20:11:32 +00004153 Tcl_CreateObjCommand(
4154 interp, "db_last_stmt_ptr", db_last_stmt_ptr, 0, 0
4155 );
danc1a60c52010-06-07 14:28:16 +00004156
drh3e27c022004-07-23 00:01:38 +00004157#ifdef SQLITE_SSE
drh348784e2000-05-29 20:41:49 +00004158 Sqlitetestsse_Init(interp);
4159#endif
4160 }
drh61212b62004-12-02 20:17:00 +00004161#endif
danc1a60c52010-06-07 14:28:16 +00004162}
4163
drhdb6bafa2015-01-09 21:54:58 +00004164/* Needed for the setrlimit() system call on unix */
4165#if defined(unix)
4166#include <sys/resource.h>
4167#endif
4168
danc1a60c52010-06-07 14:28:16 +00004169#define TCLSH_MAIN main /* Needed to fake out mktclapp */
4170int TCLSH_MAIN(int argc, char **argv){
4171 Tcl_Interp *interp;
mistachkin1f28e072013-08-15 08:06:15 +00004172
4173#if !defined(_WIN32_WCE)
4174 if( getenv("BREAK") ){
4175 fprintf(stderr,
4176 "attach debugger to process %d and press any key to continue.\n",
4177 GETPID());
4178 fgetc(stdin);
4179 }
4180#endif
4181
drhdb6bafa2015-01-09 21:54:58 +00004182 /* Since the primary use case for this binary is testing of SQLite,
4183 ** be sure to generate core files if we crash */
4184#if defined(SQLITE_TEST) && defined(unix)
4185 { struct rlimit x;
4186 getrlimit(RLIMIT_CORE, &x);
4187 x.rlim_cur = x.rlim_max;
4188 setrlimit(RLIMIT_CORE, &x);
4189 }
4190#endif /* SQLITE_TEST && unix */
4191
4192
danc1a60c52010-06-07 14:28:16 +00004193 /* Call sqlite3_shutdown() once before doing anything else. This is to
4194 ** test that sqlite3_shutdown() can be safely called by a process before
4195 ** sqlite3_initialize() is. */
4196 sqlite3_shutdown();
4197
dan0ae479d2011-09-21 16:43:07 +00004198 Tcl_FindExecutable(argv[0]);
mistachkin2953ba92014-02-14 00:25:03 +00004199 Tcl_SetSystemEncoding(NULL, "utf-8");
dan0ae479d2011-09-21 16:43:07 +00004200 interp = Tcl_CreateInterp();
4201
drh3a0f13f2010-07-12 16:47:48 +00004202#if TCLSH==2
4203 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
4204#endif
danc1a60c52010-06-07 14:28:16 +00004205
danc1a60c52010-06-07 14:28:16 +00004206 init_all(interp);
drhc7285972009-11-10 01:13:25 +00004207 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00004208 int i;
shessad42c3a2006-08-22 23:53:46 +00004209 char zArgc[32];
4210 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
4211 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00004212 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
4213 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
4214 for(i=3-TCLSH; i<argc; i++){
4215 Tcl_SetVar(interp, "argv", argv[i],
4216 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
4217 }
drh3a0f13f2010-07-12 16:47:48 +00004218 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00004219 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00004220 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00004221 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00004222 return 1;
4223 }
drh3e27c022004-07-23 00:01:38 +00004224 }
drh3a0f13f2010-07-12 16:47:48 +00004225 if( TCLSH==2 || argc<=1 ){
dan0ae479d2011-09-21 16:43:07 +00004226 Tcl_GlobalEval(interp, tclsh_main_loop());
drh348784e2000-05-29 20:41:49 +00004227 }
4228 return 0;
4229}
4230#endif /* TCLSH */