blob: e1ae8eb8ed55ea482a84486ab8b70fca90bafd88 [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);
drhb07028f2011-10-14 21:49:18 +0000922 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
drhe22a3342003-04-22 20:30:37 +0000923 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;
tpoindex1067fe12004-12-17 15:41:11 +0000971
972 nLine = 100;
973 zLine = malloc( nLine );
974 if( zLine==0 ) return 0;
975 n = 0;
drhb07028f2011-10-14 21:49:18 +0000976 while( 1 ){
tpoindex1067fe12004-12-17 15:41:11 +0000977 if( n+100>nLine ){
978 nLine = nLine*2 + 100;
979 zLine = realloc(zLine, nLine);
980 if( zLine==0 ) return 0;
981 }
982 if( fgets(&zLine[n], nLine - n, in)==0 ){
983 if( n==0 ){
984 free(zLine);
985 return 0;
986 }
987 zLine[n] = 0;
tpoindex1067fe12004-12-17 15:41:11 +0000988 break;
989 }
990 while( zLine[n] ){ n++; }
991 if( n>0 && zLine[n-1]=='\n' ){
992 n--;
993 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +0000994 break;
tpoindex1067fe12004-12-17 15:41:11 +0000995 }
996 }
997 zLine = realloc( zLine, n+1 );
998 return zLine;
999}
1000
danielk19778e556522007-11-13 10:30:24 +00001001
1002/*
dan4a4c11a2009-10-06 14:59:02 +00001003** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +00001004**
dan4a4c11a2009-10-06 14:59:02 +00001005** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +00001006**
dan4a4c11a2009-10-06 14:59:02 +00001007** It is invoked after evaluating the script SCRIPT to commit or rollback
1008** the transaction or savepoint opened by the [transaction] command.
1009*/
1010static int DbTransPostCmd(
1011 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1012 Tcl_Interp *interp, /* Tcl interpreter */
1013 int result /* Result of evaluating SCRIPT */
1014){
1015 static const char *azEnd[] = {
1016 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1017 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1018 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1019 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1020 };
1021 SqliteDb *pDb = (SqliteDb*)data[0];
1022 int rc = result;
1023 const char *zEnd;
1024
1025 pDb->nTransaction--;
1026 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1027
1028 pDb->disableAuth++;
1029 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1030 /* This is a tricky scenario to handle. The most likely cause of an
1031 ** error is that the exec() above was an attempt to commit the
1032 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1033 ** that an IO-error has occured. In either case, throw a Tcl exception
1034 ** and try to rollback the transaction.
1035 **
1036 ** But it could also be that the user executed one or more BEGIN,
1037 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1038 ** this method's logic. Not clear how this would be best handled.
1039 */
1040 if( rc!=TCL_ERROR ){
1041 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
1042 rc = TCL_ERROR;
1043 }
1044 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1045 }
1046 pDb->disableAuth--;
1047
1048 return rc;
1049}
1050
1051/*
danc431fd52011-06-27 16:55:50 +00001052** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1053** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1054** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1055** on whether or not the [db_use_legacy_prepare] command has been used to
1056** configure the connection.
1057*/
1058static int dbPrepare(
1059 SqliteDb *pDb, /* Database object */
1060 const char *zSql, /* SQL to compile */
1061 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1062 const char **pzOut /* OUT: Pointer to next SQL statement */
1063){
1064#ifdef SQLITE_TEST
1065 if( pDb->bLegacyPrepare ){
1066 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1067 }
1068#endif
1069 return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut);
1070}
1071
1072/*
dan4a4c11a2009-10-06 14:59:02 +00001073** Search the cache for a prepared-statement object that implements the
1074** first SQL statement in the buffer pointed to by parameter zIn. If
1075** no such prepared-statement can be found, allocate and prepare a new
1076** one. In either case, bind the current values of the relevant Tcl
1077** variables to any $var, :var or @var variables in the statement. Before
1078** returning, set *ppPreStmt to point to the prepared-statement object.
1079**
1080** Output parameter *pzOut is set to point to the next SQL statement in
1081** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1082** next statement.
1083**
1084** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1085** and an error message loaded into interpreter pDb->interp.
1086*/
1087static int dbPrepareAndBind(
1088 SqliteDb *pDb, /* Database object */
1089 char const *zIn, /* SQL to compile */
1090 char const **pzOut, /* OUT: Pointer to next SQL statement */
1091 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1092){
1093 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
1094 sqlite3_stmt *pStmt; /* Prepared statement object */
1095 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1096 int nSql; /* Length of zSql in bytes */
1097 int nVar; /* Number of variables in statement */
1098 int iParm = 0; /* Next free entry in apParm */
1099 int i;
1100 Tcl_Interp *interp = pDb->interp;
1101
1102 *ppPreStmt = 0;
1103
1104 /* Trim spaces from the start of zSql and calculate the remaining length. */
1105 while( isspace(zSql[0]) ){ zSql++; }
1106 nSql = strlen30(zSql);
1107
1108 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1109 int n = pPreStmt->nSql;
1110 if( nSql>=n
1111 && memcmp(pPreStmt->zSql, zSql, n)==0
1112 && (zSql[n]==0 || zSql[n-1]==';')
1113 ){
1114 pStmt = pPreStmt->pStmt;
1115 *pzOut = &zSql[pPreStmt->nSql];
1116
1117 /* When a prepared statement is found, unlink it from the
1118 ** cache list. It will later be added back to the beginning
1119 ** of the cache list in order to implement LRU replacement.
1120 */
1121 if( pPreStmt->pPrev ){
1122 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1123 }else{
1124 pDb->stmtList = pPreStmt->pNext;
1125 }
1126 if( pPreStmt->pNext ){
1127 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1128 }else{
1129 pDb->stmtLast = pPreStmt->pPrev;
1130 }
1131 pDb->nStmt--;
1132 nVar = sqlite3_bind_parameter_count(pStmt);
1133 break;
1134 }
1135 }
1136
1137 /* If no prepared statement was found. Compile the SQL text. Also allocate
1138 ** a new SqlPreparedStmt structure. */
1139 if( pPreStmt==0 ){
1140 int nByte;
1141
danc431fd52011-06-27 16:55:50 +00001142 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
dan4a4c11a2009-10-06 14:59:02 +00001143 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1144 return TCL_ERROR;
1145 }
1146 if( pStmt==0 ){
1147 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1148 /* A compile-time error in the statement. */
1149 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1150 return TCL_ERROR;
1151 }else{
1152 /* The statement was a no-op. Continue to the next statement
1153 ** in the SQL string.
1154 */
1155 return TCL_OK;
1156 }
1157 }
1158
1159 assert( pPreStmt==0 );
1160 nVar = sqlite3_bind_parameter_count(pStmt);
1161 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1162 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1163 memset(pPreStmt, 0, nByte);
1164
1165 pPreStmt->pStmt = pStmt;
drh7ed243b2012-04-19 17:19:51 +00001166 pPreStmt->nSql = (int)(*pzOut - zSql);
dan4a4c11a2009-10-06 14:59:02 +00001167 pPreStmt->zSql = sqlite3_sql(pStmt);
1168 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
danc431fd52011-06-27 16:55:50 +00001169#ifdef SQLITE_TEST
1170 if( pPreStmt->zSql==0 ){
1171 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1172 memcpy(zCopy, zSql, pPreStmt->nSql);
1173 zCopy[pPreStmt->nSql] = '\0';
1174 pPreStmt->zSql = zCopy;
1175 }
1176#endif
dan4a4c11a2009-10-06 14:59:02 +00001177 }
1178 assert( pPreStmt );
1179 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1180 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1181
1182 /* Bind values to parameters that begin with $ or : */
1183 for(i=1; i<=nVar; i++){
1184 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1185 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1186 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1187 if( pVar ){
1188 int n;
1189 u8 *data;
1190 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1191 char c = zType[0];
1192 if( zVar[0]=='@' ||
1193 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1194 /* Load a BLOB type if the Tcl variable is a bytearray and
1195 ** it has no string representation or the host
1196 ** parameter name begins with "@". */
1197 data = Tcl_GetByteArrayFromObj(pVar, &n);
1198 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1199 Tcl_IncrRefCount(pVar);
1200 pPreStmt->apParm[iParm++] = pVar;
1201 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1202 Tcl_GetIntFromObj(interp, pVar, &n);
1203 sqlite3_bind_int(pStmt, i, n);
1204 }else if( c=='d' && strcmp(zType,"double")==0 ){
1205 double r;
1206 Tcl_GetDoubleFromObj(interp, pVar, &r);
1207 sqlite3_bind_double(pStmt, i, r);
1208 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1209 (c=='i' && strcmp(zType,"int")==0) ){
1210 Tcl_WideInt v;
1211 Tcl_GetWideIntFromObj(interp, pVar, &v);
1212 sqlite3_bind_int64(pStmt, i, v);
1213 }else{
1214 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1215 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1216 Tcl_IncrRefCount(pVar);
1217 pPreStmt->apParm[iParm++] = pVar;
1218 }
1219 }else{
1220 sqlite3_bind_null(pStmt, i);
1221 }
1222 }
1223 }
1224 pPreStmt->nParm = iParm;
1225 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001226
dan4a4c11a2009-10-06 14:59:02 +00001227 return TCL_OK;
1228}
1229
dan4a4c11a2009-10-06 14:59:02 +00001230/*
1231** Release a statement reference obtained by calling dbPrepareAndBind().
1232** There should be exactly one call to this function for each call to
1233** dbPrepareAndBind().
1234**
1235** If the discard parameter is non-zero, then the statement is deleted
1236** immediately. Otherwise it is added to the LRU list and may be returned
1237** by a subsequent call to dbPrepareAndBind().
1238*/
1239static void dbReleaseStmt(
1240 SqliteDb *pDb, /* Database handle */
1241 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1242 int discard /* True to delete (not cache) the pPreStmt */
1243){
1244 int i;
1245
1246 /* Free the bound string and blob parameters */
1247 for(i=0; i<pPreStmt->nParm; i++){
1248 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1249 }
1250 pPreStmt->nParm = 0;
1251
1252 if( pDb->maxStmt<=0 || discard ){
1253 /* If the cache is turned off, deallocated the statement */
danc431fd52011-06-27 16:55:50 +00001254 dbFreeStmt(pPreStmt);
dan4a4c11a2009-10-06 14:59:02 +00001255 }else{
1256 /* Add the prepared statement to the beginning of the cache list. */
1257 pPreStmt->pNext = pDb->stmtList;
1258 pPreStmt->pPrev = 0;
1259 if( pDb->stmtList ){
1260 pDb->stmtList->pPrev = pPreStmt;
1261 }
1262 pDb->stmtList = pPreStmt;
1263 if( pDb->stmtLast==0 ){
1264 assert( pDb->nStmt==0 );
1265 pDb->stmtLast = pPreStmt;
1266 }else{
1267 assert( pDb->nStmt>0 );
1268 }
1269 pDb->nStmt++;
1270
1271 /* If we have too many statement in cache, remove the surplus from
1272 ** the end of the cache list. */
1273 while( pDb->nStmt>pDb->maxStmt ){
danc431fd52011-06-27 16:55:50 +00001274 SqlPreparedStmt *pLast = pDb->stmtLast;
1275 pDb->stmtLast = pLast->pPrev;
dan4a4c11a2009-10-06 14:59:02 +00001276 pDb->stmtLast->pNext = 0;
1277 pDb->nStmt--;
danc431fd52011-06-27 16:55:50 +00001278 dbFreeStmt(pLast);
dan4a4c11a2009-10-06 14:59:02 +00001279 }
1280 }
1281}
1282
1283/*
1284** Structure used with dbEvalXXX() functions:
1285**
1286** dbEvalInit()
1287** dbEvalStep()
1288** dbEvalFinalize()
1289** dbEvalRowInfo()
1290** dbEvalColumnValue()
1291*/
1292typedef struct DbEvalContext DbEvalContext;
1293struct DbEvalContext {
1294 SqliteDb *pDb; /* Database handle */
1295 Tcl_Obj *pSql; /* Object holding string zSql */
1296 const char *zSql; /* Remaining SQL to execute */
1297 SqlPreparedStmt *pPreStmt; /* Current statement */
1298 int nCol; /* Number of columns returned by pStmt */
1299 Tcl_Obj *pArray; /* Name of array variable */
1300 Tcl_Obj **apColName; /* Array of column names */
1301};
1302
1303/*
1304** Release any cache of column names currently held as part of
1305** the DbEvalContext structure passed as the first argument.
1306*/
1307static void dbReleaseColumnNames(DbEvalContext *p){
1308 if( p->apColName ){
1309 int i;
1310 for(i=0; i<p->nCol; i++){
1311 Tcl_DecrRefCount(p->apColName[i]);
1312 }
1313 Tcl_Free((char *)p->apColName);
1314 p->apColName = 0;
1315 }
1316 p->nCol = 0;
1317}
1318
1319/*
1320** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001321**
1322** If pArray is not NULL, then it contains the name of a Tcl array
1323** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001324** the names of the columns returned by the statement as part of each
1325** call to dbEvalStep(), in order from left to right. e.g. if the names
1326** of the returned columns are a, b and c, it does the equivalent of the
1327** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001328**
1329** set ${pArray}(*) {a b c}
1330*/
dan4a4c11a2009-10-06 14:59:02 +00001331static void dbEvalInit(
1332 DbEvalContext *p, /* Pointer to structure to initialize */
1333 SqliteDb *pDb, /* Database handle */
1334 Tcl_Obj *pSql, /* Object containing SQL script */
1335 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001336){
dan4a4c11a2009-10-06 14:59:02 +00001337 memset(p, 0, sizeof(DbEvalContext));
1338 p->pDb = pDb;
1339 p->zSql = Tcl_GetString(pSql);
1340 p->pSql = pSql;
1341 Tcl_IncrRefCount(pSql);
1342 if( pArray ){
1343 p->pArray = pArray;
1344 Tcl_IncrRefCount(pArray);
1345 }
1346}
danielk19778e556522007-11-13 10:30:24 +00001347
dan4a4c11a2009-10-06 14:59:02 +00001348/*
1349** Obtain information about the row that the DbEvalContext passed as the
1350** first argument currently points to.
1351*/
1352static void dbEvalRowInfo(
1353 DbEvalContext *p, /* Evaluation context */
1354 int *pnCol, /* OUT: Number of column names */
1355 Tcl_Obj ***papColName /* OUT: Array of column names */
1356){
danielk19778e556522007-11-13 10:30:24 +00001357 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001358 if( 0==p->apColName ){
1359 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1360 int i; /* Iterator variable */
1361 int nCol; /* Number of columns returned by pStmt */
1362 Tcl_Obj **apColName = 0; /* Array of column names */
1363
1364 p->nCol = nCol = sqlite3_column_count(pStmt);
1365 if( nCol>0 && (papColName || p->pArray) ){
1366 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1367 for(i=0; i<nCol; i++){
1368 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1369 Tcl_IncrRefCount(apColName[i]);
1370 }
1371 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001372 }
1373
1374 /* If results are being stored in an array variable, then create
1375 ** the array(*) entry for that array
1376 */
dan4a4c11a2009-10-06 14:59:02 +00001377 if( p->pArray ){
1378 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001379 Tcl_Obj *pColList = Tcl_NewObj();
1380 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001381
danielk19778e556522007-11-13 10:30:24 +00001382 for(i=0; i<nCol; i++){
1383 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1384 }
1385 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001386 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001387 Tcl_DecrRefCount(pStar);
1388 }
danielk19778e556522007-11-13 10:30:24 +00001389 }
1390
dan4a4c11a2009-10-06 14:59:02 +00001391 if( papColName ){
1392 *papColName = p->apColName;
1393 }
1394 if( pnCol ){
1395 *pnCol = p->nCol;
1396 }
1397}
1398
1399/*
1400** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1401** returned, then an error message is stored in the interpreter before
1402** returning.
1403**
1404** A return value of TCL_OK means there is a row of data available. The
1405** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1406** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1407** is returned, then the SQL script has finished executing and there are
1408** no further rows available. This is similar to SQLITE_DONE.
1409*/
1410static int dbEvalStep(DbEvalContext *p){
danc431fd52011-06-27 16:55:50 +00001411 const char *zPrevSql = 0; /* Previous value of p->zSql */
1412
dan4a4c11a2009-10-06 14:59:02 +00001413 while( p->zSql[0] || p->pPreStmt ){
1414 int rc;
1415 if( p->pPreStmt==0 ){
danc431fd52011-06-27 16:55:50 +00001416 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
dan4a4c11a2009-10-06 14:59:02 +00001417 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1418 if( rc!=TCL_OK ) return rc;
1419 }else{
1420 int rcs;
1421 SqliteDb *pDb = p->pDb;
1422 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1423 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1424
1425 rcs = sqlite3_step(pStmt);
1426 if( rcs==SQLITE_ROW ){
1427 return TCL_OK;
1428 }
1429 if( p->pArray ){
1430 dbEvalRowInfo(p, 0, 0);
1431 }
1432 rcs = sqlite3_reset(pStmt);
1433
1434 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1435 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001436 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
dan4a4c11a2009-10-06 14:59:02 +00001437 dbReleaseColumnNames(p);
1438 p->pPreStmt = 0;
1439
1440 if( rcs!=SQLITE_OK ){
1441 /* If a run-time error occurs, report the error and stop reading
1442 ** the SQL. */
dan4a4c11a2009-10-06 14:59:02 +00001443 dbReleaseStmt(pDb, pPreStmt, 1);
danc431fd52011-06-27 16:55:50 +00001444#if SQLITE_TEST
1445 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1446 /* If the runtime error was an SQLITE_SCHEMA, and the database
1447 ** handle is configured to use the legacy sqlite3_prepare()
1448 ** interface, retry prepare()/step() on the same SQL statement.
1449 ** This only happens once. If there is a second SQLITE_SCHEMA
1450 ** error, the error will be returned to the caller. */
1451 p->zSql = zPrevSql;
1452 continue;
1453 }
1454#endif
1455 Tcl_SetObjResult(pDb->interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
dan4a4c11a2009-10-06 14:59:02 +00001456 return TCL_ERROR;
1457 }else{
1458 dbReleaseStmt(pDb, pPreStmt, 0);
1459 }
1460 }
1461 }
1462
1463 /* Finished */
1464 return TCL_BREAK;
1465}
1466
1467/*
1468** Free all resources currently held by the DbEvalContext structure passed
1469** as the first argument. There should be exactly one call to this function
1470** for each call to dbEvalInit().
1471*/
1472static void dbEvalFinalize(DbEvalContext *p){
1473 if( p->pPreStmt ){
1474 sqlite3_reset(p->pPreStmt->pStmt);
1475 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1476 p->pPreStmt = 0;
1477 }
1478 if( p->pArray ){
1479 Tcl_DecrRefCount(p->pArray);
1480 p->pArray = 0;
1481 }
1482 Tcl_DecrRefCount(p->pSql);
1483 dbReleaseColumnNames(p);
1484}
1485
1486/*
1487** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1488** the value for the iCol'th column of the row currently pointed to by
1489** the DbEvalContext structure passed as the first argument.
1490*/
1491static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1492 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1493 switch( sqlite3_column_type(pStmt, iCol) ){
1494 case SQLITE_BLOB: {
1495 int bytes = sqlite3_column_bytes(pStmt, iCol);
1496 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1497 if( !zBlob ) bytes = 0;
1498 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1499 }
1500 case SQLITE_INTEGER: {
1501 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1502 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +00001503 return Tcl_NewIntObj((int)v);
dan4a4c11a2009-10-06 14:59:02 +00001504 }else{
1505 return Tcl_NewWideIntObj(v);
1506 }
1507 }
1508 case SQLITE_FLOAT: {
1509 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1510 }
1511 case SQLITE_NULL: {
1512 return dbTextToObj(p->pDb->zNull);
1513 }
1514 }
1515
1516 return dbTextToObj((char *)sqlite3_column_text(pStmt, iCol));
1517}
1518
1519/*
1520** If using Tcl version 8.6 or greater, use the NR functions to avoid
1521** recursive evalution of scripts by the [db eval] and [db trans]
1522** commands. Even if the headers used while compiling the extension
1523** are 8.6 or newer, the code still tests the Tcl version at runtime.
1524** This allows stubs-enabled builds to be used with older Tcl libraries.
1525*/
1526#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001527# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001528static int DbUseNre(void){
1529 int major, minor;
1530 Tcl_GetVersion(&major, &minor, 0, 0);
1531 return( (major==8 && minor>=6) || major>8 );
1532}
1533#else
1534/*
1535** Compiling using headers earlier than 8.6. In this case NR cannot be
1536** used, so DbUseNre() to always return zero. Add #defines for the other
1537** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1538** even though the only invocations of them are within conditional blocks
1539** of the form:
1540**
1541** if( DbUseNre() ) { ... }
1542*/
drha2c8a952009-10-13 18:38:34 +00001543# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001544# define DbUseNre() 0
1545# define Tcl_NRAddCallback(a,b,c,d,e,f) 0
1546# define Tcl_NREvalObj(a,b,c) 0
1547# define Tcl_NRCreateCommand(a,b,c,d,e,f) 0
1548#endif
1549
1550/*
1551** This function is part of the implementation of the command:
1552**
1553** $db eval SQL ?ARRAYNAME? SCRIPT
1554*/
1555static int DbEvalNextCmd(
1556 ClientData data[], /* data[0] is the (DbEvalContext*) */
1557 Tcl_Interp *interp, /* Tcl interpreter */
1558 int result /* Result so far */
1559){
1560 int rc = result; /* Return code */
1561
1562 /* The first element of the data[] array is a pointer to a DbEvalContext
1563 ** structure allocated using Tcl_Alloc(). The second element of data[]
1564 ** is a pointer to a Tcl_Obj containing the script to run for each row
1565 ** returned by the queries encapsulated in data[0]. */
1566 DbEvalContext *p = (DbEvalContext *)data[0];
1567 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1568 Tcl_Obj *pArray = p->pArray;
1569
1570 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1571 int i;
1572 int nCol;
1573 Tcl_Obj **apColName;
1574 dbEvalRowInfo(p, &nCol, &apColName);
1575 for(i=0; i<nCol; i++){
1576 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1577 if( pArray==0 ){
1578 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1579 }else{
1580 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1581 }
1582 }
1583
1584 /* The required interpreter variables are now populated with the data
1585 ** from the current row. If using NRE, schedule callbacks to evaluate
1586 ** script pScript, then to invoke this function again to fetch the next
1587 ** row (or clean up if there is no next row or the script throws an
1588 ** exception). After scheduling the callbacks, return control to the
1589 ** caller.
1590 **
1591 ** If not using NRE, evaluate pScript directly and continue with the
1592 ** next iteration of this while(...) loop. */
1593 if( DbUseNre() ){
1594 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1595 return Tcl_NREvalObj(interp, pScript, 0);
1596 }else{
1597 rc = Tcl_EvalObjEx(interp, pScript, 0);
1598 }
1599 }
1600
1601 Tcl_DecrRefCount(pScript);
1602 dbEvalFinalize(p);
1603 Tcl_Free((char *)p);
1604
1605 if( rc==TCL_OK || rc==TCL_BREAK ){
1606 Tcl_ResetResult(interp);
1607 rc = TCL_OK;
1608 }
1609 return rc;
danielk19778e556522007-11-13 10:30:24 +00001610}
1611
tpoindex1067fe12004-12-17 15:41:11 +00001612/*
drh75897232000-05-29 14:26:00 +00001613** The "sqlite" command below creates a new Tcl command for each
1614** connection it opens to an SQLite database. This routine is invoked
1615** whenever one of those connection-specific commands is executed
1616** in Tcl. For example, if you run Tcl code like this:
1617**
drh9bb575f2004-09-06 17:24:11 +00001618** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001619** db1 close
1620**
1621** The first command opens a connection to the "my_database" database
1622** and calls that connection "db1". The second command causes this
1623** subroutine to be invoked.
1624*/
drh6d313162000-09-21 13:01:35 +00001625static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001626 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001627 int choice;
drh22fbcb82004-02-01 01:22:50 +00001628 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001629 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001630 "authorizer", "backup", "busy",
1631 "cache", "changes", "close",
1632 "collate", "collation_needed", "commit_hook",
1633 "complete", "copy", "enable_load_extension",
1634 "errorcode", "eval", "exists",
1635 "function", "incrblob", "interrupt",
drh833bf962010-04-28 14:42:19 +00001636 "last_insert_rowid", "nullvalue", "onecolumn",
1637 "profile", "progress", "rekey",
1638 "restore", "rollback_hook", "status",
1639 "timeout", "total_changes", "trace",
1640 "transaction", "unlock_notify", "update_hook",
1641 "version", "wal_hook", 0
drh6d313162000-09-21 13:01:35 +00001642 };
drh411995d2002-06-25 19:31:18 +00001643 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001644 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1645 DB_CACHE, DB_CHANGES, DB_CLOSE,
1646 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1647 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1648 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1649 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
drh833bf962010-04-28 14:42:19 +00001650 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
1651 DB_PROFILE, DB_PROGRESS, DB_REKEY,
1652 DB_RESTORE, DB_ROLLBACK_HOOK, DB_STATUS,
1653 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
1654 DB_TRANSACTION, DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK,
1655 DB_VERSION, DB_WAL_HOOK
drh6d313162000-09-21 13:01:35 +00001656 };
tpoindex1067fe12004-12-17 15:41:11 +00001657 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001658
1659 if( objc<2 ){
1660 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001661 return TCL_ERROR;
1662 }
drh411995d2002-06-25 19:31:18 +00001663 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001664 return TCL_ERROR;
1665 }
1666
drh411995d2002-06-25 19:31:18 +00001667 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001668
drhe22a3342003-04-22 20:30:37 +00001669 /* $db authorizer ?CALLBACK?
1670 **
1671 ** Invoke the given callback to authorize each SQL operation as it is
1672 ** compiled. 5 arguments are appended to the callback before it is
1673 ** invoked:
1674 **
1675 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1676 ** (2) First descriptive name (depends on authorization type)
1677 ** (3) Second descriptive name
1678 ** (4) Name of the database (ex: "main", "temp")
1679 ** (5) Name of trigger that is doing the access
1680 **
1681 ** The callback should return on of the following strings: SQLITE_OK,
1682 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1683 **
1684 ** If this method is invoked with no arguments, the current authorization
1685 ** callback string is returned.
1686 */
1687 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001688#ifdef SQLITE_OMIT_AUTHORIZATION
1689 Tcl_AppendResult(interp, "authorization not available in this build", 0);
1690 return TCL_ERROR;
1691#else
drhe22a3342003-04-22 20:30:37 +00001692 if( objc>3 ){
1693 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001694 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001695 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001696 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +00001697 Tcl_AppendResult(interp, pDb->zAuth, 0);
1698 }
1699 }else{
1700 char *zAuth;
1701 int len;
1702 if( pDb->zAuth ){
1703 Tcl_Free(pDb->zAuth);
1704 }
1705 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1706 if( zAuth && len>0 ){
1707 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001708 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001709 }else{
1710 pDb->zAuth = 0;
1711 }
drhe22a3342003-04-22 20:30:37 +00001712 if( pDb->zAuth ){
1713 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001714 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +00001715 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001716 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001717 }
drhe22a3342003-04-22 20:30:37 +00001718 }
drh1211de32004-07-26 12:24:22 +00001719#endif
drhe22a3342003-04-22 20:30:37 +00001720 break;
1721 }
1722
drhdc2c4912009-02-04 22:46:47 +00001723 /* $db backup ?DATABASE? FILENAME
1724 **
1725 ** Open or create a database file named FILENAME. Transfer the
1726 ** content of local database DATABASE (default: "main") into the
1727 ** FILENAME database.
1728 */
1729 case DB_BACKUP: {
1730 const char *zDestFile;
1731 const char *zSrcDb;
1732 sqlite3 *pDest;
1733 sqlite3_backup *pBackup;
1734
1735 if( objc==3 ){
1736 zSrcDb = "main";
1737 zDestFile = Tcl_GetString(objv[2]);
1738 }else if( objc==4 ){
1739 zSrcDb = Tcl_GetString(objv[2]);
1740 zDestFile = Tcl_GetString(objv[3]);
1741 }else{
1742 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1743 return TCL_ERROR;
1744 }
1745 rc = sqlite3_open(zDestFile, &pDest);
1746 if( rc!=SQLITE_OK ){
1747 Tcl_AppendResult(interp, "cannot open target database: ",
1748 sqlite3_errmsg(pDest), (char*)0);
1749 sqlite3_close(pDest);
1750 return TCL_ERROR;
1751 }
1752 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1753 if( pBackup==0 ){
1754 Tcl_AppendResult(interp, "backup failed: ",
1755 sqlite3_errmsg(pDest), (char*)0);
1756 sqlite3_close(pDest);
1757 return TCL_ERROR;
1758 }
1759 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1760 sqlite3_backup_finish(pBackup);
1761 if( rc==SQLITE_DONE ){
1762 rc = TCL_OK;
1763 }else{
1764 Tcl_AppendResult(interp, "backup failed: ",
1765 sqlite3_errmsg(pDest), (char*)0);
1766 rc = TCL_ERROR;
1767 }
1768 sqlite3_close(pDest);
1769 break;
1770 }
1771
drhbec3f402000-08-04 13:49:02 +00001772 /* $db busy ?CALLBACK?
1773 **
1774 ** Invoke the given callback if an SQL statement attempts to open
1775 ** a locked database file.
1776 */
drh6d313162000-09-21 13:01:35 +00001777 case DB_BUSY: {
1778 if( objc>3 ){
1779 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001780 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001781 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001782 if( pDb->zBusy ){
1783 Tcl_AppendResult(interp, pDb->zBusy, 0);
1784 }
1785 }else{
drh6d313162000-09-21 13:01:35 +00001786 char *zBusy;
1787 int len;
drhbec3f402000-08-04 13:49:02 +00001788 if( pDb->zBusy ){
1789 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001790 }
drh6d313162000-09-21 13:01:35 +00001791 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1792 if( zBusy && len>0 ){
1793 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001794 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001795 }else{
1796 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001797 }
1798 if( pDb->zBusy ){
1799 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001800 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001801 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001802 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001803 }
1804 }
drh6d313162000-09-21 13:01:35 +00001805 break;
1806 }
drhbec3f402000-08-04 13:49:02 +00001807
drhfb7e7652005-01-24 00:28:42 +00001808 /* $db cache flush
1809 ** $db cache size n
1810 **
1811 ** Flush the prepared statement cache, or set the maximum number of
1812 ** cached statements.
1813 */
1814 case DB_CACHE: {
1815 char *subCmd;
1816 int n;
1817
1818 if( objc<=2 ){
1819 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1820 return TCL_ERROR;
1821 }
1822 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1823 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1824 if( objc!=3 ){
1825 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1826 return TCL_ERROR;
1827 }else{
1828 flushStmtCache( pDb );
1829 }
1830 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1831 if( objc!=4 ){
1832 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1833 return TCL_ERROR;
1834 }else{
1835 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1836 Tcl_AppendResult( interp, "cannot convert \"",
1837 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1838 return TCL_ERROR;
1839 }else{
1840 if( n<0 ){
1841 flushStmtCache( pDb );
1842 n = 0;
1843 }else if( n>MAX_PREPARED_STMTS ){
1844 n = MAX_PREPARED_STMTS;
1845 }
1846 pDb->maxStmt = n;
1847 }
1848 }
1849 }else{
1850 Tcl_AppendResult( interp, "bad option \"",
danielk1977191fadc2007-10-23 08:17:48 +00001851 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
drhfb7e7652005-01-24 00:28:42 +00001852 return TCL_ERROR;
1853 }
1854 break;
1855 }
1856
danielk1977b28af712004-06-21 06:50:26 +00001857 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001858 **
1859 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001860 ** the most recent INSERT, UPDATE or DELETE statement, not including
1861 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001862 */
1863 case DB_CHANGES: {
1864 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001865 if( objc!=2 ){
1866 Tcl_WrongNumArgs(interp, 2, objv, "");
1867 return TCL_ERROR;
1868 }
drhc8d30ac2002-04-12 10:08:59 +00001869 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001870 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001871 break;
1872 }
1873
drh75897232000-05-29 14:26:00 +00001874 /* $db close
1875 **
1876 ** Shutdown the database
1877 */
drh6d313162000-09-21 13:01:35 +00001878 case DB_CLOSE: {
1879 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1880 break;
1881 }
drh75897232000-05-29 14:26:00 +00001882
drh0f14e2e2004-06-29 12:39:08 +00001883 /*
1884 ** $db collate NAME SCRIPT
1885 **
1886 ** Create a new SQL collation function called NAME. Whenever
1887 ** that function is called, invoke SCRIPT to evaluate the function.
1888 */
1889 case DB_COLLATE: {
1890 SqlCollate *pCollate;
1891 char *zName;
1892 char *zScript;
1893 int nScript;
1894 if( objc!=4 ){
1895 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1896 return TCL_ERROR;
1897 }
1898 zName = Tcl_GetStringFromObj(objv[2], 0);
1899 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1900 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1901 if( pCollate==0 ) return TCL_ERROR;
1902 pCollate->interp = interp;
1903 pCollate->pNext = pDb->pCollate;
1904 pCollate->zScript = (char*)&pCollate[1];
1905 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001906 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001907 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1908 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001909 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001910 return TCL_ERROR;
1911 }
1912 break;
1913 }
1914
1915 /*
1916 ** $db collation_needed SCRIPT
1917 **
1918 ** Create a new SQL collation function called NAME. Whenever
1919 ** that function is called, invoke SCRIPT to evaluate the function.
1920 */
1921 case DB_COLLATION_NEEDED: {
1922 if( objc!=3 ){
1923 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1924 return TCL_ERROR;
1925 }
1926 if( pDb->pCollateNeeded ){
1927 Tcl_DecrRefCount(pDb->pCollateNeeded);
1928 }
1929 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1930 Tcl_IncrRefCount(pDb->pCollateNeeded);
1931 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1932 break;
1933 }
1934
drh19e2d372005-08-29 23:00:03 +00001935 /* $db commit_hook ?CALLBACK?
1936 **
1937 ** Invoke the given callback just before committing every SQL transaction.
1938 ** If the callback throws an exception or returns non-zero, then the
1939 ** transaction is aborted. If CALLBACK is an empty string, the callback
1940 ** is disabled.
1941 */
1942 case DB_COMMIT_HOOK: {
1943 if( objc>3 ){
1944 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1945 return TCL_ERROR;
1946 }else if( objc==2 ){
1947 if( pDb->zCommit ){
1948 Tcl_AppendResult(interp, pDb->zCommit, 0);
1949 }
1950 }else{
1951 char *zCommit;
1952 int len;
1953 if( pDb->zCommit ){
1954 Tcl_Free(pDb->zCommit);
1955 }
1956 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1957 if( zCommit && len>0 ){
1958 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001959 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001960 }else{
1961 pDb->zCommit = 0;
1962 }
1963 if( pDb->zCommit ){
1964 pDb->interp = interp;
1965 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1966 }else{
1967 sqlite3_commit_hook(pDb->db, 0, 0);
1968 }
1969 }
1970 break;
1971 }
1972
drh75897232000-05-29 14:26:00 +00001973 /* $db complete SQL
1974 **
1975 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1976 ** additional lines of input are needed. This is similar to the
1977 ** built-in "info complete" command of Tcl.
1978 */
drh6d313162000-09-21 13:01:35 +00001979 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00001980#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00001981 Tcl_Obj *pResult;
1982 int isComplete;
1983 if( objc!=3 ){
1984 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00001985 return TCL_ERROR;
1986 }
danielk19776f8a5032004-05-10 10:34:51 +00001987 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00001988 pResult = Tcl_GetObjResult(interp);
1989 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00001990#endif
drh6d313162000-09-21 13:01:35 +00001991 break;
1992 }
drhdcd997e2003-01-31 17:21:49 +00001993
drh19e2d372005-08-29 23:00:03 +00001994 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1995 **
1996 ** Copy data into table from filename, optionally using SEPARATOR
1997 ** as column separators. If a column contains a null string, or the
1998 ** value of NULLINDICATOR, a NULL is inserted for the column.
1999 ** conflict-algorithm is one of the sqlite conflict algorithms:
2000 ** rollback, abort, fail, ignore, replace
2001 ** On success, return the number of lines processed, not necessarily same
2002 ** as 'db changes' due to conflict-algorithm selected.
2003 **
2004 ** This code is basically an implementation/enhancement of
2005 ** the sqlite3 shell.c ".import" command.
2006 **
2007 ** This command usage is equivalent to the sqlite2.x COPY statement,
2008 ** which imports file data into a table using the PostgreSQL COPY file format:
2009 ** $db copy $conflit_algo $table_name $filename \t \\N
2010 */
2011 case DB_COPY: {
2012 char *zTable; /* Insert data into this table */
2013 char *zFile; /* The file from which to extract data */
2014 char *zConflict; /* The conflict algorithm to use */
2015 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00002016 int nCol; /* Number of columns in the table */
2017 int nByte; /* Number of bytes in an SQL string */
2018 int i, j; /* Loop counters */
2019 int nSep; /* Number of bytes in zSep[] */
2020 int nNull; /* Number of bytes in zNull[] */
2021 char *zSql; /* An SQL statement */
2022 char *zLine; /* A single line of input from the file */
2023 char **azCol; /* zLine[] broken up into columns */
2024 char *zCommit; /* How to commit changes */
2025 FILE *in; /* The input file */
2026 int lineno = 0; /* Line number of input file */
2027 char zLineNum[80]; /* Line number print buffer */
2028 Tcl_Obj *pResult; /* interp result */
2029
2030 char *zSep;
2031 char *zNull;
2032 if( objc<5 || objc>7 ){
2033 Tcl_WrongNumArgs(interp, 2, objv,
2034 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2035 return TCL_ERROR;
2036 }
2037 if( objc>=6 ){
2038 zSep = Tcl_GetStringFromObj(objv[5], 0);
2039 }else{
2040 zSep = "\t";
2041 }
2042 if( objc>=7 ){
2043 zNull = Tcl_GetStringFromObj(objv[6], 0);
2044 }else{
2045 zNull = "";
2046 }
2047 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2048 zTable = Tcl_GetStringFromObj(objv[3], 0);
2049 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002050 nSep = strlen30(zSep);
2051 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002052 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00002053 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00002054 return TCL_ERROR;
2055 }
drh3e59c012008-09-23 10:12:13 +00002056 if(strcmp(zConflict, "rollback") != 0 &&
2057 strcmp(zConflict, "abort" ) != 0 &&
2058 strcmp(zConflict, "fail" ) != 0 &&
2059 strcmp(zConflict, "ignore" ) != 0 &&
2060 strcmp(zConflict, "replace" ) != 0 ) {
drh19e2d372005-08-29 23:00:03 +00002061 Tcl_AppendResult(interp, "Error: \"", zConflict,
2062 "\", conflict-algorithm must be one of: rollback, "
2063 "abort, fail, ignore, or replace", 0);
2064 return TCL_ERROR;
2065 }
2066 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2067 if( zSql==0 ){
2068 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
2069 return TCL_ERROR;
2070 }
drh4f21c4a2008-12-10 22:15:00 +00002071 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002072 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002073 sqlite3_free(zSql);
2074 if( rc ){
2075 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2076 nCol = 0;
2077 }else{
2078 nCol = sqlite3_column_count(pStmt);
2079 }
2080 sqlite3_finalize(pStmt);
2081 if( nCol==0 ) {
2082 return TCL_ERROR;
2083 }
2084 zSql = malloc( nByte + 50 + nCol*2 );
2085 if( zSql==0 ) {
2086 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
2087 return TCL_ERROR;
2088 }
2089 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2090 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002091 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002092 for(i=1; i<nCol; i++){
2093 zSql[j++] = ',';
2094 zSql[j++] = '?';
2095 }
2096 zSql[j++] = ')';
2097 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002098 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002099 free(zSql);
2100 if( rc ){
2101 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2102 sqlite3_finalize(pStmt);
2103 return TCL_ERROR;
2104 }
2105 in = fopen(zFile, "rb");
2106 if( in==0 ){
2107 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2108 sqlite3_finalize(pStmt);
2109 return TCL_ERROR;
2110 }
2111 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2112 if( azCol==0 ) {
2113 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00002114 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002115 return TCL_ERROR;
2116 }
drh37527852006-03-16 16:19:56 +00002117 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002118 zCommit = "COMMIT";
2119 while( (zLine = local_getline(0, in))!=0 ){
2120 char *z;
drh19e2d372005-08-29 23:00:03 +00002121 lineno++;
2122 azCol[0] = zLine;
2123 for(i=0, z=zLine; *z; z++){
2124 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2125 *z = 0;
2126 i++;
2127 if( i<nCol ){
2128 azCol[i] = &z[nSep];
2129 z += nSep-1;
2130 }
2131 }
2132 }
2133 if( i+1!=nCol ){
2134 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002135 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002136 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002137 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002138 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002139 "Error: %s line %d: expected %d columns of data but found %d",
2140 zFile, lineno, nCol, i+1);
2141 Tcl_AppendResult(interp, zErr, 0);
2142 free(zErr);
2143 }
drh19e2d372005-08-29 23:00:03 +00002144 zCommit = "ROLLBACK";
2145 break;
2146 }
2147 for(i=0; i<nCol; i++){
2148 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002149 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
drh4f21c4a2008-12-10 22:15:00 +00002150 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002151 ){
drh19e2d372005-08-29 23:00:03 +00002152 sqlite3_bind_null(pStmt, i+1);
2153 }else{
2154 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2155 }
2156 }
2157 sqlite3_step(pStmt);
2158 rc = sqlite3_reset(pStmt);
2159 free(zLine);
2160 if( rc!=SQLITE_OK ){
2161 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
2162 zCommit = "ROLLBACK";
2163 break;
2164 }
2165 }
2166 free(azCol);
2167 fclose(in);
2168 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002169 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002170
2171 if( zCommit[0] == 'C' ){
2172 /* success, set result as number of lines processed */
2173 pResult = Tcl_GetObjResult(interp);
2174 Tcl_SetIntObj(pResult, lineno);
2175 rc = TCL_OK;
2176 }else{
2177 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002178 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00002179 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
2180 rc = TCL_ERROR;
2181 }
2182 break;
2183 }
2184
drhdcd997e2003-01-31 17:21:49 +00002185 /*
drh41449052006-07-06 17:08:48 +00002186 ** $db enable_load_extension BOOLEAN
2187 **
2188 ** Turn the extension loading feature on or off. It if off by
2189 ** default.
2190 */
2191 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002192#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002193 int onoff;
2194 if( objc!=3 ){
2195 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2196 return TCL_ERROR;
2197 }
2198 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2199 return TCL_ERROR;
2200 }
2201 sqlite3_enable_load_extension(pDb->db, onoff);
2202 break;
drhf533acc2006-12-19 18:57:11 +00002203#else
2204 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2205 0);
2206 return TCL_ERROR;
2207#endif
drh41449052006-07-06 17:08:48 +00002208 }
2209
2210 /*
drhdcd997e2003-01-31 17:21:49 +00002211 ** $db errorcode
2212 **
2213 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002214 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002215 */
2216 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002217 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002218 break;
2219 }
dan4a4c11a2009-10-06 14:59:02 +00002220
2221 /*
2222 ** $db exists $sql
2223 ** $db onecolumn $sql
2224 **
2225 ** The onecolumn method is the equivalent of:
2226 ** lindex [$db eval $sql] 0
2227 */
2228 case DB_EXISTS:
2229 case DB_ONECOLUMN: {
2230 DbEvalContext sEval;
2231 if( objc!=3 ){
2232 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2233 return TCL_ERROR;
2234 }
2235
2236 dbEvalInit(&sEval, pDb, objv[2], 0);
2237 rc = dbEvalStep(&sEval);
2238 if( choice==DB_ONECOLUMN ){
2239 if( rc==TCL_OK ){
2240 Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
dand5f12cd2011-08-18 17:47:57 +00002241 }else if( rc==TCL_BREAK ){
2242 Tcl_ResetResult(interp);
dan4a4c11a2009-10-06 14:59:02 +00002243 }
2244 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2245 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
2246 }
2247 dbEvalFinalize(&sEval);
2248
2249 if( rc==TCL_BREAK ){
2250 rc = TCL_OK;
2251 }
2252 break;
2253 }
drh75897232000-05-29 14:26:00 +00002254
2255 /*
drh895d7472004-08-20 16:02:39 +00002256 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002257 **
2258 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002259 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002260 ** If "array" and "code" are omitted, then no callback is every invoked.
2261 ** If "array" is an empty string, then the values are placed in variables
2262 ** that have the same name as the fields extracted by the query.
2263 */
dan4a4c11a2009-10-06 14:59:02 +00002264 case DB_EVAL: {
2265 if( objc<3 || objc>5 ){
2266 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2267 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002268 }
dan4a4c11a2009-10-06 14:59:02 +00002269
drh92febd92004-08-20 18:34:20 +00002270 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002271 DbEvalContext sEval;
2272 Tcl_Obj *pRet = Tcl_NewObj();
2273 Tcl_IncrRefCount(pRet);
2274 dbEvalInit(&sEval, pDb, objv[2], 0);
2275 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2276 int i;
2277 int nCol;
2278 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002279 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002280 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002281 }
2282 }
dan4a4c11a2009-10-06 14:59:02 +00002283 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002284 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002285 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002286 rc = TCL_OK;
2287 }
drh1807ce32004-09-07 13:20:35 +00002288 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002289 }else{
2290 ClientData cd[2];
2291 DbEvalContext *p;
2292 Tcl_Obj *pArray = 0;
2293 Tcl_Obj *pScript;
2294
2295 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2296 pArray = objv[3];
2297 }
2298 pScript = objv[objc-1];
2299 Tcl_IncrRefCount(pScript);
2300
2301 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2302 dbEvalInit(p, pDb, objv[2], pArray);
2303
2304 cd[0] = (void *)p;
2305 cd[1] = (void *)pScript;
2306 rc = DbEvalNextCmd(cd, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002307 }
danielk197730ccda12004-05-27 12:11:31 +00002308 break;
2309 }
drhbec3f402000-08-04 13:49:02 +00002310
2311 /*
drhe3602be2008-09-09 12:31:33 +00002312 ** $db function NAME [-argcount N] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002313 **
2314 ** Create a new SQL function called NAME. Whenever that function is
2315 ** called, invoke SCRIPT to evaluate the function.
2316 */
2317 case DB_FUNCTION: {
2318 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002319 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002320 char *zName;
drhe3602be2008-09-09 12:31:33 +00002321 int nArg = -1;
2322 if( objc==6 ){
2323 const char *z = Tcl_GetString(objv[3]);
drh4f21c4a2008-12-10 22:15:00 +00002324 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002325 if( n>2 && strncmp(z, "-argcount",n)==0 ){
2326 if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
2327 if( nArg<0 ){
2328 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2329 (char*)0);
2330 return TCL_ERROR;
2331 }
2332 }
2333 pScript = objv[5];
2334 }else if( objc!=4 ){
2335 Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
drhcabb0812002-09-14 13:47:32 +00002336 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002337 }else{
2338 pScript = objv[3];
drhcabb0812002-09-14 13:47:32 +00002339 }
2340 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002341 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002342 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002343 if( pFunc->pScript ){
2344 Tcl_DecrRefCount(pFunc->pScript);
2345 }
2346 pFunc->pScript = pScript;
2347 Tcl_IncrRefCount(pScript);
2348 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
drhe3602be2008-09-09 12:31:33 +00002349 rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00002350 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002351 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002352 rc = TCL_ERROR;
2353 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002354 }
drhcabb0812002-09-14 13:47:32 +00002355 break;
2356 }
2357
2358 /*
danielk19778cbadb02007-05-03 16:31:26 +00002359 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002360 */
2361 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002362#ifdef SQLITE_OMIT_INCRBLOB
2363 Tcl_AppendResult(interp, "incrblob not available in this build", 0);
2364 return TCL_ERROR;
2365#else
danielk19778cbadb02007-05-03 16:31:26 +00002366 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002367 const char *zDb = "main";
2368 const char *zTable;
2369 const char *zColumn;
2370 sqlite_int64 iRow;
2371
danielk19778cbadb02007-05-03 16:31:26 +00002372 /* Check for the -readonly option */
2373 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2374 isReadonly = 1;
2375 }
2376
2377 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2378 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002379 return TCL_ERROR;
2380 }
2381
danielk19778cbadb02007-05-03 16:31:26 +00002382 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002383 zDb = Tcl_GetString(objv[2]);
2384 }
2385 zTable = Tcl_GetString(objv[objc-3]);
2386 zColumn = Tcl_GetString(objv[objc-2]);
2387 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2388
2389 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002390 rc = createIncrblobChannel(
2391 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
2392 );
danielk1977b4e9af92007-05-01 17:49:49 +00002393 }
danielk197732a0d8b2007-05-04 19:03:02 +00002394#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002395 break;
2396 }
2397
2398 /*
drhf11bded2006-07-17 00:02:44 +00002399 ** $db interrupt
2400 **
2401 ** Interrupt the execution of the inner-most SQL interpreter. This
2402 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2403 */
2404 case DB_INTERRUPT: {
2405 sqlite3_interrupt(pDb->db);
2406 break;
2407 }
2408
2409 /*
drh19e2d372005-08-29 23:00:03 +00002410 ** $db nullvalue ?STRING?
2411 **
2412 ** Change text used when a NULL comes back from the database. If ?STRING?
2413 ** is not present, then the current string used for NULL is returned.
2414 ** If STRING is present, then STRING is returned.
2415 **
2416 */
2417 case DB_NULLVALUE: {
2418 if( objc!=2 && objc!=3 ){
2419 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2420 return TCL_ERROR;
2421 }
2422 if( objc==3 ){
2423 int len;
2424 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2425 if( pDb->zNull ){
2426 Tcl_Free(pDb->zNull);
2427 }
2428 if( zNull && len>0 ){
2429 pDb->zNull = Tcl_Alloc( len + 1 );
drh7fd33922011-06-20 19:00:30 +00002430 memcpy(pDb->zNull, zNull, len);
drh19e2d372005-08-29 23:00:03 +00002431 pDb->zNull[len] = '\0';
2432 }else{
2433 pDb->zNull = 0;
2434 }
2435 }
2436 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
2437 break;
2438 }
2439
2440 /*
drhaf9ff332002-01-16 21:00:27 +00002441 ** $db last_insert_rowid
2442 **
2443 ** Return an integer which is the ROWID for the most recent insert.
2444 */
2445 case DB_LAST_INSERT_ROWID: {
2446 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002447 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002448 if( objc!=2 ){
2449 Tcl_WrongNumArgs(interp, 2, objv, "");
2450 return TCL_ERROR;
2451 }
danielk19776f8a5032004-05-10 10:34:51 +00002452 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002453 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002454 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002455 break;
2456 }
2457
2458 /*
dan4a4c11a2009-10-06 14:59:02 +00002459 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002460 */
drh1807ce32004-09-07 13:20:35 +00002461
2462 /* $db progress ?N CALLBACK?
2463 **
2464 ** Invoke the given callback every N virtual machine opcodes while executing
2465 ** queries.
2466 */
2467 case DB_PROGRESS: {
2468 if( objc==2 ){
2469 if( pDb->zProgress ){
2470 Tcl_AppendResult(interp, pDb->zProgress, 0);
2471 }
2472 }else if( objc==4 ){
2473 char *zProgress;
2474 int len;
2475 int N;
2476 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002477 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002478 };
2479 if( pDb->zProgress ){
2480 Tcl_Free(pDb->zProgress);
2481 }
2482 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2483 if( zProgress && len>0 ){
2484 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002485 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002486 }else{
2487 pDb->zProgress = 0;
2488 }
2489#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2490 if( pDb->zProgress ){
2491 pDb->interp = interp;
2492 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2493 }else{
2494 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2495 }
2496#endif
2497 }else{
2498 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002499 return TCL_ERROR;
2500 }
drh5d9d7572003-08-19 14:31:01 +00002501 break;
2502 }
2503
drh19e2d372005-08-29 23:00:03 +00002504 /* $db profile ?CALLBACK?
2505 **
2506 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2507 ** that has run. The text of the SQL and the amount of elapse time are
2508 ** appended to CALLBACK before the script is run.
2509 */
2510 case DB_PROFILE: {
2511 if( objc>3 ){
2512 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2513 return TCL_ERROR;
2514 }else if( objc==2 ){
2515 if( pDb->zProfile ){
2516 Tcl_AppendResult(interp, pDb->zProfile, 0);
2517 }
2518 }else{
2519 char *zProfile;
2520 int len;
2521 if( pDb->zProfile ){
2522 Tcl_Free(pDb->zProfile);
2523 }
2524 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2525 if( zProfile && len>0 ){
2526 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002527 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002528 }else{
2529 pDb->zProfile = 0;
2530 }
shanehbb201342011-02-09 19:55:20 +00002531#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh19e2d372005-08-29 23:00:03 +00002532 if( pDb->zProfile ){
2533 pDb->interp = interp;
2534 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2535 }else{
2536 sqlite3_profile(pDb->db, 0, 0);
2537 }
2538#endif
2539 }
2540 break;
2541 }
2542
drh5d9d7572003-08-19 14:31:01 +00002543 /*
drh22fbcb82004-02-01 01:22:50 +00002544 ** $db rekey KEY
2545 **
2546 ** Change the encryption key on the currently open database.
2547 */
2548 case DB_REKEY: {
drhb07028f2011-10-14 21:49:18 +00002549#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002550 int nKey;
2551 void *pKey;
drhb07028f2011-10-14 21:49:18 +00002552#endif
drh22fbcb82004-02-01 01:22:50 +00002553 if( objc!=3 ){
2554 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2555 return TCL_ERROR;
2556 }
drh9eb9e262004-02-11 02:18:05 +00002557#ifdef SQLITE_HAS_CODEC
drhb07028f2011-10-14 21:49:18 +00002558 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh2011d5f2004-07-22 02:40:37 +00002559 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002560 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00002561 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002562 rc = TCL_ERROR;
2563 }
2564#endif
2565 break;
2566 }
2567
drhdc2c4912009-02-04 22:46:47 +00002568 /* $db restore ?DATABASE? FILENAME
2569 **
2570 ** Open a database file named FILENAME. Transfer the content
2571 ** of FILENAME into the local database DATABASE (default: "main").
2572 */
2573 case DB_RESTORE: {
2574 const char *zSrcFile;
2575 const char *zDestDb;
2576 sqlite3 *pSrc;
2577 sqlite3_backup *pBackup;
2578 int nTimeout = 0;
2579
2580 if( objc==3 ){
2581 zDestDb = "main";
2582 zSrcFile = Tcl_GetString(objv[2]);
2583 }else if( objc==4 ){
2584 zDestDb = Tcl_GetString(objv[2]);
2585 zSrcFile = Tcl_GetString(objv[3]);
2586 }else{
2587 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2588 return TCL_ERROR;
2589 }
2590 rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
2591 if( rc!=SQLITE_OK ){
2592 Tcl_AppendResult(interp, "cannot open source database: ",
2593 sqlite3_errmsg(pSrc), (char*)0);
2594 sqlite3_close(pSrc);
2595 return TCL_ERROR;
2596 }
2597 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2598 if( pBackup==0 ){
2599 Tcl_AppendResult(interp, "restore failed: ",
2600 sqlite3_errmsg(pDb->db), (char*)0);
2601 sqlite3_close(pSrc);
2602 return TCL_ERROR;
2603 }
2604 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2605 || rc==SQLITE_BUSY ){
2606 if( rc==SQLITE_BUSY ){
2607 if( nTimeout++ >= 3 ) break;
2608 sqlite3_sleep(100);
2609 }
2610 }
2611 sqlite3_backup_finish(pBackup);
2612 if( rc==SQLITE_DONE ){
2613 rc = TCL_OK;
2614 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2615 Tcl_AppendResult(interp, "restore failed: source database busy",
2616 (char*)0);
2617 rc = TCL_ERROR;
2618 }else{
2619 Tcl_AppendResult(interp, "restore failed: ",
2620 sqlite3_errmsg(pDb->db), (char*)0);
2621 rc = TCL_ERROR;
2622 }
2623 sqlite3_close(pSrc);
2624 break;
2625 }
2626
drh22fbcb82004-02-01 01:22:50 +00002627 /*
drh3c379b02010-04-07 19:31:59 +00002628 ** $db status (step|sort|autoindex)
drhd1d38482008-10-07 23:46:38 +00002629 **
2630 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2631 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2632 */
2633 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002634 int v;
2635 const char *zOp;
2636 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00002637 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00002638 return TCL_ERROR;
2639 }
2640 zOp = Tcl_GetString(objv[2]);
2641 if( strcmp(zOp, "step")==0 ){
2642 v = pDb->nStep;
2643 }else if( strcmp(zOp, "sort")==0 ){
2644 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002645 }else if( strcmp(zOp, "autoindex")==0 ){
2646 v = pDb->nIndex;
drhd1d38482008-10-07 23:46:38 +00002647 }else{
drh3c379b02010-04-07 19:31:59 +00002648 Tcl_AppendResult(interp,
2649 "bad argument: should be autoindex, step, or sort",
drhd1d38482008-10-07 23:46:38 +00002650 (char*)0);
2651 return TCL_ERROR;
2652 }
2653 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2654 break;
2655 }
2656
2657 /*
drhbec3f402000-08-04 13:49:02 +00002658 ** $db timeout MILLESECONDS
2659 **
2660 ** Delay for the number of milliseconds specified when a file is locked.
2661 */
drh6d313162000-09-21 13:01:35 +00002662 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002663 int ms;
drh6d313162000-09-21 13:01:35 +00002664 if( objc!=3 ){
2665 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002666 return TCL_ERROR;
2667 }
drh6d313162000-09-21 13:01:35 +00002668 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002669 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002670 break;
drh75897232000-05-29 14:26:00 +00002671 }
danielk197755c45f22005-04-03 23:54:43 +00002672
2673 /*
drh0f14e2e2004-06-29 12:39:08 +00002674 ** $db total_changes
2675 **
2676 ** Return the number of rows that were modified, inserted, or deleted
2677 ** since the database handle was created.
2678 */
2679 case DB_TOTAL_CHANGES: {
2680 Tcl_Obj *pResult;
2681 if( objc!=2 ){
2682 Tcl_WrongNumArgs(interp, 2, objv, "");
2683 return TCL_ERROR;
2684 }
2685 pResult = Tcl_GetObjResult(interp);
2686 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2687 break;
2688 }
2689
drhb5a20d32003-04-23 12:25:23 +00002690 /* $db trace ?CALLBACK?
2691 **
2692 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2693 ** that is executed. The text of the SQL is appended to CALLBACK before
2694 ** it is executed.
2695 */
2696 case DB_TRACE: {
2697 if( objc>3 ){
2698 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002699 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002700 }else if( objc==2 ){
2701 if( pDb->zTrace ){
2702 Tcl_AppendResult(interp, pDb->zTrace, 0);
2703 }
2704 }else{
2705 char *zTrace;
2706 int len;
2707 if( pDb->zTrace ){
2708 Tcl_Free(pDb->zTrace);
2709 }
2710 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2711 if( zTrace && len>0 ){
2712 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002713 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002714 }else{
2715 pDb->zTrace = 0;
2716 }
shanehbb201342011-02-09 19:55:20 +00002717#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drhb5a20d32003-04-23 12:25:23 +00002718 if( pDb->zTrace ){
2719 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002720 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002721 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002722 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002723 }
drh19e2d372005-08-29 23:00:03 +00002724#endif
drhb5a20d32003-04-23 12:25:23 +00002725 }
2726 break;
2727 }
2728
drh3d214232005-08-02 12:21:08 +00002729 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2730 **
2731 ** Start a new transaction (if we are not already in the midst of a
2732 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2733 ** completes, either commit the transaction or roll it back if SCRIPT
2734 ** throws an exception. Or if no new transation was started, do nothing.
2735 ** pass the exception on up the stack.
2736 **
2737 ** This command was inspired by Dave Thomas's talk on Ruby at the
2738 ** 2005 O'Reilly Open Source Convention (OSCON).
2739 */
2740 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00002741 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00002742 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00002743 if( objc!=3 && objc!=4 ){
2744 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2745 return TCL_ERROR;
2746 }
danielk1977cd38d522009-01-02 17:33:46 +00002747
dan4a4c11a2009-10-06 14:59:02 +00002748 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00002749 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002750 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002751 };
2752 enum TTYPE_enum {
2753 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2754 };
2755 int ttype;
drhb5555e72005-08-02 17:15:14 +00002756 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002757 0, &ttype) ){
2758 return TCL_ERROR;
2759 }
2760 switch( (enum TTYPE_enum)ttype ){
2761 case TTYPE_DEFERRED: /* no-op */; break;
2762 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2763 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2764 }
drh3d214232005-08-02 12:21:08 +00002765 }
danielk1977cd38d522009-01-02 17:33:46 +00002766 pScript = objv[objc-1];
2767
dan4a4c11a2009-10-06 14:59:02 +00002768 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00002769 pDb->disableAuth++;
2770 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2771 pDb->disableAuth--;
2772 if( rc!=SQLITE_OK ){
2773 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2774 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00002775 }
danielk1977cd38d522009-01-02 17:33:46 +00002776 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00002777
dan4a4c11a2009-10-06 14:59:02 +00002778 /* If using NRE, schedule a callback to invoke the script pScript, then
2779 ** a second callback to commit (or rollback) the transaction or savepoint
2780 ** opened above. If not using NRE, evaluate the script directly, then
2781 ** call function DbTransPostCmd() to commit (or rollback) the transaction
2782 ** or savepoint. */
2783 if( DbUseNre() ){
2784 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
2785 Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00002786 }else{
dan4a4c11a2009-10-06 14:59:02 +00002787 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00002788 }
2789 break;
2790 }
2791
danielk197794eb6a12005-12-15 15:22:08 +00002792 /*
danielk1977404ca072009-03-16 13:19:36 +00002793 ** $db unlock_notify ?script?
2794 */
2795 case DB_UNLOCK_NOTIFY: {
2796#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2797 Tcl_AppendResult(interp, "unlock_notify not available in this build", 0);
2798 rc = TCL_ERROR;
2799#else
2800 if( objc!=2 && objc!=3 ){
2801 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2802 rc = TCL_ERROR;
2803 }else{
2804 void (*xNotify)(void **, int) = 0;
2805 void *pNotifyArg = 0;
2806
2807 if( pDb->pUnlockNotify ){
2808 Tcl_DecrRefCount(pDb->pUnlockNotify);
2809 pDb->pUnlockNotify = 0;
2810 }
2811
2812 if( objc==3 ){
2813 xNotify = DbUnlockNotify;
2814 pNotifyArg = (void *)pDb;
2815 pDb->pUnlockNotify = objv[2];
2816 Tcl_IncrRefCount(pDb->pUnlockNotify);
2817 }
2818
2819 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
2820 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2821 rc = TCL_ERROR;
2822 }
2823 }
2824#endif
2825 break;
2826 }
2827
2828 /*
drh833bf962010-04-28 14:42:19 +00002829 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002830 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002831 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002832 */
drh833bf962010-04-28 14:42:19 +00002833 case DB_WAL_HOOK:
danielk197771fd80b2005-12-16 06:54:01 +00002834 case DB_UPDATE_HOOK:
2835 case DB_ROLLBACK_HOOK: {
2836
2837 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2838 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2839 */
2840 Tcl_Obj **ppHook;
2841 if( choice==DB_UPDATE_HOOK ){
2842 ppHook = &pDb->pUpdateHook;
drh833bf962010-04-28 14:42:19 +00002843 }else if( choice==DB_WAL_HOOK ){
drh5def0842010-05-05 20:00:25 +00002844 ppHook = &pDb->pWalHook;
danielk197771fd80b2005-12-16 06:54:01 +00002845 }else{
2846 ppHook = &pDb->pRollbackHook;
2847 }
2848
danielk197794eb6a12005-12-15 15:22:08 +00002849 if( objc!=2 && objc!=3 ){
2850 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2851 return TCL_ERROR;
2852 }
danielk197771fd80b2005-12-16 06:54:01 +00002853 if( *ppHook ){
2854 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002855 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002856 Tcl_DecrRefCount(*ppHook);
2857 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00002858 }
2859 }
2860 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002861 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00002862 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00002863 *ppHook = objv[2];
2864 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002865 }
2866 }
danielk197771fd80b2005-12-16 06:54:01 +00002867
2868 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2869 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
drh5def0842010-05-05 20:00:25 +00002870 sqlite3_wal_hook(pDb->db,(pDb->pWalHook?DbWalHandler:0),pDb);
danielk197771fd80b2005-12-16 06:54:01 +00002871
danielk197794eb6a12005-12-15 15:22:08 +00002872 break;
2873 }
2874
danielk19774397de52005-01-12 12:44:03 +00002875 /* $db version
2876 **
2877 ** Return the version string for this database.
2878 */
2879 case DB_VERSION: {
2880 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2881 break;
2882 }
2883
tpoindex1067fe12004-12-17 15:41:11 +00002884
drh6d313162000-09-21 13:01:35 +00002885 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002886 return rc;
drh75897232000-05-29 14:26:00 +00002887}
2888
drha2c8a952009-10-13 18:38:34 +00002889#if SQLITE_TCL_NRE
2890/*
2891** Adaptor that provides an objCmd interface to the NRE-enabled
2892** interface implementation.
2893*/
2894static int DbObjCmdAdaptor(
2895 void *cd,
2896 Tcl_Interp *interp,
2897 int objc,
2898 Tcl_Obj *const*objv
2899){
2900 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
2901}
2902#endif /* SQLITE_TCL_NRE */
2903
drh75897232000-05-29 14:26:00 +00002904/*
drh3570ad92007-08-31 14:31:44 +00002905** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00002906** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00002907**
2908** This is the main Tcl command. When the "sqlite" Tcl command is
2909** invoked, this routine runs to process that command.
2910**
2911** The first argument, DBNAME, is an arbitrary name for a new
2912** database connection. This command creates a new command named
2913** DBNAME that is used to control that connection. The database
2914** connection is deleted when the DBNAME command is deleted.
2915**
drh3570ad92007-08-31 14:31:44 +00002916** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00002917**
drh75897232000-05-29 14:26:00 +00002918*/
drh22fbcb82004-02-01 01:22:50 +00002919static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002920 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002921 const char *zArg;
drh75897232000-05-29 14:26:00 +00002922 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00002923 int i;
drh22fbcb82004-02-01 01:22:50 +00002924 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00002925 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00002926 int flags;
drh882e8e42006-08-24 02:42:27 +00002927 Tcl_DString translatedFilename;
drhb07028f2011-10-14 21:49:18 +00002928#ifdef SQLITE_HAS_CODEC
2929 void *pKey = 0;
2930 int nKey = 0;
2931#endif
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 ){
drhb07028f2011-10-14 21:49:18 +00002963#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00002964 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
drhb07028f2011-10-14 21:49:18 +00002965#endif
drh3570ad92007-08-31 14:31:44 +00002966 }else if( strcmp(zArg, "-vfs")==0 ){
dan3c3dd7b2010-06-22 11:10:40 +00002967 zVfs = Tcl_GetString(objv[i+1]);
drh3570ad92007-08-31 14:31:44 +00002968 }else if( strcmp(zArg, "-readonly")==0 ){
2969 int b;
2970 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2971 if( b ){
drh33f4e022007-09-03 15:19:34 +00002972 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00002973 flags |= SQLITE_OPEN_READONLY;
2974 }else{
2975 flags &= ~SQLITE_OPEN_READONLY;
2976 flags |= SQLITE_OPEN_READWRITE;
2977 }
2978 }else if( strcmp(zArg, "-create")==0 ){
2979 int b;
2980 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00002981 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00002982 flags |= SQLITE_OPEN_CREATE;
2983 }else{
2984 flags &= ~SQLITE_OPEN_CREATE;
2985 }
danielk19779a6284c2008-07-10 17:52:49 +00002986 }else if( strcmp(zArg, "-nomutex")==0 ){
2987 int b;
2988 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2989 if( b ){
2990 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00002991 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00002992 }else{
2993 flags &= ~SQLITE_OPEN_NOMUTEX;
2994 }
danc431fd52011-06-27 16:55:50 +00002995 }else if( strcmp(zArg, "-fullmutex")==0 ){
drh039963a2008-09-03 00:43:15 +00002996 int b;
2997 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2998 if( b ){
2999 flags |= SQLITE_OPEN_FULLMUTEX;
3000 flags &= ~SQLITE_OPEN_NOMUTEX;
3001 }else{
3002 flags &= ~SQLITE_OPEN_FULLMUTEX;
3003 }
drhf12b3f62011-12-21 14:42:29 +00003004 }else if( strcmp(zArg, "-uri")==0 ){
3005 int b;
3006 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3007 if( b ){
3008 flags |= SQLITE_OPEN_URI;
3009 }else{
3010 flags &= ~SQLITE_OPEN_URI;
3011 }
drh3570ad92007-08-31 14:31:44 +00003012 }else{
3013 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3014 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00003015 }
3016 }
drh3570ad92007-08-31 14:31:44 +00003017 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00003018 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00003019 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh68bd4aa2012-01-13 16:16:10 +00003020 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
drh9eb9e262004-02-11 02:18:05 +00003021#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00003022 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00003023#endif
3024 );
drh75897232000-05-29 14:26:00 +00003025 return TCL_ERROR;
3026 }
drh75897232000-05-29 14:26:00 +00003027 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003028 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00003029 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00003030 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
3031 return TCL_ERROR;
3032 }
3033 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00003034 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00003035 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
drh3570ad92007-08-31 14:31:44 +00003036 sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00003037 Tcl_DStringFree(&translatedFilename);
danielk197780290862004-05-22 09:21:21 +00003038 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
drh9404d502006-12-19 18:46:08 +00003039 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
danielk197780290862004-05-22 09:21:21 +00003040 sqlite3_close(p->db);
3041 p->db = 0;
3042 }
drh2011d5f2004-07-22 02:40:37 +00003043#ifdef SQLITE_HAS_CODEC
drhf3a65f72007-08-22 20:18:21 +00003044 if( p->db ){
3045 sqlite3_key(p->db, pKey, nKey);
3046 }
drheb8ed702004-02-11 10:37:23 +00003047#endif
drhbec3f402000-08-04 13:49:02 +00003048 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003049 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003050 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003051 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003052 return TCL_ERROR;
3053 }
drhfb7e7652005-01-24 00:28:42 +00003054 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00003055 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003056 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003057 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003058 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3059 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003060 }else{
3061 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3062 }
drh75897232000-05-29 14:26:00 +00003063 return TCL_OK;
3064}
3065
3066/*
drh90ca9752001-09-28 17:47:14 +00003067** Provide a dummy Tcl_InitStubs if we are using this as a static
3068** library.
3069*/
3070#ifndef USE_TCL_STUBS
3071# undef Tcl_InitStubs
3072# define Tcl_InitStubs(a,b,c)
3073#endif
3074
3075/*
drh29bc4612005-10-05 10:40:15 +00003076** Make sure we have a PACKAGE_VERSION macro defined. This will be
3077** defined automatically by the TEA makefile. But other makefiles
3078** do not define it.
3079*/
3080#ifndef PACKAGE_VERSION
3081# define PACKAGE_VERSION SQLITE_VERSION
3082#endif
3083
3084/*
drh75897232000-05-29 14:26:00 +00003085** Initialize this module.
3086**
3087** This Tcl module contains only a single new Tcl command named "sqlite".
3088** (Hence there is no namespace. There is no point in using a namespace
3089** if the extension only supplies one new name!) The "sqlite" command is
3090** used to open a new SQLite database. See the DbMain() routine above
3091** for additional information.
drhb652f432010-08-26 16:46:57 +00003092**
3093** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003094*/
drhb652f432010-08-26 16:46:57 +00003095EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00003096 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00003097 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00003098 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh1cca0d22010-08-25 20:35:51 +00003099
3100#ifndef SQLITE_3_SUFFIX_ONLY
3101 /* The "sqlite" alias is undocumented. It is here only to support
3102 ** legacy scripts. All new scripts should use only the "sqlite3"
3103 ** command.
3104 */
drh49766d62005-01-08 18:42:28 +00003105 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003106#endif
drh1cca0d22010-08-25 20:35:51 +00003107
drh90ca9752001-09-28 17:47:14 +00003108 return TCL_OK;
3109}
drhb652f432010-08-26 16:46:57 +00003110EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
drhb652f432010-08-26 16:46:57 +00003111EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3112EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00003113
drhd878cab2012-03-20 15:10:42 +00003114/* Because it accesses the file-system and uses persistent state, SQLite
3115** is not considered appropriate for safe interpreters. Hence, we deliberately
3116** omit the _SafeInit() interfaces.
3117*/
drh49766d62005-01-08 18:42:28 +00003118
3119#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003120int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3121int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
dana3e63c42010-08-20 12:33:59 +00003122int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3123int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00003124#endif
drh75897232000-05-29 14:26:00 +00003125
drh3e27c022004-07-23 00:01:38 +00003126#ifdef TCLSH
3127/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003128** All of the code that follows is used to build standalone TCL interpreters
3129** that are statically linked with SQLite. Enable these by compiling
3130** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3131** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3132** analysis program.
drh75897232000-05-29 14:26:00 +00003133*/
drh348784e2000-05-29 20:41:49 +00003134
drh57a02272009-10-22 20:52:05 +00003135#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3136/*
3137 * This code implements the MD5 message-digest algorithm.
3138 * The algorithm is due to Ron Rivest. This code was
3139 * written by Colin Plumb in 1993, no copyright is claimed.
3140 * This code is in the public domain; do with it what you wish.
3141 *
3142 * Equivalent code is available from RSA Data Security, Inc.
3143 * This code has been tested against that, and is equivalent,
3144 * except that you don't need to include two pages of legalese
3145 * with every copy.
3146 *
3147 * To compute the message digest of a chunk of bytes, declare an
3148 * MD5Context structure, pass it to MD5Init, call MD5Update as
3149 * needed on buffers full of bytes, and then call MD5Final, which
3150 * will fill a supplied 16-byte array with the digest.
3151 */
3152
3153/*
3154 * If compiled on a machine that doesn't have a 32-bit integer,
3155 * you just set "uint32" to the appropriate datatype for an
3156 * unsigned 32-bit integer. For example:
3157 *
3158 * cc -Duint32='unsigned long' md5.c
3159 *
3160 */
3161#ifndef uint32
3162# define uint32 unsigned int
3163#endif
3164
3165struct MD5Context {
3166 int isInit;
3167 uint32 buf[4];
3168 uint32 bits[2];
3169 unsigned char in[64];
3170};
3171typedef struct MD5Context MD5Context;
3172
3173/*
3174 * Note: this code is harmless on little-endian machines.
3175 */
3176static void byteReverse (unsigned char *buf, unsigned longs){
3177 uint32 t;
3178 do {
3179 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3180 ((unsigned)buf[1]<<8 | buf[0]);
3181 *(uint32 *)buf = t;
3182 buf += 4;
3183 } while (--longs);
3184}
3185/* The four core functions - F1 is optimized somewhat */
3186
3187/* #define F1(x, y, z) (x & y | ~x & z) */
3188#define F1(x, y, z) (z ^ (x & (y ^ z)))
3189#define F2(x, y, z) F1(z, x, y)
3190#define F3(x, y, z) (x ^ y ^ z)
3191#define F4(x, y, z) (y ^ (x | ~z))
3192
3193/* This is the central step in the MD5 algorithm. */
3194#define MD5STEP(f, w, x, y, z, data, s) \
3195 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3196
3197/*
3198 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3199 * reflect the addition of 16 longwords of new data. MD5Update blocks
3200 * the data and converts bytes into longwords for this routine.
3201 */
3202static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3203 register uint32 a, b, c, d;
3204
3205 a = buf[0];
3206 b = buf[1];
3207 c = buf[2];
3208 d = buf[3];
3209
3210 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3211 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3212 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3213 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3214 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3215 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3216 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3217 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3218 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3219 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3220 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3221 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3222 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3223 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3224 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3225 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3226
3227 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3228 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3229 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3230 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3231 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3232 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3233 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3234 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3235 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3236 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3237 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3238 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3239 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3240 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3241 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3242 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3243
3244 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3245 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3246 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3247 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3248 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3249 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3250 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3251 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3252 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3253 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3254 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3255 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3256 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3257 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3258 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3259 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3260
3261 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3262 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3263 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3264 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3265 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3266 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3267 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3268 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3269 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3270 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3271 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3272 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3273 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3274 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3275 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3276 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3277
3278 buf[0] += a;
3279 buf[1] += b;
3280 buf[2] += c;
3281 buf[3] += d;
3282}
3283
3284/*
3285 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3286 * initialization constants.
3287 */
3288static void MD5Init(MD5Context *ctx){
3289 ctx->isInit = 1;
3290 ctx->buf[0] = 0x67452301;
3291 ctx->buf[1] = 0xefcdab89;
3292 ctx->buf[2] = 0x98badcfe;
3293 ctx->buf[3] = 0x10325476;
3294 ctx->bits[0] = 0;
3295 ctx->bits[1] = 0;
3296}
3297
3298/*
3299 * Update context to reflect the concatenation of another buffer full
3300 * of bytes.
3301 */
3302static
3303void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3304 uint32 t;
3305
3306 /* Update bitcount */
3307
3308 t = ctx->bits[0];
3309 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3310 ctx->bits[1]++; /* Carry from low to high */
3311 ctx->bits[1] += len >> 29;
3312
3313 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3314
3315 /* Handle any leading odd-sized chunks */
3316
3317 if ( t ) {
3318 unsigned char *p = (unsigned char *)ctx->in + t;
3319
3320 t = 64-t;
3321 if (len < t) {
3322 memcpy(p, buf, len);
3323 return;
3324 }
3325 memcpy(p, buf, t);
3326 byteReverse(ctx->in, 16);
3327 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3328 buf += t;
3329 len -= t;
3330 }
3331
3332 /* Process data in 64-byte chunks */
3333
3334 while (len >= 64) {
3335 memcpy(ctx->in, buf, 64);
3336 byteReverse(ctx->in, 16);
3337 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3338 buf += 64;
3339 len -= 64;
3340 }
3341
3342 /* Handle any remaining bytes of data. */
3343
3344 memcpy(ctx->in, buf, len);
3345}
3346
3347/*
3348 * Final wrapup - pad to 64-byte boundary with the bit pattern
3349 * 1 0* (64-bit count of bits processed, MSB-first)
3350 */
3351static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3352 unsigned count;
3353 unsigned char *p;
3354
3355 /* Compute number of bytes mod 64 */
3356 count = (ctx->bits[0] >> 3) & 0x3F;
3357
3358 /* Set the first char of padding to 0x80. This is safe since there is
3359 always at least one byte free */
3360 p = ctx->in + count;
3361 *p++ = 0x80;
3362
3363 /* Bytes of padding needed to make 64 bytes */
3364 count = 64 - 1 - count;
3365
3366 /* Pad out to 56 mod 64 */
3367 if (count < 8) {
3368 /* Two lots of padding: Pad the first block to 64 bytes */
3369 memset(p, 0, count);
3370 byteReverse(ctx->in, 16);
3371 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3372
3373 /* Now fill the next block with 56 bytes */
3374 memset(ctx->in, 0, 56);
3375 } else {
3376 /* Pad block to 56 bytes */
3377 memset(p, 0, count-8);
3378 }
3379 byteReverse(ctx->in, 14);
3380
3381 /* Append length in bits and transform */
3382 ((uint32 *)ctx->in)[ 14 ] = ctx->bits[0];
3383 ((uint32 *)ctx->in)[ 15 ] = ctx->bits[1];
3384
3385 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3386 byteReverse((unsigned char *)ctx->buf, 4);
3387 memcpy(digest, ctx->buf, 16);
3388 memset(ctx, 0, sizeof(ctx)); /* In case it is sensitive */
3389}
3390
3391/*
3392** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3393*/
3394static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3395 static char const zEncode[] = "0123456789abcdef";
3396 int i, j;
3397
3398 for(j=i=0; i<16; i++){
3399 int a = digest[i];
3400 zBuf[j++] = zEncode[(a>>4)&0xf];
3401 zBuf[j++] = zEncode[a & 0xf];
3402 }
3403 zBuf[j] = 0;
3404}
3405
3406
3407/*
3408** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3409** each representing 16 bits of the digest and separated from each
3410** other by a "-" character.
3411*/
3412static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3413 int i, j;
3414 unsigned int x;
3415 for(i=j=0; i<16; i+=2){
3416 x = digest[i]*256 + digest[i+1];
3417 if( i>0 ) zDigest[j++] = '-';
3418 sprintf(&zDigest[j], "%05u", x);
3419 j += 5;
3420 }
3421 zDigest[j] = 0;
3422}
3423
3424/*
3425** A TCL command for md5. The argument is the text to be hashed. The
3426** Result is the hash in base64.
3427*/
3428static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3429 MD5Context ctx;
3430 unsigned char digest[16];
3431 char zBuf[50];
3432 void (*converter)(unsigned char*, char*);
3433
3434 if( argc!=2 ){
3435 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3436 " TEXT\"", 0);
3437 return TCL_ERROR;
3438 }
3439 MD5Init(&ctx);
3440 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3441 MD5Final(digest, &ctx);
3442 converter = (void(*)(unsigned char*,char*))cd;
3443 converter(digest, zBuf);
3444 Tcl_AppendResult(interp, zBuf, (char*)0);
3445 return TCL_OK;
3446}
3447
3448/*
3449** A TCL command to take the md5 hash of a file. The argument is the
3450** name of the file.
3451*/
3452static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3453 FILE *in;
3454 MD5Context ctx;
3455 void (*converter)(unsigned char*, char*);
3456 unsigned char digest[16];
3457 char zBuf[10240];
3458
3459 if( argc!=2 ){
3460 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3461 " FILENAME\"", 0);
3462 return TCL_ERROR;
3463 }
3464 in = fopen(argv[1],"rb");
3465 if( in==0 ){
3466 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
3467 "\" for reading", 0);
3468 return TCL_ERROR;
3469 }
3470 MD5Init(&ctx);
3471 for(;;){
3472 int n;
3473 n = fread(zBuf, 1, sizeof(zBuf), in);
3474 if( n<=0 ) break;
3475 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3476 }
3477 fclose(in);
3478 MD5Final(digest, &ctx);
3479 converter = (void(*)(unsigned char*,char*))cd;
3480 converter(digest, zBuf);
3481 Tcl_AppendResult(interp, zBuf, (char*)0);
3482 return TCL_OK;
3483}
3484
3485/*
3486** Register the four new TCL commands for generating MD5 checksums
3487** with the TCL interpreter.
3488*/
3489int Md5_Init(Tcl_Interp *interp){
3490 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3491 MD5DigestToBase16, 0);
3492 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3493 MD5DigestToBase10x8, 0);
3494 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3495 MD5DigestToBase16, 0);
3496 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3497 MD5DigestToBase10x8, 0);
3498 return TCL_OK;
3499}
3500#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3501
3502#if defined(SQLITE_TEST)
3503/*
3504** During testing, the special md5sum() aggregate function is available.
3505** inside SQLite. The following routines implement that function.
3506*/
3507static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3508 MD5Context *p;
3509 int i;
3510 if( argc<1 ) return;
3511 p = sqlite3_aggregate_context(context, sizeof(*p));
3512 if( p==0 ) return;
3513 if( !p->isInit ){
3514 MD5Init(p);
3515 }
3516 for(i=0; i<argc; i++){
3517 const char *zData = (char*)sqlite3_value_text(argv[i]);
3518 if( zData ){
3519 MD5Update(p, (unsigned char*)zData, strlen(zData));
3520 }
3521 }
3522}
3523static void md5finalize(sqlite3_context *context){
3524 MD5Context *p;
3525 unsigned char digest[16];
3526 char zBuf[33];
3527 p = sqlite3_aggregate_context(context, sizeof(*p));
3528 MD5Final(digest,p);
3529 MD5DigestToBase16(digest, zBuf);
3530 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3531}
3532int Md5_Register(sqlite3 *db){
3533 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
3534 md5step, md5finalize);
3535 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3536 return rc;
3537}
3538#endif /* defined(SQLITE_TEST) */
3539
3540
drh348784e2000-05-29 20:41:49 +00003541/*
drh3e27c022004-07-23 00:01:38 +00003542** If the macro TCLSH is one, then put in code this for the
3543** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003544** standard input, or if a file is named on the command line
3545** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003546*/
drh3e27c022004-07-23 00:01:38 +00003547#if TCLSH==1
dan0ae479d2011-09-21 16:43:07 +00003548static const char *tclsh_main_loop(void){
3549 static const char zMainloop[] =
3550 "set line {}\n"
3551 "while {![eof stdin]} {\n"
3552 "if {$line!=\"\"} {\n"
3553 "puts -nonewline \"> \"\n"
3554 "} else {\n"
3555 "puts -nonewline \"% \"\n"
drh348784e2000-05-29 20:41:49 +00003556 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003557 "flush stdout\n"
3558 "append line [gets stdin]\n"
3559 "if {[info complete $line]} {\n"
3560 "if {[catch {uplevel #0 $line} result]} {\n"
3561 "puts stderr \"Error: $result\"\n"
3562 "} elseif {$result!=\"\"} {\n"
3563 "puts $result\n"
3564 "}\n"
3565 "set line {}\n"
3566 "} else {\n"
3567 "append line \\n\n"
3568 "}\n"
drh348784e2000-05-29 20:41:49 +00003569 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003570 ;
3571 return zMainloop;
3572}
drh3e27c022004-07-23 00:01:38 +00003573#endif
drh3a0f13f2010-07-12 16:47:48 +00003574#if TCLSH==2
dan0ae479d2011-09-21 16:43:07 +00003575static const char *tclsh_main_loop(void);
drh3a0f13f2010-07-12 16:47:48 +00003576#endif
drh3e27c022004-07-23 00:01:38 +00003577
danc1a60c52010-06-07 14:28:16 +00003578#ifdef SQLITE_TEST
3579static void init_all(Tcl_Interp *);
3580static int init_all_cmd(
3581 ClientData cd,
3582 Tcl_Interp *interp,
3583 int objc,
3584 Tcl_Obj *CONST objv[]
3585){
danielk19770a549072009-02-17 16:29:10 +00003586
danc1a60c52010-06-07 14:28:16 +00003587 Tcl_Interp *slave;
3588 if( objc!=2 ){
3589 Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3590 return TCL_ERROR;
3591 }
3592
3593 slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3594 if( !slave ){
3595 return TCL_ERROR;
3596 }
3597
3598 init_all(slave);
3599 return TCL_OK;
3600}
danc431fd52011-06-27 16:55:50 +00003601
3602/*
3603** Tclcmd: db_use_legacy_prepare DB BOOLEAN
3604**
3605** The first argument to this command must be a database command created by
3606** [sqlite3]. If the second argument is true, then the handle is configured
3607** to use the sqlite3_prepare_v2() function to prepare statements. If it
3608** is false, sqlite3_prepare().
3609*/
3610static int db_use_legacy_prepare_cmd(
3611 ClientData cd,
3612 Tcl_Interp *interp,
3613 int objc,
3614 Tcl_Obj *CONST objv[]
3615){
3616 Tcl_CmdInfo cmdInfo;
3617 SqliteDb *pDb;
3618 int bPrepare;
3619
3620 if( objc!=3 ){
3621 Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
3622 return TCL_ERROR;
3623 }
3624
3625 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3626 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3627 return TCL_ERROR;
3628 }
3629 pDb = (SqliteDb*)cmdInfo.objClientData;
3630 if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
3631 return TCL_ERROR;
3632 }
3633
3634 pDb->bLegacyPrepare = bPrepare;
3635
3636 Tcl_ResetResult(interp);
3637 return TCL_OK;
3638}
danc1a60c52010-06-07 14:28:16 +00003639#endif
3640
3641/*
3642** Configure the interpreter passed as the first argument to have access
3643** to the commands and linked variables that make up:
3644**
3645** * the [sqlite3] extension itself,
3646**
3647** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
3648**
3649** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
3650** test suite.
3651*/
3652static void init_all(Tcl_Interp *interp){
drh38f82712004-06-18 17:10:16 +00003653 Sqlite3_Init(interp);
danc1a60c52010-06-07 14:28:16 +00003654
drh57a02272009-10-22 20:52:05 +00003655#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3656 Md5_Init(interp);
3657#endif
danc1a60c52010-06-07 14:28:16 +00003658
dan0ae479d2011-09-21 16:43:07 +00003659 /* Install the [register_dbstat_vtab] command to access the implementation
3660 ** of virtual table dbstat (source file test_stat.c). This command is
3661 ** required for testfixture and sqlite3_analyzer, but not by the production
3662 ** Tcl extension. */
3663#if defined(SQLITE_TEST) || TCLSH==2
3664 {
3665 extern int SqlitetestStat_Init(Tcl_Interp*);
3666 SqlitetestStat_Init(interp);
3667 }
3668#endif
3669
drhd9b02572001-04-15 00:37:09 +00003670#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00003671 {
drh2f999a62007-08-15 19:16:43 +00003672 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00003673 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00003674 extern int Sqlitetest2_Init(Tcl_Interp*);
3675 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00003676 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00003677 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00003678 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00003679 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00003680 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00003681 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00003682 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00003683 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
dan0a7a9152010-04-07 07:57:38 +00003684 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
drh984bfaa2008-03-19 16:08:53 +00003685 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00003686 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00003687 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003688 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00003689 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003690 extern int Sqlitetestschema_Init(Tcl_Interp*);
3691 extern int Sqlitetestsse_Init(Tcl_Interp*);
3692 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00003693 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00003694 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00003695 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00003696 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh522efc62009-11-10 17:24:37 +00003697 extern int Sqlitetestintarray_Init(Tcl_Interp*);
danc7991bd2010-05-05 19:04:59 +00003698 extern int Sqlitetestvfs_Init(Tcl_Interp *);
dan9508daa2010-08-28 18:58:00 +00003699 extern int Sqlitetestrtree_Init(Tcl_Interp*);
dan8cf35eb2010-09-01 11:40:05 +00003700 extern int Sqlitequota_Init(Tcl_Interp*);
shaneh8a922f72010-11-04 20:50:27 +00003701 extern int Sqlitemultiplex_Init(Tcl_Interp*);
dane336b002010-11-19 18:20:09 +00003702 extern int SqliteSuperlock_Init(Tcl_Interp*);
dan213ca0a2011-03-28 19:10:06 +00003703 extern int SqlitetestSyscall_Init(Tcl_Interp*);
drh326a67d2011-03-26 15:05:27 +00003704 extern int Sqlitetestfuzzer_Init(Tcl_Interp*);
drh70586be2011-04-01 23:49:44 +00003705 extern int Sqlitetestwholenumber_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00003706
dan6764a702011-06-20 11:15:06 +00003707#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00003708 extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
3709#endif
3710
danb29010c2010-12-29 18:24:38 +00003711#ifdef SQLITE_ENABLE_ZIPVFS
3712 extern int Zipvfs_Init(Tcl_Interp*);
3713 Zipvfs_Init(interp);
3714#endif
3715
drh2f999a62007-08-15 19:16:43 +00003716 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00003717 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00003718 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00003719 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00003720 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00003721 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00003722 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00003723 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00003724 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00003725 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00003726 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00003727 Sqlitetest_autoext_Init(interp);
dan0a7a9152010-04-07 07:57:38 +00003728 Sqlitetest_demovfs_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00003729 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00003730 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00003731 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003732 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00003733 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003734 Sqlitetestschema_Init(interp);
3735 Sqlitetesttclvar_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00003736 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003737 SqlitetestOnefile_Init(interp);
danielk19775d1f5aa2008-04-10 14:51:00 +00003738 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00003739 Sqlitetestbackup_Init(interp);
drh522efc62009-11-10 17:24:37 +00003740 Sqlitetestintarray_Init(interp);
danc7991bd2010-05-05 19:04:59 +00003741 Sqlitetestvfs_Init(interp);
dan9508daa2010-08-28 18:58:00 +00003742 Sqlitetestrtree_Init(interp);
dan8cf35eb2010-09-01 11:40:05 +00003743 Sqlitequota_Init(interp);
shaneh8a922f72010-11-04 20:50:27 +00003744 Sqlitemultiplex_Init(interp);
dane336b002010-11-19 18:20:09 +00003745 SqliteSuperlock_Init(interp);
dan213ca0a2011-03-28 19:10:06 +00003746 SqlitetestSyscall_Init(interp);
drh326a67d2011-03-26 15:05:27 +00003747 Sqlitetestfuzzer_Init(interp);
drh70586be2011-04-01 23:49:44 +00003748 Sqlitetestwholenumber_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003749
dan6764a702011-06-20 11:15:06 +00003750#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00003751 Sqlitetestfts3_Init(interp);
3752#endif
3753
danc431fd52011-06-27 16:55:50 +00003754 Tcl_CreateObjCommand(
3755 interp, "load_testfixture_extensions", init_all_cmd, 0, 0
3756 );
3757 Tcl_CreateObjCommand(
3758 interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
3759 );
danc1a60c52010-06-07 14:28:16 +00003760
drh89dec812005-04-28 19:03:37 +00003761#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00003762 Sqlitetestsse_Init(interp);
3763#endif
drhd1bf3512001-04-07 15:24:33 +00003764 }
3765#endif
danc1a60c52010-06-07 14:28:16 +00003766}
3767
3768#define TCLSH_MAIN main /* Needed to fake out mktclapp */
3769int TCLSH_MAIN(int argc, char **argv){
3770 Tcl_Interp *interp;
3771
3772 /* Call sqlite3_shutdown() once before doing anything else. This is to
3773 ** test that sqlite3_shutdown() can be safely called by a process before
3774 ** sqlite3_initialize() is. */
3775 sqlite3_shutdown();
3776
dan0ae479d2011-09-21 16:43:07 +00003777 Tcl_FindExecutable(argv[0]);
3778 interp = Tcl_CreateInterp();
3779
drh3a0f13f2010-07-12 16:47:48 +00003780#if TCLSH==2
3781 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
3782#endif
danc1a60c52010-06-07 14:28:16 +00003783
danc1a60c52010-06-07 14:28:16 +00003784 init_all(interp);
drhc7285972009-11-10 01:13:25 +00003785 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00003786 int i;
shessad42c3a2006-08-22 23:53:46 +00003787 char zArgc[32];
3788 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
3789 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00003790 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
3791 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00003792 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00003793 Tcl_SetVar(interp, "argv", argv[i],
3794 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3795 }
drh3a0f13f2010-07-12 16:47:48 +00003796 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00003797 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00003798 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00003799 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00003800 return 1;
3801 }
drh3e27c022004-07-23 00:01:38 +00003802 }
drh3a0f13f2010-07-12 16:47:48 +00003803 if( TCLSH==2 || argc<=1 ){
dan0ae479d2011-09-21 16:43:07 +00003804 Tcl_GlobalEval(interp, tclsh_main_loop());
drh348784e2000-05-29 20:41:49 +00003805 }
3806 return 0;
3807}
3808#endif /* TCLSH */