blob: 5ad198fe9835d40bc47c93543281bd123a7ea4c3 [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*/
drh17a68932001-01-31 13:28:08 +000028#include "tcl.h"
danielk1977b4e9af92007-05-01 17:49:49 +000029#include <errno.h>
drhbd08af42007-04-05 21:58:33 +000030
31/*
32** Some additional include files are needed if this file is not
33** appended to the amalgamation.
34*/
35#ifndef SQLITE_AMALGAMATION
drh65e8c822009-12-01 13:57:48 +000036# include "sqlite3.h"
drhbd08af42007-04-05 21:58:33 +000037# include <stdlib.h>
38# include <string.h>
39# include <assert.h>
drh65e8c822009-12-01 13:57:48 +000040 typedef unsigned char u8;
drhbd08af42007-04-05 21:58:33 +000041#endif
drheb206382009-10-24 15:51:33 +000042#include <ctype.h>
drh75897232000-05-29 14:26:00 +000043
drhad6e1372006-07-10 21:15:51 +000044/*
45 * Windows needs to know which symbols to export. Unix does not.
46 * BUILD_sqlite should be undefined for Unix.
47 */
48#ifdef BUILD_sqlite
49#undef TCL_STORAGE_CLASS
50#define TCL_STORAGE_CLASS DLLEXPORT
51#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000052
danielk1977a21c6b62005-01-24 10:25:59 +000053#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000054#define MAX_PREPARED_STMTS 100
55
drh75897232000-05-29 14:26:00 +000056/*
drh98808ba2001-10-18 12:34:46 +000057** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
58** have to do a translation when going between the two. Set the
59** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
60** this translation.
61*/
62#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
63# define UTF_TRANSLATION_NEEDED 1
64#endif
65
66/*
drhcabb0812002-09-14 13:47:32 +000067** New SQL functions can be created as TCL scripts. Each such function
68** is described by an instance of the following structure.
69*/
70typedef struct SqlFunc SqlFunc;
71struct SqlFunc {
72 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000073 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
74 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
75 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000076 SqlFunc *pNext; /* Next function on the list of them all */
77};
78
79/*
danielk19770202b292004-06-09 09:55:16 +000080** New collation sequences function can be created as TCL scripts. Each such
81** function is described by an instance of the following structure.
82*/
83typedef struct SqlCollate SqlCollate;
84struct SqlCollate {
85 Tcl_Interp *interp; /* The TCL interpret to execute the function */
86 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000087 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000088};
89
90/*
drhfb7e7652005-01-24 00:28:42 +000091** Prepared statements are cached for faster execution. Each prepared
92** statement is described by an instance of the following structure.
93*/
94typedef struct SqlPreparedStmt SqlPreparedStmt;
95struct SqlPreparedStmt {
96 SqlPreparedStmt *pNext; /* Next in linked list */
97 SqlPreparedStmt *pPrev; /* Previous on the list */
98 sqlite3_stmt *pStmt; /* The prepared statement */
99 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +0000100 const char *zSql; /* Text of the SQL statement */
dan4a4c11a2009-10-06 14:59:02 +0000101 int nParm; /* Size of apParm array */
102 Tcl_Obj **apParm; /* Array of referenced object pointers */
drhfb7e7652005-01-24 00:28:42 +0000103};
104
danielk1977d04417962007-05-02 13:16:30 +0000105typedef struct IncrblobChannel IncrblobChannel;
106
drhfb7e7652005-01-24 00:28:42 +0000107/*
drhbec3f402000-08-04 13:49:02 +0000108** There is one instance of this structure for each SQLite database
109** that has been opened by the SQLite TCL interface.
110*/
111typedef struct SqliteDb SqliteDb;
112struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000113 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000114 Tcl_Interp *interp; /* The interpreter used for this database */
115 char *zBusy; /* The busy callback routine */
116 char *zCommit; /* The commit hook callback routine */
117 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +0000118 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000119 char *zProgress; /* The progress callback routine */
120 char *zAuth; /* The authorization callback routine */
drh1f1549f2008-08-26 21:33:34 +0000121 int disableAuth; /* Disable the authorizer if it exists */
drhd1e47332005-06-26 17:55:33 +0000122 char *zNull; /* Text to substitute for an SQL NULL value */
123 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000124 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000125 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000126 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000127 SqlCollate *pCollate; /* List of SQL collation functions */
128 int rc; /* Return code of most recent sqlite3_exec() */
129 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000130 SqlPreparedStmt *stmtList; /* List of prepared statements*/
131 SqlPreparedStmt *stmtLast; /* Last statement in the list */
132 int maxStmt; /* The next maximum number of stmtList */
133 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000134 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh3c379b02010-04-07 19:31:59 +0000135 int nStep, nSort, nIndex; /* Statistics for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000136 int nTransaction; /* Number of nested [transaction] methods */
drh98808ba2001-10-18 12:34:46 +0000137};
drh297ecf12001-04-05 15:57:13 +0000138
danielk1977b4e9af92007-05-01 17:49:49 +0000139struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000140 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000141 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000142 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000143 Tcl_Channel channel; /* Channel identifier */
144 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
145 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000146};
147
drhea678832008-12-10 19:26:22 +0000148/*
149** Compute a string length that is limited to what can be stored in
150** lower 30 bits of a 32-bit signed integer.
151*/
drh4f21c4a2008-12-10 22:15:00 +0000152static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000153 const char *z2 = z;
154 while( *z2 ){ z2++; }
155 return 0x3fffffff & (int)(z2 - z);
156}
drhea678832008-12-10 19:26:22 +0000157
158
danielk197732a0d8b2007-05-04 19:03:02 +0000159#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000160/*
danielk1977d04417962007-05-02 13:16:30 +0000161** Close all incrblob channels opened using database connection pDb.
162** This is called when shutting down the database connection.
163*/
164static void closeIncrblobChannels(SqliteDb *pDb){
165 IncrblobChannel *p;
166 IncrblobChannel *pNext;
167
168 for(p=pDb->pIncrblob; p; p=pNext){
169 pNext = p->pNext;
170
171 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
172 ** which deletes the IncrblobChannel structure at *p. So do not
173 ** call Tcl_Free() here.
174 */
175 Tcl_UnregisterChannel(pDb->interp, p->channel);
176 }
177}
178
179/*
danielk1977b4e9af92007-05-01 17:49:49 +0000180** Close an incremental blob channel.
181*/
182static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
183 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000184 int rc = sqlite3_blob_close(p->pBlob);
185 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000186
187 /* Remove the channel from the SqliteDb.pIncrblob list. */
188 if( p->pNext ){
189 p->pNext->pPrev = p->pPrev;
190 }
191 if( p->pPrev ){
192 p->pPrev->pNext = p->pNext;
193 }
194 if( p->pDb->pIncrblob==p ){
195 p->pDb->pIncrblob = p->pNext;
196 }
197
danielk197792d4d7a2007-05-04 12:05:56 +0000198 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000199 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000200
201 if( rc!=SQLITE_OK ){
202 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
203 return TCL_ERROR;
204 }
danielk1977b4e9af92007-05-01 17:49:49 +0000205 return TCL_OK;
206}
207
208/*
209** Read data from an incremental blob channel.
210*/
211static int incrblobInput(
212 ClientData instanceData,
213 char *buf,
214 int bufSize,
215 int *errorCodePtr
216){
217 IncrblobChannel *p = (IncrblobChannel *)instanceData;
218 int nRead = bufSize; /* Number of bytes to read */
219 int nBlob; /* Total size of the blob */
220 int rc; /* sqlite error code */
221
222 nBlob = sqlite3_blob_bytes(p->pBlob);
223 if( (p->iSeek+nRead)>nBlob ){
224 nRead = nBlob-p->iSeek;
225 }
226 if( nRead<=0 ){
227 return 0;
228 }
229
230 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
231 if( rc!=SQLITE_OK ){
232 *errorCodePtr = rc;
233 return -1;
234 }
235
236 p->iSeek += nRead;
237 return nRead;
238}
239
danielk1977d04417962007-05-02 13:16:30 +0000240/*
241** Write data to an incremental blob channel.
242*/
danielk1977b4e9af92007-05-01 17:49:49 +0000243static int incrblobOutput(
244 ClientData instanceData,
245 CONST char *buf,
246 int toWrite,
247 int *errorCodePtr
248){
249 IncrblobChannel *p = (IncrblobChannel *)instanceData;
250 int nWrite = toWrite; /* Number of bytes to write */
251 int nBlob; /* Total size of the blob */
252 int rc; /* sqlite error code */
253
254 nBlob = sqlite3_blob_bytes(p->pBlob);
255 if( (p->iSeek+nWrite)>nBlob ){
256 *errorCodePtr = EINVAL;
257 return -1;
258 }
259 if( nWrite<=0 ){
260 return 0;
261 }
262
263 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
264 if( rc!=SQLITE_OK ){
265 *errorCodePtr = EIO;
266 return -1;
267 }
268
269 p->iSeek += nWrite;
270 return nWrite;
271}
272
273/*
274** Seek an incremental blob channel.
275*/
276static int incrblobSeek(
277 ClientData instanceData,
278 long offset,
279 int seekMode,
280 int *errorCodePtr
281){
282 IncrblobChannel *p = (IncrblobChannel *)instanceData;
283
284 switch( seekMode ){
285 case SEEK_SET:
286 p->iSeek = offset;
287 break;
288 case SEEK_CUR:
289 p->iSeek += offset;
290 break;
291 case SEEK_END:
292 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
293 break;
294
295 default: assert(!"Bad seekMode");
296 }
297
298 return p->iSeek;
299}
300
301
302static void incrblobWatch(ClientData instanceData, int mode){
303 /* NO-OP */
304}
305static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
306 return TCL_ERROR;
307}
308
309static Tcl_ChannelType IncrblobChannelType = {
310 "incrblob", /* typeName */
311 TCL_CHANNEL_VERSION_2, /* version */
312 incrblobClose, /* closeProc */
313 incrblobInput, /* inputProc */
314 incrblobOutput, /* outputProc */
315 incrblobSeek, /* seekProc */
316 0, /* setOptionProc */
317 0, /* getOptionProc */
318 incrblobWatch, /* watchProc (this is a no-op) */
319 incrblobHandle, /* getHandleProc (always returns error) */
320 0, /* close2Proc */
321 0, /* blockModeProc */
322 0, /* flushProc */
323 0, /* handlerProc */
324 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000325};
326
327/*
328** Create a new incrblob channel.
329*/
330static int createIncrblobChannel(
331 Tcl_Interp *interp,
332 SqliteDb *pDb,
333 const char *zDb,
334 const char *zTable,
335 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000336 sqlite_int64 iRow,
337 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000338){
339 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000340 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000341 sqlite3_blob *pBlob;
342 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000343 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000344
345 /* This variable is used to name the channels: "incrblob_[incr count]" */
346 static int count = 0;
347 char zChannel[64];
348
danielk19778cbadb02007-05-03 16:31:26 +0000349 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000350 if( rc!=SQLITE_OK ){
351 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
352 return TCL_ERROR;
353 }
354
355 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
356 p->iSeek = 0;
357 p->pBlob = pBlob;
358
drh5bb3eb92007-05-04 13:15:55 +0000359 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000360 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
361 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000362
danielk1977d04417962007-05-02 13:16:30 +0000363 /* Link the new channel into the SqliteDb.pIncrblob list. */
364 p->pNext = pDb->pIncrblob;
365 p->pPrev = 0;
366 if( p->pNext ){
367 p->pNext->pPrev = p;
368 }
369 pDb->pIncrblob = p;
370 p->pDb = pDb;
371
372 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000373 return TCL_OK;
374}
danielk197732a0d8b2007-05-04 19:03:02 +0000375#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
376 #define closeIncrblobChannels(pDb)
377#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000378
drh6d313162000-09-21 13:01:35 +0000379/*
drhd1e47332005-06-26 17:55:33 +0000380** Look at the script prefix in pCmd. We will be executing this script
381** after first appending one or more arguments. This routine analyzes
382** the script to see if it is safe to use Tcl_EvalObjv() on the script
383** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
384** faster.
385**
386** Scripts that are safe to use with Tcl_EvalObjv() consists of a
387** command name followed by zero or more arguments with no [...] or $
388** or {...} or ; to be seen anywhere. Most callback scripts consist
389** of just a single procedure name and they meet this requirement.
390*/
391static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
392 /* We could try to do something with Tcl_Parse(). But we will instead
393 ** just do a search for forbidden characters. If any of the forbidden
394 ** characters appear in pCmd, we will report the string as unsafe.
395 */
396 const char *z;
397 int n;
398 z = Tcl_GetStringFromObj(pCmd, &n);
399 while( n-- > 0 ){
400 int c = *(z++);
401 if( c=='$' || c=='[' || c==';' ) return 0;
402 }
403 return 1;
404}
405
406/*
407** Find an SqlFunc structure with the given name. Or create a new
408** one if an existing one cannot be found. Return a pointer to the
409** structure.
410*/
411static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
412 SqlFunc *p, *pNew;
413 int i;
drh4f21c4a2008-12-10 22:15:00 +0000414 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen30(zName) + 1 );
drhd1e47332005-06-26 17:55:33 +0000415 pNew->zName = (char*)&pNew[1];
416 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
417 pNew->zName[i] = 0;
418 for(p=pDb->pFunc; p; p=p->pNext){
419 if( strcmp(p->zName, pNew->zName)==0 ){
420 Tcl_Free((char*)pNew);
421 return p;
422 }
423 }
424 pNew->interp = pDb->interp;
425 pNew->pScript = 0;
426 pNew->pNext = pDb->pFunc;
427 pDb->pFunc = pNew;
428 return pNew;
429}
430
431/*
drhfb7e7652005-01-24 00:28:42 +0000432** Finalize and free a list of prepared statements
433*/
434static void flushStmtCache( SqliteDb *pDb ){
435 SqlPreparedStmt *pPreStmt;
436
437 while( pDb->stmtList ){
438 sqlite3_finalize( pDb->stmtList->pStmt );
439 pPreStmt = pDb->stmtList;
440 pDb->stmtList = pDb->stmtList->pNext;
441 Tcl_Free( (char*)pPreStmt );
442 }
443 pDb->nStmt = 0;
444 pDb->stmtLast = 0;
445}
446
447/*
drh895d7472004-08-20 16:02:39 +0000448** TCL calls this procedure when an sqlite3 database command is
449** deleted.
drh75897232000-05-29 14:26:00 +0000450*/
451static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000452 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000453 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000454 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000455 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000456 while( pDb->pFunc ){
457 SqlFunc *pFunc = pDb->pFunc;
458 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000459 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000460 Tcl_Free((char*)pFunc);
461 }
danielk19770202b292004-06-09 09:55:16 +0000462 while( pDb->pCollate ){
463 SqlCollate *pCollate = pDb->pCollate;
464 pDb->pCollate = pCollate->pNext;
465 Tcl_Free((char*)pCollate);
466 }
drhbec3f402000-08-04 13:49:02 +0000467 if( pDb->zBusy ){
468 Tcl_Free(pDb->zBusy);
469 }
drhb5a20d32003-04-23 12:25:23 +0000470 if( pDb->zTrace ){
471 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000472 }
drh19e2d372005-08-29 23:00:03 +0000473 if( pDb->zProfile ){
474 Tcl_Free(pDb->zProfile);
475 }
drhe22a3342003-04-22 20:30:37 +0000476 if( pDb->zAuth ){
477 Tcl_Free(pDb->zAuth);
478 }
danielk197755c45f22005-04-03 23:54:43 +0000479 if( pDb->zNull ){
480 Tcl_Free(pDb->zNull);
481 }
danielk197794eb6a12005-12-15 15:22:08 +0000482 if( pDb->pUpdateHook ){
483 Tcl_DecrRefCount(pDb->pUpdateHook);
484 }
danielk197771fd80b2005-12-16 06:54:01 +0000485 if( pDb->pRollbackHook ){
486 Tcl_DecrRefCount(pDb->pRollbackHook);
487 }
danielk197794eb6a12005-12-15 15:22:08 +0000488 if( pDb->pCollateNeeded ){
489 Tcl_DecrRefCount(pDb->pCollateNeeded);
490 }
drhbec3f402000-08-04 13:49:02 +0000491 Tcl_Free((char*)pDb);
492}
493
494/*
495** This routine is called when a database file is locked while trying
496** to execute SQL.
497*/
danielk19772a764eb2004-06-12 01:43:26 +0000498static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000499 SqliteDb *pDb = (SqliteDb*)cd;
500 int rc;
501 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000502
drh5bb3eb92007-05-04 13:15:55 +0000503 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000504 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000505 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
506 return 0;
507 }
508 return 1;
drh75897232000-05-29 14:26:00 +0000509}
510
drh26e4a8b2008-05-01 17:16:52 +0000511#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000512/*
danielk1977348bb5d2003-10-18 09:37:26 +0000513** This routine is invoked as the 'progress callback' for the database.
514*/
515static int DbProgressHandler(void *cd){
516 SqliteDb *pDb = (SqliteDb*)cd;
517 int rc;
518
519 assert( pDb->zProgress );
520 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
521 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
522 return 1;
523 }
524 return 0;
525}
drh26e4a8b2008-05-01 17:16:52 +0000526#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000527
drhd1167392006-01-23 13:00:35 +0000528#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000529/*
drhb5a20d32003-04-23 12:25:23 +0000530** This routine is called by the SQLite trace handler whenever a new
531** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000532*/
drhb5a20d32003-04-23 12:25:23 +0000533static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000534 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000535 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000536
drhb5a20d32003-04-23 12:25:23 +0000537 Tcl_DStringInit(&str);
538 Tcl_DStringAppend(&str, pDb->zTrace, -1);
539 Tcl_DStringAppendElement(&str, zSql);
540 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
541 Tcl_DStringFree(&str);
542 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000543}
drhd1167392006-01-23 13:00:35 +0000544#endif
drh0d1a6432003-04-03 15:46:04 +0000545
drhd1167392006-01-23 13:00:35 +0000546#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000547/*
drh19e2d372005-08-29 23:00:03 +0000548** This routine is called by the SQLite profile handler after a statement
549** SQL has executed. The TCL script in pDb->zProfile is evaluated.
550*/
551static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
552 SqliteDb *pDb = (SqliteDb*)cd;
553 Tcl_DString str;
554 char zTm[100];
555
556 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
557 Tcl_DStringInit(&str);
558 Tcl_DStringAppend(&str, pDb->zProfile, -1);
559 Tcl_DStringAppendElement(&str, zSql);
560 Tcl_DStringAppendElement(&str, zTm);
561 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
562 Tcl_DStringFree(&str);
563 Tcl_ResetResult(pDb->interp);
564}
drhd1167392006-01-23 13:00:35 +0000565#endif
drh19e2d372005-08-29 23:00:03 +0000566
567/*
drhaa940ea2004-01-15 02:44:03 +0000568** This routine is called when a transaction is committed. The
569** TCL script in pDb->zCommit is executed. If it returns non-zero or
570** if it throws an exception, the transaction is rolled back instead
571** of being committed.
572*/
573static int DbCommitHandler(void *cd){
574 SqliteDb *pDb = (SqliteDb*)cd;
575 int rc;
576
577 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
578 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
579 return 1;
580 }
581 return 0;
582}
583
danielk197771fd80b2005-12-16 06:54:01 +0000584static void DbRollbackHandler(void *clientData){
585 SqliteDb *pDb = (SqliteDb*)clientData;
586 assert(pDb->pRollbackHook);
587 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
588 Tcl_BackgroundError(pDb->interp);
589 }
590}
591
drhbcf4f482009-03-27 12:44:35 +0000592#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000593static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
594 char zBuf[64];
595 sprintf(zBuf, "%d", iArg);
596 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
597 sprintf(zBuf, "%d", nArg);
598 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
599}
600#else
drhbcf4f482009-03-27 12:44:35 +0000601# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000602#endif
603
drh69910da2009-03-27 12:32:54 +0000604#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000605static void DbUnlockNotify(void **apArg, int nArg){
606 int i;
607 for(i=0; i<nArg; i++){
608 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
609 SqliteDb *pDb = (SqliteDb *)apArg[i];
610 setTestUnlockNotifyVars(pDb->interp, i, nArg);
611 assert( pDb->pUnlockNotify);
612 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
613 Tcl_DecrRefCount(pDb->pUnlockNotify);
614 pDb->pUnlockNotify = 0;
615 }
616}
drh69910da2009-03-27 12:32:54 +0000617#endif
danielk1977404ca072009-03-16 13:19:36 +0000618
danielk197794eb6a12005-12-15 15:22:08 +0000619static void DbUpdateHandler(
620 void *p,
621 int op,
622 const char *zDb,
623 const char *zTbl,
624 sqlite_int64 rowid
625){
626 SqliteDb *pDb = (SqliteDb *)p;
627 Tcl_Obj *pCmd;
628
629 assert( pDb->pUpdateHook );
630 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
631
632 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
633 Tcl_IncrRefCount(pCmd);
634 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
635 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
636 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
637 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
638 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
639 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
640}
641
danielk19777cedc8d2004-06-10 10:50:08 +0000642static void tclCollateNeeded(
643 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000644 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000645 int enc,
646 const char *zName
647){
648 SqliteDb *pDb = (SqliteDb *)pCtx;
649 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
650 Tcl_IncrRefCount(pScript);
651 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
652 Tcl_EvalObjEx(pDb->interp, pScript, 0);
653 Tcl_DecrRefCount(pScript);
654}
655
drhaa940ea2004-01-15 02:44:03 +0000656/*
danielk19770202b292004-06-09 09:55:16 +0000657** This routine is called to evaluate an SQL collation function implemented
658** using TCL script.
659*/
660static int tclSqlCollate(
661 void *pCtx,
662 int nA,
663 const void *zA,
664 int nB,
665 const void *zB
666){
667 SqlCollate *p = (SqlCollate *)pCtx;
668 Tcl_Obj *pCmd;
669
670 pCmd = Tcl_NewStringObj(p->zScript, -1);
671 Tcl_IncrRefCount(pCmd);
672 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
673 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000674 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000675 Tcl_DecrRefCount(pCmd);
676 return (atoi(Tcl_GetStringResult(p->interp)));
677}
678
679/*
drhcabb0812002-09-14 13:47:32 +0000680** This routine is called to evaluate an SQL function implemented
681** using TCL script.
682*/
drhfb7e7652005-01-24 00:28:42 +0000683static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000684 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000685 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000686 int i;
687 int rc;
688
drhd1e47332005-06-26 17:55:33 +0000689 if( argc==0 ){
690 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
691 ** script object directly. This allows the TCL compiler to generate
692 ** bytecode for the command on the first invocation and thus make
693 ** subsequent invocations much faster. */
694 pCmd = p->pScript;
695 Tcl_IncrRefCount(pCmd);
696 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
697 Tcl_DecrRefCount(pCmd);
698 }else{
699 /* If there are arguments to the function, make a shallow copy of the
700 ** script object, lappend the arguments, then evaluate the copy.
701 **
702 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
703 ** The new Tcl_Obj contains pointers to the original list elements.
704 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
705 ** of the list to tclCmdNameType, that alternate representation will
706 ** be preserved and reused on the next invocation.
707 */
708 Tcl_Obj **aArg;
709 int nArg;
710 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
711 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
712 return;
713 }
714 pCmd = Tcl_NewListObj(nArg, aArg);
715 Tcl_IncrRefCount(pCmd);
716 for(i=0; i<argc; i++){
717 sqlite3_value *pIn = argv[i];
718 Tcl_Obj *pVal;
719
720 /* Set pVal to contain the i'th column of this row. */
721 switch( sqlite3_value_type(pIn) ){
722 case SQLITE_BLOB: {
723 int bytes = sqlite3_value_bytes(pIn);
724 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
725 break;
726 }
727 case SQLITE_INTEGER: {
728 sqlite_int64 v = sqlite3_value_int64(pIn);
729 if( v>=-2147483647 && v<=2147483647 ){
730 pVal = Tcl_NewIntObj(v);
731 }else{
732 pVal = Tcl_NewWideIntObj(v);
733 }
734 break;
735 }
736 case SQLITE_FLOAT: {
737 double r = sqlite3_value_double(pIn);
738 pVal = Tcl_NewDoubleObj(r);
739 break;
740 }
741 case SQLITE_NULL: {
742 pVal = Tcl_NewStringObj("", 0);
743 break;
744 }
745 default: {
746 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000747 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000748 break;
749 }
750 }
751 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
752 if( rc ){
753 Tcl_DecrRefCount(pCmd);
754 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
755 return;
756 }
danielk197751ad0ec2004-05-24 12:39:02 +0000757 }
drhd1e47332005-06-26 17:55:33 +0000758 if( !p->useEvalObjv ){
759 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
760 ** is a list without a string representation. To prevent this from
761 ** happening, make sure pCmd has a valid string representation */
762 Tcl_GetString(pCmd);
763 }
764 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
765 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000766 }
danielk1977562e8d32005-05-20 09:40:55 +0000767
drhc7f269d2005-05-05 10:30:29 +0000768 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000769 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000770 }else{
drhc7f269d2005-05-05 10:30:29 +0000771 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
772 int n;
773 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000774 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000775 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000776 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000777 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000778 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000779 data = Tcl_GetByteArrayFromObj(pVar, &n);
780 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000781 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000782 Tcl_GetIntFromObj(0, pVar, &n);
783 sqlite3_result_int(context, n);
784 }else if( c=='d' && strcmp(zType,"double")==0 ){
785 double r;
786 Tcl_GetDoubleFromObj(0, pVar, &r);
787 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +0000788 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
789 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000790 Tcl_WideInt v;
791 Tcl_GetWideIntFromObj(0, pVar, &v);
792 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000793 }else{
danielk197700fd9572005-12-07 06:27:43 +0000794 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
795 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000796 }
drhcabb0812002-09-14 13:47:32 +0000797 }
798}
drh895d7472004-08-20 16:02:39 +0000799
drhe22a3342003-04-22 20:30:37 +0000800#ifndef SQLITE_OMIT_AUTHORIZATION
801/*
802** This is the authentication function. It appends the authentication
803** type code and the two arguments to zCmd[] then invokes the result
804** on the interpreter. The reply is examined to determine if the
805** authentication fails or succeeds.
806*/
807static int auth_callback(
808 void *pArg,
809 int code,
810 const char *zArg1,
811 const char *zArg2,
812 const char *zArg3,
813 const char *zArg4
814){
815 char *zCode;
816 Tcl_DString str;
817 int rc;
818 const char *zReply;
819 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +0000820 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +0000821
822 switch( code ){
823 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
824 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
825 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
826 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
827 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
828 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
829 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
830 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
831 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
832 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
833 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
834 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
835 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
836 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
837 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
838 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
839 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
840 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
841 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
842 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
843 case SQLITE_READ : zCode="SQLITE_READ"; break;
844 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
845 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
846 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000847 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
848 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000849 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000850 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000851 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000852 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
853 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000854 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +0000855 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drhe22a3342003-04-22 20:30:37 +0000856 default : zCode="????"; break;
857 }
858 Tcl_DStringInit(&str);
859 Tcl_DStringAppend(&str, pDb->zAuth, -1);
860 Tcl_DStringAppendElement(&str, zCode);
861 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
862 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
863 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
864 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
865 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
866 Tcl_DStringFree(&str);
867 zReply = Tcl_GetStringResult(pDb->interp);
868 if( strcmp(zReply,"SQLITE_OK")==0 ){
869 rc = SQLITE_OK;
870 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
871 rc = SQLITE_DENY;
872 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
873 rc = SQLITE_IGNORE;
874 }else{
875 rc = 999;
876 }
877 return rc;
878}
879#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000880
881/*
danielk1977ef2cb632004-05-29 02:37:19 +0000882** zText is a pointer to text obtained via an sqlite3_result_text()
883** or similar interface. This routine returns a Tcl string object,
884** reference count set to 0, containing the text. If a translation
885** between iso8859 and UTF-8 is required, it is preformed.
886*/
887static Tcl_Obj *dbTextToObj(char const *zText){
888 Tcl_Obj *pVal;
889#ifdef UTF_TRANSLATION_NEEDED
890 Tcl_DString dCol;
891 Tcl_DStringInit(&dCol);
892 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
893 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
894 Tcl_DStringFree(&dCol);
895#else
896 pVal = Tcl_NewStringObj(zText, -1);
897#endif
898 return pVal;
899}
900
901/*
tpoindex1067fe12004-12-17 15:41:11 +0000902** This routine reads a line of text from FILE in, stores
903** the text in memory obtained from malloc() and returns a pointer
904** to the text. NULL is returned at end of file, or if malloc()
905** fails.
906**
907** The interface is like "readline" but no command-line editing
908** is done.
909**
910** copied from shell.c from '.import' command
911*/
912static char *local_getline(char *zPrompt, FILE *in){
913 char *zLine;
914 int nLine;
915 int n;
916 int eol;
917
918 nLine = 100;
919 zLine = malloc( nLine );
920 if( zLine==0 ) return 0;
921 n = 0;
922 eol = 0;
923 while( !eol ){
924 if( n+100>nLine ){
925 nLine = nLine*2 + 100;
926 zLine = realloc(zLine, nLine);
927 if( zLine==0 ) return 0;
928 }
929 if( fgets(&zLine[n], nLine - n, in)==0 ){
930 if( n==0 ){
931 free(zLine);
932 return 0;
933 }
934 zLine[n] = 0;
935 eol = 1;
936 break;
937 }
938 while( zLine[n] ){ n++; }
939 if( n>0 && zLine[n-1]=='\n' ){
940 n--;
941 zLine[n] = 0;
942 eol = 1;
943 }
944 }
945 zLine = realloc( zLine, n+1 );
946 return zLine;
947}
948
danielk19778e556522007-11-13 10:30:24 +0000949
950/*
dan4a4c11a2009-10-06 14:59:02 +0000951** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +0000952**
dan4a4c11a2009-10-06 14:59:02 +0000953** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +0000954**
dan4a4c11a2009-10-06 14:59:02 +0000955** It is invoked after evaluating the script SCRIPT to commit or rollback
956** the transaction or savepoint opened by the [transaction] command.
957*/
958static int DbTransPostCmd(
959 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
960 Tcl_Interp *interp, /* Tcl interpreter */
961 int result /* Result of evaluating SCRIPT */
962){
963 static const char *azEnd[] = {
964 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
965 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
966 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
967 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
968 };
969 SqliteDb *pDb = (SqliteDb*)data[0];
970 int rc = result;
971 const char *zEnd;
972
973 pDb->nTransaction--;
974 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
975
976 pDb->disableAuth++;
977 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
978 /* This is a tricky scenario to handle. The most likely cause of an
979 ** error is that the exec() above was an attempt to commit the
980 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
981 ** that an IO-error has occured. In either case, throw a Tcl exception
982 ** and try to rollback the transaction.
983 **
984 ** But it could also be that the user executed one or more BEGIN,
985 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
986 ** this method's logic. Not clear how this would be best handled.
987 */
988 if( rc!=TCL_ERROR ){
989 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
990 rc = TCL_ERROR;
991 }
992 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
993 }
994 pDb->disableAuth--;
995
996 return rc;
997}
998
999/*
1000** Search the cache for a prepared-statement object that implements the
1001** first SQL statement in the buffer pointed to by parameter zIn. If
1002** no such prepared-statement can be found, allocate and prepare a new
1003** one. In either case, bind the current values of the relevant Tcl
1004** variables to any $var, :var or @var variables in the statement. Before
1005** returning, set *ppPreStmt to point to the prepared-statement object.
1006**
1007** Output parameter *pzOut is set to point to the next SQL statement in
1008** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1009** next statement.
1010**
1011** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1012** and an error message loaded into interpreter pDb->interp.
1013*/
1014static int dbPrepareAndBind(
1015 SqliteDb *pDb, /* Database object */
1016 char const *zIn, /* SQL to compile */
1017 char const **pzOut, /* OUT: Pointer to next SQL statement */
1018 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1019){
1020 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
1021 sqlite3_stmt *pStmt; /* Prepared statement object */
1022 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1023 int nSql; /* Length of zSql in bytes */
1024 int nVar; /* Number of variables in statement */
1025 int iParm = 0; /* Next free entry in apParm */
1026 int i;
1027 Tcl_Interp *interp = pDb->interp;
1028
1029 *ppPreStmt = 0;
1030
1031 /* Trim spaces from the start of zSql and calculate the remaining length. */
1032 while( isspace(zSql[0]) ){ zSql++; }
1033 nSql = strlen30(zSql);
1034
1035 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1036 int n = pPreStmt->nSql;
1037 if( nSql>=n
1038 && memcmp(pPreStmt->zSql, zSql, n)==0
1039 && (zSql[n]==0 || zSql[n-1]==';')
1040 ){
1041 pStmt = pPreStmt->pStmt;
1042 *pzOut = &zSql[pPreStmt->nSql];
1043
1044 /* When a prepared statement is found, unlink it from the
1045 ** cache list. It will later be added back to the beginning
1046 ** of the cache list in order to implement LRU replacement.
1047 */
1048 if( pPreStmt->pPrev ){
1049 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1050 }else{
1051 pDb->stmtList = pPreStmt->pNext;
1052 }
1053 if( pPreStmt->pNext ){
1054 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1055 }else{
1056 pDb->stmtLast = pPreStmt->pPrev;
1057 }
1058 pDb->nStmt--;
1059 nVar = sqlite3_bind_parameter_count(pStmt);
1060 break;
1061 }
1062 }
1063
1064 /* If no prepared statement was found. Compile the SQL text. Also allocate
1065 ** a new SqlPreparedStmt structure. */
1066 if( pPreStmt==0 ){
1067 int nByte;
1068
1069 if( SQLITE_OK!=sqlite3_prepare_v2(pDb->db, zSql, -1, &pStmt, pzOut) ){
1070 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1071 return TCL_ERROR;
1072 }
1073 if( pStmt==0 ){
1074 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1075 /* A compile-time error in the statement. */
1076 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1077 return TCL_ERROR;
1078 }else{
1079 /* The statement was a no-op. Continue to the next statement
1080 ** in the SQL string.
1081 */
1082 return TCL_OK;
1083 }
1084 }
1085
1086 assert( pPreStmt==0 );
1087 nVar = sqlite3_bind_parameter_count(pStmt);
1088 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1089 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1090 memset(pPreStmt, 0, nByte);
1091
1092 pPreStmt->pStmt = pStmt;
1093 pPreStmt->nSql = (*pzOut - zSql);
1094 pPreStmt->zSql = sqlite3_sql(pStmt);
1095 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
1096 }
1097 assert( pPreStmt );
1098 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1099 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1100
1101 /* Bind values to parameters that begin with $ or : */
1102 for(i=1; i<=nVar; i++){
1103 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1104 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1105 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1106 if( pVar ){
1107 int n;
1108 u8 *data;
1109 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1110 char c = zType[0];
1111 if( zVar[0]=='@' ||
1112 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1113 /* Load a BLOB type if the Tcl variable is a bytearray and
1114 ** it has no string representation or the host
1115 ** parameter name begins with "@". */
1116 data = Tcl_GetByteArrayFromObj(pVar, &n);
1117 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1118 Tcl_IncrRefCount(pVar);
1119 pPreStmt->apParm[iParm++] = pVar;
1120 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1121 Tcl_GetIntFromObj(interp, pVar, &n);
1122 sqlite3_bind_int(pStmt, i, n);
1123 }else if( c=='d' && strcmp(zType,"double")==0 ){
1124 double r;
1125 Tcl_GetDoubleFromObj(interp, pVar, &r);
1126 sqlite3_bind_double(pStmt, i, r);
1127 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1128 (c=='i' && strcmp(zType,"int")==0) ){
1129 Tcl_WideInt v;
1130 Tcl_GetWideIntFromObj(interp, pVar, &v);
1131 sqlite3_bind_int64(pStmt, i, v);
1132 }else{
1133 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1134 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1135 Tcl_IncrRefCount(pVar);
1136 pPreStmt->apParm[iParm++] = pVar;
1137 }
1138 }else{
1139 sqlite3_bind_null(pStmt, i);
1140 }
1141 }
1142 }
1143 pPreStmt->nParm = iParm;
1144 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001145
dan4a4c11a2009-10-06 14:59:02 +00001146 return TCL_OK;
1147}
1148
1149
1150/*
1151** Release a statement reference obtained by calling dbPrepareAndBind().
1152** There should be exactly one call to this function for each call to
1153** dbPrepareAndBind().
1154**
1155** If the discard parameter is non-zero, then the statement is deleted
1156** immediately. Otherwise it is added to the LRU list and may be returned
1157** by a subsequent call to dbPrepareAndBind().
1158*/
1159static void dbReleaseStmt(
1160 SqliteDb *pDb, /* Database handle */
1161 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1162 int discard /* True to delete (not cache) the pPreStmt */
1163){
1164 int i;
1165
1166 /* Free the bound string and blob parameters */
1167 for(i=0; i<pPreStmt->nParm; i++){
1168 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1169 }
1170 pPreStmt->nParm = 0;
1171
1172 if( pDb->maxStmt<=0 || discard ){
1173 /* If the cache is turned off, deallocated the statement */
1174 sqlite3_finalize(pPreStmt->pStmt);
1175 Tcl_Free((char *)pPreStmt);
1176 }else{
1177 /* Add the prepared statement to the beginning of the cache list. */
1178 pPreStmt->pNext = pDb->stmtList;
1179 pPreStmt->pPrev = 0;
1180 if( pDb->stmtList ){
1181 pDb->stmtList->pPrev = pPreStmt;
1182 }
1183 pDb->stmtList = pPreStmt;
1184 if( pDb->stmtLast==0 ){
1185 assert( pDb->nStmt==0 );
1186 pDb->stmtLast = pPreStmt;
1187 }else{
1188 assert( pDb->nStmt>0 );
1189 }
1190 pDb->nStmt++;
1191
1192 /* If we have too many statement in cache, remove the surplus from
1193 ** the end of the cache list. */
1194 while( pDb->nStmt>pDb->maxStmt ){
1195 sqlite3_finalize(pDb->stmtLast->pStmt);
1196 pDb->stmtLast = pDb->stmtLast->pPrev;
1197 Tcl_Free((char*)pDb->stmtLast->pNext);
1198 pDb->stmtLast->pNext = 0;
1199 pDb->nStmt--;
1200 }
1201 }
1202}
1203
1204/*
1205** Structure used with dbEvalXXX() functions:
1206**
1207** dbEvalInit()
1208** dbEvalStep()
1209** dbEvalFinalize()
1210** dbEvalRowInfo()
1211** dbEvalColumnValue()
1212*/
1213typedef struct DbEvalContext DbEvalContext;
1214struct DbEvalContext {
1215 SqliteDb *pDb; /* Database handle */
1216 Tcl_Obj *pSql; /* Object holding string zSql */
1217 const char *zSql; /* Remaining SQL to execute */
1218 SqlPreparedStmt *pPreStmt; /* Current statement */
1219 int nCol; /* Number of columns returned by pStmt */
1220 Tcl_Obj *pArray; /* Name of array variable */
1221 Tcl_Obj **apColName; /* Array of column names */
1222};
1223
1224/*
1225** Release any cache of column names currently held as part of
1226** the DbEvalContext structure passed as the first argument.
1227*/
1228static void dbReleaseColumnNames(DbEvalContext *p){
1229 if( p->apColName ){
1230 int i;
1231 for(i=0; i<p->nCol; i++){
1232 Tcl_DecrRefCount(p->apColName[i]);
1233 }
1234 Tcl_Free((char *)p->apColName);
1235 p->apColName = 0;
1236 }
1237 p->nCol = 0;
1238}
1239
1240/*
1241** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001242**
1243** If pArray is not NULL, then it contains the name of a Tcl array
1244** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001245** the names of the columns returned by the statement as part of each
1246** call to dbEvalStep(), in order from left to right. e.g. if the names
1247** of the returned columns are a, b and c, it does the equivalent of the
1248** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001249**
1250** set ${pArray}(*) {a b c}
1251*/
dan4a4c11a2009-10-06 14:59:02 +00001252static void dbEvalInit(
1253 DbEvalContext *p, /* Pointer to structure to initialize */
1254 SqliteDb *pDb, /* Database handle */
1255 Tcl_Obj *pSql, /* Object containing SQL script */
1256 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001257){
dan4a4c11a2009-10-06 14:59:02 +00001258 memset(p, 0, sizeof(DbEvalContext));
1259 p->pDb = pDb;
1260 p->zSql = Tcl_GetString(pSql);
1261 p->pSql = pSql;
1262 Tcl_IncrRefCount(pSql);
1263 if( pArray ){
1264 p->pArray = pArray;
1265 Tcl_IncrRefCount(pArray);
1266 }
1267}
danielk19778e556522007-11-13 10:30:24 +00001268
dan4a4c11a2009-10-06 14:59:02 +00001269/*
1270** Obtain information about the row that the DbEvalContext passed as the
1271** first argument currently points to.
1272*/
1273static void dbEvalRowInfo(
1274 DbEvalContext *p, /* Evaluation context */
1275 int *pnCol, /* OUT: Number of column names */
1276 Tcl_Obj ***papColName /* OUT: Array of column names */
1277){
danielk19778e556522007-11-13 10:30:24 +00001278 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001279 if( 0==p->apColName ){
1280 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1281 int i; /* Iterator variable */
1282 int nCol; /* Number of columns returned by pStmt */
1283 Tcl_Obj **apColName = 0; /* Array of column names */
1284
1285 p->nCol = nCol = sqlite3_column_count(pStmt);
1286 if( nCol>0 && (papColName || p->pArray) ){
1287 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1288 for(i=0; i<nCol; i++){
1289 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1290 Tcl_IncrRefCount(apColName[i]);
1291 }
1292 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001293 }
1294
1295 /* If results are being stored in an array variable, then create
1296 ** the array(*) entry for that array
1297 */
dan4a4c11a2009-10-06 14:59:02 +00001298 if( p->pArray ){
1299 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001300 Tcl_Obj *pColList = Tcl_NewObj();
1301 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001302
danielk19778e556522007-11-13 10:30:24 +00001303 for(i=0; i<nCol; i++){
1304 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1305 }
1306 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001307 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001308 Tcl_DecrRefCount(pStar);
1309 }
danielk19778e556522007-11-13 10:30:24 +00001310 }
1311
dan4a4c11a2009-10-06 14:59:02 +00001312 if( papColName ){
1313 *papColName = p->apColName;
1314 }
1315 if( pnCol ){
1316 *pnCol = p->nCol;
1317 }
1318}
1319
1320/*
1321** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1322** returned, then an error message is stored in the interpreter before
1323** returning.
1324**
1325** A return value of TCL_OK means there is a row of data available. The
1326** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1327** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1328** is returned, then the SQL script has finished executing and there are
1329** no further rows available. This is similar to SQLITE_DONE.
1330*/
1331static int dbEvalStep(DbEvalContext *p){
1332 while( p->zSql[0] || p->pPreStmt ){
1333 int rc;
1334 if( p->pPreStmt==0 ){
1335 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1336 if( rc!=TCL_OK ) return rc;
1337 }else{
1338 int rcs;
1339 SqliteDb *pDb = p->pDb;
1340 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1341 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1342
1343 rcs = sqlite3_step(pStmt);
1344 if( rcs==SQLITE_ROW ){
1345 return TCL_OK;
1346 }
1347 if( p->pArray ){
1348 dbEvalRowInfo(p, 0, 0);
1349 }
1350 rcs = sqlite3_reset(pStmt);
1351
1352 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1353 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001354 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
dan4a4c11a2009-10-06 14:59:02 +00001355 dbReleaseColumnNames(p);
1356 p->pPreStmt = 0;
1357
1358 if( rcs!=SQLITE_OK ){
1359 /* If a run-time error occurs, report the error and stop reading
1360 ** the SQL. */
1361 Tcl_SetObjResult(pDb->interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1362 dbReleaseStmt(pDb, pPreStmt, 1);
1363 return TCL_ERROR;
1364 }else{
1365 dbReleaseStmt(pDb, pPreStmt, 0);
1366 }
1367 }
1368 }
1369
1370 /* Finished */
1371 return TCL_BREAK;
1372}
1373
1374/*
1375** Free all resources currently held by the DbEvalContext structure passed
1376** as the first argument. There should be exactly one call to this function
1377** for each call to dbEvalInit().
1378*/
1379static void dbEvalFinalize(DbEvalContext *p){
1380 if( p->pPreStmt ){
1381 sqlite3_reset(p->pPreStmt->pStmt);
1382 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1383 p->pPreStmt = 0;
1384 }
1385 if( p->pArray ){
1386 Tcl_DecrRefCount(p->pArray);
1387 p->pArray = 0;
1388 }
1389 Tcl_DecrRefCount(p->pSql);
1390 dbReleaseColumnNames(p);
1391}
1392
1393/*
1394** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1395** the value for the iCol'th column of the row currently pointed to by
1396** the DbEvalContext structure passed as the first argument.
1397*/
1398static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1399 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1400 switch( sqlite3_column_type(pStmt, iCol) ){
1401 case SQLITE_BLOB: {
1402 int bytes = sqlite3_column_bytes(pStmt, iCol);
1403 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1404 if( !zBlob ) bytes = 0;
1405 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1406 }
1407 case SQLITE_INTEGER: {
1408 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1409 if( v>=-2147483647 && v<=2147483647 ){
1410 return Tcl_NewIntObj(v);
1411 }else{
1412 return Tcl_NewWideIntObj(v);
1413 }
1414 }
1415 case SQLITE_FLOAT: {
1416 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1417 }
1418 case SQLITE_NULL: {
1419 return dbTextToObj(p->pDb->zNull);
1420 }
1421 }
1422
1423 return dbTextToObj((char *)sqlite3_column_text(pStmt, iCol));
1424}
1425
1426/*
1427** If using Tcl version 8.6 or greater, use the NR functions to avoid
1428** recursive evalution of scripts by the [db eval] and [db trans]
1429** commands. Even if the headers used while compiling the extension
1430** are 8.6 or newer, the code still tests the Tcl version at runtime.
1431** This allows stubs-enabled builds to be used with older Tcl libraries.
1432*/
1433#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001434# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001435static int DbUseNre(void){
1436 int major, minor;
1437 Tcl_GetVersion(&major, &minor, 0, 0);
1438 return( (major==8 && minor>=6) || major>8 );
1439}
1440#else
1441/*
1442** Compiling using headers earlier than 8.6. In this case NR cannot be
1443** used, so DbUseNre() to always return zero. Add #defines for the other
1444** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1445** even though the only invocations of them are within conditional blocks
1446** of the form:
1447**
1448** if( DbUseNre() ) { ... }
1449*/
drha2c8a952009-10-13 18:38:34 +00001450# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001451# define DbUseNre() 0
1452# define Tcl_NRAddCallback(a,b,c,d,e,f) 0
1453# define Tcl_NREvalObj(a,b,c) 0
1454# define Tcl_NRCreateCommand(a,b,c,d,e,f) 0
1455#endif
1456
1457/*
1458** This function is part of the implementation of the command:
1459**
1460** $db eval SQL ?ARRAYNAME? SCRIPT
1461*/
1462static int DbEvalNextCmd(
1463 ClientData data[], /* data[0] is the (DbEvalContext*) */
1464 Tcl_Interp *interp, /* Tcl interpreter */
1465 int result /* Result so far */
1466){
1467 int rc = result; /* Return code */
1468
1469 /* The first element of the data[] array is a pointer to a DbEvalContext
1470 ** structure allocated using Tcl_Alloc(). The second element of data[]
1471 ** is a pointer to a Tcl_Obj containing the script to run for each row
1472 ** returned by the queries encapsulated in data[0]. */
1473 DbEvalContext *p = (DbEvalContext *)data[0];
1474 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1475 Tcl_Obj *pArray = p->pArray;
1476
1477 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1478 int i;
1479 int nCol;
1480 Tcl_Obj **apColName;
1481 dbEvalRowInfo(p, &nCol, &apColName);
1482 for(i=0; i<nCol; i++){
1483 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1484 if( pArray==0 ){
1485 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1486 }else{
1487 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1488 }
1489 }
1490
1491 /* The required interpreter variables are now populated with the data
1492 ** from the current row. If using NRE, schedule callbacks to evaluate
1493 ** script pScript, then to invoke this function again to fetch the next
1494 ** row (or clean up if there is no next row or the script throws an
1495 ** exception). After scheduling the callbacks, return control to the
1496 ** caller.
1497 **
1498 ** If not using NRE, evaluate pScript directly and continue with the
1499 ** next iteration of this while(...) loop. */
1500 if( DbUseNre() ){
1501 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1502 return Tcl_NREvalObj(interp, pScript, 0);
1503 }else{
1504 rc = Tcl_EvalObjEx(interp, pScript, 0);
1505 }
1506 }
1507
1508 Tcl_DecrRefCount(pScript);
1509 dbEvalFinalize(p);
1510 Tcl_Free((char *)p);
1511
1512 if( rc==TCL_OK || rc==TCL_BREAK ){
1513 Tcl_ResetResult(interp);
1514 rc = TCL_OK;
1515 }
1516 return rc;
danielk19778e556522007-11-13 10:30:24 +00001517}
1518
tpoindex1067fe12004-12-17 15:41:11 +00001519/*
drh75897232000-05-29 14:26:00 +00001520** The "sqlite" command below creates a new Tcl command for each
1521** connection it opens to an SQLite database. This routine is invoked
1522** whenever one of those connection-specific commands is executed
1523** in Tcl. For example, if you run Tcl code like this:
1524**
drh9bb575f2004-09-06 17:24:11 +00001525** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001526** db1 close
1527**
1528** The first command opens a connection to the "my_database" database
1529** and calls that connection "db1". The second command causes this
1530** subroutine to be invoked.
1531*/
drh6d313162000-09-21 13:01:35 +00001532static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001533 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001534 int choice;
drh22fbcb82004-02-01 01:22:50 +00001535 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001536 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001537 "authorizer", "backup", "busy",
1538 "cache", "changes", "close",
1539 "collate", "collation_needed", "commit_hook",
1540 "complete", "copy", "enable_load_extension",
1541 "errorcode", "eval", "exists",
1542 "function", "incrblob", "interrupt",
1543 "last_insert_rowid", "nullvalue", "onecolumn",
1544 "profile", "progress", "rekey",
1545 "restore", "rollback_hook", "status",
1546 "timeout", "total_changes", "trace",
danielk1977404ca072009-03-16 13:19:36 +00001547 "transaction", "unlock_notify", "update_hook",
1548 "version", 0
drh6d313162000-09-21 13:01:35 +00001549 };
drh411995d2002-06-25 19:31:18 +00001550 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001551 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1552 DB_CACHE, DB_CHANGES, DB_CLOSE,
1553 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1554 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1555 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1556 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
1557 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
1558 DB_PROFILE, DB_PROGRESS, DB_REKEY,
1559 DB_RESTORE, DB_ROLLBACK_HOOK, DB_STATUS,
1560 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
danielk1977404ca072009-03-16 13:19:36 +00001561 DB_TRANSACTION, DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK,
1562 DB_VERSION,
drh6d313162000-09-21 13:01:35 +00001563 };
tpoindex1067fe12004-12-17 15:41:11 +00001564 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001565
1566 if( objc<2 ){
1567 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001568 return TCL_ERROR;
1569 }
drh411995d2002-06-25 19:31:18 +00001570 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001571 return TCL_ERROR;
1572 }
1573
drh411995d2002-06-25 19:31:18 +00001574 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001575
drhe22a3342003-04-22 20:30:37 +00001576 /* $db authorizer ?CALLBACK?
1577 **
1578 ** Invoke the given callback to authorize each SQL operation as it is
1579 ** compiled. 5 arguments are appended to the callback before it is
1580 ** invoked:
1581 **
1582 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1583 ** (2) First descriptive name (depends on authorization type)
1584 ** (3) Second descriptive name
1585 ** (4) Name of the database (ex: "main", "temp")
1586 ** (5) Name of trigger that is doing the access
1587 **
1588 ** The callback should return on of the following strings: SQLITE_OK,
1589 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1590 **
1591 ** If this method is invoked with no arguments, the current authorization
1592 ** callback string is returned.
1593 */
1594 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001595#ifdef SQLITE_OMIT_AUTHORIZATION
1596 Tcl_AppendResult(interp, "authorization not available in this build", 0);
1597 return TCL_ERROR;
1598#else
drhe22a3342003-04-22 20:30:37 +00001599 if( objc>3 ){
1600 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001601 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001602 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001603 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +00001604 Tcl_AppendResult(interp, pDb->zAuth, 0);
1605 }
1606 }else{
1607 char *zAuth;
1608 int len;
1609 if( pDb->zAuth ){
1610 Tcl_Free(pDb->zAuth);
1611 }
1612 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1613 if( zAuth && len>0 ){
1614 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001615 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001616 }else{
1617 pDb->zAuth = 0;
1618 }
drhe22a3342003-04-22 20:30:37 +00001619 if( pDb->zAuth ){
1620 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001621 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +00001622 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001623 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001624 }
drhe22a3342003-04-22 20:30:37 +00001625 }
drh1211de32004-07-26 12:24:22 +00001626#endif
drhe22a3342003-04-22 20:30:37 +00001627 break;
1628 }
1629
drhdc2c4912009-02-04 22:46:47 +00001630 /* $db backup ?DATABASE? FILENAME
1631 **
1632 ** Open or create a database file named FILENAME. Transfer the
1633 ** content of local database DATABASE (default: "main") into the
1634 ** FILENAME database.
1635 */
1636 case DB_BACKUP: {
1637 const char *zDestFile;
1638 const char *zSrcDb;
1639 sqlite3 *pDest;
1640 sqlite3_backup *pBackup;
1641
1642 if( objc==3 ){
1643 zSrcDb = "main";
1644 zDestFile = Tcl_GetString(objv[2]);
1645 }else if( objc==4 ){
1646 zSrcDb = Tcl_GetString(objv[2]);
1647 zDestFile = Tcl_GetString(objv[3]);
1648 }else{
1649 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1650 return TCL_ERROR;
1651 }
1652 rc = sqlite3_open(zDestFile, &pDest);
1653 if( rc!=SQLITE_OK ){
1654 Tcl_AppendResult(interp, "cannot open target database: ",
1655 sqlite3_errmsg(pDest), (char*)0);
1656 sqlite3_close(pDest);
1657 return TCL_ERROR;
1658 }
1659 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1660 if( pBackup==0 ){
1661 Tcl_AppendResult(interp, "backup failed: ",
1662 sqlite3_errmsg(pDest), (char*)0);
1663 sqlite3_close(pDest);
1664 return TCL_ERROR;
1665 }
1666 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1667 sqlite3_backup_finish(pBackup);
1668 if( rc==SQLITE_DONE ){
1669 rc = TCL_OK;
1670 }else{
1671 Tcl_AppendResult(interp, "backup failed: ",
1672 sqlite3_errmsg(pDest), (char*)0);
1673 rc = TCL_ERROR;
1674 }
1675 sqlite3_close(pDest);
1676 break;
1677 }
1678
drhbec3f402000-08-04 13:49:02 +00001679 /* $db busy ?CALLBACK?
1680 **
1681 ** Invoke the given callback if an SQL statement attempts to open
1682 ** a locked database file.
1683 */
drh6d313162000-09-21 13:01:35 +00001684 case DB_BUSY: {
1685 if( objc>3 ){
1686 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001687 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001688 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001689 if( pDb->zBusy ){
1690 Tcl_AppendResult(interp, pDb->zBusy, 0);
1691 }
1692 }else{
drh6d313162000-09-21 13:01:35 +00001693 char *zBusy;
1694 int len;
drhbec3f402000-08-04 13:49:02 +00001695 if( pDb->zBusy ){
1696 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001697 }
drh6d313162000-09-21 13:01:35 +00001698 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1699 if( zBusy && len>0 ){
1700 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001701 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001702 }else{
1703 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001704 }
1705 if( pDb->zBusy ){
1706 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001707 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001708 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001709 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001710 }
1711 }
drh6d313162000-09-21 13:01:35 +00001712 break;
1713 }
drhbec3f402000-08-04 13:49:02 +00001714
drhfb7e7652005-01-24 00:28:42 +00001715 /* $db cache flush
1716 ** $db cache size n
1717 **
1718 ** Flush the prepared statement cache, or set the maximum number of
1719 ** cached statements.
1720 */
1721 case DB_CACHE: {
1722 char *subCmd;
1723 int n;
1724
1725 if( objc<=2 ){
1726 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1727 return TCL_ERROR;
1728 }
1729 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1730 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1731 if( objc!=3 ){
1732 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1733 return TCL_ERROR;
1734 }else{
1735 flushStmtCache( pDb );
1736 }
1737 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1738 if( objc!=4 ){
1739 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1740 return TCL_ERROR;
1741 }else{
1742 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1743 Tcl_AppendResult( interp, "cannot convert \"",
1744 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1745 return TCL_ERROR;
1746 }else{
1747 if( n<0 ){
1748 flushStmtCache( pDb );
1749 n = 0;
1750 }else if( n>MAX_PREPARED_STMTS ){
1751 n = MAX_PREPARED_STMTS;
1752 }
1753 pDb->maxStmt = n;
1754 }
1755 }
1756 }else{
1757 Tcl_AppendResult( interp, "bad option \"",
danielk1977191fadc2007-10-23 08:17:48 +00001758 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
drhfb7e7652005-01-24 00:28:42 +00001759 return TCL_ERROR;
1760 }
1761 break;
1762 }
1763
danielk1977b28af712004-06-21 06:50:26 +00001764 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001765 **
1766 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001767 ** the most recent INSERT, UPDATE or DELETE statement, not including
1768 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001769 */
1770 case DB_CHANGES: {
1771 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001772 if( objc!=2 ){
1773 Tcl_WrongNumArgs(interp, 2, objv, "");
1774 return TCL_ERROR;
1775 }
drhc8d30ac2002-04-12 10:08:59 +00001776 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001777 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001778 break;
1779 }
1780
drh75897232000-05-29 14:26:00 +00001781 /* $db close
1782 **
1783 ** Shutdown the database
1784 */
drh6d313162000-09-21 13:01:35 +00001785 case DB_CLOSE: {
1786 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1787 break;
1788 }
drh75897232000-05-29 14:26:00 +00001789
drh0f14e2e2004-06-29 12:39:08 +00001790 /*
1791 ** $db collate NAME SCRIPT
1792 **
1793 ** Create a new SQL collation function called NAME. Whenever
1794 ** that function is called, invoke SCRIPT to evaluate the function.
1795 */
1796 case DB_COLLATE: {
1797 SqlCollate *pCollate;
1798 char *zName;
1799 char *zScript;
1800 int nScript;
1801 if( objc!=4 ){
1802 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1803 return TCL_ERROR;
1804 }
1805 zName = Tcl_GetStringFromObj(objv[2], 0);
1806 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1807 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1808 if( pCollate==0 ) return TCL_ERROR;
1809 pCollate->interp = interp;
1810 pCollate->pNext = pDb->pCollate;
1811 pCollate->zScript = (char*)&pCollate[1];
1812 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001813 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001814 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1815 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001816 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001817 return TCL_ERROR;
1818 }
1819 break;
1820 }
1821
1822 /*
1823 ** $db collation_needed SCRIPT
1824 **
1825 ** Create a new SQL collation function called NAME. Whenever
1826 ** that function is called, invoke SCRIPT to evaluate the function.
1827 */
1828 case DB_COLLATION_NEEDED: {
1829 if( objc!=3 ){
1830 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1831 return TCL_ERROR;
1832 }
1833 if( pDb->pCollateNeeded ){
1834 Tcl_DecrRefCount(pDb->pCollateNeeded);
1835 }
1836 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1837 Tcl_IncrRefCount(pDb->pCollateNeeded);
1838 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1839 break;
1840 }
1841
drh19e2d372005-08-29 23:00:03 +00001842 /* $db commit_hook ?CALLBACK?
1843 **
1844 ** Invoke the given callback just before committing every SQL transaction.
1845 ** If the callback throws an exception or returns non-zero, then the
1846 ** transaction is aborted. If CALLBACK is an empty string, the callback
1847 ** is disabled.
1848 */
1849 case DB_COMMIT_HOOK: {
1850 if( objc>3 ){
1851 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1852 return TCL_ERROR;
1853 }else if( objc==2 ){
1854 if( pDb->zCommit ){
1855 Tcl_AppendResult(interp, pDb->zCommit, 0);
1856 }
1857 }else{
1858 char *zCommit;
1859 int len;
1860 if( pDb->zCommit ){
1861 Tcl_Free(pDb->zCommit);
1862 }
1863 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1864 if( zCommit && len>0 ){
1865 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001866 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001867 }else{
1868 pDb->zCommit = 0;
1869 }
1870 if( pDb->zCommit ){
1871 pDb->interp = interp;
1872 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1873 }else{
1874 sqlite3_commit_hook(pDb->db, 0, 0);
1875 }
1876 }
1877 break;
1878 }
1879
drh75897232000-05-29 14:26:00 +00001880 /* $db complete SQL
1881 **
1882 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1883 ** additional lines of input are needed. This is similar to the
1884 ** built-in "info complete" command of Tcl.
1885 */
drh6d313162000-09-21 13:01:35 +00001886 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00001887#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00001888 Tcl_Obj *pResult;
1889 int isComplete;
1890 if( objc!=3 ){
1891 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00001892 return TCL_ERROR;
1893 }
danielk19776f8a5032004-05-10 10:34:51 +00001894 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00001895 pResult = Tcl_GetObjResult(interp);
1896 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00001897#endif
drh6d313162000-09-21 13:01:35 +00001898 break;
1899 }
drhdcd997e2003-01-31 17:21:49 +00001900
drh19e2d372005-08-29 23:00:03 +00001901 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1902 **
1903 ** Copy data into table from filename, optionally using SEPARATOR
1904 ** as column separators. If a column contains a null string, or the
1905 ** value of NULLINDICATOR, a NULL is inserted for the column.
1906 ** conflict-algorithm is one of the sqlite conflict algorithms:
1907 ** rollback, abort, fail, ignore, replace
1908 ** On success, return the number of lines processed, not necessarily same
1909 ** as 'db changes' due to conflict-algorithm selected.
1910 **
1911 ** This code is basically an implementation/enhancement of
1912 ** the sqlite3 shell.c ".import" command.
1913 **
1914 ** This command usage is equivalent to the sqlite2.x COPY statement,
1915 ** which imports file data into a table using the PostgreSQL COPY file format:
1916 ** $db copy $conflit_algo $table_name $filename \t \\N
1917 */
1918 case DB_COPY: {
1919 char *zTable; /* Insert data into this table */
1920 char *zFile; /* The file from which to extract data */
1921 char *zConflict; /* The conflict algorithm to use */
1922 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00001923 int nCol; /* Number of columns in the table */
1924 int nByte; /* Number of bytes in an SQL string */
1925 int i, j; /* Loop counters */
1926 int nSep; /* Number of bytes in zSep[] */
1927 int nNull; /* Number of bytes in zNull[] */
1928 char *zSql; /* An SQL statement */
1929 char *zLine; /* A single line of input from the file */
1930 char **azCol; /* zLine[] broken up into columns */
1931 char *zCommit; /* How to commit changes */
1932 FILE *in; /* The input file */
1933 int lineno = 0; /* Line number of input file */
1934 char zLineNum[80]; /* Line number print buffer */
1935 Tcl_Obj *pResult; /* interp result */
1936
1937 char *zSep;
1938 char *zNull;
1939 if( objc<5 || objc>7 ){
1940 Tcl_WrongNumArgs(interp, 2, objv,
1941 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1942 return TCL_ERROR;
1943 }
1944 if( objc>=6 ){
1945 zSep = Tcl_GetStringFromObj(objv[5], 0);
1946 }else{
1947 zSep = "\t";
1948 }
1949 if( objc>=7 ){
1950 zNull = Tcl_GetStringFromObj(objv[6], 0);
1951 }else{
1952 zNull = "";
1953 }
1954 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1955 zTable = Tcl_GetStringFromObj(objv[3], 0);
1956 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00001957 nSep = strlen30(zSep);
1958 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00001959 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00001960 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00001961 return TCL_ERROR;
1962 }
drh3e59c012008-09-23 10:12:13 +00001963 if(strcmp(zConflict, "rollback") != 0 &&
1964 strcmp(zConflict, "abort" ) != 0 &&
1965 strcmp(zConflict, "fail" ) != 0 &&
1966 strcmp(zConflict, "ignore" ) != 0 &&
1967 strcmp(zConflict, "replace" ) != 0 ) {
drh19e2d372005-08-29 23:00:03 +00001968 Tcl_AppendResult(interp, "Error: \"", zConflict,
1969 "\", conflict-algorithm must be one of: rollback, "
1970 "abort, fail, ignore, or replace", 0);
1971 return TCL_ERROR;
1972 }
1973 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1974 if( zSql==0 ){
1975 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1976 return TCL_ERROR;
1977 }
drh4f21c4a2008-12-10 22:15:00 +00001978 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00001979 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001980 sqlite3_free(zSql);
1981 if( rc ){
1982 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1983 nCol = 0;
1984 }else{
1985 nCol = sqlite3_column_count(pStmt);
1986 }
1987 sqlite3_finalize(pStmt);
1988 if( nCol==0 ) {
1989 return TCL_ERROR;
1990 }
1991 zSql = malloc( nByte + 50 + nCol*2 );
1992 if( zSql==0 ) {
1993 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1994 return TCL_ERROR;
1995 }
1996 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1997 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00001998 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00001999 for(i=1; i<nCol; i++){
2000 zSql[j++] = ',';
2001 zSql[j++] = '?';
2002 }
2003 zSql[j++] = ')';
2004 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002005 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002006 free(zSql);
2007 if( rc ){
2008 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2009 sqlite3_finalize(pStmt);
2010 return TCL_ERROR;
2011 }
2012 in = fopen(zFile, "rb");
2013 if( in==0 ){
2014 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2015 sqlite3_finalize(pStmt);
2016 return TCL_ERROR;
2017 }
2018 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2019 if( azCol==0 ) {
2020 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00002021 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002022 return TCL_ERROR;
2023 }
drh37527852006-03-16 16:19:56 +00002024 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002025 zCommit = "COMMIT";
2026 while( (zLine = local_getline(0, in))!=0 ){
2027 char *z;
2028 i = 0;
2029 lineno++;
2030 azCol[0] = zLine;
2031 for(i=0, z=zLine; *z; z++){
2032 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2033 *z = 0;
2034 i++;
2035 if( i<nCol ){
2036 azCol[i] = &z[nSep];
2037 z += nSep-1;
2038 }
2039 }
2040 }
2041 if( i+1!=nCol ){
2042 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002043 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002044 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002045 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002046 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002047 "Error: %s line %d: expected %d columns of data but found %d",
2048 zFile, lineno, nCol, i+1);
2049 Tcl_AppendResult(interp, zErr, 0);
2050 free(zErr);
2051 }
drh19e2d372005-08-29 23:00:03 +00002052 zCommit = "ROLLBACK";
2053 break;
2054 }
2055 for(i=0; i<nCol; i++){
2056 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002057 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
drh4f21c4a2008-12-10 22:15:00 +00002058 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002059 ){
drh19e2d372005-08-29 23:00:03 +00002060 sqlite3_bind_null(pStmt, i+1);
2061 }else{
2062 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2063 }
2064 }
2065 sqlite3_step(pStmt);
2066 rc = sqlite3_reset(pStmt);
2067 free(zLine);
2068 if( rc!=SQLITE_OK ){
2069 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
2070 zCommit = "ROLLBACK";
2071 break;
2072 }
2073 }
2074 free(azCol);
2075 fclose(in);
2076 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002077 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002078
2079 if( zCommit[0] == 'C' ){
2080 /* success, set result as number of lines processed */
2081 pResult = Tcl_GetObjResult(interp);
2082 Tcl_SetIntObj(pResult, lineno);
2083 rc = TCL_OK;
2084 }else{
2085 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002086 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00002087 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
2088 rc = TCL_ERROR;
2089 }
2090 break;
2091 }
2092
drhdcd997e2003-01-31 17:21:49 +00002093 /*
drh41449052006-07-06 17:08:48 +00002094 ** $db enable_load_extension BOOLEAN
2095 **
2096 ** Turn the extension loading feature on or off. It if off by
2097 ** default.
2098 */
2099 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002100#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002101 int onoff;
2102 if( objc!=3 ){
2103 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2104 return TCL_ERROR;
2105 }
2106 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2107 return TCL_ERROR;
2108 }
2109 sqlite3_enable_load_extension(pDb->db, onoff);
2110 break;
drhf533acc2006-12-19 18:57:11 +00002111#else
2112 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2113 0);
2114 return TCL_ERROR;
2115#endif
drh41449052006-07-06 17:08:48 +00002116 }
2117
2118 /*
drhdcd997e2003-01-31 17:21:49 +00002119 ** $db errorcode
2120 **
2121 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002122 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002123 */
2124 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002125 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002126 break;
2127 }
dan4a4c11a2009-10-06 14:59:02 +00002128
2129 /*
2130 ** $db exists $sql
2131 ** $db onecolumn $sql
2132 **
2133 ** The onecolumn method is the equivalent of:
2134 ** lindex [$db eval $sql] 0
2135 */
2136 case DB_EXISTS:
2137 case DB_ONECOLUMN: {
2138 DbEvalContext sEval;
2139 if( objc!=3 ){
2140 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2141 return TCL_ERROR;
2142 }
2143
2144 dbEvalInit(&sEval, pDb, objv[2], 0);
2145 rc = dbEvalStep(&sEval);
2146 if( choice==DB_ONECOLUMN ){
2147 if( rc==TCL_OK ){
2148 Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
2149 }
2150 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2151 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
2152 }
2153 dbEvalFinalize(&sEval);
2154
2155 if( rc==TCL_BREAK ){
2156 rc = TCL_OK;
2157 }
2158 break;
2159 }
drh75897232000-05-29 14:26:00 +00002160
2161 /*
drh895d7472004-08-20 16:02:39 +00002162 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002163 **
2164 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002165 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002166 ** If "array" and "code" are omitted, then no callback is every invoked.
2167 ** If "array" is an empty string, then the values are placed in variables
2168 ** that have the same name as the fields extracted by the query.
2169 */
dan4a4c11a2009-10-06 14:59:02 +00002170 case DB_EVAL: {
2171 if( objc<3 || objc>5 ){
2172 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2173 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002174 }
dan4a4c11a2009-10-06 14:59:02 +00002175
drh92febd92004-08-20 18:34:20 +00002176 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002177 DbEvalContext sEval;
2178 Tcl_Obj *pRet = Tcl_NewObj();
2179 Tcl_IncrRefCount(pRet);
2180 dbEvalInit(&sEval, pDb, objv[2], 0);
2181 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2182 int i;
2183 int nCol;
2184 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002185 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002186 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002187 }
2188 }
dan4a4c11a2009-10-06 14:59:02 +00002189 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002190 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002191 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002192 rc = TCL_OK;
2193 }
drh1807ce32004-09-07 13:20:35 +00002194 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002195 }else{
2196 ClientData cd[2];
2197 DbEvalContext *p;
2198 Tcl_Obj *pArray = 0;
2199 Tcl_Obj *pScript;
2200
2201 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2202 pArray = objv[3];
2203 }
2204 pScript = objv[objc-1];
2205 Tcl_IncrRefCount(pScript);
2206
2207 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2208 dbEvalInit(p, pDb, objv[2], pArray);
2209
2210 cd[0] = (void *)p;
2211 cd[1] = (void *)pScript;
2212 rc = DbEvalNextCmd(cd, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002213 }
danielk197730ccda12004-05-27 12:11:31 +00002214 break;
2215 }
drhbec3f402000-08-04 13:49:02 +00002216
2217 /*
drhe3602be2008-09-09 12:31:33 +00002218 ** $db function NAME [-argcount N] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002219 **
2220 ** Create a new SQL function called NAME. Whenever that function is
2221 ** called, invoke SCRIPT to evaluate the function.
2222 */
2223 case DB_FUNCTION: {
2224 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002225 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002226 char *zName;
drhe3602be2008-09-09 12:31:33 +00002227 int nArg = -1;
2228 if( objc==6 ){
2229 const char *z = Tcl_GetString(objv[3]);
drh4f21c4a2008-12-10 22:15:00 +00002230 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002231 if( n>2 && strncmp(z, "-argcount",n)==0 ){
2232 if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
2233 if( nArg<0 ){
2234 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2235 (char*)0);
2236 return TCL_ERROR;
2237 }
2238 }
2239 pScript = objv[5];
2240 }else if( objc!=4 ){
2241 Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
drhcabb0812002-09-14 13:47:32 +00002242 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002243 }else{
2244 pScript = objv[3];
drhcabb0812002-09-14 13:47:32 +00002245 }
2246 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002247 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002248 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002249 if( pFunc->pScript ){
2250 Tcl_DecrRefCount(pFunc->pScript);
2251 }
2252 pFunc->pScript = pScript;
2253 Tcl_IncrRefCount(pScript);
2254 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
drhe3602be2008-09-09 12:31:33 +00002255 rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00002256 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002257 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002258 rc = TCL_ERROR;
2259 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002260 }
drhcabb0812002-09-14 13:47:32 +00002261 break;
2262 }
2263
2264 /*
danielk19778cbadb02007-05-03 16:31:26 +00002265 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002266 */
2267 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002268#ifdef SQLITE_OMIT_INCRBLOB
2269 Tcl_AppendResult(interp, "incrblob not available in this build", 0);
2270 return TCL_ERROR;
2271#else
danielk19778cbadb02007-05-03 16:31:26 +00002272 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002273 const char *zDb = "main";
2274 const char *zTable;
2275 const char *zColumn;
2276 sqlite_int64 iRow;
2277
danielk19778cbadb02007-05-03 16:31:26 +00002278 /* Check for the -readonly option */
2279 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2280 isReadonly = 1;
2281 }
2282
2283 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2284 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002285 return TCL_ERROR;
2286 }
2287
danielk19778cbadb02007-05-03 16:31:26 +00002288 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002289 zDb = Tcl_GetString(objv[2]);
2290 }
2291 zTable = Tcl_GetString(objv[objc-3]);
2292 zColumn = Tcl_GetString(objv[objc-2]);
2293 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2294
2295 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002296 rc = createIncrblobChannel(
2297 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
2298 );
danielk1977b4e9af92007-05-01 17:49:49 +00002299 }
danielk197732a0d8b2007-05-04 19:03:02 +00002300#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002301 break;
2302 }
2303
2304 /*
drhf11bded2006-07-17 00:02:44 +00002305 ** $db interrupt
2306 **
2307 ** Interrupt the execution of the inner-most SQL interpreter. This
2308 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2309 */
2310 case DB_INTERRUPT: {
2311 sqlite3_interrupt(pDb->db);
2312 break;
2313 }
2314
2315 /*
drh19e2d372005-08-29 23:00:03 +00002316 ** $db nullvalue ?STRING?
2317 **
2318 ** Change text used when a NULL comes back from the database. If ?STRING?
2319 ** is not present, then the current string used for NULL is returned.
2320 ** If STRING is present, then STRING is returned.
2321 **
2322 */
2323 case DB_NULLVALUE: {
2324 if( objc!=2 && objc!=3 ){
2325 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2326 return TCL_ERROR;
2327 }
2328 if( objc==3 ){
2329 int len;
2330 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2331 if( pDb->zNull ){
2332 Tcl_Free(pDb->zNull);
2333 }
2334 if( zNull && len>0 ){
2335 pDb->zNull = Tcl_Alloc( len + 1 );
2336 strncpy(pDb->zNull, zNull, len);
2337 pDb->zNull[len] = '\0';
2338 }else{
2339 pDb->zNull = 0;
2340 }
2341 }
2342 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
2343 break;
2344 }
2345
2346 /*
drhaf9ff332002-01-16 21:00:27 +00002347 ** $db last_insert_rowid
2348 **
2349 ** Return an integer which is the ROWID for the most recent insert.
2350 */
2351 case DB_LAST_INSERT_ROWID: {
2352 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002353 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002354 if( objc!=2 ){
2355 Tcl_WrongNumArgs(interp, 2, objv, "");
2356 return TCL_ERROR;
2357 }
danielk19776f8a5032004-05-10 10:34:51 +00002358 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002359 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002360 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002361 break;
2362 }
2363
2364 /*
dan4a4c11a2009-10-06 14:59:02 +00002365 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002366 */
drh1807ce32004-09-07 13:20:35 +00002367
2368 /* $db progress ?N CALLBACK?
2369 **
2370 ** Invoke the given callback every N virtual machine opcodes while executing
2371 ** queries.
2372 */
2373 case DB_PROGRESS: {
2374 if( objc==2 ){
2375 if( pDb->zProgress ){
2376 Tcl_AppendResult(interp, pDb->zProgress, 0);
2377 }
2378 }else if( objc==4 ){
2379 char *zProgress;
2380 int len;
2381 int N;
2382 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002383 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002384 };
2385 if( pDb->zProgress ){
2386 Tcl_Free(pDb->zProgress);
2387 }
2388 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2389 if( zProgress && len>0 ){
2390 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002391 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002392 }else{
2393 pDb->zProgress = 0;
2394 }
2395#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2396 if( pDb->zProgress ){
2397 pDb->interp = interp;
2398 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2399 }else{
2400 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2401 }
2402#endif
2403 }else{
2404 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002405 return TCL_ERROR;
2406 }
drh5d9d7572003-08-19 14:31:01 +00002407 break;
2408 }
2409
drh19e2d372005-08-29 23:00:03 +00002410 /* $db profile ?CALLBACK?
2411 **
2412 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2413 ** that has run. The text of the SQL and the amount of elapse time are
2414 ** appended to CALLBACK before the script is run.
2415 */
2416 case DB_PROFILE: {
2417 if( objc>3 ){
2418 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2419 return TCL_ERROR;
2420 }else if( objc==2 ){
2421 if( pDb->zProfile ){
2422 Tcl_AppendResult(interp, pDb->zProfile, 0);
2423 }
2424 }else{
2425 char *zProfile;
2426 int len;
2427 if( pDb->zProfile ){
2428 Tcl_Free(pDb->zProfile);
2429 }
2430 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2431 if( zProfile && len>0 ){
2432 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002433 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002434 }else{
2435 pDb->zProfile = 0;
2436 }
2437#ifndef SQLITE_OMIT_TRACE
2438 if( pDb->zProfile ){
2439 pDb->interp = interp;
2440 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2441 }else{
2442 sqlite3_profile(pDb->db, 0, 0);
2443 }
2444#endif
2445 }
2446 break;
2447 }
2448
drh5d9d7572003-08-19 14:31:01 +00002449 /*
drh22fbcb82004-02-01 01:22:50 +00002450 ** $db rekey KEY
2451 **
2452 ** Change the encryption key on the currently open database.
2453 */
2454 case DB_REKEY: {
2455 int nKey;
2456 void *pKey;
2457 if( objc!=3 ){
2458 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2459 return TCL_ERROR;
2460 }
2461 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00002462#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00002463 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002464 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00002465 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002466 rc = TCL_ERROR;
2467 }
2468#endif
2469 break;
2470 }
2471
drhdc2c4912009-02-04 22:46:47 +00002472 /* $db restore ?DATABASE? FILENAME
2473 **
2474 ** Open a database file named FILENAME. Transfer the content
2475 ** of FILENAME into the local database DATABASE (default: "main").
2476 */
2477 case DB_RESTORE: {
2478 const char *zSrcFile;
2479 const char *zDestDb;
2480 sqlite3 *pSrc;
2481 sqlite3_backup *pBackup;
2482 int nTimeout = 0;
2483
2484 if( objc==3 ){
2485 zDestDb = "main";
2486 zSrcFile = Tcl_GetString(objv[2]);
2487 }else if( objc==4 ){
2488 zDestDb = Tcl_GetString(objv[2]);
2489 zSrcFile = Tcl_GetString(objv[3]);
2490 }else{
2491 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2492 return TCL_ERROR;
2493 }
2494 rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
2495 if( rc!=SQLITE_OK ){
2496 Tcl_AppendResult(interp, "cannot open source database: ",
2497 sqlite3_errmsg(pSrc), (char*)0);
2498 sqlite3_close(pSrc);
2499 return TCL_ERROR;
2500 }
2501 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2502 if( pBackup==0 ){
2503 Tcl_AppendResult(interp, "restore failed: ",
2504 sqlite3_errmsg(pDb->db), (char*)0);
2505 sqlite3_close(pSrc);
2506 return TCL_ERROR;
2507 }
2508 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2509 || rc==SQLITE_BUSY ){
2510 if( rc==SQLITE_BUSY ){
2511 if( nTimeout++ >= 3 ) break;
2512 sqlite3_sleep(100);
2513 }
2514 }
2515 sqlite3_backup_finish(pBackup);
2516 if( rc==SQLITE_DONE ){
2517 rc = TCL_OK;
2518 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2519 Tcl_AppendResult(interp, "restore failed: source database busy",
2520 (char*)0);
2521 rc = TCL_ERROR;
2522 }else{
2523 Tcl_AppendResult(interp, "restore failed: ",
2524 sqlite3_errmsg(pDb->db), (char*)0);
2525 rc = TCL_ERROR;
2526 }
2527 sqlite3_close(pSrc);
2528 break;
2529 }
2530
drh22fbcb82004-02-01 01:22:50 +00002531 /*
drh3c379b02010-04-07 19:31:59 +00002532 ** $db status (step|sort|autoindex)
drhd1d38482008-10-07 23:46:38 +00002533 **
2534 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2535 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2536 */
2537 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002538 int v;
2539 const char *zOp;
2540 if( objc!=3 ){
2541 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort)");
2542 return TCL_ERROR;
2543 }
2544 zOp = Tcl_GetString(objv[2]);
2545 if( strcmp(zOp, "step")==0 ){
2546 v = pDb->nStep;
2547 }else if( strcmp(zOp, "sort")==0 ){
2548 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002549 }else if( strcmp(zOp, "autoindex")==0 ){
2550 v = pDb->nIndex;
drhd1d38482008-10-07 23:46:38 +00002551 }else{
drh3c379b02010-04-07 19:31:59 +00002552 Tcl_AppendResult(interp,
2553 "bad argument: should be autoindex, step, or sort",
drhd1d38482008-10-07 23:46:38 +00002554 (char*)0);
2555 return TCL_ERROR;
2556 }
2557 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2558 break;
2559 }
2560
2561 /*
drhbec3f402000-08-04 13:49:02 +00002562 ** $db timeout MILLESECONDS
2563 **
2564 ** Delay for the number of milliseconds specified when a file is locked.
2565 */
drh6d313162000-09-21 13:01:35 +00002566 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002567 int ms;
drh6d313162000-09-21 13:01:35 +00002568 if( objc!=3 ){
2569 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002570 return TCL_ERROR;
2571 }
drh6d313162000-09-21 13:01:35 +00002572 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002573 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002574 break;
drh75897232000-05-29 14:26:00 +00002575 }
danielk197755c45f22005-04-03 23:54:43 +00002576
2577 /*
drh0f14e2e2004-06-29 12:39:08 +00002578 ** $db total_changes
2579 **
2580 ** Return the number of rows that were modified, inserted, or deleted
2581 ** since the database handle was created.
2582 */
2583 case DB_TOTAL_CHANGES: {
2584 Tcl_Obj *pResult;
2585 if( objc!=2 ){
2586 Tcl_WrongNumArgs(interp, 2, objv, "");
2587 return TCL_ERROR;
2588 }
2589 pResult = Tcl_GetObjResult(interp);
2590 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2591 break;
2592 }
2593
drhb5a20d32003-04-23 12:25:23 +00002594 /* $db trace ?CALLBACK?
2595 **
2596 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2597 ** that is executed. The text of the SQL is appended to CALLBACK before
2598 ** it is executed.
2599 */
2600 case DB_TRACE: {
2601 if( objc>3 ){
2602 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002603 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002604 }else if( objc==2 ){
2605 if( pDb->zTrace ){
2606 Tcl_AppendResult(interp, pDb->zTrace, 0);
2607 }
2608 }else{
2609 char *zTrace;
2610 int len;
2611 if( pDb->zTrace ){
2612 Tcl_Free(pDb->zTrace);
2613 }
2614 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2615 if( zTrace && len>0 ){
2616 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002617 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002618 }else{
2619 pDb->zTrace = 0;
2620 }
drh19e2d372005-08-29 23:00:03 +00002621#ifndef SQLITE_OMIT_TRACE
drhb5a20d32003-04-23 12:25:23 +00002622 if( pDb->zTrace ){
2623 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002624 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002625 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002626 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002627 }
drh19e2d372005-08-29 23:00:03 +00002628#endif
drhb5a20d32003-04-23 12:25:23 +00002629 }
2630 break;
2631 }
2632
drh3d214232005-08-02 12:21:08 +00002633 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2634 **
2635 ** Start a new transaction (if we are not already in the midst of a
2636 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2637 ** completes, either commit the transaction or roll it back if SCRIPT
2638 ** throws an exception. Or if no new transation was started, do nothing.
2639 ** pass the exception on up the stack.
2640 **
2641 ** This command was inspired by Dave Thomas's talk on Ruby at the
2642 ** 2005 O'Reilly Open Source Convention (OSCON).
2643 */
2644 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00002645 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00002646 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00002647 if( objc!=3 && objc!=4 ){
2648 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2649 return TCL_ERROR;
2650 }
danielk1977cd38d522009-01-02 17:33:46 +00002651
dan4a4c11a2009-10-06 14:59:02 +00002652 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00002653 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002654 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002655 };
2656 enum TTYPE_enum {
2657 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2658 };
2659 int ttype;
drhb5555e72005-08-02 17:15:14 +00002660 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002661 0, &ttype) ){
2662 return TCL_ERROR;
2663 }
2664 switch( (enum TTYPE_enum)ttype ){
2665 case TTYPE_DEFERRED: /* no-op */; break;
2666 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2667 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2668 }
drh3d214232005-08-02 12:21:08 +00002669 }
danielk1977cd38d522009-01-02 17:33:46 +00002670 pScript = objv[objc-1];
2671
dan4a4c11a2009-10-06 14:59:02 +00002672 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00002673 pDb->disableAuth++;
2674 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2675 pDb->disableAuth--;
2676 if( rc!=SQLITE_OK ){
2677 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2678 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00002679 }
danielk1977cd38d522009-01-02 17:33:46 +00002680 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00002681
dan4a4c11a2009-10-06 14:59:02 +00002682 /* If using NRE, schedule a callback to invoke the script pScript, then
2683 ** a second callback to commit (or rollback) the transaction or savepoint
2684 ** opened above. If not using NRE, evaluate the script directly, then
2685 ** call function DbTransPostCmd() to commit (or rollback) the transaction
2686 ** or savepoint. */
2687 if( DbUseNre() ){
2688 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
2689 Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00002690 }else{
dan4a4c11a2009-10-06 14:59:02 +00002691 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00002692 }
2693 break;
2694 }
2695
danielk197794eb6a12005-12-15 15:22:08 +00002696 /*
danielk1977404ca072009-03-16 13:19:36 +00002697 ** $db unlock_notify ?script?
2698 */
2699 case DB_UNLOCK_NOTIFY: {
2700#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2701 Tcl_AppendResult(interp, "unlock_notify not available in this build", 0);
2702 rc = TCL_ERROR;
2703#else
2704 if( objc!=2 && objc!=3 ){
2705 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2706 rc = TCL_ERROR;
2707 }else{
2708 void (*xNotify)(void **, int) = 0;
2709 void *pNotifyArg = 0;
2710
2711 if( pDb->pUnlockNotify ){
2712 Tcl_DecrRefCount(pDb->pUnlockNotify);
2713 pDb->pUnlockNotify = 0;
2714 }
2715
2716 if( objc==3 ){
2717 xNotify = DbUnlockNotify;
2718 pNotifyArg = (void *)pDb;
2719 pDb->pUnlockNotify = objv[2];
2720 Tcl_IncrRefCount(pDb->pUnlockNotify);
2721 }
2722
2723 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
2724 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2725 rc = TCL_ERROR;
2726 }
2727 }
2728#endif
2729 break;
2730 }
2731
2732 /*
danielk197794eb6a12005-12-15 15:22:08 +00002733 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002734 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002735 */
danielk197771fd80b2005-12-16 06:54:01 +00002736 case DB_UPDATE_HOOK:
2737 case DB_ROLLBACK_HOOK: {
2738
2739 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2740 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2741 */
2742 Tcl_Obj **ppHook;
2743 if( choice==DB_UPDATE_HOOK ){
2744 ppHook = &pDb->pUpdateHook;
2745 }else{
2746 ppHook = &pDb->pRollbackHook;
2747 }
2748
danielk197794eb6a12005-12-15 15:22:08 +00002749 if( objc!=2 && objc!=3 ){
2750 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2751 return TCL_ERROR;
2752 }
danielk197771fd80b2005-12-16 06:54:01 +00002753 if( *ppHook ){
2754 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002755 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002756 Tcl_DecrRefCount(*ppHook);
2757 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00002758 }
2759 }
2760 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002761 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00002762 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00002763 *ppHook = objv[2];
2764 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002765 }
2766 }
danielk197771fd80b2005-12-16 06:54:01 +00002767
2768 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2769 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
2770
danielk197794eb6a12005-12-15 15:22:08 +00002771 break;
2772 }
2773
danielk19774397de52005-01-12 12:44:03 +00002774 /* $db version
2775 **
2776 ** Return the version string for this database.
2777 */
2778 case DB_VERSION: {
2779 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2780 break;
2781 }
2782
tpoindex1067fe12004-12-17 15:41:11 +00002783
drh6d313162000-09-21 13:01:35 +00002784 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002785 return rc;
drh75897232000-05-29 14:26:00 +00002786}
2787
drha2c8a952009-10-13 18:38:34 +00002788#if SQLITE_TCL_NRE
2789/*
2790** Adaptor that provides an objCmd interface to the NRE-enabled
2791** interface implementation.
2792*/
2793static int DbObjCmdAdaptor(
2794 void *cd,
2795 Tcl_Interp *interp,
2796 int objc,
2797 Tcl_Obj *const*objv
2798){
2799 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
2800}
2801#endif /* SQLITE_TCL_NRE */
2802
drh75897232000-05-29 14:26:00 +00002803/*
drh3570ad92007-08-31 14:31:44 +00002804** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00002805** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00002806**
2807** This is the main Tcl command. When the "sqlite" Tcl command is
2808** invoked, this routine runs to process that command.
2809**
2810** The first argument, DBNAME, is an arbitrary name for a new
2811** database connection. This command creates a new command named
2812** DBNAME that is used to control that connection. The database
2813** connection is deleted when the DBNAME command is deleted.
2814**
drh3570ad92007-08-31 14:31:44 +00002815** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00002816**
drh75897232000-05-29 14:26:00 +00002817*/
drh22fbcb82004-02-01 01:22:50 +00002818static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002819 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002820 void *pKey = 0;
2821 int nKey = 0;
2822 const char *zArg;
drh75897232000-05-29 14:26:00 +00002823 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00002824 int i;
drh22fbcb82004-02-01 01:22:50 +00002825 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00002826 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00002827 int flags;
drh882e8e42006-08-24 02:42:27 +00002828 Tcl_DString translatedFilename;
drhd9da78a2009-03-24 15:08:09 +00002829
2830 /* In normal use, each TCL interpreter runs in a single thread. So
2831 ** by default, we can turn of mutexing on SQLite database connections.
2832 ** However, for testing purposes it is useful to have mutexes turned
2833 ** on. So, by default, mutexes default off. But if compiled with
2834 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
2835 */
2836#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
2837 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
2838#else
2839 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
2840#endif
2841
drh22fbcb82004-02-01 01:22:50 +00002842 if( objc==2 ){
2843 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002844 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00002845 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00002846 return TCL_OK;
2847 }
drh9eb9e262004-02-11 02:18:05 +00002848 if( strcmp(zArg,"-has-codec")==0 ){
2849#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002850 Tcl_AppendResult(interp,"1",0);
2851#else
2852 Tcl_AppendResult(interp,"0",0);
2853#endif
2854 return TCL_OK;
2855 }
drhfbc3eab2001-04-06 16:13:42 +00002856 }
drh3570ad92007-08-31 14:31:44 +00002857 for(i=3; i+1<objc; i+=2){
2858 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00002859 if( strcmp(zArg,"-key")==0 ){
drh3570ad92007-08-31 14:31:44 +00002860 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
2861 }else if( strcmp(zArg, "-vfs")==0 ){
2862 i++;
2863 zVfs = Tcl_GetString(objv[i]);
2864 }else if( strcmp(zArg, "-readonly")==0 ){
2865 int b;
2866 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2867 if( b ){
drh33f4e022007-09-03 15:19:34 +00002868 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00002869 flags |= SQLITE_OPEN_READONLY;
2870 }else{
2871 flags &= ~SQLITE_OPEN_READONLY;
2872 flags |= SQLITE_OPEN_READWRITE;
2873 }
2874 }else if( strcmp(zArg, "-create")==0 ){
2875 int b;
2876 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00002877 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00002878 flags |= SQLITE_OPEN_CREATE;
2879 }else{
2880 flags &= ~SQLITE_OPEN_CREATE;
2881 }
danielk19779a6284c2008-07-10 17:52:49 +00002882 }else if( strcmp(zArg, "-nomutex")==0 ){
2883 int b;
2884 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2885 if( b ){
2886 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00002887 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00002888 }else{
2889 flags &= ~SQLITE_OPEN_NOMUTEX;
2890 }
drh039963a2008-09-03 00:43:15 +00002891 }else if( strcmp(zArg, "-fullmutex")==0 ){
2892 int b;
2893 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2894 if( b ){
2895 flags |= SQLITE_OPEN_FULLMUTEX;
2896 flags &= ~SQLITE_OPEN_NOMUTEX;
2897 }else{
2898 flags &= ~SQLITE_OPEN_FULLMUTEX;
2899 }
drh3570ad92007-08-31 14:31:44 +00002900 }else{
2901 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
2902 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00002903 }
2904 }
drh3570ad92007-08-31 14:31:44 +00002905 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00002906 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00002907 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh039963a2008-09-03 00:43:15 +00002908 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN?"
drh9eb9e262004-02-11 02:18:05 +00002909#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00002910 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00002911#endif
2912 );
drh75897232000-05-29 14:26:00 +00002913 return TCL_ERROR;
2914 }
drh75897232000-05-29 14:26:00 +00002915 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00002916 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00002917 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00002918 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
2919 return TCL_ERROR;
2920 }
2921 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00002922 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00002923 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
drh3570ad92007-08-31 14:31:44 +00002924 sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00002925 Tcl_DStringFree(&translatedFilename);
danielk197780290862004-05-22 09:21:21 +00002926 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
drh9404d502006-12-19 18:46:08 +00002927 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
danielk197780290862004-05-22 09:21:21 +00002928 sqlite3_close(p->db);
2929 p->db = 0;
2930 }
drh2011d5f2004-07-22 02:40:37 +00002931#ifdef SQLITE_HAS_CODEC
drhf3a65f72007-08-22 20:18:21 +00002932 if( p->db ){
2933 sqlite3_key(p->db, pKey, nKey);
2934 }
drheb8ed702004-02-11 10:37:23 +00002935#endif
drhbec3f402000-08-04 13:49:02 +00002936 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00002937 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00002938 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00002939 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00002940 return TCL_ERROR;
2941 }
drhfb7e7652005-01-24 00:28:42 +00002942 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00002943 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00002944 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00002945 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00002946 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
2947 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00002948 }else{
2949 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
2950 }
drh75897232000-05-29 14:26:00 +00002951 return TCL_OK;
2952}
2953
2954/*
drh90ca9752001-09-28 17:47:14 +00002955** Provide a dummy Tcl_InitStubs if we are using this as a static
2956** library.
2957*/
2958#ifndef USE_TCL_STUBS
2959# undef Tcl_InitStubs
2960# define Tcl_InitStubs(a,b,c)
2961#endif
2962
2963/*
drh29bc4612005-10-05 10:40:15 +00002964** Make sure we have a PACKAGE_VERSION macro defined. This will be
2965** defined automatically by the TEA makefile. But other makefiles
2966** do not define it.
2967*/
2968#ifndef PACKAGE_VERSION
2969# define PACKAGE_VERSION SQLITE_VERSION
2970#endif
2971
2972/*
drh75897232000-05-29 14:26:00 +00002973** Initialize this module.
2974**
2975** This Tcl module contains only a single new Tcl command named "sqlite".
2976** (Hence there is no namespace. There is no point in using a namespace
2977** if the extension only supplies one new name!) The "sqlite" command is
2978** used to open a new SQLite database. See the DbMain() routine above
2979** for additional information.
2980*/
drhad6e1372006-07-10 21:15:51 +00002981EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00002982 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00002983 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002984 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh49766d62005-01-08 18:42:28 +00002985 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002986 Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
drh90ca9752001-09-28 17:47:14 +00002987 return TCL_OK;
2988}
drhad6e1372006-07-10 21:15:51 +00002989EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2990EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2991EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00002992EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2993EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2994EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2995EXTERN int Tclsqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
2996
drh49766d62005-01-08 18:42:28 +00002997
2998#ifndef SQLITE_3_SUFFIX_ONLY
drhad6e1372006-07-10 21:15:51 +00002999EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3000EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3001EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3002EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00003003EXTERN int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3004EXTERN int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3005EXTERN int Sqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3006EXTERN int Tclsqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
drh49766d62005-01-08 18:42:28 +00003007#endif
drh75897232000-05-29 14:26:00 +00003008
drh3e27c022004-07-23 00:01:38 +00003009#ifdef TCLSH
3010/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003011** All of the code that follows is used to build standalone TCL interpreters
3012** that are statically linked with SQLite. Enable these by compiling
3013** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3014** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3015** analysis program.
drh75897232000-05-29 14:26:00 +00003016*/
drh348784e2000-05-29 20:41:49 +00003017
drh57a02272009-10-22 20:52:05 +00003018#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3019/*
3020 * This code implements the MD5 message-digest algorithm.
3021 * The algorithm is due to Ron Rivest. This code was
3022 * written by Colin Plumb in 1993, no copyright is claimed.
3023 * This code is in the public domain; do with it what you wish.
3024 *
3025 * Equivalent code is available from RSA Data Security, Inc.
3026 * This code has been tested against that, and is equivalent,
3027 * except that you don't need to include two pages of legalese
3028 * with every copy.
3029 *
3030 * To compute the message digest of a chunk of bytes, declare an
3031 * MD5Context structure, pass it to MD5Init, call MD5Update as
3032 * needed on buffers full of bytes, and then call MD5Final, which
3033 * will fill a supplied 16-byte array with the digest.
3034 */
3035
3036/*
3037 * If compiled on a machine that doesn't have a 32-bit integer,
3038 * you just set "uint32" to the appropriate datatype for an
3039 * unsigned 32-bit integer. For example:
3040 *
3041 * cc -Duint32='unsigned long' md5.c
3042 *
3043 */
3044#ifndef uint32
3045# define uint32 unsigned int
3046#endif
3047
3048struct MD5Context {
3049 int isInit;
3050 uint32 buf[4];
3051 uint32 bits[2];
3052 unsigned char in[64];
3053};
3054typedef struct MD5Context MD5Context;
3055
3056/*
3057 * Note: this code is harmless on little-endian machines.
3058 */
3059static void byteReverse (unsigned char *buf, unsigned longs){
3060 uint32 t;
3061 do {
3062 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3063 ((unsigned)buf[1]<<8 | buf[0]);
3064 *(uint32 *)buf = t;
3065 buf += 4;
3066 } while (--longs);
3067}
3068/* The four core functions - F1 is optimized somewhat */
3069
3070/* #define F1(x, y, z) (x & y | ~x & z) */
3071#define F1(x, y, z) (z ^ (x & (y ^ z)))
3072#define F2(x, y, z) F1(z, x, y)
3073#define F3(x, y, z) (x ^ y ^ z)
3074#define F4(x, y, z) (y ^ (x | ~z))
3075
3076/* This is the central step in the MD5 algorithm. */
3077#define MD5STEP(f, w, x, y, z, data, s) \
3078 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3079
3080/*
3081 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3082 * reflect the addition of 16 longwords of new data. MD5Update blocks
3083 * the data and converts bytes into longwords for this routine.
3084 */
3085static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3086 register uint32 a, b, c, d;
3087
3088 a = buf[0];
3089 b = buf[1];
3090 c = buf[2];
3091 d = buf[3];
3092
3093 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3094 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3095 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3096 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3097 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3098 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3099 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3100 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3101 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3102 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3103 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3104 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3105 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3106 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3107 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3108 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3109
3110 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3111 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3112 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3113 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3114 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3115 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3116 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3117 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3118 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3119 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3120 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3121 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3122 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3123 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3124 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3125 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3126
3127 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3128 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3129 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3130 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3131 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3132 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3133 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3134 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3135 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3136 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3137 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3138 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3139 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3140 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3141 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3142 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3143
3144 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3145 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3146 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3147 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3148 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3149 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3150 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3151 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3152 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3153 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3154 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3155 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3156 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3157 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3158 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3159 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3160
3161 buf[0] += a;
3162 buf[1] += b;
3163 buf[2] += c;
3164 buf[3] += d;
3165}
3166
3167/*
3168 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3169 * initialization constants.
3170 */
3171static void MD5Init(MD5Context *ctx){
3172 ctx->isInit = 1;
3173 ctx->buf[0] = 0x67452301;
3174 ctx->buf[1] = 0xefcdab89;
3175 ctx->buf[2] = 0x98badcfe;
3176 ctx->buf[3] = 0x10325476;
3177 ctx->bits[0] = 0;
3178 ctx->bits[1] = 0;
3179}
3180
3181/*
3182 * Update context to reflect the concatenation of another buffer full
3183 * of bytes.
3184 */
3185static
3186void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3187 uint32 t;
3188
3189 /* Update bitcount */
3190
3191 t = ctx->bits[0];
3192 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3193 ctx->bits[1]++; /* Carry from low to high */
3194 ctx->bits[1] += len >> 29;
3195
3196 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3197
3198 /* Handle any leading odd-sized chunks */
3199
3200 if ( t ) {
3201 unsigned char *p = (unsigned char *)ctx->in + t;
3202
3203 t = 64-t;
3204 if (len < t) {
3205 memcpy(p, buf, len);
3206 return;
3207 }
3208 memcpy(p, buf, t);
3209 byteReverse(ctx->in, 16);
3210 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3211 buf += t;
3212 len -= t;
3213 }
3214
3215 /* Process data in 64-byte chunks */
3216
3217 while (len >= 64) {
3218 memcpy(ctx->in, buf, 64);
3219 byteReverse(ctx->in, 16);
3220 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3221 buf += 64;
3222 len -= 64;
3223 }
3224
3225 /* Handle any remaining bytes of data. */
3226
3227 memcpy(ctx->in, buf, len);
3228}
3229
3230/*
3231 * Final wrapup - pad to 64-byte boundary with the bit pattern
3232 * 1 0* (64-bit count of bits processed, MSB-first)
3233 */
3234static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3235 unsigned count;
3236 unsigned char *p;
3237
3238 /* Compute number of bytes mod 64 */
3239 count = (ctx->bits[0] >> 3) & 0x3F;
3240
3241 /* Set the first char of padding to 0x80. This is safe since there is
3242 always at least one byte free */
3243 p = ctx->in + count;
3244 *p++ = 0x80;
3245
3246 /* Bytes of padding needed to make 64 bytes */
3247 count = 64 - 1 - count;
3248
3249 /* Pad out to 56 mod 64 */
3250 if (count < 8) {
3251 /* Two lots of padding: Pad the first block to 64 bytes */
3252 memset(p, 0, count);
3253 byteReverse(ctx->in, 16);
3254 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3255
3256 /* Now fill the next block with 56 bytes */
3257 memset(ctx->in, 0, 56);
3258 } else {
3259 /* Pad block to 56 bytes */
3260 memset(p, 0, count-8);
3261 }
3262 byteReverse(ctx->in, 14);
3263
3264 /* Append length in bits and transform */
3265 ((uint32 *)ctx->in)[ 14 ] = ctx->bits[0];
3266 ((uint32 *)ctx->in)[ 15 ] = ctx->bits[1];
3267
3268 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3269 byteReverse((unsigned char *)ctx->buf, 4);
3270 memcpy(digest, ctx->buf, 16);
3271 memset(ctx, 0, sizeof(ctx)); /* In case it is sensitive */
3272}
3273
3274/*
3275** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3276*/
3277static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3278 static char const zEncode[] = "0123456789abcdef";
3279 int i, j;
3280
3281 for(j=i=0; i<16; i++){
3282 int a = digest[i];
3283 zBuf[j++] = zEncode[(a>>4)&0xf];
3284 zBuf[j++] = zEncode[a & 0xf];
3285 }
3286 zBuf[j] = 0;
3287}
3288
3289
3290/*
3291** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3292** each representing 16 bits of the digest and separated from each
3293** other by a "-" character.
3294*/
3295static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3296 int i, j;
3297 unsigned int x;
3298 for(i=j=0; i<16; i+=2){
3299 x = digest[i]*256 + digest[i+1];
3300 if( i>0 ) zDigest[j++] = '-';
3301 sprintf(&zDigest[j], "%05u", x);
3302 j += 5;
3303 }
3304 zDigest[j] = 0;
3305}
3306
3307/*
3308** A TCL command for md5. The argument is the text to be hashed. The
3309** Result is the hash in base64.
3310*/
3311static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3312 MD5Context ctx;
3313 unsigned char digest[16];
3314 char zBuf[50];
3315 void (*converter)(unsigned char*, char*);
3316
3317 if( argc!=2 ){
3318 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3319 " TEXT\"", 0);
3320 return TCL_ERROR;
3321 }
3322 MD5Init(&ctx);
3323 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3324 MD5Final(digest, &ctx);
3325 converter = (void(*)(unsigned char*,char*))cd;
3326 converter(digest, zBuf);
3327 Tcl_AppendResult(interp, zBuf, (char*)0);
3328 return TCL_OK;
3329}
3330
3331/*
3332** A TCL command to take the md5 hash of a file. The argument is the
3333** name of the file.
3334*/
3335static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3336 FILE *in;
3337 MD5Context ctx;
3338 void (*converter)(unsigned char*, char*);
3339 unsigned char digest[16];
3340 char zBuf[10240];
3341
3342 if( argc!=2 ){
3343 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3344 " FILENAME\"", 0);
3345 return TCL_ERROR;
3346 }
3347 in = fopen(argv[1],"rb");
3348 if( in==0 ){
3349 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
3350 "\" for reading", 0);
3351 return TCL_ERROR;
3352 }
3353 MD5Init(&ctx);
3354 for(;;){
3355 int n;
3356 n = fread(zBuf, 1, sizeof(zBuf), in);
3357 if( n<=0 ) break;
3358 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3359 }
3360 fclose(in);
3361 MD5Final(digest, &ctx);
3362 converter = (void(*)(unsigned char*,char*))cd;
3363 converter(digest, zBuf);
3364 Tcl_AppendResult(interp, zBuf, (char*)0);
3365 return TCL_OK;
3366}
3367
3368/*
3369** Register the four new TCL commands for generating MD5 checksums
3370** with the TCL interpreter.
3371*/
3372int Md5_Init(Tcl_Interp *interp){
3373 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3374 MD5DigestToBase16, 0);
3375 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3376 MD5DigestToBase10x8, 0);
3377 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3378 MD5DigestToBase16, 0);
3379 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3380 MD5DigestToBase10x8, 0);
3381 return TCL_OK;
3382}
3383#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3384
3385#if defined(SQLITE_TEST)
3386/*
3387** During testing, the special md5sum() aggregate function is available.
3388** inside SQLite. The following routines implement that function.
3389*/
3390static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3391 MD5Context *p;
3392 int i;
3393 if( argc<1 ) return;
3394 p = sqlite3_aggregate_context(context, sizeof(*p));
3395 if( p==0 ) return;
3396 if( !p->isInit ){
3397 MD5Init(p);
3398 }
3399 for(i=0; i<argc; i++){
3400 const char *zData = (char*)sqlite3_value_text(argv[i]);
3401 if( zData ){
3402 MD5Update(p, (unsigned char*)zData, strlen(zData));
3403 }
3404 }
3405}
3406static void md5finalize(sqlite3_context *context){
3407 MD5Context *p;
3408 unsigned char digest[16];
3409 char zBuf[33];
3410 p = sqlite3_aggregate_context(context, sizeof(*p));
3411 MD5Final(digest,p);
3412 MD5DigestToBase16(digest, zBuf);
3413 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3414}
3415int Md5_Register(sqlite3 *db){
3416 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
3417 md5step, md5finalize);
3418 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3419 return rc;
3420}
3421#endif /* defined(SQLITE_TEST) */
3422
3423
drh348784e2000-05-29 20:41:49 +00003424/*
drh3e27c022004-07-23 00:01:38 +00003425** If the macro TCLSH is one, then put in code this for the
3426** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003427** standard input, or if a file is named on the command line
3428** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003429*/
drh3e27c022004-07-23 00:01:38 +00003430#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00003431static char zMainloop[] =
3432 "set line {}\n"
3433 "while {![eof stdin]} {\n"
3434 "if {$line!=\"\"} {\n"
3435 "puts -nonewline \"> \"\n"
3436 "} else {\n"
3437 "puts -nonewline \"% \"\n"
3438 "}\n"
3439 "flush stdout\n"
3440 "append line [gets stdin]\n"
3441 "if {[info complete $line]} {\n"
3442 "if {[catch {uplevel #0 $line} result]} {\n"
3443 "puts stderr \"Error: $result\"\n"
3444 "} elseif {$result!=\"\"} {\n"
3445 "puts $result\n"
3446 "}\n"
3447 "set line {}\n"
3448 "} else {\n"
3449 "append line \\n\n"
3450 "}\n"
3451 "}\n"
3452;
drh3e27c022004-07-23 00:01:38 +00003453#endif
3454
drh348784e2000-05-29 20:41:49 +00003455#define TCLSH_MAIN main /* Needed to fake out mktclapp */
3456int TCLSH_MAIN(int argc, char **argv){
3457 Tcl_Interp *interp;
danielk19770a549072009-02-17 16:29:10 +00003458
3459 /* Call sqlite3_shutdown() once before doing anything else. This is to
3460 ** test that sqlite3_shutdown() can be safely called by a process before
3461 ** sqlite3_initialize() is. */
3462 sqlite3_shutdown();
3463
drh297ecf12001-04-05 15:57:13 +00003464 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00003465 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00003466 Sqlite3_Init(interp);
drh57a02272009-10-22 20:52:05 +00003467#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3468 Md5_Init(interp);
3469#endif
drhd9b02572001-04-15 00:37:09 +00003470#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00003471 {
drh2f999a62007-08-15 19:16:43 +00003472 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00003473 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00003474 extern int Sqlitetest2_Init(Tcl_Interp*);
3475 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00003476 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00003477 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00003478 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00003479 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00003480 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00003481 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00003482 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00003483 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
drh984bfaa2008-03-19 16:08:53 +00003484 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00003485 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00003486 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003487 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00003488 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003489 extern int Sqlitetestschema_Init(Tcl_Interp*);
3490 extern int Sqlitetestsse_Init(Tcl_Interp*);
3491 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00003492 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00003493 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00003494 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00003495 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh522efc62009-11-10 17:24:37 +00003496 extern int Sqlitetestintarray_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00003497
drh2f999a62007-08-15 19:16:43 +00003498 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00003499 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00003500 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00003501 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00003502 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00003503 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00003504 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00003505 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00003506 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00003507 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00003508 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00003509 Sqlitetest_autoext_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00003510 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00003511 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00003512 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003513 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00003514 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003515 Sqlitetestschema_Init(interp);
3516 Sqlitetesttclvar_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00003517 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003518 SqlitetestOnefile_Init(interp);
danielk19775d1f5aa2008-04-10 14:51:00 +00003519 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00003520 Sqlitetestbackup_Init(interp);
drh522efc62009-11-10 17:24:37 +00003521 Sqlitetestintarray_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003522
drh89dec812005-04-28 19:03:37 +00003523#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00003524 Sqlitetestsse_Init(interp);
3525#endif
drhd1bf3512001-04-07 15:24:33 +00003526 }
3527#endif
drhc7285972009-11-10 01:13:25 +00003528 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00003529 int i;
shessad42c3a2006-08-22 23:53:46 +00003530 char zArgc[32];
3531 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
3532 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00003533 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
3534 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00003535 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00003536 Tcl_SetVar(interp, "argv", argv[i],
3537 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3538 }
drhc7285972009-11-10 01:13:25 +00003539 if( Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00003540 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00003541 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00003542 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00003543 return 1;
3544 }
drh3e27c022004-07-23 00:01:38 +00003545 }
drhc7285972009-11-10 01:13:25 +00003546 if( argc<=1 ){
drh348784e2000-05-29 20:41:49 +00003547 Tcl_GlobalEval(interp, zMainloop);
3548 }
3549 return 0;
3550}
3551#endif /* TCLSH */