blob: d9d6a7d8ae5df0acb2e0686a03e6f6fcfabc4c19 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
drhbd08af42007-04-05 21:58:33 +000012** A TCL Interface to SQLite. Append this file to sqlite3.c and
13** compile the whole thing to build a TCL-enabled version of SQLite.
drh57a02272009-10-22 20:52:05 +000014**
15** Compile-time options:
16**
17** -DTCLSH=1 Add a "main()" routine that works as a tclsh.
18**
19** -DSQLITE_TCLMD5 When used in conjuction with -DTCLSH=1, add
20** four new commands to the TCL interpreter for
21** generating MD5 checksums: md5, md5file,
22** md5-10x8, and md5file-10x8.
23**
24** -DSQLITE_TEST When used in conjuction with -DTCLSH=1, add
25** hundreds of new commands used for testing
26** SQLite. This option implies -DSQLITE_TCLMD5.
drh75897232000-05-29 14:26:00 +000027*/
drh17a68932001-01-31 13:28:08 +000028#include "tcl.h"
danielk1977b4e9af92007-05-01 17:49:49 +000029#include <errno.h>
drhbd08af42007-04-05 21:58:33 +000030
31/*
32** Some additional include files are needed if this file is not
33** appended to the amalgamation.
34*/
35#ifndef SQLITE_AMALGAMATION
drh65e8c822009-12-01 13:57:48 +000036# include "sqlite3.h"
drhbd08af42007-04-05 21:58:33 +000037# include <stdlib.h>
38# include <string.h>
39# include <assert.h>
drh65e8c822009-12-01 13:57:48 +000040 typedef unsigned char u8;
drhbd08af42007-04-05 21:58:33 +000041#endif
drheb206382009-10-24 15:51:33 +000042#include <ctype.h>
drh75897232000-05-29 14:26:00 +000043
drhad6e1372006-07-10 21:15:51 +000044/*
45 * Windows needs to know which symbols to export. Unix does not.
46 * BUILD_sqlite should be undefined for Unix.
47 */
48#ifdef BUILD_sqlite
49#undef TCL_STORAGE_CLASS
50#define TCL_STORAGE_CLASS DLLEXPORT
51#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000052
danielk1977a21c6b62005-01-24 10:25:59 +000053#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000054#define MAX_PREPARED_STMTS 100
55
drh75897232000-05-29 14:26:00 +000056/*
drh98808ba2001-10-18 12:34:46 +000057** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
58** have to do a translation when going between the two. Set the
59** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
60** this translation.
61*/
62#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
63# define UTF_TRANSLATION_NEEDED 1
64#endif
65
66/*
drhcabb0812002-09-14 13:47:32 +000067** New SQL functions can be created as TCL scripts. Each such function
68** is described by an instance of the following structure.
69*/
70typedef struct SqlFunc SqlFunc;
71struct SqlFunc {
72 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000073 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
74 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
75 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000076 SqlFunc *pNext; /* Next function on the list of them all */
77};
78
79/*
danielk19770202b292004-06-09 09:55:16 +000080** New collation sequences function can be created as TCL scripts. Each such
81** function is described by an instance of the following structure.
82*/
83typedef struct SqlCollate SqlCollate;
84struct SqlCollate {
85 Tcl_Interp *interp; /* The TCL interpret to execute the function */
86 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000087 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000088};
89
90/*
drhfb7e7652005-01-24 00:28:42 +000091** Prepared statements are cached for faster execution. Each prepared
92** statement is described by an instance of the following structure.
93*/
94typedef struct SqlPreparedStmt SqlPreparedStmt;
95struct SqlPreparedStmt {
96 SqlPreparedStmt *pNext; /* Next in linked list */
97 SqlPreparedStmt *pPrev; /* Previous on the list */
98 sqlite3_stmt *pStmt; /* The prepared statement */
99 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +0000100 const char *zSql; /* Text of the SQL statement */
dan4a4c11a2009-10-06 14:59:02 +0000101 int nParm; /* Size of apParm array */
102 Tcl_Obj **apParm; /* Array of referenced object pointers */
drhfb7e7652005-01-24 00:28:42 +0000103};
104
danielk1977d04417962007-05-02 13:16:30 +0000105typedef struct IncrblobChannel IncrblobChannel;
106
drhfb7e7652005-01-24 00:28:42 +0000107/*
drhbec3f402000-08-04 13:49:02 +0000108** There is one instance of this structure for each SQLite database
109** that has been opened by the SQLite TCL interface.
110*/
111typedef struct SqliteDb SqliteDb;
112struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000113 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000114 Tcl_Interp *interp; /* The interpreter used for this database */
115 char *zBusy; /* The busy callback routine */
116 char *zCommit; /* The commit hook callback routine */
117 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +0000118 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000119 char *zProgress; /* The progress callback routine */
120 char *zAuth; /* The authorization callback routine */
drh1f1549f2008-08-26 21:33:34 +0000121 int disableAuth; /* Disable the authorizer if it exists */
drhd1e47332005-06-26 17:55:33 +0000122 char *zNull; /* Text to substitute for an SQL NULL value */
123 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000124 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000125 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
dan8d22a172010-04-19 18:03:51 +0000126 Tcl_Obj *pLogHook; /* WAL hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000127 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000128 SqlCollate *pCollate; /* List of SQL collation functions */
129 int rc; /* Return code of most recent sqlite3_exec() */
130 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000131 SqlPreparedStmt *stmtList; /* List of prepared statements*/
132 SqlPreparedStmt *stmtLast; /* Last statement in the list */
133 int maxStmt; /* The next maximum number of stmtList */
134 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000135 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh3c379b02010-04-07 19:31:59 +0000136 int nStep, nSort, nIndex; /* Statistics for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000137 int nTransaction; /* Number of nested [transaction] methods */
drh98808ba2001-10-18 12:34:46 +0000138};
drh297ecf12001-04-05 15:57:13 +0000139
danielk1977b4e9af92007-05-01 17:49:49 +0000140struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000141 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000142 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000143 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000144 Tcl_Channel channel; /* Channel identifier */
145 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
146 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000147};
148
drhea678832008-12-10 19:26:22 +0000149/*
150** Compute a string length that is limited to what can be stored in
151** lower 30 bits of a 32-bit signed integer.
152*/
drh4f21c4a2008-12-10 22:15:00 +0000153static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000154 const char *z2 = z;
155 while( *z2 ){ z2++; }
156 return 0x3fffffff & (int)(z2 - z);
157}
drhea678832008-12-10 19:26:22 +0000158
159
danielk197732a0d8b2007-05-04 19:03:02 +0000160#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000161/*
danielk1977d04417962007-05-02 13:16:30 +0000162** Close all incrblob channels opened using database connection pDb.
163** This is called when shutting down the database connection.
164*/
165static void closeIncrblobChannels(SqliteDb *pDb){
166 IncrblobChannel *p;
167 IncrblobChannel *pNext;
168
169 for(p=pDb->pIncrblob; p; p=pNext){
170 pNext = p->pNext;
171
172 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
173 ** which deletes the IncrblobChannel structure at *p. So do not
174 ** call Tcl_Free() here.
175 */
176 Tcl_UnregisterChannel(pDb->interp, p->channel);
177 }
178}
179
180/*
danielk1977b4e9af92007-05-01 17:49:49 +0000181** Close an incremental blob channel.
182*/
183static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
184 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000185 int rc = sqlite3_blob_close(p->pBlob);
186 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000187
188 /* Remove the channel from the SqliteDb.pIncrblob list. */
189 if( p->pNext ){
190 p->pNext->pPrev = p->pPrev;
191 }
192 if( p->pPrev ){
193 p->pPrev->pNext = p->pNext;
194 }
195 if( p->pDb->pIncrblob==p ){
196 p->pDb->pIncrblob = p->pNext;
197 }
198
danielk197792d4d7a2007-05-04 12:05:56 +0000199 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000200 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000201
202 if( rc!=SQLITE_OK ){
203 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
204 return TCL_ERROR;
205 }
danielk1977b4e9af92007-05-01 17:49:49 +0000206 return TCL_OK;
207}
208
209/*
210** Read data from an incremental blob channel.
211*/
212static int incrblobInput(
213 ClientData instanceData,
214 char *buf,
215 int bufSize,
216 int *errorCodePtr
217){
218 IncrblobChannel *p = (IncrblobChannel *)instanceData;
219 int nRead = bufSize; /* Number of bytes to read */
220 int nBlob; /* Total size of the blob */
221 int rc; /* sqlite error code */
222
223 nBlob = sqlite3_blob_bytes(p->pBlob);
224 if( (p->iSeek+nRead)>nBlob ){
225 nRead = nBlob-p->iSeek;
226 }
227 if( nRead<=0 ){
228 return 0;
229 }
230
231 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
232 if( rc!=SQLITE_OK ){
233 *errorCodePtr = rc;
234 return -1;
235 }
236
237 p->iSeek += nRead;
238 return nRead;
239}
240
danielk1977d04417962007-05-02 13:16:30 +0000241/*
242** Write data to an incremental blob channel.
243*/
danielk1977b4e9af92007-05-01 17:49:49 +0000244static int incrblobOutput(
245 ClientData instanceData,
246 CONST char *buf,
247 int toWrite,
248 int *errorCodePtr
249){
250 IncrblobChannel *p = (IncrblobChannel *)instanceData;
251 int nWrite = toWrite; /* Number of bytes to write */
252 int nBlob; /* Total size of the blob */
253 int rc; /* sqlite error code */
254
255 nBlob = sqlite3_blob_bytes(p->pBlob);
256 if( (p->iSeek+nWrite)>nBlob ){
257 *errorCodePtr = EINVAL;
258 return -1;
259 }
260 if( nWrite<=0 ){
261 return 0;
262 }
263
264 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
265 if( rc!=SQLITE_OK ){
266 *errorCodePtr = EIO;
267 return -1;
268 }
269
270 p->iSeek += nWrite;
271 return nWrite;
272}
273
274/*
275** Seek an incremental blob channel.
276*/
277static int incrblobSeek(
278 ClientData instanceData,
279 long offset,
280 int seekMode,
281 int *errorCodePtr
282){
283 IncrblobChannel *p = (IncrblobChannel *)instanceData;
284
285 switch( seekMode ){
286 case SEEK_SET:
287 p->iSeek = offset;
288 break;
289 case SEEK_CUR:
290 p->iSeek += offset;
291 break;
292 case SEEK_END:
293 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
294 break;
295
296 default: assert(!"Bad seekMode");
297 }
298
299 return p->iSeek;
300}
301
302
303static void incrblobWatch(ClientData instanceData, int mode){
304 /* NO-OP */
305}
306static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
307 return TCL_ERROR;
308}
309
310static Tcl_ChannelType IncrblobChannelType = {
311 "incrblob", /* typeName */
312 TCL_CHANNEL_VERSION_2, /* version */
313 incrblobClose, /* closeProc */
314 incrblobInput, /* inputProc */
315 incrblobOutput, /* outputProc */
316 incrblobSeek, /* seekProc */
317 0, /* setOptionProc */
318 0, /* getOptionProc */
319 incrblobWatch, /* watchProc (this is a no-op) */
320 incrblobHandle, /* getHandleProc (always returns error) */
321 0, /* close2Proc */
322 0, /* blockModeProc */
323 0, /* flushProc */
324 0, /* handlerProc */
325 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000326};
327
328/*
329** Create a new incrblob channel.
330*/
331static int createIncrblobChannel(
332 Tcl_Interp *interp,
333 SqliteDb *pDb,
334 const char *zDb,
335 const char *zTable,
336 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000337 sqlite_int64 iRow,
338 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000339){
340 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000341 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000342 sqlite3_blob *pBlob;
343 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000344 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000345
346 /* This variable is used to name the channels: "incrblob_[incr count]" */
347 static int count = 0;
348 char zChannel[64];
349
danielk19778cbadb02007-05-03 16:31:26 +0000350 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000351 if( rc!=SQLITE_OK ){
352 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
353 return TCL_ERROR;
354 }
355
356 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
357 p->iSeek = 0;
358 p->pBlob = pBlob;
359
drh5bb3eb92007-05-04 13:15:55 +0000360 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000361 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
362 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000363
danielk1977d04417962007-05-02 13:16:30 +0000364 /* Link the new channel into the SqliteDb.pIncrblob list. */
365 p->pNext = pDb->pIncrblob;
366 p->pPrev = 0;
367 if( p->pNext ){
368 p->pNext->pPrev = p;
369 }
370 pDb->pIncrblob = p;
371 p->pDb = pDb;
372
373 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000374 return TCL_OK;
375}
danielk197732a0d8b2007-05-04 19:03:02 +0000376#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
377 #define closeIncrblobChannels(pDb)
378#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000379
drh6d313162000-09-21 13:01:35 +0000380/*
drhd1e47332005-06-26 17:55:33 +0000381** Look at the script prefix in pCmd. We will be executing this script
382** after first appending one or more arguments. This routine analyzes
383** the script to see if it is safe to use Tcl_EvalObjv() on the script
384** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
385** faster.
386**
387** Scripts that are safe to use with Tcl_EvalObjv() consists of a
388** command name followed by zero or more arguments with no [...] or $
389** or {...} or ; to be seen anywhere. Most callback scripts consist
390** of just a single procedure name and they meet this requirement.
391*/
392static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
393 /* We could try to do something with Tcl_Parse(). But we will instead
394 ** just do a search for forbidden characters. If any of the forbidden
395 ** characters appear in pCmd, we will report the string as unsafe.
396 */
397 const char *z;
398 int n;
399 z = Tcl_GetStringFromObj(pCmd, &n);
400 while( n-- > 0 ){
401 int c = *(z++);
402 if( c=='$' || c=='[' || c==';' ) return 0;
403 }
404 return 1;
405}
406
407/*
408** Find an SqlFunc structure with the given name. Or create a new
409** one if an existing one cannot be found. Return a pointer to the
410** structure.
411*/
412static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
413 SqlFunc *p, *pNew;
414 int i;
drh4f21c4a2008-12-10 22:15:00 +0000415 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen30(zName) + 1 );
drhd1e47332005-06-26 17:55:33 +0000416 pNew->zName = (char*)&pNew[1];
417 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
418 pNew->zName[i] = 0;
419 for(p=pDb->pFunc; p; p=p->pNext){
420 if( strcmp(p->zName, pNew->zName)==0 ){
421 Tcl_Free((char*)pNew);
422 return p;
423 }
424 }
425 pNew->interp = pDb->interp;
426 pNew->pScript = 0;
427 pNew->pNext = pDb->pFunc;
428 pDb->pFunc = pNew;
429 return pNew;
430}
431
432/*
drhfb7e7652005-01-24 00:28:42 +0000433** Finalize and free a list of prepared statements
434*/
435static void flushStmtCache( SqliteDb *pDb ){
436 SqlPreparedStmt *pPreStmt;
437
438 while( pDb->stmtList ){
439 sqlite3_finalize( pDb->stmtList->pStmt );
440 pPreStmt = pDb->stmtList;
441 pDb->stmtList = pDb->stmtList->pNext;
442 Tcl_Free( (char*)pPreStmt );
443 }
444 pDb->nStmt = 0;
445 pDb->stmtLast = 0;
446}
447
448/*
drh895d7472004-08-20 16:02:39 +0000449** TCL calls this procedure when an sqlite3 database command is
450** deleted.
drh75897232000-05-29 14:26:00 +0000451*/
452static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000453 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000454 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000455 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000456 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000457 while( pDb->pFunc ){
458 SqlFunc *pFunc = pDb->pFunc;
459 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000460 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000461 Tcl_Free((char*)pFunc);
462 }
danielk19770202b292004-06-09 09:55:16 +0000463 while( pDb->pCollate ){
464 SqlCollate *pCollate = pDb->pCollate;
465 pDb->pCollate = pCollate->pNext;
466 Tcl_Free((char*)pCollate);
467 }
drhbec3f402000-08-04 13:49:02 +0000468 if( pDb->zBusy ){
469 Tcl_Free(pDb->zBusy);
470 }
drhb5a20d32003-04-23 12:25:23 +0000471 if( pDb->zTrace ){
472 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000473 }
drh19e2d372005-08-29 23:00:03 +0000474 if( pDb->zProfile ){
475 Tcl_Free(pDb->zProfile);
476 }
drhe22a3342003-04-22 20:30:37 +0000477 if( pDb->zAuth ){
478 Tcl_Free(pDb->zAuth);
479 }
danielk197755c45f22005-04-03 23:54:43 +0000480 if( pDb->zNull ){
481 Tcl_Free(pDb->zNull);
482 }
danielk197794eb6a12005-12-15 15:22:08 +0000483 if( pDb->pUpdateHook ){
484 Tcl_DecrRefCount(pDb->pUpdateHook);
485 }
danielk197771fd80b2005-12-16 06:54:01 +0000486 if( pDb->pRollbackHook ){
487 Tcl_DecrRefCount(pDb->pRollbackHook);
488 }
dan8d22a172010-04-19 18:03:51 +0000489 if( pDb->pLogHook ){
490 Tcl_DecrRefCount(pDb->pLogHook);
491 }
danielk197794eb6a12005-12-15 15:22:08 +0000492 if( pDb->pCollateNeeded ){
493 Tcl_DecrRefCount(pDb->pCollateNeeded);
494 }
drhbec3f402000-08-04 13:49:02 +0000495 Tcl_Free((char*)pDb);
496}
497
498/*
499** This routine is called when a database file is locked while trying
500** to execute SQL.
501*/
danielk19772a764eb2004-06-12 01:43:26 +0000502static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000503 SqliteDb *pDb = (SqliteDb*)cd;
504 int rc;
505 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000506
drh5bb3eb92007-05-04 13:15:55 +0000507 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000508 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000509 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
510 return 0;
511 }
512 return 1;
drh75897232000-05-29 14:26:00 +0000513}
514
drh26e4a8b2008-05-01 17:16:52 +0000515#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000516/*
danielk1977348bb5d2003-10-18 09:37:26 +0000517** This routine is invoked as the 'progress callback' for the database.
518*/
519static int DbProgressHandler(void *cd){
520 SqliteDb *pDb = (SqliteDb*)cd;
521 int rc;
522
523 assert( pDb->zProgress );
524 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
525 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
526 return 1;
527 }
528 return 0;
529}
drh26e4a8b2008-05-01 17:16:52 +0000530#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000531
drhd1167392006-01-23 13:00:35 +0000532#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000533/*
drhb5a20d32003-04-23 12:25:23 +0000534** This routine is called by the SQLite trace handler whenever a new
535** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000536*/
drhb5a20d32003-04-23 12:25:23 +0000537static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000538 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000539 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000540
drhb5a20d32003-04-23 12:25:23 +0000541 Tcl_DStringInit(&str);
542 Tcl_DStringAppend(&str, pDb->zTrace, -1);
543 Tcl_DStringAppendElement(&str, zSql);
544 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
545 Tcl_DStringFree(&str);
546 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000547}
drhd1167392006-01-23 13:00:35 +0000548#endif
drh0d1a6432003-04-03 15:46:04 +0000549
drhd1167392006-01-23 13:00:35 +0000550#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000551/*
drh19e2d372005-08-29 23:00:03 +0000552** This routine is called by the SQLite profile handler after a statement
553** SQL has executed. The TCL script in pDb->zProfile is evaluated.
554*/
555static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
556 SqliteDb *pDb = (SqliteDb*)cd;
557 Tcl_DString str;
558 char zTm[100];
559
560 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
561 Tcl_DStringInit(&str);
562 Tcl_DStringAppend(&str, pDb->zProfile, -1);
563 Tcl_DStringAppendElement(&str, zSql);
564 Tcl_DStringAppendElement(&str, zTm);
565 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
566 Tcl_DStringFree(&str);
567 Tcl_ResetResult(pDb->interp);
568}
drhd1167392006-01-23 13:00:35 +0000569#endif
drh19e2d372005-08-29 23:00:03 +0000570
571/*
drhaa940ea2004-01-15 02:44:03 +0000572** This routine is called when a transaction is committed. The
573** TCL script in pDb->zCommit is executed. If it returns non-zero or
574** if it throws an exception, the transaction is rolled back instead
575** of being committed.
576*/
577static int DbCommitHandler(void *cd){
578 SqliteDb *pDb = (SqliteDb*)cd;
579 int rc;
580
581 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
582 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
583 return 1;
584 }
585 return 0;
586}
587
danielk197771fd80b2005-12-16 06:54:01 +0000588static void DbRollbackHandler(void *clientData){
589 SqliteDb *pDb = (SqliteDb*)clientData;
590 assert(pDb->pRollbackHook);
591 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
592 Tcl_BackgroundError(pDb->interp);
593 }
594}
595
dan8d22a172010-04-19 18:03:51 +0000596static int DbLogHandler(
597 void *clientData,
598 sqlite3 *db,
599 const char *zDb,
600 int nEntry
601){
602 int ret = 0;
603 Tcl_Obj *p;
604 SqliteDb *pDb = (SqliteDb*)clientData;
605 Tcl_Interp *interp = pDb->interp;
606 assert(pDb->pLogHook);
607
608 p = Tcl_DuplicateObj(pDb->pLogHook);
609 Tcl_IncrRefCount(p);
610 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
611 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
612 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
613 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
614 ){
615 Tcl_BackgroundError(interp);
616 }
617 Tcl_DecrRefCount(p);
618
619 return ret;
620}
621
drhbcf4f482009-03-27 12:44:35 +0000622#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000623static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
624 char zBuf[64];
625 sprintf(zBuf, "%d", iArg);
626 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
627 sprintf(zBuf, "%d", nArg);
628 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
629}
630#else
drhbcf4f482009-03-27 12:44:35 +0000631# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000632#endif
633
drh69910da2009-03-27 12:32:54 +0000634#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000635static void DbUnlockNotify(void **apArg, int nArg){
636 int i;
637 for(i=0; i<nArg; i++){
638 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
639 SqliteDb *pDb = (SqliteDb *)apArg[i];
640 setTestUnlockNotifyVars(pDb->interp, i, nArg);
641 assert( pDb->pUnlockNotify);
642 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
643 Tcl_DecrRefCount(pDb->pUnlockNotify);
644 pDb->pUnlockNotify = 0;
645 }
646}
drh69910da2009-03-27 12:32:54 +0000647#endif
danielk1977404ca072009-03-16 13:19:36 +0000648
danielk197794eb6a12005-12-15 15:22:08 +0000649static void DbUpdateHandler(
650 void *p,
651 int op,
652 const char *zDb,
653 const char *zTbl,
654 sqlite_int64 rowid
655){
656 SqliteDb *pDb = (SqliteDb *)p;
657 Tcl_Obj *pCmd;
658
659 assert( pDb->pUpdateHook );
660 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
661
662 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
663 Tcl_IncrRefCount(pCmd);
664 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
665 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
666 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
667 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
668 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
669 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
670}
671
danielk19777cedc8d2004-06-10 10:50:08 +0000672static void tclCollateNeeded(
673 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000674 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000675 int enc,
676 const char *zName
677){
678 SqliteDb *pDb = (SqliteDb *)pCtx;
679 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
680 Tcl_IncrRefCount(pScript);
681 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
682 Tcl_EvalObjEx(pDb->interp, pScript, 0);
683 Tcl_DecrRefCount(pScript);
684}
685
drhaa940ea2004-01-15 02:44:03 +0000686/*
danielk19770202b292004-06-09 09:55:16 +0000687** This routine is called to evaluate an SQL collation function implemented
688** using TCL script.
689*/
690static int tclSqlCollate(
691 void *pCtx,
692 int nA,
693 const void *zA,
694 int nB,
695 const void *zB
696){
697 SqlCollate *p = (SqlCollate *)pCtx;
698 Tcl_Obj *pCmd;
699
700 pCmd = Tcl_NewStringObj(p->zScript, -1);
701 Tcl_IncrRefCount(pCmd);
702 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
703 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000704 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000705 Tcl_DecrRefCount(pCmd);
706 return (atoi(Tcl_GetStringResult(p->interp)));
707}
708
709/*
drhcabb0812002-09-14 13:47:32 +0000710** This routine is called to evaluate an SQL function implemented
711** using TCL script.
712*/
drhfb7e7652005-01-24 00:28:42 +0000713static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000714 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000715 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000716 int i;
717 int rc;
718
drhd1e47332005-06-26 17:55:33 +0000719 if( argc==0 ){
720 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
721 ** script object directly. This allows the TCL compiler to generate
722 ** bytecode for the command on the first invocation and thus make
723 ** subsequent invocations much faster. */
724 pCmd = p->pScript;
725 Tcl_IncrRefCount(pCmd);
726 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
727 Tcl_DecrRefCount(pCmd);
728 }else{
729 /* If there are arguments to the function, make a shallow copy of the
730 ** script object, lappend the arguments, then evaluate the copy.
731 **
732 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
733 ** The new Tcl_Obj contains pointers to the original list elements.
734 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
735 ** of the list to tclCmdNameType, that alternate representation will
736 ** be preserved and reused on the next invocation.
737 */
738 Tcl_Obj **aArg;
739 int nArg;
740 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
741 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
742 return;
743 }
744 pCmd = Tcl_NewListObj(nArg, aArg);
745 Tcl_IncrRefCount(pCmd);
746 for(i=0; i<argc; i++){
747 sqlite3_value *pIn = argv[i];
748 Tcl_Obj *pVal;
749
750 /* Set pVal to contain the i'th column of this row. */
751 switch( sqlite3_value_type(pIn) ){
752 case SQLITE_BLOB: {
753 int bytes = sqlite3_value_bytes(pIn);
754 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
755 break;
756 }
757 case SQLITE_INTEGER: {
758 sqlite_int64 v = sqlite3_value_int64(pIn);
759 if( v>=-2147483647 && v<=2147483647 ){
760 pVal = Tcl_NewIntObj(v);
761 }else{
762 pVal = Tcl_NewWideIntObj(v);
763 }
764 break;
765 }
766 case SQLITE_FLOAT: {
767 double r = sqlite3_value_double(pIn);
768 pVal = Tcl_NewDoubleObj(r);
769 break;
770 }
771 case SQLITE_NULL: {
772 pVal = Tcl_NewStringObj("", 0);
773 break;
774 }
775 default: {
776 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000777 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000778 break;
779 }
780 }
781 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
782 if( rc ){
783 Tcl_DecrRefCount(pCmd);
784 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
785 return;
786 }
danielk197751ad0ec2004-05-24 12:39:02 +0000787 }
drhd1e47332005-06-26 17:55:33 +0000788 if( !p->useEvalObjv ){
789 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
790 ** is a list without a string representation. To prevent this from
791 ** happening, make sure pCmd has a valid string representation */
792 Tcl_GetString(pCmd);
793 }
794 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
795 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000796 }
danielk1977562e8d32005-05-20 09:40:55 +0000797
drhc7f269d2005-05-05 10:30:29 +0000798 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000799 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000800 }else{
drhc7f269d2005-05-05 10:30:29 +0000801 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
802 int n;
803 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000804 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000805 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000806 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000807 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000808 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000809 data = Tcl_GetByteArrayFromObj(pVar, &n);
810 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000811 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000812 Tcl_GetIntFromObj(0, pVar, &n);
813 sqlite3_result_int(context, n);
814 }else if( c=='d' && strcmp(zType,"double")==0 ){
815 double r;
816 Tcl_GetDoubleFromObj(0, pVar, &r);
817 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +0000818 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
819 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000820 Tcl_WideInt v;
821 Tcl_GetWideIntFromObj(0, pVar, &v);
822 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000823 }else{
danielk197700fd9572005-12-07 06:27:43 +0000824 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
825 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000826 }
drhcabb0812002-09-14 13:47:32 +0000827 }
828}
drh895d7472004-08-20 16:02:39 +0000829
drhe22a3342003-04-22 20:30:37 +0000830#ifndef SQLITE_OMIT_AUTHORIZATION
831/*
832** This is the authentication function. It appends the authentication
833** type code and the two arguments to zCmd[] then invokes the result
834** on the interpreter. The reply is examined to determine if the
835** authentication fails or succeeds.
836*/
837static int auth_callback(
838 void *pArg,
839 int code,
840 const char *zArg1,
841 const char *zArg2,
842 const char *zArg3,
843 const char *zArg4
844){
845 char *zCode;
846 Tcl_DString str;
847 int rc;
848 const char *zReply;
849 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +0000850 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +0000851
852 switch( code ){
853 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
854 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
855 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
856 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
857 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
858 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
859 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
860 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
861 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
862 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
863 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
864 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
865 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
866 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
867 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
868 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
869 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
870 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
871 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
872 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
873 case SQLITE_READ : zCode="SQLITE_READ"; break;
874 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
875 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
876 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000877 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
878 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000879 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000880 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000881 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000882 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
883 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000884 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +0000885 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drhe22a3342003-04-22 20:30:37 +0000886 default : zCode="????"; break;
887 }
888 Tcl_DStringInit(&str);
889 Tcl_DStringAppend(&str, pDb->zAuth, -1);
890 Tcl_DStringAppendElement(&str, zCode);
891 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
892 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
893 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
894 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
895 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
896 Tcl_DStringFree(&str);
897 zReply = Tcl_GetStringResult(pDb->interp);
898 if( strcmp(zReply,"SQLITE_OK")==0 ){
899 rc = SQLITE_OK;
900 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
901 rc = SQLITE_DENY;
902 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
903 rc = SQLITE_IGNORE;
904 }else{
905 rc = 999;
906 }
907 return rc;
908}
909#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000910
911/*
danielk1977ef2cb632004-05-29 02:37:19 +0000912** zText is a pointer to text obtained via an sqlite3_result_text()
913** or similar interface. This routine returns a Tcl string object,
914** reference count set to 0, containing the text. If a translation
915** between iso8859 and UTF-8 is required, it is preformed.
916*/
917static Tcl_Obj *dbTextToObj(char const *zText){
918 Tcl_Obj *pVal;
919#ifdef UTF_TRANSLATION_NEEDED
920 Tcl_DString dCol;
921 Tcl_DStringInit(&dCol);
922 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
923 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
924 Tcl_DStringFree(&dCol);
925#else
926 pVal = Tcl_NewStringObj(zText, -1);
927#endif
928 return pVal;
929}
930
931/*
tpoindex1067fe12004-12-17 15:41:11 +0000932** This routine reads a line of text from FILE in, stores
933** the text in memory obtained from malloc() and returns a pointer
934** to the text. NULL is returned at end of file, or if malloc()
935** fails.
936**
937** The interface is like "readline" but no command-line editing
938** is done.
939**
940** copied from shell.c from '.import' command
941*/
942static char *local_getline(char *zPrompt, FILE *in){
943 char *zLine;
944 int nLine;
945 int n;
946 int eol;
947
948 nLine = 100;
949 zLine = malloc( nLine );
950 if( zLine==0 ) return 0;
951 n = 0;
952 eol = 0;
953 while( !eol ){
954 if( n+100>nLine ){
955 nLine = nLine*2 + 100;
956 zLine = realloc(zLine, nLine);
957 if( zLine==0 ) return 0;
958 }
959 if( fgets(&zLine[n], nLine - n, in)==0 ){
960 if( n==0 ){
961 free(zLine);
962 return 0;
963 }
964 zLine[n] = 0;
965 eol = 1;
966 break;
967 }
968 while( zLine[n] ){ n++; }
969 if( n>0 && zLine[n-1]=='\n' ){
970 n--;
971 zLine[n] = 0;
972 eol = 1;
973 }
974 }
975 zLine = realloc( zLine, n+1 );
976 return zLine;
977}
978
danielk19778e556522007-11-13 10:30:24 +0000979
980/*
dan4a4c11a2009-10-06 14:59:02 +0000981** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +0000982**
dan4a4c11a2009-10-06 14:59:02 +0000983** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +0000984**
dan4a4c11a2009-10-06 14:59:02 +0000985** It is invoked after evaluating the script SCRIPT to commit or rollback
986** the transaction or savepoint opened by the [transaction] command.
987*/
988static int DbTransPostCmd(
989 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
990 Tcl_Interp *interp, /* Tcl interpreter */
991 int result /* Result of evaluating SCRIPT */
992){
993 static const char *azEnd[] = {
994 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
995 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
996 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
997 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
998 };
999 SqliteDb *pDb = (SqliteDb*)data[0];
1000 int rc = result;
1001 const char *zEnd;
1002
1003 pDb->nTransaction--;
1004 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1005
1006 pDb->disableAuth++;
1007 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1008 /* This is a tricky scenario to handle. The most likely cause of an
1009 ** error is that the exec() above was an attempt to commit the
1010 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1011 ** that an IO-error has occured. In either case, throw a Tcl exception
1012 ** and try to rollback the transaction.
1013 **
1014 ** But it could also be that the user executed one or more BEGIN,
1015 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1016 ** this method's logic. Not clear how this would be best handled.
1017 */
1018 if( rc!=TCL_ERROR ){
1019 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
1020 rc = TCL_ERROR;
1021 }
1022 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1023 }
1024 pDb->disableAuth--;
1025
1026 return rc;
1027}
1028
1029/*
1030** Search the cache for a prepared-statement object that implements the
1031** first SQL statement in the buffer pointed to by parameter zIn. If
1032** no such prepared-statement can be found, allocate and prepare a new
1033** one. In either case, bind the current values of the relevant Tcl
1034** variables to any $var, :var or @var variables in the statement. Before
1035** returning, set *ppPreStmt to point to the prepared-statement object.
1036**
1037** Output parameter *pzOut is set to point to the next SQL statement in
1038** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1039** next statement.
1040**
1041** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1042** and an error message loaded into interpreter pDb->interp.
1043*/
1044static int dbPrepareAndBind(
1045 SqliteDb *pDb, /* Database object */
1046 char const *zIn, /* SQL to compile */
1047 char const **pzOut, /* OUT: Pointer to next SQL statement */
1048 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1049){
1050 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
1051 sqlite3_stmt *pStmt; /* Prepared statement object */
1052 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1053 int nSql; /* Length of zSql in bytes */
1054 int nVar; /* Number of variables in statement */
1055 int iParm = 0; /* Next free entry in apParm */
1056 int i;
1057 Tcl_Interp *interp = pDb->interp;
1058
1059 *ppPreStmt = 0;
1060
1061 /* Trim spaces from the start of zSql and calculate the remaining length. */
1062 while( isspace(zSql[0]) ){ zSql++; }
1063 nSql = strlen30(zSql);
1064
1065 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1066 int n = pPreStmt->nSql;
1067 if( nSql>=n
1068 && memcmp(pPreStmt->zSql, zSql, n)==0
1069 && (zSql[n]==0 || zSql[n-1]==';')
1070 ){
1071 pStmt = pPreStmt->pStmt;
1072 *pzOut = &zSql[pPreStmt->nSql];
1073
1074 /* When a prepared statement is found, unlink it from the
1075 ** cache list. It will later be added back to the beginning
1076 ** of the cache list in order to implement LRU replacement.
1077 */
1078 if( pPreStmt->pPrev ){
1079 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1080 }else{
1081 pDb->stmtList = pPreStmt->pNext;
1082 }
1083 if( pPreStmt->pNext ){
1084 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1085 }else{
1086 pDb->stmtLast = pPreStmt->pPrev;
1087 }
1088 pDb->nStmt--;
1089 nVar = sqlite3_bind_parameter_count(pStmt);
1090 break;
1091 }
1092 }
1093
1094 /* If no prepared statement was found. Compile the SQL text. Also allocate
1095 ** a new SqlPreparedStmt structure. */
1096 if( pPreStmt==0 ){
1097 int nByte;
1098
1099 if( SQLITE_OK!=sqlite3_prepare_v2(pDb->db, zSql, -1, &pStmt, pzOut) ){
1100 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1101 return TCL_ERROR;
1102 }
1103 if( pStmt==0 ){
1104 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1105 /* A compile-time error in the statement. */
1106 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1107 return TCL_ERROR;
1108 }else{
1109 /* The statement was a no-op. Continue to the next statement
1110 ** in the SQL string.
1111 */
1112 return TCL_OK;
1113 }
1114 }
1115
1116 assert( pPreStmt==0 );
1117 nVar = sqlite3_bind_parameter_count(pStmt);
1118 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1119 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1120 memset(pPreStmt, 0, nByte);
1121
1122 pPreStmt->pStmt = pStmt;
1123 pPreStmt->nSql = (*pzOut - zSql);
1124 pPreStmt->zSql = sqlite3_sql(pStmt);
1125 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
1126 }
1127 assert( pPreStmt );
1128 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1129 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1130
1131 /* Bind values to parameters that begin with $ or : */
1132 for(i=1; i<=nVar; i++){
1133 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1134 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1135 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1136 if( pVar ){
1137 int n;
1138 u8 *data;
1139 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1140 char c = zType[0];
1141 if( zVar[0]=='@' ||
1142 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1143 /* Load a BLOB type if the Tcl variable is a bytearray and
1144 ** it has no string representation or the host
1145 ** parameter name begins with "@". */
1146 data = Tcl_GetByteArrayFromObj(pVar, &n);
1147 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1148 Tcl_IncrRefCount(pVar);
1149 pPreStmt->apParm[iParm++] = pVar;
1150 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1151 Tcl_GetIntFromObj(interp, pVar, &n);
1152 sqlite3_bind_int(pStmt, i, n);
1153 }else if( c=='d' && strcmp(zType,"double")==0 ){
1154 double r;
1155 Tcl_GetDoubleFromObj(interp, pVar, &r);
1156 sqlite3_bind_double(pStmt, i, r);
1157 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1158 (c=='i' && strcmp(zType,"int")==0) ){
1159 Tcl_WideInt v;
1160 Tcl_GetWideIntFromObj(interp, pVar, &v);
1161 sqlite3_bind_int64(pStmt, i, v);
1162 }else{
1163 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1164 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1165 Tcl_IncrRefCount(pVar);
1166 pPreStmt->apParm[iParm++] = pVar;
1167 }
1168 }else{
1169 sqlite3_bind_null(pStmt, i);
1170 }
1171 }
1172 }
1173 pPreStmt->nParm = iParm;
1174 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001175
dan4a4c11a2009-10-06 14:59:02 +00001176 return TCL_OK;
1177}
1178
1179
1180/*
1181** Release a statement reference obtained by calling dbPrepareAndBind().
1182** There should be exactly one call to this function for each call to
1183** dbPrepareAndBind().
1184**
1185** If the discard parameter is non-zero, then the statement is deleted
1186** immediately. Otherwise it is added to the LRU list and may be returned
1187** by a subsequent call to dbPrepareAndBind().
1188*/
1189static void dbReleaseStmt(
1190 SqliteDb *pDb, /* Database handle */
1191 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1192 int discard /* True to delete (not cache) the pPreStmt */
1193){
1194 int i;
1195
1196 /* Free the bound string and blob parameters */
1197 for(i=0; i<pPreStmt->nParm; i++){
1198 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1199 }
1200 pPreStmt->nParm = 0;
1201
1202 if( pDb->maxStmt<=0 || discard ){
1203 /* If the cache is turned off, deallocated the statement */
1204 sqlite3_finalize(pPreStmt->pStmt);
1205 Tcl_Free((char *)pPreStmt);
1206 }else{
1207 /* Add the prepared statement to the beginning of the cache list. */
1208 pPreStmt->pNext = pDb->stmtList;
1209 pPreStmt->pPrev = 0;
1210 if( pDb->stmtList ){
1211 pDb->stmtList->pPrev = pPreStmt;
1212 }
1213 pDb->stmtList = pPreStmt;
1214 if( pDb->stmtLast==0 ){
1215 assert( pDb->nStmt==0 );
1216 pDb->stmtLast = pPreStmt;
1217 }else{
1218 assert( pDb->nStmt>0 );
1219 }
1220 pDb->nStmt++;
1221
1222 /* If we have too many statement in cache, remove the surplus from
1223 ** the end of the cache list. */
1224 while( pDb->nStmt>pDb->maxStmt ){
1225 sqlite3_finalize(pDb->stmtLast->pStmt);
1226 pDb->stmtLast = pDb->stmtLast->pPrev;
1227 Tcl_Free((char*)pDb->stmtLast->pNext);
1228 pDb->stmtLast->pNext = 0;
1229 pDb->nStmt--;
1230 }
1231 }
1232}
1233
1234/*
1235** Structure used with dbEvalXXX() functions:
1236**
1237** dbEvalInit()
1238** dbEvalStep()
1239** dbEvalFinalize()
1240** dbEvalRowInfo()
1241** dbEvalColumnValue()
1242*/
1243typedef struct DbEvalContext DbEvalContext;
1244struct DbEvalContext {
1245 SqliteDb *pDb; /* Database handle */
1246 Tcl_Obj *pSql; /* Object holding string zSql */
1247 const char *zSql; /* Remaining SQL to execute */
1248 SqlPreparedStmt *pPreStmt; /* Current statement */
1249 int nCol; /* Number of columns returned by pStmt */
1250 Tcl_Obj *pArray; /* Name of array variable */
1251 Tcl_Obj **apColName; /* Array of column names */
1252};
1253
1254/*
1255** Release any cache of column names currently held as part of
1256** the DbEvalContext structure passed as the first argument.
1257*/
1258static void dbReleaseColumnNames(DbEvalContext *p){
1259 if( p->apColName ){
1260 int i;
1261 for(i=0; i<p->nCol; i++){
1262 Tcl_DecrRefCount(p->apColName[i]);
1263 }
1264 Tcl_Free((char *)p->apColName);
1265 p->apColName = 0;
1266 }
1267 p->nCol = 0;
1268}
1269
1270/*
1271** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001272**
1273** If pArray is not NULL, then it contains the name of a Tcl array
1274** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001275** the names of the columns returned by the statement as part of each
1276** call to dbEvalStep(), in order from left to right. e.g. if the names
1277** of the returned columns are a, b and c, it does the equivalent of the
1278** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001279**
1280** set ${pArray}(*) {a b c}
1281*/
dan4a4c11a2009-10-06 14:59:02 +00001282static void dbEvalInit(
1283 DbEvalContext *p, /* Pointer to structure to initialize */
1284 SqliteDb *pDb, /* Database handle */
1285 Tcl_Obj *pSql, /* Object containing SQL script */
1286 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001287){
dan4a4c11a2009-10-06 14:59:02 +00001288 memset(p, 0, sizeof(DbEvalContext));
1289 p->pDb = pDb;
1290 p->zSql = Tcl_GetString(pSql);
1291 p->pSql = pSql;
1292 Tcl_IncrRefCount(pSql);
1293 if( pArray ){
1294 p->pArray = pArray;
1295 Tcl_IncrRefCount(pArray);
1296 }
1297}
danielk19778e556522007-11-13 10:30:24 +00001298
dan4a4c11a2009-10-06 14:59:02 +00001299/*
1300** Obtain information about the row that the DbEvalContext passed as the
1301** first argument currently points to.
1302*/
1303static void dbEvalRowInfo(
1304 DbEvalContext *p, /* Evaluation context */
1305 int *pnCol, /* OUT: Number of column names */
1306 Tcl_Obj ***papColName /* OUT: Array of column names */
1307){
danielk19778e556522007-11-13 10:30:24 +00001308 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001309 if( 0==p->apColName ){
1310 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1311 int i; /* Iterator variable */
1312 int nCol; /* Number of columns returned by pStmt */
1313 Tcl_Obj **apColName = 0; /* Array of column names */
1314
1315 p->nCol = nCol = sqlite3_column_count(pStmt);
1316 if( nCol>0 && (papColName || p->pArray) ){
1317 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1318 for(i=0; i<nCol; i++){
1319 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1320 Tcl_IncrRefCount(apColName[i]);
1321 }
1322 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001323 }
1324
1325 /* If results are being stored in an array variable, then create
1326 ** the array(*) entry for that array
1327 */
dan4a4c11a2009-10-06 14:59:02 +00001328 if( p->pArray ){
1329 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001330 Tcl_Obj *pColList = Tcl_NewObj();
1331 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001332
danielk19778e556522007-11-13 10:30:24 +00001333 for(i=0; i<nCol; i++){
1334 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1335 }
1336 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001337 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001338 Tcl_DecrRefCount(pStar);
1339 }
danielk19778e556522007-11-13 10:30:24 +00001340 }
1341
dan4a4c11a2009-10-06 14:59:02 +00001342 if( papColName ){
1343 *papColName = p->apColName;
1344 }
1345 if( pnCol ){
1346 *pnCol = p->nCol;
1347 }
1348}
1349
1350/*
1351** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1352** returned, then an error message is stored in the interpreter before
1353** returning.
1354**
1355** A return value of TCL_OK means there is a row of data available. The
1356** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1357** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1358** is returned, then the SQL script has finished executing and there are
1359** no further rows available. This is similar to SQLITE_DONE.
1360*/
1361static int dbEvalStep(DbEvalContext *p){
1362 while( p->zSql[0] || p->pPreStmt ){
1363 int rc;
1364 if( p->pPreStmt==0 ){
1365 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1366 if( rc!=TCL_OK ) return rc;
1367 }else{
1368 int rcs;
1369 SqliteDb *pDb = p->pDb;
1370 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1371 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1372
1373 rcs = sqlite3_step(pStmt);
1374 if( rcs==SQLITE_ROW ){
1375 return TCL_OK;
1376 }
1377 if( p->pArray ){
1378 dbEvalRowInfo(p, 0, 0);
1379 }
1380 rcs = sqlite3_reset(pStmt);
1381
1382 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1383 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001384 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
dan4a4c11a2009-10-06 14:59:02 +00001385 dbReleaseColumnNames(p);
1386 p->pPreStmt = 0;
1387
1388 if( rcs!=SQLITE_OK ){
1389 /* If a run-time error occurs, report the error and stop reading
1390 ** the SQL. */
1391 Tcl_SetObjResult(pDb->interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1392 dbReleaseStmt(pDb, pPreStmt, 1);
1393 return TCL_ERROR;
1394 }else{
1395 dbReleaseStmt(pDb, pPreStmt, 0);
1396 }
1397 }
1398 }
1399
1400 /* Finished */
1401 return TCL_BREAK;
1402}
1403
1404/*
1405** Free all resources currently held by the DbEvalContext structure passed
1406** as the first argument. There should be exactly one call to this function
1407** for each call to dbEvalInit().
1408*/
1409static void dbEvalFinalize(DbEvalContext *p){
1410 if( p->pPreStmt ){
1411 sqlite3_reset(p->pPreStmt->pStmt);
1412 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1413 p->pPreStmt = 0;
1414 }
1415 if( p->pArray ){
1416 Tcl_DecrRefCount(p->pArray);
1417 p->pArray = 0;
1418 }
1419 Tcl_DecrRefCount(p->pSql);
1420 dbReleaseColumnNames(p);
1421}
1422
1423/*
1424** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1425** the value for the iCol'th column of the row currently pointed to by
1426** the DbEvalContext structure passed as the first argument.
1427*/
1428static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1429 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1430 switch( sqlite3_column_type(pStmt, iCol) ){
1431 case SQLITE_BLOB: {
1432 int bytes = sqlite3_column_bytes(pStmt, iCol);
1433 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1434 if( !zBlob ) bytes = 0;
1435 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1436 }
1437 case SQLITE_INTEGER: {
1438 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1439 if( v>=-2147483647 && v<=2147483647 ){
1440 return Tcl_NewIntObj(v);
1441 }else{
1442 return Tcl_NewWideIntObj(v);
1443 }
1444 }
1445 case SQLITE_FLOAT: {
1446 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1447 }
1448 case SQLITE_NULL: {
1449 return dbTextToObj(p->pDb->zNull);
1450 }
1451 }
1452
1453 return dbTextToObj((char *)sqlite3_column_text(pStmt, iCol));
1454}
1455
1456/*
1457** If using Tcl version 8.6 or greater, use the NR functions to avoid
1458** recursive evalution of scripts by the [db eval] and [db trans]
1459** commands. Even if the headers used while compiling the extension
1460** are 8.6 or newer, the code still tests the Tcl version at runtime.
1461** This allows stubs-enabled builds to be used with older Tcl libraries.
1462*/
1463#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001464# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001465static int DbUseNre(void){
1466 int major, minor;
1467 Tcl_GetVersion(&major, &minor, 0, 0);
1468 return( (major==8 && minor>=6) || major>8 );
1469}
1470#else
1471/*
1472** Compiling using headers earlier than 8.6. In this case NR cannot be
1473** used, so DbUseNre() to always return zero. Add #defines for the other
1474** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1475** even though the only invocations of them are within conditional blocks
1476** of the form:
1477**
1478** if( DbUseNre() ) { ... }
1479*/
drha2c8a952009-10-13 18:38:34 +00001480# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001481# define DbUseNre() 0
1482# define Tcl_NRAddCallback(a,b,c,d,e,f) 0
1483# define Tcl_NREvalObj(a,b,c) 0
1484# define Tcl_NRCreateCommand(a,b,c,d,e,f) 0
1485#endif
1486
1487/*
1488** This function is part of the implementation of the command:
1489**
1490** $db eval SQL ?ARRAYNAME? SCRIPT
1491*/
1492static int DbEvalNextCmd(
1493 ClientData data[], /* data[0] is the (DbEvalContext*) */
1494 Tcl_Interp *interp, /* Tcl interpreter */
1495 int result /* Result so far */
1496){
1497 int rc = result; /* Return code */
1498
1499 /* The first element of the data[] array is a pointer to a DbEvalContext
1500 ** structure allocated using Tcl_Alloc(). The second element of data[]
1501 ** is a pointer to a Tcl_Obj containing the script to run for each row
1502 ** returned by the queries encapsulated in data[0]. */
1503 DbEvalContext *p = (DbEvalContext *)data[0];
1504 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1505 Tcl_Obj *pArray = p->pArray;
1506
1507 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1508 int i;
1509 int nCol;
1510 Tcl_Obj **apColName;
1511 dbEvalRowInfo(p, &nCol, &apColName);
1512 for(i=0; i<nCol; i++){
1513 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1514 if( pArray==0 ){
1515 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1516 }else{
1517 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1518 }
1519 }
1520
1521 /* The required interpreter variables are now populated with the data
1522 ** from the current row. If using NRE, schedule callbacks to evaluate
1523 ** script pScript, then to invoke this function again to fetch the next
1524 ** row (or clean up if there is no next row or the script throws an
1525 ** exception). After scheduling the callbacks, return control to the
1526 ** caller.
1527 **
1528 ** If not using NRE, evaluate pScript directly and continue with the
1529 ** next iteration of this while(...) loop. */
1530 if( DbUseNre() ){
1531 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1532 return Tcl_NREvalObj(interp, pScript, 0);
1533 }else{
1534 rc = Tcl_EvalObjEx(interp, pScript, 0);
1535 }
1536 }
1537
1538 Tcl_DecrRefCount(pScript);
1539 dbEvalFinalize(p);
1540 Tcl_Free((char *)p);
1541
1542 if( rc==TCL_OK || rc==TCL_BREAK ){
1543 Tcl_ResetResult(interp);
1544 rc = TCL_OK;
1545 }
1546 return rc;
danielk19778e556522007-11-13 10:30:24 +00001547}
1548
tpoindex1067fe12004-12-17 15:41:11 +00001549/*
drh75897232000-05-29 14:26:00 +00001550** The "sqlite" command below creates a new Tcl command for each
1551** connection it opens to an SQLite database. This routine is invoked
1552** whenever one of those connection-specific commands is executed
1553** in Tcl. For example, if you run Tcl code like this:
1554**
drh9bb575f2004-09-06 17:24:11 +00001555** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001556** db1 close
1557**
1558** The first command opens a connection to the "my_database" database
1559** and calls that connection "db1". The second command causes this
1560** subroutine to be invoked.
1561*/
drh6d313162000-09-21 13:01:35 +00001562static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001563 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001564 int choice;
drh22fbcb82004-02-01 01:22:50 +00001565 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001566 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001567 "authorizer", "backup", "busy",
1568 "cache", "changes", "close",
1569 "collate", "collation_needed", "commit_hook",
1570 "complete", "copy", "enable_load_extension",
1571 "errorcode", "eval", "exists",
1572 "function", "incrblob", "interrupt",
drh833bf962010-04-28 14:42:19 +00001573 "last_insert_rowid", "nullvalue", "onecolumn",
1574 "profile", "progress", "rekey",
1575 "restore", "rollback_hook", "status",
1576 "timeout", "total_changes", "trace",
1577 "transaction", "unlock_notify", "update_hook",
1578 "version", "wal_hook", 0
drh6d313162000-09-21 13:01:35 +00001579 };
drh411995d2002-06-25 19:31:18 +00001580 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001581 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1582 DB_CACHE, DB_CHANGES, DB_CLOSE,
1583 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1584 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1585 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1586 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
drh833bf962010-04-28 14:42:19 +00001587 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
1588 DB_PROFILE, DB_PROGRESS, DB_REKEY,
1589 DB_RESTORE, DB_ROLLBACK_HOOK, DB_STATUS,
1590 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
1591 DB_TRANSACTION, DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK,
1592 DB_VERSION, DB_WAL_HOOK
drh6d313162000-09-21 13:01:35 +00001593 };
tpoindex1067fe12004-12-17 15:41:11 +00001594 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001595
1596 if( objc<2 ){
1597 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001598 return TCL_ERROR;
1599 }
drh411995d2002-06-25 19:31:18 +00001600 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001601 return TCL_ERROR;
1602 }
1603
drh411995d2002-06-25 19:31:18 +00001604 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001605
drhe22a3342003-04-22 20:30:37 +00001606 /* $db authorizer ?CALLBACK?
1607 **
1608 ** Invoke the given callback to authorize each SQL operation as it is
1609 ** compiled. 5 arguments are appended to the callback before it is
1610 ** invoked:
1611 **
1612 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1613 ** (2) First descriptive name (depends on authorization type)
1614 ** (3) Second descriptive name
1615 ** (4) Name of the database (ex: "main", "temp")
1616 ** (5) Name of trigger that is doing the access
1617 **
1618 ** The callback should return on of the following strings: SQLITE_OK,
1619 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1620 **
1621 ** If this method is invoked with no arguments, the current authorization
1622 ** callback string is returned.
1623 */
1624 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001625#ifdef SQLITE_OMIT_AUTHORIZATION
1626 Tcl_AppendResult(interp, "authorization not available in this build", 0);
1627 return TCL_ERROR;
1628#else
drhe22a3342003-04-22 20:30:37 +00001629 if( objc>3 ){
1630 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001631 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001632 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001633 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +00001634 Tcl_AppendResult(interp, pDb->zAuth, 0);
1635 }
1636 }else{
1637 char *zAuth;
1638 int len;
1639 if( pDb->zAuth ){
1640 Tcl_Free(pDb->zAuth);
1641 }
1642 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1643 if( zAuth && len>0 ){
1644 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001645 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001646 }else{
1647 pDb->zAuth = 0;
1648 }
drhe22a3342003-04-22 20:30:37 +00001649 if( pDb->zAuth ){
1650 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001651 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +00001652 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001653 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001654 }
drhe22a3342003-04-22 20:30:37 +00001655 }
drh1211de32004-07-26 12:24:22 +00001656#endif
drhe22a3342003-04-22 20:30:37 +00001657 break;
1658 }
1659
drhdc2c4912009-02-04 22:46:47 +00001660 /* $db backup ?DATABASE? FILENAME
1661 **
1662 ** Open or create a database file named FILENAME. Transfer the
1663 ** content of local database DATABASE (default: "main") into the
1664 ** FILENAME database.
1665 */
1666 case DB_BACKUP: {
1667 const char *zDestFile;
1668 const char *zSrcDb;
1669 sqlite3 *pDest;
1670 sqlite3_backup *pBackup;
1671
1672 if( objc==3 ){
1673 zSrcDb = "main";
1674 zDestFile = Tcl_GetString(objv[2]);
1675 }else if( objc==4 ){
1676 zSrcDb = Tcl_GetString(objv[2]);
1677 zDestFile = Tcl_GetString(objv[3]);
1678 }else{
1679 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1680 return TCL_ERROR;
1681 }
1682 rc = sqlite3_open(zDestFile, &pDest);
1683 if( rc!=SQLITE_OK ){
1684 Tcl_AppendResult(interp, "cannot open target database: ",
1685 sqlite3_errmsg(pDest), (char*)0);
1686 sqlite3_close(pDest);
1687 return TCL_ERROR;
1688 }
1689 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1690 if( pBackup==0 ){
1691 Tcl_AppendResult(interp, "backup failed: ",
1692 sqlite3_errmsg(pDest), (char*)0);
1693 sqlite3_close(pDest);
1694 return TCL_ERROR;
1695 }
1696 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1697 sqlite3_backup_finish(pBackup);
1698 if( rc==SQLITE_DONE ){
1699 rc = TCL_OK;
1700 }else{
1701 Tcl_AppendResult(interp, "backup failed: ",
1702 sqlite3_errmsg(pDest), (char*)0);
1703 rc = TCL_ERROR;
1704 }
1705 sqlite3_close(pDest);
1706 break;
1707 }
1708
drhbec3f402000-08-04 13:49:02 +00001709 /* $db busy ?CALLBACK?
1710 **
1711 ** Invoke the given callback if an SQL statement attempts to open
1712 ** a locked database file.
1713 */
drh6d313162000-09-21 13:01:35 +00001714 case DB_BUSY: {
1715 if( objc>3 ){
1716 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001717 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001718 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001719 if( pDb->zBusy ){
1720 Tcl_AppendResult(interp, pDb->zBusy, 0);
1721 }
1722 }else{
drh6d313162000-09-21 13:01:35 +00001723 char *zBusy;
1724 int len;
drhbec3f402000-08-04 13:49:02 +00001725 if( pDb->zBusy ){
1726 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001727 }
drh6d313162000-09-21 13:01:35 +00001728 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1729 if( zBusy && len>0 ){
1730 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001731 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001732 }else{
1733 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001734 }
1735 if( pDb->zBusy ){
1736 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001737 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001738 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001739 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001740 }
1741 }
drh6d313162000-09-21 13:01:35 +00001742 break;
1743 }
drhbec3f402000-08-04 13:49:02 +00001744
drhfb7e7652005-01-24 00:28:42 +00001745 /* $db cache flush
1746 ** $db cache size n
1747 **
1748 ** Flush the prepared statement cache, or set the maximum number of
1749 ** cached statements.
1750 */
1751 case DB_CACHE: {
1752 char *subCmd;
1753 int n;
1754
1755 if( objc<=2 ){
1756 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1757 return TCL_ERROR;
1758 }
1759 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1760 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1761 if( objc!=3 ){
1762 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1763 return TCL_ERROR;
1764 }else{
1765 flushStmtCache( pDb );
1766 }
1767 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1768 if( objc!=4 ){
1769 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1770 return TCL_ERROR;
1771 }else{
1772 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1773 Tcl_AppendResult( interp, "cannot convert \"",
1774 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1775 return TCL_ERROR;
1776 }else{
1777 if( n<0 ){
1778 flushStmtCache( pDb );
1779 n = 0;
1780 }else if( n>MAX_PREPARED_STMTS ){
1781 n = MAX_PREPARED_STMTS;
1782 }
1783 pDb->maxStmt = n;
1784 }
1785 }
1786 }else{
1787 Tcl_AppendResult( interp, "bad option \"",
danielk1977191fadc2007-10-23 08:17:48 +00001788 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
drhfb7e7652005-01-24 00:28:42 +00001789 return TCL_ERROR;
1790 }
1791 break;
1792 }
1793
danielk1977b28af712004-06-21 06:50:26 +00001794 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001795 **
1796 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001797 ** the most recent INSERT, UPDATE or DELETE statement, not including
1798 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001799 */
1800 case DB_CHANGES: {
1801 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001802 if( objc!=2 ){
1803 Tcl_WrongNumArgs(interp, 2, objv, "");
1804 return TCL_ERROR;
1805 }
drhc8d30ac2002-04-12 10:08:59 +00001806 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001807 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001808 break;
1809 }
1810
drh75897232000-05-29 14:26:00 +00001811 /* $db close
1812 **
1813 ** Shutdown the database
1814 */
drh6d313162000-09-21 13:01:35 +00001815 case DB_CLOSE: {
1816 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1817 break;
1818 }
drh75897232000-05-29 14:26:00 +00001819
drh0f14e2e2004-06-29 12:39:08 +00001820 /*
1821 ** $db collate NAME 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_COLLATE: {
1827 SqlCollate *pCollate;
1828 char *zName;
1829 char *zScript;
1830 int nScript;
1831 if( objc!=4 ){
1832 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1833 return TCL_ERROR;
1834 }
1835 zName = Tcl_GetStringFromObj(objv[2], 0);
1836 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1837 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1838 if( pCollate==0 ) return TCL_ERROR;
1839 pCollate->interp = interp;
1840 pCollate->pNext = pDb->pCollate;
1841 pCollate->zScript = (char*)&pCollate[1];
1842 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001843 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001844 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1845 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001846 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001847 return TCL_ERROR;
1848 }
1849 break;
1850 }
1851
1852 /*
1853 ** $db collation_needed SCRIPT
1854 **
1855 ** Create a new SQL collation function called NAME. Whenever
1856 ** that function is called, invoke SCRIPT to evaluate the function.
1857 */
1858 case DB_COLLATION_NEEDED: {
1859 if( objc!=3 ){
1860 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1861 return TCL_ERROR;
1862 }
1863 if( pDb->pCollateNeeded ){
1864 Tcl_DecrRefCount(pDb->pCollateNeeded);
1865 }
1866 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1867 Tcl_IncrRefCount(pDb->pCollateNeeded);
1868 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1869 break;
1870 }
1871
drh19e2d372005-08-29 23:00:03 +00001872 /* $db commit_hook ?CALLBACK?
1873 **
1874 ** Invoke the given callback just before committing every SQL transaction.
1875 ** If the callback throws an exception or returns non-zero, then the
1876 ** transaction is aborted. If CALLBACK is an empty string, the callback
1877 ** is disabled.
1878 */
1879 case DB_COMMIT_HOOK: {
1880 if( objc>3 ){
1881 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1882 return TCL_ERROR;
1883 }else if( objc==2 ){
1884 if( pDb->zCommit ){
1885 Tcl_AppendResult(interp, pDb->zCommit, 0);
1886 }
1887 }else{
1888 char *zCommit;
1889 int len;
1890 if( pDb->zCommit ){
1891 Tcl_Free(pDb->zCommit);
1892 }
1893 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1894 if( zCommit && len>0 ){
1895 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001896 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001897 }else{
1898 pDb->zCommit = 0;
1899 }
1900 if( pDb->zCommit ){
1901 pDb->interp = interp;
1902 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1903 }else{
1904 sqlite3_commit_hook(pDb->db, 0, 0);
1905 }
1906 }
1907 break;
1908 }
1909
drh75897232000-05-29 14:26:00 +00001910 /* $db complete SQL
1911 **
1912 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1913 ** additional lines of input are needed. This is similar to the
1914 ** built-in "info complete" command of Tcl.
1915 */
drh6d313162000-09-21 13:01:35 +00001916 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00001917#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00001918 Tcl_Obj *pResult;
1919 int isComplete;
1920 if( objc!=3 ){
1921 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00001922 return TCL_ERROR;
1923 }
danielk19776f8a5032004-05-10 10:34:51 +00001924 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00001925 pResult = Tcl_GetObjResult(interp);
1926 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00001927#endif
drh6d313162000-09-21 13:01:35 +00001928 break;
1929 }
drhdcd997e2003-01-31 17:21:49 +00001930
drh19e2d372005-08-29 23:00:03 +00001931 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1932 **
1933 ** Copy data into table from filename, optionally using SEPARATOR
1934 ** as column separators. If a column contains a null string, or the
1935 ** value of NULLINDICATOR, a NULL is inserted for the column.
1936 ** conflict-algorithm is one of the sqlite conflict algorithms:
1937 ** rollback, abort, fail, ignore, replace
1938 ** On success, return the number of lines processed, not necessarily same
1939 ** as 'db changes' due to conflict-algorithm selected.
1940 **
1941 ** This code is basically an implementation/enhancement of
1942 ** the sqlite3 shell.c ".import" command.
1943 **
1944 ** This command usage is equivalent to the sqlite2.x COPY statement,
1945 ** which imports file data into a table using the PostgreSQL COPY file format:
1946 ** $db copy $conflit_algo $table_name $filename \t \\N
1947 */
1948 case DB_COPY: {
1949 char *zTable; /* Insert data into this table */
1950 char *zFile; /* The file from which to extract data */
1951 char *zConflict; /* The conflict algorithm to use */
1952 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00001953 int nCol; /* Number of columns in the table */
1954 int nByte; /* Number of bytes in an SQL string */
1955 int i, j; /* Loop counters */
1956 int nSep; /* Number of bytes in zSep[] */
1957 int nNull; /* Number of bytes in zNull[] */
1958 char *zSql; /* An SQL statement */
1959 char *zLine; /* A single line of input from the file */
1960 char **azCol; /* zLine[] broken up into columns */
1961 char *zCommit; /* How to commit changes */
1962 FILE *in; /* The input file */
1963 int lineno = 0; /* Line number of input file */
1964 char zLineNum[80]; /* Line number print buffer */
1965 Tcl_Obj *pResult; /* interp result */
1966
1967 char *zSep;
1968 char *zNull;
1969 if( objc<5 || objc>7 ){
1970 Tcl_WrongNumArgs(interp, 2, objv,
1971 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1972 return TCL_ERROR;
1973 }
1974 if( objc>=6 ){
1975 zSep = Tcl_GetStringFromObj(objv[5], 0);
1976 }else{
1977 zSep = "\t";
1978 }
1979 if( objc>=7 ){
1980 zNull = Tcl_GetStringFromObj(objv[6], 0);
1981 }else{
1982 zNull = "";
1983 }
1984 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1985 zTable = Tcl_GetStringFromObj(objv[3], 0);
1986 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00001987 nSep = strlen30(zSep);
1988 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00001989 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00001990 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00001991 return TCL_ERROR;
1992 }
drh3e59c012008-09-23 10:12:13 +00001993 if(strcmp(zConflict, "rollback") != 0 &&
1994 strcmp(zConflict, "abort" ) != 0 &&
1995 strcmp(zConflict, "fail" ) != 0 &&
1996 strcmp(zConflict, "ignore" ) != 0 &&
1997 strcmp(zConflict, "replace" ) != 0 ) {
drh19e2d372005-08-29 23:00:03 +00001998 Tcl_AppendResult(interp, "Error: \"", zConflict,
1999 "\", conflict-algorithm must be one of: rollback, "
2000 "abort, fail, ignore, or replace", 0);
2001 return TCL_ERROR;
2002 }
2003 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2004 if( zSql==0 ){
2005 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
2006 return TCL_ERROR;
2007 }
drh4f21c4a2008-12-10 22:15:00 +00002008 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002009 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002010 sqlite3_free(zSql);
2011 if( rc ){
2012 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2013 nCol = 0;
2014 }else{
2015 nCol = sqlite3_column_count(pStmt);
2016 }
2017 sqlite3_finalize(pStmt);
2018 if( nCol==0 ) {
2019 return TCL_ERROR;
2020 }
2021 zSql = malloc( nByte + 50 + nCol*2 );
2022 if( zSql==0 ) {
2023 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
2024 return TCL_ERROR;
2025 }
2026 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2027 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002028 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002029 for(i=1; i<nCol; i++){
2030 zSql[j++] = ',';
2031 zSql[j++] = '?';
2032 }
2033 zSql[j++] = ')';
2034 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002035 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002036 free(zSql);
2037 if( rc ){
2038 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2039 sqlite3_finalize(pStmt);
2040 return TCL_ERROR;
2041 }
2042 in = fopen(zFile, "rb");
2043 if( in==0 ){
2044 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2045 sqlite3_finalize(pStmt);
2046 return TCL_ERROR;
2047 }
2048 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2049 if( azCol==0 ) {
2050 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00002051 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002052 return TCL_ERROR;
2053 }
drh37527852006-03-16 16:19:56 +00002054 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002055 zCommit = "COMMIT";
2056 while( (zLine = local_getline(0, in))!=0 ){
2057 char *z;
2058 i = 0;
2059 lineno++;
2060 azCol[0] = zLine;
2061 for(i=0, z=zLine; *z; z++){
2062 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2063 *z = 0;
2064 i++;
2065 if( i<nCol ){
2066 azCol[i] = &z[nSep];
2067 z += nSep-1;
2068 }
2069 }
2070 }
2071 if( i+1!=nCol ){
2072 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002073 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002074 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002075 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002076 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002077 "Error: %s line %d: expected %d columns of data but found %d",
2078 zFile, lineno, nCol, i+1);
2079 Tcl_AppendResult(interp, zErr, 0);
2080 free(zErr);
2081 }
drh19e2d372005-08-29 23:00:03 +00002082 zCommit = "ROLLBACK";
2083 break;
2084 }
2085 for(i=0; i<nCol; i++){
2086 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002087 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
drh4f21c4a2008-12-10 22:15:00 +00002088 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002089 ){
drh19e2d372005-08-29 23:00:03 +00002090 sqlite3_bind_null(pStmt, i+1);
2091 }else{
2092 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2093 }
2094 }
2095 sqlite3_step(pStmt);
2096 rc = sqlite3_reset(pStmt);
2097 free(zLine);
2098 if( rc!=SQLITE_OK ){
2099 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
2100 zCommit = "ROLLBACK";
2101 break;
2102 }
2103 }
2104 free(azCol);
2105 fclose(in);
2106 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002107 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002108
2109 if( zCommit[0] == 'C' ){
2110 /* success, set result as number of lines processed */
2111 pResult = Tcl_GetObjResult(interp);
2112 Tcl_SetIntObj(pResult, lineno);
2113 rc = TCL_OK;
2114 }else{
2115 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002116 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00002117 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
2118 rc = TCL_ERROR;
2119 }
2120 break;
2121 }
2122
drhdcd997e2003-01-31 17:21:49 +00002123 /*
drh41449052006-07-06 17:08:48 +00002124 ** $db enable_load_extension BOOLEAN
2125 **
2126 ** Turn the extension loading feature on or off. It if off by
2127 ** default.
2128 */
2129 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002130#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002131 int onoff;
2132 if( objc!=3 ){
2133 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2134 return TCL_ERROR;
2135 }
2136 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2137 return TCL_ERROR;
2138 }
2139 sqlite3_enable_load_extension(pDb->db, onoff);
2140 break;
drhf533acc2006-12-19 18:57:11 +00002141#else
2142 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2143 0);
2144 return TCL_ERROR;
2145#endif
drh41449052006-07-06 17:08:48 +00002146 }
2147
2148 /*
drhdcd997e2003-01-31 17:21:49 +00002149 ** $db errorcode
2150 **
2151 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002152 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002153 */
2154 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002155 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002156 break;
2157 }
dan4a4c11a2009-10-06 14:59:02 +00002158
2159 /*
2160 ** $db exists $sql
2161 ** $db onecolumn $sql
2162 **
2163 ** The onecolumn method is the equivalent of:
2164 ** lindex [$db eval $sql] 0
2165 */
2166 case DB_EXISTS:
2167 case DB_ONECOLUMN: {
2168 DbEvalContext sEval;
2169 if( objc!=3 ){
2170 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2171 return TCL_ERROR;
2172 }
2173
2174 dbEvalInit(&sEval, pDb, objv[2], 0);
2175 rc = dbEvalStep(&sEval);
2176 if( choice==DB_ONECOLUMN ){
2177 if( rc==TCL_OK ){
2178 Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
2179 }
2180 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2181 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
2182 }
2183 dbEvalFinalize(&sEval);
2184
2185 if( rc==TCL_BREAK ){
2186 rc = TCL_OK;
2187 }
2188 break;
2189 }
drh75897232000-05-29 14:26:00 +00002190
2191 /*
drh895d7472004-08-20 16:02:39 +00002192 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002193 **
2194 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002195 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002196 ** If "array" and "code" are omitted, then no callback is every invoked.
2197 ** If "array" is an empty string, then the values are placed in variables
2198 ** that have the same name as the fields extracted by the query.
2199 */
dan4a4c11a2009-10-06 14:59:02 +00002200 case DB_EVAL: {
2201 if( objc<3 || objc>5 ){
2202 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2203 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002204 }
dan4a4c11a2009-10-06 14:59:02 +00002205
drh92febd92004-08-20 18:34:20 +00002206 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002207 DbEvalContext sEval;
2208 Tcl_Obj *pRet = Tcl_NewObj();
2209 Tcl_IncrRefCount(pRet);
2210 dbEvalInit(&sEval, pDb, objv[2], 0);
2211 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2212 int i;
2213 int nCol;
2214 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002215 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002216 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002217 }
2218 }
dan4a4c11a2009-10-06 14:59:02 +00002219 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002220 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002221 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002222 rc = TCL_OK;
2223 }
drh1807ce32004-09-07 13:20:35 +00002224 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002225 }else{
2226 ClientData cd[2];
2227 DbEvalContext *p;
2228 Tcl_Obj *pArray = 0;
2229 Tcl_Obj *pScript;
2230
2231 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2232 pArray = objv[3];
2233 }
2234 pScript = objv[objc-1];
2235 Tcl_IncrRefCount(pScript);
2236
2237 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2238 dbEvalInit(p, pDb, objv[2], pArray);
2239
2240 cd[0] = (void *)p;
2241 cd[1] = (void *)pScript;
2242 rc = DbEvalNextCmd(cd, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002243 }
danielk197730ccda12004-05-27 12:11:31 +00002244 break;
2245 }
drhbec3f402000-08-04 13:49:02 +00002246
2247 /*
drhe3602be2008-09-09 12:31:33 +00002248 ** $db function NAME [-argcount N] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002249 **
2250 ** Create a new SQL function called NAME. Whenever that function is
2251 ** called, invoke SCRIPT to evaluate the function.
2252 */
2253 case DB_FUNCTION: {
2254 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002255 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002256 char *zName;
drhe3602be2008-09-09 12:31:33 +00002257 int nArg = -1;
2258 if( objc==6 ){
2259 const char *z = Tcl_GetString(objv[3]);
drh4f21c4a2008-12-10 22:15:00 +00002260 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002261 if( n>2 && strncmp(z, "-argcount",n)==0 ){
2262 if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
2263 if( nArg<0 ){
2264 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2265 (char*)0);
2266 return TCL_ERROR;
2267 }
2268 }
2269 pScript = objv[5];
2270 }else if( objc!=4 ){
2271 Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
drhcabb0812002-09-14 13:47:32 +00002272 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002273 }else{
2274 pScript = objv[3];
drhcabb0812002-09-14 13:47:32 +00002275 }
2276 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002277 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002278 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002279 if( pFunc->pScript ){
2280 Tcl_DecrRefCount(pFunc->pScript);
2281 }
2282 pFunc->pScript = pScript;
2283 Tcl_IncrRefCount(pScript);
2284 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
drhe3602be2008-09-09 12:31:33 +00002285 rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00002286 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002287 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002288 rc = TCL_ERROR;
2289 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002290 }
drhcabb0812002-09-14 13:47:32 +00002291 break;
2292 }
2293
2294 /*
danielk19778cbadb02007-05-03 16:31:26 +00002295 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002296 */
2297 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002298#ifdef SQLITE_OMIT_INCRBLOB
2299 Tcl_AppendResult(interp, "incrblob not available in this build", 0);
2300 return TCL_ERROR;
2301#else
danielk19778cbadb02007-05-03 16:31:26 +00002302 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002303 const char *zDb = "main";
2304 const char *zTable;
2305 const char *zColumn;
2306 sqlite_int64 iRow;
2307
danielk19778cbadb02007-05-03 16:31:26 +00002308 /* Check for the -readonly option */
2309 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2310 isReadonly = 1;
2311 }
2312
2313 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2314 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002315 return TCL_ERROR;
2316 }
2317
danielk19778cbadb02007-05-03 16:31:26 +00002318 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002319 zDb = Tcl_GetString(objv[2]);
2320 }
2321 zTable = Tcl_GetString(objv[objc-3]);
2322 zColumn = Tcl_GetString(objv[objc-2]);
2323 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2324
2325 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002326 rc = createIncrblobChannel(
2327 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
2328 );
danielk1977b4e9af92007-05-01 17:49:49 +00002329 }
danielk197732a0d8b2007-05-04 19:03:02 +00002330#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002331 break;
2332 }
2333
2334 /*
drhf11bded2006-07-17 00:02:44 +00002335 ** $db interrupt
2336 **
2337 ** Interrupt the execution of the inner-most SQL interpreter. This
2338 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2339 */
2340 case DB_INTERRUPT: {
2341 sqlite3_interrupt(pDb->db);
2342 break;
2343 }
2344
2345 /*
drh19e2d372005-08-29 23:00:03 +00002346 ** $db nullvalue ?STRING?
2347 **
2348 ** Change text used when a NULL comes back from the database. If ?STRING?
2349 ** is not present, then the current string used for NULL is returned.
2350 ** If STRING is present, then STRING is returned.
2351 **
2352 */
2353 case DB_NULLVALUE: {
2354 if( objc!=2 && objc!=3 ){
2355 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2356 return TCL_ERROR;
2357 }
2358 if( objc==3 ){
2359 int len;
2360 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2361 if( pDb->zNull ){
2362 Tcl_Free(pDb->zNull);
2363 }
2364 if( zNull && len>0 ){
2365 pDb->zNull = Tcl_Alloc( len + 1 );
2366 strncpy(pDb->zNull, zNull, len);
2367 pDb->zNull[len] = '\0';
2368 }else{
2369 pDb->zNull = 0;
2370 }
2371 }
2372 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
2373 break;
2374 }
2375
2376 /*
drhaf9ff332002-01-16 21:00:27 +00002377 ** $db last_insert_rowid
2378 **
2379 ** Return an integer which is the ROWID for the most recent insert.
2380 */
2381 case DB_LAST_INSERT_ROWID: {
2382 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002383 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002384 if( objc!=2 ){
2385 Tcl_WrongNumArgs(interp, 2, objv, "");
2386 return TCL_ERROR;
2387 }
danielk19776f8a5032004-05-10 10:34:51 +00002388 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002389 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002390 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002391 break;
2392 }
2393
2394 /*
dan4a4c11a2009-10-06 14:59:02 +00002395 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002396 */
drh1807ce32004-09-07 13:20:35 +00002397
2398 /* $db progress ?N CALLBACK?
2399 **
2400 ** Invoke the given callback every N virtual machine opcodes while executing
2401 ** queries.
2402 */
2403 case DB_PROGRESS: {
2404 if( objc==2 ){
2405 if( pDb->zProgress ){
2406 Tcl_AppendResult(interp, pDb->zProgress, 0);
2407 }
2408 }else if( objc==4 ){
2409 char *zProgress;
2410 int len;
2411 int N;
2412 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002413 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002414 };
2415 if( pDb->zProgress ){
2416 Tcl_Free(pDb->zProgress);
2417 }
2418 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2419 if( zProgress && len>0 ){
2420 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002421 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002422 }else{
2423 pDb->zProgress = 0;
2424 }
2425#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2426 if( pDb->zProgress ){
2427 pDb->interp = interp;
2428 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2429 }else{
2430 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2431 }
2432#endif
2433 }else{
2434 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002435 return TCL_ERROR;
2436 }
drh5d9d7572003-08-19 14:31:01 +00002437 break;
2438 }
2439
drh19e2d372005-08-29 23:00:03 +00002440 /* $db profile ?CALLBACK?
2441 **
2442 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2443 ** that has run. The text of the SQL and the amount of elapse time are
2444 ** appended to CALLBACK before the script is run.
2445 */
2446 case DB_PROFILE: {
2447 if( objc>3 ){
2448 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2449 return TCL_ERROR;
2450 }else if( objc==2 ){
2451 if( pDb->zProfile ){
2452 Tcl_AppendResult(interp, pDb->zProfile, 0);
2453 }
2454 }else{
2455 char *zProfile;
2456 int len;
2457 if( pDb->zProfile ){
2458 Tcl_Free(pDb->zProfile);
2459 }
2460 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2461 if( zProfile && len>0 ){
2462 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002463 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002464 }else{
2465 pDb->zProfile = 0;
2466 }
2467#ifndef SQLITE_OMIT_TRACE
2468 if( pDb->zProfile ){
2469 pDb->interp = interp;
2470 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2471 }else{
2472 sqlite3_profile(pDb->db, 0, 0);
2473 }
2474#endif
2475 }
2476 break;
2477 }
2478
drh5d9d7572003-08-19 14:31:01 +00002479 /*
drh22fbcb82004-02-01 01:22:50 +00002480 ** $db rekey KEY
2481 **
2482 ** Change the encryption key on the currently open database.
2483 */
2484 case DB_REKEY: {
2485 int nKey;
2486 void *pKey;
2487 if( objc!=3 ){
2488 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2489 return TCL_ERROR;
2490 }
2491 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00002492#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00002493 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002494 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00002495 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002496 rc = TCL_ERROR;
2497 }
2498#endif
2499 break;
2500 }
2501
drhdc2c4912009-02-04 22:46:47 +00002502 /* $db restore ?DATABASE? FILENAME
2503 **
2504 ** Open a database file named FILENAME. Transfer the content
2505 ** of FILENAME into the local database DATABASE (default: "main").
2506 */
2507 case DB_RESTORE: {
2508 const char *zSrcFile;
2509 const char *zDestDb;
2510 sqlite3 *pSrc;
2511 sqlite3_backup *pBackup;
2512 int nTimeout = 0;
2513
2514 if( objc==3 ){
2515 zDestDb = "main";
2516 zSrcFile = Tcl_GetString(objv[2]);
2517 }else if( objc==4 ){
2518 zDestDb = Tcl_GetString(objv[2]);
2519 zSrcFile = Tcl_GetString(objv[3]);
2520 }else{
2521 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2522 return TCL_ERROR;
2523 }
2524 rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
2525 if( rc!=SQLITE_OK ){
2526 Tcl_AppendResult(interp, "cannot open source database: ",
2527 sqlite3_errmsg(pSrc), (char*)0);
2528 sqlite3_close(pSrc);
2529 return TCL_ERROR;
2530 }
2531 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2532 if( pBackup==0 ){
2533 Tcl_AppendResult(interp, "restore failed: ",
2534 sqlite3_errmsg(pDb->db), (char*)0);
2535 sqlite3_close(pSrc);
2536 return TCL_ERROR;
2537 }
2538 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2539 || rc==SQLITE_BUSY ){
2540 if( rc==SQLITE_BUSY ){
2541 if( nTimeout++ >= 3 ) break;
2542 sqlite3_sleep(100);
2543 }
2544 }
2545 sqlite3_backup_finish(pBackup);
2546 if( rc==SQLITE_DONE ){
2547 rc = TCL_OK;
2548 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2549 Tcl_AppendResult(interp, "restore failed: source database busy",
2550 (char*)0);
2551 rc = TCL_ERROR;
2552 }else{
2553 Tcl_AppendResult(interp, "restore failed: ",
2554 sqlite3_errmsg(pDb->db), (char*)0);
2555 rc = TCL_ERROR;
2556 }
2557 sqlite3_close(pSrc);
2558 break;
2559 }
2560
drh22fbcb82004-02-01 01:22:50 +00002561 /*
drh3c379b02010-04-07 19:31:59 +00002562 ** $db status (step|sort|autoindex)
drhd1d38482008-10-07 23:46:38 +00002563 **
2564 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2565 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2566 */
2567 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002568 int v;
2569 const char *zOp;
2570 if( objc!=3 ){
2571 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort)");
2572 return TCL_ERROR;
2573 }
2574 zOp = Tcl_GetString(objv[2]);
2575 if( strcmp(zOp, "step")==0 ){
2576 v = pDb->nStep;
2577 }else if( strcmp(zOp, "sort")==0 ){
2578 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002579 }else if( strcmp(zOp, "autoindex")==0 ){
2580 v = pDb->nIndex;
drhd1d38482008-10-07 23:46:38 +00002581 }else{
drh3c379b02010-04-07 19:31:59 +00002582 Tcl_AppendResult(interp,
2583 "bad argument: should be autoindex, step, or sort",
drhd1d38482008-10-07 23:46:38 +00002584 (char*)0);
2585 return TCL_ERROR;
2586 }
2587 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2588 break;
2589 }
2590
2591 /*
drhbec3f402000-08-04 13:49:02 +00002592 ** $db timeout MILLESECONDS
2593 **
2594 ** Delay for the number of milliseconds specified when a file is locked.
2595 */
drh6d313162000-09-21 13:01:35 +00002596 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002597 int ms;
drh6d313162000-09-21 13:01:35 +00002598 if( objc!=3 ){
2599 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002600 return TCL_ERROR;
2601 }
drh6d313162000-09-21 13:01:35 +00002602 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002603 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002604 break;
drh75897232000-05-29 14:26:00 +00002605 }
danielk197755c45f22005-04-03 23:54:43 +00002606
2607 /*
drh0f14e2e2004-06-29 12:39:08 +00002608 ** $db total_changes
2609 **
2610 ** Return the number of rows that were modified, inserted, or deleted
2611 ** since the database handle was created.
2612 */
2613 case DB_TOTAL_CHANGES: {
2614 Tcl_Obj *pResult;
2615 if( objc!=2 ){
2616 Tcl_WrongNumArgs(interp, 2, objv, "");
2617 return TCL_ERROR;
2618 }
2619 pResult = Tcl_GetObjResult(interp);
2620 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2621 break;
2622 }
2623
drhb5a20d32003-04-23 12:25:23 +00002624 /* $db trace ?CALLBACK?
2625 **
2626 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2627 ** that is executed. The text of the SQL is appended to CALLBACK before
2628 ** it is executed.
2629 */
2630 case DB_TRACE: {
2631 if( objc>3 ){
2632 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002633 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002634 }else if( objc==2 ){
2635 if( pDb->zTrace ){
2636 Tcl_AppendResult(interp, pDb->zTrace, 0);
2637 }
2638 }else{
2639 char *zTrace;
2640 int len;
2641 if( pDb->zTrace ){
2642 Tcl_Free(pDb->zTrace);
2643 }
2644 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2645 if( zTrace && len>0 ){
2646 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002647 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002648 }else{
2649 pDb->zTrace = 0;
2650 }
drh19e2d372005-08-29 23:00:03 +00002651#ifndef SQLITE_OMIT_TRACE
drhb5a20d32003-04-23 12:25:23 +00002652 if( pDb->zTrace ){
2653 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002654 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002655 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002656 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002657 }
drh19e2d372005-08-29 23:00:03 +00002658#endif
drhb5a20d32003-04-23 12:25:23 +00002659 }
2660 break;
2661 }
2662
drh3d214232005-08-02 12:21:08 +00002663 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2664 **
2665 ** Start a new transaction (if we are not already in the midst of a
2666 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2667 ** completes, either commit the transaction or roll it back if SCRIPT
2668 ** throws an exception. Or if no new transation was started, do nothing.
2669 ** pass the exception on up the stack.
2670 **
2671 ** This command was inspired by Dave Thomas's talk on Ruby at the
2672 ** 2005 O'Reilly Open Source Convention (OSCON).
2673 */
2674 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00002675 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00002676 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00002677 if( objc!=3 && objc!=4 ){
2678 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2679 return TCL_ERROR;
2680 }
danielk1977cd38d522009-01-02 17:33:46 +00002681
dan4a4c11a2009-10-06 14:59:02 +00002682 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00002683 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002684 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002685 };
2686 enum TTYPE_enum {
2687 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2688 };
2689 int ttype;
drhb5555e72005-08-02 17:15:14 +00002690 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002691 0, &ttype) ){
2692 return TCL_ERROR;
2693 }
2694 switch( (enum TTYPE_enum)ttype ){
2695 case TTYPE_DEFERRED: /* no-op */; break;
2696 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2697 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2698 }
drh3d214232005-08-02 12:21:08 +00002699 }
danielk1977cd38d522009-01-02 17:33:46 +00002700 pScript = objv[objc-1];
2701
dan4a4c11a2009-10-06 14:59:02 +00002702 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00002703 pDb->disableAuth++;
2704 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2705 pDb->disableAuth--;
2706 if( rc!=SQLITE_OK ){
2707 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2708 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00002709 }
danielk1977cd38d522009-01-02 17:33:46 +00002710 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00002711
dan4a4c11a2009-10-06 14:59:02 +00002712 /* If using NRE, schedule a callback to invoke the script pScript, then
2713 ** a second callback to commit (or rollback) the transaction or savepoint
2714 ** opened above. If not using NRE, evaluate the script directly, then
2715 ** call function DbTransPostCmd() to commit (or rollback) the transaction
2716 ** or savepoint. */
2717 if( DbUseNre() ){
2718 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
2719 Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00002720 }else{
dan4a4c11a2009-10-06 14:59:02 +00002721 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00002722 }
2723 break;
2724 }
2725
danielk197794eb6a12005-12-15 15:22:08 +00002726 /*
danielk1977404ca072009-03-16 13:19:36 +00002727 ** $db unlock_notify ?script?
2728 */
2729 case DB_UNLOCK_NOTIFY: {
2730#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2731 Tcl_AppendResult(interp, "unlock_notify not available in this build", 0);
2732 rc = TCL_ERROR;
2733#else
2734 if( objc!=2 && objc!=3 ){
2735 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2736 rc = TCL_ERROR;
2737 }else{
2738 void (*xNotify)(void **, int) = 0;
2739 void *pNotifyArg = 0;
2740
2741 if( pDb->pUnlockNotify ){
2742 Tcl_DecrRefCount(pDb->pUnlockNotify);
2743 pDb->pUnlockNotify = 0;
2744 }
2745
2746 if( objc==3 ){
2747 xNotify = DbUnlockNotify;
2748 pNotifyArg = (void *)pDb;
2749 pDb->pUnlockNotify = objv[2];
2750 Tcl_IncrRefCount(pDb->pUnlockNotify);
2751 }
2752
2753 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
2754 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2755 rc = TCL_ERROR;
2756 }
2757 }
2758#endif
2759 break;
2760 }
2761
2762 /*
drh833bf962010-04-28 14:42:19 +00002763 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002764 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002765 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002766 */
drh833bf962010-04-28 14:42:19 +00002767 case DB_WAL_HOOK:
danielk197771fd80b2005-12-16 06:54:01 +00002768 case DB_UPDATE_HOOK:
2769 case DB_ROLLBACK_HOOK: {
2770
2771 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2772 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2773 */
2774 Tcl_Obj **ppHook;
2775 if( choice==DB_UPDATE_HOOK ){
2776 ppHook = &pDb->pUpdateHook;
drh833bf962010-04-28 14:42:19 +00002777 }else if( choice==DB_WAL_HOOK ){
dan8d22a172010-04-19 18:03:51 +00002778 ppHook = &pDb->pLogHook;
danielk197771fd80b2005-12-16 06:54:01 +00002779 }else{
2780 ppHook = &pDb->pRollbackHook;
2781 }
2782
danielk197794eb6a12005-12-15 15:22:08 +00002783 if( objc!=2 && objc!=3 ){
2784 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2785 return TCL_ERROR;
2786 }
danielk197771fd80b2005-12-16 06:54:01 +00002787 if( *ppHook ){
2788 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002789 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002790 Tcl_DecrRefCount(*ppHook);
2791 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00002792 }
2793 }
2794 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002795 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00002796 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00002797 *ppHook = objv[2];
2798 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002799 }
2800 }
danielk197771fd80b2005-12-16 06:54:01 +00002801
2802 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2803 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
drh833bf962010-04-28 14:42:19 +00002804 sqlite3_wal_hook(pDb->db,(pDb->pLogHook?DbLogHandler:0),pDb);
danielk197771fd80b2005-12-16 06:54:01 +00002805
danielk197794eb6a12005-12-15 15:22:08 +00002806 break;
2807 }
2808
danielk19774397de52005-01-12 12:44:03 +00002809 /* $db version
2810 **
2811 ** Return the version string for this database.
2812 */
2813 case DB_VERSION: {
2814 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2815 break;
2816 }
2817
tpoindex1067fe12004-12-17 15:41:11 +00002818
drh6d313162000-09-21 13:01:35 +00002819 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002820 return rc;
drh75897232000-05-29 14:26:00 +00002821}
2822
drha2c8a952009-10-13 18:38:34 +00002823#if SQLITE_TCL_NRE
2824/*
2825** Adaptor that provides an objCmd interface to the NRE-enabled
2826** interface implementation.
2827*/
2828static int DbObjCmdAdaptor(
2829 void *cd,
2830 Tcl_Interp *interp,
2831 int objc,
2832 Tcl_Obj *const*objv
2833){
2834 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
2835}
2836#endif /* SQLITE_TCL_NRE */
2837
drh75897232000-05-29 14:26:00 +00002838/*
drh3570ad92007-08-31 14:31:44 +00002839** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00002840** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00002841**
2842** This is the main Tcl command. When the "sqlite" Tcl command is
2843** invoked, this routine runs to process that command.
2844**
2845** The first argument, DBNAME, is an arbitrary name for a new
2846** database connection. This command creates a new command named
2847** DBNAME that is used to control that connection. The database
2848** connection is deleted when the DBNAME command is deleted.
2849**
drh3570ad92007-08-31 14:31:44 +00002850** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00002851**
drh75897232000-05-29 14:26:00 +00002852*/
drh22fbcb82004-02-01 01:22:50 +00002853static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002854 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002855 void *pKey = 0;
2856 int nKey = 0;
2857 const char *zArg;
drh75897232000-05-29 14:26:00 +00002858 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00002859 int i;
drh22fbcb82004-02-01 01:22:50 +00002860 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00002861 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00002862 int flags;
drh882e8e42006-08-24 02:42:27 +00002863 Tcl_DString translatedFilename;
drhd9da78a2009-03-24 15:08:09 +00002864
2865 /* In normal use, each TCL interpreter runs in a single thread. So
2866 ** by default, we can turn of mutexing on SQLite database connections.
2867 ** However, for testing purposes it is useful to have mutexes turned
2868 ** on. So, by default, mutexes default off. But if compiled with
2869 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
2870 */
2871#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
2872 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
2873#else
2874 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
2875#endif
2876
drh22fbcb82004-02-01 01:22:50 +00002877 if( objc==2 ){
2878 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002879 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00002880 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00002881 return TCL_OK;
2882 }
drh9eb9e262004-02-11 02:18:05 +00002883 if( strcmp(zArg,"-has-codec")==0 ){
2884#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002885 Tcl_AppendResult(interp,"1",0);
2886#else
2887 Tcl_AppendResult(interp,"0",0);
2888#endif
2889 return TCL_OK;
2890 }
drhfbc3eab2001-04-06 16:13:42 +00002891 }
drh3570ad92007-08-31 14:31:44 +00002892 for(i=3; i+1<objc; i+=2){
2893 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00002894 if( strcmp(zArg,"-key")==0 ){
drh3570ad92007-08-31 14:31:44 +00002895 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
2896 }else if( strcmp(zArg, "-vfs")==0 ){
2897 i++;
2898 zVfs = Tcl_GetString(objv[i]);
2899 }else if( strcmp(zArg, "-readonly")==0 ){
2900 int b;
2901 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2902 if( b ){
drh33f4e022007-09-03 15:19:34 +00002903 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00002904 flags |= SQLITE_OPEN_READONLY;
2905 }else{
2906 flags &= ~SQLITE_OPEN_READONLY;
2907 flags |= SQLITE_OPEN_READWRITE;
2908 }
2909 }else if( strcmp(zArg, "-create")==0 ){
2910 int b;
2911 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00002912 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00002913 flags |= SQLITE_OPEN_CREATE;
2914 }else{
2915 flags &= ~SQLITE_OPEN_CREATE;
2916 }
danielk19779a6284c2008-07-10 17:52:49 +00002917 }else if( strcmp(zArg, "-nomutex")==0 ){
2918 int b;
2919 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2920 if( b ){
2921 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00002922 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00002923 }else{
2924 flags &= ~SQLITE_OPEN_NOMUTEX;
2925 }
drh039963a2008-09-03 00:43:15 +00002926 }else if( strcmp(zArg, "-fullmutex")==0 ){
2927 int b;
2928 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2929 if( b ){
2930 flags |= SQLITE_OPEN_FULLMUTEX;
2931 flags &= ~SQLITE_OPEN_NOMUTEX;
2932 }else{
2933 flags &= ~SQLITE_OPEN_FULLMUTEX;
2934 }
drh3570ad92007-08-31 14:31:44 +00002935 }else{
2936 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
2937 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00002938 }
2939 }
drh3570ad92007-08-31 14:31:44 +00002940 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00002941 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00002942 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh039963a2008-09-03 00:43:15 +00002943 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN?"
drh9eb9e262004-02-11 02:18:05 +00002944#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00002945 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00002946#endif
2947 );
drh75897232000-05-29 14:26:00 +00002948 return TCL_ERROR;
2949 }
drh75897232000-05-29 14:26:00 +00002950 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00002951 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00002952 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00002953 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
2954 return TCL_ERROR;
2955 }
2956 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00002957 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00002958 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
drh3570ad92007-08-31 14:31:44 +00002959 sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00002960 Tcl_DStringFree(&translatedFilename);
danielk197780290862004-05-22 09:21:21 +00002961 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
drh9404d502006-12-19 18:46:08 +00002962 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
danielk197780290862004-05-22 09:21:21 +00002963 sqlite3_close(p->db);
2964 p->db = 0;
2965 }
drh2011d5f2004-07-22 02:40:37 +00002966#ifdef SQLITE_HAS_CODEC
drhf3a65f72007-08-22 20:18:21 +00002967 if( p->db ){
2968 sqlite3_key(p->db, pKey, nKey);
2969 }
drheb8ed702004-02-11 10:37:23 +00002970#endif
drhbec3f402000-08-04 13:49:02 +00002971 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00002972 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00002973 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00002974 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00002975 return TCL_ERROR;
2976 }
drhfb7e7652005-01-24 00:28:42 +00002977 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00002978 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00002979 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00002980 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00002981 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
2982 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00002983 }else{
2984 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
2985 }
drh75897232000-05-29 14:26:00 +00002986 return TCL_OK;
2987}
2988
2989/*
drh90ca9752001-09-28 17:47:14 +00002990** Provide a dummy Tcl_InitStubs if we are using this as a static
2991** library.
2992*/
2993#ifndef USE_TCL_STUBS
2994# undef Tcl_InitStubs
2995# define Tcl_InitStubs(a,b,c)
2996#endif
2997
2998/*
drh29bc4612005-10-05 10:40:15 +00002999** Make sure we have a PACKAGE_VERSION macro defined. This will be
3000** defined automatically by the TEA makefile. But other makefiles
3001** do not define it.
3002*/
3003#ifndef PACKAGE_VERSION
3004# define PACKAGE_VERSION SQLITE_VERSION
3005#endif
3006
3007/*
drh75897232000-05-29 14:26:00 +00003008** Initialize this module.
3009**
3010** This Tcl module contains only a single new Tcl command named "sqlite".
3011** (Hence there is no namespace. There is no point in using a namespace
3012** if the extension only supplies one new name!) The "sqlite" command is
3013** used to open a new SQLite database. See the DbMain() routine above
3014** for additional information.
3015*/
drhad6e1372006-07-10 21:15:51 +00003016EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00003017 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00003018 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00003019 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh49766d62005-01-08 18:42:28 +00003020 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00003021 Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
drh90ca9752001-09-28 17:47:14 +00003022 return TCL_OK;
3023}
drhad6e1372006-07-10 21:15:51 +00003024EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3025EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3026EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00003027EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3028EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3029EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3030EXTERN int Tclsqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
3031
drh49766d62005-01-08 18:42:28 +00003032
3033#ifndef SQLITE_3_SUFFIX_ONLY
drhad6e1372006-07-10 21:15:51 +00003034EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3035EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3036EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3037EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00003038EXTERN int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3039EXTERN int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3040EXTERN int Sqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3041EXTERN int Tclsqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
drh49766d62005-01-08 18:42:28 +00003042#endif
drh75897232000-05-29 14:26:00 +00003043
drh3e27c022004-07-23 00:01:38 +00003044#ifdef TCLSH
3045/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003046** All of the code that follows is used to build standalone TCL interpreters
3047** that are statically linked with SQLite. Enable these by compiling
3048** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3049** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3050** analysis program.
drh75897232000-05-29 14:26:00 +00003051*/
drh348784e2000-05-29 20:41:49 +00003052
drh57a02272009-10-22 20:52:05 +00003053#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3054/*
3055 * This code implements the MD5 message-digest algorithm.
3056 * The algorithm is due to Ron Rivest. This code was
3057 * written by Colin Plumb in 1993, no copyright is claimed.
3058 * This code is in the public domain; do with it what you wish.
3059 *
3060 * Equivalent code is available from RSA Data Security, Inc.
3061 * This code has been tested against that, and is equivalent,
3062 * except that you don't need to include two pages of legalese
3063 * with every copy.
3064 *
3065 * To compute the message digest of a chunk of bytes, declare an
3066 * MD5Context structure, pass it to MD5Init, call MD5Update as
3067 * needed on buffers full of bytes, and then call MD5Final, which
3068 * will fill a supplied 16-byte array with the digest.
3069 */
3070
3071/*
3072 * If compiled on a machine that doesn't have a 32-bit integer,
3073 * you just set "uint32" to the appropriate datatype for an
3074 * unsigned 32-bit integer. For example:
3075 *
3076 * cc -Duint32='unsigned long' md5.c
3077 *
3078 */
3079#ifndef uint32
3080# define uint32 unsigned int
3081#endif
3082
3083struct MD5Context {
3084 int isInit;
3085 uint32 buf[4];
3086 uint32 bits[2];
3087 unsigned char in[64];
3088};
3089typedef struct MD5Context MD5Context;
3090
3091/*
3092 * Note: this code is harmless on little-endian machines.
3093 */
3094static void byteReverse (unsigned char *buf, unsigned longs){
3095 uint32 t;
3096 do {
3097 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3098 ((unsigned)buf[1]<<8 | buf[0]);
3099 *(uint32 *)buf = t;
3100 buf += 4;
3101 } while (--longs);
3102}
3103/* The four core functions - F1 is optimized somewhat */
3104
3105/* #define F1(x, y, z) (x & y | ~x & z) */
3106#define F1(x, y, z) (z ^ (x & (y ^ z)))
3107#define F2(x, y, z) F1(z, x, y)
3108#define F3(x, y, z) (x ^ y ^ z)
3109#define F4(x, y, z) (y ^ (x | ~z))
3110
3111/* This is the central step in the MD5 algorithm. */
3112#define MD5STEP(f, w, x, y, z, data, s) \
3113 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3114
3115/*
3116 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3117 * reflect the addition of 16 longwords of new data. MD5Update blocks
3118 * the data and converts bytes into longwords for this routine.
3119 */
3120static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3121 register uint32 a, b, c, d;
3122
3123 a = buf[0];
3124 b = buf[1];
3125 c = buf[2];
3126 d = buf[3];
3127
3128 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3129 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3130 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3131 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3132 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3133 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3134 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3135 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3136 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3137 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3138 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3139 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3140 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3141 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3142 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3143 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3144
3145 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3146 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3147 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3148 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3149 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3150 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3151 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3152 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3153 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3154 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3155 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3156 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3157 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3158 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3159 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3160 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3161
3162 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3163 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3164 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3165 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3166 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3167 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3168 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3169 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3170 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3171 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3172 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3173 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3174 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3175 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3176 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3177 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3178
3179 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3180 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3181 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3182 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3183 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3184 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3185 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3186 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3187 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3188 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3189 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3190 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3191 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3192 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3193 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3194 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3195
3196 buf[0] += a;
3197 buf[1] += b;
3198 buf[2] += c;
3199 buf[3] += d;
3200}
3201
3202/*
3203 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3204 * initialization constants.
3205 */
3206static void MD5Init(MD5Context *ctx){
3207 ctx->isInit = 1;
3208 ctx->buf[0] = 0x67452301;
3209 ctx->buf[1] = 0xefcdab89;
3210 ctx->buf[2] = 0x98badcfe;
3211 ctx->buf[3] = 0x10325476;
3212 ctx->bits[0] = 0;
3213 ctx->bits[1] = 0;
3214}
3215
3216/*
3217 * Update context to reflect the concatenation of another buffer full
3218 * of bytes.
3219 */
3220static
3221void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3222 uint32 t;
3223
3224 /* Update bitcount */
3225
3226 t = ctx->bits[0];
3227 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3228 ctx->bits[1]++; /* Carry from low to high */
3229 ctx->bits[1] += len >> 29;
3230
3231 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3232
3233 /* Handle any leading odd-sized chunks */
3234
3235 if ( t ) {
3236 unsigned char *p = (unsigned char *)ctx->in + t;
3237
3238 t = 64-t;
3239 if (len < t) {
3240 memcpy(p, buf, len);
3241 return;
3242 }
3243 memcpy(p, buf, t);
3244 byteReverse(ctx->in, 16);
3245 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3246 buf += t;
3247 len -= t;
3248 }
3249
3250 /* Process data in 64-byte chunks */
3251
3252 while (len >= 64) {
3253 memcpy(ctx->in, buf, 64);
3254 byteReverse(ctx->in, 16);
3255 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3256 buf += 64;
3257 len -= 64;
3258 }
3259
3260 /* Handle any remaining bytes of data. */
3261
3262 memcpy(ctx->in, buf, len);
3263}
3264
3265/*
3266 * Final wrapup - pad to 64-byte boundary with the bit pattern
3267 * 1 0* (64-bit count of bits processed, MSB-first)
3268 */
3269static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3270 unsigned count;
3271 unsigned char *p;
3272
3273 /* Compute number of bytes mod 64 */
3274 count = (ctx->bits[0] >> 3) & 0x3F;
3275
3276 /* Set the first char of padding to 0x80. This is safe since there is
3277 always at least one byte free */
3278 p = ctx->in + count;
3279 *p++ = 0x80;
3280
3281 /* Bytes of padding needed to make 64 bytes */
3282 count = 64 - 1 - count;
3283
3284 /* Pad out to 56 mod 64 */
3285 if (count < 8) {
3286 /* Two lots of padding: Pad the first block to 64 bytes */
3287 memset(p, 0, count);
3288 byteReverse(ctx->in, 16);
3289 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3290
3291 /* Now fill the next block with 56 bytes */
3292 memset(ctx->in, 0, 56);
3293 } else {
3294 /* Pad block to 56 bytes */
3295 memset(p, 0, count-8);
3296 }
3297 byteReverse(ctx->in, 14);
3298
3299 /* Append length in bits and transform */
3300 ((uint32 *)ctx->in)[ 14 ] = ctx->bits[0];
3301 ((uint32 *)ctx->in)[ 15 ] = ctx->bits[1];
3302
3303 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3304 byteReverse((unsigned char *)ctx->buf, 4);
3305 memcpy(digest, ctx->buf, 16);
3306 memset(ctx, 0, sizeof(ctx)); /* In case it is sensitive */
3307}
3308
3309/*
3310** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3311*/
3312static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3313 static char const zEncode[] = "0123456789abcdef";
3314 int i, j;
3315
3316 for(j=i=0; i<16; i++){
3317 int a = digest[i];
3318 zBuf[j++] = zEncode[(a>>4)&0xf];
3319 zBuf[j++] = zEncode[a & 0xf];
3320 }
3321 zBuf[j] = 0;
3322}
3323
3324
3325/*
3326** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3327** each representing 16 bits of the digest and separated from each
3328** other by a "-" character.
3329*/
3330static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3331 int i, j;
3332 unsigned int x;
3333 for(i=j=0; i<16; i+=2){
3334 x = digest[i]*256 + digest[i+1];
3335 if( i>0 ) zDigest[j++] = '-';
3336 sprintf(&zDigest[j], "%05u", x);
3337 j += 5;
3338 }
3339 zDigest[j] = 0;
3340}
3341
3342/*
3343** A TCL command for md5. The argument is the text to be hashed. The
3344** Result is the hash in base64.
3345*/
3346static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3347 MD5Context ctx;
3348 unsigned char digest[16];
3349 char zBuf[50];
3350 void (*converter)(unsigned char*, char*);
3351
3352 if( argc!=2 ){
3353 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3354 " TEXT\"", 0);
3355 return TCL_ERROR;
3356 }
3357 MD5Init(&ctx);
3358 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3359 MD5Final(digest, &ctx);
3360 converter = (void(*)(unsigned char*,char*))cd;
3361 converter(digest, zBuf);
3362 Tcl_AppendResult(interp, zBuf, (char*)0);
3363 return TCL_OK;
3364}
3365
3366/*
3367** A TCL command to take the md5 hash of a file. The argument is the
3368** name of the file.
3369*/
3370static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3371 FILE *in;
3372 MD5Context ctx;
3373 void (*converter)(unsigned char*, char*);
3374 unsigned char digest[16];
3375 char zBuf[10240];
3376
3377 if( argc!=2 ){
3378 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3379 " FILENAME\"", 0);
3380 return TCL_ERROR;
3381 }
3382 in = fopen(argv[1],"rb");
3383 if( in==0 ){
3384 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
3385 "\" for reading", 0);
3386 return TCL_ERROR;
3387 }
3388 MD5Init(&ctx);
3389 for(;;){
3390 int n;
3391 n = fread(zBuf, 1, sizeof(zBuf), in);
3392 if( n<=0 ) break;
3393 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3394 }
3395 fclose(in);
3396 MD5Final(digest, &ctx);
3397 converter = (void(*)(unsigned char*,char*))cd;
3398 converter(digest, zBuf);
3399 Tcl_AppendResult(interp, zBuf, (char*)0);
3400 return TCL_OK;
3401}
3402
3403/*
3404** Register the four new TCL commands for generating MD5 checksums
3405** with the TCL interpreter.
3406*/
3407int Md5_Init(Tcl_Interp *interp){
3408 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3409 MD5DigestToBase16, 0);
3410 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3411 MD5DigestToBase10x8, 0);
3412 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3413 MD5DigestToBase16, 0);
3414 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3415 MD5DigestToBase10x8, 0);
3416 return TCL_OK;
3417}
3418#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3419
3420#if defined(SQLITE_TEST)
3421/*
3422** During testing, the special md5sum() aggregate function is available.
3423** inside SQLite. The following routines implement that function.
3424*/
3425static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3426 MD5Context *p;
3427 int i;
3428 if( argc<1 ) return;
3429 p = sqlite3_aggregate_context(context, sizeof(*p));
3430 if( p==0 ) return;
3431 if( !p->isInit ){
3432 MD5Init(p);
3433 }
3434 for(i=0; i<argc; i++){
3435 const char *zData = (char*)sqlite3_value_text(argv[i]);
3436 if( zData ){
3437 MD5Update(p, (unsigned char*)zData, strlen(zData));
3438 }
3439 }
3440}
3441static void md5finalize(sqlite3_context *context){
3442 MD5Context *p;
3443 unsigned char digest[16];
3444 char zBuf[33];
3445 p = sqlite3_aggregate_context(context, sizeof(*p));
3446 MD5Final(digest,p);
3447 MD5DigestToBase16(digest, zBuf);
3448 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3449}
3450int Md5_Register(sqlite3 *db){
3451 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
3452 md5step, md5finalize);
3453 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3454 return rc;
3455}
3456#endif /* defined(SQLITE_TEST) */
3457
3458
drh348784e2000-05-29 20:41:49 +00003459/*
drh3e27c022004-07-23 00:01:38 +00003460** If the macro TCLSH is one, then put in code this for the
3461** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003462** standard input, or if a file is named on the command line
3463** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003464*/
drh3e27c022004-07-23 00:01:38 +00003465#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00003466static char zMainloop[] =
3467 "set line {}\n"
3468 "while {![eof stdin]} {\n"
3469 "if {$line!=\"\"} {\n"
3470 "puts -nonewline \"> \"\n"
3471 "} else {\n"
3472 "puts -nonewline \"% \"\n"
3473 "}\n"
3474 "flush stdout\n"
3475 "append line [gets stdin]\n"
3476 "if {[info complete $line]} {\n"
3477 "if {[catch {uplevel #0 $line} result]} {\n"
3478 "puts stderr \"Error: $result\"\n"
3479 "} elseif {$result!=\"\"} {\n"
3480 "puts $result\n"
3481 "}\n"
3482 "set line {}\n"
3483 "} else {\n"
3484 "append line \\n\n"
3485 "}\n"
3486 "}\n"
3487;
drh3e27c022004-07-23 00:01:38 +00003488#endif
3489
drh348784e2000-05-29 20:41:49 +00003490#define TCLSH_MAIN main /* Needed to fake out mktclapp */
3491int TCLSH_MAIN(int argc, char **argv){
3492 Tcl_Interp *interp;
danielk19770a549072009-02-17 16:29:10 +00003493
3494 /* Call sqlite3_shutdown() once before doing anything else. This is to
3495 ** test that sqlite3_shutdown() can be safely called by a process before
3496 ** sqlite3_initialize() is. */
3497 sqlite3_shutdown();
3498
drh297ecf12001-04-05 15:57:13 +00003499 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00003500 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00003501 Sqlite3_Init(interp);
drh57a02272009-10-22 20:52:05 +00003502#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3503 Md5_Init(interp);
3504#endif
drhd9b02572001-04-15 00:37:09 +00003505#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00003506 {
drh2f999a62007-08-15 19:16:43 +00003507 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00003508 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00003509 extern int Sqlitetest2_Init(Tcl_Interp*);
3510 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00003511 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00003512 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00003513 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00003514 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00003515 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00003516 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00003517 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00003518 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
dan0a7a9152010-04-07 07:57:38 +00003519 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
drh984bfaa2008-03-19 16:08:53 +00003520 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00003521 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00003522 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003523 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00003524 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003525 extern int Sqlitetestschema_Init(Tcl_Interp*);
3526 extern int Sqlitetestsse_Init(Tcl_Interp*);
3527 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00003528 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00003529 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00003530 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00003531 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh522efc62009-11-10 17:24:37 +00003532 extern int Sqlitetestintarray_Init(Tcl_Interp*);
danc7991bd2010-05-05 19:04:59 +00003533 extern int Sqlitetestvfs_Init(Tcl_Interp *);
drh2e66f0b2005-04-28 17:18:48 +00003534
drh2f999a62007-08-15 19:16:43 +00003535 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00003536 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00003537 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00003538 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00003539 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00003540 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00003541 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00003542 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00003543 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00003544 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00003545 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00003546 Sqlitetest_autoext_Init(interp);
dan0a7a9152010-04-07 07:57:38 +00003547 Sqlitetest_demovfs_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00003548 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00003549 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00003550 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003551 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00003552 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003553 Sqlitetestschema_Init(interp);
3554 Sqlitetesttclvar_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00003555 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003556 SqlitetestOnefile_Init(interp);
danielk19775d1f5aa2008-04-10 14:51:00 +00003557 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00003558 Sqlitetestbackup_Init(interp);
drh522efc62009-11-10 17:24:37 +00003559 Sqlitetestintarray_Init(interp);
danc7991bd2010-05-05 19:04:59 +00003560 Sqlitetestvfs_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003561
drh89dec812005-04-28 19:03:37 +00003562#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00003563 Sqlitetestsse_Init(interp);
3564#endif
drhd1bf3512001-04-07 15:24:33 +00003565 }
3566#endif
drhc7285972009-11-10 01:13:25 +00003567 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00003568 int i;
shessad42c3a2006-08-22 23:53:46 +00003569 char zArgc[32];
3570 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
3571 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00003572 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
3573 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00003574 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00003575 Tcl_SetVar(interp, "argv", argv[i],
3576 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3577 }
drhc7285972009-11-10 01:13:25 +00003578 if( Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00003579 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00003580 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00003581 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00003582 return 1;
3583 }
drh3e27c022004-07-23 00:01:38 +00003584 }
drhc7285972009-11-10 01:13:25 +00003585 if( argc<=1 ){
drh348784e2000-05-29 20:41:49 +00003586 Tcl_GlobalEval(interp, zMainloop);
3587 }
3588 return 0;
3589}
3590#endif /* TCLSH */