blob: 1743b40cf69501f2a61bd865d48226828973a7ef [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) */
dan21e8d012011-03-03 20:05:59 +0000127 Tcl_Obj *pTransHook; /* Transaction hook script (if any) */
drh5def0842010-05-05 20:00:25 +0000128 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000129 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000130 SqlCollate *pCollate; /* List of SQL collation functions */
131 int rc; /* Return code of most recent sqlite3_exec() */
132 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000133 SqlPreparedStmt *stmtList; /* List of prepared statements*/
134 SqlPreparedStmt *stmtLast; /* Last statement in the list */
135 int maxStmt; /* The next maximum number of stmtList */
136 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000137 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh3c379b02010-04-07 19:31:59 +0000138 int nStep, nSort, nIndex; /* Statistics for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000139 int nTransaction; /* Number of nested [transaction] methods */
drh98808ba2001-10-18 12:34:46 +0000140};
drh297ecf12001-04-05 15:57:13 +0000141
danielk1977b4e9af92007-05-01 17:49:49 +0000142struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000143 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000144 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000145 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000146 Tcl_Channel channel; /* Channel identifier */
147 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
148 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000149};
150
drhea678832008-12-10 19:26:22 +0000151/*
152** Compute a string length that is limited to what can be stored in
153** lower 30 bits of a 32-bit signed integer.
154*/
drh4f21c4a2008-12-10 22:15:00 +0000155static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000156 const char *z2 = z;
157 while( *z2 ){ z2++; }
158 return 0x3fffffff & (int)(z2 - z);
159}
drhea678832008-12-10 19:26:22 +0000160
161
danielk197732a0d8b2007-05-04 19:03:02 +0000162#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000163/*
danielk1977d04417962007-05-02 13:16:30 +0000164** Close all incrblob channels opened using database connection pDb.
165** This is called when shutting down the database connection.
166*/
167static void closeIncrblobChannels(SqliteDb *pDb){
168 IncrblobChannel *p;
169 IncrblobChannel *pNext;
170
171 for(p=pDb->pIncrblob; p; p=pNext){
172 pNext = p->pNext;
173
174 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
175 ** which deletes the IncrblobChannel structure at *p. So do not
176 ** call Tcl_Free() here.
177 */
178 Tcl_UnregisterChannel(pDb->interp, p->channel);
179 }
180}
181
182/*
danielk1977b4e9af92007-05-01 17:49:49 +0000183** Close an incremental blob channel.
184*/
185static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
186 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000187 int rc = sqlite3_blob_close(p->pBlob);
188 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000189
190 /* Remove the channel from the SqliteDb.pIncrblob list. */
191 if( p->pNext ){
192 p->pNext->pPrev = p->pPrev;
193 }
194 if( p->pPrev ){
195 p->pPrev->pNext = p->pNext;
196 }
197 if( p->pDb->pIncrblob==p ){
198 p->pDb->pIncrblob = p->pNext;
199 }
200
danielk197792d4d7a2007-05-04 12:05:56 +0000201 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000202 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000203
204 if( rc!=SQLITE_OK ){
205 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
206 return TCL_ERROR;
207 }
danielk1977b4e9af92007-05-01 17:49:49 +0000208 return TCL_OK;
209}
210
211/*
212** Read data from an incremental blob channel.
213*/
214static int incrblobInput(
215 ClientData instanceData,
216 char *buf,
217 int bufSize,
218 int *errorCodePtr
219){
220 IncrblobChannel *p = (IncrblobChannel *)instanceData;
221 int nRead = bufSize; /* Number of bytes to read */
222 int nBlob; /* Total size of the blob */
223 int rc; /* sqlite error code */
224
225 nBlob = sqlite3_blob_bytes(p->pBlob);
226 if( (p->iSeek+nRead)>nBlob ){
227 nRead = nBlob-p->iSeek;
228 }
229 if( nRead<=0 ){
230 return 0;
231 }
232
233 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
234 if( rc!=SQLITE_OK ){
235 *errorCodePtr = rc;
236 return -1;
237 }
238
239 p->iSeek += nRead;
240 return nRead;
241}
242
danielk1977d04417962007-05-02 13:16:30 +0000243/*
244** Write data to an incremental blob channel.
245*/
danielk1977b4e9af92007-05-01 17:49:49 +0000246static int incrblobOutput(
247 ClientData instanceData,
248 CONST char *buf,
249 int toWrite,
250 int *errorCodePtr
251){
252 IncrblobChannel *p = (IncrblobChannel *)instanceData;
253 int nWrite = toWrite; /* Number of bytes to write */
254 int nBlob; /* Total size of the blob */
255 int rc; /* sqlite error code */
256
257 nBlob = sqlite3_blob_bytes(p->pBlob);
258 if( (p->iSeek+nWrite)>nBlob ){
259 *errorCodePtr = EINVAL;
260 return -1;
261 }
262 if( nWrite<=0 ){
263 return 0;
264 }
265
266 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
267 if( rc!=SQLITE_OK ){
268 *errorCodePtr = EIO;
269 return -1;
270 }
271
272 p->iSeek += nWrite;
273 return nWrite;
274}
275
276/*
277** Seek an incremental blob channel.
278*/
279static int incrblobSeek(
280 ClientData instanceData,
281 long offset,
282 int seekMode,
283 int *errorCodePtr
284){
285 IncrblobChannel *p = (IncrblobChannel *)instanceData;
286
287 switch( seekMode ){
288 case SEEK_SET:
289 p->iSeek = offset;
290 break;
291 case SEEK_CUR:
292 p->iSeek += offset;
293 break;
294 case SEEK_END:
295 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
296 break;
297
298 default: assert(!"Bad seekMode");
299 }
300
301 return p->iSeek;
302}
303
304
305static void incrblobWatch(ClientData instanceData, int mode){
306 /* NO-OP */
307}
308static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
309 return TCL_ERROR;
310}
311
312static Tcl_ChannelType IncrblobChannelType = {
313 "incrblob", /* typeName */
314 TCL_CHANNEL_VERSION_2, /* version */
315 incrblobClose, /* closeProc */
316 incrblobInput, /* inputProc */
317 incrblobOutput, /* outputProc */
318 incrblobSeek, /* seekProc */
319 0, /* setOptionProc */
320 0, /* getOptionProc */
321 incrblobWatch, /* watchProc (this is a no-op) */
322 incrblobHandle, /* getHandleProc (always returns error) */
323 0, /* close2Proc */
324 0, /* blockModeProc */
325 0, /* flushProc */
326 0, /* handlerProc */
327 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000328};
329
330/*
331** Create a new incrblob channel.
332*/
333static int createIncrblobChannel(
334 Tcl_Interp *interp,
335 SqliteDb *pDb,
336 const char *zDb,
337 const char *zTable,
338 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000339 sqlite_int64 iRow,
340 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000341){
342 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000343 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000344 sqlite3_blob *pBlob;
345 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000346 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000347
348 /* This variable is used to name the channels: "incrblob_[incr count]" */
349 static int count = 0;
350 char zChannel[64];
351
danielk19778cbadb02007-05-03 16:31:26 +0000352 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000353 if( rc!=SQLITE_OK ){
354 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
355 return TCL_ERROR;
356 }
357
358 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
359 p->iSeek = 0;
360 p->pBlob = pBlob;
361
drh5bb3eb92007-05-04 13:15:55 +0000362 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000363 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
364 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000365
danielk1977d04417962007-05-02 13:16:30 +0000366 /* Link the new channel into the SqliteDb.pIncrblob list. */
367 p->pNext = pDb->pIncrblob;
368 p->pPrev = 0;
369 if( p->pNext ){
370 p->pNext->pPrev = p;
371 }
372 pDb->pIncrblob = p;
373 p->pDb = pDb;
374
375 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000376 return TCL_OK;
377}
danielk197732a0d8b2007-05-04 19:03:02 +0000378#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
379 #define closeIncrblobChannels(pDb)
380#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000381
drh6d313162000-09-21 13:01:35 +0000382/*
drhd1e47332005-06-26 17:55:33 +0000383** Look at the script prefix in pCmd. We will be executing this script
384** after first appending one or more arguments. This routine analyzes
385** the script to see if it is safe to use Tcl_EvalObjv() on the script
386** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
387** faster.
388**
389** Scripts that are safe to use with Tcl_EvalObjv() consists of a
390** command name followed by zero or more arguments with no [...] or $
391** or {...} or ; to be seen anywhere. Most callback scripts consist
392** of just a single procedure name and they meet this requirement.
393*/
394static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
395 /* We could try to do something with Tcl_Parse(). But we will instead
396 ** just do a search for forbidden characters. If any of the forbidden
397 ** characters appear in pCmd, we will report the string as unsafe.
398 */
399 const char *z;
400 int n;
401 z = Tcl_GetStringFromObj(pCmd, &n);
402 while( n-- > 0 ){
403 int c = *(z++);
404 if( c=='$' || c=='[' || c==';' ) return 0;
405 }
406 return 1;
407}
408
409/*
410** Find an SqlFunc structure with the given name. Or create a new
411** one if an existing one cannot be found. Return a pointer to the
412** structure.
413*/
414static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
415 SqlFunc *p, *pNew;
416 int i;
drh4f21c4a2008-12-10 22:15:00 +0000417 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen30(zName) + 1 );
drhd1e47332005-06-26 17:55:33 +0000418 pNew->zName = (char*)&pNew[1];
419 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
420 pNew->zName[i] = 0;
421 for(p=pDb->pFunc; p; p=p->pNext){
422 if( strcmp(p->zName, pNew->zName)==0 ){
423 Tcl_Free((char*)pNew);
424 return p;
425 }
426 }
427 pNew->interp = pDb->interp;
428 pNew->pScript = 0;
429 pNew->pNext = pDb->pFunc;
430 pDb->pFunc = pNew;
431 return pNew;
432}
433
434/*
drhfb7e7652005-01-24 00:28:42 +0000435** Finalize and free a list of prepared statements
436*/
437static void flushStmtCache( SqliteDb *pDb ){
438 SqlPreparedStmt *pPreStmt;
439
440 while( pDb->stmtList ){
441 sqlite3_finalize( pDb->stmtList->pStmt );
442 pPreStmt = pDb->stmtList;
443 pDb->stmtList = pDb->stmtList->pNext;
444 Tcl_Free( (char*)pPreStmt );
445 }
446 pDb->nStmt = 0;
447 pDb->stmtLast = 0;
448}
449
450/*
drh895d7472004-08-20 16:02:39 +0000451** TCL calls this procedure when an sqlite3 database command is
452** deleted.
drh75897232000-05-29 14:26:00 +0000453*/
454static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000455 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000456 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000457 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000458 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000459 while( pDb->pFunc ){
460 SqlFunc *pFunc = pDb->pFunc;
461 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000462 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000463 Tcl_Free((char*)pFunc);
464 }
danielk19770202b292004-06-09 09:55:16 +0000465 while( pDb->pCollate ){
466 SqlCollate *pCollate = pDb->pCollate;
467 pDb->pCollate = pCollate->pNext;
468 Tcl_Free((char*)pCollate);
469 }
drhbec3f402000-08-04 13:49:02 +0000470 if( pDb->zBusy ){
471 Tcl_Free(pDb->zBusy);
472 }
drhb5a20d32003-04-23 12:25:23 +0000473 if( pDb->zTrace ){
474 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000475 }
drh19e2d372005-08-29 23:00:03 +0000476 if( pDb->zProfile ){
477 Tcl_Free(pDb->zProfile);
478 }
drhe22a3342003-04-22 20:30:37 +0000479 if( pDb->zAuth ){
480 Tcl_Free(pDb->zAuth);
481 }
danielk197755c45f22005-04-03 23:54:43 +0000482 if( pDb->zNull ){
483 Tcl_Free(pDb->zNull);
484 }
danielk197794eb6a12005-12-15 15:22:08 +0000485 if( pDb->pUpdateHook ){
486 Tcl_DecrRefCount(pDb->pUpdateHook);
487 }
dan46c47d42011-03-01 18:42:07 +0000488 if( pDb->pPreUpdateHook ){
489 Tcl_DecrRefCount(pDb->pPreUpdateHook);
490 }
danielk197771fd80b2005-12-16 06:54:01 +0000491 if( pDb->pRollbackHook ){
492 Tcl_DecrRefCount(pDb->pRollbackHook);
493 }
drh5def0842010-05-05 20:00:25 +0000494 if( pDb->pWalHook ){
495 Tcl_DecrRefCount(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000496 }
danielk197794eb6a12005-12-15 15:22:08 +0000497 if( pDb->pCollateNeeded ){
498 Tcl_DecrRefCount(pDb->pCollateNeeded);
499 }
drhbec3f402000-08-04 13:49:02 +0000500 Tcl_Free((char*)pDb);
501}
502
503/*
504** This routine is called when a database file is locked while trying
505** to execute SQL.
506*/
danielk19772a764eb2004-06-12 01:43:26 +0000507static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000508 SqliteDb *pDb = (SqliteDb*)cd;
509 int rc;
510 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000511
drh5bb3eb92007-05-04 13:15:55 +0000512 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000513 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000514 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
515 return 0;
516 }
517 return 1;
drh75897232000-05-29 14:26:00 +0000518}
519
drh26e4a8b2008-05-01 17:16:52 +0000520#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000521/*
danielk1977348bb5d2003-10-18 09:37:26 +0000522** This routine is invoked as the 'progress callback' for the database.
523*/
524static int DbProgressHandler(void *cd){
525 SqliteDb *pDb = (SqliteDb*)cd;
526 int rc;
527
528 assert( pDb->zProgress );
529 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
530 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
531 return 1;
532 }
533 return 0;
534}
drh26e4a8b2008-05-01 17:16:52 +0000535#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000536
drhd1167392006-01-23 13:00:35 +0000537#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000538/*
drhb5a20d32003-04-23 12:25:23 +0000539** This routine is called by the SQLite trace handler whenever a new
540** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000541*/
drhb5a20d32003-04-23 12:25:23 +0000542static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000543 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000544 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000545
drhb5a20d32003-04-23 12:25:23 +0000546 Tcl_DStringInit(&str);
547 Tcl_DStringAppend(&str, pDb->zTrace, -1);
548 Tcl_DStringAppendElement(&str, zSql);
549 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
550 Tcl_DStringFree(&str);
551 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000552}
drhd1167392006-01-23 13:00:35 +0000553#endif
drh0d1a6432003-04-03 15:46:04 +0000554
drhd1167392006-01-23 13:00:35 +0000555#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000556/*
drh19e2d372005-08-29 23:00:03 +0000557** This routine is called by the SQLite profile handler after a statement
558** SQL has executed. The TCL script in pDb->zProfile is evaluated.
559*/
560static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
561 SqliteDb *pDb = (SqliteDb*)cd;
562 Tcl_DString str;
563 char zTm[100];
564
565 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
566 Tcl_DStringInit(&str);
567 Tcl_DStringAppend(&str, pDb->zProfile, -1);
568 Tcl_DStringAppendElement(&str, zSql);
569 Tcl_DStringAppendElement(&str, zTm);
570 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
571 Tcl_DStringFree(&str);
572 Tcl_ResetResult(pDb->interp);
573}
drhd1167392006-01-23 13:00:35 +0000574#endif
drh19e2d372005-08-29 23:00:03 +0000575
576/*
drhaa940ea2004-01-15 02:44:03 +0000577** This routine is called when a transaction is committed. The
578** TCL script in pDb->zCommit is executed. If it returns non-zero or
579** if it throws an exception, the transaction is rolled back instead
580** of being committed.
581*/
582static int DbCommitHandler(void *cd){
583 SqliteDb *pDb = (SqliteDb*)cd;
584 int rc;
585
586 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
587 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
588 return 1;
589 }
590 return 0;
591}
592
danielk197771fd80b2005-12-16 06:54:01 +0000593static void DbRollbackHandler(void *clientData){
594 SqliteDb *pDb = (SqliteDb*)clientData;
595 assert(pDb->pRollbackHook);
596 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
597 Tcl_BackgroundError(pDb->interp);
598 }
599}
600
drh5def0842010-05-05 20:00:25 +0000601/*
dan21e8d012011-03-03 20:05:59 +0000602** sqlite3_transaction_hook() callback.
603*/
604static void DbTransHandler(void *clientData, int op, int iLevel){
605 static const char *azStr[] = { "BEGIN", "COMMIT", "ROLLBACK" };
606 SqliteDb *pDb = (SqliteDb*)clientData;
607 Tcl_Interp *interp = pDb->interp;
608 Tcl_Obj *pScript;
609
610 assert(pDb->pTransHook);
611 assert( SQLITE_BEGIN==1 );
612 assert( SQLITE_COMMIT==2 );
613 assert( SQLITE_ROLLBACK==3 );
614
615 pScript = Tcl_DuplicateObj(pDb->pTransHook);
616 Tcl_IncrRefCount(pScript);
617 Tcl_ListObjAppendElement(interp, pScript, Tcl_NewStringObj(azStr[op-1], -1));
618 Tcl_ListObjAppendElement(interp, pScript, Tcl_NewIntObj(iLevel));
619 if( TCL_OK!=Tcl_EvalObjEx(interp, pScript, 0) ){
620 Tcl_BackgroundError(interp);
621 }
622 Tcl_DecrRefCount(pScript);
623}
624
625/*
drh5def0842010-05-05 20:00:25 +0000626** This procedure handles wal_hook callbacks.
627*/
628static int DbWalHandler(
dan8d22a172010-04-19 18:03:51 +0000629 void *clientData,
630 sqlite3 *db,
631 const char *zDb,
632 int nEntry
633){
drh5def0842010-05-05 20:00:25 +0000634 int ret = SQLITE_OK;
dan8d22a172010-04-19 18:03:51 +0000635 Tcl_Obj *p;
636 SqliteDb *pDb = (SqliteDb*)clientData;
637 Tcl_Interp *interp = pDb->interp;
drh5def0842010-05-05 20:00:25 +0000638 assert(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000639
drh5def0842010-05-05 20:00:25 +0000640 p = Tcl_DuplicateObj(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000641 Tcl_IncrRefCount(p);
642 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
643 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
644 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
645 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
646 ){
647 Tcl_BackgroundError(interp);
648 }
649 Tcl_DecrRefCount(p);
650
651 return ret;
652}
653
drhbcf4f482009-03-27 12:44:35 +0000654#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000655static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
656 char zBuf[64];
657 sprintf(zBuf, "%d", iArg);
658 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
659 sprintf(zBuf, "%d", nArg);
660 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
661}
662#else
drhbcf4f482009-03-27 12:44:35 +0000663# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000664#endif
665
drh69910da2009-03-27 12:32:54 +0000666#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000667static void DbUnlockNotify(void **apArg, int nArg){
668 int i;
669 for(i=0; i<nArg; i++){
670 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
671 SqliteDb *pDb = (SqliteDb *)apArg[i];
672 setTestUnlockNotifyVars(pDb->interp, i, nArg);
673 assert( pDb->pUnlockNotify);
674 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
675 Tcl_DecrRefCount(pDb->pUnlockNotify);
676 pDb->pUnlockNotify = 0;
677 }
678}
drh69910da2009-03-27 12:32:54 +0000679#endif
danielk1977404ca072009-03-16 13:19:36 +0000680
dan46c47d42011-03-01 18:42:07 +0000681/*
682** Pre-update hook callback.
683*/
684static void DbPreUpdateHandler(
685 void *p,
686 sqlite3 *db,
687 int op,
688 const char *zDb,
689 const char *zTbl,
690 sqlite_int64 iKey1,
691 sqlite_int64 iKey2
692){
693 SqliteDb *pDb = (SqliteDb *)p;
694 Tcl_Obj *pCmd;
695 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
696
697 assert( (SQLITE_DELETE-1)/9 == 0 );
698 assert( (SQLITE_INSERT-1)/9 == 1 );
699 assert( (SQLITE_UPDATE-1)/9 == 2 );
700 assert( pDb->pPreUpdateHook );
701 assert( db==pDb->db );
702 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
703
704 pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
705 Tcl_IncrRefCount(pCmd);
706 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
707 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
708 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
709 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
710 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
711 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
712 Tcl_DecrRefCount(pCmd);
713}
714
danielk197794eb6a12005-12-15 15:22:08 +0000715static void DbUpdateHandler(
716 void *p,
717 int op,
718 const char *zDb,
719 const char *zTbl,
720 sqlite_int64 rowid
721){
722 SqliteDb *pDb = (SqliteDb *)p;
723 Tcl_Obj *pCmd;
dan46c47d42011-03-01 18:42:07 +0000724 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
725
726 assert( (SQLITE_DELETE-1)/9 == 0 );
727 assert( (SQLITE_INSERT-1)/9 == 1 );
728 assert( (SQLITE_UPDATE-1)/9 == 2 );
danielk197794eb6a12005-12-15 15:22:08 +0000729
730 assert( pDb->pUpdateHook );
731 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
732
733 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
734 Tcl_IncrRefCount(pCmd);
dan46c47d42011-03-01 18:42:07 +0000735 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
danielk197794eb6a12005-12-15 15:22:08 +0000736 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
737 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
738 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
739 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
drhefdde162010-10-27 15:36:21 +0000740 Tcl_DecrRefCount(pCmd);
danielk197794eb6a12005-12-15 15:22:08 +0000741}
742
danielk19777cedc8d2004-06-10 10:50:08 +0000743static void tclCollateNeeded(
744 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000745 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000746 int enc,
747 const char *zName
748){
749 SqliteDb *pDb = (SqliteDb *)pCtx;
750 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
751 Tcl_IncrRefCount(pScript);
752 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
753 Tcl_EvalObjEx(pDb->interp, pScript, 0);
754 Tcl_DecrRefCount(pScript);
755}
756
drhaa940ea2004-01-15 02:44:03 +0000757/*
danielk19770202b292004-06-09 09:55:16 +0000758** This routine is called to evaluate an SQL collation function implemented
759** using TCL script.
760*/
761static int tclSqlCollate(
762 void *pCtx,
763 int nA,
764 const void *zA,
765 int nB,
766 const void *zB
767){
768 SqlCollate *p = (SqlCollate *)pCtx;
769 Tcl_Obj *pCmd;
770
771 pCmd = Tcl_NewStringObj(p->zScript, -1);
772 Tcl_IncrRefCount(pCmd);
773 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
774 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000775 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000776 Tcl_DecrRefCount(pCmd);
777 return (atoi(Tcl_GetStringResult(p->interp)));
778}
779
780/*
drhcabb0812002-09-14 13:47:32 +0000781** This routine is called to evaluate an SQL function implemented
782** using TCL script.
783*/
drhfb7e7652005-01-24 00:28:42 +0000784static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000785 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000786 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000787 int i;
788 int rc;
789
drhd1e47332005-06-26 17:55:33 +0000790 if( argc==0 ){
791 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
792 ** script object directly. This allows the TCL compiler to generate
793 ** bytecode for the command on the first invocation and thus make
794 ** subsequent invocations much faster. */
795 pCmd = p->pScript;
796 Tcl_IncrRefCount(pCmd);
797 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
798 Tcl_DecrRefCount(pCmd);
799 }else{
800 /* If there are arguments to the function, make a shallow copy of the
801 ** script object, lappend the arguments, then evaluate the copy.
802 **
803 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
804 ** The new Tcl_Obj contains pointers to the original list elements.
805 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
806 ** of the list to tclCmdNameType, that alternate representation will
807 ** be preserved and reused on the next invocation.
808 */
809 Tcl_Obj **aArg;
810 int nArg;
811 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
812 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
813 return;
814 }
815 pCmd = Tcl_NewListObj(nArg, aArg);
816 Tcl_IncrRefCount(pCmd);
817 for(i=0; i<argc; i++){
818 sqlite3_value *pIn = argv[i];
819 Tcl_Obj *pVal;
820
821 /* Set pVal to contain the i'th column of this row. */
822 switch( sqlite3_value_type(pIn) ){
823 case SQLITE_BLOB: {
824 int bytes = sqlite3_value_bytes(pIn);
825 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
826 break;
827 }
828 case SQLITE_INTEGER: {
829 sqlite_int64 v = sqlite3_value_int64(pIn);
830 if( v>=-2147483647 && v<=2147483647 ){
831 pVal = Tcl_NewIntObj(v);
832 }else{
833 pVal = Tcl_NewWideIntObj(v);
834 }
835 break;
836 }
837 case SQLITE_FLOAT: {
838 double r = sqlite3_value_double(pIn);
839 pVal = Tcl_NewDoubleObj(r);
840 break;
841 }
842 case SQLITE_NULL: {
843 pVal = Tcl_NewStringObj("", 0);
844 break;
845 }
846 default: {
847 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000848 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000849 break;
850 }
851 }
852 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
853 if( rc ){
854 Tcl_DecrRefCount(pCmd);
855 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
856 return;
857 }
danielk197751ad0ec2004-05-24 12:39:02 +0000858 }
drhd1e47332005-06-26 17:55:33 +0000859 if( !p->useEvalObjv ){
860 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
861 ** is a list without a string representation. To prevent this from
862 ** happening, make sure pCmd has a valid string representation */
863 Tcl_GetString(pCmd);
864 }
865 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
866 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000867 }
danielk1977562e8d32005-05-20 09:40:55 +0000868
drhc7f269d2005-05-05 10:30:29 +0000869 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000870 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000871 }else{
drhc7f269d2005-05-05 10:30:29 +0000872 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
873 int n;
874 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000875 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000876 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000877 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000878 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000879 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000880 data = Tcl_GetByteArrayFromObj(pVar, &n);
881 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000882 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000883 Tcl_GetIntFromObj(0, pVar, &n);
884 sqlite3_result_int(context, n);
885 }else if( c=='d' && strcmp(zType,"double")==0 ){
886 double r;
887 Tcl_GetDoubleFromObj(0, pVar, &r);
888 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +0000889 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
890 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000891 Tcl_WideInt v;
892 Tcl_GetWideIntFromObj(0, pVar, &v);
893 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000894 }else{
danielk197700fd9572005-12-07 06:27:43 +0000895 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
896 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000897 }
drhcabb0812002-09-14 13:47:32 +0000898 }
899}
drh895d7472004-08-20 16:02:39 +0000900
drhe22a3342003-04-22 20:30:37 +0000901#ifndef SQLITE_OMIT_AUTHORIZATION
902/*
903** This is the authentication function. It appends the authentication
904** type code and the two arguments to zCmd[] then invokes the result
905** on the interpreter. The reply is examined to determine if the
906** authentication fails or succeeds.
907*/
908static int auth_callback(
909 void *pArg,
910 int code,
911 const char *zArg1,
912 const char *zArg2,
913 const char *zArg3,
914 const char *zArg4
915){
916 char *zCode;
917 Tcl_DString str;
918 int rc;
919 const char *zReply;
920 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +0000921 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +0000922
923 switch( code ){
924 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
925 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
926 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
927 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
928 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
929 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
930 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
931 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
932 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
933 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
934 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
935 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
936 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
937 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
938 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
939 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
940 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
941 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
942 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
943 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
944 case SQLITE_READ : zCode="SQLITE_READ"; break;
945 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
946 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
947 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000948 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
949 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000950 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000951 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000952 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000953 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
954 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000955 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +0000956 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drhe22a3342003-04-22 20:30:37 +0000957 default : zCode="????"; break;
958 }
959 Tcl_DStringInit(&str);
960 Tcl_DStringAppend(&str, pDb->zAuth, -1);
961 Tcl_DStringAppendElement(&str, zCode);
962 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
963 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
964 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
965 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
966 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
967 Tcl_DStringFree(&str);
968 zReply = Tcl_GetStringResult(pDb->interp);
969 if( strcmp(zReply,"SQLITE_OK")==0 ){
970 rc = SQLITE_OK;
971 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
972 rc = SQLITE_DENY;
973 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
974 rc = SQLITE_IGNORE;
975 }else{
976 rc = 999;
977 }
978 return rc;
979}
980#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000981
982/*
danielk1977ef2cb632004-05-29 02:37:19 +0000983** zText is a pointer to text obtained via an sqlite3_result_text()
984** or similar interface. This routine returns a Tcl string object,
985** reference count set to 0, containing the text. If a translation
986** between iso8859 and UTF-8 is required, it is preformed.
987*/
988static Tcl_Obj *dbTextToObj(char const *zText){
989 Tcl_Obj *pVal;
990#ifdef UTF_TRANSLATION_NEEDED
991 Tcl_DString dCol;
992 Tcl_DStringInit(&dCol);
993 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
994 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
995 Tcl_DStringFree(&dCol);
996#else
997 pVal = Tcl_NewStringObj(zText, -1);
998#endif
999 return pVal;
1000}
1001
1002/*
tpoindex1067fe12004-12-17 15:41:11 +00001003** This routine reads a line of text from FILE in, stores
1004** the text in memory obtained from malloc() and returns a pointer
1005** to the text. NULL is returned at end of file, or if malloc()
1006** fails.
1007**
1008** The interface is like "readline" but no command-line editing
1009** is done.
1010**
1011** copied from shell.c from '.import' command
1012*/
1013static char *local_getline(char *zPrompt, FILE *in){
1014 char *zLine;
1015 int nLine;
1016 int n;
1017 int eol;
1018
1019 nLine = 100;
1020 zLine = malloc( nLine );
1021 if( zLine==0 ) return 0;
1022 n = 0;
1023 eol = 0;
1024 while( !eol ){
1025 if( n+100>nLine ){
1026 nLine = nLine*2 + 100;
1027 zLine = realloc(zLine, nLine);
1028 if( zLine==0 ) return 0;
1029 }
1030 if( fgets(&zLine[n], nLine - n, in)==0 ){
1031 if( n==0 ){
1032 free(zLine);
1033 return 0;
1034 }
1035 zLine[n] = 0;
1036 eol = 1;
1037 break;
1038 }
1039 while( zLine[n] ){ n++; }
1040 if( n>0 && zLine[n-1]=='\n' ){
1041 n--;
1042 zLine[n] = 0;
1043 eol = 1;
1044 }
1045 }
1046 zLine = realloc( zLine, n+1 );
1047 return zLine;
1048}
1049
danielk19778e556522007-11-13 10:30:24 +00001050
1051/*
dan4a4c11a2009-10-06 14:59:02 +00001052** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +00001053**
dan4a4c11a2009-10-06 14:59:02 +00001054** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +00001055**
dan4a4c11a2009-10-06 14:59:02 +00001056** It is invoked after evaluating the script SCRIPT to commit or rollback
1057** the transaction or savepoint opened by the [transaction] command.
1058*/
1059static int DbTransPostCmd(
1060 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1061 Tcl_Interp *interp, /* Tcl interpreter */
1062 int result /* Result of evaluating SCRIPT */
1063){
1064 static const char *azEnd[] = {
1065 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1066 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1067 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1068 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1069 };
1070 SqliteDb *pDb = (SqliteDb*)data[0];
1071 int rc = result;
1072 const char *zEnd;
1073
1074 pDb->nTransaction--;
1075 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1076
1077 pDb->disableAuth++;
1078 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1079 /* This is a tricky scenario to handle. The most likely cause of an
1080 ** error is that the exec() above was an attempt to commit the
1081 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1082 ** that an IO-error has occured. In either case, throw a Tcl exception
1083 ** and try to rollback the transaction.
1084 **
1085 ** But it could also be that the user executed one or more BEGIN,
1086 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1087 ** this method's logic. Not clear how this would be best handled.
1088 */
1089 if( rc!=TCL_ERROR ){
1090 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
1091 rc = TCL_ERROR;
1092 }
1093 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1094 }
1095 pDb->disableAuth--;
1096
1097 return rc;
1098}
1099
1100/*
1101** Search the cache for a prepared-statement object that implements the
1102** first SQL statement in the buffer pointed to by parameter zIn. If
1103** no such prepared-statement can be found, allocate and prepare a new
1104** one. In either case, bind the current values of the relevant Tcl
1105** variables to any $var, :var or @var variables in the statement. Before
1106** returning, set *ppPreStmt to point to the prepared-statement object.
1107**
1108** Output parameter *pzOut is set to point to the next SQL statement in
1109** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1110** next statement.
1111**
1112** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1113** and an error message loaded into interpreter pDb->interp.
1114*/
1115static int dbPrepareAndBind(
1116 SqliteDb *pDb, /* Database object */
1117 char const *zIn, /* SQL to compile */
1118 char const **pzOut, /* OUT: Pointer to next SQL statement */
1119 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1120){
1121 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
1122 sqlite3_stmt *pStmt; /* Prepared statement object */
1123 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1124 int nSql; /* Length of zSql in bytes */
1125 int nVar; /* Number of variables in statement */
1126 int iParm = 0; /* Next free entry in apParm */
1127 int i;
1128 Tcl_Interp *interp = pDb->interp;
1129
1130 *ppPreStmt = 0;
1131
1132 /* Trim spaces from the start of zSql and calculate the remaining length. */
1133 while( isspace(zSql[0]) ){ zSql++; }
1134 nSql = strlen30(zSql);
1135
1136 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1137 int n = pPreStmt->nSql;
1138 if( nSql>=n
1139 && memcmp(pPreStmt->zSql, zSql, n)==0
1140 && (zSql[n]==0 || zSql[n-1]==';')
1141 ){
1142 pStmt = pPreStmt->pStmt;
1143 *pzOut = &zSql[pPreStmt->nSql];
1144
1145 /* When a prepared statement is found, unlink it from the
1146 ** cache list. It will later be added back to the beginning
1147 ** of the cache list in order to implement LRU replacement.
1148 */
1149 if( pPreStmt->pPrev ){
1150 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1151 }else{
1152 pDb->stmtList = pPreStmt->pNext;
1153 }
1154 if( pPreStmt->pNext ){
1155 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1156 }else{
1157 pDb->stmtLast = pPreStmt->pPrev;
1158 }
1159 pDb->nStmt--;
1160 nVar = sqlite3_bind_parameter_count(pStmt);
1161 break;
1162 }
1163 }
1164
1165 /* If no prepared statement was found. Compile the SQL text. Also allocate
1166 ** a new SqlPreparedStmt structure. */
1167 if( pPreStmt==0 ){
1168 int nByte;
1169
1170 if( SQLITE_OK!=sqlite3_prepare_v2(pDb->db, zSql, -1, &pStmt, pzOut) ){
1171 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1172 return TCL_ERROR;
1173 }
1174 if( pStmt==0 ){
1175 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1176 /* A compile-time error in the statement. */
1177 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1178 return TCL_ERROR;
1179 }else{
1180 /* The statement was a no-op. Continue to the next statement
1181 ** in the SQL string.
1182 */
1183 return TCL_OK;
1184 }
1185 }
1186
1187 assert( pPreStmt==0 );
1188 nVar = sqlite3_bind_parameter_count(pStmt);
1189 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1190 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1191 memset(pPreStmt, 0, nByte);
1192
1193 pPreStmt->pStmt = pStmt;
1194 pPreStmt->nSql = (*pzOut - zSql);
1195 pPreStmt->zSql = sqlite3_sql(pStmt);
1196 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
1197 }
1198 assert( pPreStmt );
1199 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1200 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1201
1202 /* Bind values to parameters that begin with $ or : */
1203 for(i=1; i<=nVar; i++){
1204 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1205 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1206 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1207 if( pVar ){
1208 int n;
1209 u8 *data;
1210 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1211 char c = zType[0];
1212 if( zVar[0]=='@' ||
1213 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1214 /* Load a BLOB type if the Tcl variable is a bytearray and
1215 ** it has no string representation or the host
1216 ** parameter name begins with "@". */
1217 data = Tcl_GetByteArrayFromObj(pVar, &n);
1218 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1219 Tcl_IncrRefCount(pVar);
1220 pPreStmt->apParm[iParm++] = pVar;
1221 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1222 Tcl_GetIntFromObj(interp, pVar, &n);
1223 sqlite3_bind_int(pStmt, i, n);
1224 }else if( c=='d' && strcmp(zType,"double")==0 ){
1225 double r;
1226 Tcl_GetDoubleFromObj(interp, pVar, &r);
1227 sqlite3_bind_double(pStmt, i, r);
1228 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1229 (c=='i' && strcmp(zType,"int")==0) ){
1230 Tcl_WideInt v;
1231 Tcl_GetWideIntFromObj(interp, pVar, &v);
1232 sqlite3_bind_int64(pStmt, i, v);
1233 }else{
1234 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1235 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1236 Tcl_IncrRefCount(pVar);
1237 pPreStmt->apParm[iParm++] = pVar;
1238 }
1239 }else{
1240 sqlite3_bind_null(pStmt, i);
1241 }
1242 }
1243 }
1244 pPreStmt->nParm = iParm;
1245 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001246
dan4a4c11a2009-10-06 14:59:02 +00001247 return TCL_OK;
1248}
1249
1250
1251/*
1252** Release a statement reference obtained by calling dbPrepareAndBind().
1253** There should be exactly one call to this function for each call to
1254** dbPrepareAndBind().
1255**
1256** If the discard parameter is non-zero, then the statement is deleted
1257** immediately. Otherwise it is added to the LRU list and may be returned
1258** by a subsequent call to dbPrepareAndBind().
1259*/
1260static void dbReleaseStmt(
1261 SqliteDb *pDb, /* Database handle */
1262 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1263 int discard /* True to delete (not cache) the pPreStmt */
1264){
1265 int i;
1266
1267 /* Free the bound string and blob parameters */
1268 for(i=0; i<pPreStmt->nParm; i++){
1269 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1270 }
1271 pPreStmt->nParm = 0;
1272
1273 if( pDb->maxStmt<=0 || discard ){
1274 /* If the cache is turned off, deallocated the statement */
1275 sqlite3_finalize(pPreStmt->pStmt);
1276 Tcl_Free((char *)pPreStmt);
1277 }else{
1278 /* Add the prepared statement to the beginning of the cache list. */
1279 pPreStmt->pNext = pDb->stmtList;
1280 pPreStmt->pPrev = 0;
1281 if( pDb->stmtList ){
1282 pDb->stmtList->pPrev = pPreStmt;
1283 }
1284 pDb->stmtList = pPreStmt;
1285 if( pDb->stmtLast==0 ){
1286 assert( pDb->nStmt==0 );
1287 pDb->stmtLast = pPreStmt;
1288 }else{
1289 assert( pDb->nStmt>0 );
1290 }
1291 pDb->nStmt++;
1292
1293 /* If we have too many statement in cache, remove the surplus from
1294 ** the end of the cache list. */
1295 while( pDb->nStmt>pDb->maxStmt ){
1296 sqlite3_finalize(pDb->stmtLast->pStmt);
1297 pDb->stmtLast = pDb->stmtLast->pPrev;
1298 Tcl_Free((char*)pDb->stmtLast->pNext);
1299 pDb->stmtLast->pNext = 0;
1300 pDb->nStmt--;
1301 }
1302 }
1303}
1304
1305/*
1306** Structure used with dbEvalXXX() functions:
1307**
1308** dbEvalInit()
1309** dbEvalStep()
1310** dbEvalFinalize()
1311** dbEvalRowInfo()
1312** dbEvalColumnValue()
1313*/
1314typedef struct DbEvalContext DbEvalContext;
1315struct DbEvalContext {
1316 SqliteDb *pDb; /* Database handle */
1317 Tcl_Obj *pSql; /* Object holding string zSql */
1318 const char *zSql; /* Remaining SQL to execute */
1319 SqlPreparedStmt *pPreStmt; /* Current statement */
1320 int nCol; /* Number of columns returned by pStmt */
1321 Tcl_Obj *pArray; /* Name of array variable */
1322 Tcl_Obj **apColName; /* Array of column names */
1323};
1324
1325/*
1326** Release any cache of column names currently held as part of
1327** the DbEvalContext structure passed as the first argument.
1328*/
1329static void dbReleaseColumnNames(DbEvalContext *p){
1330 if( p->apColName ){
1331 int i;
1332 for(i=0; i<p->nCol; i++){
1333 Tcl_DecrRefCount(p->apColName[i]);
1334 }
1335 Tcl_Free((char *)p->apColName);
1336 p->apColName = 0;
1337 }
1338 p->nCol = 0;
1339}
1340
1341/*
1342** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001343**
1344** If pArray is not NULL, then it contains the name of a Tcl array
1345** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001346** the names of the columns returned by the statement as part of each
1347** call to dbEvalStep(), in order from left to right. e.g. if the names
1348** of the returned columns are a, b and c, it does the equivalent of the
1349** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001350**
1351** set ${pArray}(*) {a b c}
1352*/
dan4a4c11a2009-10-06 14:59:02 +00001353static void dbEvalInit(
1354 DbEvalContext *p, /* Pointer to structure to initialize */
1355 SqliteDb *pDb, /* Database handle */
1356 Tcl_Obj *pSql, /* Object containing SQL script */
1357 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001358){
dan4a4c11a2009-10-06 14:59:02 +00001359 memset(p, 0, sizeof(DbEvalContext));
1360 p->pDb = pDb;
1361 p->zSql = Tcl_GetString(pSql);
1362 p->pSql = pSql;
1363 Tcl_IncrRefCount(pSql);
1364 if( pArray ){
1365 p->pArray = pArray;
1366 Tcl_IncrRefCount(pArray);
1367 }
1368}
danielk19778e556522007-11-13 10:30:24 +00001369
dan4a4c11a2009-10-06 14:59:02 +00001370/*
1371** Obtain information about the row that the DbEvalContext passed as the
1372** first argument currently points to.
1373*/
1374static void dbEvalRowInfo(
1375 DbEvalContext *p, /* Evaluation context */
1376 int *pnCol, /* OUT: Number of column names */
1377 Tcl_Obj ***papColName /* OUT: Array of column names */
1378){
danielk19778e556522007-11-13 10:30:24 +00001379 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001380 if( 0==p->apColName ){
1381 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1382 int i; /* Iterator variable */
1383 int nCol; /* Number of columns returned by pStmt */
1384 Tcl_Obj **apColName = 0; /* Array of column names */
1385
1386 p->nCol = nCol = sqlite3_column_count(pStmt);
1387 if( nCol>0 && (papColName || p->pArray) ){
1388 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1389 for(i=0; i<nCol; i++){
1390 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1391 Tcl_IncrRefCount(apColName[i]);
1392 }
1393 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001394 }
1395
1396 /* If results are being stored in an array variable, then create
1397 ** the array(*) entry for that array
1398 */
dan4a4c11a2009-10-06 14:59:02 +00001399 if( p->pArray ){
1400 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001401 Tcl_Obj *pColList = Tcl_NewObj();
1402 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001403
danielk19778e556522007-11-13 10:30:24 +00001404 for(i=0; i<nCol; i++){
1405 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1406 }
1407 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001408 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001409 Tcl_DecrRefCount(pStar);
1410 }
danielk19778e556522007-11-13 10:30:24 +00001411 }
1412
dan4a4c11a2009-10-06 14:59:02 +00001413 if( papColName ){
1414 *papColName = p->apColName;
1415 }
1416 if( pnCol ){
1417 *pnCol = p->nCol;
1418 }
1419}
1420
1421/*
1422** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1423** returned, then an error message is stored in the interpreter before
1424** returning.
1425**
1426** A return value of TCL_OK means there is a row of data available. The
1427** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1428** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1429** is returned, then the SQL script has finished executing and there are
1430** no further rows available. This is similar to SQLITE_DONE.
1431*/
1432static int dbEvalStep(DbEvalContext *p){
1433 while( p->zSql[0] || p->pPreStmt ){
1434 int rc;
1435 if( p->pPreStmt==0 ){
1436 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1437 if( rc!=TCL_OK ) return rc;
1438 }else{
1439 int rcs;
1440 SqliteDb *pDb = p->pDb;
1441 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1442 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1443
1444 rcs = sqlite3_step(pStmt);
1445 if( rcs==SQLITE_ROW ){
1446 return TCL_OK;
1447 }
1448 if( p->pArray ){
1449 dbEvalRowInfo(p, 0, 0);
1450 }
1451 rcs = sqlite3_reset(pStmt);
1452
1453 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1454 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001455 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
dan4a4c11a2009-10-06 14:59:02 +00001456 dbReleaseColumnNames(p);
1457 p->pPreStmt = 0;
1458
1459 if( rcs!=SQLITE_OK ){
1460 /* If a run-time error occurs, report the error and stop reading
1461 ** the SQL. */
1462 Tcl_SetObjResult(pDb->interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1463 dbReleaseStmt(pDb, pPreStmt, 1);
1464 return TCL_ERROR;
1465 }else{
1466 dbReleaseStmt(pDb, pPreStmt, 0);
1467 }
1468 }
1469 }
1470
1471 /* Finished */
1472 return TCL_BREAK;
1473}
1474
1475/*
1476** Free all resources currently held by the DbEvalContext structure passed
1477** as the first argument. There should be exactly one call to this function
1478** for each call to dbEvalInit().
1479*/
1480static void dbEvalFinalize(DbEvalContext *p){
1481 if( p->pPreStmt ){
1482 sqlite3_reset(p->pPreStmt->pStmt);
1483 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1484 p->pPreStmt = 0;
1485 }
1486 if( p->pArray ){
1487 Tcl_DecrRefCount(p->pArray);
1488 p->pArray = 0;
1489 }
1490 Tcl_DecrRefCount(p->pSql);
1491 dbReleaseColumnNames(p);
1492}
1493
1494/*
1495** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1496** the value for the iCol'th column of the row currently pointed to by
1497** the DbEvalContext structure passed as the first argument.
1498*/
1499static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1500 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1501 switch( sqlite3_column_type(pStmt, iCol) ){
1502 case SQLITE_BLOB: {
1503 int bytes = sqlite3_column_bytes(pStmt, iCol);
1504 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1505 if( !zBlob ) bytes = 0;
1506 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1507 }
1508 case SQLITE_INTEGER: {
1509 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1510 if( v>=-2147483647 && v<=2147483647 ){
1511 return Tcl_NewIntObj(v);
1512 }else{
1513 return Tcl_NewWideIntObj(v);
1514 }
1515 }
1516 case SQLITE_FLOAT: {
1517 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1518 }
1519 case SQLITE_NULL: {
1520 return dbTextToObj(p->pDb->zNull);
1521 }
1522 }
1523
1524 return dbTextToObj((char *)sqlite3_column_text(pStmt, iCol));
1525}
1526
1527/*
1528** If using Tcl version 8.6 or greater, use the NR functions to avoid
1529** recursive evalution of scripts by the [db eval] and [db trans]
1530** commands. Even if the headers used while compiling the extension
1531** are 8.6 or newer, the code still tests the Tcl version at runtime.
1532** This allows stubs-enabled builds to be used with older Tcl libraries.
1533*/
1534#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001535# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001536static int DbUseNre(void){
1537 int major, minor;
1538 Tcl_GetVersion(&major, &minor, 0, 0);
1539 return( (major==8 && minor>=6) || major>8 );
1540}
1541#else
1542/*
1543** Compiling using headers earlier than 8.6. In this case NR cannot be
1544** used, so DbUseNre() to always return zero. Add #defines for the other
1545** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1546** even though the only invocations of them are within conditional blocks
1547** of the form:
1548**
1549** if( DbUseNre() ) { ... }
1550*/
drha2c8a952009-10-13 18:38:34 +00001551# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001552# define DbUseNre() 0
1553# define Tcl_NRAddCallback(a,b,c,d,e,f) 0
1554# define Tcl_NREvalObj(a,b,c) 0
1555# define Tcl_NRCreateCommand(a,b,c,d,e,f) 0
1556#endif
1557
1558/*
1559** This function is part of the implementation of the command:
1560**
1561** $db eval SQL ?ARRAYNAME? SCRIPT
1562*/
1563static int DbEvalNextCmd(
1564 ClientData data[], /* data[0] is the (DbEvalContext*) */
1565 Tcl_Interp *interp, /* Tcl interpreter */
1566 int result /* Result so far */
1567){
1568 int rc = result; /* Return code */
1569
1570 /* The first element of the data[] array is a pointer to a DbEvalContext
1571 ** structure allocated using Tcl_Alloc(). The second element of data[]
1572 ** is a pointer to a Tcl_Obj containing the script to run for each row
1573 ** returned by the queries encapsulated in data[0]. */
1574 DbEvalContext *p = (DbEvalContext *)data[0];
1575 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1576 Tcl_Obj *pArray = p->pArray;
1577
1578 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1579 int i;
1580 int nCol;
1581 Tcl_Obj **apColName;
1582 dbEvalRowInfo(p, &nCol, &apColName);
1583 for(i=0; i<nCol; i++){
1584 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1585 if( pArray==0 ){
1586 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1587 }else{
1588 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1589 }
1590 }
1591
1592 /* The required interpreter variables are now populated with the data
1593 ** from the current row. If using NRE, schedule callbacks to evaluate
1594 ** script pScript, then to invoke this function again to fetch the next
1595 ** row (or clean up if there is no next row or the script throws an
1596 ** exception). After scheduling the callbacks, return control to the
1597 ** caller.
1598 **
1599 ** If not using NRE, evaluate pScript directly and continue with the
1600 ** next iteration of this while(...) loop. */
1601 if( DbUseNre() ){
1602 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1603 return Tcl_NREvalObj(interp, pScript, 0);
1604 }else{
1605 rc = Tcl_EvalObjEx(interp, pScript, 0);
1606 }
1607 }
1608
1609 Tcl_DecrRefCount(pScript);
1610 dbEvalFinalize(p);
1611 Tcl_Free((char *)p);
1612
1613 if( rc==TCL_OK || rc==TCL_BREAK ){
1614 Tcl_ResetResult(interp);
1615 rc = TCL_OK;
1616 }
1617 return rc;
danielk19778e556522007-11-13 10:30:24 +00001618}
1619
tpoindex1067fe12004-12-17 15:41:11 +00001620/*
dan46c47d42011-03-01 18:42:07 +00001621** This function is used by the implementations of the following database
1622** handle sub-commands:
1623**
1624** $db update_hook ?SCRIPT?
1625** $db wal_hook ?SCRIPT?
1626** $db commit_hook ?SCRIPT?
1627** $db preupdate hook ?SCRIPT?
1628*/
1629static void DbHookCmd(
1630 Tcl_Interp *interp, /* Tcl interpreter */
1631 SqliteDb *pDb, /* Database handle */
1632 Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */
1633 Tcl_Obj **ppHook /* Pointer to member of SqliteDb */
1634){
1635 sqlite3 *db = pDb->db;
1636
1637 if( *ppHook ){
1638 Tcl_SetObjResult(interp, *ppHook);
1639 if( pArg ){
1640 Tcl_DecrRefCount(*ppHook);
1641 *ppHook = 0;
1642 }
1643 }
1644 if( pArg ){
1645 assert( !(*ppHook) );
1646 if( Tcl_GetCharLength(pArg)>0 ){
1647 *ppHook = pArg;
1648 Tcl_IncrRefCount(*ppHook);
1649 }
1650 }
1651
1652 sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
1653 sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1654 sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1655 sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
dan21e8d012011-03-03 20:05:59 +00001656 sqlite3_transaction_hook(db, (pDb->pTransHook?DbTransHandler:0), pDb);
dan46c47d42011-03-01 18:42:07 +00001657}
1658
1659/*
drh75897232000-05-29 14:26:00 +00001660** The "sqlite" command below creates a new Tcl command for each
1661** connection it opens to an SQLite database. This routine is invoked
1662** whenever one of those connection-specific commands is executed
1663** in Tcl. For example, if you run Tcl code like this:
1664**
drh9bb575f2004-09-06 17:24:11 +00001665** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001666** db1 close
1667**
1668** The first command opens a connection to the "my_database" database
1669** and calls that connection "db1". The second command causes this
1670** subroutine to be invoked.
1671*/
drh6d313162000-09-21 13:01:35 +00001672static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001673 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001674 int choice;
drh22fbcb82004-02-01 01:22:50 +00001675 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001676 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001677 "authorizer", "backup", "busy",
1678 "cache", "changes", "close",
1679 "collate", "collation_needed", "commit_hook",
1680 "complete", "copy", "enable_load_extension",
1681 "errorcode", "eval", "exists",
1682 "function", "incrblob", "interrupt",
drh833bf962010-04-28 14:42:19 +00001683 "last_insert_rowid", "nullvalue", "onecolumn",
dan46c47d42011-03-01 18:42:07 +00001684 "preupdate",
drh833bf962010-04-28 14:42:19 +00001685 "profile", "progress", "rekey",
1686 "restore", "rollback_hook", "status",
1687 "timeout", "total_changes", "trace",
dan21e8d012011-03-03 20:05:59 +00001688 "transaction", "transaction_hook",
1689 "unlock_notify", "update_hook",
drh833bf962010-04-28 14:42:19 +00001690 "version", "wal_hook", 0
drh6d313162000-09-21 13:01:35 +00001691 };
drh411995d2002-06-25 19:31:18 +00001692 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001693 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1694 DB_CACHE, DB_CHANGES, DB_CLOSE,
1695 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1696 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1697 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1698 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
drh833bf962010-04-28 14:42:19 +00001699 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
dan46c47d42011-03-01 18:42:07 +00001700 DB_PREUPDATE,
drh833bf962010-04-28 14:42:19 +00001701 DB_PROFILE, DB_PROGRESS, DB_REKEY,
1702 DB_RESTORE, DB_ROLLBACK_HOOK, DB_STATUS,
1703 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
dan21e8d012011-03-03 20:05:59 +00001704 DB_TRANSACTION, DB_TRANSACTION_HOOK,
1705 DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK,
drh833bf962010-04-28 14:42:19 +00001706 DB_VERSION, DB_WAL_HOOK
drh6d313162000-09-21 13:01:35 +00001707 };
tpoindex1067fe12004-12-17 15:41:11 +00001708 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001709
1710 if( objc<2 ){
1711 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001712 return TCL_ERROR;
1713 }
drh411995d2002-06-25 19:31:18 +00001714 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001715 return TCL_ERROR;
1716 }
1717
drh411995d2002-06-25 19:31:18 +00001718 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001719
drhe22a3342003-04-22 20:30:37 +00001720 /* $db authorizer ?CALLBACK?
1721 **
1722 ** Invoke the given callback to authorize each SQL operation as it is
1723 ** compiled. 5 arguments are appended to the callback before it is
1724 ** invoked:
1725 **
1726 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1727 ** (2) First descriptive name (depends on authorization type)
1728 ** (3) Second descriptive name
1729 ** (4) Name of the database (ex: "main", "temp")
1730 ** (5) Name of trigger that is doing the access
1731 **
1732 ** The callback should return on of the following strings: SQLITE_OK,
1733 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1734 **
1735 ** If this method is invoked with no arguments, the current authorization
1736 ** callback string is returned.
1737 */
1738 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001739#ifdef SQLITE_OMIT_AUTHORIZATION
1740 Tcl_AppendResult(interp, "authorization not available in this build", 0);
1741 return TCL_ERROR;
1742#else
drhe22a3342003-04-22 20:30:37 +00001743 if( objc>3 ){
1744 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001745 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001746 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001747 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +00001748 Tcl_AppendResult(interp, pDb->zAuth, 0);
1749 }
1750 }else{
1751 char *zAuth;
1752 int len;
1753 if( pDb->zAuth ){
1754 Tcl_Free(pDb->zAuth);
1755 }
1756 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1757 if( zAuth && len>0 ){
1758 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001759 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001760 }else{
1761 pDb->zAuth = 0;
1762 }
drhe22a3342003-04-22 20:30:37 +00001763 if( pDb->zAuth ){
1764 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001765 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +00001766 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001767 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001768 }
drhe22a3342003-04-22 20:30:37 +00001769 }
drh1211de32004-07-26 12:24:22 +00001770#endif
drhe22a3342003-04-22 20:30:37 +00001771 break;
1772 }
1773
drhdc2c4912009-02-04 22:46:47 +00001774 /* $db backup ?DATABASE? FILENAME
1775 **
1776 ** Open or create a database file named FILENAME. Transfer the
1777 ** content of local database DATABASE (default: "main") into the
1778 ** FILENAME database.
1779 */
1780 case DB_BACKUP: {
1781 const char *zDestFile;
1782 const char *zSrcDb;
1783 sqlite3 *pDest;
1784 sqlite3_backup *pBackup;
1785
1786 if( objc==3 ){
1787 zSrcDb = "main";
1788 zDestFile = Tcl_GetString(objv[2]);
1789 }else if( objc==4 ){
1790 zSrcDb = Tcl_GetString(objv[2]);
1791 zDestFile = Tcl_GetString(objv[3]);
1792 }else{
1793 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1794 return TCL_ERROR;
1795 }
1796 rc = sqlite3_open(zDestFile, &pDest);
1797 if( rc!=SQLITE_OK ){
1798 Tcl_AppendResult(interp, "cannot open target database: ",
1799 sqlite3_errmsg(pDest), (char*)0);
1800 sqlite3_close(pDest);
1801 return TCL_ERROR;
1802 }
1803 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1804 if( pBackup==0 ){
1805 Tcl_AppendResult(interp, "backup failed: ",
1806 sqlite3_errmsg(pDest), (char*)0);
1807 sqlite3_close(pDest);
1808 return TCL_ERROR;
1809 }
1810 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1811 sqlite3_backup_finish(pBackup);
1812 if( rc==SQLITE_DONE ){
1813 rc = TCL_OK;
1814 }else{
1815 Tcl_AppendResult(interp, "backup failed: ",
1816 sqlite3_errmsg(pDest), (char*)0);
1817 rc = TCL_ERROR;
1818 }
1819 sqlite3_close(pDest);
1820 break;
1821 }
1822
drhbec3f402000-08-04 13:49:02 +00001823 /* $db busy ?CALLBACK?
1824 **
1825 ** Invoke the given callback if an SQL statement attempts to open
1826 ** a locked database file.
1827 */
drh6d313162000-09-21 13:01:35 +00001828 case DB_BUSY: {
1829 if( objc>3 ){
1830 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001831 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001832 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001833 if( pDb->zBusy ){
1834 Tcl_AppendResult(interp, pDb->zBusy, 0);
1835 }
1836 }else{
drh6d313162000-09-21 13:01:35 +00001837 char *zBusy;
1838 int len;
drhbec3f402000-08-04 13:49:02 +00001839 if( pDb->zBusy ){
1840 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001841 }
drh6d313162000-09-21 13:01:35 +00001842 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1843 if( zBusy && len>0 ){
1844 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001845 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001846 }else{
1847 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001848 }
1849 if( pDb->zBusy ){
1850 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001851 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001852 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001853 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001854 }
1855 }
drh6d313162000-09-21 13:01:35 +00001856 break;
1857 }
drhbec3f402000-08-04 13:49:02 +00001858
drhfb7e7652005-01-24 00:28:42 +00001859 /* $db cache flush
1860 ** $db cache size n
1861 **
1862 ** Flush the prepared statement cache, or set the maximum number of
1863 ** cached statements.
1864 */
1865 case DB_CACHE: {
1866 char *subCmd;
1867 int n;
1868
1869 if( objc<=2 ){
1870 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1871 return TCL_ERROR;
1872 }
1873 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1874 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1875 if( objc!=3 ){
1876 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1877 return TCL_ERROR;
1878 }else{
1879 flushStmtCache( pDb );
1880 }
1881 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1882 if( objc!=4 ){
1883 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1884 return TCL_ERROR;
1885 }else{
1886 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1887 Tcl_AppendResult( interp, "cannot convert \"",
1888 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1889 return TCL_ERROR;
1890 }else{
1891 if( n<0 ){
1892 flushStmtCache( pDb );
1893 n = 0;
1894 }else if( n>MAX_PREPARED_STMTS ){
1895 n = MAX_PREPARED_STMTS;
1896 }
1897 pDb->maxStmt = n;
1898 }
1899 }
1900 }else{
1901 Tcl_AppendResult( interp, "bad option \"",
danielk1977191fadc2007-10-23 08:17:48 +00001902 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
drhfb7e7652005-01-24 00:28:42 +00001903 return TCL_ERROR;
1904 }
1905 break;
1906 }
1907
danielk1977b28af712004-06-21 06:50:26 +00001908 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001909 **
1910 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001911 ** the most recent INSERT, UPDATE or DELETE statement, not including
1912 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001913 */
1914 case DB_CHANGES: {
1915 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001916 if( objc!=2 ){
1917 Tcl_WrongNumArgs(interp, 2, objv, "");
1918 return TCL_ERROR;
1919 }
drhc8d30ac2002-04-12 10:08:59 +00001920 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001921 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001922 break;
1923 }
1924
drh75897232000-05-29 14:26:00 +00001925 /* $db close
1926 **
1927 ** Shutdown the database
1928 */
drh6d313162000-09-21 13:01:35 +00001929 case DB_CLOSE: {
1930 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1931 break;
1932 }
drh75897232000-05-29 14:26:00 +00001933
drh0f14e2e2004-06-29 12:39:08 +00001934 /*
1935 ** $db collate NAME SCRIPT
1936 **
1937 ** Create a new SQL collation function called NAME. Whenever
1938 ** that function is called, invoke SCRIPT to evaluate the function.
1939 */
1940 case DB_COLLATE: {
1941 SqlCollate *pCollate;
1942 char *zName;
1943 char *zScript;
1944 int nScript;
1945 if( objc!=4 ){
1946 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1947 return TCL_ERROR;
1948 }
1949 zName = Tcl_GetStringFromObj(objv[2], 0);
1950 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1951 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1952 if( pCollate==0 ) return TCL_ERROR;
1953 pCollate->interp = interp;
1954 pCollate->pNext = pDb->pCollate;
1955 pCollate->zScript = (char*)&pCollate[1];
1956 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001957 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001958 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1959 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001960 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001961 return TCL_ERROR;
1962 }
1963 break;
1964 }
1965
1966 /*
1967 ** $db collation_needed SCRIPT
1968 **
1969 ** Create a new SQL collation function called NAME. Whenever
1970 ** that function is called, invoke SCRIPT to evaluate the function.
1971 */
1972 case DB_COLLATION_NEEDED: {
1973 if( objc!=3 ){
1974 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1975 return TCL_ERROR;
1976 }
1977 if( pDb->pCollateNeeded ){
1978 Tcl_DecrRefCount(pDb->pCollateNeeded);
1979 }
1980 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1981 Tcl_IncrRefCount(pDb->pCollateNeeded);
1982 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1983 break;
1984 }
1985
drh19e2d372005-08-29 23:00:03 +00001986 /* $db commit_hook ?CALLBACK?
1987 **
1988 ** Invoke the given callback just before committing every SQL transaction.
1989 ** If the callback throws an exception or returns non-zero, then the
1990 ** transaction is aborted. If CALLBACK is an empty string, the callback
1991 ** is disabled.
1992 */
1993 case DB_COMMIT_HOOK: {
1994 if( objc>3 ){
1995 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1996 return TCL_ERROR;
1997 }else if( objc==2 ){
1998 if( pDb->zCommit ){
1999 Tcl_AppendResult(interp, pDb->zCommit, 0);
2000 }
2001 }else{
2002 char *zCommit;
2003 int len;
2004 if( pDb->zCommit ){
2005 Tcl_Free(pDb->zCommit);
2006 }
2007 zCommit = Tcl_GetStringFromObj(objv[2], &len);
2008 if( zCommit && len>0 ){
2009 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002010 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00002011 }else{
2012 pDb->zCommit = 0;
2013 }
2014 if( pDb->zCommit ){
2015 pDb->interp = interp;
2016 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
2017 }else{
2018 sqlite3_commit_hook(pDb->db, 0, 0);
2019 }
2020 }
2021 break;
2022 }
2023
drh75897232000-05-29 14:26:00 +00002024 /* $db complete SQL
2025 **
2026 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2027 ** additional lines of input are needed. This is similar to the
2028 ** built-in "info complete" command of Tcl.
2029 */
drh6d313162000-09-21 13:01:35 +00002030 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00002031#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00002032 Tcl_Obj *pResult;
2033 int isComplete;
2034 if( objc!=3 ){
2035 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00002036 return TCL_ERROR;
2037 }
danielk19776f8a5032004-05-10 10:34:51 +00002038 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00002039 pResult = Tcl_GetObjResult(interp);
2040 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00002041#endif
drh6d313162000-09-21 13:01:35 +00002042 break;
2043 }
drhdcd997e2003-01-31 17:21:49 +00002044
drh19e2d372005-08-29 23:00:03 +00002045 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2046 **
2047 ** Copy data into table from filename, optionally using SEPARATOR
2048 ** as column separators. If a column contains a null string, or the
2049 ** value of NULLINDICATOR, a NULL is inserted for the column.
2050 ** conflict-algorithm is one of the sqlite conflict algorithms:
2051 ** rollback, abort, fail, ignore, replace
2052 ** On success, return the number of lines processed, not necessarily same
2053 ** as 'db changes' due to conflict-algorithm selected.
2054 **
2055 ** This code is basically an implementation/enhancement of
2056 ** the sqlite3 shell.c ".import" command.
2057 **
2058 ** This command usage is equivalent to the sqlite2.x COPY statement,
2059 ** which imports file data into a table using the PostgreSQL COPY file format:
2060 ** $db copy $conflit_algo $table_name $filename \t \\N
2061 */
2062 case DB_COPY: {
2063 char *zTable; /* Insert data into this table */
2064 char *zFile; /* The file from which to extract data */
2065 char *zConflict; /* The conflict algorithm to use */
2066 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00002067 int nCol; /* Number of columns in the table */
2068 int nByte; /* Number of bytes in an SQL string */
2069 int i, j; /* Loop counters */
2070 int nSep; /* Number of bytes in zSep[] */
2071 int nNull; /* Number of bytes in zNull[] */
2072 char *zSql; /* An SQL statement */
2073 char *zLine; /* A single line of input from the file */
2074 char **azCol; /* zLine[] broken up into columns */
2075 char *zCommit; /* How to commit changes */
2076 FILE *in; /* The input file */
2077 int lineno = 0; /* Line number of input file */
2078 char zLineNum[80]; /* Line number print buffer */
2079 Tcl_Obj *pResult; /* interp result */
2080
2081 char *zSep;
2082 char *zNull;
2083 if( objc<5 || objc>7 ){
2084 Tcl_WrongNumArgs(interp, 2, objv,
2085 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2086 return TCL_ERROR;
2087 }
2088 if( objc>=6 ){
2089 zSep = Tcl_GetStringFromObj(objv[5], 0);
2090 }else{
2091 zSep = "\t";
2092 }
2093 if( objc>=7 ){
2094 zNull = Tcl_GetStringFromObj(objv[6], 0);
2095 }else{
2096 zNull = "";
2097 }
2098 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2099 zTable = Tcl_GetStringFromObj(objv[3], 0);
2100 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002101 nSep = strlen30(zSep);
2102 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002103 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00002104 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00002105 return TCL_ERROR;
2106 }
drh3e59c012008-09-23 10:12:13 +00002107 if(strcmp(zConflict, "rollback") != 0 &&
2108 strcmp(zConflict, "abort" ) != 0 &&
2109 strcmp(zConflict, "fail" ) != 0 &&
2110 strcmp(zConflict, "ignore" ) != 0 &&
2111 strcmp(zConflict, "replace" ) != 0 ) {
drh19e2d372005-08-29 23:00:03 +00002112 Tcl_AppendResult(interp, "Error: \"", zConflict,
2113 "\", conflict-algorithm must be one of: rollback, "
2114 "abort, fail, ignore, or replace", 0);
2115 return TCL_ERROR;
2116 }
2117 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2118 if( zSql==0 ){
2119 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
2120 return TCL_ERROR;
2121 }
drh4f21c4a2008-12-10 22:15:00 +00002122 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002123 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002124 sqlite3_free(zSql);
2125 if( rc ){
2126 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2127 nCol = 0;
2128 }else{
2129 nCol = sqlite3_column_count(pStmt);
2130 }
2131 sqlite3_finalize(pStmt);
2132 if( nCol==0 ) {
2133 return TCL_ERROR;
2134 }
2135 zSql = malloc( nByte + 50 + nCol*2 );
2136 if( zSql==0 ) {
2137 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
2138 return TCL_ERROR;
2139 }
2140 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2141 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002142 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002143 for(i=1; i<nCol; i++){
2144 zSql[j++] = ',';
2145 zSql[j++] = '?';
2146 }
2147 zSql[j++] = ')';
2148 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002149 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002150 free(zSql);
2151 if( rc ){
2152 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2153 sqlite3_finalize(pStmt);
2154 return TCL_ERROR;
2155 }
2156 in = fopen(zFile, "rb");
2157 if( in==0 ){
2158 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2159 sqlite3_finalize(pStmt);
2160 return TCL_ERROR;
2161 }
2162 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2163 if( azCol==0 ) {
2164 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00002165 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002166 return TCL_ERROR;
2167 }
drh37527852006-03-16 16:19:56 +00002168 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002169 zCommit = "COMMIT";
2170 while( (zLine = local_getline(0, in))!=0 ){
2171 char *z;
2172 i = 0;
2173 lineno++;
2174 azCol[0] = zLine;
2175 for(i=0, z=zLine; *z; z++){
2176 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2177 *z = 0;
2178 i++;
2179 if( i<nCol ){
2180 azCol[i] = &z[nSep];
2181 z += nSep-1;
2182 }
2183 }
2184 }
2185 if( i+1!=nCol ){
2186 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002187 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002188 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002189 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002190 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002191 "Error: %s line %d: expected %d columns of data but found %d",
2192 zFile, lineno, nCol, i+1);
2193 Tcl_AppendResult(interp, zErr, 0);
2194 free(zErr);
2195 }
drh19e2d372005-08-29 23:00:03 +00002196 zCommit = "ROLLBACK";
2197 break;
2198 }
2199 for(i=0; i<nCol; i++){
2200 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002201 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
drh4f21c4a2008-12-10 22:15:00 +00002202 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002203 ){
drh19e2d372005-08-29 23:00:03 +00002204 sqlite3_bind_null(pStmt, i+1);
2205 }else{
2206 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2207 }
2208 }
2209 sqlite3_step(pStmt);
2210 rc = sqlite3_reset(pStmt);
2211 free(zLine);
2212 if( rc!=SQLITE_OK ){
2213 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
2214 zCommit = "ROLLBACK";
2215 break;
2216 }
2217 }
2218 free(azCol);
2219 fclose(in);
2220 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002221 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002222
2223 if( zCommit[0] == 'C' ){
2224 /* success, set result as number of lines processed */
2225 pResult = Tcl_GetObjResult(interp);
2226 Tcl_SetIntObj(pResult, lineno);
2227 rc = TCL_OK;
2228 }else{
2229 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002230 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00002231 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
2232 rc = TCL_ERROR;
2233 }
2234 break;
2235 }
2236
drhdcd997e2003-01-31 17:21:49 +00002237 /*
drh41449052006-07-06 17:08:48 +00002238 ** $db enable_load_extension BOOLEAN
2239 **
2240 ** Turn the extension loading feature on or off. It if off by
2241 ** default.
2242 */
2243 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002244#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002245 int onoff;
2246 if( objc!=3 ){
2247 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2248 return TCL_ERROR;
2249 }
2250 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2251 return TCL_ERROR;
2252 }
2253 sqlite3_enable_load_extension(pDb->db, onoff);
2254 break;
drhf533acc2006-12-19 18:57:11 +00002255#else
2256 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2257 0);
2258 return TCL_ERROR;
2259#endif
drh41449052006-07-06 17:08:48 +00002260 }
2261
2262 /*
drhdcd997e2003-01-31 17:21:49 +00002263 ** $db errorcode
2264 **
2265 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002266 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002267 */
2268 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002269 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002270 break;
2271 }
dan4a4c11a2009-10-06 14:59:02 +00002272
2273 /*
2274 ** $db exists $sql
2275 ** $db onecolumn $sql
2276 **
2277 ** The onecolumn method is the equivalent of:
2278 ** lindex [$db eval $sql] 0
2279 */
2280 case DB_EXISTS:
2281 case DB_ONECOLUMN: {
2282 DbEvalContext sEval;
2283 if( objc!=3 ){
2284 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2285 return TCL_ERROR;
2286 }
2287
2288 dbEvalInit(&sEval, pDb, objv[2], 0);
2289 rc = dbEvalStep(&sEval);
2290 if( choice==DB_ONECOLUMN ){
2291 if( rc==TCL_OK ){
2292 Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
2293 }
2294 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2295 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
2296 }
2297 dbEvalFinalize(&sEval);
2298
2299 if( rc==TCL_BREAK ){
2300 rc = TCL_OK;
2301 }
2302 break;
2303 }
drh75897232000-05-29 14:26:00 +00002304
2305 /*
drh895d7472004-08-20 16:02:39 +00002306 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002307 **
2308 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002309 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002310 ** If "array" and "code" are omitted, then no callback is every invoked.
2311 ** If "array" is an empty string, then the values are placed in variables
2312 ** that have the same name as the fields extracted by the query.
2313 */
dan4a4c11a2009-10-06 14:59:02 +00002314 case DB_EVAL: {
2315 if( objc<3 || objc>5 ){
2316 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2317 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002318 }
dan4a4c11a2009-10-06 14:59:02 +00002319
drh92febd92004-08-20 18:34:20 +00002320 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002321 DbEvalContext sEval;
2322 Tcl_Obj *pRet = Tcl_NewObj();
2323 Tcl_IncrRefCount(pRet);
2324 dbEvalInit(&sEval, pDb, objv[2], 0);
2325 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2326 int i;
2327 int nCol;
2328 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002329 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002330 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002331 }
2332 }
dan4a4c11a2009-10-06 14:59:02 +00002333 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002334 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002335 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002336 rc = TCL_OK;
2337 }
drh1807ce32004-09-07 13:20:35 +00002338 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002339 }else{
2340 ClientData cd[2];
2341 DbEvalContext *p;
2342 Tcl_Obj *pArray = 0;
2343 Tcl_Obj *pScript;
2344
2345 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2346 pArray = objv[3];
2347 }
2348 pScript = objv[objc-1];
2349 Tcl_IncrRefCount(pScript);
2350
2351 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2352 dbEvalInit(p, pDb, objv[2], pArray);
2353
2354 cd[0] = (void *)p;
2355 cd[1] = (void *)pScript;
2356 rc = DbEvalNextCmd(cd, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002357 }
danielk197730ccda12004-05-27 12:11:31 +00002358 break;
2359 }
drhbec3f402000-08-04 13:49:02 +00002360
2361 /*
drhe3602be2008-09-09 12:31:33 +00002362 ** $db function NAME [-argcount N] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002363 **
2364 ** Create a new SQL function called NAME. Whenever that function is
2365 ** called, invoke SCRIPT to evaluate the function.
2366 */
2367 case DB_FUNCTION: {
2368 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002369 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002370 char *zName;
drhe3602be2008-09-09 12:31:33 +00002371 int nArg = -1;
2372 if( objc==6 ){
2373 const char *z = Tcl_GetString(objv[3]);
drh4f21c4a2008-12-10 22:15:00 +00002374 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002375 if( n>2 && strncmp(z, "-argcount",n)==0 ){
2376 if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
2377 if( nArg<0 ){
2378 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2379 (char*)0);
2380 return TCL_ERROR;
2381 }
2382 }
2383 pScript = objv[5];
2384 }else if( objc!=4 ){
2385 Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
drhcabb0812002-09-14 13:47:32 +00002386 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002387 }else{
2388 pScript = objv[3];
drhcabb0812002-09-14 13:47:32 +00002389 }
2390 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002391 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002392 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002393 if( pFunc->pScript ){
2394 Tcl_DecrRefCount(pFunc->pScript);
2395 }
2396 pFunc->pScript = pScript;
2397 Tcl_IncrRefCount(pScript);
2398 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
drhe3602be2008-09-09 12:31:33 +00002399 rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00002400 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002401 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002402 rc = TCL_ERROR;
2403 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002404 }
drhcabb0812002-09-14 13:47:32 +00002405 break;
2406 }
2407
2408 /*
danielk19778cbadb02007-05-03 16:31:26 +00002409 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002410 */
2411 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002412#ifdef SQLITE_OMIT_INCRBLOB
2413 Tcl_AppendResult(interp, "incrblob not available in this build", 0);
2414 return TCL_ERROR;
2415#else
danielk19778cbadb02007-05-03 16:31:26 +00002416 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002417 const char *zDb = "main";
2418 const char *zTable;
2419 const char *zColumn;
2420 sqlite_int64 iRow;
2421
danielk19778cbadb02007-05-03 16:31:26 +00002422 /* Check for the -readonly option */
2423 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2424 isReadonly = 1;
2425 }
2426
2427 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2428 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002429 return TCL_ERROR;
2430 }
2431
danielk19778cbadb02007-05-03 16:31:26 +00002432 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002433 zDb = Tcl_GetString(objv[2]);
2434 }
2435 zTable = Tcl_GetString(objv[objc-3]);
2436 zColumn = Tcl_GetString(objv[objc-2]);
2437 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2438
2439 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002440 rc = createIncrblobChannel(
2441 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
2442 );
danielk1977b4e9af92007-05-01 17:49:49 +00002443 }
danielk197732a0d8b2007-05-04 19:03:02 +00002444#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002445 break;
2446 }
2447
2448 /*
drhf11bded2006-07-17 00:02:44 +00002449 ** $db interrupt
2450 **
2451 ** Interrupt the execution of the inner-most SQL interpreter. This
2452 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2453 */
2454 case DB_INTERRUPT: {
2455 sqlite3_interrupt(pDb->db);
2456 break;
2457 }
2458
2459 /*
drh19e2d372005-08-29 23:00:03 +00002460 ** $db nullvalue ?STRING?
2461 **
2462 ** Change text used when a NULL comes back from the database. If ?STRING?
2463 ** is not present, then the current string used for NULL is returned.
2464 ** If STRING is present, then STRING is returned.
2465 **
2466 */
2467 case DB_NULLVALUE: {
2468 if( objc!=2 && objc!=3 ){
2469 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2470 return TCL_ERROR;
2471 }
2472 if( objc==3 ){
2473 int len;
2474 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2475 if( pDb->zNull ){
2476 Tcl_Free(pDb->zNull);
2477 }
2478 if( zNull && len>0 ){
2479 pDb->zNull = Tcl_Alloc( len + 1 );
2480 strncpy(pDb->zNull, zNull, len);
2481 pDb->zNull[len] = '\0';
2482 }else{
2483 pDb->zNull = 0;
2484 }
2485 }
2486 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
2487 break;
2488 }
2489
2490 /*
drhaf9ff332002-01-16 21:00:27 +00002491 ** $db last_insert_rowid
2492 **
2493 ** Return an integer which is the ROWID for the most recent insert.
2494 */
2495 case DB_LAST_INSERT_ROWID: {
2496 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002497 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002498 if( objc!=2 ){
2499 Tcl_WrongNumArgs(interp, 2, objv, "");
2500 return TCL_ERROR;
2501 }
danielk19776f8a5032004-05-10 10:34:51 +00002502 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002503 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002504 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002505 break;
2506 }
2507
2508 /*
dan4a4c11a2009-10-06 14:59:02 +00002509 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002510 */
drh1807ce32004-09-07 13:20:35 +00002511
2512 /* $db progress ?N CALLBACK?
2513 **
2514 ** Invoke the given callback every N virtual machine opcodes while executing
2515 ** queries.
2516 */
2517 case DB_PROGRESS: {
2518 if( objc==2 ){
2519 if( pDb->zProgress ){
2520 Tcl_AppendResult(interp, pDb->zProgress, 0);
2521 }
2522 }else if( objc==4 ){
2523 char *zProgress;
2524 int len;
2525 int N;
2526 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002527 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002528 };
2529 if( pDb->zProgress ){
2530 Tcl_Free(pDb->zProgress);
2531 }
2532 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2533 if( zProgress && len>0 ){
2534 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002535 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002536 }else{
2537 pDb->zProgress = 0;
2538 }
2539#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2540 if( pDb->zProgress ){
2541 pDb->interp = interp;
2542 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2543 }else{
2544 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2545 }
2546#endif
2547 }else{
2548 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002549 return TCL_ERROR;
2550 }
drh5d9d7572003-08-19 14:31:01 +00002551 break;
2552 }
2553
drh19e2d372005-08-29 23:00:03 +00002554 /* $db profile ?CALLBACK?
2555 **
2556 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2557 ** that has run. The text of the SQL and the amount of elapse time are
2558 ** appended to CALLBACK before the script is run.
2559 */
2560 case DB_PROFILE: {
2561 if( objc>3 ){
2562 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2563 return TCL_ERROR;
2564 }else if( objc==2 ){
2565 if( pDb->zProfile ){
2566 Tcl_AppendResult(interp, pDb->zProfile, 0);
2567 }
2568 }else{
2569 char *zProfile;
2570 int len;
2571 if( pDb->zProfile ){
2572 Tcl_Free(pDb->zProfile);
2573 }
2574 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2575 if( zProfile && len>0 ){
2576 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002577 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002578 }else{
2579 pDb->zProfile = 0;
2580 }
shanehbb201342011-02-09 19:55:20 +00002581#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh19e2d372005-08-29 23:00:03 +00002582 if( pDb->zProfile ){
2583 pDb->interp = interp;
2584 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2585 }else{
2586 sqlite3_profile(pDb->db, 0, 0);
2587 }
2588#endif
2589 }
2590 break;
2591 }
2592
drh5d9d7572003-08-19 14:31:01 +00002593 /*
drh22fbcb82004-02-01 01:22:50 +00002594 ** $db rekey KEY
2595 **
2596 ** Change the encryption key on the currently open database.
2597 */
2598 case DB_REKEY: {
2599 int nKey;
2600 void *pKey;
2601 if( objc!=3 ){
2602 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2603 return TCL_ERROR;
2604 }
2605 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00002606#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00002607 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002608 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00002609 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002610 rc = TCL_ERROR;
2611 }
2612#endif
2613 break;
2614 }
2615
drhdc2c4912009-02-04 22:46:47 +00002616 /* $db restore ?DATABASE? FILENAME
2617 **
2618 ** Open a database file named FILENAME. Transfer the content
2619 ** of FILENAME into the local database DATABASE (default: "main").
2620 */
2621 case DB_RESTORE: {
2622 const char *zSrcFile;
2623 const char *zDestDb;
2624 sqlite3 *pSrc;
2625 sqlite3_backup *pBackup;
2626 int nTimeout = 0;
2627
2628 if( objc==3 ){
2629 zDestDb = "main";
2630 zSrcFile = Tcl_GetString(objv[2]);
2631 }else if( objc==4 ){
2632 zDestDb = Tcl_GetString(objv[2]);
2633 zSrcFile = Tcl_GetString(objv[3]);
2634 }else{
2635 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2636 return TCL_ERROR;
2637 }
2638 rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
2639 if( rc!=SQLITE_OK ){
2640 Tcl_AppendResult(interp, "cannot open source database: ",
2641 sqlite3_errmsg(pSrc), (char*)0);
2642 sqlite3_close(pSrc);
2643 return TCL_ERROR;
2644 }
2645 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2646 if( pBackup==0 ){
2647 Tcl_AppendResult(interp, "restore failed: ",
2648 sqlite3_errmsg(pDb->db), (char*)0);
2649 sqlite3_close(pSrc);
2650 return TCL_ERROR;
2651 }
2652 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2653 || rc==SQLITE_BUSY ){
2654 if( rc==SQLITE_BUSY ){
2655 if( nTimeout++ >= 3 ) break;
2656 sqlite3_sleep(100);
2657 }
2658 }
2659 sqlite3_backup_finish(pBackup);
2660 if( rc==SQLITE_DONE ){
2661 rc = TCL_OK;
2662 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2663 Tcl_AppendResult(interp, "restore failed: source database busy",
2664 (char*)0);
2665 rc = TCL_ERROR;
2666 }else{
2667 Tcl_AppendResult(interp, "restore failed: ",
2668 sqlite3_errmsg(pDb->db), (char*)0);
2669 rc = TCL_ERROR;
2670 }
2671 sqlite3_close(pSrc);
2672 break;
2673 }
2674
drh22fbcb82004-02-01 01:22:50 +00002675 /*
drh3c379b02010-04-07 19:31:59 +00002676 ** $db status (step|sort|autoindex)
drhd1d38482008-10-07 23:46:38 +00002677 **
2678 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2679 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2680 */
2681 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002682 int v;
2683 const char *zOp;
2684 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00002685 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00002686 return TCL_ERROR;
2687 }
2688 zOp = Tcl_GetString(objv[2]);
2689 if( strcmp(zOp, "step")==0 ){
2690 v = pDb->nStep;
2691 }else if( strcmp(zOp, "sort")==0 ){
2692 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002693 }else if( strcmp(zOp, "autoindex")==0 ){
2694 v = pDb->nIndex;
drhd1d38482008-10-07 23:46:38 +00002695 }else{
drh3c379b02010-04-07 19:31:59 +00002696 Tcl_AppendResult(interp,
2697 "bad argument: should be autoindex, step, or sort",
drhd1d38482008-10-07 23:46:38 +00002698 (char*)0);
2699 return TCL_ERROR;
2700 }
2701 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2702 break;
2703 }
2704
2705 /*
drhbec3f402000-08-04 13:49:02 +00002706 ** $db timeout MILLESECONDS
2707 **
2708 ** Delay for the number of milliseconds specified when a file is locked.
2709 */
drh6d313162000-09-21 13:01:35 +00002710 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002711 int ms;
drh6d313162000-09-21 13:01:35 +00002712 if( objc!=3 ){
2713 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002714 return TCL_ERROR;
2715 }
drh6d313162000-09-21 13:01:35 +00002716 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002717 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002718 break;
drh75897232000-05-29 14:26:00 +00002719 }
danielk197755c45f22005-04-03 23:54:43 +00002720
2721 /*
drh0f14e2e2004-06-29 12:39:08 +00002722 ** $db total_changes
2723 **
2724 ** Return the number of rows that were modified, inserted, or deleted
2725 ** since the database handle was created.
2726 */
2727 case DB_TOTAL_CHANGES: {
2728 Tcl_Obj *pResult;
2729 if( objc!=2 ){
2730 Tcl_WrongNumArgs(interp, 2, objv, "");
2731 return TCL_ERROR;
2732 }
2733 pResult = Tcl_GetObjResult(interp);
2734 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2735 break;
2736 }
2737
drhb5a20d32003-04-23 12:25:23 +00002738 /* $db trace ?CALLBACK?
2739 **
2740 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2741 ** that is executed. The text of the SQL is appended to CALLBACK before
2742 ** it is executed.
2743 */
2744 case DB_TRACE: {
2745 if( objc>3 ){
2746 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002747 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002748 }else if( objc==2 ){
2749 if( pDb->zTrace ){
2750 Tcl_AppendResult(interp, pDb->zTrace, 0);
2751 }
2752 }else{
2753 char *zTrace;
2754 int len;
2755 if( pDb->zTrace ){
2756 Tcl_Free(pDb->zTrace);
2757 }
2758 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2759 if( zTrace && len>0 ){
2760 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002761 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002762 }else{
2763 pDb->zTrace = 0;
2764 }
shanehbb201342011-02-09 19:55:20 +00002765#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drhb5a20d32003-04-23 12:25:23 +00002766 if( pDb->zTrace ){
2767 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002768 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002769 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002770 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002771 }
drh19e2d372005-08-29 23:00:03 +00002772#endif
drhb5a20d32003-04-23 12:25:23 +00002773 }
2774 break;
2775 }
2776
drh3d214232005-08-02 12:21:08 +00002777 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2778 **
2779 ** Start a new transaction (if we are not already in the midst of a
2780 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2781 ** completes, either commit the transaction or roll it back if SCRIPT
2782 ** throws an exception. Or if no new transation was started, do nothing.
2783 ** pass the exception on up the stack.
2784 **
2785 ** This command was inspired by Dave Thomas's talk on Ruby at the
2786 ** 2005 O'Reilly Open Source Convention (OSCON).
2787 */
2788 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00002789 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00002790 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00002791 if( objc!=3 && objc!=4 ){
2792 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2793 return TCL_ERROR;
2794 }
danielk1977cd38d522009-01-02 17:33:46 +00002795
dan4a4c11a2009-10-06 14:59:02 +00002796 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00002797 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002798 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002799 };
2800 enum TTYPE_enum {
2801 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2802 };
2803 int ttype;
drhb5555e72005-08-02 17:15:14 +00002804 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002805 0, &ttype) ){
2806 return TCL_ERROR;
2807 }
2808 switch( (enum TTYPE_enum)ttype ){
2809 case TTYPE_DEFERRED: /* no-op */; break;
2810 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2811 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2812 }
drh3d214232005-08-02 12:21:08 +00002813 }
danielk1977cd38d522009-01-02 17:33:46 +00002814 pScript = objv[objc-1];
2815
dan4a4c11a2009-10-06 14:59:02 +00002816 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00002817 pDb->disableAuth++;
2818 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2819 pDb->disableAuth--;
2820 if( rc!=SQLITE_OK ){
2821 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2822 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00002823 }
danielk1977cd38d522009-01-02 17:33:46 +00002824 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00002825
dan4a4c11a2009-10-06 14:59:02 +00002826 /* If using NRE, schedule a callback to invoke the script pScript, then
2827 ** a second callback to commit (or rollback) the transaction or savepoint
2828 ** opened above. If not using NRE, evaluate the script directly, then
2829 ** call function DbTransPostCmd() to commit (or rollback) the transaction
2830 ** or savepoint. */
2831 if( DbUseNre() ){
2832 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
2833 Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00002834 }else{
dan4a4c11a2009-10-06 14:59:02 +00002835 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00002836 }
2837 break;
2838 }
2839
danielk197794eb6a12005-12-15 15:22:08 +00002840 /*
danielk1977404ca072009-03-16 13:19:36 +00002841 ** $db unlock_notify ?script?
2842 */
2843 case DB_UNLOCK_NOTIFY: {
2844#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2845 Tcl_AppendResult(interp, "unlock_notify not available in this build", 0);
2846 rc = TCL_ERROR;
2847#else
2848 if( objc!=2 && objc!=3 ){
2849 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2850 rc = TCL_ERROR;
2851 }else{
2852 void (*xNotify)(void **, int) = 0;
2853 void *pNotifyArg = 0;
2854
2855 if( pDb->pUnlockNotify ){
2856 Tcl_DecrRefCount(pDb->pUnlockNotify);
2857 pDb->pUnlockNotify = 0;
2858 }
2859
2860 if( objc==3 ){
2861 xNotify = DbUnlockNotify;
2862 pNotifyArg = (void *)pDb;
2863 pDb->pUnlockNotify = objv[2];
2864 Tcl_IncrRefCount(pDb->pUnlockNotify);
2865 }
2866
2867 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
2868 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2869 rc = TCL_ERROR;
2870 }
2871 }
2872#endif
2873 break;
2874 }
2875
dan46c47d42011-03-01 18:42:07 +00002876 case DB_PREUPDATE: {
2877 static const char *azSub[] = {"count", "hook", "modified", "old", 0};
2878 enum DbPreupdateSubCmd {
2879 PRE_COUNT, PRE_HOOK, PRE_MODIFIED, PRE_OLD
2880 };
2881 int iSub;
2882
2883 if( objc<3 ){
2884 Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
2885 }
2886 if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
2887 return TCL_ERROR;
2888 }
2889
2890 switch( (enum DbPreupdateSubCmd)iSub ){
2891 case PRE_COUNT: {
2892 int nCol = sqlite3_preupdate_count(pDb->db);
2893 Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
2894 break;
2895 }
2896
2897 case PRE_HOOK: {
2898 if( objc>4 ){
2899 Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
2900 return TCL_ERROR;
2901 }
2902 DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
2903 break;
2904 }
2905
2906 case PRE_MODIFIED:
2907 case PRE_OLD: {
2908 int iIdx;
2909 if( objc!=4 ){
2910 Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
2911 return TCL_ERROR;
2912 }
2913 if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
2914 return TCL_ERROR;
2915 }
2916
2917 if( iSub==PRE_MODIFIED ){
2918 int iRes;
2919 rc = sqlite3_preupdate_modified(pDb->db, iIdx, &iRes);
2920 if( rc==SQLITE_OK ) Tcl_SetObjResult(interp, Tcl_NewIntObj(iRes));
2921 }else{
2922 sqlite3_value *pValue;
2923 assert( iSub==PRE_OLD );
2924 rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
2925 if( rc==SQLITE_OK ){
2926 Tcl_Obj *pObj = Tcl_NewStringObj(sqlite3_value_text(pValue), -1);
2927 Tcl_SetObjResult(interp, pObj);
2928 }
2929 }
2930
2931 if( rc!=SQLITE_OK ){
2932 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2933 return TCL_ERROR;
2934 }
2935 }
2936 }
2937
2938 break;
2939 }
2940
danielk1977404ca072009-03-16 13:19:36 +00002941 /*
drh833bf962010-04-28 14:42:19 +00002942 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002943 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002944 ** $db rollback_hook ?script?
dan21e8d012011-03-03 20:05:59 +00002945 ** $db transaction_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002946 */
drh833bf962010-04-28 14:42:19 +00002947 case DB_WAL_HOOK:
danielk197771fd80b2005-12-16 06:54:01 +00002948 case DB_UPDATE_HOOK:
dan21e8d012011-03-03 20:05:59 +00002949 case DB_ROLLBACK_HOOK:
2950 case DB_TRANSACTION_HOOK: {
dan46c47d42011-03-01 18:42:07 +00002951 sqlite3 *db = pDb->db;
danielk197771fd80b2005-12-16 06:54:01 +00002952
2953 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2954 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2955 */
2956 Tcl_Obj **ppHook;
dan46c47d42011-03-01 18:42:07 +00002957 if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
2958 if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
2959 if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
dan21e8d012011-03-03 20:05:59 +00002960 if( choice==DB_TRANSACTION_HOOK ) ppHook = &pDb->pTransHook;
dan46c47d42011-03-01 18:42:07 +00002961 if( objc>3 ){
danielk197794eb6a12005-12-15 15:22:08 +00002962 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2963 return TCL_ERROR;
2964 }
danielk197771fd80b2005-12-16 06:54:01 +00002965
dan46c47d42011-03-01 18:42:07 +00002966 DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002967 break;
2968 }
2969
danielk19774397de52005-01-12 12:44:03 +00002970 /* $db version
2971 **
2972 ** Return the version string for this database.
2973 */
2974 case DB_VERSION: {
2975 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2976 break;
2977 }
2978
tpoindex1067fe12004-12-17 15:41:11 +00002979
drh6d313162000-09-21 13:01:35 +00002980 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002981 return rc;
drh75897232000-05-29 14:26:00 +00002982}
2983
drha2c8a952009-10-13 18:38:34 +00002984#if SQLITE_TCL_NRE
2985/*
2986** Adaptor that provides an objCmd interface to the NRE-enabled
2987** interface implementation.
2988*/
2989static int DbObjCmdAdaptor(
2990 void *cd,
2991 Tcl_Interp *interp,
2992 int objc,
2993 Tcl_Obj *const*objv
2994){
2995 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
2996}
2997#endif /* SQLITE_TCL_NRE */
2998
drh75897232000-05-29 14:26:00 +00002999/*
drh3570ad92007-08-31 14:31:44 +00003000** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00003001** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00003002**
3003** This is the main Tcl command. When the "sqlite" Tcl command is
3004** invoked, this routine runs to process that command.
3005**
3006** The first argument, DBNAME, is an arbitrary name for a new
3007** database connection. This command creates a new command named
3008** DBNAME that is used to control that connection. The database
3009** connection is deleted when the DBNAME command is deleted.
3010**
drh3570ad92007-08-31 14:31:44 +00003011** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00003012**
drh75897232000-05-29 14:26:00 +00003013*/
drh22fbcb82004-02-01 01:22:50 +00003014static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00003015 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00003016 void *pKey = 0;
3017 int nKey = 0;
3018 const char *zArg;
drh75897232000-05-29 14:26:00 +00003019 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00003020 int i;
drh22fbcb82004-02-01 01:22:50 +00003021 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00003022 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00003023 int flags;
drh882e8e42006-08-24 02:42:27 +00003024 Tcl_DString translatedFilename;
drhd9da78a2009-03-24 15:08:09 +00003025
3026 /* In normal use, each TCL interpreter runs in a single thread. So
3027 ** by default, we can turn of mutexing on SQLite database connections.
3028 ** However, for testing purposes it is useful to have mutexes turned
3029 ** on. So, by default, mutexes default off. But if compiled with
3030 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3031 */
3032#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3033 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3034#else
3035 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3036#endif
3037
drh22fbcb82004-02-01 01:22:50 +00003038 if( objc==2 ){
3039 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00003040 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00003041 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00003042 return TCL_OK;
3043 }
drh9eb9e262004-02-11 02:18:05 +00003044 if( strcmp(zArg,"-has-codec")==0 ){
3045#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00003046 Tcl_AppendResult(interp,"1",0);
3047#else
3048 Tcl_AppendResult(interp,"0",0);
3049#endif
3050 return TCL_OK;
3051 }
drhfbc3eab2001-04-06 16:13:42 +00003052 }
drh3570ad92007-08-31 14:31:44 +00003053 for(i=3; i+1<objc; i+=2){
3054 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00003055 if( strcmp(zArg,"-key")==0 ){
drh3570ad92007-08-31 14:31:44 +00003056 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
3057 }else if( strcmp(zArg, "-vfs")==0 ){
dan3c3dd7b2010-06-22 11:10:40 +00003058 zVfs = Tcl_GetString(objv[i+1]);
drh3570ad92007-08-31 14:31:44 +00003059 }else if( strcmp(zArg, "-readonly")==0 ){
3060 int b;
3061 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3062 if( b ){
drh33f4e022007-09-03 15:19:34 +00003063 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00003064 flags |= SQLITE_OPEN_READONLY;
3065 }else{
3066 flags &= ~SQLITE_OPEN_READONLY;
3067 flags |= SQLITE_OPEN_READWRITE;
3068 }
3069 }else if( strcmp(zArg, "-create")==0 ){
3070 int b;
3071 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00003072 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00003073 flags |= SQLITE_OPEN_CREATE;
3074 }else{
3075 flags &= ~SQLITE_OPEN_CREATE;
3076 }
danielk19779a6284c2008-07-10 17:52:49 +00003077 }else if( strcmp(zArg, "-nomutex")==0 ){
3078 int b;
3079 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3080 if( b ){
3081 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00003082 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00003083 }else{
3084 flags &= ~SQLITE_OPEN_NOMUTEX;
3085 }
drh039963a2008-09-03 00:43:15 +00003086 }else if( strcmp(zArg, "-fullmutex")==0 ){
3087 int b;
3088 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3089 if( b ){
3090 flags |= SQLITE_OPEN_FULLMUTEX;
3091 flags &= ~SQLITE_OPEN_NOMUTEX;
3092 }else{
3093 flags &= ~SQLITE_OPEN_FULLMUTEX;
3094 }
drh3570ad92007-08-31 14:31:44 +00003095 }else{
3096 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3097 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00003098 }
3099 }
drh3570ad92007-08-31 14:31:44 +00003100 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00003101 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00003102 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh039963a2008-09-03 00:43:15 +00003103 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN?"
drh9eb9e262004-02-11 02:18:05 +00003104#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00003105 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00003106#endif
3107 );
drh75897232000-05-29 14:26:00 +00003108 return TCL_ERROR;
3109 }
drh75897232000-05-29 14:26:00 +00003110 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003111 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00003112 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00003113 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
3114 return TCL_ERROR;
3115 }
3116 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00003117 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00003118 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
drh3570ad92007-08-31 14:31:44 +00003119 sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00003120 Tcl_DStringFree(&translatedFilename);
danielk197780290862004-05-22 09:21:21 +00003121 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
drh9404d502006-12-19 18:46:08 +00003122 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
danielk197780290862004-05-22 09:21:21 +00003123 sqlite3_close(p->db);
3124 p->db = 0;
3125 }
drh2011d5f2004-07-22 02:40:37 +00003126#ifdef SQLITE_HAS_CODEC
drhf3a65f72007-08-22 20:18:21 +00003127 if( p->db ){
3128 sqlite3_key(p->db, pKey, nKey);
3129 }
drheb8ed702004-02-11 10:37:23 +00003130#endif
drhbec3f402000-08-04 13:49:02 +00003131 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003132 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003133 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003134 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003135 return TCL_ERROR;
3136 }
drhfb7e7652005-01-24 00:28:42 +00003137 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00003138 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003139 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003140 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003141 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3142 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003143 }else{
3144 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3145 }
drh75897232000-05-29 14:26:00 +00003146 return TCL_OK;
3147}
3148
3149/*
drh90ca9752001-09-28 17:47:14 +00003150** Provide a dummy Tcl_InitStubs if we are using this as a static
3151** library.
3152*/
3153#ifndef USE_TCL_STUBS
3154# undef Tcl_InitStubs
3155# define Tcl_InitStubs(a,b,c)
3156#endif
3157
3158/*
drh29bc4612005-10-05 10:40:15 +00003159** Make sure we have a PACKAGE_VERSION macro defined. This will be
3160** defined automatically by the TEA makefile. But other makefiles
3161** do not define it.
3162*/
3163#ifndef PACKAGE_VERSION
3164# define PACKAGE_VERSION SQLITE_VERSION
3165#endif
3166
3167/*
drh75897232000-05-29 14:26:00 +00003168** Initialize this module.
3169**
3170** This Tcl module contains only a single new Tcl command named "sqlite".
3171** (Hence there is no namespace. There is no point in using a namespace
3172** if the extension only supplies one new name!) The "sqlite" command is
3173** used to open a new SQLite database. See the DbMain() routine above
3174** for additional information.
drhb652f432010-08-26 16:46:57 +00003175**
3176** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003177*/
drhb652f432010-08-26 16:46:57 +00003178EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00003179 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00003180 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00003181 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh1cca0d22010-08-25 20:35:51 +00003182
3183#ifndef SQLITE_3_SUFFIX_ONLY
3184 /* The "sqlite" alias is undocumented. It is here only to support
3185 ** legacy scripts. All new scripts should use only the "sqlite3"
3186 ** command.
3187 */
drh49766d62005-01-08 18:42:28 +00003188 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003189#endif
drh1cca0d22010-08-25 20:35:51 +00003190
drh90ca9752001-09-28 17:47:14 +00003191 return TCL_OK;
3192}
drhb652f432010-08-26 16:46:57 +00003193EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3194EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3195EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3196EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3197EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3198EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3199EXTERN int Tclsqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
drhe2c3a652008-09-23 09:58:46 +00003200
drh49766d62005-01-08 18:42:28 +00003201
3202#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003203int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3204int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3205int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3206int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3207int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3208int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3209int Sqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3210int Tclsqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
drh49766d62005-01-08 18:42:28 +00003211#endif
drh75897232000-05-29 14:26:00 +00003212
drh3e27c022004-07-23 00:01:38 +00003213#ifdef TCLSH
3214/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003215** All of the code that follows is used to build standalone TCL interpreters
3216** that are statically linked with SQLite. Enable these by compiling
3217** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3218** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3219** analysis program.
drh75897232000-05-29 14:26:00 +00003220*/
drh348784e2000-05-29 20:41:49 +00003221
drh57a02272009-10-22 20:52:05 +00003222#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3223/*
3224 * This code implements the MD5 message-digest algorithm.
3225 * The algorithm is due to Ron Rivest. This code was
3226 * written by Colin Plumb in 1993, no copyright is claimed.
3227 * This code is in the public domain; do with it what you wish.
3228 *
3229 * Equivalent code is available from RSA Data Security, Inc.
3230 * This code has been tested against that, and is equivalent,
3231 * except that you don't need to include two pages of legalese
3232 * with every copy.
3233 *
3234 * To compute the message digest of a chunk of bytes, declare an
3235 * MD5Context structure, pass it to MD5Init, call MD5Update as
3236 * needed on buffers full of bytes, and then call MD5Final, which
3237 * will fill a supplied 16-byte array with the digest.
3238 */
3239
3240/*
3241 * If compiled on a machine that doesn't have a 32-bit integer,
3242 * you just set "uint32" to the appropriate datatype for an
3243 * unsigned 32-bit integer. For example:
3244 *
3245 * cc -Duint32='unsigned long' md5.c
3246 *
3247 */
3248#ifndef uint32
3249# define uint32 unsigned int
3250#endif
3251
3252struct MD5Context {
3253 int isInit;
3254 uint32 buf[4];
3255 uint32 bits[2];
3256 unsigned char in[64];
3257};
3258typedef struct MD5Context MD5Context;
3259
3260/*
3261 * Note: this code is harmless on little-endian machines.
3262 */
3263static void byteReverse (unsigned char *buf, unsigned longs){
3264 uint32 t;
3265 do {
3266 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3267 ((unsigned)buf[1]<<8 | buf[0]);
3268 *(uint32 *)buf = t;
3269 buf += 4;
3270 } while (--longs);
3271}
3272/* The four core functions - F1 is optimized somewhat */
3273
3274/* #define F1(x, y, z) (x & y | ~x & z) */
3275#define F1(x, y, z) (z ^ (x & (y ^ z)))
3276#define F2(x, y, z) F1(z, x, y)
3277#define F3(x, y, z) (x ^ y ^ z)
3278#define F4(x, y, z) (y ^ (x | ~z))
3279
3280/* This is the central step in the MD5 algorithm. */
3281#define MD5STEP(f, w, x, y, z, data, s) \
3282 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3283
3284/*
3285 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3286 * reflect the addition of 16 longwords of new data. MD5Update blocks
3287 * the data and converts bytes into longwords for this routine.
3288 */
3289static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3290 register uint32 a, b, c, d;
3291
3292 a = buf[0];
3293 b = buf[1];
3294 c = buf[2];
3295 d = buf[3];
3296
3297 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3298 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3299 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3300 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3301 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3302 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3303 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3304 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3305 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3306 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3307 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3308 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3309 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3310 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3311 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3312 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3313
3314 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3315 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3316 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3317 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3318 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3319 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3320 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3321 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3322 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3323 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3324 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3325 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3326 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3327 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3328 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3329 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3330
3331 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3332 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3333 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3334 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3335 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3336 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3337 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3338 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3339 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3340 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3341 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3342 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3343 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3344 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3345 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3346 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3347
3348 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3349 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3350 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3351 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3352 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3353 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3354 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3355 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3356 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3357 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3358 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3359 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3360 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3361 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3362 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3363 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3364
3365 buf[0] += a;
3366 buf[1] += b;
3367 buf[2] += c;
3368 buf[3] += d;
3369}
3370
3371/*
3372 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3373 * initialization constants.
3374 */
3375static void MD5Init(MD5Context *ctx){
3376 ctx->isInit = 1;
3377 ctx->buf[0] = 0x67452301;
3378 ctx->buf[1] = 0xefcdab89;
3379 ctx->buf[2] = 0x98badcfe;
3380 ctx->buf[3] = 0x10325476;
3381 ctx->bits[0] = 0;
3382 ctx->bits[1] = 0;
3383}
3384
3385/*
3386 * Update context to reflect the concatenation of another buffer full
3387 * of bytes.
3388 */
3389static
3390void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3391 uint32 t;
3392
3393 /* Update bitcount */
3394
3395 t = ctx->bits[0];
3396 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3397 ctx->bits[1]++; /* Carry from low to high */
3398 ctx->bits[1] += len >> 29;
3399
3400 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3401
3402 /* Handle any leading odd-sized chunks */
3403
3404 if ( t ) {
3405 unsigned char *p = (unsigned char *)ctx->in + t;
3406
3407 t = 64-t;
3408 if (len < t) {
3409 memcpy(p, buf, len);
3410 return;
3411 }
3412 memcpy(p, buf, t);
3413 byteReverse(ctx->in, 16);
3414 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3415 buf += t;
3416 len -= t;
3417 }
3418
3419 /* Process data in 64-byte chunks */
3420
3421 while (len >= 64) {
3422 memcpy(ctx->in, buf, 64);
3423 byteReverse(ctx->in, 16);
3424 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3425 buf += 64;
3426 len -= 64;
3427 }
3428
3429 /* Handle any remaining bytes of data. */
3430
3431 memcpy(ctx->in, buf, len);
3432}
3433
3434/*
3435 * Final wrapup - pad to 64-byte boundary with the bit pattern
3436 * 1 0* (64-bit count of bits processed, MSB-first)
3437 */
3438static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3439 unsigned count;
3440 unsigned char *p;
3441
3442 /* Compute number of bytes mod 64 */
3443 count = (ctx->bits[0] >> 3) & 0x3F;
3444
3445 /* Set the first char of padding to 0x80. This is safe since there is
3446 always at least one byte free */
3447 p = ctx->in + count;
3448 *p++ = 0x80;
3449
3450 /* Bytes of padding needed to make 64 bytes */
3451 count = 64 - 1 - count;
3452
3453 /* Pad out to 56 mod 64 */
3454 if (count < 8) {
3455 /* Two lots of padding: Pad the first block to 64 bytes */
3456 memset(p, 0, count);
3457 byteReverse(ctx->in, 16);
3458 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3459
3460 /* Now fill the next block with 56 bytes */
3461 memset(ctx->in, 0, 56);
3462 } else {
3463 /* Pad block to 56 bytes */
3464 memset(p, 0, count-8);
3465 }
3466 byteReverse(ctx->in, 14);
3467
3468 /* Append length in bits and transform */
3469 ((uint32 *)ctx->in)[ 14 ] = ctx->bits[0];
3470 ((uint32 *)ctx->in)[ 15 ] = ctx->bits[1];
3471
3472 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3473 byteReverse((unsigned char *)ctx->buf, 4);
3474 memcpy(digest, ctx->buf, 16);
3475 memset(ctx, 0, sizeof(ctx)); /* In case it is sensitive */
3476}
3477
3478/*
3479** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3480*/
3481static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3482 static char const zEncode[] = "0123456789abcdef";
3483 int i, j;
3484
3485 for(j=i=0; i<16; i++){
3486 int a = digest[i];
3487 zBuf[j++] = zEncode[(a>>4)&0xf];
3488 zBuf[j++] = zEncode[a & 0xf];
3489 }
3490 zBuf[j] = 0;
3491}
3492
3493
3494/*
3495** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3496** each representing 16 bits of the digest and separated from each
3497** other by a "-" character.
3498*/
3499static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3500 int i, j;
3501 unsigned int x;
3502 for(i=j=0; i<16; i+=2){
3503 x = digest[i]*256 + digest[i+1];
3504 if( i>0 ) zDigest[j++] = '-';
3505 sprintf(&zDigest[j], "%05u", x);
3506 j += 5;
3507 }
3508 zDigest[j] = 0;
3509}
3510
3511/*
3512** A TCL command for md5. The argument is the text to be hashed. The
3513** Result is the hash in base64.
3514*/
3515static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3516 MD5Context ctx;
3517 unsigned char digest[16];
3518 char zBuf[50];
3519 void (*converter)(unsigned char*, char*);
3520
3521 if( argc!=2 ){
3522 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3523 " TEXT\"", 0);
3524 return TCL_ERROR;
3525 }
3526 MD5Init(&ctx);
3527 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3528 MD5Final(digest, &ctx);
3529 converter = (void(*)(unsigned char*,char*))cd;
3530 converter(digest, zBuf);
3531 Tcl_AppendResult(interp, zBuf, (char*)0);
3532 return TCL_OK;
3533}
3534
3535/*
3536** A TCL command to take the md5 hash of a file. The argument is the
3537** name of the file.
3538*/
3539static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3540 FILE *in;
3541 MD5Context ctx;
3542 void (*converter)(unsigned char*, char*);
3543 unsigned char digest[16];
3544 char zBuf[10240];
3545
3546 if( argc!=2 ){
3547 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3548 " FILENAME\"", 0);
3549 return TCL_ERROR;
3550 }
3551 in = fopen(argv[1],"rb");
3552 if( in==0 ){
3553 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
3554 "\" for reading", 0);
3555 return TCL_ERROR;
3556 }
3557 MD5Init(&ctx);
3558 for(;;){
3559 int n;
3560 n = fread(zBuf, 1, sizeof(zBuf), in);
3561 if( n<=0 ) break;
3562 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3563 }
3564 fclose(in);
3565 MD5Final(digest, &ctx);
3566 converter = (void(*)(unsigned char*,char*))cd;
3567 converter(digest, zBuf);
3568 Tcl_AppendResult(interp, zBuf, (char*)0);
3569 return TCL_OK;
3570}
3571
3572/*
3573** Register the four new TCL commands for generating MD5 checksums
3574** with the TCL interpreter.
3575*/
3576int Md5_Init(Tcl_Interp *interp){
3577 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3578 MD5DigestToBase16, 0);
3579 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3580 MD5DigestToBase10x8, 0);
3581 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3582 MD5DigestToBase16, 0);
3583 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3584 MD5DigestToBase10x8, 0);
3585 return TCL_OK;
3586}
3587#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3588
3589#if defined(SQLITE_TEST)
3590/*
3591** During testing, the special md5sum() aggregate function is available.
3592** inside SQLite. The following routines implement that function.
3593*/
3594static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3595 MD5Context *p;
3596 int i;
3597 if( argc<1 ) return;
3598 p = sqlite3_aggregate_context(context, sizeof(*p));
3599 if( p==0 ) return;
3600 if( !p->isInit ){
3601 MD5Init(p);
3602 }
3603 for(i=0; i<argc; i++){
3604 const char *zData = (char*)sqlite3_value_text(argv[i]);
3605 if( zData ){
3606 MD5Update(p, (unsigned char*)zData, strlen(zData));
3607 }
3608 }
3609}
3610static void md5finalize(sqlite3_context *context){
3611 MD5Context *p;
3612 unsigned char digest[16];
3613 char zBuf[33];
3614 p = sqlite3_aggregate_context(context, sizeof(*p));
3615 MD5Final(digest,p);
3616 MD5DigestToBase16(digest, zBuf);
3617 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3618}
3619int Md5_Register(sqlite3 *db){
3620 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
3621 md5step, md5finalize);
3622 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3623 return rc;
3624}
3625#endif /* defined(SQLITE_TEST) */
3626
3627
drh348784e2000-05-29 20:41:49 +00003628/*
drh3e27c022004-07-23 00:01:38 +00003629** If the macro TCLSH is one, then put in code this for the
3630** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003631** standard input, or if a file is named on the command line
3632** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003633*/
drh3e27c022004-07-23 00:01:38 +00003634#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00003635static char zMainloop[] =
3636 "set line {}\n"
3637 "while {![eof stdin]} {\n"
3638 "if {$line!=\"\"} {\n"
3639 "puts -nonewline \"> \"\n"
3640 "} else {\n"
3641 "puts -nonewline \"% \"\n"
3642 "}\n"
3643 "flush stdout\n"
3644 "append line [gets stdin]\n"
3645 "if {[info complete $line]} {\n"
3646 "if {[catch {uplevel #0 $line} result]} {\n"
3647 "puts stderr \"Error: $result\"\n"
3648 "} elseif {$result!=\"\"} {\n"
3649 "puts $result\n"
3650 "}\n"
3651 "set line {}\n"
3652 "} else {\n"
3653 "append line \\n\n"
3654 "}\n"
3655 "}\n"
3656;
drh3e27c022004-07-23 00:01:38 +00003657#endif
drh3a0f13f2010-07-12 16:47:48 +00003658#if TCLSH==2
3659static char zMainloop[] =
3660#include "spaceanal_tcl.h"
3661;
3662#endif
drh3e27c022004-07-23 00:01:38 +00003663
danc1a60c52010-06-07 14:28:16 +00003664#ifdef SQLITE_TEST
3665static void init_all(Tcl_Interp *);
3666static int init_all_cmd(
3667 ClientData cd,
3668 Tcl_Interp *interp,
3669 int objc,
3670 Tcl_Obj *CONST objv[]
3671){
danielk19770a549072009-02-17 16:29:10 +00003672
danc1a60c52010-06-07 14:28:16 +00003673 Tcl_Interp *slave;
3674 if( objc!=2 ){
3675 Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3676 return TCL_ERROR;
3677 }
3678
3679 slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3680 if( !slave ){
3681 return TCL_ERROR;
3682 }
3683
3684 init_all(slave);
3685 return TCL_OK;
3686}
3687#endif
3688
3689/*
3690** Configure the interpreter passed as the first argument to have access
3691** to the commands and linked variables that make up:
3692**
3693** * the [sqlite3] extension itself,
3694**
3695** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
3696**
3697** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
3698** test suite.
3699*/
3700static void init_all(Tcl_Interp *interp){
drh38f82712004-06-18 17:10:16 +00003701 Sqlite3_Init(interp);
danc1a60c52010-06-07 14:28:16 +00003702
drh57a02272009-10-22 20:52:05 +00003703#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3704 Md5_Init(interp);
3705#endif
danc1a60c52010-06-07 14:28:16 +00003706
drhd9b02572001-04-15 00:37:09 +00003707#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00003708 {
drh2f999a62007-08-15 19:16:43 +00003709 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00003710 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00003711 extern int Sqlitetest2_Init(Tcl_Interp*);
3712 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00003713 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00003714 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00003715 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00003716 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00003717 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00003718 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00003719 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00003720 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
dan0a7a9152010-04-07 07:57:38 +00003721 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
drh984bfaa2008-03-19 16:08:53 +00003722 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00003723 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00003724 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003725 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00003726 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003727 extern int Sqlitetestschema_Init(Tcl_Interp*);
3728 extern int Sqlitetestsse_Init(Tcl_Interp*);
3729 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00003730 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00003731 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00003732 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00003733 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh522efc62009-11-10 17:24:37 +00003734 extern int Sqlitetestintarray_Init(Tcl_Interp*);
danc7991bd2010-05-05 19:04:59 +00003735 extern int Sqlitetestvfs_Init(Tcl_Interp *);
dan599e9d22010-07-12 08:39:37 +00003736 extern int SqlitetestStat_Init(Tcl_Interp*);
dan9508daa2010-08-28 18:58:00 +00003737 extern int Sqlitetestrtree_Init(Tcl_Interp*);
dan8cf35eb2010-09-01 11:40:05 +00003738 extern int Sqlitequota_Init(Tcl_Interp*);
shaneh8a922f72010-11-04 20:50:27 +00003739 extern int Sqlitemultiplex_Init(Tcl_Interp*);
dane336b002010-11-19 18:20:09 +00003740 extern int SqliteSuperlock_Init(Tcl_Interp*);
dan4fccf432011-03-08 19:22:50 +00003741#ifdef SQLITE_ENABLE_SESSION
3742 extern int TestSession_Init(Tcl_Interp*);
3743#endif
drh2e66f0b2005-04-28 17:18:48 +00003744
danb29010c2010-12-29 18:24:38 +00003745#ifdef SQLITE_ENABLE_ZIPVFS
3746 extern int Zipvfs_Init(Tcl_Interp*);
3747 Zipvfs_Init(interp);
3748#endif
3749
drh2f999a62007-08-15 19:16:43 +00003750 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00003751 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00003752 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00003753 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00003754 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00003755 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00003756 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00003757 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00003758 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00003759 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00003760 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00003761 Sqlitetest_autoext_Init(interp);
dan0a7a9152010-04-07 07:57:38 +00003762 Sqlitetest_demovfs_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00003763 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00003764 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00003765 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003766 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00003767 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003768 Sqlitetestschema_Init(interp);
3769 Sqlitetesttclvar_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00003770 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003771 SqlitetestOnefile_Init(interp);
danielk19775d1f5aa2008-04-10 14:51:00 +00003772 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00003773 Sqlitetestbackup_Init(interp);
drh522efc62009-11-10 17:24:37 +00003774 Sqlitetestintarray_Init(interp);
danc7991bd2010-05-05 19:04:59 +00003775 Sqlitetestvfs_Init(interp);
dan599e9d22010-07-12 08:39:37 +00003776 SqlitetestStat_Init(interp);
dan9508daa2010-08-28 18:58:00 +00003777 Sqlitetestrtree_Init(interp);
dan8cf35eb2010-09-01 11:40:05 +00003778 Sqlitequota_Init(interp);
shaneh8a922f72010-11-04 20:50:27 +00003779 Sqlitemultiplex_Init(interp);
dane336b002010-11-19 18:20:09 +00003780 SqliteSuperlock_Init(interp);
dan4fccf432011-03-08 19:22:50 +00003781#ifdef SQLITE_ENABLE_SESSION
3782 TestSession_Init(interp);
3783#endif
danielk1977a15db352007-09-14 16:20:00 +00003784
danc1a60c52010-06-07 14:28:16 +00003785 Tcl_CreateObjCommand(interp,"load_testfixture_extensions",init_all_cmd,0,0);
3786
drh89dec812005-04-28 19:03:37 +00003787#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00003788 Sqlitetestsse_Init(interp);
3789#endif
drhd1bf3512001-04-07 15:24:33 +00003790 }
3791#endif
danc1a60c52010-06-07 14:28:16 +00003792}
3793
3794#define TCLSH_MAIN main /* Needed to fake out mktclapp */
3795int TCLSH_MAIN(int argc, char **argv){
3796 Tcl_Interp *interp;
3797
3798 /* Call sqlite3_shutdown() once before doing anything else. This is to
3799 ** test that sqlite3_shutdown() can be safely called by a process before
3800 ** sqlite3_initialize() is. */
3801 sqlite3_shutdown();
3802
drh3a0f13f2010-07-12 16:47:48 +00003803#if TCLSH==2
3804 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
3805#endif
danc1a60c52010-06-07 14:28:16 +00003806 Tcl_FindExecutable(argv[0]);
3807
3808 interp = Tcl_CreateInterp();
3809 init_all(interp);
drhc7285972009-11-10 01:13:25 +00003810 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00003811 int i;
shessad42c3a2006-08-22 23:53:46 +00003812 char zArgc[32];
3813 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
3814 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00003815 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
3816 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00003817 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00003818 Tcl_SetVar(interp, "argv", argv[i],
3819 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3820 }
drh3a0f13f2010-07-12 16:47:48 +00003821 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00003822 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00003823 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00003824 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00003825 return 1;
3826 }
drh3e27c022004-07-23 00:01:38 +00003827 }
drh3a0f13f2010-07-12 16:47:48 +00003828 if( TCLSH==2 || argc<=1 ){
drh348784e2000-05-29 20:41:49 +00003829 Tcl_GlobalEval(interp, zMainloop);
3830 }
3831 return 0;
3832}
3833#endif /* TCLSH */