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