blob: 42dd6b0f492169cf81a7f1de3b0ed6fe4bfcc1fe [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
drhbd08af42007-04-05 21:58:33 +000012** A TCL Interface to SQLite. Append this file to sqlite3.c and
13** compile the whole thing to build a TCL-enabled version of SQLite.
drh57a02272009-10-22 20:52:05 +000014**
15** Compile-time options:
16**
17** -DTCLSH=1 Add a "main()" routine that works as a tclsh.
18**
19** -DSQLITE_TCLMD5 When used in conjuction with -DTCLSH=1, add
20** four new commands to the TCL interpreter for
21** generating MD5 checksums: md5, md5file,
22** md5-10x8, and md5file-10x8.
23**
24** -DSQLITE_TEST When used in conjuction with -DTCLSH=1, add
25** hundreds of new commands used for testing
26** SQLite. This option implies -DSQLITE_TCLMD5.
drh75897232000-05-29 14:26:00 +000027*/
mistachkin27b2f052015-01-12 19:49:46 +000028
29/*
30** If requested, include the SQLite compiler options file for MSVC.
31*/
32#if defined(INCLUDE_MSVC_H)
33#include "msvc.h"
34#endif
35
drh17a68932001-01-31 13:28:08 +000036#include "tcl.h"
danielk1977b4e9af92007-05-01 17:49:49 +000037#include <errno.h>
drhbd08af42007-04-05 21:58:33 +000038
39/*
40** Some additional include files are needed if this file is not
41** appended to the amalgamation.
42*/
43#ifndef SQLITE_AMALGAMATION
drh65e8c822009-12-01 13:57:48 +000044# include "sqlite3.h"
drhbd08af42007-04-05 21:58:33 +000045# include <stdlib.h>
46# include <string.h>
47# include <assert.h>
drh65e8c822009-12-01 13:57:48 +000048 typedef unsigned char u8;
drhbd08af42007-04-05 21:58:33 +000049#endif
drheb206382009-10-24 15:51:33 +000050#include <ctype.h>
drh75897232000-05-29 14:26:00 +000051
mistachkin1f28e072013-08-15 08:06:15 +000052/* Used to get the current process ID */
53#if !defined(_WIN32)
54# include <unistd.h>
55# define GETPID getpid
56#elif !defined(_WIN32_WCE)
57# ifndef SQLITE_AMALGAMATION
58# define WIN32_LEAN_AND_MEAN
59# include <windows.h>
60# endif
61# define GETPID (int)GetCurrentProcessId
62#endif
63
drhad6e1372006-07-10 21:15:51 +000064/*
65 * Windows needs to know which symbols to export. Unix does not.
66 * BUILD_sqlite should be undefined for Unix.
67 */
68#ifdef BUILD_sqlite
69#undef TCL_STORAGE_CLASS
70#define TCL_STORAGE_CLASS DLLEXPORT
71#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000072
danielk1977a21c6b62005-01-24 10:25:59 +000073#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000074#define MAX_PREPARED_STMTS 100
75
drhc45e6712012-10-03 11:02:33 +000076/* Forward declaration */
77typedef struct SqliteDb SqliteDb;
drh98808ba2001-10-18 12:34:46 +000078
79/*
drhcabb0812002-09-14 13:47:32 +000080** New SQL functions can be created as TCL scripts. Each such function
81** is described by an instance of the following structure.
82*/
83typedef struct SqlFunc SqlFunc;
84struct SqlFunc {
85 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000086 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
drhc45e6712012-10-03 11:02:33 +000087 SqliteDb *pDb; /* Database connection that owns this function */
drhd1e47332005-06-26 17:55:33 +000088 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
89 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000090 SqlFunc *pNext; /* Next function on the list of them all */
91};
92
93/*
danielk19770202b292004-06-09 09:55:16 +000094** New collation sequences function can be created as TCL scripts. Each such
95** function is described by an instance of the following structure.
96*/
97typedef struct SqlCollate SqlCollate;
98struct SqlCollate {
99 Tcl_Interp *interp; /* The TCL interpret to execute the function */
100 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +0000101 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +0000102};
103
104/*
drhfb7e7652005-01-24 00:28:42 +0000105** Prepared statements are cached for faster execution. Each prepared
106** statement is described by an instance of the following structure.
107*/
108typedef struct SqlPreparedStmt SqlPreparedStmt;
109struct SqlPreparedStmt {
110 SqlPreparedStmt *pNext; /* Next in linked list */
111 SqlPreparedStmt *pPrev; /* Previous on the list */
112 sqlite3_stmt *pStmt; /* The prepared statement */
113 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +0000114 const char *zSql; /* Text of the SQL statement */
dan4a4c11a2009-10-06 14:59:02 +0000115 int nParm; /* Size of apParm array */
116 Tcl_Obj **apParm; /* Array of referenced object pointers */
drhfb7e7652005-01-24 00:28:42 +0000117};
118
danielk1977d04417962007-05-02 13:16:30 +0000119typedef struct IncrblobChannel IncrblobChannel;
120
drhfb7e7652005-01-24 00:28:42 +0000121/*
drhbec3f402000-08-04 13:49:02 +0000122** There is one instance of this structure for each SQLite database
123** that has been opened by the SQLite TCL interface.
danc431fd52011-06-27 16:55:50 +0000124**
125** If this module is built with SQLITE_TEST defined (to create the SQLite
126** testfixture executable), then it may be configured to use either
127** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
128** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
drhbec3f402000-08-04 13:49:02 +0000129*/
drhbec3f402000-08-04 13:49:02 +0000130struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000131 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000132 Tcl_Interp *interp; /* The interpreter used for this database */
133 char *zBusy; /* The busy callback routine */
134 char *zCommit; /* The commit hook callback routine */
135 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +0000136 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000137 char *zProgress; /* The progress callback routine */
138 char *zAuth; /* The authorization callback routine */
drh1f1549f2008-08-26 21:33:34 +0000139 int disableAuth; /* Disable the authorizer if it exists */
drhd1e47332005-06-26 17:55:33 +0000140 char *zNull; /* Text to substitute for an SQL NULL value */
141 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000142 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000143 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drh5def0842010-05-05 20:00:25 +0000144 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000145 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000146 SqlCollate *pCollate; /* List of SQL collation functions */
147 int rc; /* Return code of most recent sqlite3_exec() */
148 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000149 SqlPreparedStmt *stmtList; /* List of prepared statements*/
150 SqlPreparedStmt *stmtLast; /* Last statement in the list */
151 int maxStmt; /* The next maximum number of stmtList */
152 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000153 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh3c379b02010-04-07 19:31:59 +0000154 int nStep, nSort, nIndex; /* Statistics for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000155 int nTransaction; /* Number of nested [transaction] methods */
drh147ef392016-01-22 23:17:51 +0000156 int openFlags; /* Flags used to open. (SQLITE_OPEN_URI) */
danc431fd52011-06-27 16:55:50 +0000157#ifdef SQLITE_TEST
158 int bLegacyPrepare; /* True to use sqlite3_prepare() */
159#endif
drh98808ba2001-10-18 12:34:46 +0000160};
drh297ecf12001-04-05 15:57:13 +0000161
danielk1977b4e9af92007-05-01 17:49:49 +0000162struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000163 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000164 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000165 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000166 Tcl_Channel channel; /* Channel identifier */
167 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
168 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000169};
170
drhea678832008-12-10 19:26:22 +0000171/*
172** Compute a string length that is limited to what can be stored in
173** lower 30 bits of a 32-bit signed integer.
174*/
drh4f21c4a2008-12-10 22:15:00 +0000175static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000176 const char *z2 = z;
177 while( *z2 ){ z2++; }
178 return 0x3fffffff & (int)(z2 - z);
179}
drhea678832008-12-10 19:26:22 +0000180
181
danielk197732a0d8b2007-05-04 19:03:02 +0000182#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000183/*
danielk1977d04417962007-05-02 13:16:30 +0000184** Close all incrblob channels opened using database connection pDb.
185** This is called when shutting down the database connection.
186*/
187static void closeIncrblobChannels(SqliteDb *pDb){
188 IncrblobChannel *p;
189 IncrblobChannel *pNext;
190
191 for(p=pDb->pIncrblob; p; p=pNext){
192 pNext = p->pNext;
193
194 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
195 ** which deletes the IncrblobChannel structure at *p. So do not
196 ** call Tcl_Free() here.
197 */
198 Tcl_UnregisterChannel(pDb->interp, p->channel);
199 }
200}
201
202/*
danielk1977b4e9af92007-05-01 17:49:49 +0000203** Close an incremental blob channel.
204*/
205static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
206 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000207 int rc = sqlite3_blob_close(p->pBlob);
208 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000209
210 /* Remove the channel from the SqliteDb.pIncrblob list. */
211 if( p->pNext ){
212 p->pNext->pPrev = p->pPrev;
213 }
214 if( p->pPrev ){
215 p->pPrev->pNext = p->pNext;
216 }
217 if( p->pDb->pIncrblob==p ){
218 p->pDb->pIncrblob = p->pNext;
219 }
220
danielk197792d4d7a2007-05-04 12:05:56 +0000221 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000222 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000223
224 if( rc!=SQLITE_OK ){
225 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
226 return TCL_ERROR;
227 }
danielk1977b4e9af92007-05-01 17:49:49 +0000228 return TCL_OK;
229}
230
231/*
232** Read data from an incremental blob channel.
233*/
234static int incrblobInput(
235 ClientData instanceData,
236 char *buf,
237 int bufSize,
238 int *errorCodePtr
239){
240 IncrblobChannel *p = (IncrblobChannel *)instanceData;
241 int nRead = bufSize; /* Number of bytes to read */
242 int nBlob; /* Total size of the blob */
243 int rc; /* sqlite error code */
244
245 nBlob = sqlite3_blob_bytes(p->pBlob);
246 if( (p->iSeek+nRead)>nBlob ){
247 nRead = nBlob-p->iSeek;
248 }
249 if( nRead<=0 ){
250 return 0;
251 }
252
253 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
254 if( rc!=SQLITE_OK ){
255 *errorCodePtr = rc;
256 return -1;
257 }
258
259 p->iSeek += nRead;
260 return nRead;
261}
262
danielk1977d04417962007-05-02 13:16:30 +0000263/*
264** Write data to an incremental blob channel.
265*/
danielk1977b4e9af92007-05-01 17:49:49 +0000266static int incrblobOutput(
267 ClientData instanceData,
268 CONST char *buf,
269 int toWrite,
270 int *errorCodePtr
271){
272 IncrblobChannel *p = (IncrblobChannel *)instanceData;
273 int nWrite = toWrite; /* Number of bytes to write */
274 int nBlob; /* Total size of the blob */
275 int rc; /* sqlite error code */
276
277 nBlob = sqlite3_blob_bytes(p->pBlob);
278 if( (p->iSeek+nWrite)>nBlob ){
279 *errorCodePtr = EINVAL;
280 return -1;
281 }
282 if( nWrite<=0 ){
283 return 0;
284 }
285
286 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
287 if( rc!=SQLITE_OK ){
288 *errorCodePtr = EIO;
289 return -1;
290 }
291
292 p->iSeek += nWrite;
293 return nWrite;
294}
295
296/*
297** Seek an incremental blob channel.
298*/
299static int incrblobSeek(
300 ClientData instanceData,
301 long offset,
302 int seekMode,
303 int *errorCodePtr
304){
305 IncrblobChannel *p = (IncrblobChannel *)instanceData;
306
307 switch( seekMode ){
308 case SEEK_SET:
309 p->iSeek = offset;
310 break;
311 case SEEK_CUR:
312 p->iSeek += offset;
313 break;
314 case SEEK_END:
315 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
316 break;
317
318 default: assert(!"Bad seekMode");
319 }
320
321 return p->iSeek;
322}
323
324
325static void incrblobWatch(ClientData instanceData, int mode){
326 /* NO-OP */
327}
328static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
329 return TCL_ERROR;
330}
331
332static Tcl_ChannelType IncrblobChannelType = {
333 "incrblob", /* typeName */
334 TCL_CHANNEL_VERSION_2, /* version */
335 incrblobClose, /* closeProc */
336 incrblobInput, /* inputProc */
337 incrblobOutput, /* outputProc */
338 incrblobSeek, /* seekProc */
339 0, /* setOptionProc */
340 0, /* getOptionProc */
341 incrblobWatch, /* watchProc (this is a no-op) */
342 incrblobHandle, /* getHandleProc (always returns error) */
343 0, /* close2Proc */
344 0, /* blockModeProc */
345 0, /* flushProc */
346 0, /* handlerProc */
347 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000348};
349
350/*
351** Create a new incrblob channel.
352*/
353static int createIncrblobChannel(
354 Tcl_Interp *interp,
355 SqliteDb *pDb,
356 const char *zDb,
357 const char *zTable,
358 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000359 sqlite_int64 iRow,
360 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000361){
362 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000363 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000364 sqlite3_blob *pBlob;
365 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000366 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000367
368 /* This variable is used to name the channels: "incrblob_[incr count]" */
369 static int count = 0;
370 char zChannel[64];
371
danielk19778cbadb02007-05-03 16:31:26 +0000372 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000373 if( rc!=SQLITE_OK ){
374 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
375 return TCL_ERROR;
376 }
377
378 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
379 p->iSeek = 0;
380 p->pBlob = pBlob;
381
drh5bb3eb92007-05-04 13:15:55 +0000382 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000383 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
384 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000385
danielk1977d04417962007-05-02 13:16:30 +0000386 /* Link the new channel into the SqliteDb.pIncrblob list. */
387 p->pNext = pDb->pIncrblob;
388 p->pPrev = 0;
389 if( p->pNext ){
390 p->pNext->pPrev = p;
391 }
392 pDb->pIncrblob = p;
393 p->pDb = pDb;
394
395 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000396 return TCL_OK;
397}
danielk197732a0d8b2007-05-04 19:03:02 +0000398#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
399 #define closeIncrblobChannels(pDb)
400#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000401
drh6d313162000-09-21 13:01:35 +0000402/*
drhd1e47332005-06-26 17:55:33 +0000403** Look at the script prefix in pCmd. We will be executing this script
404** after first appending one or more arguments. This routine analyzes
405** the script to see if it is safe to use Tcl_EvalObjv() on the script
406** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
407** faster.
408**
409** Scripts that are safe to use with Tcl_EvalObjv() consists of a
410** command name followed by zero or more arguments with no [...] or $
411** or {...} or ; to be seen anywhere. Most callback scripts consist
412** of just a single procedure name and they meet this requirement.
413*/
414static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
415 /* We could try to do something with Tcl_Parse(). But we will instead
416 ** just do a search for forbidden characters. If any of the forbidden
417 ** characters appear in pCmd, we will report the string as unsafe.
418 */
419 const char *z;
420 int n;
421 z = Tcl_GetStringFromObj(pCmd, &n);
422 while( n-- > 0 ){
423 int c = *(z++);
424 if( c=='$' || c=='[' || c==';' ) return 0;
425 }
426 return 1;
427}
428
429/*
430** Find an SqlFunc structure with the given name. Or create a new
431** one if an existing one cannot be found. Return a pointer to the
432** structure.
433*/
434static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
435 SqlFunc *p, *pNew;
drh0425f182013-11-26 16:48:04 +0000436 int nName = strlen30(zName);
437 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
drhd1e47332005-06-26 17:55:33 +0000438 pNew->zName = (char*)&pNew[1];
drh0425f182013-11-26 16:48:04 +0000439 memcpy(pNew->zName, zName, nName+1);
drhd1e47332005-06-26 17:55:33 +0000440 for(p=pDb->pFunc; p; p=p->pNext){
drh0425f182013-11-26 16:48:04 +0000441 if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
drhd1e47332005-06-26 17:55:33 +0000442 Tcl_Free((char*)pNew);
443 return p;
444 }
445 }
446 pNew->interp = pDb->interp;
drhc45e6712012-10-03 11:02:33 +0000447 pNew->pDb = pDb;
drhd1e47332005-06-26 17:55:33 +0000448 pNew->pScript = 0;
449 pNew->pNext = pDb->pFunc;
450 pDb->pFunc = pNew;
451 return pNew;
452}
453
454/*
danc431fd52011-06-27 16:55:50 +0000455** Free a single SqlPreparedStmt object.
456*/
457static void dbFreeStmt(SqlPreparedStmt *pStmt){
458#ifdef SQLITE_TEST
459 if( sqlite3_sql(pStmt->pStmt)==0 ){
460 Tcl_Free((char *)pStmt->zSql);
461 }
462#endif
463 sqlite3_finalize(pStmt->pStmt);
464 Tcl_Free((char *)pStmt);
465}
466
467/*
drhfb7e7652005-01-24 00:28:42 +0000468** Finalize and free a list of prepared statements
469*/
danc431fd52011-06-27 16:55:50 +0000470static void flushStmtCache(SqliteDb *pDb){
drhfb7e7652005-01-24 00:28:42 +0000471 SqlPreparedStmt *pPreStmt;
danc431fd52011-06-27 16:55:50 +0000472 SqlPreparedStmt *pNext;
drhfb7e7652005-01-24 00:28:42 +0000473
danc431fd52011-06-27 16:55:50 +0000474 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
475 pNext = pPreStmt->pNext;
476 dbFreeStmt(pPreStmt);
drhfb7e7652005-01-24 00:28:42 +0000477 }
478 pDb->nStmt = 0;
479 pDb->stmtLast = 0;
danc431fd52011-06-27 16:55:50 +0000480 pDb->stmtList = 0;
drhfb7e7652005-01-24 00:28:42 +0000481}
482
483/*
drh895d7472004-08-20 16:02:39 +0000484** TCL calls this procedure when an sqlite3 database command is
485** deleted.
drh75897232000-05-29 14:26:00 +0000486*/
487static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000488 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000489 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000490 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000491 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000492 while( pDb->pFunc ){
493 SqlFunc *pFunc = pDb->pFunc;
494 pDb->pFunc = pFunc->pNext;
drhc45e6712012-10-03 11:02:33 +0000495 assert( pFunc->pDb==pDb );
drhd1e47332005-06-26 17:55:33 +0000496 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000497 Tcl_Free((char*)pFunc);
498 }
danielk19770202b292004-06-09 09:55:16 +0000499 while( pDb->pCollate ){
500 SqlCollate *pCollate = pDb->pCollate;
501 pDb->pCollate = pCollate->pNext;
502 Tcl_Free((char*)pCollate);
503 }
drhbec3f402000-08-04 13:49:02 +0000504 if( pDb->zBusy ){
505 Tcl_Free(pDb->zBusy);
506 }
drhb5a20d32003-04-23 12:25:23 +0000507 if( pDb->zTrace ){
508 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000509 }
drh19e2d372005-08-29 23:00:03 +0000510 if( pDb->zProfile ){
511 Tcl_Free(pDb->zProfile);
512 }
drhe22a3342003-04-22 20:30:37 +0000513 if( pDb->zAuth ){
514 Tcl_Free(pDb->zAuth);
515 }
danielk197755c45f22005-04-03 23:54:43 +0000516 if( pDb->zNull ){
517 Tcl_Free(pDb->zNull);
518 }
danielk197794eb6a12005-12-15 15:22:08 +0000519 if( pDb->pUpdateHook ){
520 Tcl_DecrRefCount(pDb->pUpdateHook);
521 }
danielk197771fd80b2005-12-16 06:54:01 +0000522 if( pDb->pRollbackHook ){
523 Tcl_DecrRefCount(pDb->pRollbackHook);
524 }
drh5def0842010-05-05 20:00:25 +0000525 if( pDb->pWalHook ){
526 Tcl_DecrRefCount(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000527 }
danielk197794eb6a12005-12-15 15:22:08 +0000528 if( pDb->pCollateNeeded ){
529 Tcl_DecrRefCount(pDb->pCollateNeeded);
530 }
drhbec3f402000-08-04 13:49:02 +0000531 Tcl_Free((char*)pDb);
532}
533
534/*
535** This routine is called when a database file is locked while trying
536** to execute SQL.
537*/
danielk19772a764eb2004-06-12 01:43:26 +0000538static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000539 SqliteDb *pDb = (SqliteDb*)cd;
540 int rc;
541 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000542
drh5bb3eb92007-05-04 13:15:55 +0000543 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000544 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000545 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
546 return 0;
547 }
548 return 1;
drh75897232000-05-29 14:26:00 +0000549}
550
drh26e4a8b2008-05-01 17:16:52 +0000551#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000552/*
danielk1977348bb5d2003-10-18 09:37:26 +0000553** This routine is invoked as the 'progress callback' for the database.
554*/
555static int DbProgressHandler(void *cd){
556 SqliteDb *pDb = (SqliteDb*)cd;
557 int rc;
558
559 assert( pDb->zProgress );
560 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
561 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
562 return 1;
563 }
564 return 0;
565}
drh26e4a8b2008-05-01 17:16:52 +0000566#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000567
drhd1167392006-01-23 13:00:35 +0000568#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000569/*
drhb5a20d32003-04-23 12:25:23 +0000570** This routine is called by the SQLite trace handler whenever a new
571** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000572*/
drhb5a20d32003-04-23 12:25:23 +0000573static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000574 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000575 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000576
drhb5a20d32003-04-23 12:25:23 +0000577 Tcl_DStringInit(&str);
578 Tcl_DStringAppend(&str, pDb->zTrace, -1);
579 Tcl_DStringAppendElement(&str, zSql);
580 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
581 Tcl_DStringFree(&str);
582 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000583}
drhd1167392006-01-23 13:00:35 +0000584#endif
drh0d1a6432003-04-03 15:46:04 +0000585
drhd1167392006-01-23 13:00:35 +0000586#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000587/*
drh19e2d372005-08-29 23:00:03 +0000588** This routine is called by the SQLite profile handler after a statement
589** SQL has executed. The TCL script in pDb->zProfile is evaluated.
590*/
591static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
592 SqliteDb *pDb = (SqliteDb*)cd;
593 Tcl_DString str;
594 char zTm[100];
595
596 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
597 Tcl_DStringInit(&str);
598 Tcl_DStringAppend(&str, pDb->zProfile, -1);
599 Tcl_DStringAppendElement(&str, zSql);
600 Tcl_DStringAppendElement(&str, zTm);
601 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
602 Tcl_DStringFree(&str);
603 Tcl_ResetResult(pDb->interp);
604}
drhd1167392006-01-23 13:00:35 +0000605#endif
drh19e2d372005-08-29 23:00:03 +0000606
607/*
drhaa940ea2004-01-15 02:44:03 +0000608** This routine is called when a transaction is committed. The
609** TCL script in pDb->zCommit is executed. If it returns non-zero or
610** if it throws an exception, the transaction is rolled back instead
611** of being committed.
612*/
613static int DbCommitHandler(void *cd){
614 SqliteDb *pDb = (SqliteDb*)cd;
615 int rc;
616
617 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
618 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
619 return 1;
620 }
621 return 0;
622}
623
danielk197771fd80b2005-12-16 06:54:01 +0000624static void DbRollbackHandler(void *clientData){
625 SqliteDb *pDb = (SqliteDb*)clientData;
626 assert(pDb->pRollbackHook);
627 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
628 Tcl_BackgroundError(pDb->interp);
629 }
630}
631
drh5def0842010-05-05 20:00:25 +0000632/*
633** This procedure handles wal_hook callbacks.
634*/
635static int DbWalHandler(
dan8d22a172010-04-19 18:03:51 +0000636 void *clientData,
637 sqlite3 *db,
638 const char *zDb,
639 int nEntry
640){
drh5def0842010-05-05 20:00:25 +0000641 int ret = SQLITE_OK;
dan8d22a172010-04-19 18:03:51 +0000642 Tcl_Obj *p;
643 SqliteDb *pDb = (SqliteDb*)clientData;
644 Tcl_Interp *interp = pDb->interp;
drh5def0842010-05-05 20:00:25 +0000645 assert(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000646
dan6e45e0c2014-12-10 20:29:49 +0000647 assert( db==pDb->db );
drh5def0842010-05-05 20:00:25 +0000648 p = Tcl_DuplicateObj(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000649 Tcl_IncrRefCount(p);
650 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
651 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
652 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
653 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
654 ){
655 Tcl_BackgroundError(interp);
656 }
657 Tcl_DecrRefCount(p);
658
659 return ret;
660}
661
drhbcf4f482009-03-27 12:44:35 +0000662#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000663static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
664 char zBuf[64];
drh65545b52015-01-19 00:35:53 +0000665 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
danielk1977404ca072009-03-16 13:19:36 +0000666 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
drh65545b52015-01-19 00:35:53 +0000667 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
danielk1977404ca072009-03-16 13:19:36 +0000668 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
669}
670#else
drhbcf4f482009-03-27 12:44:35 +0000671# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000672#endif
673
drh69910da2009-03-27 12:32:54 +0000674#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000675static void DbUnlockNotify(void **apArg, int nArg){
676 int i;
677 for(i=0; i<nArg; i++){
678 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
679 SqliteDb *pDb = (SqliteDb *)apArg[i];
680 setTestUnlockNotifyVars(pDb->interp, i, nArg);
681 assert( pDb->pUnlockNotify);
682 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
683 Tcl_DecrRefCount(pDb->pUnlockNotify);
684 pDb->pUnlockNotify = 0;
685 }
686}
drh69910da2009-03-27 12:32:54 +0000687#endif
danielk1977404ca072009-03-16 13:19:36 +0000688
danielk197794eb6a12005-12-15 15:22:08 +0000689static void DbUpdateHandler(
690 void *p,
691 int op,
692 const char *zDb,
693 const char *zTbl,
694 sqlite_int64 rowid
695){
696 SqliteDb *pDb = (SqliteDb *)p;
697 Tcl_Obj *pCmd;
698
699 assert( pDb->pUpdateHook );
700 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
701
702 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
703 Tcl_IncrRefCount(pCmd);
704 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
705 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
706 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
707 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
708 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
709 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
drhefdde162010-10-27 15:36:21 +0000710 Tcl_DecrRefCount(pCmd);
danielk197794eb6a12005-12-15 15:22:08 +0000711}
712
danielk19777cedc8d2004-06-10 10:50:08 +0000713static void tclCollateNeeded(
714 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000715 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000716 int enc,
717 const char *zName
718){
719 SqliteDb *pDb = (SqliteDb *)pCtx;
720 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
721 Tcl_IncrRefCount(pScript);
722 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
723 Tcl_EvalObjEx(pDb->interp, pScript, 0);
724 Tcl_DecrRefCount(pScript);
725}
726
drhaa940ea2004-01-15 02:44:03 +0000727/*
danielk19770202b292004-06-09 09:55:16 +0000728** This routine is called to evaluate an SQL collation function implemented
729** using TCL script.
730*/
731static int tclSqlCollate(
732 void *pCtx,
733 int nA,
734 const void *zA,
735 int nB,
736 const void *zB
737){
738 SqlCollate *p = (SqlCollate *)pCtx;
739 Tcl_Obj *pCmd;
740
741 pCmd = Tcl_NewStringObj(p->zScript, -1);
742 Tcl_IncrRefCount(pCmd);
743 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
744 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000745 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000746 Tcl_DecrRefCount(pCmd);
747 return (atoi(Tcl_GetStringResult(p->interp)));
748}
749
750/*
drhcabb0812002-09-14 13:47:32 +0000751** This routine is called to evaluate an SQL function implemented
752** using TCL script.
753*/
drhfb7e7652005-01-24 00:28:42 +0000754static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000755 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000756 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000757 int i;
758 int rc;
759
drhd1e47332005-06-26 17:55:33 +0000760 if( argc==0 ){
761 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
762 ** script object directly. This allows the TCL compiler to generate
763 ** bytecode for the command on the first invocation and thus make
764 ** subsequent invocations much faster. */
765 pCmd = p->pScript;
766 Tcl_IncrRefCount(pCmd);
767 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
768 Tcl_DecrRefCount(pCmd);
769 }else{
770 /* If there are arguments to the function, make a shallow copy of the
771 ** script object, lappend the arguments, then evaluate the copy.
772 **
peter.d.reid60ec9142014-09-06 16:39:46 +0000773 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
drhd1e47332005-06-26 17:55:33 +0000774 ** The new Tcl_Obj contains pointers to the original list elements.
775 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
776 ** of the list to tclCmdNameType, that alternate representation will
777 ** be preserved and reused on the next invocation.
778 */
779 Tcl_Obj **aArg;
780 int nArg;
781 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
782 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
783 return;
784 }
785 pCmd = Tcl_NewListObj(nArg, aArg);
786 Tcl_IncrRefCount(pCmd);
787 for(i=0; i<argc; i++){
788 sqlite3_value *pIn = argv[i];
789 Tcl_Obj *pVal;
790
791 /* Set pVal to contain the i'th column of this row. */
792 switch( sqlite3_value_type(pIn) ){
793 case SQLITE_BLOB: {
794 int bytes = sqlite3_value_bytes(pIn);
795 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
796 break;
797 }
798 case SQLITE_INTEGER: {
799 sqlite_int64 v = sqlite3_value_int64(pIn);
800 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +0000801 pVal = Tcl_NewIntObj((int)v);
drhd1e47332005-06-26 17:55:33 +0000802 }else{
803 pVal = Tcl_NewWideIntObj(v);
804 }
805 break;
806 }
807 case SQLITE_FLOAT: {
808 double r = sqlite3_value_double(pIn);
809 pVal = Tcl_NewDoubleObj(r);
810 break;
811 }
812 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +0000813 pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
drhd1e47332005-06-26 17:55:33 +0000814 break;
815 }
816 default: {
817 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000818 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000819 break;
820 }
821 }
822 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
823 if( rc ){
824 Tcl_DecrRefCount(pCmd);
825 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
826 return;
827 }
danielk197751ad0ec2004-05-24 12:39:02 +0000828 }
drhd1e47332005-06-26 17:55:33 +0000829 if( !p->useEvalObjv ){
830 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
831 ** is a list without a string representation. To prevent this from
832 ** happening, make sure pCmd has a valid string representation */
833 Tcl_GetString(pCmd);
834 }
835 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
836 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000837 }
danielk1977562e8d32005-05-20 09:40:55 +0000838
drhc7f269d2005-05-05 10:30:29 +0000839 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000840 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000841 }else{
drhc7f269d2005-05-05 10:30:29 +0000842 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
843 int n;
844 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000845 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000846 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000847 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000848 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000849 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000850 data = Tcl_GetByteArrayFromObj(pVar, &n);
851 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000852 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000853 Tcl_GetIntFromObj(0, pVar, &n);
854 sqlite3_result_int(context, n);
855 }else if( c=='d' && strcmp(zType,"double")==0 ){
856 double r;
857 Tcl_GetDoubleFromObj(0, pVar, &r);
858 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +0000859 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
860 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000861 Tcl_WideInt v;
862 Tcl_GetWideIntFromObj(0, pVar, &v);
863 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000864 }else{
danielk197700fd9572005-12-07 06:27:43 +0000865 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
866 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000867 }
drhcabb0812002-09-14 13:47:32 +0000868 }
869}
drh895d7472004-08-20 16:02:39 +0000870
drhe22a3342003-04-22 20:30:37 +0000871#ifndef SQLITE_OMIT_AUTHORIZATION
872/*
873** This is the authentication function. It appends the authentication
874** type code and the two arguments to zCmd[] then invokes the result
875** on the interpreter. The reply is examined to determine if the
876** authentication fails or succeeds.
877*/
878static int auth_callback(
879 void *pArg,
880 int code,
881 const char *zArg1,
882 const char *zArg2,
883 const char *zArg3,
884 const char *zArg4
drh32c6a482014-09-11 13:44:52 +0000885#ifdef SQLITE_USER_AUTHENTICATION
886 ,const char *zArg5
887#endif
drhe22a3342003-04-22 20:30:37 +0000888){
mistachkin6ef5e122014-01-24 17:03:55 +0000889 const char *zCode;
drhe22a3342003-04-22 20:30:37 +0000890 Tcl_DString str;
891 int rc;
892 const char *zReply;
893 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +0000894 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +0000895
896 switch( code ){
897 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
898 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
899 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
900 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
901 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
902 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
903 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
904 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
905 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
906 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
907 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
908 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
909 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
910 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
911 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
912 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
913 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
914 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
915 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
916 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
917 case SQLITE_READ : zCode="SQLITE_READ"; break;
918 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
919 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
920 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000921 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
922 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000923 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000924 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000925 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000926 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
927 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000928 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +0000929 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drh65a2aaa2014-01-16 22:40:02 +0000930 case SQLITE_RECURSIVE : zCode="SQLITE_RECURSIVE"; break;
drhe22a3342003-04-22 20:30:37 +0000931 default : zCode="????"; break;
932 }
933 Tcl_DStringInit(&str);
934 Tcl_DStringAppend(&str, pDb->zAuth, -1);
935 Tcl_DStringAppendElement(&str, zCode);
936 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
937 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
938 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
939 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
drh32c6a482014-09-11 13:44:52 +0000940#ifdef SQLITE_USER_AUTHENTICATION
941 Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
942#endif
drhe22a3342003-04-22 20:30:37 +0000943 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
944 Tcl_DStringFree(&str);
drhb07028f2011-10-14 21:49:18 +0000945 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
drhe22a3342003-04-22 20:30:37 +0000946 if( strcmp(zReply,"SQLITE_OK")==0 ){
947 rc = SQLITE_OK;
948 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
949 rc = SQLITE_DENY;
950 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
951 rc = SQLITE_IGNORE;
952 }else{
953 rc = 999;
954 }
955 return rc;
956}
957#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000958
959/*
tpoindex1067fe12004-12-17 15:41:11 +0000960** This routine reads a line of text from FILE in, stores
961** the text in memory obtained from malloc() and returns a pointer
962** to the text. NULL is returned at end of file, or if malloc()
963** fails.
964**
965** The interface is like "readline" but no command-line editing
966** is done.
967**
968** copied from shell.c from '.import' command
969*/
970static char *local_getline(char *zPrompt, FILE *in){
971 char *zLine;
972 int nLine;
973 int n;
tpoindex1067fe12004-12-17 15:41:11 +0000974
975 nLine = 100;
976 zLine = malloc( nLine );
977 if( zLine==0 ) return 0;
978 n = 0;
drhb07028f2011-10-14 21:49:18 +0000979 while( 1 ){
tpoindex1067fe12004-12-17 15:41:11 +0000980 if( n+100>nLine ){
981 nLine = nLine*2 + 100;
982 zLine = realloc(zLine, nLine);
983 if( zLine==0 ) return 0;
984 }
985 if( fgets(&zLine[n], nLine - n, in)==0 ){
986 if( n==0 ){
987 free(zLine);
988 return 0;
989 }
990 zLine[n] = 0;
tpoindex1067fe12004-12-17 15:41:11 +0000991 break;
992 }
993 while( zLine[n] ){ n++; }
994 if( n>0 && zLine[n-1]=='\n' ){
995 n--;
996 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +0000997 break;
tpoindex1067fe12004-12-17 15:41:11 +0000998 }
999 }
1000 zLine = realloc( zLine, n+1 );
1001 return zLine;
1002}
1003
danielk19778e556522007-11-13 10:30:24 +00001004
1005/*
dan4a4c11a2009-10-06 14:59:02 +00001006** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +00001007**
dan4a4c11a2009-10-06 14:59:02 +00001008** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +00001009**
dan4a4c11a2009-10-06 14:59:02 +00001010** It is invoked after evaluating the script SCRIPT to commit or rollback
1011** the transaction or savepoint opened by the [transaction] command.
1012*/
1013static int DbTransPostCmd(
1014 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1015 Tcl_Interp *interp, /* Tcl interpreter */
1016 int result /* Result of evaluating SCRIPT */
1017){
mistachkin6ef5e122014-01-24 17:03:55 +00001018 static const char *const azEnd[] = {
dan4a4c11a2009-10-06 14:59:02 +00001019 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1020 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1021 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1022 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1023 };
1024 SqliteDb *pDb = (SqliteDb*)data[0];
1025 int rc = result;
1026 const char *zEnd;
1027
1028 pDb->nTransaction--;
1029 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1030
1031 pDb->disableAuth++;
1032 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1033 /* This is a tricky scenario to handle. The most likely cause of an
1034 ** error is that the exec() above was an attempt to commit the
1035 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
mistachkin48864df2013-03-21 21:20:32 +00001036 ** that an IO-error has occurred. In either case, throw a Tcl exception
dan4a4c11a2009-10-06 14:59:02 +00001037 ** and try to rollback the transaction.
1038 **
1039 ** But it could also be that the user executed one or more BEGIN,
1040 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1041 ** this method's logic. Not clear how this would be best handled.
1042 */
1043 if( rc!=TCL_ERROR ){
drha198f2b2014-02-07 19:26:13 +00001044 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
dan4a4c11a2009-10-06 14:59:02 +00001045 rc = TCL_ERROR;
1046 }
1047 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1048 }
1049 pDb->disableAuth--;
1050
1051 return rc;
1052}
1053
1054/*
danc431fd52011-06-27 16:55:50 +00001055** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1056** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1057** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1058** on whether or not the [db_use_legacy_prepare] command has been used to
1059** configure the connection.
1060*/
1061static int dbPrepare(
1062 SqliteDb *pDb, /* Database object */
1063 const char *zSql, /* SQL to compile */
1064 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1065 const char **pzOut /* OUT: Pointer to next SQL statement */
1066){
1067#ifdef SQLITE_TEST
1068 if( pDb->bLegacyPrepare ){
1069 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1070 }
1071#endif
1072 return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut);
1073}
1074
1075/*
dan4a4c11a2009-10-06 14:59:02 +00001076** Search the cache for a prepared-statement object that implements the
1077** first SQL statement in the buffer pointed to by parameter zIn. If
1078** no such prepared-statement can be found, allocate and prepare a new
1079** one. In either case, bind the current values of the relevant Tcl
1080** variables to any $var, :var or @var variables in the statement. Before
1081** returning, set *ppPreStmt to point to the prepared-statement object.
1082**
1083** Output parameter *pzOut is set to point to the next SQL statement in
1084** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1085** next statement.
1086**
1087** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1088** and an error message loaded into interpreter pDb->interp.
1089*/
1090static int dbPrepareAndBind(
1091 SqliteDb *pDb, /* Database object */
1092 char const *zIn, /* SQL to compile */
1093 char const **pzOut, /* OUT: Pointer to next SQL statement */
1094 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1095){
1096 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
mistachkin7bb22ac2015-01-12 19:59:12 +00001097 sqlite3_stmt *pStmt = 0; /* Prepared statement object */
dan4a4c11a2009-10-06 14:59:02 +00001098 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1099 int nSql; /* Length of zSql in bytes */
mistachkin7bb22ac2015-01-12 19:59:12 +00001100 int nVar = 0; /* Number of variables in statement */
dan4a4c11a2009-10-06 14:59:02 +00001101 int iParm = 0; /* Next free entry in apParm */
drh0425f182013-11-26 16:48:04 +00001102 char c;
dan4a4c11a2009-10-06 14:59:02 +00001103 int i;
1104 Tcl_Interp *interp = pDb->interp;
1105
1106 *ppPreStmt = 0;
1107
1108 /* Trim spaces from the start of zSql and calculate the remaining length. */
drh0425f182013-11-26 16:48:04 +00001109 while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
dan4a4c11a2009-10-06 14:59:02 +00001110 nSql = strlen30(zSql);
1111
1112 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1113 int n = pPreStmt->nSql;
1114 if( nSql>=n
1115 && memcmp(pPreStmt->zSql, zSql, n)==0
1116 && (zSql[n]==0 || zSql[n-1]==';')
1117 ){
1118 pStmt = pPreStmt->pStmt;
1119 *pzOut = &zSql[pPreStmt->nSql];
1120
1121 /* When a prepared statement is found, unlink it from the
1122 ** cache list. It will later be added back to the beginning
1123 ** of the cache list in order to implement LRU replacement.
1124 */
1125 if( pPreStmt->pPrev ){
1126 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1127 }else{
1128 pDb->stmtList = pPreStmt->pNext;
1129 }
1130 if( pPreStmt->pNext ){
1131 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1132 }else{
1133 pDb->stmtLast = pPreStmt->pPrev;
1134 }
1135 pDb->nStmt--;
1136 nVar = sqlite3_bind_parameter_count(pStmt);
1137 break;
1138 }
1139 }
1140
1141 /* If no prepared statement was found. Compile the SQL text. Also allocate
1142 ** a new SqlPreparedStmt structure. */
1143 if( pPreStmt==0 ){
1144 int nByte;
1145
danc431fd52011-06-27 16:55:50 +00001146 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
drhc45e6712012-10-03 11:02:33 +00001147 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001148 return TCL_ERROR;
1149 }
1150 if( pStmt==0 ){
1151 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1152 /* A compile-time error in the statement. */
drhc45e6712012-10-03 11:02:33 +00001153 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001154 return TCL_ERROR;
1155 }else{
1156 /* The statement was a no-op. Continue to the next statement
1157 ** in the SQL string.
1158 */
1159 return TCL_OK;
1160 }
1161 }
1162
1163 assert( pPreStmt==0 );
1164 nVar = sqlite3_bind_parameter_count(pStmt);
1165 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1166 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1167 memset(pPreStmt, 0, nByte);
1168
1169 pPreStmt->pStmt = pStmt;
drh7ed243b2012-04-19 17:19:51 +00001170 pPreStmt->nSql = (int)(*pzOut - zSql);
dan4a4c11a2009-10-06 14:59:02 +00001171 pPreStmt->zSql = sqlite3_sql(pStmt);
1172 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
danc431fd52011-06-27 16:55:50 +00001173#ifdef SQLITE_TEST
1174 if( pPreStmt->zSql==0 ){
1175 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1176 memcpy(zCopy, zSql, pPreStmt->nSql);
1177 zCopy[pPreStmt->nSql] = '\0';
1178 pPreStmt->zSql = zCopy;
1179 }
1180#endif
dan4a4c11a2009-10-06 14:59:02 +00001181 }
1182 assert( pPreStmt );
1183 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1184 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1185
1186 /* Bind values to parameters that begin with $ or : */
1187 for(i=1; i<=nVar; i++){
1188 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1189 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1190 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1191 if( pVar ){
1192 int n;
1193 u8 *data;
1194 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
mistachkin8e189222015-04-19 21:43:16 +00001195 c = zType[0];
dan4a4c11a2009-10-06 14:59:02 +00001196 if( zVar[0]=='@' ||
1197 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1198 /* Load a BLOB type if the Tcl variable is a bytearray and
1199 ** it has no string representation or the host
1200 ** parameter name begins with "@". */
1201 data = Tcl_GetByteArrayFromObj(pVar, &n);
1202 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1203 Tcl_IncrRefCount(pVar);
1204 pPreStmt->apParm[iParm++] = pVar;
1205 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1206 Tcl_GetIntFromObj(interp, pVar, &n);
1207 sqlite3_bind_int(pStmt, i, n);
1208 }else if( c=='d' && strcmp(zType,"double")==0 ){
1209 double r;
1210 Tcl_GetDoubleFromObj(interp, pVar, &r);
1211 sqlite3_bind_double(pStmt, i, r);
1212 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1213 (c=='i' && strcmp(zType,"int")==0) ){
1214 Tcl_WideInt v;
1215 Tcl_GetWideIntFromObj(interp, pVar, &v);
1216 sqlite3_bind_int64(pStmt, i, v);
1217 }else{
1218 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1219 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1220 Tcl_IncrRefCount(pVar);
1221 pPreStmt->apParm[iParm++] = pVar;
1222 }
1223 }else{
1224 sqlite3_bind_null(pStmt, i);
1225 }
1226 }
1227 }
1228 pPreStmt->nParm = iParm;
1229 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001230
dan4a4c11a2009-10-06 14:59:02 +00001231 return TCL_OK;
1232}
1233
dan4a4c11a2009-10-06 14:59:02 +00001234/*
1235** Release a statement reference obtained by calling dbPrepareAndBind().
1236** There should be exactly one call to this function for each call to
1237** dbPrepareAndBind().
1238**
1239** If the discard parameter is non-zero, then the statement is deleted
1240** immediately. Otherwise it is added to the LRU list and may be returned
1241** by a subsequent call to dbPrepareAndBind().
1242*/
1243static void dbReleaseStmt(
1244 SqliteDb *pDb, /* Database handle */
1245 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1246 int discard /* True to delete (not cache) the pPreStmt */
1247){
1248 int i;
1249
1250 /* Free the bound string and blob parameters */
1251 for(i=0; i<pPreStmt->nParm; i++){
1252 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1253 }
1254 pPreStmt->nParm = 0;
1255
1256 if( pDb->maxStmt<=0 || discard ){
1257 /* If the cache is turned off, deallocated the statement */
danc431fd52011-06-27 16:55:50 +00001258 dbFreeStmt(pPreStmt);
dan4a4c11a2009-10-06 14:59:02 +00001259 }else{
1260 /* Add the prepared statement to the beginning of the cache list. */
1261 pPreStmt->pNext = pDb->stmtList;
1262 pPreStmt->pPrev = 0;
1263 if( pDb->stmtList ){
1264 pDb->stmtList->pPrev = pPreStmt;
1265 }
1266 pDb->stmtList = pPreStmt;
1267 if( pDb->stmtLast==0 ){
1268 assert( pDb->nStmt==0 );
1269 pDb->stmtLast = pPreStmt;
1270 }else{
1271 assert( pDb->nStmt>0 );
1272 }
1273 pDb->nStmt++;
1274
1275 /* If we have too many statement in cache, remove the surplus from
1276 ** the end of the cache list. */
1277 while( pDb->nStmt>pDb->maxStmt ){
danc431fd52011-06-27 16:55:50 +00001278 SqlPreparedStmt *pLast = pDb->stmtLast;
1279 pDb->stmtLast = pLast->pPrev;
dan4a4c11a2009-10-06 14:59:02 +00001280 pDb->stmtLast->pNext = 0;
1281 pDb->nStmt--;
danc431fd52011-06-27 16:55:50 +00001282 dbFreeStmt(pLast);
dan4a4c11a2009-10-06 14:59:02 +00001283 }
1284 }
1285}
1286
1287/*
1288** Structure used with dbEvalXXX() functions:
1289**
1290** dbEvalInit()
1291** dbEvalStep()
1292** dbEvalFinalize()
1293** dbEvalRowInfo()
1294** dbEvalColumnValue()
1295*/
1296typedef struct DbEvalContext DbEvalContext;
1297struct DbEvalContext {
1298 SqliteDb *pDb; /* Database handle */
1299 Tcl_Obj *pSql; /* Object holding string zSql */
1300 const char *zSql; /* Remaining SQL to execute */
1301 SqlPreparedStmt *pPreStmt; /* Current statement */
1302 int nCol; /* Number of columns returned by pStmt */
1303 Tcl_Obj *pArray; /* Name of array variable */
1304 Tcl_Obj **apColName; /* Array of column names */
1305};
1306
1307/*
1308** Release any cache of column names currently held as part of
1309** the DbEvalContext structure passed as the first argument.
1310*/
1311static void dbReleaseColumnNames(DbEvalContext *p){
1312 if( p->apColName ){
1313 int i;
1314 for(i=0; i<p->nCol; i++){
1315 Tcl_DecrRefCount(p->apColName[i]);
1316 }
1317 Tcl_Free((char *)p->apColName);
1318 p->apColName = 0;
1319 }
1320 p->nCol = 0;
1321}
1322
1323/*
1324** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001325**
1326** If pArray is not NULL, then it contains the name of a Tcl array
1327** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001328** the names of the columns returned by the statement as part of each
1329** call to dbEvalStep(), in order from left to right. e.g. if the names
1330** of the returned columns are a, b and c, it does the equivalent of the
1331** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001332**
1333** set ${pArray}(*) {a b c}
1334*/
dan4a4c11a2009-10-06 14:59:02 +00001335static void dbEvalInit(
1336 DbEvalContext *p, /* Pointer to structure to initialize */
1337 SqliteDb *pDb, /* Database handle */
1338 Tcl_Obj *pSql, /* Object containing SQL script */
1339 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001340){
dan4a4c11a2009-10-06 14:59:02 +00001341 memset(p, 0, sizeof(DbEvalContext));
1342 p->pDb = pDb;
1343 p->zSql = Tcl_GetString(pSql);
1344 p->pSql = pSql;
1345 Tcl_IncrRefCount(pSql);
1346 if( pArray ){
1347 p->pArray = pArray;
1348 Tcl_IncrRefCount(pArray);
1349 }
1350}
danielk19778e556522007-11-13 10:30:24 +00001351
dan4a4c11a2009-10-06 14:59:02 +00001352/*
1353** Obtain information about the row that the DbEvalContext passed as the
1354** first argument currently points to.
1355*/
1356static void dbEvalRowInfo(
1357 DbEvalContext *p, /* Evaluation context */
1358 int *pnCol, /* OUT: Number of column names */
1359 Tcl_Obj ***papColName /* OUT: Array of column names */
1360){
danielk19778e556522007-11-13 10:30:24 +00001361 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001362 if( 0==p->apColName ){
1363 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1364 int i; /* Iterator variable */
1365 int nCol; /* Number of columns returned by pStmt */
1366 Tcl_Obj **apColName = 0; /* Array of column names */
1367
1368 p->nCol = nCol = sqlite3_column_count(pStmt);
1369 if( nCol>0 && (papColName || p->pArray) ){
1370 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1371 for(i=0; i<nCol; i++){
drhc45e6712012-10-03 11:02:33 +00001372 apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
dan4a4c11a2009-10-06 14:59:02 +00001373 Tcl_IncrRefCount(apColName[i]);
1374 }
1375 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001376 }
1377
1378 /* If results are being stored in an array variable, then create
1379 ** the array(*) entry for that array
1380 */
dan4a4c11a2009-10-06 14:59:02 +00001381 if( p->pArray ){
1382 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001383 Tcl_Obj *pColList = Tcl_NewObj();
1384 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001385
danielk19778e556522007-11-13 10:30:24 +00001386 for(i=0; i<nCol; i++){
1387 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1388 }
1389 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001390 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001391 Tcl_DecrRefCount(pStar);
1392 }
danielk19778e556522007-11-13 10:30:24 +00001393 }
1394
dan4a4c11a2009-10-06 14:59:02 +00001395 if( papColName ){
1396 *papColName = p->apColName;
1397 }
1398 if( pnCol ){
1399 *pnCol = p->nCol;
1400 }
1401}
1402
1403/*
1404** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1405** returned, then an error message is stored in the interpreter before
1406** returning.
1407**
1408** A return value of TCL_OK means there is a row of data available. The
1409** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1410** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1411** is returned, then the SQL script has finished executing and there are
1412** no further rows available. This is similar to SQLITE_DONE.
1413*/
1414static int dbEvalStep(DbEvalContext *p){
danc431fd52011-06-27 16:55:50 +00001415 const char *zPrevSql = 0; /* Previous value of p->zSql */
1416
dan4a4c11a2009-10-06 14:59:02 +00001417 while( p->zSql[0] || p->pPreStmt ){
1418 int rc;
1419 if( p->pPreStmt==0 ){
danc431fd52011-06-27 16:55:50 +00001420 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
dan4a4c11a2009-10-06 14:59:02 +00001421 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1422 if( rc!=TCL_OK ) return rc;
1423 }else{
1424 int rcs;
1425 SqliteDb *pDb = p->pDb;
1426 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1427 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1428
1429 rcs = sqlite3_step(pStmt);
1430 if( rcs==SQLITE_ROW ){
1431 return TCL_OK;
1432 }
1433 if( p->pArray ){
1434 dbEvalRowInfo(p, 0, 0);
1435 }
1436 rcs = sqlite3_reset(pStmt);
1437
1438 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1439 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001440 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
dan4a4c11a2009-10-06 14:59:02 +00001441 dbReleaseColumnNames(p);
1442 p->pPreStmt = 0;
1443
1444 if( rcs!=SQLITE_OK ){
1445 /* If a run-time error occurs, report the error and stop reading
1446 ** the SQL. */
dan4a4c11a2009-10-06 14:59:02 +00001447 dbReleaseStmt(pDb, pPreStmt, 1);
danc431fd52011-06-27 16:55:50 +00001448#if SQLITE_TEST
1449 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1450 /* If the runtime error was an SQLITE_SCHEMA, and the database
1451 ** handle is configured to use the legacy sqlite3_prepare()
1452 ** interface, retry prepare()/step() on the same SQL statement.
1453 ** This only happens once. If there is a second SQLITE_SCHEMA
1454 ** error, the error will be returned to the caller. */
1455 p->zSql = zPrevSql;
1456 continue;
1457 }
1458#endif
drhc45e6712012-10-03 11:02:33 +00001459 Tcl_SetObjResult(pDb->interp,
1460 Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001461 return TCL_ERROR;
1462 }else{
1463 dbReleaseStmt(pDb, pPreStmt, 0);
1464 }
1465 }
1466 }
1467
1468 /* Finished */
1469 return TCL_BREAK;
1470}
1471
1472/*
1473** Free all resources currently held by the DbEvalContext structure passed
1474** as the first argument. There should be exactly one call to this function
1475** for each call to dbEvalInit().
1476*/
1477static void dbEvalFinalize(DbEvalContext *p){
1478 if( p->pPreStmt ){
1479 sqlite3_reset(p->pPreStmt->pStmt);
1480 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1481 p->pPreStmt = 0;
1482 }
1483 if( p->pArray ){
1484 Tcl_DecrRefCount(p->pArray);
1485 p->pArray = 0;
1486 }
1487 Tcl_DecrRefCount(p->pSql);
1488 dbReleaseColumnNames(p);
1489}
1490
1491/*
1492** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1493** the value for the iCol'th column of the row currently pointed to by
1494** the DbEvalContext structure passed as the first argument.
1495*/
1496static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1497 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1498 switch( sqlite3_column_type(pStmt, iCol) ){
1499 case SQLITE_BLOB: {
1500 int bytes = sqlite3_column_bytes(pStmt, iCol);
1501 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1502 if( !zBlob ) bytes = 0;
1503 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1504 }
1505 case SQLITE_INTEGER: {
1506 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1507 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +00001508 return Tcl_NewIntObj((int)v);
dan4a4c11a2009-10-06 14:59:02 +00001509 }else{
1510 return Tcl_NewWideIntObj(v);
1511 }
1512 }
1513 case SQLITE_FLOAT: {
1514 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1515 }
1516 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +00001517 return Tcl_NewStringObj(p->pDb->zNull, -1);
dan4a4c11a2009-10-06 14:59:02 +00001518 }
1519 }
1520
drh325eff52012-10-03 12:56:18 +00001521 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
dan4a4c11a2009-10-06 14:59:02 +00001522}
1523
1524/*
1525** If using Tcl version 8.6 or greater, use the NR functions to avoid
1526** recursive evalution of scripts by the [db eval] and [db trans]
1527** commands. Even if the headers used while compiling the extension
1528** are 8.6 or newer, the code still tests the Tcl version at runtime.
1529** This allows stubs-enabled builds to be used with older Tcl libraries.
1530*/
1531#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001532# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001533static int DbUseNre(void){
1534 int major, minor;
1535 Tcl_GetVersion(&major, &minor, 0, 0);
1536 return( (major==8 && minor>=6) || major>8 );
1537}
1538#else
1539/*
1540** Compiling using headers earlier than 8.6. In this case NR cannot be
1541** used, so DbUseNre() to always return zero. Add #defines for the other
1542** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1543** even though the only invocations of them are within conditional blocks
1544** of the form:
1545**
1546** if( DbUseNre() ) { ... }
1547*/
drha2c8a952009-10-13 18:38:34 +00001548# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001549# define DbUseNre() 0
drha47941f2013-12-20 18:57:44 +00001550# define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001551# define Tcl_NREvalObj(a,b,c) 0
drha47941f2013-12-20 18:57:44 +00001552# define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001553#endif
1554
1555/*
1556** This function is part of the implementation of the command:
1557**
1558** $db eval SQL ?ARRAYNAME? SCRIPT
1559*/
1560static int DbEvalNextCmd(
1561 ClientData data[], /* data[0] is the (DbEvalContext*) */
1562 Tcl_Interp *interp, /* Tcl interpreter */
1563 int result /* Result so far */
1564){
1565 int rc = result; /* Return code */
1566
1567 /* The first element of the data[] array is a pointer to a DbEvalContext
1568 ** structure allocated using Tcl_Alloc(). The second element of data[]
1569 ** is a pointer to a Tcl_Obj containing the script to run for each row
1570 ** returned by the queries encapsulated in data[0]. */
1571 DbEvalContext *p = (DbEvalContext *)data[0];
1572 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1573 Tcl_Obj *pArray = p->pArray;
1574
1575 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1576 int i;
1577 int nCol;
1578 Tcl_Obj **apColName;
1579 dbEvalRowInfo(p, &nCol, &apColName);
1580 for(i=0; i<nCol; i++){
1581 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1582 if( pArray==0 ){
1583 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1584 }else{
1585 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1586 }
1587 }
1588
1589 /* The required interpreter variables are now populated with the data
1590 ** from the current row. If using NRE, schedule callbacks to evaluate
1591 ** script pScript, then to invoke this function again to fetch the next
1592 ** row (or clean up if there is no next row or the script throws an
1593 ** exception). After scheduling the callbacks, return control to the
1594 ** caller.
1595 **
1596 ** If not using NRE, evaluate pScript directly and continue with the
1597 ** next iteration of this while(...) loop. */
1598 if( DbUseNre() ){
1599 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1600 return Tcl_NREvalObj(interp, pScript, 0);
1601 }else{
1602 rc = Tcl_EvalObjEx(interp, pScript, 0);
1603 }
1604 }
1605
1606 Tcl_DecrRefCount(pScript);
1607 dbEvalFinalize(p);
1608 Tcl_Free((char *)p);
1609
1610 if( rc==TCL_OK || rc==TCL_BREAK ){
1611 Tcl_ResetResult(interp);
1612 rc = TCL_OK;
1613 }
1614 return rc;
danielk19778e556522007-11-13 10:30:24 +00001615}
1616
tpoindex1067fe12004-12-17 15:41:11 +00001617/*
drh75897232000-05-29 14:26:00 +00001618** The "sqlite" command below creates a new Tcl command for each
1619** connection it opens to an SQLite database. This routine is invoked
1620** whenever one of those connection-specific commands is executed
1621** in Tcl. For example, if you run Tcl code like this:
1622**
drh9bb575f2004-09-06 17:24:11 +00001623** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001624** db1 close
1625**
1626** The first command opens a connection to the "my_database" database
1627** and calls that connection "db1". The second command causes this
1628** subroutine to be invoked.
1629*/
drh6d313162000-09-21 13:01:35 +00001630static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001631 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001632 int choice;
drh22fbcb82004-02-01 01:22:50 +00001633 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001634 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001635 "authorizer", "backup", "busy",
1636 "cache", "changes", "close",
1637 "collate", "collation_needed", "commit_hook",
1638 "complete", "copy", "enable_load_extension",
1639 "errorcode", "eval", "exists",
1640 "function", "incrblob", "interrupt",
drh833bf962010-04-28 14:42:19 +00001641 "last_insert_rowid", "nullvalue", "onecolumn",
1642 "profile", "progress", "rekey",
1643 "restore", "rollback_hook", "status",
1644 "timeout", "total_changes", "trace",
1645 "transaction", "unlock_notify", "update_hook",
1646 "version", "wal_hook", 0
drh6d313162000-09-21 13:01:35 +00001647 };
drh411995d2002-06-25 19:31:18 +00001648 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001649 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1650 DB_CACHE, DB_CHANGES, DB_CLOSE,
1651 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1652 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1653 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1654 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
drh833bf962010-04-28 14:42:19 +00001655 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
1656 DB_PROFILE, DB_PROGRESS, DB_REKEY,
1657 DB_RESTORE, DB_ROLLBACK_HOOK, DB_STATUS,
1658 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
1659 DB_TRANSACTION, DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK,
1660 DB_VERSION, DB_WAL_HOOK
drh6d313162000-09-21 13:01:35 +00001661 };
tpoindex1067fe12004-12-17 15:41:11 +00001662 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001663
1664 if( objc<2 ){
1665 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001666 return TCL_ERROR;
1667 }
drh411995d2002-06-25 19:31:18 +00001668 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001669 return TCL_ERROR;
1670 }
1671
drh411995d2002-06-25 19:31:18 +00001672 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001673
drhe22a3342003-04-22 20:30:37 +00001674 /* $db authorizer ?CALLBACK?
1675 **
1676 ** Invoke the given callback to authorize each SQL operation as it is
1677 ** compiled. 5 arguments are appended to the callback before it is
1678 ** invoked:
1679 **
1680 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1681 ** (2) First descriptive name (depends on authorization type)
1682 ** (3) Second descriptive name
1683 ** (4) Name of the database (ex: "main", "temp")
1684 ** (5) Name of trigger that is doing the access
1685 **
1686 ** The callback should return on of the following strings: SQLITE_OK,
1687 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1688 **
1689 ** If this method is invoked with no arguments, the current authorization
1690 ** callback string is returned.
1691 */
1692 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001693#ifdef SQLITE_OMIT_AUTHORIZATION
drha198f2b2014-02-07 19:26:13 +00001694 Tcl_AppendResult(interp, "authorization not available in this build",
1695 (char*)0);
drh1211de32004-07-26 12:24:22 +00001696 return TCL_ERROR;
1697#else
drhe22a3342003-04-22 20:30:37 +00001698 if( objc>3 ){
1699 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001700 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001701 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001702 if( pDb->zAuth ){
drha198f2b2014-02-07 19:26:13 +00001703 Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
drhe22a3342003-04-22 20:30:37 +00001704 }
1705 }else{
1706 char *zAuth;
1707 int len;
1708 if( pDb->zAuth ){
1709 Tcl_Free(pDb->zAuth);
1710 }
1711 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1712 if( zAuth && len>0 ){
1713 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001714 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001715 }else{
1716 pDb->zAuth = 0;
1717 }
drhe22a3342003-04-22 20:30:37 +00001718 if( pDb->zAuth ){
drh32c6a482014-09-11 13:44:52 +00001719 typedef int (*sqlite3_auth_cb)(
1720 void*,int,const char*,const char*,
1721 const char*,const char*);
drhe22a3342003-04-22 20:30:37 +00001722 pDb->interp = interp;
drh32c6a482014-09-11 13:44:52 +00001723 sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
drhe22a3342003-04-22 20:30:37 +00001724 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001725 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001726 }
drhe22a3342003-04-22 20:30:37 +00001727 }
drh1211de32004-07-26 12:24:22 +00001728#endif
drhe22a3342003-04-22 20:30:37 +00001729 break;
1730 }
1731
drhdc2c4912009-02-04 22:46:47 +00001732 /* $db backup ?DATABASE? FILENAME
1733 **
1734 ** Open or create a database file named FILENAME. Transfer the
1735 ** content of local database DATABASE (default: "main") into the
1736 ** FILENAME database.
1737 */
1738 case DB_BACKUP: {
1739 const char *zDestFile;
1740 const char *zSrcDb;
1741 sqlite3 *pDest;
1742 sqlite3_backup *pBackup;
1743
1744 if( objc==3 ){
1745 zSrcDb = "main";
1746 zDestFile = Tcl_GetString(objv[2]);
1747 }else if( objc==4 ){
1748 zSrcDb = Tcl_GetString(objv[2]);
1749 zDestFile = Tcl_GetString(objv[3]);
1750 }else{
1751 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1752 return TCL_ERROR;
1753 }
drh147ef392016-01-22 23:17:51 +00001754 rc = sqlite3_open_v2(zDestFile, &pDest,
1755 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00001756 if( rc!=SQLITE_OK ){
1757 Tcl_AppendResult(interp, "cannot open target database: ",
1758 sqlite3_errmsg(pDest), (char*)0);
1759 sqlite3_close(pDest);
1760 return TCL_ERROR;
1761 }
1762 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1763 if( pBackup==0 ){
1764 Tcl_AppendResult(interp, "backup failed: ",
1765 sqlite3_errmsg(pDest), (char*)0);
1766 sqlite3_close(pDest);
1767 return TCL_ERROR;
1768 }
1769 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1770 sqlite3_backup_finish(pBackup);
1771 if( rc==SQLITE_DONE ){
1772 rc = TCL_OK;
1773 }else{
1774 Tcl_AppendResult(interp, "backup failed: ",
1775 sqlite3_errmsg(pDest), (char*)0);
1776 rc = TCL_ERROR;
1777 }
1778 sqlite3_close(pDest);
1779 break;
1780 }
1781
drhbec3f402000-08-04 13:49:02 +00001782 /* $db busy ?CALLBACK?
1783 **
1784 ** Invoke the given callback if an SQL statement attempts to open
1785 ** a locked database file.
1786 */
drh6d313162000-09-21 13:01:35 +00001787 case DB_BUSY: {
1788 if( objc>3 ){
1789 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001790 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001791 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001792 if( pDb->zBusy ){
drha198f2b2014-02-07 19:26:13 +00001793 Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
drhbec3f402000-08-04 13:49:02 +00001794 }
1795 }else{
drh6d313162000-09-21 13:01:35 +00001796 char *zBusy;
1797 int len;
drhbec3f402000-08-04 13:49:02 +00001798 if( pDb->zBusy ){
1799 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001800 }
drh6d313162000-09-21 13:01:35 +00001801 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1802 if( zBusy && len>0 ){
1803 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001804 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001805 }else{
1806 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001807 }
1808 if( pDb->zBusy ){
1809 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001810 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001811 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001812 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001813 }
1814 }
drh6d313162000-09-21 13:01:35 +00001815 break;
1816 }
drhbec3f402000-08-04 13:49:02 +00001817
drhfb7e7652005-01-24 00:28:42 +00001818 /* $db cache flush
1819 ** $db cache size n
1820 **
1821 ** Flush the prepared statement cache, or set the maximum number of
1822 ** cached statements.
1823 */
1824 case DB_CACHE: {
1825 char *subCmd;
1826 int n;
1827
1828 if( objc<=2 ){
1829 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1830 return TCL_ERROR;
1831 }
1832 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1833 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1834 if( objc!=3 ){
1835 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1836 return TCL_ERROR;
1837 }else{
1838 flushStmtCache( pDb );
1839 }
1840 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1841 if( objc!=4 ){
1842 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1843 return TCL_ERROR;
1844 }else{
1845 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1846 Tcl_AppendResult( interp, "cannot convert \"",
drha198f2b2014-02-07 19:26:13 +00001847 Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
drhfb7e7652005-01-24 00:28:42 +00001848 return TCL_ERROR;
1849 }else{
1850 if( n<0 ){
1851 flushStmtCache( pDb );
1852 n = 0;
1853 }else if( n>MAX_PREPARED_STMTS ){
1854 n = MAX_PREPARED_STMTS;
1855 }
1856 pDb->maxStmt = n;
1857 }
1858 }
1859 }else{
1860 Tcl_AppendResult( interp, "bad option \"",
drha198f2b2014-02-07 19:26:13 +00001861 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
1862 (char*)0);
drhfb7e7652005-01-24 00:28:42 +00001863 return TCL_ERROR;
1864 }
1865 break;
1866 }
1867
danielk1977b28af712004-06-21 06:50:26 +00001868 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001869 **
1870 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001871 ** the most recent INSERT, UPDATE or DELETE statement, not including
1872 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001873 */
1874 case DB_CHANGES: {
1875 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001876 if( objc!=2 ){
1877 Tcl_WrongNumArgs(interp, 2, objv, "");
1878 return TCL_ERROR;
1879 }
drhc8d30ac2002-04-12 10:08:59 +00001880 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001881 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001882 break;
1883 }
1884
drh75897232000-05-29 14:26:00 +00001885 /* $db close
1886 **
1887 ** Shutdown the database
1888 */
drh6d313162000-09-21 13:01:35 +00001889 case DB_CLOSE: {
1890 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1891 break;
1892 }
drh75897232000-05-29 14:26:00 +00001893
drh0f14e2e2004-06-29 12:39:08 +00001894 /*
1895 ** $db collate NAME SCRIPT
1896 **
1897 ** Create a new SQL collation function called NAME. Whenever
1898 ** that function is called, invoke SCRIPT to evaluate the function.
1899 */
1900 case DB_COLLATE: {
1901 SqlCollate *pCollate;
1902 char *zName;
1903 char *zScript;
1904 int nScript;
1905 if( objc!=4 ){
1906 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1907 return TCL_ERROR;
1908 }
1909 zName = Tcl_GetStringFromObj(objv[2], 0);
1910 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1911 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1912 if( pCollate==0 ) return TCL_ERROR;
1913 pCollate->interp = interp;
1914 pCollate->pNext = pDb->pCollate;
1915 pCollate->zScript = (char*)&pCollate[1];
1916 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001917 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001918 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1919 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001920 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001921 return TCL_ERROR;
1922 }
1923 break;
1924 }
1925
1926 /*
1927 ** $db collation_needed SCRIPT
1928 **
1929 ** Create a new SQL collation function called NAME. Whenever
1930 ** that function is called, invoke SCRIPT to evaluate the function.
1931 */
1932 case DB_COLLATION_NEEDED: {
1933 if( objc!=3 ){
1934 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1935 return TCL_ERROR;
1936 }
1937 if( pDb->pCollateNeeded ){
1938 Tcl_DecrRefCount(pDb->pCollateNeeded);
1939 }
1940 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1941 Tcl_IncrRefCount(pDb->pCollateNeeded);
1942 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1943 break;
1944 }
1945
drh19e2d372005-08-29 23:00:03 +00001946 /* $db commit_hook ?CALLBACK?
1947 **
1948 ** Invoke the given callback just before committing every SQL transaction.
1949 ** If the callback throws an exception or returns non-zero, then the
1950 ** transaction is aborted. If CALLBACK is an empty string, the callback
1951 ** is disabled.
1952 */
1953 case DB_COMMIT_HOOK: {
1954 if( objc>3 ){
1955 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1956 return TCL_ERROR;
1957 }else if( objc==2 ){
1958 if( pDb->zCommit ){
drha198f2b2014-02-07 19:26:13 +00001959 Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
drh19e2d372005-08-29 23:00:03 +00001960 }
1961 }else{
mistachkin6ef5e122014-01-24 17:03:55 +00001962 const char *zCommit;
drh19e2d372005-08-29 23:00:03 +00001963 int len;
1964 if( pDb->zCommit ){
1965 Tcl_Free(pDb->zCommit);
1966 }
1967 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1968 if( zCommit && len>0 ){
1969 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001970 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001971 }else{
1972 pDb->zCommit = 0;
1973 }
1974 if( pDb->zCommit ){
1975 pDb->interp = interp;
1976 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1977 }else{
1978 sqlite3_commit_hook(pDb->db, 0, 0);
1979 }
1980 }
1981 break;
1982 }
1983
drh75897232000-05-29 14:26:00 +00001984 /* $db complete SQL
1985 **
1986 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1987 ** additional lines of input are needed. This is similar to the
1988 ** built-in "info complete" command of Tcl.
1989 */
drh6d313162000-09-21 13:01:35 +00001990 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00001991#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00001992 Tcl_Obj *pResult;
1993 int isComplete;
1994 if( objc!=3 ){
1995 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00001996 return TCL_ERROR;
1997 }
danielk19776f8a5032004-05-10 10:34:51 +00001998 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00001999 pResult = Tcl_GetObjResult(interp);
2000 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00002001#endif
drh6d313162000-09-21 13:01:35 +00002002 break;
2003 }
drhdcd997e2003-01-31 17:21:49 +00002004
drh19e2d372005-08-29 23:00:03 +00002005 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2006 **
2007 ** Copy data into table from filename, optionally using SEPARATOR
2008 ** as column separators. If a column contains a null string, or the
2009 ** value of NULLINDICATOR, a NULL is inserted for the column.
2010 ** conflict-algorithm is one of the sqlite conflict algorithms:
2011 ** rollback, abort, fail, ignore, replace
2012 ** On success, return the number of lines processed, not necessarily same
2013 ** as 'db changes' due to conflict-algorithm selected.
2014 **
2015 ** This code is basically an implementation/enhancement of
2016 ** the sqlite3 shell.c ".import" command.
2017 **
2018 ** This command usage is equivalent to the sqlite2.x COPY statement,
2019 ** which imports file data into a table using the PostgreSQL COPY file format:
2020 ** $db copy $conflit_algo $table_name $filename \t \\N
2021 */
2022 case DB_COPY: {
2023 char *zTable; /* Insert data into this table */
2024 char *zFile; /* The file from which to extract data */
2025 char *zConflict; /* The conflict algorithm to use */
2026 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00002027 int nCol; /* Number of columns in the table */
2028 int nByte; /* Number of bytes in an SQL string */
2029 int i, j; /* Loop counters */
2030 int nSep; /* Number of bytes in zSep[] */
2031 int nNull; /* Number of bytes in zNull[] */
2032 char *zSql; /* An SQL statement */
2033 char *zLine; /* A single line of input from the file */
2034 char **azCol; /* zLine[] broken up into columns */
mistachkin6ef5e122014-01-24 17:03:55 +00002035 const char *zCommit; /* How to commit changes */
drh19e2d372005-08-29 23:00:03 +00002036 FILE *in; /* The input file */
2037 int lineno = 0; /* Line number of input file */
2038 char zLineNum[80]; /* Line number print buffer */
2039 Tcl_Obj *pResult; /* interp result */
2040
mistachkin6ef5e122014-01-24 17:03:55 +00002041 const char *zSep;
2042 const char *zNull;
drh19e2d372005-08-29 23:00:03 +00002043 if( objc<5 || objc>7 ){
2044 Tcl_WrongNumArgs(interp, 2, objv,
2045 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2046 return TCL_ERROR;
2047 }
2048 if( objc>=6 ){
2049 zSep = Tcl_GetStringFromObj(objv[5], 0);
2050 }else{
2051 zSep = "\t";
2052 }
2053 if( objc>=7 ){
2054 zNull = Tcl_GetStringFromObj(objv[6], 0);
2055 }else{
2056 zNull = "";
2057 }
2058 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2059 zTable = Tcl_GetStringFromObj(objv[3], 0);
2060 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002061 nSep = strlen30(zSep);
2062 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002063 if( nSep==0 ){
drha198f2b2014-02-07 19:26:13 +00002064 Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2065 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002066 return TCL_ERROR;
2067 }
drh3e59c012008-09-23 10:12:13 +00002068 if(strcmp(zConflict, "rollback") != 0 &&
2069 strcmp(zConflict, "abort" ) != 0 &&
2070 strcmp(zConflict, "fail" ) != 0 &&
2071 strcmp(zConflict, "ignore" ) != 0 &&
2072 strcmp(zConflict, "replace" ) != 0 ) {
drh19e2d372005-08-29 23:00:03 +00002073 Tcl_AppendResult(interp, "Error: \"", zConflict,
2074 "\", conflict-algorithm must be one of: rollback, "
drha198f2b2014-02-07 19:26:13 +00002075 "abort, fail, ignore, or replace", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002076 return TCL_ERROR;
2077 }
2078 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2079 if( zSql==0 ){
drha198f2b2014-02-07 19:26:13 +00002080 Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002081 return TCL_ERROR;
2082 }
drh4f21c4a2008-12-10 22:15:00 +00002083 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002084 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002085 sqlite3_free(zSql);
2086 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002087 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002088 nCol = 0;
2089 }else{
2090 nCol = sqlite3_column_count(pStmt);
2091 }
2092 sqlite3_finalize(pStmt);
2093 if( nCol==0 ) {
2094 return TCL_ERROR;
2095 }
2096 zSql = malloc( nByte + 50 + nCol*2 );
2097 if( zSql==0 ) {
drha198f2b2014-02-07 19:26:13 +00002098 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002099 return TCL_ERROR;
2100 }
2101 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2102 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002103 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002104 for(i=1; i<nCol; i++){
2105 zSql[j++] = ',';
2106 zSql[j++] = '?';
2107 }
2108 zSql[j++] = ')';
2109 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002110 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002111 free(zSql);
2112 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002113 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002114 sqlite3_finalize(pStmt);
2115 return TCL_ERROR;
2116 }
2117 in = fopen(zFile, "rb");
2118 if( in==0 ){
2119 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2120 sqlite3_finalize(pStmt);
2121 return TCL_ERROR;
2122 }
2123 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2124 if( azCol==0 ) {
drha198f2b2014-02-07 19:26:13 +00002125 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh43617e92006-03-06 20:55:46 +00002126 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002127 return TCL_ERROR;
2128 }
drh37527852006-03-16 16:19:56 +00002129 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002130 zCommit = "COMMIT";
2131 while( (zLine = local_getline(0, in))!=0 ){
2132 char *z;
drh19e2d372005-08-29 23:00:03 +00002133 lineno++;
2134 azCol[0] = zLine;
2135 for(i=0, z=zLine; *z; z++){
2136 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2137 *z = 0;
2138 i++;
2139 if( i<nCol ){
2140 azCol[i] = &z[nSep];
2141 z += nSep-1;
2142 }
2143 }
2144 }
2145 if( i+1!=nCol ){
2146 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002147 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002148 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002149 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002150 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002151 "Error: %s line %d: expected %d columns of data but found %d",
2152 zFile, lineno, nCol, i+1);
drha198f2b2014-02-07 19:26:13 +00002153 Tcl_AppendResult(interp, zErr, (char*)0);
drhc1f44942006-05-10 14:39:13 +00002154 free(zErr);
2155 }
drh19e2d372005-08-29 23:00:03 +00002156 zCommit = "ROLLBACK";
2157 break;
2158 }
2159 for(i=0; i<nCol; i++){
2160 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002161 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
drh4f21c4a2008-12-10 22:15:00 +00002162 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002163 ){
drh19e2d372005-08-29 23:00:03 +00002164 sqlite3_bind_null(pStmt, i+1);
2165 }else{
2166 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2167 }
2168 }
2169 sqlite3_step(pStmt);
2170 rc = sqlite3_reset(pStmt);
2171 free(zLine);
2172 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00002173 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002174 zCommit = "ROLLBACK";
2175 break;
2176 }
2177 }
2178 free(azCol);
2179 fclose(in);
2180 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002181 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002182
2183 if( zCommit[0] == 'C' ){
2184 /* success, set result as number of lines processed */
2185 pResult = Tcl_GetObjResult(interp);
2186 Tcl_SetIntObj(pResult, lineno);
2187 rc = TCL_OK;
2188 }else{
2189 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002190 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drha198f2b2014-02-07 19:26:13 +00002191 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2192 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002193 rc = TCL_ERROR;
2194 }
2195 break;
2196 }
2197
drhdcd997e2003-01-31 17:21:49 +00002198 /*
drh41449052006-07-06 17:08:48 +00002199 ** $db enable_load_extension BOOLEAN
2200 **
2201 ** Turn the extension loading feature on or off. It if off by
2202 ** default.
2203 */
2204 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002205#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002206 int onoff;
2207 if( objc!=3 ){
2208 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2209 return TCL_ERROR;
2210 }
2211 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2212 return TCL_ERROR;
2213 }
2214 sqlite3_enable_load_extension(pDb->db, onoff);
2215 break;
drhf533acc2006-12-19 18:57:11 +00002216#else
2217 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
drha198f2b2014-02-07 19:26:13 +00002218 (char*)0);
drhf533acc2006-12-19 18:57:11 +00002219 return TCL_ERROR;
2220#endif
drh41449052006-07-06 17:08:48 +00002221 }
2222
2223 /*
drhdcd997e2003-01-31 17:21:49 +00002224 ** $db errorcode
2225 **
2226 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002227 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002228 */
2229 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002230 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002231 break;
2232 }
dan4a4c11a2009-10-06 14:59:02 +00002233
2234 /*
2235 ** $db exists $sql
2236 ** $db onecolumn $sql
2237 **
2238 ** The onecolumn method is the equivalent of:
2239 ** lindex [$db eval $sql] 0
2240 */
2241 case DB_EXISTS:
2242 case DB_ONECOLUMN: {
2243 DbEvalContext sEval;
2244 if( objc!=3 ){
2245 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2246 return TCL_ERROR;
2247 }
2248
2249 dbEvalInit(&sEval, pDb, objv[2], 0);
2250 rc = dbEvalStep(&sEval);
2251 if( choice==DB_ONECOLUMN ){
2252 if( rc==TCL_OK ){
2253 Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
dand5f12cd2011-08-18 17:47:57 +00002254 }else if( rc==TCL_BREAK ){
2255 Tcl_ResetResult(interp);
dan4a4c11a2009-10-06 14:59:02 +00002256 }
2257 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2258 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
2259 }
2260 dbEvalFinalize(&sEval);
2261
2262 if( rc==TCL_BREAK ){
2263 rc = TCL_OK;
2264 }
2265 break;
2266 }
drh75897232000-05-29 14:26:00 +00002267
2268 /*
drh895d7472004-08-20 16:02:39 +00002269 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002270 **
2271 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002272 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002273 ** If "array" and "code" are omitted, then no callback is every invoked.
2274 ** If "array" is an empty string, then the values are placed in variables
2275 ** that have the same name as the fields extracted by the query.
2276 */
dan4a4c11a2009-10-06 14:59:02 +00002277 case DB_EVAL: {
2278 if( objc<3 || objc>5 ){
2279 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2280 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002281 }
dan4a4c11a2009-10-06 14:59:02 +00002282
drh92febd92004-08-20 18:34:20 +00002283 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002284 DbEvalContext sEval;
2285 Tcl_Obj *pRet = Tcl_NewObj();
2286 Tcl_IncrRefCount(pRet);
2287 dbEvalInit(&sEval, pDb, objv[2], 0);
2288 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2289 int i;
2290 int nCol;
2291 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002292 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002293 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002294 }
2295 }
dan4a4c11a2009-10-06 14:59:02 +00002296 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002297 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002298 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002299 rc = TCL_OK;
2300 }
drh1807ce32004-09-07 13:20:35 +00002301 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002302 }else{
mistachkin8e189222015-04-19 21:43:16 +00002303 ClientData cd2[2];
dan4a4c11a2009-10-06 14:59:02 +00002304 DbEvalContext *p;
2305 Tcl_Obj *pArray = 0;
2306 Tcl_Obj *pScript;
2307
2308 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2309 pArray = objv[3];
2310 }
2311 pScript = objv[objc-1];
2312 Tcl_IncrRefCount(pScript);
2313
2314 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2315 dbEvalInit(p, pDb, objv[2], pArray);
2316
mistachkin8e189222015-04-19 21:43:16 +00002317 cd2[0] = (void *)p;
2318 cd2[1] = (void *)pScript;
2319 rc = DbEvalNextCmd(cd2, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002320 }
danielk197730ccda12004-05-27 12:11:31 +00002321 break;
2322 }
drhbec3f402000-08-04 13:49:02 +00002323
2324 /*
dan3df30592015-03-13 08:31:54 +00002325 ** $db function NAME [-argcount N] [-deterministic] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002326 **
2327 ** Create a new SQL function called NAME. Whenever that function is
2328 ** called, invoke SCRIPT to evaluate the function.
2329 */
2330 case DB_FUNCTION: {
dan3df30592015-03-13 08:31:54 +00002331 int flags = SQLITE_UTF8;
drhcabb0812002-09-14 13:47:32 +00002332 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002333 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002334 char *zName;
drhe3602be2008-09-09 12:31:33 +00002335 int nArg = -1;
dan3df30592015-03-13 08:31:54 +00002336 int i;
2337 if( objc<4 ){
2338 Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
2339 return TCL_ERROR;
2340 }
2341 for(i=3; i<(objc-1); i++){
2342 const char *z = Tcl_GetString(objv[i]);
drh4f21c4a2008-12-10 22:15:00 +00002343 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002344 if( n>2 && strncmp(z, "-argcount",n)==0 ){
dan3df30592015-03-13 08:31:54 +00002345 if( i==(objc-2) ){
2346 Tcl_AppendResult(interp, "option requires an argument: ", z, 0);
2347 return TCL_ERROR;
2348 }
2349 if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002350 if( nArg<0 ){
2351 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2352 (char*)0);
2353 return TCL_ERROR;
2354 }
dan3df30592015-03-13 08:31:54 +00002355 i++;
2356 }else
2357 if( n>2 && strncmp(z, "-deterministic",n)==0 ){
2358 flags |= SQLITE_DETERMINISTIC;
2359 }else{
2360 Tcl_AppendResult(interp, "bad option \"", z,
2361 "\": must be -argcount or -deterministic", 0
2362 );
2363 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002364 }
drhcabb0812002-09-14 13:47:32 +00002365 }
dan3df30592015-03-13 08:31:54 +00002366
2367 pScript = objv[objc-1];
drhcabb0812002-09-14 13:47:32 +00002368 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002369 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002370 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002371 if( pFunc->pScript ){
2372 Tcl_DecrRefCount(pFunc->pScript);
2373 }
2374 pFunc->pScript = pScript;
2375 Tcl_IncrRefCount(pScript);
2376 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
dan3df30592015-03-13 08:31:54 +00002377 rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
danielk1977d8123362004-06-12 09:25:12 +00002378 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002379 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002380 rc = TCL_ERROR;
2381 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002382 }
drhcabb0812002-09-14 13:47:32 +00002383 break;
2384 }
2385
2386 /*
danielk19778cbadb02007-05-03 16:31:26 +00002387 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002388 */
2389 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002390#ifdef SQLITE_OMIT_INCRBLOB
drha198f2b2014-02-07 19:26:13 +00002391 Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
danielk197732a0d8b2007-05-04 19:03:02 +00002392 return TCL_ERROR;
2393#else
danielk19778cbadb02007-05-03 16:31:26 +00002394 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002395 const char *zDb = "main";
2396 const char *zTable;
2397 const char *zColumn;
drhb3f787f2012-09-29 14:45:54 +00002398 Tcl_WideInt iRow;
danielk1977b4e9af92007-05-01 17:49:49 +00002399
danielk19778cbadb02007-05-03 16:31:26 +00002400 /* Check for the -readonly option */
2401 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2402 isReadonly = 1;
2403 }
2404
2405 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2406 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002407 return TCL_ERROR;
2408 }
2409
danielk19778cbadb02007-05-03 16:31:26 +00002410 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002411 zDb = Tcl_GetString(objv[2]);
2412 }
2413 zTable = Tcl_GetString(objv[objc-3]);
2414 zColumn = Tcl_GetString(objv[objc-2]);
2415 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2416
2417 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002418 rc = createIncrblobChannel(
danedf5b162014-08-19 09:15:41 +00002419 interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
danielk19778cbadb02007-05-03 16:31:26 +00002420 );
danielk1977b4e9af92007-05-01 17:49:49 +00002421 }
danielk197732a0d8b2007-05-04 19:03:02 +00002422#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002423 break;
2424 }
2425
2426 /*
drhf11bded2006-07-17 00:02:44 +00002427 ** $db interrupt
2428 **
2429 ** Interrupt the execution of the inner-most SQL interpreter. This
2430 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2431 */
2432 case DB_INTERRUPT: {
2433 sqlite3_interrupt(pDb->db);
2434 break;
2435 }
2436
2437 /*
drh19e2d372005-08-29 23:00:03 +00002438 ** $db nullvalue ?STRING?
2439 **
2440 ** Change text used when a NULL comes back from the database. If ?STRING?
2441 ** is not present, then the current string used for NULL is returned.
2442 ** If STRING is present, then STRING is returned.
2443 **
2444 */
2445 case DB_NULLVALUE: {
2446 if( objc!=2 && objc!=3 ){
2447 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2448 return TCL_ERROR;
2449 }
2450 if( objc==3 ){
2451 int len;
2452 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2453 if( pDb->zNull ){
2454 Tcl_Free(pDb->zNull);
2455 }
2456 if( zNull && len>0 ){
2457 pDb->zNull = Tcl_Alloc( len + 1 );
drh7fd33922011-06-20 19:00:30 +00002458 memcpy(pDb->zNull, zNull, len);
drh19e2d372005-08-29 23:00:03 +00002459 pDb->zNull[len] = '\0';
2460 }else{
2461 pDb->zNull = 0;
2462 }
2463 }
drhc45e6712012-10-03 11:02:33 +00002464 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
drh19e2d372005-08-29 23:00:03 +00002465 break;
2466 }
2467
2468 /*
drhaf9ff332002-01-16 21:00:27 +00002469 ** $db last_insert_rowid
2470 **
2471 ** Return an integer which is the ROWID for the most recent insert.
2472 */
2473 case DB_LAST_INSERT_ROWID: {
2474 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002475 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002476 if( objc!=2 ){
2477 Tcl_WrongNumArgs(interp, 2, objv, "");
2478 return TCL_ERROR;
2479 }
danielk19776f8a5032004-05-10 10:34:51 +00002480 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002481 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002482 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002483 break;
2484 }
2485
2486 /*
dan4a4c11a2009-10-06 14:59:02 +00002487 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002488 */
drh1807ce32004-09-07 13:20:35 +00002489
2490 /* $db progress ?N CALLBACK?
2491 **
2492 ** Invoke the given callback every N virtual machine opcodes while executing
2493 ** queries.
2494 */
2495 case DB_PROGRESS: {
2496 if( objc==2 ){
2497 if( pDb->zProgress ){
drha198f2b2014-02-07 19:26:13 +00002498 Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
drh1807ce32004-09-07 13:20:35 +00002499 }
2500 }else if( objc==4 ){
2501 char *zProgress;
2502 int len;
2503 int N;
2504 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002505 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002506 };
2507 if( pDb->zProgress ){
2508 Tcl_Free(pDb->zProgress);
2509 }
2510 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2511 if( zProgress && len>0 ){
2512 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002513 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002514 }else{
2515 pDb->zProgress = 0;
2516 }
2517#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2518 if( pDb->zProgress ){
2519 pDb->interp = interp;
2520 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2521 }else{
2522 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2523 }
2524#endif
2525 }else{
2526 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002527 return TCL_ERROR;
2528 }
drh5d9d7572003-08-19 14:31:01 +00002529 break;
2530 }
2531
drh19e2d372005-08-29 23:00:03 +00002532 /* $db profile ?CALLBACK?
2533 **
2534 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2535 ** that has run. The text of the SQL and the amount of elapse time are
2536 ** appended to CALLBACK before the script is run.
2537 */
2538 case DB_PROFILE: {
2539 if( objc>3 ){
2540 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2541 return TCL_ERROR;
2542 }else if( objc==2 ){
2543 if( pDb->zProfile ){
drha198f2b2014-02-07 19:26:13 +00002544 Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002545 }
2546 }else{
2547 char *zProfile;
2548 int len;
2549 if( pDb->zProfile ){
2550 Tcl_Free(pDb->zProfile);
2551 }
2552 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2553 if( zProfile && len>0 ){
2554 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002555 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002556 }else{
2557 pDb->zProfile = 0;
2558 }
shanehbb201342011-02-09 19:55:20 +00002559#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh19e2d372005-08-29 23:00:03 +00002560 if( pDb->zProfile ){
2561 pDb->interp = interp;
2562 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2563 }else{
2564 sqlite3_profile(pDb->db, 0, 0);
2565 }
2566#endif
2567 }
2568 break;
2569 }
2570
drh5d9d7572003-08-19 14:31:01 +00002571 /*
drh22fbcb82004-02-01 01:22:50 +00002572 ** $db rekey KEY
2573 **
2574 ** Change the encryption key on the currently open database.
2575 */
2576 case DB_REKEY: {
drh32f57d42016-03-16 01:03:10 +00002577#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh22fbcb82004-02-01 01:22:50 +00002578 int nKey;
2579 void *pKey;
drhb07028f2011-10-14 21:49:18 +00002580#endif
drh22fbcb82004-02-01 01:22:50 +00002581 if( objc!=3 ){
2582 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2583 return TCL_ERROR;
2584 }
drh32f57d42016-03-16 01:03:10 +00002585#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00002586 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh2011d5f2004-07-22 02:40:37 +00002587 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002588 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002589 Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
drh22fbcb82004-02-01 01:22:50 +00002590 rc = TCL_ERROR;
2591 }
2592#endif
2593 break;
2594 }
2595
drhdc2c4912009-02-04 22:46:47 +00002596 /* $db restore ?DATABASE? FILENAME
2597 **
2598 ** Open a database file named FILENAME. Transfer the content
2599 ** of FILENAME into the local database DATABASE (default: "main").
2600 */
2601 case DB_RESTORE: {
2602 const char *zSrcFile;
2603 const char *zDestDb;
2604 sqlite3 *pSrc;
2605 sqlite3_backup *pBackup;
2606 int nTimeout = 0;
2607
2608 if( objc==3 ){
2609 zDestDb = "main";
2610 zSrcFile = Tcl_GetString(objv[2]);
2611 }else if( objc==4 ){
2612 zDestDb = Tcl_GetString(objv[2]);
2613 zSrcFile = Tcl_GetString(objv[3]);
2614 }else{
2615 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2616 return TCL_ERROR;
2617 }
drh147ef392016-01-22 23:17:51 +00002618 rc = sqlite3_open_v2(zSrcFile, &pSrc,
2619 SQLITE_OPEN_READONLY | pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00002620 if( rc!=SQLITE_OK ){
2621 Tcl_AppendResult(interp, "cannot open source database: ",
2622 sqlite3_errmsg(pSrc), (char*)0);
2623 sqlite3_close(pSrc);
2624 return TCL_ERROR;
2625 }
2626 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2627 if( pBackup==0 ){
2628 Tcl_AppendResult(interp, "restore failed: ",
2629 sqlite3_errmsg(pDb->db), (char*)0);
2630 sqlite3_close(pSrc);
2631 return TCL_ERROR;
2632 }
2633 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2634 || rc==SQLITE_BUSY ){
2635 if( rc==SQLITE_BUSY ){
2636 if( nTimeout++ >= 3 ) break;
2637 sqlite3_sleep(100);
2638 }
2639 }
2640 sqlite3_backup_finish(pBackup);
2641 if( rc==SQLITE_DONE ){
2642 rc = TCL_OK;
2643 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2644 Tcl_AppendResult(interp, "restore failed: source database busy",
2645 (char*)0);
2646 rc = TCL_ERROR;
2647 }else{
2648 Tcl_AppendResult(interp, "restore failed: ",
2649 sqlite3_errmsg(pDb->db), (char*)0);
2650 rc = TCL_ERROR;
2651 }
2652 sqlite3_close(pSrc);
2653 break;
2654 }
2655
drh22fbcb82004-02-01 01:22:50 +00002656 /*
drh3c379b02010-04-07 19:31:59 +00002657 ** $db status (step|sort|autoindex)
drhd1d38482008-10-07 23:46:38 +00002658 **
2659 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2660 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2661 */
2662 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002663 int v;
2664 const char *zOp;
2665 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00002666 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00002667 return TCL_ERROR;
2668 }
2669 zOp = Tcl_GetString(objv[2]);
2670 if( strcmp(zOp, "step")==0 ){
2671 v = pDb->nStep;
2672 }else if( strcmp(zOp, "sort")==0 ){
2673 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002674 }else if( strcmp(zOp, "autoindex")==0 ){
2675 v = pDb->nIndex;
drhd1d38482008-10-07 23:46:38 +00002676 }else{
drh3c379b02010-04-07 19:31:59 +00002677 Tcl_AppendResult(interp,
2678 "bad argument: should be autoindex, step, or sort",
drhd1d38482008-10-07 23:46:38 +00002679 (char*)0);
2680 return TCL_ERROR;
2681 }
2682 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2683 break;
2684 }
2685
2686 /*
drhbec3f402000-08-04 13:49:02 +00002687 ** $db timeout MILLESECONDS
2688 **
2689 ** Delay for the number of milliseconds specified when a file is locked.
2690 */
drh6d313162000-09-21 13:01:35 +00002691 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002692 int ms;
drh6d313162000-09-21 13:01:35 +00002693 if( objc!=3 ){
2694 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002695 return TCL_ERROR;
2696 }
drh6d313162000-09-21 13:01:35 +00002697 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002698 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002699 break;
drh75897232000-05-29 14:26:00 +00002700 }
danielk197755c45f22005-04-03 23:54:43 +00002701
2702 /*
drh0f14e2e2004-06-29 12:39:08 +00002703 ** $db total_changes
2704 **
2705 ** Return the number of rows that were modified, inserted, or deleted
2706 ** since the database handle was created.
2707 */
2708 case DB_TOTAL_CHANGES: {
2709 Tcl_Obj *pResult;
2710 if( objc!=2 ){
2711 Tcl_WrongNumArgs(interp, 2, objv, "");
2712 return TCL_ERROR;
2713 }
2714 pResult = Tcl_GetObjResult(interp);
2715 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2716 break;
2717 }
2718
drhb5a20d32003-04-23 12:25:23 +00002719 /* $db trace ?CALLBACK?
2720 **
2721 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2722 ** that is executed. The text of the SQL is appended to CALLBACK before
2723 ** it is executed.
2724 */
2725 case DB_TRACE: {
2726 if( objc>3 ){
2727 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002728 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002729 }else if( objc==2 ){
2730 if( pDb->zTrace ){
drha198f2b2014-02-07 19:26:13 +00002731 Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
drhb5a20d32003-04-23 12:25:23 +00002732 }
2733 }else{
2734 char *zTrace;
2735 int len;
2736 if( pDb->zTrace ){
2737 Tcl_Free(pDb->zTrace);
2738 }
2739 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2740 if( zTrace && len>0 ){
2741 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002742 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002743 }else{
2744 pDb->zTrace = 0;
2745 }
shanehbb201342011-02-09 19:55:20 +00002746#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drhb5a20d32003-04-23 12:25:23 +00002747 if( pDb->zTrace ){
2748 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002749 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002750 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002751 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002752 }
drh19e2d372005-08-29 23:00:03 +00002753#endif
drhb5a20d32003-04-23 12:25:23 +00002754 }
2755 break;
2756 }
2757
drh3d214232005-08-02 12:21:08 +00002758 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2759 **
2760 ** Start a new transaction (if we are not already in the midst of a
2761 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2762 ** completes, either commit the transaction or roll it back if SCRIPT
2763 ** throws an exception. Or if no new transation was started, do nothing.
2764 ** pass the exception on up the stack.
2765 **
2766 ** This command was inspired by Dave Thomas's talk on Ruby at the
2767 ** 2005 O'Reilly Open Source Convention (OSCON).
2768 */
2769 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00002770 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00002771 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00002772 if( objc!=3 && objc!=4 ){
2773 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2774 return TCL_ERROR;
2775 }
danielk1977cd38d522009-01-02 17:33:46 +00002776
dan4a4c11a2009-10-06 14:59:02 +00002777 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00002778 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002779 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002780 };
2781 enum TTYPE_enum {
2782 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2783 };
2784 int ttype;
drhb5555e72005-08-02 17:15:14 +00002785 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002786 0, &ttype) ){
2787 return TCL_ERROR;
2788 }
2789 switch( (enum TTYPE_enum)ttype ){
2790 case TTYPE_DEFERRED: /* no-op */; break;
2791 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2792 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2793 }
drh3d214232005-08-02 12:21:08 +00002794 }
danielk1977cd38d522009-01-02 17:33:46 +00002795 pScript = objv[objc-1];
2796
dan4a4c11a2009-10-06 14:59:02 +00002797 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00002798 pDb->disableAuth++;
2799 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2800 pDb->disableAuth--;
2801 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00002802 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977cd38d522009-01-02 17:33:46 +00002803 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00002804 }
danielk1977cd38d522009-01-02 17:33:46 +00002805 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00002806
dan4a4c11a2009-10-06 14:59:02 +00002807 /* If using NRE, schedule a callback to invoke the script pScript, then
2808 ** a second callback to commit (or rollback) the transaction or savepoint
2809 ** opened above. If not using NRE, evaluate the script directly, then
2810 ** call function DbTransPostCmd() to commit (or rollback) the transaction
2811 ** or savepoint. */
2812 if( DbUseNre() ){
2813 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
drha47941f2013-12-20 18:57:44 +00002814 (void)Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00002815 }else{
dan4a4c11a2009-10-06 14:59:02 +00002816 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00002817 }
2818 break;
2819 }
2820
danielk197794eb6a12005-12-15 15:22:08 +00002821 /*
danielk1977404ca072009-03-16 13:19:36 +00002822 ** $db unlock_notify ?script?
2823 */
2824 case DB_UNLOCK_NOTIFY: {
2825#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
drha198f2b2014-02-07 19:26:13 +00002826 Tcl_AppendResult(interp, "unlock_notify not available in this build",
2827 (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00002828 rc = TCL_ERROR;
2829#else
2830 if( objc!=2 && objc!=3 ){
2831 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2832 rc = TCL_ERROR;
2833 }else{
2834 void (*xNotify)(void **, int) = 0;
2835 void *pNotifyArg = 0;
2836
2837 if( pDb->pUnlockNotify ){
2838 Tcl_DecrRefCount(pDb->pUnlockNotify);
2839 pDb->pUnlockNotify = 0;
2840 }
2841
2842 if( objc==3 ){
2843 xNotify = DbUnlockNotify;
2844 pNotifyArg = (void *)pDb;
2845 pDb->pUnlockNotify = objv[2];
2846 Tcl_IncrRefCount(pDb->pUnlockNotify);
2847 }
2848
2849 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
drha198f2b2014-02-07 19:26:13 +00002850 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00002851 rc = TCL_ERROR;
2852 }
2853 }
2854#endif
2855 break;
2856 }
2857
2858 /*
drh833bf962010-04-28 14:42:19 +00002859 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002860 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002861 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002862 */
drh833bf962010-04-28 14:42:19 +00002863 case DB_WAL_HOOK:
danielk197771fd80b2005-12-16 06:54:01 +00002864 case DB_UPDATE_HOOK:
2865 case DB_ROLLBACK_HOOK: {
2866
2867 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2868 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2869 */
2870 Tcl_Obj **ppHook;
2871 if( choice==DB_UPDATE_HOOK ){
2872 ppHook = &pDb->pUpdateHook;
drh833bf962010-04-28 14:42:19 +00002873 }else if( choice==DB_WAL_HOOK ){
drh5def0842010-05-05 20:00:25 +00002874 ppHook = &pDb->pWalHook;
danielk197771fd80b2005-12-16 06:54:01 +00002875 }else{
2876 ppHook = &pDb->pRollbackHook;
2877 }
2878
danielk197794eb6a12005-12-15 15:22:08 +00002879 if( objc!=2 && objc!=3 ){
2880 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2881 return TCL_ERROR;
2882 }
danielk197771fd80b2005-12-16 06:54:01 +00002883 if( *ppHook ){
2884 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002885 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002886 Tcl_DecrRefCount(*ppHook);
2887 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00002888 }
2889 }
2890 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002891 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00002892 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00002893 *ppHook = objv[2];
2894 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002895 }
2896 }
danielk197771fd80b2005-12-16 06:54:01 +00002897
2898 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2899 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
drh5def0842010-05-05 20:00:25 +00002900 sqlite3_wal_hook(pDb->db,(pDb->pWalHook?DbWalHandler:0),pDb);
danielk197771fd80b2005-12-16 06:54:01 +00002901
danielk197794eb6a12005-12-15 15:22:08 +00002902 break;
2903 }
2904
danielk19774397de52005-01-12 12:44:03 +00002905 /* $db version
2906 **
2907 ** Return the version string for this database.
2908 */
2909 case DB_VERSION: {
2910 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2911 break;
2912 }
2913
tpoindex1067fe12004-12-17 15:41:11 +00002914
drh6d313162000-09-21 13:01:35 +00002915 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002916 return rc;
drh75897232000-05-29 14:26:00 +00002917}
2918
drha2c8a952009-10-13 18:38:34 +00002919#if SQLITE_TCL_NRE
2920/*
2921** Adaptor that provides an objCmd interface to the NRE-enabled
2922** interface implementation.
2923*/
2924static int DbObjCmdAdaptor(
2925 void *cd,
2926 Tcl_Interp *interp,
2927 int objc,
2928 Tcl_Obj *const*objv
2929){
2930 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
2931}
2932#endif /* SQLITE_TCL_NRE */
2933
drh75897232000-05-29 14:26:00 +00002934/*
drh3570ad92007-08-31 14:31:44 +00002935** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00002936** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00002937**
2938** This is the main Tcl command. When the "sqlite" Tcl command is
2939** invoked, this routine runs to process that command.
2940**
2941** The first argument, DBNAME, is an arbitrary name for a new
2942** database connection. This command creates a new command named
2943** DBNAME that is used to control that connection. The database
2944** connection is deleted when the DBNAME command is deleted.
2945**
drh3570ad92007-08-31 14:31:44 +00002946** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00002947**
drh75897232000-05-29 14:26:00 +00002948*/
drh22fbcb82004-02-01 01:22:50 +00002949static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002950 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002951 const char *zArg;
drh75897232000-05-29 14:26:00 +00002952 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00002953 int i;
drh22fbcb82004-02-01 01:22:50 +00002954 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00002955 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00002956 int flags;
drh882e8e42006-08-24 02:42:27 +00002957 Tcl_DString translatedFilename;
drh32f57d42016-03-16 01:03:10 +00002958#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00002959 void *pKey = 0;
2960 int nKey = 0;
2961#endif
mistachkin540ebf82012-09-10 07:29:29 +00002962 int rc;
drhd9da78a2009-03-24 15:08:09 +00002963
2964 /* In normal use, each TCL interpreter runs in a single thread. So
2965 ** by default, we can turn of mutexing on SQLite database connections.
2966 ** However, for testing purposes it is useful to have mutexes turned
2967 ** on. So, by default, mutexes default off. But if compiled with
2968 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
2969 */
2970#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
2971 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
2972#else
2973 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
2974#endif
2975
drh22fbcb82004-02-01 01:22:50 +00002976 if( objc==2 ){
2977 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002978 if( strcmp(zArg,"-version")==0 ){
drha198f2b2014-02-07 19:26:13 +00002979 Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
drh647cb0e2002-11-04 19:32:25 +00002980 return TCL_OK;
2981 }
drh72bf6a32016-01-07 02:06:55 +00002982 if( strcmp(zArg,"-sourceid")==0 ){
2983 Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0);
2984 return TCL_OK;
2985 }
drh9eb9e262004-02-11 02:18:05 +00002986 if( strcmp(zArg,"-has-codec")==0 ){
drh32f57d42016-03-16 01:03:10 +00002987#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drha198f2b2014-02-07 19:26:13 +00002988 Tcl_AppendResult(interp,"1",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00002989#else
drha198f2b2014-02-07 19:26:13 +00002990 Tcl_AppendResult(interp,"0",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00002991#endif
2992 return TCL_OK;
2993 }
drhfbc3eab2001-04-06 16:13:42 +00002994 }
drh3570ad92007-08-31 14:31:44 +00002995 for(i=3; i+1<objc; i+=2){
2996 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00002997 if( strcmp(zArg,"-key")==0 ){
drh32f57d42016-03-16 01:03:10 +00002998#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh3570ad92007-08-31 14:31:44 +00002999 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
drhb07028f2011-10-14 21:49:18 +00003000#endif
drh3570ad92007-08-31 14:31:44 +00003001 }else if( strcmp(zArg, "-vfs")==0 ){
dan3c3dd7b2010-06-22 11:10:40 +00003002 zVfs = Tcl_GetString(objv[i+1]);
drh3570ad92007-08-31 14:31:44 +00003003 }else if( strcmp(zArg, "-readonly")==0 ){
3004 int b;
3005 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3006 if( b ){
drh33f4e022007-09-03 15:19:34 +00003007 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00003008 flags |= SQLITE_OPEN_READONLY;
3009 }else{
3010 flags &= ~SQLITE_OPEN_READONLY;
3011 flags |= SQLITE_OPEN_READWRITE;
3012 }
3013 }else if( strcmp(zArg, "-create")==0 ){
3014 int b;
3015 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00003016 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00003017 flags |= SQLITE_OPEN_CREATE;
3018 }else{
3019 flags &= ~SQLITE_OPEN_CREATE;
3020 }
danielk19779a6284c2008-07-10 17:52:49 +00003021 }else if( strcmp(zArg, "-nomutex")==0 ){
3022 int b;
3023 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3024 if( b ){
3025 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00003026 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00003027 }else{
3028 flags &= ~SQLITE_OPEN_NOMUTEX;
3029 }
danc431fd52011-06-27 16:55:50 +00003030 }else if( strcmp(zArg, "-fullmutex")==0 ){
drh039963a2008-09-03 00:43:15 +00003031 int b;
3032 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3033 if( b ){
3034 flags |= SQLITE_OPEN_FULLMUTEX;
3035 flags &= ~SQLITE_OPEN_NOMUTEX;
3036 }else{
3037 flags &= ~SQLITE_OPEN_FULLMUTEX;
3038 }
drhf12b3f62011-12-21 14:42:29 +00003039 }else if( strcmp(zArg, "-uri")==0 ){
3040 int b;
3041 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3042 if( b ){
3043 flags |= SQLITE_OPEN_URI;
3044 }else{
3045 flags &= ~SQLITE_OPEN_URI;
3046 }
drh3570ad92007-08-31 14:31:44 +00003047 }else{
3048 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3049 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00003050 }
3051 }
drh3570ad92007-08-31 14:31:44 +00003052 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00003053 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00003054 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh68bd4aa2012-01-13 16:16:10 +00003055 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
drh32f57d42016-03-16 01:03:10 +00003056#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh3570ad92007-08-31 14:31:44 +00003057 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00003058#endif
3059 );
drh75897232000-05-29 14:26:00 +00003060 return TCL_ERROR;
3061 }
drh75897232000-05-29 14:26:00 +00003062 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003063 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00003064 if( p==0 ){
mistachkin6ef5e122014-01-24 17:03:55 +00003065 Tcl_SetResult(interp, (char *)"malloc failed", TCL_STATIC);
drhbec3f402000-08-04 13:49:02 +00003066 return TCL_ERROR;
3067 }
3068 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00003069 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00003070 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003071 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00003072 Tcl_DStringFree(&translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003073 if( p->db ){
3074 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3075 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3076 sqlite3_close(p->db);
3077 p->db = 0;
3078 }
3079 }else{
mistachkin5dac8432012-09-11 02:00:25 +00003080 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
danielk197780290862004-05-22 09:21:21 +00003081 }
drh32f57d42016-03-16 01:03:10 +00003082#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhf3a65f72007-08-22 20:18:21 +00003083 if( p->db ){
3084 sqlite3_key(p->db, pKey, nKey);
3085 }
drheb8ed702004-02-11 10:37:23 +00003086#endif
drhbec3f402000-08-04 13:49:02 +00003087 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003088 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003089 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003090 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003091 return TCL_ERROR;
3092 }
drhfb7e7652005-01-24 00:28:42 +00003093 p->maxStmt = NUM_PREPARED_STMTS;
drh147ef392016-01-22 23:17:51 +00003094 p->openFlags = flags & SQLITE_OPEN_URI;
drh5169bbc2006-08-24 14:59:45 +00003095 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003096 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003097 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003098 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3099 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003100 }else{
3101 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3102 }
drh75897232000-05-29 14:26:00 +00003103 return TCL_OK;
3104}
3105
3106/*
drh90ca9752001-09-28 17:47:14 +00003107** Provide a dummy Tcl_InitStubs if we are using this as a static
3108** library.
3109*/
3110#ifndef USE_TCL_STUBS
3111# undef Tcl_InitStubs
drh0e85ccf2013-06-03 12:34:46 +00003112# define Tcl_InitStubs(a,b,c) TCL_VERSION
drh90ca9752001-09-28 17:47:14 +00003113#endif
3114
3115/*
drh29bc4612005-10-05 10:40:15 +00003116** Make sure we have a PACKAGE_VERSION macro defined. This will be
3117** defined automatically by the TEA makefile. But other makefiles
3118** do not define it.
3119*/
3120#ifndef PACKAGE_VERSION
3121# define PACKAGE_VERSION SQLITE_VERSION
3122#endif
3123
3124/*
drh75897232000-05-29 14:26:00 +00003125** Initialize this module.
3126**
3127** This Tcl module contains only a single new Tcl command named "sqlite".
3128** (Hence there is no namespace. There is no point in using a namespace
3129** if the extension only supplies one new name!) The "sqlite" command is
3130** used to open a new SQLite database. See the DbMain() routine above
3131** for additional information.
drhb652f432010-08-26 16:46:57 +00003132**
3133** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003134*/
drhb652f432010-08-26 16:46:57 +00003135EXTERN int Sqlite3_Init(Tcl_Interp *interp){
mistachkin27b2f052015-01-12 19:49:46 +00003136 int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
drh6dc8cbe2013-05-31 15:36:07 +00003137 if( rc==TCL_OK ){
3138 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh1cca0d22010-08-25 20:35:51 +00003139#ifndef SQLITE_3_SUFFIX_ONLY
drh6dc8cbe2013-05-31 15:36:07 +00003140 /* The "sqlite" alias is undocumented. It is here only to support
3141 ** legacy scripts. All new scripts should use only the "sqlite3"
3142 ** command. */
3143 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003144#endif
drh6dc8cbe2013-05-31 15:36:07 +00003145 rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3146 }
3147 return rc;
drh90ca9752001-09-28 17:47:14 +00003148}
drhb652f432010-08-26 16:46:57 +00003149EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
drhb652f432010-08-26 16:46:57 +00003150EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3151EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00003152
drhd878cab2012-03-20 15:10:42 +00003153/* Because it accesses the file-system and uses persistent state, SQLite
drhe75a9eb2016-02-13 18:54:10 +00003154** is not considered appropriate for safe interpreters. Hence, we cause
3155** the _SafeInit() interfaces return TCL_ERROR.
drhd878cab2012-03-20 15:10:42 +00003156*/
drhe75a9eb2016-02-13 18:54:10 +00003157EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
3158EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
3159
3160
drh49766d62005-01-08 18:42:28 +00003161
3162#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003163int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3164int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
dana3e63c42010-08-20 12:33:59 +00003165int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3166int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00003167#endif
drh75897232000-05-29 14:26:00 +00003168
drh3e27c022004-07-23 00:01:38 +00003169#ifdef TCLSH
3170/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003171** All of the code that follows is used to build standalone TCL interpreters
3172** that are statically linked with SQLite. Enable these by compiling
3173** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3174** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3175** analysis program.
drh75897232000-05-29 14:26:00 +00003176*/
drh348784e2000-05-29 20:41:49 +00003177
drh57a02272009-10-22 20:52:05 +00003178#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3179/*
3180 * This code implements the MD5 message-digest algorithm.
3181 * The algorithm is due to Ron Rivest. This code was
3182 * written by Colin Plumb in 1993, no copyright is claimed.
3183 * This code is in the public domain; do with it what you wish.
3184 *
3185 * Equivalent code is available from RSA Data Security, Inc.
3186 * This code has been tested against that, and is equivalent,
3187 * except that you don't need to include two pages of legalese
3188 * with every copy.
3189 *
3190 * To compute the message digest of a chunk of bytes, declare an
3191 * MD5Context structure, pass it to MD5Init, call MD5Update as
3192 * needed on buffers full of bytes, and then call MD5Final, which
3193 * will fill a supplied 16-byte array with the digest.
3194 */
3195
3196/*
3197 * If compiled on a machine that doesn't have a 32-bit integer,
3198 * you just set "uint32" to the appropriate datatype for an
3199 * unsigned 32-bit integer. For example:
3200 *
3201 * cc -Duint32='unsigned long' md5.c
3202 *
3203 */
3204#ifndef uint32
3205# define uint32 unsigned int
3206#endif
3207
3208struct MD5Context {
3209 int isInit;
3210 uint32 buf[4];
3211 uint32 bits[2];
3212 unsigned char in[64];
3213};
3214typedef struct MD5Context MD5Context;
3215
3216/*
3217 * Note: this code is harmless on little-endian machines.
3218 */
3219static void byteReverse (unsigned char *buf, unsigned longs){
3220 uint32 t;
3221 do {
3222 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3223 ((unsigned)buf[1]<<8 | buf[0]);
3224 *(uint32 *)buf = t;
3225 buf += 4;
3226 } while (--longs);
3227}
3228/* The four core functions - F1 is optimized somewhat */
3229
3230/* #define F1(x, y, z) (x & y | ~x & z) */
3231#define F1(x, y, z) (z ^ (x & (y ^ z)))
3232#define F2(x, y, z) F1(z, x, y)
3233#define F3(x, y, z) (x ^ y ^ z)
3234#define F4(x, y, z) (y ^ (x | ~z))
3235
3236/* This is the central step in the MD5 algorithm. */
3237#define MD5STEP(f, w, x, y, z, data, s) \
3238 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3239
3240/*
3241 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3242 * reflect the addition of 16 longwords of new data. MD5Update blocks
3243 * the data and converts bytes into longwords for this routine.
3244 */
3245static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3246 register uint32 a, b, c, d;
3247
3248 a = buf[0];
3249 b = buf[1];
3250 c = buf[2];
3251 d = buf[3];
3252
3253 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3254 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3255 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3256 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3257 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3258 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3259 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3260 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3261 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3262 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3263 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3264 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3265 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3266 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3267 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3268 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3269
3270 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3271 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3272 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3273 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3274 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3275 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3276 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3277 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3278 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3279 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3280 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3281 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3282 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3283 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3284 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3285 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3286
3287 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3288 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3289 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3290 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3291 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3292 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3293 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3294 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3295 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3296 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3297 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3298 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3299 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3300 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3301 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3302 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3303
3304 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3305 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3306 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3307 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3308 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3309 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3310 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3311 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3312 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3313 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3314 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3315 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3316 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3317 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3318 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3319 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3320
3321 buf[0] += a;
3322 buf[1] += b;
3323 buf[2] += c;
3324 buf[3] += d;
3325}
3326
3327/*
3328 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3329 * initialization constants.
3330 */
3331static void MD5Init(MD5Context *ctx){
3332 ctx->isInit = 1;
3333 ctx->buf[0] = 0x67452301;
3334 ctx->buf[1] = 0xefcdab89;
3335 ctx->buf[2] = 0x98badcfe;
3336 ctx->buf[3] = 0x10325476;
3337 ctx->bits[0] = 0;
3338 ctx->bits[1] = 0;
3339}
3340
3341/*
3342 * Update context to reflect the concatenation of another buffer full
3343 * of bytes.
3344 */
3345static
3346void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3347 uint32 t;
3348
3349 /* Update bitcount */
3350
3351 t = ctx->bits[0];
3352 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3353 ctx->bits[1]++; /* Carry from low to high */
3354 ctx->bits[1] += len >> 29;
3355
3356 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3357
3358 /* Handle any leading odd-sized chunks */
3359
3360 if ( t ) {
3361 unsigned char *p = (unsigned char *)ctx->in + t;
3362
3363 t = 64-t;
3364 if (len < t) {
3365 memcpy(p, buf, len);
3366 return;
3367 }
3368 memcpy(p, buf, t);
3369 byteReverse(ctx->in, 16);
3370 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3371 buf += t;
3372 len -= t;
3373 }
3374
3375 /* Process data in 64-byte chunks */
3376
3377 while (len >= 64) {
3378 memcpy(ctx->in, buf, 64);
3379 byteReverse(ctx->in, 16);
3380 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3381 buf += 64;
3382 len -= 64;
3383 }
3384
3385 /* Handle any remaining bytes of data. */
3386
3387 memcpy(ctx->in, buf, len);
3388}
3389
3390/*
3391 * Final wrapup - pad to 64-byte boundary with the bit pattern
3392 * 1 0* (64-bit count of bits processed, MSB-first)
3393 */
3394static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3395 unsigned count;
3396 unsigned char *p;
3397
3398 /* Compute number of bytes mod 64 */
3399 count = (ctx->bits[0] >> 3) & 0x3F;
3400
3401 /* Set the first char of padding to 0x80. This is safe since there is
3402 always at least one byte free */
3403 p = ctx->in + count;
3404 *p++ = 0x80;
3405
3406 /* Bytes of padding needed to make 64 bytes */
3407 count = 64 - 1 - count;
3408
3409 /* Pad out to 56 mod 64 */
3410 if (count < 8) {
3411 /* Two lots of padding: Pad the first block to 64 bytes */
3412 memset(p, 0, count);
3413 byteReverse(ctx->in, 16);
3414 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3415
3416 /* Now fill the next block with 56 bytes */
3417 memset(ctx->in, 0, 56);
3418 } else {
3419 /* Pad block to 56 bytes */
3420 memset(p, 0, count-8);
3421 }
3422 byteReverse(ctx->in, 14);
3423
3424 /* Append length in bits and transform */
drha47941f2013-12-20 18:57:44 +00003425 memcpy(ctx->in + 14*4, ctx->bits, 8);
drh57a02272009-10-22 20:52:05 +00003426
3427 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3428 byteReverse((unsigned char *)ctx->buf, 4);
3429 memcpy(digest, ctx->buf, 16);
drh57a02272009-10-22 20:52:05 +00003430}
3431
3432/*
3433** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3434*/
3435static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3436 static char const zEncode[] = "0123456789abcdef";
3437 int i, j;
3438
3439 for(j=i=0; i<16; i++){
3440 int a = digest[i];
3441 zBuf[j++] = zEncode[(a>>4)&0xf];
3442 zBuf[j++] = zEncode[a & 0xf];
3443 }
3444 zBuf[j] = 0;
3445}
3446
3447
3448/*
3449** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3450** each representing 16 bits of the digest and separated from each
3451** other by a "-" character.
3452*/
3453static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3454 int i, j;
3455 unsigned int x;
3456 for(i=j=0; i<16; i+=2){
3457 x = digest[i]*256 + digest[i+1];
3458 if( i>0 ) zDigest[j++] = '-';
drh05f6c672015-02-26 16:32:33 +00003459 sqlite3_snprintf(50-j, &zDigest[j], "%05u", x);
drh57a02272009-10-22 20:52:05 +00003460 j += 5;
3461 }
3462 zDigest[j] = 0;
3463}
3464
3465/*
3466** A TCL command for md5. The argument is the text to be hashed. The
3467** Result is the hash in base64.
3468*/
3469static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3470 MD5Context ctx;
3471 unsigned char digest[16];
3472 char zBuf[50];
3473 void (*converter)(unsigned char*, char*);
3474
3475 if( argc!=2 ){
3476 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
drha198f2b2014-02-07 19:26:13 +00003477 " TEXT\"", (char*)0);
drh57a02272009-10-22 20:52:05 +00003478 return TCL_ERROR;
3479 }
3480 MD5Init(&ctx);
3481 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3482 MD5Final(digest, &ctx);
3483 converter = (void(*)(unsigned char*,char*))cd;
3484 converter(digest, zBuf);
3485 Tcl_AppendResult(interp, zBuf, (char*)0);
3486 return TCL_OK;
3487}
3488
3489/*
3490** A TCL command to take the md5 hash of a file. The argument is the
3491** name of the file.
3492*/
3493static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3494 FILE *in;
3495 MD5Context ctx;
3496 void (*converter)(unsigned char*, char*);
3497 unsigned char digest[16];
3498 char zBuf[10240];
3499
3500 if( argc!=2 ){
3501 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
drha198f2b2014-02-07 19:26:13 +00003502 " FILENAME\"", (char*)0);
drh57a02272009-10-22 20:52:05 +00003503 return TCL_ERROR;
3504 }
3505 in = fopen(argv[1],"rb");
3506 if( in==0 ){
3507 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
drha198f2b2014-02-07 19:26:13 +00003508 "\" for reading", (char*)0);
drh57a02272009-10-22 20:52:05 +00003509 return TCL_ERROR;
3510 }
3511 MD5Init(&ctx);
3512 for(;;){
3513 int n;
drh83cc1392012-04-19 18:04:28 +00003514 n = (int)fread(zBuf, 1, sizeof(zBuf), in);
drh57a02272009-10-22 20:52:05 +00003515 if( n<=0 ) break;
3516 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3517 }
3518 fclose(in);
3519 MD5Final(digest, &ctx);
3520 converter = (void(*)(unsigned char*,char*))cd;
3521 converter(digest, zBuf);
3522 Tcl_AppendResult(interp, zBuf, (char*)0);
3523 return TCL_OK;
3524}
3525
3526/*
3527** Register the four new TCL commands for generating MD5 checksums
3528** with the TCL interpreter.
3529*/
3530int Md5_Init(Tcl_Interp *interp){
3531 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3532 MD5DigestToBase16, 0);
3533 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3534 MD5DigestToBase10x8, 0);
3535 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3536 MD5DigestToBase16, 0);
3537 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3538 MD5DigestToBase10x8, 0);
3539 return TCL_OK;
3540}
3541#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3542
3543#if defined(SQLITE_TEST)
3544/*
3545** During testing, the special md5sum() aggregate function is available.
3546** inside SQLite. The following routines implement that function.
3547*/
3548static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3549 MD5Context *p;
3550 int i;
3551 if( argc<1 ) return;
3552 p = sqlite3_aggregate_context(context, sizeof(*p));
3553 if( p==0 ) return;
3554 if( !p->isInit ){
3555 MD5Init(p);
3556 }
3557 for(i=0; i<argc; i++){
3558 const char *zData = (char*)sqlite3_value_text(argv[i]);
3559 if( zData ){
drh83cc1392012-04-19 18:04:28 +00003560 MD5Update(p, (unsigned char*)zData, (int)strlen(zData));
drh57a02272009-10-22 20:52:05 +00003561 }
3562 }
3563}
3564static void md5finalize(sqlite3_context *context){
3565 MD5Context *p;
3566 unsigned char digest[16];
3567 char zBuf[33];
3568 p = sqlite3_aggregate_context(context, sizeof(*p));
3569 MD5Final(digest,p);
3570 MD5DigestToBase16(digest, zBuf);
3571 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3572}
3573int Md5_Register(sqlite3 *db){
3574 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
3575 md5step, md5finalize);
3576 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3577 return rc;
3578}
3579#endif /* defined(SQLITE_TEST) */
3580
3581
drh348784e2000-05-29 20:41:49 +00003582/*
drh3e27c022004-07-23 00:01:38 +00003583** If the macro TCLSH is one, then put in code this for the
3584** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003585** standard input, or if a file is named on the command line
3586** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003587*/
drh3e27c022004-07-23 00:01:38 +00003588#if TCLSH==1
dan0ae479d2011-09-21 16:43:07 +00003589static const char *tclsh_main_loop(void){
3590 static const char zMainloop[] =
3591 "set line {}\n"
3592 "while {![eof stdin]} {\n"
3593 "if {$line!=\"\"} {\n"
3594 "puts -nonewline \"> \"\n"
3595 "} else {\n"
3596 "puts -nonewline \"% \"\n"
drh348784e2000-05-29 20:41:49 +00003597 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003598 "flush stdout\n"
3599 "append line [gets stdin]\n"
3600 "if {[info complete $line]} {\n"
3601 "if {[catch {uplevel #0 $line} result]} {\n"
3602 "puts stderr \"Error: $result\"\n"
3603 "} elseif {$result!=\"\"} {\n"
3604 "puts $result\n"
3605 "}\n"
3606 "set line {}\n"
3607 "} else {\n"
3608 "append line \\n\n"
3609 "}\n"
drh348784e2000-05-29 20:41:49 +00003610 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003611 ;
3612 return zMainloop;
3613}
drh3e27c022004-07-23 00:01:38 +00003614#endif
drh3a0f13f2010-07-12 16:47:48 +00003615#if TCLSH==2
dan0ae479d2011-09-21 16:43:07 +00003616static const char *tclsh_main_loop(void);
drh3a0f13f2010-07-12 16:47:48 +00003617#endif
drh3e27c022004-07-23 00:01:38 +00003618
danc1a60c52010-06-07 14:28:16 +00003619#ifdef SQLITE_TEST
3620static void init_all(Tcl_Interp *);
3621static int init_all_cmd(
3622 ClientData cd,
3623 Tcl_Interp *interp,
3624 int objc,
3625 Tcl_Obj *CONST objv[]
3626){
danielk19770a549072009-02-17 16:29:10 +00003627
danc1a60c52010-06-07 14:28:16 +00003628 Tcl_Interp *slave;
3629 if( objc!=2 ){
3630 Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3631 return TCL_ERROR;
3632 }
3633
3634 slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3635 if( !slave ){
3636 return TCL_ERROR;
3637 }
3638
3639 init_all(slave);
3640 return TCL_OK;
3641}
danc431fd52011-06-27 16:55:50 +00003642
3643/*
3644** Tclcmd: db_use_legacy_prepare DB BOOLEAN
3645**
3646** The first argument to this command must be a database command created by
3647** [sqlite3]. If the second argument is true, then the handle is configured
3648** to use the sqlite3_prepare_v2() function to prepare statements. If it
3649** is false, sqlite3_prepare().
3650*/
3651static int db_use_legacy_prepare_cmd(
3652 ClientData cd,
3653 Tcl_Interp *interp,
3654 int objc,
3655 Tcl_Obj *CONST objv[]
3656){
3657 Tcl_CmdInfo cmdInfo;
3658 SqliteDb *pDb;
3659 int bPrepare;
3660
3661 if( objc!=3 ){
3662 Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
3663 return TCL_ERROR;
3664 }
3665
3666 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3667 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3668 return TCL_ERROR;
3669 }
3670 pDb = (SqliteDb*)cmdInfo.objClientData;
3671 if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
3672 return TCL_ERROR;
3673 }
3674
3675 pDb->bLegacyPrepare = bPrepare;
3676
3677 Tcl_ResetResult(interp);
3678 return TCL_OK;
3679}
dan04489b62014-10-31 20:11:32 +00003680
3681/*
3682** Tclcmd: db_last_stmt_ptr DB
3683**
3684** If the statement cache associated with database DB is not empty,
3685** return the text representation of the most recently used statement
3686** handle.
3687*/
3688static int db_last_stmt_ptr(
3689 ClientData cd,
3690 Tcl_Interp *interp,
3691 int objc,
3692 Tcl_Obj *CONST objv[]
3693){
3694 extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
3695 Tcl_CmdInfo cmdInfo;
3696 SqliteDb *pDb;
3697 sqlite3_stmt *pStmt = 0;
3698 char zBuf[100];
3699
3700 if( objc!=2 ){
3701 Tcl_WrongNumArgs(interp, 1, objv, "DB");
3702 return TCL_ERROR;
3703 }
3704
3705 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3706 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3707 return TCL_ERROR;
3708 }
3709 pDb = (SqliteDb*)cmdInfo.objClientData;
3710
3711 if( pDb->stmtList ) pStmt = pDb->stmtList->pStmt;
3712 if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ){
3713 return TCL_ERROR;
3714 }
3715 Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
3716
3717 return TCL_OK;
3718}
drh1a4a6802015-05-04 18:31:09 +00003719#endif /* SQLITE_TEST */
danc1a60c52010-06-07 14:28:16 +00003720
3721/*
3722** Configure the interpreter passed as the first argument to have access
3723** to the commands and linked variables that make up:
3724**
3725** * the [sqlite3] extension itself,
3726**
3727** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
3728**
3729** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
3730** test suite.
3731*/
3732static void init_all(Tcl_Interp *interp){
drh38f82712004-06-18 17:10:16 +00003733 Sqlite3_Init(interp);
danc1a60c52010-06-07 14:28:16 +00003734
drh57a02272009-10-22 20:52:05 +00003735#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3736 Md5_Init(interp);
3737#endif
danc1a60c52010-06-07 14:28:16 +00003738
drhd9b02572001-04-15 00:37:09 +00003739#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00003740 {
drh2f999a62007-08-15 19:16:43 +00003741 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00003742 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00003743 extern int Sqlitetest2_Init(Tcl_Interp*);
3744 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00003745 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00003746 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00003747 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00003748 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00003749 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00003750 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00003751 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00003752 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
danb391b942014-11-07 14:41:11 +00003753 extern int Sqlitetest_blob_Init(Tcl_Interp*);
dan0a7a9152010-04-07 07:57:38 +00003754 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
drh984bfaa2008-03-19 16:08:53 +00003755 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00003756 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00003757 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003758 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00003759 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003760 extern int Sqlitetestschema_Init(Tcl_Interp*);
3761 extern int Sqlitetestsse_Init(Tcl_Interp*);
3762 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
dan9f5ff372013-01-11 09:58:54 +00003763 extern int Sqlitetestfs_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00003764 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00003765 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00003766 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00003767 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh522efc62009-11-10 17:24:37 +00003768 extern int Sqlitetestintarray_Init(Tcl_Interp*);
danc7991bd2010-05-05 19:04:59 +00003769 extern int Sqlitetestvfs_Init(Tcl_Interp *);
dan9508daa2010-08-28 18:58:00 +00003770 extern int Sqlitetestrtree_Init(Tcl_Interp*);
dan8cf35eb2010-09-01 11:40:05 +00003771 extern int Sqlitequota_Init(Tcl_Interp*);
shaneh8a922f72010-11-04 20:50:27 +00003772 extern int Sqlitemultiplex_Init(Tcl_Interp*);
dane336b002010-11-19 18:20:09 +00003773 extern int SqliteSuperlock_Init(Tcl_Interp*);
dan213ca0a2011-03-28 19:10:06 +00003774 extern int SqlitetestSyscall_Init(Tcl_Interp*);
dan89a89562014-12-01 20:05:00 +00003775 extern int Fts5tcl_Init(Tcl_Interp *);
drhcfb8f8d2015-07-23 20:44:49 +00003776 extern int SqliteRbu_Init(Tcl_Interp*);
dan8e4251b2016-03-01 18:07:43 +00003777 extern int Sqlitetesttcl_Init(Tcl_Interp*);
dan6764a702011-06-20 11:15:06 +00003778#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00003779 extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
3780#endif
3781
danb29010c2010-12-29 18:24:38 +00003782#ifdef SQLITE_ENABLE_ZIPVFS
3783 extern int Zipvfs_Init(Tcl_Interp*);
3784 Zipvfs_Init(interp);
3785#endif
3786
drh2f999a62007-08-15 19:16:43 +00003787 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00003788 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00003789 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00003790 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00003791 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00003792 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00003793 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00003794 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00003795 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00003796 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00003797 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00003798 Sqlitetest_autoext_Init(interp);
danb391b942014-11-07 14:41:11 +00003799 Sqlitetest_blob_Init(interp);
dan0a7a9152010-04-07 07:57:38 +00003800 Sqlitetest_demovfs_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00003801 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00003802 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00003803 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003804 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00003805 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003806 Sqlitetestschema_Init(interp);
3807 Sqlitetesttclvar_Init(interp);
dan9f5ff372013-01-11 09:58:54 +00003808 Sqlitetestfs_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00003809 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003810 SqlitetestOnefile_Init(interp);
danielk19775d1f5aa2008-04-10 14:51:00 +00003811 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00003812 Sqlitetestbackup_Init(interp);
drh522efc62009-11-10 17:24:37 +00003813 Sqlitetestintarray_Init(interp);
danc7991bd2010-05-05 19:04:59 +00003814 Sqlitetestvfs_Init(interp);
dan9508daa2010-08-28 18:58:00 +00003815 Sqlitetestrtree_Init(interp);
dan8cf35eb2010-09-01 11:40:05 +00003816 Sqlitequota_Init(interp);
shaneh8a922f72010-11-04 20:50:27 +00003817 Sqlitemultiplex_Init(interp);
dane336b002010-11-19 18:20:09 +00003818 SqliteSuperlock_Init(interp);
dan213ca0a2011-03-28 19:10:06 +00003819 SqlitetestSyscall_Init(interp);
dan89a89562014-12-01 20:05:00 +00003820 Fts5tcl_Init(interp);
drhcfb8f8d2015-07-23 20:44:49 +00003821 SqliteRbu_Init(interp);
dan8e4251b2016-03-01 18:07:43 +00003822 Sqlitetesttcl_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003823
dan6764a702011-06-20 11:15:06 +00003824#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00003825 Sqlitetestfts3_Init(interp);
3826#endif
3827
danc431fd52011-06-27 16:55:50 +00003828 Tcl_CreateObjCommand(
3829 interp, "load_testfixture_extensions", init_all_cmd, 0, 0
3830 );
3831 Tcl_CreateObjCommand(
3832 interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
3833 );
dan04489b62014-10-31 20:11:32 +00003834 Tcl_CreateObjCommand(
3835 interp, "db_last_stmt_ptr", db_last_stmt_ptr, 0, 0
3836 );
danc1a60c52010-06-07 14:28:16 +00003837
drh89dec812005-04-28 19:03:37 +00003838#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00003839 Sqlitetestsse_Init(interp);
3840#endif
drhd1bf3512001-04-07 15:24:33 +00003841 }
3842#endif
danc1a60c52010-06-07 14:28:16 +00003843}
3844
drhdb6bafa2015-01-09 21:54:58 +00003845/* Needed for the setrlimit() system call on unix */
3846#if defined(unix)
3847#include <sys/resource.h>
3848#endif
3849
danc1a60c52010-06-07 14:28:16 +00003850#define TCLSH_MAIN main /* Needed to fake out mktclapp */
3851int TCLSH_MAIN(int argc, char **argv){
3852 Tcl_Interp *interp;
mistachkin1f28e072013-08-15 08:06:15 +00003853
3854#if !defined(_WIN32_WCE)
3855 if( getenv("BREAK") ){
3856 fprintf(stderr,
3857 "attach debugger to process %d and press any key to continue.\n",
3858 GETPID());
3859 fgetc(stdin);
3860 }
3861#endif
3862
drhdb6bafa2015-01-09 21:54:58 +00003863 /* Since the primary use case for this binary is testing of SQLite,
3864 ** be sure to generate core files if we crash */
3865#if defined(SQLITE_TEST) && defined(unix)
3866 { struct rlimit x;
3867 getrlimit(RLIMIT_CORE, &x);
3868 x.rlim_cur = x.rlim_max;
3869 setrlimit(RLIMIT_CORE, &x);
3870 }
3871#endif /* SQLITE_TEST && unix */
3872
3873
danc1a60c52010-06-07 14:28:16 +00003874 /* Call sqlite3_shutdown() once before doing anything else. This is to
3875 ** test that sqlite3_shutdown() can be safely called by a process before
3876 ** sqlite3_initialize() is. */
3877 sqlite3_shutdown();
3878
dan0ae479d2011-09-21 16:43:07 +00003879 Tcl_FindExecutable(argv[0]);
mistachkin2953ba92014-02-14 00:25:03 +00003880 Tcl_SetSystemEncoding(NULL, "utf-8");
dan0ae479d2011-09-21 16:43:07 +00003881 interp = Tcl_CreateInterp();
3882
drh3a0f13f2010-07-12 16:47:48 +00003883#if TCLSH==2
3884 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
3885#endif
danc1a60c52010-06-07 14:28:16 +00003886
danc1a60c52010-06-07 14:28:16 +00003887 init_all(interp);
drhc7285972009-11-10 01:13:25 +00003888 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00003889 int i;
shessad42c3a2006-08-22 23:53:46 +00003890 char zArgc[32];
3891 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
3892 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00003893 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
3894 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00003895 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00003896 Tcl_SetVar(interp, "argv", argv[i],
3897 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3898 }
drh3a0f13f2010-07-12 16:47:48 +00003899 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00003900 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00003901 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00003902 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00003903 return 1;
3904 }
drh3e27c022004-07-23 00:01:38 +00003905 }
drh3a0f13f2010-07-12 16:47:48 +00003906 if( TCLSH==2 || argc<=1 ){
dan0ae479d2011-09-21 16:43:07 +00003907 Tcl_GlobalEval(interp, tclsh_main_loop());
drh348784e2000-05-29 20:41:49 +00003908 }
3909 return 0;
3910}
3911#endif /* TCLSH */