blob: d2a0582e475b5a59c81aefcf360f55f9e8391317 [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.
danc431fd52011-06-27 16:55:50 +0000110**
111** If this module is built with SQLITE_TEST defined (to create the SQLite
112** testfixture executable), then it may be configured to use either
113** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
114** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
drhbec3f402000-08-04 13:49:02 +0000115*/
116typedef struct SqliteDb SqliteDb;
117struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000118 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000119 Tcl_Interp *interp; /* The interpreter used for this database */
120 char *zBusy; /* The busy callback routine */
121 char *zCommit; /* The commit hook callback routine */
122 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +0000123 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000124 char *zProgress; /* The progress callback routine */
125 char *zAuth; /* The authorization callback routine */
drh1f1549f2008-08-26 21:33:34 +0000126 int disableAuth; /* Disable the authorizer if it exists */
drhd1e47332005-06-26 17:55:33 +0000127 char *zNull; /* Text to substitute for an SQL NULL value */
128 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000129 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000130 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drh5def0842010-05-05 20:00:25 +0000131 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000132 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000133 SqlCollate *pCollate; /* List of SQL collation functions */
134 int rc; /* Return code of most recent sqlite3_exec() */
135 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000136 SqlPreparedStmt *stmtList; /* List of prepared statements*/
137 SqlPreparedStmt *stmtLast; /* Last statement in the list */
138 int maxStmt; /* The next maximum number of stmtList */
139 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000140 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh3c379b02010-04-07 19:31:59 +0000141 int nStep, nSort, nIndex; /* Statistics for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000142 int nTransaction; /* Number of nested [transaction] methods */
danc431fd52011-06-27 16:55:50 +0000143#ifdef SQLITE_TEST
144 int bLegacyPrepare; /* True to use sqlite3_prepare() */
145#endif
drh98808ba2001-10-18 12:34:46 +0000146};
drh297ecf12001-04-05 15:57:13 +0000147
danielk1977b4e9af92007-05-01 17:49:49 +0000148struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000149 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000150 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000151 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000152 Tcl_Channel channel; /* Channel identifier */
153 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
154 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000155};
156
drhea678832008-12-10 19:26:22 +0000157/*
158** Compute a string length that is limited to what can be stored in
159** lower 30 bits of a 32-bit signed integer.
160*/
drh4f21c4a2008-12-10 22:15:00 +0000161static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000162 const char *z2 = z;
163 while( *z2 ){ z2++; }
164 return 0x3fffffff & (int)(z2 - z);
165}
drhea678832008-12-10 19:26:22 +0000166
167
danielk197732a0d8b2007-05-04 19:03:02 +0000168#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000169/*
danielk1977d04417962007-05-02 13:16:30 +0000170** Close all incrblob channels opened using database connection pDb.
171** This is called when shutting down the database connection.
172*/
173static void closeIncrblobChannels(SqliteDb *pDb){
174 IncrblobChannel *p;
175 IncrblobChannel *pNext;
176
177 for(p=pDb->pIncrblob; p; p=pNext){
178 pNext = p->pNext;
179
180 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
181 ** which deletes the IncrblobChannel structure at *p. So do not
182 ** call Tcl_Free() here.
183 */
184 Tcl_UnregisterChannel(pDb->interp, p->channel);
185 }
186}
187
188/*
danielk1977b4e9af92007-05-01 17:49:49 +0000189** Close an incremental blob channel.
190*/
191static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
192 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000193 int rc = sqlite3_blob_close(p->pBlob);
194 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000195
196 /* Remove the channel from the SqliteDb.pIncrblob list. */
197 if( p->pNext ){
198 p->pNext->pPrev = p->pPrev;
199 }
200 if( p->pPrev ){
201 p->pPrev->pNext = p->pNext;
202 }
203 if( p->pDb->pIncrblob==p ){
204 p->pDb->pIncrblob = p->pNext;
205 }
206
danielk197792d4d7a2007-05-04 12:05:56 +0000207 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000208 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000209
210 if( rc!=SQLITE_OK ){
211 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
212 return TCL_ERROR;
213 }
danielk1977b4e9af92007-05-01 17:49:49 +0000214 return TCL_OK;
215}
216
217/*
218** Read data from an incremental blob channel.
219*/
220static int incrblobInput(
221 ClientData instanceData,
222 char *buf,
223 int bufSize,
224 int *errorCodePtr
225){
226 IncrblobChannel *p = (IncrblobChannel *)instanceData;
227 int nRead = bufSize; /* Number of bytes to read */
228 int nBlob; /* Total size of the blob */
229 int rc; /* sqlite error code */
230
231 nBlob = sqlite3_blob_bytes(p->pBlob);
232 if( (p->iSeek+nRead)>nBlob ){
233 nRead = nBlob-p->iSeek;
234 }
235 if( nRead<=0 ){
236 return 0;
237 }
238
239 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
240 if( rc!=SQLITE_OK ){
241 *errorCodePtr = rc;
242 return -1;
243 }
244
245 p->iSeek += nRead;
246 return nRead;
247}
248
danielk1977d04417962007-05-02 13:16:30 +0000249/*
250** Write data to an incremental blob channel.
251*/
danielk1977b4e9af92007-05-01 17:49:49 +0000252static int incrblobOutput(
253 ClientData instanceData,
254 CONST char *buf,
255 int toWrite,
256 int *errorCodePtr
257){
258 IncrblobChannel *p = (IncrblobChannel *)instanceData;
259 int nWrite = toWrite; /* Number of bytes to write */
260 int nBlob; /* Total size of the blob */
261 int rc; /* sqlite error code */
262
263 nBlob = sqlite3_blob_bytes(p->pBlob);
264 if( (p->iSeek+nWrite)>nBlob ){
265 *errorCodePtr = EINVAL;
266 return -1;
267 }
268 if( nWrite<=0 ){
269 return 0;
270 }
271
272 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
273 if( rc!=SQLITE_OK ){
274 *errorCodePtr = EIO;
275 return -1;
276 }
277
278 p->iSeek += nWrite;
279 return nWrite;
280}
281
282/*
283** Seek an incremental blob channel.
284*/
285static int incrblobSeek(
286 ClientData instanceData,
287 long offset,
288 int seekMode,
289 int *errorCodePtr
290){
291 IncrblobChannel *p = (IncrblobChannel *)instanceData;
292
293 switch( seekMode ){
294 case SEEK_SET:
295 p->iSeek = offset;
296 break;
297 case SEEK_CUR:
298 p->iSeek += offset;
299 break;
300 case SEEK_END:
301 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
302 break;
303
304 default: assert(!"Bad seekMode");
305 }
306
307 return p->iSeek;
308}
309
310
311static void incrblobWatch(ClientData instanceData, int mode){
312 /* NO-OP */
313}
314static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
315 return TCL_ERROR;
316}
317
318static Tcl_ChannelType IncrblobChannelType = {
319 "incrblob", /* typeName */
320 TCL_CHANNEL_VERSION_2, /* version */
321 incrblobClose, /* closeProc */
322 incrblobInput, /* inputProc */
323 incrblobOutput, /* outputProc */
324 incrblobSeek, /* seekProc */
325 0, /* setOptionProc */
326 0, /* getOptionProc */
327 incrblobWatch, /* watchProc (this is a no-op) */
328 incrblobHandle, /* getHandleProc (always returns error) */
329 0, /* close2Proc */
330 0, /* blockModeProc */
331 0, /* flushProc */
332 0, /* handlerProc */
333 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000334};
335
336/*
337** Create a new incrblob channel.
338*/
339static int createIncrblobChannel(
340 Tcl_Interp *interp,
341 SqliteDb *pDb,
342 const char *zDb,
343 const char *zTable,
344 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000345 sqlite_int64 iRow,
346 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000347){
348 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000349 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000350 sqlite3_blob *pBlob;
351 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000352 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000353
354 /* This variable is used to name the channels: "incrblob_[incr count]" */
355 static int count = 0;
356 char zChannel[64];
357
danielk19778cbadb02007-05-03 16:31:26 +0000358 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000359 if( rc!=SQLITE_OK ){
360 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
361 return TCL_ERROR;
362 }
363
364 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
365 p->iSeek = 0;
366 p->pBlob = pBlob;
367
drh5bb3eb92007-05-04 13:15:55 +0000368 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000369 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
370 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000371
danielk1977d04417962007-05-02 13:16:30 +0000372 /* Link the new channel into the SqliteDb.pIncrblob list. */
373 p->pNext = pDb->pIncrblob;
374 p->pPrev = 0;
375 if( p->pNext ){
376 p->pNext->pPrev = p;
377 }
378 pDb->pIncrblob = p;
379 p->pDb = pDb;
380
381 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000382 return TCL_OK;
383}
danielk197732a0d8b2007-05-04 19:03:02 +0000384#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
385 #define closeIncrblobChannels(pDb)
386#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000387
drh6d313162000-09-21 13:01:35 +0000388/*
drhd1e47332005-06-26 17:55:33 +0000389** Look at the script prefix in pCmd. We will be executing this script
390** after first appending one or more arguments. This routine analyzes
391** the script to see if it is safe to use Tcl_EvalObjv() on the script
392** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
393** faster.
394**
395** Scripts that are safe to use with Tcl_EvalObjv() consists of a
396** command name followed by zero or more arguments with no [...] or $
397** or {...} or ; to be seen anywhere. Most callback scripts consist
398** of just a single procedure name and they meet this requirement.
399*/
400static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
401 /* We could try to do something with Tcl_Parse(). But we will instead
402 ** just do a search for forbidden characters. If any of the forbidden
403 ** characters appear in pCmd, we will report the string as unsafe.
404 */
405 const char *z;
406 int n;
407 z = Tcl_GetStringFromObj(pCmd, &n);
408 while( n-- > 0 ){
409 int c = *(z++);
410 if( c=='$' || c=='[' || c==';' ) return 0;
411 }
412 return 1;
413}
414
415/*
416** Find an SqlFunc structure with the given name. Or create a new
417** one if an existing one cannot be found. Return a pointer to the
418** structure.
419*/
420static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
421 SqlFunc *p, *pNew;
422 int i;
drh4f21c4a2008-12-10 22:15:00 +0000423 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen30(zName) + 1 );
drhd1e47332005-06-26 17:55:33 +0000424 pNew->zName = (char*)&pNew[1];
425 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
426 pNew->zName[i] = 0;
427 for(p=pDb->pFunc; p; p=p->pNext){
428 if( strcmp(p->zName, pNew->zName)==0 ){
429 Tcl_Free((char*)pNew);
430 return p;
431 }
432 }
433 pNew->interp = pDb->interp;
434 pNew->pScript = 0;
435 pNew->pNext = pDb->pFunc;
436 pDb->pFunc = pNew;
437 return pNew;
438}
439
440/*
danc431fd52011-06-27 16:55:50 +0000441** Free a single SqlPreparedStmt object.
442*/
443static void dbFreeStmt(SqlPreparedStmt *pStmt){
444#ifdef SQLITE_TEST
445 if( sqlite3_sql(pStmt->pStmt)==0 ){
446 Tcl_Free((char *)pStmt->zSql);
447 }
448#endif
449 sqlite3_finalize(pStmt->pStmt);
450 Tcl_Free((char *)pStmt);
451}
452
453/*
drhfb7e7652005-01-24 00:28:42 +0000454** Finalize and free a list of prepared statements
455*/
danc431fd52011-06-27 16:55:50 +0000456static void flushStmtCache(SqliteDb *pDb){
drhfb7e7652005-01-24 00:28:42 +0000457 SqlPreparedStmt *pPreStmt;
danc431fd52011-06-27 16:55:50 +0000458 SqlPreparedStmt *pNext;
drhfb7e7652005-01-24 00:28:42 +0000459
danc431fd52011-06-27 16:55:50 +0000460 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
461 pNext = pPreStmt->pNext;
462 dbFreeStmt(pPreStmt);
drhfb7e7652005-01-24 00:28:42 +0000463 }
464 pDb->nStmt = 0;
465 pDb->stmtLast = 0;
danc431fd52011-06-27 16:55:50 +0000466 pDb->stmtList = 0;
drhfb7e7652005-01-24 00:28:42 +0000467}
468
469/*
drh895d7472004-08-20 16:02:39 +0000470** TCL calls this procedure when an sqlite3 database command is
471** deleted.
drh75897232000-05-29 14:26:00 +0000472*/
473static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000474 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000475 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000476 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000477 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000478 while( pDb->pFunc ){
479 SqlFunc *pFunc = pDb->pFunc;
480 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000481 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000482 Tcl_Free((char*)pFunc);
483 }
danielk19770202b292004-06-09 09:55:16 +0000484 while( pDb->pCollate ){
485 SqlCollate *pCollate = pDb->pCollate;
486 pDb->pCollate = pCollate->pNext;
487 Tcl_Free((char*)pCollate);
488 }
drhbec3f402000-08-04 13:49:02 +0000489 if( pDb->zBusy ){
490 Tcl_Free(pDb->zBusy);
491 }
drhb5a20d32003-04-23 12:25:23 +0000492 if( pDb->zTrace ){
493 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000494 }
drh19e2d372005-08-29 23:00:03 +0000495 if( pDb->zProfile ){
496 Tcl_Free(pDb->zProfile);
497 }
drhe22a3342003-04-22 20:30:37 +0000498 if( pDb->zAuth ){
499 Tcl_Free(pDb->zAuth);
500 }
danielk197755c45f22005-04-03 23:54:43 +0000501 if( pDb->zNull ){
502 Tcl_Free(pDb->zNull);
503 }
danielk197794eb6a12005-12-15 15:22:08 +0000504 if( pDb->pUpdateHook ){
505 Tcl_DecrRefCount(pDb->pUpdateHook);
506 }
danielk197771fd80b2005-12-16 06:54:01 +0000507 if( pDb->pRollbackHook ){
508 Tcl_DecrRefCount(pDb->pRollbackHook);
509 }
drh5def0842010-05-05 20:00:25 +0000510 if( pDb->pWalHook ){
511 Tcl_DecrRefCount(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000512 }
danielk197794eb6a12005-12-15 15:22:08 +0000513 if( pDb->pCollateNeeded ){
514 Tcl_DecrRefCount(pDb->pCollateNeeded);
515 }
drhbec3f402000-08-04 13:49:02 +0000516 Tcl_Free((char*)pDb);
517}
518
519/*
520** This routine is called when a database file is locked while trying
521** to execute SQL.
522*/
danielk19772a764eb2004-06-12 01:43:26 +0000523static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000524 SqliteDb *pDb = (SqliteDb*)cd;
525 int rc;
526 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000527
drh5bb3eb92007-05-04 13:15:55 +0000528 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000529 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000530 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
531 return 0;
532 }
533 return 1;
drh75897232000-05-29 14:26:00 +0000534}
535
drh26e4a8b2008-05-01 17:16:52 +0000536#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000537/*
danielk1977348bb5d2003-10-18 09:37:26 +0000538** This routine is invoked as the 'progress callback' for the database.
539*/
540static int DbProgressHandler(void *cd){
541 SqliteDb *pDb = (SqliteDb*)cd;
542 int rc;
543
544 assert( pDb->zProgress );
545 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
546 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
547 return 1;
548 }
549 return 0;
550}
drh26e4a8b2008-05-01 17:16:52 +0000551#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000552
drhd1167392006-01-23 13:00:35 +0000553#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000554/*
drhb5a20d32003-04-23 12:25:23 +0000555** This routine is called by the SQLite trace handler whenever a new
556** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000557*/
drhb5a20d32003-04-23 12:25:23 +0000558static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000559 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000560 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000561
drhb5a20d32003-04-23 12:25:23 +0000562 Tcl_DStringInit(&str);
563 Tcl_DStringAppend(&str, pDb->zTrace, -1);
564 Tcl_DStringAppendElement(&str, zSql);
565 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
566 Tcl_DStringFree(&str);
567 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000568}
drhd1167392006-01-23 13:00:35 +0000569#endif
drh0d1a6432003-04-03 15:46:04 +0000570
drhd1167392006-01-23 13:00:35 +0000571#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000572/*
drh19e2d372005-08-29 23:00:03 +0000573** This routine is called by the SQLite profile handler after a statement
574** SQL has executed. The TCL script in pDb->zProfile is evaluated.
575*/
576static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
577 SqliteDb *pDb = (SqliteDb*)cd;
578 Tcl_DString str;
579 char zTm[100];
580
581 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
582 Tcl_DStringInit(&str);
583 Tcl_DStringAppend(&str, pDb->zProfile, -1);
584 Tcl_DStringAppendElement(&str, zSql);
585 Tcl_DStringAppendElement(&str, zTm);
586 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
587 Tcl_DStringFree(&str);
588 Tcl_ResetResult(pDb->interp);
589}
drhd1167392006-01-23 13:00:35 +0000590#endif
drh19e2d372005-08-29 23:00:03 +0000591
592/*
drhaa940ea2004-01-15 02:44:03 +0000593** This routine is called when a transaction is committed. The
594** TCL script in pDb->zCommit is executed. If it returns non-zero or
595** if it throws an exception, the transaction is rolled back instead
596** of being committed.
597*/
598static int DbCommitHandler(void *cd){
599 SqliteDb *pDb = (SqliteDb*)cd;
600 int rc;
601
602 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
603 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
604 return 1;
605 }
606 return 0;
607}
608
danielk197771fd80b2005-12-16 06:54:01 +0000609static void DbRollbackHandler(void *clientData){
610 SqliteDb *pDb = (SqliteDb*)clientData;
611 assert(pDb->pRollbackHook);
612 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
613 Tcl_BackgroundError(pDb->interp);
614 }
615}
616
drh5def0842010-05-05 20:00:25 +0000617/*
618** This procedure handles wal_hook callbacks.
619*/
620static int DbWalHandler(
dan8d22a172010-04-19 18:03:51 +0000621 void *clientData,
622 sqlite3 *db,
623 const char *zDb,
624 int nEntry
625){
drh5def0842010-05-05 20:00:25 +0000626 int ret = SQLITE_OK;
dan8d22a172010-04-19 18:03:51 +0000627 Tcl_Obj *p;
628 SqliteDb *pDb = (SqliteDb*)clientData;
629 Tcl_Interp *interp = pDb->interp;
drh5def0842010-05-05 20:00:25 +0000630 assert(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000631
drh5def0842010-05-05 20:00:25 +0000632 p = Tcl_DuplicateObj(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000633 Tcl_IncrRefCount(p);
634 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
635 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
636 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
637 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
638 ){
639 Tcl_BackgroundError(interp);
640 }
641 Tcl_DecrRefCount(p);
642
643 return ret;
644}
645
drhbcf4f482009-03-27 12:44:35 +0000646#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000647static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
648 char zBuf[64];
649 sprintf(zBuf, "%d", iArg);
650 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
651 sprintf(zBuf, "%d", nArg);
652 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
653}
654#else
drhbcf4f482009-03-27 12:44:35 +0000655# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000656#endif
657
drh69910da2009-03-27 12:32:54 +0000658#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000659static void DbUnlockNotify(void **apArg, int nArg){
660 int i;
661 for(i=0; i<nArg; i++){
662 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
663 SqliteDb *pDb = (SqliteDb *)apArg[i];
664 setTestUnlockNotifyVars(pDb->interp, i, nArg);
665 assert( pDb->pUnlockNotify);
666 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
667 Tcl_DecrRefCount(pDb->pUnlockNotify);
668 pDb->pUnlockNotify = 0;
669 }
670}
drh69910da2009-03-27 12:32:54 +0000671#endif
danielk1977404ca072009-03-16 13:19:36 +0000672
danielk197794eb6a12005-12-15 15:22:08 +0000673static void DbUpdateHandler(
674 void *p,
675 int op,
676 const char *zDb,
677 const char *zTbl,
678 sqlite_int64 rowid
679){
680 SqliteDb *pDb = (SqliteDb *)p;
681 Tcl_Obj *pCmd;
682
683 assert( pDb->pUpdateHook );
684 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
685
686 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
687 Tcl_IncrRefCount(pCmd);
688 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
689 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
690 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
691 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
692 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
693 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
drhefdde162010-10-27 15:36:21 +0000694 Tcl_DecrRefCount(pCmd);
danielk197794eb6a12005-12-15 15:22:08 +0000695}
696
danielk19777cedc8d2004-06-10 10:50:08 +0000697static void tclCollateNeeded(
698 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000699 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000700 int enc,
701 const char *zName
702){
703 SqliteDb *pDb = (SqliteDb *)pCtx;
704 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
705 Tcl_IncrRefCount(pScript);
706 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
707 Tcl_EvalObjEx(pDb->interp, pScript, 0);
708 Tcl_DecrRefCount(pScript);
709}
710
drhaa940ea2004-01-15 02:44:03 +0000711/*
danielk19770202b292004-06-09 09:55:16 +0000712** This routine is called to evaluate an SQL collation function implemented
713** using TCL script.
714*/
715static int tclSqlCollate(
716 void *pCtx,
717 int nA,
718 const void *zA,
719 int nB,
720 const void *zB
721){
722 SqlCollate *p = (SqlCollate *)pCtx;
723 Tcl_Obj *pCmd;
724
725 pCmd = Tcl_NewStringObj(p->zScript, -1);
726 Tcl_IncrRefCount(pCmd);
727 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
728 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000729 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000730 Tcl_DecrRefCount(pCmd);
731 return (atoi(Tcl_GetStringResult(p->interp)));
732}
733
734/*
drhcabb0812002-09-14 13:47:32 +0000735** This routine is called to evaluate an SQL function implemented
736** using TCL script.
737*/
drhfb7e7652005-01-24 00:28:42 +0000738static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000739 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000740 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000741 int i;
742 int rc;
743
drhd1e47332005-06-26 17:55:33 +0000744 if( argc==0 ){
745 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
746 ** script object directly. This allows the TCL compiler to generate
747 ** bytecode for the command on the first invocation and thus make
748 ** subsequent invocations much faster. */
749 pCmd = p->pScript;
750 Tcl_IncrRefCount(pCmd);
751 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
752 Tcl_DecrRefCount(pCmd);
753 }else{
754 /* If there are arguments to the function, make a shallow copy of the
755 ** script object, lappend the arguments, then evaluate the copy.
756 **
757 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
758 ** The new Tcl_Obj contains pointers to the original list elements.
759 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
760 ** of the list to tclCmdNameType, that alternate representation will
761 ** be preserved and reused on the next invocation.
762 */
763 Tcl_Obj **aArg;
764 int nArg;
765 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
766 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
767 return;
768 }
769 pCmd = Tcl_NewListObj(nArg, aArg);
770 Tcl_IncrRefCount(pCmd);
771 for(i=0; i<argc; i++){
772 sqlite3_value *pIn = argv[i];
773 Tcl_Obj *pVal;
774
775 /* Set pVal to contain the i'th column of this row. */
776 switch( sqlite3_value_type(pIn) ){
777 case SQLITE_BLOB: {
778 int bytes = sqlite3_value_bytes(pIn);
779 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
780 break;
781 }
782 case SQLITE_INTEGER: {
783 sqlite_int64 v = sqlite3_value_int64(pIn);
784 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +0000785 pVal = Tcl_NewIntObj((int)v);
drhd1e47332005-06-26 17:55:33 +0000786 }else{
787 pVal = Tcl_NewWideIntObj(v);
788 }
789 break;
790 }
791 case SQLITE_FLOAT: {
792 double r = sqlite3_value_double(pIn);
793 pVal = Tcl_NewDoubleObj(r);
794 break;
795 }
796 case SQLITE_NULL: {
797 pVal = Tcl_NewStringObj("", 0);
798 break;
799 }
800 default: {
801 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000802 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000803 break;
804 }
805 }
806 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
807 if( rc ){
808 Tcl_DecrRefCount(pCmd);
809 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
810 return;
811 }
danielk197751ad0ec2004-05-24 12:39:02 +0000812 }
drhd1e47332005-06-26 17:55:33 +0000813 if( !p->useEvalObjv ){
814 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
815 ** is a list without a string representation. To prevent this from
816 ** happening, make sure pCmd has a valid string representation */
817 Tcl_GetString(pCmd);
818 }
819 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
820 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000821 }
danielk1977562e8d32005-05-20 09:40:55 +0000822
drhc7f269d2005-05-05 10:30:29 +0000823 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000824 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000825 }else{
drhc7f269d2005-05-05 10:30:29 +0000826 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
827 int n;
828 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000829 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000830 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000831 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000832 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000833 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000834 data = Tcl_GetByteArrayFromObj(pVar, &n);
835 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000836 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000837 Tcl_GetIntFromObj(0, pVar, &n);
838 sqlite3_result_int(context, n);
839 }else if( c=='d' && strcmp(zType,"double")==0 ){
840 double r;
841 Tcl_GetDoubleFromObj(0, pVar, &r);
842 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +0000843 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
844 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000845 Tcl_WideInt v;
846 Tcl_GetWideIntFromObj(0, pVar, &v);
847 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000848 }else{
danielk197700fd9572005-12-07 06:27:43 +0000849 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
850 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000851 }
drhcabb0812002-09-14 13:47:32 +0000852 }
853}
drh895d7472004-08-20 16:02:39 +0000854
drhe22a3342003-04-22 20:30:37 +0000855#ifndef SQLITE_OMIT_AUTHORIZATION
856/*
857** This is the authentication function. It appends the authentication
858** type code and the two arguments to zCmd[] then invokes the result
859** on the interpreter. The reply is examined to determine if the
860** authentication fails or succeeds.
861*/
862static int auth_callback(
863 void *pArg,
864 int code,
865 const char *zArg1,
866 const char *zArg2,
867 const char *zArg3,
868 const char *zArg4
869){
870 char *zCode;
871 Tcl_DString str;
872 int rc;
873 const char *zReply;
874 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +0000875 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +0000876
877 switch( code ){
878 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
879 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
880 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
881 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
882 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
883 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
884 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
885 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
886 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
887 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
888 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
889 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
890 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
891 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
892 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
893 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
894 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
895 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
896 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
897 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
898 case SQLITE_READ : zCode="SQLITE_READ"; break;
899 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
900 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
901 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000902 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
903 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000904 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000905 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000906 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000907 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
908 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000909 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +0000910 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drhe22a3342003-04-22 20:30:37 +0000911 default : zCode="????"; break;
912 }
913 Tcl_DStringInit(&str);
914 Tcl_DStringAppend(&str, pDb->zAuth, -1);
915 Tcl_DStringAppendElement(&str, zCode);
916 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
917 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
918 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
919 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
920 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
921 Tcl_DStringFree(&str);
922 zReply = Tcl_GetStringResult(pDb->interp);
923 if( strcmp(zReply,"SQLITE_OK")==0 ){
924 rc = SQLITE_OK;
925 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
926 rc = SQLITE_DENY;
927 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
928 rc = SQLITE_IGNORE;
929 }else{
930 rc = 999;
931 }
932 return rc;
933}
934#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000935
936/*
danielk1977ef2cb632004-05-29 02:37:19 +0000937** zText is a pointer to text obtained via an sqlite3_result_text()
938** or similar interface. This routine returns a Tcl string object,
939** reference count set to 0, containing the text. If a translation
940** between iso8859 and UTF-8 is required, it is preformed.
941*/
942static Tcl_Obj *dbTextToObj(char const *zText){
943 Tcl_Obj *pVal;
944#ifdef UTF_TRANSLATION_NEEDED
945 Tcl_DString dCol;
946 Tcl_DStringInit(&dCol);
947 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
948 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
949 Tcl_DStringFree(&dCol);
950#else
951 pVal = Tcl_NewStringObj(zText, -1);
952#endif
953 return pVal;
954}
955
956/*
tpoindex1067fe12004-12-17 15:41:11 +0000957** This routine reads a line of text from FILE in, stores
958** the text in memory obtained from malloc() and returns a pointer
959** to the text. NULL is returned at end of file, or if malloc()
960** fails.
961**
962** The interface is like "readline" but no command-line editing
963** is done.
964**
965** copied from shell.c from '.import' command
966*/
967static char *local_getline(char *zPrompt, FILE *in){
968 char *zLine;
969 int nLine;
970 int n;
971 int eol;
972
973 nLine = 100;
974 zLine = malloc( nLine );
975 if( zLine==0 ) return 0;
976 n = 0;
977 eol = 0;
978 while( !eol ){
979 if( n+100>nLine ){
980 nLine = nLine*2 + 100;
981 zLine = realloc(zLine, nLine);
982 if( zLine==0 ) return 0;
983 }
984 if( fgets(&zLine[n], nLine - n, in)==0 ){
985 if( n==0 ){
986 free(zLine);
987 return 0;
988 }
989 zLine[n] = 0;
990 eol = 1;
991 break;
992 }
993 while( zLine[n] ){ n++; }
994 if( n>0 && zLine[n-1]=='\n' ){
995 n--;
996 zLine[n] = 0;
997 eol = 1;
998 }
999 }
1000 zLine = realloc( zLine, n+1 );
1001 return zLine;
1002}
1003
danielk19778e556522007-11-13 10:30:24 +00001004
1005/*
dan4a4c11a2009-10-06 14:59:02 +00001006** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +00001007**
dan4a4c11a2009-10-06 14:59:02 +00001008** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +00001009**
dan4a4c11a2009-10-06 14:59:02 +00001010** It is invoked after evaluating the script SCRIPT to commit or rollback
1011** the transaction or savepoint opened by the [transaction] command.
1012*/
1013static int DbTransPostCmd(
1014 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1015 Tcl_Interp *interp, /* Tcl interpreter */
1016 int result /* Result of evaluating SCRIPT */
1017){
1018 static const char *azEnd[] = {
1019 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1020 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1021 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1022 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1023 };
1024 SqliteDb *pDb = (SqliteDb*)data[0];
1025 int rc = result;
1026 const char *zEnd;
1027
1028 pDb->nTransaction--;
1029 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1030
1031 pDb->disableAuth++;
1032 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1033 /* This is a tricky scenario to handle. The most likely cause of an
1034 ** error is that the exec() above was an attempt to commit the
1035 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1036 ** that an IO-error has occured. In either case, throw a Tcl exception
1037 ** and try to rollback the transaction.
1038 **
1039 ** But it could also be that the user executed one or more BEGIN,
1040 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1041 ** this method's logic. Not clear how this would be best handled.
1042 */
1043 if( rc!=TCL_ERROR ){
1044 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
1045 rc = TCL_ERROR;
1046 }
1047 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1048 }
1049 pDb->disableAuth--;
1050
1051 return rc;
1052}
1053
1054/*
danc431fd52011-06-27 16:55:50 +00001055** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1056** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1057** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1058** on whether or not the [db_use_legacy_prepare] command has been used to
1059** configure the connection.
1060*/
1061static int dbPrepare(
1062 SqliteDb *pDb, /* Database object */
1063 const char *zSql, /* SQL to compile */
1064 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1065 const char **pzOut /* OUT: Pointer to next SQL statement */
1066){
1067#ifdef SQLITE_TEST
1068 if( pDb->bLegacyPrepare ){
1069 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1070 }
1071#endif
1072 return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut);
1073}
1074
1075/*
dan4a4c11a2009-10-06 14:59:02 +00001076** Search the cache for a prepared-statement object that implements the
1077** first SQL statement in the buffer pointed to by parameter zIn. If
1078** no such prepared-statement can be found, allocate and prepare a new
1079** one. In either case, bind the current values of the relevant Tcl
1080** variables to any $var, :var or @var variables in the statement. Before
1081** returning, set *ppPreStmt to point to the prepared-statement object.
1082**
1083** Output parameter *pzOut is set to point to the next SQL statement in
1084** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1085** next statement.
1086**
1087** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1088** and an error message loaded into interpreter pDb->interp.
1089*/
1090static int dbPrepareAndBind(
1091 SqliteDb *pDb, /* Database object */
1092 char const *zIn, /* SQL to compile */
1093 char const **pzOut, /* OUT: Pointer to next SQL statement */
1094 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1095){
1096 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
1097 sqlite3_stmt *pStmt; /* Prepared statement object */
1098 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1099 int nSql; /* Length of zSql in bytes */
1100 int nVar; /* Number of variables in statement */
1101 int iParm = 0; /* Next free entry in apParm */
1102 int i;
1103 Tcl_Interp *interp = pDb->interp;
1104
1105 *ppPreStmt = 0;
1106
1107 /* Trim spaces from the start of zSql and calculate the remaining length. */
1108 while( isspace(zSql[0]) ){ zSql++; }
1109 nSql = strlen30(zSql);
1110
1111 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1112 int n = pPreStmt->nSql;
1113 if( nSql>=n
1114 && memcmp(pPreStmt->zSql, zSql, n)==0
1115 && (zSql[n]==0 || zSql[n-1]==';')
1116 ){
1117 pStmt = pPreStmt->pStmt;
1118 *pzOut = &zSql[pPreStmt->nSql];
1119
1120 /* When a prepared statement is found, unlink it from the
1121 ** cache list. It will later be added back to the beginning
1122 ** of the cache list in order to implement LRU replacement.
1123 */
1124 if( pPreStmt->pPrev ){
1125 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1126 }else{
1127 pDb->stmtList = pPreStmt->pNext;
1128 }
1129 if( pPreStmt->pNext ){
1130 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1131 }else{
1132 pDb->stmtLast = pPreStmt->pPrev;
1133 }
1134 pDb->nStmt--;
1135 nVar = sqlite3_bind_parameter_count(pStmt);
1136 break;
1137 }
1138 }
1139
1140 /* If no prepared statement was found. Compile the SQL text. Also allocate
1141 ** a new SqlPreparedStmt structure. */
1142 if( pPreStmt==0 ){
1143 int nByte;
1144
danc431fd52011-06-27 16:55:50 +00001145 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
dan4a4c11a2009-10-06 14:59:02 +00001146 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1147 return TCL_ERROR;
1148 }
1149 if( pStmt==0 ){
1150 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1151 /* A compile-time error in the statement. */
1152 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1153 return TCL_ERROR;
1154 }else{
1155 /* The statement was a no-op. Continue to the next statement
1156 ** in the SQL string.
1157 */
1158 return TCL_OK;
1159 }
1160 }
1161
1162 assert( pPreStmt==0 );
1163 nVar = sqlite3_bind_parameter_count(pStmt);
1164 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1165 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1166 memset(pPreStmt, 0, nByte);
1167
1168 pPreStmt->pStmt = pStmt;
1169 pPreStmt->nSql = (*pzOut - zSql);
1170 pPreStmt->zSql = sqlite3_sql(pStmt);
1171 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
danc431fd52011-06-27 16:55:50 +00001172#ifdef SQLITE_TEST
1173 if( pPreStmt->zSql==0 ){
1174 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1175 memcpy(zCopy, zSql, pPreStmt->nSql);
1176 zCopy[pPreStmt->nSql] = '\0';
1177 pPreStmt->zSql = zCopy;
1178 }
1179#endif
dan4a4c11a2009-10-06 14:59:02 +00001180 }
1181 assert( pPreStmt );
1182 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1183 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1184
1185 /* Bind values to parameters that begin with $ or : */
1186 for(i=1; i<=nVar; i++){
1187 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1188 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1189 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1190 if( pVar ){
1191 int n;
1192 u8 *data;
1193 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1194 char c = zType[0];
1195 if( zVar[0]=='@' ||
1196 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1197 /* Load a BLOB type if the Tcl variable is a bytearray and
1198 ** it has no string representation or the host
1199 ** parameter name begins with "@". */
1200 data = Tcl_GetByteArrayFromObj(pVar, &n);
1201 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1202 Tcl_IncrRefCount(pVar);
1203 pPreStmt->apParm[iParm++] = pVar;
1204 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1205 Tcl_GetIntFromObj(interp, pVar, &n);
1206 sqlite3_bind_int(pStmt, i, n);
1207 }else if( c=='d' && strcmp(zType,"double")==0 ){
1208 double r;
1209 Tcl_GetDoubleFromObj(interp, pVar, &r);
1210 sqlite3_bind_double(pStmt, i, r);
1211 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1212 (c=='i' && strcmp(zType,"int")==0) ){
1213 Tcl_WideInt v;
1214 Tcl_GetWideIntFromObj(interp, pVar, &v);
1215 sqlite3_bind_int64(pStmt, i, v);
1216 }else{
1217 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1218 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1219 Tcl_IncrRefCount(pVar);
1220 pPreStmt->apParm[iParm++] = pVar;
1221 }
1222 }else{
1223 sqlite3_bind_null(pStmt, i);
1224 }
1225 }
1226 }
1227 pPreStmt->nParm = iParm;
1228 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001229
dan4a4c11a2009-10-06 14:59:02 +00001230 return TCL_OK;
1231}
1232
dan4a4c11a2009-10-06 14:59:02 +00001233/*
1234** Release a statement reference obtained by calling dbPrepareAndBind().
1235** There should be exactly one call to this function for each call to
1236** dbPrepareAndBind().
1237**
1238** If the discard parameter is non-zero, then the statement is deleted
1239** immediately. Otherwise it is added to the LRU list and may be returned
1240** by a subsequent call to dbPrepareAndBind().
1241*/
1242static void dbReleaseStmt(
1243 SqliteDb *pDb, /* Database handle */
1244 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1245 int discard /* True to delete (not cache) the pPreStmt */
1246){
1247 int i;
1248
1249 /* Free the bound string and blob parameters */
1250 for(i=0; i<pPreStmt->nParm; i++){
1251 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1252 }
1253 pPreStmt->nParm = 0;
1254
1255 if( pDb->maxStmt<=0 || discard ){
1256 /* If the cache is turned off, deallocated the statement */
danc431fd52011-06-27 16:55:50 +00001257 dbFreeStmt(pPreStmt);
dan4a4c11a2009-10-06 14:59:02 +00001258 }else{
1259 /* Add the prepared statement to the beginning of the cache list. */
1260 pPreStmt->pNext = pDb->stmtList;
1261 pPreStmt->pPrev = 0;
1262 if( pDb->stmtList ){
1263 pDb->stmtList->pPrev = pPreStmt;
1264 }
1265 pDb->stmtList = pPreStmt;
1266 if( pDb->stmtLast==0 ){
1267 assert( pDb->nStmt==0 );
1268 pDb->stmtLast = pPreStmt;
1269 }else{
1270 assert( pDb->nStmt>0 );
1271 }
1272 pDb->nStmt++;
1273
1274 /* If we have too many statement in cache, remove the surplus from
1275 ** the end of the cache list. */
1276 while( pDb->nStmt>pDb->maxStmt ){
danc431fd52011-06-27 16:55:50 +00001277 SqlPreparedStmt *pLast = pDb->stmtLast;
1278 pDb->stmtLast = pLast->pPrev;
dan4a4c11a2009-10-06 14:59:02 +00001279 pDb->stmtLast->pNext = 0;
1280 pDb->nStmt--;
danc431fd52011-06-27 16:55:50 +00001281 dbFreeStmt(pLast);
dan4a4c11a2009-10-06 14:59:02 +00001282 }
1283 }
1284}
1285
1286/*
1287** Structure used with dbEvalXXX() functions:
1288**
1289** dbEvalInit()
1290** dbEvalStep()
1291** dbEvalFinalize()
1292** dbEvalRowInfo()
1293** dbEvalColumnValue()
1294*/
1295typedef struct DbEvalContext DbEvalContext;
1296struct DbEvalContext {
1297 SqliteDb *pDb; /* Database handle */
1298 Tcl_Obj *pSql; /* Object holding string zSql */
1299 const char *zSql; /* Remaining SQL to execute */
1300 SqlPreparedStmt *pPreStmt; /* Current statement */
1301 int nCol; /* Number of columns returned by pStmt */
1302 Tcl_Obj *pArray; /* Name of array variable */
1303 Tcl_Obj **apColName; /* Array of column names */
1304};
1305
1306/*
1307** Release any cache of column names currently held as part of
1308** the DbEvalContext structure passed as the first argument.
1309*/
1310static void dbReleaseColumnNames(DbEvalContext *p){
1311 if( p->apColName ){
1312 int i;
1313 for(i=0; i<p->nCol; i++){
1314 Tcl_DecrRefCount(p->apColName[i]);
1315 }
1316 Tcl_Free((char *)p->apColName);
1317 p->apColName = 0;
1318 }
1319 p->nCol = 0;
1320}
1321
1322/*
1323** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001324**
1325** If pArray is not NULL, then it contains the name of a Tcl array
1326** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001327** the names of the columns returned by the statement as part of each
1328** call to dbEvalStep(), in order from left to right. e.g. if the names
1329** of the returned columns are a, b and c, it does the equivalent of the
1330** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001331**
1332** set ${pArray}(*) {a b c}
1333*/
dan4a4c11a2009-10-06 14:59:02 +00001334static void dbEvalInit(
1335 DbEvalContext *p, /* Pointer to structure to initialize */
1336 SqliteDb *pDb, /* Database handle */
1337 Tcl_Obj *pSql, /* Object containing SQL script */
1338 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001339){
dan4a4c11a2009-10-06 14:59:02 +00001340 memset(p, 0, sizeof(DbEvalContext));
1341 p->pDb = pDb;
1342 p->zSql = Tcl_GetString(pSql);
1343 p->pSql = pSql;
1344 Tcl_IncrRefCount(pSql);
1345 if( pArray ){
1346 p->pArray = pArray;
1347 Tcl_IncrRefCount(pArray);
1348 }
1349}
danielk19778e556522007-11-13 10:30:24 +00001350
dan4a4c11a2009-10-06 14:59:02 +00001351/*
1352** Obtain information about the row that the DbEvalContext passed as the
1353** first argument currently points to.
1354*/
1355static void dbEvalRowInfo(
1356 DbEvalContext *p, /* Evaluation context */
1357 int *pnCol, /* OUT: Number of column names */
1358 Tcl_Obj ***papColName /* OUT: Array of column names */
1359){
danielk19778e556522007-11-13 10:30:24 +00001360 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001361 if( 0==p->apColName ){
1362 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1363 int i; /* Iterator variable */
1364 int nCol; /* Number of columns returned by pStmt */
1365 Tcl_Obj **apColName = 0; /* Array of column names */
1366
1367 p->nCol = nCol = sqlite3_column_count(pStmt);
1368 if( nCol>0 && (papColName || p->pArray) ){
1369 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1370 for(i=0; i<nCol; i++){
1371 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1372 Tcl_IncrRefCount(apColName[i]);
1373 }
1374 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001375 }
1376
1377 /* If results are being stored in an array variable, then create
1378 ** the array(*) entry for that array
1379 */
dan4a4c11a2009-10-06 14:59:02 +00001380 if( p->pArray ){
1381 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001382 Tcl_Obj *pColList = Tcl_NewObj();
1383 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001384
danielk19778e556522007-11-13 10:30:24 +00001385 for(i=0; i<nCol; i++){
1386 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1387 }
1388 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001389 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001390 Tcl_DecrRefCount(pStar);
1391 }
danielk19778e556522007-11-13 10:30:24 +00001392 }
1393
dan4a4c11a2009-10-06 14:59:02 +00001394 if( papColName ){
1395 *papColName = p->apColName;
1396 }
1397 if( pnCol ){
1398 *pnCol = p->nCol;
1399 }
1400}
1401
1402/*
1403** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1404** returned, then an error message is stored in the interpreter before
1405** returning.
1406**
1407** A return value of TCL_OK means there is a row of data available. The
1408** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1409** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1410** is returned, then the SQL script has finished executing and there are
1411** no further rows available. This is similar to SQLITE_DONE.
1412*/
1413static int dbEvalStep(DbEvalContext *p){
danc431fd52011-06-27 16:55:50 +00001414 const char *zPrevSql = 0; /* Previous value of p->zSql */
1415
dan4a4c11a2009-10-06 14:59:02 +00001416 while( p->zSql[0] || p->pPreStmt ){
1417 int rc;
1418 if( p->pPreStmt==0 ){
danc431fd52011-06-27 16:55:50 +00001419 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
dan4a4c11a2009-10-06 14:59:02 +00001420 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1421 if( rc!=TCL_OK ) return rc;
1422 }else{
1423 int rcs;
1424 SqliteDb *pDb = p->pDb;
1425 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1426 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1427
1428 rcs = sqlite3_step(pStmt);
1429 if( rcs==SQLITE_ROW ){
1430 return TCL_OK;
1431 }
1432 if( p->pArray ){
1433 dbEvalRowInfo(p, 0, 0);
1434 }
1435 rcs = sqlite3_reset(pStmt);
1436
1437 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1438 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001439 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
dan4a4c11a2009-10-06 14:59:02 +00001440 dbReleaseColumnNames(p);
1441 p->pPreStmt = 0;
1442
1443 if( rcs!=SQLITE_OK ){
1444 /* If a run-time error occurs, report the error and stop reading
1445 ** the SQL. */
dan4a4c11a2009-10-06 14:59:02 +00001446 dbReleaseStmt(pDb, pPreStmt, 1);
danc431fd52011-06-27 16:55:50 +00001447#if SQLITE_TEST
1448 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1449 /* If the runtime error was an SQLITE_SCHEMA, and the database
1450 ** handle is configured to use the legacy sqlite3_prepare()
1451 ** interface, retry prepare()/step() on the same SQL statement.
1452 ** This only happens once. If there is a second SQLITE_SCHEMA
1453 ** error, the error will be returned to the caller. */
1454 p->zSql = zPrevSql;
1455 continue;
1456 }
1457#endif
1458 Tcl_SetObjResult(pDb->interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
dan4a4c11a2009-10-06 14:59:02 +00001459 return TCL_ERROR;
1460 }else{
1461 dbReleaseStmt(pDb, pPreStmt, 0);
1462 }
1463 }
1464 }
1465
1466 /* Finished */
1467 return TCL_BREAK;
1468}
1469
1470/*
1471** Free all resources currently held by the DbEvalContext structure passed
1472** as the first argument. There should be exactly one call to this function
1473** for each call to dbEvalInit().
1474*/
1475static void dbEvalFinalize(DbEvalContext *p){
1476 if( p->pPreStmt ){
1477 sqlite3_reset(p->pPreStmt->pStmt);
1478 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1479 p->pPreStmt = 0;
1480 }
1481 if( p->pArray ){
1482 Tcl_DecrRefCount(p->pArray);
1483 p->pArray = 0;
1484 }
1485 Tcl_DecrRefCount(p->pSql);
1486 dbReleaseColumnNames(p);
1487}
1488
1489/*
1490** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1491** the value for the iCol'th column of the row currently pointed to by
1492** the DbEvalContext structure passed as the first argument.
1493*/
1494static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1495 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1496 switch( sqlite3_column_type(pStmt, iCol) ){
1497 case SQLITE_BLOB: {
1498 int bytes = sqlite3_column_bytes(pStmt, iCol);
1499 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1500 if( !zBlob ) bytes = 0;
1501 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1502 }
1503 case SQLITE_INTEGER: {
1504 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1505 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +00001506 return Tcl_NewIntObj((int)v);
dan4a4c11a2009-10-06 14:59:02 +00001507 }else{
1508 return Tcl_NewWideIntObj(v);
1509 }
1510 }
1511 case SQLITE_FLOAT: {
1512 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1513 }
1514 case SQLITE_NULL: {
1515 return dbTextToObj(p->pDb->zNull);
1516 }
1517 }
1518
1519 return dbTextToObj((char *)sqlite3_column_text(pStmt, iCol));
1520}
1521
1522/*
1523** If using Tcl version 8.6 or greater, use the NR functions to avoid
1524** recursive evalution of scripts by the [db eval] and [db trans]
1525** commands. Even if the headers used while compiling the extension
1526** are 8.6 or newer, the code still tests the Tcl version at runtime.
1527** This allows stubs-enabled builds to be used with older Tcl libraries.
1528*/
1529#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001530# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001531static int DbUseNre(void){
1532 int major, minor;
1533 Tcl_GetVersion(&major, &minor, 0, 0);
1534 return( (major==8 && minor>=6) || major>8 );
1535}
1536#else
1537/*
1538** Compiling using headers earlier than 8.6. In this case NR cannot be
1539** used, so DbUseNre() to always return zero. Add #defines for the other
1540** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1541** even though the only invocations of them are within conditional blocks
1542** of the form:
1543**
1544** if( DbUseNre() ) { ... }
1545*/
drha2c8a952009-10-13 18:38:34 +00001546# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001547# define DbUseNre() 0
1548# define Tcl_NRAddCallback(a,b,c,d,e,f) 0
1549# define Tcl_NREvalObj(a,b,c) 0
1550# define Tcl_NRCreateCommand(a,b,c,d,e,f) 0
1551#endif
1552
1553/*
1554** This function is part of the implementation of the command:
1555**
1556** $db eval SQL ?ARRAYNAME? SCRIPT
1557*/
1558static int DbEvalNextCmd(
1559 ClientData data[], /* data[0] is the (DbEvalContext*) */
1560 Tcl_Interp *interp, /* Tcl interpreter */
1561 int result /* Result so far */
1562){
1563 int rc = result; /* Return code */
1564
1565 /* The first element of the data[] array is a pointer to a DbEvalContext
1566 ** structure allocated using Tcl_Alloc(). The second element of data[]
1567 ** is a pointer to a Tcl_Obj containing the script to run for each row
1568 ** returned by the queries encapsulated in data[0]. */
1569 DbEvalContext *p = (DbEvalContext *)data[0];
1570 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1571 Tcl_Obj *pArray = p->pArray;
1572
1573 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1574 int i;
1575 int nCol;
1576 Tcl_Obj **apColName;
1577 dbEvalRowInfo(p, &nCol, &apColName);
1578 for(i=0; i<nCol; i++){
1579 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1580 if( pArray==0 ){
1581 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1582 }else{
1583 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1584 }
1585 }
1586
1587 /* The required interpreter variables are now populated with the data
1588 ** from the current row. If using NRE, schedule callbacks to evaluate
1589 ** script pScript, then to invoke this function again to fetch the next
1590 ** row (or clean up if there is no next row or the script throws an
1591 ** exception). After scheduling the callbacks, return control to the
1592 ** caller.
1593 **
1594 ** If not using NRE, evaluate pScript directly and continue with the
1595 ** next iteration of this while(...) loop. */
1596 if( DbUseNre() ){
1597 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1598 return Tcl_NREvalObj(interp, pScript, 0);
1599 }else{
1600 rc = Tcl_EvalObjEx(interp, pScript, 0);
1601 }
1602 }
1603
1604 Tcl_DecrRefCount(pScript);
1605 dbEvalFinalize(p);
1606 Tcl_Free((char *)p);
1607
1608 if( rc==TCL_OK || rc==TCL_BREAK ){
1609 Tcl_ResetResult(interp);
1610 rc = TCL_OK;
1611 }
1612 return rc;
danielk19778e556522007-11-13 10:30:24 +00001613}
1614
tpoindex1067fe12004-12-17 15:41:11 +00001615/*
drh75897232000-05-29 14:26:00 +00001616** The "sqlite" command below creates a new Tcl command for each
1617** connection it opens to an SQLite database. This routine is invoked
1618** whenever one of those connection-specific commands is executed
1619** in Tcl. For example, if you run Tcl code like this:
1620**
drh9bb575f2004-09-06 17:24:11 +00001621** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001622** db1 close
1623**
1624** The first command opens a connection to the "my_database" database
1625** and calls that connection "db1". The second command causes this
1626** subroutine to be invoked.
1627*/
drh6d313162000-09-21 13:01:35 +00001628static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001629 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001630 int choice;
drh22fbcb82004-02-01 01:22:50 +00001631 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001632 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001633 "authorizer", "backup", "busy",
1634 "cache", "changes", "close",
1635 "collate", "collation_needed", "commit_hook",
1636 "complete", "copy", "enable_load_extension",
1637 "errorcode", "eval", "exists",
1638 "function", "incrblob", "interrupt",
drh833bf962010-04-28 14:42:19 +00001639 "last_insert_rowid", "nullvalue", "onecolumn",
1640 "profile", "progress", "rekey",
1641 "restore", "rollback_hook", "status",
1642 "timeout", "total_changes", "trace",
1643 "transaction", "unlock_notify", "update_hook",
1644 "version", "wal_hook", 0
drh6d313162000-09-21 13:01:35 +00001645 };
drh411995d2002-06-25 19:31:18 +00001646 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001647 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1648 DB_CACHE, DB_CHANGES, DB_CLOSE,
1649 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1650 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1651 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1652 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
drh833bf962010-04-28 14:42:19 +00001653 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
1654 DB_PROFILE, DB_PROGRESS, DB_REKEY,
1655 DB_RESTORE, DB_ROLLBACK_HOOK, DB_STATUS,
1656 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
1657 DB_TRANSACTION, DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK,
1658 DB_VERSION, DB_WAL_HOOK
drh6d313162000-09-21 13:01:35 +00001659 };
tpoindex1067fe12004-12-17 15:41:11 +00001660 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001661
1662 if( objc<2 ){
1663 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001664 return TCL_ERROR;
1665 }
drh411995d2002-06-25 19:31:18 +00001666 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001667 return TCL_ERROR;
1668 }
1669
drh411995d2002-06-25 19:31:18 +00001670 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001671
drhe22a3342003-04-22 20:30:37 +00001672 /* $db authorizer ?CALLBACK?
1673 **
1674 ** Invoke the given callback to authorize each SQL operation as it is
1675 ** compiled. 5 arguments are appended to the callback before it is
1676 ** invoked:
1677 **
1678 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1679 ** (2) First descriptive name (depends on authorization type)
1680 ** (3) Second descriptive name
1681 ** (4) Name of the database (ex: "main", "temp")
1682 ** (5) Name of trigger that is doing the access
1683 **
1684 ** The callback should return on of the following strings: SQLITE_OK,
1685 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1686 **
1687 ** If this method is invoked with no arguments, the current authorization
1688 ** callback string is returned.
1689 */
1690 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001691#ifdef SQLITE_OMIT_AUTHORIZATION
1692 Tcl_AppendResult(interp, "authorization not available in this build", 0);
1693 return TCL_ERROR;
1694#else
drhe22a3342003-04-22 20:30:37 +00001695 if( objc>3 ){
1696 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001697 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001698 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001699 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +00001700 Tcl_AppendResult(interp, pDb->zAuth, 0);
1701 }
1702 }else{
1703 char *zAuth;
1704 int len;
1705 if( pDb->zAuth ){
1706 Tcl_Free(pDb->zAuth);
1707 }
1708 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1709 if( zAuth && len>0 ){
1710 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001711 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001712 }else{
1713 pDb->zAuth = 0;
1714 }
drhe22a3342003-04-22 20:30:37 +00001715 if( pDb->zAuth ){
1716 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001717 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +00001718 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001719 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001720 }
drhe22a3342003-04-22 20:30:37 +00001721 }
drh1211de32004-07-26 12:24:22 +00001722#endif
drhe22a3342003-04-22 20:30:37 +00001723 break;
1724 }
1725
drhdc2c4912009-02-04 22:46:47 +00001726 /* $db backup ?DATABASE? FILENAME
1727 **
1728 ** Open or create a database file named FILENAME. Transfer the
1729 ** content of local database DATABASE (default: "main") into the
1730 ** FILENAME database.
1731 */
1732 case DB_BACKUP: {
1733 const char *zDestFile;
1734 const char *zSrcDb;
1735 sqlite3 *pDest;
1736 sqlite3_backup *pBackup;
1737
1738 if( objc==3 ){
1739 zSrcDb = "main";
1740 zDestFile = Tcl_GetString(objv[2]);
1741 }else if( objc==4 ){
1742 zSrcDb = Tcl_GetString(objv[2]);
1743 zDestFile = Tcl_GetString(objv[3]);
1744 }else{
1745 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1746 return TCL_ERROR;
1747 }
1748 rc = sqlite3_open(zDestFile, &pDest);
1749 if( rc!=SQLITE_OK ){
1750 Tcl_AppendResult(interp, "cannot open target database: ",
1751 sqlite3_errmsg(pDest), (char*)0);
1752 sqlite3_close(pDest);
1753 return TCL_ERROR;
1754 }
1755 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1756 if( pBackup==0 ){
1757 Tcl_AppendResult(interp, "backup failed: ",
1758 sqlite3_errmsg(pDest), (char*)0);
1759 sqlite3_close(pDest);
1760 return TCL_ERROR;
1761 }
1762 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1763 sqlite3_backup_finish(pBackup);
1764 if( rc==SQLITE_DONE ){
1765 rc = TCL_OK;
1766 }else{
1767 Tcl_AppendResult(interp, "backup failed: ",
1768 sqlite3_errmsg(pDest), (char*)0);
1769 rc = TCL_ERROR;
1770 }
1771 sqlite3_close(pDest);
1772 break;
1773 }
1774
drhbec3f402000-08-04 13:49:02 +00001775 /* $db busy ?CALLBACK?
1776 **
1777 ** Invoke the given callback if an SQL statement attempts to open
1778 ** a locked database file.
1779 */
drh6d313162000-09-21 13:01:35 +00001780 case DB_BUSY: {
1781 if( objc>3 ){
1782 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001783 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001784 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001785 if( pDb->zBusy ){
1786 Tcl_AppendResult(interp, pDb->zBusy, 0);
1787 }
1788 }else{
drh6d313162000-09-21 13:01:35 +00001789 char *zBusy;
1790 int len;
drhbec3f402000-08-04 13:49:02 +00001791 if( pDb->zBusy ){
1792 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001793 }
drh6d313162000-09-21 13:01:35 +00001794 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1795 if( zBusy && len>0 ){
1796 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001797 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001798 }else{
1799 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001800 }
1801 if( pDb->zBusy ){
1802 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001803 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001804 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001805 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001806 }
1807 }
drh6d313162000-09-21 13:01:35 +00001808 break;
1809 }
drhbec3f402000-08-04 13:49:02 +00001810
drhfb7e7652005-01-24 00:28:42 +00001811 /* $db cache flush
1812 ** $db cache size n
1813 **
1814 ** Flush the prepared statement cache, or set the maximum number of
1815 ** cached statements.
1816 */
1817 case DB_CACHE: {
1818 char *subCmd;
1819 int n;
1820
1821 if( objc<=2 ){
1822 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1823 return TCL_ERROR;
1824 }
1825 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1826 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1827 if( objc!=3 ){
1828 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1829 return TCL_ERROR;
1830 }else{
1831 flushStmtCache( pDb );
1832 }
1833 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1834 if( objc!=4 ){
1835 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1836 return TCL_ERROR;
1837 }else{
1838 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1839 Tcl_AppendResult( interp, "cannot convert \"",
1840 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1841 return TCL_ERROR;
1842 }else{
1843 if( n<0 ){
1844 flushStmtCache( pDb );
1845 n = 0;
1846 }else if( n>MAX_PREPARED_STMTS ){
1847 n = MAX_PREPARED_STMTS;
1848 }
1849 pDb->maxStmt = n;
1850 }
1851 }
1852 }else{
1853 Tcl_AppendResult( interp, "bad option \"",
danielk1977191fadc2007-10-23 08:17:48 +00001854 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
drhfb7e7652005-01-24 00:28:42 +00001855 return TCL_ERROR;
1856 }
1857 break;
1858 }
1859
danielk1977b28af712004-06-21 06:50:26 +00001860 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001861 **
1862 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001863 ** the most recent INSERT, UPDATE or DELETE statement, not including
1864 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001865 */
1866 case DB_CHANGES: {
1867 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001868 if( objc!=2 ){
1869 Tcl_WrongNumArgs(interp, 2, objv, "");
1870 return TCL_ERROR;
1871 }
drhc8d30ac2002-04-12 10:08:59 +00001872 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001873 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001874 break;
1875 }
1876
drh75897232000-05-29 14:26:00 +00001877 /* $db close
1878 **
1879 ** Shutdown the database
1880 */
drh6d313162000-09-21 13:01:35 +00001881 case DB_CLOSE: {
1882 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1883 break;
1884 }
drh75897232000-05-29 14:26:00 +00001885
drh0f14e2e2004-06-29 12:39:08 +00001886 /*
1887 ** $db collate NAME SCRIPT
1888 **
1889 ** Create a new SQL collation function called NAME. Whenever
1890 ** that function is called, invoke SCRIPT to evaluate the function.
1891 */
1892 case DB_COLLATE: {
1893 SqlCollate *pCollate;
1894 char *zName;
1895 char *zScript;
1896 int nScript;
1897 if( objc!=4 ){
1898 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1899 return TCL_ERROR;
1900 }
1901 zName = Tcl_GetStringFromObj(objv[2], 0);
1902 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1903 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1904 if( pCollate==0 ) return TCL_ERROR;
1905 pCollate->interp = interp;
1906 pCollate->pNext = pDb->pCollate;
1907 pCollate->zScript = (char*)&pCollate[1];
1908 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001909 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001910 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1911 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001912 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001913 return TCL_ERROR;
1914 }
1915 break;
1916 }
1917
1918 /*
1919 ** $db collation_needed SCRIPT
1920 **
1921 ** Create a new SQL collation function called NAME. Whenever
1922 ** that function is called, invoke SCRIPT to evaluate the function.
1923 */
1924 case DB_COLLATION_NEEDED: {
1925 if( objc!=3 ){
1926 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1927 return TCL_ERROR;
1928 }
1929 if( pDb->pCollateNeeded ){
1930 Tcl_DecrRefCount(pDb->pCollateNeeded);
1931 }
1932 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1933 Tcl_IncrRefCount(pDb->pCollateNeeded);
1934 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1935 break;
1936 }
1937
drh19e2d372005-08-29 23:00:03 +00001938 /* $db commit_hook ?CALLBACK?
1939 **
1940 ** Invoke the given callback just before committing every SQL transaction.
1941 ** If the callback throws an exception or returns non-zero, then the
1942 ** transaction is aborted. If CALLBACK is an empty string, the callback
1943 ** is disabled.
1944 */
1945 case DB_COMMIT_HOOK: {
1946 if( objc>3 ){
1947 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1948 return TCL_ERROR;
1949 }else if( objc==2 ){
1950 if( pDb->zCommit ){
1951 Tcl_AppendResult(interp, pDb->zCommit, 0);
1952 }
1953 }else{
1954 char *zCommit;
1955 int len;
1956 if( pDb->zCommit ){
1957 Tcl_Free(pDb->zCommit);
1958 }
1959 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1960 if( zCommit && len>0 ){
1961 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001962 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001963 }else{
1964 pDb->zCommit = 0;
1965 }
1966 if( pDb->zCommit ){
1967 pDb->interp = interp;
1968 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1969 }else{
1970 sqlite3_commit_hook(pDb->db, 0, 0);
1971 }
1972 }
1973 break;
1974 }
1975
drh75897232000-05-29 14:26:00 +00001976 /* $db complete SQL
1977 **
1978 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1979 ** additional lines of input are needed. This is similar to the
1980 ** built-in "info complete" command of Tcl.
1981 */
drh6d313162000-09-21 13:01:35 +00001982 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00001983#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00001984 Tcl_Obj *pResult;
1985 int isComplete;
1986 if( objc!=3 ){
1987 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00001988 return TCL_ERROR;
1989 }
danielk19776f8a5032004-05-10 10:34:51 +00001990 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00001991 pResult = Tcl_GetObjResult(interp);
1992 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00001993#endif
drh6d313162000-09-21 13:01:35 +00001994 break;
1995 }
drhdcd997e2003-01-31 17:21:49 +00001996
drh19e2d372005-08-29 23:00:03 +00001997 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1998 **
1999 ** Copy data into table from filename, optionally using SEPARATOR
2000 ** as column separators. If a column contains a null string, or the
2001 ** value of NULLINDICATOR, a NULL is inserted for the column.
2002 ** conflict-algorithm is one of the sqlite conflict algorithms:
2003 ** rollback, abort, fail, ignore, replace
2004 ** On success, return the number of lines processed, not necessarily same
2005 ** as 'db changes' due to conflict-algorithm selected.
2006 **
2007 ** This code is basically an implementation/enhancement of
2008 ** the sqlite3 shell.c ".import" command.
2009 **
2010 ** This command usage is equivalent to the sqlite2.x COPY statement,
2011 ** which imports file data into a table using the PostgreSQL COPY file format:
2012 ** $db copy $conflit_algo $table_name $filename \t \\N
2013 */
2014 case DB_COPY: {
2015 char *zTable; /* Insert data into this table */
2016 char *zFile; /* The file from which to extract data */
2017 char *zConflict; /* The conflict algorithm to use */
2018 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00002019 int nCol; /* Number of columns in the table */
2020 int nByte; /* Number of bytes in an SQL string */
2021 int i, j; /* Loop counters */
2022 int nSep; /* Number of bytes in zSep[] */
2023 int nNull; /* Number of bytes in zNull[] */
2024 char *zSql; /* An SQL statement */
2025 char *zLine; /* A single line of input from the file */
2026 char **azCol; /* zLine[] broken up into columns */
2027 char *zCommit; /* How to commit changes */
2028 FILE *in; /* The input file */
2029 int lineno = 0; /* Line number of input file */
2030 char zLineNum[80]; /* Line number print buffer */
2031 Tcl_Obj *pResult; /* interp result */
2032
2033 char *zSep;
2034 char *zNull;
2035 if( objc<5 || objc>7 ){
2036 Tcl_WrongNumArgs(interp, 2, objv,
2037 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2038 return TCL_ERROR;
2039 }
2040 if( objc>=6 ){
2041 zSep = Tcl_GetStringFromObj(objv[5], 0);
2042 }else{
2043 zSep = "\t";
2044 }
2045 if( objc>=7 ){
2046 zNull = Tcl_GetStringFromObj(objv[6], 0);
2047 }else{
2048 zNull = "";
2049 }
2050 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2051 zTable = Tcl_GetStringFromObj(objv[3], 0);
2052 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002053 nSep = strlen30(zSep);
2054 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002055 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00002056 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00002057 return TCL_ERROR;
2058 }
drh3e59c012008-09-23 10:12:13 +00002059 if(strcmp(zConflict, "rollback") != 0 &&
2060 strcmp(zConflict, "abort" ) != 0 &&
2061 strcmp(zConflict, "fail" ) != 0 &&
2062 strcmp(zConflict, "ignore" ) != 0 &&
2063 strcmp(zConflict, "replace" ) != 0 ) {
drh19e2d372005-08-29 23:00:03 +00002064 Tcl_AppendResult(interp, "Error: \"", zConflict,
2065 "\", conflict-algorithm must be one of: rollback, "
2066 "abort, fail, ignore, or replace", 0);
2067 return TCL_ERROR;
2068 }
2069 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2070 if( zSql==0 ){
2071 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
2072 return TCL_ERROR;
2073 }
drh4f21c4a2008-12-10 22:15:00 +00002074 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002075 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002076 sqlite3_free(zSql);
2077 if( rc ){
2078 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2079 nCol = 0;
2080 }else{
2081 nCol = sqlite3_column_count(pStmt);
2082 }
2083 sqlite3_finalize(pStmt);
2084 if( nCol==0 ) {
2085 return TCL_ERROR;
2086 }
2087 zSql = malloc( nByte + 50 + nCol*2 );
2088 if( zSql==0 ) {
2089 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
2090 return TCL_ERROR;
2091 }
2092 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2093 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002094 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002095 for(i=1; i<nCol; i++){
2096 zSql[j++] = ',';
2097 zSql[j++] = '?';
2098 }
2099 zSql[j++] = ')';
2100 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002101 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002102 free(zSql);
2103 if( rc ){
2104 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2105 sqlite3_finalize(pStmt);
2106 return TCL_ERROR;
2107 }
2108 in = fopen(zFile, "rb");
2109 if( in==0 ){
2110 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2111 sqlite3_finalize(pStmt);
2112 return TCL_ERROR;
2113 }
2114 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2115 if( azCol==0 ) {
2116 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00002117 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002118 return TCL_ERROR;
2119 }
drh37527852006-03-16 16:19:56 +00002120 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002121 zCommit = "COMMIT";
2122 while( (zLine = local_getline(0, in))!=0 ){
2123 char *z;
2124 i = 0;
2125 lineno++;
2126 azCol[0] = zLine;
2127 for(i=0, z=zLine; *z; z++){
2128 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2129 *z = 0;
2130 i++;
2131 if( i<nCol ){
2132 azCol[i] = &z[nSep];
2133 z += nSep-1;
2134 }
2135 }
2136 }
2137 if( i+1!=nCol ){
2138 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002139 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002140 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002141 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002142 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002143 "Error: %s line %d: expected %d columns of data but found %d",
2144 zFile, lineno, nCol, i+1);
2145 Tcl_AppendResult(interp, zErr, 0);
2146 free(zErr);
2147 }
drh19e2d372005-08-29 23:00:03 +00002148 zCommit = "ROLLBACK";
2149 break;
2150 }
2151 for(i=0; i<nCol; i++){
2152 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002153 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
drh4f21c4a2008-12-10 22:15:00 +00002154 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002155 ){
drh19e2d372005-08-29 23:00:03 +00002156 sqlite3_bind_null(pStmt, i+1);
2157 }else{
2158 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2159 }
2160 }
2161 sqlite3_step(pStmt);
2162 rc = sqlite3_reset(pStmt);
2163 free(zLine);
2164 if( rc!=SQLITE_OK ){
2165 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
2166 zCommit = "ROLLBACK";
2167 break;
2168 }
2169 }
2170 free(azCol);
2171 fclose(in);
2172 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002173 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002174
2175 if( zCommit[0] == 'C' ){
2176 /* success, set result as number of lines processed */
2177 pResult = Tcl_GetObjResult(interp);
2178 Tcl_SetIntObj(pResult, lineno);
2179 rc = TCL_OK;
2180 }else{
2181 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002182 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00002183 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
2184 rc = TCL_ERROR;
2185 }
2186 break;
2187 }
2188
drhdcd997e2003-01-31 17:21:49 +00002189 /*
drh41449052006-07-06 17:08:48 +00002190 ** $db enable_load_extension BOOLEAN
2191 **
2192 ** Turn the extension loading feature on or off. It if off by
2193 ** default.
2194 */
2195 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002196#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002197 int onoff;
2198 if( objc!=3 ){
2199 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2200 return TCL_ERROR;
2201 }
2202 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2203 return TCL_ERROR;
2204 }
2205 sqlite3_enable_load_extension(pDb->db, onoff);
2206 break;
drhf533acc2006-12-19 18:57:11 +00002207#else
2208 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2209 0);
2210 return TCL_ERROR;
2211#endif
drh41449052006-07-06 17:08:48 +00002212 }
2213
2214 /*
drhdcd997e2003-01-31 17:21:49 +00002215 ** $db errorcode
2216 **
2217 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002218 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002219 */
2220 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002221 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002222 break;
2223 }
dan4a4c11a2009-10-06 14:59:02 +00002224
2225 /*
2226 ** $db exists $sql
2227 ** $db onecolumn $sql
2228 **
2229 ** The onecolumn method is the equivalent of:
2230 ** lindex [$db eval $sql] 0
2231 */
2232 case DB_EXISTS:
2233 case DB_ONECOLUMN: {
2234 DbEvalContext sEval;
2235 if( objc!=3 ){
2236 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2237 return TCL_ERROR;
2238 }
2239
2240 dbEvalInit(&sEval, pDb, objv[2], 0);
2241 rc = dbEvalStep(&sEval);
2242 if( choice==DB_ONECOLUMN ){
2243 if( rc==TCL_OK ){
2244 Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
dand5f12cd2011-08-18 17:47:57 +00002245 }else if( rc==TCL_BREAK ){
2246 Tcl_ResetResult(interp);
dan4a4c11a2009-10-06 14:59:02 +00002247 }
2248 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2249 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
2250 }
2251 dbEvalFinalize(&sEval);
2252
2253 if( rc==TCL_BREAK ){
2254 rc = TCL_OK;
2255 }
2256 break;
2257 }
drh75897232000-05-29 14:26:00 +00002258
2259 /*
drh895d7472004-08-20 16:02:39 +00002260 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002261 **
2262 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002263 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002264 ** If "array" and "code" are omitted, then no callback is every invoked.
2265 ** If "array" is an empty string, then the values are placed in variables
2266 ** that have the same name as the fields extracted by the query.
2267 */
dan4a4c11a2009-10-06 14:59:02 +00002268 case DB_EVAL: {
2269 if( objc<3 || objc>5 ){
2270 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2271 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002272 }
dan4a4c11a2009-10-06 14:59:02 +00002273
drh92febd92004-08-20 18:34:20 +00002274 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002275 DbEvalContext sEval;
2276 Tcl_Obj *pRet = Tcl_NewObj();
2277 Tcl_IncrRefCount(pRet);
2278 dbEvalInit(&sEval, pDb, objv[2], 0);
2279 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2280 int i;
2281 int nCol;
2282 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002283 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002284 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002285 }
2286 }
dan4a4c11a2009-10-06 14:59:02 +00002287 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002288 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002289 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002290 rc = TCL_OK;
2291 }
drh1807ce32004-09-07 13:20:35 +00002292 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002293 }else{
2294 ClientData cd[2];
2295 DbEvalContext *p;
2296 Tcl_Obj *pArray = 0;
2297 Tcl_Obj *pScript;
2298
2299 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2300 pArray = objv[3];
2301 }
2302 pScript = objv[objc-1];
2303 Tcl_IncrRefCount(pScript);
2304
2305 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2306 dbEvalInit(p, pDb, objv[2], pArray);
2307
2308 cd[0] = (void *)p;
2309 cd[1] = (void *)pScript;
2310 rc = DbEvalNextCmd(cd, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002311 }
danielk197730ccda12004-05-27 12:11:31 +00002312 break;
2313 }
drhbec3f402000-08-04 13:49:02 +00002314
2315 /*
drhe3602be2008-09-09 12:31:33 +00002316 ** $db function NAME [-argcount N] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002317 **
2318 ** Create a new SQL function called NAME. Whenever that function is
2319 ** called, invoke SCRIPT to evaluate the function.
2320 */
2321 case DB_FUNCTION: {
2322 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002323 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002324 char *zName;
drhe3602be2008-09-09 12:31:33 +00002325 int nArg = -1;
2326 if( objc==6 ){
2327 const char *z = Tcl_GetString(objv[3]);
drh4f21c4a2008-12-10 22:15:00 +00002328 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002329 if( n>2 && strncmp(z, "-argcount",n)==0 ){
2330 if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
2331 if( nArg<0 ){
2332 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2333 (char*)0);
2334 return TCL_ERROR;
2335 }
2336 }
2337 pScript = objv[5];
2338 }else if( objc!=4 ){
2339 Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
drhcabb0812002-09-14 13:47:32 +00002340 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002341 }else{
2342 pScript = objv[3];
drhcabb0812002-09-14 13:47:32 +00002343 }
2344 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002345 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002346 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002347 if( pFunc->pScript ){
2348 Tcl_DecrRefCount(pFunc->pScript);
2349 }
2350 pFunc->pScript = pScript;
2351 Tcl_IncrRefCount(pScript);
2352 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
drhe3602be2008-09-09 12:31:33 +00002353 rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00002354 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002355 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002356 rc = TCL_ERROR;
2357 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002358 }
drhcabb0812002-09-14 13:47:32 +00002359 break;
2360 }
2361
2362 /*
danielk19778cbadb02007-05-03 16:31:26 +00002363 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002364 */
2365 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002366#ifdef SQLITE_OMIT_INCRBLOB
2367 Tcl_AppendResult(interp, "incrblob not available in this build", 0);
2368 return TCL_ERROR;
2369#else
danielk19778cbadb02007-05-03 16:31:26 +00002370 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002371 const char *zDb = "main";
2372 const char *zTable;
2373 const char *zColumn;
2374 sqlite_int64 iRow;
2375
danielk19778cbadb02007-05-03 16:31:26 +00002376 /* Check for the -readonly option */
2377 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2378 isReadonly = 1;
2379 }
2380
2381 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2382 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002383 return TCL_ERROR;
2384 }
2385
danielk19778cbadb02007-05-03 16:31:26 +00002386 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002387 zDb = Tcl_GetString(objv[2]);
2388 }
2389 zTable = Tcl_GetString(objv[objc-3]);
2390 zColumn = Tcl_GetString(objv[objc-2]);
2391 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2392
2393 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002394 rc = createIncrblobChannel(
2395 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
2396 );
danielk1977b4e9af92007-05-01 17:49:49 +00002397 }
danielk197732a0d8b2007-05-04 19:03:02 +00002398#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002399 break;
2400 }
2401
2402 /*
drhf11bded2006-07-17 00:02:44 +00002403 ** $db interrupt
2404 **
2405 ** Interrupt the execution of the inner-most SQL interpreter. This
2406 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2407 */
2408 case DB_INTERRUPT: {
2409 sqlite3_interrupt(pDb->db);
2410 break;
2411 }
2412
2413 /*
drh19e2d372005-08-29 23:00:03 +00002414 ** $db nullvalue ?STRING?
2415 **
2416 ** Change text used when a NULL comes back from the database. If ?STRING?
2417 ** is not present, then the current string used for NULL is returned.
2418 ** If STRING is present, then STRING is returned.
2419 **
2420 */
2421 case DB_NULLVALUE: {
2422 if( objc!=2 && objc!=3 ){
2423 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2424 return TCL_ERROR;
2425 }
2426 if( objc==3 ){
2427 int len;
2428 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2429 if( pDb->zNull ){
2430 Tcl_Free(pDb->zNull);
2431 }
2432 if( zNull && len>0 ){
2433 pDb->zNull = Tcl_Alloc( len + 1 );
drh7fd33922011-06-20 19:00:30 +00002434 memcpy(pDb->zNull, zNull, len);
drh19e2d372005-08-29 23:00:03 +00002435 pDb->zNull[len] = '\0';
2436 }else{
2437 pDb->zNull = 0;
2438 }
2439 }
2440 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
2441 break;
2442 }
2443
2444 /*
drhaf9ff332002-01-16 21:00:27 +00002445 ** $db last_insert_rowid
2446 **
2447 ** Return an integer which is the ROWID for the most recent insert.
2448 */
2449 case DB_LAST_INSERT_ROWID: {
2450 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002451 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002452 if( objc!=2 ){
2453 Tcl_WrongNumArgs(interp, 2, objv, "");
2454 return TCL_ERROR;
2455 }
danielk19776f8a5032004-05-10 10:34:51 +00002456 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002457 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002458 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002459 break;
2460 }
2461
2462 /*
dan4a4c11a2009-10-06 14:59:02 +00002463 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002464 */
drh1807ce32004-09-07 13:20:35 +00002465
2466 /* $db progress ?N CALLBACK?
2467 **
2468 ** Invoke the given callback every N virtual machine opcodes while executing
2469 ** queries.
2470 */
2471 case DB_PROGRESS: {
2472 if( objc==2 ){
2473 if( pDb->zProgress ){
2474 Tcl_AppendResult(interp, pDb->zProgress, 0);
2475 }
2476 }else if( objc==4 ){
2477 char *zProgress;
2478 int len;
2479 int N;
2480 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002481 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002482 };
2483 if( pDb->zProgress ){
2484 Tcl_Free(pDb->zProgress);
2485 }
2486 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2487 if( zProgress && len>0 ){
2488 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002489 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002490 }else{
2491 pDb->zProgress = 0;
2492 }
2493#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2494 if( pDb->zProgress ){
2495 pDb->interp = interp;
2496 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2497 }else{
2498 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2499 }
2500#endif
2501 }else{
2502 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002503 return TCL_ERROR;
2504 }
drh5d9d7572003-08-19 14:31:01 +00002505 break;
2506 }
2507
drh19e2d372005-08-29 23:00:03 +00002508 /* $db profile ?CALLBACK?
2509 **
2510 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2511 ** that has run. The text of the SQL and the amount of elapse time are
2512 ** appended to CALLBACK before the script is run.
2513 */
2514 case DB_PROFILE: {
2515 if( objc>3 ){
2516 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2517 return TCL_ERROR;
2518 }else if( objc==2 ){
2519 if( pDb->zProfile ){
2520 Tcl_AppendResult(interp, pDb->zProfile, 0);
2521 }
2522 }else{
2523 char *zProfile;
2524 int len;
2525 if( pDb->zProfile ){
2526 Tcl_Free(pDb->zProfile);
2527 }
2528 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2529 if( zProfile && len>0 ){
2530 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002531 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002532 }else{
2533 pDb->zProfile = 0;
2534 }
shanehbb201342011-02-09 19:55:20 +00002535#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh19e2d372005-08-29 23:00:03 +00002536 if( pDb->zProfile ){
2537 pDb->interp = interp;
2538 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2539 }else{
2540 sqlite3_profile(pDb->db, 0, 0);
2541 }
2542#endif
2543 }
2544 break;
2545 }
2546
drh5d9d7572003-08-19 14:31:01 +00002547 /*
drh22fbcb82004-02-01 01:22:50 +00002548 ** $db rekey KEY
2549 **
2550 ** Change the encryption key on the currently open database.
2551 */
2552 case DB_REKEY: {
2553 int nKey;
2554 void *pKey;
2555 if( objc!=3 ){
2556 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2557 return TCL_ERROR;
2558 }
2559 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00002560#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00002561 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002562 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00002563 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002564 rc = TCL_ERROR;
2565 }
2566#endif
2567 break;
2568 }
2569
drhdc2c4912009-02-04 22:46:47 +00002570 /* $db restore ?DATABASE? FILENAME
2571 **
2572 ** Open a database file named FILENAME. Transfer the content
2573 ** of FILENAME into the local database DATABASE (default: "main").
2574 */
2575 case DB_RESTORE: {
2576 const char *zSrcFile;
2577 const char *zDestDb;
2578 sqlite3 *pSrc;
2579 sqlite3_backup *pBackup;
2580 int nTimeout = 0;
2581
2582 if( objc==3 ){
2583 zDestDb = "main";
2584 zSrcFile = Tcl_GetString(objv[2]);
2585 }else if( objc==4 ){
2586 zDestDb = Tcl_GetString(objv[2]);
2587 zSrcFile = Tcl_GetString(objv[3]);
2588 }else{
2589 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2590 return TCL_ERROR;
2591 }
2592 rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
2593 if( rc!=SQLITE_OK ){
2594 Tcl_AppendResult(interp, "cannot open source database: ",
2595 sqlite3_errmsg(pSrc), (char*)0);
2596 sqlite3_close(pSrc);
2597 return TCL_ERROR;
2598 }
2599 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2600 if( pBackup==0 ){
2601 Tcl_AppendResult(interp, "restore failed: ",
2602 sqlite3_errmsg(pDb->db), (char*)0);
2603 sqlite3_close(pSrc);
2604 return TCL_ERROR;
2605 }
2606 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2607 || rc==SQLITE_BUSY ){
2608 if( rc==SQLITE_BUSY ){
2609 if( nTimeout++ >= 3 ) break;
2610 sqlite3_sleep(100);
2611 }
2612 }
2613 sqlite3_backup_finish(pBackup);
2614 if( rc==SQLITE_DONE ){
2615 rc = TCL_OK;
2616 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2617 Tcl_AppendResult(interp, "restore failed: source database busy",
2618 (char*)0);
2619 rc = TCL_ERROR;
2620 }else{
2621 Tcl_AppendResult(interp, "restore failed: ",
2622 sqlite3_errmsg(pDb->db), (char*)0);
2623 rc = TCL_ERROR;
2624 }
2625 sqlite3_close(pSrc);
2626 break;
2627 }
2628
drh22fbcb82004-02-01 01:22:50 +00002629 /*
drh3c379b02010-04-07 19:31:59 +00002630 ** $db status (step|sort|autoindex)
drhd1d38482008-10-07 23:46:38 +00002631 **
2632 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2633 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2634 */
2635 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002636 int v;
2637 const char *zOp;
2638 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00002639 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00002640 return TCL_ERROR;
2641 }
2642 zOp = Tcl_GetString(objv[2]);
2643 if( strcmp(zOp, "step")==0 ){
2644 v = pDb->nStep;
2645 }else if( strcmp(zOp, "sort")==0 ){
2646 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002647 }else if( strcmp(zOp, "autoindex")==0 ){
2648 v = pDb->nIndex;
drhd1d38482008-10-07 23:46:38 +00002649 }else{
drh3c379b02010-04-07 19:31:59 +00002650 Tcl_AppendResult(interp,
2651 "bad argument: should be autoindex, step, or sort",
drhd1d38482008-10-07 23:46:38 +00002652 (char*)0);
2653 return TCL_ERROR;
2654 }
2655 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2656 break;
2657 }
2658
2659 /*
drhbec3f402000-08-04 13:49:02 +00002660 ** $db timeout MILLESECONDS
2661 **
2662 ** Delay for the number of milliseconds specified when a file is locked.
2663 */
drh6d313162000-09-21 13:01:35 +00002664 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002665 int ms;
drh6d313162000-09-21 13:01:35 +00002666 if( objc!=3 ){
2667 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002668 return TCL_ERROR;
2669 }
drh6d313162000-09-21 13:01:35 +00002670 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002671 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002672 break;
drh75897232000-05-29 14:26:00 +00002673 }
danielk197755c45f22005-04-03 23:54:43 +00002674
2675 /*
drh0f14e2e2004-06-29 12:39:08 +00002676 ** $db total_changes
2677 **
2678 ** Return the number of rows that were modified, inserted, or deleted
2679 ** since the database handle was created.
2680 */
2681 case DB_TOTAL_CHANGES: {
2682 Tcl_Obj *pResult;
2683 if( objc!=2 ){
2684 Tcl_WrongNumArgs(interp, 2, objv, "");
2685 return TCL_ERROR;
2686 }
2687 pResult = Tcl_GetObjResult(interp);
2688 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2689 break;
2690 }
2691
drhb5a20d32003-04-23 12:25:23 +00002692 /* $db trace ?CALLBACK?
2693 **
2694 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2695 ** that is executed. The text of the SQL is appended to CALLBACK before
2696 ** it is executed.
2697 */
2698 case DB_TRACE: {
2699 if( objc>3 ){
2700 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002701 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002702 }else if( objc==2 ){
2703 if( pDb->zTrace ){
2704 Tcl_AppendResult(interp, pDb->zTrace, 0);
2705 }
2706 }else{
2707 char *zTrace;
2708 int len;
2709 if( pDb->zTrace ){
2710 Tcl_Free(pDb->zTrace);
2711 }
2712 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2713 if( zTrace && len>0 ){
2714 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002715 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002716 }else{
2717 pDb->zTrace = 0;
2718 }
shanehbb201342011-02-09 19:55:20 +00002719#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drhb5a20d32003-04-23 12:25:23 +00002720 if( pDb->zTrace ){
2721 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002722 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002723 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002724 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002725 }
drh19e2d372005-08-29 23:00:03 +00002726#endif
drhb5a20d32003-04-23 12:25:23 +00002727 }
2728 break;
2729 }
2730
drh3d214232005-08-02 12:21:08 +00002731 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2732 **
2733 ** Start a new transaction (if we are not already in the midst of a
2734 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2735 ** completes, either commit the transaction or roll it back if SCRIPT
2736 ** throws an exception. Or if no new transation was started, do nothing.
2737 ** pass the exception on up the stack.
2738 **
2739 ** This command was inspired by Dave Thomas's talk on Ruby at the
2740 ** 2005 O'Reilly Open Source Convention (OSCON).
2741 */
2742 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00002743 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00002744 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00002745 if( objc!=3 && objc!=4 ){
2746 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2747 return TCL_ERROR;
2748 }
danielk1977cd38d522009-01-02 17:33:46 +00002749
dan4a4c11a2009-10-06 14:59:02 +00002750 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00002751 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002752 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002753 };
2754 enum TTYPE_enum {
2755 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2756 };
2757 int ttype;
drhb5555e72005-08-02 17:15:14 +00002758 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002759 0, &ttype) ){
2760 return TCL_ERROR;
2761 }
2762 switch( (enum TTYPE_enum)ttype ){
2763 case TTYPE_DEFERRED: /* no-op */; break;
2764 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2765 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2766 }
drh3d214232005-08-02 12:21:08 +00002767 }
danielk1977cd38d522009-01-02 17:33:46 +00002768 pScript = objv[objc-1];
2769
dan4a4c11a2009-10-06 14:59:02 +00002770 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00002771 pDb->disableAuth++;
2772 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2773 pDb->disableAuth--;
2774 if( rc!=SQLITE_OK ){
2775 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2776 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00002777 }
danielk1977cd38d522009-01-02 17:33:46 +00002778 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00002779
dan4a4c11a2009-10-06 14:59:02 +00002780 /* If using NRE, schedule a callback to invoke the script pScript, then
2781 ** a second callback to commit (or rollback) the transaction or savepoint
2782 ** opened above. If not using NRE, evaluate the script directly, then
2783 ** call function DbTransPostCmd() to commit (or rollback) the transaction
2784 ** or savepoint. */
2785 if( DbUseNre() ){
2786 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
2787 Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00002788 }else{
dan4a4c11a2009-10-06 14:59:02 +00002789 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00002790 }
2791 break;
2792 }
2793
danielk197794eb6a12005-12-15 15:22:08 +00002794 /*
danielk1977404ca072009-03-16 13:19:36 +00002795 ** $db unlock_notify ?script?
2796 */
2797 case DB_UNLOCK_NOTIFY: {
2798#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2799 Tcl_AppendResult(interp, "unlock_notify not available in this build", 0);
2800 rc = TCL_ERROR;
2801#else
2802 if( objc!=2 && objc!=3 ){
2803 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2804 rc = TCL_ERROR;
2805 }else{
2806 void (*xNotify)(void **, int) = 0;
2807 void *pNotifyArg = 0;
2808
2809 if( pDb->pUnlockNotify ){
2810 Tcl_DecrRefCount(pDb->pUnlockNotify);
2811 pDb->pUnlockNotify = 0;
2812 }
2813
2814 if( objc==3 ){
2815 xNotify = DbUnlockNotify;
2816 pNotifyArg = (void *)pDb;
2817 pDb->pUnlockNotify = objv[2];
2818 Tcl_IncrRefCount(pDb->pUnlockNotify);
2819 }
2820
2821 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
2822 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2823 rc = TCL_ERROR;
2824 }
2825 }
2826#endif
2827 break;
2828 }
2829
2830 /*
drh833bf962010-04-28 14:42:19 +00002831 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002832 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002833 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002834 */
drh833bf962010-04-28 14:42:19 +00002835 case DB_WAL_HOOK:
danielk197771fd80b2005-12-16 06:54:01 +00002836 case DB_UPDATE_HOOK:
2837 case DB_ROLLBACK_HOOK: {
2838
2839 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2840 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2841 */
2842 Tcl_Obj **ppHook;
2843 if( choice==DB_UPDATE_HOOK ){
2844 ppHook = &pDb->pUpdateHook;
drh833bf962010-04-28 14:42:19 +00002845 }else if( choice==DB_WAL_HOOK ){
drh5def0842010-05-05 20:00:25 +00002846 ppHook = &pDb->pWalHook;
danielk197771fd80b2005-12-16 06:54:01 +00002847 }else{
2848 ppHook = &pDb->pRollbackHook;
2849 }
2850
danielk197794eb6a12005-12-15 15:22:08 +00002851 if( objc!=2 && objc!=3 ){
2852 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2853 return TCL_ERROR;
2854 }
danielk197771fd80b2005-12-16 06:54:01 +00002855 if( *ppHook ){
2856 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002857 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002858 Tcl_DecrRefCount(*ppHook);
2859 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00002860 }
2861 }
2862 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002863 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00002864 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00002865 *ppHook = objv[2];
2866 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002867 }
2868 }
danielk197771fd80b2005-12-16 06:54:01 +00002869
2870 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2871 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
drh5def0842010-05-05 20:00:25 +00002872 sqlite3_wal_hook(pDb->db,(pDb->pWalHook?DbWalHandler:0),pDb);
danielk197771fd80b2005-12-16 06:54:01 +00002873
danielk197794eb6a12005-12-15 15:22:08 +00002874 break;
2875 }
2876
danielk19774397de52005-01-12 12:44:03 +00002877 /* $db version
2878 **
2879 ** Return the version string for this database.
2880 */
2881 case DB_VERSION: {
2882 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2883 break;
2884 }
2885
tpoindex1067fe12004-12-17 15:41:11 +00002886
drh6d313162000-09-21 13:01:35 +00002887 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002888 return rc;
drh75897232000-05-29 14:26:00 +00002889}
2890
drha2c8a952009-10-13 18:38:34 +00002891#if SQLITE_TCL_NRE
2892/*
2893** Adaptor that provides an objCmd interface to the NRE-enabled
2894** interface implementation.
2895*/
2896static int DbObjCmdAdaptor(
2897 void *cd,
2898 Tcl_Interp *interp,
2899 int objc,
2900 Tcl_Obj *const*objv
2901){
2902 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
2903}
2904#endif /* SQLITE_TCL_NRE */
2905
drh75897232000-05-29 14:26:00 +00002906/*
drh3570ad92007-08-31 14:31:44 +00002907** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00002908** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00002909**
2910** This is the main Tcl command. When the "sqlite" Tcl command is
2911** invoked, this routine runs to process that command.
2912**
2913** The first argument, DBNAME, is an arbitrary name for a new
2914** database connection. This command creates a new command named
2915** DBNAME that is used to control that connection. The database
2916** connection is deleted when the DBNAME command is deleted.
2917**
drh3570ad92007-08-31 14:31:44 +00002918** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00002919**
drh75897232000-05-29 14:26:00 +00002920*/
drh22fbcb82004-02-01 01:22:50 +00002921static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002922 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002923 void *pKey = 0;
2924 int nKey = 0;
2925 const char *zArg;
drh75897232000-05-29 14:26:00 +00002926 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00002927 int i;
drh22fbcb82004-02-01 01:22:50 +00002928 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00002929 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00002930 int flags;
drh882e8e42006-08-24 02:42:27 +00002931 Tcl_DString translatedFilename;
drhd9da78a2009-03-24 15:08:09 +00002932
2933 /* In normal use, each TCL interpreter runs in a single thread. So
2934 ** by default, we can turn of mutexing on SQLite database connections.
2935 ** However, for testing purposes it is useful to have mutexes turned
2936 ** on. So, by default, mutexes default off. But if compiled with
2937 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
2938 */
2939#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
2940 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
2941#else
2942 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
2943#endif
2944
drh22fbcb82004-02-01 01:22:50 +00002945 if( objc==2 ){
2946 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002947 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00002948 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00002949 return TCL_OK;
2950 }
drh9eb9e262004-02-11 02:18:05 +00002951 if( strcmp(zArg,"-has-codec")==0 ){
2952#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002953 Tcl_AppendResult(interp,"1",0);
2954#else
2955 Tcl_AppendResult(interp,"0",0);
2956#endif
2957 return TCL_OK;
2958 }
drhfbc3eab2001-04-06 16:13:42 +00002959 }
drh3570ad92007-08-31 14:31:44 +00002960 for(i=3; i+1<objc; i+=2){
2961 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00002962 if( strcmp(zArg,"-key")==0 ){
drh3570ad92007-08-31 14:31:44 +00002963 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
2964 }else if( strcmp(zArg, "-vfs")==0 ){
dan3c3dd7b2010-06-22 11:10:40 +00002965 zVfs = Tcl_GetString(objv[i+1]);
drh3570ad92007-08-31 14:31:44 +00002966 }else if( strcmp(zArg, "-readonly")==0 ){
2967 int b;
2968 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2969 if( b ){
drh33f4e022007-09-03 15:19:34 +00002970 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00002971 flags |= SQLITE_OPEN_READONLY;
2972 }else{
2973 flags &= ~SQLITE_OPEN_READONLY;
2974 flags |= SQLITE_OPEN_READWRITE;
2975 }
2976 }else if( strcmp(zArg, "-create")==0 ){
2977 int b;
2978 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00002979 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00002980 flags |= SQLITE_OPEN_CREATE;
2981 }else{
2982 flags &= ~SQLITE_OPEN_CREATE;
2983 }
danielk19779a6284c2008-07-10 17:52:49 +00002984 }else if( strcmp(zArg, "-nomutex")==0 ){
2985 int b;
2986 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2987 if( b ){
2988 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00002989 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00002990 }else{
2991 flags &= ~SQLITE_OPEN_NOMUTEX;
2992 }
danc431fd52011-06-27 16:55:50 +00002993 }else if( strcmp(zArg, "-fullmutex")==0 ){
drh039963a2008-09-03 00:43:15 +00002994 int b;
2995 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2996 if( b ){
2997 flags |= SQLITE_OPEN_FULLMUTEX;
2998 flags &= ~SQLITE_OPEN_NOMUTEX;
2999 }else{
3000 flags &= ~SQLITE_OPEN_FULLMUTEX;
3001 }
drh3570ad92007-08-31 14:31:44 +00003002 }else{
3003 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3004 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00003005 }
3006 }
drh3570ad92007-08-31 14:31:44 +00003007 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00003008 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00003009 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh039963a2008-09-03 00:43:15 +00003010 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN?"
drh9eb9e262004-02-11 02:18:05 +00003011#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00003012 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00003013#endif
3014 );
drh75897232000-05-29 14:26:00 +00003015 return TCL_ERROR;
3016 }
drh75897232000-05-29 14:26:00 +00003017 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003018 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00003019 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00003020 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
3021 return TCL_ERROR;
3022 }
3023 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00003024 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00003025 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
drh3570ad92007-08-31 14:31:44 +00003026 sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00003027 Tcl_DStringFree(&translatedFilename);
danielk197780290862004-05-22 09:21:21 +00003028 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
drh9404d502006-12-19 18:46:08 +00003029 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
danielk197780290862004-05-22 09:21:21 +00003030 sqlite3_close(p->db);
3031 p->db = 0;
3032 }
drh2011d5f2004-07-22 02:40:37 +00003033#ifdef SQLITE_HAS_CODEC
drhf3a65f72007-08-22 20:18:21 +00003034 if( p->db ){
3035 sqlite3_key(p->db, pKey, nKey);
3036 }
drheb8ed702004-02-11 10:37:23 +00003037#endif
drhbec3f402000-08-04 13:49:02 +00003038 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003039 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003040 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003041 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003042 return TCL_ERROR;
3043 }
drhfb7e7652005-01-24 00:28:42 +00003044 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00003045 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003046 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003047 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003048 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3049 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003050 }else{
3051 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3052 }
drh75897232000-05-29 14:26:00 +00003053 return TCL_OK;
3054}
3055
3056/*
drh90ca9752001-09-28 17:47:14 +00003057** Provide a dummy Tcl_InitStubs if we are using this as a static
3058** library.
3059*/
3060#ifndef USE_TCL_STUBS
3061# undef Tcl_InitStubs
3062# define Tcl_InitStubs(a,b,c)
3063#endif
3064
3065/*
drh29bc4612005-10-05 10:40:15 +00003066** Make sure we have a PACKAGE_VERSION macro defined. This will be
3067** defined automatically by the TEA makefile. But other makefiles
3068** do not define it.
3069*/
3070#ifndef PACKAGE_VERSION
3071# define PACKAGE_VERSION SQLITE_VERSION
3072#endif
3073
3074/*
drh75897232000-05-29 14:26:00 +00003075** Initialize this module.
3076**
3077** This Tcl module contains only a single new Tcl command named "sqlite".
3078** (Hence there is no namespace. There is no point in using a namespace
3079** if the extension only supplies one new name!) The "sqlite" command is
3080** used to open a new SQLite database. See the DbMain() routine above
3081** for additional information.
drhb652f432010-08-26 16:46:57 +00003082**
3083** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003084*/
drhb652f432010-08-26 16:46:57 +00003085EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00003086 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00003087 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00003088 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh1cca0d22010-08-25 20:35:51 +00003089
3090#ifndef SQLITE_3_SUFFIX_ONLY
3091 /* The "sqlite" alias is undocumented. It is here only to support
3092 ** legacy scripts. All new scripts should use only the "sqlite3"
3093 ** command.
3094 */
drh49766d62005-01-08 18:42:28 +00003095 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003096#endif
drh1cca0d22010-08-25 20:35:51 +00003097
drh90ca9752001-09-28 17:47:14 +00003098 return TCL_OK;
3099}
drhb652f432010-08-26 16:46:57 +00003100EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3101EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3102EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3103EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3104EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3105EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3106EXTERN int Tclsqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
drhe2c3a652008-09-23 09:58:46 +00003107
drh49766d62005-01-08 18:42:28 +00003108
3109#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003110int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3111int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3112int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3113int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3114int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3115int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3116int Sqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3117int Tclsqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
drh49766d62005-01-08 18:42:28 +00003118#endif
drh75897232000-05-29 14:26:00 +00003119
drh3e27c022004-07-23 00:01:38 +00003120#ifdef TCLSH
3121/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003122** All of the code that follows is used to build standalone TCL interpreters
3123** that are statically linked with SQLite. Enable these by compiling
3124** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3125** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3126** analysis program.
drh75897232000-05-29 14:26:00 +00003127*/
drh348784e2000-05-29 20:41:49 +00003128
drh57a02272009-10-22 20:52:05 +00003129#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3130/*
3131 * This code implements the MD5 message-digest algorithm.
3132 * The algorithm is due to Ron Rivest. This code was
3133 * written by Colin Plumb in 1993, no copyright is claimed.
3134 * This code is in the public domain; do with it what you wish.
3135 *
3136 * Equivalent code is available from RSA Data Security, Inc.
3137 * This code has been tested against that, and is equivalent,
3138 * except that you don't need to include two pages of legalese
3139 * with every copy.
3140 *
3141 * To compute the message digest of a chunk of bytes, declare an
3142 * MD5Context structure, pass it to MD5Init, call MD5Update as
3143 * needed on buffers full of bytes, and then call MD5Final, which
3144 * will fill a supplied 16-byte array with the digest.
3145 */
3146
3147/*
3148 * If compiled on a machine that doesn't have a 32-bit integer,
3149 * you just set "uint32" to the appropriate datatype for an
3150 * unsigned 32-bit integer. For example:
3151 *
3152 * cc -Duint32='unsigned long' md5.c
3153 *
3154 */
3155#ifndef uint32
3156# define uint32 unsigned int
3157#endif
3158
3159struct MD5Context {
3160 int isInit;
3161 uint32 buf[4];
3162 uint32 bits[2];
3163 unsigned char in[64];
3164};
3165typedef struct MD5Context MD5Context;
3166
3167/*
3168 * Note: this code is harmless on little-endian machines.
3169 */
3170static void byteReverse (unsigned char *buf, unsigned longs){
3171 uint32 t;
3172 do {
3173 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3174 ((unsigned)buf[1]<<8 | buf[0]);
3175 *(uint32 *)buf = t;
3176 buf += 4;
3177 } while (--longs);
3178}
3179/* The four core functions - F1 is optimized somewhat */
3180
3181/* #define F1(x, y, z) (x & y | ~x & z) */
3182#define F1(x, y, z) (z ^ (x & (y ^ z)))
3183#define F2(x, y, z) F1(z, x, y)
3184#define F3(x, y, z) (x ^ y ^ z)
3185#define F4(x, y, z) (y ^ (x | ~z))
3186
3187/* This is the central step in the MD5 algorithm. */
3188#define MD5STEP(f, w, x, y, z, data, s) \
3189 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3190
3191/*
3192 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3193 * reflect the addition of 16 longwords of new data. MD5Update blocks
3194 * the data and converts bytes into longwords for this routine.
3195 */
3196static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3197 register uint32 a, b, c, d;
3198
3199 a = buf[0];
3200 b = buf[1];
3201 c = buf[2];
3202 d = buf[3];
3203
3204 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3205 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3206 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3207 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3208 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3209 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3210 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3211 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3212 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3213 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3214 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3215 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3216 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3217 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3218 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3219 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3220
3221 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3222 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3223 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3224 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3225 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3226 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3227 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3228 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3229 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3230 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3231 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3232 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3233 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3234 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3235 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3236 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3237
3238 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3239 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3240 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3241 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3242 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3243 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3244 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3245 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3246 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3247 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3248 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3249 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3250 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3251 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3252 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3253 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3254
3255 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3256 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3257 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3258 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3259 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3260 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3261 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3262 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3263 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3264 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3265 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3266 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3267 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3268 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3269 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3270 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3271
3272 buf[0] += a;
3273 buf[1] += b;
3274 buf[2] += c;
3275 buf[3] += d;
3276}
3277
3278/*
3279 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3280 * initialization constants.
3281 */
3282static void MD5Init(MD5Context *ctx){
3283 ctx->isInit = 1;
3284 ctx->buf[0] = 0x67452301;
3285 ctx->buf[1] = 0xefcdab89;
3286 ctx->buf[2] = 0x98badcfe;
3287 ctx->buf[3] = 0x10325476;
3288 ctx->bits[0] = 0;
3289 ctx->bits[1] = 0;
3290}
3291
3292/*
3293 * Update context to reflect the concatenation of another buffer full
3294 * of bytes.
3295 */
3296static
3297void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3298 uint32 t;
3299
3300 /* Update bitcount */
3301
3302 t = ctx->bits[0];
3303 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3304 ctx->bits[1]++; /* Carry from low to high */
3305 ctx->bits[1] += len >> 29;
3306
3307 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3308
3309 /* Handle any leading odd-sized chunks */
3310
3311 if ( t ) {
3312 unsigned char *p = (unsigned char *)ctx->in + t;
3313
3314 t = 64-t;
3315 if (len < t) {
3316 memcpy(p, buf, len);
3317 return;
3318 }
3319 memcpy(p, buf, t);
3320 byteReverse(ctx->in, 16);
3321 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3322 buf += t;
3323 len -= t;
3324 }
3325
3326 /* Process data in 64-byte chunks */
3327
3328 while (len >= 64) {
3329 memcpy(ctx->in, buf, 64);
3330 byteReverse(ctx->in, 16);
3331 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3332 buf += 64;
3333 len -= 64;
3334 }
3335
3336 /* Handle any remaining bytes of data. */
3337
3338 memcpy(ctx->in, buf, len);
3339}
3340
3341/*
3342 * Final wrapup - pad to 64-byte boundary with the bit pattern
3343 * 1 0* (64-bit count of bits processed, MSB-first)
3344 */
3345static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3346 unsigned count;
3347 unsigned char *p;
3348
3349 /* Compute number of bytes mod 64 */
3350 count = (ctx->bits[0] >> 3) & 0x3F;
3351
3352 /* Set the first char of padding to 0x80. This is safe since there is
3353 always at least one byte free */
3354 p = ctx->in + count;
3355 *p++ = 0x80;
3356
3357 /* Bytes of padding needed to make 64 bytes */
3358 count = 64 - 1 - count;
3359
3360 /* Pad out to 56 mod 64 */
3361 if (count < 8) {
3362 /* Two lots of padding: Pad the first block to 64 bytes */
3363 memset(p, 0, count);
3364 byteReverse(ctx->in, 16);
3365 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3366
3367 /* Now fill the next block with 56 bytes */
3368 memset(ctx->in, 0, 56);
3369 } else {
3370 /* Pad block to 56 bytes */
3371 memset(p, 0, count-8);
3372 }
3373 byteReverse(ctx->in, 14);
3374
3375 /* Append length in bits and transform */
3376 ((uint32 *)ctx->in)[ 14 ] = ctx->bits[0];
3377 ((uint32 *)ctx->in)[ 15 ] = ctx->bits[1];
3378
3379 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3380 byteReverse((unsigned char *)ctx->buf, 4);
3381 memcpy(digest, ctx->buf, 16);
3382 memset(ctx, 0, sizeof(ctx)); /* In case it is sensitive */
3383}
3384
3385/*
3386** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3387*/
3388static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3389 static char const zEncode[] = "0123456789abcdef";
3390 int i, j;
3391
3392 for(j=i=0; i<16; i++){
3393 int a = digest[i];
3394 zBuf[j++] = zEncode[(a>>4)&0xf];
3395 zBuf[j++] = zEncode[a & 0xf];
3396 }
3397 zBuf[j] = 0;
3398}
3399
3400
3401/*
3402** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3403** each representing 16 bits of the digest and separated from each
3404** other by a "-" character.
3405*/
3406static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3407 int i, j;
3408 unsigned int x;
3409 for(i=j=0; i<16; i+=2){
3410 x = digest[i]*256 + digest[i+1];
3411 if( i>0 ) zDigest[j++] = '-';
3412 sprintf(&zDigest[j], "%05u", x);
3413 j += 5;
3414 }
3415 zDigest[j] = 0;
3416}
3417
3418/*
3419** A TCL command for md5. The argument is the text to be hashed. The
3420** Result is the hash in base64.
3421*/
3422static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3423 MD5Context ctx;
3424 unsigned char digest[16];
3425 char zBuf[50];
3426 void (*converter)(unsigned char*, char*);
3427
3428 if( argc!=2 ){
3429 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3430 " TEXT\"", 0);
3431 return TCL_ERROR;
3432 }
3433 MD5Init(&ctx);
3434 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3435 MD5Final(digest, &ctx);
3436 converter = (void(*)(unsigned char*,char*))cd;
3437 converter(digest, zBuf);
3438 Tcl_AppendResult(interp, zBuf, (char*)0);
3439 return TCL_OK;
3440}
3441
3442/*
3443** A TCL command to take the md5 hash of a file. The argument is the
3444** name of the file.
3445*/
3446static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3447 FILE *in;
3448 MD5Context ctx;
3449 void (*converter)(unsigned char*, char*);
3450 unsigned char digest[16];
3451 char zBuf[10240];
3452
3453 if( argc!=2 ){
3454 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3455 " FILENAME\"", 0);
3456 return TCL_ERROR;
3457 }
3458 in = fopen(argv[1],"rb");
3459 if( in==0 ){
3460 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
3461 "\" for reading", 0);
3462 return TCL_ERROR;
3463 }
3464 MD5Init(&ctx);
3465 for(;;){
3466 int n;
3467 n = fread(zBuf, 1, sizeof(zBuf), in);
3468 if( n<=0 ) break;
3469 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3470 }
3471 fclose(in);
3472 MD5Final(digest, &ctx);
3473 converter = (void(*)(unsigned char*,char*))cd;
3474 converter(digest, zBuf);
3475 Tcl_AppendResult(interp, zBuf, (char*)0);
3476 return TCL_OK;
3477}
3478
3479/*
3480** Register the four new TCL commands for generating MD5 checksums
3481** with the TCL interpreter.
3482*/
3483int Md5_Init(Tcl_Interp *interp){
3484 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3485 MD5DigestToBase16, 0);
3486 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3487 MD5DigestToBase10x8, 0);
3488 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3489 MD5DigestToBase16, 0);
3490 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3491 MD5DigestToBase10x8, 0);
3492 return TCL_OK;
3493}
3494#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3495
3496#if defined(SQLITE_TEST)
3497/*
3498** During testing, the special md5sum() aggregate function is available.
3499** inside SQLite. The following routines implement that function.
3500*/
3501static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3502 MD5Context *p;
3503 int i;
3504 if( argc<1 ) return;
3505 p = sqlite3_aggregate_context(context, sizeof(*p));
3506 if( p==0 ) return;
3507 if( !p->isInit ){
3508 MD5Init(p);
3509 }
3510 for(i=0; i<argc; i++){
3511 const char *zData = (char*)sqlite3_value_text(argv[i]);
3512 if( zData ){
3513 MD5Update(p, (unsigned char*)zData, strlen(zData));
3514 }
3515 }
3516}
3517static void md5finalize(sqlite3_context *context){
3518 MD5Context *p;
3519 unsigned char digest[16];
3520 char zBuf[33];
3521 p = sqlite3_aggregate_context(context, sizeof(*p));
3522 MD5Final(digest,p);
3523 MD5DigestToBase16(digest, zBuf);
3524 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3525}
3526int Md5_Register(sqlite3 *db){
3527 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
3528 md5step, md5finalize);
3529 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3530 return rc;
3531}
3532#endif /* defined(SQLITE_TEST) */
3533
3534
drh348784e2000-05-29 20:41:49 +00003535/*
drh3e27c022004-07-23 00:01:38 +00003536** If the macro TCLSH is one, then put in code this for the
3537** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003538** standard input, or if a file is named on the command line
3539** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003540*/
drh3e27c022004-07-23 00:01:38 +00003541#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00003542static char zMainloop[] =
3543 "set line {}\n"
3544 "while {![eof stdin]} {\n"
3545 "if {$line!=\"\"} {\n"
3546 "puts -nonewline \"> \"\n"
3547 "} else {\n"
3548 "puts -nonewline \"% \"\n"
3549 "}\n"
3550 "flush stdout\n"
3551 "append line [gets stdin]\n"
3552 "if {[info complete $line]} {\n"
3553 "if {[catch {uplevel #0 $line} result]} {\n"
3554 "puts stderr \"Error: $result\"\n"
3555 "} elseif {$result!=\"\"} {\n"
3556 "puts $result\n"
3557 "}\n"
3558 "set line {}\n"
3559 "} else {\n"
3560 "append line \\n\n"
3561 "}\n"
3562 "}\n"
3563;
drh3e27c022004-07-23 00:01:38 +00003564#endif
drh3a0f13f2010-07-12 16:47:48 +00003565#if TCLSH==2
3566static char zMainloop[] =
3567#include "spaceanal_tcl.h"
3568;
3569#endif
drh3e27c022004-07-23 00:01:38 +00003570
danc1a60c52010-06-07 14:28:16 +00003571#ifdef SQLITE_TEST
3572static void init_all(Tcl_Interp *);
3573static int init_all_cmd(
3574 ClientData cd,
3575 Tcl_Interp *interp,
3576 int objc,
3577 Tcl_Obj *CONST objv[]
3578){
danielk19770a549072009-02-17 16:29:10 +00003579
danc1a60c52010-06-07 14:28:16 +00003580 Tcl_Interp *slave;
3581 if( objc!=2 ){
3582 Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3583 return TCL_ERROR;
3584 }
3585
3586 slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3587 if( !slave ){
3588 return TCL_ERROR;
3589 }
3590
3591 init_all(slave);
3592 return TCL_OK;
3593}
danc431fd52011-06-27 16:55:50 +00003594
3595/*
3596** Tclcmd: db_use_legacy_prepare DB BOOLEAN
3597**
3598** The first argument to this command must be a database command created by
3599** [sqlite3]. If the second argument is true, then the handle is configured
3600** to use the sqlite3_prepare_v2() function to prepare statements. If it
3601** is false, sqlite3_prepare().
3602*/
3603static int db_use_legacy_prepare_cmd(
3604 ClientData cd,
3605 Tcl_Interp *interp,
3606 int objc,
3607 Tcl_Obj *CONST objv[]
3608){
3609 Tcl_CmdInfo cmdInfo;
3610 SqliteDb *pDb;
3611 int bPrepare;
3612
3613 if( objc!=3 ){
3614 Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
3615 return TCL_ERROR;
3616 }
3617
3618 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3619 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3620 return TCL_ERROR;
3621 }
3622 pDb = (SqliteDb*)cmdInfo.objClientData;
3623 if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
3624 return TCL_ERROR;
3625 }
3626
3627 pDb->bLegacyPrepare = bPrepare;
3628
3629 Tcl_ResetResult(interp);
3630 return TCL_OK;
3631}
danc1a60c52010-06-07 14:28:16 +00003632#endif
3633
3634/*
3635** Configure the interpreter passed as the first argument to have access
3636** to the commands and linked variables that make up:
3637**
3638** * the [sqlite3] extension itself,
3639**
3640** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
3641**
3642** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
3643** test suite.
3644*/
3645static void init_all(Tcl_Interp *interp){
drh38f82712004-06-18 17:10:16 +00003646 Sqlite3_Init(interp);
danc1a60c52010-06-07 14:28:16 +00003647
drh57a02272009-10-22 20:52:05 +00003648#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3649 Md5_Init(interp);
3650#endif
danc1a60c52010-06-07 14:28:16 +00003651
drhd9b02572001-04-15 00:37:09 +00003652#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00003653 {
drh2f999a62007-08-15 19:16:43 +00003654 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00003655 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00003656 extern int Sqlitetest2_Init(Tcl_Interp*);
3657 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00003658 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00003659 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00003660 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00003661 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00003662 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00003663 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00003664 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00003665 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
dan0a7a9152010-04-07 07:57:38 +00003666 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
drh984bfaa2008-03-19 16:08:53 +00003667 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00003668 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00003669 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003670 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00003671 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003672 extern int Sqlitetestschema_Init(Tcl_Interp*);
3673 extern int Sqlitetestsse_Init(Tcl_Interp*);
3674 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00003675 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00003676 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00003677 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00003678 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh522efc62009-11-10 17:24:37 +00003679 extern int Sqlitetestintarray_Init(Tcl_Interp*);
danc7991bd2010-05-05 19:04:59 +00003680 extern int Sqlitetestvfs_Init(Tcl_Interp *);
dan599e9d22010-07-12 08:39:37 +00003681 extern int SqlitetestStat_Init(Tcl_Interp*);
dan9508daa2010-08-28 18:58:00 +00003682 extern int Sqlitetestrtree_Init(Tcl_Interp*);
dan8cf35eb2010-09-01 11:40:05 +00003683 extern int Sqlitequota_Init(Tcl_Interp*);
shaneh8a922f72010-11-04 20:50:27 +00003684 extern int Sqlitemultiplex_Init(Tcl_Interp*);
dane336b002010-11-19 18:20:09 +00003685 extern int SqliteSuperlock_Init(Tcl_Interp*);
dan213ca0a2011-03-28 19:10:06 +00003686 extern int SqlitetestSyscall_Init(Tcl_Interp*);
drh326a67d2011-03-26 15:05:27 +00003687 extern int Sqlitetestfuzzer_Init(Tcl_Interp*);
drh70586be2011-04-01 23:49:44 +00003688 extern int Sqlitetestwholenumber_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00003689
dan6764a702011-06-20 11:15:06 +00003690#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00003691 extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
3692#endif
3693
danb29010c2010-12-29 18:24:38 +00003694#ifdef SQLITE_ENABLE_ZIPVFS
3695 extern int Zipvfs_Init(Tcl_Interp*);
3696 Zipvfs_Init(interp);
3697#endif
3698
drh2f999a62007-08-15 19:16:43 +00003699 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00003700 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00003701 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00003702 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00003703 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00003704 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00003705 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00003706 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00003707 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00003708 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00003709 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00003710 Sqlitetest_autoext_Init(interp);
dan0a7a9152010-04-07 07:57:38 +00003711 Sqlitetest_demovfs_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00003712 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00003713 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00003714 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003715 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00003716 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003717 Sqlitetestschema_Init(interp);
3718 Sqlitetesttclvar_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00003719 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003720 SqlitetestOnefile_Init(interp);
danielk19775d1f5aa2008-04-10 14:51:00 +00003721 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00003722 Sqlitetestbackup_Init(interp);
drh522efc62009-11-10 17:24:37 +00003723 Sqlitetestintarray_Init(interp);
danc7991bd2010-05-05 19:04:59 +00003724 Sqlitetestvfs_Init(interp);
dan599e9d22010-07-12 08:39:37 +00003725 SqlitetestStat_Init(interp);
dan9508daa2010-08-28 18:58:00 +00003726 Sqlitetestrtree_Init(interp);
dan8cf35eb2010-09-01 11:40:05 +00003727 Sqlitequota_Init(interp);
shaneh8a922f72010-11-04 20:50:27 +00003728 Sqlitemultiplex_Init(interp);
dane336b002010-11-19 18:20:09 +00003729 SqliteSuperlock_Init(interp);
dan213ca0a2011-03-28 19:10:06 +00003730 SqlitetestSyscall_Init(interp);
drh326a67d2011-03-26 15:05:27 +00003731 Sqlitetestfuzzer_Init(interp);
drh70586be2011-04-01 23:49:44 +00003732 Sqlitetestwholenumber_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003733
dan6764a702011-06-20 11:15:06 +00003734#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00003735 Sqlitetestfts3_Init(interp);
3736#endif
3737
danc431fd52011-06-27 16:55:50 +00003738 Tcl_CreateObjCommand(
3739 interp, "load_testfixture_extensions", init_all_cmd, 0, 0
3740 );
3741 Tcl_CreateObjCommand(
3742 interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
3743 );
danc1a60c52010-06-07 14:28:16 +00003744
drh89dec812005-04-28 19:03:37 +00003745#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00003746 Sqlitetestsse_Init(interp);
3747#endif
drhd1bf3512001-04-07 15:24:33 +00003748 }
3749#endif
danc1a60c52010-06-07 14:28:16 +00003750}
3751
3752#define TCLSH_MAIN main /* Needed to fake out mktclapp */
3753int TCLSH_MAIN(int argc, char **argv){
3754 Tcl_Interp *interp;
3755
3756 /* Call sqlite3_shutdown() once before doing anything else. This is to
3757 ** test that sqlite3_shutdown() can be safely called by a process before
3758 ** sqlite3_initialize() is. */
3759 sqlite3_shutdown();
3760
drh3a0f13f2010-07-12 16:47:48 +00003761#if TCLSH==2
3762 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
3763#endif
danc1a60c52010-06-07 14:28:16 +00003764 Tcl_FindExecutable(argv[0]);
3765
3766 interp = Tcl_CreateInterp();
3767 init_all(interp);
drhc7285972009-11-10 01:13:25 +00003768 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00003769 int i;
shessad42c3a2006-08-22 23:53:46 +00003770 char zArgc[32];
3771 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
3772 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00003773 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
3774 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00003775 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00003776 Tcl_SetVar(interp, "argv", argv[i],
3777 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3778 }
drh3a0f13f2010-07-12 16:47:48 +00003779 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00003780 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00003781 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00003782 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00003783 return 1;
3784 }
drh3e27c022004-07-23 00:01:38 +00003785 }
drh3a0f13f2010-07-12 16:47:48 +00003786 if( TCLSH==2 || argc<=1 ){
drh348784e2000-05-29 20:41:49 +00003787 Tcl_GlobalEval(interp, zMainloop);
3788 }
3789 return 0;
3790}
3791#endif /* TCLSH */