blob: 91c6094fa91fe2614ca71ad94aa78739381ad9c5 [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) */
dan46c47d42011-03-01 18:42:07 +0000125 Tcl_Obj *pPreUpdateHook; /* Pre-update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000126 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drh5def0842010-05-05 20:00:25 +0000127 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000128 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000129 SqlCollate *pCollate; /* List of SQL collation functions */
130 int rc; /* Return code of most recent sqlite3_exec() */
131 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000132 SqlPreparedStmt *stmtList; /* List of prepared statements*/
133 SqlPreparedStmt *stmtLast; /* Last statement in the list */
134 int maxStmt; /* The next maximum number of stmtList */
135 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000136 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh3c379b02010-04-07 19:31:59 +0000137 int nStep, nSort, nIndex; /* Statistics for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000138 int nTransaction; /* Number of nested [transaction] methods */
drh98808ba2001-10-18 12:34:46 +0000139};
drh297ecf12001-04-05 15:57:13 +0000140
danielk1977b4e9af92007-05-01 17:49:49 +0000141struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000142 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000143 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000144 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000145 Tcl_Channel channel; /* Channel identifier */
146 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
147 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000148};
149
drhea678832008-12-10 19:26:22 +0000150/*
151** Compute a string length that is limited to what can be stored in
152** lower 30 bits of a 32-bit signed integer.
153*/
drh4f21c4a2008-12-10 22:15:00 +0000154static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000155 const char *z2 = z;
156 while( *z2 ){ z2++; }
157 return 0x3fffffff & (int)(z2 - z);
158}
drhea678832008-12-10 19:26:22 +0000159
160
danielk197732a0d8b2007-05-04 19:03:02 +0000161#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000162/*
danielk1977d04417962007-05-02 13:16:30 +0000163** Close all incrblob channels opened using database connection pDb.
164** This is called when shutting down the database connection.
165*/
166static void closeIncrblobChannels(SqliteDb *pDb){
167 IncrblobChannel *p;
168 IncrblobChannel *pNext;
169
170 for(p=pDb->pIncrblob; p; p=pNext){
171 pNext = p->pNext;
172
173 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
174 ** which deletes the IncrblobChannel structure at *p. So do not
175 ** call Tcl_Free() here.
176 */
177 Tcl_UnregisterChannel(pDb->interp, p->channel);
178 }
179}
180
181/*
danielk1977b4e9af92007-05-01 17:49:49 +0000182** Close an incremental blob channel.
183*/
184static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
185 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000186 int rc = sqlite3_blob_close(p->pBlob);
187 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000188
189 /* Remove the channel from the SqliteDb.pIncrblob list. */
190 if( p->pNext ){
191 p->pNext->pPrev = p->pPrev;
192 }
193 if( p->pPrev ){
194 p->pPrev->pNext = p->pNext;
195 }
196 if( p->pDb->pIncrblob==p ){
197 p->pDb->pIncrblob = p->pNext;
198 }
199
danielk197792d4d7a2007-05-04 12:05:56 +0000200 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000201 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000202
203 if( rc!=SQLITE_OK ){
204 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
205 return TCL_ERROR;
206 }
danielk1977b4e9af92007-05-01 17:49:49 +0000207 return TCL_OK;
208}
209
210/*
211** Read data from an incremental blob channel.
212*/
213static int incrblobInput(
214 ClientData instanceData,
215 char *buf,
216 int bufSize,
217 int *errorCodePtr
218){
219 IncrblobChannel *p = (IncrblobChannel *)instanceData;
220 int nRead = bufSize; /* Number of bytes to read */
221 int nBlob; /* Total size of the blob */
222 int rc; /* sqlite error code */
223
224 nBlob = sqlite3_blob_bytes(p->pBlob);
225 if( (p->iSeek+nRead)>nBlob ){
226 nRead = nBlob-p->iSeek;
227 }
228 if( nRead<=0 ){
229 return 0;
230 }
231
232 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
233 if( rc!=SQLITE_OK ){
234 *errorCodePtr = rc;
235 return -1;
236 }
237
238 p->iSeek += nRead;
239 return nRead;
240}
241
danielk1977d04417962007-05-02 13:16:30 +0000242/*
243** Write data to an incremental blob channel.
244*/
danielk1977b4e9af92007-05-01 17:49:49 +0000245static int incrblobOutput(
246 ClientData instanceData,
247 CONST char *buf,
248 int toWrite,
249 int *errorCodePtr
250){
251 IncrblobChannel *p = (IncrblobChannel *)instanceData;
252 int nWrite = toWrite; /* Number of bytes to write */
253 int nBlob; /* Total size of the blob */
254 int rc; /* sqlite error code */
255
256 nBlob = sqlite3_blob_bytes(p->pBlob);
257 if( (p->iSeek+nWrite)>nBlob ){
258 *errorCodePtr = EINVAL;
259 return -1;
260 }
261 if( nWrite<=0 ){
262 return 0;
263 }
264
265 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
266 if( rc!=SQLITE_OK ){
267 *errorCodePtr = EIO;
268 return -1;
269 }
270
271 p->iSeek += nWrite;
272 return nWrite;
273}
274
275/*
276** Seek an incremental blob channel.
277*/
278static int incrblobSeek(
279 ClientData instanceData,
280 long offset,
281 int seekMode,
282 int *errorCodePtr
283){
284 IncrblobChannel *p = (IncrblobChannel *)instanceData;
285
286 switch( seekMode ){
287 case SEEK_SET:
288 p->iSeek = offset;
289 break;
290 case SEEK_CUR:
291 p->iSeek += offset;
292 break;
293 case SEEK_END:
294 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
295 break;
296
297 default: assert(!"Bad seekMode");
298 }
299
300 return p->iSeek;
301}
302
303
304static void incrblobWatch(ClientData instanceData, int mode){
305 /* NO-OP */
306}
307static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
308 return TCL_ERROR;
309}
310
311static Tcl_ChannelType IncrblobChannelType = {
312 "incrblob", /* typeName */
313 TCL_CHANNEL_VERSION_2, /* version */
314 incrblobClose, /* closeProc */
315 incrblobInput, /* inputProc */
316 incrblobOutput, /* outputProc */
317 incrblobSeek, /* seekProc */
318 0, /* setOptionProc */
319 0, /* getOptionProc */
320 incrblobWatch, /* watchProc (this is a no-op) */
321 incrblobHandle, /* getHandleProc (always returns error) */
322 0, /* close2Proc */
323 0, /* blockModeProc */
324 0, /* flushProc */
325 0, /* handlerProc */
326 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000327};
328
329/*
330** Create a new incrblob channel.
331*/
332static int createIncrblobChannel(
333 Tcl_Interp *interp,
334 SqliteDb *pDb,
335 const char *zDb,
336 const char *zTable,
337 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000338 sqlite_int64 iRow,
339 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000340){
341 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000342 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000343 sqlite3_blob *pBlob;
344 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000345 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000346
347 /* This variable is used to name the channels: "incrblob_[incr count]" */
348 static int count = 0;
349 char zChannel[64];
350
danielk19778cbadb02007-05-03 16:31:26 +0000351 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000352 if( rc!=SQLITE_OK ){
353 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
354 return TCL_ERROR;
355 }
356
357 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
358 p->iSeek = 0;
359 p->pBlob = pBlob;
360
drh5bb3eb92007-05-04 13:15:55 +0000361 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000362 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
363 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000364
danielk1977d04417962007-05-02 13:16:30 +0000365 /* Link the new channel into the SqliteDb.pIncrblob list. */
366 p->pNext = pDb->pIncrblob;
367 p->pPrev = 0;
368 if( p->pNext ){
369 p->pNext->pPrev = p;
370 }
371 pDb->pIncrblob = p;
372 p->pDb = pDb;
373
374 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000375 return TCL_OK;
376}
danielk197732a0d8b2007-05-04 19:03:02 +0000377#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
378 #define closeIncrblobChannels(pDb)
379#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000380
drh6d313162000-09-21 13:01:35 +0000381/*
drhd1e47332005-06-26 17:55:33 +0000382** Look at the script prefix in pCmd. We will be executing this script
383** after first appending one or more arguments. This routine analyzes
384** the script to see if it is safe to use Tcl_EvalObjv() on the script
385** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
386** faster.
387**
388** Scripts that are safe to use with Tcl_EvalObjv() consists of a
389** command name followed by zero or more arguments with no [...] or $
390** or {...} or ; to be seen anywhere. Most callback scripts consist
391** of just a single procedure name and they meet this requirement.
392*/
393static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
394 /* We could try to do something with Tcl_Parse(). But we will instead
395 ** just do a search for forbidden characters. If any of the forbidden
396 ** characters appear in pCmd, we will report the string as unsafe.
397 */
398 const char *z;
399 int n;
400 z = Tcl_GetStringFromObj(pCmd, &n);
401 while( n-- > 0 ){
402 int c = *(z++);
403 if( c=='$' || c=='[' || c==';' ) return 0;
404 }
405 return 1;
406}
407
408/*
409** Find an SqlFunc structure with the given name. Or create a new
410** one if an existing one cannot be found. Return a pointer to the
411** structure.
412*/
413static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
414 SqlFunc *p, *pNew;
415 int i;
drh4f21c4a2008-12-10 22:15:00 +0000416 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen30(zName) + 1 );
drhd1e47332005-06-26 17:55:33 +0000417 pNew->zName = (char*)&pNew[1];
418 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
419 pNew->zName[i] = 0;
420 for(p=pDb->pFunc; p; p=p->pNext){
421 if( strcmp(p->zName, pNew->zName)==0 ){
422 Tcl_Free((char*)pNew);
423 return p;
424 }
425 }
426 pNew->interp = pDb->interp;
427 pNew->pScript = 0;
428 pNew->pNext = pDb->pFunc;
429 pDb->pFunc = pNew;
430 return pNew;
431}
432
433/*
drhfb7e7652005-01-24 00:28:42 +0000434** Finalize and free a list of prepared statements
435*/
436static void flushStmtCache( SqliteDb *pDb ){
437 SqlPreparedStmt *pPreStmt;
438
439 while( pDb->stmtList ){
440 sqlite3_finalize( pDb->stmtList->pStmt );
441 pPreStmt = pDb->stmtList;
442 pDb->stmtList = pDb->stmtList->pNext;
443 Tcl_Free( (char*)pPreStmt );
444 }
445 pDb->nStmt = 0;
446 pDb->stmtLast = 0;
447}
448
449/*
drh895d7472004-08-20 16:02:39 +0000450** TCL calls this procedure when an sqlite3 database command is
451** deleted.
drh75897232000-05-29 14:26:00 +0000452*/
453static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000454 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000455 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000456 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000457 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000458 while( pDb->pFunc ){
459 SqlFunc *pFunc = pDb->pFunc;
460 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000461 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000462 Tcl_Free((char*)pFunc);
463 }
danielk19770202b292004-06-09 09:55:16 +0000464 while( pDb->pCollate ){
465 SqlCollate *pCollate = pDb->pCollate;
466 pDb->pCollate = pCollate->pNext;
467 Tcl_Free((char*)pCollate);
468 }
drhbec3f402000-08-04 13:49:02 +0000469 if( pDb->zBusy ){
470 Tcl_Free(pDb->zBusy);
471 }
drhb5a20d32003-04-23 12:25:23 +0000472 if( pDb->zTrace ){
473 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000474 }
drh19e2d372005-08-29 23:00:03 +0000475 if( pDb->zProfile ){
476 Tcl_Free(pDb->zProfile);
477 }
drhe22a3342003-04-22 20:30:37 +0000478 if( pDb->zAuth ){
479 Tcl_Free(pDb->zAuth);
480 }
danielk197755c45f22005-04-03 23:54:43 +0000481 if( pDb->zNull ){
482 Tcl_Free(pDb->zNull);
483 }
danielk197794eb6a12005-12-15 15:22:08 +0000484 if( pDb->pUpdateHook ){
485 Tcl_DecrRefCount(pDb->pUpdateHook);
486 }
dan46c47d42011-03-01 18:42:07 +0000487 if( pDb->pPreUpdateHook ){
488 Tcl_DecrRefCount(pDb->pPreUpdateHook);
489 }
danielk197771fd80b2005-12-16 06:54:01 +0000490 if( pDb->pRollbackHook ){
491 Tcl_DecrRefCount(pDb->pRollbackHook);
492 }
drh5def0842010-05-05 20:00:25 +0000493 if( pDb->pWalHook ){
494 Tcl_DecrRefCount(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000495 }
danielk197794eb6a12005-12-15 15:22:08 +0000496 if( pDb->pCollateNeeded ){
497 Tcl_DecrRefCount(pDb->pCollateNeeded);
498 }
drhbec3f402000-08-04 13:49:02 +0000499 Tcl_Free((char*)pDb);
500}
501
502/*
503** This routine is called when a database file is locked while trying
504** to execute SQL.
505*/
danielk19772a764eb2004-06-12 01:43:26 +0000506static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000507 SqliteDb *pDb = (SqliteDb*)cd;
508 int rc;
509 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000510
drh5bb3eb92007-05-04 13:15:55 +0000511 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000512 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000513 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
514 return 0;
515 }
516 return 1;
drh75897232000-05-29 14:26:00 +0000517}
518
drh26e4a8b2008-05-01 17:16:52 +0000519#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000520/*
danielk1977348bb5d2003-10-18 09:37:26 +0000521** This routine is invoked as the 'progress callback' for the database.
522*/
523static int DbProgressHandler(void *cd){
524 SqliteDb *pDb = (SqliteDb*)cd;
525 int rc;
526
527 assert( pDb->zProgress );
528 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
529 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
530 return 1;
531 }
532 return 0;
533}
drh26e4a8b2008-05-01 17:16:52 +0000534#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000535
drhd1167392006-01-23 13:00:35 +0000536#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000537/*
drhb5a20d32003-04-23 12:25:23 +0000538** This routine is called by the SQLite trace handler whenever a new
539** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000540*/
drhb5a20d32003-04-23 12:25:23 +0000541static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000542 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000543 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000544
drhb5a20d32003-04-23 12:25:23 +0000545 Tcl_DStringInit(&str);
546 Tcl_DStringAppend(&str, pDb->zTrace, -1);
547 Tcl_DStringAppendElement(&str, zSql);
548 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
549 Tcl_DStringFree(&str);
550 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000551}
drhd1167392006-01-23 13:00:35 +0000552#endif
drh0d1a6432003-04-03 15:46:04 +0000553
drhd1167392006-01-23 13:00:35 +0000554#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000555/*
drh19e2d372005-08-29 23:00:03 +0000556** This routine is called by the SQLite profile handler after a statement
557** SQL has executed. The TCL script in pDb->zProfile is evaluated.
558*/
559static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
560 SqliteDb *pDb = (SqliteDb*)cd;
561 Tcl_DString str;
562 char zTm[100];
563
564 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
565 Tcl_DStringInit(&str);
566 Tcl_DStringAppend(&str, pDb->zProfile, -1);
567 Tcl_DStringAppendElement(&str, zSql);
568 Tcl_DStringAppendElement(&str, zTm);
569 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
570 Tcl_DStringFree(&str);
571 Tcl_ResetResult(pDb->interp);
572}
drhd1167392006-01-23 13:00:35 +0000573#endif
drh19e2d372005-08-29 23:00:03 +0000574
575/*
drhaa940ea2004-01-15 02:44:03 +0000576** This routine is called when a transaction is committed. The
577** TCL script in pDb->zCommit is executed. If it returns non-zero or
578** if it throws an exception, the transaction is rolled back instead
579** of being committed.
580*/
581static int DbCommitHandler(void *cd){
582 SqliteDb *pDb = (SqliteDb*)cd;
583 int rc;
584
585 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
586 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
587 return 1;
588 }
589 return 0;
590}
591
danielk197771fd80b2005-12-16 06:54:01 +0000592static void DbRollbackHandler(void *clientData){
593 SqliteDb *pDb = (SqliteDb*)clientData;
594 assert(pDb->pRollbackHook);
595 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
596 Tcl_BackgroundError(pDb->interp);
597 }
598}
599
drh5def0842010-05-05 20:00:25 +0000600/*
601** This procedure handles wal_hook callbacks.
602*/
603static int DbWalHandler(
dan8d22a172010-04-19 18:03:51 +0000604 void *clientData,
605 sqlite3 *db,
606 const char *zDb,
607 int nEntry
608){
drh5def0842010-05-05 20:00:25 +0000609 int ret = SQLITE_OK;
dan8d22a172010-04-19 18:03:51 +0000610 Tcl_Obj *p;
611 SqliteDb *pDb = (SqliteDb*)clientData;
612 Tcl_Interp *interp = pDb->interp;
drh5def0842010-05-05 20:00:25 +0000613 assert(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000614
drh5def0842010-05-05 20:00:25 +0000615 p = Tcl_DuplicateObj(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000616 Tcl_IncrRefCount(p);
617 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
618 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
619 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
620 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
621 ){
622 Tcl_BackgroundError(interp);
623 }
624 Tcl_DecrRefCount(p);
625
626 return ret;
627}
628
drhbcf4f482009-03-27 12:44:35 +0000629#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000630static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
631 char zBuf[64];
632 sprintf(zBuf, "%d", iArg);
633 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
634 sprintf(zBuf, "%d", nArg);
635 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
636}
637#else
drhbcf4f482009-03-27 12:44:35 +0000638# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000639#endif
640
drh69910da2009-03-27 12:32:54 +0000641#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000642static void DbUnlockNotify(void **apArg, int nArg){
643 int i;
644 for(i=0; i<nArg; i++){
645 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
646 SqliteDb *pDb = (SqliteDb *)apArg[i];
647 setTestUnlockNotifyVars(pDb->interp, i, nArg);
648 assert( pDb->pUnlockNotify);
649 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
650 Tcl_DecrRefCount(pDb->pUnlockNotify);
651 pDb->pUnlockNotify = 0;
652 }
653}
drh69910da2009-03-27 12:32:54 +0000654#endif
danielk1977404ca072009-03-16 13:19:36 +0000655
dan46c47d42011-03-01 18:42:07 +0000656/*
657** Pre-update hook callback.
658*/
659static void DbPreUpdateHandler(
660 void *p,
661 sqlite3 *db,
662 int op,
663 const char *zDb,
664 const char *zTbl,
665 sqlite_int64 iKey1,
666 sqlite_int64 iKey2
667){
668 SqliteDb *pDb = (SqliteDb *)p;
669 Tcl_Obj *pCmd;
670 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
671
672 assert( (SQLITE_DELETE-1)/9 == 0 );
673 assert( (SQLITE_INSERT-1)/9 == 1 );
674 assert( (SQLITE_UPDATE-1)/9 == 2 );
675 assert( pDb->pPreUpdateHook );
676 assert( db==pDb->db );
677 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
678
679 pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
680 Tcl_IncrRefCount(pCmd);
681 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
682 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
683 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
684 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
685 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
686 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
687 Tcl_DecrRefCount(pCmd);
688}
689
danielk197794eb6a12005-12-15 15:22:08 +0000690static void DbUpdateHandler(
691 void *p,
692 int op,
693 const char *zDb,
694 const char *zTbl,
695 sqlite_int64 rowid
696){
697 SqliteDb *pDb = (SqliteDb *)p;
698 Tcl_Obj *pCmd;
dan46c47d42011-03-01 18:42:07 +0000699 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
700
701 assert( (SQLITE_DELETE-1)/9 == 0 );
702 assert( (SQLITE_INSERT-1)/9 == 1 );
703 assert( (SQLITE_UPDATE-1)/9 == 2 );
danielk197794eb6a12005-12-15 15:22:08 +0000704
705 assert( pDb->pUpdateHook );
706 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
707
708 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
709 Tcl_IncrRefCount(pCmd);
dan46c47d42011-03-01 18:42:07 +0000710 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
danielk197794eb6a12005-12-15 15:22:08 +0000711 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
712 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
713 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
714 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
drhefdde162010-10-27 15:36:21 +0000715 Tcl_DecrRefCount(pCmd);
danielk197794eb6a12005-12-15 15:22:08 +0000716}
717
danielk19777cedc8d2004-06-10 10:50:08 +0000718static void tclCollateNeeded(
719 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000720 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000721 int enc,
722 const char *zName
723){
724 SqliteDb *pDb = (SqliteDb *)pCtx;
725 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
726 Tcl_IncrRefCount(pScript);
727 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
728 Tcl_EvalObjEx(pDb->interp, pScript, 0);
729 Tcl_DecrRefCount(pScript);
730}
731
drhaa940ea2004-01-15 02:44:03 +0000732/*
danielk19770202b292004-06-09 09:55:16 +0000733** This routine is called to evaluate an SQL collation function implemented
734** using TCL script.
735*/
736static int tclSqlCollate(
737 void *pCtx,
738 int nA,
739 const void *zA,
740 int nB,
741 const void *zB
742){
743 SqlCollate *p = (SqlCollate *)pCtx;
744 Tcl_Obj *pCmd;
745
746 pCmd = Tcl_NewStringObj(p->zScript, -1);
747 Tcl_IncrRefCount(pCmd);
748 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
749 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000750 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000751 Tcl_DecrRefCount(pCmd);
752 return (atoi(Tcl_GetStringResult(p->interp)));
753}
754
755/*
drhcabb0812002-09-14 13:47:32 +0000756** This routine is called to evaluate an SQL function implemented
757** using TCL script.
758*/
drhfb7e7652005-01-24 00:28:42 +0000759static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000760 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000761 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000762 int i;
763 int rc;
764
drhd1e47332005-06-26 17:55:33 +0000765 if( argc==0 ){
766 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
767 ** script object directly. This allows the TCL compiler to generate
768 ** bytecode for the command on the first invocation and thus make
769 ** subsequent invocations much faster. */
770 pCmd = p->pScript;
771 Tcl_IncrRefCount(pCmd);
772 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
773 Tcl_DecrRefCount(pCmd);
774 }else{
775 /* If there are arguments to the function, make a shallow copy of the
776 ** script object, lappend the arguments, then evaluate the copy.
777 **
778 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
779 ** The new Tcl_Obj contains pointers to the original list elements.
780 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
781 ** of the list to tclCmdNameType, that alternate representation will
782 ** be preserved and reused on the next invocation.
783 */
784 Tcl_Obj **aArg;
785 int nArg;
786 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
787 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
788 return;
789 }
790 pCmd = Tcl_NewListObj(nArg, aArg);
791 Tcl_IncrRefCount(pCmd);
792 for(i=0; i<argc; i++){
793 sqlite3_value *pIn = argv[i];
794 Tcl_Obj *pVal;
795
796 /* Set pVal to contain the i'th column of this row. */
797 switch( sqlite3_value_type(pIn) ){
798 case SQLITE_BLOB: {
799 int bytes = sqlite3_value_bytes(pIn);
800 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
801 break;
802 }
803 case SQLITE_INTEGER: {
804 sqlite_int64 v = sqlite3_value_int64(pIn);
805 if( v>=-2147483647 && v<=2147483647 ){
806 pVal = Tcl_NewIntObj(v);
807 }else{
808 pVal = Tcl_NewWideIntObj(v);
809 }
810 break;
811 }
812 case SQLITE_FLOAT: {
813 double r = sqlite3_value_double(pIn);
814 pVal = Tcl_NewDoubleObj(r);
815 break;
816 }
817 case SQLITE_NULL: {
818 pVal = Tcl_NewStringObj("", 0);
819 break;
820 }
821 default: {
822 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000823 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000824 break;
825 }
826 }
827 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
828 if( rc ){
829 Tcl_DecrRefCount(pCmd);
830 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
831 return;
832 }
danielk197751ad0ec2004-05-24 12:39:02 +0000833 }
drhd1e47332005-06-26 17:55:33 +0000834 if( !p->useEvalObjv ){
835 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
836 ** is a list without a string representation. To prevent this from
837 ** happening, make sure pCmd has a valid string representation */
838 Tcl_GetString(pCmd);
839 }
840 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
841 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000842 }
danielk1977562e8d32005-05-20 09:40:55 +0000843
drhc7f269d2005-05-05 10:30:29 +0000844 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000845 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000846 }else{
drhc7f269d2005-05-05 10:30:29 +0000847 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
848 int n;
849 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000850 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000851 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000852 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000853 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000854 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000855 data = Tcl_GetByteArrayFromObj(pVar, &n);
856 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000857 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000858 Tcl_GetIntFromObj(0, pVar, &n);
859 sqlite3_result_int(context, n);
860 }else if( c=='d' && strcmp(zType,"double")==0 ){
861 double r;
862 Tcl_GetDoubleFromObj(0, pVar, &r);
863 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +0000864 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
865 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000866 Tcl_WideInt v;
867 Tcl_GetWideIntFromObj(0, pVar, &v);
868 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000869 }else{
danielk197700fd9572005-12-07 06:27:43 +0000870 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
871 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000872 }
drhcabb0812002-09-14 13:47:32 +0000873 }
874}
drh895d7472004-08-20 16:02:39 +0000875
drhe22a3342003-04-22 20:30:37 +0000876#ifndef SQLITE_OMIT_AUTHORIZATION
877/*
878** This is the authentication function. It appends the authentication
879** type code and the two arguments to zCmd[] then invokes the result
880** on the interpreter. The reply is examined to determine if the
881** authentication fails or succeeds.
882*/
883static int auth_callback(
884 void *pArg,
885 int code,
886 const char *zArg1,
887 const char *zArg2,
888 const char *zArg3,
889 const char *zArg4
890){
891 char *zCode;
892 Tcl_DString str;
893 int rc;
894 const char *zReply;
895 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +0000896 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +0000897
898 switch( code ){
899 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
900 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
901 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
902 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
903 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
904 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
905 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
906 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
907 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
908 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
909 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
910 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
911 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
912 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
913 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
914 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
915 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
916 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
917 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
918 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
919 case SQLITE_READ : zCode="SQLITE_READ"; break;
920 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
921 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
922 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000923 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
924 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000925 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000926 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000927 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000928 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
929 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000930 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +0000931 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drhe22a3342003-04-22 20:30:37 +0000932 default : zCode="????"; break;
933 }
934 Tcl_DStringInit(&str);
935 Tcl_DStringAppend(&str, pDb->zAuth, -1);
936 Tcl_DStringAppendElement(&str, zCode);
937 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
938 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
939 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
940 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
941 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
942 Tcl_DStringFree(&str);
943 zReply = Tcl_GetStringResult(pDb->interp);
944 if( strcmp(zReply,"SQLITE_OK")==0 ){
945 rc = SQLITE_OK;
946 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
947 rc = SQLITE_DENY;
948 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
949 rc = SQLITE_IGNORE;
950 }else{
951 rc = 999;
952 }
953 return rc;
954}
955#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000956
957/*
danielk1977ef2cb632004-05-29 02:37:19 +0000958** zText is a pointer to text obtained via an sqlite3_result_text()
959** or similar interface. This routine returns a Tcl string object,
960** reference count set to 0, containing the text. If a translation
961** between iso8859 and UTF-8 is required, it is preformed.
962*/
963static Tcl_Obj *dbTextToObj(char const *zText){
964 Tcl_Obj *pVal;
965#ifdef UTF_TRANSLATION_NEEDED
966 Tcl_DString dCol;
967 Tcl_DStringInit(&dCol);
968 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
969 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
970 Tcl_DStringFree(&dCol);
971#else
972 pVal = Tcl_NewStringObj(zText, -1);
973#endif
974 return pVal;
975}
976
977/*
tpoindex1067fe12004-12-17 15:41:11 +0000978** This routine reads a line of text from FILE in, stores
979** the text in memory obtained from malloc() and returns a pointer
980** to the text. NULL is returned at end of file, or if malloc()
981** fails.
982**
983** The interface is like "readline" but no command-line editing
984** is done.
985**
986** copied from shell.c from '.import' command
987*/
988static char *local_getline(char *zPrompt, FILE *in){
989 char *zLine;
990 int nLine;
991 int n;
992 int eol;
993
994 nLine = 100;
995 zLine = malloc( nLine );
996 if( zLine==0 ) return 0;
997 n = 0;
998 eol = 0;
999 while( !eol ){
1000 if( n+100>nLine ){
1001 nLine = nLine*2 + 100;
1002 zLine = realloc(zLine, nLine);
1003 if( zLine==0 ) return 0;
1004 }
1005 if( fgets(&zLine[n], nLine - n, in)==0 ){
1006 if( n==0 ){
1007 free(zLine);
1008 return 0;
1009 }
1010 zLine[n] = 0;
1011 eol = 1;
1012 break;
1013 }
1014 while( zLine[n] ){ n++; }
1015 if( n>0 && zLine[n-1]=='\n' ){
1016 n--;
1017 zLine[n] = 0;
1018 eol = 1;
1019 }
1020 }
1021 zLine = realloc( zLine, n+1 );
1022 return zLine;
1023}
1024
danielk19778e556522007-11-13 10:30:24 +00001025
1026/*
dan4a4c11a2009-10-06 14:59:02 +00001027** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +00001028**
dan4a4c11a2009-10-06 14:59:02 +00001029** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +00001030**
dan4a4c11a2009-10-06 14:59:02 +00001031** It is invoked after evaluating the script SCRIPT to commit or rollback
1032** the transaction or savepoint opened by the [transaction] command.
1033*/
1034static int DbTransPostCmd(
1035 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1036 Tcl_Interp *interp, /* Tcl interpreter */
1037 int result /* Result of evaluating SCRIPT */
1038){
1039 static const char *azEnd[] = {
1040 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1041 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1042 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1043 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1044 };
1045 SqliteDb *pDb = (SqliteDb*)data[0];
1046 int rc = result;
1047 const char *zEnd;
1048
1049 pDb->nTransaction--;
1050 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1051
1052 pDb->disableAuth++;
1053 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1054 /* This is a tricky scenario to handle. The most likely cause of an
1055 ** error is that the exec() above was an attempt to commit the
1056 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1057 ** that an IO-error has occured. In either case, throw a Tcl exception
1058 ** and try to rollback the transaction.
1059 **
1060 ** But it could also be that the user executed one or more BEGIN,
1061 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1062 ** this method's logic. Not clear how this would be best handled.
1063 */
1064 if( rc!=TCL_ERROR ){
1065 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
1066 rc = TCL_ERROR;
1067 }
1068 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1069 }
1070 pDb->disableAuth--;
1071
1072 return rc;
1073}
1074
1075/*
1076** Search the cache for a prepared-statement object that implements the
1077** first SQL statement in the buffer pointed to by parameter zIn. If
1078** no such prepared-statement can be found, allocate and prepare a new
1079** one. In either case, bind the current values of the relevant Tcl
1080** variables to any $var, :var or @var variables in the statement. Before
1081** returning, set *ppPreStmt to point to the prepared-statement object.
1082**
1083** Output parameter *pzOut is set to point to the next SQL statement in
1084** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1085** next statement.
1086**
1087** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1088** and an error message loaded into interpreter pDb->interp.
1089*/
1090static int dbPrepareAndBind(
1091 SqliteDb *pDb, /* Database object */
1092 char const *zIn, /* SQL to compile */
1093 char const **pzOut, /* OUT: Pointer to next SQL statement */
1094 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1095){
1096 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
1097 sqlite3_stmt *pStmt; /* Prepared statement object */
1098 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1099 int nSql; /* Length of zSql in bytes */
1100 int nVar; /* Number of variables in statement */
1101 int iParm = 0; /* Next free entry in apParm */
1102 int i;
1103 Tcl_Interp *interp = pDb->interp;
1104
1105 *ppPreStmt = 0;
1106
1107 /* Trim spaces from the start of zSql and calculate the remaining length. */
1108 while( isspace(zSql[0]) ){ zSql++; }
1109 nSql = strlen30(zSql);
1110
1111 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1112 int n = pPreStmt->nSql;
1113 if( nSql>=n
1114 && memcmp(pPreStmt->zSql, zSql, n)==0
1115 && (zSql[n]==0 || zSql[n-1]==';')
1116 ){
1117 pStmt = pPreStmt->pStmt;
1118 *pzOut = &zSql[pPreStmt->nSql];
1119
1120 /* When a prepared statement is found, unlink it from the
1121 ** cache list. It will later be added back to the beginning
1122 ** of the cache list in order to implement LRU replacement.
1123 */
1124 if( pPreStmt->pPrev ){
1125 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1126 }else{
1127 pDb->stmtList = pPreStmt->pNext;
1128 }
1129 if( pPreStmt->pNext ){
1130 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1131 }else{
1132 pDb->stmtLast = pPreStmt->pPrev;
1133 }
1134 pDb->nStmt--;
1135 nVar = sqlite3_bind_parameter_count(pStmt);
1136 break;
1137 }
1138 }
1139
1140 /* If no prepared statement was found. Compile the SQL text. Also allocate
1141 ** a new SqlPreparedStmt structure. */
1142 if( pPreStmt==0 ){
1143 int nByte;
1144
1145 if( SQLITE_OK!=sqlite3_prepare_v2(pDb->db, zSql, -1, &pStmt, pzOut) ){
1146 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1147 return TCL_ERROR;
1148 }
1149 if( pStmt==0 ){
1150 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1151 /* A compile-time error in the statement. */
1152 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1153 return TCL_ERROR;
1154 }else{
1155 /* The statement was a no-op. Continue to the next statement
1156 ** in the SQL string.
1157 */
1158 return TCL_OK;
1159 }
1160 }
1161
1162 assert( pPreStmt==0 );
1163 nVar = sqlite3_bind_parameter_count(pStmt);
1164 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1165 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1166 memset(pPreStmt, 0, nByte);
1167
1168 pPreStmt->pStmt = pStmt;
1169 pPreStmt->nSql = (*pzOut - zSql);
1170 pPreStmt->zSql = sqlite3_sql(pStmt);
1171 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
1172 }
1173 assert( pPreStmt );
1174 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1175 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1176
1177 /* Bind values to parameters that begin with $ or : */
1178 for(i=1; i<=nVar; i++){
1179 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1180 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1181 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1182 if( pVar ){
1183 int n;
1184 u8 *data;
1185 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1186 char c = zType[0];
1187 if( zVar[0]=='@' ||
1188 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1189 /* Load a BLOB type if the Tcl variable is a bytearray and
1190 ** it has no string representation or the host
1191 ** parameter name begins with "@". */
1192 data = Tcl_GetByteArrayFromObj(pVar, &n);
1193 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1194 Tcl_IncrRefCount(pVar);
1195 pPreStmt->apParm[iParm++] = pVar;
1196 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1197 Tcl_GetIntFromObj(interp, pVar, &n);
1198 sqlite3_bind_int(pStmt, i, n);
1199 }else if( c=='d' && strcmp(zType,"double")==0 ){
1200 double r;
1201 Tcl_GetDoubleFromObj(interp, pVar, &r);
1202 sqlite3_bind_double(pStmt, i, r);
1203 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1204 (c=='i' && strcmp(zType,"int")==0) ){
1205 Tcl_WideInt v;
1206 Tcl_GetWideIntFromObj(interp, pVar, &v);
1207 sqlite3_bind_int64(pStmt, i, v);
1208 }else{
1209 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1210 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1211 Tcl_IncrRefCount(pVar);
1212 pPreStmt->apParm[iParm++] = pVar;
1213 }
1214 }else{
1215 sqlite3_bind_null(pStmt, i);
1216 }
1217 }
1218 }
1219 pPreStmt->nParm = iParm;
1220 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001221
dan4a4c11a2009-10-06 14:59:02 +00001222 return TCL_OK;
1223}
1224
1225
1226/*
1227** Release a statement reference obtained by calling dbPrepareAndBind().
1228** There should be exactly one call to this function for each call to
1229** dbPrepareAndBind().
1230**
1231** If the discard parameter is non-zero, then the statement is deleted
1232** immediately. Otherwise it is added to the LRU list and may be returned
1233** by a subsequent call to dbPrepareAndBind().
1234*/
1235static void dbReleaseStmt(
1236 SqliteDb *pDb, /* Database handle */
1237 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1238 int discard /* True to delete (not cache) the pPreStmt */
1239){
1240 int i;
1241
1242 /* Free the bound string and blob parameters */
1243 for(i=0; i<pPreStmt->nParm; i++){
1244 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1245 }
1246 pPreStmt->nParm = 0;
1247
1248 if( pDb->maxStmt<=0 || discard ){
1249 /* If the cache is turned off, deallocated the statement */
1250 sqlite3_finalize(pPreStmt->pStmt);
1251 Tcl_Free((char *)pPreStmt);
1252 }else{
1253 /* Add the prepared statement to the beginning of the cache list. */
1254 pPreStmt->pNext = pDb->stmtList;
1255 pPreStmt->pPrev = 0;
1256 if( pDb->stmtList ){
1257 pDb->stmtList->pPrev = pPreStmt;
1258 }
1259 pDb->stmtList = pPreStmt;
1260 if( pDb->stmtLast==0 ){
1261 assert( pDb->nStmt==0 );
1262 pDb->stmtLast = pPreStmt;
1263 }else{
1264 assert( pDb->nStmt>0 );
1265 }
1266 pDb->nStmt++;
1267
1268 /* If we have too many statement in cache, remove the surplus from
1269 ** the end of the cache list. */
1270 while( pDb->nStmt>pDb->maxStmt ){
1271 sqlite3_finalize(pDb->stmtLast->pStmt);
1272 pDb->stmtLast = pDb->stmtLast->pPrev;
1273 Tcl_Free((char*)pDb->stmtLast->pNext);
1274 pDb->stmtLast->pNext = 0;
1275 pDb->nStmt--;
1276 }
1277 }
1278}
1279
1280/*
1281** Structure used with dbEvalXXX() functions:
1282**
1283** dbEvalInit()
1284** dbEvalStep()
1285** dbEvalFinalize()
1286** dbEvalRowInfo()
1287** dbEvalColumnValue()
1288*/
1289typedef struct DbEvalContext DbEvalContext;
1290struct DbEvalContext {
1291 SqliteDb *pDb; /* Database handle */
1292 Tcl_Obj *pSql; /* Object holding string zSql */
1293 const char *zSql; /* Remaining SQL to execute */
1294 SqlPreparedStmt *pPreStmt; /* Current statement */
1295 int nCol; /* Number of columns returned by pStmt */
1296 Tcl_Obj *pArray; /* Name of array variable */
1297 Tcl_Obj **apColName; /* Array of column names */
1298};
1299
1300/*
1301** Release any cache of column names currently held as part of
1302** the DbEvalContext structure passed as the first argument.
1303*/
1304static void dbReleaseColumnNames(DbEvalContext *p){
1305 if( p->apColName ){
1306 int i;
1307 for(i=0; i<p->nCol; i++){
1308 Tcl_DecrRefCount(p->apColName[i]);
1309 }
1310 Tcl_Free((char *)p->apColName);
1311 p->apColName = 0;
1312 }
1313 p->nCol = 0;
1314}
1315
1316/*
1317** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001318**
1319** If pArray is not NULL, then it contains the name of a Tcl array
1320** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001321** the names of the columns returned by the statement as part of each
1322** call to dbEvalStep(), in order from left to right. e.g. if the names
1323** of the returned columns are a, b and c, it does the equivalent of the
1324** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001325**
1326** set ${pArray}(*) {a b c}
1327*/
dan4a4c11a2009-10-06 14:59:02 +00001328static void dbEvalInit(
1329 DbEvalContext *p, /* Pointer to structure to initialize */
1330 SqliteDb *pDb, /* Database handle */
1331 Tcl_Obj *pSql, /* Object containing SQL script */
1332 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001333){
dan4a4c11a2009-10-06 14:59:02 +00001334 memset(p, 0, sizeof(DbEvalContext));
1335 p->pDb = pDb;
1336 p->zSql = Tcl_GetString(pSql);
1337 p->pSql = pSql;
1338 Tcl_IncrRefCount(pSql);
1339 if( pArray ){
1340 p->pArray = pArray;
1341 Tcl_IncrRefCount(pArray);
1342 }
1343}
danielk19778e556522007-11-13 10:30:24 +00001344
dan4a4c11a2009-10-06 14:59:02 +00001345/*
1346** Obtain information about the row that the DbEvalContext passed as the
1347** first argument currently points to.
1348*/
1349static void dbEvalRowInfo(
1350 DbEvalContext *p, /* Evaluation context */
1351 int *pnCol, /* OUT: Number of column names */
1352 Tcl_Obj ***papColName /* OUT: Array of column names */
1353){
danielk19778e556522007-11-13 10:30:24 +00001354 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001355 if( 0==p->apColName ){
1356 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1357 int i; /* Iterator variable */
1358 int nCol; /* Number of columns returned by pStmt */
1359 Tcl_Obj **apColName = 0; /* Array of column names */
1360
1361 p->nCol = nCol = sqlite3_column_count(pStmt);
1362 if( nCol>0 && (papColName || p->pArray) ){
1363 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1364 for(i=0; i<nCol; i++){
1365 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1366 Tcl_IncrRefCount(apColName[i]);
1367 }
1368 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001369 }
1370
1371 /* If results are being stored in an array variable, then create
1372 ** the array(*) entry for that array
1373 */
dan4a4c11a2009-10-06 14:59:02 +00001374 if( p->pArray ){
1375 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001376 Tcl_Obj *pColList = Tcl_NewObj();
1377 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001378
danielk19778e556522007-11-13 10:30:24 +00001379 for(i=0; i<nCol; i++){
1380 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1381 }
1382 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001383 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001384 Tcl_DecrRefCount(pStar);
1385 }
danielk19778e556522007-11-13 10:30:24 +00001386 }
1387
dan4a4c11a2009-10-06 14:59:02 +00001388 if( papColName ){
1389 *papColName = p->apColName;
1390 }
1391 if( pnCol ){
1392 *pnCol = p->nCol;
1393 }
1394}
1395
1396/*
1397** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1398** returned, then an error message is stored in the interpreter before
1399** returning.
1400**
1401** A return value of TCL_OK means there is a row of data available. The
1402** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1403** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1404** is returned, then the SQL script has finished executing and there are
1405** no further rows available. This is similar to SQLITE_DONE.
1406*/
1407static int dbEvalStep(DbEvalContext *p){
1408 while( p->zSql[0] || p->pPreStmt ){
1409 int rc;
1410 if( p->pPreStmt==0 ){
1411 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1412 if( rc!=TCL_OK ) return rc;
1413 }else{
1414 int rcs;
1415 SqliteDb *pDb = p->pDb;
1416 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1417 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1418
1419 rcs = sqlite3_step(pStmt);
1420 if( rcs==SQLITE_ROW ){
1421 return TCL_OK;
1422 }
1423 if( p->pArray ){
1424 dbEvalRowInfo(p, 0, 0);
1425 }
1426 rcs = sqlite3_reset(pStmt);
1427
1428 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1429 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001430 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
dan4a4c11a2009-10-06 14:59:02 +00001431 dbReleaseColumnNames(p);
1432 p->pPreStmt = 0;
1433
1434 if( rcs!=SQLITE_OK ){
1435 /* If a run-time error occurs, report the error and stop reading
1436 ** the SQL. */
1437 Tcl_SetObjResult(pDb->interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1438 dbReleaseStmt(pDb, pPreStmt, 1);
1439 return TCL_ERROR;
1440 }else{
1441 dbReleaseStmt(pDb, pPreStmt, 0);
1442 }
1443 }
1444 }
1445
1446 /* Finished */
1447 return TCL_BREAK;
1448}
1449
1450/*
1451** Free all resources currently held by the DbEvalContext structure passed
1452** as the first argument. There should be exactly one call to this function
1453** for each call to dbEvalInit().
1454*/
1455static void dbEvalFinalize(DbEvalContext *p){
1456 if( p->pPreStmt ){
1457 sqlite3_reset(p->pPreStmt->pStmt);
1458 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1459 p->pPreStmt = 0;
1460 }
1461 if( p->pArray ){
1462 Tcl_DecrRefCount(p->pArray);
1463 p->pArray = 0;
1464 }
1465 Tcl_DecrRefCount(p->pSql);
1466 dbReleaseColumnNames(p);
1467}
1468
1469/*
1470** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1471** the value for the iCol'th column of the row currently pointed to by
1472** the DbEvalContext structure passed as the first argument.
1473*/
1474static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1475 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1476 switch( sqlite3_column_type(pStmt, iCol) ){
1477 case SQLITE_BLOB: {
1478 int bytes = sqlite3_column_bytes(pStmt, iCol);
1479 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1480 if( !zBlob ) bytes = 0;
1481 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1482 }
1483 case SQLITE_INTEGER: {
1484 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1485 if( v>=-2147483647 && v<=2147483647 ){
1486 return Tcl_NewIntObj(v);
1487 }else{
1488 return Tcl_NewWideIntObj(v);
1489 }
1490 }
1491 case SQLITE_FLOAT: {
1492 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1493 }
1494 case SQLITE_NULL: {
1495 return dbTextToObj(p->pDb->zNull);
1496 }
1497 }
1498
1499 return dbTextToObj((char *)sqlite3_column_text(pStmt, iCol));
1500}
1501
1502/*
1503** If using Tcl version 8.6 or greater, use the NR functions to avoid
1504** recursive evalution of scripts by the [db eval] and [db trans]
1505** commands. Even if the headers used while compiling the extension
1506** are 8.6 or newer, the code still tests the Tcl version at runtime.
1507** This allows stubs-enabled builds to be used with older Tcl libraries.
1508*/
1509#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001510# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001511static int DbUseNre(void){
1512 int major, minor;
1513 Tcl_GetVersion(&major, &minor, 0, 0);
1514 return( (major==8 && minor>=6) || major>8 );
1515}
1516#else
1517/*
1518** Compiling using headers earlier than 8.6. In this case NR cannot be
1519** used, so DbUseNre() to always return zero. Add #defines for the other
1520** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1521** even though the only invocations of them are within conditional blocks
1522** of the form:
1523**
1524** if( DbUseNre() ) { ... }
1525*/
drha2c8a952009-10-13 18:38:34 +00001526# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001527# define DbUseNre() 0
1528# define Tcl_NRAddCallback(a,b,c,d,e,f) 0
1529# define Tcl_NREvalObj(a,b,c) 0
1530# define Tcl_NRCreateCommand(a,b,c,d,e,f) 0
1531#endif
1532
1533/*
1534** This function is part of the implementation of the command:
1535**
1536** $db eval SQL ?ARRAYNAME? SCRIPT
1537*/
1538static int DbEvalNextCmd(
1539 ClientData data[], /* data[0] is the (DbEvalContext*) */
1540 Tcl_Interp *interp, /* Tcl interpreter */
1541 int result /* Result so far */
1542){
1543 int rc = result; /* Return code */
1544
1545 /* The first element of the data[] array is a pointer to a DbEvalContext
1546 ** structure allocated using Tcl_Alloc(). The second element of data[]
1547 ** is a pointer to a Tcl_Obj containing the script to run for each row
1548 ** returned by the queries encapsulated in data[0]. */
1549 DbEvalContext *p = (DbEvalContext *)data[0];
1550 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1551 Tcl_Obj *pArray = p->pArray;
1552
1553 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1554 int i;
1555 int nCol;
1556 Tcl_Obj **apColName;
1557 dbEvalRowInfo(p, &nCol, &apColName);
1558 for(i=0; i<nCol; i++){
1559 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1560 if( pArray==0 ){
1561 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1562 }else{
1563 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1564 }
1565 }
1566
1567 /* The required interpreter variables are now populated with the data
1568 ** from the current row. If using NRE, schedule callbacks to evaluate
1569 ** script pScript, then to invoke this function again to fetch the next
1570 ** row (or clean up if there is no next row or the script throws an
1571 ** exception). After scheduling the callbacks, return control to the
1572 ** caller.
1573 **
1574 ** If not using NRE, evaluate pScript directly and continue with the
1575 ** next iteration of this while(...) loop. */
1576 if( DbUseNre() ){
1577 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1578 return Tcl_NREvalObj(interp, pScript, 0);
1579 }else{
1580 rc = Tcl_EvalObjEx(interp, pScript, 0);
1581 }
1582 }
1583
1584 Tcl_DecrRefCount(pScript);
1585 dbEvalFinalize(p);
1586 Tcl_Free((char *)p);
1587
1588 if( rc==TCL_OK || rc==TCL_BREAK ){
1589 Tcl_ResetResult(interp);
1590 rc = TCL_OK;
1591 }
1592 return rc;
danielk19778e556522007-11-13 10:30:24 +00001593}
1594
tpoindex1067fe12004-12-17 15:41:11 +00001595/*
dan46c47d42011-03-01 18:42:07 +00001596** This function is used by the implementations of the following database
1597** handle sub-commands:
1598**
1599** $db update_hook ?SCRIPT?
1600** $db wal_hook ?SCRIPT?
1601** $db commit_hook ?SCRIPT?
1602** $db preupdate hook ?SCRIPT?
1603*/
1604static void DbHookCmd(
1605 Tcl_Interp *interp, /* Tcl interpreter */
1606 SqliteDb *pDb, /* Database handle */
1607 Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */
1608 Tcl_Obj **ppHook /* Pointer to member of SqliteDb */
1609){
1610 sqlite3 *db = pDb->db;
1611
1612 if( *ppHook ){
1613 Tcl_SetObjResult(interp, *ppHook);
1614 if( pArg ){
1615 Tcl_DecrRefCount(*ppHook);
1616 *ppHook = 0;
1617 }
1618 }
1619 if( pArg ){
1620 assert( !(*ppHook) );
1621 if( Tcl_GetCharLength(pArg)>0 ){
1622 *ppHook = pArg;
1623 Tcl_IncrRefCount(*ppHook);
1624 }
1625 }
1626
1627 sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
1628 sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1629 sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1630 sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
1631}
1632
1633/*
drh75897232000-05-29 14:26:00 +00001634** The "sqlite" command below creates a new Tcl command for each
1635** connection it opens to an SQLite database. This routine is invoked
1636** whenever one of those connection-specific commands is executed
1637** in Tcl. For example, if you run Tcl code like this:
1638**
drh9bb575f2004-09-06 17:24:11 +00001639** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001640** db1 close
1641**
1642** The first command opens a connection to the "my_database" database
1643** and calls that connection "db1". The second command causes this
1644** subroutine to be invoked.
1645*/
drh6d313162000-09-21 13:01:35 +00001646static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001647 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001648 int choice;
drh22fbcb82004-02-01 01:22:50 +00001649 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001650 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001651 "authorizer", "backup", "busy",
1652 "cache", "changes", "close",
1653 "collate", "collation_needed", "commit_hook",
1654 "complete", "copy", "enable_load_extension",
1655 "errorcode", "eval", "exists",
1656 "function", "incrblob", "interrupt",
drh833bf962010-04-28 14:42:19 +00001657 "last_insert_rowid", "nullvalue", "onecolumn",
dan46c47d42011-03-01 18:42:07 +00001658 "preupdate",
drh833bf962010-04-28 14:42:19 +00001659 "profile", "progress", "rekey",
1660 "restore", "rollback_hook", "status",
1661 "timeout", "total_changes", "trace",
1662 "transaction", "unlock_notify", "update_hook",
1663 "version", "wal_hook", 0
drh6d313162000-09-21 13:01:35 +00001664 };
drh411995d2002-06-25 19:31:18 +00001665 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001666 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1667 DB_CACHE, DB_CHANGES, DB_CLOSE,
1668 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1669 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1670 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1671 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
drh833bf962010-04-28 14:42:19 +00001672 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
dan46c47d42011-03-01 18:42:07 +00001673 DB_PREUPDATE,
drh833bf962010-04-28 14:42:19 +00001674 DB_PROFILE, DB_PROGRESS, DB_REKEY,
1675 DB_RESTORE, DB_ROLLBACK_HOOK, DB_STATUS,
1676 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
1677 DB_TRANSACTION, DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK,
1678 DB_VERSION, DB_WAL_HOOK
drh6d313162000-09-21 13:01:35 +00001679 };
tpoindex1067fe12004-12-17 15:41:11 +00001680 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001681
1682 if( objc<2 ){
1683 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001684 return TCL_ERROR;
1685 }
drh411995d2002-06-25 19:31:18 +00001686 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001687 return TCL_ERROR;
1688 }
1689
drh411995d2002-06-25 19:31:18 +00001690 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001691
drhe22a3342003-04-22 20:30:37 +00001692 /* $db authorizer ?CALLBACK?
1693 **
1694 ** Invoke the given callback to authorize each SQL operation as it is
1695 ** compiled. 5 arguments are appended to the callback before it is
1696 ** invoked:
1697 **
1698 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1699 ** (2) First descriptive name (depends on authorization type)
1700 ** (3) Second descriptive name
1701 ** (4) Name of the database (ex: "main", "temp")
1702 ** (5) Name of trigger that is doing the access
1703 **
1704 ** The callback should return on of the following strings: SQLITE_OK,
1705 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1706 **
1707 ** If this method is invoked with no arguments, the current authorization
1708 ** callback string is returned.
1709 */
1710 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001711#ifdef SQLITE_OMIT_AUTHORIZATION
1712 Tcl_AppendResult(interp, "authorization not available in this build", 0);
1713 return TCL_ERROR;
1714#else
drhe22a3342003-04-22 20:30:37 +00001715 if( objc>3 ){
1716 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001717 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001718 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001719 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +00001720 Tcl_AppendResult(interp, pDb->zAuth, 0);
1721 }
1722 }else{
1723 char *zAuth;
1724 int len;
1725 if( pDb->zAuth ){
1726 Tcl_Free(pDb->zAuth);
1727 }
1728 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1729 if( zAuth && len>0 ){
1730 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001731 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001732 }else{
1733 pDb->zAuth = 0;
1734 }
drhe22a3342003-04-22 20:30:37 +00001735 if( pDb->zAuth ){
1736 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001737 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +00001738 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001739 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001740 }
drhe22a3342003-04-22 20:30:37 +00001741 }
drh1211de32004-07-26 12:24:22 +00001742#endif
drhe22a3342003-04-22 20:30:37 +00001743 break;
1744 }
1745
drhdc2c4912009-02-04 22:46:47 +00001746 /* $db backup ?DATABASE? FILENAME
1747 **
1748 ** Open or create a database file named FILENAME. Transfer the
1749 ** content of local database DATABASE (default: "main") into the
1750 ** FILENAME database.
1751 */
1752 case DB_BACKUP: {
1753 const char *zDestFile;
1754 const char *zSrcDb;
1755 sqlite3 *pDest;
1756 sqlite3_backup *pBackup;
1757
1758 if( objc==3 ){
1759 zSrcDb = "main";
1760 zDestFile = Tcl_GetString(objv[2]);
1761 }else if( objc==4 ){
1762 zSrcDb = Tcl_GetString(objv[2]);
1763 zDestFile = Tcl_GetString(objv[3]);
1764 }else{
1765 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1766 return TCL_ERROR;
1767 }
1768 rc = sqlite3_open(zDestFile, &pDest);
1769 if( rc!=SQLITE_OK ){
1770 Tcl_AppendResult(interp, "cannot open target database: ",
1771 sqlite3_errmsg(pDest), (char*)0);
1772 sqlite3_close(pDest);
1773 return TCL_ERROR;
1774 }
1775 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1776 if( pBackup==0 ){
1777 Tcl_AppendResult(interp, "backup failed: ",
1778 sqlite3_errmsg(pDest), (char*)0);
1779 sqlite3_close(pDest);
1780 return TCL_ERROR;
1781 }
1782 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1783 sqlite3_backup_finish(pBackup);
1784 if( rc==SQLITE_DONE ){
1785 rc = TCL_OK;
1786 }else{
1787 Tcl_AppendResult(interp, "backup failed: ",
1788 sqlite3_errmsg(pDest), (char*)0);
1789 rc = TCL_ERROR;
1790 }
1791 sqlite3_close(pDest);
1792 break;
1793 }
1794
drhbec3f402000-08-04 13:49:02 +00001795 /* $db busy ?CALLBACK?
1796 **
1797 ** Invoke the given callback if an SQL statement attempts to open
1798 ** a locked database file.
1799 */
drh6d313162000-09-21 13:01:35 +00001800 case DB_BUSY: {
1801 if( objc>3 ){
1802 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001803 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001804 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001805 if( pDb->zBusy ){
1806 Tcl_AppendResult(interp, pDb->zBusy, 0);
1807 }
1808 }else{
drh6d313162000-09-21 13:01:35 +00001809 char *zBusy;
1810 int len;
drhbec3f402000-08-04 13:49:02 +00001811 if( pDb->zBusy ){
1812 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001813 }
drh6d313162000-09-21 13:01:35 +00001814 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1815 if( zBusy && len>0 ){
1816 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001817 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001818 }else{
1819 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001820 }
1821 if( pDb->zBusy ){
1822 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001823 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001824 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001825 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001826 }
1827 }
drh6d313162000-09-21 13:01:35 +00001828 break;
1829 }
drhbec3f402000-08-04 13:49:02 +00001830
drhfb7e7652005-01-24 00:28:42 +00001831 /* $db cache flush
1832 ** $db cache size n
1833 **
1834 ** Flush the prepared statement cache, or set the maximum number of
1835 ** cached statements.
1836 */
1837 case DB_CACHE: {
1838 char *subCmd;
1839 int n;
1840
1841 if( objc<=2 ){
1842 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1843 return TCL_ERROR;
1844 }
1845 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1846 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1847 if( objc!=3 ){
1848 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1849 return TCL_ERROR;
1850 }else{
1851 flushStmtCache( pDb );
1852 }
1853 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1854 if( objc!=4 ){
1855 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1856 return TCL_ERROR;
1857 }else{
1858 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1859 Tcl_AppendResult( interp, "cannot convert \"",
1860 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1861 return TCL_ERROR;
1862 }else{
1863 if( n<0 ){
1864 flushStmtCache( pDb );
1865 n = 0;
1866 }else if( n>MAX_PREPARED_STMTS ){
1867 n = MAX_PREPARED_STMTS;
1868 }
1869 pDb->maxStmt = n;
1870 }
1871 }
1872 }else{
1873 Tcl_AppendResult( interp, "bad option \"",
danielk1977191fadc2007-10-23 08:17:48 +00001874 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
drhfb7e7652005-01-24 00:28:42 +00001875 return TCL_ERROR;
1876 }
1877 break;
1878 }
1879
danielk1977b28af712004-06-21 06:50:26 +00001880 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001881 **
1882 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001883 ** the most recent INSERT, UPDATE or DELETE statement, not including
1884 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001885 */
1886 case DB_CHANGES: {
1887 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001888 if( objc!=2 ){
1889 Tcl_WrongNumArgs(interp, 2, objv, "");
1890 return TCL_ERROR;
1891 }
drhc8d30ac2002-04-12 10:08:59 +00001892 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001893 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001894 break;
1895 }
1896
drh75897232000-05-29 14:26:00 +00001897 /* $db close
1898 **
1899 ** Shutdown the database
1900 */
drh6d313162000-09-21 13:01:35 +00001901 case DB_CLOSE: {
1902 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1903 break;
1904 }
drh75897232000-05-29 14:26:00 +00001905
drh0f14e2e2004-06-29 12:39:08 +00001906 /*
1907 ** $db collate NAME SCRIPT
1908 **
1909 ** Create a new SQL collation function called NAME. Whenever
1910 ** that function is called, invoke SCRIPT to evaluate the function.
1911 */
1912 case DB_COLLATE: {
1913 SqlCollate *pCollate;
1914 char *zName;
1915 char *zScript;
1916 int nScript;
1917 if( objc!=4 ){
1918 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1919 return TCL_ERROR;
1920 }
1921 zName = Tcl_GetStringFromObj(objv[2], 0);
1922 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1923 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1924 if( pCollate==0 ) return TCL_ERROR;
1925 pCollate->interp = interp;
1926 pCollate->pNext = pDb->pCollate;
1927 pCollate->zScript = (char*)&pCollate[1];
1928 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001929 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001930 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1931 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001932 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001933 return TCL_ERROR;
1934 }
1935 break;
1936 }
1937
1938 /*
1939 ** $db collation_needed SCRIPT
1940 **
1941 ** Create a new SQL collation function called NAME. Whenever
1942 ** that function is called, invoke SCRIPT to evaluate the function.
1943 */
1944 case DB_COLLATION_NEEDED: {
1945 if( objc!=3 ){
1946 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1947 return TCL_ERROR;
1948 }
1949 if( pDb->pCollateNeeded ){
1950 Tcl_DecrRefCount(pDb->pCollateNeeded);
1951 }
1952 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1953 Tcl_IncrRefCount(pDb->pCollateNeeded);
1954 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1955 break;
1956 }
1957
drh19e2d372005-08-29 23:00:03 +00001958 /* $db commit_hook ?CALLBACK?
1959 **
1960 ** Invoke the given callback just before committing every SQL transaction.
1961 ** If the callback throws an exception or returns non-zero, then the
1962 ** transaction is aborted. If CALLBACK is an empty string, the callback
1963 ** is disabled.
1964 */
1965 case DB_COMMIT_HOOK: {
1966 if( objc>3 ){
1967 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1968 return TCL_ERROR;
1969 }else if( objc==2 ){
1970 if( pDb->zCommit ){
1971 Tcl_AppendResult(interp, pDb->zCommit, 0);
1972 }
1973 }else{
1974 char *zCommit;
1975 int len;
1976 if( pDb->zCommit ){
1977 Tcl_Free(pDb->zCommit);
1978 }
1979 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1980 if( zCommit && len>0 ){
1981 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001982 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001983 }else{
1984 pDb->zCommit = 0;
1985 }
1986 if( pDb->zCommit ){
1987 pDb->interp = interp;
1988 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1989 }else{
1990 sqlite3_commit_hook(pDb->db, 0, 0);
1991 }
1992 }
1993 break;
1994 }
1995
drh75897232000-05-29 14:26:00 +00001996 /* $db complete SQL
1997 **
1998 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1999 ** additional lines of input are needed. This is similar to the
2000 ** built-in "info complete" command of Tcl.
2001 */
drh6d313162000-09-21 13:01:35 +00002002 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00002003#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00002004 Tcl_Obj *pResult;
2005 int isComplete;
2006 if( objc!=3 ){
2007 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00002008 return TCL_ERROR;
2009 }
danielk19776f8a5032004-05-10 10:34:51 +00002010 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00002011 pResult = Tcl_GetObjResult(interp);
2012 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00002013#endif
drh6d313162000-09-21 13:01:35 +00002014 break;
2015 }
drhdcd997e2003-01-31 17:21:49 +00002016
drh19e2d372005-08-29 23:00:03 +00002017 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2018 **
2019 ** Copy data into table from filename, optionally using SEPARATOR
2020 ** as column separators. If a column contains a null string, or the
2021 ** value of NULLINDICATOR, a NULL is inserted for the column.
2022 ** conflict-algorithm is one of the sqlite conflict algorithms:
2023 ** rollback, abort, fail, ignore, replace
2024 ** On success, return the number of lines processed, not necessarily same
2025 ** as 'db changes' due to conflict-algorithm selected.
2026 **
2027 ** This code is basically an implementation/enhancement of
2028 ** the sqlite3 shell.c ".import" command.
2029 **
2030 ** This command usage is equivalent to the sqlite2.x COPY statement,
2031 ** which imports file data into a table using the PostgreSQL COPY file format:
2032 ** $db copy $conflit_algo $table_name $filename \t \\N
2033 */
2034 case DB_COPY: {
2035 char *zTable; /* Insert data into this table */
2036 char *zFile; /* The file from which to extract data */
2037 char *zConflict; /* The conflict algorithm to use */
2038 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00002039 int nCol; /* Number of columns in the table */
2040 int nByte; /* Number of bytes in an SQL string */
2041 int i, j; /* Loop counters */
2042 int nSep; /* Number of bytes in zSep[] */
2043 int nNull; /* Number of bytes in zNull[] */
2044 char *zSql; /* An SQL statement */
2045 char *zLine; /* A single line of input from the file */
2046 char **azCol; /* zLine[] broken up into columns */
2047 char *zCommit; /* How to commit changes */
2048 FILE *in; /* The input file */
2049 int lineno = 0; /* Line number of input file */
2050 char zLineNum[80]; /* Line number print buffer */
2051 Tcl_Obj *pResult; /* interp result */
2052
2053 char *zSep;
2054 char *zNull;
2055 if( objc<5 || objc>7 ){
2056 Tcl_WrongNumArgs(interp, 2, objv,
2057 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2058 return TCL_ERROR;
2059 }
2060 if( objc>=6 ){
2061 zSep = Tcl_GetStringFromObj(objv[5], 0);
2062 }else{
2063 zSep = "\t";
2064 }
2065 if( objc>=7 ){
2066 zNull = Tcl_GetStringFromObj(objv[6], 0);
2067 }else{
2068 zNull = "";
2069 }
2070 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2071 zTable = Tcl_GetStringFromObj(objv[3], 0);
2072 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002073 nSep = strlen30(zSep);
2074 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002075 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00002076 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00002077 return TCL_ERROR;
2078 }
drh3e59c012008-09-23 10:12:13 +00002079 if(strcmp(zConflict, "rollback") != 0 &&
2080 strcmp(zConflict, "abort" ) != 0 &&
2081 strcmp(zConflict, "fail" ) != 0 &&
2082 strcmp(zConflict, "ignore" ) != 0 &&
2083 strcmp(zConflict, "replace" ) != 0 ) {
drh19e2d372005-08-29 23:00:03 +00002084 Tcl_AppendResult(interp, "Error: \"", zConflict,
2085 "\", conflict-algorithm must be one of: rollback, "
2086 "abort, fail, ignore, or replace", 0);
2087 return TCL_ERROR;
2088 }
2089 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2090 if( zSql==0 ){
2091 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
2092 return TCL_ERROR;
2093 }
drh4f21c4a2008-12-10 22:15:00 +00002094 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002095 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002096 sqlite3_free(zSql);
2097 if( rc ){
2098 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2099 nCol = 0;
2100 }else{
2101 nCol = sqlite3_column_count(pStmt);
2102 }
2103 sqlite3_finalize(pStmt);
2104 if( nCol==0 ) {
2105 return TCL_ERROR;
2106 }
2107 zSql = malloc( nByte + 50 + nCol*2 );
2108 if( zSql==0 ) {
2109 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
2110 return TCL_ERROR;
2111 }
2112 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2113 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002114 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002115 for(i=1; i<nCol; i++){
2116 zSql[j++] = ',';
2117 zSql[j++] = '?';
2118 }
2119 zSql[j++] = ')';
2120 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002121 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002122 free(zSql);
2123 if( rc ){
2124 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2125 sqlite3_finalize(pStmt);
2126 return TCL_ERROR;
2127 }
2128 in = fopen(zFile, "rb");
2129 if( in==0 ){
2130 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2131 sqlite3_finalize(pStmt);
2132 return TCL_ERROR;
2133 }
2134 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2135 if( azCol==0 ) {
2136 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00002137 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002138 return TCL_ERROR;
2139 }
drh37527852006-03-16 16:19:56 +00002140 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002141 zCommit = "COMMIT";
2142 while( (zLine = local_getline(0, in))!=0 ){
2143 char *z;
2144 i = 0;
2145 lineno++;
2146 azCol[0] = zLine;
2147 for(i=0, z=zLine; *z; z++){
2148 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2149 *z = 0;
2150 i++;
2151 if( i<nCol ){
2152 azCol[i] = &z[nSep];
2153 z += nSep-1;
2154 }
2155 }
2156 }
2157 if( i+1!=nCol ){
2158 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002159 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002160 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002161 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002162 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002163 "Error: %s line %d: expected %d columns of data but found %d",
2164 zFile, lineno, nCol, i+1);
2165 Tcl_AppendResult(interp, zErr, 0);
2166 free(zErr);
2167 }
drh19e2d372005-08-29 23:00:03 +00002168 zCommit = "ROLLBACK";
2169 break;
2170 }
2171 for(i=0; i<nCol; i++){
2172 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002173 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
drh4f21c4a2008-12-10 22:15:00 +00002174 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002175 ){
drh19e2d372005-08-29 23:00:03 +00002176 sqlite3_bind_null(pStmt, i+1);
2177 }else{
2178 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2179 }
2180 }
2181 sqlite3_step(pStmt);
2182 rc = sqlite3_reset(pStmt);
2183 free(zLine);
2184 if( rc!=SQLITE_OK ){
2185 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
2186 zCommit = "ROLLBACK";
2187 break;
2188 }
2189 }
2190 free(azCol);
2191 fclose(in);
2192 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002193 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002194
2195 if( zCommit[0] == 'C' ){
2196 /* success, set result as number of lines processed */
2197 pResult = Tcl_GetObjResult(interp);
2198 Tcl_SetIntObj(pResult, lineno);
2199 rc = TCL_OK;
2200 }else{
2201 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002202 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00002203 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
2204 rc = TCL_ERROR;
2205 }
2206 break;
2207 }
2208
drhdcd997e2003-01-31 17:21:49 +00002209 /*
drh41449052006-07-06 17:08:48 +00002210 ** $db enable_load_extension BOOLEAN
2211 **
2212 ** Turn the extension loading feature on or off. It if off by
2213 ** default.
2214 */
2215 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002216#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002217 int onoff;
2218 if( objc!=3 ){
2219 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2220 return TCL_ERROR;
2221 }
2222 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2223 return TCL_ERROR;
2224 }
2225 sqlite3_enable_load_extension(pDb->db, onoff);
2226 break;
drhf533acc2006-12-19 18:57:11 +00002227#else
2228 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2229 0);
2230 return TCL_ERROR;
2231#endif
drh41449052006-07-06 17:08:48 +00002232 }
2233
2234 /*
drhdcd997e2003-01-31 17:21:49 +00002235 ** $db errorcode
2236 **
2237 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002238 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002239 */
2240 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002241 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002242 break;
2243 }
dan4a4c11a2009-10-06 14:59:02 +00002244
2245 /*
2246 ** $db exists $sql
2247 ** $db onecolumn $sql
2248 **
2249 ** The onecolumn method is the equivalent of:
2250 ** lindex [$db eval $sql] 0
2251 */
2252 case DB_EXISTS:
2253 case DB_ONECOLUMN: {
2254 DbEvalContext sEval;
2255 if( objc!=3 ){
2256 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2257 return TCL_ERROR;
2258 }
2259
2260 dbEvalInit(&sEval, pDb, objv[2], 0);
2261 rc = dbEvalStep(&sEval);
2262 if( choice==DB_ONECOLUMN ){
2263 if( rc==TCL_OK ){
2264 Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
2265 }
2266 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2267 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
2268 }
2269 dbEvalFinalize(&sEval);
2270
2271 if( rc==TCL_BREAK ){
2272 rc = TCL_OK;
2273 }
2274 break;
2275 }
drh75897232000-05-29 14:26:00 +00002276
2277 /*
drh895d7472004-08-20 16:02:39 +00002278 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002279 **
2280 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002281 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002282 ** If "array" and "code" are omitted, then no callback is every invoked.
2283 ** If "array" is an empty string, then the values are placed in variables
2284 ** that have the same name as the fields extracted by the query.
2285 */
dan4a4c11a2009-10-06 14:59:02 +00002286 case DB_EVAL: {
2287 if( objc<3 || objc>5 ){
2288 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2289 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002290 }
dan4a4c11a2009-10-06 14:59:02 +00002291
drh92febd92004-08-20 18:34:20 +00002292 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002293 DbEvalContext sEval;
2294 Tcl_Obj *pRet = Tcl_NewObj();
2295 Tcl_IncrRefCount(pRet);
2296 dbEvalInit(&sEval, pDb, objv[2], 0);
2297 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2298 int i;
2299 int nCol;
2300 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002301 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002302 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002303 }
2304 }
dan4a4c11a2009-10-06 14:59:02 +00002305 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002306 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002307 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002308 rc = TCL_OK;
2309 }
drh1807ce32004-09-07 13:20:35 +00002310 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002311 }else{
2312 ClientData cd[2];
2313 DbEvalContext *p;
2314 Tcl_Obj *pArray = 0;
2315 Tcl_Obj *pScript;
2316
2317 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2318 pArray = objv[3];
2319 }
2320 pScript = objv[objc-1];
2321 Tcl_IncrRefCount(pScript);
2322
2323 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2324 dbEvalInit(p, pDb, objv[2], pArray);
2325
2326 cd[0] = (void *)p;
2327 cd[1] = (void *)pScript;
2328 rc = DbEvalNextCmd(cd, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002329 }
danielk197730ccda12004-05-27 12:11:31 +00002330 break;
2331 }
drhbec3f402000-08-04 13:49:02 +00002332
2333 /*
drhe3602be2008-09-09 12:31:33 +00002334 ** $db function NAME [-argcount N] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002335 **
2336 ** Create a new SQL function called NAME. Whenever that function is
2337 ** called, invoke SCRIPT to evaluate the function.
2338 */
2339 case DB_FUNCTION: {
2340 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002341 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002342 char *zName;
drhe3602be2008-09-09 12:31:33 +00002343 int nArg = -1;
2344 if( objc==6 ){
2345 const char *z = Tcl_GetString(objv[3]);
drh4f21c4a2008-12-10 22:15:00 +00002346 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002347 if( n>2 && strncmp(z, "-argcount",n)==0 ){
2348 if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
2349 if( nArg<0 ){
2350 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2351 (char*)0);
2352 return TCL_ERROR;
2353 }
2354 }
2355 pScript = objv[5];
2356 }else if( objc!=4 ){
2357 Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
drhcabb0812002-09-14 13:47:32 +00002358 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002359 }else{
2360 pScript = objv[3];
drhcabb0812002-09-14 13:47:32 +00002361 }
2362 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002363 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002364 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002365 if( pFunc->pScript ){
2366 Tcl_DecrRefCount(pFunc->pScript);
2367 }
2368 pFunc->pScript = pScript;
2369 Tcl_IncrRefCount(pScript);
2370 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
drhe3602be2008-09-09 12:31:33 +00002371 rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00002372 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002373 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002374 rc = TCL_ERROR;
2375 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002376 }
drhcabb0812002-09-14 13:47:32 +00002377 break;
2378 }
2379
2380 /*
danielk19778cbadb02007-05-03 16:31:26 +00002381 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002382 */
2383 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002384#ifdef SQLITE_OMIT_INCRBLOB
2385 Tcl_AppendResult(interp, "incrblob not available in this build", 0);
2386 return TCL_ERROR;
2387#else
danielk19778cbadb02007-05-03 16:31:26 +00002388 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002389 const char *zDb = "main";
2390 const char *zTable;
2391 const char *zColumn;
2392 sqlite_int64 iRow;
2393
danielk19778cbadb02007-05-03 16:31:26 +00002394 /* Check for the -readonly option */
2395 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2396 isReadonly = 1;
2397 }
2398
2399 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2400 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002401 return TCL_ERROR;
2402 }
2403
danielk19778cbadb02007-05-03 16:31:26 +00002404 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002405 zDb = Tcl_GetString(objv[2]);
2406 }
2407 zTable = Tcl_GetString(objv[objc-3]);
2408 zColumn = Tcl_GetString(objv[objc-2]);
2409 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2410
2411 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002412 rc = createIncrblobChannel(
2413 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
2414 );
danielk1977b4e9af92007-05-01 17:49:49 +00002415 }
danielk197732a0d8b2007-05-04 19:03:02 +00002416#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002417 break;
2418 }
2419
2420 /*
drhf11bded2006-07-17 00:02:44 +00002421 ** $db interrupt
2422 **
2423 ** Interrupt the execution of the inner-most SQL interpreter. This
2424 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2425 */
2426 case DB_INTERRUPT: {
2427 sqlite3_interrupt(pDb->db);
2428 break;
2429 }
2430
2431 /*
drh19e2d372005-08-29 23:00:03 +00002432 ** $db nullvalue ?STRING?
2433 **
2434 ** Change text used when a NULL comes back from the database. If ?STRING?
2435 ** is not present, then the current string used for NULL is returned.
2436 ** If STRING is present, then STRING is returned.
2437 **
2438 */
2439 case DB_NULLVALUE: {
2440 if( objc!=2 && objc!=3 ){
2441 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2442 return TCL_ERROR;
2443 }
2444 if( objc==3 ){
2445 int len;
2446 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2447 if( pDb->zNull ){
2448 Tcl_Free(pDb->zNull);
2449 }
2450 if( zNull && len>0 ){
2451 pDb->zNull = Tcl_Alloc( len + 1 );
2452 strncpy(pDb->zNull, zNull, len);
2453 pDb->zNull[len] = '\0';
2454 }else{
2455 pDb->zNull = 0;
2456 }
2457 }
2458 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
2459 break;
2460 }
2461
2462 /*
drhaf9ff332002-01-16 21:00:27 +00002463 ** $db last_insert_rowid
2464 **
2465 ** Return an integer which is the ROWID for the most recent insert.
2466 */
2467 case DB_LAST_INSERT_ROWID: {
2468 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002469 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002470 if( objc!=2 ){
2471 Tcl_WrongNumArgs(interp, 2, objv, "");
2472 return TCL_ERROR;
2473 }
danielk19776f8a5032004-05-10 10:34:51 +00002474 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002475 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002476 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002477 break;
2478 }
2479
2480 /*
dan4a4c11a2009-10-06 14:59:02 +00002481 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002482 */
drh1807ce32004-09-07 13:20:35 +00002483
2484 /* $db progress ?N CALLBACK?
2485 **
2486 ** Invoke the given callback every N virtual machine opcodes while executing
2487 ** queries.
2488 */
2489 case DB_PROGRESS: {
2490 if( objc==2 ){
2491 if( pDb->zProgress ){
2492 Tcl_AppendResult(interp, pDb->zProgress, 0);
2493 }
2494 }else if( objc==4 ){
2495 char *zProgress;
2496 int len;
2497 int N;
2498 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002499 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002500 };
2501 if( pDb->zProgress ){
2502 Tcl_Free(pDb->zProgress);
2503 }
2504 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2505 if( zProgress && len>0 ){
2506 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002507 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002508 }else{
2509 pDb->zProgress = 0;
2510 }
2511#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2512 if( pDb->zProgress ){
2513 pDb->interp = interp;
2514 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2515 }else{
2516 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2517 }
2518#endif
2519 }else{
2520 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002521 return TCL_ERROR;
2522 }
drh5d9d7572003-08-19 14:31:01 +00002523 break;
2524 }
2525
drh19e2d372005-08-29 23:00:03 +00002526 /* $db profile ?CALLBACK?
2527 **
2528 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2529 ** that has run. The text of the SQL and the amount of elapse time are
2530 ** appended to CALLBACK before the script is run.
2531 */
2532 case DB_PROFILE: {
2533 if( objc>3 ){
2534 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2535 return TCL_ERROR;
2536 }else if( objc==2 ){
2537 if( pDb->zProfile ){
2538 Tcl_AppendResult(interp, pDb->zProfile, 0);
2539 }
2540 }else{
2541 char *zProfile;
2542 int len;
2543 if( pDb->zProfile ){
2544 Tcl_Free(pDb->zProfile);
2545 }
2546 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2547 if( zProfile && len>0 ){
2548 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002549 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002550 }else{
2551 pDb->zProfile = 0;
2552 }
shanehbb201342011-02-09 19:55:20 +00002553#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh19e2d372005-08-29 23:00:03 +00002554 if( pDb->zProfile ){
2555 pDb->interp = interp;
2556 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2557 }else{
2558 sqlite3_profile(pDb->db, 0, 0);
2559 }
2560#endif
2561 }
2562 break;
2563 }
2564
drh5d9d7572003-08-19 14:31:01 +00002565 /*
drh22fbcb82004-02-01 01:22:50 +00002566 ** $db rekey KEY
2567 **
2568 ** Change the encryption key on the currently open database.
2569 */
2570 case DB_REKEY: {
2571 int nKey;
2572 void *pKey;
2573 if( objc!=3 ){
2574 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2575 return TCL_ERROR;
2576 }
2577 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00002578#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00002579 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002580 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00002581 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002582 rc = TCL_ERROR;
2583 }
2584#endif
2585 break;
2586 }
2587
drhdc2c4912009-02-04 22:46:47 +00002588 /* $db restore ?DATABASE? FILENAME
2589 **
2590 ** Open a database file named FILENAME. Transfer the content
2591 ** of FILENAME into the local database DATABASE (default: "main").
2592 */
2593 case DB_RESTORE: {
2594 const char *zSrcFile;
2595 const char *zDestDb;
2596 sqlite3 *pSrc;
2597 sqlite3_backup *pBackup;
2598 int nTimeout = 0;
2599
2600 if( objc==3 ){
2601 zDestDb = "main";
2602 zSrcFile = Tcl_GetString(objv[2]);
2603 }else if( objc==4 ){
2604 zDestDb = Tcl_GetString(objv[2]);
2605 zSrcFile = Tcl_GetString(objv[3]);
2606 }else{
2607 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2608 return TCL_ERROR;
2609 }
2610 rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
2611 if( rc!=SQLITE_OK ){
2612 Tcl_AppendResult(interp, "cannot open source database: ",
2613 sqlite3_errmsg(pSrc), (char*)0);
2614 sqlite3_close(pSrc);
2615 return TCL_ERROR;
2616 }
2617 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2618 if( pBackup==0 ){
2619 Tcl_AppendResult(interp, "restore failed: ",
2620 sqlite3_errmsg(pDb->db), (char*)0);
2621 sqlite3_close(pSrc);
2622 return TCL_ERROR;
2623 }
2624 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2625 || rc==SQLITE_BUSY ){
2626 if( rc==SQLITE_BUSY ){
2627 if( nTimeout++ >= 3 ) break;
2628 sqlite3_sleep(100);
2629 }
2630 }
2631 sqlite3_backup_finish(pBackup);
2632 if( rc==SQLITE_DONE ){
2633 rc = TCL_OK;
2634 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2635 Tcl_AppendResult(interp, "restore failed: source database busy",
2636 (char*)0);
2637 rc = TCL_ERROR;
2638 }else{
2639 Tcl_AppendResult(interp, "restore failed: ",
2640 sqlite3_errmsg(pDb->db), (char*)0);
2641 rc = TCL_ERROR;
2642 }
2643 sqlite3_close(pSrc);
2644 break;
2645 }
2646
drh22fbcb82004-02-01 01:22:50 +00002647 /*
drh3c379b02010-04-07 19:31:59 +00002648 ** $db status (step|sort|autoindex)
drhd1d38482008-10-07 23:46:38 +00002649 **
2650 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2651 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2652 */
2653 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002654 int v;
2655 const char *zOp;
2656 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00002657 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00002658 return TCL_ERROR;
2659 }
2660 zOp = Tcl_GetString(objv[2]);
2661 if( strcmp(zOp, "step")==0 ){
2662 v = pDb->nStep;
2663 }else if( strcmp(zOp, "sort")==0 ){
2664 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002665 }else if( strcmp(zOp, "autoindex")==0 ){
2666 v = pDb->nIndex;
drhd1d38482008-10-07 23:46:38 +00002667 }else{
drh3c379b02010-04-07 19:31:59 +00002668 Tcl_AppendResult(interp,
2669 "bad argument: should be autoindex, step, or sort",
drhd1d38482008-10-07 23:46:38 +00002670 (char*)0);
2671 return TCL_ERROR;
2672 }
2673 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2674 break;
2675 }
2676
2677 /*
drhbec3f402000-08-04 13:49:02 +00002678 ** $db timeout MILLESECONDS
2679 **
2680 ** Delay for the number of milliseconds specified when a file is locked.
2681 */
drh6d313162000-09-21 13:01:35 +00002682 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002683 int ms;
drh6d313162000-09-21 13:01:35 +00002684 if( objc!=3 ){
2685 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002686 return TCL_ERROR;
2687 }
drh6d313162000-09-21 13:01:35 +00002688 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002689 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002690 break;
drh75897232000-05-29 14:26:00 +00002691 }
danielk197755c45f22005-04-03 23:54:43 +00002692
2693 /*
drh0f14e2e2004-06-29 12:39:08 +00002694 ** $db total_changes
2695 **
2696 ** Return the number of rows that were modified, inserted, or deleted
2697 ** since the database handle was created.
2698 */
2699 case DB_TOTAL_CHANGES: {
2700 Tcl_Obj *pResult;
2701 if( objc!=2 ){
2702 Tcl_WrongNumArgs(interp, 2, objv, "");
2703 return TCL_ERROR;
2704 }
2705 pResult = Tcl_GetObjResult(interp);
2706 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2707 break;
2708 }
2709
drhb5a20d32003-04-23 12:25:23 +00002710 /* $db trace ?CALLBACK?
2711 **
2712 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2713 ** that is executed. The text of the SQL is appended to CALLBACK before
2714 ** it is executed.
2715 */
2716 case DB_TRACE: {
2717 if( objc>3 ){
2718 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002719 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002720 }else if( objc==2 ){
2721 if( pDb->zTrace ){
2722 Tcl_AppendResult(interp, pDb->zTrace, 0);
2723 }
2724 }else{
2725 char *zTrace;
2726 int len;
2727 if( pDb->zTrace ){
2728 Tcl_Free(pDb->zTrace);
2729 }
2730 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2731 if( zTrace && len>0 ){
2732 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002733 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002734 }else{
2735 pDb->zTrace = 0;
2736 }
shanehbb201342011-02-09 19:55:20 +00002737#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drhb5a20d32003-04-23 12:25:23 +00002738 if( pDb->zTrace ){
2739 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002740 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002741 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002742 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002743 }
drh19e2d372005-08-29 23:00:03 +00002744#endif
drhb5a20d32003-04-23 12:25:23 +00002745 }
2746 break;
2747 }
2748
drh3d214232005-08-02 12:21:08 +00002749 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2750 **
2751 ** Start a new transaction (if we are not already in the midst of a
2752 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2753 ** completes, either commit the transaction or roll it back if SCRIPT
2754 ** throws an exception. Or if no new transation was started, do nothing.
2755 ** pass the exception on up the stack.
2756 **
2757 ** This command was inspired by Dave Thomas's talk on Ruby at the
2758 ** 2005 O'Reilly Open Source Convention (OSCON).
2759 */
2760 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00002761 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00002762 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00002763 if( objc!=3 && objc!=4 ){
2764 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2765 return TCL_ERROR;
2766 }
danielk1977cd38d522009-01-02 17:33:46 +00002767
dan4a4c11a2009-10-06 14:59:02 +00002768 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00002769 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002770 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002771 };
2772 enum TTYPE_enum {
2773 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2774 };
2775 int ttype;
drhb5555e72005-08-02 17:15:14 +00002776 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002777 0, &ttype) ){
2778 return TCL_ERROR;
2779 }
2780 switch( (enum TTYPE_enum)ttype ){
2781 case TTYPE_DEFERRED: /* no-op */; break;
2782 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2783 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2784 }
drh3d214232005-08-02 12:21:08 +00002785 }
danielk1977cd38d522009-01-02 17:33:46 +00002786 pScript = objv[objc-1];
2787
dan4a4c11a2009-10-06 14:59:02 +00002788 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00002789 pDb->disableAuth++;
2790 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2791 pDb->disableAuth--;
2792 if( rc!=SQLITE_OK ){
2793 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2794 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00002795 }
danielk1977cd38d522009-01-02 17:33:46 +00002796 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00002797
dan4a4c11a2009-10-06 14:59:02 +00002798 /* If using NRE, schedule a callback to invoke the script pScript, then
2799 ** a second callback to commit (or rollback) the transaction or savepoint
2800 ** opened above. If not using NRE, evaluate the script directly, then
2801 ** call function DbTransPostCmd() to commit (or rollback) the transaction
2802 ** or savepoint. */
2803 if( DbUseNre() ){
2804 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
2805 Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00002806 }else{
dan4a4c11a2009-10-06 14:59:02 +00002807 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00002808 }
2809 break;
2810 }
2811
danielk197794eb6a12005-12-15 15:22:08 +00002812 /*
danielk1977404ca072009-03-16 13:19:36 +00002813 ** $db unlock_notify ?script?
2814 */
2815 case DB_UNLOCK_NOTIFY: {
2816#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2817 Tcl_AppendResult(interp, "unlock_notify not available in this build", 0);
2818 rc = TCL_ERROR;
2819#else
2820 if( objc!=2 && objc!=3 ){
2821 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2822 rc = TCL_ERROR;
2823 }else{
2824 void (*xNotify)(void **, int) = 0;
2825 void *pNotifyArg = 0;
2826
2827 if( pDb->pUnlockNotify ){
2828 Tcl_DecrRefCount(pDb->pUnlockNotify);
2829 pDb->pUnlockNotify = 0;
2830 }
2831
2832 if( objc==3 ){
2833 xNotify = DbUnlockNotify;
2834 pNotifyArg = (void *)pDb;
2835 pDb->pUnlockNotify = objv[2];
2836 Tcl_IncrRefCount(pDb->pUnlockNotify);
2837 }
2838
2839 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
2840 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2841 rc = TCL_ERROR;
2842 }
2843 }
2844#endif
2845 break;
2846 }
2847
dan46c47d42011-03-01 18:42:07 +00002848 case DB_PREUPDATE: {
2849 static const char *azSub[] = {"count", "hook", "modified", "old", 0};
2850 enum DbPreupdateSubCmd {
2851 PRE_COUNT, PRE_HOOK, PRE_MODIFIED, PRE_OLD
2852 };
2853 int iSub;
2854
2855 if( objc<3 ){
2856 Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
2857 }
2858 if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
2859 return TCL_ERROR;
2860 }
2861
2862 switch( (enum DbPreupdateSubCmd)iSub ){
2863 case PRE_COUNT: {
2864 int nCol = sqlite3_preupdate_count(pDb->db);
2865 Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
2866 break;
2867 }
2868
2869 case PRE_HOOK: {
2870 if( objc>4 ){
2871 Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
2872 return TCL_ERROR;
2873 }
2874 DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
2875 break;
2876 }
2877
2878 case PRE_MODIFIED:
2879 case PRE_OLD: {
2880 int iIdx;
2881 if( objc!=4 ){
2882 Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
2883 return TCL_ERROR;
2884 }
2885 if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
2886 return TCL_ERROR;
2887 }
2888
2889 if( iSub==PRE_MODIFIED ){
2890 int iRes;
2891 rc = sqlite3_preupdate_modified(pDb->db, iIdx, &iRes);
2892 if( rc==SQLITE_OK ) Tcl_SetObjResult(interp, Tcl_NewIntObj(iRes));
2893 }else{
2894 sqlite3_value *pValue;
2895 assert( iSub==PRE_OLD );
2896 rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
2897 if( rc==SQLITE_OK ){
2898 Tcl_Obj *pObj = Tcl_NewStringObj(sqlite3_value_text(pValue), -1);
2899 Tcl_SetObjResult(interp, pObj);
2900 }
2901 }
2902
2903 if( rc!=SQLITE_OK ){
2904 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2905 return TCL_ERROR;
2906 }
2907 }
2908 }
2909
2910 break;
2911 }
2912
danielk1977404ca072009-03-16 13:19:36 +00002913 /*
drh833bf962010-04-28 14:42:19 +00002914 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002915 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002916 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002917 */
drh833bf962010-04-28 14:42:19 +00002918 case DB_WAL_HOOK:
danielk197771fd80b2005-12-16 06:54:01 +00002919 case DB_UPDATE_HOOK:
2920 case DB_ROLLBACK_HOOK: {
dan46c47d42011-03-01 18:42:07 +00002921 sqlite3 *db = pDb->db;
danielk197771fd80b2005-12-16 06:54:01 +00002922
2923 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2924 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2925 */
2926 Tcl_Obj **ppHook;
dan46c47d42011-03-01 18:42:07 +00002927 if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
2928 if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
2929 if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
2930 if( objc>3 ){
danielk197794eb6a12005-12-15 15:22:08 +00002931 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2932 return TCL_ERROR;
2933 }
danielk197771fd80b2005-12-16 06:54:01 +00002934
dan46c47d42011-03-01 18:42:07 +00002935 DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002936 break;
2937 }
2938
danielk19774397de52005-01-12 12:44:03 +00002939 /* $db version
2940 **
2941 ** Return the version string for this database.
2942 */
2943 case DB_VERSION: {
2944 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2945 break;
2946 }
2947
tpoindex1067fe12004-12-17 15:41:11 +00002948
drh6d313162000-09-21 13:01:35 +00002949 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002950 return rc;
drh75897232000-05-29 14:26:00 +00002951}
2952
drha2c8a952009-10-13 18:38:34 +00002953#if SQLITE_TCL_NRE
2954/*
2955** Adaptor that provides an objCmd interface to the NRE-enabled
2956** interface implementation.
2957*/
2958static int DbObjCmdAdaptor(
2959 void *cd,
2960 Tcl_Interp *interp,
2961 int objc,
2962 Tcl_Obj *const*objv
2963){
2964 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
2965}
2966#endif /* SQLITE_TCL_NRE */
2967
drh75897232000-05-29 14:26:00 +00002968/*
drh3570ad92007-08-31 14:31:44 +00002969** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00002970** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00002971**
2972** This is the main Tcl command. When the "sqlite" Tcl command is
2973** invoked, this routine runs to process that command.
2974**
2975** The first argument, DBNAME, is an arbitrary name for a new
2976** database connection. This command creates a new command named
2977** DBNAME that is used to control that connection. The database
2978** connection is deleted when the DBNAME command is deleted.
2979**
drh3570ad92007-08-31 14:31:44 +00002980** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00002981**
drh75897232000-05-29 14:26:00 +00002982*/
drh22fbcb82004-02-01 01:22:50 +00002983static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002984 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002985 void *pKey = 0;
2986 int nKey = 0;
2987 const char *zArg;
drh75897232000-05-29 14:26:00 +00002988 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00002989 int i;
drh22fbcb82004-02-01 01:22:50 +00002990 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00002991 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00002992 int flags;
drh882e8e42006-08-24 02:42:27 +00002993 Tcl_DString translatedFilename;
drhd9da78a2009-03-24 15:08:09 +00002994
2995 /* In normal use, each TCL interpreter runs in a single thread. So
2996 ** by default, we can turn of mutexing on SQLite database connections.
2997 ** However, for testing purposes it is useful to have mutexes turned
2998 ** on. So, by default, mutexes default off. But if compiled with
2999 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3000 */
3001#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3002 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3003#else
3004 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3005#endif
3006
drh22fbcb82004-02-01 01:22:50 +00003007 if( objc==2 ){
3008 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00003009 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00003010 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00003011 return TCL_OK;
3012 }
drh9eb9e262004-02-11 02:18:05 +00003013 if( strcmp(zArg,"-has-codec")==0 ){
3014#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00003015 Tcl_AppendResult(interp,"1",0);
3016#else
3017 Tcl_AppendResult(interp,"0",0);
3018#endif
3019 return TCL_OK;
3020 }
drhfbc3eab2001-04-06 16:13:42 +00003021 }
drh3570ad92007-08-31 14:31:44 +00003022 for(i=3; i+1<objc; i+=2){
3023 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00003024 if( strcmp(zArg,"-key")==0 ){
drh3570ad92007-08-31 14:31:44 +00003025 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
3026 }else if( strcmp(zArg, "-vfs")==0 ){
dan3c3dd7b2010-06-22 11:10:40 +00003027 zVfs = Tcl_GetString(objv[i+1]);
drh3570ad92007-08-31 14:31:44 +00003028 }else if( strcmp(zArg, "-readonly")==0 ){
3029 int b;
3030 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3031 if( b ){
drh33f4e022007-09-03 15:19:34 +00003032 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00003033 flags |= SQLITE_OPEN_READONLY;
3034 }else{
3035 flags &= ~SQLITE_OPEN_READONLY;
3036 flags |= SQLITE_OPEN_READWRITE;
3037 }
3038 }else if( strcmp(zArg, "-create")==0 ){
3039 int b;
3040 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00003041 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00003042 flags |= SQLITE_OPEN_CREATE;
3043 }else{
3044 flags &= ~SQLITE_OPEN_CREATE;
3045 }
danielk19779a6284c2008-07-10 17:52:49 +00003046 }else if( strcmp(zArg, "-nomutex")==0 ){
3047 int b;
3048 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3049 if( b ){
3050 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00003051 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00003052 }else{
3053 flags &= ~SQLITE_OPEN_NOMUTEX;
3054 }
drh039963a2008-09-03 00:43:15 +00003055 }else if( strcmp(zArg, "-fullmutex")==0 ){
3056 int b;
3057 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3058 if( b ){
3059 flags |= SQLITE_OPEN_FULLMUTEX;
3060 flags &= ~SQLITE_OPEN_NOMUTEX;
3061 }else{
3062 flags &= ~SQLITE_OPEN_FULLMUTEX;
3063 }
drh3570ad92007-08-31 14:31:44 +00003064 }else{
3065 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3066 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00003067 }
3068 }
drh3570ad92007-08-31 14:31:44 +00003069 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00003070 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00003071 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh039963a2008-09-03 00:43:15 +00003072 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN?"
drh9eb9e262004-02-11 02:18:05 +00003073#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00003074 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00003075#endif
3076 );
drh75897232000-05-29 14:26:00 +00003077 return TCL_ERROR;
3078 }
drh75897232000-05-29 14:26:00 +00003079 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003080 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00003081 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00003082 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
3083 return TCL_ERROR;
3084 }
3085 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00003086 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00003087 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
drh3570ad92007-08-31 14:31:44 +00003088 sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00003089 Tcl_DStringFree(&translatedFilename);
danielk197780290862004-05-22 09:21:21 +00003090 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
drh9404d502006-12-19 18:46:08 +00003091 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
danielk197780290862004-05-22 09:21:21 +00003092 sqlite3_close(p->db);
3093 p->db = 0;
3094 }
drh2011d5f2004-07-22 02:40:37 +00003095#ifdef SQLITE_HAS_CODEC
drhf3a65f72007-08-22 20:18:21 +00003096 if( p->db ){
3097 sqlite3_key(p->db, pKey, nKey);
3098 }
drheb8ed702004-02-11 10:37:23 +00003099#endif
drhbec3f402000-08-04 13:49:02 +00003100 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003101 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003102 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003103 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003104 return TCL_ERROR;
3105 }
drhfb7e7652005-01-24 00:28:42 +00003106 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00003107 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003108 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003109 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003110 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3111 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003112 }else{
3113 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3114 }
drh75897232000-05-29 14:26:00 +00003115 return TCL_OK;
3116}
3117
3118/*
drh90ca9752001-09-28 17:47:14 +00003119** Provide a dummy Tcl_InitStubs if we are using this as a static
3120** library.
3121*/
3122#ifndef USE_TCL_STUBS
3123# undef Tcl_InitStubs
3124# define Tcl_InitStubs(a,b,c)
3125#endif
3126
3127/*
drh29bc4612005-10-05 10:40:15 +00003128** Make sure we have a PACKAGE_VERSION macro defined. This will be
3129** defined automatically by the TEA makefile. But other makefiles
3130** do not define it.
3131*/
3132#ifndef PACKAGE_VERSION
3133# define PACKAGE_VERSION SQLITE_VERSION
3134#endif
3135
3136/*
drh75897232000-05-29 14:26:00 +00003137** Initialize this module.
3138**
3139** This Tcl module contains only a single new Tcl command named "sqlite".
3140** (Hence there is no namespace. There is no point in using a namespace
3141** if the extension only supplies one new name!) The "sqlite" command is
3142** used to open a new SQLite database. See the DbMain() routine above
3143** for additional information.
drhb652f432010-08-26 16:46:57 +00003144**
3145** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003146*/
drhb652f432010-08-26 16:46:57 +00003147EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00003148 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00003149 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00003150 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh1cca0d22010-08-25 20:35:51 +00003151
3152#ifndef SQLITE_3_SUFFIX_ONLY
3153 /* The "sqlite" alias is undocumented. It is here only to support
3154 ** legacy scripts. All new scripts should use only the "sqlite3"
3155 ** command.
3156 */
drh49766d62005-01-08 18:42:28 +00003157 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003158#endif
drh1cca0d22010-08-25 20:35:51 +00003159
drh90ca9752001-09-28 17:47:14 +00003160 return TCL_OK;
3161}
drhb652f432010-08-26 16:46:57 +00003162EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3163EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3164EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3165EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3166EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3167EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3168EXTERN int Tclsqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
drhe2c3a652008-09-23 09:58:46 +00003169
drh49766d62005-01-08 18:42:28 +00003170
3171#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003172int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3173int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3174int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3175int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3176int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3177int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3178int Sqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3179int Tclsqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
drh49766d62005-01-08 18:42:28 +00003180#endif
drh75897232000-05-29 14:26:00 +00003181
drh3e27c022004-07-23 00:01:38 +00003182#ifdef TCLSH
3183/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003184** All of the code that follows is used to build standalone TCL interpreters
3185** that are statically linked with SQLite. Enable these by compiling
3186** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3187** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3188** analysis program.
drh75897232000-05-29 14:26:00 +00003189*/
drh348784e2000-05-29 20:41:49 +00003190
drh57a02272009-10-22 20:52:05 +00003191#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3192/*
3193 * This code implements the MD5 message-digest algorithm.
3194 * The algorithm is due to Ron Rivest. This code was
3195 * written by Colin Plumb in 1993, no copyright is claimed.
3196 * This code is in the public domain; do with it what you wish.
3197 *
3198 * Equivalent code is available from RSA Data Security, Inc.
3199 * This code has been tested against that, and is equivalent,
3200 * except that you don't need to include two pages of legalese
3201 * with every copy.
3202 *
3203 * To compute the message digest of a chunk of bytes, declare an
3204 * MD5Context structure, pass it to MD5Init, call MD5Update as
3205 * needed on buffers full of bytes, and then call MD5Final, which
3206 * will fill a supplied 16-byte array with the digest.
3207 */
3208
3209/*
3210 * If compiled on a machine that doesn't have a 32-bit integer,
3211 * you just set "uint32" to the appropriate datatype for an
3212 * unsigned 32-bit integer. For example:
3213 *
3214 * cc -Duint32='unsigned long' md5.c
3215 *
3216 */
3217#ifndef uint32
3218# define uint32 unsigned int
3219#endif
3220
3221struct MD5Context {
3222 int isInit;
3223 uint32 buf[4];
3224 uint32 bits[2];
3225 unsigned char in[64];
3226};
3227typedef struct MD5Context MD5Context;
3228
3229/*
3230 * Note: this code is harmless on little-endian machines.
3231 */
3232static void byteReverse (unsigned char *buf, unsigned longs){
3233 uint32 t;
3234 do {
3235 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3236 ((unsigned)buf[1]<<8 | buf[0]);
3237 *(uint32 *)buf = t;
3238 buf += 4;
3239 } while (--longs);
3240}
3241/* The four core functions - F1 is optimized somewhat */
3242
3243/* #define F1(x, y, z) (x & y | ~x & z) */
3244#define F1(x, y, z) (z ^ (x & (y ^ z)))
3245#define F2(x, y, z) F1(z, x, y)
3246#define F3(x, y, z) (x ^ y ^ z)
3247#define F4(x, y, z) (y ^ (x | ~z))
3248
3249/* This is the central step in the MD5 algorithm. */
3250#define MD5STEP(f, w, x, y, z, data, s) \
3251 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3252
3253/*
3254 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3255 * reflect the addition of 16 longwords of new data. MD5Update blocks
3256 * the data and converts bytes into longwords for this routine.
3257 */
3258static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3259 register uint32 a, b, c, d;
3260
3261 a = buf[0];
3262 b = buf[1];
3263 c = buf[2];
3264 d = buf[3];
3265
3266 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3267 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3268 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3269 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3270 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3271 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3272 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3273 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3274 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3275 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3276 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3277 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3278 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3279 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3280 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3281 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3282
3283 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3284 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3285 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3286 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3287 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3288 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3289 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3290 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3291 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3292 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3293 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3294 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3295 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3296 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3297 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3298 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3299
3300 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3301 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3302 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3303 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3304 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3305 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3306 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3307 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3308 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3309 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3310 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3311 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3312 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3313 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3314 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3315 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3316
3317 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3318 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3319 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3320 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3321 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3322 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3323 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3324 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3325 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3326 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3327 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3328 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3329 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3330 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3331 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3332 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3333
3334 buf[0] += a;
3335 buf[1] += b;
3336 buf[2] += c;
3337 buf[3] += d;
3338}
3339
3340/*
3341 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3342 * initialization constants.
3343 */
3344static void MD5Init(MD5Context *ctx){
3345 ctx->isInit = 1;
3346 ctx->buf[0] = 0x67452301;
3347 ctx->buf[1] = 0xefcdab89;
3348 ctx->buf[2] = 0x98badcfe;
3349 ctx->buf[3] = 0x10325476;
3350 ctx->bits[0] = 0;
3351 ctx->bits[1] = 0;
3352}
3353
3354/*
3355 * Update context to reflect the concatenation of another buffer full
3356 * of bytes.
3357 */
3358static
3359void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3360 uint32 t;
3361
3362 /* Update bitcount */
3363
3364 t = ctx->bits[0];
3365 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3366 ctx->bits[1]++; /* Carry from low to high */
3367 ctx->bits[1] += len >> 29;
3368
3369 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3370
3371 /* Handle any leading odd-sized chunks */
3372
3373 if ( t ) {
3374 unsigned char *p = (unsigned char *)ctx->in + t;
3375
3376 t = 64-t;
3377 if (len < t) {
3378 memcpy(p, buf, len);
3379 return;
3380 }
3381 memcpy(p, buf, t);
3382 byteReverse(ctx->in, 16);
3383 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3384 buf += t;
3385 len -= t;
3386 }
3387
3388 /* Process data in 64-byte chunks */
3389
3390 while (len >= 64) {
3391 memcpy(ctx->in, buf, 64);
3392 byteReverse(ctx->in, 16);
3393 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3394 buf += 64;
3395 len -= 64;
3396 }
3397
3398 /* Handle any remaining bytes of data. */
3399
3400 memcpy(ctx->in, buf, len);
3401}
3402
3403/*
3404 * Final wrapup - pad to 64-byte boundary with the bit pattern
3405 * 1 0* (64-bit count of bits processed, MSB-first)
3406 */
3407static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3408 unsigned count;
3409 unsigned char *p;
3410
3411 /* Compute number of bytes mod 64 */
3412 count = (ctx->bits[0] >> 3) & 0x3F;
3413
3414 /* Set the first char of padding to 0x80. This is safe since there is
3415 always at least one byte free */
3416 p = ctx->in + count;
3417 *p++ = 0x80;
3418
3419 /* Bytes of padding needed to make 64 bytes */
3420 count = 64 - 1 - count;
3421
3422 /* Pad out to 56 mod 64 */
3423 if (count < 8) {
3424 /* Two lots of padding: Pad the first block to 64 bytes */
3425 memset(p, 0, count);
3426 byteReverse(ctx->in, 16);
3427 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3428
3429 /* Now fill the next block with 56 bytes */
3430 memset(ctx->in, 0, 56);
3431 } else {
3432 /* Pad block to 56 bytes */
3433 memset(p, 0, count-8);
3434 }
3435 byteReverse(ctx->in, 14);
3436
3437 /* Append length in bits and transform */
3438 ((uint32 *)ctx->in)[ 14 ] = ctx->bits[0];
3439 ((uint32 *)ctx->in)[ 15 ] = ctx->bits[1];
3440
3441 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3442 byteReverse((unsigned char *)ctx->buf, 4);
3443 memcpy(digest, ctx->buf, 16);
3444 memset(ctx, 0, sizeof(ctx)); /* In case it is sensitive */
3445}
3446
3447/*
3448** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3449*/
3450static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3451 static char const zEncode[] = "0123456789abcdef";
3452 int i, j;
3453
3454 for(j=i=0; i<16; i++){
3455 int a = digest[i];
3456 zBuf[j++] = zEncode[(a>>4)&0xf];
3457 zBuf[j++] = zEncode[a & 0xf];
3458 }
3459 zBuf[j] = 0;
3460}
3461
3462
3463/*
3464** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3465** each representing 16 bits of the digest and separated from each
3466** other by a "-" character.
3467*/
3468static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3469 int i, j;
3470 unsigned int x;
3471 for(i=j=0; i<16; i+=2){
3472 x = digest[i]*256 + digest[i+1];
3473 if( i>0 ) zDigest[j++] = '-';
3474 sprintf(&zDigest[j], "%05u", x);
3475 j += 5;
3476 }
3477 zDigest[j] = 0;
3478}
3479
3480/*
3481** A TCL command for md5. The argument is the text to be hashed. The
3482** Result is the hash in base64.
3483*/
3484static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3485 MD5Context ctx;
3486 unsigned char digest[16];
3487 char zBuf[50];
3488 void (*converter)(unsigned char*, char*);
3489
3490 if( argc!=2 ){
3491 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3492 " TEXT\"", 0);
3493 return TCL_ERROR;
3494 }
3495 MD5Init(&ctx);
3496 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3497 MD5Final(digest, &ctx);
3498 converter = (void(*)(unsigned char*,char*))cd;
3499 converter(digest, zBuf);
3500 Tcl_AppendResult(interp, zBuf, (char*)0);
3501 return TCL_OK;
3502}
3503
3504/*
3505** A TCL command to take the md5 hash of a file. The argument is the
3506** name of the file.
3507*/
3508static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3509 FILE *in;
3510 MD5Context ctx;
3511 void (*converter)(unsigned char*, char*);
3512 unsigned char digest[16];
3513 char zBuf[10240];
3514
3515 if( argc!=2 ){
3516 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3517 " FILENAME\"", 0);
3518 return TCL_ERROR;
3519 }
3520 in = fopen(argv[1],"rb");
3521 if( in==0 ){
3522 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
3523 "\" for reading", 0);
3524 return TCL_ERROR;
3525 }
3526 MD5Init(&ctx);
3527 for(;;){
3528 int n;
3529 n = fread(zBuf, 1, sizeof(zBuf), in);
3530 if( n<=0 ) break;
3531 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3532 }
3533 fclose(in);
3534 MD5Final(digest, &ctx);
3535 converter = (void(*)(unsigned char*,char*))cd;
3536 converter(digest, zBuf);
3537 Tcl_AppendResult(interp, zBuf, (char*)0);
3538 return TCL_OK;
3539}
3540
3541/*
3542** Register the four new TCL commands for generating MD5 checksums
3543** with the TCL interpreter.
3544*/
3545int Md5_Init(Tcl_Interp *interp){
3546 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3547 MD5DigestToBase16, 0);
3548 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3549 MD5DigestToBase10x8, 0);
3550 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3551 MD5DigestToBase16, 0);
3552 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3553 MD5DigestToBase10x8, 0);
3554 return TCL_OK;
3555}
3556#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3557
3558#if defined(SQLITE_TEST)
3559/*
3560** During testing, the special md5sum() aggregate function is available.
3561** inside SQLite. The following routines implement that function.
3562*/
3563static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3564 MD5Context *p;
3565 int i;
3566 if( argc<1 ) return;
3567 p = sqlite3_aggregate_context(context, sizeof(*p));
3568 if( p==0 ) return;
3569 if( !p->isInit ){
3570 MD5Init(p);
3571 }
3572 for(i=0; i<argc; i++){
3573 const char *zData = (char*)sqlite3_value_text(argv[i]);
3574 if( zData ){
3575 MD5Update(p, (unsigned char*)zData, strlen(zData));
3576 }
3577 }
3578}
3579static void md5finalize(sqlite3_context *context){
3580 MD5Context *p;
3581 unsigned char digest[16];
3582 char zBuf[33];
3583 p = sqlite3_aggregate_context(context, sizeof(*p));
3584 MD5Final(digest,p);
3585 MD5DigestToBase16(digest, zBuf);
3586 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3587}
3588int Md5_Register(sqlite3 *db){
3589 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
3590 md5step, md5finalize);
3591 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3592 return rc;
3593}
3594#endif /* defined(SQLITE_TEST) */
3595
3596
drh348784e2000-05-29 20:41:49 +00003597/*
drh3e27c022004-07-23 00:01:38 +00003598** If the macro TCLSH is one, then put in code this for the
3599** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003600** standard input, or if a file is named on the command line
3601** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003602*/
drh3e27c022004-07-23 00:01:38 +00003603#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00003604static char zMainloop[] =
3605 "set line {}\n"
3606 "while {![eof stdin]} {\n"
3607 "if {$line!=\"\"} {\n"
3608 "puts -nonewline \"> \"\n"
3609 "} else {\n"
3610 "puts -nonewline \"% \"\n"
3611 "}\n"
3612 "flush stdout\n"
3613 "append line [gets stdin]\n"
3614 "if {[info complete $line]} {\n"
3615 "if {[catch {uplevel #0 $line} result]} {\n"
3616 "puts stderr \"Error: $result\"\n"
3617 "} elseif {$result!=\"\"} {\n"
3618 "puts $result\n"
3619 "}\n"
3620 "set line {}\n"
3621 "} else {\n"
3622 "append line \\n\n"
3623 "}\n"
3624 "}\n"
3625;
drh3e27c022004-07-23 00:01:38 +00003626#endif
drh3a0f13f2010-07-12 16:47:48 +00003627#if TCLSH==2
3628static char zMainloop[] =
3629#include "spaceanal_tcl.h"
3630;
3631#endif
drh3e27c022004-07-23 00:01:38 +00003632
danc1a60c52010-06-07 14:28:16 +00003633#ifdef SQLITE_TEST
3634static void init_all(Tcl_Interp *);
3635static int init_all_cmd(
3636 ClientData cd,
3637 Tcl_Interp *interp,
3638 int objc,
3639 Tcl_Obj *CONST objv[]
3640){
danielk19770a549072009-02-17 16:29:10 +00003641
danc1a60c52010-06-07 14:28:16 +00003642 Tcl_Interp *slave;
3643 if( objc!=2 ){
3644 Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3645 return TCL_ERROR;
3646 }
3647
3648 slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3649 if( !slave ){
3650 return TCL_ERROR;
3651 }
3652
3653 init_all(slave);
3654 return TCL_OK;
3655}
3656#endif
3657
3658/*
3659** Configure the interpreter passed as the first argument to have access
3660** to the commands and linked variables that make up:
3661**
3662** * the [sqlite3] extension itself,
3663**
3664** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
3665**
3666** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
3667** test suite.
3668*/
3669static void init_all(Tcl_Interp *interp){
drh38f82712004-06-18 17:10:16 +00003670 Sqlite3_Init(interp);
danc1a60c52010-06-07 14:28:16 +00003671
drh57a02272009-10-22 20:52:05 +00003672#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3673 Md5_Init(interp);
3674#endif
danc1a60c52010-06-07 14:28:16 +00003675
drhd9b02572001-04-15 00:37:09 +00003676#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00003677 {
drh2f999a62007-08-15 19:16:43 +00003678 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00003679 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00003680 extern int Sqlitetest2_Init(Tcl_Interp*);
3681 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00003682 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00003683 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00003684 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00003685 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00003686 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00003687 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00003688 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00003689 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
dan0a7a9152010-04-07 07:57:38 +00003690 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
drh984bfaa2008-03-19 16:08:53 +00003691 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00003692 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00003693 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003694 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00003695 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003696 extern int Sqlitetestschema_Init(Tcl_Interp*);
3697 extern int Sqlitetestsse_Init(Tcl_Interp*);
3698 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00003699 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00003700 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00003701 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00003702 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh522efc62009-11-10 17:24:37 +00003703 extern int Sqlitetestintarray_Init(Tcl_Interp*);
danc7991bd2010-05-05 19:04:59 +00003704 extern int Sqlitetestvfs_Init(Tcl_Interp *);
dan599e9d22010-07-12 08:39:37 +00003705 extern int SqlitetestStat_Init(Tcl_Interp*);
dan9508daa2010-08-28 18:58:00 +00003706 extern int Sqlitetestrtree_Init(Tcl_Interp*);
dan8cf35eb2010-09-01 11:40:05 +00003707 extern int Sqlitequota_Init(Tcl_Interp*);
shaneh8a922f72010-11-04 20:50:27 +00003708 extern int Sqlitemultiplex_Init(Tcl_Interp*);
dane336b002010-11-19 18:20:09 +00003709 extern int SqliteSuperlock_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00003710
danb29010c2010-12-29 18:24:38 +00003711#ifdef SQLITE_ENABLE_ZIPVFS
3712 extern int Zipvfs_Init(Tcl_Interp*);
3713 Zipvfs_Init(interp);
3714#endif
3715
drh2f999a62007-08-15 19:16:43 +00003716 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00003717 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00003718 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00003719 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00003720 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00003721 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00003722 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00003723 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00003724 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00003725 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00003726 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00003727 Sqlitetest_autoext_Init(interp);
dan0a7a9152010-04-07 07:57:38 +00003728 Sqlitetest_demovfs_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00003729 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00003730 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00003731 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003732 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00003733 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003734 Sqlitetestschema_Init(interp);
3735 Sqlitetesttclvar_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00003736 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003737 SqlitetestOnefile_Init(interp);
danielk19775d1f5aa2008-04-10 14:51:00 +00003738 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00003739 Sqlitetestbackup_Init(interp);
drh522efc62009-11-10 17:24:37 +00003740 Sqlitetestintarray_Init(interp);
danc7991bd2010-05-05 19:04:59 +00003741 Sqlitetestvfs_Init(interp);
dan599e9d22010-07-12 08:39:37 +00003742 SqlitetestStat_Init(interp);
dan9508daa2010-08-28 18:58:00 +00003743 Sqlitetestrtree_Init(interp);
dan8cf35eb2010-09-01 11:40:05 +00003744 Sqlitequota_Init(interp);
shaneh8a922f72010-11-04 20:50:27 +00003745 Sqlitemultiplex_Init(interp);
dane336b002010-11-19 18:20:09 +00003746 SqliteSuperlock_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003747
danc1a60c52010-06-07 14:28:16 +00003748 Tcl_CreateObjCommand(interp,"load_testfixture_extensions",init_all_cmd,0,0);
3749
drh89dec812005-04-28 19:03:37 +00003750#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00003751 Sqlitetestsse_Init(interp);
3752#endif
drhd1bf3512001-04-07 15:24:33 +00003753 }
3754#endif
danc1a60c52010-06-07 14:28:16 +00003755}
3756
3757#define TCLSH_MAIN main /* Needed to fake out mktclapp */
3758int TCLSH_MAIN(int argc, char **argv){
3759 Tcl_Interp *interp;
3760
3761 /* Call sqlite3_shutdown() once before doing anything else. This is to
3762 ** test that sqlite3_shutdown() can be safely called by a process before
3763 ** sqlite3_initialize() is. */
3764 sqlite3_shutdown();
3765
drh3a0f13f2010-07-12 16:47:48 +00003766#if TCLSH==2
3767 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
3768#endif
danc1a60c52010-06-07 14:28:16 +00003769 Tcl_FindExecutable(argv[0]);
3770
3771 interp = Tcl_CreateInterp();
3772 init_all(interp);
drhc7285972009-11-10 01:13:25 +00003773 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00003774 int i;
shessad42c3a2006-08-22 23:53:46 +00003775 char zArgc[32];
3776 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
3777 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00003778 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
3779 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00003780 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00003781 Tcl_SetVar(interp, "argv", argv[i],
3782 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3783 }
drh3a0f13f2010-07-12 16:47:48 +00003784 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00003785 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00003786 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00003787 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00003788 return 1;
3789 }
drh3e27c022004-07-23 00:01:38 +00003790 }
drh3a0f13f2010-07-12 16:47:48 +00003791 if( TCLSH==2 || argc<=1 ){
drh348784e2000-05-29 20:41:49 +00003792 Tcl_GlobalEval(interp, zMainloop);
3793 }
3794 return 0;
3795}
3796#endif /* TCLSH */