blob: bb930f0c755165241188a43971079a1bbc48d56c [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/*
mistachkin540ebf82012-09-10 07:29:29 +000045** This function is used to translate a return code into an error
46** message.
47*/
48const char *sqlite3ErrStr(int rc);
49
50/*
drhad6e1372006-07-10 21:15:51 +000051 * Windows needs to know which symbols to export. Unix does not.
52 * BUILD_sqlite should be undefined for Unix.
53 */
54#ifdef BUILD_sqlite
55#undef TCL_STORAGE_CLASS
56#define TCL_STORAGE_CLASS DLLEXPORT
57#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000058
danielk1977a21c6b62005-01-24 10:25:59 +000059#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000060#define MAX_PREPARED_STMTS 100
61
drh75897232000-05-29 14:26:00 +000062/*
drh98808ba2001-10-18 12:34:46 +000063** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
64** have to do a translation when going between the two. Set the
65** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
66** this translation.
67*/
68#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
69# define UTF_TRANSLATION_NEEDED 1
70#endif
71
72/*
drhcabb0812002-09-14 13:47:32 +000073** New SQL functions can be created as TCL scripts. Each such function
74** is described by an instance of the following structure.
75*/
76typedef struct SqlFunc SqlFunc;
77struct SqlFunc {
78 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000079 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
80 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
81 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000082 SqlFunc *pNext; /* Next function on the list of them all */
83};
84
85/*
danielk19770202b292004-06-09 09:55:16 +000086** New collation sequences function can be created as TCL scripts. Each such
87** function is described by an instance of the following structure.
88*/
89typedef struct SqlCollate SqlCollate;
90struct SqlCollate {
91 Tcl_Interp *interp; /* The TCL interpret to execute the function */
92 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000093 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000094};
95
96/*
drhfb7e7652005-01-24 00:28:42 +000097** Prepared statements are cached for faster execution. Each prepared
98** statement is described by an instance of the following structure.
99*/
100typedef struct SqlPreparedStmt SqlPreparedStmt;
101struct SqlPreparedStmt {
102 SqlPreparedStmt *pNext; /* Next in linked list */
103 SqlPreparedStmt *pPrev; /* Previous on the list */
104 sqlite3_stmt *pStmt; /* The prepared statement */
105 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +0000106 const char *zSql; /* Text of the SQL statement */
dan4a4c11a2009-10-06 14:59:02 +0000107 int nParm; /* Size of apParm array */
108 Tcl_Obj **apParm; /* Array of referenced object pointers */
drhfb7e7652005-01-24 00:28:42 +0000109};
110
danielk1977d04417962007-05-02 13:16:30 +0000111typedef struct IncrblobChannel IncrblobChannel;
112
drhfb7e7652005-01-24 00:28:42 +0000113/*
drhbec3f402000-08-04 13:49:02 +0000114** There is one instance of this structure for each SQLite database
115** that has been opened by the SQLite TCL interface.
danc431fd52011-06-27 16:55:50 +0000116**
117** If this module is built with SQLITE_TEST defined (to create the SQLite
118** testfixture executable), then it may be configured to use either
119** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
120** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
drhbec3f402000-08-04 13:49:02 +0000121*/
122typedef struct SqliteDb SqliteDb;
123struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000124 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000125 Tcl_Interp *interp; /* The interpreter used for this database */
126 char *zBusy; /* The busy callback routine */
127 char *zCommit; /* The commit hook callback routine */
128 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +0000129 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000130 char *zProgress; /* The progress callback routine */
131 char *zAuth; /* The authorization callback routine */
drh1f1549f2008-08-26 21:33:34 +0000132 int disableAuth; /* Disable the authorizer if it exists */
drhd1e47332005-06-26 17:55:33 +0000133 char *zNull; /* Text to substitute for an SQL NULL value */
134 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000135 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000136 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drh5def0842010-05-05 20:00:25 +0000137 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000138 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000139 SqlCollate *pCollate; /* List of SQL collation functions */
140 int rc; /* Return code of most recent sqlite3_exec() */
141 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000142 SqlPreparedStmt *stmtList; /* List of prepared statements*/
143 SqlPreparedStmt *stmtLast; /* Last statement in the list */
144 int maxStmt; /* The next maximum number of stmtList */
145 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000146 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh3c379b02010-04-07 19:31:59 +0000147 int nStep, nSort, nIndex; /* Statistics for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000148 int nTransaction; /* Number of nested [transaction] methods */
danc431fd52011-06-27 16:55:50 +0000149#ifdef SQLITE_TEST
150 int bLegacyPrepare; /* True to use sqlite3_prepare() */
151#endif
drh98808ba2001-10-18 12:34:46 +0000152};
drh297ecf12001-04-05 15:57:13 +0000153
danielk1977b4e9af92007-05-01 17:49:49 +0000154struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000155 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000156 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000157 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000158 Tcl_Channel channel; /* Channel identifier */
159 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
160 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000161};
162
drhea678832008-12-10 19:26:22 +0000163/*
164** Compute a string length that is limited to what can be stored in
165** lower 30 bits of a 32-bit signed integer.
166*/
drh4f21c4a2008-12-10 22:15:00 +0000167static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000168 const char *z2 = z;
169 while( *z2 ){ z2++; }
170 return 0x3fffffff & (int)(z2 - z);
171}
drhea678832008-12-10 19:26:22 +0000172
173
danielk197732a0d8b2007-05-04 19:03:02 +0000174#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000175/*
danielk1977d04417962007-05-02 13:16:30 +0000176** Close all incrblob channels opened using database connection pDb.
177** This is called when shutting down the database connection.
178*/
179static void closeIncrblobChannels(SqliteDb *pDb){
180 IncrblobChannel *p;
181 IncrblobChannel *pNext;
182
183 for(p=pDb->pIncrblob; p; p=pNext){
184 pNext = p->pNext;
185
186 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
187 ** which deletes the IncrblobChannel structure at *p. So do not
188 ** call Tcl_Free() here.
189 */
190 Tcl_UnregisterChannel(pDb->interp, p->channel);
191 }
192}
193
194/*
danielk1977b4e9af92007-05-01 17:49:49 +0000195** Close an incremental blob channel.
196*/
197static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
198 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000199 int rc = sqlite3_blob_close(p->pBlob);
200 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000201
202 /* Remove the channel from the SqliteDb.pIncrblob list. */
203 if( p->pNext ){
204 p->pNext->pPrev = p->pPrev;
205 }
206 if( p->pPrev ){
207 p->pPrev->pNext = p->pNext;
208 }
209 if( p->pDb->pIncrblob==p ){
210 p->pDb->pIncrblob = p->pNext;
211 }
212
danielk197792d4d7a2007-05-04 12:05:56 +0000213 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000214 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000215
216 if( rc!=SQLITE_OK ){
217 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
218 return TCL_ERROR;
219 }
danielk1977b4e9af92007-05-01 17:49:49 +0000220 return TCL_OK;
221}
222
223/*
224** Read data from an incremental blob channel.
225*/
226static int incrblobInput(
227 ClientData instanceData,
228 char *buf,
229 int bufSize,
230 int *errorCodePtr
231){
232 IncrblobChannel *p = (IncrblobChannel *)instanceData;
233 int nRead = bufSize; /* Number of bytes to read */
234 int nBlob; /* Total size of the blob */
235 int rc; /* sqlite error code */
236
237 nBlob = sqlite3_blob_bytes(p->pBlob);
238 if( (p->iSeek+nRead)>nBlob ){
239 nRead = nBlob-p->iSeek;
240 }
241 if( nRead<=0 ){
242 return 0;
243 }
244
245 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
246 if( rc!=SQLITE_OK ){
247 *errorCodePtr = rc;
248 return -1;
249 }
250
251 p->iSeek += nRead;
252 return nRead;
253}
254
danielk1977d04417962007-05-02 13:16:30 +0000255/*
256** Write data to an incremental blob channel.
257*/
danielk1977b4e9af92007-05-01 17:49:49 +0000258static int incrblobOutput(
259 ClientData instanceData,
260 CONST char *buf,
261 int toWrite,
262 int *errorCodePtr
263){
264 IncrblobChannel *p = (IncrblobChannel *)instanceData;
265 int nWrite = toWrite; /* Number of bytes to write */
266 int nBlob; /* Total size of the blob */
267 int rc; /* sqlite error code */
268
269 nBlob = sqlite3_blob_bytes(p->pBlob);
270 if( (p->iSeek+nWrite)>nBlob ){
271 *errorCodePtr = EINVAL;
272 return -1;
273 }
274 if( nWrite<=0 ){
275 return 0;
276 }
277
278 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
279 if( rc!=SQLITE_OK ){
280 *errorCodePtr = EIO;
281 return -1;
282 }
283
284 p->iSeek += nWrite;
285 return nWrite;
286}
287
288/*
289** Seek an incremental blob channel.
290*/
291static int incrblobSeek(
292 ClientData instanceData,
293 long offset,
294 int seekMode,
295 int *errorCodePtr
296){
297 IncrblobChannel *p = (IncrblobChannel *)instanceData;
298
299 switch( seekMode ){
300 case SEEK_SET:
301 p->iSeek = offset;
302 break;
303 case SEEK_CUR:
304 p->iSeek += offset;
305 break;
306 case SEEK_END:
307 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
308 break;
309
310 default: assert(!"Bad seekMode");
311 }
312
313 return p->iSeek;
314}
315
316
317static void incrblobWatch(ClientData instanceData, int mode){
318 /* NO-OP */
319}
320static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
321 return TCL_ERROR;
322}
323
324static Tcl_ChannelType IncrblobChannelType = {
325 "incrblob", /* typeName */
326 TCL_CHANNEL_VERSION_2, /* version */
327 incrblobClose, /* closeProc */
328 incrblobInput, /* inputProc */
329 incrblobOutput, /* outputProc */
330 incrblobSeek, /* seekProc */
331 0, /* setOptionProc */
332 0, /* getOptionProc */
333 incrblobWatch, /* watchProc (this is a no-op) */
334 incrblobHandle, /* getHandleProc (always returns error) */
335 0, /* close2Proc */
336 0, /* blockModeProc */
337 0, /* flushProc */
338 0, /* handlerProc */
339 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000340};
341
342/*
343** Create a new incrblob channel.
344*/
345static int createIncrblobChannel(
346 Tcl_Interp *interp,
347 SqliteDb *pDb,
348 const char *zDb,
349 const char *zTable,
350 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000351 sqlite_int64 iRow,
352 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000353){
354 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000355 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000356 sqlite3_blob *pBlob;
357 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000358 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000359
360 /* This variable is used to name the channels: "incrblob_[incr count]" */
361 static int count = 0;
362 char zChannel[64];
363
danielk19778cbadb02007-05-03 16:31:26 +0000364 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000365 if( rc!=SQLITE_OK ){
366 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
367 return TCL_ERROR;
368 }
369
370 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
371 p->iSeek = 0;
372 p->pBlob = pBlob;
373
drh5bb3eb92007-05-04 13:15:55 +0000374 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000375 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
376 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000377
danielk1977d04417962007-05-02 13:16:30 +0000378 /* Link the new channel into the SqliteDb.pIncrblob list. */
379 p->pNext = pDb->pIncrblob;
380 p->pPrev = 0;
381 if( p->pNext ){
382 p->pNext->pPrev = p;
383 }
384 pDb->pIncrblob = p;
385 p->pDb = pDb;
386
387 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000388 return TCL_OK;
389}
danielk197732a0d8b2007-05-04 19:03:02 +0000390#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
391 #define closeIncrblobChannels(pDb)
392#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000393
drh6d313162000-09-21 13:01:35 +0000394/*
drhd1e47332005-06-26 17:55:33 +0000395** Look at the script prefix in pCmd. We will be executing this script
396** after first appending one or more arguments. This routine analyzes
397** the script to see if it is safe to use Tcl_EvalObjv() on the script
398** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
399** faster.
400**
401** Scripts that are safe to use with Tcl_EvalObjv() consists of a
402** command name followed by zero or more arguments with no [...] or $
403** or {...} or ; to be seen anywhere. Most callback scripts consist
404** of just a single procedure name and they meet this requirement.
405*/
406static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
407 /* We could try to do something with Tcl_Parse(). But we will instead
408 ** just do a search for forbidden characters. If any of the forbidden
409 ** characters appear in pCmd, we will report the string as unsafe.
410 */
411 const char *z;
412 int n;
413 z = Tcl_GetStringFromObj(pCmd, &n);
414 while( n-- > 0 ){
415 int c = *(z++);
416 if( c=='$' || c=='[' || c==';' ) return 0;
417 }
418 return 1;
419}
420
421/*
422** Find an SqlFunc structure with the given name. Or create a new
423** one if an existing one cannot be found. Return a pointer to the
424** structure.
425*/
426static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
427 SqlFunc *p, *pNew;
428 int i;
drh4f21c4a2008-12-10 22:15:00 +0000429 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen30(zName) + 1 );
drhd1e47332005-06-26 17:55:33 +0000430 pNew->zName = (char*)&pNew[1];
431 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
432 pNew->zName[i] = 0;
433 for(p=pDb->pFunc; p; p=p->pNext){
434 if( strcmp(p->zName, pNew->zName)==0 ){
435 Tcl_Free((char*)pNew);
436 return p;
437 }
438 }
439 pNew->interp = pDb->interp;
440 pNew->pScript = 0;
441 pNew->pNext = pDb->pFunc;
442 pDb->pFunc = pNew;
443 return pNew;
444}
445
446/*
danc431fd52011-06-27 16:55:50 +0000447** Free a single SqlPreparedStmt object.
448*/
449static void dbFreeStmt(SqlPreparedStmt *pStmt){
450#ifdef SQLITE_TEST
451 if( sqlite3_sql(pStmt->pStmt)==0 ){
452 Tcl_Free((char *)pStmt->zSql);
453 }
454#endif
455 sqlite3_finalize(pStmt->pStmt);
456 Tcl_Free((char *)pStmt);
457}
458
459/*
drhfb7e7652005-01-24 00:28:42 +0000460** Finalize and free a list of prepared statements
461*/
danc431fd52011-06-27 16:55:50 +0000462static void flushStmtCache(SqliteDb *pDb){
drhfb7e7652005-01-24 00:28:42 +0000463 SqlPreparedStmt *pPreStmt;
danc431fd52011-06-27 16:55:50 +0000464 SqlPreparedStmt *pNext;
drhfb7e7652005-01-24 00:28:42 +0000465
danc431fd52011-06-27 16:55:50 +0000466 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
467 pNext = pPreStmt->pNext;
468 dbFreeStmt(pPreStmt);
drhfb7e7652005-01-24 00:28:42 +0000469 }
470 pDb->nStmt = 0;
471 pDb->stmtLast = 0;
danc431fd52011-06-27 16:55:50 +0000472 pDb->stmtList = 0;
drhfb7e7652005-01-24 00:28:42 +0000473}
474
475/*
drh895d7472004-08-20 16:02:39 +0000476** TCL calls this procedure when an sqlite3 database command is
477** deleted.
drh75897232000-05-29 14:26:00 +0000478*/
479static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000480 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000481 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000482 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000483 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000484 while( pDb->pFunc ){
485 SqlFunc *pFunc = pDb->pFunc;
486 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000487 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000488 Tcl_Free((char*)pFunc);
489 }
danielk19770202b292004-06-09 09:55:16 +0000490 while( pDb->pCollate ){
491 SqlCollate *pCollate = pDb->pCollate;
492 pDb->pCollate = pCollate->pNext;
493 Tcl_Free((char*)pCollate);
494 }
drhbec3f402000-08-04 13:49:02 +0000495 if( pDb->zBusy ){
496 Tcl_Free(pDb->zBusy);
497 }
drhb5a20d32003-04-23 12:25:23 +0000498 if( pDb->zTrace ){
499 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000500 }
drh19e2d372005-08-29 23:00:03 +0000501 if( pDb->zProfile ){
502 Tcl_Free(pDb->zProfile);
503 }
drhe22a3342003-04-22 20:30:37 +0000504 if( pDb->zAuth ){
505 Tcl_Free(pDb->zAuth);
506 }
danielk197755c45f22005-04-03 23:54:43 +0000507 if( pDb->zNull ){
508 Tcl_Free(pDb->zNull);
509 }
danielk197794eb6a12005-12-15 15:22:08 +0000510 if( pDb->pUpdateHook ){
511 Tcl_DecrRefCount(pDb->pUpdateHook);
512 }
danielk197771fd80b2005-12-16 06:54:01 +0000513 if( pDb->pRollbackHook ){
514 Tcl_DecrRefCount(pDb->pRollbackHook);
515 }
drh5def0842010-05-05 20:00:25 +0000516 if( pDb->pWalHook ){
517 Tcl_DecrRefCount(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000518 }
danielk197794eb6a12005-12-15 15:22:08 +0000519 if( pDb->pCollateNeeded ){
520 Tcl_DecrRefCount(pDb->pCollateNeeded);
521 }
drhbec3f402000-08-04 13:49:02 +0000522 Tcl_Free((char*)pDb);
523}
524
525/*
526** This routine is called when a database file is locked while trying
527** to execute SQL.
528*/
danielk19772a764eb2004-06-12 01:43:26 +0000529static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000530 SqliteDb *pDb = (SqliteDb*)cd;
531 int rc;
532 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000533
drh5bb3eb92007-05-04 13:15:55 +0000534 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000535 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000536 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
537 return 0;
538 }
539 return 1;
drh75897232000-05-29 14:26:00 +0000540}
541
drh26e4a8b2008-05-01 17:16:52 +0000542#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000543/*
danielk1977348bb5d2003-10-18 09:37:26 +0000544** This routine is invoked as the 'progress callback' for the database.
545*/
546static int DbProgressHandler(void *cd){
547 SqliteDb *pDb = (SqliteDb*)cd;
548 int rc;
549
550 assert( pDb->zProgress );
551 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
552 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
553 return 1;
554 }
555 return 0;
556}
drh26e4a8b2008-05-01 17:16:52 +0000557#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000558
drhd1167392006-01-23 13:00:35 +0000559#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000560/*
drhb5a20d32003-04-23 12:25:23 +0000561** This routine is called by the SQLite trace handler whenever a new
562** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000563*/
drhb5a20d32003-04-23 12:25:23 +0000564static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000565 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000566 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000567
drhb5a20d32003-04-23 12:25:23 +0000568 Tcl_DStringInit(&str);
569 Tcl_DStringAppend(&str, pDb->zTrace, -1);
570 Tcl_DStringAppendElement(&str, zSql);
571 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
572 Tcl_DStringFree(&str);
573 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000574}
drhd1167392006-01-23 13:00:35 +0000575#endif
drh0d1a6432003-04-03 15:46:04 +0000576
drhd1167392006-01-23 13:00:35 +0000577#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000578/*
drh19e2d372005-08-29 23:00:03 +0000579** This routine is called by the SQLite profile handler after a statement
580** SQL has executed. The TCL script in pDb->zProfile is evaluated.
581*/
582static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
583 SqliteDb *pDb = (SqliteDb*)cd;
584 Tcl_DString str;
585 char zTm[100];
586
587 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
588 Tcl_DStringInit(&str);
589 Tcl_DStringAppend(&str, pDb->zProfile, -1);
590 Tcl_DStringAppendElement(&str, zSql);
591 Tcl_DStringAppendElement(&str, zTm);
592 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
593 Tcl_DStringFree(&str);
594 Tcl_ResetResult(pDb->interp);
595}
drhd1167392006-01-23 13:00:35 +0000596#endif
drh19e2d372005-08-29 23:00:03 +0000597
598/*
drhaa940ea2004-01-15 02:44:03 +0000599** This routine is called when a transaction is committed. The
600** TCL script in pDb->zCommit is executed. If it returns non-zero or
601** if it throws an exception, the transaction is rolled back instead
602** of being committed.
603*/
604static int DbCommitHandler(void *cd){
605 SqliteDb *pDb = (SqliteDb*)cd;
606 int rc;
607
608 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
609 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
610 return 1;
611 }
612 return 0;
613}
614
danielk197771fd80b2005-12-16 06:54:01 +0000615static void DbRollbackHandler(void *clientData){
616 SqliteDb *pDb = (SqliteDb*)clientData;
617 assert(pDb->pRollbackHook);
618 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
619 Tcl_BackgroundError(pDb->interp);
620 }
621}
622
drh5def0842010-05-05 20:00:25 +0000623/*
624** This procedure handles wal_hook callbacks.
625*/
626static int DbWalHandler(
dan8d22a172010-04-19 18:03:51 +0000627 void *clientData,
628 sqlite3 *db,
629 const char *zDb,
630 int nEntry
631){
drh5def0842010-05-05 20:00:25 +0000632 int ret = SQLITE_OK;
dan8d22a172010-04-19 18:03:51 +0000633 Tcl_Obj *p;
634 SqliteDb *pDb = (SqliteDb*)clientData;
635 Tcl_Interp *interp = pDb->interp;
drh5def0842010-05-05 20:00:25 +0000636 assert(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000637
drh5def0842010-05-05 20:00:25 +0000638 p = Tcl_DuplicateObj(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000639 Tcl_IncrRefCount(p);
640 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
641 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
642 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
643 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
644 ){
645 Tcl_BackgroundError(interp);
646 }
647 Tcl_DecrRefCount(p);
648
649 return ret;
650}
651
drhbcf4f482009-03-27 12:44:35 +0000652#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000653static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
654 char zBuf[64];
655 sprintf(zBuf, "%d", iArg);
656 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
657 sprintf(zBuf, "%d", nArg);
658 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
659}
660#else
drhbcf4f482009-03-27 12:44:35 +0000661# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000662#endif
663
drh69910da2009-03-27 12:32:54 +0000664#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000665static void DbUnlockNotify(void **apArg, int nArg){
666 int i;
667 for(i=0; i<nArg; i++){
668 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
669 SqliteDb *pDb = (SqliteDb *)apArg[i];
670 setTestUnlockNotifyVars(pDb->interp, i, nArg);
671 assert( pDb->pUnlockNotify);
672 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
673 Tcl_DecrRefCount(pDb->pUnlockNotify);
674 pDb->pUnlockNotify = 0;
675 }
676}
drh69910da2009-03-27 12:32:54 +0000677#endif
danielk1977404ca072009-03-16 13:19:36 +0000678
danielk197794eb6a12005-12-15 15:22:08 +0000679static void DbUpdateHandler(
680 void *p,
681 int op,
682 const char *zDb,
683 const char *zTbl,
684 sqlite_int64 rowid
685){
686 SqliteDb *pDb = (SqliteDb *)p;
687 Tcl_Obj *pCmd;
688
689 assert( pDb->pUpdateHook );
690 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
691
692 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
693 Tcl_IncrRefCount(pCmd);
694 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
695 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
696 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
697 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
698 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
699 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
drhefdde162010-10-27 15:36:21 +0000700 Tcl_DecrRefCount(pCmd);
danielk197794eb6a12005-12-15 15:22:08 +0000701}
702
danielk19777cedc8d2004-06-10 10:50:08 +0000703static void tclCollateNeeded(
704 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000705 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000706 int enc,
707 const char *zName
708){
709 SqliteDb *pDb = (SqliteDb *)pCtx;
710 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
711 Tcl_IncrRefCount(pScript);
712 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
713 Tcl_EvalObjEx(pDb->interp, pScript, 0);
714 Tcl_DecrRefCount(pScript);
715}
716
drhaa940ea2004-01-15 02:44:03 +0000717/*
danielk19770202b292004-06-09 09:55:16 +0000718** This routine is called to evaluate an SQL collation function implemented
719** using TCL script.
720*/
721static int tclSqlCollate(
722 void *pCtx,
723 int nA,
724 const void *zA,
725 int nB,
726 const void *zB
727){
728 SqlCollate *p = (SqlCollate *)pCtx;
729 Tcl_Obj *pCmd;
730
731 pCmd = Tcl_NewStringObj(p->zScript, -1);
732 Tcl_IncrRefCount(pCmd);
733 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
734 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000735 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000736 Tcl_DecrRefCount(pCmd);
737 return (atoi(Tcl_GetStringResult(p->interp)));
738}
739
740/*
drhcabb0812002-09-14 13:47:32 +0000741** This routine is called to evaluate an SQL function implemented
742** using TCL script.
743*/
drhfb7e7652005-01-24 00:28:42 +0000744static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000745 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000746 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000747 int i;
748 int rc;
749
drhd1e47332005-06-26 17:55:33 +0000750 if( argc==0 ){
751 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
752 ** script object directly. This allows the TCL compiler to generate
753 ** bytecode for the command on the first invocation and thus make
754 ** subsequent invocations much faster. */
755 pCmd = p->pScript;
756 Tcl_IncrRefCount(pCmd);
757 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
758 Tcl_DecrRefCount(pCmd);
759 }else{
760 /* If there are arguments to the function, make a shallow copy of the
761 ** script object, lappend the arguments, then evaluate the copy.
762 **
763 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
764 ** The new Tcl_Obj contains pointers to the original list elements.
765 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
766 ** of the list to tclCmdNameType, that alternate representation will
767 ** be preserved and reused on the next invocation.
768 */
769 Tcl_Obj **aArg;
770 int nArg;
771 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
772 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
773 return;
774 }
775 pCmd = Tcl_NewListObj(nArg, aArg);
776 Tcl_IncrRefCount(pCmd);
777 for(i=0; i<argc; i++){
778 sqlite3_value *pIn = argv[i];
779 Tcl_Obj *pVal;
780
781 /* Set pVal to contain the i'th column of this row. */
782 switch( sqlite3_value_type(pIn) ){
783 case SQLITE_BLOB: {
784 int bytes = sqlite3_value_bytes(pIn);
785 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
786 break;
787 }
788 case SQLITE_INTEGER: {
789 sqlite_int64 v = sqlite3_value_int64(pIn);
790 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +0000791 pVal = Tcl_NewIntObj((int)v);
drhd1e47332005-06-26 17:55:33 +0000792 }else{
793 pVal = Tcl_NewWideIntObj(v);
794 }
795 break;
796 }
797 case SQLITE_FLOAT: {
798 double r = sqlite3_value_double(pIn);
799 pVal = Tcl_NewDoubleObj(r);
800 break;
801 }
802 case SQLITE_NULL: {
803 pVal = Tcl_NewStringObj("", 0);
804 break;
805 }
806 default: {
807 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000808 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000809 break;
810 }
811 }
812 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
813 if( rc ){
814 Tcl_DecrRefCount(pCmd);
815 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
816 return;
817 }
danielk197751ad0ec2004-05-24 12:39:02 +0000818 }
drhd1e47332005-06-26 17:55:33 +0000819 if( !p->useEvalObjv ){
820 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
821 ** is a list without a string representation. To prevent this from
822 ** happening, make sure pCmd has a valid string representation */
823 Tcl_GetString(pCmd);
824 }
825 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
826 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000827 }
danielk1977562e8d32005-05-20 09:40:55 +0000828
drhc7f269d2005-05-05 10:30:29 +0000829 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000830 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000831 }else{
drhc7f269d2005-05-05 10:30:29 +0000832 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
833 int n;
834 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000835 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000836 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000837 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000838 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000839 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000840 data = Tcl_GetByteArrayFromObj(pVar, &n);
841 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000842 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000843 Tcl_GetIntFromObj(0, pVar, &n);
844 sqlite3_result_int(context, n);
845 }else if( c=='d' && strcmp(zType,"double")==0 ){
846 double r;
847 Tcl_GetDoubleFromObj(0, pVar, &r);
848 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +0000849 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
850 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000851 Tcl_WideInt v;
852 Tcl_GetWideIntFromObj(0, pVar, &v);
853 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000854 }else{
danielk197700fd9572005-12-07 06:27:43 +0000855 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
856 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000857 }
drhcabb0812002-09-14 13:47:32 +0000858 }
859}
drh895d7472004-08-20 16:02:39 +0000860
drhe22a3342003-04-22 20:30:37 +0000861#ifndef SQLITE_OMIT_AUTHORIZATION
862/*
863** This is the authentication function. It appends the authentication
864** type code and the two arguments to zCmd[] then invokes the result
865** on the interpreter. The reply is examined to determine if the
866** authentication fails or succeeds.
867*/
868static int auth_callback(
869 void *pArg,
870 int code,
871 const char *zArg1,
872 const char *zArg2,
873 const char *zArg3,
874 const char *zArg4
875){
876 char *zCode;
877 Tcl_DString str;
878 int rc;
879 const char *zReply;
880 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +0000881 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +0000882
883 switch( code ){
884 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
885 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
886 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
887 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
888 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
889 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
890 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
891 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
892 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
893 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
894 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
895 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
896 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
897 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
898 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
899 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
900 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
901 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
902 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
903 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
904 case SQLITE_READ : zCode="SQLITE_READ"; break;
905 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
906 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
907 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000908 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
909 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000910 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000911 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000912 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000913 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
914 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000915 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +0000916 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drhe22a3342003-04-22 20:30:37 +0000917 default : zCode="????"; break;
918 }
919 Tcl_DStringInit(&str);
920 Tcl_DStringAppend(&str, pDb->zAuth, -1);
921 Tcl_DStringAppendElement(&str, zCode);
922 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
923 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
924 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
925 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
926 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
927 Tcl_DStringFree(&str);
drhb07028f2011-10-14 21:49:18 +0000928 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
drhe22a3342003-04-22 20:30:37 +0000929 if( strcmp(zReply,"SQLITE_OK")==0 ){
930 rc = SQLITE_OK;
931 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
932 rc = SQLITE_DENY;
933 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
934 rc = SQLITE_IGNORE;
935 }else{
936 rc = 999;
937 }
938 return rc;
939}
940#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000941
942/*
danielk1977ef2cb632004-05-29 02:37:19 +0000943** zText is a pointer to text obtained via an sqlite3_result_text()
944** or similar interface. This routine returns a Tcl string object,
945** reference count set to 0, containing the text. If a translation
946** between iso8859 and UTF-8 is required, it is preformed.
947*/
948static Tcl_Obj *dbTextToObj(char const *zText){
949 Tcl_Obj *pVal;
950#ifdef UTF_TRANSLATION_NEEDED
951 Tcl_DString dCol;
952 Tcl_DStringInit(&dCol);
953 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
954 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
955 Tcl_DStringFree(&dCol);
956#else
957 pVal = Tcl_NewStringObj(zText, -1);
958#endif
959 return pVal;
960}
961
962/*
tpoindex1067fe12004-12-17 15:41:11 +0000963** This routine reads a line of text from FILE in, stores
964** the text in memory obtained from malloc() and returns a pointer
965** to the text. NULL is returned at end of file, or if malloc()
966** fails.
967**
968** The interface is like "readline" but no command-line editing
969** is done.
970**
971** copied from shell.c from '.import' command
972*/
973static char *local_getline(char *zPrompt, FILE *in){
974 char *zLine;
975 int nLine;
976 int n;
tpoindex1067fe12004-12-17 15:41:11 +0000977
978 nLine = 100;
979 zLine = malloc( nLine );
980 if( zLine==0 ) return 0;
981 n = 0;
drhb07028f2011-10-14 21:49:18 +0000982 while( 1 ){
tpoindex1067fe12004-12-17 15:41:11 +0000983 if( n+100>nLine ){
984 nLine = nLine*2 + 100;
985 zLine = realloc(zLine, nLine);
986 if( zLine==0 ) return 0;
987 }
988 if( fgets(&zLine[n], nLine - n, in)==0 ){
989 if( n==0 ){
990 free(zLine);
991 return 0;
992 }
993 zLine[n] = 0;
tpoindex1067fe12004-12-17 15:41:11 +0000994 break;
995 }
996 while( zLine[n] ){ n++; }
997 if( n>0 && zLine[n-1]=='\n' ){
998 n--;
999 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +00001000 break;
tpoindex1067fe12004-12-17 15:41:11 +00001001 }
1002 }
1003 zLine = realloc( zLine, n+1 );
1004 return zLine;
1005}
1006
danielk19778e556522007-11-13 10:30:24 +00001007
1008/*
dan4a4c11a2009-10-06 14:59:02 +00001009** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +00001010**
dan4a4c11a2009-10-06 14:59:02 +00001011** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +00001012**
dan4a4c11a2009-10-06 14:59:02 +00001013** It is invoked after evaluating the script SCRIPT to commit or rollback
1014** the transaction or savepoint opened by the [transaction] command.
1015*/
1016static int DbTransPostCmd(
1017 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1018 Tcl_Interp *interp, /* Tcl interpreter */
1019 int result /* Result of evaluating SCRIPT */
1020){
1021 static const char *azEnd[] = {
1022 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1023 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1024 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1025 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1026 };
1027 SqliteDb *pDb = (SqliteDb*)data[0];
1028 int rc = result;
1029 const char *zEnd;
1030
1031 pDb->nTransaction--;
1032 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1033
1034 pDb->disableAuth++;
1035 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1036 /* This is a tricky scenario to handle. The most likely cause of an
1037 ** error is that the exec() above was an attempt to commit the
1038 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1039 ** that an IO-error has occured. In either case, throw a Tcl exception
1040 ** and try to rollback the transaction.
1041 **
1042 ** But it could also be that the user executed one or more BEGIN,
1043 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1044 ** this method's logic. Not clear how this would be best handled.
1045 */
1046 if( rc!=TCL_ERROR ){
1047 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
1048 rc = TCL_ERROR;
1049 }
1050 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1051 }
1052 pDb->disableAuth--;
1053
1054 return rc;
1055}
1056
1057/*
danc431fd52011-06-27 16:55:50 +00001058** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1059** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1060** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1061** on whether or not the [db_use_legacy_prepare] command has been used to
1062** configure the connection.
1063*/
1064static int dbPrepare(
1065 SqliteDb *pDb, /* Database object */
1066 const char *zSql, /* SQL to compile */
1067 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1068 const char **pzOut /* OUT: Pointer to next SQL statement */
1069){
1070#ifdef SQLITE_TEST
1071 if( pDb->bLegacyPrepare ){
1072 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1073 }
1074#endif
1075 return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut);
1076}
1077
1078/*
dan4a4c11a2009-10-06 14:59:02 +00001079** Search the cache for a prepared-statement object that implements the
1080** first SQL statement in the buffer pointed to by parameter zIn. If
1081** no such prepared-statement can be found, allocate and prepare a new
1082** one. In either case, bind the current values of the relevant Tcl
1083** variables to any $var, :var or @var variables in the statement. Before
1084** returning, set *ppPreStmt to point to the prepared-statement object.
1085**
1086** Output parameter *pzOut is set to point to the next SQL statement in
1087** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1088** next statement.
1089**
1090** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1091** and an error message loaded into interpreter pDb->interp.
1092*/
1093static int dbPrepareAndBind(
1094 SqliteDb *pDb, /* Database object */
1095 char const *zIn, /* SQL to compile */
1096 char const **pzOut, /* OUT: Pointer to next SQL statement */
1097 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1098){
1099 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
1100 sqlite3_stmt *pStmt; /* Prepared statement object */
1101 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1102 int nSql; /* Length of zSql in bytes */
1103 int nVar; /* Number of variables in statement */
1104 int iParm = 0; /* Next free entry in apParm */
1105 int i;
1106 Tcl_Interp *interp = pDb->interp;
1107
1108 *ppPreStmt = 0;
1109
1110 /* Trim spaces from the start of zSql and calculate the remaining length. */
1111 while( isspace(zSql[0]) ){ zSql++; }
1112 nSql = strlen30(zSql);
1113
1114 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1115 int n = pPreStmt->nSql;
1116 if( nSql>=n
1117 && memcmp(pPreStmt->zSql, zSql, n)==0
1118 && (zSql[n]==0 || zSql[n-1]==';')
1119 ){
1120 pStmt = pPreStmt->pStmt;
1121 *pzOut = &zSql[pPreStmt->nSql];
1122
1123 /* When a prepared statement is found, unlink it from the
1124 ** cache list. It will later be added back to the beginning
1125 ** of the cache list in order to implement LRU replacement.
1126 */
1127 if( pPreStmt->pPrev ){
1128 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1129 }else{
1130 pDb->stmtList = pPreStmt->pNext;
1131 }
1132 if( pPreStmt->pNext ){
1133 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1134 }else{
1135 pDb->stmtLast = pPreStmt->pPrev;
1136 }
1137 pDb->nStmt--;
1138 nVar = sqlite3_bind_parameter_count(pStmt);
1139 break;
1140 }
1141 }
1142
1143 /* If no prepared statement was found. Compile the SQL text. Also allocate
1144 ** a new SqlPreparedStmt structure. */
1145 if( pPreStmt==0 ){
1146 int nByte;
1147
danc431fd52011-06-27 16:55:50 +00001148 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
dan4a4c11a2009-10-06 14:59:02 +00001149 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1150 return TCL_ERROR;
1151 }
1152 if( pStmt==0 ){
1153 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1154 /* A compile-time error in the statement. */
1155 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1156 return TCL_ERROR;
1157 }else{
1158 /* The statement was a no-op. Continue to the next statement
1159 ** in the SQL string.
1160 */
1161 return TCL_OK;
1162 }
1163 }
1164
1165 assert( pPreStmt==0 );
1166 nVar = sqlite3_bind_parameter_count(pStmt);
1167 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1168 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1169 memset(pPreStmt, 0, nByte);
1170
1171 pPreStmt->pStmt = pStmt;
drh7ed243b2012-04-19 17:19:51 +00001172 pPreStmt->nSql = (int)(*pzOut - zSql);
dan4a4c11a2009-10-06 14:59:02 +00001173 pPreStmt->zSql = sqlite3_sql(pStmt);
1174 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
danc431fd52011-06-27 16:55:50 +00001175#ifdef SQLITE_TEST
1176 if( pPreStmt->zSql==0 ){
1177 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1178 memcpy(zCopy, zSql, pPreStmt->nSql);
1179 zCopy[pPreStmt->nSql] = '\0';
1180 pPreStmt->zSql = zCopy;
1181 }
1182#endif
dan4a4c11a2009-10-06 14:59:02 +00001183 }
1184 assert( pPreStmt );
1185 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1186 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1187
1188 /* Bind values to parameters that begin with $ or : */
1189 for(i=1; i<=nVar; i++){
1190 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1191 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1192 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1193 if( pVar ){
1194 int n;
1195 u8 *data;
1196 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1197 char c = zType[0];
1198 if( zVar[0]=='@' ||
1199 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1200 /* Load a BLOB type if the Tcl variable is a bytearray and
1201 ** it has no string representation or the host
1202 ** parameter name begins with "@". */
1203 data = Tcl_GetByteArrayFromObj(pVar, &n);
1204 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1205 Tcl_IncrRefCount(pVar);
1206 pPreStmt->apParm[iParm++] = pVar;
1207 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1208 Tcl_GetIntFromObj(interp, pVar, &n);
1209 sqlite3_bind_int(pStmt, i, n);
1210 }else if( c=='d' && strcmp(zType,"double")==0 ){
1211 double r;
1212 Tcl_GetDoubleFromObj(interp, pVar, &r);
1213 sqlite3_bind_double(pStmt, i, r);
1214 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1215 (c=='i' && strcmp(zType,"int")==0) ){
1216 Tcl_WideInt v;
1217 Tcl_GetWideIntFromObj(interp, pVar, &v);
1218 sqlite3_bind_int64(pStmt, i, v);
1219 }else{
1220 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1221 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1222 Tcl_IncrRefCount(pVar);
1223 pPreStmt->apParm[iParm++] = pVar;
1224 }
1225 }else{
1226 sqlite3_bind_null(pStmt, i);
1227 }
1228 }
1229 }
1230 pPreStmt->nParm = iParm;
1231 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001232
dan4a4c11a2009-10-06 14:59:02 +00001233 return TCL_OK;
1234}
1235
dan4a4c11a2009-10-06 14:59:02 +00001236/*
1237** Release a statement reference obtained by calling dbPrepareAndBind().
1238** There should be exactly one call to this function for each call to
1239** dbPrepareAndBind().
1240**
1241** If the discard parameter is non-zero, then the statement is deleted
1242** immediately. Otherwise it is added to the LRU list and may be returned
1243** by a subsequent call to dbPrepareAndBind().
1244*/
1245static void dbReleaseStmt(
1246 SqliteDb *pDb, /* Database handle */
1247 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1248 int discard /* True to delete (not cache) the pPreStmt */
1249){
1250 int i;
1251
1252 /* Free the bound string and blob parameters */
1253 for(i=0; i<pPreStmt->nParm; i++){
1254 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1255 }
1256 pPreStmt->nParm = 0;
1257
1258 if( pDb->maxStmt<=0 || discard ){
1259 /* If the cache is turned off, deallocated the statement */
danc431fd52011-06-27 16:55:50 +00001260 dbFreeStmt(pPreStmt);
dan4a4c11a2009-10-06 14:59:02 +00001261 }else{
1262 /* Add the prepared statement to the beginning of the cache list. */
1263 pPreStmt->pNext = pDb->stmtList;
1264 pPreStmt->pPrev = 0;
1265 if( pDb->stmtList ){
1266 pDb->stmtList->pPrev = pPreStmt;
1267 }
1268 pDb->stmtList = pPreStmt;
1269 if( pDb->stmtLast==0 ){
1270 assert( pDb->nStmt==0 );
1271 pDb->stmtLast = pPreStmt;
1272 }else{
1273 assert( pDb->nStmt>0 );
1274 }
1275 pDb->nStmt++;
1276
1277 /* If we have too many statement in cache, remove the surplus from
1278 ** the end of the cache list. */
1279 while( pDb->nStmt>pDb->maxStmt ){
danc431fd52011-06-27 16:55:50 +00001280 SqlPreparedStmt *pLast = pDb->stmtLast;
1281 pDb->stmtLast = pLast->pPrev;
dan4a4c11a2009-10-06 14:59:02 +00001282 pDb->stmtLast->pNext = 0;
1283 pDb->nStmt--;
danc431fd52011-06-27 16:55:50 +00001284 dbFreeStmt(pLast);
dan4a4c11a2009-10-06 14:59:02 +00001285 }
1286 }
1287}
1288
1289/*
1290** Structure used with dbEvalXXX() functions:
1291**
1292** dbEvalInit()
1293** dbEvalStep()
1294** dbEvalFinalize()
1295** dbEvalRowInfo()
1296** dbEvalColumnValue()
1297*/
1298typedef struct DbEvalContext DbEvalContext;
1299struct DbEvalContext {
1300 SqliteDb *pDb; /* Database handle */
1301 Tcl_Obj *pSql; /* Object holding string zSql */
1302 const char *zSql; /* Remaining SQL to execute */
1303 SqlPreparedStmt *pPreStmt; /* Current statement */
1304 int nCol; /* Number of columns returned by pStmt */
1305 Tcl_Obj *pArray; /* Name of array variable */
1306 Tcl_Obj **apColName; /* Array of column names */
1307};
1308
1309/*
1310** Release any cache of column names currently held as part of
1311** the DbEvalContext structure passed as the first argument.
1312*/
1313static void dbReleaseColumnNames(DbEvalContext *p){
1314 if( p->apColName ){
1315 int i;
1316 for(i=0; i<p->nCol; i++){
1317 Tcl_DecrRefCount(p->apColName[i]);
1318 }
1319 Tcl_Free((char *)p->apColName);
1320 p->apColName = 0;
1321 }
1322 p->nCol = 0;
1323}
1324
1325/*
1326** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001327**
1328** If pArray is not NULL, then it contains the name of a Tcl array
1329** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001330** the names of the columns returned by the statement as part of each
1331** call to dbEvalStep(), in order from left to right. e.g. if the names
1332** of the returned columns are a, b and c, it does the equivalent of the
1333** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001334**
1335** set ${pArray}(*) {a b c}
1336*/
dan4a4c11a2009-10-06 14:59:02 +00001337static void dbEvalInit(
1338 DbEvalContext *p, /* Pointer to structure to initialize */
1339 SqliteDb *pDb, /* Database handle */
1340 Tcl_Obj *pSql, /* Object containing SQL script */
1341 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001342){
dan4a4c11a2009-10-06 14:59:02 +00001343 memset(p, 0, sizeof(DbEvalContext));
1344 p->pDb = pDb;
1345 p->zSql = Tcl_GetString(pSql);
1346 p->pSql = pSql;
1347 Tcl_IncrRefCount(pSql);
1348 if( pArray ){
1349 p->pArray = pArray;
1350 Tcl_IncrRefCount(pArray);
1351 }
1352}
danielk19778e556522007-11-13 10:30:24 +00001353
dan4a4c11a2009-10-06 14:59:02 +00001354/*
1355** Obtain information about the row that the DbEvalContext passed as the
1356** first argument currently points to.
1357*/
1358static void dbEvalRowInfo(
1359 DbEvalContext *p, /* Evaluation context */
1360 int *pnCol, /* OUT: Number of column names */
1361 Tcl_Obj ***papColName /* OUT: Array of column names */
1362){
danielk19778e556522007-11-13 10:30:24 +00001363 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001364 if( 0==p->apColName ){
1365 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1366 int i; /* Iterator variable */
1367 int nCol; /* Number of columns returned by pStmt */
1368 Tcl_Obj **apColName = 0; /* Array of column names */
1369
1370 p->nCol = nCol = sqlite3_column_count(pStmt);
1371 if( nCol>0 && (papColName || p->pArray) ){
1372 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1373 for(i=0; i<nCol; i++){
1374 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1375 Tcl_IncrRefCount(apColName[i]);
1376 }
1377 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001378 }
1379
1380 /* If results are being stored in an array variable, then create
1381 ** the array(*) entry for that array
1382 */
dan4a4c11a2009-10-06 14:59:02 +00001383 if( p->pArray ){
1384 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001385 Tcl_Obj *pColList = Tcl_NewObj();
1386 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001387
danielk19778e556522007-11-13 10:30:24 +00001388 for(i=0; i<nCol; i++){
1389 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1390 }
1391 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001392 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001393 Tcl_DecrRefCount(pStar);
1394 }
danielk19778e556522007-11-13 10:30:24 +00001395 }
1396
dan4a4c11a2009-10-06 14:59:02 +00001397 if( papColName ){
1398 *papColName = p->apColName;
1399 }
1400 if( pnCol ){
1401 *pnCol = p->nCol;
1402 }
1403}
1404
1405/*
1406** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1407** returned, then an error message is stored in the interpreter before
1408** returning.
1409**
1410** A return value of TCL_OK means there is a row of data available. The
1411** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1412** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1413** is returned, then the SQL script has finished executing and there are
1414** no further rows available. This is similar to SQLITE_DONE.
1415*/
1416static int dbEvalStep(DbEvalContext *p){
danc431fd52011-06-27 16:55:50 +00001417 const char *zPrevSql = 0; /* Previous value of p->zSql */
1418
dan4a4c11a2009-10-06 14:59:02 +00001419 while( p->zSql[0] || p->pPreStmt ){
1420 int rc;
1421 if( p->pPreStmt==0 ){
danc431fd52011-06-27 16:55:50 +00001422 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
dan4a4c11a2009-10-06 14:59:02 +00001423 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1424 if( rc!=TCL_OK ) return rc;
1425 }else{
1426 int rcs;
1427 SqliteDb *pDb = p->pDb;
1428 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1429 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1430
1431 rcs = sqlite3_step(pStmt);
1432 if( rcs==SQLITE_ROW ){
1433 return TCL_OK;
1434 }
1435 if( p->pArray ){
1436 dbEvalRowInfo(p, 0, 0);
1437 }
1438 rcs = sqlite3_reset(pStmt);
1439
1440 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1441 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001442 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
dan4a4c11a2009-10-06 14:59:02 +00001443 dbReleaseColumnNames(p);
1444 p->pPreStmt = 0;
1445
1446 if( rcs!=SQLITE_OK ){
1447 /* If a run-time error occurs, report the error and stop reading
1448 ** the SQL. */
dan4a4c11a2009-10-06 14:59:02 +00001449 dbReleaseStmt(pDb, pPreStmt, 1);
danc431fd52011-06-27 16:55:50 +00001450#if SQLITE_TEST
1451 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1452 /* If the runtime error was an SQLITE_SCHEMA, and the database
1453 ** handle is configured to use the legacy sqlite3_prepare()
1454 ** interface, retry prepare()/step() on the same SQL statement.
1455 ** This only happens once. If there is a second SQLITE_SCHEMA
1456 ** error, the error will be returned to the caller. */
1457 p->zSql = zPrevSql;
1458 continue;
1459 }
1460#endif
1461 Tcl_SetObjResult(pDb->interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
dan4a4c11a2009-10-06 14:59:02 +00001462 return TCL_ERROR;
1463 }else{
1464 dbReleaseStmt(pDb, pPreStmt, 0);
1465 }
1466 }
1467 }
1468
1469 /* Finished */
1470 return TCL_BREAK;
1471}
1472
1473/*
1474** Free all resources currently held by the DbEvalContext structure passed
1475** as the first argument. There should be exactly one call to this function
1476** for each call to dbEvalInit().
1477*/
1478static void dbEvalFinalize(DbEvalContext *p){
1479 if( p->pPreStmt ){
1480 sqlite3_reset(p->pPreStmt->pStmt);
1481 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1482 p->pPreStmt = 0;
1483 }
1484 if( p->pArray ){
1485 Tcl_DecrRefCount(p->pArray);
1486 p->pArray = 0;
1487 }
1488 Tcl_DecrRefCount(p->pSql);
1489 dbReleaseColumnNames(p);
1490}
1491
1492/*
1493** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1494** the value for the iCol'th column of the row currently pointed to by
1495** the DbEvalContext structure passed as the first argument.
1496*/
1497static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1498 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1499 switch( sqlite3_column_type(pStmt, iCol) ){
1500 case SQLITE_BLOB: {
1501 int bytes = sqlite3_column_bytes(pStmt, iCol);
1502 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1503 if( !zBlob ) bytes = 0;
1504 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1505 }
1506 case SQLITE_INTEGER: {
1507 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1508 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +00001509 return Tcl_NewIntObj((int)v);
dan4a4c11a2009-10-06 14:59:02 +00001510 }else{
1511 return Tcl_NewWideIntObj(v);
1512 }
1513 }
1514 case SQLITE_FLOAT: {
1515 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1516 }
1517 case SQLITE_NULL: {
1518 return dbTextToObj(p->pDb->zNull);
1519 }
1520 }
1521
1522 return dbTextToObj((char *)sqlite3_column_text(pStmt, iCol));
1523}
1524
1525/*
1526** If using Tcl version 8.6 or greater, use the NR functions to avoid
1527** recursive evalution of scripts by the [db eval] and [db trans]
1528** commands. Even if the headers used while compiling the extension
1529** are 8.6 or newer, the code still tests the Tcl version at runtime.
1530** This allows stubs-enabled builds to be used with older Tcl libraries.
1531*/
1532#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001533# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001534static int DbUseNre(void){
1535 int major, minor;
1536 Tcl_GetVersion(&major, &minor, 0, 0);
1537 return( (major==8 && minor>=6) || major>8 );
1538}
1539#else
1540/*
1541** Compiling using headers earlier than 8.6. In this case NR cannot be
1542** used, so DbUseNre() to always return zero. Add #defines for the other
1543** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1544** even though the only invocations of them are within conditional blocks
1545** of the form:
1546**
1547** if( DbUseNre() ) { ... }
1548*/
drha2c8a952009-10-13 18:38:34 +00001549# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001550# define DbUseNre() 0
1551# define Tcl_NRAddCallback(a,b,c,d,e,f) 0
1552# define Tcl_NREvalObj(a,b,c) 0
1553# define Tcl_NRCreateCommand(a,b,c,d,e,f) 0
1554#endif
1555
1556/*
1557** This function is part of the implementation of the command:
1558**
1559** $db eval SQL ?ARRAYNAME? SCRIPT
1560*/
1561static int DbEvalNextCmd(
1562 ClientData data[], /* data[0] is the (DbEvalContext*) */
1563 Tcl_Interp *interp, /* Tcl interpreter */
1564 int result /* Result so far */
1565){
1566 int rc = result; /* Return code */
1567
1568 /* The first element of the data[] array is a pointer to a DbEvalContext
1569 ** structure allocated using Tcl_Alloc(). The second element of data[]
1570 ** is a pointer to a Tcl_Obj containing the script to run for each row
1571 ** returned by the queries encapsulated in data[0]. */
1572 DbEvalContext *p = (DbEvalContext *)data[0];
1573 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1574 Tcl_Obj *pArray = p->pArray;
1575
1576 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1577 int i;
1578 int nCol;
1579 Tcl_Obj **apColName;
1580 dbEvalRowInfo(p, &nCol, &apColName);
1581 for(i=0; i<nCol; i++){
1582 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1583 if( pArray==0 ){
1584 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1585 }else{
1586 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1587 }
1588 }
1589
1590 /* The required interpreter variables are now populated with the data
1591 ** from the current row. If using NRE, schedule callbacks to evaluate
1592 ** script pScript, then to invoke this function again to fetch the next
1593 ** row (or clean up if there is no next row or the script throws an
1594 ** exception). After scheduling the callbacks, return control to the
1595 ** caller.
1596 **
1597 ** If not using NRE, evaluate pScript directly and continue with the
1598 ** next iteration of this while(...) loop. */
1599 if( DbUseNre() ){
1600 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1601 return Tcl_NREvalObj(interp, pScript, 0);
1602 }else{
1603 rc = Tcl_EvalObjEx(interp, pScript, 0);
1604 }
1605 }
1606
1607 Tcl_DecrRefCount(pScript);
1608 dbEvalFinalize(p);
1609 Tcl_Free((char *)p);
1610
1611 if( rc==TCL_OK || rc==TCL_BREAK ){
1612 Tcl_ResetResult(interp);
1613 rc = TCL_OK;
1614 }
1615 return rc;
danielk19778e556522007-11-13 10:30:24 +00001616}
1617
tpoindex1067fe12004-12-17 15:41:11 +00001618/*
drh75897232000-05-29 14:26:00 +00001619** The "sqlite" command below creates a new Tcl command for each
1620** connection it opens to an SQLite database. This routine is invoked
1621** whenever one of those connection-specific commands is executed
1622** in Tcl. For example, if you run Tcl code like this:
1623**
drh9bb575f2004-09-06 17:24:11 +00001624** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001625** db1 close
1626**
1627** The first command opens a connection to the "my_database" database
1628** and calls that connection "db1". The second command causes this
1629** subroutine to be invoked.
1630*/
drh6d313162000-09-21 13:01:35 +00001631static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001632 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001633 int choice;
drh22fbcb82004-02-01 01:22:50 +00001634 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001635 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001636 "authorizer", "backup", "busy",
1637 "cache", "changes", "close",
1638 "collate", "collation_needed", "commit_hook",
1639 "complete", "copy", "enable_load_extension",
1640 "errorcode", "eval", "exists",
1641 "function", "incrblob", "interrupt",
drh833bf962010-04-28 14:42:19 +00001642 "last_insert_rowid", "nullvalue", "onecolumn",
1643 "profile", "progress", "rekey",
1644 "restore", "rollback_hook", "status",
1645 "timeout", "total_changes", "trace",
1646 "transaction", "unlock_notify", "update_hook",
1647 "version", "wal_hook", 0
drh6d313162000-09-21 13:01:35 +00001648 };
drh411995d2002-06-25 19:31:18 +00001649 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001650 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1651 DB_CACHE, DB_CHANGES, DB_CLOSE,
1652 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1653 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1654 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1655 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
drh833bf962010-04-28 14:42:19 +00001656 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
1657 DB_PROFILE, DB_PROGRESS, DB_REKEY,
1658 DB_RESTORE, DB_ROLLBACK_HOOK, DB_STATUS,
1659 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
1660 DB_TRANSACTION, DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK,
1661 DB_VERSION, DB_WAL_HOOK
drh6d313162000-09-21 13:01:35 +00001662 };
tpoindex1067fe12004-12-17 15:41:11 +00001663 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001664
1665 if( objc<2 ){
1666 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001667 return TCL_ERROR;
1668 }
drh411995d2002-06-25 19:31:18 +00001669 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001670 return TCL_ERROR;
1671 }
1672
drh411995d2002-06-25 19:31:18 +00001673 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001674
drhe22a3342003-04-22 20:30:37 +00001675 /* $db authorizer ?CALLBACK?
1676 **
1677 ** Invoke the given callback to authorize each SQL operation as it is
1678 ** compiled. 5 arguments are appended to the callback before it is
1679 ** invoked:
1680 **
1681 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1682 ** (2) First descriptive name (depends on authorization type)
1683 ** (3) Second descriptive name
1684 ** (4) Name of the database (ex: "main", "temp")
1685 ** (5) Name of trigger that is doing the access
1686 **
1687 ** The callback should return on of the following strings: SQLITE_OK,
1688 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1689 **
1690 ** If this method is invoked with no arguments, the current authorization
1691 ** callback string is returned.
1692 */
1693 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001694#ifdef SQLITE_OMIT_AUTHORIZATION
1695 Tcl_AppendResult(interp, "authorization not available in this build", 0);
1696 return TCL_ERROR;
1697#else
drhe22a3342003-04-22 20:30:37 +00001698 if( objc>3 ){
1699 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001700 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001701 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001702 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +00001703 Tcl_AppendResult(interp, pDb->zAuth, 0);
1704 }
1705 }else{
1706 char *zAuth;
1707 int len;
1708 if( pDb->zAuth ){
1709 Tcl_Free(pDb->zAuth);
1710 }
1711 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1712 if( zAuth && len>0 ){
1713 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001714 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001715 }else{
1716 pDb->zAuth = 0;
1717 }
drhe22a3342003-04-22 20:30:37 +00001718 if( pDb->zAuth ){
1719 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001720 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +00001721 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001722 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001723 }
drhe22a3342003-04-22 20:30:37 +00001724 }
drh1211de32004-07-26 12:24:22 +00001725#endif
drhe22a3342003-04-22 20:30:37 +00001726 break;
1727 }
1728
drhdc2c4912009-02-04 22:46:47 +00001729 /* $db backup ?DATABASE? FILENAME
1730 **
1731 ** Open or create a database file named FILENAME. Transfer the
1732 ** content of local database DATABASE (default: "main") into the
1733 ** FILENAME database.
1734 */
1735 case DB_BACKUP: {
1736 const char *zDestFile;
1737 const char *zSrcDb;
1738 sqlite3 *pDest;
1739 sqlite3_backup *pBackup;
1740
1741 if( objc==3 ){
1742 zSrcDb = "main";
1743 zDestFile = Tcl_GetString(objv[2]);
1744 }else if( objc==4 ){
1745 zSrcDb = Tcl_GetString(objv[2]);
1746 zDestFile = Tcl_GetString(objv[3]);
1747 }else{
1748 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1749 return TCL_ERROR;
1750 }
1751 rc = sqlite3_open(zDestFile, &pDest);
1752 if( rc!=SQLITE_OK ){
1753 Tcl_AppendResult(interp, "cannot open target database: ",
1754 sqlite3_errmsg(pDest), (char*)0);
1755 sqlite3_close(pDest);
1756 return TCL_ERROR;
1757 }
1758 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1759 if( pBackup==0 ){
1760 Tcl_AppendResult(interp, "backup failed: ",
1761 sqlite3_errmsg(pDest), (char*)0);
1762 sqlite3_close(pDest);
1763 return TCL_ERROR;
1764 }
1765 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1766 sqlite3_backup_finish(pBackup);
1767 if( rc==SQLITE_DONE ){
1768 rc = TCL_OK;
1769 }else{
1770 Tcl_AppendResult(interp, "backup failed: ",
1771 sqlite3_errmsg(pDest), (char*)0);
1772 rc = TCL_ERROR;
1773 }
1774 sqlite3_close(pDest);
1775 break;
1776 }
1777
drhbec3f402000-08-04 13:49:02 +00001778 /* $db busy ?CALLBACK?
1779 **
1780 ** Invoke the given callback if an SQL statement attempts to open
1781 ** a locked database file.
1782 */
drh6d313162000-09-21 13:01:35 +00001783 case DB_BUSY: {
1784 if( objc>3 ){
1785 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001786 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001787 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001788 if( pDb->zBusy ){
1789 Tcl_AppendResult(interp, pDb->zBusy, 0);
1790 }
1791 }else{
drh6d313162000-09-21 13:01:35 +00001792 char *zBusy;
1793 int len;
drhbec3f402000-08-04 13:49:02 +00001794 if( pDb->zBusy ){
1795 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001796 }
drh6d313162000-09-21 13:01:35 +00001797 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1798 if( zBusy && len>0 ){
1799 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001800 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001801 }else{
1802 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001803 }
1804 if( pDb->zBusy ){
1805 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001806 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001807 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001808 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001809 }
1810 }
drh6d313162000-09-21 13:01:35 +00001811 break;
1812 }
drhbec3f402000-08-04 13:49:02 +00001813
drhfb7e7652005-01-24 00:28:42 +00001814 /* $db cache flush
1815 ** $db cache size n
1816 **
1817 ** Flush the prepared statement cache, or set the maximum number of
1818 ** cached statements.
1819 */
1820 case DB_CACHE: {
1821 char *subCmd;
1822 int n;
1823
1824 if( objc<=2 ){
1825 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1826 return TCL_ERROR;
1827 }
1828 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1829 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1830 if( objc!=3 ){
1831 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1832 return TCL_ERROR;
1833 }else{
1834 flushStmtCache( pDb );
1835 }
1836 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1837 if( objc!=4 ){
1838 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1839 return TCL_ERROR;
1840 }else{
1841 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1842 Tcl_AppendResult( interp, "cannot convert \"",
1843 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1844 return TCL_ERROR;
1845 }else{
1846 if( n<0 ){
1847 flushStmtCache( pDb );
1848 n = 0;
1849 }else if( n>MAX_PREPARED_STMTS ){
1850 n = MAX_PREPARED_STMTS;
1851 }
1852 pDb->maxStmt = n;
1853 }
1854 }
1855 }else{
1856 Tcl_AppendResult( interp, "bad option \"",
danielk1977191fadc2007-10-23 08:17:48 +00001857 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
drhfb7e7652005-01-24 00:28:42 +00001858 return TCL_ERROR;
1859 }
1860 break;
1861 }
1862
danielk1977b28af712004-06-21 06:50:26 +00001863 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001864 **
1865 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001866 ** the most recent INSERT, UPDATE or DELETE statement, not including
1867 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001868 */
1869 case DB_CHANGES: {
1870 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001871 if( objc!=2 ){
1872 Tcl_WrongNumArgs(interp, 2, objv, "");
1873 return TCL_ERROR;
1874 }
drhc8d30ac2002-04-12 10:08:59 +00001875 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001876 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001877 break;
1878 }
1879
drh75897232000-05-29 14:26:00 +00001880 /* $db close
1881 **
1882 ** Shutdown the database
1883 */
drh6d313162000-09-21 13:01:35 +00001884 case DB_CLOSE: {
1885 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1886 break;
1887 }
drh75897232000-05-29 14:26:00 +00001888
drh0f14e2e2004-06-29 12:39:08 +00001889 /*
1890 ** $db collate NAME SCRIPT
1891 **
1892 ** Create a new SQL collation function called NAME. Whenever
1893 ** that function is called, invoke SCRIPT to evaluate the function.
1894 */
1895 case DB_COLLATE: {
1896 SqlCollate *pCollate;
1897 char *zName;
1898 char *zScript;
1899 int nScript;
1900 if( objc!=4 ){
1901 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1902 return TCL_ERROR;
1903 }
1904 zName = Tcl_GetStringFromObj(objv[2], 0);
1905 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1906 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1907 if( pCollate==0 ) return TCL_ERROR;
1908 pCollate->interp = interp;
1909 pCollate->pNext = pDb->pCollate;
1910 pCollate->zScript = (char*)&pCollate[1];
1911 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001912 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001913 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1914 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001915 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001916 return TCL_ERROR;
1917 }
1918 break;
1919 }
1920
1921 /*
1922 ** $db collation_needed SCRIPT
1923 **
1924 ** Create a new SQL collation function called NAME. Whenever
1925 ** that function is called, invoke SCRIPT to evaluate the function.
1926 */
1927 case DB_COLLATION_NEEDED: {
1928 if( objc!=3 ){
1929 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1930 return TCL_ERROR;
1931 }
1932 if( pDb->pCollateNeeded ){
1933 Tcl_DecrRefCount(pDb->pCollateNeeded);
1934 }
1935 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1936 Tcl_IncrRefCount(pDb->pCollateNeeded);
1937 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1938 break;
1939 }
1940
drh19e2d372005-08-29 23:00:03 +00001941 /* $db commit_hook ?CALLBACK?
1942 **
1943 ** Invoke the given callback just before committing every SQL transaction.
1944 ** If the callback throws an exception or returns non-zero, then the
1945 ** transaction is aborted. If CALLBACK is an empty string, the callback
1946 ** is disabled.
1947 */
1948 case DB_COMMIT_HOOK: {
1949 if( objc>3 ){
1950 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1951 return TCL_ERROR;
1952 }else if( objc==2 ){
1953 if( pDb->zCommit ){
1954 Tcl_AppendResult(interp, pDb->zCommit, 0);
1955 }
1956 }else{
1957 char *zCommit;
1958 int len;
1959 if( pDb->zCommit ){
1960 Tcl_Free(pDb->zCommit);
1961 }
1962 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1963 if( zCommit && len>0 ){
1964 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001965 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001966 }else{
1967 pDb->zCommit = 0;
1968 }
1969 if( pDb->zCommit ){
1970 pDb->interp = interp;
1971 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1972 }else{
1973 sqlite3_commit_hook(pDb->db, 0, 0);
1974 }
1975 }
1976 break;
1977 }
1978
drh75897232000-05-29 14:26:00 +00001979 /* $db complete SQL
1980 **
1981 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1982 ** additional lines of input are needed. This is similar to the
1983 ** built-in "info complete" command of Tcl.
1984 */
drh6d313162000-09-21 13:01:35 +00001985 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00001986#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00001987 Tcl_Obj *pResult;
1988 int isComplete;
1989 if( objc!=3 ){
1990 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00001991 return TCL_ERROR;
1992 }
danielk19776f8a5032004-05-10 10:34:51 +00001993 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00001994 pResult = Tcl_GetObjResult(interp);
1995 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00001996#endif
drh6d313162000-09-21 13:01:35 +00001997 break;
1998 }
drhdcd997e2003-01-31 17:21:49 +00001999
drh19e2d372005-08-29 23:00:03 +00002000 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2001 **
2002 ** Copy data into table from filename, optionally using SEPARATOR
2003 ** as column separators. If a column contains a null string, or the
2004 ** value of NULLINDICATOR, a NULL is inserted for the column.
2005 ** conflict-algorithm is one of the sqlite conflict algorithms:
2006 ** rollback, abort, fail, ignore, replace
2007 ** On success, return the number of lines processed, not necessarily same
2008 ** as 'db changes' due to conflict-algorithm selected.
2009 **
2010 ** This code is basically an implementation/enhancement of
2011 ** the sqlite3 shell.c ".import" command.
2012 **
2013 ** This command usage is equivalent to the sqlite2.x COPY statement,
2014 ** which imports file data into a table using the PostgreSQL COPY file format:
2015 ** $db copy $conflit_algo $table_name $filename \t \\N
2016 */
2017 case DB_COPY: {
2018 char *zTable; /* Insert data into this table */
2019 char *zFile; /* The file from which to extract data */
2020 char *zConflict; /* The conflict algorithm to use */
2021 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00002022 int nCol; /* Number of columns in the table */
2023 int nByte; /* Number of bytes in an SQL string */
2024 int i, j; /* Loop counters */
2025 int nSep; /* Number of bytes in zSep[] */
2026 int nNull; /* Number of bytes in zNull[] */
2027 char *zSql; /* An SQL statement */
2028 char *zLine; /* A single line of input from the file */
2029 char **azCol; /* zLine[] broken up into columns */
2030 char *zCommit; /* How to commit changes */
2031 FILE *in; /* The input file */
2032 int lineno = 0; /* Line number of input file */
2033 char zLineNum[80]; /* Line number print buffer */
2034 Tcl_Obj *pResult; /* interp result */
2035
2036 char *zSep;
2037 char *zNull;
2038 if( objc<5 || objc>7 ){
2039 Tcl_WrongNumArgs(interp, 2, objv,
2040 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2041 return TCL_ERROR;
2042 }
2043 if( objc>=6 ){
2044 zSep = Tcl_GetStringFromObj(objv[5], 0);
2045 }else{
2046 zSep = "\t";
2047 }
2048 if( objc>=7 ){
2049 zNull = Tcl_GetStringFromObj(objv[6], 0);
2050 }else{
2051 zNull = "";
2052 }
2053 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2054 zTable = Tcl_GetStringFromObj(objv[3], 0);
2055 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002056 nSep = strlen30(zSep);
2057 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002058 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00002059 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00002060 return TCL_ERROR;
2061 }
drh3e59c012008-09-23 10:12:13 +00002062 if(strcmp(zConflict, "rollback") != 0 &&
2063 strcmp(zConflict, "abort" ) != 0 &&
2064 strcmp(zConflict, "fail" ) != 0 &&
2065 strcmp(zConflict, "ignore" ) != 0 &&
2066 strcmp(zConflict, "replace" ) != 0 ) {
drh19e2d372005-08-29 23:00:03 +00002067 Tcl_AppendResult(interp, "Error: \"", zConflict,
2068 "\", conflict-algorithm must be one of: rollback, "
2069 "abort, fail, ignore, or replace", 0);
2070 return TCL_ERROR;
2071 }
2072 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2073 if( zSql==0 ){
2074 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
2075 return TCL_ERROR;
2076 }
drh4f21c4a2008-12-10 22:15:00 +00002077 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002078 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002079 sqlite3_free(zSql);
2080 if( rc ){
2081 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2082 nCol = 0;
2083 }else{
2084 nCol = sqlite3_column_count(pStmt);
2085 }
2086 sqlite3_finalize(pStmt);
2087 if( nCol==0 ) {
2088 return TCL_ERROR;
2089 }
2090 zSql = malloc( nByte + 50 + nCol*2 );
2091 if( zSql==0 ) {
2092 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
2093 return TCL_ERROR;
2094 }
2095 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2096 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002097 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002098 for(i=1; i<nCol; i++){
2099 zSql[j++] = ',';
2100 zSql[j++] = '?';
2101 }
2102 zSql[j++] = ')';
2103 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002104 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002105 free(zSql);
2106 if( rc ){
2107 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2108 sqlite3_finalize(pStmt);
2109 return TCL_ERROR;
2110 }
2111 in = fopen(zFile, "rb");
2112 if( in==0 ){
2113 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2114 sqlite3_finalize(pStmt);
2115 return TCL_ERROR;
2116 }
2117 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2118 if( azCol==0 ) {
2119 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00002120 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002121 return TCL_ERROR;
2122 }
drh37527852006-03-16 16:19:56 +00002123 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002124 zCommit = "COMMIT";
2125 while( (zLine = local_getline(0, in))!=0 ){
2126 char *z;
drh19e2d372005-08-29 23:00:03 +00002127 lineno++;
2128 azCol[0] = zLine;
2129 for(i=0, z=zLine; *z; z++){
2130 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2131 *z = 0;
2132 i++;
2133 if( i<nCol ){
2134 azCol[i] = &z[nSep];
2135 z += nSep-1;
2136 }
2137 }
2138 }
2139 if( i+1!=nCol ){
2140 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002141 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002142 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002143 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002144 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002145 "Error: %s line %d: expected %d columns of data but found %d",
2146 zFile, lineno, nCol, i+1);
2147 Tcl_AppendResult(interp, zErr, 0);
2148 free(zErr);
2149 }
drh19e2d372005-08-29 23:00:03 +00002150 zCommit = "ROLLBACK";
2151 break;
2152 }
2153 for(i=0; i<nCol; i++){
2154 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002155 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
drh4f21c4a2008-12-10 22:15:00 +00002156 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002157 ){
drh19e2d372005-08-29 23:00:03 +00002158 sqlite3_bind_null(pStmt, i+1);
2159 }else{
2160 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2161 }
2162 }
2163 sqlite3_step(pStmt);
2164 rc = sqlite3_reset(pStmt);
2165 free(zLine);
2166 if( rc!=SQLITE_OK ){
2167 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
2168 zCommit = "ROLLBACK";
2169 break;
2170 }
2171 }
2172 free(azCol);
2173 fclose(in);
2174 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002175 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002176
2177 if( zCommit[0] == 'C' ){
2178 /* success, set result as number of lines processed */
2179 pResult = Tcl_GetObjResult(interp);
2180 Tcl_SetIntObj(pResult, lineno);
2181 rc = TCL_OK;
2182 }else{
2183 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002184 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00002185 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
2186 rc = TCL_ERROR;
2187 }
2188 break;
2189 }
2190
drhdcd997e2003-01-31 17:21:49 +00002191 /*
drh41449052006-07-06 17:08:48 +00002192 ** $db enable_load_extension BOOLEAN
2193 **
2194 ** Turn the extension loading feature on or off. It if off by
2195 ** default.
2196 */
2197 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002198#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002199 int onoff;
2200 if( objc!=3 ){
2201 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2202 return TCL_ERROR;
2203 }
2204 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2205 return TCL_ERROR;
2206 }
2207 sqlite3_enable_load_extension(pDb->db, onoff);
2208 break;
drhf533acc2006-12-19 18:57:11 +00002209#else
2210 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2211 0);
2212 return TCL_ERROR;
2213#endif
drh41449052006-07-06 17:08:48 +00002214 }
2215
2216 /*
drhdcd997e2003-01-31 17:21:49 +00002217 ** $db errorcode
2218 **
2219 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002220 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002221 */
2222 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002223 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002224 break;
2225 }
dan4a4c11a2009-10-06 14:59:02 +00002226
2227 /*
2228 ** $db exists $sql
2229 ** $db onecolumn $sql
2230 **
2231 ** The onecolumn method is the equivalent of:
2232 ** lindex [$db eval $sql] 0
2233 */
2234 case DB_EXISTS:
2235 case DB_ONECOLUMN: {
2236 DbEvalContext sEval;
2237 if( objc!=3 ){
2238 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2239 return TCL_ERROR;
2240 }
2241
2242 dbEvalInit(&sEval, pDb, objv[2], 0);
2243 rc = dbEvalStep(&sEval);
2244 if( choice==DB_ONECOLUMN ){
2245 if( rc==TCL_OK ){
2246 Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
dand5f12cd2011-08-18 17:47:57 +00002247 }else if( rc==TCL_BREAK ){
2248 Tcl_ResetResult(interp);
dan4a4c11a2009-10-06 14:59:02 +00002249 }
2250 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2251 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
2252 }
2253 dbEvalFinalize(&sEval);
2254
2255 if( rc==TCL_BREAK ){
2256 rc = TCL_OK;
2257 }
2258 break;
2259 }
drh75897232000-05-29 14:26:00 +00002260
2261 /*
drh895d7472004-08-20 16:02:39 +00002262 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002263 **
2264 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002265 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002266 ** If "array" and "code" are omitted, then no callback is every invoked.
2267 ** If "array" is an empty string, then the values are placed in variables
2268 ** that have the same name as the fields extracted by the query.
2269 */
dan4a4c11a2009-10-06 14:59:02 +00002270 case DB_EVAL: {
2271 if( objc<3 || objc>5 ){
2272 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2273 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002274 }
dan4a4c11a2009-10-06 14:59:02 +00002275
drh92febd92004-08-20 18:34:20 +00002276 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002277 DbEvalContext sEval;
2278 Tcl_Obj *pRet = Tcl_NewObj();
2279 Tcl_IncrRefCount(pRet);
2280 dbEvalInit(&sEval, pDb, objv[2], 0);
2281 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2282 int i;
2283 int nCol;
2284 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002285 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002286 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002287 }
2288 }
dan4a4c11a2009-10-06 14:59:02 +00002289 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002290 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002291 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002292 rc = TCL_OK;
2293 }
drh1807ce32004-09-07 13:20:35 +00002294 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002295 }else{
2296 ClientData cd[2];
2297 DbEvalContext *p;
2298 Tcl_Obj *pArray = 0;
2299 Tcl_Obj *pScript;
2300
2301 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2302 pArray = objv[3];
2303 }
2304 pScript = objv[objc-1];
2305 Tcl_IncrRefCount(pScript);
2306
2307 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2308 dbEvalInit(p, pDb, objv[2], pArray);
2309
2310 cd[0] = (void *)p;
2311 cd[1] = (void *)pScript;
2312 rc = DbEvalNextCmd(cd, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002313 }
danielk197730ccda12004-05-27 12:11:31 +00002314 break;
2315 }
drhbec3f402000-08-04 13:49:02 +00002316
2317 /*
drhe3602be2008-09-09 12:31:33 +00002318 ** $db function NAME [-argcount N] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002319 **
2320 ** Create a new SQL function called NAME. Whenever that function is
2321 ** called, invoke SCRIPT to evaluate the function.
2322 */
2323 case DB_FUNCTION: {
2324 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002325 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002326 char *zName;
drhe3602be2008-09-09 12:31:33 +00002327 int nArg = -1;
2328 if( objc==6 ){
2329 const char *z = Tcl_GetString(objv[3]);
drh4f21c4a2008-12-10 22:15:00 +00002330 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002331 if( n>2 && strncmp(z, "-argcount",n)==0 ){
2332 if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
2333 if( nArg<0 ){
2334 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2335 (char*)0);
2336 return TCL_ERROR;
2337 }
2338 }
2339 pScript = objv[5];
2340 }else if( objc!=4 ){
2341 Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
drhcabb0812002-09-14 13:47:32 +00002342 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002343 }else{
2344 pScript = objv[3];
drhcabb0812002-09-14 13:47:32 +00002345 }
2346 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002347 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002348 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002349 if( pFunc->pScript ){
2350 Tcl_DecrRefCount(pFunc->pScript);
2351 }
2352 pFunc->pScript = pScript;
2353 Tcl_IncrRefCount(pScript);
2354 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
drhe3602be2008-09-09 12:31:33 +00002355 rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00002356 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002357 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002358 rc = TCL_ERROR;
2359 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002360 }
drhcabb0812002-09-14 13:47:32 +00002361 break;
2362 }
2363
2364 /*
danielk19778cbadb02007-05-03 16:31:26 +00002365 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002366 */
2367 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002368#ifdef SQLITE_OMIT_INCRBLOB
2369 Tcl_AppendResult(interp, "incrblob not available in this build", 0);
2370 return TCL_ERROR;
2371#else
danielk19778cbadb02007-05-03 16:31:26 +00002372 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002373 const char *zDb = "main";
2374 const char *zTable;
2375 const char *zColumn;
2376 sqlite_int64 iRow;
2377
danielk19778cbadb02007-05-03 16:31:26 +00002378 /* Check for the -readonly option */
2379 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2380 isReadonly = 1;
2381 }
2382
2383 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2384 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002385 return TCL_ERROR;
2386 }
2387
danielk19778cbadb02007-05-03 16:31:26 +00002388 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002389 zDb = Tcl_GetString(objv[2]);
2390 }
2391 zTable = Tcl_GetString(objv[objc-3]);
2392 zColumn = Tcl_GetString(objv[objc-2]);
2393 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2394
2395 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002396 rc = createIncrblobChannel(
2397 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
2398 );
danielk1977b4e9af92007-05-01 17:49:49 +00002399 }
danielk197732a0d8b2007-05-04 19:03:02 +00002400#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002401 break;
2402 }
2403
2404 /*
drhf11bded2006-07-17 00:02:44 +00002405 ** $db interrupt
2406 **
2407 ** Interrupt the execution of the inner-most SQL interpreter. This
2408 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2409 */
2410 case DB_INTERRUPT: {
2411 sqlite3_interrupt(pDb->db);
2412 break;
2413 }
2414
2415 /*
drh19e2d372005-08-29 23:00:03 +00002416 ** $db nullvalue ?STRING?
2417 **
2418 ** Change text used when a NULL comes back from the database. If ?STRING?
2419 ** is not present, then the current string used for NULL is returned.
2420 ** If STRING is present, then STRING is returned.
2421 **
2422 */
2423 case DB_NULLVALUE: {
2424 if( objc!=2 && objc!=3 ){
2425 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2426 return TCL_ERROR;
2427 }
2428 if( objc==3 ){
2429 int len;
2430 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2431 if( pDb->zNull ){
2432 Tcl_Free(pDb->zNull);
2433 }
2434 if( zNull && len>0 ){
2435 pDb->zNull = Tcl_Alloc( len + 1 );
drh7fd33922011-06-20 19:00:30 +00002436 memcpy(pDb->zNull, zNull, len);
drh19e2d372005-08-29 23:00:03 +00002437 pDb->zNull[len] = '\0';
2438 }else{
2439 pDb->zNull = 0;
2440 }
2441 }
2442 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
2443 break;
2444 }
2445
2446 /*
drhaf9ff332002-01-16 21:00:27 +00002447 ** $db last_insert_rowid
2448 **
2449 ** Return an integer which is the ROWID for the most recent insert.
2450 */
2451 case DB_LAST_INSERT_ROWID: {
2452 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002453 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002454 if( objc!=2 ){
2455 Tcl_WrongNumArgs(interp, 2, objv, "");
2456 return TCL_ERROR;
2457 }
danielk19776f8a5032004-05-10 10:34:51 +00002458 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002459 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002460 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002461 break;
2462 }
2463
2464 /*
dan4a4c11a2009-10-06 14:59:02 +00002465 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002466 */
drh1807ce32004-09-07 13:20:35 +00002467
2468 /* $db progress ?N CALLBACK?
2469 **
2470 ** Invoke the given callback every N virtual machine opcodes while executing
2471 ** queries.
2472 */
2473 case DB_PROGRESS: {
2474 if( objc==2 ){
2475 if( pDb->zProgress ){
2476 Tcl_AppendResult(interp, pDb->zProgress, 0);
2477 }
2478 }else if( objc==4 ){
2479 char *zProgress;
2480 int len;
2481 int N;
2482 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002483 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002484 };
2485 if( pDb->zProgress ){
2486 Tcl_Free(pDb->zProgress);
2487 }
2488 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2489 if( zProgress && len>0 ){
2490 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002491 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002492 }else{
2493 pDb->zProgress = 0;
2494 }
2495#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2496 if( pDb->zProgress ){
2497 pDb->interp = interp;
2498 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2499 }else{
2500 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2501 }
2502#endif
2503 }else{
2504 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002505 return TCL_ERROR;
2506 }
drh5d9d7572003-08-19 14:31:01 +00002507 break;
2508 }
2509
drh19e2d372005-08-29 23:00:03 +00002510 /* $db profile ?CALLBACK?
2511 **
2512 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2513 ** that has run. The text of the SQL and the amount of elapse time are
2514 ** appended to CALLBACK before the script is run.
2515 */
2516 case DB_PROFILE: {
2517 if( objc>3 ){
2518 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2519 return TCL_ERROR;
2520 }else if( objc==2 ){
2521 if( pDb->zProfile ){
2522 Tcl_AppendResult(interp, pDb->zProfile, 0);
2523 }
2524 }else{
2525 char *zProfile;
2526 int len;
2527 if( pDb->zProfile ){
2528 Tcl_Free(pDb->zProfile);
2529 }
2530 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2531 if( zProfile && len>0 ){
2532 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002533 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002534 }else{
2535 pDb->zProfile = 0;
2536 }
shanehbb201342011-02-09 19:55:20 +00002537#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh19e2d372005-08-29 23:00:03 +00002538 if( pDb->zProfile ){
2539 pDb->interp = interp;
2540 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2541 }else{
2542 sqlite3_profile(pDb->db, 0, 0);
2543 }
2544#endif
2545 }
2546 break;
2547 }
2548
drh5d9d7572003-08-19 14:31:01 +00002549 /*
drh22fbcb82004-02-01 01:22:50 +00002550 ** $db rekey KEY
2551 **
2552 ** Change the encryption key on the currently open database.
2553 */
2554 case DB_REKEY: {
drhb07028f2011-10-14 21:49:18 +00002555#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002556 int nKey;
2557 void *pKey;
drhb07028f2011-10-14 21:49:18 +00002558#endif
drh22fbcb82004-02-01 01:22:50 +00002559 if( objc!=3 ){
2560 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2561 return TCL_ERROR;
2562 }
drh9eb9e262004-02-11 02:18:05 +00002563#ifdef SQLITE_HAS_CODEC
drhb07028f2011-10-14 21:49:18 +00002564 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh2011d5f2004-07-22 02:40:37 +00002565 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002566 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00002567 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002568 rc = TCL_ERROR;
2569 }
2570#endif
2571 break;
2572 }
2573
drhdc2c4912009-02-04 22:46:47 +00002574 /* $db restore ?DATABASE? FILENAME
2575 **
2576 ** Open a database file named FILENAME. Transfer the content
2577 ** of FILENAME into the local database DATABASE (default: "main").
2578 */
2579 case DB_RESTORE: {
2580 const char *zSrcFile;
2581 const char *zDestDb;
2582 sqlite3 *pSrc;
2583 sqlite3_backup *pBackup;
2584 int nTimeout = 0;
2585
2586 if( objc==3 ){
2587 zDestDb = "main";
2588 zSrcFile = Tcl_GetString(objv[2]);
2589 }else if( objc==4 ){
2590 zDestDb = Tcl_GetString(objv[2]);
2591 zSrcFile = Tcl_GetString(objv[3]);
2592 }else{
2593 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2594 return TCL_ERROR;
2595 }
2596 rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
2597 if( rc!=SQLITE_OK ){
2598 Tcl_AppendResult(interp, "cannot open source database: ",
2599 sqlite3_errmsg(pSrc), (char*)0);
2600 sqlite3_close(pSrc);
2601 return TCL_ERROR;
2602 }
2603 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2604 if( pBackup==0 ){
2605 Tcl_AppendResult(interp, "restore failed: ",
2606 sqlite3_errmsg(pDb->db), (char*)0);
2607 sqlite3_close(pSrc);
2608 return TCL_ERROR;
2609 }
2610 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2611 || rc==SQLITE_BUSY ){
2612 if( rc==SQLITE_BUSY ){
2613 if( nTimeout++ >= 3 ) break;
2614 sqlite3_sleep(100);
2615 }
2616 }
2617 sqlite3_backup_finish(pBackup);
2618 if( rc==SQLITE_DONE ){
2619 rc = TCL_OK;
2620 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2621 Tcl_AppendResult(interp, "restore failed: source database busy",
2622 (char*)0);
2623 rc = TCL_ERROR;
2624 }else{
2625 Tcl_AppendResult(interp, "restore failed: ",
2626 sqlite3_errmsg(pDb->db), (char*)0);
2627 rc = TCL_ERROR;
2628 }
2629 sqlite3_close(pSrc);
2630 break;
2631 }
2632
drh22fbcb82004-02-01 01:22:50 +00002633 /*
drh3c379b02010-04-07 19:31:59 +00002634 ** $db status (step|sort|autoindex)
drhd1d38482008-10-07 23:46:38 +00002635 **
2636 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2637 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2638 */
2639 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002640 int v;
2641 const char *zOp;
2642 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00002643 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00002644 return TCL_ERROR;
2645 }
2646 zOp = Tcl_GetString(objv[2]);
2647 if( strcmp(zOp, "step")==0 ){
2648 v = pDb->nStep;
2649 }else if( strcmp(zOp, "sort")==0 ){
2650 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002651 }else if( strcmp(zOp, "autoindex")==0 ){
2652 v = pDb->nIndex;
drhd1d38482008-10-07 23:46:38 +00002653 }else{
drh3c379b02010-04-07 19:31:59 +00002654 Tcl_AppendResult(interp,
2655 "bad argument: should be autoindex, step, or sort",
drhd1d38482008-10-07 23:46:38 +00002656 (char*)0);
2657 return TCL_ERROR;
2658 }
2659 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2660 break;
2661 }
2662
2663 /*
drhbec3f402000-08-04 13:49:02 +00002664 ** $db timeout MILLESECONDS
2665 **
2666 ** Delay for the number of milliseconds specified when a file is locked.
2667 */
drh6d313162000-09-21 13:01:35 +00002668 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002669 int ms;
drh6d313162000-09-21 13:01:35 +00002670 if( objc!=3 ){
2671 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002672 return TCL_ERROR;
2673 }
drh6d313162000-09-21 13:01:35 +00002674 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002675 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002676 break;
drh75897232000-05-29 14:26:00 +00002677 }
danielk197755c45f22005-04-03 23:54:43 +00002678
2679 /*
drh0f14e2e2004-06-29 12:39:08 +00002680 ** $db total_changes
2681 **
2682 ** Return the number of rows that were modified, inserted, or deleted
2683 ** since the database handle was created.
2684 */
2685 case DB_TOTAL_CHANGES: {
2686 Tcl_Obj *pResult;
2687 if( objc!=2 ){
2688 Tcl_WrongNumArgs(interp, 2, objv, "");
2689 return TCL_ERROR;
2690 }
2691 pResult = Tcl_GetObjResult(interp);
2692 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2693 break;
2694 }
2695
drhb5a20d32003-04-23 12:25:23 +00002696 /* $db trace ?CALLBACK?
2697 **
2698 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2699 ** that is executed. The text of the SQL is appended to CALLBACK before
2700 ** it is executed.
2701 */
2702 case DB_TRACE: {
2703 if( objc>3 ){
2704 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002705 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002706 }else if( objc==2 ){
2707 if( pDb->zTrace ){
2708 Tcl_AppendResult(interp, pDb->zTrace, 0);
2709 }
2710 }else{
2711 char *zTrace;
2712 int len;
2713 if( pDb->zTrace ){
2714 Tcl_Free(pDb->zTrace);
2715 }
2716 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2717 if( zTrace && len>0 ){
2718 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002719 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002720 }else{
2721 pDb->zTrace = 0;
2722 }
shanehbb201342011-02-09 19:55:20 +00002723#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drhb5a20d32003-04-23 12:25:23 +00002724 if( pDb->zTrace ){
2725 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002726 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002727 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002728 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002729 }
drh19e2d372005-08-29 23:00:03 +00002730#endif
drhb5a20d32003-04-23 12:25:23 +00002731 }
2732 break;
2733 }
2734
drh3d214232005-08-02 12:21:08 +00002735 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2736 **
2737 ** Start a new transaction (if we are not already in the midst of a
2738 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2739 ** completes, either commit the transaction or roll it back if SCRIPT
2740 ** throws an exception. Or if no new transation was started, do nothing.
2741 ** pass the exception on up the stack.
2742 **
2743 ** This command was inspired by Dave Thomas's talk on Ruby at the
2744 ** 2005 O'Reilly Open Source Convention (OSCON).
2745 */
2746 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00002747 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00002748 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00002749 if( objc!=3 && objc!=4 ){
2750 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2751 return TCL_ERROR;
2752 }
danielk1977cd38d522009-01-02 17:33:46 +00002753
dan4a4c11a2009-10-06 14:59:02 +00002754 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00002755 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002756 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002757 };
2758 enum TTYPE_enum {
2759 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2760 };
2761 int ttype;
drhb5555e72005-08-02 17:15:14 +00002762 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002763 0, &ttype) ){
2764 return TCL_ERROR;
2765 }
2766 switch( (enum TTYPE_enum)ttype ){
2767 case TTYPE_DEFERRED: /* no-op */; break;
2768 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2769 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2770 }
drh3d214232005-08-02 12:21:08 +00002771 }
danielk1977cd38d522009-01-02 17:33:46 +00002772 pScript = objv[objc-1];
2773
dan4a4c11a2009-10-06 14:59:02 +00002774 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00002775 pDb->disableAuth++;
2776 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2777 pDb->disableAuth--;
2778 if( rc!=SQLITE_OK ){
2779 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2780 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00002781 }
danielk1977cd38d522009-01-02 17:33:46 +00002782 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00002783
dan4a4c11a2009-10-06 14:59:02 +00002784 /* If using NRE, schedule a callback to invoke the script pScript, then
2785 ** a second callback to commit (or rollback) the transaction or savepoint
2786 ** opened above. If not using NRE, evaluate the script directly, then
2787 ** call function DbTransPostCmd() to commit (or rollback) the transaction
2788 ** or savepoint. */
2789 if( DbUseNre() ){
2790 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
2791 Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00002792 }else{
dan4a4c11a2009-10-06 14:59:02 +00002793 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00002794 }
2795 break;
2796 }
2797
danielk197794eb6a12005-12-15 15:22:08 +00002798 /*
danielk1977404ca072009-03-16 13:19:36 +00002799 ** $db unlock_notify ?script?
2800 */
2801 case DB_UNLOCK_NOTIFY: {
2802#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2803 Tcl_AppendResult(interp, "unlock_notify not available in this build", 0);
2804 rc = TCL_ERROR;
2805#else
2806 if( objc!=2 && objc!=3 ){
2807 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2808 rc = TCL_ERROR;
2809 }else{
2810 void (*xNotify)(void **, int) = 0;
2811 void *pNotifyArg = 0;
2812
2813 if( pDb->pUnlockNotify ){
2814 Tcl_DecrRefCount(pDb->pUnlockNotify);
2815 pDb->pUnlockNotify = 0;
2816 }
2817
2818 if( objc==3 ){
2819 xNotify = DbUnlockNotify;
2820 pNotifyArg = (void *)pDb;
2821 pDb->pUnlockNotify = objv[2];
2822 Tcl_IncrRefCount(pDb->pUnlockNotify);
2823 }
2824
2825 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
2826 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2827 rc = TCL_ERROR;
2828 }
2829 }
2830#endif
2831 break;
2832 }
2833
2834 /*
drh833bf962010-04-28 14:42:19 +00002835 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002836 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002837 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002838 */
drh833bf962010-04-28 14:42:19 +00002839 case DB_WAL_HOOK:
danielk197771fd80b2005-12-16 06:54:01 +00002840 case DB_UPDATE_HOOK:
2841 case DB_ROLLBACK_HOOK: {
2842
2843 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2844 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2845 */
2846 Tcl_Obj **ppHook;
2847 if( choice==DB_UPDATE_HOOK ){
2848 ppHook = &pDb->pUpdateHook;
drh833bf962010-04-28 14:42:19 +00002849 }else if( choice==DB_WAL_HOOK ){
drh5def0842010-05-05 20:00:25 +00002850 ppHook = &pDb->pWalHook;
danielk197771fd80b2005-12-16 06:54:01 +00002851 }else{
2852 ppHook = &pDb->pRollbackHook;
2853 }
2854
danielk197794eb6a12005-12-15 15:22:08 +00002855 if( objc!=2 && objc!=3 ){
2856 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2857 return TCL_ERROR;
2858 }
danielk197771fd80b2005-12-16 06:54:01 +00002859 if( *ppHook ){
2860 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002861 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002862 Tcl_DecrRefCount(*ppHook);
2863 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00002864 }
2865 }
2866 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002867 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00002868 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00002869 *ppHook = objv[2];
2870 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002871 }
2872 }
danielk197771fd80b2005-12-16 06:54:01 +00002873
2874 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2875 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
drh5def0842010-05-05 20:00:25 +00002876 sqlite3_wal_hook(pDb->db,(pDb->pWalHook?DbWalHandler:0),pDb);
danielk197771fd80b2005-12-16 06:54:01 +00002877
danielk197794eb6a12005-12-15 15:22:08 +00002878 break;
2879 }
2880
danielk19774397de52005-01-12 12:44:03 +00002881 /* $db version
2882 **
2883 ** Return the version string for this database.
2884 */
2885 case DB_VERSION: {
2886 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2887 break;
2888 }
2889
tpoindex1067fe12004-12-17 15:41:11 +00002890
drh6d313162000-09-21 13:01:35 +00002891 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002892 return rc;
drh75897232000-05-29 14:26:00 +00002893}
2894
drha2c8a952009-10-13 18:38:34 +00002895#if SQLITE_TCL_NRE
2896/*
2897** Adaptor that provides an objCmd interface to the NRE-enabled
2898** interface implementation.
2899*/
2900static int DbObjCmdAdaptor(
2901 void *cd,
2902 Tcl_Interp *interp,
2903 int objc,
2904 Tcl_Obj *const*objv
2905){
2906 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
2907}
2908#endif /* SQLITE_TCL_NRE */
2909
drh75897232000-05-29 14:26:00 +00002910/*
drh3570ad92007-08-31 14:31:44 +00002911** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00002912** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00002913**
2914** This is the main Tcl command. When the "sqlite" Tcl command is
2915** invoked, this routine runs to process that command.
2916**
2917** The first argument, DBNAME, is an arbitrary name for a new
2918** database connection. This command creates a new command named
2919** DBNAME that is used to control that connection. The database
2920** connection is deleted when the DBNAME command is deleted.
2921**
drh3570ad92007-08-31 14:31:44 +00002922** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00002923**
drh75897232000-05-29 14:26:00 +00002924*/
drh22fbcb82004-02-01 01:22:50 +00002925static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002926 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002927 const char *zArg;
drh75897232000-05-29 14:26:00 +00002928 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00002929 int i;
drh22fbcb82004-02-01 01:22:50 +00002930 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00002931 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00002932 int flags;
drh882e8e42006-08-24 02:42:27 +00002933 Tcl_DString translatedFilename;
drhb07028f2011-10-14 21:49:18 +00002934#ifdef SQLITE_HAS_CODEC
2935 void *pKey = 0;
2936 int nKey = 0;
2937#endif
mistachkin540ebf82012-09-10 07:29:29 +00002938 int rc;
drhd9da78a2009-03-24 15:08:09 +00002939
2940 /* In normal use, each TCL interpreter runs in a single thread. So
2941 ** by default, we can turn of mutexing on SQLite database connections.
2942 ** However, for testing purposes it is useful to have mutexes turned
2943 ** on. So, by default, mutexes default off. But if compiled with
2944 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
2945 */
2946#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
2947 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
2948#else
2949 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
2950#endif
2951
drh22fbcb82004-02-01 01:22:50 +00002952 if( objc==2 ){
2953 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002954 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00002955 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00002956 return TCL_OK;
2957 }
drh9eb9e262004-02-11 02:18:05 +00002958 if( strcmp(zArg,"-has-codec")==0 ){
2959#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002960 Tcl_AppendResult(interp,"1",0);
2961#else
2962 Tcl_AppendResult(interp,"0",0);
2963#endif
2964 return TCL_OK;
2965 }
drhfbc3eab2001-04-06 16:13:42 +00002966 }
drh3570ad92007-08-31 14:31:44 +00002967 for(i=3; i+1<objc; i+=2){
2968 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00002969 if( strcmp(zArg,"-key")==0 ){
drhb07028f2011-10-14 21:49:18 +00002970#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00002971 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
drhb07028f2011-10-14 21:49:18 +00002972#endif
drh3570ad92007-08-31 14:31:44 +00002973 }else if( strcmp(zArg, "-vfs")==0 ){
dan3c3dd7b2010-06-22 11:10:40 +00002974 zVfs = Tcl_GetString(objv[i+1]);
drh3570ad92007-08-31 14:31:44 +00002975 }else if( strcmp(zArg, "-readonly")==0 ){
2976 int b;
2977 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2978 if( b ){
drh33f4e022007-09-03 15:19:34 +00002979 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00002980 flags |= SQLITE_OPEN_READONLY;
2981 }else{
2982 flags &= ~SQLITE_OPEN_READONLY;
2983 flags |= SQLITE_OPEN_READWRITE;
2984 }
2985 }else if( strcmp(zArg, "-create")==0 ){
2986 int b;
2987 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00002988 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00002989 flags |= SQLITE_OPEN_CREATE;
2990 }else{
2991 flags &= ~SQLITE_OPEN_CREATE;
2992 }
danielk19779a6284c2008-07-10 17:52:49 +00002993 }else if( strcmp(zArg, "-nomutex")==0 ){
2994 int b;
2995 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2996 if( b ){
2997 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00002998 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00002999 }else{
3000 flags &= ~SQLITE_OPEN_NOMUTEX;
3001 }
danc431fd52011-06-27 16:55:50 +00003002 }else if( strcmp(zArg, "-fullmutex")==0 ){
drh039963a2008-09-03 00:43:15 +00003003 int b;
3004 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3005 if( b ){
3006 flags |= SQLITE_OPEN_FULLMUTEX;
3007 flags &= ~SQLITE_OPEN_NOMUTEX;
3008 }else{
3009 flags &= ~SQLITE_OPEN_FULLMUTEX;
3010 }
drhf12b3f62011-12-21 14:42:29 +00003011 }else if( strcmp(zArg, "-uri")==0 ){
3012 int b;
3013 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3014 if( b ){
3015 flags |= SQLITE_OPEN_URI;
3016 }else{
3017 flags &= ~SQLITE_OPEN_URI;
3018 }
drh3570ad92007-08-31 14:31:44 +00003019 }else{
3020 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3021 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00003022 }
3023 }
drh3570ad92007-08-31 14:31:44 +00003024 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00003025 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00003026 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh68bd4aa2012-01-13 16:16:10 +00003027 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
drh9eb9e262004-02-11 02:18:05 +00003028#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00003029 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00003030#endif
3031 );
drh75897232000-05-29 14:26:00 +00003032 return TCL_ERROR;
3033 }
drh75897232000-05-29 14:26:00 +00003034 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003035 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00003036 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00003037 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
3038 return TCL_ERROR;
3039 }
3040 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00003041 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00003042 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003043 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00003044 Tcl_DStringFree(&translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003045 if( p->db ){
3046 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3047 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3048 sqlite3_close(p->db);
3049 p->db = 0;
3050 }
3051 }else{
3052 zErrMsg = sqlite3_mprintf("%s", sqlite3ErrStr(rc));
danielk197780290862004-05-22 09:21:21 +00003053 }
drh2011d5f2004-07-22 02:40:37 +00003054#ifdef SQLITE_HAS_CODEC
drhf3a65f72007-08-22 20:18:21 +00003055 if( p->db ){
3056 sqlite3_key(p->db, pKey, nKey);
3057 }
drheb8ed702004-02-11 10:37:23 +00003058#endif
drhbec3f402000-08-04 13:49:02 +00003059 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003060 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003061 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003062 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003063 return TCL_ERROR;
3064 }
drhfb7e7652005-01-24 00:28:42 +00003065 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00003066 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003067 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003068 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003069 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3070 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003071 }else{
3072 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3073 }
drh75897232000-05-29 14:26:00 +00003074 return TCL_OK;
3075}
3076
3077/*
drh90ca9752001-09-28 17:47:14 +00003078** Provide a dummy Tcl_InitStubs if we are using this as a static
3079** library.
3080*/
3081#ifndef USE_TCL_STUBS
3082# undef Tcl_InitStubs
3083# define Tcl_InitStubs(a,b,c)
3084#endif
3085
3086/*
drh29bc4612005-10-05 10:40:15 +00003087** Make sure we have a PACKAGE_VERSION macro defined. This will be
3088** defined automatically by the TEA makefile. But other makefiles
3089** do not define it.
3090*/
3091#ifndef PACKAGE_VERSION
3092# define PACKAGE_VERSION SQLITE_VERSION
3093#endif
3094
3095/*
drh75897232000-05-29 14:26:00 +00003096** Initialize this module.
3097**
3098** This Tcl module contains only a single new Tcl command named "sqlite".
3099** (Hence there is no namespace. There is no point in using a namespace
3100** if the extension only supplies one new name!) The "sqlite" command is
3101** used to open a new SQLite database. See the DbMain() routine above
3102** for additional information.
drhb652f432010-08-26 16:46:57 +00003103**
3104** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003105*/
drhb652f432010-08-26 16:46:57 +00003106EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00003107 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00003108 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00003109 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh1cca0d22010-08-25 20:35:51 +00003110
3111#ifndef SQLITE_3_SUFFIX_ONLY
3112 /* The "sqlite" alias is undocumented. It is here only to support
3113 ** legacy scripts. All new scripts should use only the "sqlite3"
3114 ** command.
3115 */
drh49766d62005-01-08 18:42:28 +00003116 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003117#endif
drh1cca0d22010-08-25 20:35:51 +00003118
drh90ca9752001-09-28 17:47:14 +00003119 return TCL_OK;
3120}
drhb652f432010-08-26 16:46:57 +00003121EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
drhb652f432010-08-26 16:46:57 +00003122EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3123EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00003124
drhd878cab2012-03-20 15:10:42 +00003125/* Because it accesses the file-system and uses persistent state, SQLite
3126** is not considered appropriate for safe interpreters. Hence, we deliberately
3127** omit the _SafeInit() interfaces.
3128*/
drh49766d62005-01-08 18:42:28 +00003129
3130#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003131int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3132int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
dana3e63c42010-08-20 12:33:59 +00003133int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3134int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00003135#endif
drh75897232000-05-29 14:26:00 +00003136
drh3e27c022004-07-23 00:01:38 +00003137#ifdef TCLSH
3138/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003139** All of the code that follows is used to build standalone TCL interpreters
3140** that are statically linked with SQLite. Enable these by compiling
3141** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3142** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3143** analysis program.
drh75897232000-05-29 14:26:00 +00003144*/
drh348784e2000-05-29 20:41:49 +00003145
drh57a02272009-10-22 20:52:05 +00003146#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3147/*
3148 * This code implements the MD5 message-digest algorithm.
3149 * The algorithm is due to Ron Rivest. This code was
3150 * written by Colin Plumb in 1993, no copyright is claimed.
3151 * This code is in the public domain; do with it what you wish.
3152 *
3153 * Equivalent code is available from RSA Data Security, Inc.
3154 * This code has been tested against that, and is equivalent,
3155 * except that you don't need to include two pages of legalese
3156 * with every copy.
3157 *
3158 * To compute the message digest of a chunk of bytes, declare an
3159 * MD5Context structure, pass it to MD5Init, call MD5Update as
3160 * needed on buffers full of bytes, and then call MD5Final, which
3161 * will fill a supplied 16-byte array with the digest.
3162 */
3163
3164/*
3165 * If compiled on a machine that doesn't have a 32-bit integer,
3166 * you just set "uint32" to the appropriate datatype for an
3167 * unsigned 32-bit integer. For example:
3168 *
3169 * cc -Duint32='unsigned long' md5.c
3170 *
3171 */
3172#ifndef uint32
3173# define uint32 unsigned int
3174#endif
3175
3176struct MD5Context {
3177 int isInit;
3178 uint32 buf[4];
3179 uint32 bits[2];
3180 unsigned char in[64];
3181};
3182typedef struct MD5Context MD5Context;
3183
3184/*
3185 * Note: this code is harmless on little-endian machines.
3186 */
3187static void byteReverse (unsigned char *buf, unsigned longs){
3188 uint32 t;
3189 do {
3190 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3191 ((unsigned)buf[1]<<8 | buf[0]);
3192 *(uint32 *)buf = t;
3193 buf += 4;
3194 } while (--longs);
3195}
3196/* The four core functions - F1 is optimized somewhat */
3197
3198/* #define F1(x, y, z) (x & y | ~x & z) */
3199#define F1(x, y, z) (z ^ (x & (y ^ z)))
3200#define F2(x, y, z) F1(z, x, y)
3201#define F3(x, y, z) (x ^ y ^ z)
3202#define F4(x, y, z) (y ^ (x | ~z))
3203
3204/* This is the central step in the MD5 algorithm. */
3205#define MD5STEP(f, w, x, y, z, data, s) \
3206 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3207
3208/*
3209 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3210 * reflect the addition of 16 longwords of new data. MD5Update blocks
3211 * the data and converts bytes into longwords for this routine.
3212 */
3213static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3214 register uint32 a, b, c, d;
3215
3216 a = buf[0];
3217 b = buf[1];
3218 c = buf[2];
3219 d = buf[3];
3220
3221 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3222 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3223 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3224 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3225 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3226 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3227 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3228 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3229 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3230 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3231 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3232 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3233 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3234 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3235 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3236 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3237
3238 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3239 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3240 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3241 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3242 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3243 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3244 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3245 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3246 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3247 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3248 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3249 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3250 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3251 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3252 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3253 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3254
3255 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3256 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3257 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3258 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3259 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3260 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3261 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3262 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3263 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3264 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3265 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3266 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3267 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3268 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3269 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3270 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3271
3272 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3273 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3274 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3275 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3276 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3277 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3278 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3279 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3280 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3281 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3282 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3283 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3284 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3285 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3286 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3287 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3288
3289 buf[0] += a;
3290 buf[1] += b;
3291 buf[2] += c;
3292 buf[3] += d;
3293}
3294
3295/*
3296 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3297 * initialization constants.
3298 */
3299static void MD5Init(MD5Context *ctx){
3300 ctx->isInit = 1;
3301 ctx->buf[0] = 0x67452301;
3302 ctx->buf[1] = 0xefcdab89;
3303 ctx->buf[2] = 0x98badcfe;
3304 ctx->buf[3] = 0x10325476;
3305 ctx->bits[0] = 0;
3306 ctx->bits[1] = 0;
3307}
3308
3309/*
3310 * Update context to reflect the concatenation of another buffer full
3311 * of bytes.
3312 */
3313static
3314void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3315 uint32 t;
3316
3317 /* Update bitcount */
3318
3319 t = ctx->bits[0];
3320 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3321 ctx->bits[1]++; /* Carry from low to high */
3322 ctx->bits[1] += len >> 29;
3323
3324 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3325
3326 /* Handle any leading odd-sized chunks */
3327
3328 if ( t ) {
3329 unsigned char *p = (unsigned char *)ctx->in + t;
3330
3331 t = 64-t;
3332 if (len < t) {
3333 memcpy(p, buf, len);
3334 return;
3335 }
3336 memcpy(p, buf, t);
3337 byteReverse(ctx->in, 16);
3338 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3339 buf += t;
3340 len -= t;
3341 }
3342
3343 /* Process data in 64-byte chunks */
3344
3345 while (len >= 64) {
3346 memcpy(ctx->in, buf, 64);
3347 byteReverse(ctx->in, 16);
3348 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3349 buf += 64;
3350 len -= 64;
3351 }
3352
3353 /* Handle any remaining bytes of data. */
3354
3355 memcpy(ctx->in, buf, len);
3356}
3357
3358/*
3359 * Final wrapup - pad to 64-byte boundary with the bit pattern
3360 * 1 0* (64-bit count of bits processed, MSB-first)
3361 */
3362static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3363 unsigned count;
3364 unsigned char *p;
3365
3366 /* Compute number of bytes mod 64 */
3367 count = (ctx->bits[0] >> 3) & 0x3F;
3368
3369 /* Set the first char of padding to 0x80. This is safe since there is
3370 always at least one byte free */
3371 p = ctx->in + count;
3372 *p++ = 0x80;
3373
3374 /* Bytes of padding needed to make 64 bytes */
3375 count = 64 - 1 - count;
3376
3377 /* Pad out to 56 mod 64 */
3378 if (count < 8) {
3379 /* Two lots of padding: Pad the first block to 64 bytes */
3380 memset(p, 0, count);
3381 byteReverse(ctx->in, 16);
3382 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3383
3384 /* Now fill the next block with 56 bytes */
3385 memset(ctx->in, 0, 56);
3386 } else {
3387 /* Pad block to 56 bytes */
3388 memset(p, 0, count-8);
3389 }
3390 byteReverse(ctx->in, 14);
3391
3392 /* Append length in bits and transform */
3393 ((uint32 *)ctx->in)[ 14 ] = ctx->bits[0];
3394 ((uint32 *)ctx->in)[ 15 ] = ctx->bits[1];
3395
3396 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3397 byteReverse((unsigned char *)ctx->buf, 4);
3398 memcpy(digest, ctx->buf, 16);
3399 memset(ctx, 0, sizeof(ctx)); /* In case it is sensitive */
3400}
3401
3402/*
3403** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3404*/
3405static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3406 static char const zEncode[] = "0123456789abcdef";
3407 int i, j;
3408
3409 for(j=i=0; i<16; i++){
3410 int a = digest[i];
3411 zBuf[j++] = zEncode[(a>>4)&0xf];
3412 zBuf[j++] = zEncode[a & 0xf];
3413 }
3414 zBuf[j] = 0;
3415}
3416
3417
3418/*
3419** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3420** each representing 16 bits of the digest and separated from each
3421** other by a "-" character.
3422*/
3423static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3424 int i, j;
3425 unsigned int x;
3426 for(i=j=0; i<16; i+=2){
3427 x = digest[i]*256 + digest[i+1];
3428 if( i>0 ) zDigest[j++] = '-';
3429 sprintf(&zDigest[j], "%05u", x);
3430 j += 5;
3431 }
3432 zDigest[j] = 0;
3433}
3434
3435/*
3436** A TCL command for md5. The argument is the text to be hashed. The
3437** Result is the hash in base64.
3438*/
3439static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3440 MD5Context ctx;
3441 unsigned char digest[16];
3442 char zBuf[50];
3443 void (*converter)(unsigned char*, char*);
3444
3445 if( argc!=2 ){
3446 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3447 " TEXT\"", 0);
3448 return TCL_ERROR;
3449 }
3450 MD5Init(&ctx);
3451 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3452 MD5Final(digest, &ctx);
3453 converter = (void(*)(unsigned char*,char*))cd;
3454 converter(digest, zBuf);
3455 Tcl_AppendResult(interp, zBuf, (char*)0);
3456 return TCL_OK;
3457}
3458
3459/*
3460** A TCL command to take the md5 hash of a file. The argument is the
3461** name of the file.
3462*/
3463static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3464 FILE *in;
3465 MD5Context ctx;
3466 void (*converter)(unsigned char*, char*);
3467 unsigned char digest[16];
3468 char zBuf[10240];
3469
3470 if( argc!=2 ){
3471 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3472 " FILENAME\"", 0);
3473 return TCL_ERROR;
3474 }
3475 in = fopen(argv[1],"rb");
3476 if( in==0 ){
3477 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
3478 "\" for reading", 0);
3479 return TCL_ERROR;
3480 }
3481 MD5Init(&ctx);
3482 for(;;){
3483 int n;
drh83cc1392012-04-19 18:04:28 +00003484 n = (int)fread(zBuf, 1, sizeof(zBuf), in);
drh57a02272009-10-22 20:52:05 +00003485 if( n<=0 ) break;
3486 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3487 }
3488 fclose(in);
3489 MD5Final(digest, &ctx);
3490 converter = (void(*)(unsigned char*,char*))cd;
3491 converter(digest, zBuf);
3492 Tcl_AppendResult(interp, zBuf, (char*)0);
3493 return TCL_OK;
3494}
3495
3496/*
3497** Register the four new TCL commands for generating MD5 checksums
3498** with the TCL interpreter.
3499*/
3500int Md5_Init(Tcl_Interp *interp){
3501 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3502 MD5DigestToBase16, 0);
3503 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3504 MD5DigestToBase10x8, 0);
3505 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3506 MD5DigestToBase16, 0);
3507 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3508 MD5DigestToBase10x8, 0);
3509 return TCL_OK;
3510}
3511#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3512
3513#if defined(SQLITE_TEST)
3514/*
3515** During testing, the special md5sum() aggregate function is available.
3516** inside SQLite. The following routines implement that function.
3517*/
3518static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3519 MD5Context *p;
3520 int i;
3521 if( argc<1 ) return;
3522 p = sqlite3_aggregate_context(context, sizeof(*p));
3523 if( p==0 ) return;
3524 if( !p->isInit ){
3525 MD5Init(p);
3526 }
3527 for(i=0; i<argc; i++){
3528 const char *zData = (char*)sqlite3_value_text(argv[i]);
3529 if( zData ){
drh83cc1392012-04-19 18:04:28 +00003530 MD5Update(p, (unsigned char*)zData, (int)strlen(zData));
drh57a02272009-10-22 20:52:05 +00003531 }
3532 }
3533}
3534static void md5finalize(sqlite3_context *context){
3535 MD5Context *p;
3536 unsigned char digest[16];
3537 char zBuf[33];
3538 p = sqlite3_aggregate_context(context, sizeof(*p));
3539 MD5Final(digest,p);
3540 MD5DigestToBase16(digest, zBuf);
3541 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3542}
3543int Md5_Register(sqlite3 *db){
3544 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
3545 md5step, md5finalize);
3546 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3547 return rc;
3548}
3549#endif /* defined(SQLITE_TEST) */
3550
3551
drh348784e2000-05-29 20:41:49 +00003552/*
drh3e27c022004-07-23 00:01:38 +00003553** If the macro TCLSH is one, then put in code this for the
3554** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003555** standard input, or if a file is named on the command line
3556** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003557*/
drh3e27c022004-07-23 00:01:38 +00003558#if TCLSH==1
dan0ae479d2011-09-21 16:43:07 +00003559static const char *tclsh_main_loop(void){
3560 static const char zMainloop[] =
3561 "set line {}\n"
3562 "while {![eof stdin]} {\n"
3563 "if {$line!=\"\"} {\n"
3564 "puts -nonewline \"> \"\n"
3565 "} else {\n"
3566 "puts -nonewline \"% \"\n"
drh348784e2000-05-29 20:41:49 +00003567 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003568 "flush stdout\n"
3569 "append line [gets stdin]\n"
3570 "if {[info complete $line]} {\n"
3571 "if {[catch {uplevel #0 $line} result]} {\n"
3572 "puts stderr \"Error: $result\"\n"
3573 "} elseif {$result!=\"\"} {\n"
3574 "puts $result\n"
3575 "}\n"
3576 "set line {}\n"
3577 "} else {\n"
3578 "append line \\n\n"
3579 "}\n"
drh348784e2000-05-29 20:41:49 +00003580 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003581 ;
3582 return zMainloop;
3583}
drh3e27c022004-07-23 00:01:38 +00003584#endif
drh3a0f13f2010-07-12 16:47:48 +00003585#if TCLSH==2
dan0ae479d2011-09-21 16:43:07 +00003586static const char *tclsh_main_loop(void);
drh3a0f13f2010-07-12 16:47:48 +00003587#endif
drh3e27c022004-07-23 00:01:38 +00003588
danc1a60c52010-06-07 14:28:16 +00003589#ifdef SQLITE_TEST
3590static void init_all(Tcl_Interp *);
3591static int init_all_cmd(
3592 ClientData cd,
3593 Tcl_Interp *interp,
3594 int objc,
3595 Tcl_Obj *CONST objv[]
3596){
danielk19770a549072009-02-17 16:29:10 +00003597
danc1a60c52010-06-07 14:28:16 +00003598 Tcl_Interp *slave;
3599 if( objc!=2 ){
3600 Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3601 return TCL_ERROR;
3602 }
3603
3604 slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3605 if( !slave ){
3606 return TCL_ERROR;
3607 }
3608
3609 init_all(slave);
3610 return TCL_OK;
3611}
danc431fd52011-06-27 16:55:50 +00003612
3613/*
3614** Tclcmd: db_use_legacy_prepare DB BOOLEAN
3615**
3616** The first argument to this command must be a database command created by
3617** [sqlite3]. If the second argument is true, then the handle is configured
3618** to use the sqlite3_prepare_v2() function to prepare statements. If it
3619** is false, sqlite3_prepare().
3620*/
3621static int db_use_legacy_prepare_cmd(
3622 ClientData cd,
3623 Tcl_Interp *interp,
3624 int objc,
3625 Tcl_Obj *CONST objv[]
3626){
3627 Tcl_CmdInfo cmdInfo;
3628 SqliteDb *pDb;
3629 int bPrepare;
3630
3631 if( objc!=3 ){
3632 Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
3633 return TCL_ERROR;
3634 }
3635
3636 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3637 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3638 return TCL_ERROR;
3639 }
3640 pDb = (SqliteDb*)cmdInfo.objClientData;
3641 if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
3642 return TCL_ERROR;
3643 }
3644
3645 pDb->bLegacyPrepare = bPrepare;
3646
3647 Tcl_ResetResult(interp);
3648 return TCL_OK;
3649}
danc1a60c52010-06-07 14:28:16 +00003650#endif
3651
3652/*
3653** Configure the interpreter passed as the first argument to have access
3654** to the commands and linked variables that make up:
3655**
3656** * the [sqlite3] extension itself,
3657**
3658** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
3659**
3660** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
3661** test suite.
3662*/
3663static void init_all(Tcl_Interp *interp){
drh38f82712004-06-18 17:10:16 +00003664 Sqlite3_Init(interp);
danc1a60c52010-06-07 14:28:16 +00003665
drh57a02272009-10-22 20:52:05 +00003666#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3667 Md5_Init(interp);
3668#endif
danc1a60c52010-06-07 14:28:16 +00003669
dan0ae479d2011-09-21 16:43:07 +00003670 /* Install the [register_dbstat_vtab] command to access the implementation
3671 ** of virtual table dbstat (source file test_stat.c). This command is
3672 ** required for testfixture and sqlite3_analyzer, but not by the production
3673 ** Tcl extension. */
3674#if defined(SQLITE_TEST) || TCLSH==2
3675 {
3676 extern int SqlitetestStat_Init(Tcl_Interp*);
3677 SqlitetestStat_Init(interp);
3678 }
3679#endif
3680
drhd9b02572001-04-15 00:37:09 +00003681#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00003682 {
drh2f999a62007-08-15 19:16:43 +00003683 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00003684 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00003685 extern int Sqlitetest2_Init(Tcl_Interp*);
3686 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00003687 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00003688 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00003689 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00003690 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00003691 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00003692 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00003693 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00003694 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
dan0a7a9152010-04-07 07:57:38 +00003695 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
drh984bfaa2008-03-19 16:08:53 +00003696 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00003697 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00003698 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003699 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00003700 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003701 extern int Sqlitetestschema_Init(Tcl_Interp*);
3702 extern int Sqlitetestsse_Init(Tcl_Interp*);
3703 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00003704 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00003705 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00003706 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00003707 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh522efc62009-11-10 17:24:37 +00003708 extern int Sqlitetestintarray_Init(Tcl_Interp*);
danc7991bd2010-05-05 19:04:59 +00003709 extern int Sqlitetestvfs_Init(Tcl_Interp *);
dan9508daa2010-08-28 18:58:00 +00003710 extern int Sqlitetestrtree_Init(Tcl_Interp*);
dan8cf35eb2010-09-01 11:40:05 +00003711 extern int Sqlitequota_Init(Tcl_Interp*);
shaneh8a922f72010-11-04 20:50:27 +00003712 extern int Sqlitemultiplex_Init(Tcl_Interp*);
dane336b002010-11-19 18:20:09 +00003713 extern int SqliteSuperlock_Init(Tcl_Interp*);
dan213ca0a2011-03-28 19:10:06 +00003714 extern int SqlitetestSyscall_Init(Tcl_Interp*);
drh326a67d2011-03-26 15:05:27 +00003715 extern int Sqlitetestfuzzer_Init(Tcl_Interp*);
drh70586be2011-04-01 23:49:44 +00003716 extern int Sqlitetestwholenumber_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00003717
dan6764a702011-06-20 11:15:06 +00003718#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00003719 extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
3720#endif
3721
danb29010c2010-12-29 18:24:38 +00003722#ifdef SQLITE_ENABLE_ZIPVFS
3723 extern int Zipvfs_Init(Tcl_Interp*);
3724 Zipvfs_Init(interp);
3725#endif
3726
drh2f999a62007-08-15 19:16:43 +00003727 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00003728 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00003729 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00003730 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00003731 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00003732 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00003733 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00003734 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00003735 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00003736 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00003737 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00003738 Sqlitetest_autoext_Init(interp);
dan0a7a9152010-04-07 07:57:38 +00003739 Sqlitetest_demovfs_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00003740 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00003741 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00003742 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003743 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00003744 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003745 Sqlitetestschema_Init(interp);
3746 Sqlitetesttclvar_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00003747 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003748 SqlitetestOnefile_Init(interp);
danielk19775d1f5aa2008-04-10 14:51:00 +00003749 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00003750 Sqlitetestbackup_Init(interp);
drh522efc62009-11-10 17:24:37 +00003751 Sqlitetestintarray_Init(interp);
danc7991bd2010-05-05 19:04:59 +00003752 Sqlitetestvfs_Init(interp);
dan9508daa2010-08-28 18:58:00 +00003753 Sqlitetestrtree_Init(interp);
dan8cf35eb2010-09-01 11:40:05 +00003754 Sqlitequota_Init(interp);
shaneh8a922f72010-11-04 20:50:27 +00003755 Sqlitemultiplex_Init(interp);
dane336b002010-11-19 18:20:09 +00003756 SqliteSuperlock_Init(interp);
dan213ca0a2011-03-28 19:10:06 +00003757 SqlitetestSyscall_Init(interp);
drh326a67d2011-03-26 15:05:27 +00003758 Sqlitetestfuzzer_Init(interp);
drh70586be2011-04-01 23:49:44 +00003759 Sqlitetestwholenumber_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003760
dan6764a702011-06-20 11:15:06 +00003761#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00003762 Sqlitetestfts3_Init(interp);
3763#endif
3764
danc431fd52011-06-27 16:55:50 +00003765 Tcl_CreateObjCommand(
3766 interp, "load_testfixture_extensions", init_all_cmd, 0, 0
3767 );
3768 Tcl_CreateObjCommand(
3769 interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
3770 );
danc1a60c52010-06-07 14:28:16 +00003771
drh89dec812005-04-28 19:03:37 +00003772#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00003773 Sqlitetestsse_Init(interp);
3774#endif
drhd1bf3512001-04-07 15:24:33 +00003775 }
3776#endif
danc1a60c52010-06-07 14:28:16 +00003777}
3778
3779#define TCLSH_MAIN main /* Needed to fake out mktclapp */
3780int TCLSH_MAIN(int argc, char **argv){
3781 Tcl_Interp *interp;
3782
3783 /* Call sqlite3_shutdown() once before doing anything else. This is to
3784 ** test that sqlite3_shutdown() can be safely called by a process before
3785 ** sqlite3_initialize() is. */
3786 sqlite3_shutdown();
3787
dan0ae479d2011-09-21 16:43:07 +00003788 Tcl_FindExecutable(argv[0]);
3789 interp = Tcl_CreateInterp();
3790
drh3a0f13f2010-07-12 16:47:48 +00003791#if TCLSH==2
3792 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
3793#endif
danc1a60c52010-06-07 14:28:16 +00003794
danc1a60c52010-06-07 14:28:16 +00003795 init_all(interp);
drhc7285972009-11-10 01:13:25 +00003796 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00003797 int i;
shessad42c3a2006-08-22 23:53:46 +00003798 char zArgc[32];
3799 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
3800 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00003801 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
3802 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00003803 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00003804 Tcl_SetVar(interp, "argv", argv[i],
3805 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3806 }
drh3a0f13f2010-07-12 16:47:48 +00003807 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00003808 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00003809 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00003810 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00003811 return 1;
3812 }
drh3e27c022004-07-23 00:01:38 +00003813 }
drh3a0f13f2010-07-12 16:47:48 +00003814 if( TCLSH==2 || argc<=1 ){
dan0ae479d2011-09-21 16:43:07 +00003815 Tcl_GlobalEval(interp, tclsh_main_loop());
drh348784e2000-05-29 20:41:49 +00003816 }
3817 return 0;
3818}
3819#endif /* TCLSH */