blob: de0e992bd46561cbdc79cee0893e675c67f9c52a [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
drh9b1c62d2011-03-30 21:04:43 +0000656#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +0000657/*
658** Pre-update hook callback.
659*/
660static void DbPreUpdateHandler(
661 void *p,
662 sqlite3 *db,
663 int op,
664 const char *zDb,
665 const char *zTbl,
666 sqlite_int64 iKey1,
667 sqlite_int64 iKey2
668){
669 SqliteDb *pDb = (SqliteDb *)p;
670 Tcl_Obj *pCmd;
671 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
672
673 assert( (SQLITE_DELETE-1)/9 == 0 );
674 assert( (SQLITE_INSERT-1)/9 == 1 );
675 assert( (SQLITE_UPDATE-1)/9 == 2 );
676 assert( pDb->pPreUpdateHook );
677 assert( db==pDb->db );
678 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
679
680 pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
681 Tcl_IncrRefCount(pCmd);
682 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
683 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
684 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
685 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
686 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
687 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
688 Tcl_DecrRefCount(pCmd);
689}
drh9b1c62d2011-03-30 21:04:43 +0000690#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +0000691
danielk197794eb6a12005-12-15 15:22:08 +0000692static void DbUpdateHandler(
693 void *p,
694 int op,
695 const char *zDb,
696 const char *zTbl,
697 sqlite_int64 rowid
698){
699 SqliteDb *pDb = (SqliteDb *)p;
700 Tcl_Obj *pCmd;
dan46c47d42011-03-01 18:42:07 +0000701 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
702
703 assert( (SQLITE_DELETE-1)/9 == 0 );
704 assert( (SQLITE_INSERT-1)/9 == 1 );
705 assert( (SQLITE_UPDATE-1)/9 == 2 );
danielk197794eb6a12005-12-15 15:22:08 +0000706
707 assert( pDb->pUpdateHook );
708 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
709
710 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
711 Tcl_IncrRefCount(pCmd);
dan46c47d42011-03-01 18:42:07 +0000712 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
danielk197794eb6a12005-12-15 15:22:08 +0000713 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
714 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
715 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
716 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
drhefdde162010-10-27 15:36:21 +0000717 Tcl_DecrRefCount(pCmd);
danielk197794eb6a12005-12-15 15:22:08 +0000718}
719
danielk19777cedc8d2004-06-10 10:50:08 +0000720static void tclCollateNeeded(
721 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000722 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000723 int enc,
724 const char *zName
725){
726 SqliteDb *pDb = (SqliteDb *)pCtx;
727 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
728 Tcl_IncrRefCount(pScript);
729 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
730 Tcl_EvalObjEx(pDb->interp, pScript, 0);
731 Tcl_DecrRefCount(pScript);
732}
733
drhaa940ea2004-01-15 02:44:03 +0000734/*
danielk19770202b292004-06-09 09:55:16 +0000735** This routine is called to evaluate an SQL collation function implemented
736** using TCL script.
737*/
738static int tclSqlCollate(
739 void *pCtx,
740 int nA,
741 const void *zA,
742 int nB,
743 const void *zB
744){
745 SqlCollate *p = (SqlCollate *)pCtx;
746 Tcl_Obj *pCmd;
747
748 pCmd = Tcl_NewStringObj(p->zScript, -1);
749 Tcl_IncrRefCount(pCmd);
750 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
751 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000752 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000753 Tcl_DecrRefCount(pCmd);
754 return (atoi(Tcl_GetStringResult(p->interp)));
755}
756
757/*
drhcabb0812002-09-14 13:47:32 +0000758** This routine is called to evaluate an SQL function implemented
759** using TCL script.
760*/
drhfb7e7652005-01-24 00:28:42 +0000761static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000762 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000763 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000764 int i;
765 int rc;
766
drhd1e47332005-06-26 17:55:33 +0000767 if( argc==0 ){
768 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
769 ** script object directly. This allows the TCL compiler to generate
770 ** bytecode for the command on the first invocation and thus make
771 ** subsequent invocations much faster. */
772 pCmd = p->pScript;
773 Tcl_IncrRefCount(pCmd);
774 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
775 Tcl_DecrRefCount(pCmd);
776 }else{
777 /* If there are arguments to the function, make a shallow copy of the
778 ** script object, lappend the arguments, then evaluate the copy.
779 **
780 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
781 ** The new Tcl_Obj contains pointers to the original list elements.
782 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
783 ** of the list to tclCmdNameType, that alternate representation will
784 ** be preserved and reused on the next invocation.
785 */
786 Tcl_Obj **aArg;
787 int nArg;
788 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
789 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
790 return;
791 }
792 pCmd = Tcl_NewListObj(nArg, aArg);
793 Tcl_IncrRefCount(pCmd);
794 for(i=0; i<argc; i++){
795 sqlite3_value *pIn = argv[i];
796 Tcl_Obj *pVal;
797
798 /* Set pVal to contain the i'th column of this row. */
799 switch( sqlite3_value_type(pIn) ){
800 case SQLITE_BLOB: {
801 int bytes = sqlite3_value_bytes(pIn);
802 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
803 break;
804 }
805 case SQLITE_INTEGER: {
806 sqlite_int64 v = sqlite3_value_int64(pIn);
807 if( v>=-2147483647 && v<=2147483647 ){
808 pVal = Tcl_NewIntObj(v);
809 }else{
810 pVal = Tcl_NewWideIntObj(v);
811 }
812 break;
813 }
814 case SQLITE_FLOAT: {
815 double r = sqlite3_value_double(pIn);
816 pVal = Tcl_NewDoubleObj(r);
817 break;
818 }
819 case SQLITE_NULL: {
820 pVal = Tcl_NewStringObj("", 0);
821 break;
822 }
823 default: {
824 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000825 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000826 break;
827 }
828 }
829 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
830 if( rc ){
831 Tcl_DecrRefCount(pCmd);
832 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
833 return;
834 }
danielk197751ad0ec2004-05-24 12:39:02 +0000835 }
drhd1e47332005-06-26 17:55:33 +0000836 if( !p->useEvalObjv ){
837 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
838 ** is a list without a string representation. To prevent this from
839 ** happening, make sure pCmd has a valid string representation */
840 Tcl_GetString(pCmd);
841 }
842 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
843 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000844 }
danielk1977562e8d32005-05-20 09:40:55 +0000845
drhc7f269d2005-05-05 10:30:29 +0000846 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000847 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000848 }else{
drhc7f269d2005-05-05 10:30:29 +0000849 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
850 int n;
851 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000852 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000853 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000854 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000855 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000856 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000857 data = Tcl_GetByteArrayFromObj(pVar, &n);
858 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000859 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000860 Tcl_GetIntFromObj(0, pVar, &n);
861 sqlite3_result_int(context, n);
862 }else if( c=='d' && strcmp(zType,"double")==0 ){
863 double r;
864 Tcl_GetDoubleFromObj(0, pVar, &r);
865 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +0000866 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
867 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000868 Tcl_WideInt v;
869 Tcl_GetWideIntFromObj(0, pVar, &v);
870 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000871 }else{
danielk197700fd9572005-12-07 06:27:43 +0000872 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
873 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000874 }
drhcabb0812002-09-14 13:47:32 +0000875 }
876}
drh895d7472004-08-20 16:02:39 +0000877
drhe22a3342003-04-22 20:30:37 +0000878#ifndef SQLITE_OMIT_AUTHORIZATION
879/*
880** This is the authentication function. It appends the authentication
881** type code and the two arguments to zCmd[] then invokes the result
882** on the interpreter. The reply is examined to determine if the
883** authentication fails or succeeds.
884*/
885static int auth_callback(
886 void *pArg,
887 int code,
888 const char *zArg1,
889 const char *zArg2,
890 const char *zArg3,
891 const char *zArg4
892){
893 char *zCode;
894 Tcl_DString str;
895 int rc;
896 const char *zReply;
897 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +0000898 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +0000899
900 switch( code ){
901 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
902 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
903 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
904 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
905 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
906 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
907 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
908 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
909 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
910 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
911 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
912 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
913 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
914 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
915 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
916 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
917 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
918 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
919 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
920 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
921 case SQLITE_READ : zCode="SQLITE_READ"; break;
922 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
923 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
924 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000925 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
926 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000927 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000928 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000929 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000930 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
931 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000932 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +0000933 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drhe22a3342003-04-22 20:30:37 +0000934 default : zCode="????"; break;
935 }
936 Tcl_DStringInit(&str);
937 Tcl_DStringAppend(&str, pDb->zAuth, -1);
938 Tcl_DStringAppendElement(&str, zCode);
939 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
940 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
941 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
942 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
943 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
944 Tcl_DStringFree(&str);
945 zReply = Tcl_GetStringResult(pDb->interp);
946 if( strcmp(zReply,"SQLITE_OK")==0 ){
947 rc = SQLITE_OK;
948 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
949 rc = SQLITE_DENY;
950 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
951 rc = SQLITE_IGNORE;
952 }else{
953 rc = 999;
954 }
955 return rc;
956}
957#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000958
959/*
danielk1977ef2cb632004-05-29 02:37:19 +0000960** zText is a pointer to text obtained via an sqlite3_result_text()
961** or similar interface. This routine returns a Tcl string object,
962** reference count set to 0, containing the text. If a translation
963** between iso8859 and UTF-8 is required, it is preformed.
964*/
965static Tcl_Obj *dbTextToObj(char const *zText){
966 Tcl_Obj *pVal;
967#ifdef UTF_TRANSLATION_NEEDED
968 Tcl_DString dCol;
969 Tcl_DStringInit(&dCol);
970 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
971 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
972 Tcl_DStringFree(&dCol);
973#else
974 pVal = Tcl_NewStringObj(zText, -1);
975#endif
976 return pVal;
977}
978
979/*
tpoindex1067fe12004-12-17 15:41:11 +0000980** This routine reads a line of text from FILE in, stores
981** the text in memory obtained from malloc() and returns a pointer
982** to the text. NULL is returned at end of file, or if malloc()
983** fails.
984**
985** The interface is like "readline" but no command-line editing
986** is done.
987**
988** copied from shell.c from '.import' command
989*/
990static char *local_getline(char *zPrompt, FILE *in){
991 char *zLine;
992 int nLine;
993 int n;
994 int eol;
995
996 nLine = 100;
997 zLine = malloc( nLine );
998 if( zLine==0 ) return 0;
999 n = 0;
1000 eol = 0;
1001 while( !eol ){
1002 if( n+100>nLine ){
1003 nLine = nLine*2 + 100;
1004 zLine = realloc(zLine, nLine);
1005 if( zLine==0 ) return 0;
1006 }
1007 if( fgets(&zLine[n], nLine - n, in)==0 ){
1008 if( n==0 ){
1009 free(zLine);
1010 return 0;
1011 }
1012 zLine[n] = 0;
1013 eol = 1;
1014 break;
1015 }
1016 while( zLine[n] ){ n++; }
1017 if( n>0 && zLine[n-1]=='\n' ){
1018 n--;
1019 zLine[n] = 0;
1020 eol = 1;
1021 }
1022 }
1023 zLine = realloc( zLine, n+1 );
1024 return zLine;
1025}
1026
danielk19778e556522007-11-13 10:30:24 +00001027
1028/*
dan4a4c11a2009-10-06 14:59:02 +00001029** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +00001030**
dan4a4c11a2009-10-06 14:59:02 +00001031** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +00001032**
dan4a4c11a2009-10-06 14:59:02 +00001033** It is invoked after evaluating the script SCRIPT to commit or rollback
1034** the transaction or savepoint opened by the [transaction] command.
1035*/
1036static int DbTransPostCmd(
1037 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1038 Tcl_Interp *interp, /* Tcl interpreter */
1039 int result /* Result of evaluating SCRIPT */
1040){
1041 static const char *azEnd[] = {
1042 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1043 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1044 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1045 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1046 };
1047 SqliteDb *pDb = (SqliteDb*)data[0];
1048 int rc = result;
1049 const char *zEnd;
1050
1051 pDb->nTransaction--;
1052 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1053
1054 pDb->disableAuth++;
1055 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1056 /* This is a tricky scenario to handle. The most likely cause of an
1057 ** error is that the exec() above was an attempt to commit the
1058 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1059 ** that an IO-error has occured. In either case, throw a Tcl exception
1060 ** and try to rollback the transaction.
1061 **
1062 ** But it could also be that the user executed one or more BEGIN,
1063 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1064 ** this method's logic. Not clear how this would be best handled.
1065 */
1066 if( rc!=TCL_ERROR ){
1067 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
1068 rc = TCL_ERROR;
1069 }
1070 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1071 }
1072 pDb->disableAuth--;
1073
1074 return rc;
1075}
1076
1077/*
1078** Search the cache for a prepared-statement object that implements the
1079** first SQL statement in the buffer pointed to by parameter zIn. If
1080** no such prepared-statement can be found, allocate and prepare a new
1081** one. In either case, bind the current values of the relevant Tcl
1082** variables to any $var, :var or @var variables in the statement. Before
1083** returning, set *ppPreStmt to point to the prepared-statement object.
1084**
1085** Output parameter *pzOut is set to point to the next SQL statement in
1086** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1087** next statement.
1088**
1089** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1090** and an error message loaded into interpreter pDb->interp.
1091*/
1092static int dbPrepareAndBind(
1093 SqliteDb *pDb, /* Database object */
1094 char const *zIn, /* SQL to compile */
1095 char const **pzOut, /* OUT: Pointer to next SQL statement */
1096 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1097){
1098 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
1099 sqlite3_stmt *pStmt; /* Prepared statement object */
1100 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1101 int nSql; /* Length of zSql in bytes */
1102 int nVar; /* Number of variables in statement */
1103 int iParm = 0; /* Next free entry in apParm */
1104 int i;
1105 Tcl_Interp *interp = pDb->interp;
1106
1107 *ppPreStmt = 0;
1108
1109 /* Trim spaces from the start of zSql and calculate the remaining length. */
1110 while( isspace(zSql[0]) ){ zSql++; }
1111 nSql = strlen30(zSql);
1112
1113 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1114 int n = pPreStmt->nSql;
1115 if( nSql>=n
1116 && memcmp(pPreStmt->zSql, zSql, n)==0
1117 && (zSql[n]==0 || zSql[n-1]==';')
1118 ){
1119 pStmt = pPreStmt->pStmt;
1120 *pzOut = &zSql[pPreStmt->nSql];
1121
1122 /* When a prepared statement is found, unlink it from the
1123 ** cache list. It will later be added back to the beginning
1124 ** of the cache list in order to implement LRU replacement.
1125 */
1126 if( pPreStmt->pPrev ){
1127 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1128 }else{
1129 pDb->stmtList = pPreStmt->pNext;
1130 }
1131 if( pPreStmt->pNext ){
1132 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1133 }else{
1134 pDb->stmtLast = pPreStmt->pPrev;
1135 }
1136 pDb->nStmt--;
1137 nVar = sqlite3_bind_parameter_count(pStmt);
1138 break;
1139 }
1140 }
1141
1142 /* If no prepared statement was found. Compile the SQL text. Also allocate
1143 ** a new SqlPreparedStmt structure. */
1144 if( pPreStmt==0 ){
1145 int nByte;
1146
1147 if( SQLITE_OK!=sqlite3_prepare_v2(pDb->db, zSql, -1, &pStmt, pzOut) ){
1148 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1149 return TCL_ERROR;
1150 }
1151 if( pStmt==0 ){
1152 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1153 /* A compile-time error in the statement. */
1154 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1155 return TCL_ERROR;
1156 }else{
1157 /* The statement was a no-op. Continue to the next statement
1158 ** in the SQL string.
1159 */
1160 return TCL_OK;
1161 }
1162 }
1163
1164 assert( pPreStmt==0 );
1165 nVar = sqlite3_bind_parameter_count(pStmt);
1166 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1167 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1168 memset(pPreStmt, 0, nByte);
1169
1170 pPreStmt->pStmt = pStmt;
1171 pPreStmt->nSql = (*pzOut - zSql);
1172 pPreStmt->zSql = sqlite3_sql(pStmt);
1173 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
1174 }
1175 assert( pPreStmt );
1176 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1177 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1178
1179 /* Bind values to parameters that begin with $ or : */
1180 for(i=1; i<=nVar; i++){
1181 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1182 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1183 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1184 if( pVar ){
1185 int n;
1186 u8 *data;
1187 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1188 char c = zType[0];
1189 if( zVar[0]=='@' ||
1190 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1191 /* Load a BLOB type if the Tcl variable is a bytearray and
1192 ** it has no string representation or the host
1193 ** parameter name begins with "@". */
1194 data = Tcl_GetByteArrayFromObj(pVar, &n);
1195 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1196 Tcl_IncrRefCount(pVar);
1197 pPreStmt->apParm[iParm++] = pVar;
1198 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1199 Tcl_GetIntFromObj(interp, pVar, &n);
1200 sqlite3_bind_int(pStmt, i, n);
1201 }else if( c=='d' && strcmp(zType,"double")==0 ){
1202 double r;
1203 Tcl_GetDoubleFromObj(interp, pVar, &r);
1204 sqlite3_bind_double(pStmt, i, r);
1205 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1206 (c=='i' && strcmp(zType,"int")==0) ){
1207 Tcl_WideInt v;
1208 Tcl_GetWideIntFromObj(interp, pVar, &v);
1209 sqlite3_bind_int64(pStmt, i, v);
1210 }else{
1211 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1212 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1213 Tcl_IncrRefCount(pVar);
1214 pPreStmt->apParm[iParm++] = pVar;
1215 }
1216 }else{
1217 sqlite3_bind_null(pStmt, i);
1218 }
1219 }
1220 }
1221 pPreStmt->nParm = iParm;
1222 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001223
dan4a4c11a2009-10-06 14:59:02 +00001224 return TCL_OK;
1225}
1226
1227
1228/*
1229** Release a statement reference obtained by calling dbPrepareAndBind().
1230** There should be exactly one call to this function for each call to
1231** dbPrepareAndBind().
1232**
1233** If the discard parameter is non-zero, then the statement is deleted
1234** immediately. Otherwise it is added to the LRU list and may be returned
1235** by a subsequent call to dbPrepareAndBind().
1236*/
1237static void dbReleaseStmt(
1238 SqliteDb *pDb, /* Database handle */
1239 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1240 int discard /* True to delete (not cache) the pPreStmt */
1241){
1242 int i;
1243
1244 /* Free the bound string and blob parameters */
1245 for(i=0; i<pPreStmt->nParm; i++){
1246 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1247 }
1248 pPreStmt->nParm = 0;
1249
1250 if( pDb->maxStmt<=0 || discard ){
1251 /* If the cache is turned off, deallocated the statement */
1252 sqlite3_finalize(pPreStmt->pStmt);
1253 Tcl_Free((char *)pPreStmt);
1254 }else{
1255 /* Add the prepared statement to the beginning of the cache list. */
1256 pPreStmt->pNext = pDb->stmtList;
1257 pPreStmt->pPrev = 0;
1258 if( pDb->stmtList ){
1259 pDb->stmtList->pPrev = pPreStmt;
1260 }
1261 pDb->stmtList = pPreStmt;
1262 if( pDb->stmtLast==0 ){
1263 assert( pDb->nStmt==0 );
1264 pDb->stmtLast = pPreStmt;
1265 }else{
1266 assert( pDb->nStmt>0 );
1267 }
1268 pDb->nStmt++;
1269
1270 /* If we have too many statement in cache, remove the surplus from
1271 ** the end of the cache list. */
1272 while( pDb->nStmt>pDb->maxStmt ){
1273 sqlite3_finalize(pDb->stmtLast->pStmt);
1274 pDb->stmtLast = pDb->stmtLast->pPrev;
1275 Tcl_Free((char*)pDb->stmtLast->pNext);
1276 pDb->stmtLast->pNext = 0;
1277 pDb->nStmt--;
1278 }
1279 }
1280}
1281
1282/*
1283** Structure used with dbEvalXXX() functions:
1284**
1285** dbEvalInit()
1286** dbEvalStep()
1287** dbEvalFinalize()
1288** dbEvalRowInfo()
1289** dbEvalColumnValue()
1290*/
1291typedef struct DbEvalContext DbEvalContext;
1292struct DbEvalContext {
1293 SqliteDb *pDb; /* Database handle */
1294 Tcl_Obj *pSql; /* Object holding string zSql */
1295 const char *zSql; /* Remaining SQL to execute */
1296 SqlPreparedStmt *pPreStmt; /* Current statement */
1297 int nCol; /* Number of columns returned by pStmt */
1298 Tcl_Obj *pArray; /* Name of array variable */
1299 Tcl_Obj **apColName; /* Array of column names */
1300};
1301
1302/*
1303** Release any cache of column names currently held as part of
1304** the DbEvalContext structure passed as the first argument.
1305*/
1306static void dbReleaseColumnNames(DbEvalContext *p){
1307 if( p->apColName ){
1308 int i;
1309 for(i=0; i<p->nCol; i++){
1310 Tcl_DecrRefCount(p->apColName[i]);
1311 }
1312 Tcl_Free((char *)p->apColName);
1313 p->apColName = 0;
1314 }
1315 p->nCol = 0;
1316}
1317
1318/*
1319** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001320**
1321** If pArray is not NULL, then it contains the name of a Tcl array
1322** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001323** the names of the columns returned by the statement as part of each
1324** call to dbEvalStep(), in order from left to right. e.g. if the names
1325** of the returned columns are a, b and c, it does the equivalent of the
1326** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001327**
1328** set ${pArray}(*) {a b c}
1329*/
dan4a4c11a2009-10-06 14:59:02 +00001330static void dbEvalInit(
1331 DbEvalContext *p, /* Pointer to structure to initialize */
1332 SqliteDb *pDb, /* Database handle */
1333 Tcl_Obj *pSql, /* Object containing SQL script */
1334 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001335){
dan4a4c11a2009-10-06 14:59:02 +00001336 memset(p, 0, sizeof(DbEvalContext));
1337 p->pDb = pDb;
1338 p->zSql = Tcl_GetString(pSql);
1339 p->pSql = pSql;
1340 Tcl_IncrRefCount(pSql);
1341 if( pArray ){
1342 p->pArray = pArray;
1343 Tcl_IncrRefCount(pArray);
1344 }
1345}
danielk19778e556522007-11-13 10:30:24 +00001346
dan4a4c11a2009-10-06 14:59:02 +00001347/*
1348** Obtain information about the row that the DbEvalContext passed as the
1349** first argument currently points to.
1350*/
1351static void dbEvalRowInfo(
1352 DbEvalContext *p, /* Evaluation context */
1353 int *pnCol, /* OUT: Number of column names */
1354 Tcl_Obj ***papColName /* OUT: Array of column names */
1355){
danielk19778e556522007-11-13 10:30:24 +00001356 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001357 if( 0==p->apColName ){
1358 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1359 int i; /* Iterator variable */
1360 int nCol; /* Number of columns returned by pStmt */
1361 Tcl_Obj **apColName = 0; /* Array of column names */
1362
1363 p->nCol = nCol = sqlite3_column_count(pStmt);
1364 if( nCol>0 && (papColName || p->pArray) ){
1365 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1366 for(i=0; i<nCol; i++){
1367 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1368 Tcl_IncrRefCount(apColName[i]);
1369 }
1370 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001371 }
1372
1373 /* If results are being stored in an array variable, then create
1374 ** the array(*) entry for that array
1375 */
dan4a4c11a2009-10-06 14:59:02 +00001376 if( p->pArray ){
1377 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001378 Tcl_Obj *pColList = Tcl_NewObj();
1379 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001380
danielk19778e556522007-11-13 10:30:24 +00001381 for(i=0; i<nCol; i++){
1382 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1383 }
1384 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001385 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001386 Tcl_DecrRefCount(pStar);
1387 }
danielk19778e556522007-11-13 10:30:24 +00001388 }
1389
dan4a4c11a2009-10-06 14:59:02 +00001390 if( papColName ){
1391 *papColName = p->apColName;
1392 }
1393 if( pnCol ){
1394 *pnCol = p->nCol;
1395 }
1396}
1397
1398/*
1399** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1400** returned, then an error message is stored in the interpreter before
1401** returning.
1402**
1403** A return value of TCL_OK means there is a row of data available. The
1404** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1405** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1406** is returned, then the SQL script has finished executing and there are
1407** no further rows available. This is similar to SQLITE_DONE.
1408*/
1409static int dbEvalStep(DbEvalContext *p){
1410 while( p->zSql[0] || p->pPreStmt ){
1411 int rc;
1412 if( p->pPreStmt==0 ){
1413 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1414 if( rc!=TCL_OK ) return rc;
1415 }else{
1416 int rcs;
1417 SqliteDb *pDb = p->pDb;
1418 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1419 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1420
1421 rcs = sqlite3_step(pStmt);
1422 if( rcs==SQLITE_ROW ){
1423 return TCL_OK;
1424 }
1425 if( p->pArray ){
1426 dbEvalRowInfo(p, 0, 0);
1427 }
1428 rcs = sqlite3_reset(pStmt);
1429
1430 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1431 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001432 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
dan4a4c11a2009-10-06 14:59:02 +00001433 dbReleaseColumnNames(p);
1434 p->pPreStmt = 0;
1435
1436 if( rcs!=SQLITE_OK ){
1437 /* If a run-time error occurs, report the error and stop reading
1438 ** the SQL. */
1439 Tcl_SetObjResult(pDb->interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1440 dbReleaseStmt(pDb, pPreStmt, 1);
1441 return TCL_ERROR;
1442 }else{
1443 dbReleaseStmt(pDb, pPreStmt, 0);
1444 }
1445 }
1446 }
1447
1448 /* Finished */
1449 return TCL_BREAK;
1450}
1451
1452/*
1453** Free all resources currently held by the DbEvalContext structure passed
1454** as the first argument. There should be exactly one call to this function
1455** for each call to dbEvalInit().
1456*/
1457static void dbEvalFinalize(DbEvalContext *p){
1458 if( p->pPreStmt ){
1459 sqlite3_reset(p->pPreStmt->pStmt);
1460 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1461 p->pPreStmt = 0;
1462 }
1463 if( p->pArray ){
1464 Tcl_DecrRefCount(p->pArray);
1465 p->pArray = 0;
1466 }
1467 Tcl_DecrRefCount(p->pSql);
1468 dbReleaseColumnNames(p);
1469}
1470
1471/*
1472** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1473** the value for the iCol'th column of the row currently pointed to by
1474** the DbEvalContext structure passed as the first argument.
1475*/
1476static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1477 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1478 switch( sqlite3_column_type(pStmt, iCol) ){
1479 case SQLITE_BLOB: {
1480 int bytes = sqlite3_column_bytes(pStmt, iCol);
1481 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1482 if( !zBlob ) bytes = 0;
1483 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1484 }
1485 case SQLITE_INTEGER: {
1486 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1487 if( v>=-2147483647 && v<=2147483647 ){
1488 return Tcl_NewIntObj(v);
1489 }else{
1490 return Tcl_NewWideIntObj(v);
1491 }
1492 }
1493 case SQLITE_FLOAT: {
1494 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1495 }
1496 case SQLITE_NULL: {
1497 return dbTextToObj(p->pDb->zNull);
1498 }
1499 }
1500
1501 return dbTextToObj((char *)sqlite3_column_text(pStmt, iCol));
1502}
1503
1504/*
1505** If using Tcl version 8.6 or greater, use the NR functions to avoid
1506** recursive evalution of scripts by the [db eval] and [db trans]
1507** commands. Even if the headers used while compiling the extension
1508** are 8.6 or newer, the code still tests the Tcl version at runtime.
1509** This allows stubs-enabled builds to be used with older Tcl libraries.
1510*/
1511#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001512# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001513static int DbUseNre(void){
1514 int major, minor;
1515 Tcl_GetVersion(&major, &minor, 0, 0);
1516 return( (major==8 && minor>=6) || major>8 );
1517}
1518#else
1519/*
1520** Compiling using headers earlier than 8.6. In this case NR cannot be
1521** used, so DbUseNre() to always return zero. Add #defines for the other
1522** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1523** even though the only invocations of them are within conditional blocks
1524** of the form:
1525**
1526** if( DbUseNre() ) { ... }
1527*/
drha2c8a952009-10-13 18:38:34 +00001528# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001529# define DbUseNre() 0
1530# define Tcl_NRAddCallback(a,b,c,d,e,f) 0
1531# define Tcl_NREvalObj(a,b,c) 0
1532# define Tcl_NRCreateCommand(a,b,c,d,e,f) 0
1533#endif
1534
1535/*
1536** This function is part of the implementation of the command:
1537**
1538** $db eval SQL ?ARRAYNAME? SCRIPT
1539*/
1540static int DbEvalNextCmd(
1541 ClientData data[], /* data[0] is the (DbEvalContext*) */
1542 Tcl_Interp *interp, /* Tcl interpreter */
1543 int result /* Result so far */
1544){
1545 int rc = result; /* Return code */
1546
1547 /* The first element of the data[] array is a pointer to a DbEvalContext
1548 ** structure allocated using Tcl_Alloc(). The second element of data[]
1549 ** is a pointer to a Tcl_Obj containing the script to run for each row
1550 ** returned by the queries encapsulated in data[0]. */
1551 DbEvalContext *p = (DbEvalContext *)data[0];
1552 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1553 Tcl_Obj *pArray = p->pArray;
1554
1555 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1556 int i;
1557 int nCol;
1558 Tcl_Obj **apColName;
1559 dbEvalRowInfo(p, &nCol, &apColName);
1560 for(i=0; i<nCol; i++){
1561 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1562 if( pArray==0 ){
1563 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1564 }else{
1565 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1566 }
1567 }
1568
1569 /* The required interpreter variables are now populated with the data
1570 ** from the current row. If using NRE, schedule callbacks to evaluate
1571 ** script pScript, then to invoke this function again to fetch the next
1572 ** row (or clean up if there is no next row or the script throws an
1573 ** exception). After scheduling the callbacks, return control to the
1574 ** caller.
1575 **
1576 ** If not using NRE, evaluate pScript directly and continue with the
1577 ** next iteration of this while(...) loop. */
1578 if( DbUseNre() ){
1579 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1580 return Tcl_NREvalObj(interp, pScript, 0);
1581 }else{
1582 rc = Tcl_EvalObjEx(interp, pScript, 0);
1583 }
1584 }
1585
1586 Tcl_DecrRefCount(pScript);
1587 dbEvalFinalize(p);
1588 Tcl_Free((char *)p);
1589
1590 if( rc==TCL_OK || rc==TCL_BREAK ){
1591 Tcl_ResetResult(interp);
1592 rc = TCL_OK;
1593 }
1594 return rc;
danielk19778e556522007-11-13 10:30:24 +00001595}
1596
tpoindex1067fe12004-12-17 15:41:11 +00001597/*
dan46c47d42011-03-01 18:42:07 +00001598** This function is used by the implementations of the following database
1599** handle sub-commands:
1600**
1601** $db update_hook ?SCRIPT?
1602** $db wal_hook ?SCRIPT?
1603** $db commit_hook ?SCRIPT?
1604** $db preupdate hook ?SCRIPT?
1605*/
1606static void DbHookCmd(
1607 Tcl_Interp *interp, /* Tcl interpreter */
1608 SqliteDb *pDb, /* Database handle */
1609 Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */
1610 Tcl_Obj **ppHook /* Pointer to member of SqliteDb */
1611){
1612 sqlite3 *db = pDb->db;
1613
1614 if( *ppHook ){
1615 Tcl_SetObjResult(interp, *ppHook);
1616 if( pArg ){
1617 Tcl_DecrRefCount(*ppHook);
1618 *ppHook = 0;
1619 }
1620 }
1621 if( pArg ){
1622 assert( !(*ppHook) );
1623 if( Tcl_GetCharLength(pArg)>0 ){
1624 *ppHook = pArg;
1625 Tcl_IncrRefCount(*ppHook);
1626 }
1627 }
1628
drh9b1c62d2011-03-30 21:04:43 +00001629#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +00001630 sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
drh9b1c62d2011-03-30 21:04:43 +00001631#endif
dan46c47d42011-03-01 18:42:07 +00001632 sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1633 sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1634 sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
1635}
1636
1637/*
drh75897232000-05-29 14:26:00 +00001638** The "sqlite" command below creates a new Tcl command for each
1639** connection it opens to an SQLite database. This routine is invoked
1640** whenever one of those connection-specific commands is executed
1641** in Tcl. For example, if you run Tcl code like this:
1642**
drh9bb575f2004-09-06 17:24:11 +00001643** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001644** db1 close
1645**
1646** The first command opens a connection to the "my_database" database
1647** and calls that connection "db1". The second command causes this
1648** subroutine to be invoked.
1649*/
drh6d313162000-09-21 13:01:35 +00001650static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001651 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001652 int choice;
drh22fbcb82004-02-01 01:22:50 +00001653 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001654 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001655 "authorizer", "backup", "busy",
1656 "cache", "changes", "close",
1657 "collate", "collation_needed", "commit_hook",
1658 "complete", "copy", "enable_load_extension",
1659 "errorcode", "eval", "exists",
1660 "function", "incrblob", "interrupt",
drh833bf962010-04-28 14:42:19 +00001661 "last_insert_rowid", "nullvalue", "onecolumn",
drh304637c2011-03-18 16:47:27 +00001662 "preupdate", "profile", "progress",
1663 "rekey", "restore", "rollback_hook",
1664 "status", "timeout", "total_changes",
1665 "trace", "transaction", "unlock_notify",
1666 "update_hook", "version", "wal_hook",
1667 0
drh6d313162000-09-21 13:01:35 +00001668 };
drh411995d2002-06-25 19:31:18 +00001669 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001670 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1671 DB_CACHE, DB_CHANGES, DB_CLOSE,
1672 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1673 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1674 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1675 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
drh833bf962010-04-28 14:42:19 +00001676 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
drh304637c2011-03-18 16:47:27 +00001677 DB_PREUPDATE, DB_PROFILE, DB_PROGRESS,
1678 DB_REKEY, DB_RESTORE, DB_ROLLBACK_HOOK,
1679 DB_STATUS, DB_TIMEOUT, DB_TOTAL_CHANGES,
1680 DB_TRACE, DB_TRANSACTION, DB_UNLOCK_NOTIFY,
1681 DB_UPDATE_HOOK, DB_VERSION, DB_WAL_HOOK,
drh6d313162000-09-21 13:01:35 +00001682 };
tpoindex1067fe12004-12-17 15:41:11 +00001683 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001684
1685 if( objc<2 ){
1686 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001687 return TCL_ERROR;
1688 }
drh411995d2002-06-25 19:31:18 +00001689 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001690 return TCL_ERROR;
1691 }
1692
drh411995d2002-06-25 19:31:18 +00001693 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001694
drhe22a3342003-04-22 20:30:37 +00001695 /* $db authorizer ?CALLBACK?
1696 **
1697 ** Invoke the given callback to authorize each SQL operation as it is
1698 ** compiled. 5 arguments are appended to the callback before it is
1699 ** invoked:
1700 **
1701 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1702 ** (2) First descriptive name (depends on authorization type)
1703 ** (3) Second descriptive name
1704 ** (4) Name of the database (ex: "main", "temp")
1705 ** (5) Name of trigger that is doing the access
1706 **
1707 ** The callback should return on of the following strings: SQLITE_OK,
1708 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1709 **
1710 ** If this method is invoked with no arguments, the current authorization
1711 ** callback string is returned.
1712 */
1713 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001714#ifdef SQLITE_OMIT_AUTHORIZATION
1715 Tcl_AppendResult(interp, "authorization not available in this build", 0);
1716 return TCL_ERROR;
1717#else
drhe22a3342003-04-22 20:30:37 +00001718 if( objc>3 ){
1719 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001720 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001721 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001722 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +00001723 Tcl_AppendResult(interp, pDb->zAuth, 0);
1724 }
1725 }else{
1726 char *zAuth;
1727 int len;
1728 if( pDb->zAuth ){
1729 Tcl_Free(pDb->zAuth);
1730 }
1731 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1732 if( zAuth && len>0 ){
1733 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001734 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001735 }else{
1736 pDb->zAuth = 0;
1737 }
drhe22a3342003-04-22 20:30:37 +00001738 if( pDb->zAuth ){
1739 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001740 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +00001741 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001742 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001743 }
drhe22a3342003-04-22 20:30:37 +00001744 }
drh1211de32004-07-26 12:24:22 +00001745#endif
drhe22a3342003-04-22 20:30:37 +00001746 break;
1747 }
1748
drhdc2c4912009-02-04 22:46:47 +00001749 /* $db backup ?DATABASE? FILENAME
1750 **
1751 ** Open or create a database file named FILENAME. Transfer the
1752 ** content of local database DATABASE (default: "main") into the
1753 ** FILENAME database.
1754 */
1755 case DB_BACKUP: {
1756 const char *zDestFile;
1757 const char *zSrcDb;
1758 sqlite3 *pDest;
1759 sqlite3_backup *pBackup;
1760
1761 if( objc==3 ){
1762 zSrcDb = "main";
1763 zDestFile = Tcl_GetString(objv[2]);
1764 }else if( objc==4 ){
1765 zSrcDb = Tcl_GetString(objv[2]);
1766 zDestFile = Tcl_GetString(objv[3]);
1767 }else{
1768 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1769 return TCL_ERROR;
1770 }
1771 rc = sqlite3_open(zDestFile, &pDest);
1772 if( rc!=SQLITE_OK ){
1773 Tcl_AppendResult(interp, "cannot open target database: ",
1774 sqlite3_errmsg(pDest), (char*)0);
1775 sqlite3_close(pDest);
1776 return TCL_ERROR;
1777 }
1778 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1779 if( pBackup==0 ){
1780 Tcl_AppendResult(interp, "backup failed: ",
1781 sqlite3_errmsg(pDest), (char*)0);
1782 sqlite3_close(pDest);
1783 return TCL_ERROR;
1784 }
1785 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1786 sqlite3_backup_finish(pBackup);
1787 if( rc==SQLITE_DONE ){
1788 rc = TCL_OK;
1789 }else{
1790 Tcl_AppendResult(interp, "backup failed: ",
1791 sqlite3_errmsg(pDest), (char*)0);
1792 rc = TCL_ERROR;
1793 }
1794 sqlite3_close(pDest);
1795 break;
1796 }
1797
drhbec3f402000-08-04 13:49:02 +00001798 /* $db busy ?CALLBACK?
1799 **
1800 ** Invoke the given callback if an SQL statement attempts to open
1801 ** a locked database file.
1802 */
drh6d313162000-09-21 13:01:35 +00001803 case DB_BUSY: {
1804 if( objc>3 ){
1805 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001806 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001807 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001808 if( pDb->zBusy ){
1809 Tcl_AppendResult(interp, pDb->zBusy, 0);
1810 }
1811 }else{
drh6d313162000-09-21 13:01:35 +00001812 char *zBusy;
1813 int len;
drhbec3f402000-08-04 13:49:02 +00001814 if( pDb->zBusy ){
1815 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001816 }
drh6d313162000-09-21 13:01:35 +00001817 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1818 if( zBusy && len>0 ){
1819 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001820 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001821 }else{
1822 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001823 }
1824 if( pDb->zBusy ){
1825 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001826 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001827 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001828 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001829 }
1830 }
drh6d313162000-09-21 13:01:35 +00001831 break;
1832 }
drhbec3f402000-08-04 13:49:02 +00001833
drhfb7e7652005-01-24 00:28:42 +00001834 /* $db cache flush
1835 ** $db cache size n
1836 **
1837 ** Flush the prepared statement cache, or set the maximum number of
1838 ** cached statements.
1839 */
1840 case DB_CACHE: {
1841 char *subCmd;
1842 int n;
1843
1844 if( objc<=2 ){
1845 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1846 return TCL_ERROR;
1847 }
1848 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1849 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1850 if( objc!=3 ){
1851 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1852 return TCL_ERROR;
1853 }else{
1854 flushStmtCache( pDb );
1855 }
1856 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1857 if( objc!=4 ){
1858 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1859 return TCL_ERROR;
1860 }else{
1861 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1862 Tcl_AppendResult( interp, "cannot convert \"",
1863 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1864 return TCL_ERROR;
1865 }else{
1866 if( n<0 ){
1867 flushStmtCache( pDb );
1868 n = 0;
1869 }else if( n>MAX_PREPARED_STMTS ){
1870 n = MAX_PREPARED_STMTS;
1871 }
1872 pDb->maxStmt = n;
1873 }
1874 }
1875 }else{
1876 Tcl_AppendResult( interp, "bad option \"",
danielk1977191fadc2007-10-23 08:17:48 +00001877 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
drhfb7e7652005-01-24 00:28:42 +00001878 return TCL_ERROR;
1879 }
1880 break;
1881 }
1882
danielk1977b28af712004-06-21 06:50:26 +00001883 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001884 **
1885 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001886 ** the most recent INSERT, UPDATE or DELETE statement, not including
1887 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001888 */
1889 case DB_CHANGES: {
1890 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001891 if( objc!=2 ){
1892 Tcl_WrongNumArgs(interp, 2, objv, "");
1893 return TCL_ERROR;
1894 }
drhc8d30ac2002-04-12 10:08:59 +00001895 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001896 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001897 break;
1898 }
1899
drh75897232000-05-29 14:26:00 +00001900 /* $db close
1901 **
1902 ** Shutdown the database
1903 */
drh6d313162000-09-21 13:01:35 +00001904 case DB_CLOSE: {
1905 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1906 break;
1907 }
drh75897232000-05-29 14:26:00 +00001908
drh0f14e2e2004-06-29 12:39:08 +00001909 /*
1910 ** $db collate NAME SCRIPT
1911 **
1912 ** Create a new SQL collation function called NAME. Whenever
1913 ** that function is called, invoke SCRIPT to evaluate the function.
1914 */
1915 case DB_COLLATE: {
1916 SqlCollate *pCollate;
1917 char *zName;
1918 char *zScript;
1919 int nScript;
1920 if( objc!=4 ){
1921 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1922 return TCL_ERROR;
1923 }
1924 zName = Tcl_GetStringFromObj(objv[2], 0);
1925 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1926 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1927 if( pCollate==0 ) return TCL_ERROR;
1928 pCollate->interp = interp;
1929 pCollate->pNext = pDb->pCollate;
1930 pCollate->zScript = (char*)&pCollate[1];
1931 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001932 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001933 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1934 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001935 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001936 return TCL_ERROR;
1937 }
1938 break;
1939 }
1940
1941 /*
1942 ** $db collation_needed SCRIPT
1943 **
1944 ** Create a new SQL collation function called NAME. Whenever
1945 ** that function is called, invoke SCRIPT to evaluate the function.
1946 */
1947 case DB_COLLATION_NEEDED: {
1948 if( objc!=3 ){
1949 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1950 return TCL_ERROR;
1951 }
1952 if( pDb->pCollateNeeded ){
1953 Tcl_DecrRefCount(pDb->pCollateNeeded);
1954 }
1955 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1956 Tcl_IncrRefCount(pDb->pCollateNeeded);
1957 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1958 break;
1959 }
1960
drh19e2d372005-08-29 23:00:03 +00001961 /* $db commit_hook ?CALLBACK?
1962 **
1963 ** Invoke the given callback just before committing every SQL transaction.
1964 ** If the callback throws an exception or returns non-zero, then the
1965 ** transaction is aborted. If CALLBACK is an empty string, the callback
1966 ** is disabled.
1967 */
1968 case DB_COMMIT_HOOK: {
1969 if( objc>3 ){
1970 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1971 return TCL_ERROR;
1972 }else if( objc==2 ){
1973 if( pDb->zCommit ){
1974 Tcl_AppendResult(interp, pDb->zCommit, 0);
1975 }
1976 }else{
1977 char *zCommit;
1978 int len;
1979 if( pDb->zCommit ){
1980 Tcl_Free(pDb->zCommit);
1981 }
1982 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1983 if( zCommit && len>0 ){
1984 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001985 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001986 }else{
1987 pDb->zCommit = 0;
1988 }
1989 if( pDb->zCommit ){
1990 pDb->interp = interp;
1991 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1992 }else{
1993 sqlite3_commit_hook(pDb->db, 0, 0);
1994 }
1995 }
1996 break;
1997 }
1998
drh75897232000-05-29 14:26:00 +00001999 /* $db complete SQL
2000 **
2001 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2002 ** additional lines of input are needed. This is similar to the
2003 ** built-in "info complete" command of Tcl.
2004 */
drh6d313162000-09-21 13:01:35 +00002005 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00002006#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00002007 Tcl_Obj *pResult;
2008 int isComplete;
2009 if( objc!=3 ){
2010 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00002011 return TCL_ERROR;
2012 }
danielk19776f8a5032004-05-10 10:34:51 +00002013 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00002014 pResult = Tcl_GetObjResult(interp);
2015 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00002016#endif
drh6d313162000-09-21 13:01:35 +00002017 break;
2018 }
drhdcd997e2003-01-31 17:21:49 +00002019
drh19e2d372005-08-29 23:00:03 +00002020 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2021 **
2022 ** Copy data into table from filename, optionally using SEPARATOR
2023 ** as column separators. If a column contains a null string, or the
2024 ** value of NULLINDICATOR, a NULL is inserted for the column.
2025 ** conflict-algorithm is one of the sqlite conflict algorithms:
2026 ** rollback, abort, fail, ignore, replace
2027 ** On success, return the number of lines processed, not necessarily same
2028 ** as 'db changes' due to conflict-algorithm selected.
2029 **
2030 ** This code is basically an implementation/enhancement of
2031 ** the sqlite3 shell.c ".import" command.
2032 **
2033 ** This command usage is equivalent to the sqlite2.x COPY statement,
2034 ** which imports file data into a table using the PostgreSQL COPY file format:
2035 ** $db copy $conflit_algo $table_name $filename \t \\N
2036 */
2037 case DB_COPY: {
2038 char *zTable; /* Insert data into this table */
2039 char *zFile; /* The file from which to extract data */
2040 char *zConflict; /* The conflict algorithm to use */
2041 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00002042 int nCol; /* Number of columns in the table */
2043 int nByte; /* Number of bytes in an SQL string */
2044 int i, j; /* Loop counters */
2045 int nSep; /* Number of bytes in zSep[] */
2046 int nNull; /* Number of bytes in zNull[] */
2047 char *zSql; /* An SQL statement */
2048 char *zLine; /* A single line of input from the file */
2049 char **azCol; /* zLine[] broken up into columns */
2050 char *zCommit; /* How to commit changes */
2051 FILE *in; /* The input file */
2052 int lineno = 0; /* Line number of input file */
2053 char zLineNum[80]; /* Line number print buffer */
2054 Tcl_Obj *pResult; /* interp result */
2055
2056 char *zSep;
2057 char *zNull;
2058 if( objc<5 || objc>7 ){
2059 Tcl_WrongNumArgs(interp, 2, objv,
2060 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2061 return TCL_ERROR;
2062 }
2063 if( objc>=6 ){
2064 zSep = Tcl_GetStringFromObj(objv[5], 0);
2065 }else{
2066 zSep = "\t";
2067 }
2068 if( objc>=7 ){
2069 zNull = Tcl_GetStringFromObj(objv[6], 0);
2070 }else{
2071 zNull = "";
2072 }
2073 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2074 zTable = Tcl_GetStringFromObj(objv[3], 0);
2075 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002076 nSep = strlen30(zSep);
2077 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002078 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00002079 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00002080 return TCL_ERROR;
2081 }
drh3e59c012008-09-23 10:12:13 +00002082 if(strcmp(zConflict, "rollback") != 0 &&
2083 strcmp(zConflict, "abort" ) != 0 &&
2084 strcmp(zConflict, "fail" ) != 0 &&
2085 strcmp(zConflict, "ignore" ) != 0 &&
2086 strcmp(zConflict, "replace" ) != 0 ) {
drh19e2d372005-08-29 23:00:03 +00002087 Tcl_AppendResult(interp, "Error: \"", zConflict,
2088 "\", conflict-algorithm must be one of: rollback, "
2089 "abort, fail, ignore, or replace", 0);
2090 return TCL_ERROR;
2091 }
2092 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2093 if( zSql==0 ){
2094 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
2095 return TCL_ERROR;
2096 }
drh4f21c4a2008-12-10 22:15:00 +00002097 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002098 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002099 sqlite3_free(zSql);
2100 if( rc ){
2101 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2102 nCol = 0;
2103 }else{
2104 nCol = sqlite3_column_count(pStmt);
2105 }
2106 sqlite3_finalize(pStmt);
2107 if( nCol==0 ) {
2108 return TCL_ERROR;
2109 }
2110 zSql = malloc( nByte + 50 + nCol*2 );
2111 if( zSql==0 ) {
2112 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
2113 return TCL_ERROR;
2114 }
2115 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2116 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002117 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002118 for(i=1; i<nCol; i++){
2119 zSql[j++] = ',';
2120 zSql[j++] = '?';
2121 }
2122 zSql[j++] = ')';
2123 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002124 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002125 free(zSql);
2126 if( rc ){
2127 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2128 sqlite3_finalize(pStmt);
2129 return TCL_ERROR;
2130 }
2131 in = fopen(zFile, "rb");
2132 if( in==0 ){
2133 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2134 sqlite3_finalize(pStmt);
2135 return TCL_ERROR;
2136 }
2137 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2138 if( azCol==0 ) {
2139 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00002140 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002141 return TCL_ERROR;
2142 }
drh37527852006-03-16 16:19:56 +00002143 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002144 zCommit = "COMMIT";
2145 while( (zLine = local_getline(0, in))!=0 ){
2146 char *z;
2147 i = 0;
2148 lineno++;
2149 azCol[0] = zLine;
2150 for(i=0, z=zLine; *z; z++){
2151 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2152 *z = 0;
2153 i++;
2154 if( i<nCol ){
2155 azCol[i] = &z[nSep];
2156 z += nSep-1;
2157 }
2158 }
2159 }
2160 if( i+1!=nCol ){
2161 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002162 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002163 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002164 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002165 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002166 "Error: %s line %d: expected %d columns of data but found %d",
2167 zFile, lineno, nCol, i+1);
2168 Tcl_AppendResult(interp, zErr, 0);
2169 free(zErr);
2170 }
drh19e2d372005-08-29 23:00:03 +00002171 zCommit = "ROLLBACK";
2172 break;
2173 }
2174 for(i=0; i<nCol; i++){
2175 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002176 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
drh4f21c4a2008-12-10 22:15:00 +00002177 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002178 ){
drh19e2d372005-08-29 23:00:03 +00002179 sqlite3_bind_null(pStmt, i+1);
2180 }else{
2181 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2182 }
2183 }
2184 sqlite3_step(pStmt);
2185 rc = sqlite3_reset(pStmt);
2186 free(zLine);
2187 if( rc!=SQLITE_OK ){
2188 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
2189 zCommit = "ROLLBACK";
2190 break;
2191 }
2192 }
2193 free(azCol);
2194 fclose(in);
2195 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002196 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002197
2198 if( zCommit[0] == 'C' ){
2199 /* success, set result as number of lines processed */
2200 pResult = Tcl_GetObjResult(interp);
2201 Tcl_SetIntObj(pResult, lineno);
2202 rc = TCL_OK;
2203 }else{
2204 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002205 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00002206 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
2207 rc = TCL_ERROR;
2208 }
2209 break;
2210 }
2211
drhdcd997e2003-01-31 17:21:49 +00002212 /*
drh41449052006-07-06 17:08:48 +00002213 ** $db enable_load_extension BOOLEAN
2214 **
2215 ** Turn the extension loading feature on or off. It if off by
2216 ** default.
2217 */
2218 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002219#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002220 int onoff;
2221 if( objc!=3 ){
2222 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2223 return TCL_ERROR;
2224 }
2225 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2226 return TCL_ERROR;
2227 }
2228 sqlite3_enable_load_extension(pDb->db, onoff);
2229 break;
drhf533acc2006-12-19 18:57:11 +00002230#else
2231 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2232 0);
2233 return TCL_ERROR;
2234#endif
drh41449052006-07-06 17:08:48 +00002235 }
2236
2237 /*
drhdcd997e2003-01-31 17:21:49 +00002238 ** $db errorcode
2239 **
2240 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002241 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002242 */
2243 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002244 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002245 break;
2246 }
dan4a4c11a2009-10-06 14:59:02 +00002247
2248 /*
2249 ** $db exists $sql
2250 ** $db onecolumn $sql
2251 **
2252 ** The onecolumn method is the equivalent of:
2253 ** lindex [$db eval $sql] 0
2254 */
2255 case DB_EXISTS:
2256 case DB_ONECOLUMN: {
2257 DbEvalContext sEval;
2258 if( objc!=3 ){
2259 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2260 return TCL_ERROR;
2261 }
2262
2263 dbEvalInit(&sEval, pDb, objv[2], 0);
2264 rc = dbEvalStep(&sEval);
2265 if( choice==DB_ONECOLUMN ){
2266 if( rc==TCL_OK ){
2267 Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
2268 }
2269 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2270 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
2271 }
2272 dbEvalFinalize(&sEval);
2273
2274 if( rc==TCL_BREAK ){
2275 rc = TCL_OK;
2276 }
2277 break;
2278 }
drh75897232000-05-29 14:26:00 +00002279
2280 /*
drh895d7472004-08-20 16:02:39 +00002281 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002282 **
2283 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002284 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002285 ** If "array" and "code" are omitted, then no callback is every invoked.
2286 ** If "array" is an empty string, then the values are placed in variables
2287 ** that have the same name as the fields extracted by the query.
2288 */
dan4a4c11a2009-10-06 14:59:02 +00002289 case DB_EVAL: {
2290 if( objc<3 || objc>5 ){
2291 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2292 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002293 }
dan4a4c11a2009-10-06 14:59:02 +00002294
drh92febd92004-08-20 18:34:20 +00002295 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002296 DbEvalContext sEval;
2297 Tcl_Obj *pRet = Tcl_NewObj();
2298 Tcl_IncrRefCount(pRet);
2299 dbEvalInit(&sEval, pDb, objv[2], 0);
2300 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2301 int i;
2302 int nCol;
2303 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002304 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002305 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002306 }
2307 }
dan4a4c11a2009-10-06 14:59:02 +00002308 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002309 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002310 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002311 rc = TCL_OK;
2312 }
drh1807ce32004-09-07 13:20:35 +00002313 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002314 }else{
2315 ClientData cd[2];
2316 DbEvalContext *p;
2317 Tcl_Obj *pArray = 0;
2318 Tcl_Obj *pScript;
2319
2320 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2321 pArray = objv[3];
2322 }
2323 pScript = objv[objc-1];
2324 Tcl_IncrRefCount(pScript);
2325
2326 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2327 dbEvalInit(p, pDb, objv[2], pArray);
2328
2329 cd[0] = (void *)p;
2330 cd[1] = (void *)pScript;
2331 rc = DbEvalNextCmd(cd, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002332 }
danielk197730ccda12004-05-27 12:11:31 +00002333 break;
2334 }
drhbec3f402000-08-04 13:49:02 +00002335
2336 /*
drhe3602be2008-09-09 12:31:33 +00002337 ** $db function NAME [-argcount N] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002338 **
2339 ** Create a new SQL function called NAME. Whenever that function is
2340 ** called, invoke SCRIPT to evaluate the function.
2341 */
2342 case DB_FUNCTION: {
2343 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002344 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002345 char *zName;
drhe3602be2008-09-09 12:31:33 +00002346 int nArg = -1;
2347 if( objc==6 ){
2348 const char *z = Tcl_GetString(objv[3]);
drh4f21c4a2008-12-10 22:15:00 +00002349 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002350 if( n>2 && strncmp(z, "-argcount",n)==0 ){
2351 if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
2352 if( nArg<0 ){
2353 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2354 (char*)0);
2355 return TCL_ERROR;
2356 }
2357 }
2358 pScript = objv[5];
2359 }else if( objc!=4 ){
2360 Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
drhcabb0812002-09-14 13:47:32 +00002361 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002362 }else{
2363 pScript = objv[3];
drhcabb0812002-09-14 13:47:32 +00002364 }
2365 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002366 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002367 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002368 if( pFunc->pScript ){
2369 Tcl_DecrRefCount(pFunc->pScript);
2370 }
2371 pFunc->pScript = pScript;
2372 Tcl_IncrRefCount(pScript);
2373 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
drhe3602be2008-09-09 12:31:33 +00002374 rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00002375 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002376 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002377 rc = TCL_ERROR;
2378 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002379 }
drhcabb0812002-09-14 13:47:32 +00002380 break;
2381 }
2382
2383 /*
danielk19778cbadb02007-05-03 16:31:26 +00002384 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002385 */
2386 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002387#ifdef SQLITE_OMIT_INCRBLOB
2388 Tcl_AppendResult(interp, "incrblob not available in this build", 0);
2389 return TCL_ERROR;
2390#else
danielk19778cbadb02007-05-03 16:31:26 +00002391 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002392 const char *zDb = "main";
2393 const char *zTable;
2394 const char *zColumn;
2395 sqlite_int64 iRow;
2396
danielk19778cbadb02007-05-03 16:31:26 +00002397 /* Check for the -readonly option */
2398 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2399 isReadonly = 1;
2400 }
2401
2402 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2403 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002404 return TCL_ERROR;
2405 }
2406
danielk19778cbadb02007-05-03 16:31:26 +00002407 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002408 zDb = Tcl_GetString(objv[2]);
2409 }
2410 zTable = Tcl_GetString(objv[objc-3]);
2411 zColumn = Tcl_GetString(objv[objc-2]);
2412 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2413
2414 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002415 rc = createIncrblobChannel(
2416 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
2417 );
danielk1977b4e9af92007-05-01 17:49:49 +00002418 }
danielk197732a0d8b2007-05-04 19:03:02 +00002419#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002420 break;
2421 }
2422
2423 /*
drhf11bded2006-07-17 00:02:44 +00002424 ** $db interrupt
2425 **
2426 ** Interrupt the execution of the inner-most SQL interpreter. This
2427 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2428 */
2429 case DB_INTERRUPT: {
2430 sqlite3_interrupt(pDb->db);
2431 break;
2432 }
2433
2434 /*
drh19e2d372005-08-29 23:00:03 +00002435 ** $db nullvalue ?STRING?
2436 **
2437 ** Change text used when a NULL comes back from the database. If ?STRING?
2438 ** is not present, then the current string used for NULL is returned.
2439 ** If STRING is present, then STRING is returned.
2440 **
2441 */
2442 case DB_NULLVALUE: {
2443 if( objc!=2 && objc!=3 ){
2444 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2445 return TCL_ERROR;
2446 }
2447 if( objc==3 ){
2448 int len;
2449 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2450 if( pDb->zNull ){
2451 Tcl_Free(pDb->zNull);
2452 }
2453 if( zNull && len>0 ){
2454 pDb->zNull = Tcl_Alloc( len + 1 );
2455 strncpy(pDb->zNull, zNull, len);
2456 pDb->zNull[len] = '\0';
2457 }else{
2458 pDb->zNull = 0;
2459 }
2460 }
2461 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
2462 break;
2463 }
2464
2465 /*
drhaf9ff332002-01-16 21:00:27 +00002466 ** $db last_insert_rowid
2467 **
2468 ** Return an integer which is the ROWID for the most recent insert.
2469 */
2470 case DB_LAST_INSERT_ROWID: {
2471 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002472 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002473 if( objc!=2 ){
2474 Tcl_WrongNumArgs(interp, 2, objv, "");
2475 return TCL_ERROR;
2476 }
danielk19776f8a5032004-05-10 10:34:51 +00002477 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002478 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002479 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002480 break;
2481 }
2482
2483 /*
dan4a4c11a2009-10-06 14:59:02 +00002484 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002485 */
drh1807ce32004-09-07 13:20:35 +00002486
2487 /* $db progress ?N CALLBACK?
2488 **
2489 ** Invoke the given callback every N virtual machine opcodes while executing
2490 ** queries.
2491 */
2492 case DB_PROGRESS: {
2493 if( objc==2 ){
2494 if( pDb->zProgress ){
2495 Tcl_AppendResult(interp, pDb->zProgress, 0);
2496 }
2497 }else if( objc==4 ){
2498 char *zProgress;
2499 int len;
2500 int N;
2501 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002502 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002503 };
2504 if( pDb->zProgress ){
2505 Tcl_Free(pDb->zProgress);
2506 }
2507 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2508 if( zProgress && len>0 ){
2509 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002510 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002511 }else{
2512 pDb->zProgress = 0;
2513 }
2514#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2515 if( pDb->zProgress ){
2516 pDb->interp = interp;
2517 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2518 }else{
2519 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2520 }
2521#endif
2522 }else{
2523 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002524 return TCL_ERROR;
2525 }
drh5d9d7572003-08-19 14:31:01 +00002526 break;
2527 }
2528
drh19e2d372005-08-29 23:00:03 +00002529 /* $db profile ?CALLBACK?
2530 **
2531 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2532 ** that has run. The text of the SQL and the amount of elapse time are
2533 ** appended to CALLBACK before the script is run.
2534 */
2535 case DB_PROFILE: {
2536 if( objc>3 ){
2537 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2538 return TCL_ERROR;
2539 }else if( objc==2 ){
2540 if( pDb->zProfile ){
2541 Tcl_AppendResult(interp, pDb->zProfile, 0);
2542 }
2543 }else{
2544 char *zProfile;
2545 int len;
2546 if( pDb->zProfile ){
2547 Tcl_Free(pDb->zProfile);
2548 }
2549 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2550 if( zProfile && len>0 ){
2551 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002552 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002553 }else{
2554 pDb->zProfile = 0;
2555 }
shanehbb201342011-02-09 19:55:20 +00002556#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh19e2d372005-08-29 23:00:03 +00002557 if( pDb->zProfile ){
2558 pDb->interp = interp;
2559 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2560 }else{
2561 sqlite3_profile(pDb->db, 0, 0);
2562 }
2563#endif
2564 }
2565 break;
2566 }
2567
drh5d9d7572003-08-19 14:31:01 +00002568 /*
drh22fbcb82004-02-01 01:22:50 +00002569 ** $db rekey KEY
2570 **
2571 ** Change the encryption key on the currently open database.
2572 */
2573 case DB_REKEY: {
2574 int nKey;
2575 void *pKey;
2576 if( objc!=3 ){
2577 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2578 return TCL_ERROR;
2579 }
2580 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00002581#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00002582 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002583 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00002584 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002585 rc = TCL_ERROR;
2586 }
2587#endif
2588 break;
2589 }
2590
drhdc2c4912009-02-04 22:46:47 +00002591 /* $db restore ?DATABASE? FILENAME
2592 **
2593 ** Open a database file named FILENAME. Transfer the content
2594 ** of FILENAME into the local database DATABASE (default: "main").
2595 */
2596 case DB_RESTORE: {
2597 const char *zSrcFile;
2598 const char *zDestDb;
2599 sqlite3 *pSrc;
2600 sqlite3_backup *pBackup;
2601 int nTimeout = 0;
2602
2603 if( objc==3 ){
2604 zDestDb = "main";
2605 zSrcFile = Tcl_GetString(objv[2]);
2606 }else if( objc==4 ){
2607 zDestDb = Tcl_GetString(objv[2]);
2608 zSrcFile = Tcl_GetString(objv[3]);
2609 }else{
2610 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2611 return TCL_ERROR;
2612 }
2613 rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
2614 if( rc!=SQLITE_OK ){
2615 Tcl_AppendResult(interp, "cannot open source database: ",
2616 sqlite3_errmsg(pSrc), (char*)0);
2617 sqlite3_close(pSrc);
2618 return TCL_ERROR;
2619 }
2620 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2621 if( pBackup==0 ){
2622 Tcl_AppendResult(interp, "restore failed: ",
2623 sqlite3_errmsg(pDb->db), (char*)0);
2624 sqlite3_close(pSrc);
2625 return TCL_ERROR;
2626 }
2627 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2628 || rc==SQLITE_BUSY ){
2629 if( rc==SQLITE_BUSY ){
2630 if( nTimeout++ >= 3 ) break;
2631 sqlite3_sleep(100);
2632 }
2633 }
2634 sqlite3_backup_finish(pBackup);
2635 if( rc==SQLITE_DONE ){
2636 rc = TCL_OK;
2637 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2638 Tcl_AppendResult(interp, "restore failed: source database busy",
2639 (char*)0);
2640 rc = TCL_ERROR;
2641 }else{
2642 Tcl_AppendResult(interp, "restore failed: ",
2643 sqlite3_errmsg(pDb->db), (char*)0);
2644 rc = TCL_ERROR;
2645 }
2646 sqlite3_close(pSrc);
2647 break;
2648 }
2649
drh22fbcb82004-02-01 01:22:50 +00002650 /*
drh3c379b02010-04-07 19:31:59 +00002651 ** $db status (step|sort|autoindex)
drhd1d38482008-10-07 23:46:38 +00002652 **
2653 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2654 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2655 */
2656 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002657 int v;
2658 const char *zOp;
2659 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00002660 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00002661 return TCL_ERROR;
2662 }
2663 zOp = Tcl_GetString(objv[2]);
2664 if( strcmp(zOp, "step")==0 ){
2665 v = pDb->nStep;
2666 }else if( strcmp(zOp, "sort")==0 ){
2667 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002668 }else if( strcmp(zOp, "autoindex")==0 ){
2669 v = pDb->nIndex;
drhd1d38482008-10-07 23:46:38 +00002670 }else{
drh3c379b02010-04-07 19:31:59 +00002671 Tcl_AppendResult(interp,
2672 "bad argument: should be autoindex, step, or sort",
drhd1d38482008-10-07 23:46:38 +00002673 (char*)0);
2674 return TCL_ERROR;
2675 }
2676 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2677 break;
2678 }
2679
2680 /*
drhbec3f402000-08-04 13:49:02 +00002681 ** $db timeout MILLESECONDS
2682 **
2683 ** Delay for the number of milliseconds specified when a file is locked.
2684 */
drh6d313162000-09-21 13:01:35 +00002685 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002686 int ms;
drh6d313162000-09-21 13:01:35 +00002687 if( objc!=3 ){
2688 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002689 return TCL_ERROR;
2690 }
drh6d313162000-09-21 13:01:35 +00002691 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002692 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002693 break;
drh75897232000-05-29 14:26:00 +00002694 }
danielk197755c45f22005-04-03 23:54:43 +00002695
2696 /*
drh0f14e2e2004-06-29 12:39:08 +00002697 ** $db total_changes
2698 **
2699 ** Return the number of rows that were modified, inserted, or deleted
2700 ** since the database handle was created.
2701 */
2702 case DB_TOTAL_CHANGES: {
2703 Tcl_Obj *pResult;
2704 if( objc!=2 ){
2705 Tcl_WrongNumArgs(interp, 2, objv, "");
2706 return TCL_ERROR;
2707 }
2708 pResult = Tcl_GetObjResult(interp);
2709 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2710 break;
2711 }
2712
drhb5a20d32003-04-23 12:25:23 +00002713 /* $db trace ?CALLBACK?
2714 **
2715 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2716 ** that is executed. The text of the SQL is appended to CALLBACK before
2717 ** it is executed.
2718 */
2719 case DB_TRACE: {
2720 if( objc>3 ){
2721 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002722 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002723 }else if( objc==2 ){
2724 if( pDb->zTrace ){
2725 Tcl_AppendResult(interp, pDb->zTrace, 0);
2726 }
2727 }else{
2728 char *zTrace;
2729 int len;
2730 if( pDb->zTrace ){
2731 Tcl_Free(pDb->zTrace);
2732 }
2733 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2734 if( zTrace && len>0 ){
2735 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002736 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002737 }else{
2738 pDb->zTrace = 0;
2739 }
shanehbb201342011-02-09 19:55:20 +00002740#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drhb5a20d32003-04-23 12:25:23 +00002741 if( pDb->zTrace ){
2742 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002743 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002744 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002745 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002746 }
drh19e2d372005-08-29 23:00:03 +00002747#endif
drhb5a20d32003-04-23 12:25:23 +00002748 }
2749 break;
2750 }
2751
drh3d214232005-08-02 12:21:08 +00002752 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2753 **
2754 ** Start a new transaction (if we are not already in the midst of a
2755 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2756 ** completes, either commit the transaction or roll it back if SCRIPT
2757 ** throws an exception. Or if no new transation was started, do nothing.
2758 ** pass the exception on up the stack.
2759 **
2760 ** This command was inspired by Dave Thomas's talk on Ruby at the
2761 ** 2005 O'Reilly Open Source Convention (OSCON).
2762 */
2763 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00002764 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00002765 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00002766 if( objc!=3 && objc!=4 ){
2767 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2768 return TCL_ERROR;
2769 }
danielk1977cd38d522009-01-02 17:33:46 +00002770
dan4a4c11a2009-10-06 14:59:02 +00002771 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00002772 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002773 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002774 };
2775 enum TTYPE_enum {
2776 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2777 };
2778 int ttype;
drhb5555e72005-08-02 17:15:14 +00002779 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002780 0, &ttype) ){
2781 return TCL_ERROR;
2782 }
2783 switch( (enum TTYPE_enum)ttype ){
2784 case TTYPE_DEFERRED: /* no-op */; break;
2785 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2786 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2787 }
drh3d214232005-08-02 12:21:08 +00002788 }
danielk1977cd38d522009-01-02 17:33:46 +00002789 pScript = objv[objc-1];
2790
dan4a4c11a2009-10-06 14:59:02 +00002791 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00002792 pDb->disableAuth++;
2793 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2794 pDb->disableAuth--;
2795 if( rc!=SQLITE_OK ){
2796 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2797 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00002798 }
danielk1977cd38d522009-01-02 17:33:46 +00002799 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00002800
dan4a4c11a2009-10-06 14:59:02 +00002801 /* If using NRE, schedule a callback to invoke the script pScript, then
2802 ** a second callback to commit (or rollback) the transaction or savepoint
2803 ** opened above. If not using NRE, evaluate the script directly, then
2804 ** call function DbTransPostCmd() to commit (or rollback) the transaction
2805 ** or savepoint. */
2806 if( DbUseNre() ){
2807 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
2808 Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00002809 }else{
dan4a4c11a2009-10-06 14:59:02 +00002810 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00002811 }
2812 break;
2813 }
2814
danielk197794eb6a12005-12-15 15:22:08 +00002815 /*
danielk1977404ca072009-03-16 13:19:36 +00002816 ** $db unlock_notify ?script?
2817 */
2818 case DB_UNLOCK_NOTIFY: {
2819#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2820 Tcl_AppendResult(interp, "unlock_notify not available in this build", 0);
2821 rc = TCL_ERROR;
2822#else
2823 if( objc!=2 && objc!=3 ){
2824 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2825 rc = TCL_ERROR;
2826 }else{
2827 void (*xNotify)(void **, int) = 0;
2828 void *pNotifyArg = 0;
2829
2830 if( pDb->pUnlockNotify ){
2831 Tcl_DecrRefCount(pDb->pUnlockNotify);
2832 pDb->pUnlockNotify = 0;
2833 }
2834
2835 if( objc==3 ){
2836 xNotify = DbUnlockNotify;
2837 pNotifyArg = (void *)pDb;
2838 pDb->pUnlockNotify = objv[2];
2839 Tcl_IncrRefCount(pDb->pUnlockNotify);
2840 }
2841
2842 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
2843 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2844 rc = TCL_ERROR;
2845 }
2846 }
2847#endif
2848 break;
2849 }
2850
drh304637c2011-03-18 16:47:27 +00002851 /*
2852 ** $db preupdate_hook count
2853 ** $db preupdate_hook hook ?SCRIPT?
2854 ** $db preupdate_hook new INDEX
2855 ** $db preupdate_hook old INDEX
2856 */
dan46c47d42011-03-01 18:42:07 +00002857 case DB_PREUPDATE: {
drh9b1c62d2011-03-30 21:04:43 +00002858#ifndef SQLITE_ENABLE_PREUPDATE_HOOK
2859 Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time");
2860 rc = TCL_ERROR;
2861#else
dan1e7a2d42011-03-22 18:45:29 +00002862 static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
dan46c47d42011-03-01 18:42:07 +00002863 enum DbPreupdateSubCmd {
dan1e7a2d42011-03-22 18:45:29 +00002864 PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
dan46c47d42011-03-01 18:42:07 +00002865 };
2866 int iSub;
2867
2868 if( objc<3 ){
2869 Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
2870 }
2871 if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
2872 return TCL_ERROR;
2873 }
2874
2875 switch( (enum DbPreupdateSubCmd)iSub ){
2876 case PRE_COUNT: {
2877 int nCol = sqlite3_preupdate_count(pDb->db);
2878 Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
2879 break;
2880 }
2881
2882 case PRE_HOOK: {
2883 if( objc>4 ){
2884 Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
2885 return TCL_ERROR;
2886 }
2887 DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
2888 break;
2889 }
2890
dan1e7a2d42011-03-22 18:45:29 +00002891 case PRE_DEPTH: {
2892 Tcl_Obj *pRet;
2893 if( objc!=3 ){
2894 Tcl_WrongNumArgs(interp, 3, objv, "");
2895 return TCL_ERROR;
2896 }
2897 pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
2898 Tcl_SetObjResult(interp, pRet);
2899 break;
2900 }
2901
dan37db03b2011-03-16 19:59:18 +00002902 case PRE_NEW:
dan46c47d42011-03-01 18:42:07 +00002903 case PRE_OLD: {
2904 int iIdx;
dan37db03b2011-03-16 19:59:18 +00002905 sqlite3_value *pValue;
dan46c47d42011-03-01 18:42:07 +00002906 if( objc!=4 ){
2907 Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
2908 return TCL_ERROR;
2909 }
2910 if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
2911 return TCL_ERROR;
2912 }
2913
dan37db03b2011-03-16 19:59:18 +00002914 if( iSub==PRE_OLD ){
dan46c47d42011-03-01 18:42:07 +00002915 rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
dan37db03b2011-03-16 19:59:18 +00002916 }else{
2917 assert( iSub==PRE_NEW );
2918 rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
dan46c47d42011-03-01 18:42:07 +00002919 }
2920
dan37db03b2011-03-16 19:59:18 +00002921 if( rc==SQLITE_OK ){
drh304637c2011-03-18 16:47:27 +00002922 Tcl_Obj *pObj;
2923 pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
dan37db03b2011-03-16 19:59:18 +00002924 Tcl_SetObjResult(interp, pObj);
2925 }else{
dan46c47d42011-03-01 18:42:07 +00002926 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2927 return TCL_ERROR;
2928 }
2929 }
2930 }
drh9b1c62d2011-03-30 21:04:43 +00002931#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +00002932 break;
2933 }
2934
danielk1977404ca072009-03-16 13:19:36 +00002935 /*
drh833bf962010-04-28 14:42:19 +00002936 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002937 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002938 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002939 */
drh833bf962010-04-28 14:42:19 +00002940 case DB_WAL_HOOK:
danielk197771fd80b2005-12-16 06:54:01 +00002941 case DB_UPDATE_HOOK:
dan6566ebe2011-03-16 09:49:14 +00002942 case DB_ROLLBACK_HOOK: {
danielk197771fd80b2005-12-16 06:54:01 +00002943 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2944 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2945 */
2946 Tcl_Obj **ppHook;
dan46c47d42011-03-01 18:42:07 +00002947 if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
2948 if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
2949 if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
2950 if( objc>3 ){
danielk197794eb6a12005-12-15 15:22:08 +00002951 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2952 return TCL_ERROR;
2953 }
danielk197771fd80b2005-12-16 06:54:01 +00002954
dan46c47d42011-03-01 18:42:07 +00002955 DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002956 break;
2957 }
2958
danielk19774397de52005-01-12 12:44:03 +00002959 /* $db version
2960 **
2961 ** Return the version string for this database.
2962 */
2963 case DB_VERSION: {
2964 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2965 break;
2966 }
2967
tpoindex1067fe12004-12-17 15:41:11 +00002968
drh6d313162000-09-21 13:01:35 +00002969 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002970 return rc;
drh75897232000-05-29 14:26:00 +00002971}
2972
drha2c8a952009-10-13 18:38:34 +00002973#if SQLITE_TCL_NRE
2974/*
2975** Adaptor that provides an objCmd interface to the NRE-enabled
2976** interface implementation.
2977*/
2978static int DbObjCmdAdaptor(
2979 void *cd,
2980 Tcl_Interp *interp,
2981 int objc,
2982 Tcl_Obj *const*objv
2983){
2984 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
2985}
2986#endif /* SQLITE_TCL_NRE */
2987
drh75897232000-05-29 14:26:00 +00002988/*
drh3570ad92007-08-31 14:31:44 +00002989** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00002990** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00002991**
2992** This is the main Tcl command. When the "sqlite" Tcl command is
2993** invoked, this routine runs to process that command.
2994**
2995** The first argument, DBNAME, is an arbitrary name for a new
2996** database connection. This command creates a new command named
2997** DBNAME that is used to control that connection. The database
2998** connection is deleted when the DBNAME command is deleted.
2999**
drh3570ad92007-08-31 14:31:44 +00003000** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00003001**
drh75897232000-05-29 14:26:00 +00003002*/
drh22fbcb82004-02-01 01:22:50 +00003003static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00003004 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00003005 void *pKey = 0;
3006 int nKey = 0;
3007 const char *zArg;
drh75897232000-05-29 14:26:00 +00003008 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00003009 int i;
drh22fbcb82004-02-01 01:22:50 +00003010 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00003011 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00003012 int flags;
drh882e8e42006-08-24 02:42:27 +00003013 Tcl_DString translatedFilename;
drhd9da78a2009-03-24 15:08:09 +00003014
3015 /* In normal use, each TCL interpreter runs in a single thread. So
3016 ** by default, we can turn of mutexing on SQLite database connections.
3017 ** However, for testing purposes it is useful to have mutexes turned
3018 ** on. So, by default, mutexes default off. But if compiled with
3019 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3020 */
3021#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3022 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3023#else
3024 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3025#endif
3026
drh22fbcb82004-02-01 01:22:50 +00003027 if( objc==2 ){
3028 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00003029 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00003030 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00003031 return TCL_OK;
3032 }
drh9eb9e262004-02-11 02:18:05 +00003033 if( strcmp(zArg,"-has-codec")==0 ){
3034#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00003035 Tcl_AppendResult(interp,"1",0);
3036#else
3037 Tcl_AppendResult(interp,"0",0);
3038#endif
3039 return TCL_OK;
3040 }
drhfbc3eab2001-04-06 16:13:42 +00003041 }
drh3570ad92007-08-31 14:31:44 +00003042 for(i=3; i+1<objc; i+=2){
3043 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00003044 if( strcmp(zArg,"-key")==0 ){
drh3570ad92007-08-31 14:31:44 +00003045 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
3046 }else if( strcmp(zArg, "-vfs")==0 ){
dan3c3dd7b2010-06-22 11:10:40 +00003047 zVfs = Tcl_GetString(objv[i+1]);
drh3570ad92007-08-31 14:31:44 +00003048 }else if( strcmp(zArg, "-readonly")==0 ){
3049 int b;
3050 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3051 if( b ){
drh33f4e022007-09-03 15:19:34 +00003052 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00003053 flags |= SQLITE_OPEN_READONLY;
3054 }else{
3055 flags &= ~SQLITE_OPEN_READONLY;
3056 flags |= SQLITE_OPEN_READWRITE;
3057 }
3058 }else if( strcmp(zArg, "-create")==0 ){
3059 int b;
3060 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00003061 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00003062 flags |= SQLITE_OPEN_CREATE;
3063 }else{
3064 flags &= ~SQLITE_OPEN_CREATE;
3065 }
danielk19779a6284c2008-07-10 17:52:49 +00003066 }else if( strcmp(zArg, "-nomutex")==0 ){
3067 int b;
3068 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3069 if( b ){
3070 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00003071 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00003072 }else{
3073 flags &= ~SQLITE_OPEN_NOMUTEX;
3074 }
drh039963a2008-09-03 00:43:15 +00003075 }else if( strcmp(zArg, "-fullmutex")==0 ){
3076 int b;
3077 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3078 if( b ){
3079 flags |= SQLITE_OPEN_FULLMUTEX;
3080 flags &= ~SQLITE_OPEN_NOMUTEX;
3081 }else{
3082 flags &= ~SQLITE_OPEN_FULLMUTEX;
3083 }
drh3570ad92007-08-31 14:31:44 +00003084 }else{
3085 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3086 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00003087 }
3088 }
drh3570ad92007-08-31 14:31:44 +00003089 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00003090 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00003091 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh039963a2008-09-03 00:43:15 +00003092 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN?"
drh9eb9e262004-02-11 02:18:05 +00003093#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00003094 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00003095#endif
3096 );
drh75897232000-05-29 14:26:00 +00003097 return TCL_ERROR;
3098 }
drh75897232000-05-29 14:26:00 +00003099 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003100 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00003101 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00003102 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
3103 return TCL_ERROR;
3104 }
3105 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00003106 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00003107 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
drh3570ad92007-08-31 14:31:44 +00003108 sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00003109 Tcl_DStringFree(&translatedFilename);
danielk197780290862004-05-22 09:21:21 +00003110 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
drh9404d502006-12-19 18:46:08 +00003111 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
danielk197780290862004-05-22 09:21:21 +00003112 sqlite3_close(p->db);
3113 p->db = 0;
3114 }
drh2011d5f2004-07-22 02:40:37 +00003115#ifdef SQLITE_HAS_CODEC
drhf3a65f72007-08-22 20:18:21 +00003116 if( p->db ){
3117 sqlite3_key(p->db, pKey, nKey);
3118 }
drheb8ed702004-02-11 10:37:23 +00003119#endif
drhbec3f402000-08-04 13:49:02 +00003120 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003121 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003122 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003123 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003124 return TCL_ERROR;
3125 }
drhfb7e7652005-01-24 00:28:42 +00003126 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00003127 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003128 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003129 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003130 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3131 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003132 }else{
3133 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3134 }
drh75897232000-05-29 14:26:00 +00003135 return TCL_OK;
3136}
3137
3138/*
drh90ca9752001-09-28 17:47:14 +00003139** Provide a dummy Tcl_InitStubs if we are using this as a static
3140** library.
3141*/
3142#ifndef USE_TCL_STUBS
3143# undef Tcl_InitStubs
3144# define Tcl_InitStubs(a,b,c)
3145#endif
3146
3147/*
drh29bc4612005-10-05 10:40:15 +00003148** Make sure we have a PACKAGE_VERSION macro defined. This will be
3149** defined automatically by the TEA makefile. But other makefiles
3150** do not define it.
3151*/
3152#ifndef PACKAGE_VERSION
3153# define PACKAGE_VERSION SQLITE_VERSION
3154#endif
3155
3156/*
drh75897232000-05-29 14:26:00 +00003157** Initialize this module.
3158**
3159** This Tcl module contains only a single new Tcl command named "sqlite".
3160** (Hence there is no namespace. There is no point in using a namespace
3161** if the extension only supplies one new name!) The "sqlite" command is
3162** used to open a new SQLite database. See the DbMain() routine above
3163** for additional information.
drhb652f432010-08-26 16:46:57 +00003164**
3165** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003166*/
drhb652f432010-08-26 16:46:57 +00003167EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00003168 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00003169 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00003170 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh1cca0d22010-08-25 20:35:51 +00003171
3172#ifndef SQLITE_3_SUFFIX_ONLY
3173 /* The "sqlite" alias is undocumented. It is here only to support
3174 ** legacy scripts. All new scripts should use only the "sqlite3"
3175 ** command.
3176 */
drh49766d62005-01-08 18:42:28 +00003177 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003178#endif
drh1cca0d22010-08-25 20:35:51 +00003179
drh90ca9752001-09-28 17:47:14 +00003180 return TCL_OK;
3181}
drhb652f432010-08-26 16:46:57 +00003182EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3183EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3184EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3185EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3186EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3187EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3188EXTERN int Tclsqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
drhe2c3a652008-09-23 09:58:46 +00003189
drh49766d62005-01-08 18:42:28 +00003190
3191#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003192int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3193int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3194int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3195int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3196int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3197int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3198int Sqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3199int Tclsqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
drh49766d62005-01-08 18:42:28 +00003200#endif
drh75897232000-05-29 14:26:00 +00003201
drh3e27c022004-07-23 00:01:38 +00003202#ifdef TCLSH
3203/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003204** All of the code that follows is used to build standalone TCL interpreters
3205** that are statically linked with SQLite. Enable these by compiling
3206** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3207** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3208** analysis program.
drh75897232000-05-29 14:26:00 +00003209*/
drh348784e2000-05-29 20:41:49 +00003210
drh57a02272009-10-22 20:52:05 +00003211#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3212/*
3213 * This code implements the MD5 message-digest algorithm.
3214 * The algorithm is due to Ron Rivest. This code was
3215 * written by Colin Plumb in 1993, no copyright is claimed.
3216 * This code is in the public domain; do with it what you wish.
3217 *
3218 * Equivalent code is available from RSA Data Security, Inc.
3219 * This code has been tested against that, and is equivalent,
3220 * except that you don't need to include two pages of legalese
3221 * with every copy.
3222 *
3223 * To compute the message digest of a chunk of bytes, declare an
3224 * MD5Context structure, pass it to MD5Init, call MD5Update as
3225 * needed on buffers full of bytes, and then call MD5Final, which
3226 * will fill a supplied 16-byte array with the digest.
3227 */
3228
3229/*
3230 * If compiled on a machine that doesn't have a 32-bit integer,
3231 * you just set "uint32" to the appropriate datatype for an
3232 * unsigned 32-bit integer. For example:
3233 *
3234 * cc -Duint32='unsigned long' md5.c
3235 *
3236 */
3237#ifndef uint32
3238# define uint32 unsigned int
3239#endif
3240
3241struct MD5Context {
3242 int isInit;
3243 uint32 buf[4];
3244 uint32 bits[2];
3245 unsigned char in[64];
3246};
3247typedef struct MD5Context MD5Context;
3248
3249/*
3250 * Note: this code is harmless on little-endian machines.
3251 */
3252static void byteReverse (unsigned char *buf, unsigned longs){
3253 uint32 t;
3254 do {
3255 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3256 ((unsigned)buf[1]<<8 | buf[0]);
3257 *(uint32 *)buf = t;
3258 buf += 4;
3259 } while (--longs);
3260}
3261/* The four core functions - F1 is optimized somewhat */
3262
3263/* #define F1(x, y, z) (x & y | ~x & z) */
3264#define F1(x, y, z) (z ^ (x & (y ^ z)))
3265#define F2(x, y, z) F1(z, x, y)
3266#define F3(x, y, z) (x ^ y ^ z)
3267#define F4(x, y, z) (y ^ (x | ~z))
3268
3269/* This is the central step in the MD5 algorithm. */
3270#define MD5STEP(f, w, x, y, z, data, s) \
3271 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3272
3273/*
3274 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3275 * reflect the addition of 16 longwords of new data. MD5Update blocks
3276 * the data and converts bytes into longwords for this routine.
3277 */
3278static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3279 register uint32 a, b, c, d;
3280
3281 a = buf[0];
3282 b = buf[1];
3283 c = buf[2];
3284 d = buf[3];
3285
3286 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3287 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3288 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3289 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3290 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3291 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3292 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3293 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3294 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3295 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3296 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3297 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3298 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3299 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3300 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3301 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3302
3303 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3304 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3305 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3306 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3307 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3308 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3309 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3310 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3311 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3312 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3313 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3314 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3315 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3316 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3317 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3318 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3319
3320 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3321 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3322 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3323 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3324 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3325 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3326 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3327 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3328 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3329 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3330 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3331 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3332 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3333 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3334 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3335 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3336
3337 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3338 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3339 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3340 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3341 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3342 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3343 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3344 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3345 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3346 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3347 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3348 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3349 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3350 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3351 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3352 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3353
3354 buf[0] += a;
3355 buf[1] += b;
3356 buf[2] += c;
3357 buf[3] += d;
3358}
3359
3360/*
3361 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3362 * initialization constants.
3363 */
3364static void MD5Init(MD5Context *ctx){
3365 ctx->isInit = 1;
3366 ctx->buf[0] = 0x67452301;
3367 ctx->buf[1] = 0xefcdab89;
3368 ctx->buf[2] = 0x98badcfe;
3369 ctx->buf[3] = 0x10325476;
3370 ctx->bits[0] = 0;
3371 ctx->bits[1] = 0;
3372}
3373
3374/*
3375 * Update context to reflect the concatenation of another buffer full
3376 * of bytes.
3377 */
3378static
3379void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3380 uint32 t;
3381
3382 /* Update bitcount */
3383
3384 t = ctx->bits[0];
3385 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3386 ctx->bits[1]++; /* Carry from low to high */
3387 ctx->bits[1] += len >> 29;
3388
3389 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3390
3391 /* Handle any leading odd-sized chunks */
3392
3393 if ( t ) {
3394 unsigned char *p = (unsigned char *)ctx->in + t;
3395
3396 t = 64-t;
3397 if (len < t) {
3398 memcpy(p, buf, len);
3399 return;
3400 }
3401 memcpy(p, buf, t);
3402 byteReverse(ctx->in, 16);
3403 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3404 buf += t;
3405 len -= t;
3406 }
3407
3408 /* Process data in 64-byte chunks */
3409
3410 while (len >= 64) {
3411 memcpy(ctx->in, buf, 64);
3412 byteReverse(ctx->in, 16);
3413 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3414 buf += 64;
3415 len -= 64;
3416 }
3417
3418 /* Handle any remaining bytes of data. */
3419
3420 memcpy(ctx->in, buf, len);
3421}
3422
3423/*
3424 * Final wrapup - pad to 64-byte boundary with the bit pattern
3425 * 1 0* (64-bit count of bits processed, MSB-first)
3426 */
3427static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3428 unsigned count;
3429 unsigned char *p;
3430
3431 /* Compute number of bytes mod 64 */
3432 count = (ctx->bits[0] >> 3) & 0x3F;
3433
3434 /* Set the first char of padding to 0x80. This is safe since there is
3435 always at least one byte free */
3436 p = ctx->in + count;
3437 *p++ = 0x80;
3438
3439 /* Bytes of padding needed to make 64 bytes */
3440 count = 64 - 1 - count;
3441
3442 /* Pad out to 56 mod 64 */
3443 if (count < 8) {
3444 /* Two lots of padding: Pad the first block to 64 bytes */
3445 memset(p, 0, count);
3446 byteReverse(ctx->in, 16);
3447 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3448
3449 /* Now fill the next block with 56 bytes */
3450 memset(ctx->in, 0, 56);
3451 } else {
3452 /* Pad block to 56 bytes */
3453 memset(p, 0, count-8);
3454 }
3455 byteReverse(ctx->in, 14);
3456
3457 /* Append length in bits and transform */
3458 ((uint32 *)ctx->in)[ 14 ] = ctx->bits[0];
3459 ((uint32 *)ctx->in)[ 15 ] = ctx->bits[1];
3460
3461 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3462 byteReverse((unsigned char *)ctx->buf, 4);
3463 memcpy(digest, ctx->buf, 16);
3464 memset(ctx, 0, sizeof(ctx)); /* In case it is sensitive */
3465}
3466
3467/*
3468** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3469*/
3470static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3471 static char const zEncode[] = "0123456789abcdef";
3472 int i, j;
3473
3474 for(j=i=0; i<16; i++){
3475 int a = digest[i];
3476 zBuf[j++] = zEncode[(a>>4)&0xf];
3477 zBuf[j++] = zEncode[a & 0xf];
3478 }
3479 zBuf[j] = 0;
3480}
3481
3482
3483/*
3484** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3485** each representing 16 bits of the digest and separated from each
3486** other by a "-" character.
3487*/
3488static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3489 int i, j;
3490 unsigned int x;
3491 for(i=j=0; i<16; i+=2){
3492 x = digest[i]*256 + digest[i+1];
3493 if( i>0 ) zDigest[j++] = '-';
3494 sprintf(&zDigest[j], "%05u", x);
3495 j += 5;
3496 }
3497 zDigest[j] = 0;
3498}
3499
3500/*
3501** A TCL command for md5. The argument is the text to be hashed. The
3502** Result is the hash in base64.
3503*/
3504static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3505 MD5Context ctx;
3506 unsigned char digest[16];
3507 char zBuf[50];
3508 void (*converter)(unsigned char*, char*);
3509
3510 if( argc!=2 ){
3511 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3512 " TEXT\"", 0);
3513 return TCL_ERROR;
3514 }
3515 MD5Init(&ctx);
3516 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3517 MD5Final(digest, &ctx);
3518 converter = (void(*)(unsigned char*,char*))cd;
3519 converter(digest, zBuf);
3520 Tcl_AppendResult(interp, zBuf, (char*)0);
3521 return TCL_OK;
3522}
3523
3524/*
3525** A TCL command to take the md5 hash of a file. The argument is the
3526** name of the file.
3527*/
3528static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3529 FILE *in;
3530 MD5Context ctx;
3531 void (*converter)(unsigned char*, char*);
3532 unsigned char digest[16];
3533 char zBuf[10240];
3534
3535 if( argc!=2 ){
3536 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3537 " FILENAME\"", 0);
3538 return TCL_ERROR;
3539 }
3540 in = fopen(argv[1],"rb");
3541 if( in==0 ){
3542 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
3543 "\" for reading", 0);
3544 return TCL_ERROR;
3545 }
3546 MD5Init(&ctx);
3547 for(;;){
3548 int n;
3549 n = fread(zBuf, 1, sizeof(zBuf), in);
3550 if( n<=0 ) break;
3551 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3552 }
3553 fclose(in);
3554 MD5Final(digest, &ctx);
3555 converter = (void(*)(unsigned char*,char*))cd;
3556 converter(digest, zBuf);
3557 Tcl_AppendResult(interp, zBuf, (char*)0);
3558 return TCL_OK;
3559}
3560
3561/*
3562** Register the four new TCL commands for generating MD5 checksums
3563** with the TCL interpreter.
3564*/
3565int Md5_Init(Tcl_Interp *interp){
3566 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3567 MD5DigestToBase16, 0);
3568 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3569 MD5DigestToBase10x8, 0);
3570 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3571 MD5DigestToBase16, 0);
3572 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3573 MD5DigestToBase10x8, 0);
3574 return TCL_OK;
3575}
3576#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3577
3578#if defined(SQLITE_TEST)
3579/*
3580** During testing, the special md5sum() aggregate function is available.
3581** inside SQLite. The following routines implement that function.
3582*/
3583static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3584 MD5Context *p;
3585 int i;
3586 if( argc<1 ) return;
3587 p = sqlite3_aggregate_context(context, sizeof(*p));
3588 if( p==0 ) return;
3589 if( !p->isInit ){
3590 MD5Init(p);
3591 }
3592 for(i=0; i<argc; i++){
3593 const char *zData = (char*)sqlite3_value_text(argv[i]);
3594 if( zData ){
3595 MD5Update(p, (unsigned char*)zData, strlen(zData));
3596 }
3597 }
3598}
3599static void md5finalize(sqlite3_context *context){
3600 MD5Context *p;
3601 unsigned char digest[16];
3602 char zBuf[33];
3603 p = sqlite3_aggregate_context(context, sizeof(*p));
3604 MD5Final(digest,p);
3605 MD5DigestToBase16(digest, zBuf);
3606 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3607}
3608int Md5_Register(sqlite3 *db){
3609 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
3610 md5step, md5finalize);
3611 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3612 return rc;
3613}
3614#endif /* defined(SQLITE_TEST) */
3615
3616
drh348784e2000-05-29 20:41:49 +00003617/*
drh3e27c022004-07-23 00:01:38 +00003618** If the macro TCLSH is one, then put in code this for the
3619** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003620** standard input, or if a file is named on the command line
3621** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003622*/
drh3e27c022004-07-23 00:01:38 +00003623#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00003624static char zMainloop[] =
3625 "set line {}\n"
3626 "while {![eof stdin]} {\n"
3627 "if {$line!=\"\"} {\n"
3628 "puts -nonewline \"> \"\n"
3629 "} else {\n"
3630 "puts -nonewline \"% \"\n"
3631 "}\n"
3632 "flush stdout\n"
3633 "append line [gets stdin]\n"
3634 "if {[info complete $line]} {\n"
3635 "if {[catch {uplevel #0 $line} result]} {\n"
3636 "puts stderr \"Error: $result\"\n"
3637 "} elseif {$result!=\"\"} {\n"
3638 "puts $result\n"
3639 "}\n"
3640 "set line {}\n"
3641 "} else {\n"
3642 "append line \\n\n"
3643 "}\n"
3644 "}\n"
3645;
drh3e27c022004-07-23 00:01:38 +00003646#endif
drh3a0f13f2010-07-12 16:47:48 +00003647#if TCLSH==2
3648static char zMainloop[] =
3649#include "spaceanal_tcl.h"
3650;
3651#endif
drh3e27c022004-07-23 00:01:38 +00003652
danc1a60c52010-06-07 14:28:16 +00003653#ifdef SQLITE_TEST
3654static void init_all(Tcl_Interp *);
3655static int init_all_cmd(
3656 ClientData cd,
3657 Tcl_Interp *interp,
3658 int objc,
3659 Tcl_Obj *CONST objv[]
3660){
danielk19770a549072009-02-17 16:29:10 +00003661
danc1a60c52010-06-07 14:28:16 +00003662 Tcl_Interp *slave;
3663 if( objc!=2 ){
3664 Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3665 return TCL_ERROR;
3666 }
3667
3668 slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3669 if( !slave ){
3670 return TCL_ERROR;
3671 }
3672
3673 init_all(slave);
3674 return TCL_OK;
3675}
3676#endif
3677
3678/*
3679** Configure the interpreter passed as the first argument to have access
3680** to the commands and linked variables that make up:
3681**
3682** * the [sqlite3] extension itself,
3683**
3684** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
3685**
3686** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
3687** test suite.
3688*/
3689static void init_all(Tcl_Interp *interp){
drh38f82712004-06-18 17:10:16 +00003690 Sqlite3_Init(interp);
danc1a60c52010-06-07 14:28:16 +00003691
drh57a02272009-10-22 20:52:05 +00003692#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3693 Md5_Init(interp);
3694#endif
danc1a60c52010-06-07 14:28:16 +00003695
drhd9b02572001-04-15 00:37:09 +00003696#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00003697 {
drh2f999a62007-08-15 19:16:43 +00003698 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00003699 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00003700 extern int Sqlitetest2_Init(Tcl_Interp*);
3701 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00003702 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00003703 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00003704 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00003705 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00003706 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00003707 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00003708 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00003709 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
dan0a7a9152010-04-07 07:57:38 +00003710 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
drh984bfaa2008-03-19 16:08:53 +00003711 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00003712 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00003713 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003714 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00003715 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003716 extern int Sqlitetestschema_Init(Tcl_Interp*);
3717 extern int Sqlitetestsse_Init(Tcl_Interp*);
3718 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00003719 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00003720 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00003721 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00003722 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh522efc62009-11-10 17:24:37 +00003723 extern int Sqlitetestintarray_Init(Tcl_Interp*);
danc7991bd2010-05-05 19:04:59 +00003724 extern int Sqlitetestvfs_Init(Tcl_Interp *);
dan599e9d22010-07-12 08:39:37 +00003725 extern int SqlitetestStat_Init(Tcl_Interp*);
dan9508daa2010-08-28 18:58:00 +00003726 extern int Sqlitetestrtree_Init(Tcl_Interp*);
dan8cf35eb2010-09-01 11:40:05 +00003727 extern int Sqlitequota_Init(Tcl_Interp*);
shaneh8a922f72010-11-04 20:50:27 +00003728 extern int Sqlitemultiplex_Init(Tcl_Interp*);
dane336b002010-11-19 18:20:09 +00003729 extern int SqliteSuperlock_Init(Tcl_Interp*);
dan213ca0a2011-03-28 19:10:06 +00003730 extern int SqlitetestSyscall_Init(Tcl_Interp*);
drh9b1c62d2011-03-30 21:04:43 +00003731#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
dan4fccf432011-03-08 19:22:50 +00003732 extern int TestSession_Init(Tcl_Interp*);
3733#endif
danb29010c2010-12-29 18:24:38 +00003734#ifdef SQLITE_ENABLE_ZIPVFS
3735 extern int Zipvfs_Init(Tcl_Interp*);
3736 Zipvfs_Init(interp);
3737#endif
3738
drh2f999a62007-08-15 19:16:43 +00003739 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00003740 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00003741 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00003742 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00003743 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00003744 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00003745 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00003746 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00003747 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00003748 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00003749 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00003750 Sqlitetest_autoext_Init(interp);
dan0a7a9152010-04-07 07:57:38 +00003751 Sqlitetest_demovfs_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00003752 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00003753 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00003754 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003755 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00003756 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003757 Sqlitetestschema_Init(interp);
3758 Sqlitetesttclvar_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00003759 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003760 SqlitetestOnefile_Init(interp);
danielk19775d1f5aa2008-04-10 14:51:00 +00003761 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00003762 Sqlitetestbackup_Init(interp);
drh522efc62009-11-10 17:24:37 +00003763 Sqlitetestintarray_Init(interp);
danc7991bd2010-05-05 19:04:59 +00003764 Sqlitetestvfs_Init(interp);
dan599e9d22010-07-12 08:39:37 +00003765 SqlitetestStat_Init(interp);
dan9508daa2010-08-28 18:58:00 +00003766 Sqlitetestrtree_Init(interp);
dan8cf35eb2010-09-01 11:40:05 +00003767 Sqlitequota_Init(interp);
shaneh8a922f72010-11-04 20:50:27 +00003768 Sqlitemultiplex_Init(interp);
dane336b002010-11-19 18:20:09 +00003769 SqliteSuperlock_Init(interp);
dan213ca0a2011-03-28 19:10:06 +00003770 SqlitetestSyscall_Init(interp);
drh9b1c62d2011-03-30 21:04:43 +00003771#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
dan4fccf432011-03-08 19:22:50 +00003772 TestSession_Init(interp);
3773#endif
danielk1977a15db352007-09-14 16:20:00 +00003774
danc1a60c52010-06-07 14:28:16 +00003775 Tcl_CreateObjCommand(interp,"load_testfixture_extensions",init_all_cmd,0,0);
3776
drh89dec812005-04-28 19:03:37 +00003777#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00003778 Sqlitetestsse_Init(interp);
3779#endif
drhd1bf3512001-04-07 15:24:33 +00003780 }
3781#endif
danc1a60c52010-06-07 14:28:16 +00003782}
3783
3784#define TCLSH_MAIN main /* Needed to fake out mktclapp */
3785int TCLSH_MAIN(int argc, char **argv){
3786 Tcl_Interp *interp;
3787
3788 /* Call sqlite3_shutdown() once before doing anything else. This is to
3789 ** test that sqlite3_shutdown() can be safely called by a process before
3790 ** sqlite3_initialize() is. */
3791 sqlite3_shutdown();
3792
drh3a0f13f2010-07-12 16:47:48 +00003793#if TCLSH==2
3794 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
3795#endif
danc1a60c52010-06-07 14:28:16 +00003796 Tcl_FindExecutable(argv[0]);
3797
3798 interp = Tcl_CreateInterp();
3799 init_all(interp);
drhc7285972009-11-10 01:13:25 +00003800 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00003801 int i;
shessad42c3a2006-08-22 23:53:46 +00003802 char zArgc[32];
3803 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
3804 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00003805 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
3806 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00003807 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00003808 Tcl_SetVar(interp, "argv", argv[i],
3809 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3810 }
drh3a0f13f2010-07-12 16:47:48 +00003811 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00003812 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00003813 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00003814 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00003815 return 1;
3816 }
drh3e27c022004-07-23 00:01:38 +00003817 }
drh3a0f13f2010-07-12 16:47:48 +00003818 if( TCLSH==2 || argc<=1 ){
drh348784e2000-05-29 20:41:49 +00003819 Tcl_GlobalEval(interp, zMainloop);
3820 }
3821 return 0;
3822}
3823#endif /* TCLSH */