blob: 2777d2f9f8b52644c7059fcb167a4de51f569fa8 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
drhbd08af42007-04-05 21:58:33 +000012** A TCL Interface to SQLite. Append this file to sqlite3.c and
13** compile the whole thing to build a TCL-enabled version of SQLite.
drh57a02272009-10-22 20:52:05 +000014**
15** Compile-time options:
16**
17** -DTCLSH=1 Add a "main()" routine that works as a tclsh.
18**
19** -DSQLITE_TCLMD5 When used in conjuction with -DTCLSH=1, add
20** four new commands to the TCL interpreter for
21** generating MD5 checksums: md5, md5file,
22** md5-10x8, and md5file-10x8.
23**
24** -DSQLITE_TEST When used in conjuction with -DTCLSH=1, add
25** hundreds of new commands used for testing
26** SQLite. This option implies -DSQLITE_TCLMD5.
drh75897232000-05-29 14:26:00 +000027*/
drh17a68932001-01-31 13:28:08 +000028#include "tcl.h"
danielk1977b4e9af92007-05-01 17:49:49 +000029#include <errno.h>
drhbd08af42007-04-05 21:58:33 +000030
31/*
32** Some additional include files are needed if this file is not
33** appended to the amalgamation.
34*/
35#ifndef SQLITE_AMALGAMATION
drh65e8c822009-12-01 13:57:48 +000036# include "sqlite3.h"
drhbd08af42007-04-05 21:58:33 +000037# include <stdlib.h>
38# include <string.h>
39# include <assert.h>
drh65e8c822009-12-01 13:57:48 +000040 typedef unsigned char u8;
drhbd08af42007-04-05 21:58:33 +000041#endif
drheb206382009-10-24 15:51:33 +000042#include <ctype.h>
drh75897232000-05-29 14:26:00 +000043
drhad6e1372006-07-10 21:15:51 +000044/*
45 * Windows needs to know which symbols to export. Unix does not.
46 * BUILD_sqlite should be undefined for Unix.
47 */
48#ifdef BUILD_sqlite
49#undef TCL_STORAGE_CLASS
50#define TCL_STORAGE_CLASS DLLEXPORT
51#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000052
danielk1977a21c6b62005-01-24 10:25:59 +000053#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000054#define MAX_PREPARED_STMTS 100
55
drhc45e6712012-10-03 11:02:33 +000056/* Forward declaration */
57typedef struct SqliteDb SqliteDb;
drh98808ba2001-10-18 12:34:46 +000058
59/*
drhcabb0812002-09-14 13:47:32 +000060** New SQL functions can be created as TCL scripts. Each such function
61** is described by an instance of the following structure.
62*/
63typedef struct SqlFunc SqlFunc;
64struct SqlFunc {
65 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000066 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
drhc45e6712012-10-03 11:02:33 +000067 SqliteDb *pDb; /* Database connection that owns this function */
drhd1e47332005-06-26 17:55:33 +000068 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
69 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000070 SqlFunc *pNext; /* Next function on the list of them all */
71};
72
73/*
danielk19770202b292004-06-09 09:55:16 +000074** New collation sequences function can be created as TCL scripts. Each such
75** function is described by an instance of the following structure.
76*/
77typedef struct SqlCollate SqlCollate;
78struct SqlCollate {
79 Tcl_Interp *interp; /* The TCL interpret to execute the function */
80 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000081 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000082};
83
84/*
drhfb7e7652005-01-24 00:28:42 +000085** Prepared statements are cached for faster execution. Each prepared
86** statement is described by an instance of the following structure.
87*/
88typedef struct SqlPreparedStmt SqlPreparedStmt;
89struct SqlPreparedStmt {
90 SqlPreparedStmt *pNext; /* Next in linked list */
91 SqlPreparedStmt *pPrev; /* Previous on the list */
92 sqlite3_stmt *pStmt; /* The prepared statement */
93 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +000094 const char *zSql; /* Text of the SQL statement */
dan4a4c11a2009-10-06 14:59:02 +000095 int nParm; /* Size of apParm array */
96 Tcl_Obj **apParm; /* Array of referenced object pointers */
drhfb7e7652005-01-24 00:28:42 +000097};
98
danielk1977d04417962007-05-02 13:16:30 +000099typedef struct IncrblobChannel IncrblobChannel;
100
drhfb7e7652005-01-24 00:28:42 +0000101/*
drhbec3f402000-08-04 13:49:02 +0000102** There is one instance of this structure for each SQLite database
103** that has been opened by the SQLite TCL interface.
danc431fd52011-06-27 16:55:50 +0000104**
105** If this module is built with SQLITE_TEST defined (to create the SQLite
106** testfixture executable), then it may be configured to use either
107** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
108** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
drhbec3f402000-08-04 13:49:02 +0000109*/
drhbec3f402000-08-04 13:49:02 +0000110struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000111 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000112 Tcl_Interp *interp; /* The interpreter used for this database */
113 char *zBusy; /* The busy callback routine */
114 char *zCommit; /* The commit hook callback routine */
115 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +0000116 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000117 char *zProgress; /* The progress callback routine */
118 char *zAuth; /* The authorization callback routine */
drh1f1549f2008-08-26 21:33:34 +0000119 int disableAuth; /* Disable the authorizer if it exists */
drhd1e47332005-06-26 17:55:33 +0000120 char *zNull; /* Text to substitute for an SQL NULL value */
121 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000122 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000123 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drh5def0842010-05-05 20:00:25 +0000124 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000125 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000126 SqlCollate *pCollate; /* List of SQL collation functions */
127 int rc; /* Return code of most recent sqlite3_exec() */
128 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000129 SqlPreparedStmt *stmtList; /* List of prepared statements*/
130 SqlPreparedStmt *stmtLast; /* Last statement in the list */
131 int maxStmt; /* The next maximum number of stmtList */
132 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000133 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh3c379b02010-04-07 19:31:59 +0000134 int nStep, nSort, nIndex; /* Statistics for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000135 int nTransaction; /* Number of nested [transaction] methods */
danc431fd52011-06-27 16:55:50 +0000136#ifdef SQLITE_TEST
137 int bLegacyPrepare; /* True to use sqlite3_prepare() */
138#endif
drh98808ba2001-10-18 12:34:46 +0000139};
drh297ecf12001-04-05 15:57:13 +0000140
danielk1977b4e9af92007-05-01 17:49:49 +0000141struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000142 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000143 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000144 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000145 Tcl_Channel channel; /* Channel identifier */
146 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
147 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000148};
149
drhea678832008-12-10 19:26:22 +0000150/*
151** Compute a string length that is limited to what can be stored in
152** lower 30 bits of a 32-bit signed integer.
153*/
drh4f21c4a2008-12-10 22:15:00 +0000154static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000155 const char *z2 = z;
156 while( *z2 ){ z2++; }
157 return 0x3fffffff & (int)(z2 - z);
158}
drhea678832008-12-10 19:26:22 +0000159
160
danielk197732a0d8b2007-05-04 19:03:02 +0000161#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000162/*
danielk1977d04417962007-05-02 13:16:30 +0000163** Close all incrblob channels opened using database connection pDb.
164** This is called when shutting down the database connection.
165*/
166static void closeIncrblobChannels(SqliteDb *pDb){
167 IncrblobChannel *p;
168 IncrblobChannel *pNext;
169
170 for(p=pDb->pIncrblob; p; p=pNext){
171 pNext = p->pNext;
172
173 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
174 ** which deletes the IncrblobChannel structure at *p. So do not
175 ** call Tcl_Free() here.
176 */
177 Tcl_UnregisterChannel(pDb->interp, p->channel);
178 }
179}
180
181/*
danielk1977b4e9af92007-05-01 17:49:49 +0000182** Close an incremental blob channel.
183*/
184static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
185 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000186 int rc = sqlite3_blob_close(p->pBlob);
187 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000188
189 /* Remove the channel from the SqliteDb.pIncrblob list. */
190 if( p->pNext ){
191 p->pNext->pPrev = p->pPrev;
192 }
193 if( p->pPrev ){
194 p->pPrev->pNext = p->pNext;
195 }
196 if( p->pDb->pIncrblob==p ){
197 p->pDb->pIncrblob = p->pNext;
198 }
199
danielk197792d4d7a2007-05-04 12:05:56 +0000200 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000201 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000202
203 if( rc!=SQLITE_OK ){
204 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
205 return TCL_ERROR;
206 }
danielk1977b4e9af92007-05-01 17:49:49 +0000207 return TCL_OK;
208}
209
210/*
211** Read data from an incremental blob channel.
212*/
213static int incrblobInput(
214 ClientData instanceData,
215 char *buf,
216 int bufSize,
217 int *errorCodePtr
218){
219 IncrblobChannel *p = (IncrblobChannel *)instanceData;
220 int nRead = bufSize; /* Number of bytes to read */
221 int nBlob; /* Total size of the blob */
222 int rc; /* sqlite error code */
223
224 nBlob = sqlite3_blob_bytes(p->pBlob);
225 if( (p->iSeek+nRead)>nBlob ){
226 nRead = nBlob-p->iSeek;
227 }
228 if( nRead<=0 ){
229 return 0;
230 }
231
232 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
233 if( rc!=SQLITE_OK ){
234 *errorCodePtr = rc;
235 return -1;
236 }
237
238 p->iSeek += nRead;
239 return nRead;
240}
241
danielk1977d04417962007-05-02 13:16:30 +0000242/*
243** Write data to an incremental blob channel.
244*/
danielk1977b4e9af92007-05-01 17:49:49 +0000245static int incrblobOutput(
246 ClientData instanceData,
247 CONST char *buf,
248 int toWrite,
249 int *errorCodePtr
250){
251 IncrblobChannel *p = (IncrblobChannel *)instanceData;
252 int nWrite = toWrite; /* Number of bytes to write */
253 int nBlob; /* Total size of the blob */
254 int rc; /* sqlite error code */
255
256 nBlob = sqlite3_blob_bytes(p->pBlob);
257 if( (p->iSeek+nWrite)>nBlob ){
258 *errorCodePtr = EINVAL;
259 return -1;
260 }
261 if( nWrite<=0 ){
262 return 0;
263 }
264
265 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
266 if( rc!=SQLITE_OK ){
267 *errorCodePtr = EIO;
268 return -1;
269 }
270
271 p->iSeek += nWrite;
272 return nWrite;
273}
274
275/*
276** Seek an incremental blob channel.
277*/
278static int incrblobSeek(
279 ClientData instanceData,
280 long offset,
281 int seekMode,
282 int *errorCodePtr
283){
284 IncrblobChannel *p = (IncrblobChannel *)instanceData;
285
286 switch( seekMode ){
287 case SEEK_SET:
288 p->iSeek = offset;
289 break;
290 case SEEK_CUR:
291 p->iSeek += offset;
292 break;
293 case SEEK_END:
294 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
295 break;
296
297 default: assert(!"Bad seekMode");
298 }
299
300 return p->iSeek;
301}
302
303
304static void incrblobWatch(ClientData instanceData, int mode){
305 /* NO-OP */
306}
307static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
308 return TCL_ERROR;
309}
310
311static Tcl_ChannelType IncrblobChannelType = {
312 "incrblob", /* typeName */
313 TCL_CHANNEL_VERSION_2, /* version */
314 incrblobClose, /* closeProc */
315 incrblobInput, /* inputProc */
316 incrblobOutput, /* outputProc */
317 incrblobSeek, /* seekProc */
318 0, /* setOptionProc */
319 0, /* getOptionProc */
320 incrblobWatch, /* watchProc (this is a no-op) */
321 incrblobHandle, /* getHandleProc (always returns error) */
322 0, /* close2Proc */
323 0, /* blockModeProc */
324 0, /* flushProc */
325 0, /* handlerProc */
326 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000327};
328
329/*
330** Create a new incrblob channel.
331*/
332static int createIncrblobChannel(
333 Tcl_Interp *interp,
334 SqliteDb *pDb,
335 const char *zDb,
336 const char *zTable,
337 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000338 sqlite_int64 iRow,
339 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000340){
341 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000342 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000343 sqlite3_blob *pBlob;
344 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000345 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000346
347 /* This variable is used to name the channels: "incrblob_[incr count]" */
348 static int count = 0;
349 char zChannel[64];
350
danielk19778cbadb02007-05-03 16:31:26 +0000351 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000352 if( rc!=SQLITE_OK ){
353 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
354 return TCL_ERROR;
355 }
356
357 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
358 p->iSeek = 0;
359 p->pBlob = pBlob;
360
drh5bb3eb92007-05-04 13:15:55 +0000361 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000362 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
363 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000364
danielk1977d04417962007-05-02 13:16:30 +0000365 /* Link the new channel into the SqliteDb.pIncrblob list. */
366 p->pNext = pDb->pIncrblob;
367 p->pPrev = 0;
368 if( p->pNext ){
369 p->pNext->pPrev = p;
370 }
371 pDb->pIncrblob = p;
372 p->pDb = pDb;
373
374 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000375 return TCL_OK;
376}
danielk197732a0d8b2007-05-04 19:03:02 +0000377#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
378 #define closeIncrblobChannels(pDb)
379#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000380
drh6d313162000-09-21 13:01:35 +0000381/*
drhd1e47332005-06-26 17:55:33 +0000382** Look at the script prefix in pCmd. We will be executing this script
383** after first appending one or more arguments. This routine analyzes
384** the script to see if it is safe to use Tcl_EvalObjv() on the script
385** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
386** faster.
387**
388** Scripts that are safe to use with Tcl_EvalObjv() consists of a
389** command name followed by zero or more arguments with no [...] or $
390** or {...} or ; to be seen anywhere. Most callback scripts consist
391** of just a single procedure name and they meet this requirement.
392*/
393static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
394 /* We could try to do something with Tcl_Parse(). But we will instead
395 ** just do a search for forbidden characters. If any of the forbidden
396 ** characters appear in pCmd, we will report the string as unsafe.
397 */
398 const char *z;
399 int n;
400 z = Tcl_GetStringFromObj(pCmd, &n);
401 while( n-- > 0 ){
402 int c = *(z++);
403 if( c=='$' || c=='[' || c==';' ) return 0;
404 }
405 return 1;
406}
407
408/*
409** Find an SqlFunc structure with the given name. Or create a new
410** one if an existing one cannot be found. Return a pointer to the
411** structure.
412*/
413static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
414 SqlFunc *p, *pNew;
415 int i;
drh4f21c4a2008-12-10 22:15:00 +0000416 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen30(zName) + 1 );
drhd1e47332005-06-26 17:55:33 +0000417 pNew->zName = (char*)&pNew[1];
418 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
419 pNew->zName[i] = 0;
420 for(p=pDb->pFunc; p; p=p->pNext){
421 if( strcmp(p->zName, pNew->zName)==0 ){
422 Tcl_Free((char*)pNew);
423 return p;
424 }
425 }
426 pNew->interp = pDb->interp;
drhc45e6712012-10-03 11:02:33 +0000427 pNew->pDb = pDb;
drhd1e47332005-06-26 17:55:33 +0000428 pNew->pScript = 0;
429 pNew->pNext = pDb->pFunc;
430 pDb->pFunc = pNew;
431 return pNew;
432}
433
434/*
danc431fd52011-06-27 16:55:50 +0000435** Free a single SqlPreparedStmt object.
436*/
437static void dbFreeStmt(SqlPreparedStmt *pStmt){
438#ifdef SQLITE_TEST
439 if( sqlite3_sql(pStmt->pStmt)==0 ){
440 Tcl_Free((char *)pStmt->zSql);
441 }
442#endif
443 sqlite3_finalize(pStmt->pStmt);
444 Tcl_Free((char *)pStmt);
445}
446
447/*
drhfb7e7652005-01-24 00:28:42 +0000448** Finalize and free a list of prepared statements
449*/
danc431fd52011-06-27 16:55:50 +0000450static void flushStmtCache(SqliteDb *pDb){
drhfb7e7652005-01-24 00:28:42 +0000451 SqlPreparedStmt *pPreStmt;
danc431fd52011-06-27 16:55:50 +0000452 SqlPreparedStmt *pNext;
drhfb7e7652005-01-24 00:28:42 +0000453
danc431fd52011-06-27 16:55:50 +0000454 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
455 pNext = pPreStmt->pNext;
456 dbFreeStmt(pPreStmt);
drhfb7e7652005-01-24 00:28:42 +0000457 }
458 pDb->nStmt = 0;
459 pDb->stmtLast = 0;
danc431fd52011-06-27 16:55:50 +0000460 pDb->stmtList = 0;
drhfb7e7652005-01-24 00:28:42 +0000461}
462
463/*
drh895d7472004-08-20 16:02:39 +0000464** TCL calls this procedure when an sqlite3 database command is
465** deleted.
drh75897232000-05-29 14:26:00 +0000466*/
467static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000468 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000469 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000470 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000471 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000472 while( pDb->pFunc ){
473 SqlFunc *pFunc = pDb->pFunc;
474 pDb->pFunc = pFunc->pNext;
drhc45e6712012-10-03 11:02:33 +0000475 assert( pFunc->pDb==pDb );
drhd1e47332005-06-26 17:55:33 +0000476 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000477 Tcl_Free((char*)pFunc);
478 }
danielk19770202b292004-06-09 09:55:16 +0000479 while( pDb->pCollate ){
480 SqlCollate *pCollate = pDb->pCollate;
481 pDb->pCollate = pCollate->pNext;
482 Tcl_Free((char*)pCollate);
483 }
drhbec3f402000-08-04 13:49:02 +0000484 if( pDb->zBusy ){
485 Tcl_Free(pDb->zBusy);
486 }
drhb5a20d32003-04-23 12:25:23 +0000487 if( pDb->zTrace ){
488 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000489 }
drh19e2d372005-08-29 23:00:03 +0000490 if( pDb->zProfile ){
491 Tcl_Free(pDb->zProfile);
492 }
drhe22a3342003-04-22 20:30:37 +0000493 if( pDb->zAuth ){
494 Tcl_Free(pDb->zAuth);
495 }
danielk197755c45f22005-04-03 23:54:43 +0000496 if( pDb->zNull ){
497 Tcl_Free(pDb->zNull);
498 }
danielk197794eb6a12005-12-15 15:22:08 +0000499 if( pDb->pUpdateHook ){
500 Tcl_DecrRefCount(pDb->pUpdateHook);
501 }
danielk197771fd80b2005-12-16 06:54:01 +0000502 if( pDb->pRollbackHook ){
503 Tcl_DecrRefCount(pDb->pRollbackHook);
504 }
drh5def0842010-05-05 20:00:25 +0000505 if( pDb->pWalHook ){
506 Tcl_DecrRefCount(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000507 }
danielk197794eb6a12005-12-15 15:22:08 +0000508 if( pDb->pCollateNeeded ){
509 Tcl_DecrRefCount(pDb->pCollateNeeded);
510 }
drhbec3f402000-08-04 13:49:02 +0000511 Tcl_Free((char*)pDb);
512}
513
514/*
515** This routine is called when a database file is locked while trying
516** to execute SQL.
517*/
danielk19772a764eb2004-06-12 01:43:26 +0000518static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000519 SqliteDb *pDb = (SqliteDb*)cd;
520 int rc;
521 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000522
drh5bb3eb92007-05-04 13:15:55 +0000523 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000524 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000525 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
526 return 0;
527 }
528 return 1;
drh75897232000-05-29 14:26:00 +0000529}
530
drh26e4a8b2008-05-01 17:16:52 +0000531#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000532/*
danielk1977348bb5d2003-10-18 09:37:26 +0000533** This routine is invoked as the 'progress callback' for the database.
534*/
535static int DbProgressHandler(void *cd){
536 SqliteDb *pDb = (SqliteDb*)cd;
537 int rc;
538
539 assert( pDb->zProgress );
540 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
541 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
542 return 1;
543 }
544 return 0;
545}
drh26e4a8b2008-05-01 17:16:52 +0000546#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000547
drhd1167392006-01-23 13:00:35 +0000548#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000549/*
drhb5a20d32003-04-23 12:25:23 +0000550** This routine is called by the SQLite trace handler whenever a new
551** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000552*/
drhb5a20d32003-04-23 12:25:23 +0000553static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000554 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000555 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000556
drhb5a20d32003-04-23 12:25:23 +0000557 Tcl_DStringInit(&str);
558 Tcl_DStringAppend(&str, pDb->zTrace, -1);
559 Tcl_DStringAppendElement(&str, zSql);
560 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
561 Tcl_DStringFree(&str);
562 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000563}
drhd1167392006-01-23 13:00:35 +0000564#endif
drh0d1a6432003-04-03 15:46:04 +0000565
drhd1167392006-01-23 13:00:35 +0000566#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000567/*
drh19e2d372005-08-29 23:00:03 +0000568** This routine is called by the SQLite profile handler after a statement
569** SQL has executed. The TCL script in pDb->zProfile is evaluated.
570*/
571static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
572 SqliteDb *pDb = (SqliteDb*)cd;
573 Tcl_DString str;
574 char zTm[100];
575
576 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
577 Tcl_DStringInit(&str);
578 Tcl_DStringAppend(&str, pDb->zProfile, -1);
579 Tcl_DStringAppendElement(&str, zSql);
580 Tcl_DStringAppendElement(&str, zTm);
581 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
582 Tcl_DStringFree(&str);
583 Tcl_ResetResult(pDb->interp);
584}
drhd1167392006-01-23 13:00:35 +0000585#endif
drh19e2d372005-08-29 23:00:03 +0000586
587/*
drhaa940ea2004-01-15 02:44:03 +0000588** This routine is called when a transaction is committed. The
589** TCL script in pDb->zCommit is executed. If it returns non-zero or
590** if it throws an exception, the transaction is rolled back instead
591** of being committed.
592*/
593static int DbCommitHandler(void *cd){
594 SqliteDb *pDb = (SqliteDb*)cd;
595 int rc;
596
597 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
598 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
599 return 1;
600 }
601 return 0;
602}
603
danielk197771fd80b2005-12-16 06:54:01 +0000604static void DbRollbackHandler(void *clientData){
605 SqliteDb *pDb = (SqliteDb*)clientData;
606 assert(pDb->pRollbackHook);
607 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
608 Tcl_BackgroundError(pDb->interp);
609 }
610}
611
drh5def0842010-05-05 20:00:25 +0000612/*
613** This procedure handles wal_hook callbacks.
614*/
615static int DbWalHandler(
dan8d22a172010-04-19 18:03:51 +0000616 void *clientData,
617 sqlite3 *db,
618 const char *zDb,
619 int nEntry
620){
drh5def0842010-05-05 20:00:25 +0000621 int ret = SQLITE_OK;
dan8d22a172010-04-19 18:03:51 +0000622 Tcl_Obj *p;
623 SqliteDb *pDb = (SqliteDb*)clientData;
624 Tcl_Interp *interp = pDb->interp;
drh5def0842010-05-05 20:00:25 +0000625 assert(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000626
drh5def0842010-05-05 20:00:25 +0000627 p = Tcl_DuplicateObj(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000628 Tcl_IncrRefCount(p);
629 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
630 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
631 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
632 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
633 ){
634 Tcl_BackgroundError(interp);
635 }
636 Tcl_DecrRefCount(p);
637
638 return ret;
639}
640
drhbcf4f482009-03-27 12:44:35 +0000641#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000642static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
643 char zBuf[64];
644 sprintf(zBuf, "%d", iArg);
645 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
646 sprintf(zBuf, "%d", nArg);
647 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
648}
649#else
drhbcf4f482009-03-27 12:44:35 +0000650# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000651#endif
652
drh69910da2009-03-27 12:32:54 +0000653#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000654static void DbUnlockNotify(void **apArg, int nArg){
655 int i;
656 for(i=0; i<nArg; i++){
657 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
658 SqliteDb *pDb = (SqliteDb *)apArg[i];
659 setTestUnlockNotifyVars(pDb->interp, i, nArg);
660 assert( pDb->pUnlockNotify);
661 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
662 Tcl_DecrRefCount(pDb->pUnlockNotify);
663 pDb->pUnlockNotify = 0;
664 }
665}
drh69910da2009-03-27 12:32:54 +0000666#endif
danielk1977404ca072009-03-16 13:19:36 +0000667
danielk197794eb6a12005-12-15 15:22:08 +0000668static void DbUpdateHandler(
669 void *p,
670 int op,
671 const char *zDb,
672 const char *zTbl,
673 sqlite_int64 rowid
674){
675 SqliteDb *pDb = (SqliteDb *)p;
676 Tcl_Obj *pCmd;
677
678 assert( pDb->pUpdateHook );
679 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
680
681 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
682 Tcl_IncrRefCount(pCmd);
683 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
684 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
685 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
686 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
687 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
688 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
drhefdde162010-10-27 15:36:21 +0000689 Tcl_DecrRefCount(pCmd);
danielk197794eb6a12005-12-15 15:22:08 +0000690}
691
danielk19777cedc8d2004-06-10 10:50:08 +0000692static void tclCollateNeeded(
693 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000694 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000695 int enc,
696 const char *zName
697){
698 SqliteDb *pDb = (SqliteDb *)pCtx;
699 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
700 Tcl_IncrRefCount(pScript);
701 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
702 Tcl_EvalObjEx(pDb->interp, pScript, 0);
703 Tcl_DecrRefCount(pScript);
704}
705
drhaa940ea2004-01-15 02:44:03 +0000706/*
danielk19770202b292004-06-09 09:55:16 +0000707** This routine is called to evaluate an SQL collation function implemented
708** using TCL script.
709*/
710static int tclSqlCollate(
711 void *pCtx,
712 int nA,
713 const void *zA,
714 int nB,
715 const void *zB
716){
717 SqlCollate *p = (SqlCollate *)pCtx;
718 Tcl_Obj *pCmd;
719
720 pCmd = Tcl_NewStringObj(p->zScript, -1);
721 Tcl_IncrRefCount(pCmd);
722 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
723 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000724 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000725 Tcl_DecrRefCount(pCmd);
726 return (atoi(Tcl_GetStringResult(p->interp)));
727}
728
729/*
drhcabb0812002-09-14 13:47:32 +0000730** This routine is called to evaluate an SQL function implemented
731** using TCL script.
732*/
drhfb7e7652005-01-24 00:28:42 +0000733static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000734 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000735 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000736 int i;
737 int rc;
738
drhd1e47332005-06-26 17:55:33 +0000739 if( argc==0 ){
740 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
741 ** script object directly. This allows the TCL compiler to generate
742 ** bytecode for the command on the first invocation and thus make
743 ** subsequent invocations much faster. */
744 pCmd = p->pScript;
745 Tcl_IncrRefCount(pCmd);
746 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
747 Tcl_DecrRefCount(pCmd);
748 }else{
749 /* If there are arguments to the function, make a shallow copy of the
750 ** script object, lappend the arguments, then evaluate the copy.
751 **
752 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
753 ** The new Tcl_Obj contains pointers to the original list elements.
754 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
755 ** of the list to tclCmdNameType, that alternate representation will
756 ** be preserved and reused on the next invocation.
757 */
758 Tcl_Obj **aArg;
759 int nArg;
760 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
761 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
762 return;
763 }
764 pCmd = Tcl_NewListObj(nArg, aArg);
765 Tcl_IncrRefCount(pCmd);
766 for(i=0; i<argc; i++){
767 sqlite3_value *pIn = argv[i];
768 Tcl_Obj *pVal;
769
770 /* Set pVal to contain the i'th column of this row. */
771 switch( sqlite3_value_type(pIn) ){
772 case SQLITE_BLOB: {
773 int bytes = sqlite3_value_bytes(pIn);
774 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
775 break;
776 }
777 case SQLITE_INTEGER: {
778 sqlite_int64 v = sqlite3_value_int64(pIn);
779 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +0000780 pVal = Tcl_NewIntObj((int)v);
drhd1e47332005-06-26 17:55:33 +0000781 }else{
782 pVal = Tcl_NewWideIntObj(v);
783 }
784 break;
785 }
786 case SQLITE_FLOAT: {
787 double r = sqlite3_value_double(pIn);
788 pVal = Tcl_NewDoubleObj(r);
789 break;
790 }
791 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +0000792 pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
drhd1e47332005-06-26 17:55:33 +0000793 break;
794 }
795 default: {
796 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000797 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000798 break;
799 }
800 }
801 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
802 if( rc ){
803 Tcl_DecrRefCount(pCmd);
804 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
805 return;
806 }
danielk197751ad0ec2004-05-24 12:39:02 +0000807 }
drhd1e47332005-06-26 17:55:33 +0000808 if( !p->useEvalObjv ){
809 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
810 ** is a list without a string representation. To prevent this from
811 ** happening, make sure pCmd has a valid string representation */
812 Tcl_GetString(pCmd);
813 }
814 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
815 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000816 }
danielk1977562e8d32005-05-20 09:40:55 +0000817
drhc7f269d2005-05-05 10:30:29 +0000818 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000819 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000820 }else{
drhc7f269d2005-05-05 10:30:29 +0000821 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
822 int n;
823 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000824 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000825 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000826 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000827 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000828 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000829 data = Tcl_GetByteArrayFromObj(pVar, &n);
830 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000831 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000832 Tcl_GetIntFromObj(0, pVar, &n);
833 sqlite3_result_int(context, n);
834 }else if( c=='d' && strcmp(zType,"double")==0 ){
835 double r;
836 Tcl_GetDoubleFromObj(0, pVar, &r);
837 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +0000838 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
839 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000840 Tcl_WideInt v;
841 Tcl_GetWideIntFromObj(0, pVar, &v);
842 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000843 }else{
danielk197700fd9572005-12-07 06:27:43 +0000844 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
845 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000846 }
drhcabb0812002-09-14 13:47:32 +0000847 }
848}
drh895d7472004-08-20 16:02:39 +0000849
drhe22a3342003-04-22 20:30:37 +0000850#ifndef SQLITE_OMIT_AUTHORIZATION
851/*
852** This is the authentication function. It appends the authentication
853** type code and the two arguments to zCmd[] then invokes the result
854** on the interpreter. The reply is examined to determine if the
855** authentication fails or succeeds.
856*/
857static int auth_callback(
858 void *pArg,
859 int code,
860 const char *zArg1,
861 const char *zArg2,
862 const char *zArg3,
863 const char *zArg4
864){
865 char *zCode;
866 Tcl_DString str;
867 int rc;
868 const char *zReply;
869 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +0000870 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +0000871
872 switch( code ){
873 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
874 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
875 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
876 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
877 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
878 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
879 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
880 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
881 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
882 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
883 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
884 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
885 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
886 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
887 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
888 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
889 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
890 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
891 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
892 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
893 case SQLITE_READ : zCode="SQLITE_READ"; break;
894 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
895 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
896 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000897 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
898 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000899 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000900 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000901 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000902 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
903 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000904 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +0000905 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drhe22a3342003-04-22 20:30:37 +0000906 default : zCode="????"; break;
907 }
908 Tcl_DStringInit(&str);
909 Tcl_DStringAppend(&str, pDb->zAuth, -1);
910 Tcl_DStringAppendElement(&str, zCode);
911 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
912 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
913 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
914 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
915 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
916 Tcl_DStringFree(&str);
drhb07028f2011-10-14 21:49:18 +0000917 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
drhe22a3342003-04-22 20:30:37 +0000918 if( strcmp(zReply,"SQLITE_OK")==0 ){
919 rc = SQLITE_OK;
920 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
921 rc = SQLITE_DENY;
922 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
923 rc = SQLITE_IGNORE;
924 }else{
925 rc = 999;
926 }
927 return rc;
928}
929#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000930
931/*
tpoindex1067fe12004-12-17 15:41:11 +0000932** This routine reads a line of text from FILE in, stores
933** the text in memory obtained from malloc() and returns a pointer
934** to the text. NULL is returned at end of file, or if malloc()
935** fails.
936**
937** The interface is like "readline" but no command-line editing
938** is done.
939**
940** copied from shell.c from '.import' command
941*/
942static char *local_getline(char *zPrompt, FILE *in){
943 char *zLine;
944 int nLine;
945 int n;
tpoindex1067fe12004-12-17 15:41:11 +0000946
947 nLine = 100;
948 zLine = malloc( nLine );
949 if( zLine==0 ) return 0;
950 n = 0;
drhb07028f2011-10-14 21:49:18 +0000951 while( 1 ){
tpoindex1067fe12004-12-17 15:41:11 +0000952 if( n+100>nLine ){
953 nLine = nLine*2 + 100;
954 zLine = realloc(zLine, nLine);
955 if( zLine==0 ) return 0;
956 }
957 if( fgets(&zLine[n], nLine - n, in)==0 ){
958 if( n==0 ){
959 free(zLine);
960 return 0;
961 }
962 zLine[n] = 0;
tpoindex1067fe12004-12-17 15:41:11 +0000963 break;
964 }
965 while( zLine[n] ){ n++; }
966 if( n>0 && zLine[n-1]=='\n' ){
967 n--;
968 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +0000969 break;
tpoindex1067fe12004-12-17 15:41:11 +0000970 }
971 }
972 zLine = realloc( zLine, n+1 );
973 return zLine;
974}
975
danielk19778e556522007-11-13 10:30:24 +0000976
977/*
dan4a4c11a2009-10-06 14:59:02 +0000978** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +0000979**
dan4a4c11a2009-10-06 14:59:02 +0000980** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +0000981**
dan4a4c11a2009-10-06 14:59:02 +0000982** It is invoked after evaluating the script SCRIPT to commit or rollback
983** the transaction or savepoint opened by the [transaction] command.
984*/
985static int DbTransPostCmd(
986 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
987 Tcl_Interp *interp, /* Tcl interpreter */
988 int result /* Result of evaluating SCRIPT */
989){
990 static const char *azEnd[] = {
991 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
992 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
993 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
994 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
995 };
996 SqliteDb *pDb = (SqliteDb*)data[0];
997 int rc = result;
998 const char *zEnd;
999
1000 pDb->nTransaction--;
1001 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1002
1003 pDb->disableAuth++;
1004 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1005 /* This is a tricky scenario to handle. The most likely cause of an
1006 ** error is that the exec() above was an attempt to commit the
1007 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1008 ** that an IO-error has occured. In either case, throw a Tcl exception
1009 ** and try to rollback the transaction.
1010 **
1011 ** But it could also be that the user executed one or more BEGIN,
1012 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1013 ** this method's logic. Not clear how this would be best handled.
1014 */
1015 if( rc!=TCL_ERROR ){
1016 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
1017 rc = TCL_ERROR;
1018 }
1019 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1020 }
1021 pDb->disableAuth--;
1022
1023 return rc;
1024}
1025
1026/*
danc431fd52011-06-27 16:55:50 +00001027** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1028** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1029** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1030** on whether or not the [db_use_legacy_prepare] command has been used to
1031** configure the connection.
1032*/
1033static int dbPrepare(
1034 SqliteDb *pDb, /* Database object */
1035 const char *zSql, /* SQL to compile */
1036 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1037 const char **pzOut /* OUT: Pointer to next SQL statement */
1038){
1039#ifdef SQLITE_TEST
1040 if( pDb->bLegacyPrepare ){
1041 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1042 }
1043#endif
1044 return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut);
1045}
1046
1047/*
dan4a4c11a2009-10-06 14:59:02 +00001048** Search the cache for a prepared-statement object that implements the
1049** first SQL statement in the buffer pointed to by parameter zIn. If
1050** no such prepared-statement can be found, allocate and prepare a new
1051** one. In either case, bind the current values of the relevant Tcl
1052** variables to any $var, :var or @var variables in the statement. Before
1053** returning, set *ppPreStmt to point to the prepared-statement object.
1054**
1055** Output parameter *pzOut is set to point to the next SQL statement in
1056** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1057** next statement.
1058**
1059** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1060** and an error message loaded into interpreter pDb->interp.
1061*/
1062static int dbPrepareAndBind(
1063 SqliteDb *pDb, /* Database object */
1064 char const *zIn, /* SQL to compile */
1065 char const **pzOut, /* OUT: Pointer to next SQL statement */
1066 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1067){
1068 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
1069 sqlite3_stmt *pStmt; /* Prepared statement object */
1070 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1071 int nSql; /* Length of zSql in bytes */
1072 int nVar; /* Number of variables in statement */
1073 int iParm = 0; /* Next free entry in apParm */
1074 int i;
1075 Tcl_Interp *interp = pDb->interp;
1076
1077 *ppPreStmt = 0;
1078
1079 /* Trim spaces from the start of zSql and calculate the remaining length. */
1080 while( isspace(zSql[0]) ){ zSql++; }
1081 nSql = strlen30(zSql);
1082
1083 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1084 int n = pPreStmt->nSql;
1085 if( nSql>=n
1086 && memcmp(pPreStmt->zSql, zSql, n)==0
1087 && (zSql[n]==0 || zSql[n-1]==';')
1088 ){
1089 pStmt = pPreStmt->pStmt;
1090 *pzOut = &zSql[pPreStmt->nSql];
1091
1092 /* When a prepared statement is found, unlink it from the
1093 ** cache list. It will later be added back to the beginning
1094 ** of the cache list in order to implement LRU replacement.
1095 */
1096 if( pPreStmt->pPrev ){
1097 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1098 }else{
1099 pDb->stmtList = pPreStmt->pNext;
1100 }
1101 if( pPreStmt->pNext ){
1102 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1103 }else{
1104 pDb->stmtLast = pPreStmt->pPrev;
1105 }
1106 pDb->nStmt--;
1107 nVar = sqlite3_bind_parameter_count(pStmt);
1108 break;
1109 }
1110 }
1111
1112 /* If no prepared statement was found. Compile the SQL text. Also allocate
1113 ** a new SqlPreparedStmt structure. */
1114 if( pPreStmt==0 ){
1115 int nByte;
1116
danc431fd52011-06-27 16:55:50 +00001117 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
drhc45e6712012-10-03 11:02:33 +00001118 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001119 return TCL_ERROR;
1120 }
1121 if( pStmt==0 ){
1122 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1123 /* A compile-time error in the statement. */
drhc45e6712012-10-03 11:02:33 +00001124 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001125 return TCL_ERROR;
1126 }else{
1127 /* The statement was a no-op. Continue to the next statement
1128 ** in the SQL string.
1129 */
1130 return TCL_OK;
1131 }
1132 }
1133
1134 assert( pPreStmt==0 );
1135 nVar = sqlite3_bind_parameter_count(pStmt);
1136 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1137 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1138 memset(pPreStmt, 0, nByte);
1139
1140 pPreStmt->pStmt = pStmt;
drh7ed243b2012-04-19 17:19:51 +00001141 pPreStmt->nSql = (int)(*pzOut - zSql);
dan4a4c11a2009-10-06 14:59:02 +00001142 pPreStmt->zSql = sqlite3_sql(pStmt);
1143 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
danc431fd52011-06-27 16:55:50 +00001144#ifdef SQLITE_TEST
1145 if( pPreStmt->zSql==0 ){
1146 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1147 memcpy(zCopy, zSql, pPreStmt->nSql);
1148 zCopy[pPreStmt->nSql] = '\0';
1149 pPreStmt->zSql = zCopy;
1150 }
1151#endif
dan4a4c11a2009-10-06 14:59:02 +00001152 }
1153 assert( pPreStmt );
1154 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1155 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1156
1157 /* Bind values to parameters that begin with $ or : */
1158 for(i=1; i<=nVar; i++){
1159 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1160 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1161 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1162 if( pVar ){
1163 int n;
1164 u8 *data;
1165 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1166 char c = zType[0];
1167 if( zVar[0]=='@' ||
1168 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1169 /* Load a BLOB type if the Tcl variable is a bytearray and
1170 ** it has no string representation or the host
1171 ** parameter name begins with "@". */
1172 data = Tcl_GetByteArrayFromObj(pVar, &n);
1173 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1174 Tcl_IncrRefCount(pVar);
1175 pPreStmt->apParm[iParm++] = pVar;
1176 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1177 Tcl_GetIntFromObj(interp, pVar, &n);
1178 sqlite3_bind_int(pStmt, i, n);
1179 }else if( c=='d' && strcmp(zType,"double")==0 ){
1180 double r;
1181 Tcl_GetDoubleFromObj(interp, pVar, &r);
1182 sqlite3_bind_double(pStmt, i, r);
1183 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1184 (c=='i' && strcmp(zType,"int")==0) ){
1185 Tcl_WideInt v;
1186 Tcl_GetWideIntFromObj(interp, pVar, &v);
1187 sqlite3_bind_int64(pStmt, i, v);
1188 }else{
1189 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1190 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1191 Tcl_IncrRefCount(pVar);
1192 pPreStmt->apParm[iParm++] = pVar;
1193 }
1194 }else{
1195 sqlite3_bind_null(pStmt, i);
1196 }
1197 }
1198 }
1199 pPreStmt->nParm = iParm;
1200 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001201
dan4a4c11a2009-10-06 14:59:02 +00001202 return TCL_OK;
1203}
1204
dan4a4c11a2009-10-06 14:59:02 +00001205/*
1206** Release a statement reference obtained by calling dbPrepareAndBind().
1207** There should be exactly one call to this function for each call to
1208** dbPrepareAndBind().
1209**
1210** If the discard parameter is non-zero, then the statement is deleted
1211** immediately. Otherwise it is added to the LRU list and may be returned
1212** by a subsequent call to dbPrepareAndBind().
1213*/
1214static void dbReleaseStmt(
1215 SqliteDb *pDb, /* Database handle */
1216 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1217 int discard /* True to delete (not cache) the pPreStmt */
1218){
1219 int i;
1220
1221 /* Free the bound string and blob parameters */
1222 for(i=0; i<pPreStmt->nParm; i++){
1223 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1224 }
1225 pPreStmt->nParm = 0;
1226
1227 if( pDb->maxStmt<=0 || discard ){
1228 /* If the cache is turned off, deallocated the statement */
danc431fd52011-06-27 16:55:50 +00001229 dbFreeStmt(pPreStmt);
dan4a4c11a2009-10-06 14:59:02 +00001230 }else{
1231 /* Add the prepared statement to the beginning of the cache list. */
1232 pPreStmt->pNext = pDb->stmtList;
1233 pPreStmt->pPrev = 0;
1234 if( pDb->stmtList ){
1235 pDb->stmtList->pPrev = pPreStmt;
1236 }
1237 pDb->stmtList = pPreStmt;
1238 if( pDb->stmtLast==0 ){
1239 assert( pDb->nStmt==0 );
1240 pDb->stmtLast = pPreStmt;
1241 }else{
1242 assert( pDb->nStmt>0 );
1243 }
1244 pDb->nStmt++;
1245
1246 /* If we have too many statement in cache, remove the surplus from
1247 ** the end of the cache list. */
1248 while( pDb->nStmt>pDb->maxStmt ){
danc431fd52011-06-27 16:55:50 +00001249 SqlPreparedStmt *pLast = pDb->stmtLast;
1250 pDb->stmtLast = pLast->pPrev;
dan4a4c11a2009-10-06 14:59:02 +00001251 pDb->stmtLast->pNext = 0;
1252 pDb->nStmt--;
danc431fd52011-06-27 16:55:50 +00001253 dbFreeStmt(pLast);
dan4a4c11a2009-10-06 14:59:02 +00001254 }
1255 }
1256}
1257
1258/*
1259** Structure used with dbEvalXXX() functions:
1260**
1261** dbEvalInit()
1262** dbEvalStep()
1263** dbEvalFinalize()
1264** dbEvalRowInfo()
1265** dbEvalColumnValue()
1266*/
1267typedef struct DbEvalContext DbEvalContext;
1268struct DbEvalContext {
1269 SqliteDb *pDb; /* Database handle */
1270 Tcl_Obj *pSql; /* Object holding string zSql */
1271 const char *zSql; /* Remaining SQL to execute */
1272 SqlPreparedStmt *pPreStmt; /* Current statement */
1273 int nCol; /* Number of columns returned by pStmt */
1274 Tcl_Obj *pArray; /* Name of array variable */
1275 Tcl_Obj **apColName; /* Array of column names */
1276};
1277
1278/*
1279** Release any cache of column names currently held as part of
1280** the DbEvalContext structure passed as the first argument.
1281*/
1282static void dbReleaseColumnNames(DbEvalContext *p){
1283 if( p->apColName ){
1284 int i;
1285 for(i=0; i<p->nCol; i++){
1286 Tcl_DecrRefCount(p->apColName[i]);
1287 }
1288 Tcl_Free((char *)p->apColName);
1289 p->apColName = 0;
1290 }
1291 p->nCol = 0;
1292}
1293
1294/*
1295** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001296**
1297** If pArray is not NULL, then it contains the name of a Tcl array
1298** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001299** the names of the columns returned by the statement as part of each
1300** call to dbEvalStep(), in order from left to right. e.g. if the names
1301** of the returned columns are a, b and c, it does the equivalent of the
1302** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001303**
1304** set ${pArray}(*) {a b c}
1305*/
dan4a4c11a2009-10-06 14:59:02 +00001306static void dbEvalInit(
1307 DbEvalContext *p, /* Pointer to structure to initialize */
1308 SqliteDb *pDb, /* Database handle */
1309 Tcl_Obj *pSql, /* Object containing SQL script */
1310 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001311){
dan4a4c11a2009-10-06 14:59:02 +00001312 memset(p, 0, sizeof(DbEvalContext));
1313 p->pDb = pDb;
1314 p->zSql = Tcl_GetString(pSql);
1315 p->pSql = pSql;
1316 Tcl_IncrRefCount(pSql);
1317 if( pArray ){
1318 p->pArray = pArray;
1319 Tcl_IncrRefCount(pArray);
1320 }
1321}
danielk19778e556522007-11-13 10:30:24 +00001322
dan4a4c11a2009-10-06 14:59:02 +00001323/*
1324** Obtain information about the row that the DbEvalContext passed as the
1325** first argument currently points to.
1326*/
1327static void dbEvalRowInfo(
1328 DbEvalContext *p, /* Evaluation context */
1329 int *pnCol, /* OUT: Number of column names */
1330 Tcl_Obj ***papColName /* OUT: Array of column names */
1331){
danielk19778e556522007-11-13 10:30:24 +00001332 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001333 if( 0==p->apColName ){
1334 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1335 int i; /* Iterator variable */
1336 int nCol; /* Number of columns returned by pStmt */
1337 Tcl_Obj **apColName = 0; /* Array of column names */
1338
1339 p->nCol = nCol = sqlite3_column_count(pStmt);
1340 if( nCol>0 && (papColName || p->pArray) ){
1341 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1342 for(i=0; i<nCol; i++){
drhc45e6712012-10-03 11:02:33 +00001343 apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
dan4a4c11a2009-10-06 14:59:02 +00001344 Tcl_IncrRefCount(apColName[i]);
1345 }
1346 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001347 }
1348
1349 /* If results are being stored in an array variable, then create
1350 ** the array(*) entry for that array
1351 */
dan4a4c11a2009-10-06 14:59:02 +00001352 if( p->pArray ){
1353 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001354 Tcl_Obj *pColList = Tcl_NewObj();
1355 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001356
danielk19778e556522007-11-13 10:30:24 +00001357 for(i=0; i<nCol; i++){
1358 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1359 }
1360 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001361 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001362 Tcl_DecrRefCount(pStar);
1363 }
danielk19778e556522007-11-13 10:30:24 +00001364 }
1365
dan4a4c11a2009-10-06 14:59:02 +00001366 if( papColName ){
1367 *papColName = p->apColName;
1368 }
1369 if( pnCol ){
1370 *pnCol = p->nCol;
1371 }
1372}
1373
1374/*
1375** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1376** returned, then an error message is stored in the interpreter before
1377** returning.
1378**
1379** A return value of TCL_OK means there is a row of data available. The
1380** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1381** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1382** is returned, then the SQL script has finished executing and there are
1383** no further rows available. This is similar to SQLITE_DONE.
1384*/
1385static int dbEvalStep(DbEvalContext *p){
danc431fd52011-06-27 16:55:50 +00001386 const char *zPrevSql = 0; /* Previous value of p->zSql */
1387
dan4a4c11a2009-10-06 14:59:02 +00001388 while( p->zSql[0] || p->pPreStmt ){
1389 int rc;
1390 if( p->pPreStmt==0 ){
danc431fd52011-06-27 16:55:50 +00001391 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
dan4a4c11a2009-10-06 14:59:02 +00001392 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1393 if( rc!=TCL_OK ) return rc;
1394 }else{
1395 int rcs;
1396 SqliteDb *pDb = p->pDb;
1397 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1398 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1399
1400 rcs = sqlite3_step(pStmt);
1401 if( rcs==SQLITE_ROW ){
1402 return TCL_OK;
1403 }
1404 if( p->pArray ){
1405 dbEvalRowInfo(p, 0, 0);
1406 }
1407 rcs = sqlite3_reset(pStmt);
1408
1409 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1410 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001411 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
dan4a4c11a2009-10-06 14:59:02 +00001412 dbReleaseColumnNames(p);
1413 p->pPreStmt = 0;
1414
1415 if( rcs!=SQLITE_OK ){
1416 /* If a run-time error occurs, report the error and stop reading
1417 ** the SQL. */
dan4a4c11a2009-10-06 14:59:02 +00001418 dbReleaseStmt(pDb, pPreStmt, 1);
danc431fd52011-06-27 16:55:50 +00001419#if SQLITE_TEST
1420 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1421 /* If the runtime error was an SQLITE_SCHEMA, and the database
1422 ** handle is configured to use the legacy sqlite3_prepare()
1423 ** interface, retry prepare()/step() on the same SQL statement.
1424 ** This only happens once. If there is a second SQLITE_SCHEMA
1425 ** error, the error will be returned to the caller. */
1426 p->zSql = zPrevSql;
1427 continue;
1428 }
1429#endif
drhc45e6712012-10-03 11:02:33 +00001430 Tcl_SetObjResult(pDb->interp,
1431 Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001432 return TCL_ERROR;
1433 }else{
1434 dbReleaseStmt(pDb, pPreStmt, 0);
1435 }
1436 }
1437 }
1438
1439 /* Finished */
1440 return TCL_BREAK;
1441}
1442
1443/*
1444** Free all resources currently held by the DbEvalContext structure passed
1445** as the first argument. There should be exactly one call to this function
1446** for each call to dbEvalInit().
1447*/
1448static void dbEvalFinalize(DbEvalContext *p){
1449 if( p->pPreStmt ){
1450 sqlite3_reset(p->pPreStmt->pStmt);
1451 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1452 p->pPreStmt = 0;
1453 }
1454 if( p->pArray ){
1455 Tcl_DecrRefCount(p->pArray);
1456 p->pArray = 0;
1457 }
1458 Tcl_DecrRefCount(p->pSql);
1459 dbReleaseColumnNames(p);
1460}
1461
1462/*
1463** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1464** the value for the iCol'th column of the row currently pointed to by
1465** the DbEvalContext structure passed as the first argument.
1466*/
1467static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1468 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1469 switch( sqlite3_column_type(pStmt, iCol) ){
1470 case SQLITE_BLOB: {
1471 int bytes = sqlite3_column_bytes(pStmt, iCol);
1472 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1473 if( !zBlob ) bytes = 0;
1474 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1475 }
1476 case SQLITE_INTEGER: {
1477 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1478 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +00001479 return Tcl_NewIntObj((int)v);
dan4a4c11a2009-10-06 14:59:02 +00001480 }else{
1481 return Tcl_NewWideIntObj(v);
1482 }
1483 }
1484 case SQLITE_FLOAT: {
1485 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1486 }
1487 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +00001488 return Tcl_NewStringObj(p->pDb->zNull, -1);
dan4a4c11a2009-10-06 14:59:02 +00001489 }
1490 }
1491
drh325eff52012-10-03 12:56:18 +00001492 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
dan4a4c11a2009-10-06 14:59:02 +00001493}
1494
1495/*
1496** If using Tcl version 8.6 or greater, use the NR functions to avoid
1497** recursive evalution of scripts by the [db eval] and [db trans]
1498** commands. Even if the headers used while compiling the extension
1499** are 8.6 or newer, the code still tests the Tcl version at runtime.
1500** This allows stubs-enabled builds to be used with older Tcl libraries.
1501*/
1502#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001503# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001504static int DbUseNre(void){
1505 int major, minor;
1506 Tcl_GetVersion(&major, &minor, 0, 0);
1507 return( (major==8 && minor>=6) || major>8 );
1508}
1509#else
1510/*
1511** Compiling using headers earlier than 8.6. In this case NR cannot be
1512** used, so DbUseNre() to always return zero. Add #defines for the other
1513** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1514** even though the only invocations of them are within conditional blocks
1515** of the form:
1516**
1517** if( DbUseNre() ) { ... }
1518*/
drha2c8a952009-10-13 18:38:34 +00001519# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001520# define DbUseNre() 0
1521# define Tcl_NRAddCallback(a,b,c,d,e,f) 0
1522# define Tcl_NREvalObj(a,b,c) 0
1523# define Tcl_NRCreateCommand(a,b,c,d,e,f) 0
1524#endif
1525
1526/*
1527** This function is part of the implementation of the command:
1528**
1529** $db eval SQL ?ARRAYNAME? SCRIPT
1530*/
1531static int DbEvalNextCmd(
1532 ClientData data[], /* data[0] is the (DbEvalContext*) */
1533 Tcl_Interp *interp, /* Tcl interpreter */
1534 int result /* Result so far */
1535){
1536 int rc = result; /* Return code */
1537
1538 /* The first element of the data[] array is a pointer to a DbEvalContext
1539 ** structure allocated using Tcl_Alloc(). The second element of data[]
1540 ** is a pointer to a Tcl_Obj containing the script to run for each row
1541 ** returned by the queries encapsulated in data[0]. */
1542 DbEvalContext *p = (DbEvalContext *)data[0];
1543 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1544 Tcl_Obj *pArray = p->pArray;
1545
1546 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1547 int i;
1548 int nCol;
1549 Tcl_Obj **apColName;
1550 dbEvalRowInfo(p, &nCol, &apColName);
1551 for(i=0; i<nCol; i++){
1552 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1553 if( pArray==0 ){
1554 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1555 }else{
1556 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1557 }
1558 }
1559
1560 /* The required interpreter variables are now populated with the data
1561 ** from the current row. If using NRE, schedule callbacks to evaluate
1562 ** script pScript, then to invoke this function again to fetch the next
1563 ** row (or clean up if there is no next row or the script throws an
1564 ** exception). After scheduling the callbacks, return control to the
1565 ** caller.
1566 **
1567 ** If not using NRE, evaluate pScript directly and continue with the
1568 ** next iteration of this while(...) loop. */
1569 if( DbUseNre() ){
1570 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1571 return Tcl_NREvalObj(interp, pScript, 0);
1572 }else{
1573 rc = Tcl_EvalObjEx(interp, pScript, 0);
1574 }
1575 }
1576
1577 Tcl_DecrRefCount(pScript);
1578 dbEvalFinalize(p);
1579 Tcl_Free((char *)p);
1580
1581 if( rc==TCL_OK || rc==TCL_BREAK ){
1582 Tcl_ResetResult(interp);
1583 rc = TCL_OK;
1584 }
1585 return rc;
danielk19778e556522007-11-13 10:30:24 +00001586}
1587
tpoindex1067fe12004-12-17 15:41:11 +00001588/*
drh75897232000-05-29 14:26:00 +00001589** The "sqlite" command below creates a new Tcl command for each
1590** connection it opens to an SQLite database. This routine is invoked
1591** whenever one of those connection-specific commands is executed
1592** in Tcl. For example, if you run Tcl code like this:
1593**
drh9bb575f2004-09-06 17:24:11 +00001594** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001595** db1 close
1596**
1597** The first command opens a connection to the "my_database" database
1598** and calls that connection "db1". The second command causes this
1599** subroutine to be invoked.
1600*/
drh6d313162000-09-21 13:01:35 +00001601static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001602 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001603 int choice;
drh22fbcb82004-02-01 01:22:50 +00001604 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001605 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001606 "authorizer", "backup", "busy",
1607 "cache", "changes", "close",
1608 "collate", "collation_needed", "commit_hook",
1609 "complete", "copy", "enable_load_extension",
1610 "errorcode", "eval", "exists",
1611 "function", "incrblob", "interrupt",
drh833bf962010-04-28 14:42:19 +00001612 "last_insert_rowid", "nullvalue", "onecolumn",
1613 "profile", "progress", "rekey",
1614 "restore", "rollback_hook", "status",
1615 "timeout", "total_changes", "trace",
1616 "transaction", "unlock_notify", "update_hook",
1617 "version", "wal_hook", 0
drh6d313162000-09-21 13:01:35 +00001618 };
drh411995d2002-06-25 19:31:18 +00001619 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001620 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1621 DB_CACHE, DB_CHANGES, DB_CLOSE,
1622 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1623 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1624 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1625 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
drh833bf962010-04-28 14:42:19 +00001626 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
1627 DB_PROFILE, DB_PROGRESS, DB_REKEY,
1628 DB_RESTORE, DB_ROLLBACK_HOOK, DB_STATUS,
1629 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
1630 DB_TRANSACTION, DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK,
1631 DB_VERSION, DB_WAL_HOOK
drh6d313162000-09-21 13:01:35 +00001632 };
tpoindex1067fe12004-12-17 15:41:11 +00001633 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001634
1635 if( objc<2 ){
1636 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001637 return TCL_ERROR;
1638 }
drh411995d2002-06-25 19:31:18 +00001639 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001640 return TCL_ERROR;
1641 }
1642
drh411995d2002-06-25 19:31:18 +00001643 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001644
drhe22a3342003-04-22 20:30:37 +00001645 /* $db authorizer ?CALLBACK?
1646 **
1647 ** Invoke the given callback to authorize each SQL operation as it is
1648 ** compiled. 5 arguments are appended to the callback before it is
1649 ** invoked:
1650 **
1651 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1652 ** (2) First descriptive name (depends on authorization type)
1653 ** (3) Second descriptive name
1654 ** (4) Name of the database (ex: "main", "temp")
1655 ** (5) Name of trigger that is doing the access
1656 **
1657 ** The callback should return on of the following strings: SQLITE_OK,
1658 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1659 **
1660 ** If this method is invoked with no arguments, the current authorization
1661 ** callback string is returned.
1662 */
1663 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001664#ifdef SQLITE_OMIT_AUTHORIZATION
1665 Tcl_AppendResult(interp, "authorization not available in this build", 0);
1666 return TCL_ERROR;
1667#else
drhe22a3342003-04-22 20:30:37 +00001668 if( objc>3 ){
1669 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001670 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001671 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001672 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +00001673 Tcl_AppendResult(interp, pDb->zAuth, 0);
1674 }
1675 }else{
1676 char *zAuth;
1677 int len;
1678 if( pDb->zAuth ){
1679 Tcl_Free(pDb->zAuth);
1680 }
1681 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1682 if( zAuth && len>0 ){
1683 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001684 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001685 }else{
1686 pDb->zAuth = 0;
1687 }
drhe22a3342003-04-22 20:30:37 +00001688 if( pDb->zAuth ){
1689 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001690 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +00001691 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001692 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001693 }
drhe22a3342003-04-22 20:30:37 +00001694 }
drh1211de32004-07-26 12:24:22 +00001695#endif
drhe22a3342003-04-22 20:30:37 +00001696 break;
1697 }
1698
drhdc2c4912009-02-04 22:46:47 +00001699 /* $db backup ?DATABASE? FILENAME
1700 **
1701 ** Open or create a database file named FILENAME. Transfer the
1702 ** content of local database DATABASE (default: "main") into the
1703 ** FILENAME database.
1704 */
1705 case DB_BACKUP: {
1706 const char *zDestFile;
1707 const char *zSrcDb;
1708 sqlite3 *pDest;
1709 sqlite3_backup *pBackup;
1710
1711 if( objc==3 ){
1712 zSrcDb = "main";
1713 zDestFile = Tcl_GetString(objv[2]);
1714 }else if( objc==4 ){
1715 zSrcDb = Tcl_GetString(objv[2]);
1716 zDestFile = Tcl_GetString(objv[3]);
1717 }else{
1718 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1719 return TCL_ERROR;
1720 }
1721 rc = sqlite3_open(zDestFile, &pDest);
1722 if( rc!=SQLITE_OK ){
1723 Tcl_AppendResult(interp, "cannot open target database: ",
1724 sqlite3_errmsg(pDest), (char*)0);
1725 sqlite3_close(pDest);
1726 return TCL_ERROR;
1727 }
1728 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1729 if( pBackup==0 ){
1730 Tcl_AppendResult(interp, "backup failed: ",
1731 sqlite3_errmsg(pDest), (char*)0);
1732 sqlite3_close(pDest);
1733 return TCL_ERROR;
1734 }
1735 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1736 sqlite3_backup_finish(pBackup);
1737 if( rc==SQLITE_DONE ){
1738 rc = TCL_OK;
1739 }else{
1740 Tcl_AppendResult(interp, "backup failed: ",
1741 sqlite3_errmsg(pDest), (char*)0);
1742 rc = TCL_ERROR;
1743 }
1744 sqlite3_close(pDest);
1745 break;
1746 }
1747
drhbec3f402000-08-04 13:49:02 +00001748 /* $db busy ?CALLBACK?
1749 **
1750 ** Invoke the given callback if an SQL statement attempts to open
1751 ** a locked database file.
1752 */
drh6d313162000-09-21 13:01:35 +00001753 case DB_BUSY: {
1754 if( objc>3 ){
1755 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001756 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001757 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001758 if( pDb->zBusy ){
1759 Tcl_AppendResult(interp, pDb->zBusy, 0);
1760 }
1761 }else{
drh6d313162000-09-21 13:01:35 +00001762 char *zBusy;
1763 int len;
drhbec3f402000-08-04 13:49:02 +00001764 if( pDb->zBusy ){
1765 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001766 }
drh6d313162000-09-21 13:01:35 +00001767 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1768 if( zBusy && len>0 ){
1769 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001770 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001771 }else{
1772 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001773 }
1774 if( pDb->zBusy ){
1775 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001776 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001777 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001778 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001779 }
1780 }
drh6d313162000-09-21 13:01:35 +00001781 break;
1782 }
drhbec3f402000-08-04 13:49:02 +00001783
drhfb7e7652005-01-24 00:28:42 +00001784 /* $db cache flush
1785 ** $db cache size n
1786 **
1787 ** Flush the prepared statement cache, or set the maximum number of
1788 ** cached statements.
1789 */
1790 case DB_CACHE: {
1791 char *subCmd;
1792 int n;
1793
1794 if( objc<=2 ){
1795 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1796 return TCL_ERROR;
1797 }
1798 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1799 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1800 if( objc!=3 ){
1801 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1802 return TCL_ERROR;
1803 }else{
1804 flushStmtCache( pDb );
1805 }
1806 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1807 if( objc!=4 ){
1808 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1809 return TCL_ERROR;
1810 }else{
1811 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1812 Tcl_AppendResult( interp, "cannot convert \"",
1813 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1814 return TCL_ERROR;
1815 }else{
1816 if( n<0 ){
1817 flushStmtCache( pDb );
1818 n = 0;
1819 }else if( n>MAX_PREPARED_STMTS ){
1820 n = MAX_PREPARED_STMTS;
1821 }
1822 pDb->maxStmt = n;
1823 }
1824 }
1825 }else{
1826 Tcl_AppendResult( interp, "bad option \"",
danielk1977191fadc2007-10-23 08:17:48 +00001827 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
drhfb7e7652005-01-24 00:28:42 +00001828 return TCL_ERROR;
1829 }
1830 break;
1831 }
1832
danielk1977b28af712004-06-21 06:50:26 +00001833 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001834 **
1835 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001836 ** the most recent INSERT, UPDATE or DELETE statement, not including
1837 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001838 */
1839 case DB_CHANGES: {
1840 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001841 if( objc!=2 ){
1842 Tcl_WrongNumArgs(interp, 2, objv, "");
1843 return TCL_ERROR;
1844 }
drhc8d30ac2002-04-12 10:08:59 +00001845 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001846 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001847 break;
1848 }
1849
drh75897232000-05-29 14:26:00 +00001850 /* $db close
1851 **
1852 ** Shutdown the database
1853 */
drh6d313162000-09-21 13:01:35 +00001854 case DB_CLOSE: {
1855 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1856 break;
1857 }
drh75897232000-05-29 14:26:00 +00001858
drh0f14e2e2004-06-29 12:39:08 +00001859 /*
1860 ** $db collate NAME SCRIPT
1861 **
1862 ** Create a new SQL collation function called NAME. Whenever
1863 ** that function is called, invoke SCRIPT to evaluate the function.
1864 */
1865 case DB_COLLATE: {
1866 SqlCollate *pCollate;
1867 char *zName;
1868 char *zScript;
1869 int nScript;
1870 if( objc!=4 ){
1871 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1872 return TCL_ERROR;
1873 }
1874 zName = Tcl_GetStringFromObj(objv[2], 0);
1875 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1876 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1877 if( pCollate==0 ) return TCL_ERROR;
1878 pCollate->interp = interp;
1879 pCollate->pNext = pDb->pCollate;
1880 pCollate->zScript = (char*)&pCollate[1];
1881 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001882 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001883 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1884 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001885 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001886 return TCL_ERROR;
1887 }
1888 break;
1889 }
1890
1891 /*
1892 ** $db collation_needed SCRIPT
1893 **
1894 ** Create a new SQL collation function called NAME. Whenever
1895 ** that function is called, invoke SCRIPT to evaluate the function.
1896 */
1897 case DB_COLLATION_NEEDED: {
1898 if( objc!=3 ){
1899 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1900 return TCL_ERROR;
1901 }
1902 if( pDb->pCollateNeeded ){
1903 Tcl_DecrRefCount(pDb->pCollateNeeded);
1904 }
1905 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1906 Tcl_IncrRefCount(pDb->pCollateNeeded);
1907 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1908 break;
1909 }
1910
drh19e2d372005-08-29 23:00:03 +00001911 /* $db commit_hook ?CALLBACK?
1912 **
1913 ** Invoke the given callback just before committing every SQL transaction.
1914 ** If the callback throws an exception or returns non-zero, then the
1915 ** transaction is aborted. If CALLBACK is an empty string, the callback
1916 ** is disabled.
1917 */
1918 case DB_COMMIT_HOOK: {
1919 if( objc>3 ){
1920 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1921 return TCL_ERROR;
1922 }else if( objc==2 ){
1923 if( pDb->zCommit ){
1924 Tcl_AppendResult(interp, pDb->zCommit, 0);
1925 }
1926 }else{
1927 char *zCommit;
1928 int len;
1929 if( pDb->zCommit ){
1930 Tcl_Free(pDb->zCommit);
1931 }
1932 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1933 if( zCommit && len>0 ){
1934 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001935 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001936 }else{
1937 pDb->zCommit = 0;
1938 }
1939 if( pDb->zCommit ){
1940 pDb->interp = interp;
1941 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1942 }else{
1943 sqlite3_commit_hook(pDb->db, 0, 0);
1944 }
1945 }
1946 break;
1947 }
1948
drh75897232000-05-29 14:26:00 +00001949 /* $db complete SQL
1950 **
1951 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1952 ** additional lines of input are needed. This is similar to the
1953 ** built-in "info complete" command of Tcl.
1954 */
drh6d313162000-09-21 13:01:35 +00001955 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00001956#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00001957 Tcl_Obj *pResult;
1958 int isComplete;
1959 if( objc!=3 ){
1960 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00001961 return TCL_ERROR;
1962 }
danielk19776f8a5032004-05-10 10:34:51 +00001963 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00001964 pResult = Tcl_GetObjResult(interp);
1965 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00001966#endif
drh6d313162000-09-21 13:01:35 +00001967 break;
1968 }
drhdcd997e2003-01-31 17:21:49 +00001969
drh19e2d372005-08-29 23:00:03 +00001970 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1971 **
1972 ** Copy data into table from filename, optionally using SEPARATOR
1973 ** as column separators. If a column contains a null string, or the
1974 ** value of NULLINDICATOR, a NULL is inserted for the column.
1975 ** conflict-algorithm is one of the sqlite conflict algorithms:
1976 ** rollback, abort, fail, ignore, replace
1977 ** On success, return the number of lines processed, not necessarily same
1978 ** as 'db changes' due to conflict-algorithm selected.
1979 **
1980 ** This code is basically an implementation/enhancement of
1981 ** the sqlite3 shell.c ".import" command.
1982 **
1983 ** This command usage is equivalent to the sqlite2.x COPY statement,
1984 ** which imports file data into a table using the PostgreSQL COPY file format:
1985 ** $db copy $conflit_algo $table_name $filename \t \\N
1986 */
1987 case DB_COPY: {
1988 char *zTable; /* Insert data into this table */
1989 char *zFile; /* The file from which to extract data */
1990 char *zConflict; /* The conflict algorithm to use */
1991 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00001992 int nCol; /* Number of columns in the table */
1993 int nByte; /* Number of bytes in an SQL string */
1994 int i, j; /* Loop counters */
1995 int nSep; /* Number of bytes in zSep[] */
1996 int nNull; /* Number of bytes in zNull[] */
1997 char *zSql; /* An SQL statement */
1998 char *zLine; /* A single line of input from the file */
1999 char **azCol; /* zLine[] broken up into columns */
2000 char *zCommit; /* How to commit changes */
2001 FILE *in; /* The input file */
2002 int lineno = 0; /* Line number of input file */
2003 char zLineNum[80]; /* Line number print buffer */
2004 Tcl_Obj *pResult; /* interp result */
2005
2006 char *zSep;
2007 char *zNull;
2008 if( objc<5 || objc>7 ){
2009 Tcl_WrongNumArgs(interp, 2, objv,
2010 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2011 return TCL_ERROR;
2012 }
2013 if( objc>=6 ){
2014 zSep = Tcl_GetStringFromObj(objv[5], 0);
2015 }else{
2016 zSep = "\t";
2017 }
2018 if( objc>=7 ){
2019 zNull = Tcl_GetStringFromObj(objv[6], 0);
2020 }else{
2021 zNull = "";
2022 }
2023 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2024 zTable = Tcl_GetStringFromObj(objv[3], 0);
2025 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002026 nSep = strlen30(zSep);
2027 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002028 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00002029 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00002030 return TCL_ERROR;
2031 }
drh3e59c012008-09-23 10:12:13 +00002032 if(strcmp(zConflict, "rollback") != 0 &&
2033 strcmp(zConflict, "abort" ) != 0 &&
2034 strcmp(zConflict, "fail" ) != 0 &&
2035 strcmp(zConflict, "ignore" ) != 0 &&
2036 strcmp(zConflict, "replace" ) != 0 ) {
drh19e2d372005-08-29 23:00:03 +00002037 Tcl_AppendResult(interp, "Error: \"", zConflict,
2038 "\", conflict-algorithm must be one of: rollback, "
2039 "abort, fail, ignore, or replace", 0);
2040 return TCL_ERROR;
2041 }
2042 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2043 if( zSql==0 ){
2044 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
2045 return TCL_ERROR;
2046 }
drh4f21c4a2008-12-10 22:15:00 +00002047 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002048 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002049 sqlite3_free(zSql);
2050 if( rc ){
2051 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2052 nCol = 0;
2053 }else{
2054 nCol = sqlite3_column_count(pStmt);
2055 }
2056 sqlite3_finalize(pStmt);
2057 if( nCol==0 ) {
2058 return TCL_ERROR;
2059 }
2060 zSql = malloc( nByte + 50 + nCol*2 );
2061 if( zSql==0 ) {
2062 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
2063 return TCL_ERROR;
2064 }
2065 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2066 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002067 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002068 for(i=1; i<nCol; i++){
2069 zSql[j++] = ',';
2070 zSql[j++] = '?';
2071 }
2072 zSql[j++] = ')';
2073 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002074 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002075 free(zSql);
2076 if( rc ){
2077 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2078 sqlite3_finalize(pStmt);
2079 return TCL_ERROR;
2080 }
2081 in = fopen(zFile, "rb");
2082 if( in==0 ){
2083 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2084 sqlite3_finalize(pStmt);
2085 return TCL_ERROR;
2086 }
2087 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2088 if( azCol==0 ) {
2089 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00002090 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002091 return TCL_ERROR;
2092 }
drh37527852006-03-16 16:19:56 +00002093 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002094 zCommit = "COMMIT";
2095 while( (zLine = local_getline(0, in))!=0 ){
2096 char *z;
drh19e2d372005-08-29 23:00:03 +00002097 lineno++;
2098 azCol[0] = zLine;
2099 for(i=0, z=zLine; *z; z++){
2100 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2101 *z = 0;
2102 i++;
2103 if( i<nCol ){
2104 azCol[i] = &z[nSep];
2105 z += nSep-1;
2106 }
2107 }
2108 }
2109 if( i+1!=nCol ){
2110 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002111 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002112 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002113 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002114 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002115 "Error: %s line %d: expected %d columns of data but found %d",
2116 zFile, lineno, nCol, i+1);
2117 Tcl_AppendResult(interp, zErr, 0);
2118 free(zErr);
2119 }
drh19e2d372005-08-29 23:00:03 +00002120 zCommit = "ROLLBACK";
2121 break;
2122 }
2123 for(i=0; i<nCol; i++){
2124 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002125 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
drh4f21c4a2008-12-10 22:15:00 +00002126 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002127 ){
drh19e2d372005-08-29 23:00:03 +00002128 sqlite3_bind_null(pStmt, i+1);
2129 }else{
2130 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2131 }
2132 }
2133 sqlite3_step(pStmt);
2134 rc = sqlite3_reset(pStmt);
2135 free(zLine);
2136 if( rc!=SQLITE_OK ){
2137 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
2138 zCommit = "ROLLBACK";
2139 break;
2140 }
2141 }
2142 free(azCol);
2143 fclose(in);
2144 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002145 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002146
2147 if( zCommit[0] == 'C' ){
2148 /* success, set result as number of lines processed */
2149 pResult = Tcl_GetObjResult(interp);
2150 Tcl_SetIntObj(pResult, lineno);
2151 rc = TCL_OK;
2152 }else{
2153 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002154 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00002155 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
2156 rc = TCL_ERROR;
2157 }
2158 break;
2159 }
2160
drhdcd997e2003-01-31 17:21:49 +00002161 /*
drh41449052006-07-06 17:08:48 +00002162 ** $db enable_load_extension BOOLEAN
2163 **
2164 ** Turn the extension loading feature on or off. It if off by
2165 ** default.
2166 */
2167 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002168#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002169 int onoff;
2170 if( objc!=3 ){
2171 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2172 return TCL_ERROR;
2173 }
2174 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2175 return TCL_ERROR;
2176 }
2177 sqlite3_enable_load_extension(pDb->db, onoff);
2178 break;
drhf533acc2006-12-19 18:57:11 +00002179#else
2180 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2181 0);
2182 return TCL_ERROR;
2183#endif
drh41449052006-07-06 17:08:48 +00002184 }
2185
2186 /*
drhdcd997e2003-01-31 17:21:49 +00002187 ** $db errorcode
2188 **
2189 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002190 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002191 */
2192 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002193 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002194 break;
2195 }
dan4a4c11a2009-10-06 14:59:02 +00002196
2197 /*
2198 ** $db exists $sql
2199 ** $db onecolumn $sql
2200 **
2201 ** The onecolumn method is the equivalent of:
2202 ** lindex [$db eval $sql] 0
2203 */
2204 case DB_EXISTS:
2205 case DB_ONECOLUMN: {
2206 DbEvalContext sEval;
2207 if( objc!=3 ){
2208 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2209 return TCL_ERROR;
2210 }
2211
2212 dbEvalInit(&sEval, pDb, objv[2], 0);
2213 rc = dbEvalStep(&sEval);
2214 if( choice==DB_ONECOLUMN ){
2215 if( rc==TCL_OK ){
2216 Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
dand5f12cd2011-08-18 17:47:57 +00002217 }else if( rc==TCL_BREAK ){
2218 Tcl_ResetResult(interp);
dan4a4c11a2009-10-06 14:59:02 +00002219 }
2220 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2221 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
2222 }
2223 dbEvalFinalize(&sEval);
2224
2225 if( rc==TCL_BREAK ){
2226 rc = TCL_OK;
2227 }
2228 break;
2229 }
drh75897232000-05-29 14:26:00 +00002230
2231 /*
drh895d7472004-08-20 16:02:39 +00002232 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002233 **
2234 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002235 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002236 ** If "array" and "code" are omitted, then no callback is every invoked.
2237 ** If "array" is an empty string, then the values are placed in variables
2238 ** that have the same name as the fields extracted by the query.
2239 */
dan4a4c11a2009-10-06 14:59:02 +00002240 case DB_EVAL: {
2241 if( objc<3 || objc>5 ){
2242 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2243 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002244 }
dan4a4c11a2009-10-06 14:59:02 +00002245
drh92febd92004-08-20 18:34:20 +00002246 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002247 DbEvalContext sEval;
2248 Tcl_Obj *pRet = Tcl_NewObj();
2249 Tcl_IncrRefCount(pRet);
2250 dbEvalInit(&sEval, pDb, objv[2], 0);
2251 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2252 int i;
2253 int nCol;
2254 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002255 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002256 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002257 }
2258 }
dan4a4c11a2009-10-06 14:59:02 +00002259 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002260 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002261 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002262 rc = TCL_OK;
2263 }
drh1807ce32004-09-07 13:20:35 +00002264 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002265 }else{
2266 ClientData cd[2];
2267 DbEvalContext *p;
2268 Tcl_Obj *pArray = 0;
2269 Tcl_Obj *pScript;
2270
2271 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2272 pArray = objv[3];
2273 }
2274 pScript = objv[objc-1];
2275 Tcl_IncrRefCount(pScript);
2276
2277 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2278 dbEvalInit(p, pDb, objv[2], pArray);
2279
2280 cd[0] = (void *)p;
2281 cd[1] = (void *)pScript;
2282 rc = DbEvalNextCmd(cd, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002283 }
danielk197730ccda12004-05-27 12:11:31 +00002284 break;
2285 }
drhbec3f402000-08-04 13:49:02 +00002286
2287 /*
drhe3602be2008-09-09 12:31:33 +00002288 ** $db function NAME [-argcount N] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002289 **
2290 ** Create a new SQL function called NAME. Whenever that function is
2291 ** called, invoke SCRIPT to evaluate the function.
2292 */
2293 case DB_FUNCTION: {
2294 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002295 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002296 char *zName;
drhe3602be2008-09-09 12:31:33 +00002297 int nArg = -1;
2298 if( objc==6 ){
2299 const char *z = Tcl_GetString(objv[3]);
drh4f21c4a2008-12-10 22:15:00 +00002300 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002301 if( n>2 && strncmp(z, "-argcount",n)==0 ){
2302 if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
2303 if( nArg<0 ){
2304 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2305 (char*)0);
2306 return TCL_ERROR;
2307 }
2308 }
2309 pScript = objv[5];
2310 }else if( objc!=4 ){
2311 Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
drhcabb0812002-09-14 13:47:32 +00002312 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002313 }else{
2314 pScript = objv[3];
drhcabb0812002-09-14 13:47:32 +00002315 }
2316 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002317 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002318 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002319 if( pFunc->pScript ){
2320 Tcl_DecrRefCount(pFunc->pScript);
2321 }
2322 pFunc->pScript = pScript;
2323 Tcl_IncrRefCount(pScript);
2324 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
drhe3602be2008-09-09 12:31:33 +00002325 rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00002326 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002327 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002328 rc = TCL_ERROR;
2329 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002330 }
drhcabb0812002-09-14 13:47:32 +00002331 break;
2332 }
2333
2334 /*
danielk19778cbadb02007-05-03 16:31:26 +00002335 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002336 */
2337 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002338#ifdef SQLITE_OMIT_INCRBLOB
2339 Tcl_AppendResult(interp, "incrblob not available in this build", 0);
2340 return TCL_ERROR;
2341#else
danielk19778cbadb02007-05-03 16:31:26 +00002342 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002343 const char *zDb = "main";
2344 const char *zTable;
2345 const char *zColumn;
drhb3f787f2012-09-29 14:45:54 +00002346 Tcl_WideInt iRow;
danielk1977b4e9af92007-05-01 17:49:49 +00002347
danielk19778cbadb02007-05-03 16:31:26 +00002348 /* Check for the -readonly option */
2349 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2350 isReadonly = 1;
2351 }
2352
2353 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2354 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002355 return TCL_ERROR;
2356 }
2357
danielk19778cbadb02007-05-03 16:31:26 +00002358 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002359 zDb = Tcl_GetString(objv[2]);
2360 }
2361 zTable = Tcl_GetString(objv[objc-3]);
2362 zColumn = Tcl_GetString(objv[objc-2]);
2363 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2364
2365 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002366 rc = createIncrblobChannel(
2367 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
2368 );
danielk1977b4e9af92007-05-01 17:49:49 +00002369 }
danielk197732a0d8b2007-05-04 19:03:02 +00002370#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002371 break;
2372 }
2373
2374 /*
drhf11bded2006-07-17 00:02:44 +00002375 ** $db interrupt
2376 **
2377 ** Interrupt the execution of the inner-most SQL interpreter. This
2378 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2379 */
2380 case DB_INTERRUPT: {
2381 sqlite3_interrupt(pDb->db);
2382 break;
2383 }
2384
2385 /*
drh19e2d372005-08-29 23:00:03 +00002386 ** $db nullvalue ?STRING?
2387 **
2388 ** Change text used when a NULL comes back from the database. If ?STRING?
2389 ** is not present, then the current string used for NULL is returned.
2390 ** If STRING is present, then STRING is returned.
2391 **
2392 */
2393 case DB_NULLVALUE: {
2394 if( objc!=2 && objc!=3 ){
2395 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2396 return TCL_ERROR;
2397 }
2398 if( objc==3 ){
2399 int len;
2400 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2401 if( pDb->zNull ){
2402 Tcl_Free(pDb->zNull);
2403 }
2404 if( zNull && len>0 ){
2405 pDb->zNull = Tcl_Alloc( len + 1 );
drh7fd33922011-06-20 19:00:30 +00002406 memcpy(pDb->zNull, zNull, len);
drh19e2d372005-08-29 23:00:03 +00002407 pDb->zNull[len] = '\0';
2408 }else{
2409 pDb->zNull = 0;
2410 }
2411 }
drhc45e6712012-10-03 11:02:33 +00002412 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
drh19e2d372005-08-29 23:00:03 +00002413 break;
2414 }
2415
2416 /*
drhaf9ff332002-01-16 21:00:27 +00002417 ** $db last_insert_rowid
2418 **
2419 ** Return an integer which is the ROWID for the most recent insert.
2420 */
2421 case DB_LAST_INSERT_ROWID: {
2422 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002423 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002424 if( objc!=2 ){
2425 Tcl_WrongNumArgs(interp, 2, objv, "");
2426 return TCL_ERROR;
2427 }
danielk19776f8a5032004-05-10 10:34:51 +00002428 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002429 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002430 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002431 break;
2432 }
2433
2434 /*
dan4a4c11a2009-10-06 14:59:02 +00002435 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002436 */
drh1807ce32004-09-07 13:20:35 +00002437
2438 /* $db progress ?N CALLBACK?
2439 **
2440 ** Invoke the given callback every N virtual machine opcodes while executing
2441 ** queries.
2442 */
2443 case DB_PROGRESS: {
2444 if( objc==2 ){
2445 if( pDb->zProgress ){
2446 Tcl_AppendResult(interp, pDb->zProgress, 0);
2447 }
2448 }else if( objc==4 ){
2449 char *zProgress;
2450 int len;
2451 int N;
2452 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002453 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002454 };
2455 if( pDb->zProgress ){
2456 Tcl_Free(pDb->zProgress);
2457 }
2458 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2459 if( zProgress && len>0 ){
2460 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002461 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002462 }else{
2463 pDb->zProgress = 0;
2464 }
2465#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2466 if( pDb->zProgress ){
2467 pDb->interp = interp;
2468 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2469 }else{
2470 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2471 }
2472#endif
2473 }else{
2474 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002475 return TCL_ERROR;
2476 }
drh5d9d7572003-08-19 14:31:01 +00002477 break;
2478 }
2479
drh19e2d372005-08-29 23:00:03 +00002480 /* $db profile ?CALLBACK?
2481 **
2482 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2483 ** that has run. The text of the SQL and the amount of elapse time are
2484 ** appended to CALLBACK before the script is run.
2485 */
2486 case DB_PROFILE: {
2487 if( objc>3 ){
2488 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2489 return TCL_ERROR;
2490 }else if( objc==2 ){
2491 if( pDb->zProfile ){
2492 Tcl_AppendResult(interp, pDb->zProfile, 0);
2493 }
2494 }else{
2495 char *zProfile;
2496 int len;
2497 if( pDb->zProfile ){
2498 Tcl_Free(pDb->zProfile);
2499 }
2500 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2501 if( zProfile && len>0 ){
2502 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002503 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002504 }else{
2505 pDb->zProfile = 0;
2506 }
shanehbb201342011-02-09 19:55:20 +00002507#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh19e2d372005-08-29 23:00:03 +00002508 if( pDb->zProfile ){
2509 pDb->interp = interp;
2510 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2511 }else{
2512 sqlite3_profile(pDb->db, 0, 0);
2513 }
2514#endif
2515 }
2516 break;
2517 }
2518
drh5d9d7572003-08-19 14:31:01 +00002519 /*
drh22fbcb82004-02-01 01:22:50 +00002520 ** $db rekey KEY
2521 **
2522 ** Change the encryption key on the currently open database.
2523 */
2524 case DB_REKEY: {
drhb07028f2011-10-14 21:49:18 +00002525#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002526 int nKey;
2527 void *pKey;
drhb07028f2011-10-14 21:49:18 +00002528#endif
drh22fbcb82004-02-01 01:22:50 +00002529 if( objc!=3 ){
2530 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2531 return TCL_ERROR;
2532 }
drh9eb9e262004-02-11 02:18:05 +00002533#ifdef SQLITE_HAS_CODEC
drhb07028f2011-10-14 21:49:18 +00002534 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh2011d5f2004-07-22 02:40:37 +00002535 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002536 if( rc ){
mistachkin5dac8432012-09-11 02:00:25 +00002537 Tcl_AppendResult(interp, sqlite3_errstr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002538 rc = TCL_ERROR;
2539 }
2540#endif
2541 break;
2542 }
2543
drhdc2c4912009-02-04 22:46:47 +00002544 /* $db restore ?DATABASE? FILENAME
2545 **
2546 ** Open a database file named FILENAME. Transfer the content
2547 ** of FILENAME into the local database DATABASE (default: "main").
2548 */
2549 case DB_RESTORE: {
2550 const char *zSrcFile;
2551 const char *zDestDb;
2552 sqlite3 *pSrc;
2553 sqlite3_backup *pBackup;
2554 int nTimeout = 0;
2555
2556 if( objc==3 ){
2557 zDestDb = "main";
2558 zSrcFile = Tcl_GetString(objv[2]);
2559 }else if( objc==4 ){
2560 zDestDb = Tcl_GetString(objv[2]);
2561 zSrcFile = Tcl_GetString(objv[3]);
2562 }else{
2563 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2564 return TCL_ERROR;
2565 }
2566 rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
2567 if( rc!=SQLITE_OK ){
2568 Tcl_AppendResult(interp, "cannot open source database: ",
2569 sqlite3_errmsg(pSrc), (char*)0);
2570 sqlite3_close(pSrc);
2571 return TCL_ERROR;
2572 }
2573 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2574 if( pBackup==0 ){
2575 Tcl_AppendResult(interp, "restore failed: ",
2576 sqlite3_errmsg(pDb->db), (char*)0);
2577 sqlite3_close(pSrc);
2578 return TCL_ERROR;
2579 }
2580 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2581 || rc==SQLITE_BUSY ){
2582 if( rc==SQLITE_BUSY ){
2583 if( nTimeout++ >= 3 ) break;
2584 sqlite3_sleep(100);
2585 }
2586 }
2587 sqlite3_backup_finish(pBackup);
2588 if( rc==SQLITE_DONE ){
2589 rc = TCL_OK;
2590 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2591 Tcl_AppendResult(interp, "restore failed: source database busy",
2592 (char*)0);
2593 rc = TCL_ERROR;
2594 }else{
2595 Tcl_AppendResult(interp, "restore failed: ",
2596 sqlite3_errmsg(pDb->db), (char*)0);
2597 rc = TCL_ERROR;
2598 }
2599 sqlite3_close(pSrc);
2600 break;
2601 }
2602
drh22fbcb82004-02-01 01:22:50 +00002603 /*
drh3c379b02010-04-07 19:31:59 +00002604 ** $db status (step|sort|autoindex)
drhd1d38482008-10-07 23:46:38 +00002605 **
2606 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2607 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2608 */
2609 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002610 int v;
2611 const char *zOp;
2612 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00002613 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00002614 return TCL_ERROR;
2615 }
2616 zOp = Tcl_GetString(objv[2]);
2617 if( strcmp(zOp, "step")==0 ){
2618 v = pDb->nStep;
2619 }else if( strcmp(zOp, "sort")==0 ){
2620 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002621 }else if( strcmp(zOp, "autoindex")==0 ){
2622 v = pDb->nIndex;
drhd1d38482008-10-07 23:46:38 +00002623 }else{
drh3c379b02010-04-07 19:31:59 +00002624 Tcl_AppendResult(interp,
2625 "bad argument: should be autoindex, step, or sort",
drhd1d38482008-10-07 23:46:38 +00002626 (char*)0);
2627 return TCL_ERROR;
2628 }
2629 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2630 break;
2631 }
2632
2633 /*
drhbec3f402000-08-04 13:49:02 +00002634 ** $db timeout MILLESECONDS
2635 **
2636 ** Delay for the number of milliseconds specified when a file is locked.
2637 */
drh6d313162000-09-21 13:01:35 +00002638 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002639 int ms;
drh6d313162000-09-21 13:01:35 +00002640 if( objc!=3 ){
2641 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002642 return TCL_ERROR;
2643 }
drh6d313162000-09-21 13:01:35 +00002644 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002645 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002646 break;
drh75897232000-05-29 14:26:00 +00002647 }
danielk197755c45f22005-04-03 23:54:43 +00002648
2649 /*
drh0f14e2e2004-06-29 12:39:08 +00002650 ** $db total_changes
2651 **
2652 ** Return the number of rows that were modified, inserted, or deleted
2653 ** since the database handle was created.
2654 */
2655 case DB_TOTAL_CHANGES: {
2656 Tcl_Obj *pResult;
2657 if( objc!=2 ){
2658 Tcl_WrongNumArgs(interp, 2, objv, "");
2659 return TCL_ERROR;
2660 }
2661 pResult = Tcl_GetObjResult(interp);
2662 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2663 break;
2664 }
2665
drhb5a20d32003-04-23 12:25:23 +00002666 /* $db trace ?CALLBACK?
2667 **
2668 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2669 ** that is executed. The text of the SQL is appended to CALLBACK before
2670 ** it is executed.
2671 */
2672 case DB_TRACE: {
2673 if( objc>3 ){
2674 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002675 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002676 }else if( objc==2 ){
2677 if( pDb->zTrace ){
2678 Tcl_AppendResult(interp, pDb->zTrace, 0);
2679 }
2680 }else{
2681 char *zTrace;
2682 int len;
2683 if( pDb->zTrace ){
2684 Tcl_Free(pDb->zTrace);
2685 }
2686 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2687 if( zTrace && len>0 ){
2688 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002689 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002690 }else{
2691 pDb->zTrace = 0;
2692 }
shanehbb201342011-02-09 19:55:20 +00002693#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drhb5a20d32003-04-23 12:25:23 +00002694 if( pDb->zTrace ){
2695 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002696 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002697 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002698 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002699 }
drh19e2d372005-08-29 23:00:03 +00002700#endif
drhb5a20d32003-04-23 12:25:23 +00002701 }
2702 break;
2703 }
2704
drh3d214232005-08-02 12:21:08 +00002705 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2706 **
2707 ** Start a new transaction (if we are not already in the midst of a
2708 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2709 ** completes, either commit the transaction or roll it back if SCRIPT
2710 ** throws an exception. Or if no new transation was started, do nothing.
2711 ** pass the exception on up the stack.
2712 **
2713 ** This command was inspired by Dave Thomas's talk on Ruby at the
2714 ** 2005 O'Reilly Open Source Convention (OSCON).
2715 */
2716 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00002717 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00002718 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00002719 if( objc!=3 && objc!=4 ){
2720 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2721 return TCL_ERROR;
2722 }
danielk1977cd38d522009-01-02 17:33:46 +00002723
dan4a4c11a2009-10-06 14:59:02 +00002724 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00002725 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002726 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002727 };
2728 enum TTYPE_enum {
2729 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2730 };
2731 int ttype;
drhb5555e72005-08-02 17:15:14 +00002732 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002733 0, &ttype) ){
2734 return TCL_ERROR;
2735 }
2736 switch( (enum TTYPE_enum)ttype ){
2737 case TTYPE_DEFERRED: /* no-op */; break;
2738 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2739 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2740 }
drh3d214232005-08-02 12:21:08 +00002741 }
danielk1977cd38d522009-01-02 17:33:46 +00002742 pScript = objv[objc-1];
2743
dan4a4c11a2009-10-06 14:59:02 +00002744 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00002745 pDb->disableAuth++;
2746 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2747 pDb->disableAuth--;
2748 if( rc!=SQLITE_OK ){
2749 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2750 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00002751 }
danielk1977cd38d522009-01-02 17:33:46 +00002752 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00002753
dan4a4c11a2009-10-06 14:59:02 +00002754 /* If using NRE, schedule a callback to invoke the script pScript, then
2755 ** a second callback to commit (or rollback) the transaction or savepoint
2756 ** opened above. If not using NRE, evaluate the script directly, then
2757 ** call function DbTransPostCmd() to commit (or rollback) the transaction
2758 ** or savepoint. */
2759 if( DbUseNre() ){
2760 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
2761 Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00002762 }else{
dan4a4c11a2009-10-06 14:59:02 +00002763 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00002764 }
2765 break;
2766 }
2767
danielk197794eb6a12005-12-15 15:22:08 +00002768 /*
danielk1977404ca072009-03-16 13:19:36 +00002769 ** $db unlock_notify ?script?
2770 */
2771 case DB_UNLOCK_NOTIFY: {
2772#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2773 Tcl_AppendResult(interp, "unlock_notify not available in this build", 0);
2774 rc = TCL_ERROR;
2775#else
2776 if( objc!=2 && objc!=3 ){
2777 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2778 rc = TCL_ERROR;
2779 }else{
2780 void (*xNotify)(void **, int) = 0;
2781 void *pNotifyArg = 0;
2782
2783 if( pDb->pUnlockNotify ){
2784 Tcl_DecrRefCount(pDb->pUnlockNotify);
2785 pDb->pUnlockNotify = 0;
2786 }
2787
2788 if( objc==3 ){
2789 xNotify = DbUnlockNotify;
2790 pNotifyArg = (void *)pDb;
2791 pDb->pUnlockNotify = objv[2];
2792 Tcl_IncrRefCount(pDb->pUnlockNotify);
2793 }
2794
2795 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
2796 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2797 rc = TCL_ERROR;
2798 }
2799 }
2800#endif
2801 break;
2802 }
2803
2804 /*
drh833bf962010-04-28 14:42:19 +00002805 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002806 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002807 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002808 */
drh833bf962010-04-28 14:42:19 +00002809 case DB_WAL_HOOK:
danielk197771fd80b2005-12-16 06:54:01 +00002810 case DB_UPDATE_HOOK:
2811 case DB_ROLLBACK_HOOK: {
2812
2813 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2814 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2815 */
2816 Tcl_Obj **ppHook;
2817 if( choice==DB_UPDATE_HOOK ){
2818 ppHook = &pDb->pUpdateHook;
drh833bf962010-04-28 14:42:19 +00002819 }else if( choice==DB_WAL_HOOK ){
drh5def0842010-05-05 20:00:25 +00002820 ppHook = &pDb->pWalHook;
danielk197771fd80b2005-12-16 06:54:01 +00002821 }else{
2822 ppHook = &pDb->pRollbackHook;
2823 }
2824
danielk197794eb6a12005-12-15 15:22:08 +00002825 if( objc!=2 && objc!=3 ){
2826 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2827 return TCL_ERROR;
2828 }
danielk197771fd80b2005-12-16 06:54:01 +00002829 if( *ppHook ){
2830 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002831 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002832 Tcl_DecrRefCount(*ppHook);
2833 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00002834 }
2835 }
2836 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002837 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00002838 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00002839 *ppHook = objv[2];
2840 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002841 }
2842 }
danielk197771fd80b2005-12-16 06:54:01 +00002843
2844 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2845 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
drh5def0842010-05-05 20:00:25 +00002846 sqlite3_wal_hook(pDb->db,(pDb->pWalHook?DbWalHandler:0),pDb);
danielk197771fd80b2005-12-16 06:54:01 +00002847
danielk197794eb6a12005-12-15 15:22:08 +00002848 break;
2849 }
2850
danielk19774397de52005-01-12 12:44:03 +00002851 /* $db version
2852 **
2853 ** Return the version string for this database.
2854 */
2855 case DB_VERSION: {
2856 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2857 break;
2858 }
2859
tpoindex1067fe12004-12-17 15:41:11 +00002860
drh6d313162000-09-21 13:01:35 +00002861 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002862 return rc;
drh75897232000-05-29 14:26:00 +00002863}
2864
drha2c8a952009-10-13 18:38:34 +00002865#if SQLITE_TCL_NRE
2866/*
2867** Adaptor that provides an objCmd interface to the NRE-enabled
2868** interface implementation.
2869*/
2870static int DbObjCmdAdaptor(
2871 void *cd,
2872 Tcl_Interp *interp,
2873 int objc,
2874 Tcl_Obj *const*objv
2875){
2876 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
2877}
2878#endif /* SQLITE_TCL_NRE */
2879
drh75897232000-05-29 14:26:00 +00002880/*
drh3570ad92007-08-31 14:31:44 +00002881** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00002882** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00002883**
2884** This is the main Tcl command. When the "sqlite" Tcl command is
2885** invoked, this routine runs to process that command.
2886**
2887** The first argument, DBNAME, is an arbitrary name for a new
2888** database connection. This command creates a new command named
2889** DBNAME that is used to control that connection. The database
2890** connection is deleted when the DBNAME command is deleted.
2891**
drh3570ad92007-08-31 14:31:44 +00002892** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00002893**
drh75897232000-05-29 14:26:00 +00002894*/
drh22fbcb82004-02-01 01:22:50 +00002895static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002896 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002897 const char *zArg;
drh75897232000-05-29 14:26:00 +00002898 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00002899 int i;
drh22fbcb82004-02-01 01:22:50 +00002900 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00002901 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00002902 int flags;
drh882e8e42006-08-24 02:42:27 +00002903 Tcl_DString translatedFilename;
drhb07028f2011-10-14 21:49:18 +00002904#ifdef SQLITE_HAS_CODEC
2905 void *pKey = 0;
2906 int nKey = 0;
2907#endif
mistachkin540ebf82012-09-10 07:29:29 +00002908 int rc;
drhd9da78a2009-03-24 15:08:09 +00002909
2910 /* In normal use, each TCL interpreter runs in a single thread. So
2911 ** by default, we can turn of mutexing on SQLite database connections.
2912 ** However, for testing purposes it is useful to have mutexes turned
2913 ** on. So, by default, mutexes default off. But if compiled with
2914 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
2915 */
2916#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
2917 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
2918#else
2919 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
2920#endif
2921
drh22fbcb82004-02-01 01:22:50 +00002922 if( objc==2 ){
2923 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002924 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00002925 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00002926 return TCL_OK;
2927 }
drh9eb9e262004-02-11 02:18:05 +00002928 if( strcmp(zArg,"-has-codec")==0 ){
2929#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002930 Tcl_AppendResult(interp,"1",0);
2931#else
2932 Tcl_AppendResult(interp,"0",0);
2933#endif
2934 return TCL_OK;
2935 }
drhfbc3eab2001-04-06 16:13:42 +00002936 }
drh3570ad92007-08-31 14:31:44 +00002937 for(i=3; i+1<objc; i+=2){
2938 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00002939 if( strcmp(zArg,"-key")==0 ){
drhb07028f2011-10-14 21:49:18 +00002940#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00002941 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
drhb07028f2011-10-14 21:49:18 +00002942#endif
drh3570ad92007-08-31 14:31:44 +00002943 }else if( strcmp(zArg, "-vfs")==0 ){
dan3c3dd7b2010-06-22 11:10:40 +00002944 zVfs = Tcl_GetString(objv[i+1]);
drh3570ad92007-08-31 14:31:44 +00002945 }else if( strcmp(zArg, "-readonly")==0 ){
2946 int b;
2947 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2948 if( b ){
drh33f4e022007-09-03 15:19:34 +00002949 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00002950 flags |= SQLITE_OPEN_READONLY;
2951 }else{
2952 flags &= ~SQLITE_OPEN_READONLY;
2953 flags |= SQLITE_OPEN_READWRITE;
2954 }
2955 }else if( strcmp(zArg, "-create")==0 ){
2956 int b;
2957 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00002958 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00002959 flags |= SQLITE_OPEN_CREATE;
2960 }else{
2961 flags &= ~SQLITE_OPEN_CREATE;
2962 }
danielk19779a6284c2008-07-10 17:52:49 +00002963 }else if( strcmp(zArg, "-nomutex")==0 ){
2964 int b;
2965 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2966 if( b ){
2967 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00002968 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00002969 }else{
2970 flags &= ~SQLITE_OPEN_NOMUTEX;
2971 }
danc431fd52011-06-27 16:55:50 +00002972 }else if( strcmp(zArg, "-fullmutex")==0 ){
drh039963a2008-09-03 00:43:15 +00002973 int b;
2974 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2975 if( b ){
2976 flags |= SQLITE_OPEN_FULLMUTEX;
2977 flags &= ~SQLITE_OPEN_NOMUTEX;
2978 }else{
2979 flags &= ~SQLITE_OPEN_FULLMUTEX;
2980 }
drhf12b3f62011-12-21 14:42:29 +00002981 }else if( strcmp(zArg, "-uri")==0 ){
2982 int b;
2983 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2984 if( b ){
2985 flags |= SQLITE_OPEN_URI;
2986 }else{
2987 flags &= ~SQLITE_OPEN_URI;
2988 }
drh3570ad92007-08-31 14:31:44 +00002989 }else{
2990 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
2991 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00002992 }
2993 }
drh3570ad92007-08-31 14:31:44 +00002994 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00002995 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00002996 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh68bd4aa2012-01-13 16:16:10 +00002997 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
drh9eb9e262004-02-11 02:18:05 +00002998#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00002999 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00003000#endif
3001 );
drh75897232000-05-29 14:26:00 +00003002 return TCL_ERROR;
3003 }
drh75897232000-05-29 14:26:00 +00003004 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003005 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00003006 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00003007 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
3008 return TCL_ERROR;
3009 }
3010 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00003011 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00003012 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003013 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00003014 Tcl_DStringFree(&translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003015 if( p->db ){
3016 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3017 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3018 sqlite3_close(p->db);
3019 p->db = 0;
3020 }
3021 }else{
mistachkin5dac8432012-09-11 02:00:25 +00003022 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
danielk197780290862004-05-22 09:21:21 +00003023 }
drh2011d5f2004-07-22 02:40:37 +00003024#ifdef SQLITE_HAS_CODEC
drhf3a65f72007-08-22 20:18:21 +00003025 if( p->db ){
3026 sqlite3_key(p->db, pKey, nKey);
3027 }
drheb8ed702004-02-11 10:37:23 +00003028#endif
drhbec3f402000-08-04 13:49:02 +00003029 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003030 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003031 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003032 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003033 return TCL_ERROR;
3034 }
drhfb7e7652005-01-24 00:28:42 +00003035 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00003036 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003037 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003038 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003039 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3040 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003041 }else{
3042 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3043 }
drh75897232000-05-29 14:26:00 +00003044 return TCL_OK;
3045}
3046
3047/*
drh90ca9752001-09-28 17:47:14 +00003048** Provide a dummy Tcl_InitStubs if we are using this as a static
3049** library.
3050*/
3051#ifndef USE_TCL_STUBS
3052# undef Tcl_InitStubs
3053# define Tcl_InitStubs(a,b,c)
3054#endif
3055
3056/*
drh29bc4612005-10-05 10:40:15 +00003057** Make sure we have a PACKAGE_VERSION macro defined. This will be
3058** defined automatically by the TEA makefile. But other makefiles
3059** do not define it.
3060*/
3061#ifndef PACKAGE_VERSION
3062# define PACKAGE_VERSION SQLITE_VERSION
3063#endif
3064
3065/*
drh75897232000-05-29 14:26:00 +00003066** Initialize this module.
3067**
3068** This Tcl module contains only a single new Tcl command named "sqlite".
3069** (Hence there is no namespace. There is no point in using a namespace
3070** if the extension only supplies one new name!) The "sqlite" command is
3071** used to open a new SQLite database. See the DbMain() routine above
3072** for additional information.
drhb652f432010-08-26 16:46:57 +00003073**
3074** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003075*/
drhb652f432010-08-26 16:46:57 +00003076EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00003077 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00003078 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00003079 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh1cca0d22010-08-25 20:35:51 +00003080
3081#ifndef SQLITE_3_SUFFIX_ONLY
3082 /* The "sqlite" alias is undocumented. It is here only to support
3083 ** legacy scripts. All new scripts should use only the "sqlite3"
3084 ** command.
3085 */
drh49766d62005-01-08 18:42:28 +00003086 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003087#endif
drh1cca0d22010-08-25 20:35:51 +00003088
drh90ca9752001-09-28 17:47:14 +00003089 return TCL_OK;
3090}
drhb652f432010-08-26 16:46:57 +00003091EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
drhb652f432010-08-26 16:46:57 +00003092EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3093EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00003094
drhd878cab2012-03-20 15:10:42 +00003095/* Because it accesses the file-system and uses persistent state, SQLite
3096** is not considered appropriate for safe interpreters. Hence, we deliberately
3097** omit the _SafeInit() interfaces.
3098*/
drh49766d62005-01-08 18:42:28 +00003099
3100#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003101int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3102int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
dana3e63c42010-08-20 12:33:59 +00003103int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3104int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00003105#endif
drh75897232000-05-29 14:26:00 +00003106
drh3e27c022004-07-23 00:01:38 +00003107#ifdef TCLSH
3108/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003109** All of the code that follows is used to build standalone TCL interpreters
3110** that are statically linked with SQLite. Enable these by compiling
3111** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3112** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3113** analysis program.
drh75897232000-05-29 14:26:00 +00003114*/
drh348784e2000-05-29 20:41:49 +00003115
drh57a02272009-10-22 20:52:05 +00003116#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3117/*
3118 * This code implements the MD5 message-digest algorithm.
3119 * The algorithm is due to Ron Rivest. This code was
3120 * written by Colin Plumb in 1993, no copyright is claimed.
3121 * This code is in the public domain; do with it what you wish.
3122 *
3123 * Equivalent code is available from RSA Data Security, Inc.
3124 * This code has been tested against that, and is equivalent,
3125 * except that you don't need to include two pages of legalese
3126 * with every copy.
3127 *
3128 * To compute the message digest of a chunk of bytes, declare an
3129 * MD5Context structure, pass it to MD5Init, call MD5Update as
3130 * needed on buffers full of bytes, and then call MD5Final, which
3131 * will fill a supplied 16-byte array with the digest.
3132 */
3133
3134/*
3135 * If compiled on a machine that doesn't have a 32-bit integer,
3136 * you just set "uint32" to the appropriate datatype for an
3137 * unsigned 32-bit integer. For example:
3138 *
3139 * cc -Duint32='unsigned long' md5.c
3140 *
3141 */
3142#ifndef uint32
3143# define uint32 unsigned int
3144#endif
3145
3146struct MD5Context {
3147 int isInit;
3148 uint32 buf[4];
3149 uint32 bits[2];
3150 unsigned char in[64];
3151};
3152typedef struct MD5Context MD5Context;
3153
3154/*
3155 * Note: this code is harmless on little-endian machines.
3156 */
3157static void byteReverse (unsigned char *buf, unsigned longs){
3158 uint32 t;
3159 do {
3160 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3161 ((unsigned)buf[1]<<8 | buf[0]);
3162 *(uint32 *)buf = t;
3163 buf += 4;
3164 } while (--longs);
3165}
3166/* The four core functions - F1 is optimized somewhat */
3167
3168/* #define F1(x, y, z) (x & y | ~x & z) */
3169#define F1(x, y, z) (z ^ (x & (y ^ z)))
3170#define F2(x, y, z) F1(z, x, y)
3171#define F3(x, y, z) (x ^ y ^ z)
3172#define F4(x, y, z) (y ^ (x | ~z))
3173
3174/* This is the central step in the MD5 algorithm. */
3175#define MD5STEP(f, w, x, y, z, data, s) \
3176 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3177
3178/*
3179 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3180 * reflect the addition of 16 longwords of new data. MD5Update blocks
3181 * the data and converts bytes into longwords for this routine.
3182 */
3183static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3184 register uint32 a, b, c, d;
3185
3186 a = buf[0];
3187 b = buf[1];
3188 c = buf[2];
3189 d = buf[3];
3190
3191 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3192 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3193 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3194 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3195 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3196 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3197 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3198 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3199 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3200 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3201 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3202 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3203 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3204 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3205 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3206 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3207
3208 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3209 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3210 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3211 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3212 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3213 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3214 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3215 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3216 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3217 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3218 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3219 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3220 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3221 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3222 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3223 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3224
3225 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3226 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3227 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3228 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3229 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3230 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3231 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3232 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3233 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3234 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3235 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3236 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3237 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3238 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3239 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3240 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3241
3242 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3243 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3244 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3245 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3246 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3247 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3248 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3249 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3250 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3251 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3252 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3253 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3254 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3255 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3256 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3257 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3258
3259 buf[0] += a;
3260 buf[1] += b;
3261 buf[2] += c;
3262 buf[3] += d;
3263}
3264
3265/*
3266 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3267 * initialization constants.
3268 */
3269static void MD5Init(MD5Context *ctx){
3270 ctx->isInit = 1;
3271 ctx->buf[0] = 0x67452301;
3272 ctx->buf[1] = 0xefcdab89;
3273 ctx->buf[2] = 0x98badcfe;
3274 ctx->buf[3] = 0x10325476;
3275 ctx->bits[0] = 0;
3276 ctx->bits[1] = 0;
3277}
3278
3279/*
3280 * Update context to reflect the concatenation of another buffer full
3281 * of bytes.
3282 */
3283static
3284void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3285 uint32 t;
3286
3287 /* Update bitcount */
3288
3289 t = ctx->bits[0];
3290 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3291 ctx->bits[1]++; /* Carry from low to high */
3292 ctx->bits[1] += len >> 29;
3293
3294 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3295
3296 /* Handle any leading odd-sized chunks */
3297
3298 if ( t ) {
3299 unsigned char *p = (unsigned char *)ctx->in + t;
3300
3301 t = 64-t;
3302 if (len < t) {
3303 memcpy(p, buf, len);
3304 return;
3305 }
3306 memcpy(p, buf, t);
3307 byteReverse(ctx->in, 16);
3308 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3309 buf += t;
3310 len -= t;
3311 }
3312
3313 /* Process data in 64-byte chunks */
3314
3315 while (len >= 64) {
3316 memcpy(ctx->in, buf, 64);
3317 byteReverse(ctx->in, 16);
3318 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3319 buf += 64;
3320 len -= 64;
3321 }
3322
3323 /* Handle any remaining bytes of data. */
3324
3325 memcpy(ctx->in, buf, len);
3326}
3327
3328/*
3329 * Final wrapup - pad to 64-byte boundary with the bit pattern
3330 * 1 0* (64-bit count of bits processed, MSB-first)
3331 */
3332static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3333 unsigned count;
3334 unsigned char *p;
3335
3336 /* Compute number of bytes mod 64 */
3337 count = (ctx->bits[0] >> 3) & 0x3F;
3338
3339 /* Set the first char of padding to 0x80. This is safe since there is
3340 always at least one byte free */
3341 p = ctx->in + count;
3342 *p++ = 0x80;
3343
3344 /* Bytes of padding needed to make 64 bytes */
3345 count = 64 - 1 - count;
3346
3347 /* Pad out to 56 mod 64 */
3348 if (count < 8) {
3349 /* Two lots of padding: Pad the first block to 64 bytes */
3350 memset(p, 0, count);
3351 byteReverse(ctx->in, 16);
3352 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3353
3354 /* Now fill the next block with 56 bytes */
3355 memset(ctx->in, 0, 56);
3356 } else {
3357 /* Pad block to 56 bytes */
3358 memset(p, 0, count-8);
3359 }
3360 byteReverse(ctx->in, 14);
3361
3362 /* Append length in bits and transform */
3363 ((uint32 *)ctx->in)[ 14 ] = ctx->bits[0];
3364 ((uint32 *)ctx->in)[ 15 ] = ctx->bits[1];
3365
3366 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3367 byteReverse((unsigned char *)ctx->buf, 4);
3368 memcpy(digest, ctx->buf, 16);
3369 memset(ctx, 0, sizeof(ctx)); /* In case it is sensitive */
3370}
3371
3372/*
3373** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3374*/
3375static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3376 static char const zEncode[] = "0123456789abcdef";
3377 int i, j;
3378
3379 for(j=i=0; i<16; i++){
3380 int a = digest[i];
3381 zBuf[j++] = zEncode[(a>>4)&0xf];
3382 zBuf[j++] = zEncode[a & 0xf];
3383 }
3384 zBuf[j] = 0;
3385}
3386
3387
3388/*
3389** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3390** each representing 16 bits of the digest and separated from each
3391** other by a "-" character.
3392*/
3393static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3394 int i, j;
3395 unsigned int x;
3396 for(i=j=0; i<16; i+=2){
3397 x = digest[i]*256 + digest[i+1];
3398 if( i>0 ) zDigest[j++] = '-';
3399 sprintf(&zDigest[j], "%05u", x);
3400 j += 5;
3401 }
3402 zDigest[j] = 0;
3403}
3404
3405/*
3406** A TCL command for md5. The argument is the text to be hashed. The
3407** Result is the hash in base64.
3408*/
3409static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3410 MD5Context ctx;
3411 unsigned char digest[16];
3412 char zBuf[50];
3413 void (*converter)(unsigned char*, char*);
3414
3415 if( argc!=2 ){
3416 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3417 " TEXT\"", 0);
3418 return TCL_ERROR;
3419 }
3420 MD5Init(&ctx);
3421 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3422 MD5Final(digest, &ctx);
3423 converter = (void(*)(unsigned char*,char*))cd;
3424 converter(digest, zBuf);
3425 Tcl_AppendResult(interp, zBuf, (char*)0);
3426 return TCL_OK;
3427}
3428
3429/*
3430** A TCL command to take the md5 hash of a file. The argument is the
3431** name of the file.
3432*/
3433static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3434 FILE *in;
3435 MD5Context ctx;
3436 void (*converter)(unsigned char*, char*);
3437 unsigned char digest[16];
3438 char zBuf[10240];
3439
3440 if( argc!=2 ){
3441 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3442 " FILENAME\"", 0);
3443 return TCL_ERROR;
3444 }
3445 in = fopen(argv[1],"rb");
3446 if( in==0 ){
3447 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
3448 "\" for reading", 0);
3449 return TCL_ERROR;
3450 }
3451 MD5Init(&ctx);
3452 for(;;){
3453 int n;
drh83cc1392012-04-19 18:04:28 +00003454 n = (int)fread(zBuf, 1, sizeof(zBuf), in);
drh57a02272009-10-22 20:52:05 +00003455 if( n<=0 ) break;
3456 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3457 }
3458 fclose(in);
3459 MD5Final(digest, &ctx);
3460 converter = (void(*)(unsigned char*,char*))cd;
3461 converter(digest, zBuf);
3462 Tcl_AppendResult(interp, zBuf, (char*)0);
3463 return TCL_OK;
3464}
3465
3466/*
3467** Register the four new TCL commands for generating MD5 checksums
3468** with the TCL interpreter.
3469*/
3470int Md5_Init(Tcl_Interp *interp){
3471 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3472 MD5DigestToBase16, 0);
3473 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3474 MD5DigestToBase10x8, 0);
3475 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3476 MD5DigestToBase16, 0);
3477 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3478 MD5DigestToBase10x8, 0);
3479 return TCL_OK;
3480}
3481#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3482
3483#if defined(SQLITE_TEST)
3484/*
3485** During testing, the special md5sum() aggregate function is available.
3486** inside SQLite. The following routines implement that function.
3487*/
3488static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3489 MD5Context *p;
3490 int i;
3491 if( argc<1 ) return;
3492 p = sqlite3_aggregate_context(context, sizeof(*p));
3493 if( p==0 ) return;
3494 if( !p->isInit ){
3495 MD5Init(p);
3496 }
3497 for(i=0; i<argc; i++){
3498 const char *zData = (char*)sqlite3_value_text(argv[i]);
3499 if( zData ){
drh83cc1392012-04-19 18:04:28 +00003500 MD5Update(p, (unsigned char*)zData, (int)strlen(zData));
drh57a02272009-10-22 20:52:05 +00003501 }
3502 }
3503}
3504static void md5finalize(sqlite3_context *context){
3505 MD5Context *p;
3506 unsigned char digest[16];
3507 char zBuf[33];
3508 p = sqlite3_aggregate_context(context, sizeof(*p));
3509 MD5Final(digest,p);
3510 MD5DigestToBase16(digest, zBuf);
3511 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3512}
3513int Md5_Register(sqlite3 *db){
3514 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
3515 md5step, md5finalize);
3516 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3517 return rc;
3518}
3519#endif /* defined(SQLITE_TEST) */
3520
3521
drh348784e2000-05-29 20:41:49 +00003522/*
drh3e27c022004-07-23 00:01:38 +00003523** If the macro TCLSH is one, then put in code this for the
3524** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003525** standard input, or if a file is named on the command line
3526** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003527*/
drh3e27c022004-07-23 00:01:38 +00003528#if TCLSH==1
dan0ae479d2011-09-21 16:43:07 +00003529static const char *tclsh_main_loop(void){
3530 static const char zMainloop[] =
3531 "set line {}\n"
3532 "while {![eof stdin]} {\n"
3533 "if {$line!=\"\"} {\n"
3534 "puts -nonewline \"> \"\n"
3535 "} else {\n"
3536 "puts -nonewline \"% \"\n"
drh348784e2000-05-29 20:41:49 +00003537 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003538 "flush stdout\n"
3539 "append line [gets stdin]\n"
3540 "if {[info complete $line]} {\n"
3541 "if {[catch {uplevel #0 $line} result]} {\n"
3542 "puts stderr \"Error: $result\"\n"
3543 "} elseif {$result!=\"\"} {\n"
3544 "puts $result\n"
3545 "}\n"
3546 "set line {}\n"
3547 "} else {\n"
3548 "append line \\n\n"
3549 "}\n"
drh348784e2000-05-29 20:41:49 +00003550 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003551 ;
3552 return zMainloop;
3553}
drh3e27c022004-07-23 00:01:38 +00003554#endif
drh3a0f13f2010-07-12 16:47:48 +00003555#if TCLSH==2
dan0ae479d2011-09-21 16:43:07 +00003556static const char *tclsh_main_loop(void);
drh3a0f13f2010-07-12 16:47:48 +00003557#endif
drh3e27c022004-07-23 00:01:38 +00003558
danc1a60c52010-06-07 14:28:16 +00003559#ifdef SQLITE_TEST
3560static void init_all(Tcl_Interp *);
3561static int init_all_cmd(
3562 ClientData cd,
3563 Tcl_Interp *interp,
3564 int objc,
3565 Tcl_Obj *CONST objv[]
3566){
danielk19770a549072009-02-17 16:29:10 +00003567
danc1a60c52010-06-07 14:28:16 +00003568 Tcl_Interp *slave;
3569 if( objc!=2 ){
3570 Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3571 return TCL_ERROR;
3572 }
3573
3574 slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3575 if( !slave ){
3576 return TCL_ERROR;
3577 }
3578
3579 init_all(slave);
3580 return TCL_OK;
3581}
danc431fd52011-06-27 16:55:50 +00003582
3583/*
3584** Tclcmd: db_use_legacy_prepare DB BOOLEAN
3585**
3586** The first argument to this command must be a database command created by
3587** [sqlite3]. If the second argument is true, then the handle is configured
3588** to use the sqlite3_prepare_v2() function to prepare statements. If it
3589** is false, sqlite3_prepare().
3590*/
3591static int db_use_legacy_prepare_cmd(
3592 ClientData cd,
3593 Tcl_Interp *interp,
3594 int objc,
3595 Tcl_Obj *CONST objv[]
3596){
3597 Tcl_CmdInfo cmdInfo;
3598 SqliteDb *pDb;
3599 int bPrepare;
3600
3601 if( objc!=3 ){
3602 Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
3603 return TCL_ERROR;
3604 }
3605
3606 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3607 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3608 return TCL_ERROR;
3609 }
3610 pDb = (SqliteDb*)cmdInfo.objClientData;
3611 if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
3612 return TCL_ERROR;
3613 }
3614
3615 pDb->bLegacyPrepare = bPrepare;
3616
3617 Tcl_ResetResult(interp);
3618 return TCL_OK;
3619}
danc1a60c52010-06-07 14:28:16 +00003620#endif
3621
3622/*
3623** Configure the interpreter passed as the first argument to have access
3624** to the commands and linked variables that make up:
3625**
3626** * the [sqlite3] extension itself,
3627**
3628** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
3629**
3630** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
3631** test suite.
3632*/
3633static void init_all(Tcl_Interp *interp){
drh38f82712004-06-18 17:10:16 +00003634 Sqlite3_Init(interp);
danc1a60c52010-06-07 14:28:16 +00003635
drh57a02272009-10-22 20:52:05 +00003636#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3637 Md5_Init(interp);
3638#endif
danc1a60c52010-06-07 14:28:16 +00003639
dan0ae479d2011-09-21 16:43:07 +00003640 /* Install the [register_dbstat_vtab] command to access the implementation
3641 ** of virtual table dbstat (source file test_stat.c). This command is
3642 ** required for testfixture and sqlite3_analyzer, but not by the production
3643 ** Tcl extension. */
3644#if defined(SQLITE_TEST) || TCLSH==2
3645 {
3646 extern int SqlitetestStat_Init(Tcl_Interp*);
3647 SqlitetestStat_Init(interp);
3648 }
3649#endif
3650
drhd9b02572001-04-15 00:37:09 +00003651#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00003652 {
drh2f999a62007-08-15 19:16:43 +00003653 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00003654 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00003655 extern int Sqlitetest2_Init(Tcl_Interp*);
3656 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00003657 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00003658 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00003659 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00003660 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00003661 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00003662 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00003663 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00003664 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
dan0a7a9152010-04-07 07:57:38 +00003665 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
drh984bfaa2008-03-19 16:08:53 +00003666 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00003667 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00003668 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003669 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00003670 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003671 extern int Sqlitetestschema_Init(Tcl_Interp*);
3672 extern int Sqlitetestsse_Init(Tcl_Interp*);
3673 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
dan9f5ff372013-01-11 09:58:54 +00003674 extern int Sqlitetestfs_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00003675 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00003676 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00003677 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00003678 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh522efc62009-11-10 17:24:37 +00003679 extern int Sqlitetestintarray_Init(Tcl_Interp*);
danc7991bd2010-05-05 19:04:59 +00003680 extern int Sqlitetestvfs_Init(Tcl_Interp *);
dan9508daa2010-08-28 18:58:00 +00003681 extern int Sqlitetestrtree_Init(Tcl_Interp*);
dan8cf35eb2010-09-01 11:40:05 +00003682 extern int Sqlitequota_Init(Tcl_Interp*);
shaneh8a922f72010-11-04 20:50:27 +00003683 extern int Sqlitemultiplex_Init(Tcl_Interp*);
dane336b002010-11-19 18:20:09 +00003684 extern int SqliteSuperlock_Init(Tcl_Interp*);
dan213ca0a2011-03-28 19:10:06 +00003685 extern int SqlitetestSyscall_Init(Tcl_Interp*);
drh326a67d2011-03-26 15:05:27 +00003686 extern int Sqlitetestfuzzer_Init(Tcl_Interp*);
drh70586be2011-04-01 23:49:44 +00003687 extern int Sqlitetestwholenumber_Init(Tcl_Interp*);
drh14172742012-12-31 19:18:38 +00003688 extern int Sqlitetestregexp_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00003689
dan6764a702011-06-20 11:15:06 +00003690#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00003691 extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
3692#endif
3693
danb29010c2010-12-29 18:24:38 +00003694#ifdef SQLITE_ENABLE_ZIPVFS
3695 extern int Zipvfs_Init(Tcl_Interp*);
3696 Zipvfs_Init(interp);
3697#endif
3698
drh2f999a62007-08-15 19:16:43 +00003699 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00003700 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00003701 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00003702 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00003703 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00003704 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00003705 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00003706 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00003707 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00003708 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00003709 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00003710 Sqlitetest_autoext_Init(interp);
dan0a7a9152010-04-07 07:57:38 +00003711 Sqlitetest_demovfs_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00003712 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00003713 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00003714 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003715 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00003716 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003717 Sqlitetestschema_Init(interp);
3718 Sqlitetesttclvar_Init(interp);
dan9f5ff372013-01-11 09:58:54 +00003719 Sqlitetestfs_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00003720 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003721 SqlitetestOnefile_Init(interp);
danielk19775d1f5aa2008-04-10 14:51:00 +00003722 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00003723 Sqlitetestbackup_Init(interp);
drh522efc62009-11-10 17:24:37 +00003724 Sqlitetestintarray_Init(interp);
danc7991bd2010-05-05 19:04:59 +00003725 Sqlitetestvfs_Init(interp);
dan9508daa2010-08-28 18:58:00 +00003726 Sqlitetestrtree_Init(interp);
dan8cf35eb2010-09-01 11:40:05 +00003727 Sqlitequota_Init(interp);
shaneh8a922f72010-11-04 20:50:27 +00003728 Sqlitemultiplex_Init(interp);
dane336b002010-11-19 18:20:09 +00003729 SqliteSuperlock_Init(interp);
dan213ca0a2011-03-28 19:10:06 +00003730 SqlitetestSyscall_Init(interp);
drh326a67d2011-03-26 15:05:27 +00003731 Sqlitetestfuzzer_Init(interp);
drh70586be2011-04-01 23:49:44 +00003732 Sqlitetestwholenumber_Init(interp);
drh14172742012-12-31 19:18:38 +00003733 Sqlitetestregexp_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003734
dan6764a702011-06-20 11:15:06 +00003735#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00003736 Sqlitetestfts3_Init(interp);
3737#endif
3738
danc431fd52011-06-27 16:55:50 +00003739 Tcl_CreateObjCommand(
3740 interp, "load_testfixture_extensions", init_all_cmd, 0, 0
3741 );
3742 Tcl_CreateObjCommand(
3743 interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
3744 );
danc1a60c52010-06-07 14:28:16 +00003745
drh89dec812005-04-28 19:03:37 +00003746#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00003747 Sqlitetestsse_Init(interp);
3748#endif
drhd1bf3512001-04-07 15:24:33 +00003749 }
3750#endif
danc1a60c52010-06-07 14:28:16 +00003751}
3752
3753#define TCLSH_MAIN main /* Needed to fake out mktclapp */
3754int TCLSH_MAIN(int argc, char **argv){
3755 Tcl_Interp *interp;
3756
3757 /* Call sqlite3_shutdown() once before doing anything else. This is to
3758 ** test that sqlite3_shutdown() can be safely called by a process before
3759 ** sqlite3_initialize() is. */
3760 sqlite3_shutdown();
3761
dan0ae479d2011-09-21 16:43:07 +00003762 Tcl_FindExecutable(argv[0]);
3763 interp = Tcl_CreateInterp();
3764
drh3a0f13f2010-07-12 16:47:48 +00003765#if TCLSH==2
3766 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
3767#endif
danc1a60c52010-06-07 14:28:16 +00003768
danc1a60c52010-06-07 14:28:16 +00003769 init_all(interp);
drhc7285972009-11-10 01:13:25 +00003770 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00003771 int i;
shessad42c3a2006-08-22 23:53:46 +00003772 char zArgc[32];
3773 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
3774 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00003775 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
3776 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00003777 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00003778 Tcl_SetVar(interp, "argv", argv[i],
3779 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3780 }
drh3a0f13f2010-07-12 16:47:48 +00003781 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00003782 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00003783 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00003784 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00003785 return 1;
3786 }
drh3e27c022004-07-23 00:01:38 +00003787 }
drh3a0f13f2010-07-12 16:47:48 +00003788 if( TCLSH==2 || argc<=1 ){
dan0ae479d2011-09-21 16:43:07 +00003789 Tcl_GlobalEval(interp, tclsh_main_loop());
drh348784e2000-05-29 20:41:49 +00003790 }
3791 return 0;
3792}
3793#endif /* TCLSH */