blob: d26c62285913f7f8ea3787673013c7cdf7d9f4f9 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
drhbd08af42007-04-05 21:58:33 +000012** A TCL Interface to SQLite. Append this file to sqlite3.c and
13** compile the whole thing to build a TCL-enabled version of SQLite.
drh57a02272009-10-22 20:52:05 +000014**
15** Compile-time options:
16**
17** -DTCLSH=1 Add a "main()" routine that works as a tclsh.
18**
19** -DSQLITE_TCLMD5 When used in conjuction with -DTCLSH=1, add
20** four new commands to the TCL interpreter for
21** generating MD5 checksums: md5, md5file,
22** md5-10x8, and md5file-10x8.
23**
24** -DSQLITE_TEST When used in conjuction with -DTCLSH=1, add
25** hundreds of new commands used for testing
26** SQLite. This option implies -DSQLITE_TCLMD5.
drh75897232000-05-29 14:26:00 +000027*/
mistachkin27b2f052015-01-12 19:49:46 +000028
29/*
30** If requested, include the SQLite compiler options file for MSVC.
31*/
32#if defined(INCLUDE_MSVC_H)
mistachkin52b1dbb2016-07-28 14:37:04 +000033# include "msvc.h"
mistachkin27b2f052015-01-12 19:49:46 +000034#endif
35
mistachkin52b1dbb2016-07-28 14:37:04 +000036#if defined(INCLUDE_SQLITE_TCL_H)
37# include "sqlite_tcl.h"
38#else
39# include "tcl.h"
40#endif
danielk1977b4e9af92007-05-01 17:49:49 +000041#include <errno.h>
drhbd08af42007-04-05 21:58:33 +000042
43/*
44** Some additional include files are needed if this file is not
45** appended to the amalgamation.
46*/
47#ifndef SQLITE_AMALGAMATION
drh65e8c822009-12-01 13:57:48 +000048# include "sqlite3.h"
drhbd08af42007-04-05 21:58:33 +000049# include <stdlib.h>
50# include <string.h>
51# include <assert.h>
drh65e8c822009-12-01 13:57:48 +000052 typedef unsigned char u8;
drhbd08af42007-04-05 21:58:33 +000053#endif
drheb206382009-10-24 15:51:33 +000054#include <ctype.h>
drh75897232000-05-29 14:26:00 +000055
mistachkin1f28e072013-08-15 08:06:15 +000056/* Used to get the current process ID */
57#if !defined(_WIN32)
58# include <unistd.h>
59# define GETPID getpid
60#elif !defined(_WIN32_WCE)
61# ifndef SQLITE_AMALGAMATION
62# define WIN32_LEAN_AND_MEAN
63# include <windows.h>
64# endif
65# define GETPID (int)GetCurrentProcessId
66#endif
67
drhad6e1372006-07-10 21:15:51 +000068/*
69 * Windows needs to know which symbols to export. Unix does not.
70 * BUILD_sqlite should be undefined for Unix.
71 */
72#ifdef BUILD_sqlite
73#undef TCL_STORAGE_CLASS
74#define TCL_STORAGE_CLASS DLLEXPORT
75#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000076
danielk1977a21c6b62005-01-24 10:25:59 +000077#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000078#define MAX_PREPARED_STMTS 100
79
drhc45e6712012-10-03 11:02:33 +000080/* Forward declaration */
81typedef struct SqliteDb SqliteDb;
drh98808ba2001-10-18 12:34:46 +000082
83/*
drhcabb0812002-09-14 13:47:32 +000084** New SQL functions can be created as TCL scripts. Each such function
85** is described by an instance of the following structure.
86*/
87typedef struct SqlFunc SqlFunc;
88struct SqlFunc {
89 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000090 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
drhc45e6712012-10-03 11:02:33 +000091 SqliteDb *pDb; /* Database connection that owns this function */
drhd1e47332005-06-26 17:55:33 +000092 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
93 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000094 SqlFunc *pNext; /* Next function on the list of them all */
95};
96
97/*
danielk19770202b292004-06-09 09:55:16 +000098** New collation sequences function can be created as TCL scripts. Each such
99** function is described by an instance of the following structure.
100*/
101typedef struct SqlCollate SqlCollate;
102struct SqlCollate {
103 Tcl_Interp *interp; /* The TCL interpret to execute the function */
104 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +0000105 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +0000106};
107
108/*
drhfb7e7652005-01-24 00:28:42 +0000109** Prepared statements are cached for faster execution. Each prepared
110** statement is described by an instance of the following structure.
111*/
112typedef struct SqlPreparedStmt SqlPreparedStmt;
113struct SqlPreparedStmt {
114 SqlPreparedStmt *pNext; /* Next in linked list */
115 SqlPreparedStmt *pPrev; /* Previous on the list */
116 sqlite3_stmt *pStmt; /* The prepared statement */
117 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +0000118 const char *zSql; /* Text of the SQL statement */
dan4a4c11a2009-10-06 14:59:02 +0000119 int nParm; /* Size of apParm array */
120 Tcl_Obj **apParm; /* Array of referenced object pointers */
drhfb7e7652005-01-24 00:28:42 +0000121};
122
danielk1977d04417962007-05-02 13:16:30 +0000123typedef struct IncrblobChannel IncrblobChannel;
124
drhfb7e7652005-01-24 00:28:42 +0000125/*
drhbec3f402000-08-04 13:49:02 +0000126** There is one instance of this structure for each SQLite database
127** that has been opened by the SQLite TCL interface.
danc431fd52011-06-27 16:55:50 +0000128**
129** If this module is built with SQLITE_TEST defined (to create the SQLite
130** testfixture executable), then it may be configured to use either
131** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
132** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
drhbec3f402000-08-04 13:49:02 +0000133*/
drhbec3f402000-08-04 13:49:02 +0000134struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000135 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000136 Tcl_Interp *interp; /* The interpreter used for this database */
137 char *zBusy; /* The busy callback routine */
138 char *zCommit; /* The commit hook callback routine */
139 char *zTrace; /* The trace callback routine */
mistachkinb56660f2016-07-14 21:26:09 +0000140 char *zTraceV2; /* The trace_v2 callback routine */
drh19e2d372005-08-29 23:00:03 +0000141 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000142 char *zProgress; /* The progress callback routine */
143 char *zAuth; /* The authorization callback routine */
drh1f1549f2008-08-26 21:33:34 +0000144 int disableAuth; /* Disable the authorizer if it exists */
drhd1e47332005-06-26 17:55:33 +0000145 char *zNull; /* Text to substitute for an SQL NULL value */
146 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000147 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
dan46c47d42011-03-01 18:42:07 +0000148 Tcl_Obj *pPreUpdateHook; /* Pre-update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000149 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drh5def0842010-05-05 20:00:25 +0000150 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000151 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000152 SqlCollate *pCollate; /* List of SQL collation functions */
153 int rc; /* Return code of most recent sqlite3_exec() */
154 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000155 SqlPreparedStmt *stmtList; /* List of prepared statements*/
156 SqlPreparedStmt *stmtLast; /* Last statement in the list */
157 int maxStmt; /* The next maximum number of stmtList */
158 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000159 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh3c379b02010-04-07 19:31:59 +0000160 int nStep, nSort, nIndex; /* Statistics for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000161 int nTransaction; /* Number of nested [transaction] methods */
drh147ef392016-01-22 23:17:51 +0000162 int openFlags; /* Flags used to open. (SQLITE_OPEN_URI) */
danc431fd52011-06-27 16:55:50 +0000163#ifdef SQLITE_TEST
164 int bLegacyPrepare; /* True to use sqlite3_prepare() */
165#endif
drh98808ba2001-10-18 12:34:46 +0000166};
drh297ecf12001-04-05 15:57:13 +0000167
danielk1977b4e9af92007-05-01 17:49:49 +0000168struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000169 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000170 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000171 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000172 Tcl_Channel channel; /* Channel identifier */
173 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
174 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000175};
176
drhea678832008-12-10 19:26:22 +0000177/*
178** Compute a string length that is limited to what can be stored in
179** lower 30 bits of a 32-bit signed integer.
180*/
drh4f21c4a2008-12-10 22:15:00 +0000181static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000182 const char *z2 = z;
183 while( *z2 ){ z2++; }
184 return 0x3fffffff & (int)(z2 - z);
185}
drhea678832008-12-10 19:26:22 +0000186
187
danielk197732a0d8b2007-05-04 19:03:02 +0000188#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000189/*
danielk1977d04417962007-05-02 13:16:30 +0000190** Close all incrblob channels opened using database connection pDb.
191** This is called when shutting down the database connection.
192*/
193static void closeIncrblobChannels(SqliteDb *pDb){
194 IncrblobChannel *p;
195 IncrblobChannel *pNext;
196
197 for(p=pDb->pIncrblob; p; p=pNext){
198 pNext = p->pNext;
199
mistachkinb56660f2016-07-14 21:26:09 +0000200 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
danielk1977d04417962007-05-02 13:16:30 +0000201 ** which deletes the IncrblobChannel structure at *p. So do not
202 ** call Tcl_Free() here.
203 */
204 Tcl_UnregisterChannel(pDb->interp, p->channel);
205 }
206}
207
208/*
danielk1977b4e9af92007-05-01 17:49:49 +0000209** Close an incremental blob channel.
210*/
211static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
212 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000213 int rc = sqlite3_blob_close(p->pBlob);
214 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000215
216 /* Remove the channel from the SqliteDb.pIncrblob list. */
217 if( p->pNext ){
218 p->pNext->pPrev = p->pPrev;
219 }
220 if( p->pPrev ){
221 p->pPrev->pNext = p->pNext;
222 }
223 if( p->pDb->pIncrblob==p ){
224 p->pDb->pIncrblob = p->pNext;
225 }
226
danielk197792d4d7a2007-05-04 12:05:56 +0000227 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000228 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000229
230 if( rc!=SQLITE_OK ){
231 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
232 return TCL_ERROR;
233 }
danielk1977b4e9af92007-05-01 17:49:49 +0000234 return TCL_OK;
235}
236
237/*
238** Read data from an incremental blob channel.
239*/
240static int incrblobInput(
mistachkinb56660f2016-07-14 21:26:09 +0000241 ClientData instanceData,
242 char *buf,
danielk1977b4e9af92007-05-01 17:49:49 +0000243 int bufSize,
244 int *errorCodePtr
245){
246 IncrblobChannel *p = (IncrblobChannel *)instanceData;
247 int nRead = bufSize; /* Number of bytes to read */
248 int nBlob; /* Total size of the blob */
249 int rc; /* sqlite error code */
250
251 nBlob = sqlite3_blob_bytes(p->pBlob);
252 if( (p->iSeek+nRead)>nBlob ){
253 nRead = nBlob-p->iSeek;
254 }
255 if( nRead<=0 ){
256 return 0;
257 }
258
259 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
260 if( rc!=SQLITE_OK ){
261 *errorCodePtr = rc;
262 return -1;
263 }
264
265 p->iSeek += nRead;
266 return nRead;
267}
268
danielk1977d04417962007-05-02 13:16:30 +0000269/*
270** Write data to an incremental blob channel.
271*/
danielk1977b4e9af92007-05-01 17:49:49 +0000272static int incrblobOutput(
mistachkinb56660f2016-07-14 21:26:09 +0000273 ClientData instanceData,
274 CONST char *buf,
danielk1977b4e9af92007-05-01 17:49:49 +0000275 int toWrite,
276 int *errorCodePtr
277){
278 IncrblobChannel *p = (IncrblobChannel *)instanceData;
279 int nWrite = toWrite; /* Number of bytes to write */
280 int nBlob; /* Total size of the blob */
281 int rc; /* sqlite error code */
282
283 nBlob = sqlite3_blob_bytes(p->pBlob);
284 if( (p->iSeek+nWrite)>nBlob ){
285 *errorCodePtr = EINVAL;
286 return -1;
287 }
288 if( nWrite<=0 ){
289 return 0;
290 }
291
292 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
293 if( rc!=SQLITE_OK ){
294 *errorCodePtr = EIO;
295 return -1;
296 }
297
298 p->iSeek += nWrite;
299 return nWrite;
300}
301
302/*
303** Seek an incremental blob channel.
304*/
305static int incrblobSeek(
mistachkinb56660f2016-07-14 21:26:09 +0000306 ClientData instanceData,
danielk1977b4e9af92007-05-01 17:49:49 +0000307 long offset,
308 int seekMode,
309 int *errorCodePtr
310){
311 IncrblobChannel *p = (IncrblobChannel *)instanceData;
312
313 switch( seekMode ){
314 case SEEK_SET:
315 p->iSeek = offset;
316 break;
317 case SEEK_CUR:
318 p->iSeek += offset;
319 break;
320 case SEEK_END:
321 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
322 break;
323
324 default: assert(!"Bad seekMode");
325 }
326
327 return p->iSeek;
328}
329
330
mistachkinb56660f2016-07-14 21:26:09 +0000331static void incrblobWatch(ClientData instanceData, int mode){
332 /* NO-OP */
danielk1977b4e9af92007-05-01 17:49:49 +0000333}
334static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
335 return TCL_ERROR;
336}
337
338static Tcl_ChannelType IncrblobChannelType = {
339 "incrblob", /* typeName */
340 TCL_CHANNEL_VERSION_2, /* version */
341 incrblobClose, /* closeProc */
342 incrblobInput, /* inputProc */
343 incrblobOutput, /* outputProc */
344 incrblobSeek, /* seekProc */
345 0, /* setOptionProc */
346 0, /* getOptionProc */
347 incrblobWatch, /* watchProc (this is a no-op) */
348 incrblobHandle, /* getHandleProc (always returns error) */
349 0, /* close2Proc */
350 0, /* blockModeProc */
351 0, /* flushProc */
352 0, /* handlerProc */
353 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000354};
355
356/*
357** Create a new incrblob channel.
358*/
359static int createIncrblobChannel(
mistachkinb56660f2016-07-14 21:26:09 +0000360 Tcl_Interp *interp,
361 SqliteDb *pDb,
danielk1977b4e9af92007-05-01 17:49:49 +0000362 const char *zDb,
mistachkinb56660f2016-07-14 21:26:09 +0000363 const char *zTable,
364 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000365 sqlite_int64 iRow,
366 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000367){
368 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000369 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000370 sqlite3_blob *pBlob;
371 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000372 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000373
374 /* This variable is used to name the channels: "incrblob_[incr count]" */
375 static int count = 0;
376 char zChannel[64];
377
danielk19778cbadb02007-05-03 16:31:26 +0000378 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000379 if( rc!=SQLITE_OK ){
380 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
381 return TCL_ERROR;
382 }
383
384 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
385 p->iSeek = 0;
386 p->pBlob = pBlob;
387
drh5bb3eb92007-05-04 13:15:55 +0000388 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000389 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
390 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000391
danielk1977d04417962007-05-02 13:16:30 +0000392 /* Link the new channel into the SqliteDb.pIncrblob list. */
393 p->pNext = pDb->pIncrblob;
394 p->pPrev = 0;
395 if( p->pNext ){
396 p->pNext->pPrev = p;
397 }
398 pDb->pIncrblob = p;
399 p->pDb = pDb;
400
401 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000402 return TCL_OK;
403}
danielk197732a0d8b2007-05-04 19:03:02 +0000404#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
405 #define closeIncrblobChannels(pDb)
406#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000407
drh6d313162000-09-21 13:01:35 +0000408/*
drhd1e47332005-06-26 17:55:33 +0000409** Look at the script prefix in pCmd. We will be executing this script
410** after first appending one or more arguments. This routine analyzes
411** the script to see if it is safe to use Tcl_EvalObjv() on the script
412** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
413** faster.
414**
415** Scripts that are safe to use with Tcl_EvalObjv() consists of a
416** command name followed by zero or more arguments with no [...] or $
417** or {...} or ; to be seen anywhere. Most callback scripts consist
418** of just a single procedure name and they meet this requirement.
419*/
420static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
421 /* We could try to do something with Tcl_Parse(). But we will instead
422 ** just do a search for forbidden characters. If any of the forbidden
423 ** characters appear in pCmd, we will report the string as unsafe.
424 */
425 const char *z;
426 int n;
427 z = Tcl_GetStringFromObj(pCmd, &n);
428 while( n-- > 0 ){
429 int c = *(z++);
430 if( c=='$' || c=='[' || c==';' ) return 0;
431 }
432 return 1;
433}
434
435/*
436** Find an SqlFunc structure with the given name. Or create a new
437** one if an existing one cannot be found. Return a pointer to the
438** structure.
439*/
440static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
441 SqlFunc *p, *pNew;
drh0425f182013-11-26 16:48:04 +0000442 int nName = strlen30(zName);
443 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
drhd1e47332005-06-26 17:55:33 +0000444 pNew->zName = (char*)&pNew[1];
drh0425f182013-11-26 16:48:04 +0000445 memcpy(pNew->zName, zName, nName+1);
mistachkinb56660f2016-07-14 21:26:09 +0000446 for(p=pDb->pFunc; p; p=p->pNext){
drh0425f182013-11-26 16:48:04 +0000447 if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
drhd1e47332005-06-26 17:55:33 +0000448 Tcl_Free((char*)pNew);
449 return p;
450 }
451 }
452 pNew->interp = pDb->interp;
drhc45e6712012-10-03 11:02:33 +0000453 pNew->pDb = pDb;
drhd1e47332005-06-26 17:55:33 +0000454 pNew->pScript = 0;
455 pNew->pNext = pDb->pFunc;
456 pDb->pFunc = pNew;
457 return pNew;
458}
459
460/*
danc431fd52011-06-27 16:55:50 +0000461** Free a single SqlPreparedStmt object.
462*/
463static void dbFreeStmt(SqlPreparedStmt *pStmt){
464#ifdef SQLITE_TEST
465 if( sqlite3_sql(pStmt->pStmt)==0 ){
466 Tcl_Free((char *)pStmt->zSql);
467 }
468#endif
469 sqlite3_finalize(pStmt->pStmt);
470 Tcl_Free((char *)pStmt);
471}
472
473/*
drhfb7e7652005-01-24 00:28:42 +0000474** Finalize and free a list of prepared statements
475*/
danc431fd52011-06-27 16:55:50 +0000476static void flushStmtCache(SqliteDb *pDb){
drhfb7e7652005-01-24 00:28:42 +0000477 SqlPreparedStmt *pPreStmt;
danc431fd52011-06-27 16:55:50 +0000478 SqlPreparedStmt *pNext;
drhfb7e7652005-01-24 00:28:42 +0000479
danc431fd52011-06-27 16:55:50 +0000480 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
481 pNext = pPreStmt->pNext;
482 dbFreeStmt(pPreStmt);
drhfb7e7652005-01-24 00:28:42 +0000483 }
484 pDb->nStmt = 0;
485 pDb->stmtLast = 0;
danc431fd52011-06-27 16:55:50 +0000486 pDb->stmtList = 0;
drhfb7e7652005-01-24 00:28:42 +0000487}
488
489/*
drh895d7472004-08-20 16:02:39 +0000490** TCL calls this procedure when an sqlite3 database command is
491** deleted.
drh75897232000-05-29 14:26:00 +0000492*/
493static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000494 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000495 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000496 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000497 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000498 while( pDb->pFunc ){
499 SqlFunc *pFunc = pDb->pFunc;
500 pDb->pFunc = pFunc->pNext;
drhc45e6712012-10-03 11:02:33 +0000501 assert( pFunc->pDb==pDb );
drhd1e47332005-06-26 17:55:33 +0000502 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000503 Tcl_Free((char*)pFunc);
504 }
danielk19770202b292004-06-09 09:55:16 +0000505 while( pDb->pCollate ){
506 SqlCollate *pCollate = pDb->pCollate;
507 pDb->pCollate = pCollate->pNext;
508 Tcl_Free((char*)pCollate);
509 }
drhbec3f402000-08-04 13:49:02 +0000510 if( pDb->zBusy ){
511 Tcl_Free(pDb->zBusy);
512 }
drhb5a20d32003-04-23 12:25:23 +0000513 if( pDb->zTrace ){
514 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000515 }
mistachkinb56660f2016-07-14 21:26:09 +0000516 if( pDb->zTraceV2 ){
517 Tcl_Free(pDb->zTraceV2);
518 }
drh19e2d372005-08-29 23:00:03 +0000519 if( pDb->zProfile ){
520 Tcl_Free(pDb->zProfile);
521 }
drhe22a3342003-04-22 20:30:37 +0000522 if( pDb->zAuth ){
523 Tcl_Free(pDb->zAuth);
524 }
danielk197755c45f22005-04-03 23:54:43 +0000525 if( pDb->zNull ){
526 Tcl_Free(pDb->zNull);
527 }
danielk197794eb6a12005-12-15 15:22:08 +0000528 if( pDb->pUpdateHook ){
529 Tcl_DecrRefCount(pDb->pUpdateHook);
530 }
dan46c47d42011-03-01 18:42:07 +0000531 if( pDb->pPreUpdateHook ){
532 Tcl_DecrRefCount(pDb->pPreUpdateHook);
533 }
danielk197771fd80b2005-12-16 06:54:01 +0000534 if( pDb->pRollbackHook ){
535 Tcl_DecrRefCount(pDb->pRollbackHook);
536 }
drh5def0842010-05-05 20:00:25 +0000537 if( pDb->pWalHook ){
538 Tcl_DecrRefCount(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000539 }
danielk197794eb6a12005-12-15 15:22:08 +0000540 if( pDb->pCollateNeeded ){
541 Tcl_DecrRefCount(pDb->pCollateNeeded);
542 }
drhbec3f402000-08-04 13:49:02 +0000543 Tcl_Free((char*)pDb);
544}
545
546/*
547** This routine is called when a database file is locked while trying
548** to execute SQL.
549*/
danielk19772a764eb2004-06-12 01:43:26 +0000550static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000551 SqliteDb *pDb = (SqliteDb*)cd;
552 int rc;
553 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000554
drh5bb3eb92007-05-04 13:15:55 +0000555 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000556 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000557 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
558 return 0;
559 }
560 return 1;
drh75897232000-05-29 14:26:00 +0000561}
562
drh26e4a8b2008-05-01 17:16:52 +0000563#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000564/*
danielk1977348bb5d2003-10-18 09:37:26 +0000565** This routine is invoked as the 'progress callback' for the database.
566*/
567static int DbProgressHandler(void *cd){
568 SqliteDb *pDb = (SqliteDb*)cd;
569 int rc;
570
571 assert( pDb->zProgress );
572 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
573 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
574 return 1;
575 }
576 return 0;
577}
drh26e4a8b2008-05-01 17:16:52 +0000578#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000579
drhd1167392006-01-23 13:00:35 +0000580#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000581/*
drhb5a20d32003-04-23 12:25:23 +0000582** This routine is called by the SQLite trace handler whenever a new
583** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000584*/
drhb5a20d32003-04-23 12:25:23 +0000585static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000586 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000587 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000588
drhb5a20d32003-04-23 12:25:23 +0000589 Tcl_DStringInit(&str);
590 Tcl_DStringAppend(&str, pDb->zTrace, -1);
591 Tcl_DStringAppendElement(&str, zSql);
592 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
593 Tcl_DStringFree(&str);
594 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000595}
drhd1167392006-01-23 13:00:35 +0000596#endif
drh0d1a6432003-04-03 15:46:04 +0000597
drhd1167392006-01-23 13:00:35 +0000598#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000599/*
mistachkinb56660f2016-07-14 21:26:09 +0000600** This routine is called by the SQLite trace_v2 handler whenever a new
601** supported event is generated. Unsupported event types are ignored.
602** The TCL script in pDb->zTraceV2 is executed, with the arguments for
603** the event appended to it (as list elements).
604*/
605static int DbTraceV2Handler(
606 unsigned type, /* One of the SQLITE_TRACE_* event types. */
607 void *cd, /* The original context data pointer. */
608 void *pd, /* Primary event data, depends on event type. */
609 void *xd /* Extra event data, depends on event type. */
610){
611 SqliteDb *pDb = (SqliteDb*)cd;
612 Tcl_Obj *pCmd;
613
614 switch( type ){
615 case SQLITE_TRACE_STMT: {
616 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
617 char *zSql = (char *)xd;
618
619 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
620 Tcl_IncrRefCount(pCmd);
621 Tcl_ListObjAppendElement(pDb->interp, pCmd,
622 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
623 Tcl_ListObjAppendElement(pDb->interp, pCmd,
624 Tcl_NewStringObj(zSql, -1));
625 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
626 Tcl_DecrRefCount(pCmd);
627 Tcl_ResetResult(pDb->interp);
628 break;
629 }
630 case SQLITE_TRACE_PROFILE: {
631 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
632 sqlite3_int64 ns = (sqlite3_int64)xd;
633
634 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
635 Tcl_IncrRefCount(pCmd);
636 Tcl_ListObjAppendElement(pDb->interp, pCmd,
637 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
638 Tcl_ListObjAppendElement(pDb->interp, pCmd,
639 Tcl_NewWideIntObj((Tcl_WideInt)ns));
640 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
641 Tcl_DecrRefCount(pCmd);
642 Tcl_ResetResult(pDb->interp);
643 break;
644 }
645 case SQLITE_TRACE_ROW: {
646 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
647
648 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
649 Tcl_IncrRefCount(pCmd);
650 Tcl_ListObjAppendElement(pDb->interp, pCmd,
651 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
652 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
653 Tcl_DecrRefCount(pCmd);
654 Tcl_ResetResult(pDb->interp);
655 break;
656 }
657 case SQLITE_TRACE_CLOSE: {
658 sqlite3 *db = (sqlite3 *)pd;
659
660 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
661 Tcl_IncrRefCount(pCmd);
662 Tcl_ListObjAppendElement(pDb->interp, pCmd,
663 Tcl_NewWideIntObj((Tcl_WideInt)db));
664 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
665 Tcl_DecrRefCount(pCmd);
666 Tcl_ResetResult(pDb->interp);
667 break;
668 }
669 }
670 return SQLITE_OK;
671}
672#endif
673
674#ifndef SQLITE_OMIT_TRACE
675/*
drh19e2d372005-08-29 23:00:03 +0000676** This routine is called by the SQLite profile handler after a statement
677** SQL has executed. The TCL script in pDb->zProfile is evaluated.
678*/
679static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
680 SqliteDb *pDb = (SqliteDb*)cd;
681 Tcl_DString str;
682 char zTm[100];
683
684 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
685 Tcl_DStringInit(&str);
686 Tcl_DStringAppend(&str, pDb->zProfile, -1);
687 Tcl_DStringAppendElement(&str, zSql);
688 Tcl_DStringAppendElement(&str, zTm);
689 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
690 Tcl_DStringFree(&str);
691 Tcl_ResetResult(pDb->interp);
692}
drhd1167392006-01-23 13:00:35 +0000693#endif
drh19e2d372005-08-29 23:00:03 +0000694
695/*
drhaa940ea2004-01-15 02:44:03 +0000696** This routine is called when a transaction is committed. The
697** TCL script in pDb->zCommit is executed. If it returns non-zero or
698** if it throws an exception, the transaction is rolled back instead
699** of being committed.
700*/
701static int DbCommitHandler(void *cd){
702 SqliteDb *pDb = (SqliteDb*)cd;
703 int rc;
704
705 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
706 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
707 return 1;
708 }
709 return 0;
710}
711
danielk197771fd80b2005-12-16 06:54:01 +0000712static void DbRollbackHandler(void *clientData){
713 SqliteDb *pDb = (SqliteDb*)clientData;
714 assert(pDb->pRollbackHook);
715 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
716 Tcl_BackgroundError(pDb->interp);
717 }
718}
719
drh5def0842010-05-05 20:00:25 +0000720/*
721** This procedure handles wal_hook callbacks.
722*/
723static int DbWalHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000724 void *clientData,
725 sqlite3 *db,
726 const char *zDb,
dan8d22a172010-04-19 18:03:51 +0000727 int nEntry
728){
drh5def0842010-05-05 20:00:25 +0000729 int ret = SQLITE_OK;
dan8d22a172010-04-19 18:03:51 +0000730 Tcl_Obj *p;
731 SqliteDb *pDb = (SqliteDb*)clientData;
732 Tcl_Interp *interp = pDb->interp;
drh5def0842010-05-05 20:00:25 +0000733 assert(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000734
dan6e45e0c2014-12-10 20:29:49 +0000735 assert( db==pDb->db );
drh5def0842010-05-05 20:00:25 +0000736 p = Tcl_DuplicateObj(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000737 Tcl_IncrRefCount(p);
738 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
739 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
mistachkinb56660f2016-07-14 21:26:09 +0000740 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
dan8d22a172010-04-19 18:03:51 +0000741 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
742 ){
743 Tcl_BackgroundError(interp);
744 }
745 Tcl_DecrRefCount(p);
746
747 return ret;
748}
749
drhbcf4f482009-03-27 12:44:35 +0000750#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000751static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
752 char zBuf[64];
drh65545b52015-01-19 00:35:53 +0000753 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
danielk1977404ca072009-03-16 13:19:36 +0000754 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
drh65545b52015-01-19 00:35:53 +0000755 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
danielk1977404ca072009-03-16 13:19:36 +0000756 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
757}
758#else
drhbcf4f482009-03-27 12:44:35 +0000759# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000760#endif
761
drh69910da2009-03-27 12:32:54 +0000762#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000763static void DbUnlockNotify(void **apArg, int nArg){
764 int i;
765 for(i=0; i<nArg; i++){
766 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
767 SqliteDb *pDb = (SqliteDb *)apArg[i];
768 setTestUnlockNotifyVars(pDb->interp, i, nArg);
769 assert( pDb->pUnlockNotify);
770 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
771 Tcl_DecrRefCount(pDb->pUnlockNotify);
772 pDb->pUnlockNotify = 0;
773 }
774}
drh69910da2009-03-27 12:32:54 +0000775#endif
danielk1977404ca072009-03-16 13:19:36 +0000776
drh9b1c62d2011-03-30 21:04:43 +0000777#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +0000778/*
779** Pre-update hook callback.
780*/
781static void DbPreUpdateHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000782 void *p,
dan46c47d42011-03-01 18:42:07 +0000783 sqlite3 *db,
784 int op,
mistachkinb56660f2016-07-14 21:26:09 +0000785 const char *zDb,
786 const char *zTbl,
dan46c47d42011-03-01 18:42:07 +0000787 sqlite_int64 iKey1,
788 sqlite_int64 iKey2
789){
790 SqliteDb *pDb = (SqliteDb *)p;
791 Tcl_Obj *pCmd;
792 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
793
794 assert( (SQLITE_DELETE-1)/9 == 0 );
795 assert( (SQLITE_INSERT-1)/9 == 1 );
796 assert( (SQLITE_UPDATE-1)/9 == 2 );
797 assert( pDb->pPreUpdateHook );
798 assert( db==pDb->db );
799 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
800
801 pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
802 Tcl_IncrRefCount(pCmd);
803 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
804 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
805 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
806 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
807 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
808 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
809 Tcl_DecrRefCount(pCmd);
810}
drh9b1c62d2011-03-30 21:04:43 +0000811#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +0000812
danielk197794eb6a12005-12-15 15:22:08 +0000813static void DbUpdateHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000814 void *p,
danielk197794eb6a12005-12-15 15:22:08 +0000815 int op,
mistachkinb56660f2016-07-14 21:26:09 +0000816 const char *zDb,
817 const char *zTbl,
danielk197794eb6a12005-12-15 15:22:08 +0000818 sqlite_int64 rowid
819){
820 SqliteDb *pDb = (SqliteDb *)p;
821 Tcl_Obj *pCmd;
dan46c47d42011-03-01 18:42:07 +0000822 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
823
824 assert( (SQLITE_DELETE-1)/9 == 0 );
825 assert( (SQLITE_INSERT-1)/9 == 1 );
826 assert( (SQLITE_UPDATE-1)/9 == 2 );
danielk197794eb6a12005-12-15 15:22:08 +0000827
828 assert( pDb->pUpdateHook );
829 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
830
831 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
832 Tcl_IncrRefCount(pCmd);
dan46c47d42011-03-01 18:42:07 +0000833 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
danielk197794eb6a12005-12-15 15:22:08 +0000834 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
835 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
836 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
837 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
drhefdde162010-10-27 15:36:21 +0000838 Tcl_DecrRefCount(pCmd);
danielk197794eb6a12005-12-15 15:22:08 +0000839}
840
danielk19777cedc8d2004-06-10 10:50:08 +0000841static void tclCollateNeeded(
842 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000843 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000844 int enc,
845 const char *zName
846){
847 SqliteDb *pDb = (SqliteDb *)pCtx;
848 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
849 Tcl_IncrRefCount(pScript);
850 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
851 Tcl_EvalObjEx(pDb->interp, pScript, 0);
852 Tcl_DecrRefCount(pScript);
853}
854
drhaa940ea2004-01-15 02:44:03 +0000855/*
danielk19770202b292004-06-09 09:55:16 +0000856** This routine is called to evaluate an SQL collation function implemented
857** using TCL script.
858*/
859static int tclSqlCollate(
860 void *pCtx,
861 int nA,
862 const void *zA,
863 int nB,
864 const void *zB
865){
866 SqlCollate *p = (SqlCollate *)pCtx;
867 Tcl_Obj *pCmd;
868
869 pCmd = Tcl_NewStringObj(p->zScript, -1);
870 Tcl_IncrRefCount(pCmd);
871 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
872 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000873 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000874 Tcl_DecrRefCount(pCmd);
875 return (atoi(Tcl_GetStringResult(p->interp)));
876}
877
878/*
drhcabb0812002-09-14 13:47:32 +0000879** This routine is called to evaluate an SQL function implemented
880** using TCL script.
881*/
drhfb7e7652005-01-24 00:28:42 +0000882static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000883 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000884 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000885 int i;
886 int rc;
887
drhd1e47332005-06-26 17:55:33 +0000888 if( argc==0 ){
889 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
890 ** script object directly. This allows the TCL compiler to generate
891 ** bytecode for the command on the first invocation and thus make
892 ** subsequent invocations much faster. */
893 pCmd = p->pScript;
894 Tcl_IncrRefCount(pCmd);
895 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
896 Tcl_DecrRefCount(pCmd);
897 }else{
898 /* If there are arguments to the function, make a shallow copy of the
899 ** script object, lappend the arguments, then evaluate the copy.
900 **
peter.d.reid60ec9142014-09-06 16:39:46 +0000901 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
mistachkinb56660f2016-07-14 21:26:09 +0000902 ** The new Tcl_Obj contains pointers to the original list elements.
drhd1e47332005-06-26 17:55:33 +0000903 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
904 ** of the list to tclCmdNameType, that alternate representation will
905 ** be preserved and reused on the next invocation.
906 */
907 Tcl_Obj **aArg;
908 int nArg;
909 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
mistachkinb56660f2016-07-14 21:26:09 +0000910 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhd1e47332005-06-26 17:55:33 +0000911 return;
mistachkinb56660f2016-07-14 21:26:09 +0000912 }
drhd1e47332005-06-26 17:55:33 +0000913 pCmd = Tcl_NewListObj(nArg, aArg);
914 Tcl_IncrRefCount(pCmd);
915 for(i=0; i<argc; i++){
916 sqlite3_value *pIn = argv[i];
917 Tcl_Obj *pVal;
mistachkinb56660f2016-07-14 21:26:09 +0000918
drhd1e47332005-06-26 17:55:33 +0000919 /* Set pVal to contain the i'th column of this row. */
920 switch( sqlite3_value_type(pIn) ){
921 case SQLITE_BLOB: {
922 int bytes = sqlite3_value_bytes(pIn);
923 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
924 break;
925 }
926 case SQLITE_INTEGER: {
927 sqlite_int64 v = sqlite3_value_int64(pIn);
928 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +0000929 pVal = Tcl_NewIntObj((int)v);
drhd1e47332005-06-26 17:55:33 +0000930 }else{
931 pVal = Tcl_NewWideIntObj(v);
932 }
933 break;
934 }
935 case SQLITE_FLOAT: {
936 double r = sqlite3_value_double(pIn);
937 pVal = Tcl_NewDoubleObj(r);
938 break;
939 }
940 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +0000941 pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
drhd1e47332005-06-26 17:55:33 +0000942 break;
943 }
944 default: {
945 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000946 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000947 break;
948 }
949 }
950 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
951 if( rc ){
952 Tcl_DecrRefCount(pCmd);
mistachkinb56660f2016-07-14 21:26:09 +0000953 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhd1e47332005-06-26 17:55:33 +0000954 return;
955 }
danielk197751ad0ec2004-05-24 12:39:02 +0000956 }
drhd1e47332005-06-26 17:55:33 +0000957 if( !p->useEvalObjv ){
958 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
959 ** is a list without a string representation. To prevent this from
960 ** happening, make sure pCmd has a valid string representation */
961 Tcl_GetString(pCmd);
962 }
963 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
964 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000965 }
danielk1977562e8d32005-05-20 09:40:55 +0000966
drhc7f269d2005-05-05 10:30:29 +0000967 if( rc && rc!=TCL_RETURN ){
mistachkinb56660f2016-07-14 21:26:09 +0000968 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000969 }else{
drhc7f269d2005-05-05 10:30:29 +0000970 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
971 int n;
972 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000973 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000974 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000975 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000976 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000977 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000978 data = Tcl_GetByteArrayFromObj(pVar, &n);
979 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000980 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000981 Tcl_GetIntFromObj(0, pVar, &n);
982 sqlite3_result_int(context, n);
983 }else if( c=='d' && strcmp(zType,"double")==0 ){
984 double r;
985 Tcl_GetDoubleFromObj(0, pVar, &r);
986 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +0000987 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
988 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000989 Tcl_WideInt v;
990 Tcl_GetWideIntFromObj(0, pVar, &v);
991 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000992 }else{
danielk197700fd9572005-12-07 06:27:43 +0000993 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
994 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000995 }
drhcabb0812002-09-14 13:47:32 +0000996 }
997}
drh895d7472004-08-20 16:02:39 +0000998
drhe22a3342003-04-22 20:30:37 +0000999#ifndef SQLITE_OMIT_AUTHORIZATION
1000/*
1001** This is the authentication function. It appends the authentication
1002** type code and the two arguments to zCmd[] then invokes the result
1003** on the interpreter. The reply is examined to determine if the
1004** authentication fails or succeeds.
1005*/
1006static int auth_callback(
1007 void *pArg,
1008 int code,
1009 const char *zArg1,
1010 const char *zArg2,
1011 const char *zArg3,
1012 const char *zArg4
drh32c6a482014-09-11 13:44:52 +00001013#ifdef SQLITE_USER_AUTHENTICATION
1014 ,const char *zArg5
1015#endif
drhe22a3342003-04-22 20:30:37 +00001016){
mistachkin6ef5e122014-01-24 17:03:55 +00001017 const char *zCode;
drhe22a3342003-04-22 20:30:37 +00001018 Tcl_DString str;
1019 int rc;
1020 const char *zReply;
1021 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +00001022 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +00001023
1024 switch( code ){
1025 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
1026 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
1027 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
1028 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
1029 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
1030 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
1031 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
1032 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
1033 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
1034 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
1035 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
1036 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
1037 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
1038 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
1039 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
1040 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
1041 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
1042 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
1043 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
1044 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
1045 case SQLITE_READ : zCode="SQLITE_READ"; break;
1046 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
1047 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
1048 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +00001049 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
1050 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +00001051 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +00001052 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +00001053 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +00001054 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
1055 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +00001056 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +00001057 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drh65a2aaa2014-01-16 22:40:02 +00001058 case SQLITE_RECURSIVE : zCode="SQLITE_RECURSIVE"; break;
drhe22a3342003-04-22 20:30:37 +00001059 default : zCode="????"; break;
1060 }
1061 Tcl_DStringInit(&str);
1062 Tcl_DStringAppend(&str, pDb->zAuth, -1);
1063 Tcl_DStringAppendElement(&str, zCode);
1064 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
1065 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
1066 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
1067 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
drh32c6a482014-09-11 13:44:52 +00001068#ifdef SQLITE_USER_AUTHENTICATION
1069 Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
mistachkinb56660f2016-07-14 21:26:09 +00001070#endif
drhe22a3342003-04-22 20:30:37 +00001071 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
1072 Tcl_DStringFree(&str);
drhb07028f2011-10-14 21:49:18 +00001073 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
drhe22a3342003-04-22 20:30:37 +00001074 if( strcmp(zReply,"SQLITE_OK")==0 ){
1075 rc = SQLITE_OK;
1076 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
1077 rc = SQLITE_DENY;
1078 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
1079 rc = SQLITE_IGNORE;
1080 }else{
1081 rc = 999;
1082 }
1083 return rc;
1084}
1085#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +00001086
1087/*
tpoindex1067fe12004-12-17 15:41:11 +00001088** This routine reads a line of text from FILE in, stores
1089** the text in memory obtained from malloc() and returns a pointer
1090** to the text. NULL is returned at end of file, or if malloc()
1091** fails.
1092**
1093** The interface is like "readline" but no command-line editing
1094** is done.
1095**
1096** copied from shell.c from '.import' command
1097*/
1098static char *local_getline(char *zPrompt, FILE *in){
1099 char *zLine;
1100 int nLine;
1101 int n;
tpoindex1067fe12004-12-17 15:41:11 +00001102
1103 nLine = 100;
1104 zLine = malloc( nLine );
1105 if( zLine==0 ) return 0;
1106 n = 0;
drhb07028f2011-10-14 21:49:18 +00001107 while( 1 ){
tpoindex1067fe12004-12-17 15:41:11 +00001108 if( n+100>nLine ){
1109 nLine = nLine*2 + 100;
1110 zLine = realloc(zLine, nLine);
1111 if( zLine==0 ) return 0;
1112 }
1113 if( fgets(&zLine[n], nLine - n, in)==0 ){
1114 if( n==0 ){
1115 free(zLine);
1116 return 0;
1117 }
1118 zLine[n] = 0;
tpoindex1067fe12004-12-17 15:41:11 +00001119 break;
1120 }
1121 while( zLine[n] ){ n++; }
1122 if( n>0 && zLine[n-1]=='\n' ){
1123 n--;
1124 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +00001125 break;
tpoindex1067fe12004-12-17 15:41:11 +00001126 }
1127 }
1128 zLine = realloc( zLine, n+1 );
1129 return zLine;
1130}
1131
danielk19778e556522007-11-13 10:30:24 +00001132
1133/*
dan4a4c11a2009-10-06 14:59:02 +00001134** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +00001135**
dan4a4c11a2009-10-06 14:59:02 +00001136** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +00001137**
dan4a4c11a2009-10-06 14:59:02 +00001138** It is invoked after evaluating the script SCRIPT to commit or rollback
1139** the transaction or savepoint opened by the [transaction] command.
1140*/
1141static int DbTransPostCmd(
1142 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1143 Tcl_Interp *interp, /* Tcl interpreter */
1144 int result /* Result of evaluating SCRIPT */
1145){
mistachkin6ef5e122014-01-24 17:03:55 +00001146 static const char *const azEnd[] = {
dan4a4c11a2009-10-06 14:59:02 +00001147 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1148 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1149 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1150 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1151 };
1152 SqliteDb *pDb = (SqliteDb*)data[0];
1153 int rc = result;
1154 const char *zEnd;
1155
1156 pDb->nTransaction--;
1157 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1158
1159 pDb->disableAuth++;
1160 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1161 /* This is a tricky scenario to handle. The most likely cause of an
mistachkinb56660f2016-07-14 21:26:09 +00001162 ** error is that the exec() above was an attempt to commit the
dan4a4c11a2009-10-06 14:59:02 +00001163 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
mistachkin48864df2013-03-21 21:20:32 +00001164 ** that an IO-error has occurred. In either case, throw a Tcl exception
dan4a4c11a2009-10-06 14:59:02 +00001165 ** and try to rollback the transaction.
1166 **
mistachkinb56660f2016-07-14 21:26:09 +00001167 ** But it could also be that the user executed one or more BEGIN,
dan4a4c11a2009-10-06 14:59:02 +00001168 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1169 ** this method's logic. Not clear how this would be best handled.
1170 */
1171 if( rc!=TCL_ERROR ){
drha198f2b2014-02-07 19:26:13 +00001172 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
dan4a4c11a2009-10-06 14:59:02 +00001173 rc = TCL_ERROR;
1174 }
1175 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1176 }
1177 pDb->disableAuth--;
1178
1179 return rc;
1180}
1181
1182/*
danc431fd52011-06-27 16:55:50 +00001183** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1184** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1185** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
mistachkinb56660f2016-07-14 21:26:09 +00001186** on whether or not the [db_use_legacy_prepare] command has been used to
danc431fd52011-06-27 16:55:50 +00001187** configure the connection.
1188*/
1189static int dbPrepare(
1190 SqliteDb *pDb, /* Database object */
1191 const char *zSql, /* SQL to compile */
1192 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1193 const char **pzOut /* OUT: Pointer to next SQL statement */
1194){
1195#ifdef SQLITE_TEST
1196 if( pDb->bLegacyPrepare ){
1197 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1198 }
1199#endif
1200 return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut);
1201}
1202
1203/*
dan4a4c11a2009-10-06 14:59:02 +00001204** Search the cache for a prepared-statement object that implements the
1205** first SQL statement in the buffer pointed to by parameter zIn. If
1206** no such prepared-statement can be found, allocate and prepare a new
1207** one. In either case, bind the current values of the relevant Tcl
1208** variables to any $var, :var or @var variables in the statement. Before
1209** returning, set *ppPreStmt to point to the prepared-statement object.
1210**
1211** Output parameter *pzOut is set to point to the next SQL statement in
1212** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1213** next statement.
1214**
1215** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1216** and an error message loaded into interpreter pDb->interp.
1217*/
1218static int dbPrepareAndBind(
1219 SqliteDb *pDb, /* Database object */
1220 char const *zIn, /* SQL to compile */
1221 char const **pzOut, /* OUT: Pointer to next SQL statement */
1222 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1223){
1224 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
mistachkin7bb22ac2015-01-12 19:59:12 +00001225 sqlite3_stmt *pStmt = 0; /* Prepared statement object */
dan4a4c11a2009-10-06 14:59:02 +00001226 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1227 int nSql; /* Length of zSql in bytes */
mistachkin7bb22ac2015-01-12 19:59:12 +00001228 int nVar = 0; /* Number of variables in statement */
dan4a4c11a2009-10-06 14:59:02 +00001229 int iParm = 0; /* Next free entry in apParm */
drh0425f182013-11-26 16:48:04 +00001230 char c;
dan4a4c11a2009-10-06 14:59:02 +00001231 int i;
1232 Tcl_Interp *interp = pDb->interp;
1233
1234 *ppPreStmt = 0;
1235
1236 /* Trim spaces from the start of zSql and calculate the remaining length. */
drh0425f182013-11-26 16:48:04 +00001237 while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
dan4a4c11a2009-10-06 14:59:02 +00001238 nSql = strlen30(zSql);
1239
1240 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1241 int n = pPreStmt->nSql;
mistachkinb56660f2016-07-14 21:26:09 +00001242 if( nSql>=n
dan4a4c11a2009-10-06 14:59:02 +00001243 && memcmp(pPreStmt->zSql, zSql, n)==0
1244 && (zSql[n]==0 || zSql[n-1]==';')
1245 ){
1246 pStmt = pPreStmt->pStmt;
1247 *pzOut = &zSql[pPreStmt->nSql];
1248
1249 /* When a prepared statement is found, unlink it from the
1250 ** cache list. It will later be added back to the beginning
1251 ** of the cache list in order to implement LRU replacement.
1252 */
1253 if( pPreStmt->pPrev ){
1254 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1255 }else{
1256 pDb->stmtList = pPreStmt->pNext;
1257 }
1258 if( pPreStmt->pNext ){
1259 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1260 }else{
1261 pDb->stmtLast = pPreStmt->pPrev;
1262 }
1263 pDb->nStmt--;
1264 nVar = sqlite3_bind_parameter_count(pStmt);
1265 break;
1266 }
1267 }
mistachkinb56660f2016-07-14 21:26:09 +00001268
dan4a4c11a2009-10-06 14:59:02 +00001269 /* If no prepared statement was found. Compile the SQL text. Also allocate
1270 ** a new SqlPreparedStmt structure. */
1271 if( pPreStmt==0 ){
1272 int nByte;
1273
danc431fd52011-06-27 16:55:50 +00001274 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
drhc45e6712012-10-03 11:02:33 +00001275 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001276 return TCL_ERROR;
1277 }
1278 if( pStmt==0 ){
1279 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1280 /* A compile-time error in the statement. */
drhc45e6712012-10-03 11:02:33 +00001281 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001282 return TCL_ERROR;
1283 }else{
1284 /* The statement was a no-op. Continue to the next statement
1285 ** in the SQL string.
1286 */
1287 return TCL_OK;
1288 }
1289 }
1290
1291 assert( pPreStmt==0 );
1292 nVar = sqlite3_bind_parameter_count(pStmt);
1293 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1294 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1295 memset(pPreStmt, 0, nByte);
1296
1297 pPreStmt->pStmt = pStmt;
drh7ed243b2012-04-19 17:19:51 +00001298 pPreStmt->nSql = (int)(*pzOut - zSql);
dan4a4c11a2009-10-06 14:59:02 +00001299 pPreStmt->zSql = sqlite3_sql(pStmt);
1300 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
danc431fd52011-06-27 16:55:50 +00001301#ifdef SQLITE_TEST
1302 if( pPreStmt->zSql==0 ){
1303 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1304 memcpy(zCopy, zSql, pPreStmt->nSql);
1305 zCopy[pPreStmt->nSql] = '\0';
1306 pPreStmt->zSql = zCopy;
1307 }
1308#endif
dan4a4c11a2009-10-06 14:59:02 +00001309 }
1310 assert( pPreStmt );
1311 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1312 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1313
mistachkinb56660f2016-07-14 21:26:09 +00001314 /* Bind values to parameters that begin with $ or : */
dan4a4c11a2009-10-06 14:59:02 +00001315 for(i=1; i<=nVar; i++){
1316 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1317 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1318 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1319 if( pVar ){
1320 int n;
1321 u8 *data;
1322 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
mistachkin8e189222015-04-19 21:43:16 +00001323 c = zType[0];
dan4a4c11a2009-10-06 14:59:02 +00001324 if( zVar[0]=='@' ||
1325 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1326 /* Load a BLOB type if the Tcl variable is a bytearray and
1327 ** it has no string representation or the host
1328 ** parameter name begins with "@". */
1329 data = Tcl_GetByteArrayFromObj(pVar, &n);
1330 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1331 Tcl_IncrRefCount(pVar);
1332 pPreStmt->apParm[iParm++] = pVar;
1333 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1334 Tcl_GetIntFromObj(interp, pVar, &n);
1335 sqlite3_bind_int(pStmt, i, n);
1336 }else if( c=='d' && strcmp(zType,"double")==0 ){
1337 double r;
1338 Tcl_GetDoubleFromObj(interp, pVar, &r);
1339 sqlite3_bind_double(pStmt, i, r);
1340 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1341 (c=='i' && strcmp(zType,"int")==0) ){
1342 Tcl_WideInt v;
1343 Tcl_GetWideIntFromObj(interp, pVar, &v);
1344 sqlite3_bind_int64(pStmt, i, v);
1345 }else{
1346 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1347 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1348 Tcl_IncrRefCount(pVar);
1349 pPreStmt->apParm[iParm++] = pVar;
1350 }
1351 }else{
1352 sqlite3_bind_null(pStmt, i);
1353 }
1354 }
1355 }
1356 pPreStmt->nParm = iParm;
1357 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001358
dan4a4c11a2009-10-06 14:59:02 +00001359 return TCL_OK;
1360}
1361
dan4a4c11a2009-10-06 14:59:02 +00001362/*
1363** Release a statement reference obtained by calling dbPrepareAndBind().
1364** There should be exactly one call to this function for each call to
1365** dbPrepareAndBind().
1366**
1367** If the discard parameter is non-zero, then the statement is deleted
1368** immediately. Otherwise it is added to the LRU list and may be returned
1369** by a subsequent call to dbPrepareAndBind().
1370*/
1371static void dbReleaseStmt(
1372 SqliteDb *pDb, /* Database handle */
1373 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1374 int discard /* True to delete (not cache) the pPreStmt */
1375){
1376 int i;
1377
1378 /* Free the bound string and blob parameters */
1379 for(i=0; i<pPreStmt->nParm; i++){
1380 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1381 }
1382 pPreStmt->nParm = 0;
1383
1384 if( pDb->maxStmt<=0 || discard ){
1385 /* If the cache is turned off, deallocated the statement */
danc431fd52011-06-27 16:55:50 +00001386 dbFreeStmt(pPreStmt);
dan4a4c11a2009-10-06 14:59:02 +00001387 }else{
1388 /* Add the prepared statement to the beginning of the cache list. */
1389 pPreStmt->pNext = pDb->stmtList;
1390 pPreStmt->pPrev = 0;
1391 if( pDb->stmtList ){
1392 pDb->stmtList->pPrev = pPreStmt;
1393 }
1394 pDb->stmtList = pPreStmt;
1395 if( pDb->stmtLast==0 ){
1396 assert( pDb->nStmt==0 );
1397 pDb->stmtLast = pPreStmt;
1398 }else{
1399 assert( pDb->nStmt>0 );
1400 }
1401 pDb->nStmt++;
mistachkinb56660f2016-07-14 21:26:09 +00001402
1403 /* If we have too many statement in cache, remove the surplus from
dan4a4c11a2009-10-06 14:59:02 +00001404 ** the end of the cache list. */
1405 while( pDb->nStmt>pDb->maxStmt ){
danc431fd52011-06-27 16:55:50 +00001406 SqlPreparedStmt *pLast = pDb->stmtLast;
1407 pDb->stmtLast = pLast->pPrev;
dan4a4c11a2009-10-06 14:59:02 +00001408 pDb->stmtLast->pNext = 0;
1409 pDb->nStmt--;
danc431fd52011-06-27 16:55:50 +00001410 dbFreeStmt(pLast);
dan4a4c11a2009-10-06 14:59:02 +00001411 }
1412 }
1413}
1414
1415/*
1416** Structure used with dbEvalXXX() functions:
1417**
1418** dbEvalInit()
1419** dbEvalStep()
1420** dbEvalFinalize()
1421** dbEvalRowInfo()
1422** dbEvalColumnValue()
1423*/
1424typedef struct DbEvalContext DbEvalContext;
1425struct DbEvalContext {
1426 SqliteDb *pDb; /* Database handle */
1427 Tcl_Obj *pSql; /* Object holding string zSql */
1428 const char *zSql; /* Remaining SQL to execute */
1429 SqlPreparedStmt *pPreStmt; /* Current statement */
1430 int nCol; /* Number of columns returned by pStmt */
1431 Tcl_Obj *pArray; /* Name of array variable */
1432 Tcl_Obj **apColName; /* Array of column names */
1433};
1434
1435/*
1436** Release any cache of column names currently held as part of
1437** the DbEvalContext structure passed as the first argument.
1438*/
1439static void dbReleaseColumnNames(DbEvalContext *p){
1440 if( p->apColName ){
1441 int i;
1442 for(i=0; i<p->nCol; i++){
1443 Tcl_DecrRefCount(p->apColName[i]);
1444 }
1445 Tcl_Free((char *)p->apColName);
1446 p->apColName = 0;
1447 }
1448 p->nCol = 0;
1449}
1450
1451/*
1452** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001453**
1454** If pArray is not NULL, then it contains the name of a Tcl array
1455** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001456** the names of the columns returned by the statement as part of each
mistachkinb56660f2016-07-14 21:26:09 +00001457** call to dbEvalStep(), in order from left to right. e.g. if the names
1458** of the returned columns are a, b and c, it does the equivalent of the
dan4a4c11a2009-10-06 14:59:02 +00001459** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001460**
1461** set ${pArray}(*) {a b c}
1462*/
dan4a4c11a2009-10-06 14:59:02 +00001463static void dbEvalInit(
1464 DbEvalContext *p, /* Pointer to structure to initialize */
1465 SqliteDb *pDb, /* Database handle */
1466 Tcl_Obj *pSql, /* Object containing SQL script */
1467 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001468){
dan4a4c11a2009-10-06 14:59:02 +00001469 memset(p, 0, sizeof(DbEvalContext));
1470 p->pDb = pDb;
1471 p->zSql = Tcl_GetString(pSql);
1472 p->pSql = pSql;
1473 Tcl_IncrRefCount(pSql);
1474 if( pArray ){
1475 p->pArray = pArray;
1476 Tcl_IncrRefCount(pArray);
1477 }
1478}
danielk19778e556522007-11-13 10:30:24 +00001479
dan4a4c11a2009-10-06 14:59:02 +00001480/*
1481** Obtain information about the row that the DbEvalContext passed as the
1482** first argument currently points to.
1483*/
1484static void dbEvalRowInfo(
1485 DbEvalContext *p, /* Evaluation context */
1486 int *pnCol, /* OUT: Number of column names */
1487 Tcl_Obj ***papColName /* OUT: Array of column names */
1488){
danielk19778e556522007-11-13 10:30:24 +00001489 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001490 if( 0==p->apColName ){
1491 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1492 int i; /* Iterator variable */
1493 int nCol; /* Number of columns returned by pStmt */
1494 Tcl_Obj **apColName = 0; /* Array of column names */
1495
1496 p->nCol = nCol = sqlite3_column_count(pStmt);
1497 if( nCol>0 && (papColName || p->pArray) ){
1498 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1499 for(i=0; i<nCol; i++){
drhc45e6712012-10-03 11:02:33 +00001500 apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
dan4a4c11a2009-10-06 14:59:02 +00001501 Tcl_IncrRefCount(apColName[i]);
1502 }
1503 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001504 }
1505
1506 /* If results are being stored in an array variable, then create
1507 ** the array(*) entry for that array
1508 */
dan4a4c11a2009-10-06 14:59:02 +00001509 if( p->pArray ){
1510 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001511 Tcl_Obj *pColList = Tcl_NewObj();
1512 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001513
danielk19778e556522007-11-13 10:30:24 +00001514 for(i=0; i<nCol; i++){
1515 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1516 }
1517 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001518 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001519 Tcl_DecrRefCount(pStar);
1520 }
danielk19778e556522007-11-13 10:30:24 +00001521 }
1522
dan4a4c11a2009-10-06 14:59:02 +00001523 if( papColName ){
1524 *papColName = p->apColName;
1525 }
1526 if( pnCol ){
1527 *pnCol = p->nCol;
1528 }
1529}
1530
1531/*
1532** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1533** returned, then an error message is stored in the interpreter before
1534** returning.
1535**
1536** A return value of TCL_OK means there is a row of data available. The
1537** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1538** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1539** is returned, then the SQL script has finished executing and there are
1540** no further rows available. This is similar to SQLITE_DONE.
1541*/
1542static int dbEvalStep(DbEvalContext *p){
danc431fd52011-06-27 16:55:50 +00001543 const char *zPrevSql = 0; /* Previous value of p->zSql */
1544
dan4a4c11a2009-10-06 14:59:02 +00001545 while( p->zSql[0] || p->pPreStmt ){
1546 int rc;
1547 if( p->pPreStmt==0 ){
danc431fd52011-06-27 16:55:50 +00001548 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
dan4a4c11a2009-10-06 14:59:02 +00001549 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1550 if( rc!=TCL_OK ) return rc;
1551 }else{
1552 int rcs;
1553 SqliteDb *pDb = p->pDb;
1554 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1555 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1556
1557 rcs = sqlite3_step(pStmt);
1558 if( rcs==SQLITE_ROW ){
1559 return TCL_OK;
1560 }
1561 if( p->pArray ){
1562 dbEvalRowInfo(p, 0, 0);
1563 }
1564 rcs = sqlite3_reset(pStmt);
1565
1566 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1567 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001568 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
dan4a4c11a2009-10-06 14:59:02 +00001569 dbReleaseColumnNames(p);
1570 p->pPreStmt = 0;
1571
1572 if( rcs!=SQLITE_OK ){
1573 /* If a run-time error occurs, report the error and stop reading
1574 ** the SQL. */
dan4a4c11a2009-10-06 14:59:02 +00001575 dbReleaseStmt(pDb, pPreStmt, 1);
danc431fd52011-06-27 16:55:50 +00001576#if SQLITE_TEST
1577 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1578 /* If the runtime error was an SQLITE_SCHEMA, and the database
mistachkinb56660f2016-07-14 21:26:09 +00001579 ** handle is configured to use the legacy sqlite3_prepare()
danc431fd52011-06-27 16:55:50 +00001580 ** interface, retry prepare()/step() on the same SQL statement.
1581 ** This only happens once. If there is a second SQLITE_SCHEMA
1582 ** error, the error will be returned to the caller. */
1583 p->zSql = zPrevSql;
1584 continue;
1585 }
1586#endif
drhc45e6712012-10-03 11:02:33 +00001587 Tcl_SetObjResult(pDb->interp,
1588 Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001589 return TCL_ERROR;
1590 }else{
1591 dbReleaseStmt(pDb, pPreStmt, 0);
1592 }
1593 }
1594 }
1595
1596 /* Finished */
1597 return TCL_BREAK;
1598}
1599
1600/*
1601** Free all resources currently held by the DbEvalContext structure passed
1602** as the first argument. There should be exactly one call to this function
1603** for each call to dbEvalInit().
1604*/
1605static void dbEvalFinalize(DbEvalContext *p){
1606 if( p->pPreStmt ){
1607 sqlite3_reset(p->pPreStmt->pStmt);
1608 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1609 p->pPreStmt = 0;
1610 }
1611 if( p->pArray ){
1612 Tcl_DecrRefCount(p->pArray);
1613 p->pArray = 0;
1614 }
1615 Tcl_DecrRefCount(p->pSql);
1616 dbReleaseColumnNames(p);
1617}
1618
1619/*
1620** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1621** the value for the iCol'th column of the row currently pointed to by
1622** the DbEvalContext structure passed as the first argument.
1623*/
1624static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1625 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1626 switch( sqlite3_column_type(pStmt, iCol) ){
1627 case SQLITE_BLOB: {
1628 int bytes = sqlite3_column_bytes(pStmt, iCol);
1629 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1630 if( !zBlob ) bytes = 0;
1631 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1632 }
1633 case SQLITE_INTEGER: {
1634 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1635 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +00001636 return Tcl_NewIntObj((int)v);
dan4a4c11a2009-10-06 14:59:02 +00001637 }else{
1638 return Tcl_NewWideIntObj(v);
1639 }
1640 }
1641 case SQLITE_FLOAT: {
1642 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1643 }
1644 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +00001645 return Tcl_NewStringObj(p->pDb->zNull, -1);
dan4a4c11a2009-10-06 14:59:02 +00001646 }
1647 }
1648
drh325eff52012-10-03 12:56:18 +00001649 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
dan4a4c11a2009-10-06 14:59:02 +00001650}
1651
1652/*
1653** If using Tcl version 8.6 or greater, use the NR functions to avoid
1654** recursive evalution of scripts by the [db eval] and [db trans]
1655** commands. Even if the headers used while compiling the extension
1656** are 8.6 or newer, the code still tests the Tcl version at runtime.
1657** This allows stubs-enabled builds to be used with older Tcl libraries.
1658*/
1659#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001660# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001661static int DbUseNre(void){
1662 int major, minor;
1663 Tcl_GetVersion(&major, &minor, 0, 0);
1664 return( (major==8 && minor>=6) || major>8 );
1665}
1666#else
mistachkinb56660f2016-07-14 21:26:09 +00001667/*
dan4a4c11a2009-10-06 14:59:02 +00001668** Compiling using headers earlier than 8.6. In this case NR cannot be
1669** used, so DbUseNre() to always return zero. Add #defines for the other
1670** Tcl_NRxxx() functions to prevent them from causing compilation errors,
mistachkinb56660f2016-07-14 21:26:09 +00001671** even though the only invocations of them are within conditional blocks
dan4a4c11a2009-10-06 14:59:02 +00001672** of the form:
1673**
1674** if( DbUseNre() ) { ... }
1675*/
drha2c8a952009-10-13 18:38:34 +00001676# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001677# define DbUseNre() 0
drha47941f2013-12-20 18:57:44 +00001678# define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001679# define Tcl_NREvalObj(a,b,c) 0
drha47941f2013-12-20 18:57:44 +00001680# define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001681#endif
1682
1683/*
1684** This function is part of the implementation of the command:
1685**
1686** $db eval SQL ?ARRAYNAME? SCRIPT
1687*/
1688static int DbEvalNextCmd(
1689 ClientData data[], /* data[0] is the (DbEvalContext*) */
1690 Tcl_Interp *interp, /* Tcl interpreter */
1691 int result /* Result so far */
1692){
1693 int rc = result; /* Return code */
1694
1695 /* The first element of the data[] array is a pointer to a DbEvalContext
1696 ** structure allocated using Tcl_Alloc(). The second element of data[]
1697 ** is a pointer to a Tcl_Obj containing the script to run for each row
1698 ** returned by the queries encapsulated in data[0]. */
1699 DbEvalContext *p = (DbEvalContext *)data[0];
1700 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1701 Tcl_Obj *pArray = p->pArray;
1702
1703 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1704 int i;
1705 int nCol;
1706 Tcl_Obj **apColName;
1707 dbEvalRowInfo(p, &nCol, &apColName);
1708 for(i=0; i<nCol; i++){
1709 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1710 if( pArray==0 ){
1711 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1712 }else{
1713 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1714 }
1715 }
1716
mistachkinb56660f2016-07-14 21:26:09 +00001717 /* The required interpreter variables are now populated with the data
dan4a4c11a2009-10-06 14:59:02 +00001718 ** from the current row. If using NRE, schedule callbacks to evaluate
1719 ** script pScript, then to invoke this function again to fetch the next
1720 ** row (or clean up if there is no next row or the script throws an
mistachkinb56660f2016-07-14 21:26:09 +00001721 ** exception). After scheduling the callbacks, return control to the
dan4a4c11a2009-10-06 14:59:02 +00001722 ** caller.
1723 **
1724 ** If not using NRE, evaluate pScript directly and continue with the
1725 ** next iteration of this while(...) loop. */
1726 if( DbUseNre() ){
1727 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1728 return Tcl_NREvalObj(interp, pScript, 0);
1729 }else{
1730 rc = Tcl_EvalObjEx(interp, pScript, 0);
1731 }
1732 }
1733
1734 Tcl_DecrRefCount(pScript);
1735 dbEvalFinalize(p);
1736 Tcl_Free((char *)p);
1737
1738 if( rc==TCL_OK || rc==TCL_BREAK ){
1739 Tcl_ResetResult(interp);
1740 rc = TCL_OK;
1741 }
1742 return rc;
danielk19778e556522007-11-13 10:30:24 +00001743}
1744
tpoindex1067fe12004-12-17 15:41:11 +00001745/*
mistachkinb56660f2016-07-14 21:26:09 +00001746** This function is used by the implementations of the following database
dan46c47d42011-03-01 18:42:07 +00001747** handle sub-commands:
1748**
1749** $db update_hook ?SCRIPT?
1750** $db wal_hook ?SCRIPT?
1751** $db commit_hook ?SCRIPT?
1752** $db preupdate hook ?SCRIPT?
1753*/
1754static void DbHookCmd(
1755 Tcl_Interp *interp, /* Tcl interpreter */
1756 SqliteDb *pDb, /* Database handle */
1757 Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */
1758 Tcl_Obj **ppHook /* Pointer to member of SqliteDb */
1759){
1760 sqlite3 *db = pDb->db;
1761
1762 if( *ppHook ){
1763 Tcl_SetObjResult(interp, *ppHook);
1764 if( pArg ){
1765 Tcl_DecrRefCount(*ppHook);
1766 *ppHook = 0;
1767 }
1768 }
1769 if( pArg ){
1770 assert( !(*ppHook) );
1771 if( Tcl_GetCharLength(pArg)>0 ){
1772 *ppHook = pArg;
1773 Tcl_IncrRefCount(*ppHook);
1774 }
1775 }
1776
drh9b1c62d2011-03-30 21:04:43 +00001777#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +00001778 sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
drh9b1c62d2011-03-30 21:04:43 +00001779#endif
dan46c47d42011-03-01 18:42:07 +00001780 sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1781 sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1782 sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
1783}
1784
1785/*
drh75897232000-05-29 14:26:00 +00001786** The "sqlite" command below creates a new Tcl command for each
1787** connection it opens to an SQLite database. This routine is invoked
1788** whenever one of those connection-specific commands is executed
1789** in Tcl. For example, if you run Tcl code like this:
1790**
drh9bb575f2004-09-06 17:24:11 +00001791** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001792** db1 close
1793**
1794** The first command opens a connection to the "my_database" database
1795** and calls that connection "db1". The second command causes this
1796** subroutine to be invoked.
1797*/
drh6d313162000-09-21 13:01:35 +00001798static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001799 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001800 int choice;
drh22fbcb82004-02-01 01:22:50 +00001801 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001802 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001803 "authorizer", "backup", "busy",
1804 "cache", "changes", "close",
1805 "collate", "collation_needed", "commit_hook",
1806 "complete", "copy", "enable_load_extension",
1807 "errorcode", "eval", "exists",
1808 "function", "incrblob", "interrupt",
drh833bf962010-04-28 14:42:19 +00001809 "last_insert_rowid", "nullvalue", "onecolumn",
drh304637c2011-03-18 16:47:27 +00001810 "preupdate", "profile", "progress",
1811 "rekey", "restore", "rollback_hook",
1812 "status", "timeout", "total_changes",
mistachkinb56660f2016-07-14 21:26:09 +00001813 "trace", "trace_v2", "transaction",
1814 "unlock_notify", "update_hook", "version",
1815 "wal_hook",
1816 0
drh6d313162000-09-21 13:01:35 +00001817 };
drh411995d2002-06-25 19:31:18 +00001818 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001819 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1820 DB_CACHE, DB_CHANGES, DB_CLOSE,
1821 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1822 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1823 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1824 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
drh833bf962010-04-28 14:42:19 +00001825 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
drh304637c2011-03-18 16:47:27 +00001826 DB_PREUPDATE, DB_PROFILE, DB_PROGRESS,
1827 DB_REKEY, DB_RESTORE, DB_ROLLBACK_HOOK,
1828 DB_STATUS, DB_TIMEOUT, DB_TOTAL_CHANGES,
mistachkinb56660f2016-07-14 21:26:09 +00001829 DB_TRACE, DB_TRACE_V2, DB_TRANSACTION,
1830 DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK, DB_VERSION,
1831 DB_WAL_HOOK,
drh6d313162000-09-21 13:01:35 +00001832 };
tpoindex1067fe12004-12-17 15:41:11 +00001833 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001834
1835 if( objc<2 ){
1836 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001837 return TCL_ERROR;
1838 }
drh411995d2002-06-25 19:31:18 +00001839 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001840 return TCL_ERROR;
1841 }
1842
drh411995d2002-06-25 19:31:18 +00001843 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001844
drhe22a3342003-04-22 20:30:37 +00001845 /* $db authorizer ?CALLBACK?
1846 **
1847 ** Invoke the given callback to authorize each SQL operation as it is
1848 ** compiled. 5 arguments are appended to the callback before it is
1849 ** invoked:
1850 **
1851 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1852 ** (2) First descriptive name (depends on authorization type)
1853 ** (3) Second descriptive name
1854 ** (4) Name of the database (ex: "main", "temp")
1855 ** (5) Name of trigger that is doing the access
1856 **
1857 ** The callback should return on of the following strings: SQLITE_OK,
1858 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1859 **
1860 ** If this method is invoked with no arguments, the current authorization
1861 ** callback string is returned.
1862 */
1863 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001864#ifdef SQLITE_OMIT_AUTHORIZATION
drha198f2b2014-02-07 19:26:13 +00001865 Tcl_AppendResult(interp, "authorization not available in this build",
1866 (char*)0);
drh1211de32004-07-26 12:24:22 +00001867 return TCL_ERROR;
1868#else
drhe22a3342003-04-22 20:30:37 +00001869 if( objc>3 ){
1870 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001871 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001872 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001873 if( pDb->zAuth ){
drha198f2b2014-02-07 19:26:13 +00001874 Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
drhe22a3342003-04-22 20:30:37 +00001875 }
1876 }else{
1877 char *zAuth;
1878 int len;
1879 if( pDb->zAuth ){
1880 Tcl_Free(pDb->zAuth);
1881 }
1882 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1883 if( zAuth && len>0 ){
1884 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001885 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001886 }else{
1887 pDb->zAuth = 0;
1888 }
drhe22a3342003-04-22 20:30:37 +00001889 if( pDb->zAuth ){
drh32c6a482014-09-11 13:44:52 +00001890 typedef int (*sqlite3_auth_cb)(
1891 void*,int,const char*,const char*,
1892 const char*,const char*);
drhe22a3342003-04-22 20:30:37 +00001893 pDb->interp = interp;
drh32c6a482014-09-11 13:44:52 +00001894 sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
drhe22a3342003-04-22 20:30:37 +00001895 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001896 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001897 }
drhe22a3342003-04-22 20:30:37 +00001898 }
drh1211de32004-07-26 12:24:22 +00001899#endif
drhe22a3342003-04-22 20:30:37 +00001900 break;
1901 }
1902
drhdc2c4912009-02-04 22:46:47 +00001903 /* $db backup ?DATABASE? FILENAME
1904 **
1905 ** Open or create a database file named FILENAME. Transfer the
1906 ** content of local database DATABASE (default: "main") into the
1907 ** FILENAME database.
1908 */
1909 case DB_BACKUP: {
1910 const char *zDestFile;
1911 const char *zSrcDb;
1912 sqlite3 *pDest;
1913 sqlite3_backup *pBackup;
1914
1915 if( objc==3 ){
1916 zSrcDb = "main";
1917 zDestFile = Tcl_GetString(objv[2]);
1918 }else if( objc==4 ){
1919 zSrcDb = Tcl_GetString(objv[2]);
1920 zDestFile = Tcl_GetString(objv[3]);
1921 }else{
1922 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1923 return TCL_ERROR;
1924 }
drh147ef392016-01-22 23:17:51 +00001925 rc = sqlite3_open_v2(zDestFile, &pDest,
1926 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00001927 if( rc!=SQLITE_OK ){
1928 Tcl_AppendResult(interp, "cannot open target database: ",
1929 sqlite3_errmsg(pDest), (char*)0);
1930 sqlite3_close(pDest);
1931 return TCL_ERROR;
1932 }
1933 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1934 if( pBackup==0 ){
1935 Tcl_AppendResult(interp, "backup failed: ",
1936 sqlite3_errmsg(pDest), (char*)0);
1937 sqlite3_close(pDest);
1938 return TCL_ERROR;
1939 }
1940 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1941 sqlite3_backup_finish(pBackup);
1942 if( rc==SQLITE_DONE ){
1943 rc = TCL_OK;
1944 }else{
1945 Tcl_AppendResult(interp, "backup failed: ",
1946 sqlite3_errmsg(pDest), (char*)0);
1947 rc = TCL_ERROR;
1948 }
1949 sqlite3_close(pDest);
1950 break;
1951 }
1952
drhbec3f402000-08-04 13:49:02 +00001953 /* $db busy ?CALLBACK?
1954 **
1955 ** Invoke the given callback if an SQL statement attempts to open
1956 ** a locked database file.
1957 */
drh6d313162000-09-21 13:01:35 +00001958 case DB_BUSY: {
1959 if( objc>3 ){
1960 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001961 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001962 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001963 if( pDb->zBusy ){
drha198f2b2014-02-07 19:26:13 +00001964 Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
drhbec3f402000-08-04 13:49:02 +00001965 }
1966 }else{
drh6d313162000-09-21 13:01:35 +00001967 char *zBusy;
1968 int len;
drhbec3f402000-08-04 13:49:02 +00001969 if( pDb->zBusy ){
1970 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001971 }
drh6d313162000-09-21 13:01:35 +00001972 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1973 if( zBusy && len>0 ){
1974 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001975 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001976 }else{
1977 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001978 }
1979 if( pDb->zBusy ){
1980 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001981 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001982 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001983 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001984 }
1985 }
drh6d313162000-09-21 13:01:35 +00001986 break;
1987 }
drhbec3f402000-08-04 13:49:02 +00001988
drhfb7e7652005-01-24 00:28:42 +00001989 /* $db cache flush
1990 ** $db cache size n
1991 **
1992 ** Flush the prepared statement cache, or set the maximum number of
1993 ** cached statements.
1994 */
1995 case DB_CACHE: {
1996 char *subCmd;
1997 int n;
1998
1999 if( objc<=2 ){
2000 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
2001 return TCL_ERROR;
2002 }
2003 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
2004 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
2005 if( objc!=3 ){
2006 Tcl_WrongNumArgs(interp, 2, objv, "flush");
2007 return TCL_ERROR;
2008 }else{
2009 flushStmtCache( pDb );
2010 }
2011 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
2012 if( objc!=4 ){
2013 Tcl_WrongNumArgs(interp, 2, objv, "size n");
2014 return TCL_ERROR;
2015 }else{
2016 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
mistachkinb56660f2016-07-14 21:26:09 +00002017 Tcl_AppendResult( interp, "cannot convert \"",
drha198f2b2014-02-07 19:26:13 +00002018 Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
drhfb7e7652005-01-24 00:28:42 +00002019 return TCL_ERROR;
2020 }else{
2021 if( n<0 ){
2022 flushStmtCache( pDb );
2023 n = 0;
2024 }else if( n>MAX_PREPARED_STMTS ){
2025 n = MAX_PREPARED_STMTS;
2026 }
2027 pDb->maxStmt = n;
2028 }
2029 }
2030 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002031 Tcl_AppendResult( interp, "bad option \"",
drha198f2b2014-02-07 19:26:13 +00002032 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
2033 (char*)0);
drhfb7e7652005-01-24 00:28:42 +00002034 return TCL_ERROR;
2035 }
2036 break;
2037 }
2038
danielk1977b28af712004-06-21 06:50:26 +00002039 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00002040 **
2041 ** Return the number of rows that were modified, inserted, or deleted by
mistachkinb56660f2016-07-14 21:26:09 +00002042 ** the most recent INSERT, UPDATE or DELETE statement, not including
danielk1977b28af712004-06-21 06:50:26 +00002043 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00002044 */
2045 case DB_CHANGES: {
2046 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00002047 if( objc!=2 ){
2048 Tcl_WrongNumArgs(interp, 2, objv, "");
2049 return TCL_ERROR;
2050 }
drhc8d30ac2002-04-12 10:08:59 +00002051 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00002052 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00002053 break;
2054 }
2055
drh75897232000-05-29 14:26:00 +00002056 /* $db close
2057 **
2058 ** Shutdown the database
2059 */
drh6d313162000-09-21 13:01:35 +00002060 case DB_CLOSE: {
2061 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
2062 break;
2063 }
drh75897232000-05-29 14:26:00 +00002064
drh0f14e2e2004-06-29 12:39:08 +00002065 /*
2066 ** $db collate NAME SCRIPT
2067 **
2068 ** Create a new SQL collation function called NAME. Whenever
2069 ** that function is called, invoke SCRIPT to evaluate the function.
2070 */
2071 case DB_COLLATE: {
2072 SqlCollate *pCollate;
2073 char *zName;
2074 char *zScript;
2075 int nScript;
2076 if( objc!=4 ){
2077 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
2078 return TCL_ERROR;
2079 }
2080 zName = Tcl_GetStringFromObj(objv[2], 0);
2081 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
2082 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
2083 if( pCollate==0 ) return TCL_ERROR;
2084 pCollate->interp = interp;
2085 pCollate->pNext = pDb->pCollate;
2086 pCollate->zScript = (char*)&pCollate[1];
2087 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00002088 memcpy(pCollate->zScript, zScript, nScript+1);
mistachkinb56660f2016-07-14 21:26:09 +00002089 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
drh0f14e2e2004-06-29 12:39:08 +00002090 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00002091 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00002092 return TCL_ERROR;
2093 }
2094 break;
2095 }
2096
2097 /*
2098 ** $db collation_needed SCRIPT
2099 **
2100 ** Create a new SQL collation function called NAME. Whenever
2101 ** that function is called, invoke SCRIPT to evaluate the function.
2102 */
2103 case DB_COLLATION_NEEDED: {
2104 if( objc!=3 ){
2105 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
2106 return TCL_ERROR;
2107 }
2108 if( pDb->pCollateNeeded ){
2109 Tcl_DecrRefCount(pDb->pCollateNeeded);
2110 }
2111 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
2112 Tcl_IncrRefCount(pDb->pCollateNeeded);
2113 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
2114 break;
2115 }
2116
drh19e2d372005-08-29 23:00:03 +00002117 /* $db commit_hook ?CALLBACK?
2118 **
2119 ** Invoke the given callback just before committing every SQL transaction.
2120 ** If the callback throws an exception or returns non-zero, then the
2121 ** transaction is aborted. If CALLBACK is an empty string, the callback
2122 ** is disabled.
2123 */
2124 case DB_COMMIT_HOOK: {
2125 if( objc>3 ){
2126 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2127 return TCL_ERROR;
2128 }else if( objc==2 ){
2129 if( pDb->zCommit ){
drha198f2b2014-02-07 19:26:13 +00002130 Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002131 }
2132 }else{
mistachkin6ef5e122014-01-24 17:03:55 +00002133 const char *zCommit;
drh19e2d372005-08-29 23:00:03 +00002134 int len;
2135 if( pDb->zCommit ){
2136 Tcl_Free(pDb->zCommit);
2137 }
2138 zCommit = Tcl_GetStringFromObj(objv[2], &len);
2139 if( zCommit && len>0 ){
2140 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002141 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00002142 }else{
2143 pDb->zCommit = 0;
2144 }
2145 if( pDb->zCommit ){
2146 pDb->interp = interp;
2147 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
2148 }else{
2149 sqlite3_commit_hook(pDb->db, 0, 0);
2150 }
2151 }
2152 break;
2153 }
2154
drh75897232000-05-29 14:26:00 +00002155 /* $db complete SQL
2156 **
2157 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2158 ** additional lines of input are needed. This is similar to the
2159 ** built-in "info complete" command of Tcl.
2160 */
drh6d313162000-09-21 13:01:35 +00002161 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00002162#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00002163 Tcl_Obj *pResult;
2164 int isComplete;
2165 if( objc!=3 ){
2166 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00002167 return TCL_ERROR;
2168 }
danielk19776f8a5032004-05-10 10:34:51 +00002169 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00002170 pResult = Tcl_GetObjResult(interp);
2171 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00002172#endif
drh6d313162000-09-21 13:01:35 +00002173 break;
2174 }
drhdcd997e2003-01-31 17:21:49 +00002175
drh19e2d372005-08-29 23:00:03 +00002176 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2177 **
2178 ** Copy data into table from filename, optionally using SEPARATOR
2179 ** as column separators. If a column contains a null string, or the
2180 ** value of NULLINDICATOR, a NULL is inserted for the column.
2181 ** conflict-algorithm is one of the sqlite conflict algorithms:
2182 ** rollback, abort, fail, ignore, replace
2183 ** On success, return the number of lines processed, not necessarily same
2184 ** as 'db changes' due to conflict-algorithm selected.
2185 **
2186 ** This code is basically an implementation/enhancement of
2187 ** the sqlite3 shell.c ".import" command.
2188 **
2189 ** This command usage is equivalent to the sqlite2.x COPY statement,
2190 ** which imports file data into a table using the PostgreSQL COPY file format:
2191 ** $db copy $conflit_algo $table_name $filename \t \\N
2192 */
2193 case DB_COPY: {
2194 char *zTable; /* Insert data into this table */
2195 char *zFile; /* The file from which to extract data */
2196 char *zConflict; /* The conflict algorithm to use */
2197 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00002198 int nCol; /* Number of columns in the table */
2199 int nByte; /* Number of bytes in an SQL string */
2200 int i, j; /* Loop counters */
2201 int nSep; /* Number of bytes in zSep[] */
2202 int nNull; /* Number of bytes in zNull[] */
2203 char *zSql; /* An SQL statement */
2204 char *zLine; /* A single line of input from the file */
2205 char **azCol; /* zLine[] broken up into columns */
mistachkin6ef5e122014-01-24 17:03:55 +00002206 const char *zCommit; /* How to commit changes */
drh19e2d372005-08-29 23:00:03 +00002207 FILE *in; /* The input file */
2208 int lineno = 0; /* Line number of input file */
2209 char zLineNum[80]; /* Line number print buffer */
2210 Tcl_Obj *pResult; /* interp result */
2211
mistachkin6ef5e122014-01-24 17:03:55 +00002212 const char *zSep;
2213 const char *zNull;
drh19e2d372005-08-29 23:00:03 +00002214 if( objc<5 || objc>7 ){
mistachkinb56660f2016-07-14 21:26:09 +00002215 Tcl_WrongNumArgs(interp, 2, objv,
drh19e2d372005-08-29 23:00:03 +00002216 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2217 return TCL_ERROR;
2218 }
2219 if( objc>=6 ){
2220 zSep = Tcl_GetStringFromObj(objv[5], 0);
2221 }else{
2222 zSep = "\t";
2223 }
2224 if( objc>=7 ){
2225 zNull = Tcl_GetStringFromObj(objv[6], 0);
2226 }else{
2227 zNull = "";
2228 }
2229 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2230 zTable = Tcl_GetStringFromObj(objv[3], 0);
2231 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002232 nSep = strlen30(zSep);
2233 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002234 if( nSep==0 ){
drha198f2b2014-02-07 19:26:13 +00002235 Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2236 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002237 return TCL_ERROR;
2238 }
drh3e59c012008-09-23 10:12:13 +00002239 if(strcmp(zConflict, "rollback") != 0 &&
2240 strcmp(zConflict, "abort" ) != 0 &&
2241 strcmp(zConflict, "fail" ) != 0 &&
2242 strcmp(zConflict, "ignore" ) != 0 &&
2243 strcmp(zConflict, "replace" ) != 0 ) {
mistachkinb56660f2016-07-14 21:26:09 +00002244 Tcl_AppendResult(interp, "Error: \"", zConflict,
drh19e2d372005-08-29 23:00:03 +00002245 "\", conflict-algorithm must be one of: rollback, "
drha198f2b2014-02-07 19:26:13 +00002246 "abort, fail, ignore, or replace", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002247 return TCL_ERROR;
2248 }
2249 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2250 if( zSql==0 ){
drha198f2b2014-02-07 19:26:13 +00002251 Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002252 return TCL_ERROR;
2253 }
drh4f21c4a2008-12-10 22:15:00 +00002254 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002255 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002256 sqlite3_free(zSql);
2257 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002258 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002259 nCol = 0;
2260 }else{
2261 nCol = sqlite3_column_count(pStmt);
2262 }
2263 sqlite3_finalize(pStmt);
2264 if( nCol==0 ) {
2265 return TCL_ERROR;
2266 }
2267 zSql = malloc( nByte + 50 + nCol*2 );
2268 if( zSql==0 ) {
drha198f2b2014-02-07 19:26:13 +00002269 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002270 return TCL_ERROR;
2271 }
2272 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2273 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002274 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002275 for(i=1; i<nCol; i++){
2276 zSql[j++] = ',';
2277 zSql[j++] = '?';
2278 }
2279 zSql[j++] = ')';
2280 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002281 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002282 free(zSql);
2283 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002284 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002285 sqlite3_finalize(pStmt);
2286 return TCL_ERROR;
2287 }
2288 in = fopen(zFile, "rb");
2289 if( in==0 ){
2290 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2291 sqlite3_finalize(pStmt);
2292 return TCL_ERROR;
2293 }
2294 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2295 if( azCol==0 ) {
drha198f2b2014-02-07 19:26:13 +00002296 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh43617e92006-03-06 20:55:46 +00002297 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002298 return TCL_ERROR;
2299 }
drh37527852006-03-16 16:19:56 +00002300 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002301 zCommit = "COMMIT";
2302 while( (zLine = local_getline(0, in))!=0 ){
2303 char *z;
drh19e2d372005-08-29 23:00:03 +00002304 lineno++;
2305 azCol[0] = zLine;
2306 for(i=0, z=zLine; *z; z++){
2307 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2308 *z = 0;
2309 i++;
2310 if( i<nCol ){
2311 azCol[i] = &z[nSep];
2312 z += nSep-1;
2313 }
2314 }
2315 }
2316 if( i+1!=nCol ){
2317 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002318 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002319 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002320 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002321 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002322 "Error: %s line %d: expected %d columns of data but found %d",
2323 zFile, lineno, nCol, i+1);
drha198f2b2014-02-07 19:26:13 +00002324 Tcl_AppendResult(interp, zErr, (char*)0);
drhc1f44942006-05-10 14:39:13 +00002325 free(zErr);
2326 }
drh19e2d372005-08-29 23:00:03 +00002327 zCommit = "ROLLBACK";
2328 break;
2329 }
2330 for(i=0; i<nCol; i++){
2331 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002332 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
mistachkinb56660f2016-07-14 21:26:09 +00002333 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002334 ){
drh19e2d372005-08-29 23:00:03 +00002335 sqlite3_bind_null(pStmt, i+1);
2336 }else{
2337 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2338 }
2339 }
2340 sqlite3_step(pStmt);
2341 rc = sqlite3_reset(pStmt);
2342 free(zLine);
2343 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00002344 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002345 zCommit = "ROLLBACK";
2346 break;
2347 }
2348 }
2349 free(azCol);
2350 fclose(in);
2351 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002352 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002353
2354 if( zCommit[0] == 'C' ){
2355 /* success, set result as number of lines processed */
2356 pResult = Tcl_GetObjResult(interp);
2357 Tcl_SetIntObj(pResult, lineno);
2358 rc = TCL_OK;
2359 }else{
2360 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002361 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drha198f2b2014-02-07 19:26:13 +00002362 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2363 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002364 rc = TCL_ERROR;
2365 }
2366 break;
2367 }
2368
drhdcd997e2003-01-31 17:21:49 +00002369 /*
drh41449052006-07-06 17:08:48 +00002370 ** $db enable_load_extension BOOLEAN
2371 **
2372 ** Turn the extension loading feature on or off. It if off by
2373 ** default.
2374 */
2375 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002376#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002377 int onoff;
2378 if( objc!=3 ){
2379 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2380 return TCL_ERROR;
2381 }
2382 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2383 return TCL_ERROR;
2384 }
2385 sqlite3_enable_load_extension(pDb->db, onoff);
2386 break;
drhf533acc2006-12-19 18:57:11 +00002387#else
2388 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
drha198f2b2014-02-07 19:26:13 +00002389 (char*)0);
drhf533acc2006-12-19 18:57:11 +00002390 return TCL_ERROR;
2391#endif
drh41449052006-07-06 17:08:48 +00002392 }
2393
2394 /*
drhdcd997e2003-01-31 17:21:49 +00002395 ** $db errorcode
2396 **
2397 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002398 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002399 */
2400 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002401 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002402 break;
2403 }
dan4a4c11a2009-10-06 14:59:02 +00002404
2405 /*
2406 ** $db exists $sql
2407 ** $db onecolumn $sql
2408 **
2409 ** The onecolumn method is the equivalent of:
2410 ** lindex [$db eval $sql] 0
2411 */
mistachkinb56660f2016-07-14 21:26:09 +00002412 case DB_EXISTS:
dan4a4c11a2009-10-06 14:59:02 +00002413 case DB_ONECOLUMN: {
drhedc40242016-06-13 12:34:38 +00002414 Tcl_Obj *pResult = 0;
dan4a4c11a2009-10-06 14:59:02 +00002415 DbEvalContext sEval;
2416 if( objc!=3 ){
2417 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2418 return TCL_ERROR;
2419 }
2420
2421 dbEvalInit(&sEval, pDb, objv[2], 0);
2422 rc = dbEvalStep(&sEval);
2423 if( choice==DB_ONECOLUMN ){
2424 if( rc==TCL_OK ){
drhedc40242016-06-13 12:34:38 +00002425 pResult = dbEvalColumnValue(&sEval, 0);
dand5f12cd2011-08-18 17:47:57 +00002426 }else if( rc==TCL_BREAK ){
2427 Tcl_ResetResult(interp);
dan4a4c11a2009-10-06 14:59:02 +00002428 }
2429 }else if( rc==TCL_BREAK || rc==TCL_OK ){
drhedc40242016-06-13 12:34:38 +00002430 pResult = Tcl_NewBooleanObj(rc==TCL_OK);
dan4a4c11a2009-10-06 14:59:02 +00002431 }
2432 dbEvalFinalize(&sEval);
drhedc40242016-06-13 12:34:38 +00002433 if( pResult ) Tcl_SetObjResult(interp, pResult);
dan4a4c11a2009-10-06 14:59:02 +00002434
2435 if( rc==TCL_BREAK ){
2436 rc = TCL_OK;
2437 }
2438 break;
2439 }
mistachkinb56660f2016-07-14 21:26:09 +00002440
drh75897232000-05-29 14:26:00 +00002441 /*
drh895d7472004-08-20 16:02:39 +00002442 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002443 **
2444 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002445 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002446 ** If "array" and "code" are omitted, then no callback is every invoked.
2447 ** If "array" is an empty string, then the values are placed in variables
2448 ** that have the same name as the fields extracted by the query.
2449 */
dan4a4c11a2009-10-06 14:59:02 +00002450 case DB_EVAL: {
2451 if( objc<3 || objc>5 ){
2452 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2453 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002454 }
dan4a4c11a2009-10-06 14:59:02 +00002455
drh92febd92004-08-20 18:34:20 +00002456 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002457 DbEvalContext sEval;
2458 Tcl_Obj *pRet = Tcl_NewObj();
2459 Tcl_IncrRefCount(pRet);
2460 dbEvalInit(&sEval, pDb, objv[2], 0);
2461 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2462 int i;
2463 int nCol;
2464 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002465 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002466 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002467 }
2468 }
dan4a4c11a2009-10-06 14:59:02 +00002469 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002470 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002471 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002472 rc = TCL_OK;
2473 }
drh1807ce32004-09-07 13:20:35 +00002474 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002475 }else{
mistachkin8e189222015-04-19 21:43:16 +00002476 ClientData cd2[2];
dan4a4c11a2009-10-06 14:59:02 +00002477 DbEvalContext *p;
2478 Tcl_Obj *pArray = 0;
2479 Tcl_Obj *pScript;
2480
2481 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2482 pArray = objv[3];
2483 }
2484 pScript = objv[objc-1];
2485 Tcl_IncrRefCount(pScript);
mistachkinb56660f2016-07-14 21:26:09 +00002486
dan4a4c11a2009-10-06 14:59:02 +00002487 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2488 dbEvalInit(p, pDb, objv[2], pArray);
2489
mistachkin8e189222015-04-19 21:43:16 +00002490 cd2[0] = (void *)p;
2491 cd2[1] = (void *)pScript;
2492 rc = DbEvalNextCmd(cd2, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002493 }
danielk197730ccda12004-05-27 12:11:31 +00002494 break;
2495 }
drhbec3f402000-08-04 13:49:02 +00002496
2497 /*
dan3df30592015-03-13 08:31:54 +00002498 ** $db function NAME [-argcount N] [-deterministic] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002499 **
2500 ** Create a new SQL function called NAME. Whenever that function is
2501 ** called, invoke SCRIPT to evaluate the function.
2502 */
2503 case DB_FUNCTION: {
dan3df30592015-03-13 08:31:54 +00002504 int flags = SQLITE_UTF8;
drhcabb0812002-09-14 13:47:32 +00002505 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002506 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002507 char *zName;
drhe3602be2008-09-09 12:31:33 +00002508 int nArg = -1;
dan3df30592015-03-13 08:31:54 +00002509 int i;
2510 if( objc<4 ){
2511 Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
2512 return TCL_ERROR;
2513 }
2514 for(i=3; i<(objc-1); i++){
2515 const char *z = Tcl_GetString(objv[i]);
drh4f21c4a2008-12-10 22:15:00 +00002516 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002517 if( n>2 && strncmp(z, "-argcount",n)==0 ){
dan3df30592015-03-13 08:31:54 +00002518 if( i==(objc-2) ){
2519 Tcl_AppendResult(interp, "option requires an argument: ", z, 0);
2520 return TCL_ERROR;
2521 }
2522 if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002523 if( nArg<0 ){
2524 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2525 (char*)0);
2526 return TCL_ERROR;
2527 }
dan3df30592015-03-13 08:31:54 +00002528 i++;
2529 }else
2530 if( n>2 && strncmp(z, "-deterministic",n)==0 ){
2531 flags |= SQLITE_DETERMINISTIC;
2532 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002533 Tcl_AppendResult(interp, "bad option \"", z,
dan3df30592015-03-13 08:31:54 +00002534 "\": must be -argcount or -deterministic", 0
2535 );
2536 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002537 }
drhcabb0812002-09-14 13:47:32 +00002538 }
dan3df30592015-03-13 08:31:54 +00002539
2540 pScript = objv[objc-1];
drhcabb0812002-09-14 13:47:32 +00002541 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002542 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002543 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002544 if( pFunc->pScript ){
2545 Tcl_DecrRefCount(pFunc->pScript);
2546 }
2547 pFunc->pScript = pScript;
2548 Tcl_IncrRefCount(pScript);
2549 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
dan3df30592015-03-13 08:31:54 +00002550 rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
danielk1977d8123362004-06-12 09:25:12 +00002551 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002552 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002553 rc = TCL_ERROR;
2554 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002555 }
drhcabb0812002-09-14 13:47:32 +00002556 break;
2557 }
2558
2559 /*
danielk19778cbadb02007-05-03 16:31:26 +00002560 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002561 */
2562 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002563#ifdef SQLITE_OMIT_INCRBLOB
drha198f2b2014-02-07 19:26:13 +00002564 Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
danielk197732a0d8b2007-05-04 19:03:02 +00002565 return TCL_ERROR;
2566#else
danielk19778cbadb02007-05-03 16:31:26 +00002567 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002568 const char *zDb = "main";
2569 const char *zTable;
2570 const char *zColumn;
drhb3f787f2012-09-29 14:45:54 +00002571 Tcl_WideInt iRow;
danielk1977b4e9af92007-05-01 17:49:49 +00002572
danielk19778cbadb02007-05-03 16:31:26 +00002573 /* Check for the -readonly option */
2574 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2575 isReadonly = 1;
2576 }
2577
2578 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2579 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002580 return TCL_ERROR;
2581 }
2582
danielk19778cbadb02007-05-03 16:31:26 +00002583 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002584 zDb = Tcl_GetString(objv[2]);
2585 }
2586 zTable = Tcl_GetString(objv[objc-3]);
2587 zColumn = Tcl_GetString(objv[objc-2]);
2588 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2589
2590 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002591 rc = createIncrblobChannel(
danedf5b162014-08-19 09:15:41 +00002592 interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
danielk19778cbadb02007-05-03 16:31:26 +00002593 );
danielk1977b4e9af92007-05-01 17:49:49 +00002594 }
danielk197732a0d8b2007-05-04 19:03:02 +00002595#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002596 break;
2597 }
2598
2599 /*
drhf11bded2006-07-17 00:02:44 +00002600 ** $db interrupt
2601 **
2602 ** Interrupt the execution of the inner-most SQL interpreter. This
2603 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2604 */
2605 case DB_INTERRUPT: {
2606 sqlite3_interrupt(pDb->db);
2607 break;
2608 }
2609
2610 /*
drh19e2d372005-08-29 23:00:03 +00002611 ** $db nullvalue ?STRING?
2612 **
2613 ** Change text used when a NULL comes back from the database. If ?STRING?
2614 ** is not present, then the current string used for NULL is returned.
2615 ** If STRING is present, then STRING is returned.
2616 **
2617 */
2618 case DB_NULLVALUE: {
2619 if( objc!=2 && objc!=3 ){
2620 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2621 return TCL_ERROR;
2622 }
2623 if( objc==3 ){
2624 int len;
2625 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2626 if( pDb->zNull ){
2627 Tcl_Free(pDb->zNull);
2628 }
2629 if( zNull && len>0 ){
2630 pDb->zNull = Tcl_Alloc( len + 1 );
drh7fd33922011-06-20 19:00:30 +00002631 memcpy(pDb->zNull, zNull, len);
drh19e2d372005-08-29 23:00:03 +00002632 pDb->zNull[len] = '\0';
2633 }else{
2634 pDb->zNull = 0;
2635 }
2636 }
drhc45e6712012-10-03 11:02:33 +00002637 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
drh19e2d372005-08-29 23:00:03 +00002638 break;
2639 }
2640
2641 /*
mistachkinb56660f2016-07-14 21:26:09 +00002642 ** $db last_insert_rowid
drhaf9ff332002-01-16 21:00:27 +00002643 **
2644 ** Return an integer which is the ROWID for the most recent insert.
2645 */
2646 case DB_LAST_INSERT_ROWID: {
2647 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002648 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002649 if( objc!=2 ){
2650 Tcl_WrongNumArgs(interp, 2, objv, "");
2651 return TCL_ERROR;
2652 }
danielk19776f8a5032004-05-10 10:34:51 +00002653 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002654 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002655 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002656 break;
2657 }
2658
2659 /*
dan4a4c11a2009-10-06 14:59:02 +00002660 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002661 */
drh1807ce32004-09-07 13:20:35 +00002662
2663 /* $db progress ?N CALLBACK?
mistachkinb56660f2016-07-14 21:26:09 +00002664 **
drh1807ce32004-09-07 13:20:35 +00002665 ** Invoke the given callback every N virtual machine opcodes while executing
2666 ** queries.
2667 */
2668 case DB_PROGRESS: {
2669 if( objc==2 ){
2670 if( pDb->zProgress ){
drha198f2b2014-02-07 19:26:13 +00002671 Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
drh1807ce32004-09-07 13:20:35 +00002672 }
2673 }else if( objc==4 ){
2674 char *zProgress;
2675 int len;
2676 int N;
2677 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002678 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002679 };
2680 if( pDb->zProgress ){
2681 Tcl_Free(pDb->zProgress);
2682 }
2683 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2684 if( zProgress && len>0 ){
2685 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002686 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002687 }else{
2688 pDb->zProgress = 0;
2689 }
2690#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2691 if( pDb->zProgress ){
2692 pDb->interp = interp;
2693 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2694 }else{
2695 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2696 }
2697#endif
2698 }else{
2699 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002700 return TCL_ERROR;
2701 }
drh5d9d7572003-08-19 14:31:01 +00002702 break;
2703 }
2704
drh19e2d372005-08-29 23:00:03 +00002705 /* $db profile ?CALLBACK?
2706 **
2707 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2708 ** that has run. The text of the SQL and the amount of elapse time are
2709 ** appended to CALLBACK before the script is run.
2710 */
2711 case DB_PROFILE: {
2712 if( objc>3 ){
2713 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2714 return TCL_ERROR;
2715 }else if( objc==2 ){
2716 if( pDb->zProfile ){
drha198f2b2014-02-07 19:26:13 +00002717 Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002718 }
2719 }else{
2720 char *zProfile;
2721 int len;
2722 if( pDb->zProfile ){
2723 Tcl_Free(pDb->zProfile);
2724 }
2725 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2726 if( zProfile && len>0 ){
2727 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002728 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002729 }else{
2730 pDb->zProfile = 0;
2731 }
shanehbb201342011-02-09 19:55:20 +00002732#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh19e2d372005-08-29 23:00:03 +00002733 if( pDb->zProfile ){
2734 pDb->interp = interp;
2735 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2736 }else{
2737 sqlite3_profile(pDb->db, 0, 0);
2738 }
2739#endif
2740 }
2741 break;
2742 }
2743
drh5d9d7572003-08-19 14:31:01 +00002744 /*
drh22fbcb82004-02-01 01:22:50 +00002745 ** $db rekey KEY
2746 **
2747 ** Change the encryption key on the currently open database.
2748 */
2749 case DB_REKEY: {
drh32f57d42016-03-16 01:03:10 +00002750#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh22fbcb82004-02-01 01:22:50 +00002751 int nKey;
2752 void *pKey;
drhb07028f2011-10-14 21:49:18 +00002753#endif
drh22fbcb82004-02-01 01:22:50 +00002754 if( objc!=3 ){
2755 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2756 return TCL_ERROR;
2757 }
drh32f57d42016-03-16 01:03:10 +00002758#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00002759 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh2011d5f2004-07-22 02:40:37 +00002760 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002761 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002762 Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
drh22fbcb82004-02-01 01:22:50 +00002763 rc = TCL_ERROR;
2764 }
2765#endif
2766 break;
2767 }
2768
drhdc2c4912009-02-04 22:46:47 +00002769 /* $db restore ?DATABASE? FILENAME
2770 **
mistachkinb56660f2016-07-14 21:26:09 +00002771 ** Open a database file named FILENAME. Transfer the content
drhdc2c4912009-02-04 22:46:47 +00002772 ** of FILENAME into the local database DATABASE (default: "main").
2773 */
2774 case DB_RESTORE: {
2775 const char *zSrcFile;
2776 const char *zDestDb;
2777 sqlite3 *pSrc;
2778 sqlite3_backup *pBackup;
2779 int nTimeout = 0;
2780
2781 if( objc==3 ){
2782 zDestDb = "main";
2783 zSrcFile = Tcl_GetString(objv[2]);
2784 }else if( objc==4 ){
2785 zDestDb = Tcl_GetString(objv[2]);
2786 zSrcFile = Tcl_GetString(objv[3]);
2787 }else{
2788 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2789 return TCL_ERROR;
2790 }
drh147ef392016-01-22 23:17:51 +00002791 rc = sqlite3_open_v2(zSrcFile, &pSrc,
2792 SQLITE_OPEN_READONLY | pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00002793 if( rc!=SQLITE_OK ){
2794 Tcl_AppendResult(interp, "cannot open source database: ",
2795 sqlite3_errmsg(pSrc), (char*)0);
2796 sqlite3_close(pSrc);
2797 return TCL_ERROR;
2798 }
2799 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2800 if( pBackup==0 ){
2801 Tcl_AppendResult(interp, "restore failed: ",
2802 sqlite3_errmsg(pDb->db), (char*)0);
2803 sqlite3_close(pSrc);
2804 return TCL_ERROR;
2805 }
2806 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2807 || rc==SQLITE_BUSY ){
2808 if( rc==SQLITE_BUSY ){
2809 if( nTimeout++ >= 3 ) break;
2810 sqlite3_sleep(100);
2811 }
2812 }
2813 sqlite3_backup_finish(pBackup);
2814 if( rc==SQLITE_DONE ){
2815 rc = TCL_OK;
2816 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2817 Tcl_AppendResult(interp, "restore failed: source database busy",
2818 (char*)0);
2819 rc = TCL_ERROR;
2820 }else{
2821 Tcl_AppendResult(interp, "restore failed: ",
2822 sqlite3_errmsg(pDb->db), (char*)0);
2823 rc = TCL_ERROR;
2824 }
2825 sqlite3_close(pSrc);
2826 break;
2827 }
2828
drh22fbcb82004-02-01 01:22:50 +00002829 /*
drh3c379b02010-04-07 19:31:59 +00002830 ** $db status (step|sort|autoindex)
drhd1d38482008-10-07 23:46:38 +00002831 **
mistachkinb56660f2016-07-14 21:26:09 +00002832 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
drhd1d38482008-10-07 23:46:38 +00002833 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2834 */
2835 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002836 int v;
2837 const char *zOp;
2838 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00002839 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00002840 return TCL_ERROR;
2841 }
2842 zOp = Tcl_GetString(objv[2]);
2843 if( strcmp(zOp, "step")==0 ){
2844 v = pDb->nStep;
2845 }else if( strcmp(zOp, "sort")==0 ){
2846 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002847 }else if( strcmp(zOp, "autoindex")==0 ){
2848 v = pDb->nIndex;
drhd1d38482008-10-07 23:46:38 +00002849 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002850 Tcl_AppendResult(interp,
2851 "bad argument: should be autoindex, step, or sort",
drhd1d38482008-10-07 23:46:38 +00002852 (char*)0);
2853 return TCL_ERROR;
2854 }
2855 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2856 break;
2857 }
mistachkinb56660f2016-07-14 21:26:09 +00002858
drhd1d38482008-10-07 23:46:38 +00002859 /*
drhbec3f402000-08-04 13:49:02 +00002860 ** $db timeout MILLESECONDS
2861 **
2862 ** Delay for the number of milliseconds specified when a file is locked.
2863 */
drh6d313162000-09-21 13:01:35 +00002864 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002865 int ms;
drh6d313162000-09-21 13:01:35 +00002866 if( objc!=3 ){
2867 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002868 return TCL_ERROR;
2869 }
drh6d313162000-09-21 13:01:35 +00002870 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002871 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002872 break;
drh75897232000-05-29 14:26:00 +00002873 }
mistachkinb56660f2016-07-14 21:26:09 +00002874
danielk197755c45f22005-04-03 23:54:43 +00002875 /*
drh0f14e2e2004-06-29 12:39:08 +00002876 ** $db total_changes
2877 **
mistachkinb56660f2016-07-14 21:26:09 +00002878 ** Return the number of rows that were modified, inserted, or deleted
drh0f14e2e2004-06-29 12:39:08 +00002879 ** since the database handle was created.
2880 */
2881 case DB_TOTAL_CHANGES: {
2882 Tcl_Obj *pResult;
2883 if( objc!=2 ){
2884 Tcl_WrongNumArgs(interp, 2, objv, "");
2885 return TCL_ERROR;
2886 }
2887 pResult = Tcl_GetObjResult(interp);
2888 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2889 break;
2890 }
2891
drhb5a20d32003-04-23 12:25:23 +00002892 /* $db trace ?CALLBACK?
2893 **
2894 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2895 ** that is executed. The text of the SQL is appended to CALLBACK before
2896 ** it is executed.
2897 */
2898 case DB_TRACE: {
2899 if( objc>3 ){
2900 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002901 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002902 }else if( objc==2 ){
2903 if( pDb->zTrace ){
drha198f2b2014-02-07 19:26:13 +00002904 Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
drhb5a20d32003-04-23 12:25:23 +00002905 }
2906 }else{
2907 char *zTrace;
2908 int len;
2909 if( pDb->zTrace ){
2910 Tcl_Free(pDb->zTrace);
2911 }
2912 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2913 if( zTrace && len>0 ){
2914 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002915 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002916 }else{
2917 pDb->zTrace = 0;
2918 }
drh087ec072016-07-25 00:05:56 +00002919#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) \
2920 && !defined(SQLITE_OMIT_DEPRECATED)
drhb5a20d32003-04-23 12:25:23 +00002921 if( pDb->zTrace ){
2922 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002923 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002924 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002925 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002926 }
drh19e2d372005-08-29 23:00:03 +00002927#endif
drhb5a20d32003-04-23 12:25:23 +00002928 }
2929 break;
2930 }
2931
mistachkinb56660f2016-07-14 21:26:09 +00002932 /* $db trace_v2 ?CALLBACK? ?MASK?
2933 **
2934 ** Make arrangements to invoke the CALLBACK routine for each trace event
2935 ** matching the mask that is generated. The parameters are appended to
2936 ** CALLBACK before it is executed.
2937 */
2938 case DB_TRACE_V2: {
2939 if( objc>4 ){
2940 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK? ?MASK?");
2941 return TCL_ERROR;
2942 }else if( objc==2 ){
2943 if( pDb->zTraceV2 ){
2944 Tcl_AppendResult(interp, pDb->zTraceV2, (char*)0);
2945 }
2946 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002947 char *zTraceV2;
2948 int len;
mistachkinb52dcd82016-07-14 23:17:03 +00002949 Tcl_WideInt wMask = 0;
mistachkinb56660f2016-07-14 21:26:09 +00002950 if( objc==4 ){
mistachkinb52dcd82016-07-14 23:17:03 +00002951 static const char *TTYPE_strs[] = {
2952 "statement", "profile", "row", "close", 0
2953 };
2954 enum TTYPE_enum {
2955 TTYPE_STMT, TTYPE_PROFILE, TTYPE_ROW, TTYPE_CLOSE
2956 };
2957 int i;
2958 if( TCL_OK!=Tcl_ListObjLength(interp, objv[3], &len) ){
mistachkinb56660f2016-07-14 21:26:09 +00002959 return TCL_ERROR;
2960 }
mistachkinb52dcd82016-07-14 23:17:03 +00002961 for(i=0; i<len; i++){
2962 Tcl_Obj *pObj;
2963 int ttype;
2964 if( TCL_OK!=Tcl_ListObjIndex(interp, objv[3], i, &pObj) ){
2965 return TCL_ERROR;
2966 }
2967 if( Tcl_GetIndexFromObj(interp, pObj, TTYPE_strs, "trace type",
2968 0, &ttype)!=TCL_OK ){
2969 Tcl_WideInt wType;
2970 Tcl_Obj *pError = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
2971 Tcl_IncrRefCount(pError);
2972 if( TCL_OK==Tcl_GetWideIntFromObj(interp, pObj, &wType) ){
2973 Tcl_DecrRefCount(pError);
2974 wMask |= wType;
2975 }else{
2976 Tcl_SetObjResult(interp, pError);
2977 Tcl_DecrRefCount(pError);
2978 return TCL_ERROR;
2979 }
2980 }else{
2981 switch( (enum TTYPE_enum)ttype ){
2982 case TTYPE_STMT: wMask |= SQLITE_TRACE_STMT; break;
2983 case TTYPE_PROFILE: wMask |= SQLITE_TRACE_PROFILE; break;
2984 case TTYPE_ROW: wMask |= SQLITE_TRACE_ROW; break;
2985 case TTYPE_CLOSE: wMask |= SQLITE_TRACE_CLOSE; break;
2986 }
2987 }
2988 }
mistachkinb56660f2016-07-14 21:26:09 +00002989 }else{
mistachkinb52dcd82016-07-14 23:17:03 +00002990 wMask = SQLITE_TRACE_STMT; /* use the "legacy" default */
mistachkinb56660f2016-07-14 21:26:09 +00002991 }
2992 if( pDb->zTraceV2 ){
2993 Tcl_Free(pDb->zTraceV2);
2994 }
2995 zTraceV2 = Tcl_GetStringFromObj(objv[2], &len);
2996 if( zTraceV2 && len>0 ){
2997 pDb->zTraceV2 = Tcl_Alloc( len + 1 );
2998 memcpy(pDb->zTraceV2, zTraceV2, len+1);
2999 }else{
3000 pDb->zTraceV2 = 0;
3001 }
3002#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3003 if( pDb->zTraceV2 ){
3004 pDb->interp = interp;
3005 sqlite3_trace_v2(pDb->db, (unsigned)wMask, DbTraceV2Handler, pDb);
3006 }else{
3007 sqlite3_trace_v2(pDb->db, 0, 0, 0);
3008 }
3009#endif
3010 }
3011 break;
3012 }
3013
drh3d214232005-08-02 12:21:08 +00003014 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
3015 **
3016 ** Start a new transaction (if we are not already in the midst of a
3017 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
3018 ** completes, either commit the transaction or roll it back if SCRIPT
3019 ** throws an exception. Or if no new transation was started, do nothing.
3020 ** pass the exception on up the stack.
3021 **
3022 ** This command was inspired by Dave Thomas's talk on Ruby at the
3023 ** 2005 O'Reilly Open Source Convention (OSCON).
3024 */
3025 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00003026 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00003027 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00003028 if( objc!=3 && objc!=4 ){
3029 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
3030 return TCL_ERROR;
3031 }
danielk1977cd38d522009-01-02 17:33:46 +00003032
dan4a4c11a2009-10-06 14:59:02 +00003033 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00003034 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00003035 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00003036 };
3037 enum TTYPE_enum {
3038 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
3039 };
3040 int ttype;
drhb5555e72005-08-02 17:15:14 +00003041 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00003042 0, &ttype) ){
3043 return TCL_ERROR;
3044 }
3045 switch( (enum TTYPE_enum)ttype ){
3046 case TTYPE_DEFERRED: /* no-op */; break;
3047 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
3048 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
3049 }
drh3d214232005-08-02 12:21:08 +00003050 }
danielk1977cd38d522009-01-02 17:33:46 +00003051 pScript = objv[objc-1];
3052
dan4a4c11a2009-10-06 14:59:02 +00003053 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00003054 pDb->disableAuth++;
3055 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
3056 pDb->disableAuth--;
3057 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00003058 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977cd38d522009-01-02 17:33:46 +00003059 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00003060 }
danielk1977cd38d522009-01-02 17:33:46 +00003061 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00003062
dan4a4c11a2009-10-06 14:59:02 +00003063 /* If using NRE, schedule a callback to invoke the script pScript, then
3064 ** a second callback to commit (or rollback) the transaction or savepoint
3065 ** opened above. If not using NRE, evaluate the script directly, then
mistachkinb56660f2016-07-14 21:26:09 +00003066 ** call function DbTransPostCmd() to commit (or rollback) the transaction
dan4a4c11a2009-10-06 14:59:02 +00003067 ** or savepoint. */
3068 if( DbUseNre() ){
3069 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
drha47941f2013-12-20 18:57:44 +00003070 (void)Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00003071 }else{
dan4a4c11a2009-10-06 14:59:02 +00003072 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00003073 }
3074 break;
3075 }
3076
danielk197794eb6a12005-12-15 15:22:08 +00003077 /*
danielk1977404ca072009-03-16 13:19:36 +00003078 ** $db unlock_notify ?script?
3079 */
3080 case DB_UNLOCK_NOTIFY: {
3081#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
drha198f2b2014-02-07 19:26:13 +00003082 Tcl_AppendResult(interp, "unlock_notify not available in this build",
3083 (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00003084 rc = TCL_ERROR;
3085#else
3086 if( objc!=2 && objc!=3 ){
3087 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3088 rc = TCL_ERROR;
3089 }else{
3090 void (*xNotify)(void **, int) = 0;
3091 void *pNotifyArg = 0;
3092
3093 if( pDb->pUnlockNotify ){
3094 Tcl_DecrRefCount(pDb->pUnlockNotify);
3095 pDb->pUnlockNotify = 0;
3096 }
mistachkinb56660f2016-07-14 21:26:09 +00003097
danielk1977404ca072009-03-16 13:19:36 +00003098 if( objc==3 ){
3099 xNotify = DbUnlockNotify;
3100 pNotifyArg = (void *)pDb;
3101 pDb->pUnlockNotify = objv[2];
3102 Tcl_IncrRefCount(pDb->pUnlockNotify);
3103 }
mistachkinb56660f2016-07-14 21:26:09 +00003104
danielk1977404ca072009-03-16 13:19:36 +00003105 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
drha198f2b2014-02-07 19:26:13 +00003106 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00003107 rc = TCL_ERROR;
3108 }
3109 }
3110#endif
3111 break;
3112 }
3113
drh304637c2011-03-18 16:47:27 +00003114 /*
3115 ** $db preupdate_hook count
3116 ** $db preupdate_hook hook ?SCRIPT?
3117 ** $db preupdate_hook new INDEX
3118 ** $db preupdate_hook old INDEX
3119 */
dan46c47d42011-03-01 18:42:07 +00003120 case DB_PREUPDATE: {
drh9b1c62d2011-03-30 21:04:43 +00003121#ifndef SQLITE_ENABLE_PREUPDATE_HOOK
3122 Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time");
3123 rc = TCL_ERROR;
3124#else
dan1e7a2d42011-03-22 18:45:29 +00003125 static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
dan46c47d42011-03-01 18:42:07 +00003126 enum DbPreupdateSubCmd {
dan1e7a2d42011-03-22 18:45:29 +00003127 PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
dan46c47d42011-03-01 18:42:07 +00003128 };
3129 int iSub;
3130
3131 if( objc<3 ){
3132 Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
3133 }
3134 if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
3135 return TCL_ERROR;
3136 }
3137
3138 switch( (enum DbPreupdateSubCmd)iSub ){
3139 case PRE_COUNT: {
3140 int nCol = sqlite3_preupdate_count(pDb->db);
3141 Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
3142 break;
3143 }
3144
3145 case PRE_HOOK: {
3146 if( objc>4 ){
3147 Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
3148 return TCL_ERROR;
3149 }
3150 DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
3151 break;
3152 }
3153
dan1e7a2d42011-03-22 18:45:29 +00003154 case PRE_DEPTH: {
3155 Tcl_Obj *pRet;
3156 if( objc!=3 ){
3157 Tcl_WrongNumArgs(interp, 3, objv, "");
3158 return TCL_ERROR;
3159 }
3160 pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
3161 Tcl_SetObjResult(interp, pRet);
3162 break;
3163 }
3164
dan37db03b2011-03-16 19:59:18 +00003165 case PRE_NEW:
dan46c47d42011-03-01 18:42:07 +00003166 case PRE_OLD: {
3167 int iIdx;
dan37db03b2011-03-16 19:59:18 +00003168 sqlite3_value *pValue;
dan46c47d42011-03-01 18:42:07 +00003169 if( objc!=4 ){
3170 Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
3171 return TCL_ERROR;
3172 }
3173 if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
3174 return TCL_ERROR;
3175 }
3176
dan37db03b2011-03-16 19:59:18 +00003177 if( iSub==PRE_OLD ){
dan46c47d42011-03-01 18:42:07 +00003178 rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
dan37db03b2011-03-16 19:59:18 +00003179 }else{
3180 assert( iSub==PRE_NEW );
3181 rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
dan46c47d42011-03-01 18:42:07 +00003182 }
3183
dan37db03b2011-03-16 19:59:18 +00003184 if( rc==SQLITE_OK ){
drh304637c2011-03-18 16:47:27 +00003185 Tcl_Obj *pObj;
3186 pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
dan37db03b2011-03-16 19:59:18 +00003187 Tcl_SetObjResult(interp, pObj);
3188 }else{
dan46c47d42011-03-01 18:42:07 +00003189 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
3190 return TCL_ERROR;
3191 }
3192 }
3193 }
drh9b1c62d2011-03-30 21:04:43 +00003194#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +00003195 break;
3196 }
3197
danielk1977404ca072009-03-16 13:19:36 +00003198 /*
drh833bf962010-04-28 14:42:19 +00003199 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003200 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00003201 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003202 */
mistachkinb56660f2016-07-14 21:26:09 +00003203 case DB_WAL_HOOK:
3204 case DB_UPDATE_HOOK:
dan6566ebe2011-03-16 09:49:14 +00003205 case DB_ROLLBACK_HOOK: {
mistachkinb56660f2016-07-14 21:26:09 +00003206 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
danielk197771fd80b2005-12-16 06:54:01 +00003207 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3208 */
mistachkinb56660f2016-07-14 21:26:09 +00003209 Tcl_Obj **ppHook = 0;
dan46c47d42011-03-01 18:42:07 +00003210 if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
3211 if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
3212 if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
3213 if( objc>3 ){
danielk197794eb6a12005-12-15 15:22:08 +00003214 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3215 return TCL_ERROR;
3216 }
danielk197771fd80b2005-12-16 06:54:01 +00003217
dan46c47d42011-03-01 18:42:07 +00003218 DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00003219 break;
3220 }
3221
danielk19774397de52005-01-12 12:44:03 +00003222 /* $db version
3223 **
3224 ** Return the version string for this database.
3225 */
3226 case DB_VERSION: {
3227 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
3228 break;
3229 }
3230
tpoindex1067fe12004-12-17 15:41:11 +00003231
drh6d313162000-09-21 13:01:35 +00003232 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00003233 return rc;
drh75897232000-05-29 14:26:00 +00003234}
3235
drha2c8a952009-10-13 18:38:34 +00003236#if SQLITE_TCL_NRE
3237/*
3238** Adaptor that provides an objCmd interface to the NRE-enabled
3239** interface implementation.
3240*/
3241static int DbObjCmdAdaptor(
3242 void *cd,
3243 Tcl_Interp *interp,
3244 int objc,
3245 Tcl_Obj *const*objv
3246){
3247 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
3248}
3249#endif /* SQLITE_TCL_NRE */
3250
drh75897232000-05-29 14:26:00 +00003251/*
drh3570ad92007-08-31 14:31:44 +00003252** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00003253** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00003254**
3255** This is the main Tcl command. When the "sqlite" Tcl command is
3256** invoked, this routine runs to process that command.
3257**
3258** The first argument, DBNAME, is an arbitrary name for a new
3259** database connection. This command creates a new command named
3260** DBNAME that is used to control that connection. The database
3261** connection is deleted when the DBNAME command is deleted.
3262**
drh3570ad92007-08-31 14:31:44 +00003263** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00003264**
drh75897232000-05-29 14:26:00 +00003265*/
drh22fbcb82004-02-01 01:22:50 +00003266static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00003267 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00003268 const char *zArg;
drh75897232000-05-29 14:26:00 +00003269 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00003270 int i;
drh22fbcb82004-02-01 01:22:50 +00003271 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00003272 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00003273 int flags;
drh882e8e42006-08-24 02:42:27 +00003274 Tcl_DString translatedFilename;
drh32f57d42016-03-16 01:03:10 +00003275#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00003276 void *pKey = 0;
3277 int nKey = 0;
3278#endif
mistachkin540ebf82012-09-10 07:29:29 +00003279 int rc;
drhd9da78a2009-03-24 15:08:09 +00003280
3281 /* In normal use, each TCL interpreter runs in a single thread. So
3282 ** by default, we can turn of mutexing on SQLite database connections.
3283 ** However, for testing purposes it is useful to have mutexes turned
3284 ** on. So, by default, mutexes default off. But if compiled with
3285 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3286 */
3287#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3288 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3289#else
3290 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3291#endif
3292
drh22fbcb82004-02-01 01:22:50 +00003293 if( objc==2 ){
3294 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00003295 if( strcmp(zArg,"-version")==0 ){
drha198f2b2014-02-07 19:26:13 +00003296 Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
drh647cb0e2002-11-04 19:32:25 +00003297 return TCL_OK;
3298 }
drh72bf6a32016-01-07 02:06:55 +00003299 if( strcmp(zArg,"-sourceid")==0 ){
3300 Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0);
3301 return TCL_OK;
3302 }
drh9eb9e262004-02-11 02:18:05 +00003303 if( strcmp(zArg,"-has-codec")==0 ){
drh32f57d42016-03-16 01:03:10 +00003304#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drha198f2b2014-02-07 19:26:13 +00003305 Tcl_AppendResult(interp,"1",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003306#else
drha198f2b2014-02-07 19:26:13 +00003307 Tcl_AppendResult(interp,"0",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003308#endif
3309 return TCL_OK;
3310 }
drhfbc3eab2001-04-06 16:13:42 +00003311 }
drh3570ad92007-08-31 14:31:44 +00003312 for(i=3; i+1<objc; i+=2){
3313 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00003314 if( strcmp(zArg,"-key")==0 ){
drh32f57d42016-03-16 01:03:10 +00003315#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh3570ad92007-08-31 14:31:44 +00003316 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
drhb07028f2011-10-14 21:49:18 +00003317#endif
drh3570ad92007-08-31 14:31:44 +00003318 }else if( strcmp(zArg, "-vfs")==0 ){
dan3c3dd7b2010-06-22 11:10:40 +00003319 zVfs = Tcl_GetString(objv[i+1]);
drh3570ad92007-08-31 14:31:44 +00003320 }else if( strcmp(zArg, "-readonly")==0 ){
3321 int b;
3322 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3323 if( b ){
drh33f4e022007-09-03 15:19:34 +00003324 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00003325 flags |= SQLITE_OPEN_READONLY;
3326 }else{
3327 flags &= ~SQLITE_OPEN_READONLY;
3328 flags |= SQLITE_OPEN_READWRITE;
3329 }
3330 }else if( strcmp(zArg, "-create")==0 ){
3331 int b;
3332 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00003333 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00003334 flags |= SQLITE_OPEN_CREATE;
3335 }else{
3336 flags &= ~SQLITE_OPEN_CREATE;
3337 }
danielk19779a6284c2008-07-10 17:52:49 +00003338 }else if( strcmp(zArg, "-nomutex")==0 ){
3339 int b;
3340 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3341 if( b ){
3342 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00003343 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00003344 }else{
3345 flags &= ~SQLITE_OPEN_NOMUTEX;
3346 }
danc431fd52011-06-27 16:55:50 +00003347 }else if( strcmp(zArg, "-fullmutex")==0 ){
drh039963a2008-09-03 00:43:15 +00003348 int b;
3349 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3350 if( b ){
3351 flags |= SQLITE_OPEN_FULLMUTEX;
3352 flags &= ~SQLITE_OPEN_NOMUTEX;
3353 }else{
3354 flags &= ~SQLITE_OPEN_FULLMUTEX;
3355 }
drhf12b3f62011-12-21 14:42:29 +00003356 }else if( strcmp(zArg, "-uri")==0 ){
3357 int b;
3358 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3359 if( b ){
3360 flags |= SQLITE_OPEN_URI;
3361 }else{
3362 flags &= ~SQLITE_OPEN_URI;
3363 }
drh3570ad92007-08-31 14:31:44 +00003364 }else{
3365 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3366 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00003367 }
3368 }
drh3570ad92007-08-31 14:31:44 +00003369 if( objc<3 || (objc&1)!=1 ){
mistachkinb56660f2016-07-14 21:26:09 +00003370 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00003371 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh68bd4aa2012-01-13 16:16:10 +00003372 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
drh32f57d42016-03-16 01:03:10 +00003373#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh3570ad92007-08-31 14:31:44 +00003374 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00003375#endif
3376 );
drh75897232000-05-29 14:26:00 +00003377 return TCL_ERROR;
3378 }
drh75897232000-05-29 14:26:00 +00003379 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003380 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00003381 if( p==0 ){
mistachkin6ef5e122014-01-24 17:03:55 +00003382 Tcl_SetResult(interp, (char *)"malloc failed", TCL_STATIC);
drhbec3f402000-08-04 13:49:02 +00003383 return TCL_ERROR;
3384 }
3385 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00003386 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00003387 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003388 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00003389 Tcl_DStringFree(&translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003390 if( p->db ){
3391 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3392 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3393 sqlite3_close(p->db);
3394 p->db = 0;
3395 }
3396 }else{
mistachkin5dac8432012-09-11 02:00:25 +00003397 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
danielk197780290862004-05-22 09:21:21 +00003398 }
drh32f57d42016-03-16 01:03:10 +00003399#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhf3a65f72007-08-22 20:18:21 +00003400 if( p->db ){
3401 sqlite3_key(p->db, pKey, nKey);
3402 }
drheb8ed702004-02-11 10:37:23 +00003403#endif
drhbec3f402000-08-04 13:49:02 +00003404 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003405 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003406 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003407 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003408 return TCL_ERROR;
3409 }
drhfb7e7652005-01-24 00:28:42 +00003410 p->maxStmt = NUM_PREPARED_STMTS;
drh147ef392016-01-22 23:17:51 +00003411 p->openFlags = flags & SQLITE_OPEN_URI;
drh5169bbc2006-08-24 14:59:45 +00003412 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003413 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003414 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003415 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3416 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003417 }else{
3418 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3419 }
drh75897232000-05-29 14:26:00 +00003420 return TCL_OK;
3421}
3422
3423/*
drh90ca9752001-09-28 17:47:14 +00003424** Provide a dummy Tcl_InitStubs if we are using this as a static
3425** library.
3426*/
3427#ifndef USE_TCL_STUBS
3428# undef Tcl_InitStubs
drh0e85ccf2013-06-03 12:34:46 +00003429# define Tcl_InitStubs(a,b,c) TCL_VERSION
drh90ca9752001-09-28 17:47:14 +00003430#endif
3431
3432/*
drh29bc4612005-10-05 10:40:15 +00003433** Make sure we have a PACKAGE_VERSION macro defined. This will be
3434** defined automatically by the TEA makefile. But other makefiles
3435** do not define it.
3436*/
3437#ifndef PACKAGE_VERSION
3438# define PACKAGE_VERSION SQLITE_VERSION
3439#endif
3440
3441/*
drh75897232000-05-29 14:26:00 +00003442** Initialize this module.
3443**
3444** This Tcl module contains only a single new Tcl command named "sqlite".
3445** (Hence there is no namespace. There is no point in using a namespace
3446** if the extension only supplies one new name!) The "sqlite" command is
3447** used to open a new SQLite database. See the DbMain() routine above
3448** for additional information.
drhb652f432010-08-26 16:46:57 +00003449**
3450** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003451*/
drhb652f432010-08-26 16:46:57 +00003452EXTERN int Sqlite3_Init(Tcl_Interp *interp){
mistachkin27b2f052015-01-12 19:49:46 +00003453 int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
drh6dc8cbe2013-05-31 15:36:07 +00003454 if( rc==TCL_OK ){
3455 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh1cca0d22010-08-25 20:35:51 +00003456#ifndef SQLITE_3_SUFFIX_ONLY
drh6dc8cbe2013-05-31 15:36:07 +00003457 /* The "sqlite" alias is undocumented. It is here only to support
3458 ** legacy scripts. All new scripts should use only the "sqlite3"
3459 ** command. */
3460 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003461#endif
drh6dc8cbe2013-05-31 15:36:07 +00003462 rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3463 }
3464 return rc;
drh90ca9752001-09-28 17:47:14 +00003465}
drhb652f432010-08-26 16:46:57 +00003466EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
drhb652f432010-08-26 16:46:57 +00003467EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3468EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00003469
drhd878cab2012-03-20 15:10:42 +00003470/* Because it accesses the file-system and uses persistent state, SQLite
drhe75a9eb2016-02-13 18:54:10 +00003471** is not considered appropriate for safe interpreters. Hence, we cause
3472** the _SafeInit() interfaces return TCL_ERROR.
drhd878cab2012-03-20 15:10:42 +00003473*/
drhe75a9eb2016-02-13 18:54:10 +00003474EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
3475EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
3476
3477
drh49766d62005-01-08 18:42:28 +00003478
3479#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003480int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3481int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
dana3e63c42010-08-20 12:33:59 +00003482int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3483int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00003484#endif
drh75897232000-05-29 14:26:00 +00003485
drh3e27c022004-07-23 00:01:38 +00003486#ifdef TCLSH
3487/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003488** All of the code that follows is used to build standalone TCL interpreters
3489** that are statically linked with SQLite. Enable these by compiling
3490** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3491** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3492** analysis program.
drh75897232000-05-29 14:26:00 +00003493*/
drh348784e2000-05-29 20:41:49 +00003494
drh57a02272009-10-22 20:52:05 +00003495#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3496/*
3497 * This code implements the MD5 message-digest algorithm.
3498 * The algorithm is due to Ron Rivest. This code was
3499 * written by Colin Plumb in 1993, no copyright is claimed.
3500 * This code is in the public domain; do with it what you wish.
3501 *
3502 * Equivalent code is available from RSA Data Security, Inc.
3503 * This code has been tested against that, and is equivalent,
3504 * except that you don't need to include two pages of legalese
3505 * with every copy.
3506 *
3507 * To compute the message digest of a chunk of bytes, declare an
3508 * MD5Context structure, pass it to MD5Init, call MD5Update as
3509 * needed on buffers full of bytes, and then call MD5Final, which
3510 * will fill a supplied 16-byte array with the digest.
3511 */
3512
3513/*
3514 * If compiled on a machine that doesn't have a 32-bit integer,
3515 * you just set "uint32" to the appropriate datatype for an
3516 * unsigned 32-bit integer. For example:
3517 *
3518 * cc -Duint32='unsigned long' md5.c
3519 *
3520 */
3521#ifndef uint32
3522# define uint32 unsigned int
3523#endif
3524
3525struct MD5Context {
3526 int isInit;
3527 uint32 buf[4];
3528 uint32 bits[2];
3529 unsigned char in[64];
3530};
3531typedef struct MD5Context MD5Context;
3532
3533/*
3534 * Note: this code is harmless on little-endian machines.
3535 */
3536static void byteReverse (unsigned char *buf, unsigned longs){
3537 uint32 t;
3538 do {
3539 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3540 ((unsigned)buf[1]<<8 | buf[0]);
3541 *(uint32 *)buf = t;
3542 buf += 4;
3543 } while (--longs);
3544}
3545/* The four core functions - F1 is optimized somewhat */
3546
3547/* #define F1(x, y, z) (x & y | ~x & z) */
3548#define F1(x, y, z) (z ^ (x & (y ^ z)))
3549#define F2(x, y, z) F1(z, x, y)
3550#define F3(x, y, z) (x ^ y ^ z)
3551#define F4(x, y, z) (y ^ (x | ~z))
3552
3553/* This is the central step in the MD5 algorithm. */
3554#define MD5STEP(f, w, x, y, z, data, s) \
3555 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3556
3557/*
3558 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3559 * reflect the addition of 16 longwords of new data. MD5Update blocks
3560 * the data and converts bytes into longwords for this routine.
3561 */
3562static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3563 register uint32 a, b, c, d;
3564
3565 a = buf[0];
3566 b = buf[1];
3567 c = buf[2];
3568 d = buf[3];
3569
3570 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3571 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3572 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3573 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3574 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3575 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3576 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3577 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3578 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3579 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3580 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3581 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3582 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3583 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3584 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3585 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3586
3587 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3588 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3589 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3590 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3591 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3592 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3593 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3594 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3595 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3596 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3597 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3598 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3599 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3600 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3601 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3602 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3603
3604 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3605 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3606 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3607 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3608 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3609 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3610 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3611 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3612 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3613 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3614 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3615 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3616 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3617 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3618 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3619 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3620
3621 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3622 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3623 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3624 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3625 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3626 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3627 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3628 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3629 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3630 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3631 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3632 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3633 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3634 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3635 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3636 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3637
3638 buf[0] += a;
3639 buf[1] += b;
3640 buf[2] += c;
3641 buf[3] += d;
3642}
3643
3644/*
3645 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3646 * initialization constants.
3647 */
3648static void MD5Init(MD5Context *ctx){
3649 ctx->isInit = 1;
3650 ctx->buf[0] = 0x67452301;
3651 ctx->buf[1] = 0xefcdab89;
3652 ctx->buf[2] = 0x98badcfe;
3653 ctx->buf[3] = 0x10325476;
3654 ctx->bits[0] = 0;
3655 ctx->bits[1] = 0;
3656}
3657
3658/*
3659 * Update context to reflect the concatenation of another buffer full
3660 * of bytes.
3661 */
mistachkinb56660f2016-07-14 21:26:09 +00003662static
drh57a02272009-10-22 20:52:05 +00003663void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3664 uint32 t;
3665
3666 /* Update bitcount */
3667
3668 t = ctx->bits[0];
3669 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3670 ctx->bits[1]++; /* Carry from low to high */
3671 ctx->bits[1] += len >> 29;
3672
3673 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3674
3675 /* Handle any leading odd-sized chunks */
3676
3677 if ( t ) {
3678 unsigned char *p = (unsigned char *)ctx->in + t;
3679
3680 t = 64-t;
3681 if (len < t) {
3682 memcpy(p, buf, len);
3683 return;
3684 }
3685 memcpy(p, buf, t);
3686 byteReverse(ctx->in, 16);
3687 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3688 buf += t;
3689 len -= t;
3690 }
3691
3692 /* Process data in 64-byte chunks */
3693
3694 while (len >= 64) {
3695 memcpy(ctx->in, buf, 64);
3696 byteReverse(ctx->in, 16);
3697 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3698 buf += 64;
3699 len -= 64;
3700 }
3701
3702 /* Handle any remaining bytes of data. */
3703
3704 memcpy(ctx->in, buf, len);
3705}
3706
3707/*
mistachkinb56660f2016-07-14 21:26:09 +00003708 * Final wrapup - pad to 64-byte boundary with the bit pattern
drh57a02272009-10-22 20:52:05 +00003709 * 1 0* (64-bit count of bits processed, MSB-first)
3710 */
3711static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3712 unsigned count;
3713 unsigned char *p;
3714
3715 /* Compute number of bytes mod 64 */
3716 count = (ctx->bits[0] >> 3) & 0x3F;
3717
3718 /* Set the first char of padding to 0x80. This is safe since there is
3719 always at least one byte free */
3720 p = ctx->in + count;
3721 *p++ = 0x80;
3722
3723 /* Bytes of padding needed to make 64 bytes */
3724 count = 64 - 1 - count;
3725
3726 /* Pad out to 56 mod 64 */
3727 if (count < 8) {
3728 /* Two lots of padding: Pad the first block to 64 bytes */
3729 memset(p, 0, count);
3730 byteReverse(ctx->in, 16);
3731 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3732
3733 /* Now fill the next block with 56 bytes */
3734 memset(ctx->in, 0, 56);
3735 } else {
3736 /* Pad block to 56 bytes */
3737 memset(p, 0, count-8);
3738 }
3739 byteReverse(ctx->in, 14);
3740
3741 /* Append length in bits and transform */
drha47941f2013-12-20 18:57:44 +00003742 memcpy(ctx->in + 14*4, ctx->bits, 8);
drh57a02272009-10-22 20:52:05 +00003743
3744 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3745 byteReverse((unsigned char *)ctx->buf, 4);
3746 memcpy(digest, ctx->buf, 16);
drh57a02272009-10-22 20:52:05 +00003747}
3748
3749/*
3750** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3751*/
3752static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3753 static char const zEncode[] = "0123456789abcdef";
3754 int i, j;
3755
3756 for(j=i=0; i<16; i++){
3757 int a = digest[i];
3758 zBuf[j++] = zEncode[(a>>4)&0xf];
3759 zBuf[j++] = zEncode[a & 0xf];
3760 }
3761 zBuf[j] = 0;
3762}
3763
3764
3765/*
3766** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3767** each representing 16 bits of the digest and separated from each
3768** other by a "-" character.
3769*/
3770static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3771 int i, j;
3772 unsigned int x;
3773 for(i=j=0; i<16; i+=2){
3774 x = digest[i]*256 + digest[i+1];
3775 if( i>0 ) zDigest[j++] = '-';
drh05f6c672015-02-26 16:32:33 +00003776 sqlite3_snprintf(50-j, &zDigest[j], "%05u", x);
drh57a02272009-10-22 20:52:05 +00003777 j += 5;
3778 }
3779 zDigest[j] = 0;
3780}
3781
3782/*
3783** A TCL command for md5. The argument is the text to be hashed. The
mistachkinb56660f2016-07-14 21:26:09 +00003784** Result is the hash in base64.
drh57a02272009-10-22 20:52:05 +00003785*/
3786static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3787 MD5Context ctx;
3788 unsigned char digest[16];
3789 char zBuf[50];
3790 void (*converter)(unsigned char*, char*);
3791
3792 if( argc!=2 ){
mistachkinb56660f2016-07-14 21:26:09 +00003793 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
drha198f2b2014-02-07 19:26:13 +00003794 " TEXT\"", (char*)0);
drh57a02272009-10-22 20:52:05 +00003795 return TCL_ERROR;
3796 }
3797 MD5Init(&ctx);
3798 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3799 MD5Final(digest, &ctx);
3800 converter = (void(*)(unsigned char*,char*))cd;
3801 converter(digest, zBuf);
3802 Tcl_AppendResult(interp, zBuf, (char*)0);
3803 return TCL_OK;
3804}
3805
3806/*
3807** A TCL command to take the md5 hash of a file. The argument is the
3808** name of the file.
3809*/
3810static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3811 FILE *in;
3812 MD5Context ctx;
3813 void (*converter)(unsigned char*, char*);
3814 unsigned char digest[16];
3815 char zBuf[10240];
3816
3817 if( argc!=2 ){
mistachkinb56660f2016-07-14 21:26:09 +00003818 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
drha198f2b2014-02-07 19:26:13 +00003819 " FILENAME\"", (char*)0);
drh57a02272009-10-22 20:52:05 +00003820 return TCL_ERROR;
3821 }
3822 in = fopen(argv[1],"rb");
3823 if( in==0 ){
mistachkinb56660f2016-07-14 21:26:09 +00003824 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
drha198f2b2014-02-07 19:26:13 +00003825 "\" for reading", (char*)0);
drh57a02272009-10-22 20:52:05 +00003826 return TCL_ERROR;
3827 }
3828 MD5Init(&ctx);
3829 for(;;){
3830 int n;
drh83cc1392012-04-19 18:04:28 +00003831 n = (int)fread(zBuf, 1, sizeof(zBuf), in);
drh57a02272009-10-22 20:52:05 +00003832 if( n<=0 ) break;
3833 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3834 }
3835 fclose(in);
3836 MD5Final(digest, &ctx);
3837 converter = (void(*)(unsigned char*,char*))cd;
3838 converter(digest, zBuf);
3839 Tcl_AppendResult(interp, zBuf, (char*)0);
3840 return TCL_OK;
3841}
3842
3843/*
3844** Register the four new TCL commands for generating MD5 checksums
3845** with the TCL interpreter.
3846*/
3847int Md5_Init(Tcl_Interp *interp){
3848 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3849 MD5DigestToBase16, 0);
3850 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3851 MD5DigestToBase10x8, 0);
3852 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3853 MD5DigestToBase16, 0);
3854 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3855 MD5DigestToBase10x8, 0);
3856 return TCL_OK;
3857}
3858#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3859
3860#if defined(SQLITE_TEST)
3861/*
3862** During testing, the special md5sum() aggregate function is available.
3863** inside SQLite. The following routines implement that function.
3864*/
3865static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3866 MD5Context *p;
3867 int i;
3868 if( argc<1 ) return;
3869 p = sqlite3_aggregate_context(context, sizeof(*p));
3870 if( p==0 ) return;
3871 if( !p->isInit ){
3872 MD5Init(p);
3873 }
3874 for(i=0; i<argc; i++){
3875 const char *zData = (char*)sqlite3_value_text(argv[i]);
3876 if( zData ){
drh83cc1392012-04-19 18:04:28 +00003877 MD5Update(p, (unsigned char*)zData, (int)strlen(zData));
drh57a02272009-10-22 20:52:05 +00003878 }
3879 }
3880}
3881static void md5finalize(sqlite3_context *context){
3882 MD5Context *p;
3883 unsigned char digest[16];
3884 char zBuf[33];
3885 p = sqlite3_aggregate_context(context, sizeof(*p));
3886 MD5Final(digest,p);
3887 MD5DigestToBase16(digest, zBuf);
3888 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3889}
3890int Md5_Register(sqlite3 *db){
mistachkinb56660f2016-07-14 21:26:09 +00003891 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
drh57a02272009-10-22 20:52:05 +00003892 md5step, md5finalize);
3893 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3894 return rc;
3895}
3896#endif /* defined(SQLITE_TEST) */
3897
3898
drh348784e2000-05-29 20:41:49 +00003899/*
drh3e27c022004-07-23 00:01:38 +00003900** If the macro TCLSH is one, then put in code this for the
3901** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003902** standard input, or if a file is named on the command line
3903** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003904*/
drh3e27c022004-07-23 00:01:38 +00003905#if TCLSH==1
dan0ae479d2011-09-21 16:43:07 +00003906static const char *tclsh_main_loop(void){
3907 static const char zMainloop[] =
3908 "set line {}\n"
3909 "while {![eof stdin]} {\n"
3910 "if {$line!=\"\"} {\n"
3911 "puts -nonewline \"> \"\n"
3912 "} else {\n"
3913 "puts -nonewline \"% \"\n"
drh348784e2000-05-29 20:41:49 +00003914 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003915 "flush stdout\n"
3916 "append line [gets stdin]\n"
3917 "if {[info complete $line]} {\n"
3918 "if {[catch {uplevel #0 $line} result]} {\n"
3919 "puts stderr \"Error: $result\"\n"
3920 "} elseif {$result!=\"\"} {\n"
3921 "puts $result\n"
3922 "}\n"
3923 "set line {}\n"
3924 "} else {\n"
3925 "append line \\n\n"
3926 "}\n"
drh348784e2000-05-29 20:41:49 +00003927 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003928 ;
3929 return zMainloop;
3930}
drh3e27c022004-07-23 00:01:38 +00003931#endif
drh3a0f13f2010-07-12 16:47:48 +00003932#if TCLSH==2
dan0ae479d2011-09-21 16:43:07 +00003933static const char *tclsh_main_loop(void);
drh3a0f13f2010-07-12 16:47:48 +00003934#endif
drh3e27c022004-07-23 00:01:38 +00003935
danc1a60c52010-06-07 14:28:16 +00003936#ifdef SQLITE_TEST
3937static void init_all(Tcl_Interp *);
3938static int init_all_cmd(
3939 ClientData cd,
3940 Tcl_Interp *interp,
3941 int objc,
3942 Tcl_Obj *CONST objv[]
3943){
danielk19770a549072009-02-17 16:29:10 +00003944
danc1a60c52010-06-07 14:28:16 +00003945 Tcl_Interp *slave;
3946 if( objc!=2 ){
3947 Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3948 return TCL_ERROR;
3949 }
3950
3951 slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3952 if( !slave ){
3953 return TCL_ERROR;
3954 }
3955
3956 init_all(slave);
3957 return TCL_OK;
3958}
danc431fd52011-06-27 16:55:50 +00003959
3960/*
3961** Tclcmd: db_use_legacy_prepare DB BOOLEAN
3962**
3963** The first argument to this command must be a database command created by
3964** [sqlite3]. If the second argument is true, then the handle is configured
3965** to use the sqlite3_prepare_v2() function to prepare statements. If it
3966** is false, sqlite3_prepare().
3967*/
3968static int db_use_legacy_prepare_cmd(
3969 ClientData cd,
3970 Tcl_Interp *interp,
3971 int objc,
3972 Tcl_Obj *CONST objv[]
3973){
3974 Tcl_CmdInfo cmdInfo;
3975 SqliteDb *pDb;
3976 int bPrepare;
3977
3978 if( objc!=3 ){
3979 Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
3980 return TCL_ERROR;
3981 }
3982
3983 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3984 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3985 return TCL_ERROR;
3986 }
3987 pDb = (SqliteDb*)cmdInfo.objClientData;
3988 if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
3989 return TCL_ERROR;
3990 }
3991
3992 pDb->bLegacyPrepare = bPrepare;
3993
3994 Tcl_ResetResult(interp);
3995 return TCL_OK;
3996}
dan04489b62014-10-31 20:11:32 +00003997
3998/*
3999** Tclcmd: db_last_stmt_ptr DB
4000**
4001** If the statement cache associated with database DB is not empty,
4002** return the text representation of the most recently used statement
4003** handle.
4004*/
4005static int db_last_stmt_ptr(
4006 ClientData cd,
4007 Tcl_Interp *interp,
4008 int objc,
4009 Tcl_Obj *CONST objv[]
4010){
4011 extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
4012 Tcl_CmdInfo cmdInfo;
4013 SqliteDb *pDb;
4014 sqlite3_stmt *pStmt = 0;
4015 char zBuf[100];
4016
4017 if( objc!=2 ){
4018 Tcl_WrongNumArgs(interp, 1, objv, "DB");
4019 return TCL_ERROR;
4020 }
4021
4022 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
4023 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
4024 return TCL_ERROR;
4025 }
4026 pDb = (SqliteDb*)cmdInfo.objClientData;
4027
4028 if( pDb->stmtList ) pStmt = pDb->stmtList->pStmt;
4029 if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ){
4030 return TCL_ERROR;
4031 }
4032 Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
4033
4034 return TCL_OK;
4035}
drh1a4a6802015-05-04 18:31:09 +00004036#endif /* SQLITE_TEST */
4037
danc1a60c52010-06-07 14:28:16 +00004038/*
4039** Configure the interpreter passed as the first argument to have access
4040** to the commands and linked variables that make up:
4041**
mistachkinb56660f2016-07-14 21:26:09 +00004042** * the [sqlite3] extension itself,
danc1a60c52010-06-07 14:28:16 +00004043**
4044** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
4045**
4046** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
4047** test suite.
4048*/
4049static void init_all(Tcl_Interp *interp){
drh38f82712004-06-18 17:10:16 +00004050 Sqlite3_Init(interp);
danc1a60c52010-06-07 14:28:16 +00004051
drh57a02272009-10-22 20:52:05 +00004052#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
4053 Md5_Init(interp);
4054#endif
danc1a60c52010-06-07 14:28:16 +00004055
drhd9b02572001-04-15 00:37:09 +00004056#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00004057 {
drh2f999a62007-08-15 19:16:43 +00004058 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00004059 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00004060 extern int Sqlitetest2_Init(Tcl_Interp*);
4061 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00004062 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00004063 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00004064 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00004065 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00004066 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00004067 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00004068 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00004069 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
danb391b942014-11-07 14:41:11 +00004070 extern int Sqlitetest_blob_Init(Tcl_Interp*);
dan0a7a9152010-04-07 07:57:38 +00004071 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
drh984bfaa2008-03-19 16:08:53 +00004072 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00004073 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00004074 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00004075 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00004076 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00004077 extern int Sqlitetestschema_Init(Tcl_Interp*);
4078 extern int Sqlitetestsse_Init(Tcl_Interp*);
4079 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
dan9f5ff372013-01-11 09:58:54 +00004080 extern int Sqlitetestfs_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00004081 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00004082 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00004083 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00004084 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh522efc62009-11-10 17:24:37 +00004085 extern int Sqlitetestintarray_Init(Tcl_Interp*);
danc7991bd2010-05-05 19:04:59 +00004086 extern int Sqlitetestvfs_Init(Tcl_Interp *);
dan9508daa2010-08-28 18:58:00 +00004087 extern int Sqlitetestrtree_Init(Tcl_Interp*);
dan8cf35eb2010-09-01 11:40:05 +00004088 extern int Sqlitequota_Init(Tcl_Interp*);
shaneh8a922f72010-11-04 20:50:27 +00004089 extern int Sqlitemultiplex_Init(Tcl_Interp*);
dane336b002010-11-19 18:20:09 +00004090 extern int SqliteSuperlock_Init(Tcl_Interp*);
dan213ca0a2011-03-28 19:10:06 +00004091 extern int SqlitetestSyscall_Init(Tcl_Interp*);
drh9b1c62d2011-03-30 21:04:43 +00004092#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
dan4fccf432011-03-08 19:22:50 +00004093 extern int TestSession_Init(Tcl_Interp*);
4094#endif
dan89a89562014-12-01 20:05:00 +00004095 extern int Fts5tcl_Init(Tcl_Interp *);
drhcfb8f8d2015-07-23 20:44:49 +00004096 extern int SqliteRbu_Init(Tcl_Interp*);
dan8e4251b2016-03-01 18:07:43 +00004097 extern int Sqlitetesttcl_Init(Tcl_Interp*);
dan6764a702011-06-20 11:15:06 +00004098#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00004099 extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
4100#endif
4101
danb29010c2010-12-29 18:24:38 +00004102#ifdef SQLITE_ENABLE_ZIPVFS
4103 extern int Zipvfs_Init(Tcl_Interp*);
4104 Zipvfs_Init(interp);
4105#endif
4106
drh2f999a62007-08-15 19:16:43 +00004107 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00004108 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00004109 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00004110 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00004111 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00004112 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00004113 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00004114 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00004115 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00004116 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00004117 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00004118 Sqlitetest_autoext_Init(interp);
danb391b942014-11-07 14:41:11 +00004119 Sqlitetest_blob_Init(interp);
dan0a7a9152010-04-07 07:57:38 +00004120 Sqlitetest_demovfs_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00004121 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00004122 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00004123 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00004124 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00004125 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00004126 Sqlitetestschema_Init(interp);
4127 Sqlitetesttclvar_Init(interp);
dan9f5ff372013-01-11 09:58:54 +00004128 Sqlitetestfs_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00004129 SqlitetestThread_Init(interp);
mistachkin52b1dbb2016-07-28 14:37:04 +00004130 SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00004131 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00004132 Sqlitetestbackup_Init(interp);
drh522efc62009-11-10 17:24:37 +00004133 Sqlitetestintarray_Init(interp);
danc7991bd2010-05-05 19:04:59 +00004134 Sqlitetestvfs_Init(interp);
dan9508daa2010-08-28 18:58:00 +00004135 Sqlitetestrtree_Init(interp);
dan8cf35eb2010-09-01 11:40:05 +00004136 Sqlitequota_Init(interp);
shaneh8a922f72010-11-04 20:50:27 +00004137 Sqlitemultiplex_Init(interp);
dane336b002010-11-19 18:20:09 +00004138 SqliteSuperlock_Init(interp);
dan213ca0a2011-03-28 19:10:06 +00004139 SqlitetestSyscall_Init(interp);
drh9b1c62d2011-03-30 21:04:43 +00004140#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
dan4fccf432011-03-08 19:22:50 +00004141 TestSession_Init(interp);
4142#endif
dan89a89562014-12-01 20:05:00 +00004143 Fts5tcl_Init(interp);
drhcfb8f8d2015-07-23 20:44:49 +00004144 SqliteRbu_Init(interp);
dan8e4251b2016-03-01 18:07:43 +00004145 Sqlitetesttcl_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00004146
dan6764a702011-06-20 11:15:06 +00004147#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00004148 Sqlitetestfts3_Init(interp);
4149#endif
drh2e66f0b2005-04-28 17:18:48 +00004150
danc431fd52011-06-27 16:55:50 +00004151 Tcl_CreateObjCommand(
4152 interp, "load_testfixture_extensions", init_all_cmd, 0, 0
4153 );
4154 Tcl_CreateObjCommand(
4155 interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
4156 );
dan04489b62014-10-31 20:11:32 +00004157 Tcl_CreateObjCommand(
4158 interp, "db_last_stmt_ptr", db_last_stmt_ptr, 0, 0
4159 );
danc1a60c52010-06-07 14:28:16 +00004160
drh3e27c022004-07-23 00:01:38 +00004161#ifdef SQLITE_SSE
drh348784e2000-05-29 20:41:49 +00004162 Sqlitetestsse_Init(interp);
4163#endif
4164 }
drh61212b62004-12-02 20:17:00 +00004165#endif
danc1a60c52010-06-07 14:28:16 +00004166}
4167
drhdb6bafa2015-01-09 21:54:58 +00004168/* Needed for the setrlimit() system call on unix */
4169#if defined(unix)
4170#include <sys/resource.h>
4171#endif
4172
danc1a60c52010-06-07 14:28:16 +00004173#define TCLSH_MAIN main /* Needed to fake out mktclapp */
mistachkin69def7f2016-07-28 04:14:37 +00004174int SQLITE_CDECL TCLSH_MAIN(int argc, char **argv){
danc1a60c52010-06-07 14:28:16 +00004175 Tcl_Interp *interp;
mistachkin1f28e072013-08-15 08:06:15 +00004176
4177#if !defined(_WIN32_WCE)
4178 if( getenv("BREAK") ){
4179 fprintf(stderr,
4180 "attach debugger to process %d and press any key to continue.\n",
4181 GETPID());
4182 fgetc(stdin);
4183 }
4184#endif
4185
drhdb6bafa2015-01-09 21:54:58 +00004186 /* Since the primary use case for this binary is testing of SQLite,
4187 ** be sure to generate core files if we crash */
4188#if defined(SQLITE_TEST) && defined(unix)
4189 { struct rlimit x;
4190 getrlimit(RLIMIT_CORE, &x);
4191 x.rlim_cur = x.rlim_max;
4192 setrlimit(RLIMIT_CORE, &x);
4193 }
4194#endif /* SQLITE_TEST && unix */
4195
4196
danc1a60c52010-06-07 14:28:16 +00004197 /* Call sqlite3_shutdown() once before doing anything else. This is to
4198 ** test that sqlite3_shutdown() can be safely called by a process before
4199 ** sqlite3_initialize() is. */
4200 sqlite3_shutdown();
4201
dan0ae479d2011-09-21 16:43:07 +00004202 Tcl_FindExecutable(argv[0]);
mistachkin2953ba92014-02-14 00:25:03 +00004203 Tcl_SetSystemEncoding(NULL, "utf-8");
dan0ae479d2011-09-21 16:43:07 +00004204 interp = Tcl_CreateInterp();
4205
drh3a0f13f2010-07-12 16:47:48 +00004206#if TCLSH==2
4207 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
4208#endif
danc1a60c52010-06-07 14:28:16 +00004209
danc1a60c52010-06-07 14:28:16 +00004210 init_all(interp);
drhc7285972009-11-10 01:13:25 +00004211 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00004212 int i;
shessad42c3a2006-08-22 23:53:46 +00004213 char zArgc[32];
4214 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
4215 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00004216 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
4217 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
4218 for(i=3-TCLSH; i<argc; i++){
4219 Tcl_SetVar(interp, "argv", argv[i],
4220 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
4221 }
drh3a0f13f2010-07-12 16:47:48 +00004222 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00004223 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00004224 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00004225 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00004226 return 1;
4227 }
drh3e27c022004-07-23 00:01:38 +00004228 }
drh3a0f13f2010-07-12 16:47:48 +00004229 if( TCLSH==2 || argc<=1 ){
dan0ae479d2011-09-21 16:43:07 +00004230 Tcl_GlobalEval(interp, tclsh_main_loop());
drh348784e2000-05-29 20:41:49 +00004231 }
4232 return 0;
4233}
4234#endif /* TCLSH */