blob: e5c4ef6fdec6a2d685412286ac49d10ab48fe78d [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) */
dan46c47d42011-03-01 18:42:07 +0000143 Tcl_Obj *pPreUpdateHook; /* Pre-update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000144 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drh5def0842010-05-05 20:00:25 +0000145 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000146 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000147 SqlCollate *pCollate; /* List of SQL collation functions */
148 int rc; /* Return code of most recent sqlite3_exec() */
149 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000150 SqlPreparedStmt *stmtList; /* List of prepared statements*/
151 SqlPreparedStmt *stmtLast; /* Last statement in the list */
152 int maxStmt; /* The next maximum number of stmtList */
153 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000154 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh3c379b02010-04-07 19:31:59 +0000155 int nStep, nSort, nIndex; /* Statistics for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000156 int nTransaction; /* Number of nested [transaction] methods */
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 }
dan46c47d42011-03-01 18:42:07 +0000522 if( pDb->pPreUpdateHook ){
523 Tcl_DecrRefCount(pDb->pPreUpdateHook);
524 }
danielk197771fd80b2005-12-16 06:54:01 +0000525 if( pDb->pRollbackHook ){
526 Tcl_DecrRefCount(pDb->pRollbackHook);
527 }
drh5def0842010-05-05 20:00:25 +0000528 if( pDb->pWalHook ){
529 Tcl_DecrRefCount(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000530 }
danielk197794eb6a12005-12-15 15:22:08 +0000531 if( pDb->pCollateNeeded ){
532 Tcl_DecrRefCount(pDb->pCollateNeeded);
533 }
drhbec3f402000-08-04 13:49:02 +0000534 Tcl_Free((char*)pDb);
535}
536
537/*
538** This routine is called when a database file is locked while trying
539** to execute SQL.
540*/
danielk19772a764eb2004-06-12 01:43:26 +0000541static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000542 SqliteDb *pDb = (SqliteDb*)cd;
543 int rc;
544 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000545
drh5bb3eb92007-05-04 13:15:55 +0000546 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000547 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000548 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
549 return 0;
550 }
551 return 1;
drh75897232000-05-29 14:26:00 +0000552}
553
drh26e4a8b2008-05-01 17:16:52 +0000554#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000555/*
danielk1977348bb5d2003-10-18 09:37:26 +0000556** This routine is invoked as the 'progress callback' for the database.
557*/
558static int DbProgressHandler(void *cd){
559 SqliteDb *pDb = (SqliteDb*)cd;
560 int rc;
561
562 assert( pDb->zProgress );
563 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
564 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
565 return 1;
566 }
567 return 0;
568}
drh26e4a8b2008-05-01 17:16:52 +0000569#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000570
drhd1167392006-01-23 13:00:35 +0000571#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000572/*
drhb5a20d32003-04-23 12:25:23 +0000573** This routine is called by the SQLite trace handler whenever a new
574** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000575*/
drhb5a20d32003-04-23 12:25:23 +0000576static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000577 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000578 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000579
drhb5a20d32003-04-23 12:25:23 +0000580 Tcl_DStringInit(&str);
581 Tcl_DStringAppend(&str, pDb->zTrace, -1);
582 Tcl_DStringAppendElement(&str, zSql);
583 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
584 Tcl_DStringFree(&str);
585 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000586}
drhd1167392006-01-23 13:00:35 +0000587#endif
drh0d1a6432003-04-03 15:46:04 +0000588
drhd1167392006-01-23 13:00:35 +0000589#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000590/*
drh19e2d372005-08-29 23:00:03 +0000591** This routine is called by the SQLite profile handler after a statement
592** SQL has executed. The TCL script in pDb->zProfile is evaluated.
593*/
594static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
595 SqliteDb *pDb = (SqliteDb*)cd;
596 Tcl_DString str;
597 char zTm[100];
598
599 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
600 Tcl_DStringInit(&str);
601 Tcl_DStringAppend(&str, pDb->zProfile, -1);
602 Tcl_DStringAppendElement(&str, zSql);
603 Tcl_DStringAppendElement(&str, zTm);
604 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
605 Tcl_DStringFree(&str);
606 Tcl_ResetResult(pDb->interp);
607}
drhd1167392006-01-23 13:00:35 +0000608#endif
drh19e2d372005-08-29 23:00:03 +0000609
610/*
drhaa940ea2004-01-15 02:44:03 +0000611** This routine is called when a transaction is committed. The
612** TCL script in pDb->zCommit is executed. If it returns non-zero or
613** if it throws an exception, the transaction is rolled back instead
614** of being committed.
615*/
616static int DbCommitHandler(void *cd){
617 SqliteDb *pDb = (SqliteDb*)cd;
618 int rc;
619
620 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
621 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
622 return 1;
623 }
624 return 0;
625}
626
danielk197771fd80b2005-12-16 06:54:01 +0000627static void DbRollbackHandler(void *clientData){
628 SqliteDb *pDb = (SqliteDb*)clientData;
629 assert(pDb->pRollbackHook);
630 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
631 Tcl_BackgroundError(pDb->interp);
632 }
633}
634
drh5def0842010-05-05 20:00:25 +0000635/*
636** This procedure handles wal_hook callbacks.
637*/
638static int DbWalHandler(
dan8d22a172010-04-19 18:03:51 +0000639 void *clientData,
640 sqlite3 *db,
641 const char *zDb,
642 int nEntry
643){
drh5def0842010-05-05 20:00:25 +0000644 int ret = SQLITE_OK;
dan8d22a172010-04-19 18:03:51 +0000645 Tcl_Obj *p;
646 SqliteDb *pDb = (SqliteDb*)clientData;
647 Tcl_Interp *interp = pDb->interp;
drh5def0842010-05-05 20:00:25 +0000648 assert(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000649
dan6e45e0c2014-12-10 20:29:49 +0000650 assert( db==pDb->db );
drh5def0842010-05-05 20:00:25 +0000651 p = Tcl_DuplicateObj(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000652 Tcl_IncrRefCount(p);
653 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
654 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
655 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
656 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
657 ){
658 Tcl_BackgroundError(interp);
659 }
660 Tcl_DecrRefCount(p);
661
662 return ret;
663}
664
drhbcf4f482009-03-27 12:44:35 +0000665#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000666static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
667 char zBuf[64];
drh65545b52015-01-19 00:35:53 +0000668 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
danielk1977404ca072009-03-16 13:19:36 +0000669 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
drh65545b52015-01-19 00:35:53 +0000670 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
danielk1977404ca072009-03-16 13:19:36 +0000671 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
672}
673#else
drhbcf4f482009-03-27 12:44:35 +0000674# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000675#endif
676
drh69910da2009-03-27 12:32:54 +0000677#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000678static void DbUnlockNotify(void **apArg, int nArg){
679 int i;
680 for(i=0; i<nArg; i++){
681 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
682 SqliteDb *pDb = (SqliteDb *)apArg[i];
683 setTestUnlockNotifyVars(pDb->interp, i, nArg);
684 assert( pDb->pUnlockNotify);
685 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
686 Tcl_DecrRefCount(pDb->pUnlockNotify);
687 pDb->pUnlockNotify = 0;
688 }
689}
drh69910da2009-03-27 12:32:54 +0000690#endif
danielk1977404ca072009-03-16 13:19:36 +0000691
drh9b1c62d2011-03-30 21:04:43 +0000692#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +0000693/*
694** Pre-update hook callback.
695*/
696static void DbPreUpdateHandler(
697 void *p,
698 sqlite3 *db,
699 int op,
700 const char *zDb,
701 const char *zTbl,
702 sqlite_int64 iKey1,
703 sqlite_int64 iKey2
704){
705 SqliteDb *pDb = (SqliteDb *)p;
706 Tcl_Obj *pCmd;
707 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
708
709 assert( (SQLITE_DELETE-1)/9 == 0 );
710 assert( (SQLITE_INSERT-1)/9 == 1 );
711 assert( (SQLITE_UPDATE-1)/9 == 2 );
712 assert( pDb->pPreUpdateHook );
713 assert( db==pDb->db );
714 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
715
716 pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
717 Tcl_IncrRefCount(pCmd);
718 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
719 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
720 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
721 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
722 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
723 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
724 Tcl_DecrRefCount(pCmd);
725}
drh9b1c62d2011-03-30 21:04:43 +0000726#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +0000727
danielk197794eb6a12005-12-15 15:22:08 +0000728static void DbUpdateHandler(
729 void *p,
730 int op,
731 const char *zDb,
732 const char *zTbl,
733 sqlite_int64 rowid
734){
735 SqliteDb *pDb = (SqliteDb *)p;
736 Tcl_Obj *pCmd;
dan46c47d42011-03-01 18:42:07 +0000737 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
738
739 assert( (SQLITE_DELETE-1)/9 == 0 );
740 assert( (SQLITE_INSERT-1)/9 == 1 );
741 assert( (SQLITE_UPDATE-1)/9 == 2 );
danielk197794eb6a12005-12-15 15:22:08 +0000742
743 assert( pDb->pUpdateHook );
744 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
745
746 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
747 Tcl_IncrRefCount(pCmd);
dan46c47d42011-03-01 18:42:07 +0000748 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
danielk197794eb6a12005-12-15 15:22:08 +0000749 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
750 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
751 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
752 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
drhefdde162010-10-27 15:36:21 +0000753 Tcl_DecrRefCount(pCmd);
danielk197794eb6a12005-12-15 15:22:08 +0000754}
755
danielk19777cedc8d2004-06-10 10:50:08 +0000756static void tclCollateNeeded(
757 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000758 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000759 int enc,
760 const char *zName
761){
762 SqliteDb *pDb = (SqliteDb *)pCtx;
763 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
764 Tcl_IncrRefCount(pScript);
765 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
766 Tcl_EvalObjEx(pDb->interp, pScript, 0);
767 Tcl_DecrRefCount(pScript);
768}
769
drhaa940ea2004-01-15 02:44:03 +0000770/*
danielk19770202b292004-06-09 09:55:16 +0000771** This routine is called to evaluate an SQL collation function implemented
772** using TCL script.
773*/
774static int tclSqlCollate(
775 void *pCtx,
776 int nA,
777 const void *zA,
778 int nB,
779 const void *zB
780){
781 SqlCollate *p = (SqlCollate *)pCtx;
782 Tcl_Obj *pCmd;
783
784 pCmd = Tcl_NewStringObj(p->zScript, -1);
785 Tcl_IncrRefCount(pCmd);
786 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
787 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000788 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000789 Tcl_DecrRefCount(pCmd);
790 return (atoi(Tcl_GetStringResult(p->interp)));
791}
792
793/*
drhcabb0812002-09-14 13:47:32 +0000794** This routine is called to evaluate an SQL function implemented
795** using TCL script.
796*/
drhfb7e7652005-01-24 00:28:42 +0000797static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000798 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000799 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000800 int i;
801 int rc;
802
drhd1e47332005-06-26 17:55:33 +0000803 if( argc==0 ){
804 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
805 ** script object directly. This allows the TCL compiler to generate
806 ** bytecode for the command on the first invocation and thus make
807 ** subsequent invocations much faster. */
808 pCmd = p->pScript;
809 Tcl_IncrRefCount(pCmd);
810 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
811 Tcl_DecrRefCount(pCmd);
812 }else{
813 /* If there are arguments to the function, make a shallow copy of the
814 ** script object, lappend the arguments, then evaluate the copy.
815 **
peter.d.reid60ec9142014-09-06 16:39:46 +0000816 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
drhd1e47332005-06-26 17:55:33 +0000817 ** The new Tcl_Obj contains pointers to the original list elements.
818 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
819 ** of the list to tclCmdNameType, that alternate representation will
820 ** be preserved and reused on the next invocation.
821 */
822 Tcl_Obj **aArg;
823 int nArg;
824 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
825 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
826 return;
827 }
828 pCmd = Tcl_NewListObj(nArg, aArg);
829 Tcl_IncrRefCount(pCmd);
830 for(i=0; i<argc; i++){
831 sqlite3_value *pIn = argv[i];
832 Tcl_Obj *pVal;
833
834 /* Set pVal to contain the i'th column of this row. */
835 switch( sqlite3_value_type(pIn) ){
836 case SQLITE_BLOB: {
837 int bytes = sqlite3_value_bytes(pIn);
838 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
839 break;
840 }
841 case SQLITE_INTEGER: {
842 sqlite_int64 v = sqlite3_value_int64(pIn);
843 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +0000844 pVal = Tcl_NewIntObj((int)v);
drhd1e47332005-06-26 17:55:33 +0000845 }else{
846 pVal = Tcl_NewWideIntObj(v);
847 }
848 break;
849 }
850 case SQLITE_FLOAT: {
851 double r = sqlite3_value_double(pIn);
852 pVal = Tcl_NewDoubleObj(r);
853 break;
854 }
855 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +0000856 pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
drhd1e47332005-06-26 17:55:33 +0000857 break;
858 }
859 default: {
860 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000861 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000862 break;
863 }
864 }
865 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
866 if( rc ){
867 Tcl_DecrRefCount(pCmd);
868 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
869 return;
870 }
danielk197751ad0ec2004-05-24 12:39:02 +0000871 }
drhd1e47332005-06-26 17:55:33 +0000872 if( !p->useEvalObjv ){
873 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
874 ** is a list without a string representation. To prevent this from
875 ** happening, make sure pCmd has a valid string representation */
876 Tcl_GetString(pCmd);
877 }
878 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
879 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000880 }
danielk1977562e8d32005-05-20 09:40:55 +0000881
drhc7f269d2005-05-05 10:30:29 +0000882 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000883 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000884 }else{
drhc7f269d2005-05-05 10:30:29 +0000885 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
886 int n;
887 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000888 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000889 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000890 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000891 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000892 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000893 data = Tcl_GetByteArrayFromObj(pVar, &n);
894 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000895 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000896 Tcl_GetIntFromObj(0, pVar, &n);
897 sqlite3_result_int(context, n);
898 }else if( c=='d' && strcmp(zType,"double")==0 ){
899 double r;
900 Tcl_GetDoubleFromObj(0, pVar, &r);
901 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +0000902 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
903 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000904 Tcl_WideInt v;
905 Tcl_GetWideIntFromObj(0, pVar, &v);
906 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000907 }else{
danielk197700fd9572005-12-07 06:27:43 +0000908 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
909 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000910 }
drhcabb0812002-09-14 13:47:32 +0000911 }
912}
drh895d7472004-08-20 16:02:39 +0000913
drhe22a3342003-04-22 20:30:37 +0000914#ifndef SQLITE_OMIT_AUTHORIZATION
915/*
916** This is the authentication function. It appends the authentication
917** type code and the two arguments to zCmd[] then invokes the result
918** on the interpreter. The reply is examined to determine if the
919** authentication fails or succeeds.
920*/
921static int auth_callback(
922 void *pArg,
923 int code,
924 const char *zArg1,
925 const char *zArg2,
926 const char *zArg3,
927 const char *zArg4
drh32c6a482014-09-11 13:44:52 +0000928#ifdef SQLITE_USER_AUTHENTICATION
929 ,const char *zArg5
930#endif
drhe22a3342003-04-22 20:30:37 +0000931){
mistachkin6ef5e122014-01-24 17:03:55 +0000932 const char *zCode;
drhe22a3342003-04-22 20:30:37 +0000933 Tcl_DString str;
934 int rc;
935 const char *zReply;
936 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +0000937 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +0000938
939 switch( code ){
940 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
941 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
942 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
943 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
944 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
945 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
946 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
947 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
948 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
949 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
950 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
951 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
952 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
953 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
954 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
955 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
956 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
957 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
958 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
959 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
960 case SQLITE_READ : zCode="SQLITE_READ"; break;
961 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
962 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
963 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000964 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
965 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000966 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000967 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000968 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000969 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
970 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000971 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +0000972 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drh65a2aaa2014-01-16 22:40:02 +0000973 case SQLITE_RECURSIVE : zCode="SQLITE_RECURSIVE"; break;
drhe22a3342003-04-22 20:30:37 +0000974 default : zCode="????"; break;
975 }
976 Tcl_DStringInit(&str);
977 Tcl_DStringAppend(&str, pDb->zAuth, -1);
978 Tcl_DStringAppendElement(&str, zCode);
979 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
980 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
981 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
982 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
drh32c6a482014-09-11 13:44:52 +0000983#ifdef SQLITE_USER_AUTHENTICATION
984 Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
985#endif
drhe22a3342003-04-22 20:30:37 +0000986 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
987 Tcl_DStringFree(&str);
drhb07028f2011-10-14 21:49:18 +0000988 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
drhe22a3342003-04-22 20:30:37 +0000989 if( strcmp(zReply,"SQLITE_OK")==0 ){
990 rc = SQLITE_OK;
991 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
992 rc = SQLITE_DENY;
993 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
994 rc = SQLITE_IGNORE;
995 }else{
996 rc = 999;
997 }
998 return rc;
999}
1000#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +00001001
1002/*
tpoindex1067fe12004-12-17 15:41:11 +00001003** This routine reads a line of text from FILE in, stores
1004** the text in memory obtained from malloc() and returns a pointer
1005** to the text. NULL is returned at end of file, or if malloc()
1006** fails.
1007**
1008** The interface is like "readline" but no command-line editing
1009** is done.
1010**
1011** copied from shell.c from '.import' command
1012*/
1013static char *local_getline(char *zPrompt, FILE *in){
1014 char *zLine;
1015 int nLine;
1016 int n;
tpoindex1067fe12004-12-17 15:41:11 +00001017
1018 nLine = 100;
1019 zLine = malloc( nLine );
1020 if( zLine==0 ) return 0;
1021 n = 0;
drhb07028f2011-10-14 21:49:18 +00001022 while( 1 ){
tpoindex1067fe12004-12-17 15:41:11 +00001023 if( n+100>nLine ){
1024 nLine = nLine*2 + 100;
1025 zLine = realloc(zLine, nLine);
1026 if( zLine==0 ) return 0;
1027 }
1028 if( fgets(&zLine[n], nLine - n, in)==0 ){
1029 if( n==0 ){
1030 free(zLine);
1031 return 0;
1032 }
1033 zLine[n] = 0;
tpoindex1067fe12004-12-17 15:41:11 +00001034 break;
1035 }
1036 while( zLine[n] ){ n++; }
1037 if( n>0 && zLine[n-1]=='\n' ){
1038 n--;
1039 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +00001040 break;
tpoindex1067fe12004-12-17 15:41:11 +00001041 }
1042 }
1043 zLine = realloc( zLine, n+1 );
1044 return zLine;
1045}
1046
danielk19778e556522007-11-13 10:30:24 +00001047
1048/*
dan4a4c11a2009-10-06 14:59:02 +00001049** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +00001050**
dan4a4c11a2009-10-06 14:59:02 +00001051** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +00001052**
dan4a4c11a2009-10-06 14:59:02 +00001053** It is invoked after evaluating the script SCRIPT to commit or rollback
1054** the transaction or savepoint opened by the [transaction] command.
1055*/
1056static int DbTransPostCmd(
1057 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1058 Tcl_Interp *interp, /* Tcl interpreter */
1059 int result /* Result of evaluating SCRIPT */
1060){
mistachkin6ef5e122014-01-24 17:03:55 +00001061 static const char *const azEnd[] = {
dan4a4c11a2009-10-06 14:59:02 +00001062 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1063 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1064 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1065 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1066 };
1067 SqliteDb *pDb = (SqliteDb*)data[0];
1068 int rc = result;
1069 const char *zEnd;
1070
1071 pDb->nTransaction--;
1072 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1073
1074 pDb->disableAuth++;
1075 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1076 /* This is a tricky scenario to handle. The most likely cause of an
1077 ** error is that the exec() above was an attempt to commit the
1078 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
mistachkin48864df2013-03-21 21:20:32 +00001079 ** that an IO-error has occurred. In either case, throw a Tcl exception
dan4a4c11a2009-10-06 14:59:02 +00001080 ** and try to rollback the transaction.
1081 **
1082 ** But it could also be that the user executed one or more BEGIN,
1083 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1084 ** this method's logic. Not clear how this would be best handled.
1085 */
1086 if( rc!=TCL_ERROR ){
drha198f2b2014-02-07 19:26:13 +00001087 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
dan4a4c11a2009-10-06 14:59:02 +00001088 rc = TCL_ERROR;
1089 }
1090 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1091 }
1092 pDb->disableAuth--;
1093
1094 return rc;
1095}
1096
1097/*
danc431fd52011-06-27 16:55:50 +00001098** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1099** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1100** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1101** on whether or not the [db_use_legacy_prepare] command has been used to
1102** configure the connection.
1103*/
1104static int dbPrepare(
1105 SqliteDb *pDb, /* Database object */
1106 const char *zSql, /* SQL to compile */
1107 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1108 const char **pzOut /* OUT: Pointer to next SQL statement */
1109){
1110#ifdef SQLITE_TEST
1111 if( pDb->bLegacyPrepare ){
1112 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1113 }
1114#endif
1115 return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut);
1116}
1117
1118/*
dan4a4c11a2009-10-06 14:59:02 +00001119** Search the cache for a prepared-statement object that implements the
1120** first SQL statement in the buffer pointed to by parameter zIn. If
1121** no such prepared-statement can be found, allocate and prepare a new
1122** one. In either case, bind the current values of the relevant Tcl
1123** variables to any $var, :var or @var variables in the statement. Before
1124** returning, set *ppPreStmt to point to the prepared-statement object.
1125**
1126** Output parameter *pzOut is set to point to the next SQL statement in
1127** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1128** next statement.
1129**
1130** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1131** and an error message loaded into interpreter pDb->interp.
1132*/
1133static int dbPrepareAndBind(
1134 SqliteDb *pDb, /* Database object */
1135 char const *zIn, /* SQL to compile */
1136 char const **pzOut, /* OUT: Pointer to next SQL statement */
1137 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1138){
1139 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
mistachkin7bb22ac2015-01-12 19:59:12 +00001140 sqlite3_stmt *pStmt = 0; /* Prepared statement object */
dan4a4c11a2009-10-06 14:59:02 +00001141 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1142 int nSql; /* Length of zSql in bytes */
mistachkin7bb22ac2015-01-12 19:59:12 +00001143 int nVar = 0; /* Number of variables in statement */
dan4a4c11a2009-10-06 14:59:02 +00001144 int iParm = 0; /* Next free entry in apParm */
drh0425f182013-11-26 16:48:04 +00001145 char c;
dan4a4c11a2009-10-06 14:59:02 +00001146 int i;
1147 Tcl_Interp *interp = pDb->interp;
1148
1149 *ppPreStmt = 0;
1150
1151 /* Trim spaces from the start of zSql and calculate the remaining length. */
drh0425f182013-11-26 16:48:04 +00001152 while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
dan4a4c11a2009-10-06 14:59:02 +00001153 nSql = strlen30(zSql);
1154
1155 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1156 int n = pPreStmt->nSql;
1157 if( nSql>=n
1158 && memcmp(pPreStmt->zSql, zSql, n)==0
1159 && (zSql[n]==0 || zSql[n-1]==';')
1160 ){
1161 pStmt = pPreStmt->pStmt;
1162 *pzOut = &zSql[pPreStmt->nSql];
1163
1164 /* When a prepared statement is found, unlink it from the
1165 ** cache list. It will later be added back to the beginning
1166 ** of the cache list in order to implement LRU replacement.
1167 */
1168 if( pPreStmt->pPrev ){
1169 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1170 }else{
1171 pDb->stmtList = pPreStmt->pNext;
1172 }
1173 if( pPreStmt->pNext ){
1174 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1175 }else{
1176 pDb->stmtLast = pPreStmt->pPrev;
1177 }
1178 pDb->nStmt--;
1179 nVar = sqlite3_bind_parameter_count(pStmt);
1180 break;
1181 }
1182 }
1183
1184 /* If no prepared statement was found. Compile the SQL text. Also allocate
1185 ** a new SqlPreparedStmt structure. */
1186 if( pPreStmt==0 ){
1187 int nByte;
1188
danc431fd52011-06-27 16:55:50 +00001189 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
drhc45e6712012-10-03 11:02:33 +00001190 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001191 return TCL_ERROR;
1192 }
1193 if( pStmt==0 ){
1194 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1195 /* A compile-time error in the statement. */
drhc45e6712012-10-03 11:02:33 +00001196 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001197 return TCL_ERROR;
1198 }else{
1199 /* The statement was a no-op. Continue to the next statement
1200 ** in the SQL string.
1201 */
1202 return TCL_OK;
1203 }
1204 }
1205
1206 assert( pPreStmt==0 );
1207 nVar = sqlite3_bind_parameter_count(pStmt);
1208 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1209 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1210 memset(pPreStmt, 0, nByte);
1211
1212 pPreStmt->pStmt = pStmt;
drh7ed243b2012-04-19 17:19:51 +00001213 pPreStmt->nSql = (int)(*pzOut - zSql);
dan4a4c11a2009-10-06 14:59:02 +00001214 pPreStmt->zSql = sqlite3_sql(pStmt);
1215 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
danc431fd52011-06-27 16:55:50 +00001216#ifdef SQLITE_TEST
1217 if( pPreStmt->zSql==0 ){
1218 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1219 memcpy(zCopy, zSql, pPreStmt->nSql);
1220 zCopy[pPreStmt->nSql] = '\0';
1221 pPreStmt->zSql = zCopy;
1222 }
1223#endif
dan4a4c11a2009-10-06 14:59:02 +00001224 }
1225 assert( pPreStmt );
1226 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1227 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1228
1229 /* Bind values to parameters that begin with $ or : */
1230 for(i=1; i<=nVar; i++){
1231 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1232 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1233 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1234 if( pVar ){
1235 int n;
1236 u8 *data;
1237 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
mistachkin8e189222015-04-19 21:43:16 +00001238 c = zType[0];
dan4a4c11a2009-10-06 14:59:02 +00001239 if( zVar[0]=='@' ||
1240 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1241 /* Load a BLOB type if the Tcl variable is a bytearray and
1242 ** it has no string representation or the host
1243 ** parameter name begins with "@". */
1244 data = Tcl_GetByteArrayFromObj(pVar, &n);
1245 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1246 Tcl_IncrRefCount(pVar);
1247 pPreStmt->apParm[iParm++] = pVar;
1248 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1249 Tcl_GetIntFromObj(interp, pVar, &n);
1250 sqlite3_bind_int(pStmt, i, n);
1251 }else if( c=='d' && strcmp(zType,"double")==0 ){
1252 double r;
1253 Tcl_GetDoubleFromObj(interp, pVar, &r);
1254 sqlite3_bind_double(pStmt, i, r);
1255 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1256 (c=='i' && strcmp(zType,"int")==0) ){
1257 Tcl_WideInt v;
1258 Tcl_GetWideIntFromObj(interp, pVar, &v);
1259 sqlite3_bind_int64(pStmt, i, v);
1260 }else{
1261 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1262 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1263 Tcl_IncrRefCount(pVar);
1264 pPreStmt->apParm[iParm++] = pVar;
1265 }
1266 }else{
1267 sqlite3_bind_null(pStmt, i);
1268 }
1269 }
1270 }
1271 pPreStmt->nParm = iParm;
1272 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001273
dan4a4c11a2009-10-06 14:59:02 +00001274 return TCL_OK;
1275}
1276
dan4a4c11a2009-10-06 14:59:02 +00001277/*
1278** Release a statement reference obtained by calling dbPrepareAndBind().
1279** There should be exactly one call to this function for each call to
1280** dbPrepareAndBind().
1281**
1282** If the discard parameter is non-zero, then the statement is deleted
1283** immediately. Otherwise it is added to the LRU list and may be returned
1284** by a subsequent call to dbPrepareAndBind().
1285*/
1286static void dbReleaseStmt(
1287 SqliteDb *pDb, /* Database handle */
1288 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1289 int discard /* True to delete (not cache) the pPreStmt */
1290){
1291 int i;
1292
1293 /* Free the bound string and blob parameters */
1294 for(i=0; i<pPreStmt->nParm; i++){
1295 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1296 }
1297 pPreStmt->nParm = 0;
1298
1299 if( pDb->maxStmt<=0 || discard ){
1300 /* If the cache is turned off, deallocated the statement */
danc431fd52011-06-27 16:55:50 +00001301 dbFreeStmt(pPreStmt);
dan4a4c11a2009-10-06 14:59:02 +00001302 }else{
1303 /* Add the prepared statement to the beginning of the cache list. */
1304 pPreStmt->pNext = pDb->stmtList;
1305 pPreStmt->pPrev = 0;
1306 if( pDb->stmtList ){
1307 pDb->stmtList->pPrev = pPreStmt;
1308 }
1309 pDb->stmtList = pPreStmt;
1310 if( pDb->stmtLast==0 ){
1311 assert( pDb->nStmt==0 );
1312 pDb->stmtLast = pPreStmt;
1313 }else{
1314 assert( pDb->nStmt>0 );
1315 }
1316 pDb->nStmt++;
1317
1318 /* If we have too many statement in cache, remove the surplus from
1319 ** the end of the cache list. */
1320 while( pDb->nStmt>pDb->maxStmt ){
danc431fd52011-06-27 16:55:50 +00001321 SqlPreparedStmt *pLast = pDb->stmtLast;
1322 pDb->stmtLast = pLast->pPrev;
dan4a4c11a2009-10-06 14:59:02 +00001323 pDb->stmtLast->pNext = 0;
1324 pDb->nStmt--;
danc431fd52011-06-27 16:55:50 +00001325 dbFreeStmt(pLast);
dan4a4c11a2009-10-06 14:59:02 +00001326 }
1327 }
1328}
1329
1330/*
1331** Structure used with dbEvalXXX() functions:
1332**
1333** dbEvalInit()
1334** dbEvalStep()
1335** dbEvalFinalize()
1336** dbEvalRowInfo()
1337** dbEvalColumnValue()
1338*/
1339typedef struct DbEvalContext DbEvalContext;
1340struct DbEvalContext {
1341 SqliteDb *pDb; /* Database handle */
1342 Tcl_Obj *pSql; /* Object holding string zSql */
1343 const char *zSql; /* Remaining SQL to execute */
1344 SqlPreparedStmt *pPreStmt; /* Current statement */
1345 int nCol; /* Number of columns returned by pStmt */
1346 Tcl_Obj *pArray; /* Name of array variable */
1347 Tcl_Obj **apColName; /* Array of column names */
1348};
1349
1350/*
1351** Release any cache of column names currently held as part of
1352** the DbEvalContext structure passed as the first argument.
1353*/
1354static void dbReleaseColumnNames(DbEvalContext *p){
1355 if( p->apColName ){
1356 int i;
1357 for(i=0; i<p->nCol; i++){
1358 Tcl_DecrRefCount(p->apColName[i]);
1359 }
1360 Tcl_Free((char *)p->apColName);
1361 p->apColName = 0;
1362 }
1363 p->nCol = 0;
1364}
1365
1366/*
1367** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001368**
1369** If pArray is not NULL, then it contains the name of a Tcl array
1370** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001371** the names of the columns returned by the statement as part of each
1372** call to dbEvalStep(), in order from left to right. e.g. if the names
1373** of the returned columns are a, b and c, it does the equivalent of the
1374** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001375**
1376** set ${pArray}(*) {a b c}
1377*/
dan4a4c11a2009-10-06 14:59:02 +00001378static void dbEvalInit(
1379 DbEvalContext *p, /* Pointer to structure to initialize */
1380 SqliteDb *pDb, /* Database handle */
1381 Tcl_Obj *pSql, /* Object containing SQL script */
1382 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001383){
dan4a4c11a2009-10-06 14:59:02 +00001384 memset(p, 0, sizeof(DbEvalContext));
1385 p->pDb = pDb;
1386 p->zSql = Tcl_GetString(pSql);
1387 p->pSql = pSql;
1388 Tcl_IncrRefCount(pSql);
1389 if( pArray ){
1390 p->pArray = pArray;
1391 Tcl_IncrRefCount(pArray);
1392 }
1393}
danielk19778e556522007-11-13 10:30:24 +00001394
dan4a4c11a2009-10-06 14:59:02 +00001395/*
1396** Obtain information about the row that the DbEvalContext passed as the
1397** first argument currently points to.
1398*/
1399static void dbEvalRowInfo(
1400 DbEvalContext *p, /* Evaluation context */
1401 int *pnCol, /* OUT: Number of column names */
1402 Tcl_Obj ***papColName /* OUT: Array of column names */
1403){
danielk19778e556522007-11-13 10:30:24 +00001404 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001405 if( 0==p->apColName ){
1406 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1407 int i; /* Iterator variable */
1408 int nCol; /* Number of columns returned by pStmt */
1409 Tcl_Obj **apColName = 0; /* Array of column names */
1410
1411 p->nCol = nCol = sqlite3_column_count(pStmt);
1412 if( nCol>0 && (papColName || p->pArray) ){
1413 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1414 for(i=0; i<nCol; i++){
drhc45e6712012-10-03 11:02:33 +00001415 apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
dan4a4c11a2009-10-06 14:59:02 +00001416 Tcl_IncrRefCount(apColName[i]);
1417 }
1418 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001419 }
1420
1421 /* If results are being stored in an array variable, then create
1422 ** the array(*) entry for that array
1423 */
dan4a4c11a2009-10-06 14:59:02 +00001424 if( p->pArray ){
1425 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001426 Tcl_Obj *pColList = Tcl_NewObj();
1427 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001428
danielk19778e556522007-11-13 10:30:24 +00001429 for(i=0; i<nCol; i++){
1430 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1431 }
1432 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001433 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001434 Tcl_DecrRefCount(pStar);
1435 }
danielk19778e556522007-11-13 10:30:24 +00001436 }
1437
dan4a4c11a2009-10-06 14:59:02 +00001438 if( papColName ){
1439 *papColName = p->apColName;
1440 }
1441 if( pnCol ){
1442 *pnCol = p->nCol;
1443 }
1444}
1445
1446/*
1447** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1448** returned, then an error message is stored in the interpreter before
1449** returning.
1450**
1451** A return value of TCL_OK means there is a row of data available. The
1452** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1453** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1454** is returned, then the SQL script has finished executing and there are
1455** no further rows available. This is similar to SQLITE_DONE.
1456*/
1457static int dbEvalStep(DbEvalContext *p){
danc431fd52011-06-27 16:55:50 +00001458 const char *zPrevSql = 0; /* Previous value of p->zSql */
1459
dan4a4c11a2009-10-06 14:59:02 +00001460 while( p->zSql[0] || p->pPreStmt ){
1461 int rc;
1462 if( p->pPreStmt==0 ){
danc431fd52011-06-27 16:55:50 +00001463 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
dan4a4c11a2009-10-06 14:59:02 +00001464 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1465 if( rc!=TCL_OK ) return rc;
1466 }else{
1467 int rcs;
1468 SqliteDb *pDb = p->pDb;
1469 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1470 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1471
1472 rcs = sqlite3_step(pStmt);
1473 if( rcs==SQLITE_ROW ){
1474 return TCL_OK;
1475 }
1476 if( p->pArray ){
1477 dbEvalRowInfo(p, 0, 0);
1478 }
1479 rcs = sqlite3_reset(pStmt);
1480
1481 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1482 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001483 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
dan4a4c11a2009-10-06 14:59:02 +00001484 dbReleaseColumnNames(p);
1485 p->pPreStmt = 0;
1486
1487 if( rcs!=SQLITE_OK ){
1488 /* If a run-time error occurs, report the error and stop reading
1489 ** the SQL. */
dan4a4c11a2009-10-06 14:59:02 +00001490 dbReleaseStmt(pDb, pPreStmt, 1);
danc431fd52011-06-27 16:55:50 +00001491#if SQLITE_TEST
1492 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1493 /* If the runtime error was an SQLITE_SCHEMA, and the database
1494 ** handle is configured to use the legacy sqlite3_prepare()
1495 ** interface, retry prepare()/step() on the same SQL statement.
1496 ** This only happens once. If there is a second SQLITE_SCHEMA
1497 ** error, the error will be returned to the caller. */
1498 p->zSql = zPrevSql;
1499 continue;
1500 }
1501#endif
drhc45e6712012-10-03 11:02:33 +00001502 Tcl_SetObjResult(pDb->interp,
1503 Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001504 return TCL_ERROR;
1505 }else{
1506 dbReleaseStmt(pDb, pPreStmt, 0);
1507 }
1508 }
1509 }
1510
1511 /* Finished */
1512 return TCL_BREAK;
1513}
1514
1515/*
1516** Free all resources currently held by the DbEvalContext structure passed
1517** as the first argument. There should be exactly one call to this function
1518** for each call to dbEvalInit().
1519*/
1520static void dbEvalFinalize(DbEvalContext *p){
1521 if( p->pPreStmt ){
1522 sqlite3_reset(p->pPreStmt->pStmt);
1523 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1524 p->pPreStmt = 0;
1525 }
1526 if( p->pArray ){
1527 Tcl_DecrRefCount(p->pArray);
1528 p->pArray = 0;
1529 }
1530 Tcl_DecrRefCount(p->pSql);
1531 dbReleaseColumnNames(p);
1532}
1533
1534/*
1535** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1536** the value for the iCol'th column of the row currently pointed to by
1537** the DbEvalContext structure passed as the first argument.
1538*/
1539static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1540 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1541 switch( sqlite3_column_type(pStmt, iCol) ){
1542 case SQLITE_BLOB: {
1543 int bytes = sqlite3_column_bytes(pStmt, iCol);
1544 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1545 if( !zBlob ) bytes = 0;
1546 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1547 }
1548 case SQLITE_INTEGER: {
1549 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1550 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +00001551 return Tcl_NewIntObj((int)v);
dan4a4c11a2009-10-06 14:59:02 +00001552 }else{
1553 return Tcl_NewWideIntObj(v);
1554 }
1555 }
1556 case SQLITE_FLOAT: {
1557 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1558 }
1559 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +00001560 return Tcl_NewStringObj(p->pDb->zNull, -1);
dan4a4c11a2009-10-06 14:59:02 +00001561 }
1562 }
1563
drh325eff52012-10-03 12:56:18 +00001564 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
dan4a4c11a2009-10-06 14:59:02 +00001565}
1566
1567/*
1568** If using Tcl version 8.6 or greater, use the NR functions to avoid
1569** recursive evalution of scripts by the [db eval] and [db trans]
1570** commands. Even if the headers used while compiling the extension
1571** are 8.6 or newer, the code still tests the Tcl version at runtime.
1572** This allows stubs-enabled builds to be used with older Tcl libraries.
1573*/
1574#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001575# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001576static int DbUseNre(void){
1577 int major, minor;
1578 Tcl_GetVersion(&major, &minor, 0, 0);
1579 return( (major==8 && minor>=6) || major>8 );
1580}
1581#else
1582/*
1583** Compiling using headers earlier than 8.6. In this case NR cannot be
1584** used, so DbUseNre() to always return zero. Add #defines for the other
1585** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1586** even though the only invocations of them are within conditional blocks
1587** of the form:
1588**
1589** if( DbUseNre() ) { ... }
1590*/
drha2c8a952009-10-13 18:38:34 +00001591# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001592# define DbUseNre() 0
drha47941f2013-12-20 18:57:44 +00001593# define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001594# define Tcl_NREvalObj(a,b,c) 0
drha47941f2013-12-20 18:57:44 +00001595# define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001596#endif
1597
1598/*
1599** This function is part of the implementation of the command:
1600**
1601** $db eval SQL ?ARRAYNAME? SCRIPT
1602*/
1603static int DbEvalNextCmd(
1604 ClientData data[], /* data[0] is the (DbEvalContext*) */
1605 Tcl_Interp *interp, /* Tcl interpreter */
1606 int result /* Result so far */
1607){
1608 int rc = result; /* Return code */
1609
1610 /* The first element of the data[] array is a pointer to a DbEvalContext
1611 ** structure allocated using Tcl_Alloc(). The second element of data[]
1612 ** is a pointer to a Tcl_Obj containing the script to run for each row
1613 ** returned by the queries encapsulated in data[0]. */
1614 DbEvalContext *p = (DbEvalContext *)data[0];
1615 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1616 Tcl_Obj *pArray = p->pArray;
1617
1618 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1619 int i;
1620 int nCol;
1621 Tcl_Obj **apColName;
1622 dbEvalRowInfo(p, &nCol, &apColName);
1623 for(i=0; i<nCol; i++){
1624 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1625 if( pArray==0 ){
1626 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1627 }else{
1628 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1629 }
1630 }
1631
1632 /* The required interpreter variables are now populated with the data
1633 ** from the current row. If using NRE, schedule callbacks to evaluate
1634 ** script pScript, then to invoke this function again to fetch the next
1635 ** row (or clean up if there is no next row or the script throws an
1636 ** exception). After scheduling the callbacks, return control to the
1637 ** caller.
1638 **
1639 ** If not using NRE, evaluate pScript directly and continue with the
1640 ** next iteration of this while(...) loop. */
1641 if( DbUseNre() ){
1642 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1643 return Tcl_NREvalObj(interp, pScript, 0);
1644 }else{
1645 rc = Tcl_EvalObjEx(interp, pScript, 0);
1646 }
1647 }
1648
1649 Tcl_DecrRefCount(pScript);
1650 dbEvalFinalize(p);
1651 Tcl_Free((char *)p);
1652
1653 if( rc==TCL_OK || rc==TCL_BREAK ){
1654 Tcl_ResetResult(interp);
1655 rc = TCL_OK;
1656 }
1657 return rc;
danielk19778e556522007-11-13 10:30:24 +00001658}
1659
tpoindex1067fe12004-12-17 15:41:11 +00001660/*
dan46c47d42011-03-01 18:42:07 +00001661** This function is used by the implementations of the following database
1662** handle sub-commands:
1663**
1664** $db update_hook ?SCRIPT?
1665** $db wal_hook ?SCRIPT?
1666** $db commit_hook ?SCRIPT?
1667** $db preupdate hook ?SCRIPT?
1668*/
1669static void DbHookCmd(
1670 Tcl_Interp *interp, /* Tcl interpreter */
1671 SqliteDb *pDb, /* Database handle */
1672 Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */
1673 Tcl_Obj **ppHook /* Pointer to member of SqliteDb */
1674){
1675 sqlite3 *db = pDb->db;
1676
1677 if( *ppHook ){
1678 Tcl_SetObjResult(interp, *ppHook);
1679 if( pArg ){
1680 Tcl_DecrRefCount(*ppHook);
1681 *ppHook = 0;
1682 }
1683 }
1684 if( pArg ){
1685 assert( !(*ppHook) );
1686 if( Tcl_GetCharLength(pArg)>0 ){
1687 *ppHook = pArg;
1688 Tcl_IncrRefCount(*ppHook);
1689 }
1690 }
1691
drh9b1c62d2011-03-30 21:04:43 +00001692#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +00001693 sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
drh9b1c62d2011-03-30 21:04:43 +00001694#endif
dan46c47d42011-03-01 18:42:07 +00001695 sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1696 sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1697 sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
1698}
1699
1700/*
drh75897232000-05-29 14:26:00 +00001701** The "sqlite" command below creates a new Tcl command for each
1702** connection it opens to an SQLite database. This routine is invoked
1703** whenever one of those connection-specific commands is executed
1704** in Tcl. For example, if you run Tcl code like this:
1705**
drh9bb575f2004-09-06 17:24:11 +00001706** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001707** db1 close
1708**
1709** The first command opens a connection to the "my_database" database
1710** and calls that connection "db1". The second command causes this
1711** subroutine to be invoked.
1712*/
drh6d313162000-09-21 13:01:35 +00001713static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001714 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001715 int choice;
drh22fbcb82004-02-01 01:22:50 +00001716 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001717 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001718 "authorizer", "backup", "busy",
1719 "cache", "changes", "close",
1720 "collate", "collation_needed", "commit_hook",
1721 "complete", "copy", "enable_load_extension",
1722 "errorcode", "eval", "exists",
1723 "function", "incrblob", "interrupt",
drh833bf962010-04-28 14:42:19 +00001724 "last_insert_rowid", "nullvalue", "onecolumn",
drh304637c2011-03-18 16:47:27 +00001725 "preupdate", "profile", "progress",
1726 "rekey", "restore", "rollback_hook",
1727 "status", "timeout", "total_changes",
1728 "trace", "transaction", "unlock_notify",
1729 "update_hook", "version", "wal_hook",
1730 0
drh6d313162000-09-21 13:01:35 +00001731 };
drh411995d2002-06-25 19:31:18 +00001732 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001733 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1734 DB_CACHE, DB_CHANGES, DB_CLOSE,
1735 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1736 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1737 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1738 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
drh833bf962010-04-28 14:42:19 +00001739 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
drh304637c2011-03-18 16:47:27 +00001740 DB_PREUPDATE, DB_PROFILE, DB_PROGRESS,
1741 DB_REKEY, DB_RESTORE, DB_ROLLBACK_HOOK,
1742 DB_STATUS, DB_TIMEOUT, DB_TOTAL_CHANGES,
1743 DB_TRACE, DB_TRANSACTION, DB_UNLOCK_NOTIFY,
1744 DB_UPDATE_HOOK, DB_VERSION, DB_WAL_HOOK,
drh6d313162000-09-21 13:01:35 +00001745 };
tpoindex1067fe12004-12-17 15:41:11 +00001746 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001747
1748 if( objc<2 ){
1749 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001750 return TCL_ERROR;
1751 }
drh411995d2002-06-25 19:31:18 +00001752 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001753 return TCL_ERROR;
1754 }
1755
drh411995d2002-06-25 19:31:18 +00001756 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001757
drhe22a3342003-04-22 20:30:37 +00001758 /* $db authorizer ?CALLBACK?
1759 **
1760 ** Invoke the given callback to authorize each SQL operation as it is
1761 ** compiled. 5 arguments are appended to the callback before it is
1762 ** invoked:
1763 **
1764 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1765 ** (2) First descriptive name (depends on authorization type)
1766 ** (3) Second descriptive name
1767 ** (4) Name of the database (ex: "main", "temp")
1768 ** (5) Name of trigger that is doing the access
1769 **
1770 ** The callback should return on of the following strings: SQLITE_OK,
1771 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1772 **
1773 ** If this method is invoked with no arguments, the current authorization
1774 ** callback string is returned.
1775 */
1776 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001777#ifdef SQLITE_OMIT_AUTHORIZATION
drha198f2b2014-02-07 19:26:13 +00001778 Tcl_AppendResult(interp, "authorization not available in this build",
1779 (char*)0);
drh1211de32004-07-26 12:24:22 +00001780 return TCL_ERROR;
1781#else
drhe22a3342003-04-22 20:30:37 +00001782 if( objc>3 ){
1783 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001784 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001785 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001786 if( pDb->zAuth ){
drha198f2b2014-02-07 19:26:13 +00001787 Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
drhe22a3342003-04-22 20:30:37 +00001788 }
1789 }else{
1790 char *zAuth;
1791 int len;
1792 if( pDb->zAuth ){
1793 Tcl_Free(pDb->zAuth);
1794 }
1795 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1796 if( zAuth && len>0 ){
1797 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001798 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001799 }else{
1800 pDb->zAuth = 0;
1801 }
drhe22a3342003-04-22 20:30:37 +00001802 if( pDb->zAuth ){
drh32c6a482014-09-11 13:44:52 +00001803 typedef int (*sqlite3_auth_cb)(
1804 void*,int,const char*,const char*,
1805 const char*,const char*);
drhe22a3342003-04-22 20:30:37 +00001806 pDb->interp = interp;
drh32c6a482014-09-11 13:44:52 +00001807 sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
drhe22a3342003-04-22 20:30:37 +00001808 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001809 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001810 }
drhe22a3342003-04-22 20:30:37 +00001811 }
drh1211de32004-07-26 12:24:22 +00001812#endif
drhe22a3342003-04-22 20:30:37 +00001813 break;
1814 }
1815
drhdc2c4912009-02-04 22:46:47 +00001816 /* $db backup ?DATABASE? FILENAME
1817 **
1818 ** Open or create a database file named FILENAME. Transfer the
1819 ** content of local database DATABASE (default: "main") into the
1820 ** FILENAME database.
1821 */
1822 case DB_BACKUP: {
1823 const char *zDestFile;
1824 const char *zSrcDb;
1825 sqlite3 *pDest;
1826 sqlite3_backup *pBackup;
1827
1828 if( objc==3 ){
1829 zSrcDb = "main";
1830 zDestFile = Tcl_GetString(objv[2]);
1831 }else if( objc==4 ){
1832 zSrcDb = Tcl_GetString(objv[2]);
1833 zDestFile = Tcl_GetString(objv[3]);
1834 }else{
1835 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1836 return TCL_ERROR;
1837 }
1838 rc = sqlite3_open(zDestFile, &pDest);
1839 if( rc!=SQLITE_OK ){
1840 Tcl_AppendResult(interp, "cannot open target database: ",
1841 sqlite3_errmsg(pDest), (char*)0);
1842 sqlite3_close(pDest);
1843 return TCL_ERROR;
1844 }
1845 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1846 if( pBackup==0 ){
1847 Tcl_AppendResult(interp, "backup failed: ",
1848 sqlite3_errmsg(pDest), (char*)0);
1849 sqlite3_close(pDest);
1850 return TCL_ERROR;
1851 }
1852 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1853 sqlite3_backup_finish(pBackup);
1854 if( rc==SQLITE_DONE ){
1855 rc = TCL_OK;
1856 }else{
1857 Tcl_AppendResult(interp, "backup failed: ",
1858 sqlite3_errmsg(pDest), (char*)0);
1859 rc = TCL_ERROR;
1860 }
1861 sqlite3_close(pDest);
1862 break;
1863 }
1864
drhbec3f402000-08-04 13:49:02 +00001865 /* $db busy ?CALLBACK?
1866 **
1867 ** Invoke the given callback if an SQL statement attempts to open
1868 ** a locked database file.
1869 */
drh6d313162000-09-21 13:01:35 +00001870 case DB_BUSY: {
1871 if( objc>3 ){
1872 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001873 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001874 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001875 if( pDb->zBusy ){
drha198f2b2014-02-07 19:26:13 +00001876 Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
drhbec3f402000-08-04 13:49:02 +00001877 }
1878 }else{
drh6d313162000-09-21 13:01:35 +00001879 char *zBusy;
1880 int len;
drhbec3f402000-08-04 13:49:02 +00001881 if( pDb->zBusy ){
1882 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001883 }
drh6d313162000-09-21 13:01:35 +00001884 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1885 if( zBusy && len>0 ){
1886 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001887 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001888 }else{
1889 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001890 }
1891 if( pDb->zBusy ){
1892 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001893 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001894 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001895 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001896 }
1897 }
drh6d313162000-09-21 13:01:35 +00001898 break;
1899 }
drhbec3f402000-08-04 13:49:02 +00001900
drhfb7e7652005-01-24 00:28:42 +00001901 /* $db cache flush
1902 ** $db cache size n
1903 **
1904 ** Flush the prepared statement cache, or set the maximum number of
1905 ** cached statements.
1906 */
1907 case DB_CACHE: {
1908 char *subCmd;
1909 int n;
1910
1911 if( objc<=2 ){
1912 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1913 return TCL_ERROR;
1914 }
1915 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1916 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1917 if( objc!=3 ){
1918 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1919 return TCL_ERROR;
1920 }else{
1921 flushStmtCache( pDb );
1922 }
1923 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1924 if( objc!=4 ){
1925 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1926 return TCL_ERROR;
1927 }else{
1928 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1929 Tcl_AppendResult( interp, "cannot convert \"",
drha198f2b2014-02-07 19:26:13 +00001930 Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
drhfb7e7652005-01-24 00:28:42 +00001931 return TCL_ERROR;
1932 }else{
1933 if( n<0 ){
1934 flushStmtCache( pDb );
1935 n = 0;
1936 }else if( n>MAX_PREPARED_STMTS ){
1937 n = MAX_PREPARED_STMTS;
1938 }
1939 pDb->maxStmt = n;
1940 }
1941 }
1942 }else{
1943 Tcl_AppendResult( interp, "bad option \"",
drha198f2b2014-02-07 19:26:13 +00001944 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
1945 (char*)0);
drhfb7e7652005-01-24 00:28:42 +00001946 return TCL_ERROR;
1947 }
1948 break;
1949 }
1950
danielk1977b28af712004-06-21 06:50:26 +00001951 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001952 **
1953 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001954 ** the most recent INSERT, UPDATE or DELETE statement, not including
1955 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001956 */
1957 case DB_CHANGES: {
1958 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001959 if( objc!=2 ){
1960 Tcl_WrongNumArgs(interp, 2, objv, "");
1961 return TCL_ERROR;
1962 }
drhc8d30ac2002-04-12 10:08:59 +00001963 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001964 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001965 break;
1966 }
1967
drh75897232000-05-29 14:26:00 +00001968 /* $db close
1969 **
1970 ** Shutdown the database
1971 */
drh6d313162000-09-21 13:01:35 +00001972 case DB_CLOSE: {
1973 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1974 break;
1975 }
drh75897232000-05-29 14:26:00 +00001976
drh0f14e2e2004-06-29 12:39:08 +00001977 /*
1978 ** $db collate NAME SCRIPT
1979 **
1980 ** Create a new SQL collation function called NAME. Whenever
1981 ** that function is called, invoke SCRIPT to evaluate the function.
1982 */
1983 case DB_COLLATE: {
1984 SqlCollate *pCollate;
1985 char *zName;
1986 char *zScript;
1987 int nScript;
1988 if( objc!=4 ){
1989 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1990 return TCL_ERROR;
1991 }
1992 zName = Tcl_GetStringFromObj(objv[2], 0);
1993 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1994 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1995 if( pCollate==0 ) return TCL_ERROR;
1996 pCollate->interp = interp;
1997 pCollate->pNext = pDb->pCollate;
1998 pCollate->zScript = (char*)&pCollate[1];
1999 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00002000 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00002001 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
2002 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00002003 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00002004 return TCL_ERROR;
2005 }
2006 break;
2007 }
2008
2009 /*
2010 ** $db collation_needed SCRIPT
2011 **
2012 ** Create a new SQL collation function called NAME. Whenever
2013 ** that function is called, invoke SCRIPT to evaluate the function.
2014 */
2015 case DB_COLLATION_NEEDED: {
2016 if( objc!=3 ){
2017 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
2018 return TCL_ERROR;
2019 }
2020 if( pDb->pCollateNeeded ){
2021 Tcl_DecrRefCount(pDb->pCollateNeeded);
2022 }
2023 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
2024 Tcl_IncrRefCount(pDb->pCollateNeeded);
2025 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
2026 break;
2027 }
2028
drh19e2d372005-08-29 23:00:03 +00002029 /* $db commit_hook ?CALLBACK?
2030 **
2031 ** Invoke the given callback just before committing every SQL transaction.
2032 ** If the callback throws an exception or returns non-zero, then the
2033 ** transaction is aborted. If CALLBACK is an empty string, the callback
2034 ** is disabled.
2035 */
2036 case DB_COMMIT_HOOK: {
2037 if( objc>3 ){
2038 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2039 return TCL_ERROR;
2040 }else if( objc==2 ){
2041 if( pDb->zCommit ){
drha198f2b2014-02-07 19:26:13 +00002042 Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002043 }
2044 }else{
mistachkin6ef5e122014-01-24 17:03:55 +00002045 const char *zCommit;
drh19e2d372005-08-29 23:00:03 +00002046 int len;
2047 if( pDb->zCommit ){
2048 Tcl_Free(pDb->zCommit);
2049 }
2050 zCommit = Tcl_GetStringFromObj(objv[2], &len);
2051 if( zCommit && len>0 ){
2052 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002053 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00002054 }else{
2055 pDb->zCommit = 0;
2056 }
2057 if( pDb->zCommit ){
2058 pDb->interp = interp;
2059 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
2060 }else{
2061 sqlite3_commit_hook(pDb->db, 0, 0);
2062 }
2063 }
2064 break;
2065 }
2066
drh75897232000-05-29 14:26:00 +00002067 /* $db complete SQL
2068 **
2069 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2070 ** additional lines of input are needed. This is similar to the
2071 ** built-in "info complete" command of Tcl.
2072 */
drh6d313162000-09-21 13:01:35 +00002073 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00002074#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00002075 Tcl_Obj *pResult;
2076 int isComplete;
2077 if( objc!=3 ){
2078 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00002079 return TCL_ERROR;
2080 }
danielk19776f8a5032004-05-10 10:34:51 +00002081 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00002082 pResult = Tcl_GetObjResult(interp);
2083 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00002084#endif
drh6d313162000-09-21 13:01:35 +00002085 break;
2086 }
drhdcd997e2003-01-31 17:21:49 +00002087
drh19e2d372005-08-29 23:00:03 +00002088 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2089 **
2090 ** Copy data into table from filename, optionally using SEPARATOR
2091 ** as column separators. If a column contains a null string, or the
2092 ** value of NULLINDICATOR, a NULL is inserted for the column.
2093 ** conflict-algorithm is one of the sqlite conflict algorithms:
2094 ** rollback, abort, fail, ignore, replace
2095 ** On success, return the number of lines processed, not necessarily same
2096 ** as 'db changes' due to conflict-algorithm selected.
2097 **
2098 ** This code is basically an implementation/enhancement of
2099 ** the sqlite3 shell.c ".import" command.
2100 **
2101 ** This command usage is equivalent to the sqlite2.x COPY statement,
2102 ** which imports file data into a table using the PostgreSQL COPY file format:
2103 ** $db copy $conflit_algo $table_name $filename \t \\N
2104 */
2105 case DB_COPY: {
2106 char *zTable; /* Insert data into this table */
2107 char *zFile; /* The file from which to extract data */
2108 char *zConflict; /* The conflict algorithm to use */
2109 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00002110 int nCol; /* Number of columns in the table */
2111 int nByte; /* Number of bytes in an SQL string */
2112 int i, j; /* Loop counters */
2113 int nSep; /* Number of bytes in zSep[] */
2114 int nNull; /* Number of bytes in zNull[] */
2115 char *zSql; /* An SQL statement */
2116 char *zLine; /* A single line of input from the file */
2117 char **azCol; /* zLine[] broken up into columns */
mistachkin6ef5e122014-01-24 17:03:55 +00002118 const char *zCommit; /* How to commit changes */
drh19e2d372005-08-29 23:00:03 +00002119 FILE *in; /* The input file */
2120 int lineno = 0; /* Line number of input file */
2121 char zLineNum[80]; /* Line number print buffer */
2122 Tcl_Obj *pResult; /* interp result */
2123
mistachkin6ef5e122014-01-24 17:03:55 +00002124 const char *zSep;
2125 const char *zNull;
drh19e2d372005-08-29 23:00:03 +00002126 if( objc<5 || objc>7 ){
2127 Tcl_WrongNumArgs(interp, 2, objv,
2128 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2129 return TCL_ERROR;
2130 }
2131 if( objc>=6 ){
2132 zSep = Tcl_GetStringFromObj(objv[5], 0);
2133 }else{
2134 zSep = "\t";
2135 }
2136 if( objc>=7 ){
2137 zNull = Tcl_GetStringFromObj(objv[6], 0);
2138 }else{
2139 zNull = "";
2140 }
2141 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2142 zTable = Tcl_GetStringFromObj(objv[3], 0);
2143 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002144 nSep = strlen30(zSep);
2145 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002146 if( nSep==0 ){
drha198f2b2014-02-07 19:26:13 +00002147 Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2148 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002149 return TCL_ERROR;
2150 }
drh3e59c012008-09-23 10:12:13 +00002151 if(strcmp(zConflict, "rollback") != 0 &&
2152 strcmp(zConflict, "abort" ) != 0 &&
2153 strcmp(zConflict, "fail" ) != 0 &&
2154 strcmp(zConflict, "ignore" ) != 0 &&
2155 strcmp(zConflict, "replace" ) != 0 ) {
drh19e2d372005-08-29 23:00:03 +00002156 Tcl_AppendResult(interp, "Error: \"", zConflict,
2157 "\", conflict-algorithm must be one of: rollback, "
drha198f2b2014-02-07 19:26:13 +00002158 "abort, fail, ignore, or replace", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002159 return TCL_ERROR;
2160 }
2161 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2162 if( zSql==0 ){
drha198f2b2014-02-07 19:26:13 +00002163 Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002164 return TCL_ERROR;
2165 }
drh4f21c4a2008-12-10 22:15:00 +00002166 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002167 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002168 sqlite3_free(zSql);
2169 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002170 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002171 nCol = 0;
2172 }else{
2173 nCol = sqlite3_column_count(pStmt);
2174 }
2175 sqlite3_finalize(pStmt);
2176 if( nCol==0 ) {
2177 return TCL_ERROR;
2178 }
2179 zSql = malloc( nByte + 50 + nCol*2 );
2180 if( zSql==0 ) {
drha198f2b2014-02-07 19:26:13 +00002181 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002182 return TCL_ERROR;
2183 }
2184 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2185 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002186 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002187 for(i=1; i<nCol; i++){
2188 zSql[j++] = ',';
2189 zSql[j++] = '?';
2190 }
2191 zSql[j++] = ')';
2192 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002193 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002194 free(zSql);
2195 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002196 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002197 sqlite3_finalize(pStmt);
2198 return TCL_ERROR;
2199 }
2200 in = fopen(zFile, "rb");
2201 if( in==0 ){
2202 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2203 sqlite3_finalize(pStmt);
2204 return TCL_ERROR;
2205 }
2206 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2207 if( azCol==0 ) {
drha198f2b2014-02-07 19:26:13 +00002208 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh43617e92006-03-06 20:55:46 +00002209 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002210 return TCL_ERROR;
2211 }
drh37527852006-03-16 16:19:56 +00002212 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002213 zCommit = "COMMIT";
2214 while( (zLine = local_getline(0, in))!=0 ){
2215 char *z;
drh19e2d372005-08-29 23:00:03 +00002216 lineno++;
2217 azCol[0] = zLine;
2218 for(i=0, z=zLine; *z; z++){
2219 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2220 *z = 0;
2221 i++;
2222 if( i<nCol ){
2223 azCol[i] = &z[nSep];
2224 z += nSep-1;
2225 }
2226 }
2227 }
2228 if( i+1!=nCol ){
2229 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002230 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002231 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002232 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002233 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002234 "Error: %s line %d: expected %d columns of data but found %d",
2235 zFile, lineno, nCol, i+1);
drha198f2b2014-02-07 19:26:13 +00002236 Tcl_AppendResult(interp, zErr, (char*)0);
drhc1f44942006-05-10 14:39:13 +00002237 free(zErr);
2238 }
drh19e2d372005-08-29 23:00:03 +00002239 zCommit = "ROLLBACK";
2240 break;
2241 }
2242 for(i=0; i<nCol; i++){
2243 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002244 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
drh4f21c4a2008-12-10 22:15:00 +00002245 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002246 ){
drh19e2d372005-08-29 23:00:03 +00002247 sqlite3_bind_null(pStmt, i+1);
2248 }else{
2249 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2250 }
2251 }
2252 sqlite3_step(pStmt);
2253 rc = sqlite3_reset(pStmt);
2254 free(zLine);
2255 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00002256 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002257 zCommit = "ROLLBACK";
2258 break;
2259 }
2260 }
2261 free(azCol);
2262 fclose(in);
2263 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002264 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002265
2266 if( zCommit[0] == 'C' ){
2267 /* success, set result as number of lines processed */
2268 pResult = Tcl_GetObjResult(interp);
2269 Tcl_SetIntObj(pResult, lineno);
2270 rc = TCL_OK;
2271 }else{
2272 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002273 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drha198f2b2014-02-07 19:26:13 +00002274 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2275 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002276 rc = TCL_ERROR;
2277 }
2278 break;
2279 }
2280
drhdcd997e2003-01-31 17:21:49 +00002281 /*
drh41449052006-07-06 17:08:48 +00002282 ** $db enable_load_extension BOOLEAN
2283 **
2284 ** Turn the extension loading feature on or off. It if off by
2285 ** default.
2286 */
2287 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002288#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002289 int onoff;
2290 if( objc!=3 ){
2291 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2292 return TCL_ERROR;
2293 }
2294 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2295 return TCL_ERROR;
2296 }
2297 sqlite3_enable_load_extension(pDb->db, onoff);
2298 break;
drhf533acc2006-12-19 18:57:11 +00002299#else
2300 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
drha198f2b2014-02-07 19:26:13 +00002301 (char*)0);
drhf533acc2006-12-19 18:57:11 +00002302 return TCL_ERROR;
2303#endif
drh41449052006-07-06 17:08:48 +00002304 }
2305
2306 /*
drhdcd997e2003-01-31 17:21:49 +00002307 ** $db errorcode
2308 **
2309 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002310 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002311 */
2312 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002313 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002314 break;
2315 }
dan4a4c11a2009-10-06 14:59:02 +00002316
2317 /*
2318 ** $db exists $sql
2319 ** $db onecolumn $sql
2320 **
2321 ** The onecolumn method is the equivalent of:
2322 ** lindex [$db eval $sql] 0
2323 */
2324 case DB_EXISTS:
2325 case DB_ONECOLUMN: {
2326 DbEvalContext sEval;
2327 if( objc!=3 ){
2328 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2329 return TCL_ERROR;
2330 }
2331
2332 dbEvalInit(&sEval, pDb, objv[2], 0);
2333 rc = dbEvalStep(&sEval);
2334 if( choice==DB_ONECOLUMN ){
2335 if( rc==TCL_OK ){
2336 Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
dand5f12cd2011-08-18 17:47:57 +00002337 }else if( rc==TCL_BREAK ){
2338 Tcl_ResetResult(interp);
dan4a4c11a2009-10-06 14:59:02 +00002339 }
2340 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2341 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
2342 }
2343 dbEvalFinalize(&sEval);
2344
2345 if( rc==TCL_BREAK ){
2346 rc = TCL_OK;
2347 }
2348 break;
2349 }
drh75897232000-05-29 14:26:00 +00002350
2351 /*
drh895d7472004-08-20 16:02:39 +00002352 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002353 **
2354 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002355 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002356 ** If "array" and "code" are omitted, then no callback is every invoked.
2357 ** If "array" is an empty string, then the values are placed in variables
2358 ** that have the same name as the fields extracted by the query.
2359 */
dan4a4c11a2009-10-06 14:59:02 +00002360 case DB_EVAL: {
2361 if( objc<3 || objc>5 ){
2362 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2363 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002364 }
dan4a4c11a2009-10-06 14:59:02 +00002365
drh92febd92004-08-20 18:34:20 +00002366 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002367 DbEvalContext sEval;
2368 Tcl_Obj *pRet = Tcl_NewObj();
2369 Tcl_IncrRefCount(pRet);
2370 dbEvalInit(&sEval, pDb, objv[2], 0);
2371 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2372 int i;
2373 int nCol;
2374 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002375 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002376 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002377 }
2378 }
dan4a4c11a2009-10-06 14:59:02 +00002379 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002380 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002381 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002382 rc = TCL_OK;
2383 }
drh1807ce32004-09-07 13:20:35 +00002384 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002385 }else{
mistachkin8e189222015-04-19 21:43:16 +00002386 ClientData cd2[2];
dan4a4c11a2009-10-06 14:59:02 +00002387 DbEvalContext *p;
2388 Tcl_Obj *pArray = 0;
2389 Tcl_Obj *pScript;
2390
2391 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2392 pArray = objv[3];
2393 }
2394 pScript = objv[objc-1];
2395 Tcl_IncrRefCount(pScript);
2396
2397 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2398 dbEvalInit(p, pDb, objv[2], pArray);
2399
mistachkin8e189222015-04-19 21:43:16 +00002400 cd2[0] = (void *)p;
2401 cd2[1] = (void *)pScript;
2402 rc = DbEvalNextCmd(cd2, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002403 }
danielk197730ccda12004-05-27 12:11:31 +00002404 break;
2405 }
drhbec3f402000-08-04 13:49:02 +00002406
2407 /*
dan3df30592015-03-13 08:31:54 +00002408 ** $db function NAME [-argcount N] [-deterministic] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002409 **
2410 ** Create a new SQL function called NAME. Whenever that function is
2411 ** called, invoke SCRIPT to evaluate the function.
2412 */
2413 case DB_FUNCTION: {
dan3df30592015-03-13 08:31:54 +00002414 int flags = SQLITE_UTF8;
drhcabb0812002-09-14 13:47:32 +00002415 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002416 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002417 char *zName;
drhe3602be2008-09-09 12:31:33 +00002418 int nArg = -1;
dan3df30592015-03-13 08:31:54 +00002419 int i;
2420 if( objc<4 ){
2421 Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
2422 return TCL_ERROR;
2423 }
2424 for(i=3; i<(objc-1); i++){
2425 const char *z = Tcl_GetString(objv[i]);
drh4f21c4a2008-12-10 22:15:00 +00002426 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002427 if( n>2 && strncmp(z, "-argcount",n)==0 ){
dan3df30592015-03-13 08:31:54 +00002428 if( i==(objc-2) ){
2429 Tcl_AppendResult(interp, "option requires an argument: ", z, 0);
2430 return TCL_ERROR;
2431 }
2432 if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002433 if( nArg<0 ){
2434 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2435 (char*)0);
2436 return TCL_ERROR;
2437 }
dan3df30592015-03-13 08:31:54 +00002438 i++;
2439 }else
2440 if( n>2 && strncmp(z, "-deterministic",n)==0 ){
2441 flags |= SQLITE_DETERMINISTIC;
2442 }else{
2443 Tcl_AppendResult(interp, "bad option \"", z,
2444 "\": must be -argcount or -deterministic", 0
2445 );
2446 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002447 }
drhcabb0812002-09-14 13:47:32 +00002448 }
dan3df30592015-03-13 08:31:54 +00002449
2450 pScript = objv[objc-1];
drhcabb0812002-09-14 13:47:32 +00002451 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002452 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002453 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002454 if( pFunc->pScript ){
2455 Tcl_DecrRefCount(pFunc->pScript);
2456 }
2457 pFunc->pScript = pScript;
2458 Tcl_IncrRefCount(pScript);
2459 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
dan3df30592015-03-13 08:31:54 +00002460 rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
danielk1977d8123362004-06-12 09:25:12 +00002461 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002462 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002463 rc = TCL_ERROR;
2464 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002465 }
drhcabb0812002-09-14 13:47:32 +00002466 break;
2467 }
2468
2469 /*
danielk19778cbadb02007-05-03 16:31:26 +00002470 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002471 */
2472 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002473#ifdef SQLITE_OMIT_INCRBLOB
drha198f2b2014-02-07 19:26:13 +00002474 Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
danielk197732a0d8b2007-05-04 19:03:02 +00002475 return TCL_ERROR;
2476#else
danielk19778cbadb02007-05-03 16:31:26 +00002477 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002478 const char *zDb = "main";
2479 const char *zTable;
2480 const char *zColumn;
drhb3f787f2012-09-29 14:45:54 +00002481 Tcl_WideInt iRow;
danielk1977b4e9af92007-05-01 17:49:49 +00002482
danielk19778cbadb02007-05-03 16:31:26 +00002483 /* Check for the -readonly option */
2484 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2485 isReadonly = 1;
2486 }
2487
2488 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2489 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002490 return TCL_ERROR;
2491 }
2492
danielk19778cbadb02007-05-03 16:31:26 +00002493 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002494 zDb = Tcl_GetString(objv[2]);
2495 }
2496 zTable = Tcl_GetString(objv[objc-3]);
2497 zColumn = Tcl_GetString(objv[objc-2]);
2498 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2499
2500 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002501 rc = createIncrblobChannel(
danedf5b162014-08-19 09:15:41 +00002502 interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
danielk19778cbadb02007-05-03 16:31:26 +00002503 );
danielk1977b4e9af92007-05-01 17:49:49 +00002504 }
danielk197732a0d8b2007-05-04 19:03:02 +00002505#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002506 break;
2507 }
2508
2509 /*
drhf11bded2006-07-17 00:02:44 +00002510 ** $db interrupt
2511 **
2512 ** Interrupt the execution of the inner-most SQL interpreter. This
2513 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2514 */
2515 case DB_INTERRUPT: {
2516 sqlite3_interrupt(pDb->db);
2517 break;
2518 }
2519
2520 /*
drh19e2d372005-08-29 23:00:03 +00002521 ** $db nullvalue ?STRING?
2522 **
2523 ** Change text used when a NULL comes back from the database. If ?STRING?
2524 ** is not present, then the current string used for NULL is returned.
2525 ** If STRING is present, then STRING is returned.
2526 **
2527 */
2528 case DB_NULLVALUE: {
2529 if( objc!=2 && objc!=3 ){
2530 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2531 return TCL_ERROR;
2532 }
2533 if( objc==3 ){
2534 int len;
2535 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2536 if( pDb->zNull ){
2537 Tcl_Free(pDb->zNull);
2538 }
2539 if( zNull && len>0 ){
2540 pDb->zNull = Tcl_Alloc( len + 1 );
drh7fd33922011-06-20 19:00:30 +00002541 memcpy(pDb->zNull, zNull, len);
drh19e2d372005-08-29 23:00:03 +00002542 pDb->zNull[len] = '\0';
2543 }else{
2544 pDb->zNull = 0;
2545 }
2546 }
drhc45e6712012-10-03 11:02:33 +00002547 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
drh19e2d372005-08-29 23:00:03 +00002548 break;
2549 }
2550
2551 /*
drhaf9ff332002-01-16 21:00:27 +00002552 ** $db last_insert_rowid
2553 **
2554 ** Return an integer which is the ROWID for the most recent insert.
2555 */
2556 case DB_LAST_INSERT_ROWID: {
2557 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002558 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002559 if( objc!=2 ){
2560 Tcl_WrongNumArgs(interp, 2, objv, "");
2561 return TCL_ERROR;
2562 }
danielk19776f8a5032004-05-10 10:34:51 +00002563 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002564 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002565 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002566 break;
2567 }
2568
2569 /*
dan4a4c11a2009-10-06 14:59:02 +00002570 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002571 */
drh1807ce32004-09-07 13:20:35 +00002572
2573 /* $db progress ?N CALLBACK?
2574 **
2575 ** Invoke the given callback every N virtual machine opcodes while executing
2576 ** queries.
2577 */
2578 case DB_PROGRESS: {
2579 if( objc==2 ){
2580 if( pDb->zProgress ){
drha198f2b2014-02-07 19:26:13 +00002581 Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
drh1807ce32004-09-07 13:20:35 +00002582 }
2583 }else if( objc==4 ){
2584 char *zProgress;
2585 int len;
2586 int N;
2587 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002588 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002589 };
2590 if( pDb->zProgress ){
2591 Tcl_Free(pDb->zProgress);
2592 }
2593 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2594 if( zProgress && len>0 ){
2595 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002596 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002597 }else{
2598 pDb->zProgress = 0;
2599 }
2600#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2601 if( pDb->zProgress ){
2602 pDb->interp = interp;
2603 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2604 }else{
2605 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2606 }
2607#endif
2608 }else{
2609 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002610 return TCL_ERROR;
2611 }
drh5d9d7572003-08-19 14:31:01 +00002612 break;
2613 }
2614
drh19e2d372005-08-29 23:00:03 +00002615 /* $db profile ?CALLBACK?
2616 **
2617 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2618 ** that has run. The text of the SQL and the amount of elapse time are
2619 ** appended to CALLBACK before the script is run.
2620 */
2621 case DB_PROFILE: {
2622 if( objc>3 ){
2623 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2624 return TCL_ERROR;
2625 }else if( objc==2 ){
2626 if( pDb->zProfile ){
drha198f2b2014-02-07 19:26:13 +00002627 Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002628 }
2629 }else{
2630 char *zProfile;
2631 int len;
2632 if( pDb->zProfile ){
2633 Tcl_Free(pDb->zProfile);
2634 }
2635 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2636 if( zProfile && len>0 ){
2637 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002638 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002639 }else{
2640 pDb->zProfile = 0;
2641 }
shanehbb201342011-02-09 19:55:20 +00002642#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh19e2d372005-08-29 23:00:03 +00002643 if( pDb->zProfile ){
2644 pDb->interp = interp;
2645 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2646 }else{
2647 sqlite3_profile(pDb->db, 0, 0);
2648 }
2649#endif
2650 }
2651 break;
2652 }
2653
drh5d9d7572003-08-19 14:31:01 +00002654 /*
drh22fbcb82004-02-01 01:22:50 +00002655 ** $db rekey KEY
2656 **
2657 ** Change the encryption key on the currently open database.
2658 */
2659 case DB_REKEY: {
drhb07028f2011-10-14 21:49:18 +00002660#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002661 int nKey;
2662 void *pKey;
drhb07028f2011-10-14 21:49:18 +00002663#endif
drh22fbcb82004-02-01 01:22:50 +00002664 if( objc!=3 ){
2665 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2666 return TCL_ERROR;
2667 }
drh9eb9e262004-02-11 02:18:05 +00002668#ifdef SQLITE_HAS_CODEC
drhb07028f2011-10-14 21:49:18 +00002669 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh2011d5f2004-07-22 02:40:37 +00002670 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002671 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002672 Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
drh22fbcb82004-02-01 01:22:50 +00002673 rc = TCL_ERROR;
2674 }
2675#endif
2676 break;
2677 }
2678
drhdc2c4912009-02-04 22:46:47 +00002679 /* $db restore ?DATABASE? FILENAME
2680 **
2681 ** Open a database file named FILENAME. Transfer the content
2682 ** of FILENAME into the local database DATABASE (default: "main").
2683 */
2684 case DB_RESTORE: {
2685 const char *zSrcFile;
2686 const char *zDestDb;
2687 sqlite3 *pSrc;
2688 sqlite3_backup *pBackup;
2689 int nTimeout = 0;
2690
2691 if( objc==3 ){
2692 zDestDb = "main";
2693 zSrcFile = Tcl_GetString(objv[2]);
2694 }else if( objc==4 ){
2695 zDestDb = Tcl_GetString(objv[2]);
2696 zSrcFile = Tcl_GetString(objv[3]);
2697 }else{
2698 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2699 return TCL_ERROR;
2700 }
2701 rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
2702 if( rc!=SQLITE_OK ){
2703 Tcl_AppendResult(interp, "cannot open source database: ",
2704 sqlite3_errmsg(pSrc), (char*)0);
2705 sqlite3_close(pSrc);
2706 return TCL_ERROR;
2707 }
2708 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2709 if( pBackup==0 ){
2710 Tcl_AppendResult(interp, "restore failed: ",
2711 sqlite3_errmsg(pDb->db), (char*)0);
2712 sqlite3_close(pSrc);
2713 return TCL_ERROR;
2714 }
2715 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2716 || rc==SQLITE_BUSY ){
2717 if( rc==SQLITE_BUSY ){
2718 if( nTimeout++ >= 3 ) break;
2719 sqlite3_sleep(100);
2720 }
2721 }
2722 sqlite3_backup_finish(pBackup);
2723 if( rc==SQLITE_DONE ){
2724 rc = TCL_OK;
2725 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2726 Tcl_AppendResult(interp, "restore failed: source database busy",
2727 (char*)0);
2728 rc = TCL_ERROR;
2729 }else{
2730 Tcl_AppendResult(interp, "restore failed: ",
2731 sqlite3_errmsg(pDb->db), (char*)0);
2732 rc = TCL_ERROR;
2733 }
2734 sqlite3_close(pSrc);
2735 break;
2736 }
2737
drh22fbcb82004-02-01 01:22:50 +00002738 /*
drh3c379b02010-04-07 19:31:59 +00002739 ** $db status (step|sort|autoindex)
drhd1d38482008-10-07 23:46:38 +00002740 **
2741 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2742 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2743 */
2744 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002745 int v;
2746 const char *zOp;
2747 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00002748 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00002749 return TCL_ERROR;
2750 }
2751 zOp = Tcl_GetString(objv[2]);
2752 if( strcmp(zOp, "step")==0 ){
2753 v = pDb->nStep;
2754 }else if( strcmp(zOp, "sort")==0 ){
2755 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002756 }else if( strcmp(zOp, "autoindex")==0 ){
2757 v = pDb->nIndex;
drhd1d38482008-10-07 23:46:38 +00002758 }else{
drh3c379b02010-04-07 19:31:59 +00002759 Tcl_AppendResult(interp,
2760 "bad argument: should be autoindex, step, or sort",
drhd1d38482008-10-07 23:46:38 +00002761 (char*)0);
2762 return TCL_ERROR;
2763 }
2764 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2765 break;
2766 }
2767
2768 /*
drhbec3f402000-08-04 13:49:02 +00002769 ** $db timeout MILLESECONDS
2770 **
2771 ** Delay for the number of milliseconds specified when a file is locked.
2772 */
drh6d313162000-09-21 13:01:35 +00002773 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002774 int ms;
drh6d313162000-09-21 13:01:35 +00002775 if( objc!=3 ){
2776 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002777 return TCL_ERROR;
2778 }
drh6d313162000-09-21 13:01:35 +00002779 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002780 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002781 break;
drh75897232000-05-29 14:26:00 +00002782 }
danielk197755c45f22005-04-03 23:54:43 +00002783
2784 /*
drh0f14e2e2004-06-29 12:39:08 +00002785 ** $db total_changes
2786 **
2787 ** Return the number of rows that were modified, inserted, or deleted
2788 ** since the database handle was created.
2789 */
2790 case DB_TOTAL_CHANGES: {
2791 Tcl_Obj *pResult;
2792 if( objc!=2 ){
2793 Tcl_WrongNumArgs(interp, 2, objv, "");
2794 return TCL_ERROR;
2795 }
2796 pResult = Tcl_GetObjResult(interp);
2797 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2798 break;
2799 }
2800
drhb5a20d32003-04-23 12:25:23 +00002801 /* $db trace ?CALLBACK?
2802 **
2803 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2804 ** that is executed. The text of the SQL is appended to CALLBACK before
2805 ** it is executed.
2806 */
2807 case DB_TRACE: {
2808 if( objc>3 ){
2809 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002810 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002811 }else if( objc==2 ){
2812 if( pDb->zTrace ){
drha198f2b2014-02-07 19:26:13 +00002813 Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
drhb5a20d32003-04-23 12:25:23 +00002814 }
2815 }else{
2816 char *zTrace;
2817 int len;
2818 if( pDb->zTrace ){
2819 Tcl_Free(pDb->zTrace);
2820 }
2821 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2822 if( zTrace && len>0 ){
2823 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002824 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002825 }else{
2826 pDb->zTrace = 0;
2827 }
shanehbb201342011-02-09 19:55:20 +00002828#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drhb5a20d32003-04-23 12:25:23 +00002829 if( pDb->zTrace ){
2830 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002831 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002832 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002833 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002834 }
drh19e2d372005-08-29 23:00:03 +00002835#endif
drhb5a20d32003-04-23 12:25:23 +00002836 }
2837 break;
2838 }
2839
drh3d214232005-08-02 12:21:08 +00002840 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2841 **
2842 ** Start a new transaction (if we are not already in the midst of a
2843 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2844 ** completes, either commit the transaction or roll it back if SCRIPT
2845 ** throws an exception. Or if no new transation was started, do nothing.
2846 ** pass the exception on up the stack.
2847 **
2848 ** This command was inspired by Dave Thomas's talk on Ruby at the
2849 ** 2005 O'Reilly Open Source Convention (OSCON).
2850 */
2851 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00002852 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00002853 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00002854 if( objc!=3 && objc!=4 ){
2855 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2856 return TCL_ERROR;
2857 }
danielk1977cd38d522009-01-02 17:33:46 +00002858
dan4a4c11a2009-10-06 14:59:02 +00002859 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00002860 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002861 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002862 };
2863 enum TTYPE_enum {
2864 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2865 };
2866 int ttype;
drhb5555e72005-08-02 17:15:14 +00002867 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002868 0, &ttype) ){
2869 return TCL_ERROR;
2870 }
2871 switch( (enum TTYPE_enum)ttype ){
2872 case TTYPE_DEFERRED: /* no-op */; break;
2873 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2874 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2875 }
drh3d214232005-08-02 12:21:08 +00002876 }
danielk1977cd38d522009-01-02 17:33:46 +00002877 pScript = objv[objc-1];
2878
dan4a4c11a2009-10-06 14:59:02 +00002879 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00002880 pDb->disableAuth++;
2881 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2882 pDb->disableAuth--;
2883 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00002884 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977cd38d522009-01-02 17:33:46 +00002885 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00002886 }
danielk1977cd38d522009-01-02 17:33:46 +00002887 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00002888
dan4a4c11a2009-10-06 14:59:02 +00002889 /* If using NRE, schedule a callback to invoke the script pScript, then
2890 ** a second callback to commit (or rollback) the transaction or savepoint
2891 ** opened above. If not using NRE, evaluate the script directly, then
2892 ** call function DbTransPostCmd() to commit (or rollback) the transaction
2893 ** or savepoint. */
2894 if( DbUseNre() ){
2895 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
drha47941f2013-12-20 18:57:44 +00002896 (void)Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00002897 }else{
dan4a4c11a2009-10-06 14:59:02 +00002898 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00002899 }
2900 break;
2901 }
2902
danielk197794eb6a12005-12-15 15:22:08 +00002903 /*
danielk1977404ca072009-03-16 13:19:36 +00002904 ** $db unlock_notify ?script?
2905 */
2906 case DB_UNLOCK_NOTIFY: {
2907#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
drha198f2b2014-02-07 19:26:13 +00002908 Tcl_AppendResult(interp, "unlock_notify not available in this build",
2909 (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00002910 rc = TCL_ERROR;
2911#else
2912 if( objc!=2 && objc!=3 ){
2913 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2914 rc = TCL_ERROR;
2915 }else{
2916 void (*xNotify)(void **, int) = 0;
2917 void *pNotifyArg = 0;
2918
2919 if( pDb->pUnlockNotify ){
2920 Tcl_DecrRefCount(pDb->pUnlockNotify);
2921 pDb->pUnlockNotify = 0;
2922 }
2923
2924 if( objc==3 ){
2925 xNotify = DbUnlockNotify;
2926 pNotifyArg = (void *)pDb;
2927 pDb->pUnlockNotify = objv[2];
2928 Tcl_IncrRefCount(pDb->pUnlockNotify);
2929 }
2930
2931 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
drha198f2b2014-02-07 19:26:13 +00002932 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00002933 rc = TCL_ERROR;
2934 }
2935 }
2936#endif
2937 break;
2938 }
2939
drh304637c2011-03-18 16:47:27 +00002940 /*
2941 ** $db preupdate_hook count
2942 ** $db preupdate_hook hook ?SCRIPT?
2943 ** $db preupdate_hook new INDEX
2944 ** $db preupdate_hook old INDEX
2945 */
dan46c47d42011-03-01 18:42:07 +00002946 case DB_PREUPDATE: {
drh9b1c62d2011-03-30 21:04:43 +00002947#ifndef SQLITE_ENABLE_PREUPDATE_HOOK
2948 Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time");
2949 rc = TCL_ERROR;
2950#else
dan1e7a2d42011-03-22 18:45:29 +00002951 static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
dan46c47d42011-03-01 18:42:07 +00002952 enum DbPreupdateSubCmd {
dan1e7a2d42011-03-22 18:45:29 +00002953 PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
dan46c47d42011-03-01 18:42:07 +00002954 };
2955 int iSub;
2956
2957 if( objc<3 ){
2958 Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
2959 }
2960 if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
2961 return TCL_ERROR;
2962 }
2963
2964 switch( (enum DbPreupdateSubCmd)iSub ){
2965 case PRE_COUNT: {
2966 int nCol = sqlite3_preupdate_count(pDb->db);
2967 Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
2968 break;
2969 }
2970
2971 case PRE_HOOK: {
2972 if( objc>4 ){
2973 Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
2974 return TCL_ERROR;
2975 }
2976 DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
2977 break;
2978 }
2979
dan1e7a2d42011-03-22 18:45:29 +00002980 case PRE_DEPTH: {
2981 Tcl_Obj *pRet;
2982 if( objc!=3 ){
2983 Tcl_WrongNumArgs(interp, 3, objv, "");
2984 return TCL_ERROR;
2985 }
2986 pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
2987 Tcl_SetObjResult(interp, pRet);
2988 break;
2989 }
2990
dan37db03b2011-03-16 19:59:18 +00002991 case PRE_NEW:
dan46c47d42011-03-01 18:42:07 +00002992 case PRE_OLD: {
2993 int iIdx;
dan37db03b2011-03-16 19:59:18 +00002994 sqlite3_value *pValue;
dan46c47d42011-03-01 18:42:07 +00002995 if( objc!=4 ){
2996 Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
2997 return TCL_ERROR;
2998 }
2999 if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
3000 return TCL_ERROR;
3001 }
3002
dan37db03b2011-03-16 19:59:18 +00003003 if( iSub==PRE_OLD ){
dan46c47d42011-03-01 18:42:07 +00003004 rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
dan37db03b2011-03-16 19:59:18 +00003005 }else{
3006 assert( iSub==PRE_NEW );
3007 rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
dan46c47d42011-03-01 18:42:07 +00003008 }
3009
dan37db03b2011-03-16 19:59:18 +00003010 if( rc==SQLITE_OK ){
drh304637c2011-03-18 16:47:27 +00003011 Tcl_Obj *pObj;
3012 pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
dan37db03b2011-03-16 19:59:18 +00003013 Tcl_SetObjResult(interp, pObj);
3014 }else{
dan46c47d42011-03-01 18:42:07 +00003015 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
3016 return TCL_ERROR;
3017 }
3018 }
3019 }
drh9b1c62d2011-03-30 21:04:43 +00003020#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +00003021 break;
3022 }
3023
danielk1977404ca072009-03-16 13:19:36 +00003024 /*
drh833bf962010-04-28 14:42:19 +00003025 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003026 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00003027 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003028 */
drh833bf962010-04-28 14:42:19 +00003029 case DB_WAL_HOOK:
danielk197771fd80b2005-12-16 06:54:01 +00003030 case DB_UPDATE_HOOK:
dan6566ebe2011-03-16 09:49:14 +00003031 case DB_ROLLBACK_HOOK: {
danielk197771fd80b2005-12-16 06:54:01 +00003032 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
3033 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3034 */
3035 Tcl_Obj **ppHook;
dan46c47d42011-03-01 18:42:07 +00003036 if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
3037 if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
3038 if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
3039 if( objc>3 ){
danielk197794eb6a12005-12-15 15:22:08 +00003040 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3041 return TCL_ERROR;
3042 }
danielk197771fd80b2005-12-16 06:54:01 +00003043
dan46c47d42011-03-01 18:42:07 +00003044 DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00003045 break;
3046 }
3047
danielk19774397de52005-01-12 12:44:03 +00003048 /* $db version
3049 **
3050 ** Return the version string for this database.
3051 */
3052 case DB_VERSION: {
3053 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
3054 break;
3055 }
3056
tpoindex1067fe12004-12-17 15:41:11 +00003057
drh6d313162000-09-21 13:01:35 +00003058 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00003059 return rc;
drh75897232000-05-29 14:26:00 +00003060}
3061
drha2c8a952009-10-13 18:38:34 +00003062#if SQLITE_TCL_NRE
3063/*
3064** Adaptor that provides an objCmd interface to the NRE-enabled
3065** interface implementation.
3066*/
3067static int DbObjCmdAdaptor(
3068 void *cd,
3069 Tcl_Interp *interp,
3070 int objc,
3071 Tcl_Obj *const*objv
3072){
3073 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
3074}
3075#endif /* SQLITE_TCL_NRE */
3076
drh75897232000-05-29 14:26:00 +00003077/*
drh3570ad92007-08-31 14:31:44 +00003078** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00003079** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00003080**
3081** This is the main Tcl command. When the "sqlite" Tcl command is
3082** invoked, this routine runs to process that command.
3083**
3084** The first argument, DBNAME, is an arbitrary name for a new
3085** database connection. This command creates a new command named
3086** DBNAME that is used to control that connection. The database
3087** connection is deleted when the DBNAME command is deleted.
3088**
drh3570ad92007-08-31 14:31:44 +00003089** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00003090**
drh75897232000-05-29 14:26:00 +00003091*/
drh22fbcb82004-02-01 01:22:50 +00003092static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00003093 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00003094 const char *zArg;
drh75897232000-05-29 14:26:00 +00003095 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00003096 int i;
drh22fbcb82004-02-01 01:22:50 +00003097 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00003098 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00003099 int flags;
drh882e8e42006-08-24 02:42:27 +00003100 Tcl_DString translatedFilename;
drhb07028f2011-10-14 21:49:18 +00003101#ifdef SQLITE_HAS_CODEC
3102 void *pKey = 0;
3103 int nKey = 0;
3104#endif
mistachkin540ebf82012-09-10 07:29:29 +00003105 int rc;
drhd9da78a2009-03-24 15:08:09 +00003106
3107 /* In normal use, each TCL interpreter runs in a single thread. So
3108 ** by default, we can turn of mutexing on SQLite database connections.
3109 ** However, for testing purposes it is useful to have mutexes turned
3110 ** on. So, by default, mutexes default off. But if compiled with
3111 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3112 */
3113#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3114 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3115#else
3116 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3117#endif
3118
drh22fbcb82004-02-01 01:22:50 +00003119 if( objc==2 ){
3120 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00003121 if( strcmp(zArg,"-version")==0 ){
drha198f2b2014-02-07 19:26:13 +00003122 Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
drh647cb0e2002-11-04 19:32:25 +00003123 return TCL_OK;
3124 }
drh9eb9e262004-02-11 02:18:05 +00003125 if( strcmp(zArg,"-has-codec")==0 ){
3126#ifdef SQLITE_HAS_CODEC
drha198f2b2014-02-07 19:26:13 +00003127 Tcl_AppendResult(interp,"1",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003128#else
drha198f2b2014-02-07 19:26:13 +00003129 Tcl_AppendResult(interp,"0",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003130#endif
3131 return TCL_OK;
3132 }
drhfbc3eab2001-04-06 16:13:42 +00003133 }
drh3570ad92007-08-31 14:31:44 +00003134 for(i=3; i+1<objc; i+=2){
3135 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00003136 if( strcmp(zArg,"-key")==0 ){
drhb07028f2011-10-14 21:49:18 +00003137#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00003138 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
drhb07028f2011-10-14 21:49:18 +00003139#endif
drh3570ad92007-08-31 14:31:44 +00003140 }else if( strcmp(zArg, "-vfs")==0 ){
dan3c3dd7b2010-06-22 11:10:40 +00003141 zVfs = Tcl_GetString(objv[i+1]);
drh3570ad92007-08-31 14:31:44 +00003142 }else if( strcmp(zArg, "-readonly")==0 ){
3143 int b;
3144 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3145 if( b ){
drh33f4e022007-09-03 15:19:34 +00003146 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00003147 flags |= SQLITE_OPEN_READONLY;
3148 }else{
3149 flags &= ~SQLITE_OPEN_READONLY;
3150 flags |= SQLITE_OPEN_READWRITE;
3151 }
3152 }else if( strcmp(zArg, "-create")==0 ){
3153 int b;
3154 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00003155 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00003156 flags |= SQLITE_OPEN_CREATE;
3157 }else{
3158 flags &= ~SQLITE_OPEN_CREATE;
3159 }
danielk19779a6284c2008-07-10 17:52:49 +00003160 }else if( strcmp(zArg, "-nomutex")==0 ){
3161 int b;
3162 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3163 if( b ){
3164 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00003165 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00003166 }else{
3167 flags &= ~SQLITE_OPEN_NOMUTEX;
3168 }
danc431fd52011-06-27 16:55:50 +00003169 }else if( strcmp(zArg, "-fullmutex")==0 ){
drh039963a2008-09-03 00:43:15 +00003170 int b;
3171 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3172 if( b ){
3173 flags |= SQLITE_OPEN_FULLMUTEX;
3174 flags &= ~SQLITE_OPEN_NOMUTEX;
3175 }else{
3176 flags &= ~SQLITE_OPEN_FULLMUTEX;
3177 }
drhf12b3f62011-12-21 14:42:29 +00003178 }else if( strcmp(zArg, "-uri")==0 ){
3179 int b;
3180 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3181 if( b ){
3182 flags |= SQLITE_OPEN_URI;
3183 }else{
3184 flags &= ~SQLITE_OPEN_URI;
3185 }
drh3570ad92007-08-31 14:31:44 +00003186 }else{
3187 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3188 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00003189 }
3190 }
drh3570ad92007-08-31 14:31:44 +00003191 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00003192 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00003193 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh68bd4aa2012-01-13 16:16:10 +00003194 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
drh9eb9e262004-02-11 02:18:05 +00003195#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00003196 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00003197#endif
3198 );
drh75897232000-05-29 14:26:00 +00003199 return TCL_ERROR;
3200 }
drh75897232000-05-29 14:26:00 +00003201 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003202 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00003203 if( p==0 ){
mistachkin6ef5e122014-01-24 17:03:55 +00003204 Tcl_SetResult(interp, (char *)"malloc failed", TCL_STATIC);
drhbec3f402000-08-04 13:49:02 +00003205 return TCL_ERROR;
3206 }
3207 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00003208 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00003209 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003210 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00003211 Tcl_DStringFree(&translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003212 if( p->db ){
3213 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3214 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3215 sqlite3_close(p->db);
3216 p->db = 0;
3217 }
3218 }else{
mistachkin5dac8432012-09-11 02:00:25 +00003219 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
danielk197780290862004-05-22 09:21:21 +00003220 }
drh2011d5f2004-07-22 02:40:37 +00003221#ifdef SQLITE_HAS_CODEC
drhf3a65f72007-08-22 20:18:21 +00003222 if( p->db ){
3223 sqlite3_key(p->db, pKey, nKey);
3224 }
drheb8ed702004-02-11 10:37:23 +00003225#endif
drhbec3f402000-08-04 13:49:02 +00003226 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003227 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003228 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003229 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003230 return TCL_ERROR;
3231 }
drhfb7e7652005-01-24 00:28:42 +00003232 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00003233 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003234 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003235 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003236 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3237 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003238 }else{
3239 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3240 }
drh75897232000-05-29 14:26:00 +00003241 return TCL_OK;
3242}
3243
3244/*
drh90ca9752001-09-28 17:47:14 +00003245** Provide a dummy Tcl_InitStubs if we are using this as a static
3246** library.
3247*/
3248#ifndef USE_TCL_STUBS
3249# undef Tcl_InitStubs
drh0e85ccf2013-06-03 12:34:46 +00003250# define Tcl_InitStubs(a,b,c) TCL_VERSION
drh90ca9752001-09-28 17:47:14 +00003251#endif
3252
3253/*
drh29bc4612005-10-05 10:40:15 +00003254** Make sure we have a PACKAGE_VERSION macro defined. This will be
3255** defined automatically by the TEA makefile. But other makefiles
3256** do not define it.
3257*/
3258#ifndef PACKAGE_VERSION
3259# define PACKAGE_VERSION SQLITE_VERSION
3260#endif
3261
3262/*
drh75897232000-05-29 14:26:00 +00003263** Initialize this module.
3264**
3265** This Tcl module contains only a single new Tcl command named "sqlite".
3266** (Hence there is no namespace. There is no point in using a namespace
3267** if the extension only supplies one new name!) The "sqlite" command is
3268** used to open a new SQLite database. See the DbMain() routine above
3269** for additional information.
drhb652f432010-08-26 16:46:57 +00003270**
3271** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003272*/
drhb652f432010-08-26 16:46:57 +00003273EXTERN int Sqlite3_Init(Tcl_Interp *interp){
mistachkin27b2f052015-01-12 19:49:46 +00003274 int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
drh6dc8cbe2013-05-31 15:36:07 +00003275 if( rc==TCL_OK ){
3276 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh1cca0d22010-08-25 20:35:51 +00003277#ifndef SQLITE_3_SUFFIX_ONLY
drh6dc8cbe2013-05-31 15:36:07 +00003278 /* The "sqlite" alias is undocumented. It is here only to support
3279 ** legacy scripts. All new scripts should use only the "sqlite3"
3280 ** command. */
3281 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003282#endif
drh6dc8cbe2013-05-31 15:36:07 +00003283 rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3284 }
3285 return rc;
drh90ca9752001-09-28 17:47:14 +00003286}
drhb652f432010-08-26 16:46:57 +00003287EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
drhb652f432010-08-26 16:46:57 +00003288EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3289EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00003290
drhd878cab2012-03-20 15:10:42 +00003291/* Because it accesses the file-system and uses persistent state, SQLite
3292** is not considered appropriate for safe interpreters. Hence, we deliberately
3293** omit the _SafeInit() interfaces.
3294*/
drh49766d62005-01-08 18:42:28 +00003295
3296#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003297int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3298int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
dana3e63c42010-08-20 12:33:59 +00003299int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3300int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00003301#endif
drh75897232000-05-29 14:26:00 +00003302
drh3e27c022004-07-23 00:01:38 +00003303#ifdef TCLSH
3304/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003305** All of the code that follows is used to build standalone TCL interpreters
3306** that are statically linked with SQLite. Enable these by compiling
3307** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3308** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3309** analysis program.
drh75897232000-05-29 14:26:00 +00003310*/
drh348784e2000-05-29 20:41:49 +00003311
drh57a02272009-10-22 20:52:05 +00003312#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3313/*
3314 * This code implements the MD5 message-digest algorithm.
3315 * The algorithm is due to Ron Rivest. This code was
3316 * written by Colin Plumb in 1993, no copyright is claimed.
3317 * This code is in the public domain; do with it what you wish.
3318 *
3319 * Equivalent code is available from RSA Data Security, Inc.
3320 * This code has been tested against that, and is equivalent,
3321 * except that you don't need to include two pages of legalese
3322 * with every copy.
3323 *
3324 * To compute the message digest of a chunk of bytes, declare an
3325 * MD5Context structure, pass it to MD5Init, call MD5Update as
3326 * needed on buffers full of bytes, and then call MD5Final, which
3327 * will fill a supplied 16-byte array with the digest.
3328 */
3329
3330/*
3331 * If compiled on a machine that doesn't have a 32-bit integer,
3332 * you just set "uint32" to the appropriate datatype for an
3333 * unsigned 32-bit integer. For example:
3334 *
3335 * cc -Duint32='unsigned long' md5.c
3336 *
3337 */
3338#ifndef uint32
3339# define uint32 unsigned int
3340#endif
3341
3342struct MD5Context {
3343 int isInit;
3344 uint32 buf[4];
3345 uint32 bits[2];
3346 unsigned char in[64];
3347};
3348typedef struct MD5Context MD5Context;
3349
3350/*
3351 * Note: this code is harmless on little-endian machines.
3352 */
3353static void byteReverse (unsigned char *buf, unsigned longs){
3354 uint32 t;
3355 do {
3356 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3357 ((unsigned)buf[1]<<8 | buf[0]);
3358 *(uint32 *)buf = t;
3359 buf += 4;
3360 } while (--longs);
3361}
3362/* The four core functions - F1 is optimized somewhat */
3363
3364/* #define F1(x, y, z) (x & y | ~x & z) */
3365#define F1(x, y, z) (z ^ (x & (y ^ z)))
3366#define F2(x, y, z) F1(z, x, y)
3367#define F3(x, y, z) (x ^ y ^ z)
3368#define F4(x, y, z) (y ^ (x | ~z))
3369
3370/* This is the central step in the MD5 algorithm. */
3371#define MD5STEP(f, w, x, y, z, data, s) \
3372 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3373
3374/*
3375 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3376 * reflect the addition of 16 longwords of new data. MD5Update blocks
3377 * the data and converts bytes into longwords for this routine.
3378 */
3379static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3380 register uint32 a, b, c, d;
3381
3382 a = buf[0];
3383 b = buf[1];
3384 c = buf[2];
3385 d = buf[3];
3386
3387 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3388 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3389 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3390 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3391 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3392 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3393 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3394 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3395 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3396 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3397 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3398 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3399 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3400 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3401 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3402 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3403
3404 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3405 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3406 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3407 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3408 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3409 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3410 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3411 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3412 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3413 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3414 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3415 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3416 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3417 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3418 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3419 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3420
3421 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3422 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3423 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3424 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3425 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3426 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3427 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3428 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3429 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3430 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3431 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3432 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3433 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3434 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3435 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3436 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3437
3438 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3439 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3440 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3441 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3442 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3443 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3444 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3445 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3446 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3447 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3448 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3449 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3450 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3451 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3452 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3453 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3454
3455 buf[0] += a;
3456 buf[1] += b;
3457 buf[2] += c;
3458 buf[3] += d;
3459}
3460
3461/*
3462 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3463 * initialization constants.
3464 */
3465static void MD5Init(MD5Context *ctx){
3466 ctx->isInit = 1;
3467 ctx->buf[0] = 0x67452301;
3468 ctx->buf[1] = 0xefcdab89;
3469 ctx->buf[2] = 0x98badcfe;
3470 ctx->buf[3] = 0x10325476;
3471 ctx->bits[0] = 0;
3472 ctx->bits[1] = 0;
3473}
3474
3475/*
3476 * Update context to reflect the concatenation of another buffer full
3477 * of bytes.
3478 */
3479static
3480void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3481 uint32 t;
3482
3483 /* Update bitcount */
3484
3485 t = ctx->bits[0];
3486 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3487 ctx->bits[1]++; /* Carry from low to high */
3488 ctx->bits[1] += len >> 29;
3489
3490 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3491
3492 /* Handle any leading odd-sized chunks */
3493
3494 if ( t ) {
3495 unsigned char *p = (unsigned char *)ctx->in + t;
3496
3497 t = 64-t;
3498 if (len < t) {
3499 memcpy(p, buf, len);
3500 return;
3501 }
3502 memcpy(p, buf, t);
3503 byteReverse(ctx->in, 16);
3504 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3505 buf += t;
3506 len -= t;
3507 }
3508
3509 /* Process data in 64-byte chunks */
3510
3511 while (len >= 64) {
3512 memcpy(ctx->in, buf, 64);
3513 byteReverse(ctx->in, 16);
3514 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3515 buf += 64;
3516 len -= 64;
3517 }
3518
3519 /* Handle any remaining bytes of data. */
3520
3521 memcpy(ctx->in, buf, len);
3522}
3523
3524/*
3525 * Final wrapup - pad to 64-byte boundary with the bit pattern
3526 * 1 0* (64-bit count of bits processed, MSB-first)
3527 */
3528static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3529 unsigned count;
3530 unsigned char *p;
3531
3532 /* Compute number of bytes mod 64 */
3533 count = (ctx->bits[0] >> 3) & 0x3F;
3534
3535 /* Set the first char of padding to 0x80. This is safe since there is
3536 always at least one byte free */
3537 p = ctx->in + count;
3538 *p++ = 0x80;
3539
3540 /* Bytes of padding needed to make 64 bytes */
3541 count = 64 - 1 - count;
3542
3543 /* Pad out to 56 mod 64 */
3544 if (count < 8) {
3545 /* Two lots of padding: Pad the first block to 64 bytes */
3546 memset(p, 0, count);
3547 byteReverse(ctx->in, 16);
3548 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3549
3550 /* Now fill the next block with 56 bytes */
3551 memset(ctx->in, 0, 56);
3552 } else {
3553 /* Pad block to 56 bytes */
3554 memset(p, 0, count-8);
3555 }
3556 byteReverse(ctx->in, 14);
3557
3558 /* Append length in bits and transform */
drha47941f2013-12-20 18:57:44 +00003559 memcpy(ctx->in + 14*4, ctx->bits, 8);
drh57a02272009-10-22 20:52:05 +00003560
3561 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3562 byteReverse((unsigned char *)ctx->buf, 4);
3563 memcpy(digest, ctx->buf, 16);
drh57a02272009-10-22 20:52:05 +00003564}
3565
3566/*
3567** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3568*/
3569static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3570 static char const zEncode[] = "0123456789abcdef";
3571 int i, j;
3572
3573 for(j=i=0; i<16; i++){
3574 int a = digest[i];
3575 zBuf[j++] = zEncode[(a>>4)&0xf];
3576 zBuf[j++] = zEncode[a & 0xf];
3577 }
3578 zBuf[j] = 0;
3579}
3580
3581
3582/*
3583** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3584** each representing 16 bits of the digest and separated from each
3585** other by a "-" character.
3586*/
3587static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3588 int i, j;
3589 unsigned int x;
3590 for(i=j=0; i<16; i+=2){
3591 x = digest[i]*256 + digest[i+1];
3592 if( i>0 ) zDigest[j++] = '-';
drh05f6c672015-02-26 16:32:33 +00003593 sqlite3_snprintf(50-j, &zDigest[j], "%05u", x);
drh57a02272009-10-22 20:52:05 +00003594 j += 5;
3595 }
3596 zDigest[j] = 0;
3597}
3598
3599/*
3600** A TCL command for md5. The argument is the text to be hashed. The
3601** Result is the hash in base64.
3602*/
3603static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3604 MD5Context ctx;
3605 unsigned char digest[16];
3606 char zBuf[50];
3607 void (*converter)(unsigned char*, char*);
3608
3609 if( argc!=2 ){
3610 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
drha198f2b2014-02-07 19:26:13 +00003611 " TEXT\"", (char*)0);
drh57a02272009-10-22 20:52:05 +00003612 return TCL_ERROR;
3613 }
3614 MD5Init(&ctx);
3615 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3616 MD5Final(digest, &ctx);
3617 converter = (void(*)(unsigned char*,char*))cd;
3618 converter(digest, zBuf);
3619 Tcl_AppendResult(interp, zBuf, (char*)0);
3620 return TCL_OK;
3621}
3622
3623/*
3624** A TCL command to take the md5 hash of a file. The argument is the
3625** name of the file.
3626*/
3627static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3628 FILE *in;
3629 MD5Context ctx;
3630 void (*converter)(unsigned char*, char*);
3631 unsigned char digest[16];
3632 char zBuf[10240];
3633
3634 if( argc!=2 ){
3635 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
drha198f2b2014-02-07 19:26:13 +00003636 " FILENAME\"", (char*)0);
drh57a02272009-10-22 20:52:05 +00003637 return TCL_ERROR;
3638 }
3639 in = fopen(argv[1],"rb");
3640 if( in==0 ){
3641 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
drha198f2b2014-02-07 19:26:13 +00003642 "\" for reading", (char*)0);
drh57a02272009-10-22 20:52:05 +00003643 return TCL_ERROR;
3644 }
3645 MD5Init(&ctx);
3646 for(;;){
3647 int n;
drh83cc1392012-04-19 18:04:28 +00003648 n = (int)fread(zBuf, 1, sizeof(zBuf), in);
drh57a02272009-10-22 20:52:05 +00003649 if( n<=0 ) break;
3650 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3651 }
3652 fclose(in);
3653 MD5Final(digest, &ctx);
3654 converter = (void(*)(unsigned char*,char*))cd;
3655 converter(digest, zBuf);
3656 Tcl_AppendResult(interp, zBuf, (char*)0);
3657 return TCL_OK;
3658}
3659
3660/*
3661** Register the four new TCL commands for generating MD5 checksums
3662** with the TCL interpreter.
3663*/
3664int Md5_Init(Tcl_Interp *interp){
3665 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3666 MD5DigestToBase16, 0);
3667 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3668 MD5DigestToBase10x8, 0);
3669 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3670 MD5DigestToBase16, 0);
3671 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3672 MD5DigestToBase10x8, 0);
3673 return TCL_OK;
3674}
3675#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3676
3677#if defined(SQLITE_TEST)
3678/*
3679** During testing, the special md5sum() aggregate function is available.
3680** inside SQLite. The following routines implement that function.
3681*/
3682static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3683 MD5Context *p;
3684 int i;
3685 if( argc<1 ) return;
3686 p = sqlite3_aggregate_context(context, sizeof(*p));
3687 if( p==0 ) return;
3688 if( !p->isInit ){
3689 MD5Init(p);
3690 }
3691 for(i=0; i<argc; i++){
3692 const char *zData = (char*)sqlite3_value_text(argv[i]);
3693 if( zData ){
drh83cc1392012-04-19 18:04:28 +00003694 MD5Update(p, (unsigned char*)zData, (int)strlen(zData));
drh57a02272009-10-22 20:52:05 +00003695 }
3696 }
3697}
3698static void md5finalize(sqlite3_context *context){
3699 MD5Context *p;
3700 unsigned char digest[16];
3701 char zBuf[33];
3702 p = sqlite3_aggregate_context(context, sizeof(*p));
3703 MD5Final(digest,p);
3704 MD5DigestToBase16(digest, zBuf);
3705 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3706}
3707int Md5_Register(sqlite3 *db){
3708 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
3709 md5step, md5finalize);
3710 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3711 return rc;
3712}
3713#endif /* defined(SQLITE_TEST) */
3714
3715
drh348784e2000-05-29 20:41:49 +00003716/*
drh3e27c022004-07-23 00:01:38 +00003717** If the macro TCLSH is one, then put in code this for the
3718** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003719** standard input, or if a file is named on the command line
3720** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003721*/
drh3e27c022004-07-23 00:01:38 +00003722#if TCLSH==1
dan0ae479d2011-09-21 16:43:07 +00003723static const char *tclsh_main_loop(void){
3724 static const char zMainloop[] =
3725 "set line {}\n"
3726 "while {![eof stdin]} {\n"
3727 "if {$line!=\"\"} {\n"
3728 "puts -nonewline \"> \"\n"
3729 "} else {\n"
3730 "puts -nonewline \"% \"\n"
drh348784e2000-05-29 20:41:49 +00003731 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003732 "flush stdout\n"
3733 "append line [gets stdin]\n"
3734 "if {[info complete $line]} {\n"
3735 "if {[catch {uplevel #0 $line} result]} {\n"
3736 "puts stderr \"Error: $result\"\n"
3737 "} elseif {$result!=\"\"} {\n"
3738 "puts $result\n"
3739 "}\n"
3740 "set line {}\n"
3741 "} else {\n"
3742 "append line \\n\n"
3743 "}\n"
drh348784e2000-05-29 20:41:49 +00003744 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003745 ;
3746 return zMainloop;
3747}
drh3e27c022004-07-23 00:01:38 +00003748#endif
drh3a0f13f2010-07-12 16:47:48 +00003749#if TCLSH==2
dan0ae479d2011-09-21 16:43:07 +00003750static const char *tclsh_main_loop(void);
drh3a0f13f2010-07-12 16:47:48 +00003751#endif
drh3e27c022004-07-23 00:01:38 +00003752
danc1a60c52010-06-07 14:28:16 +00003753#ifdef SQLITE_TEST
3754static void init_all(Tcl_Interp *);
3755static int init_all_cmd(
3756 ClientData cd,
3757 Tcl_Interp *interp,
3758 int objc,
3759 Tcl_Obj *CONST objv[]
3760){
danielk19770a549072009-02-17 16:29:10 +00003761
danc1a60c52010-06-07 14:28:16 +00003762 Tcl_Interp *slave;
3763 if( objc!=2 ){
3764 Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3765 return TCL_ERROR;
3766 }
3767
3768 slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3769 if( !slave ){
3770 return TCL_ERROR;
3771 }
3772
3773 init_all(slave);
3774 return TCL_OK;
3775}
danc431fd52011-06-27 16:55:50 +00003776
3777/*
3778** Tclcmd: db_use_legacy_prepare DB BOOLEAN
3779**
3780** The first argument to this command must be a database command created by
3781** [sqlite3]. If the second argument is true, then the handle is configured
3782** to use the sqlite3_prepare_v2() function to prepare statements. If it
3783** is false, sqlite3_prepare().
3784*/
3785static int db_use_legacy_prepare_cmd(
3786 ClientData cd,
3787 Tcl_Interp *interp,
3788 int objc,
3789 Tcl_Obj *CONST objv[]
3790){
3791 Tcl_CmdInfo cmdInfo;
3792 SqliteDb *pDb;
3793 int bPrepare;
3794
3795 if( objc!=3 ){
3796 Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
3797 return TCL_ERROR;
3798 }
3799
3800 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3801 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3802 return TCL_ERROR;
3803 }
3804 pDb = (SqliteDb*)cmdInfo.objClientData;
3805 if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
3806 return TCL_ERROR;
3807 }
3808
3809 pDb->bLegacyPrepare = bPrepare;
3810
3811 Tcl_ResetResult(interp);
3812 return TCL_OK;
3813}
dan04489b62014-10-31 20:11:32 +00003814
3815/*
3816** Tclcmd: db_last_stmt_ptr DB
3817**
3818** If the statement cache associated with database DB is not empty,
3819** return the text representation of the most recently used statement
3820** handle.
3821*/
3822static int db_last_stmt_ptr(
3823 ClientData cd,
3824 Tcl_Interp *interp,
3825 int objc,
3826 Tcl_Obj *CONST objv[]
3827){
3828 extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
3829 Tcl_CmdInfo cmdInfo;
3830 SqliteDb *pDb;
3831 sqlite3_stmt *pStmt = 0;
3832 char zBuf[100];
3833
3834 if( objc!=2 ){
3835 Tcl_WrongNumArgs(interp, 1, objv, "DB");
3836 return TCL_ERROR;
3837 }
3838
3839 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3840 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3841 return TCL_ERROR;
3842 }
3843 pDb = (SqliteDb*)cmdInfo.objClientData;
3844
3845 if( pDb->stmtList ) pStmt = pDb->stmtList->pStmt;
3846 if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ){
3847 return TCL_ERROR;
3848 }
3849 Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
3850
3851 return TCL_OK;
3852}
drh1a4a6802015-05-04 18:31:09 +00003853#endif /* SQLITE_TEST */
3854
danc1a60c52010-06-07 14:28:16 +00003855/*
3856** Configure the interpreter passed as the first argument to have access
3857** to the commands and linked variables that make up:
3858**
3859** * the [sqlite3] extension itself,
3860**
3861** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
3862**
3863** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
3864** test suite.
3865*/
3866static void init_all(Tcl_Interp *interp){
drh38f82712004-06-18 17:10:16 +00003867 Sqlite3_Init(interp);
danc1a60c52010-06-07 14:28:16 +00003868
drh57a02272009-10-22 20:52:05 +00003869#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3870 Md5_Init(interp);
3871#endif
danc1a60c52010-06-07 14:28:16 +00003872
drhd9b02572001-04-15 00:37:09 +00003873#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00003874 {
drh2f999a62007-08-15 19:16:43 +00003875 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00003876 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00003877 extern int Sqlitetest2_Init(Tcl_Interp*);
3878 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00003879 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00003880 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00003881 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00003882 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00003883 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00003884 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00003885 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00003886 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
danb391b942014-11-07 14:41:11 +00003887 extern int Sqlitetest_blob_Init(Tcl_Interp*);
dan0a7a9152010-04-07 07:57:38 +00003888 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
drh984bfaa2008-03-19 16:08:53 +00003889 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00003890 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00003891 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003892 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00003893 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003894 extern int Sqlitetestschema_Init(Tcl_Interp*);
3895 extern int Sqlitetestsse_Init(Tcl_Interp*);
3896 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
dan9f5ff372013-01-11 09:58:54 +00003897 extern int Sqlitetestfs_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00003898 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00003899 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00003900 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00003901 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh522efc62009-11-10 17:24:37 +00003902 extern int Sqlitetestintarray_Init(Tcl_Interp*);
danc7991bd2010-05-05 19:04:59 +00003903 extern int Sqlitetestvfs_Init(Tcl_Interp *);
dan9508daa2010-08-28 18:58:00 +00003904 extern int Sqlitetestrtree_Init(Tcl_Interp*);
dan8cf35eb2010-09-01 11:40:05 +00003905 extern int Sqlitequota_Init(Tcl_Interp*);
shaneh8a922f72010-11-04 20:50:27 +00003906 extern int Sqlitemultiplex_Init(Tcl_Interp*);
dane336b002010-11-19 18:20:09 +00003907 extern int SqliteSuperlock_Init(Tcl_Interp*);
dan213ca0a2011-03-28 19:10:06 +00003908 extern int SqlitetestSyscall_Init(Tcl_Interp*);
drh9b1c62d2011-03-30 21:04:43 +00003909#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
dan4fccf432011-03-08 19:22:50 +00003910 extern int TestSession_Init(Tcl_Interp*);
3911#endif
danb0083752014-09-02 19:59:40 +00003912 extern int SqliteOta_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00003913
dan6764a702011-06-20 11:15:06 +00003914#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00003915 extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
3916#endif
3917
danb29010c2010-12-29 18:24:38 +00003918#ifdef SQLITE_ENABLE_ZIPVFS
3919 extern int Zipvfs_Init(Tcl_Interp*);
3920 Zipvfs_Init(interp);
3921#endif
3922
drh2f999a62007-08-15 19:16:43 +00003923 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00003924 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00003925 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00003926 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00003927 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00003928 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00003929 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00003930 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00003931 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00003932 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00003933 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00003934 Sqlitetest_autoext_Init(interp);
danb391b942014-11-07 14:41:11 +00003935 Sqlitetest_blob_Init(interp);
dan0a7a9152010-04-07 07:57:38 +00003936 Sqlitetest_demovfs_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00003937 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00003938 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00003939 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003940 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00003941 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003942 Sqlitetestschema_Init(interp);
3943 Sqlitetesttclvar_Init(interp);
dan9f5ff372013-01-11 09:58:54 +00003944 Sqlitetestfs_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00003945 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003946 SqlitetestOnefile_Init(interp);
danielk19775d1f5aa2008-04-10 14:51:00 +00003947 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00003948 Sqlitetestbackup_Init(interp);
drh522efc62009-11-10 17:24:37 +00003949 Sqlitetestintarray_Init(interp);
danc7991bd2010-05-05 19:04:59 +00003950 Sqlitetestvfs_Init(interp);
dan9508daa2010-08-28 18:58:00 +00003951 Sqlitetestrtree_Init(interp);
dan8cf35eb2010-09-01 11:40:05 +00003952 Sqlitequota_Init(interp);
shaneh8a922f72010-11-04 20:50:27 +00003953 Sqlitemultiplex_Init(interp);
dane336b002010-11-19 18:20:09 +00003954 SqliteSuperlock_Init(interp);
dan213ca0a2011-03-28 19:10:06 +00003955 SqlitetestSyscall_Init(interp);
drh9b1c62d2011-03-30 21:04:43 +00003956#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
dan4fccf432011-03-08 19:22:50 +00003957 TestSession_Init(interp);
3958#endif
danb0083752014-09-02 19:59:40 +00003959 SqliteOta_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003960
dan6764a702011-06-20 11:15:06 +00003961#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00003962 Sqlitetestfts3_Init(interp);
3963#endif
drh2e66f0b2005-04-28 17:18:48 +00003964
danc431fd52011-06-27 16:55:50 +00003965 Tcl_CreateObjCommand(
3966 interp, "load_testfixture_extensions", init_all_cmd, 0, 0
3967 );
3968 Tcl_CreateObjCommand(
3969 interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
3970 );
dan04489b62014-10-31 20:11:32 +00003971 Tcl_CreateObjCommand(
3972 interp, "db_last_stmt_ptr", db_last_stmt_ptr, 0, 0
3973 );
danc1a60c52010-06-07 14:28:16 +00003974
drh3e27c022004-07-23 00:01:38 +00003975#ifdef SQLITE_SSE
drh348784e2000-05-29 20:41:49 +00003976 Sqlitetestsse_Init(interp);
3977#endif
3978 }
drh61212b62004-12-02 20:17:00 +00003979#endif
danc1a60c52010-06-07 14:28:16 +00003980}
3981
drhdb6bafa2015-01-09 21:54:58 +00003982/* Needed for the setrlimit() system call on unix */
3983#if defined(unix)
3984#include <sys/resource.h>
3985#endif
3986
danc1a60c52010-06-07 14:28:16 +00003987#define TCLSH_MAIN main /* Needed to fake out mktclapp */
3988int TCLSH_MAIN(int argc, char **argv){
3989 Tcl_Interp *interp;
mistachkin1f28e072013-08-15 08:06:15 +00003990
3991#if !defined(_WIN32_WCE)
3992 if( getenv("BREAK") ){
3993 fprintf(stderr,
3994 "attach debugger to process %d and press any key to continue.\n",
3995 GETPID());
3996 fgetc(stdin);
3997 }
3998#endif
3999
drhdb6bafa2015-01-09 21:54:58 +00004000 /* Since the primary use case for this binary is testing of SQLite,
4001 ** be sure to generate core files if we crash */
4002#if defined(SQLITE_TEST) && defined(unix)
4003 { struct rlimit x;
4004 getrlimit(RLIMIT_CORE, &x);
4005 x.rlim_cur = x.rlim_max;
4006 setrlimit(RLIMIT_CORE, &x);
4007 }
4008#endif /* SQLITE_TEST && unix */
4009
4010
danc1a60c52010-06-07 14:28:16 +00004011 /* Call sqlite3_shutdown() once before doing anything else. This is to
4012 ** test that sqlite3_shutdown() can be safely called by a process before
4013 ** sqlite3_initialize() is. */
4014 sqlite3_shutdown();
4015
dan0ae479d2011-09-21 16:43:07 +00004016 Tcl_FindExecutable(argv[0]);
mistachkin2953ba92014-02-14 00:25:03 +00004017 Tcl_SetSystemEncoding(NULL, "utf-8");
dan0ae479d2011-09-21 16:43:07 +00004018 interp = Tcl_CreateInterp();
4019
drh3a0f13f2010-07-12 16:47:48 +00004020#if TCLSH==2
4021 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
4022#endif
danc1a60c52010-06-07 14:28:16 +00004023
danc1a60c52010-06-07 14:28:16 +00004024 init_all(interp);
drhc7285972009-11-10 01:13:25 +00004025 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00004026 int i;
shessad42c3a2006-08-22 23:53:46 +00004027 char zArgc[32];
4028 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
4029 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00004030 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
4031 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
4032 for(i=3-TCLSH; i<argc; i++){
4033 Tcl_SetVar(interp, "argv", argv[i],
4034 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
4035 }
drh3a0f13f2010-07-12 16:47:48 +00004036 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00004037 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00004038 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00004039 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00004040 return 1;
4041 }
drh3e27c022004-07-23 00:01:38 +00004042 }
drh3a0f13f2010-07-12 16:47:48 +00004043 if( TCLSH==2 || argc<=1 ){
dan0ae479d2011-09-21 16:43:07 +00004044 Tcl_GlobalEval(interp, tclsh_main_loop());
drh348784e2000-05-29 20:41:49 +00004045 }
4046 return 0;
4047}
4048#endif /* TCLSH */