blob: 604e9379522a842f77cf93b4528a48654b3af02d [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
36# include "sqliteInt.h"
drhbd08af42007-04-05 21:58:33 +000037# include <stdlib.h>
38# include <string.h>
39# include <assert.h>
drhbd08af42007-04-05 21:58:33 +000040#endif
drheb206382009-10-24 15:51:33 +000041#include <ctype.h>
drh75897232000-05-29 14:26:00 +000042
drhad6e1372006-07-10 21:15:51 +000043/*
44 * Windows needs to know which symbols to export. Unix does not.
45 * BUILD_sqlite should be undefined for Unix.
46 */
47#ifdef BUILD_sqlite
48#undef TCL_STORAGE_CLASS
49#define TCL_STORAGE_CLASS DLLEXPORT
50#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000051
danielk1977a21c6b62005-01-24 10:25:59 +000052#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000053#define MAX_PREPARED_STMTS 100
54
drh75897232000-05-29 14:26:00 +000055/*
drh98808ba2001-10-18 12:34:46 +000056** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
57** have to do a translation when going between the two. Set the
58** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
59** this translation.
60*/
61#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
62# define UTF_TRANSLATION_NEEDED 1
63#endif
64
65/*
drhcabb0812002-09-14 13:47:32 +000066** New SQL functions can be created as TCL scripts. Each such function
67** is described by an instance of the following structure.
68*/
69typedef struct SqlFunc SqlFunc;
70struct SqlFunc {
71 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000072 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
73 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
74 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000075 SqlFunc *pNext; /* Next function on the list of them all */
76};
77
78/*
danielk19770202b292004-06-09 09:55:16 +000079** New collation sequences function can be created as TCL scripts. Each such
80** function is described by an instance of the following structure.
81*/
82typedef struct SqlCollate SqlCollate;
83struct SqlCollate {
84 Tcl_Interp *interp; /* The TCL interpret to execute the function */
85 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000086 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000087};
88
89/*
drhfb7e7652005-01-24 00:28:42 +000090** Prepared statements are cached for faster execution. Each prepared
91** statement is described by an instance of the following structure.
92*/
93typedef struct SqlPreparedStmt SqlPreparedStmt;
94struct SqlPreparedStmt {
95 SqlPreparedStmt *pNext; /* Next in linked list */
96 SqlPreparedStmt *pPrev; /* Previous on the list */
97 sqlite3_stmt *pStmt; /* The prepared statement */
98 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +000099 const char *zSql; /* Text of the SQL statement */
dan4a4c11a2009-10-06 14:59:02 +0000100 int nParm; /* Size of apParm array */
101 Tcl_Obj **apParm; /* Array of referenced object pointers */
drhfb7e7652005-01-24 00:28:42 +0000102};
103
danielk1977d04417962007-05-02 13:16:30 +0000104typedef struct IncrblobChannel IncrblobChannel;
105
drhfb7e7652005-01-24 00:28:42 +0000106/*
drhbec3f402000-08-04 13:49:02 +0000107** There is one instance of this structure for each SQLite database
108** that has been opened by the SQLite TCL interface.
109*/
110typedef struct SqliteDb SqliteDb;
111struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000112 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000113 Tcl_Interp *interp; /* The interpreter used for this database */
114 char *zBusy; /* The busy callback routine */
115 char *zCommit; /* The commit hook callback routine */
116 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +0000117 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000118 char *zProgress; /* The progress callback routine */
119 char *zAuth; /* The authorization callback routine */
drh1f1549f2008-08-26 21:33:34 +0000120 int disableAuth; /* Disable the authorizer if it exists */
drhd1e47332005-06-26 17:55:33 +0000121 char *zNull; /* Text to substitute for an SQL NULL value */
122 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000123 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000124 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000125 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000126 SqlCollate *pCollate; /* List of SQL collation functions */
127 int rc; /* Return code of most recent sqlite3_exec() */
128 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000129 SqlPreparedStmt *stmtList; /* List of prepared statements*/
130 SqlPreparedStmt *stmtLast; /* Last statement in the list */
131 int maxStmt; /* The next maximum number of stmtList */
132 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000133 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drhd1d38482008-10-07 23:46:38 +0000134 int nStep, nSort; /* Statistics for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000135 int nTransaction; /* Number of nested [transaction] methods */
drh98808ba2001-10-18 12:34:46 +0000136};
drh297ecf12001-04-05 15:57:13 +0000137
danielk1977b4e9af92007-05-01 17:49:49 +0000138struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000139 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000140 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000141 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000142 Tcl_Channel channel; /* Channel identifier */
143 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
144 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000145};
146
drhea678832008-12-10 19:26:22 +0000147/*
148** Compute a string length that is limited to what can be stored in
149** lower 30 bits of a 32-bit signed integer.
150*/
drh4f21c4a2008-12-10 22:15:00 +0000151static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000152 const char *z2 = z;
153 while( *z2 ){ z2++; }
154 return 0x3fffffff & (int)(z2 - z);
155}
drhea678832008-12-10 19:26:22 +0000156
157
danielk197732a0d8b2007-05-04 19:03:02 +0000158#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000159/*
danielk1977d04417962007-05-02 13:16:30 +0000160** Close all incrblob channels opened using database connection pDb.
161** This is called when shutting down the database connection.
162*/
163static void closeIncrblobChannels(SqliteDb *pDb){
164 IncrblobChannel *p;
165 IncrblobChannel *pNext;
166
167 for(p=pDb->pIncrblob; p; p=pNext){
168 pNext = p->pNext;
169
170 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
171 ** which deletes the IncrblobChannel structure at *p. So do not
172 ** call Tcl_Free() here.
173 */
174 Tcl_UnregisterChannel(pDb->interp, p->channel);
175 }
176}
177
178/*
danielk1977b4e9af92007-05-01 17:49:49 +0000179** Close an incremental blob channel.
180*/
181static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
182 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000183 int rc = sqlite3_blob_close(p->pBlob);
184 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000185
186 /* Remove the channel from the SqliteDb.pIncrblob list. */
187 if( p->pNext ){
188 p->pNext->pPrev = p->pPrev;
189 }
190 if( p->pPrev ){
191 p->pPrev->pNext = p->pNext;
192 }
193 if( p->pDb->pIncrblob==p ){
194 p->pDb->pIncrblob = p->pNext;
195 }
196
danielk197792d4d7a2007-05-04 12:05:56 +0000197 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000198 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000199
200 if( rc!=SQLITE_OK ){
201 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
202 return TCL_ERROR;
203 }
danielk1977b4e9af92007-05-01 17:49:49 +0000204 return TCL_OK;
205}
206
207/*
208** Read data from an incremental blob channel.
209*/
210static int incrblobInput(
211 ClientData instanceData,
212 char *buf,
213 int bufSize,
214 int *errorCodePtr
215){
216 IncrblobChannel *p = (IncrblobChannel *)instanceData;
217 int nRead = bufSize; /* Number of bytes to read */
218 int nBlob; /* Total size of the blob */
219 int rc; /* sqlite error code */
220
221 nBlob = sqlite3_blob_bytes(p->pBlob);
222 if( (p->iSeek+nRead)>nBlob ){
223 nRead = nBlob-p->iSeek;
224 }
225 if( nRead<=0 ){
226 return 0;
227 }
228
229 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
230 if( rc!=SQLITE_OK ){
231 *errorCodePtr = rc;
232 return -1;
233 }
234
235 p->iSeek += nRead;
236 return nRead;
237}
238
danielk1977d04417962007-05-02 13:16:30 +0000239/*
240** Write data to an incremental blob channel.
241*/
danielk1977b4e9af92007-05-01 17:49:49 +0000242static int incrblobOutput(
243 ClientData instanceData,
244 CONST char *buf,
245 int toWrite,
246 int *errorCodePtr
247){
248 IncrblobChannel *p = (IncrblobChannel *)instanceData;
249 int nWrite = toWrite; /* Number of bytes to write */
250 int nBlob; /* Total size of the blob */
251 int rc; /* sqlite error code */
252
253 nBlob = sqlite3_blob_bytes(p->pBlob);
254 if( (p->iSeek+nWrite)>nBlob ){
255 *errorCodePtr = EINVAL;
256 return -1;
257 }
258 if( nWrite<=0 ){
259 return 0;
260 }
261
262 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
263 if( rc!=SQLITE_OK ){
264 *errorCodePtr = EIO;
265 return -1;
266 }
267
268 p->iSeek += nWrite;
269 return nWrite;
270}
271
272/*
273** Seek an incremental blob channel.
274*/
275static int incrblobSeek(
276 ClientData instanceData,
277 long offset,
278 int seekMode,
279 int *errorCodePtr
280){
281 IncrblobChannel *p = (IncrblobChannel *)instanceData;
282
283 switch( seekMode ){
284 case SEEK_SET:
285 p->iSeek = offset;
286 break;
287 case SEEK_CUR:
288 p->iSeek += offset;
289 break;
290 case SEEK_END:
291 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
292 break;
293
294 default: assert(!"Bad seekMode");
295 }
296
297 return p->iSeek;
298}
299
300
301static void incrblobWatch(ClientData instanceData, int mode){
302 /* NO-OP */
303}
304static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
305 return TCL_ERROR;
306}
307
308static Tcl_ChannelType IncrblobChannelType = {
309 "incrblob", /* typeName */
310 TCL_CHANNEL_VERSION_2, /* version */
311 incrblobClose, /* closeProc */
312 incrblobInput, /* inputProc */
313 incrblobOutput, /* outputProc */
314 incrblobSeek, /* seekProc */
315 0, /* setOptionProc */
316 0, /* getOptionProc */
317 incrblobWatch, /* watchProc (this is a no-op) */
318 incrblobHandle, /* getHandleProc (always returns error) */
319 0, /* close2Proc */
320 0, /* blockModeProc */
321 0, /* flushProc */
322 0, /* handlerProc */
323 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000324};
325
326/*
327** Create a new incrblob channel.
328*/
329static int createIncrblobChannel(
330 Tcl_Interp *interp,
331 SqliteDb *pDb,
332 const char *zDb,
333 const char *zTable,
334 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000335 sqlite_int64 iRow,
336 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000337){
338 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000339 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000340 sqlite3_blob *pBlob;
341 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000342 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000343
344 /* This variable is used to name the channels: "incrblob_[incr count]" */
345 static int count = 0;
346 char zChannel[64];
347
danielk19778cbadb02007-05-03 16:31:26 +0000348 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000349 if( rc!=SQLITE_OK ){
350 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
351 return TCL_ERROR;
352 }
353
354 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
355 p->iSeek = 0;
356 p->pBlob = pBlob;
357
drh5bb3eb92007-05-04 13:15:55 +0000358 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000359 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
360 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000361
danielk1977d04417962007-05-02 13:16:30 +0000362 /* Link the new channel into the SqliteDb.pIncrblob list. */
363 p->pNext = pDb->pIncrblob;
364 p->pPrev = 0;
365 if( p->pNext ){
366 p->pNext->pPrev = p;
367 }
368 pDb->pIncrblob = p;
369 p->pDb = pDb;
370
371 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000372 return TCL_OK;
373}
danielk197732a0d8b2007-05-04 19:03:02 +0000374#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
375 #define closeIncrblobChannels(pDb)
376#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000377
drh6d313162000-09-21 13:01:35 +0000378/*
drhd1e47332005-06-26 17:55:33 +0000379** Look at the script prefix in pCmd. We will be executing this script
380** after first appending one or more arguments. This routine analyzes
381** the script to see if it is safe to use Tcl_EvalObjv() on the script
382** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
383** faster.
384**
385** Scripts that are safe to use with Tcl_EvalObjv() consists of a
386** command name followed by zero or more arguments with no [...] or $
387** or {...} or ; to be seen anywhere. Most callback scripts consist
388** of just a single procedure name and they meet this requirement.
389*/
390static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
391 /* We could try to do something with Tcl_Parse(). But we will instead
392 ** just do a search for forbidden characters. If any of the forbidden
393 ** characters appear in pCmd, we will report the string as unsafe.
394 */
395 const char *z;
396 int n;
397 z = Tcl_GetStringFromObj(pCmd, &n);
398 while( n-- > 0 ){
399 int c = *(z++);
400 if( c=='$' || c=='[' || c==';' ) return 0;
401 }
402 return 1;
403}
404
405/*
406** Find an SqlFunc structure with the given name. Or create a new
407** one if an existing one cannot be found. Return a pointer to the
408** structure.
409*/
410static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
411 SqlFunc *p, *pNew;
412 int i;
drh4f21c4a2008-12-10 22:15:00 +0000413 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen30(zName) + 1 );
drhd1e47332005-06-26 17:55:33 +0000414 pNew->zName = (char*)&pNew[1];
415 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
416 pNew->zName[i] = 0;
417 for(p=pDb->pFunc; p; p=p->pNext){
418 if( strcmp(p->zName, pNew->zName)==0 ){
419 Tcl_Free((char*)pNew);
420 return p;
421 }
422 }
423 pNew->interp = pDb->interp;
424 pNew->pScript = 0;
425 pNew->pNext = pDb->pFunc;
426 pDb->pFunc = pNew;
427 return pNew;
428}
429
430/*
drhfb7e7652005-01-24 00:28:42 +0000431** Finalize and free a list of prepared statements
432*/
433static void flushStmtCache( SqliteDb *pDb ){
434 SqlPreparedStmt *pPreStmt;
435
436 while( pDb->stmtList ){
437 sqlite3_finalize( pDb->stmtList->pStmt );
438 pPreStmt = pDb->stmtList;
439 pDb->stmtList = pDb->stmtList->pNext;
440 Tcl_Free( (char*)pPreStmt );
441 }
442 pDb->nStmt = 0;
443 pDb->stmtLast = 0;
444}
445
446/*
drh895d7472004-08-20 16:02:39 +0000447** TCL calls this procedure when an sqlite3 database command is
448** deleted.
drh75897232000-05-29 14:26:00 +0000449*/
450static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000451 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000452 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000453 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000454 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000455 while( pDb->pFunc ){
456 SqlFunc *pFunc = pDb->pFunc;
457 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000458 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000459 Tcl_Free((char*)pFunc);
460 }
danielk19770202b292004-06-09 09:55:16 +0000461 while( pDb->pCollate ){
462 SqlCollate *pCollate = pDb->pCollate;
463 pDb->pCollate = pCollate->pNext;
464 Tcl_Free((char*)pCollate);
465 }
drhbec3f402000-08-04 13:49:02 +0000466 if( pDb->zBusy ){
467 Tcl_Free(pDb->zBusy);
468 }
drhb5a20d32003-04-23 12:25:23 +0000469 if( pDb->zTrace ){
470 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000471 }
drh19e2d372005-08-29 23:00:03 +0000472 if( pDb->zProfile ){
473 Tcl_Free(pDb->zProfile);
474 }
drhe22a3342003-04-22 20:30:37 +0000475 if( pDb->zAuth ){
476 Tcl_Free(pDb->zAuth);
477 }
danielk197755c45f22005-04-03 23:54:43 +0000478 if( pDb->zNull ){
479 Tcl_Free(pDb->zNull);
480 }
danielk197794eb6a12005-12-15 15:22:08 +0000481 if( pDb->pUpdateHook ){
482 Tcl_DecrRefCount(pDb->pUpdateHook);
483 }
danielk197771fd80b2005-12-16 06:54:01 +0000484 if( pDb->pRollbackHook ){
485 Tcl_DecrRefCount(pDb->pRollbackHook);
486 }
danielk197794eb6a12005-12-15 15:22:08 +0000487 if( pDb->pCollateNeeded ){
488 Tcl_DecrRefCount(pDb->pCollateNeeded);
489 }
drhbec3f402000-08-04 13:49:02 +0000490 Tcl_Free((char*)pDb);
491}
492
493/*
494** This routine is called when a database file is locked while trying
495** to execute SQL.
496*/
danielk19772a764eb2004-06-12 01:43:26 +0000497static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000498 SqliteDb *pDb = (SqliteDb*)cd;
499 int rc;
500 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000501
drh5bb3eb92007-05-04 13:15:55 +0000502 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000503 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000504 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
505 return 0;
506 }
507 return 1;
drh75897232000-05-29 14:26:00 +0000508}
509
drh26e4a8b2008-05-01 17:16:52 +0000510#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000511/*
danielk1977348bb5d2003-10-18 09:37:26 +0000512** This routine is invoked as the 'progress callback' for the database.
513*/
514static int DbProgressHandler(void *cd){
515 SqliteDb *pDb = (SqliteDb*)cd;
516 int rc;
517
518 assert( pDb->zProgress );
519 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
520 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
521 return 1;
522 }
523 return 0;
524}
drh26e4a8b2008-05-01 17:16:52 +0000525#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000526
drhd1167392006-01-23 13:00:35 +0000527#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000528/*
drhb5a20d32003-04-23 12:25:23 +0000529** This routine is called by the SQLite trace handler whenever a new
530** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000531*/
drhb5a20d32003-04-23 12:25:23 +0000532static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000533 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000534 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000535
drhb5a20d32003-04-23 12:25:23 +0000536 Tcl_DStringInit(&str);
537 Tcl_DStringAppend(&str, pDb->zTrace, -1);
538 Tcl_DStringAppendElement(&str, zSql);
539 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
540 Tcl_DStringFree(&str);
541 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000542}
drhd1167392006-01-23 13:00:35 +0000543#endif
drh0d1a6432003-04-03 15:46:04 +0000544
drhd1167392006-01-23 13:00:35 +0000545#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000546/*
drh19e2d372005-08-29 23:00:03 +0000547** This routine is called by the SQLite profile handler after a statement
548** SQL has executed. The TCL script in pDb->zProfile is evaluated.
549*/
550static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
551 SqliteDb *pDb = (SqliteDb*)cd;
552 Tcl_DString str;
553 char zTm[100];
554
555 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
556 Tcl_DStringInit(&str);
557 Tcl_DStringAppend(&str, pDb->zProfile, -1);
558 Tcl_DStringAppendElement(&str, zSql);
559 Tcl_DStringAppendElement(&str, zTm);
560 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
561 Tcl_DStringFree(&str);
562 Tcl_ResetResult(pDb->interp);
563}
drhd1167392006-01-23 13:00:35 +0000564#endif
drh19e2d372005-08-29 23:00:03 +0000565
566/*
drhaa940ea2004-01-15 02:44:03 +0000567** This routine is called when a transaction is committed. The
568** TCL script in pDb->zCommit is executed. If it returns non-zero or
569** if it throws an exception, the transaction is rolled back instead
570** of being committed.
571*/
572static int DbCommitHandler(void *cd){
573 SqliteDb *pDb = (SqliteDb*)cd;
574 int rc;
575
576 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
577 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
578 return 1;
579 }
580 return 0;
581}
582
danielk197771fd80b2005-12-16 06:54:01 +0000583static void DbRollbackHandler(void *clientData){
584 SqliteDb *pDb = (SqliteDb*)clientData;
585 assert(pDb->pRollbackHook);
586 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
587 Tcl_BackgroundError(pDb->interp);
588 }
589}
590
drhbcf4f482009-03-27 12:44:35 +0000591#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000592static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
593 char zBuf[64];
594 sprintf(zBuf, "%d", iArg);
595 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
596 sprintf(zBuf, "%d", nArg);
597 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
598}
599#else
drhbcf4f482009-03-27 12:44:35 +0000600# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000601#endif
602
drh69910da2009-03-27 12:32:54 +0000603#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000604static void DbUnlockNotify(void **apArg, int nArg){
605 int i;
606 for(i=0; i<nArg; i++){
607 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
608 SqliteDb *pDb = (SqliteDb *)apArg[i];
609 setTestUnlockNotifyVars(pDb->interp, i, nArg);
610 assert( pDb->pUnlockNotify);
611 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
612 Tcl_DecrRefCount(pDb->pUnlockNotify);
613 pDb->pUnlockNotify = 0;
614 }
615}
drh69910da2009-03-27 12:32:54 +0000616#endif
danielk1977404ca072009-03-16 13:19:36 +0000617
danielk197794eb6a12005-12-15 15:22:08 +0000618static void DbUpdateHandler(
619 void *p,
620 int op,
621 const char *zDb,
622 const char *zTbl,
623 sqlite_int64 rowid
624){
625 SqliteDb *pDb = (SqliteDb *)p;
626 Tcl_Obj *pCmd;
627
628 assert( pDb->pUpdateHook );
629 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
630
631 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
632 Tcl_IncrRefCount(pCmd);
633 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
634 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
635 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
636 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
637 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
638 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
639}
640
danielk19777cedc8d2004-06-10 10:50:08 +0000641static void tclCollateNeeded(
642 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000643 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000644 int enc,
645 const char *zName
646){
647 SqliteDb *pDb = (SqliteDb *)pCtx;
648 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
649 Tcl_IncrRefCount(pScript);
650 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
651 Tcl_EvalObjEx(pDb->interp, pScript, 0);
652 Tcl_DecrRefCount(pScript);
653}
654
drhaa940ea2004-01-15 02:44:03 +0000655/*
danielk19770202b292004-06-09 09:55:16 +0000656** This routine is called to evaluate an SQL collation function implemented
657** using TCL script.
658*/
659static int tclSqlCollate(
660 void *pCtx,
661 int nA,
662 const void *zA,
663 int nB,
664 const void *zB
665){
666 SqlCollate *p = (SqlCollate *)pCtx;
667 Tcl_Obj *pCmd;
668
669 pCmd = Tcl_NewStringObj(p->zScript, -1);
670 Tcl_IncrRefCount(pCmd);
671 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
672 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000673 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000674 Tcl_DecrRefCount(pCmd);
675 return (atoi(Tcl_GetStringResult(p->interp)));
676}
677
678/*
drhcabb0812002-09-14 13:47:32 +0000679** This routine is called to evaluate an SQL function implemented
680** using TCL script.
681*/
drhfb7e7652005-01-24 00:28:42 +0000682static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000683 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000684 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000685 int i;
686 int rc;
687
drhd1e47332005-06-26 17:55:33 +0000688 if( argc==0 ){
689 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
690 ** script object directly. This allows the TCL compiler to generate
691 ** bytecode for the command on the first invocation and thus make
692 ** subsequent invocations much faster. */
693 pCmd = p->pScript;
694 Tcl_IncrRefCount(pCmd);
695 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
696 Tcl_DecrRefCount(pCmd);
697 }else{
698 /* If there are arguments to the function, make a shallow copy of the
699 ** script object, lappend the arguments, then evaluate the copy.
700 **
701 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
702 ** The new Tcl_Obj contains pointers to the original list elements.
703 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
704 ** of the list to tclCmdNameType, that alternate representation will
705 ** be preserved and reused on the next invocation.
706 */
707 Tcl_Obj **aArg;
708 int nArg;
709 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
710 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
711 return;
712 }
713 pCmd = Tcl_NewListObj(nArg, aArg);
714 Tcl_IncrRefCount(pCmd);
715 for(i=0; i<argc; i++){
716 sqlite3_value *pIn = argv[i];
717 Tcl_Obj *pVal;
718
719 /* Set pVal to contain the i'th column of this row. */
720 switch( sqlite3_value_type(pIn) ){
721 case SQLITE_BLOB: {
722 int bytes = sqlite3_value_bytes(pIn);
723 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
724 break;
725 }
726 case SQLITE_INTEGER: {
727 sqlite_int64 v = sqlite3_value_int64(pIn);
728 if( v>=-2147483647 && v<=2147483647 ){
729 pVal = Tcl_NewIntObj(v);
730 }else{
731 pVal = Tcl_NewWideIntObj(v);
732 }
733 break;
734 }
735 case SQLITE_FLOAT: {
736 double r = sqlite3_value_double(pIn);
737 pVal = Tcl_NewDoubleObj(r);
738 break;
739 }
740 case SQLITE_NULL: {
741 pVal = Tcl_NewStringObj("", 0);
742 break;
743 }
744 default: {
745 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000746 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000747 break;
748 }
749 }
750 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
751 if( rc ){
752 Tcl_DecrRefCount(pCmd);
753 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
754 return;
755 }
danielk197751ad0ec2004-05-24 12:39:02 +0000756 }
drhd1e47332005-06-26 17:55:33 +0000757 if( !p->useEvalObjv ){
758 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
759 ** is a list without a string representation. To prevent this from
760 ** happening, make sure pCmd has a valid string representation */
761 Tcl_GetString(pCmd);
762 }
763 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
764 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000765 }
danielk1977562e8d32005-05-20 09:40:55 +0000766
drhc7f269d2005-05-05 10:30:29 +0000767 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000768 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000769 }else{
drhc7f269d2005-05-05 10:30:29 +0000770 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
771 int n;
772 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000773 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000774 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000775 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000776 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000777 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000778 data = Tcl_GetByteArrayFromObj(pVar, &n);
779 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000780 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000781 Tcl_GetIntFromObj(0, pVar, &n);
782 sqlite3_result_int(context, n);
783 }else if( c=='d' && strcmp(zType,"double")==0 ){
784 double r;
785 Tcl_GetDoubleFromObj(0, pVar, &r);
786 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +0000787 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
788 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000789 Tcl_WideInt v;
790 Tcl_GetWideIntFromObj(0, pVar, &v);
791 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000792 }else{
danielk197700fd9572005-12-07 06:27:43 +0000793 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
794 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000795 }
drhcabb0812002-09-14 13:47:32 +0000796 }
797}
drh895d7472004-08-20 16:02:39 +0000798
drhe22a3342003-04-22 20:30:37 +0000799#ifndef SQLITE_OMIT_AUTHORIZATION
800/*
801** This is the authentication function. It appends the authentication
802** type code and the two arguments to zCmd[] then invokes the result
803** on the interpreter. The reply is examined to determine if the
804** authentication fails or succeeds.
805*/
806static int auth_callback(
807 void *pArg,
808 int code,
809 const char *zArg1,
810 const char *zArg2,
811 const char *zArg3,
812 const char *zArg4
813){
814 char *zCode;
815 Tcl_DString str;
816 int rc;
817 const char *zReply;
818 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +0000819 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +0000820
821 switch( code ){
822 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
823 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
824 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
825 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
826 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
827 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
828 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
829 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
830 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
831 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
832 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
833 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
834 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
835 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
836 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
837 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
838 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
839 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
840 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
841 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
842 case SQLITE_READ : zCode="SQLITE_READ"; break;
843 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
844 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
845 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000846 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
847 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000848 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000849 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000850 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000851 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
852 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000853 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +0000854 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drhe22a3342003-04-22 20:30:37 +0000855 default : zCode="????"; break;
856 }
857 Tcl_DStringInit(&str);
858 Tcl_DStringAppend(&str, pDb->zAuth, -1);
859 Tcl_DStringAppendElement(&str, zCode);
860 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
861 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
862 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
863 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
864 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
865 Tcl_DStringFree(&str);
866 zReply = Tcl_GetStringResult(pDb->interp);
867 if( strcmp(zReply,"SQLITE_OK")==0 ){
868 rc = SQLITE_OK;
869 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
870 rc = SQLITE_DENY;
871 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
872 rc = SQLITE_IGNORE;
873 }else{
874 rc = 999;
875 }
876 return rc;
877}
878#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000879
880/*
danielk1977ef2cb632004-05-29 02:37:19 +0000881** zText is a pointer to text obtained via an sqlite3_result_text()
882** or similar interface. This routine returns a Tcl string object,
883** reference count set to 0, containing the text. If a translation
884** between iso8859 and UTF-8 is required, it is preformed.
885*/
886static Tcl_Obj *dbTextToObj(char const *zText){
887 Tcl_Obj *pVal;
888#ifdef UTF_TRANSLATION_NEEDED
889 Tcl_DString dCol;
890 Tcl_DStringInit(&dCol);
891 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
892 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
893 Tcl_DStringFree(&dCol);
894#else
895 pVal = Tcl_NewStringObj(zText, -1);
896#endif
897 return pVal;
898}
899
900/*
tpoindex1067fe12004-12-17 15:41:11 +0000901** This routine reads a line of text from FILE in, stores
902** the text in memory obtained from malloc() and returns a pointer
903** to the text. NULL is returned at end of file, or if malloc()
904** fails.
905**
906** The interface is like "readline" but no command-line editing
907** is done.
908**
909** copied from shell.c from '.import' command
910*/
911static char *local_getline(char *zPrompt, FILE *in){
912 char *zLine;
913 int nLine;
914 int n;
915 int eol;
916
917 nLine = 100;
918 zLine = malloc( nLine );
919 if( zLine==0 ) return 0;
920 n = 0;
921 eol = 0;
922 while( !eol ){
923 if( n+100>nLine ){
924 nLine = nLine*2 + 100;
925 zLine = realloc(zLine, nLine);
926 if( zLine==0 ) return 0;
927 }
928 if( fgets(&zLine[n], nLine - n, in)==0 ){
929 if( n==0 ){
930 free(zLine);
931 return 0;
932 }
933 zLine[n] = 0;
934 eol = 1;
935 break;
936 }
937 while( zLine[n] ){ n++; }
938 if( n>0 && zLine[n-1]=='\n' ){
939 n--;
940 zLine[n] = 0;
941 eol = 1;
942 }
943 }
944 zLine = realloc( zLine, n+1 );
945 return zLine;
946}
947
danielk19778e556522007-11-13 10:30:24 +0000948
949/*
dan4a4c11a2009-10-06 14:59:02 +0000950** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +0000951**
dan4a4c11a2009-10-06 14:59:02 +0000952** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +0000953**
dan4a4c11a2009-10-06 14:59:02 +0000954** It is invoked after evaluating the script SCRIPT to commit or rollback
955** the transaction or savepoint opened by the [transaction] command.
956*/
957static int DbTransPostCmd(
958 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
959 Tcl_Interp *interp, /* Tcl interpreter */
960 int result /* Result of evaluating SCRIPT */
961){
962 static const char *azEnd[] = {
963 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
964 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
965 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
966 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
967 };
968 SqliteDb *pDb = (SqliteDb*)data[0];
969 int rc = result;
970 const char *zEnd;
971
972 pDb->nTransaction--;
973 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
974
975 pDb->disableAuth++;
976 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
977 /* This is a tricky scenario to handle. The most likely cause of an
978 ** error is that the exec() above was an attempt to commit the
979 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
980 ** that an IO-error has occured. In either case, throw a Tcl exception
981 ** and try to rollback the transaction.
982 **
983 ** But it could also be that the user executed one or more BEGIN,
984 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
985 ** this method's logic. Not clear how this would be best handled.
986 */
987 if( rc!=TCL_ERROR ){
988 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
989 rc = TCL_ERROR;
990 }
991 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
992 }
993 pDb->disableAuth--;
994
995 return rc;
996}
997
998/*
999** Search the cache for a prepared-statement object that implements the
1000** first SQL statement in the buffer pointed to by parameter zIn. If
1001** no such prepared-statement can be found, allocate and prepare a new
1002** one. In either case, bind the current values of the relevant Tcl
1003** variables to any $var, :var or @var variables in the statement. Before
1004** returning, set *ppPreStmt to point to the prepared-statement object.
1005**
1006** Output parameter *pzOut is set to point to the next SQL statement in
1007** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1008** next statement.
1009**
1010** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1011** and an error message loaded into interpreter pDb->interp.
1012*/
1013static int dbPrepareAndBind(
1014 SqliteDb *pDb, /* Database object */
1015 char const *zIn, /* SQL to compile */
1016 char const **pzOut, /* OUT: Pointer to next SQL statement */
1017 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1018){
1019 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
1020 sqlite3_stmt *pStmt; /* Prepared statement object */
1021 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1022 int nSql; /* Length of zSql in bytes */
1023 int nVar; /* Number of variables in statement */
1024 int iParm = 0; /* Next free entry in apParm */
1025 int i;
1026 Tcl_Interp *interp = pDb->interp;
1027
1028 *ppPreStmt = 0;
1029
1030 /* Trim spaces from the start of zSql and calculate the remaining length. */
1031 while( isspace(zSql[0]) ){ zSql++; }
1032 nSql = strlen30(zSql);
1033
1034 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1035 int n = pPreStmt->nSql;
1036 if( nSql>=n
1037 && memcmp(pPreStmt->zSql, zSql, n)==0
1038 && (zSql[n]==0 || zSql[n-1]==';')
1039 ){
1040 pStmt = pPreStmt->pStmt;
1041 *pzOut = &zSql[pPreStmt->nSql];
1042
1043 /* When a prepared statement is found, unlink it from the
1044 ** cache list. It will later be added back to the beginning
1045 ** of the cache list in order to implement LRU replacement.
1046 */
1047 if( pPreStmt->pPrev ){
1048 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1049 }else{
1050 pDb->stmtList = pPreStmt->pNext;
1051 }
1052 if( pPreStmt->pNext ){
1053 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1054 }else{
1055 pDb->stmtLast = pPreStmt->pPrev;
1056 }
1057 pDb->nStmt--;
1058 nVar = sqlite3_bind_parameter_count(pStmt);
1059 break;
1060 }
1061 }
1062
1063 /* If no prepared statement was found. Compile the SQL text. Also allocate
1064 ** a new SqlPreparedStmt structure. */
1065 if( pPreStmt==0 ){
1066 int nByte;
1067
1068 if( SQLITE_OK!=sqlite3_prepare_v2(pDb->db, zSql, -1, &pStmt, pzOut) ){
1069 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1070 return TCL_ERROR;
1071 }
1072 if( pStmt==0 ){
1073 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1074 /* A compile-time error in the statement. */
1075 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1076 return TCL_ERROR;
1077 }else{
1078 /* The statement was a no-op. Continue to the next statement
1079 ** in the SQL string.
1080 */
1081 return TCL_OK;
1082 }
1083 }
1084
1085 assert( pPreStmt==0 );
1086 nVar = sqlite3_bind_parameter_count(pStmt);
1087 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1088 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1089 memset(pPreStmt, 0, nByte);
1090
1091 pPreStmt->pStmt = pStmt;
1092 pPreStmt->nSql = (*pzOut - zSql);
1093 pPreStmt->zSql = sqlite3_sql(pStmt);
1094 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
1095 }
1096 assert( pPreStmt );
1097 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1098 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1099
1100 /* Bind values to parameters that begin with $ or : */
1101 for(i=1; i<=nVar; i++){
1102 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1103 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1104 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1105 if( pVar ){
1106 int n;
1107 u8 *data;
1108 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1109 char c = zType[0];
1110 if( zVar[0]=='@' ||
1111 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1112 /* Load a BLOB type if the Tcl variable is a bytearray and
1113 ** it has no string representation or the host
1114 ** parameter name begins with "@". */
1115 data = Tcl_GetByteArrayFromObj(pVar, &n);
1116 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1117 Tcl_IncrRefCount(pVar);
1118 pPreStmt->apParm[iParm++] = pVar;
1119 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1120 Tcl_GetIntFromObj(interp, pVar, &n);
1121 sqlite3_bind_int(pStmt, i, n);
1122 }else if( c=='d' && strcmp(zType,"double")==0 ){
1123 double r;
1124 Tcl_GetDoubleFromObj(interp, pVar, &r);
1125 sqlite3_bind_double(pStmt, i, r);
1126 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1127 (c=='i' && strcmp(zType,"int")==0) ){
1128 Tcl_WideInt v;
1129 Tcl_GetWideIntFromObj(interp, pVar, &v);
1130 sqlite3_bind_int64(pStmt, i, v);
1131 }else{
1132 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1133 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1134 Tcl_IncrRefCount(pVar);
1135 pPreStmt->apParm[iParm++] = pVar;
1136 }
1137 }else{
1138 sqlite3_bind_null(pStmt, i);
1139 }
1140 }
1141 }
1142 pPreStmt->nParm = iParm;
1143 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001144
dan4a4c11a2009-10-06 14:59:02 +00001145 return TCL_OK;
1146}
1147
1148
1149/*
1150** Release a statement reference obtained by calling dbPrepareAndBind().
1151** There should be exactly one call to this function for each call to
1152** dbPrepareAndBind().
1153**
1154** If the discard parameter is non-zero, then the statement is deleted
1155** immediately. Otherwise it is added to the LRU list and may be returned
1156** by a subsequent call to dbPrepareAndBind().
1157*/
1158static void dbReleaseStmt(
1159 SqliteDb *pDb, /* Database handle */
1160 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1161 int discard /* True to delete (not cache) the pPreStmt */
1162){
1163 int i;
1164
1165 /* Free the bound string and blob parameters */
1166 for(i=0; i<pPreStmt->nParm; i++){
1167 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1168 }
1169 pPreStmt->nParm = 0;
1170
1171 if( pDb->maxStmt<=0 || discard ){
1172 /* If the cache is turned off, deallocated the statement */
1173 sqlite3_finalize(pPreStmt->pStmt);
1174 Tcl_Free((char *)pPreStmt);
1175 }else{
1176 /* Add the prepared statement to the beginning of the cache list. */
1177 pPreStmt->pNext = pDb->stmtList;
1178 pPreStmt->pPrev = 0;
1179 if( pDb->stmtList ){
1180 pDb->stmtList->pPrev = pPreStmt;
1181 }
1182 pDb->stmtList = pPreStmt;
1183 if( pDb->stmtLast==0 ){
1184 assert( pDb->nStmt==0 );
1185 pDb->stmtLast = pPreStmt;
1186 }else{
1187 assert( pDb->nStmt>0 );
1188 }
1189 pDb->nStmt++;
1190
1191 /* If we have too many statement in cache, remove the surplus from
1192 ** the end of the cache list. */
1193 while( pDb->nStmt>pDb->maxStmt ){
1194 sqlite3_finalize(pDb->stmtLast->pStmt);
1195 pDb->stmtLast = pDb->stmtLast->pPrev;
1196 Tcl_Free((char*)pDb->stmtLast->pNext);
1197 pDb->stmtLast->pNext = 0;
1198 pDb->nStmt--;
1199 }
1200 }
1201}
1202
1203/*
1204** Structure used with dbEvalXXX() functions:
1205**
1206** dbEvalInit()
1207** dbEvalStep()
1208** dbEvalFinalize()
1209** dbEvalRowInfo()
1210** dbEvalColumnValue()
1211*/
1212typedef struct DbEvalContext DbEvalContext;
1213struct DbEvalContext {
1214 SqliteDb *pDb; /* Database handle */
1215 Tcl_Obj *pSql; /* Object holding string zSql */
1216 const char *zSql; /* Remaining SQL to execute */
1217 SqlPreparedStmt *pPreStmt; /* Current statement */
1218 int nCol; /* Number of columns returned by pStmt */
1219 Tcl_Obj *pArray; /* Name of array variable */
1220 Tcl_Obj **apColName; /* Array of column names */
1221};
1222
1223/*
1224** Release any cache of column names currently held as part of
1225** the DbEvalContext structure passed as the first argument.
1226*/
1227static void dbReleaseColumnNames(DbEvalContext *p){
1228 if( p->apColName ){
1229 int i;
1230 for(i=0; i<p->nCol; i++){
1231 Tcl_DecrRefCount(p->apColName[i]);
1232 }
1233 Tcl_Free((char *)p->apColName);
1234 p->apColName = 0;
1235 }
1236 p->nCol = 0;
1237}
1238
1239/*
1240** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001241**
1242** If pArray is not NULL, then it contains the name of a Tcl array
1243** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001244** the names of the columns returned by the statement as part of each
1245** call to dbEvalStep(), in order from left to right. e.g. if the names
1246** of the returned columns are a, b and c, it does the equivalent of the
1247** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001248**
1249** set ${pArray}(*) {a b c}
1250*/
dan4a4c11a2009-10-06 14:59:02 +00001251static void dbEvalInit(
1252 DbEvalContext *p, /* Pointer to structure to initialize */
1253 SqliteDb *pDb, /* Database handle */
1254 Tcl_Obj *pSql, /* Object containing SQL script */
1255 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001256){
dan4a4c11a2009-10-06 14:59:02 +00001257 memset(p, 0, sizeof(DbEvalContext));
1258 p->pDb = pDb;
1259 p->zSql = Tcl_GetString(pSql);
1260 p->pSql = pSql;
1261 Tcl_IncrRefCount(pSql);
1262 if( pArray ){
1263 p->pArray = pArray;
1264 Tcl_IncrRefCount(pArray);
1265 }
1266}
danielk19778e556522007-11-13 10:30:24 +00001267
dan4a4c11a2009-10-06 14:59:02 +00001268/*
1269** Obtain information about the row that the DbEvalContext passed as the
1270** first argument currently points to.
1271*/
1272static void dbEvalRowInfo(
1273 DbEvalContext *p, /* Evaluation context */
1274 int *pnCol, /* OUT: Number of column names */
1275 Tcl_Obj ***papColName /* OUT: Array of column names */
1276){
danielk19778e556522007-11-13 10:30:24 +00001277 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001278 if( 0==p->apColName ){
1279 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1280 int i; /* Iterator variable */
1281 int nCol; /* Number of columns returned by pStmt */
1282 Tcl_Obj **apColName = 0; /* Array of column names */
1283
1284 p->nCol = nCol = sqlite3_column_count(pStmt);
1285 if( nCol>0 && (papColName || p->pArray) ){
1286 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1287 for(i=0; i<nCol; i++){
1288 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1289 Tcl_IncrRefCount(apColName[i]);
1290 }
1291 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001292 }
1293
1294 /* If results are being stored in an array variable, then create
1295 ** the array(*) entry for that array
1296 */
dan4a4c11a2009-10-06 14:59:02 +00001297 if( p->pArray ){
1298 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001299 Tcl_Obj *pColList = Tcl_NewObj();
1300 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001301
danielk19778e556522007-11-13 10:30:24 +00001302 for(i=0; i<nCol; i++){
1303 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1304 }
1305 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001306 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001307 Tcl_DecrRefCount(pStar);
1308 }
danielk19778e556522007-11-13 10:30:24 +00001309 }
1310
dan4a4c11a2009-10-06 14:59:02 +00001311 if( papColName ){
1312 *papColName = p->apColName;
1313 }
1314 if( pnCol ){
1315 *pnCol = p->nCol;
1316 }
1317}
1318
1319/*
1320** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1321** returned, then an error message is stored in the interpreter before
1322** returning.
1323**
1324** A return value of TCL_OK means there is a row of data available. The
1325** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1326** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1327** is returned, then the SQL script has finished executing and there are
1328** no further rows available. This is similar to SQLITE_DONE.
1329*/
1330static int dbEvalStep(DbEvalContext *p){
1331 while( p->zSql[0] || p->pPreStmt ){
1332 int rc;
1333 if( p->pPreStmt==0 ){
1334 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1335 if( rc!=TCL_OK ) return rc;
1336 }else{
1337 int rcs;
1338 SqliteDb *pDb = p->pDb;
1339 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1340 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1341
1342 rcs = sqlite3_step(pStmt);
1343 if( rcs==SQLITE_ROW ){
1344 return TCL_OK;
1345 }
1346 if( p->pArray ){
1347 dbEvalRowInfo(p, 0, 0);
1348 }
1349 rcs = sqlite3_reset(pStmt);
1350
1351 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1352 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
1353 dbReleaseColumnNames(p);
1354 p->pPreStmt = 0;
1355
1356 if( rcs!=SQLITE_OK ){
1357 /* If a run-time error occurs, report the error and stop reading
1358 ** the SQL. */
1359 Tcl_SetObjResult(pDb->interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1360 dbReleaseStmt(pDb, pPreStmt, 1);
1361 return TCL_ERROR;
1362 }else{
1363 dbReleaseStmt(pDb, pPreStmt, 0);
1364 }
1365 }
1366 }
1367
1368 /* Finished */
1369 return TCL_BREAK;
1370}
1371
1372/*
1373** Free all resources currently held by the DbEvalContext structure passed
1374** as the first argument. There should be exactly one call to this function
1375** for each call to dbEvalInit().
1376*/
1377static void dbEvalFinalize(DbEvalContext *p){
1378 if( p->pPreStmt ){
1379 sqlite3_reset(p->pPreStmt->pStmt);
1380 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1381 p->pPreStmt = 0;
1382 }
1383 if( p->pArray ){
1384 Tcl_DecrRefCount(p->pArray);
1385 p->pArray = 0;
1386 }
1387 Tcl_DecrRefCount(p->pSql);
1388 dbReleaseColumnNames(p);
1389}
1390
1391/*
1392** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1393** the value for the iCol'th column of the row currently pointed to by
1394** the DbEvalContext structure passed as the first argument.
1395*/
1396static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1397 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1398 switch( sqlite3_column_type(pStmt, iCol) ){
1399 case SQLITE_BLOB: {
1400 int bytes = sqlite3_column_bytes(pStmt, iCol);
1401 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1402 if( !zBlob ) bytes = 0;
1403 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1404 }
1405 case SQLITE_INTEGER: {
1406 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1407 if( v>=-2147483647 && v<=2147483647 ){
1408 return Tcl_NewIntObj(v);
1409 }else{
1410 return Tcl_NewWideIntObj(v);
1411 }
1412 }
1413 case SQLITE_FLOAT: {
1414 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1415 }
1416 case SQLITE_NULL: {
1417 return dbTextToObj(p->pDb->zNull);
1418 }
1419 }
1420
1421 return dbTextToObj((char *)sqlite3_column_text(pStmt, iCol));
1422}
1423
1424/*
1425** If using Tcl version 8.6 or greater, use the NR functions to avoid
1426** recursive evalution of scripts by the [db eval] and [db trans]
1427** commands. Even if the headers used while compiling the extension
1428** are 8.6 or newer, the code still tests the Tcl version at runtime.
1429** This allows stubs-enabled builds to be used with older Tcl libraries.
1430*/
1431#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001432# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001433static int DbUseNre(void){
1434 int major, minor;
1435 Tcl_GetVersion(&major, &minor, 0, 0);
1436 return( (major==8 && minor>=6) || major>8 );
1437}
1438#else
1439/*
1440** Compiling using headers earlier than 8.6. In this case NR cannot be
1441** used, so DbUseNre() to always return zero. Add #defines for the other
1442** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1443** even though the only invocations of them are within conditional blocks
1444** of the form:
1445**
1446** if( DbUseNre() ) { ... }
1447*/
drha2c8a952009-10-13 18:38:34 +00001448# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001449# define DbUseNre() 0
1450# define Tcl_NRAddCallback(a,b,c,d,e,f) 0
1451# define Tcl_NREvalObj(a,b,c) 0
1452# define Tcl_NRCreateCommand(a,b,c,d,e,f) 0
1453#endif
1454
1455/*
1456** This function is part of the implementation of the command:
1457**
1458** $db eval SQL ?ARRAYNAME? SCRIPT
1459*/
1460static int DbEvalNextCmd(
1461 ClientData data[], /* data[0] is the (DbEvalContext*) */
1462 Tcl_Interp *interp, /* Tcl interpreter */
1463 int result /* Result so far */
1464){
1465 int rc = result; /* Return code */
1466
1467 /* The first element of the data[] array is a pointer to a DbEvalContext
1468 ** structure allocated using Tcl_Alloc(). The second element of data[]
1469 ** is a pointer to a Tcl_Obj containing the script to run for each row
1470 ** returned by the queries encapsulated in data[0]. */
1471 DbEvalContext *p = (DbEvalContext *)data[0];
1472 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1473 Tcl_Obj *pArray = p->pArray;
1474
1475 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1476 int i;
1477 int nCol;
1478 Tcl_Obj **apColName;
1479 dbEvalRowInfo(p, &nCol, &apColName);
1480 for(i=0; i<nCol; i++){
1481 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1482 if( pArray==0 ){
1483 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1484 }else{
1485 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1486 }
1487 }
1488
1489 /* The required interpreter variables are now populated with the data
1490 ** from the current row. If using NRE, schedule callbacks to evaluate
1491 ** script pScript, then to invoke this function again to fetch the next
1492 ** row (or clean up if there is no next row or the script throws an
1493 ** exception). After scheduling the callbacks, return control to the
1494 ** caller.
1495 **
1496 ** If not using NRE, evaluate pScript directly and continue with the
1497 ** next iteration of this while(...) loop. */
1498 if( DbUseNre() ){
1499 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1500 return Tcl_NREvalObj(interp, pScript, 0);
1501 }else{
1502 rc = Tcl_EvalObjEx(interp, pScript, 0);
1503 }
1504 }
1505
1506 Tcl_DecrRefCount(pScript);
1507 dbEvalFinalize(p);
1508 Tcl_Free((char *)p);
1509
1510 if( rc==TCL_OK || rc==TCL_BREAK ){
1511 Tcl_ResetResult(interp);
1512 rc = TCL_OK;
1513 }
1514 return rc;
danielk19778e556522007-11-13 10:30:24 +00001515}
1516
tpoindex1067fe12004-12-17 15:41:11 +00001517/*
drh75897232000-05-29 14:26:00 +00001518** The "sqlite" command below creates a new Tcl command for each
1519** connection it opens to an SQLite database. This routine is invoked
1520** whenever one of those connection-specific commands is executed
1521** in Tcl. For example, if you run Tcl code like this:
1522**
drh9bb575f2004-09-06 17:24:11 +00001523** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001524** db1 close
1525**
1526** The first command opens a connection to the "my_database" database
1527** and calls that connection "db1". The second command causes this
1528** subroutine to be invoked.
1529*/
drh6d313162000-09-21 13:01:35 +00001530static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001531 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001532 int choice;
drh22fbcb82004-02-01 01:22:50 +00001533 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001534 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001535 "authorizer", "backup", "busy",
1536 "cache", "changes", "close",
1537 "collate", "collation_needed", "commit_hook",
1538 "complete", "copy", "enable_load_extension",
1539 "errorcode", "eval", "exists",
1540 "function", "incrblob", "interrupt",
1541 "last_insert_rowid", "nullvalue", "onecolumn",
1542 "profile", "progress", "rekey",
1543 "restore", "rollback_hook", "status",
1544 "timeout", "total_changes", "trace",
danielk1977404ca072009-03-16 13:19:36 +00001545 "transaction", "unlock_notify", "update_hook",
1546 "version", 0
drh6d313162000-09-21 13:01:35 +00001547 };
drh411995d2002-06-25 19:31:18 +00001548 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001549 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1550 DB_CACHE, DB_CHANGES, DB_CLOSE,
1551 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1552 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1553 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1554 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
1555 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
1556 DB_PROFILE, DB_PROGRESS, DB_REKEY,
1557 DB_RESTORE, DB_ROLLBACK_HOOK, DB_STATUS,
1558 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
danielk1977404ca072009-03-16 13:19:36 +00001559 DB_TRANSACTION, DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK,
1560 DB_VERSION,
drh6d313162000-09-21 13:01:35 +00001561 };
tpoindex1067fe12004-12-17 15:41:11 +00001562 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001563
1564 if( objc<2 ){
1565 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001566 return TCL_ERROR;
1567 }
drh411995d2002-06-25 19:31:18 +00001568 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001569 return TCL_ERROR;
1570 }
1571
drh411995d2002-06-25 19:31:18 +00001572 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001573
drhe22a3342003-04-22 20:30:37 +00001574 /* $db authorizer ?CALLBACK?
1575 **
1576 ** Invoke the given callback to authorize each SQL operation as it is
1577 ** compiled. 5 arguments are appended to the callback before it is
1578 ** invoked:
1579 **
1580 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1581 ** (2) First descriptive name (depends on authorization type)
1582 ** (3) Second descriptive name
1583 ** (4) Name of the database (ex: "main", "temp")
1584 ** (5) Name of trigger that is doing the access
1585 **
1586 ** The callback should return on of the following strings: SQLITE_OK,
1587 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1588 **
1589 ** If this method is invoked with no arguments, the current authorization
1590 ** callback string is returned.
1591 */
1592 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001593#ifdef SQLITE_OMIT_AUTHORIZATION
1594 Tcl_AppendResult(interp, "authorization not available in this build", 0);
1595 return TCL_ERROR;
1596#else
drhe22a3342003-04-22 20:30:37 +00001597 if( objc>3 ){
1598 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001599 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001600 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001601 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +00001602 Tcl_AppendResult(interp, pDb->zAuth, 0);
1603 }
1604 }else{
1605 char *zAuth;
1606 int len;
1607 if( pDb->zAuth ){
1608 Tcl_Free(pDb->zAuth);
1609 }
1610 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1611 if( zAuth && len>0 ){
1612 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001613 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001614 }else{
1615 pDb->zAuth = 0;
1616 }
drhe22a3342003-04-22 20:30:37 +00001617 if( pDb->zAuth ){
1618 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001619 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +00001620 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001621 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001622 }
drhe22a3342003-04-22 20:30:37 +00001623 }
drh1211de32004-07-26 12:24:22 +00001624#endif
drhe22a3342003-04-22 20:30:37 +00001625 break;
1626 }
1627
drhdc2c4912009-02-04 22:46:47 +00001628 /* $db backup ?DATABASE? FILENAME
1629 **
1630 ** Open or create a database file named FILENAME. Transfer the
1631 ** content of local database DATABASE (default: "main") into the
1632 ** FILENAME database.
1633 */
1634 case DB_BACKUP: {
1635 const char *zDestFile;
1636 const char *zSrcDb;
1637 sqlite3 *pDest;
1638 sqlite3_backup *pBackup;
1639
1640 if( objc==3 ){
1641 zSrcDb = "main";
1642 zDestFile = Tcl_GetString(objv[2]);
1643 }else if( objc==4 ){
1644 zSrcDb = Tcl_GetString(objv[2]);
1645 zDestFile = Tcl_GetString(objv[3]);
1646 }else{
1647 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1648 return TCL_ERROR;
1649 }
1650 rc = sqlite3_open(zDestFile, &pDest);
1651 if( rc!=SQLITE_OK ){
1652 Tcl_AppendResult(interp, "cannot open target database: ",
1653 sqlite3_errmsg(pDest), (char*)0);
1654 sqlite3_close(pDest);
1655 return TCL_ERROR;
1656 }
1657 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1658 if( pBackup==0 ){
1659 Tcl_AppendResult(interp, "backup failed: ",
1660 sqlite3_errmsg(pDest), (char*)0);
1661 sqlite3_close(pDest);
1662 return TCL_ERROR;
1663 }
1664 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1665 sqlite3_backup_finish(pBackup);
1666 if( rc==SQLITE_DONE ){
1667 rc = TCL_OK;
1668 }else{
1669 Tcl_AppendResult(interp, "backup failed: ",
1670 sqlite3_errmsg(pDest), (char*)0);
1671 rc = TCL_ERROR;
1672 }
1673 sqlite3_close(pDest);
1674 break;
1675 }
1676
drhbec3f402000-08-04 13:49:02 +00001677 /* $db busy ?CALLBACK?
1678 **
1679 ** Invoke the given callback if an SQL statement attempts to open
1680 ** a locked database file.
1681 */
drh6d313162000-09-21 13:01:35 +00001682 case DB_BUSY: {
1683 if( objc>3 ){
1684 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001685 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001686 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001687 if( pDb->zBusy ){
1688 Tcl_AppendResult(interp, pDb->zBusy, 0);
1689 }
1690 }else{
drh6d313162000-09-21 13:01:35 +00001691 char *zBusy;
1692 int len;
drhbec3f402000-08-04 13:49:02 +00001693 if( pDb->zBusy ){
1694 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001695 }
drh6d313162000-09-21 13:01:35 +00001696 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1697 if( zBusy && len>0 ){
1698 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001699 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001700 }else{
1701 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001702 }
1703 if( pDb->zBusy ){
1704 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001705 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001706 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001707 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001708 }
1709 }
drh6d313162000-09-21 13:01:35 +00001710 break;
1711 }
drhbec3f402000-08-04 13:49:02 +00001712
drhfb7e7652005-01-24 00:28:42 +00001713 /* $db cache flush
1714 ** $db cache size n
1715 **
1716 ** Flush the prepared statement cache, or set the maximum number of
1717 ** cached statements.
1718 */
1719 case DB_CACHE: {
1720 char *subCmd;
1721 int n;
1722
1723 if( objc<=2 ){
1724 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1725 return TCL_ERROR;
1726 }
1727 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1728 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1729 if( objc!=3 ){
1730 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1731 return TCL_ERROR;
1732 }else{
1733 flushStmtCache( pDb );
1734 }
1735 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1736 if( objc!=4 ){
1737 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1738 return TCL_ERROR;
1739 }else{
1740 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1741 Tcl_AppendResult( interp, "cannot convert \"",
1742 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1743 return TCL_ERROR;
1744 }else{
1745 if( n<0 ){
1746 flushStmtCache( pDb );
1747 n = 0;
1748 }else if( n>MAX_PREPARED_STMTS ){
1749 n = MAX_PREPARED_STMTS;
1750 }
1751 pDb->maxStmt = n;
1752 }
1753 }
1754 }else{
1755 Tcl_AppendResult( interp, "bad option \"",
danielk1977191fadc2007-10-23 08:17:48 +00001756 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
drhfb7e7652005-01-24 00:28:42 +00001757 return TCL_ERROR;
1758 }
1759 break;
1760 }
1761
danielk1977b28af712004-06-21 06:50:26 +00001762 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001763 **
1764 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001765 ** the most recent INSERT, UPDATE or DELETE statement, not including
1766 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001767 */
1768 case DB_CHANGES: {
1769 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001770 if( objc!=2 ){
1771 Tcl_WrongNumArgs(interp, 2, objv, "");
1772 return TCL_ERROR;
1773 }
drhc8d30ac2002-04-12 10:08:59 +00001774 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001775 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001776 break;
1777 }
1778
drh75897232000-05-29 14:26:00 +00001779 /* $db close
1780 **
1781 ** Shutdown the database
1782 */
drh6d313162000-09-21 13:01:35 +00001783 case DB_CLOSE: {
1784 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1785 break;
1786 }
drh75897232000-05-29 14:26:00 +00001787
drh0f14e2e2004-06-29 12:39:08 +00001788 /*
1789 ** $db collate NAME SCRIPT
1790 **
1791 ** Create a new SQL collation function called NAME. Whenever
1792 ** that function is called, invoke SCRIPT to evaluate the function.
1793 */
1794 case DB_COLLATE: {
1795 SqlCollate *pCollate;
1796 char *zName;
1797 char *zScript;
1798 int nScript;
1799 if( objc!=4 ){
1800 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1801 return TCL_ERROR;
1802 }
1803 zName = Tcl_GetStringFromObj(objv[2], 0);
1804 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1805 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1806 if( pCollate==0 ) return TCL_ERROR;
1807 pCollate->interp = interp;
1808 pCollate->pNext = pDb->pCollate;
1809 pCollate->zScript = (char*)&pCollate[1];
1810 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001811 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001812 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1813 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001814 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001815 return TCL_ERROR;
1816 }
1817 break;
1818 }
1819
1820 /*
1821 ** $db collation_needed SCRIPT
1822 **
1823 ** Create a new SQL collation function called NAME. Whenever
1824 ** that function is called, invoke SCRIPT to evaluate the function.
1825 */
1826 case DB_COLLATION_NEEDED: {
1827 if( objc!=3 ){
1828 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1829 return TCL_ERROR;
1830 }
1831 if( pDb->pCollateNeeded ){
1832 Tcl_DecrRefCount(pDb->pCollateNeeded);
1833 }
1834 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1835 Tcl_IncrRefCount(pDb->pCollateNeeded);
1836 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1837 break;
1838 }
1839
drh19e2d372005-08-29 23:00:03 +00001840 /* $db commit_hook ?CALLBACK?
1841 **
1842 ** Invoke the given callback just before committing every SQL transaction.
1843 ** If the callback throws an exception or returns non-zero, then the
1844 ** transaction is aborted. If CALLBACK is an empty string, the callback
1845 ** is disabled.
1846 */
1847 case DB_COMMIT_HOOK: {
1848 if( objc>3 ){
1849 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1850 return TCL_ERROR;
1851 }else if( objc==2 ){
1852 if( pDb->zCommit ){
1853 Tcl_AppendResult(interp, pDb->zCommit, 0);
1854 }
1855 }else{
1856 char *zCommit;
1857 int len;
1858 if( pDb->zCommit ){
1859 Tcl_Free(pDb->zCommit);
1860 }
1861 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1862 if( zCommit && len>0 ){
1863 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001864 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001865 }else{
1866 pDb->zCommit = 0;
1867 }
1868 if( pDb->zCommit ){
1869 pDb->interp = interp;
1870 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1871 }else{
1872 sqlite3_commit_hook(pDb->db, 0, 0);
1873 }
1874 }
1875 break;
1876 }
1877
drh75897232000-05-29 14:26:00 +00001878 /* $db complete SQL
1879 **
1880 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1881 ** additional lines of input are needed. This is similar to the
1882 ** built-in "info complete" command of Tcl.
1883 */
drh6d313162000-09-21 13:01:35 +00001884 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00001885#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00001886 Tcl_Obj *pResult;
1887 int isComplete;
1888 if( objc!=3 ){
1889 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00001890 return TCL_ERROR;
1891 }
danielk19776f8a5032004-05-10 10:34:51 +00001892 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00001893 pResult = Tcl_GetObjResult(interp);
1894 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00001895#endif
drh6d313162000-09-21 13:01:35 +00001896 break;
1897 }
drhdcd997e2003-01-31 17:21:49 +00001898
drh19e2d372005-08-29 23:00:03 +00001899 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1900 **
1901 ** Copy data into table from filename, optionally using SEPARATOR
1902 ** as column separators. If a column contains a null string, or the
1903 ** value of NULLINDICATOR, a NULL is inserted for the column.
1904 ** conflict-algorithm is one of the sqlite conflict algorithms:
1905 ** rollback, abort, fail, ignore, replace
1906 ** On success, return the number of lines processed, not necessarily same
1907 ** as 'db changes' due to conflict-algorithm selected.
1908 **
1909 ** This code is basically an implementation/enhancement of
1910 ** the sqlite3 shell.c ".import" command.
1911 **
1912 ** This command usage is equivalent to the sqlite2.x COPY statement,
1913 ** which imports file data into a table using the PostgreSQL COPY file format:
1914 ** $db copy $conflit_algo $table_name $filename \t \\N
1915 */
1916 case DB_COPY: {
1917 char *zTable; /* Insert data into this table */
1918 char *zFile; /* The file from which to extract data */
1919 char *zConflict; /* The conflict algorithm to use */
1920 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00001921 int nCol; /* Number of columns in the table */
1922 int nByte; /* Number of bytes in an SQL string */
1923 int i, j; /* Loop counters */
1924 int nSep; /* Number of bytes in zSep[] */
1925 int nNull; /* Number of bytes in zNull[] */
1926 char *zSql; /* An SQL statement */
1927 char *zLine; /* A single line of input from the file */
1928 char **azCol; /* zLine[] broken up into columns */
1929 char *zCommit; /* How to commit changes */
1930 FILE *in; /* The input file */
1931 int lineno = 0; /* Line number of input file */
1932 char zLineNum[80]; /* Line number print buffer */
1933 Tcl_Obj *pResult; /* interp result */
1934
1935 char *zSep;
1936 char *zNull;
1937 if( objc<5 || objc>7 ){
1938 Tcl_WrongNumArgs(interp, 2, objv,
1939 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1940 return TCL_ERROR;
1941 }
1942 if( objc>=6 ){
1943 zSep = Tcl_GetStringFromObj(objv[5], 0);
1944 }else{
1945 zSep = "\t";
1946 }
1947 if( objc>=7 ){
1948 zNull = Tcl_GetStringFromObj(objv[6], 0);
1949 }else{
1950 zNull = "";
1951 }
1952 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1953 zTable = Tcl_GetStringFromObj(objv[3], 0);
1954 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00001955 nSep = strlen30(zSep);
1956 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00001957 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00001958 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00001959 return TCL_ERROR;
1960 }
drh3e59c012008-09-23 10:12:13 +00001961 if(strcmp(zConflict, "rollback") != 0 &&
1962 strcmp(zConflict, "abort" ) != 0 &&
1963 strcmp(zConflict, "fail" ) != 0 &&
1964 strcmp(zConflict, "ignore" ) != 0 &&
1965 strcmp(zConflict, "replace" ) != 0 ) {
drh19e2d372005-08-29 23:00:03 +00001966 Tcl_AppendResult(interp, "Error: \"", zConflict,
1967 "\", conflict-algorithm must be one of: rollback, "
1968 "abort, fail, ignore, or replace", 0);
1969 return TCL_ERROR;
1970 }
1971 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1972 if( zSql==0 ){
1973 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1974 return TCL_ERROR;
1975 }
drh4f21c4a2008-12-10 22:15:00 +00001976 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00001977 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001978 sqlite3_free(zSql);
1979 if( rc ){
1980 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1981 nCol = 0;
1982 }else{
1983 nCol = sqlite3_column_count(pStmt);
1984 }
1985 sqlite3_finalize(pStmt);
1986 if( nCol==0 ) {
1987 return TCL_ERROR;
1988 }
1989 zSql = malloc( nByte + 50 + nCol*2 );
1990 if( zSql==0 ) {
1991 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1992 return TCL_ERROR;
1993 }
1994 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1995 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00001996 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00001997 for(i=1; i<nCol; i++){
1998 zSql[j++] = ',';
1999 zSql[j++] = '?';
2000 }
2001 zSql[j++] = ')';
2002 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002003 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002004 free(zSql);
2005 if( rc ){
2006 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2007 sqlite3_finalize(pStmt);
2008 return TCL_ERROR;
2009 }
2010 in = fopen(zFile, "rb");
2011 if( in==0 ){
2012 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2013 sqlite3_finalize(pStmt);
2014 return TCL_ERROR;
2015 }
2016 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2017 if( azCol==0 ) {
2018 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00002019 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002020 return TCL_ERROR;
2021 }
drh37527852006-03-16 16:19:56 +00002022 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002023 zCommit = "COMMIT";
2024 while( (zLine = local_getline(0, in))!=0 ){
2025 char *z;
2026 i = 0;
2027 lineno++;
2028 azCol[0] = zLine;
2029 for(i=0, z=zLine; *z; z++){
2030 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2031 *z = 0;
2032 i++;
2033 if( i<nCol ){
2034 azCol[i] = &z[nSep];
2035 z += nSep-1;
2036 }
2037 }
2038 }
2039 if( i+1!=nCol ){
2040 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002041 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002042 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002043 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002044 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002045 "Error: %s line %d: expected %d columns of data but found %d",
2046 zFile, lineno, nCol, i+1);
2047 Tcl_AppendResult(interp, zErr, 0);
2048 free(zErr);
2049 }
drh19e2d372005-08-29 23:00:03 +00002050 zCommit = "ROLLBACK";
2051 break;
2052 }
2053 for(i=0; i<nCol; i++){
2054 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002055 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
drh4f21c4a2008-12-10 22:15:00 +00002056 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002057 ){
drh19e2d372005-08-29 23:00:03 +00002058 sqlite3_bind_null(pStmt, i+1);
2059 }else{
2060 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2061 }
2062 }
2063 sqlite3_step(pStmt);
2064 rc = sqlite3_reset(pStmt);
2065 free(zLine);
2066 if( rc!=SQLITE_OK ){
2067 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
2068 zCommit = "ROLLBACK";
2069 break;
2070 }
2071 }
2072 free(azCol);
2073 fclose(in);
2074 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002075 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002076
2077 if( zCommit[0] == 'C' ){
2078 /* success, set result as number of lines processed */
2079 pResult = Tcl_GetObjResult(interp);
2080 Tcl_SetIntObj(pResult, lineno);
2081 rc = TCL_OK;
2082 }else{
2083 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002084 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00002085 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
2086 rc = TCL_ERROR;
2087 }
2088 break;
2089 }
2090
drhdcd997e2003-01-31 17:21:49 +00002091 /*
drh41449052006-07-06 17:08:48 +00002092 ** $db enable_load_extension BOOLEAN
2093 **
2094 ** Turn the extension loading feature on or off. It if off by
2095 ** default.
2096 */
2097 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002098#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002099 int onoff;
2100 if( objc!=3 ){
2101 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2102 return TCL_ERROR;
2103 }
2104 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2105 return TCL_ERROR;
2106 }
2107 sqlite3_enable_load_extension(pDb->db, onoff);
2108 break;
drhf533acc2006-12-19 18:57:11 +00002109#else
2110 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2111 0);
2112 return TCL_ERROR;
2113#endif
drh41449052006-07-06 17:08:48 +00002114 }
2115
2116 /*
drhdcd997e2003-01-31 17:21:49 +00002117 ** $db errorcode
2118 **
2119 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002120 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002121 */
2122 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002123 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002124 break;
2125 }
dan4a4c11a2009-10-06 14:59:02 +00002126
2127 /*
2128 ** $db exists $sql
2129 ** $db onecolumn $sql
2130 **
2131 ** The onecolumn method is the equivalent of:
2132 ** lindex [$db eval $sql] 0
2133 */
2134 case DB_EXISTS:
2135 case DB_ONECOLUMN: {
2136 DbEvalContext sEval;
2137 if( objc!=3 ){
2138 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2139 return TCL_ERROR;
2140 }
2141
2142 dbEvalInit(&sEval, pDb, objv[2], 0);
2143 rc = dbEvalStep(&sEval);
2144 if( choice==DB_ONECOLUMN ){
2145 if( rc==TCL_OK ){
2146 Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
2147 }
2148 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2149 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
2150 }
2151 dbEvalFinalize(&sEval);
2152
2153 if( rc==TCL_BREAK ){
2154 rc = TCL_OK;
2155 }
2156 break;
2157 }
drh75897232000-05-29 14:26:00 +00002158
2159 /*
drh895d7472004-08-20 16:02:39 +00002160 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002161 **
2162 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002163 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002164 ** If "array" and "code" are omitted, then no callback is every invoked.
2165 ** If "array" is an empty string, then the values are placed in variables
2166 ** that have the same name as the fields extracted by the query.
2167 */
dan4a4c11a2009-10-06 14:59:02 +00002168 case DB_EVAL: {
2169 if( objc<3 || objc>5 ){
2170 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2171 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002172 }
dan4a4c11a2009-10-06 14:59:02 +00002173
drh92febd92004-08-20 18:34:20 +00002174 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002175 DbEvalContext sEval;
2176 Tcl_Obj *pRet = Tcl_NewObj();
2177 Tcl_IncrRefCount(pRet);
2178 dbEvalInit(&sEval, pDb, objv[2], 0);
2179 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2180 int i;
2181 int nCol;
2182 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002183 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002184 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002185 }
2186 }
dan4a4c11a2009-10-06 14:59:02 +00002187 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002188 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002189 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002190 rc = TCL_OK;
2191 }
drh1807ce32004-09-07 13:20:35 +00002192 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002193 }else{
2194 ClientData cd[2];
2195 DbEvalContext *p;
2196 Tcl_Obj *pArray = 0;
2197 Tcl_Obj *pScript;
2198
2199 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2200 pArray = objv[3];
2201 }
2202 pScript = objv[objc-1];
2203 Tcl_IncrRefCount(pScript);
2204
2205 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2206 dbEvalInit(p, pDb, objv[2], pArray);
2207
2208 cd[0] = (void *)p;
2209 cd[1] = (void *)pScript;
2210 rc = DbEvalNextCmd(cd, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002211 }
danielk197730ccda12004-05-27 12:11:31 +00002212 break;
2213 }
drhbec3f402000-08-04 13:49:02 +00002214
2215 /*
drhe3602be2008-09-09 12:31:33 +00002216 ** $db function NAME [-argcount N] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002217 **
2218 ** Create a new SQL function called NAME. Whenever that function is
2219 ** called, invoke SCRIPT to evaluate the function.
2220 */
2221 case DB_FUNCTION: {
2222 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002223 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002224 char *zName;
drhe3602be2008-09-09 12:31:33 +00002225 int nArg = -1;
2226 if( objc==6 ){
2227 const char *z = Tcl_GetString(objv[3]);
drh4f21c4a2008-12-10 22:15:00 +00002228 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002229 if( n>2 && strncmp(z, "-argcount",n)==0 ){
2230 if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
2231 if( nArg<0 ){
2232 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2233 (char*)0);
2234 return TCL_ERROR;
2235 }
2236 }
2237 pScript = objv[5];
2238 }else if( objc!=4 ){
2239 Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
drhcabb0812002-09-14 13:47:32 +00002240 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002241 }else{
2242 pScript = objv[3];
drhcabb0812002-09-14 13:47:32 +00002243 }
2244 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002245 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002246 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002247 if( pFunc->pScript ){
2248 Tcl_DecrRefCount(pFunc->pScript);
2249 }
2250 pFunc->pScript = pScript;
2251 Tcl_IncrRefCount(pScript);
2252 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
drhe3602be2008-09-09 12:31:33 +00002253 rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00002254 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002255 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002256 rc = TCL_ERROR;
2257 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002258 }
drhcabb0812002-09-14 13:47:32 +00002259 break;
2260 }
2261
2262 /*
danielk19778cbadb02007-05-03 16:31:26 +00002263 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002264 */
2265 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002266#ifdef SQLITE_OMIT_INCRBLOB
2267 Tcl_AppendResult(interp, "incrblob not available in this build", 0);
2268 return TCL_ERROR;
2269#else
danielk19778cbadb02007-05-03 16:31:26 +00002270 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002271 const char *zDb = "main";
2272 const char *zTable;
2273 const char *zColumn;
2274 sqlite_int64 iRow;
2275
danielk19778cbadb02007-05-03 16:31:26 +00002276 /* Check for the -readonly option */
2277 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2278 isReadonly = 1;
2279 }
2280
2281 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2282 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002283 return TCL_ERROR;
2284 }
2285
danielk19778cbadb02007-05-03 16:31:26 +00002286 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002287 zDb = Tcl_GetString(objv[2]);
2288 }
2289 zTable = Tcl_GetString(objv[objc-3]);
2290 zColumn = Tcl_GetString(objv[objc-2]);
2291 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2292
2293 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002294 rc = createIncrblobChannel(
2295 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
2296 );
danielk1977b4e9af92007-05-01 17:49:49 +00002297 }
danielk197732a0d8b2007-05-04 19:03:02 +00002298#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002299 break;
2300 }
2301
2302 /*
drhf11bded2006-07-17 00:02:44 +00002303 ** $db interrupt
2304 **
2305 ** Interrupt the execution of the inner-most SQL interpreter. This
2306 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2307 */
2308 case DB_INTERRUPT: {
2309 sqlite3_interrupt(pDb->db);
2310 break;
2311 }
2312
2313 /*
drh19e2d372005-08-29 23:00:03 +00002314 ** $db nullvalue ?STRING?
2315 **
2316 ** Change text used when a NULL comes back from the database. If ?STRING?
2317 ** is not present, then the current string used for NULL is returned.
2318 ** If STRING is present, then STRING is returned.
2319 **
2320 */
2321 case DB_NULLVALUE: {
2322 if( objc!=2 && objc!=3 ){
2323 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2324 return TCL_ERROR;
2325 }
2326 if( objc==3 ){
2327 int len;
2328 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2329 if( pDb->zNull ){
2330 Tcl_Free(pDb->zNull);
2331 }
2332 if( zNull && len>0 ){
2333 pDb->zNull = Tcl_Alloc( len + 1 );
2334 strncpy(pDb->zNull, zNull, len);
2335 pDb->zNull[len] = '\0';
2336 }else{
2337 pDb->zNull = 0;
2338 }
2339 }
2340 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
2341 break;
2342 }
2343
2344 /*
drhaf9ff332002-01-16 21:00:27 +00002345 ** $db last_insert_rowid
2346 **
2347 ** Return an integer which is the ROWID for the most recent insert.
2348 */
2349 case DB_LAST_INSERT_ROWID: {
2350 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002351 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002352 if( objc!=2 ){
2353 Tcl_WrongNumArgs(interp, 2, objv, "");
2354 return TCL_ERROR;
2355 }
danielk19776f8a5032004-05-10 10:34:51 +00002356 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002357 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002358 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002359 break;
2360 }
2361
2362 /*
dan4a4c11a2009-10-06 14:59:02 +00002363 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002364 */
drh1807ce32004-09-07 13:20:35 +00002365
2366 /* $db progress ?N CALLBACK?
2367 **
2368 ** Invoke the given callback every N virtual machine opcodes while executing
2369 ** queries.
2370 */
2371 case DB_PROGRESS: {
2372 if( objc==2 ){
2373 if( pDb->zProgress ){
2374 Tcl_AppendResult(interp, pDb->zProgress, 0);
2375 }
2376 }else if( objc==4 ){
2377 char *zProgress;
2378 int len;
2379 int N;
2380 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002381 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002382 };
2383 if( pDb->zProgress ){
2384 Tcl_Free(pDb->zProgress);
2385 }
2386 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2387 if( zProgress && len>0 ){
2388 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002389 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002390 }else{
2391 pDb->zProgress = 0;
2392 }
2393#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2394 if( pDb->zProgress ){
2395 pDb->interp = interp;
2396 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2397 }else{
2398 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2399 }
2400#endif
2401 }else{
2402 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002403 return TCL_ERROR;
2404 }
drh5d9d7572003-08-19 14:31:01 +00002405 break;
2406 }
2407
drh19e2d372005-08-29 23:00:03 +00002408 /* $db profile ?CALLBACK?
2409 **
2410 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2411 ** that has run. The text of the SQL and the amount of elapse time are
2412 ** appended to CALLBACK before the script is run.
2413 */
2414 case DB_PROFILE: {
2415 if( objc>3 ){
2416 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2417 return TCL_ERROR;
2418 }else if( objc==2 ){
2419 if( pDb->zProfile ){
2420 Tcl_AppendResult(interp, pDb->zProfile, 0);
2421 }
2422 }else{
2423 char *zProfile;
2424 int len;
2425 if( pDb->zProfile ){
2426 Tcl_Free(pDb->zProfile);
2427 }
2428 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2429 if( zProfile && len>0 ){
2430 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002431 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002432 }else{
2433 pDb->zProfile = 0;
2434 }
2435#ifndef SQLITE_OMIT_TRACE
2436 if( pDb->zProfile ){
2437 pDb->interp = interp;
2438 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2439 }else{
2440 sqlite3_profile(pDb->db, 0, 0);
2441 }
2442#endif
2443 }
2444 break;
2445 }
2446
drh5d9d7572003-08-19 14:31:01 +00002447 /*
drh22fbcb82004-02-01 01:22:50 +00002448 ** $db rekey KEY
2449 **
2450 ** Change the encryption key on the currently open database.
2451 */
2452 case DB_REKEY: {
2453 int nKey;
2454 void *pKey;
2455 if( objc!=3 ){
2456 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2457 return TCL_ERROR;
2458 }
2459 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00002460#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00002461 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002462 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00002463 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002464 rc = TCL_ERROR;
2465 }
2466#endif
2467 break;
2468 }
2469
drhdc2c4912009-02-04 22:46:47 +00002470 /* $db restore ?DATABASE? FILENAME
2471 **
2472 ** Open a database file named FILENAME. Transfer the content
2473 ** of FILENAME into the local database DATABASE (default: "main").
2474 */
2475 case DB_RESTORE: {
2476 const char *zSrcFile;
2477 const char *zDestDb;
2478 sqlite3 *pSrc;
2479 sqlite3_backup *pBackup;
2480 int nTimeout = 0;
2481
2482 if( objc==3 ){
2483 zDestDb = "main";
2484 zSrcFile = Tcl_GetString(objv[2]);
2485 }else if( objc==4 ){
2486 zDestDb = Tcl_GetString(objv[2]);
2487 zSrcFile = Tcl_GetString(objv[3]);
2488 }else{
2489 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2490 return TCL_ERROR;
2491 }
2492 rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
2493 if( rc!=SQLITE_OK ){
2494 Tcl_AppendResult(interp, "cannot open source database: ",
2495 sqlite3_errmsg(pSrc), (char*)0);
2496 sqlite3_close(pSrc);
2497 return TCL_ERROR;
2498 }
2499 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2500 if( pBackup==0 ){
2501 Tcl_AppendResult(interp, "restore failed: ",
2502 sqlite3_errmsg(pDb->db), (char*)0);
2503 sqlite3_close(pSrc);
2504 return TCL_ERROR;
2505 }
2506 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2507 || rc==SQLITE_BUSY ){
2508 if( rc==SQLITE_BUSY ){
2509 if( nTimeout++ >= 3 ) break;
2510 sqlite3_sleep(100);
2511 }
2512 }
2513 sqlite3_backup_finish(pBackup);
2514 if( rc==SQLITE_DONE ){
2515 rc = TCL_OK;
2516 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2517 Tcl_AppendResult(interp, "restore failed: source database busy",
2518 (char*)0);
2519 rc = TCL_ERROR;
2520 }else{
2521 Tcl_AppendResult(interp, "restore failed: ",
2522 sqlite3_errmsg(pDb->db), (char*)0);
2523 rc = TCL_ERROR;
2524 }
2525 sqlite3_close(pSrc);
2526 break;
2527 }
2528
drh22fbcb82004-02-01 01:22:50 +00002529 /*
drhd1d38482008-10-07 23:46:38 +00002530 ** $db status (step|sort)
2531 **
2532 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2533 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2534 */
2535 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002536 int v;
2537 const char *zOp;
2538 if( objc!=3 ){
2539 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort)");
2540 return TCL_ERROR;
2541 }
2542 zOp = Tcl_GetString(objv[2]);
2543 if( strcmp(zOp, "step")==0 ){
2544 v = pDb->nStep;
2545 }else if( strcmp(zOp, "sort")==0 ){
2546 v = pDb->nSort;
2547 }else{
2548 Tcl_AppendResult(interp, "bad argument: should be step or sort",
2549 (char*)0);
2550 return TCL_ERROR;
2551 }
2552 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2553 break;
2554 }
2555
2556 /*
drhbec3f402000-08-04 13:49:02 +00002557 ** $db timeout MILLESECONDS
2558 **
2559 ** Delay for the number of milliseconds specified when a file is locked.
2560 */
drh6d313162000-09-21 13:01:35 +00002561 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002562 int ms;
drh6d313162000-09-21 13:01:35 +00002563 if( objc!=3 ){
2564 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002565 return TCL_ERROR;
2566 }
drh6d313162000-09-21 13:01:35 +00002567 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002568 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002569 break;
drh75897232000-05-29 14:26:00 +00002570 }
danielk197755c45f22005-04-03 23:54:43 +00002571
2572 /*
drh0f14e2e2004-06-29 12:39:08 +00002573 ** $db total_changes
2574 **
2575 ** Return the number of rows that were modified, inserted, or deleted
2576 ** since the database handle was created.
2577 */
2578 case DB_TOTAL_CHANGES: {
2579 Tcl_Obj *pResult;
2580 if( objc!=2 ){
2581 Tcl_WrongNumArgs(interp, 2, objv, "");
2582 return TCL_ERROR;
2583 }
2584 pResult = Tcl_GetObjResult(interp);
2585 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2586 break;
2587 }
2588
drhb5a20d32003-04-23 12:25:23 +00002589 /* $db trace ?CALLBACK?
2590 **
2591 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2592 ** that is executed. The text of the SQL is appended to CALLBACK before
2593 ** it is executed.
2594 */
2595 case DB_TRACE: {
2596 if( objc>3 ){
2597 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002598 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002599 }else if( objc==2 ){
2600 if( pDb->zTrace ){
2601 Tcl_AppendResult(interp, pDb->zTrace, 0);
2602 }
2603 }else{
2604 char *zTrace;
2605 int len;
2606 if( pDb->zTrace ){
2607 Tcl_Free(pDb->zTrace);
2608 }
2609 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2610 if( zTrace && len>0 ){
2611 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002612 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002613 }else{
2614 pDb->zTrace = 0;
2615 }
drh19e2d372005-08-29 23:00:03 +00002616#ifndef SQLITE_OMIT_TRACE
drhb5a20d32003-04-23 12:25:23 +00002617 if( pDb->zTrace ){
2618 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002619 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002620 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002621 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002622 }
drh19e2d372005-08-29 23:00:03 +00002623#endif
drhb5a20d32003-04-23 12:25:23 +00002624 }
2625 break;
2626 }
2627
drh3d214232005-08-02 12:21:08 +00002628 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2629 **
2630 ** Start a new transaction (if we are not already in the midst of a
2631 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2632 ** completes, either commit the transaction or roll it back if SCRIPT
2633 ** throws an exception. Or if no new transation was started, do nothing.
2634 ** pass the exception on up the stack.
2635 **
2636 ** This command was inspired by Dave Thomas's talk on Ruby at the
2637 ** 2005 O'Reilly Open Source Convention (OSCON).
2638 */
2639 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00002640 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00002641 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00002642 if( objc!=3 && objc!=4 ){
2643 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2644 return TCL_ERROR;
2645 }
danielk1977cd38d522009-01-02 17:33:46 +00002646
dan4a4c11a2009-10-06 14:59:02 +00002647 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00002648 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002649 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002650 };
2651 enum TTYPE_enum {
2652 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2653 };
2654 int ttype;
drhb5555e72005-08-02 17:15:14 +00002655 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002656 0, &ttype) ){
2657 return TCL_ERROR;
2658 }
2659 switch( (enum TTYPE_enum)ttype ){
2660 case TTYPE_DEFERRED: /* no-op */; break;
2661 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2662 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2663 }
drh3d214232005-08-02 12:21:08 +00002664 }
danielk1977cd38d522009-01-02 17:33:46 +00002665 pScript = objv[objc-1];
2666
dan4a4c11a2009-10-06 14:59:02 +00002667 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00002668 pDb->disableAuth++;
2669 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2670 pDb->disableAuth--;
2671 if( rc!=SQLITE_OK ){
2672 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2673 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00002674 }
danielk1977cd38d522009-01-02 17:33:46 +00002675 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00002676
dan4a4c11a2009-10-06 14:59:02 +00002677 /* If using NRE, schedule a callback to invoke the script pScript, then
2678 ** a second callback to commit (or rollback) the transaction or savepoint
2679 ** opened above. If not using NRE, evaluate the script directly, then
2680 ** call function DbTransPostCmd() to commit (or rollback) the transaction
2681 ** or savepoint. */
2682 if( DbUseNre() ){
2683 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
2684 Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00002685 }else{
dan4a4c11a2009-10-06 14:59:02 +00002686 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00002687 }
2688 break;
2689 }
2690
danielk197794eb6a12005-12-15 15:22:08 +00002691 /*
danielk1977404ca072009-03-16 13:19:36 +00002692 ** $db unlock_notify ?script?
2693 */
2694 case DB_UNLOCK_NOTIFY: {
2695#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2696 Tcl_AppendResult(interp, "unlock_notify not available in this build", 0);
2697 rc = TCL_ERROR;
2698#else
2699 if( objc!=2 && objc!=3 ){
2700 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2701 rc = TCL_ERROR;
2702 }else{
2703 void (*xNotify)(void **, int) = 0;
2704 void *pNotifyArg = 0;
2705
2706 if( pDb->pUnlockNotify ){
2707 Tcl_DecrRefCount(pDb->pUnlockNotify);
2708 pDb->pUnlockNotify = 0;
2709 }
2710
2711 if( objc==3 ){
2712 xNotify = DbUnlockNotify;
2713 pNotifyArg = (void *)pDb;
2714 pDb->pUnlockNotify = objv[2];
2715 Tcl_IncrRefCount(pDb->pUnlockNotify);
2716 }
2717
2718 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
2719 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2720 rc = TCL_ERROR;
2721 }
2722 }
2723#endif
2724 break;
2725 }
2726
2727 /*
danielk197794eb6a12005-12-15 15:22:08 +00002728 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002729 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002730 */
danielk197771fd80b2005-12-16 06:54:01 +00002731 case DB_UPDATE_HOOK:
2732 case DB_ROLLBACK_HOOK: {
2733
2734 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2735 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2736 */
2737 Tcl_Obj **ppHook;
2738 if( choice==DB_UPDATE_HOOK ){
2739 ppHook = &pDb->pUpdateHook;
2740 }else{
2741 ppHook = &pDb->pRollbackHook;
2742 }
2743
danielk197794eb6a12005-12-15 15:22:08 +00002744 if( objc!=2 && objc!=3 ){
2745 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2746 return TCL_ERROR;
2747 }
danielk197771fd80b2005-12-16 06:54:01 +00002748 if( *ppHook ){
2749 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002750 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002751 Tcl_DecrRefCount(*ppHook);
2752 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00002753 }
2754 }
2755 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002756 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00002757 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00002758 *ppHook = objv[2];
2759 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002760 }
2761 }
danielk197771fd80b2005-12-16 06:54:01 +00002762
2763 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2764 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
2765
danielk197794eb6a12005-12-15 15:22:08 +00002766 break;
2767 }
2768
danielk19774397de52005-01-12 12:44:03 +00002769 /* $db version
2770 **
2771 ** Return the version string for this database.
2772 */
2773 case DB_VERSION: {
2774 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2775 break;
2776 }
2777
tpoindex1067fe12004-12-17 15:41:11 +00002778
drh6d313162000-09-21 13:01:35 +00002779 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002780 return rc;
drh75897232000-05-29 14:26:00 +00002781}
2782
drha2c8a952009-10-13 18:38:34 +00002783#if SQLITE_TCL_NRE
2784/*
2785** Adaptor that provides an objCmd interface to the NRE-enabled
2786** interface implementation.
2787*/
2788static int DbObjCmdAdaptor(
2789 void *cd,
2790 Tcl_Interp *interp,
2791 int objc,
2792 Tcl_Obj *const*objv
2793){
2794 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
2795}
2796#endif /* SQLITE_TCL_NRE */
2797
drh75897232000-05-29 14:26:00 +00002798/*
drh3570ad92007-08-31 14:31:44 +00002799** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00002800** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00002801**
2802** This is the main Tcl command. When the "sqlite" Tcl command is
2803** invoked, this routine runs to process that command.
2804**
2805** The first argument, DBNAME, is an arbitrary name for a new
2806** database connection. This command creates a new command named
2807** DBNAME that is used to control that connection. The database
2808** connection is deleted when the DBNAME command is deleted.
2809**
drh3570ad92007-08-31 14:31:44 +00002810** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00002811**
drh75897232000-05-29 14:26:00 +00002812*/
drh22fbcb82004-02-01 01:22:50 +00002813static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002814 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002815 void *pKey = 0;
2816 int nKey = 0;
2817 const char *zArg;
drh75897232000-05-29 14:26:00 +00002818 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00002819 int i;
drh22fbcb82004-02-01 01:22:50 +00002820 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00002821 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00002822 int flags;
drh882e8e42006-08-24 02:42:27 +00002823 Tcl_DString translatedFilename;
drhd9da78a2009-03-24 15:08:09 +00002824
2825 /* In normal use, each TCL interpreter runs in a single thread. So
2826 ** by default, we can turn of mutexing on SQLite database connections.
2827 ** However, for testing purposes it is useful to have mutexes turned
2828 ** on. So, by default, mutexes default off. But if compiled with
2829 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
2830 */
2831#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
2832 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
2833#else
2834 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
2835#endif
2836
drh22fbcb82004-02-01 01:22:50 +00002837 if( objc==2 ){
2838 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002839 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00002840 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00002841 return TCL_OK;
2842 }
drh9eb9e262004-02-11 02:18:05 +00002843 if( strcmp(zArg,"-has-codec")==0 ){
2844#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002845 Tcl_AppendResult(interp,"1",0);
2846#else
2847 Tcl_AppendResult(interp,"0",0);
2848#endif
2849 return TCL_OK;
2850 }
drhfbc3eab2001-04-06 16:13:42 +00002851 }
drh3570ad92007-08-31 14:31:44 +00002852 for(i=3; i+1<objc; i+=2){
2853 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00002854 if( strcmp(zArg,"-key")==0 ){
drh3570ad92007-08-31 14:31:44 +00002855 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
2856 }else if( strcmp(zArg, "-vfs")==0 ){
2857 i++;
2858 zVfs = Tcl_GetString(objv[i]);
2859 }else if( strcmp(zArg, "-readonly")==0 ){
2860 int b;
2861 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2862 if( b ){
drh33f4e022007-09-03 15:19:34 +00002863 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00002864 flags |= SQLITE_OPEN_READONLY;
2865 }else{
2866 flags &= ~SQLITE_OPEN_READONLY;
2867 flags |= SQLITE_OPEN_READWRITE;
2868 }
2869 }else if( strcmp(zArg, "-create")==0 ){
2870 int b;
2871 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00002872 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00002873 flags |= SQLITE_OPEN_CREATE;
2874 }else{
2875 flags &= ~SQLITE_OPEN_CREATE;
2876 }
danielk19779a6284c2008-07-10 17:52:49 +00002877 }else if( strcmp(zArg, "-nomutex")==0 ){
2878 int b;
2879 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2880 if( b ){
2881 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00002882 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00002883 }else{
2884 flags &= ~SQLITE_OPEN_NOMUTEX;
2885 }
drh039963a2008-09-03 00:43:15 +00002886 }else if( strcmp(zArg, "-fullmutex")==0 ){
2887 int b;
2888 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2889 if( b ){
2890 flags |= SQLITE_OPEN_FULLMUTEX;
2891 flags &= ~SQLITE_OPEN_NOMUTEX;
2892 }else{
2893 flags &= ~SQLITE_OPEN_FULLMUTEX;
2894 }
drh3570ad92007-08-31 14:31:44 +00002895 }else{
2896 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
2897 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00002898 }
2899 }
drh3570ad92007-08-31 14:31:44 +00002900 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00002901 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00002902 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh039963a2008-09-03 00:43:15 +00002903 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN?"
drh9eb9e262004-02-11 02:18:05 +00002904#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00002905 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00002906#endif
2907 );
drh75897232000-05-29 14:26:00 +00002908 return TCL_ERROR;
2909 }
drh75897232000-05-29 14:26:00 +00002910 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00002911 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00002912 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00002913 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
2914 return TCL_ERROR;
2915 }
2916 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00002917 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00002918 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
drh3570ad92007-08-31 14:31:44 +00002919 sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00002920 Tcl_DStringFree(&translatedFilename);
danielk197780290862004-05-22 09:21:21 +00002921 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
drh9404d502006-12-19 18:46:08 +00002922 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
danielk197780290862004-05-22 09:21:21 +00002923 sqlite3_close(p->db);
2924 p->db = 0;
2925 }
drh2011d5f2004-07-22 02:40:37 +00002926#ifdef SQLITE_HAS_CODEC
drhf3a65f72007-08-22 20:18:21 +00002927 if( p->db ){
2928 sqlite3_key(p->db, pKey, nKey);
2929 }
drheb8ed702004-02-11 10:37:23 +00002930#endif
drhbec3f402000-08-04 13:49:02 +00002931 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00002932 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00002933 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00002934 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00002935 return TCL_ERROR;
2936 }
drhfb7e7652005-01-24 00:28:42 +00002937 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00002938 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00002939 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00002940 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00002941 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
2942 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00002943 }else{
2944 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
2945 }
drh75897232000-05-29 14:26:00 +00002946 return TCL_OK;
2947}
2948
2949/*
drh90ca9752001-09-28 17:47:14 +00002950** Provide a dummy Tcl_InitStubs if we are using this as a static
2951** library.
2952*/
2953#ifndef USE_TCL_STUBS
2954# undef Tcl_InitStubs
2955# define Tcl_InitStubs(a,b,c)
2956#endif
2957
2958/*
drh29bc4612005-10-05 10:40:15 +00002959** Make sure we have a PACKAGE_VERSION macro defined. This will be
2960** defined automatically by the TEA makefile. But other makefiles
2961** do not define it.
2962*/
2963#ifndef PACKAGE_VERSION
2964# define PACKAGE_VERSION SQLITE_VERSION
2965#endif
2966
2967/*
drh75897232000-05-29 14:26:00 +00002968** Initialize this module.
2969**
2970** This Tcl module contains only a single new Tcl command named "sqlite".
2971** (Hence there is no namespace. There is no point in using a namespace
2972** if the extension only supplies one new name!) The "sqlite" command is
2973** used to open a new SQLite database. See the DbMain() routine above
2974** for additional information.
2975*/
drhad6e1372006-07-10 21:15:51 +00002976EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00002977 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00002978 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002979 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh49766d62005-01-08 18:42:28 +00002980 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002981 Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
drh90ca9752001-09-28 17:47:14 +00002982 return TCL_OK;
2983}
drhad6e1372006-07-10 21:15:51 +00002984EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2985EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2986EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00002987EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2988EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2989EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2990EXTERN int Tclsqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
2991
drh49766d62005-01-08 18:42:28 +00002992
2993#ifndef SQLITE_3_SUFFIX_ONLY
drhad6e1372006-07-10 21:15:51 +00002994EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2995EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2996EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2997EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00002998EXTERN int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2999EXTERN int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3000EXTERN int Sqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3001EXTERN int Tclsqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
drh49766d62005-01-08 18:42:28 +00003002#endif
drh75897232000-05-29 14:26:00 +00003003
drh3e27c022004-07-23 00:01:38 +00003004#ifdef TCLSH
3005/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003006** All of the code that follows is used to build standalone TCL interpreters
3007** that are statically linked with SQLite. Enable these by compiling
3008** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3009** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3010** analysis program.
drh75897232000-05-29 14:26:00 +00003011*/
drh348784e2000-05-29 20:41:49 +00003012
drh57a02272009-10-22 20:52:05 +00003013#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3014/*
3015 * This code implements the MD5 message-digest algorithm.
3016 * The algorithm is due to Ron Rivest. This code was
3017 * written by Colin Plumb in 1993, no copyright is claimed.
3018 * This code is in the public domain; do with it what you wish.
3019 *
3020 * Equivalent code is available from RSA Data Security, Inc.
3021 * This code has been tested against that, and is equivalent,
3022 * except that you don't need to include two pages of legalese
3023 * with every copy.
3024 *
3025 * To compute the message digest of a chunk of bytes, declare an
3026 * MD5Context structure, pass it to MD5Init, call MD5Update as
3027 * needed on buffers full of bytes, and then call MD5Final, which
3028 * will fill a supplied 16-byte array with the digest.
3029 */
3030
3031/*
3032 * If compiled on a machine that doesn't have a 32-bit integer,
3033 * you just set "uint32" to the appropriate datatype for an
3034 * unsigned 32-bit integer. For example:
3035 *
3036 * cc -Duint32='unsigned long' md5.c
3037 *
3038 */
3039#ifndef uint32
3040# define uint32 unsigned int
3041#endif
3042
3043struct MD5Context {
3044 int isInit;
3045 uint32 buf[4];
3046 uint32 bits[2];
3047 unsigned char in[64];
3048};
3049typedef struct MD5Context MD5Context;
3050
3051/*
3052 * Note: this code is harmless on little-endian machines.
3053 */
3054static void byteReverse (unsigned char *buf, unsigned longs){
3055 uint32 t;
3056 do {
3057 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3058 ((unsigned)buf[1]<<8 | buf[0]);
3059 *(uint32 *)buf = t;
3060 buf += 4;
3061 } while (--longs);
3062}
3063/* The four core functions - F1 is optimized somewhat */
3064
3065/* #define F1(x, y, z) (x & y | ~x & z) */
3066#define F1(x, y, z) (z ^ (x & (y ^ z)))
3067#define F2(x, y, z) F1(z, x, y)
3068#define F3(x, y, z) (x ^ y ^ z)
3069#define F4(x, y, z) (y ^ (x | ~z))
3070
3071/* This is the central step in the MD5 algorithm. */
3072#define MD5STEP(f, w, x, y, z, data, s) \
3073 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3074
3075/*
3076 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3077 * reflect the addition of 16 longwords of new data. MD5Update blocks
3078 * the data and converts bytes into longwords for this routine.
3079 */
3080static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3081 register uint32 a, b, c, d;
3082
3083 a = buf[0];
3084 b = buf[1];
3085 c = buf[2];
3086 d = buf[3];
3087
3088 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3089 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3090 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3091 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3092 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3093 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3094 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3095 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3096 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3097 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3098 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3099 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3100 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3101 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3102 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3103 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3104
3105 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3106 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3107 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3108 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3109 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3110 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3111 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3112 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3113 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3114 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3115 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3116 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3117 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3118 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3119 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3120 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3121
3122 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3123 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3124 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3125 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3126 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3127 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3128 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3129 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3130 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3131 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3132 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3133 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3134 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3135 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3136 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3137 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3138
3139 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3140 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3141 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3142 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3143 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3144 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3145 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3146 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3147 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3148 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3149 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3150 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3151 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3152 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3153 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3154 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3155
3156 buf[0] += a;
3157 buf[1] += b;
3158 buf[2] += c;
3159 buf[3] += d;
3160}
3161
3162/*
3163 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3164 * initialization constants.
3165 */
3166static void MD5Init(MD5Context *ctx){
3167 ctx->isInit = 1;
3168 ctx->buf[0] = 0x67452301;
3169 ctx->buf[1] = 0xefcdab89;
3170 ctx->buf[2] = 0x98badcfe;
3171 ctx->buf[3] = 0x10325476;
3172 ctx->bits[0] = 0;
3173 ctx->bits[1] = 0;
3174}
3175
3176/*
3177 * Update context to reflect the concatenation of another buffer full
3178 * of bytes.
3179 */
3180static
3181void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3182 uint32 t;
3183
3184 /* Update bitcount */
3185
3186 t = ctx->bits[0];
3187 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3188 ctx->bits[1]++; /* Carry from low to high */
3189 ctx->bits[1] += len >> 29;
3190
3191 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3192
3193 /* Handle any leading odd-sized chunks */
3194
3195 if ( t ) {
3196 unsigned char *p = (unsigned char *)ctx->in + t;
3197
3198 t = 64-t;
3199 if (len < t) {
3200 memcpy(p, buf, len);
3201 return;
3202 }
3203 memcpy(p, buf, t);
3204 byteReverse(ctx->in, 16);
3205 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3206 buf += t;
3207 len -= t;
3208 }
3209
3210 /* Process data in 64-byte chunks */
3211
3212 while (len >= 64) {
3213 memcpy(ctx->in, buf, 64);
3214 byteReverse(ctx->in, 16);
3215 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3216 buf += 64;
3217 len -= 64;
3218 }
3219
3220 /* Handle any remaining bytes of data. */
3221
3222 memcpy(ctx->in, buf, len);
3223}
3224
3225/*
3226 * Final wrapup - pad to 64-byte boundary with the bit pattern
3227 * 1 0* (64-bit count of bits processed, MSB-first)
3228 */
3229static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3230 unsigned count;
3231 unsigned char *p;
3232
3233 /* Compute number of bytes mod 64 */
3234 count = (ctx->bits[0] >> 3) & 0x3F;
3235
3236 /* Set the first char of padding to 0x80. This is safe since there is
3237 always at least one byte free */
3238 p = ctx->in + count;
3239 *p++ = 0x80;
3240
3241 /* Bytes of padding needed to make 64 bytes */
3242 count = 64 - 1 - count;
3243
3244 /* Pad out to 56 mod 64 */
3245 if (count < 8) {
3246 /* Two lots of padding: Pad the first block to 64 bytes */
3247 memset(p, 0, count);
3248 byteReverse(ctx->in, 16);
3249 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3250
3251 /* Now fill the next block with 56 bytes */
3252 memset(ctx->in, 0, 56);
3253 } else {
3254 /* Pad block to 56 bytes */
3255 memset(p, 0, count-8);
3256 }
3257 byteReverse(ctx->in, 14);
3258
3259 /* Append length in bits and transform */
3260 ((uint32 *)ctx->in)[ 14 ] = ctx->bits[0];
3261 ((uint32 *)ctx->in)[ 15 ] = ctx->bits[1];
3262
3263 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3264 byteReverse((unsigned char *)ctx->buf, 4);
3265 memcpy(digest, ctx->buf, 16);
3266 memset(ctx, 0, sizeof(ctx)); /* In case it is sensitive */
3267}
3268
3269/*
3270** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3271*/
3272static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3273 static char const zEncode[] = "0123456789abcdef";
3274 int i, j;
3275
3276 for(j=i=0; i<16; i++){
3277 int a = digest[i];
3278 zBuf[j++] = zEncode[(a>>4)&0xf];
3279 zBuf[j++] = zEncode[a & 0xf];
3280 }
3281 zBuf[j] = 0;
3282}
3283
3284
3285/*
3286** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3287** each representing 16 bits of the digest and separated from each
3288** other by a "-" character.
3289*/
3290static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3291 int i, j;
3292 unsigned int x;
3293 for(i=j=0; i<16; i+=2){
3294 x = digest[i]*256 + digest[i+1];
3295 if( i>0 ) zDigest[j++] = '-';
3296 sprintf(&zDigest[j], "%05u", x);
3297 j += 5;
3298 }
3299 zDigest[j] = 0;
3300}
3301
3302/*
3303** A TCL command for md5. The argument is the text to be hashed. The
3304** Result is the hash in base64.
3305*/
3306static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3307 MD5Context ctx;
3308 unsigned char digest[16];
3309 char zBuf[50];
3310 void (*converter)(unsigned char*, char*);
3311
3312 if( argc!=2 ){
3313 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3314 " TEXT\"", 0);
3315 return TCL_ERROR;
3316 }
3317 MD5Init(&ctx);
3318 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3319 MD5Final(digest, &ctx);
3320 converter = (void(*)(unsigned char*,char*))cd;
3321 converter(digest, zBuf);
3322 Tcl_AppendResult(interp, zBuf, (char*)0);
3323 return TCL_OK;
3324}
3325
3326/*
3327** A TCL command to take the md5 hash of a file. The argument is the
3328** name of the file.
3329*/
3330static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3331 FILE *in;
3332 MD5Context ctx;
3333 void (*converter)(unsigned char*, char*);
3334 unsigned char digest[16];
3335 char zBuf[10240];
3336
3337 if( argc!=2 ){
3338 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3339 " FILENAME\"", 0);
3340 return TCL_ERROR;
3341 }
3342 in = fopen(argv[1],"rb");
3343 if( in==0 ){
3344 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
3345 "\" for reading", 0);
3346 return TCL_ERROR;
3347 }
3348 MD5Init(&ctx);
3349 for(;;){
3350 int n;
3351 n = fread(zBuf, 1, sizeof(zBuf), in);
3352 if( n<=0 ) break;
3353 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3354 }
3355 fclose(in);
3356 MD5Final(digest, &ctx);
3357 converter = (void(*)(unsigned char*,char*))cd;
3358 converter(digest, zBuf);
3359 Tcl_AppendResult(interp, zBuf, (char*)0);
3360 return TCL_OK;
3361}
3362
3363/*
3364** Register the four new TCL commands for generating MD5 checksums
3365** with the TCL interpreter.
3366*/
3367int Md5_Init(Tcl_Interp *interp){
3368 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3369 MD5DigestToBase16, 0);
3370 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3371 MD5DigestToBase10x8, 0);
3372 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3373 MD5DigestToBase16, 0);
3374 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3375 MD5DigestToBase10x8, 0);
3376 return TCL_OK;
3377}
3378#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3379
3380#if defined(SQLITE_TEST)
3381/*
3382** During testing, the special md5sum() aggregate function is available.
3383** inside SQLite. The following routines implement that function.
3384*/
3385static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3386 MD5Context *p;
3387 int i;
3388 if( argc<1 ) return;
3389 p = sqlite3_aggregate_context(context, sizeof(*p));
3390 if( p==0 ) return;
3391 if( !p->isInit ){
3392 MD5Init(p);
3393 }
3394 for(i=0; i<argc; i++){
3395 const char *zData = (char*)sqlite3_value_text(argv[i]);
3396 if( zData ){
3397 MD5Update(p, (unsigned char*)zData, strlen(zData));
3398 }
3399 }
3400}
3401static void md5finalize(sqlite3_context *context){
3402 MD5Context *p;
3403 unsigned char digest[16];
3404 char zBuf[33];
3405 p = sqlite3_aggregate_context(context, sizeof(*p));
3406 MD5Final(digest,p);
3407 MD5DigestToBase16(digest, zBuf);
3408 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3409}
3410int Md5_Register(sqlite3 *db){
3411 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
3412 md5step, md5finalize);
3413 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3414 return rc;
3415}
3416#endif /* defined(SQLITE_TEST) */
3417
3418
drh348784e2000-05-29 20:41:49 +00003419/*
drh3e27c022004-07-23 00:01:38 +00003420** If the macro TCLSH is one, then put in code this for the
3421** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003422** standard input, or if a file is named on the command line
3423** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003424*/
drh3e27c022004-07-23 00:01:38 +00003425#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00003426static char zMainloop[] =
3427 "set line {}\n"
3428 "while {![eof stdin]} {\n"
3429 "if {$line!=\"\"} {\n"
3430 "puts -nonewline \"> \"\n"
3431 "} else {\n"
3432 "puts -nonewline \"% \"\n"
3433 "}\n"
3434 "flush stdout\n"
3435 "append line [gets stdin]\n"
3436 "if {[info complete $line]} {\n"
3437 "if {[catch {uplevel #0 $line} result]} {\n"
3438 "puts stderr \"Error: $result\"\n"
3439 "} elseif {$result!=\"\"} {\n"
3440 "puts $result\n"
3441 "}\n"
3442 "set line {}\n"
3443 "} else {\n"
3444 "append line \\n\n"
3445 "}\n"
3446 "}\n"
3447;
drh3e27c022004-07-23 00:01:38 +00003448#endif
3449
drh348784e2000-05-29 20:41:49 +00003450#define TCLSH_MAIN main /* Needed to fake out mktclapp */
3451int TCLSH_MAIN(int argc, char **argv){
3452 Tcl_Interp *interp;
danielk19770a549072009-02-17 16:29:10 +00003453
3454 /* Call sqlite3_shutdown() once before doing anything else. This is to
3455 ** test that sqlite3_shutdown() can be safely called by a process before
3456 ** sqlite3_initialize() is. */
3457 sqlite3_shutdown();
3458
drh297ecf12001-04-05 15:57:13 +00003459 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00003460 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00003461 Sqlite3_Init(interp);
drh57a02272009-10-22 20:52:05 +00003462#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3463 Md5_Init(interp);
3464#endif
drhd9b02572001-04-15 00:37:09 +00003465#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00003466 {
drh2f999a62007-08-15 19:16:43 +00003467 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00003468 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00003469 extern int Sqlitetest2_Init(Tcl_Interp*);
3470 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00003471 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00003472 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00003473 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00003474 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00003475 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00003476 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00003477 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00003478 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
drh984bfaa2008-03-19 16:08:53 +00003479 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00003480 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00003481 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003482 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00003483 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003484 extern int Sqlitetestschema_Init(Tcl_Interp*);
3485 extern int Sqlitetestsse_Init(Tcl_Interp*);
3486 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00003487 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00003488 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00003489 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00003490 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00003491
drh2f999a62007-08-15 19:16:43 +00003492 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00003493 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00003494 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00003495 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00003496 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00003497 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00003498 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00003499 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00003500 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00003501 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00003502 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00003503 Sqlitetest_autoext_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00003504 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00003505 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00003506 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003507 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00003508 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003509 Sqlitetestschema_Init(interp);
3510 Sqlitetesttclvar_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00003511 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003512 SqlitetestOnefile_Init(interp);
danielk19775d1f5aa2008-04-10 14:51:00 +00003513 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00003514 Sqlitetestbackup_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003515
drh89dec812005-04-28 19:03:37 +00003516#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00003517 Sqlitetestsse_Init(interp);
3518#endif
drhd1bf3512001-04-07 15:24:33 +00003519 }
3520#endif
drhc7285972009-11-10 01:13:25 +00003521 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00003522 int i;
shessad42c3a2006-08-22 23:53:46 +00003523 char zArgc[32];
3524 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
3525 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00003526 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
3527 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00003528 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00003529 Tcl_SetVar(interp, "argv", argv[i],
3530 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3531 }
drhc7285972009-11-10 01:13:25 +00003532 if( Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00003533 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00003534 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00003535 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00003536 return 1;
3537 }
drh3e27c022004-07-23 00:01:38 +00003538 }
drhc7285972009-11-10 01:13:25 +00003539 if( argc<=1 ){
drh348784e2000-05-29 20:41:49 +00003540 Tcl_GlobalEval(interp, zMainloop);
3541 }
3542 return 0;
3543}
3544#endif /* TCLSH */