blob: e3e5628b1701c53a0b1ae026d3135a324e136d55 [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
mistachkin1f28e072013-08-15 08:06:15 +000044/* Used to get the current process ID */
45#if !defined(_WIN32)
46# include <unistd.h>
47# define GETPID getpid
48#elif !defined(_WIN32_WCE)
49# ifndef SQLITE_AMALGAMATION
50# define WIN32_LEAN_AND_MEAN
51# include <windows.h>
52# endif
53# define GETPID (int)GetCurrentProcessId
54#endif
55
drhad6e1372006-07-10 21:15:51 +000056/*
57 * Windows needs to know which symbols to export. Unix does not.
58 * BUILD_sqlite should be undefined for Unix.
59 */
60#ifdef BUILD_sqlite
61#undef TCL_STORAGE_CLASS
62#define TCL_STORAGE_CLASS DLLEXPORT
63#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000064
danielk1977a21c6b62005-01-24 10:25:59 +000065#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000066#define MAX_PREPARED_STMTS 100
67
drhc45e6712012-10-03 11:02:33 +000068/* Forward declaration */
69typedef struct SqliteDb SqliteDb;
drh98808ba2001-10-18 12:34:46 +000070
71/*
drhcabb0812002-09-14 13:47:32 +000072** New SQL functions can be created as TCL scripts. Each such function
73** is described by an instance of the following structure.
74*/
75typedef struct SqlFunc SqlFunc;
76struct SqlFunc {
77 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000078 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
drhc45e6712012-10-03 11:02:33 +000079 SqliteDb *pDb; /* Database connection that owns this function */
drhd1e47332005-06-26 17:55:33 +000080 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
81 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000082 SqlFunc *pNext; /* Next function on the list of them all */
83};
84
85/*
danielk19770202b292004-06-09 09:55:16 +000086** New collation sequences function can be created as TCL scripts. Each such
87** function is described by an instance of the following structure.
88*/
89typedef struct SqlCollate SqlCollate;
90struct SqlCollate {
91 Tcl_Interp *interp; /* The TCL interpret to execute the function */
92 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000093 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000094};
95
96/*
drhfb7e7652005-01-24 00:28:42 +000097** Prepared statements are cached for faster execution. Each prepared
98** statement is described by an instance of the following structure.
99*/
100typedef struct SqlPreparedStmt SqlPreparedStmt;
101struct SqlPreparedStmt {
102 SqlPreparedStmt *pNext; /* Next in linked list */
103 SqlPreparedStmt *pPrev; /* Previous on the list */
104 sqlite3_stmt *pStmt; /* The prepared statement */
105 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +0000106 const char *zSql; /* Text of the SQL statement */
dan4a4c11a2009-10-06 14:59:02 +0000107 int nParm; /* Size of apParm array */
108 Tcl_Obj **apParm; /* Array of referenced object pointers */
drhfb7e7652005-01-24 00:28:42 +0000109};
110
danielk1977d04417962007-05-02 13:16:30 +0000111typedef struct IncrblobChannel IncrblobChannel;
112
drhfb7e7652005-01-24 00:28:42 +0000113/*
drhbec3f402000-08-04 13:49:02 +0000114** There is one instance of this structure for each SQLite database
115** that has been opened by the SQLite TCL interface.
danc431fd52011-06-27 16:55:50 +0000116**
117** If this module is built with SQLITE_TEST defined (to create the SQLite
118** testfixture executable), then it may be configured to use either
119** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
120** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
drhbec3f402000-08-04 13:49:02 +0000121*/
drhbec3f402000-08-04 13:49:02 +0000122struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000123 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000124 Tcl_Interp *interp; /* The interpreter used for this database */
125 char *zBusy; /* The busy callback routine */
126 char *zCommit; /* The commit hook callback routine */
127 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +0000128 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000129 char *zProgress; /* The progress callback routine */
130 char *zAuth; /* The authorization callback routine */
drh1f1549f2008-08-26 21:33:34 +0000131 int disableAuth; /* Disable the authorizer if it exists */
drhd1e47332005-06-26 17:55:33 +0000132 char *zNull; /* Text to substitute for an SQL NULL value */
133 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000134 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000135 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drh5def0842010-05-05 20:00:25 +0000136 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000137 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000138 SqlCollate *pCollate; /* List of SQL collation functions */
139 int rc; /* Return code of most recent sqlite3_exec() */
140 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000141 SqlPreparedStmt *stmtList; /* List of prepared statements*/
142 SqlPreparedStmt *stmtLast; /* Last statement in the list */
143 int maxStmt; /* The next maximum number of stmtList */
144 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000145 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh3c379b02010-04-07 19:31:59 +0000146 int nStep, nSort, nIndex; /* Statistics for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000147 int nTransaction; /* Number of nested [transaction] methods */
danc431fd52011-06-27 16:55:50 +0000148#ifdef SQLITE_TEST
149 int bLegacyPrepare; /* True to use sqlite3_prepare() */
150#endif
drh98808ba2001-10-18 12:34:46 +0000151};
drh297ecf12001-04-05 15:57:13 +0000152
danielk1977b4e9af92007-05-01 17:49:49 +0000153struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000154 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000155 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000156 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000157 Tcl_Channel channel; /* Channel identifier */
158 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
159 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000160};
161
drhea678832008-12-10 19:26:22 +0000162/*
163** Compute a string length that is limited to what can be stored in
164** lower 30 bits of a 32-bit signed integer.
165*/
drh4f21c4a2008-12-10 22:15:00 +0000166static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000167 const char *z2 = z;
168 while( *z2 ){ z2++; }
169 return 0x3fffffff & (int)(z2 - z);
170}
drhea678832008-12-10 19:26:22 +0000171
172
danielk197732a0d8b2007-05-04 19:03:02 +0000173#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000174/*
danielk1977d04417962007-05-02 13:16:30 +0000175** Close all incrblob channels opened using database connection pDb.
176** This is called when shutting down the database connection.
177*/
178static void closeIncrblobChannels(SqliteDb *pDb){
179 IncrblobChannel *p;
180 IncrblobChannel *pNext;
181
182 for(p=pDb->pIncrblob; p; p=pNext){
183 pNext = p->pNext;
184
185 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
186 ** which deletes the IncrblobChannel structure at *p. So do not
187 ** call Tcl_Free() here.
188 */
189 Tcl_UnregisterChannel(pDb->interp, p->channel);
190 }
191}
192
193/*
danielk1977b4e9af92007-05-01 17:49:49 +0000194** Close an incremental blob channel.
195*/
196static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
197 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000198 int rc = sqlite3_blob_close(p->pBlob);
199 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000200
201 /* Remove the channel from the SqliteDb.pIncrblob list. */
202 if( p->pNext ){
203 p->pNext->pPrev = p->pPrev;
204 }
205 if( p->pPrev ){
206 p->pPrev->pNext = p->pNext;
207 }
208 if( p->pDb->pIncrblob==p ){
209 p->pDb->pIncrblob = p->pNext;
210 }
211
danielk197792d4d7a2007-05-04 12:05:56 +0000212 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000213 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000214
215 if( rc!=SQLITE_OK ){
216 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
217 return TCL_ERROR;
218 }
danielk1977b4e9af92007-05-01 17:49:49 +0000219 return TCL_OK;
220}
221
222/*
223** Read data from an incremental blob channel.
224*/
225static int incrblobInput(
226 ClientData instanceData,
227 char *buf,
228 int bufSize,
229 int *errorCodePtr
230){
231 IncrblobChannel *p = (IncrblobChannel *)instanceData;
232 int nRead = bufSize; /* Number of bytes to read */
233 int nBlob; /* Total size of the blob */
234 int rc; /* sqlite error code */
235
236 nBlob = sqlite3_blob_bytes(p->pBlob);
237 if( (p->iSeek+nRead)>nBlob ){
238 nRead = nBlob-p->iSeek;
239 }
240 if( nRead<=0 ){
241 return 0;
242 }
243
244 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
245 if( rc!=SQLITE_OK ){
246 *errorCodePtr = rc;
247 return -1;
248 }
249
250 p->iSeek += nRead;
251 return nRead;
252}
253
danielk1977d04417962007-05-02 13:16:30 +0000254/*
255** Write data to an incremental blob channel.
256*/
danielk1977b4e9af92007-05-01 17:49:49 +0000257static int incrblobOutput(
258 ClientData instanceData,
259 CONST char *buf,
260 int toWrite,
261 int *errorCodePtr
262){
263 IncrblobChannel *p = (IncrblobChannel *)instanceData;
264 int nWrite = toWrite; /* Number of bytes to write */
265 int nBlob; /* Total size of the blob */
266 int rc; /* sqlite error code */
267
268 nBlob = sqlite3_blob_bytes(p->pBlob);
269 if( (p->iSeek+nWrite)>nBlob ){
270 *errorCodePtr = EINVAL;
271 return -1;
272 }
273 if( nWrite<=0 ){
274 return 0;
275 }
276
277 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
278 if( rc!=SQLITE_OK ){
279 *errorCodePtr = EIO;
280 return -1;
281 }
282
283 p->iSeek += nWrite;
284 return nWrite;
285}
286
287/*
288** Seek an incremental blob channel.
289*/
290static int incrblobSeek(
291 ClientData instanceData,
292 long offset,
293 int seekMode,
294 int *errorCodePtr
295){
296 IncrblobChannel *p = (IncrblobChannel *)instanceData;
297
298 switch( seekMode ){
299 case SEEK_SET:
300 p->iSeek = offset;
301 break;
302 case SEEK_CUR:
303 p->iSeek += offset;
304 break;
305 case SEEK_END:
306 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
307 break;
308
309 default: assert(!"Bad seekMode");
310 }
311
312 return p->iSeek;
313}
314
315
316static void incrblobWatch(ClientData instanceData, int mode){
317 /* NO-OP */
318}
319static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
320 return TCL_ERROR;
321}
322
323static Tcl_ChannelType IncrblobChannelType = {
324 "incrblob", /* typeName */
325 TCL_CHANNEL_VERSION_2, /* version */
326 incrblobClose, /* closeProc */
327 incrblobInput, /* inputProc */
328 incrblobOutput, /* outputProc */
329 incrblobSeek, /* seekProc */
330 0, /* setOptionProc */
331 0, /* getOptionProc */
332 incrblobWatch, /* watchProc (this is a no-op) */
333 incrblobHandle, /* getHandleProc (always returns error) */
334 0, /* close2Proc */
335 0, /* blockModeProc */
336 0, /* flushProc */
337 0, /* handlerProc */
338 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000339};
340
341/*
342** Create a new incrblob channel.
343*/
344static int createIncrblobChannel(
345 Tcl_Interp *interp,
346 SqliteDb *pDb,
347 const char *zDb,
348 const char *zTable,
349 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000350 sqlite_int64 iRow,
351 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000352){
353 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000354 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000355 sqlite3_blob *pBlob;
356 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000357 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000358
359 /* This variable is used to name the channels: "incrblob_[incr count]" */
360 static int count = 0;
361 char zChannel[64];
362
danielk19778cbadb02007-05-03 16:31:26 +0000363 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000364 if( rc!=SQLITE_OK ){
365 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
366 return TCL_ERROR;
367 }
368
369 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
370 p->iSeek = 0;
371 p->pBlob = pBlob;
372
drh5bb3eb92007-05-04 13:15:55 +0000373 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000374 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
375 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000376
danielk1977d04417962007-05-02 13:16:30 +0000377 /* Link the new channel into the SqliteDb.pIncrblob list. */
378 p->pNext = pDb->pIncrblob;
379 p->pPrev = 0;
380 if( p->pNext ){
381 p->pNext->pPrev = p;
382 }
383 pDb->pIncrblob = p;
384 p->pDb = pDb;
385
386 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000387 return TCL_OK;
388}
danielk197732a0d8b2007-05-04 19:03:02 +0000389#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
390 #define closeIncrblobChannels(pDb)
391#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000392
drh6d313162000-09-21 13:01:35 +0000393/*
drhd1e47332005-06-26 17:55:33 +0000394** Look at the script prefix in pCmd. We will be executing this script
395** after first appending one or more arguments. This routine analyzes
396** the script to see if it is safe to use Tcl_EvalObjv() on the script
397** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
398** faster.
399**
400** Scripts that are safe to use with Tcl_EvalObjv() consists of a
401** command name followed by zero or more arguments with no [...] or $
402** or {...} or ; to be seen anywhere. Most callback scripts consist
403** of just a single procedure name and they meet this requirement.
404*/
405static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
406 /* We could try to do something with Tcl_Parse(). But we will instead
407 ** just do a search for forbidden characters. If any of the forbidden
408 ** characters appear in pCmd, we will report the string as unsafe.
409 */
410 const char *z;
411 int n;
412 z = Tcl_GetStringFromObj(pCmd, &n);
413 while( n-- > 0 ){
414 int c = *(z++);
415 if( c=='$' || c=='[' || c==';' ) return 0;
416 }
417 return 1;
418}
419
420/*
421** Find an SqlFunc structure with the given name. Or create a new
422** one if an existing one cannot be found. Return a pointer to the
423** structure.
424*/
425static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
426 SqlFunc *p, *pNew;
drh0425f182013-11-26 16:48:04 +0000427 int nName = strlen30(zName);
428 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
drhd1e47332005-06-26 17:55:33 +0000429 pNew->zName = (char*)&pNew[1];
drh0425f182013-11-26 16:48:04 +0000430 memcpy(pNew->zName, zName, nName+1);
drhd1e47332005-06-26 17:55:33 +0000431 for(p=pDb->pFunc; p; p=p->pNext){
drh0425f182013-11-26 16:48:04 +0000432 if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
drhd1e47332005-06-26 17:55:33 +0000433 Tcl_Free((char*)pNew);
434 return p;
435 }
436 }
437 pNew->interp = pDb->interp;
drhc45e6712012-10-03 11:02:33 +0000438 pNew->pDb = pDb;
drhd1e47332005-06-26 17:55:33 +0000439 pNew->pScript = 0;
440 pNew->pNext = pDb->pFunc;
441 pDb->pFunc = pNew;
442 return pNew;
443}
444
445/*
danc431fd52011-06-27 16:55:50 +0000446** Free a single SqlPreparedStmt object.
447*/
448static void dbFreeStmt(SqlPreparedStmt *pStmt){
449#ifdef SQLITE_TEST
450 if( sqlite3_sql(pStmt->pStmt)==0 ){
451 Tcl_Free((char *)pStmt->zSql);
452 }
453#endif
454 sqlite3_finalize(pStmt->pStmt);
455 Tcl_Free((char *)pStmt);
456}
457
458/*
drhfb7e7652005-01-24 00:28:42 +0000459** Finalize and free a list of prepared statements
460*/
danc431fd52011-06-27 16:55:50 +0000461static void flushStmtCache(SqliteDb *pDb){
drhfb7e7652005-01-24 00:28:42 +0000462 SqlPreparedStmt *pPreStmt;
danc431fd52011-06-27 16:55:50 +0000463 SqlPreparedStmt *pNext;
drhfb7e7652005-01-24 00:28:42 +0000464
danc431fd52011-06-27 16:55:50 +0000465 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
466 pNext = pPreStmt->pNext;
467 dbFreeStmt(pPreStmt);
drhfb7e7652005-01-24 00:28:42 +0000468 }
469 pDb->nStmt = 0;
470 pDb->stmtLast = 0;
danc431fd52011-06-27 16:55:50 +0000471 pDb->stmtList = 0;
drhfb7e7652005-01-24 00:28:42 +0000472}
473
474/*
drh895d7472004-08-20 16:02:39 +0000475** TCL calls this procedure when an sqlite3 database command is
476** deleted.
drh75897232000-05-29 14:26:00 +0000477*/
478static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000479 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000480 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000481 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000482 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000483 while( pDb->pFunc ){
484 SqlFunc *pFunc = pDb->pFunc;
485 pDb->pFunc = pFunc->pNext;
drhc45e6712012-10-03 11:02:33 +0000486 assert( pFunc->pDb==pDb );
drhd1e47332005-06-26 17:55:33 +0000487 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000488 Tcl_Free((char*)pFunc);
489 }
danielk19770202b292004-06-09 09:55:16 +0000490 while( pDb->pCollate ){
491 SqlCollate *pCollate = pDb->pCollate;
492 pDb->pCollate = pCollate->pNext;
493 Tcl_Free((char*)pCollate);
494 }
drhbec3f402000-08-04 13:49:02 +0000495 if( pDb->zBusy ){
496 Tcl_Free(pDb->zBusy);
497 }
drhb5a20d32003-04-23 12:25:23 +0000498 if( pDb->zTrace ){
499 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000500 }
drh19e2d372005-08-29 23:00:03 +0000501 if( pDb->zProfile ){
502 Tcl_Free(pDb->zProfile);
503 }
drhe22a3342003-04-22 20:30:37 +0000504 if( pDb->zAuth ){
505 Tcl_Free(pDb->zAuth);
506 }
danielk197755c45f22005-04-03 23:54:43 +0000507 if( pDb->zNull ){
508 Tcl_Free(pDb->zNull);
509 }
danielk197794eb6a12005-12-15 15:22:08 +0000510 if( pDb->pUpdateHook ){
511 Tcl_DecrRefCount(pDb->pUpdateHook);
512 }
danielk197771fd80b2005-12-16 06:54:01 +0000513 if( pDb->pRollbackHook ){
514 Tcl_DecrRefCount(pDb->pRollbackHook);
515 }
drh5def0842010-05-05 20:00:25 +0000516 if( pDb->pWalHook ){
517 Tcl_DecrRefCount(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000518 }
danielk197794eb6a12005-12-15 15:22:08 +0000519 if( pDb->pCollateNeeded ){
520 Tcl_DecrRefCount(pDb->pCollateNeeded);
521 }
drhbec3f402000-08-04 13:49:02 +0000522 Tcl_Free((char*)pDb);
523}
524
525/*
526** This routine is called when a database file is locked while trying
527** to execute SQL.
528*/
danielk19772a764eb2004-06-12 01:43:26 +0000529static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000530 SqliteDb *pDb = (SqliteDb*)cd;
531 int rc;
532 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000533
drh5bb3eb92007-05-04 13:15:55 +0000534 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000535 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000536 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
537 return 0;
538 }
539 return 1;
drh75897232000-05-29 14:26:00 +0000540}
541
drh26e4a8b2008-05-01 17:16:52 +0000542#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000543/*
danielk1977348bb5d2003-10-18 09:37:26 +0000544** This routine is invoked as the 'progress callback' for the database.
545*/
546static int DbProgressHandler(void *cd){
547 SqliteDb *pDb = (SqliteDb*)cd;
548 int rc;
549
550 assert( pDb->zProgress );
551 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
552 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
553 return 1;
554 }
555 return 0;
556}
drh26e4a8b2008-05-01 17:16:52 +0000557#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000558
drhd1167392006-01-23 13:00:35 +0000559#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000560/*
drhb5a20d32003-04-23 12:25:23 +0000561** This routine is called by the SQLite trace handler whenever a new
562** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000563*/
drhb5a20d32003-04-23 12:25:23 +0000564static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000565 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000566 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000567
drhb5a20d32003-04-23 12:25:23 +0000568 Tcl_DStringInit(&str);
569 Tcl_DStringAppend(&str, pDb->zTrace, -1);
570 Tcl_DStringAppendElement(&str, zSql);
571 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
572 Tcl_DStringFree(&str);
573 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000574}
drhd1167392006-01-23 13:00:35 +0000575#endif
drh0d1a6432003-04-03 15:46:04 +0000576
drhd1167392006-01-23 13:00:35 +0000577#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000578/*
drh19e2d372005-08-29 23:00:03 +0000579** This routine is called by the SQLite profile handler after a statement
580** SQL has executed. The TCL script in pDb->zProfile is evaluated.
581*/
582static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
583 SqliteDb *pDb = (SqliteDb*)cd;
584 Tcl_DString str;
585 char zTm[100];
586
587 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
588 Tcl_DStringInit(&str);
589 Tcl_DStringAppend(&str, pDb->zProfile, -1);
590 Tcl_DStringAppendElement(&str, zSql);
591 Tcl_DStringAppendElement(&str, zTm);
592 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
593 Tcl_DStringFree(&str);
594 Tcl_ResetResult(pDb->interp);
595}
drhd1167392006-01-23 13:00:35 +0000596#endif
drh19e2d372005-08-29 23:00:03 +0000597
598/*
drhaa940ea2004-01-15 02:44:03 +0000599** This routine is called when a transaction is committed. The
600** TCL script in pDb->zCommit is executed. If it returns non-zero or
601** if it throws an exception, the transaction is rolled back instead
602** of being committed.
603*/
604static int DbCommitHandler(void *cd){
605 SqliteDb *pDb = (SqliteDb*)cd;
606 int rc;
607
608 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
609 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
610 return 1;
611 }
612 return 0;
613}
614
danielk197771fd80b2005-12-16 06:54:01 +0000615static void DbRollbackHandler(void *clientData){
616 SqliteDb *pDb = (SqliteDb*)clientData;
617 assert(pDb->pRollbackHook);
618 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
619 Tcl_BackgroundError(pDb->interp);
620 }
621}
622
drh5def0842010-05-05 20:00:25 +0000623/*
624** This procedure handles wal_hook callbacks.
625*/
626static int DbWalHandler(
dan8d22a172010-04-19 18:03:51 +0000627 void *clientData,
628 sqlite3 *db,
629 const char *zDb,
630 int nEntry
631){
drh5def0842010-05-05 20:00:25 +0000632 int ret = SQLITE_OK;
dan8d22a172010-04-19 18:03:51 +0000633 Tcl_Obj *p;
634 SqliteDb *pDb = (SqliteDb*)clientData;
635 Tcl_Interp *interp = pDb->interp;
drh5def0842010-05-05 20:00:25 +0000636 assert(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000637
drh5def0842010-05-05 20:00:25 +0000638 p = Tcl_DuplicateObj(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000639 Tcl_IncrRefCount(p);
640 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
641 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
642 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
643 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
644 ){
645 Tcl_BackgroundError(interp);
646 }
647 Tcl_DecrRefCount(p);
648
649 return ret;
650}
651
drhbcf4f482009-03-27 12:44:35 +0000652#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000653static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
654 char zBuf[64];
655 sprintf(zBuf, "%d", iArg);
656 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
657 sprintf(zBuf, "%d", nArg);
658 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
659}
660#else
drhbcf4f482009-03-27 12:44:35 +0000661# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000662#endif
663
drh69910da2009-03-27 12:32:54 +0000664#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000665static void DbUnlockNotify(void **apArg, int nArg){
666 int i;
667 for(i=0; i<nArg; i++){
668 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
669 SqliteDb *pDb = (SqliteDb *)apArg[i];
670 setTestUnlockNotifyVars(pDb->interp, i, nArg);
671 assert( pDb->pUnlockNotify);
672 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
673 Tcl_DecrRefCount(pDb->pUnlockNotify);
674 pDb->pUnlockNotify = 0;
675 }
676}
drh69910da2009-03-27 12:32:54 +0000677#endif
danielk1977404ca072009-03-16 13:19:36 +0000678
danielk197794eb6a12005-12-15 15:22:08 +0000679static void DbUpdateHandler(
680 void *p,
681 int op,
682 const char *zDb,
683 const char *zTbl,
684 sqlite_int64 rowid
685){
686 SqliteDb *pDb = (SqliteDb *)p;
687 Tcl_Obj *pCmd;
688
689 assert( pDb->pUpdateHook );
690 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
691
692 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
693 Tcl_IncrRefCount(pCmd);
694 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
695 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
696 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
697 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
698 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
699 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
drhefdde162010-10-27 15:36:21 +0000700 Tcl_DecrRefCount(pCmd);
danielk197794eb6a12005-12-15 15:22:08 +0000701}
702
danielk19777cedc8d2004-06-10 10:50:08 +0000703static void tclCollateNeeded(
704 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000705 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000706 int enc,
707 const char *zName
708){
709 SqliteDb *pDb = (SqliteDb *)pCtx;
710 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
711 Tcl_IncrRefCount(pScript);
712 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
713 Tcl_EvalObjEx(pDb->interp, pScript, 0);
714 Tcl_DecrRefCount(pScript);
715}
716
drhaa940ea2004-01-15 02:44:03 +0000717/*
danielk19770202b292004-06-09 09:55:16 +0000718** This routine is called to evaluate an SQL collation function implemented
719** using TCL script.
720*/
721static int tclSqlCollate(
722 void *pCtx,
723 int nA,
724 const void *zA,
725 int nB,
726 const void *zB
727){
728 SqlCollate *p = (SqlCollate *)pCtx;
729 Tcl_Obj *pCmd;
730
731 pCmd = Tcl_NewStringObj(p->zScript, -1);
732 Tcl_IncrRefCount(pCmd);
733 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
734 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000735 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000736 Tcl_DecrRefCount(pCmd);
737 return (atoi(Tcl_GetStringResult(p->interp)));
738}
739
740/*
drhcabb0812002-09-14 13:47:32 +0000741** This routine is called to evaluate an SQL function implemented
742** using TCL script.
743*/
drhfb7e7652005-01-24 00:28:42 +0000744static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000745 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000746 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000747 int i;
748 int rc;
749
drhd1e47332005-06-26 17:55:33 +0000750 if( argc==0 ){
751 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
752 ** script object directly. This allows the TCL compiler to generate
753 ** bytecode for the command on the first invocation and thus make
754 ** subsequent invocations much faster. */
755 pCmd = p->pScript;
756 Tcl_IncrRefCount(pCmd);
757 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
758 Tcl_DecrRefCount(pCmd);
759 }else{
760 /* If there are arguments to the function, make a shallow copy of the
761 ** script object, lappend the arguments, then evaluate the copy.
762 **
763 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
764 ** The new Tcl_Obj contains pointers to the original list elements.
765 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
766 ** of the list to tclCmdNameType, that alternate representation will
767 ** be preserved and reused on the next invocation.
768 */
769 Tcl_Obj **aArg;
770 int nArg;
771 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
772 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
773 return;
774 }
775 pCmd = Tcl_NewListObj(nArg, aArg);
776 Tcl_IncrRefCount(pCmd);
777 for(i=0; i<argc; i++){
778 sqlite3_value *pIn = argv[i];
779 Tcl_Obj *pVal;
780
781 /* Set pVal to contain the i'th column of this row. */
782 switch( sqlite3_value_type(pIn) ){
783 case SQLITE_BLOB: {
784 int bytes = sqlite3_value_bytes(pIn);
785 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
786 break;
787 }
788 case SQLITE_INTEGER: {
789 sqlite_int64 v = sqlite3_value_int64(pIn);
790 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +0000791 pVal = Tcl_NewIntObj((int)v);
drhd1e47332005-06-26 17:55:33 +0000792 }else{
793 pVal = Tcl_NewWideIntObj(v);
794 }
795 break;
796 }
797 case SQLITE_FLOAT: {
798 double r = sqlite3_value_double(pIn);
799 pVal = Tcl_NewDoubleObj(r);
800 break;
801 }
802 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +0000803 pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
drhd1e47332005-06-26 17:55:33 +0000804 break;
805 }
806 default: {
807 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000808 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000809 break;
810 }
811 }
812 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
813 if( rc ){
814 Tcl_DecrRefCount(pCmd);
815 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
816 return;
817 }
danielk197751ad0ec2004-05-24 12:39:02 +0000818 }
drhd1e47332005-06-26 17:55:33 +0000819 if( !p->useEvalObjv ){
820 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
821 ** is a list without a string representation. To prevent this from
822 ** happening, make sure pCmd has a valid string representation */
823 Tcl_GetString(pCmd);
824 }
825 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
826 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000827 }
danielk1977562e8d32005-05-20 09:40:55 +0000828
drhc7f269d2005-05-05 10:30:29 +0000829 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000830 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000831 }else{
drhc7f269d2005-05-05 10:30:29 +0000832 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
833 int n;
834 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000835 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000836 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000837 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000838 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000839 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000840 data = Tcl_GetByteArrayFromObj(pVar, &n);
841 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000842 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000843 Tcl_GetIntFromObj(0, pVar, &n);
844 sqlite3_result_int(context, n);
845 }else if( c=='d' && strcmp(zType,"double")==0 ){
846 double r;
847 Tcl_GetDoubleFromObj(0, pVar, &r);
848 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +0000849 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
850 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000851 Tcl_WideInt v;
852 Tcl_GetWideIntFromObj(0, pVar, &v);
853 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000854 }else{
danielk197700fd9572005-12-07 06:27:43 +0000855 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
856 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000857 }
drhcabb0812002-09-14 13:47:32 +0000858 }
859}
drh895d7472004-08-20 16:02:39 +0000860
drhe22a3342003-04-22 20:30:37 +0000861#ifndef SQLITE_OMIT_AUTHORIZATION
862/*
863** This is the authentication function. It appends the authentication
864** type code and the two arguments to zCmd[] then invokes the result
865** on the interpreter. The reply is examined to determine if the
866** authentication fails or succeeds.
867*/
868static int auth_callback(
869 void *pArg,
870 int code,
871 const char *zArg1,
872 const char *zArg2,
873 const char *zArg3,
874 const char *zArg4
875){
876 char *zCode;
877 Tcl_DString str;
878 int rc;
879 const char *zReply;
880 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +0000881 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +0000882
883 switch( code ){
884 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
885 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
886 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
887 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
888 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
889 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
890 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
891 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
892 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
893 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
894 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
895 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
896 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
897 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
898 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
899 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
900 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
901 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
902 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
903 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
904 case SQLITE_READ : zCode="SQLITE_READ"; break;
905 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
906 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
907 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000908 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
909 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000910 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000911 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000912 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000913 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
914 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000915 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +0000916 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drhe22a3342003-04-22 20:30:37 +0000917 default : zCode="????"; break;
918 }
919 Tcl_DStringInit(&str);
920 Tcl_DStringAppend(&str, pDb->zAuth, -1);
921 Tcl_DStringAppendElement(&str, zCode);
922 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
923 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
924 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
925 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
926 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
927 Tcl_DStringFree(&str);
drhb07028f2011-10-14 21:49:18 +0000928 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
drhe22a3342003-04-22 20:30:37 +0000929 if( strcmp(zReply,"SQLITE_OK")==0 ){
930 rc = SQLITE_OK;
931 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
932 rc = SQLITE_DENY;
933 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
934 rc = SQLITE_IGNORE;
935 }else{
936 rc = 999;
937 }
938 return rc;
939}
940#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000941
942/*
tpoindex1067fe12004-12-17 15:41:11 +0000943** This routine reads a line of text from FILE in, stores
944** the text in memory obtained from malloc() and returns a pointer
945** to the text. NULL is returned at end of file, or if malloc()
946** fails.
947**
948** The interface is like "readline" but no command-line editing
949** is done.
950**
951** copied from shell.c from '.import' command
952*/
953static char *local_getline(char *zPrompt, FILE *in){
954 char *zLine;
955 int nLine;
956 int n;
tpoindex1067fe12004-12-17 15:41:11 +0000957
958 nLine = 100;
959 zLine = malloc( nLine );
960 if( zLine==0 ) return 0;
961 n = 0;
drhb07028f2011-10-14 21:49:18 +0000962 while( 1 ){
tpoindex1067fe12004-12-17 15:41:11 +0000963 if( n+100>nLine ){
964 nLine = nLine*2 + 100;
965 zLine = realloc(zLine, nLine);
966 if( zLine==0 ) return 0;
967 }
968 if( fgets(&zLine[n], nLine - n, in)==0 ){
969 if( n==0 ){
970 free(zLine);
971 return 0;
972 }
973 zLine[n] = 0;
tpoindex1067fe12004-12-17 15:41:11 +0000974 break;
975 }
976 while( zLine[n] ){ n++; }
977 if( n>0 && zLine[n-1]=='\n' ){
978 n--;
979 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +0000980 break;
tpoindex1067fe12004-12-17 15:41:11 +0000981 }
982 }
983 zLine = realloc( zLine, n+1 );
984 return zLine;
985}
986
danielk19778e556522007-11-13 10:30:24 +0000987
988/*
dan4a4c11a2009-10-06 14:59:02 +0000989** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +0000990**
dan4a4c11a2009-10-06 14:59:02 +0000991** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +0000992**
dan4a4c11a2009-10-06 14:59:02 +0000993** It is invoked after evaluating the script SCRIPT to commit or rollback
994** the transaction or savepoint opened by the [transaction] command.
995*/
996static int DbTransPostCmd(
997 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
998 Tcl_Interp *interp, /* Tcl interpreter */
999 int result /* Result of evaluating SCRIPT */
1000){
1001 static const char *azEnd[] = {
1002 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1003 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1004 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1005 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1006 };
1007 SqliteDb *pDb = (SqliteDb*)data[0];
1008 int rc = result;
1009 const char *zEnd;
1010
1011 pDb->nTransaction--;
1012 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1013
1014 pDb->disableAuth++;
1015 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1016 /* This is a tricky scenario to handle. The most likely cause of an
1017 ** error is that the exec() above was an attempt to commit the
1018 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
mistachkin48864df2013-03-21 21:20:32 +00001019 ** that an IO-error has occurred. In either case, throw a Tcl exception
dan4a4c11a2009-10-06 14:59:02 +00001020 ** and try to rollback the transaction.
1021 **
1022 ** But it could also be that the user executed one or more BEGIN,
1023 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1024 ** this method's logic. Not clear how this would be best handled.
1025 */
1026 if( rc!=TCL_ERROR ){
1027 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
1028 rc = TCL_ERROR;
1029 }
1030 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1031 }
1032 pDb->disableAuth--;
1033
1034 return rc;
1035}
1036
1037/*
danc431fd52011-06-27 16:55:50 +00001038** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1039** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1040** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1041** on whether or not the [db_use_legacy_prepare] command has been used to
1042** configure the connection.
1043*/
1044static int dbPrepare(
1045 SqliteDb *pDb, /* Database object */
1046 const char *zSql, /* SQL to compile */
1047 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1048 const char **pzOut /* OUT: Pointer to next SQL statement */
1049){
1050#ifdef SQLITE_TEST
1051 if( pDb->bLegacyPrepare ){
1052 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1053 }
1054#endif
1055 return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut);
1056}
1057
1058/*
dan4a4c11a2009-10-06 14:59:02 +00001059** Search the cache for a prepared-statement object that implements the
1060** first SQL statement in the buffer pointed to by parameter zIn. If
1061** no such prepared-statement can be found, allocate and prepare a new
1062** one. In either case, bind the current values of the relevant Tcl
1063** variables to any $var, :var or @var variables in the statement. Before
1064** returning, set *ppPreStmt to point to the prepared-statement object.
1065**
1066** Output parameter *pzOut is set to point to the next SQL statement in
1067** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1068** next statement.
1069**
1070** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1071** and an error message loaded into interpreter pDb->interp.
1072*/
1073static int dbPrepareAndBind(
1074 SqliteDb *pDb, /* Database object */
1075 char const *zIn, /* SQL to compile */
1076 char const **pzOut, /* OUT: Pointer to next SQL statement */
1077 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1078){
1079 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
1080 sqlite3_stmt *pStmt; /* Prepared statement object */
1081 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1082 int nSql; /* Length of zSql in bytes */
1083 int nVar; /* Number of variables in statement */
1084 int iParm = 0; /* Next free entry in apParm */
drh0425f182013-11-26 16:48:04 +00001085 char c;
dan4a4c11a2009-10-06 14:59:02 +00001086 int i;
1087 Tcl_Interp *interp = pDb->interp;
1088
1089 *ppPreStmt = 0;
1090
1091 /* Trim spaces from the start of zSql and calculate the remaining length. */
drh0425f182013-11-26 16:48:04 +00001092 while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
dan4a4c11a2009-10-06 14:59:02 +00001093 nSql = strlen30(zSql);
1094
1095 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1096 int n = pPreStmt->nSql;
1097 if( nSql>=n
1098 && memcmp(pPreStmt->zSql, zSql, n)==0
1099 && (zSql[n]==0 || zSql[n-1]==';')
1100 ){
1101 pStmt = pPreStmt->pStmt;
1102 *pzOut = &zSql[pPreStmt->nSql];
1103
1104 /* When a prepared statement is found, unlink it from the
1105 ** cache list. It will later be added back to the beginning
1106 ** of the cache list in order to implement LRU replacement.
1107 */
1108 if( pPreStmt->pPrev ){
1109 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1110 }else{
1111 pDb->stmtList = pPreStmt->pNext;
1112 }
1113 if( pPreStmt->pNext ){
1114 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1115 }else{
1116 pDb->stmtLast = pPreStmt->pPrev;
1117 }
1118 pDb->nStmt--;
1119 nVar = sqlite3_bind_parameter_count(pStmt);
1120 break;
1121 }
1122 }
1123
1124 /* If no prepared statement was found. Compile the SQL text. Also allocate
1125 ** a new SqlPreparedStmt structure. */
1126 if( pPreStmt==0 ){
1127 int nByte;
1128
danc431fd52011-06-27 16:55:50 +00001129 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
drhc45e6712012-10-03 11:02:33 +00001130 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001131 return TCL_ERROR;
1132 }
1133 if( pStmt==0 ){
1134 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1135 /* A compile-time error in the statement. */
drhc45e6712012-10-03 11:02:33 +00001136 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001137 return TCL_ERROR;
1138 }else{
1139 /* The statement was a no-op. Continue to the next statement
1140 ** in the SQL string.
1141 */
1142 return TCL_OK;
1143 }
1144 }
1145
1146 assert( pPreStmt==0 );
1147 nVar = sqlite3_bind_parameter_count(pStmt);
1148 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1149 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1150 memset(pPreStmt, 0, nByte);
1151
1152 pPreStmt->pStmt = pStmt;
drh7ed243b2012-04-19 17:19:51 +00001153 pPreStmt->nSql = (int)(*pzOut - zSql);
dan4a4c11a2009-10-06 14:59:02 +00001154 pPreStmt->zSql = sqlite3_sql(pStmt);
1155 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
danc431fd52011-06-27 16:55:50 +00001156#ifdef SQLITE_TEST
1157 if( pPreStmt->zSql==0 ){
1158 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1159 memcpy(zCopy, zSql, pPreStmt->nSql);
1160 zCopy[pPreStmt->nSql] = '\0';
1161 pPreStmt->zSql = zCopy;
1162 }
1163#endif
dan4a4c11a2009-10-06 14:59:02 +00001164 }
1165 assert( pPreStmt );
1166 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1167 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1168
1169 /* Bind values to parameters that begin with $ or : */
1170 for(i=1; i<=nVar; i++){
1171 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1172 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1173 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1174 if( pVar ){
1175 int n;
1176 u8 *data;
1177 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1178 char c = zType[0];
1179 if( zVar[0]=='@' ||
1180 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1181 /* Load a BLOB type if the Tcl variable is a bytearray and
1182 ** it has no string representation or the host
1183 ** parameter name begins with "@". */
1184 data = Tcl_GetByteArrayFromObj(pVar, &n);
1185 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1186 Tcl_IncrRefCount(pVar);
1187 pPreStmt->apParm[iParm++] = pVar;
1188 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1189 Tcl_GetIntFromObj(interp, pVar, &n);
1190 sqlite3_bind_int(pStmt, i, n);
1191 }else if( c=='d' && strcmp(zType,"double")==0 ){
1192 double r;
1193 Tcl_GetDoubleFromObj(interp, pVar, &r);
1194 sqlite3_bind_double(pStmt, i, r);
1195 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1196 (c=='i' && strcmp(zType,"int")==0) ){
1197 Tcl_WideInt v;
1198 Tcl_GetWideIntFromObj(interp, pVar, &v);
1199 sqlite3_bind_int64(pStmt, i, v);
1200 }else{
1201 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1202 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1203 Tcl_IncrRefCount(pVar);
1204 pPreStmt->apParm[iParm++] = pVar;
1205 }
1206 }else{
1207 sqlite3_bind_null(pStmt, i);
1208 }
1209 }
1210 }
1211 pPreStmt->nParm = iParm;
1212 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001213
dan4a4c11a2009-10-06 14:59:02 +00001214 return TCL_OK;
1215}
1216
dan4a4c11a2009-10-06 14:59:02 +00001217/*
1218** Release a statement reference obtained by calling dbPrepareAndBind().
1219** There should be exactly one call to this function for each call to
1220** dbPrepareAndBind().
1221**
1222** If the discard parameter is non-zero, then the statement is deleted
1223** immediately. Otherwise it is added to the LRU list and may be returned
1224** by a subsequent call to dbPrepareAndBind().
1225*/
1226static void dbReleaseStmt(
1227 SqliteDb *pDb, /* Database handle */
1228 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1229 int discard /* True to delete (not cache) the pPreStmt */
1230){
1231 int i;
1232
1233 /* Free the bound string and blob parameters */
1234 for(i=0; i<pPreStmt->nParm; i++){
1235 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1236 }
1237 pPreStmt->nParm = 0;
1238
1239 if( pDb->maxStmt<=0 || discard ){
1240 /* If the cache is turned off, deallocated the statement */
danc431fd52011-06-27 16:55:50 +00001241 dbFreeStmt(pPreStmt);
dan4a4c11a2009-10-06 14:59:02 +00001242 }else{
1243 /* Add the prepared statement to the beginning of the cache list. */
1244 pPreStmt->pNext = pDb->stmtList;
1245 pPreStmt->pPrev = 0;
1246 if( pDb->stmtList ){
1247 pDb->stmtList->pPrev = pPreStmt;
1248 }
1249 pDb->stmtList = pPreStmt;
1250 if( pDb->stmtLast==0 ){
1251 assert( pDb->nStmt==0 );
1252 pDb->stmtLast = pPreStmt;
1253 }else{
1254 assert( pDb->nStmt>0 );
1255 }
1256 pDb->nStmt++;
1257
1258 /* If we have too many statement in cache, remove the surplus from
1259 ** the end of the cache list. */
1260 while( pDb->nStmt>pDb->maxStmt ){
danc431fd52011-06-27 16:55:50 +00001261 SqlPreparedStmt *pLast = pDb->stmtLast;
1262 pDb->stmtLast = pLast->pPrev;
dan4a4c11a2009-10-06 14:59:02 +00001263 pDb->stmtLast->pNext = 0;
1264 pDb->nStmt--;
danc431fd52011-06-27 16:55:50 +00001265 dbFreeStmt(pLast);
dan4a4c11a2009-10-06 14:59:02 +00001266 }
1267 }
1268}
1269
1270/*
1271** Structure used with dbEvalXXX() functions:
1272**
1273** dbEvalInit()
1274** dbEvalStep()
1275** dbEvalFinalize()
1276** dbEvalRowInfo()
1277** dbEvalColumnValue()
1278*/
1279typedef struct DbEvalContext DbEvalContext;
1280struct DbEvalContext {
1281 SqliteDb *pDb; /* Database handle */
1282 Tcl_Obj *pSql; /* Object holding string zSql */
1283 const char *zSql; /* Remaining SQL to execute */
1284 SqlPreparedStmt *pPreStmt; /* Current statement */
1285 int nCol; /* Number of columns returned by pStmt */
1286 Tcl_Obj *pArray; /* Name of array variable */
1287 Tcl_Obj **apColName; /* Array of column names */
1288};
1289
1290/*
1291** Release any cache of column names currently held as part of
1292** the DbEvalContext structure passed as the first argument.
1293*/
1294static void dbReleaseColumnNames(DbEvalContext *p){
1295 if( p->apColName ){
1296 int i;
1297 for(i=0; i<p->nCol; i++){
1298 Tcl_DecrRefCount(p->apColName[i]);
1299 }
1300 Tcl_Free((char *)p->apColName);
1301 p->apColName = 0;
1302 }
1303 p->nCol = 0;
1304}
1305
1306/*
1307** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001308**
1309** If pArray is not NULL, then it contains the name of a Tcl array
1310** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001311** the names of the columns returned by the statement as part of each
1312** call to dbEvalStep(), in order from left to right. e.g. if the names
1313** of the returned columns are a, b and c, it does the equivalent of the
1314** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001315**
1316** set ${pArray}(*) {a b c}
1317*/
dan4a4c11a2009-10-06 14:59:02 +00001318static void dbEvalInit(
1319 DbEvalContext *p, /* Pointer to structure to initialize */
1320 SqliteDb *pDb, /* Database handle */
1321 Tcl_Obj *pSql, /* Object containing SQL script */
1322 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001323){
dan4a4c11a2009-10-06 14:59:02 +00001324 memset(p, 0, sizeof(DbEvalContext));
1325 p->pDb = pDb;
1326 p->zSql = Tcl_GetString(pSql);
1327 p->pSql = pSql;
1328 Tcl_IncrRefCount(pSql);
1329 if( pArray ){
1330 p->pArray = pArray;
1331 Tcl_IncrRefCount(pArray);
1332 }
1333}
danielk19778e556522007-11-13 10:30:24 +00001334
dan4a4c11a2009-10-06 14:59:02 +00001335/*
1336** Obtain information about the row that the DbEvalContext passed as the
1337** first argument currently points to.
1338*/
1339static void dbEvalRowInfo(
1340 DbEvalContext *p, /* Evaluation context */
1341 int *pnCol, /* OUT: Number of column names */
1342 Tcl_Obj ***papColName /* OUT: Array of column names */
1343){
danielk19778e556522007-11-13 10:30:24 +00001344 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001345 if( 0==p->apColName ){
1346 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1347 int i; /* Iterator variable */
1348 int nCol; /* Number of columns returned by pStmt */
1349 Tcl_Obj **apColName = 0; /* Array of column names */
1350
1351 p->nCol = nCol = sqlite3_column_count(pStmt);
1352 if( nCol>0 && (papColName || p->pArray) ){
1353 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1354 for(i=0; i<nCol; i++){
drhc45e6712012-10-03 11:02:33 +00001355 apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
dan4a4c11a2009-10-06 14:59:02 +00001356 Tcl_IncrRefCount(apColName[i]);
1357 }
1358 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001359 }
1360
1361 /* If results are being stored in an array variable, then create
1362 ** the array(*) entry for that array
1363 */
dan4a4c11a2009-10-06 14:59:02 +00001364 if( p->pArray ){
1365 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001366 Tcl_Obj *pColList = Tcl_NewObj();
1367 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001368
danielk19778e556522007-11-13 10:30:24 +00001369 for(i=0; i<nCol; i++){
1370 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1371 }
1372 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001373 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001374 Tcl_DecrRefCount(pStar);
1375 }
danielk19778e556522007-11-13 10:30:24 +00001376 }
1377
dan4a4c11a2009-10-06 14:59:02 +00001378 if( papColName ){
1379 *papColName = p->apColName;
1380 }
1381 if( pnCol ){
1382 *pnCol = p->nCol;
1383 }
1384}
1385
1386/*
1387** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1388** returned, then an error message is stored in the interpreter before
1389** returning.
1390**
1391** A return value of TCL_OK means there is a row of data available. The
1392** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1393** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1394** is returned, then the SQL script has finished executing and there are
1395** no further rows available. This is similar to SQLITE_DONE.
1396*/
1397static int dbEvalStep(DbEvalContext *p){
danc431fd52011-06-27 16:55:50 +00001398 const char *zPrevSql = 0; /* Previous value of p->zSql */
1399
dan4a4c11a2009-10-06 14:59:02 +00001400 while( p->zSql[0] || p->pPreStmt ){
1401 int rc;
1402 if( p->pPreStmt==0 ){
danc431fd52011-06-27 16:55:50 +00001403 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
dan4a4c11a2009-10-06 14:59:02 +00001404 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1405 if( rc!=TCL_OK ) return rc;
1406 }else{
1407 int rcs;
1408 SqliteDb *pDb = p->pDb;
1409 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1410 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1411
1412 rcs = sqlite3_step(pStmt);
1413 if( rcs==SQLITE_ROW ){
1414 return TCL_OK;
1415 }
1416 if( p->pArray ){
1417 dbEvalRowInfo(p, 0, 0);
1418 }
1419 rcs = sqlite3_reset(pStmt);
1420
1421 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1422 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001423 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
dan4a4c11a2009-10-06 14:59:02 +00001424 dbReleaseColumnNames(p);
1425 p->pPreStmt = 0;
1426
1427 if( rcs!=SQLITE_OK ){
1428 /* If a run-time error occurs, report the error and stop reading
1429 ** the SQL. */
dan4a4c11a2009-10-06 14:59:02 +00001430 dbReleaseStmt(pDb, pPreStmt, 1);
danc431fd52011-06-27 16:55:50 +00001431#if SQLITE_TEST
1432 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1433 /* If the runtime error was an SQLITE_SCHEMA, and the database
1434 ** handle is configured to use the legacy sqlite3_prepare()
1435 ** interface, retry prepare()/step() on the same SQL statement.
1436 ** This only happens once. If there is a second SQLITE_SCHEMA
1437 ** error, the error will be returned to the caller. */
1438 p->zSql = zPrevSql;
1439 continue;
1440 }
1441#endif
drhc45e6712012-10-03 11:02:33 +00001442 Tcl_SetObjResult(pDb->interp,
1443 Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001444 return TCL_ERROR;
1445 }else{
1446 dbReleaseStmt(pDb, pPreStmt, 0);
1447 }
1448 }
1449 }
1450
1451 /* Finished */
1452 return TCL_BREAK;
1453}
1454
1455/*
1456** Free all resources currently held by the DbEvalContext structure passed
1457** as the first argument. There should be exactly one call to this function
1458** for each call to dbEvalInit().
1459*/
1460static void dbEvalFinalize(DbEvalContext *p){
1461 if( p->pPreStmt ){
1462 sqlite3_reset(p->pPreStmt->pStmt);
1463 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1464 p->pPreStmt = 0;
1465 }
1466 if( p->pArray ){
1467 Tcl_DecrRefCount(p->pArray);
1468 p->pArray = 0;
1469 }
1470 Tcl_DecrRefCount(p->pSql);
1471 dbReleaseColumnNames(p);
1472}
1473
1474/*
1475** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1476** the value for the iCol'th column of the row currently pointed to by
1477** the DbEvalContext structure passed as the first argument.
1478*/
1479static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1480 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1481 switch( sqlite3_column_type(pStmt, iCol) ){
1482 case SQLITE_BLOB: {
1483 int bytes = sqlite3_column_bytes(pStmt, iCol);
1484 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1485 if( !zBlob ) bytes = 0;
1486 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1487 }
1488 case SQLITE_INTEGER: {
1489 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1490 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +00001491 return Tcl_NewIntObj((int)v);
dan4a4c11a2009-10-06 14:59:02 +00001492 }else{
1493 return Tcl_NewWideIntObj(v);
1494 }
1495 }
1496 case SQLITE_FLOAT: {
1497 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1498 }
1499 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +00001500 return Tcl_NewStringObj(p->pDb->zNull, -1);
dan4a4c11a2009-10-06 14:59:02 +00001501 }
1502 }
1503
drh325eff52012-10-03 12:56:18 +00001504 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
dan4a4c11a2009-10-06 14:59:02 +00001505}
1506
1507/*
1508** If using Tcl version 8.6 or greater, use the NR functions to avoid
1509** recursive evalution of scripts by the [db eval] and [db trans]
1510** commands. Even if the headers used while compiling the extension
1511** are 8.6 or newer, the code still tests the Tcl version at runtime.
1512** This allows stubs-enabled builds to be used with older Tcl libraries.
1513*/
1514#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001515# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001516static int DbUseNre(void){
1517 int major, minor;
1518 Tcl_GetVersion(&major, &minor, 0, 0);
1519 return( (major==8 && minor>=6) || major>8 );
1520}
1521#else
1522/*
1523** Compiling using headers earlier than 8.6. In this case NR cannot be
1524** used, so DbUseNre() to always return zero. Add #defines for the other
1525** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1526** even though the only invocations of them are within conditional blocks
1527** of the form:
1528**
1529** if( DbUseNre() ) { ... }
1530*/
drha2c8a952009-10-13 18:38:34 +00001531# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001532# define DbUseNre() 0
drha47941f2013-12-20 18:57:44 +00001533# define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001534# define Tcl_NREvalObj(a,b,c) 0
drha47941f2013-12-20 18:57:44 +00001535# define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001536#endif
1537
1538/*
1539** This function is part of the implementation of the command:
1540**
1541** $db eval SQL ?ARRAYNAME? SCRIPT
1542*/
1543static int DbEvalNextCmd(
1544 ClientData data[], /* data[0] is the (DbEvalContext*) */
1545 Tcl_Interp *interp, /* Tcl interpreter */
1546 int result /* Result so far */
1547){
1548 int rc = result; /* Return code */
1549
1550 /* The first element of the data[] array is a pointer to a DbEvalContext
1551 ** structure allocated using Tcl_Alloc(). The second element of data[]
1552 ** is a pointer to a Tcl_Obj containing the script to run for each row
1553 ** returned by the queries encapsulated in data[0]. */
1554 DbEvalContext *p = (DbEvalContext *)data[0];
1555 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1556 Tcl_Obj *pArray = p->pArray;
1557
1558 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1559 int i;
1560 int nCol;
1561 Tcl_Obj **apColName;
1562 dbEvalRowInfo(p, &nCol, &apColName);
1563 for(i=0; i<nCol; i++){
1564 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1565 if( pArray==0 ){
1566 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1567 }else{
1568 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1569 }
1570 }
1571
1572 /* The required interpreter variables are now populated with the data
1573 ** from the current row. If using NRE, schedule callbacks to evaluate
1574 ** script pScript, then to invoke this function again to fetch the next
1575 ** row (or clean up if there is no next row or the script throws an
1576 ** exception). After scheduling the callbacks, return control to the
1577 ** caller.
1578 **
1579 ** If not using NRE, evaluate pScript directly and continue with the
1580 ** next iteration of this while(...) loop. */
1581 if( DbUseNre() ){
1582 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1583 return Tcl_NREvalObj(interp, pScript, 0);
1584 }else{
1585 rc = Tcl_EvalObjEx(interp, pScript, 0);
1586 }
1587 }
1588
1589 Tcl_DecrRefCount(pScript);
1590 dbEvalFinalize(p);
1591 Tcl_Free((char *)p);
1592
1593 if( rc==TCL_OK || rc==TCL_BREAK ){
1594 Tcl_ResetResult(interp);
1595 rc = TCL_OK;
1596 }
1597 return rc;
danielk19778e556522007-11-13 10:30:24 +00001598}
1599
tpoindex1067fe12004-12-17 15:41:11 +00001600/*
drh75897232000-05-29 14:26:00 +00001601** The "sqlite" command below creates a new Tcl command for each
1602** connection it opens to an SQLite database. This routine is invoked
1603** whenever one of those connection-specific commands is executed
1604** in Tcl. For example, if you run Tcl code like this:
1605**
drh9bb575f2004-09-06 17:24:11 +00001606** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001607** db1 close
1608**
1609** The first command opens a connection to the "my_database" database
1610** and calls that connection "db1". The second command causes this
1611** subroutine to be invoked.
1612*/
drh6d313162000-09-21 13:01:35 +00001613static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001614 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001615 int choice;
drh22fbcb82004-02-01 01:22:50 +00001616 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001617 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001618 "authorizer", "backup", "busy",
1619 "cache", "changes", "close",
1620 "collate", "collation_needed", "commit_hook",
1621 "complete", "copy", "enable_load_extension",
1622 "errorcode", "eval", "exists",
1623 "function", "incrblob", "interrupt",
drh833bf962010-04-28 14:42:19 +00001624 "last_insert_rowid", "nullvalue", "onecolumn",
1625 "profile", "progress", "rekey",
1626 "restore", "rollback_hook", "status",
1627 "timeout", "total_changes", "trace",
1628 "transaction", "unlock_notify", "update_hook",
1629 "version", "wal_hook", 0
drh6d313162000-09-21 13:01:35 +00001630 };
drh411995d2002-06-25 19:31:18 +00001631 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001632 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1633 DB_CACHE, DB_CHANGES, DB_CLOSE,
1634 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1635 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1636 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1637 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
drh833bf962010-04-28 14:42:19 +00001638 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
1639 DB_PROFILE, DB_PROGRESS, DB_REKEY,
1640 DB_RESTORE, DB_ROLLBACK_HOOK, DB_STATUS,
1641 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
1642 DB_TRANSACTION, DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK,
1643 DB_VERSION, DB_WAL_HOOK
drh6d313162000-09-21 13:01:35 +00001644 };
tpoindex1067fe12004-12-17 15:41:11 +00001645 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001646
1647 if( objc<2 ){
1648 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001649 return TCL_ERROR;
1650 }
drh411995d2002-06-25 19:31:18 +00001651 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001652 return TCL_ERROR;
1653 }
1654
drh411995d2002-06-25 19:31:18 +00001655 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001656
drhe22a3342003-04-22 20:30:37 +00001657 /* $db authorizer ?CALLBACK?
1658 **
1659 ** Invoke the given callback to authorize each SQL operation as it is
1660 ** compiled. 5 arguments are appended to the callback before it is
1661 ** invoked:
1662 **
1663 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1664 ** (2) First descriptive name (depends on authorization type)
1665 ** (3) Second descriptive name
1666 ** (4) Name of the database (ex: "main", "temp")
1667 ** (5) Name of trigger that is doing the access
1668 **
1669 ** The callback should return on of the following strings: SQLITE_OK,
1670 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1671 **
1672 ** If this method is invoked with no arguments, the current authorization
1673 ** callback string is returned.
1674 */
1675 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001676#ifdef SQLITE_OMIT_AUTHORIZATION
1677 Tcl_AppendResult(interp, "authorization not available in this build", 0);
1678 return TCL_ERROR;
1679#else
drhe22a3342003-04-22 20:30:37 +00001680 if( objc>3 ){
1681 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001682 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001683 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001684 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +00001685 Tcl_AppendResult(interp, pDb->zAuth, 0);
1686 }
1687 }else{
1688 char *zAuth;
1689 int len;
1690 if( pDb->zAuth ){
1691 Tcl_Free(pDb->zAuth);
1692 }
1693 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1694 if( zAuth && len>0 ){
1695 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001696 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001697 }else{
1698 pDb->zAuth = 0;
1699 }
drhe22a3342003-04-22 20:30:37 +00001700 if( pDb->zAuth ){
1701 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001702 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +00001703 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001704 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001705 }
drhe22a3342003-04-22 20:30:37 +00001706 }
drh1211de32004-07-26 12:24:22 +00001707#endif
drhe22a3342003-04-22 20:30:37 +00001708 break;
1709 }
1710
drhdc2c4912009-02-04 22:46:47 +00001711 /* $db backup ?DATABASE? FILENAME
1712 **
1713 ** Open or create a database file named FILENAME. Transfer the
1714 ** content of local database DATABASE (default: "main") into the
1715 ** FILENAME database.
1716 */
1717 case DB_BACKUP: {
1718 const char *zDestFile;
1719 const char *zSrcDb;
1720 sqlite3 *pDest;
1721 sqlite3_backup *pBackup;
1722
1723 if( objc==3 ){
1724 zSrcDb = "main";
1725 zDestFile = Tcl_GetString(objv[2]);
1726 }else if( objc==4 ){
1727 zSrcDb = Tcl_GetString(objv[2]);
1728 zDestFile = Tcl_GetString(objv[3]);
1729 }else{
1730 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1731 return TCL_ERROR;
1732 }
1733 rc = sqlite3_open(zDestFile, &pDest);
1734 if( rc!=SQLITE_OK ){
1735 Tcl_AppendResult(interp, "cannot open target database: ",
1736 sqlite3_errmsg(pDest), (char*)0);
1737 sqlite3_close(pDest);
1738 return TCL_ERROR;
1739 }
1740 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1741 if( pBackup==0 ){
1742 Tcl_AppendResult(interp, "backup failed: ",
1743 sqlite3_errmsg(pDest), (char*)0);
1744 sqlite3_close(pDest);
1745 return TCL_ERROR;
1746 }
1747 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1748 sqlite3_backup_finish(pBackup);
1749 if( rc==SQLITE_DONE ){
1750 rc = TCL_OK;
1751 }else{
1752 Tcl_AppendResult(interp, "backup failed: ",
1753 sqlite3_errmsg(pDest), (char*)0);
1754 rc = TCL_ERROR;
1755 }
1756 sqlite3_close(pDest);
1757 break;
1758 }
1759
drhbec3f402000-08-04 13:49:02 +00001760 /* $db busy ?CALLBACK?
1761 **
1762 ** Invoke the given callback if an SQL statement attempts to open
1763 ** a locked database file.
1764 */
drh6d313162000-09-21 13:01:35 +00001765 case DB_BUSY: {
1766 if( objc>3 ){
1767 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001768 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001769 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001770 if( pDb->zBusy ){
1771 Tcl_AppendResult(interp, pDb->zBusy, 0);
1772 }
1773 }else{
drh6d313162000-09-21 13:01:35 +00001774 char *zBusy;
1775 int len;
drhbec3f402000-08-04 13:49:02 +00001776 if( pDb->zBusy ){
1777 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001778 }
drh6d313162000-09-21 13:01:35 +00001779 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1780 if( zBusy && len>0 ){
1781 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001782 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001783 }else{
1784 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001785 }
1786 if( pDb->zBusy ){
1787 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001788 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001789 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001790 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001791 }
1792 }
drh6d313162000-09-21 13:01:35 +00001793 break;
1794 }
drhbec3f402000-08-04 13:49:02 +00001795
drhfb7e7652005-01-24 00:28:42 +00001796 /* $db cache flush
1797 ** $db cache size n
1798 **
1799 ** Flush the prepared statement cache, or set the maximum number of
1800 ** cached statements.
1801 */
1802 case DB_CACHE: {
1803 char *subCmd;
1804 int n;
1805
1806 if( objc<=2 ){
1807 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1808 return TCL_ERROR;
1809 }
1810 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1811 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1812 if( objc!=3 ){
1813 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1814 return TCL_ERROR;
1815 }else{
1816 flushStmtCache( pDb );
1817 }
1818 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1819 if( objc!=4 ){
1820 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1821 return TCL_ERROR;
1822 }else{
1823 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1824 Tcl_AppendResult( interp, "cannot convert \"",
1825 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1826 return TCL_ERROR;
1827 }else{
1828 if( n<0 ){
1829 flushStmtCache( pDb );
1830 n = 0;
1831 }else if( n>MAX_PREPARED_STMTS ){
1832 n = MAX_PREPARED_STMTS;
1833 }
1834 pDb->maxStmt = n;
1835 }
1836 }
1837 }else{
1838 Tcl_AppendResult( interp, "bad option \"",
danielk1977191fadc2007-10-23 08:17:48 +00001839 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
drhfb7e7652005-01-24 00:28:42 +00001840 return TCL_ERROR;
1841 }
1842 break;
1843 }
1844
danielk1977b28af712004-06-21 06:50:26 +00001845 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001846 **
1847 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001848 ** the most recent INSERT, UPDATE or DELETE statement, not including
1849 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001850 */
1851 case DB_CHANGES: {
1852 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001853 if( objc!=2 ){
1854 Tcl_WrongNumArgs(interp, 2, objv, "");
1855 return TCL_ERROR;
1856 }
drhc8d30ac2002-04-12 10:08:59 +00001857 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001858 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001859 break;
1860 }
1861
drh75897232000-05-29 14:26:00 +00001862 /* $db close
1863 **
1864 ** Shutdown the database
1865 */
drh6d313162000-09-21 13:01:35 +00001866 case DB_CLOSE: {
1867 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1868 break;
1869 }
drh75897232000-05-29 14:26:00 +00001870
drh0f14e2e2004-06-29 12:39:08 +00001871 /*
1872 ** $db collate NAME SCRIPT
1873 **
1874 ** Create a new SQL collation function called NAME. Whenever
1875 ** that function is called, invoke SCRIPT to evaluate the function.
1876 */
1877 case DB_COLLATE: {
1878 SqlCollate *pCollate;
1879 char *zName;
1880 char *zScript;
1881 int nScript;
1882 if( objc!=4 ){
1883 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1884 return TCL_ERROR;
1885 }
1886 zName = Tcl_GetStringFromObj(objv[2], 0);
1887 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1888 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1889 if( pCollate==0 ) return TCL_ERROR;
1890 pCollate->interp = interp;
1891 pCollate->pNext = pDb->pCollate;
1892 pCollate->zScript = (char*)&pCollate[1];
1893 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001894 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001895 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1896 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001897 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001898 return TCL_ERROR;
1899 }
1900 break;
1901 }
1902
1903 /*
1904 ** $db collation_needed SCRIPT
1905 **
1906 ** Create a new SQL collation function called NAME. Whenever
1907 ** that function is called, invoke SCRIPT to evaluate the function.
1908 */
1909 case DB_COLLATION_NEEDED: {
1910 if( objc!=3 ){
1911 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1912 return TCL_ERROR;
1913 }
1914 if( pDb->pCollateNeeded ){
1915 Tcl_DecrRefCount(pDb->pCollateNeeded);
1916 }
1917 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1918 Tcl_IncrRefCount(pDb->pCollateNeeded);
1919 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1920 break;
1921 }
1922
drh19e2d372005-08-29 23:00:03 +00001923 /* $db commit_hook ?CALLBACK?
1924 **
1925 ** Invoke the given callback just before committing every SQL transaction.
1926 ** If the callback throws an exception or returns non-zero, then the
1927 ** transaction is aborted. If CALLBACK is an empty string, the callback
1928 ** is disabled.
1929 */
1930 case DB_COMMIT_HOOK: {
1931 if( objc>3 ){
1932 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1933 return TCL_ERROR;
1934 }else if( objc==2 ){
1935 if( pDb->zCommit ){
1936 Tcl_AppendResult(interp, pDb->zCommit, 0);
1937 }
1938 }else{
1939 char *zCommit;
1940 int len;
1941 if( pDb->zCommit ){
1942 Tcl_Free(pDb->zCommit);
1943 }
1944 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1945 if( zCommit && len>0 ){
1946 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001947 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001948 }else{
1949 pDb->zCommit = 0;
1950 }
1951 if( pDb->zCommit ){
1952 pDb->interp = interp;
1953 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1954 }else{
1955 sqlite3_commit_hook(pDb->db, 0, 0);
1956 }
1957 }
1958 break;
1959 }
1960
drh75897232000-05-29 14:26:00 +00001961 /* $db complete SQL
1962 **
1963 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1964 ** additional lines of input are needed. This is similar to the
1965 ** built-in "info complete" command of Tcl.
1966 */
drh6d313162000-09-21 13:01:35 +00001967 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00001968#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00001969 Tcl_Obj *pResult;
1970 int isComplete;
1971 if( objc!=3 ){
1972 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00001973 return TCL_ERROR;
1974 }
danielk19776f8a5032004-05-10 10:34:51 +00001975 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00001976 pResult = Tcl_GetObjResult(interp);
1977 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00001978#endif
drh6d313162000-09-21 13:01:35 +00001979 break;
1980 }
drhdcd997e2003-01-31 17:21:49 +00001981
drh19e2d372005-08-29 23:00:03 +00001982 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1983 **
1984 ** Copy data into table from filename, optionally using SEPARATOR
1985 ** as column separators. If a column contains a null string, or the
1986 ** value of NULLINDICATOR, a NULL is inserted for the column.
1987 ** conflict-algorithm is one of the sqlite conflict algorithms:
1988 ** rollback, abort, fail, ignore, replace
1989 ** On success, return the number of lines processed, not necessarily same
1990 ** as 'db changes' due to conflict-algorithm selected.
1991 **
1992 ** This code is basically an implementation/enhancement of
1993 ** the sqlite3 shell.c ".import" command.
1994 **
1995 ** This command usage is equivalent to the sqlite2.x COPY statement,
1996 ** which imports file data into a table using the PostgreSQL COPY file format:
1997 ** $db copy $conflit_algo $table_name $filename \t \\N
1998 */
1999 case DB_COPY: {
2000 char *zTable; /* Insert data into this table */
2001 char *zFile; /* The file from which to extract data */
2002 char *zConflict; /* The conflict algorithm to use */
2003 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00002004 int nCol; /* Number of columns in the table */
2005 int nByte; /* Number of bytes in an SQL string */
2006 int i, j; /* Loop counters */
2007 int nSep; /* Number of bytes in zSep[] */
2008 int nNull; /* Number of bytes in zNull[] */
2009 char *zSql; /* An SQL statement */
2010 char *zLine; /* A single line of input from the file */
2011 char **azCol; /* zLine[] broken up into columns */
2012 char *zCommit; /* How to commit changes */
2013 FILE *in; /* The input file */
2014 int lineno = 0; /* Line number of input file */
2015 char zLineNum[80]; /* Line number print buffer */
2016 Tcl_Obj *pResult; /* interp result */
2017
2018 char *zSep;
2019 char *zNull;
2020 if( objc<5 || objc>7 ){
2021 Tcl_WrongNumArgs(interp, 2, objv,
2022 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2023 return TCL_ERROR;
2024 }
2025 if( objc>=6 ){
2026 zSep = Tcl_GetStringFromObj(objv[5], 0);
2027 }else{
2028 zSep = "\t";
2029 }
2030 if( objc>=7 ){
2031 zNull = Tcl_GetStringFromObj(objv[6], 0);
2032 }else{
2033 zNull = "";
2034 }
2035 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2036 zTable = Tcl_GetStringFromObj(objv[3], 0);
2037 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002038 nSep = strlen30(zSep);
2039 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002040 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00002041 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00002042 return TCL_ERROR;
2043 }
drh3e59c012008-09-23 10:12:13 +00002044 if(strcmp(zConflict, "rollback") != 0 &&
2045 strcmp(zConflict, "abort" ) != 0 &&
2046 strcmp(zConflict, "fail" ) != 0 &&
2047 strcmp(zConflict, "ignore" ) != 0 &&
2048 strcmp(zConflict, "replace" ) != 0 ) {
drh19e2d372005-08-29 23:00:03 +00002049 Tcl_AppendResult(interp, "Error: \"", zConflict,
2050 "\", conflict-algorithm must be one of: rollback, "
2051 "abort, fail, ignore, or replace", 0);
2052 return TCL_ERROR;
2053 }
2054 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2055 if( zSql==0 ){
2056 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
2057 return TCL_ERROR;
2058 }
drh4f21c4a2008-12-10 22:15:00 +00002059 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002060 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002061 sqlite3_free(zSql);
2062 if( rc ){
2063 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2064 nCol = 0;
2065 }else{
2066 nCol = sqlite3_column_count(pStmt);
2067 }
2068 sqlite3_finalize(pStmt);
2069 if( nCol==0 ) {
2070 return TCL_ERROR;
2071 }
2072 zSql = malloc( nByte + 50 + nCol*2 );
2073 if( zSql==0 ) {
2074 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
2075 return TCL_ERROR;
2076 }
2077 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2078 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002079 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002080 for(i=1; i<nCol; i++){
2081 zSql[j++] = ',';
2082 zSql[j++] = '?';
2083 }
2084 zSql[j++] = ')';
2085 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002086 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002087 free(zSql);
2088 if( rc ){
2089 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
2090 sqlite3_finalize(pStmt);
2091 return TCL_ERROR;
2092 }
2093 in = fopen(zFile, "rb");
2094 if( in==0 ){
2095 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2096 sqlite3_finalize(pStmt);
2097 return TCL_ERROR;
2098 }
2099 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2100 if( azCol==0 ) {
2101 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00002102 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002103 return TCL_ERROR;
2104 }
drh37527852006-03-16 16:19:56 +00002105 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002106 zCommit = "COMMIT";
2107 while( (zLine = local_getline(0, in))!=0 ){
2108 char *z;
drh19e2d372005-08-29 23:00:03 +00002109 lineno++;
2110 azCol[0] = zLine;
2111 for(i=0, z=zLine; *z; z++){
2112 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2113 *z = 0;
2114 i++;
2115 if( i<nCol ){
2116 azCol[i] = &z[nSep];
2117 z += nSep-1;
2118 }
2119 }
2120 }
2121 if( i+1!=nCol ){
2122 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002123 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002124 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002125 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002126 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002127 "Error: %s line %d: expected %d columns of data but found %d",
2128 zFile, lineno, nCol, i+1);
2129 Tcl_AppendResult(interp, zErr, 0);
2130 free(zErr);
2131 }
drh19e2d372005-08-29 23:00:03 +00002132 zCommit = "ROLLBACK";
2133 break;
2134 }
2135 for(i=0; i<nCol; i++){
2136 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002137 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
drh4f21c4a2008-12-10 22:15:00 +00002138 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002139 ){
drh19e2d372005-08-29 23:00:03 +00002140 sqlite3_bind_null(pStmt, i+1);
2141 }else{
2142 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2143 }
2144 }
2145 sqlite3_step(pStmt);
2146 rc = sqlite3_reset(pStmt);
2147 free(zLine);
2148 if( rc!=SQLITE_OK ){
2149 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
2150 zCommit = "ROLLBACK";
2151 break;
2152 }
2153 }
2154 free(azCol);
2155 fclose(in);
2156 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002157 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002158
2159 if( zCommit[0] == 'C' ){
2160 /* success, set result as number of lines processed */
2161 pResult = Tcl_GetObjResult(interp);
2162 Tcl_SetIntObj(pResult, lineno);
2163 rc = TCL_OK;
2164 }else{
2165 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002166 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00002167 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
2168 rc = TCL_ERROR;
2169 }
2170 break;
2171 }
2172
drhdcd997e2003-01-31 17:21:49 +00002173 /*
drh41449052006-07-06 17:08:48 +00002174 ** $db enable_load_extension BOOLEAN
2175 **
2176 ** Turn the extension loading feature on or off. It if off by
2177 ** default.
2178 */
2179 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002180#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002181 int onoff;
2182 if( objc!=3 ){
2183 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2184 return TCL_ERROR;
2185 }
2186 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2187 return TCL_ERROR;
2188 }
2189 sqlite3_enable_load_extension(pDb->db, onoff);
2190 break;
drhf533acc2006-12-19 18:57:11 +00002191#else
2192 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2193 0);
2194 return TCL_ERROR;
2195#endif
drh41449052006-07-06 17:08:48 +00002196 }
2197
2198 /*
drhdcd997e2003-01-31 17:21:49 +00002199 ** $db errorcode
2200 **
2201 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002202 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002203 */
2204 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002205 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002206 break;
2207 }
dan4a4c11a2009-10-06 14:59:02 +00002208
2209 /*
2210 ** $db exists $sql
2211 ** $db onecolumn $sql
2212 **
2213 ** The onecolumn method is the equivalent of:
2214 ** lindex [$db eval $sql] 0
2215 */
2216 case DB_EXISTS:
2217 case DB_ONECOLUMN: {
2218 DbEvalContext sEval;
2219 if( objc!=3 ){
2220 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2221 return TCL_ERROR;
2222 }
2223
2224 dbEvalInit(&sEval, pDb, objv[2], 0);
2225 rc = dbEvalStep(&sEval);
2226 if( choice==DB_ONECOLUMN ){
2227 if( rc==TCL_OK ){
2228 Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
dand5f12cd2011-08-18 17:47:57 +00002229 }else if( rc==TCL_BREAK ){
2230 Tcl_ResetResult(interp);
dan4a4c11a2009-10-06 14:59:02 +00002231 }
2232 }else if( rc==TCL_BREAK || rc==TCL_OK ){
2233 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
2234 }
2235 dbEvalFinalize(&sEval);
2236
2237 if( rc==TCL_BREAK ){
2238 rc = TCL_OK;
2239 }
2240 break;
2241 }
drh75897232000-05-29 14:26:00 +00002242
2243 /*
drh895d7472004-08-20 16:02:39 +00002244 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002245 **
2246 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002247 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002248 ** If "array" and "code" are omitted, then no callback is every invoked.
2249 ** If "array" is an empty string, then the values are placed in variables
2250 ** that have the same name as the fields extracted by the query.
2251 */
dan4a4c11a2009-10-06 14:59:02 +00002252 case DB_EVAL: {
2253 if( objc<3 || objc>5 ){
2254 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2255 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002256 }
dan4a4c11a2009-10-06 14:59:02 +00002257
drh92febd92004-08-20 18:34:20 +00002258 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002259 DbEvalContext sEval;
2260 Tcl_Obj *pRet = Tcl_NewObj();
2261 Tcl_IncrRefCount(pRet);
2262 dbEvalInit(&sEval, pDb, objv[2], 0);
2263 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2264 int i;
2265 int nCol;
2266 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002267 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002268 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002269 }
2270 }
dan4a4c11a2009-10-06 14:59:02 +00002271 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002272 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002273 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002274 rc = TCL_OK;
2275 }
drh1807ce32004-09-07 13:20:35 +00002276 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002277 }else{
2278 ClientData cd[2];
2279 DbEvalContext *p;
2280 Tcl_Obj *pArray = 0;
2281 Tcl_Obj *pScript;
2282
2283 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2284 pArray = objv[3];
2285 }
2286 pScript = objv[objc-1];
2287 Tcl_IncrRefCount(pScript);
2288
2289 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2290 dbEvalInit(p, pDb, objv[2], pArray);
2291
2292 cd[0] = (void *)p;
2293 cd[1] = (void *)pScript;
2294 rc = DbEvalNextCmd(cd, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002295 }
danielk197730ccda12004-05-27 12:11:31 +00002296 break;
2297 }
drhbec3f402000-08-04 13:49:02 +00002298
2299 /*
drhe3602be2008-09-09 12:31:33 +00002300 ** $db function NAME [-argcount N] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002301 **
2302 ** Create a new SQL function called NAME. Whenever that function is
2303 ** called, invoke SCRIPT to evaluate the function.
2304 */
2305 case DB_FUNCTION: {
2306 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002307 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002308 char *zName;
drhe3602be2008-09-09 12:31:33 +00002309 int nArg = -1;
2310 if( objc==6 ){
2311 const char *z = Tcl_GetString(objv[3]);
drh4f21c4a2008-12-10 22:15:00 +00002312 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002313 if( n>2 && strncmp(z, "-argcount",n)==0 ){
2314 if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
2315 if( nArg<0 ){
2316 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2317 (char*)0);
2318 return TCL_ERROR;
2319 }
2320 }
2321 pScript = objv[5];
2322 }else if( objc!=4 ){
2323 Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
drhcabb0812002-09-14 13:47:32 +00002324 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002325 }else{
2326 pScript = objv[3];
drhcabb0812002-09-14 13:47:32 +00002327 }
2328 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002329 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002330 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002331 if( pFunc->pScript ){
2332 Tcl_DecrRefCount(pFunc->pScript);
2333 }
2334 pFunc->pScript = pScript;
2335 Tcl_IncrRefCount(pScript);
2336 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
drhe3602be2008-09-09 12:31:33 +00002337 rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00002338 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002339 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002340 rc = TCL_ERROR;
2341 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002342 }
drhcabb0812002-09-14 13:47:32 +00002343 break;
2344 }
2345
2346 /*
danielk19778cbadb02007-05-03 16:31:26 +00002347 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002348 */
2349 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002350#ifdef SQLITE_OMIT_INCRBLOB
2351 Tcl_AppendResult(interp, "incrblob not available in this build", 0);
2352 return TCL_ERROR;
2353#else
danielk19778cbadb02007-05-03 16:31:26 +00002354 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002355 const char *zDb = "main";
2356 const char *zTable;
2357 const char *zColumn;
drhb3f787f2012-09-29 14:45:54 +00002358 Tcl_WideInt iRow;
danielk1977b4e9af92007-05-01 17:49:49 +00002359
danielk19778cbadb02007-05-03 16:31:26 +00002360 /* Check for the -readonly option */
2361 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2362 isReadonly = 1;
2363 }
2364
2365 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2366 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002367 return TCL_ERROR;
2368 }
2369
danielk19778cbadb02007-05-03 16:31:26 +00002370 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002371 zDb = Tcl_GetString(objv[2]);
2372 }
2373 zTable = Tcl_GetString(objv[objc-3]);
2374 zColumn = Tcl_GetString(objv[objc-2]);
2375 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2376
2377 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002378 rc = createIncrblobChannel(
2379 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
2380 );
danielk1977b4e9af92007-05-01 17:49:49 +00002381 }
danielk197732a0d8b2007-05-04 19:03:02 +00002382#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002383 break;
2384 }
2385
2386 /*
drhf11bded2006-07-17 00:02:44 +00002387 ** $db interrupt
2388 **
2389 ** Interrupt the execution of the inner-most SQL interpreter. This
2390 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2391 */
2392 case DB_INTERRUPT: {
2393 sqlite3_interrupt(pDb->db);
2394 break;
2395 }
2396
2397 /*
drh19e2d372005-08-29 23:00:03 +00002398 ** $db nullvalue ?STRING?
2399 **
2400 ** Change text used when a NULL comes back from the database. If ?STRING?
2401 ** is not present, then the current string used for NULL is returned.
2402 ** If STRING is present, then STRING is returned.
2403 **
2404 */
2405 case DB_NULLVALUE: {
2406 if( objc!=2 && objc!=3 ){
2407 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2408 return TCL_ERROR;
2409 }
2410 if( objc==3 ){
2411 int len;
2412 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2413 if( pDb->zNull ){
2414 Tcl_Free(pDb->zNull);
2415 }
2416 if( zNull && len>0 ){
2417 pDb->zNull = Tcl_Alloc( len + 1 );
drh7fd33922011-06-20 19:00:30 +00002418 memcpy(pDb->zNull, zNull, len);
drh19e2d372005-08-29 23:00:03 +00002419 pDb->zNull[len] = '\0';
2420 }else{
2421 pDb->zNull = 0;
2422 }
2423 }
drhc45e6712012-10-03 11:02:33 +00002424 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
drh19e2d372005-08-29 23:00:03 +00002425 break;
2426 }
2427
2428 /*
drhaf9ff332002-01-16 21:00:27 +00002429 ** $db last_insert_rowid
2430 **
2431 ** Return an integer which is the ROWID for the most recent insert.
2432 */
2433 case DB_LAST_INSERT_ROWID: {
2434 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002435 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002436 if( objc!=2 ){
2437 Tcl_WrongNumArgs(interp, 2, objv, "");
2438 return TCL_ERROR;
2439 }
danielk19776f8a5032004-05-10 10:34:51 +00002440 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002441 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002442 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002443 break;
2444 }
2445
2446 /*
dan4a4c11a2009-10-06 14:59:02 +00002447 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002448 */
drh1807ce32004-09-07 13:20:35 +00002449
2450 /* $db progress ?N CALLBACK?
2451 **
2452 ** Invoke the given callback every N virtual machine opcodes while executing
2453 ** queries.
2454 */
2455 case DB_PROGRESS: {
2456 if( objc==2 ){
2457 if( pDb->zProgress ){
2458 Tcl_AppendResult(interp, pDb->zProgress, 0);
2459 }
2460 }else if( objc==4 ){
2461 char *zProgress;
2462 int len;
2463 int N;
2464 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002465 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002466 };
2467 if( pDb->zProgress ){
2468 Tcl_Free(pDb->zProgress);
2469 }
2470 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2471 if( zProgress && len>0 ){
2472 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002473 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002474 }else{
2475 pDb->zProgress = 0;
2476 }
2477#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2478 if( pDb->zProgress ){
2479 pDb->interp = interp;
2480 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2481 }else{
2482 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2483 }
2484#endif
2485 }else{
2486 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002487 return TCL_ERROR;
2488 }
drh5d9d7572003-08-19 14:31:01 +00002489 break;
2490 }
2491
drh19e2d372005-08-29 23:00:03 +00002492 /* $db profile ?CALLBACK?
2493 **
2494 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2495 ** that has run. The text of the SQL and the amount of elapse time are
2496 ** appended to CALLBACK before the script is run.
2497 */
2498 case DB_PROFILE: {
2499 if( objc>3 ){
2500 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2501 return TCL_ERROR;
2502 }else if( objc==2 ){
2503 if( pDb->zProfile ){
2504 Tcl_AppendResult(interp, pDb->zProfile, 0);
2505 }
2506 }else{
2507 char *zProfile;
2508 int len;
2509 if( pDb->zProfile ){
2510 Tcl_Free(pDb->zProfile);
2511 }
2512 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2513 if( zProfile && len>0 ){
2514 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002515 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002516 }else{
2517 pDb->zProfile = 0;
2518 }
shanehbb201342011-02-09 19:55:20 +00002519#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh19e2d372005-08-29 23:00:03 +00002520 if( pDb->zProfile ){
2521 pDb->interp = interp;
2522 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2523 }else{
2524 sqlite3_profile(pDb->db, 0, 0);
2525 }
2526#endif
2527 }
2528 break;
2529 }
2530
drh5d9d7572003-08-19 14:31:01 +00002531 /*
drh22fbcb82004-02-01 01:22:50 +00002532 ** $db rekey KEY
2533 **
2534 ** Change the encryption key on the currently open database.
2535 */
2536 case DB_REKEY: {
drhb07028f2011-10-14 21:49:18 +00002537#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002538 int nKey;
2539 void *pKey;
drhb07028f2011-10-14 21:49:18 +00002540#endif
drh22fbcb82004-02-01 01:22:50 +00002541 if( objc!=3 ){
2542 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2543 return TCL_ERROR;
2544 }
drh9eb9e262004-02-11 02:18:05 +00002545#ifdef SQLITE_HAS_CODEC
drhb07028f2011-10-14 21:49:18 +00002546 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh2011d5f2004-07-22 02:40:37 +00002547 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002548 if( rc ){
mistachkin5dac8432012-09-11 02:00:25 +00002549 Tcl_AppendResult(interp, sqlite3_errstr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002550 rc = TCL_ERROR;
2551 }
2552#endif
2553 break;
2554 }
2555
drhdc2c4912009-02-04 22:46:47 +00002556 /* $db restore ?DATABASE? FILENAME
2557 **
2558 ** Open a database file named FILENAME. Transfer the content
2559 ** of FILENAME into the local database DATABASE (default: "main").
2560 */
2561 case DB_RESTORE: {
2562 const char *zSrcFile;
2563 const char *zDestDb;
2564 sqlite3 *pSrc;
2565 sqlite3_backup *pBackup;
2566 int nTimeout = 0;
2567
2568 if( objc==3 ){
2569 zDestDb = "main";
2570 zSrcFile = Tcl_GetString(objv[2]);
2571 }else if( objc==4 ){
2572 zDestDb = Tcl_GetString(objv[2]);
2573 zSrcFile = Tcl_GetString(objv[3]);
2574 }else{
2575 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2576 return TCL_ERROR;
2577 }
2578 rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
2579 if( rc!=SQLITE_OK ){
2580 Tcl_AppendResult(interp, "cannot open source database: ",
2581 sqlite3_errmsg(pSrc), (char*)0);
2582 sqlite3_close(pSrc);
2583 return TCL_ERROR;
2584 }
2585 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2586 if( pBackup==0 ){
2587 Tcl_AppendResult(interp, "restore failed: ",
2588 sqlite3_errmsg(pDb->db), (char*)0);
2589 sqlite3_close(pSrc);
2590 return TCL_ERROR;
2591 }
2592 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2593 || rc==SQLITE_BUSY ){
2594 if( rc==SQLITE_BUSY ){
2595 if( nTimeout++ >= 3 ) break;
2596 sqlite3_sleep(100);
2597 }
2598 }
2599 sqlite3_backup_finish(pBackup);
2600 if( rc==SQLITE_DONE ){
2601 rc = TCL_OK;
2602 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2603 Tcl_AppendResult(interp, "restore failed: source database busy",
2604 (char*)0);
2605 rc = TCL_ERROR;
2606 }else{
2607 Tcl_AppendResult(interp, "restore failed: ",
2608 sqlite3_errmsg(pDb->db), (char*)0);
2609 rc = TCL_ERROR;
2610 }
2611 sqlite3_close(pSrc);
2612 break;
2613 }
2614
drh22fbcb82004-02-01 01:22:50 +00002615 /*
drh3c379b02010-04-07 19:31:59 +00002616 ** $db status (step|sort|autoindex)
drhd1d38482008-10-07 23:46:38 +00002617 **
2618 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2619 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2620 */
2621 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002622 int v;
2623 const char *zOp;
2624 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00002625 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00002626 return TCL_ERROR;
2627 }
2628 zOp = Tcl_GetString(objv[2]);
2629 if( strcmp(zOp, "step")==0 ){
2630 v = pDb->nStep;
2631 }else if( strcmp(zOp, "sort")==0 ){
2632 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002633 }else if( strcmp(zOp, "autoindex")==0 ){
2634 v = pDb->nIndex;
drhd1d38482008-10-07 23:46:38 +00002635 }else{
drh3c379b02010-04-07 19:31:59 +00002636 Tcl_AppendResult(interp,
2637 "bad argument: should be autoindex, step, or sort",
drhd1d38482008-10-07 23:46:38 +00002638 (char*)0);
2639 return TCL_ERROR;
2640 }
2641 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2642 break;
2643 }
2644
2645 /*
drhbec3f402000-08-04 13:49:02 +00002646 ** $db timeout MILLESECONDS
2647 **
2648 ** Delay for the number of milliseconds specified when a file is locked.
2649 */
drh6d313162000-09-21 13:01:35 +00002650 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002651 int ms;
drh6d313162000-09-21 13:01:35 +00002652 if( objc!=3 ){
2653 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002654 return TCL_ERROR;
2655 }
drh6d313162000-09-21 13:01:35 +00002656 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002657 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002658 break;
drh75897232000-05-29 14:26:00 +00002659 }
danielk197755c45f22005-04-03 23:54:43 +00002660
2661 /*
drh0f14e2e2004-06-29 12:39:08 +00002662 ** $db total_changes
2663 **
2664 ** Return the number of rows that were modified, inserted, or deleted
2665 ** since the database handle was created.
2666 */
2667 case DB_TOTAL_CHANGES: {
2668 Tcl_Obj *pResult;
2669 if( objc!=2 ){
2670 Tcl_WrongNumArgs(interp, 2, objv, "");
2671 return TCL_ERROR;
2672 }
2673 pResult = Tcl_GetObjResult(interp);
2674 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2675 break;
2676 }
2677
drhb5a20d32003-04-23 12:25:23 +00002678 /* $db trace ?CALLBACK?
2679 **
2680 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2681 ** that is executed. The text of the SQL is appended to CALLBACK before
2682 ** it is executed.
2683 */
2684 case DB_TRACE: {
2685 if( objc>3 ){
2686 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002687 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002688 }else if( objc==2 ){
2689 if( pDb->zTrace ){
2690 Tcl_AppendResult(interp, pDb->zTrace, 0);
2691 }
2692 }else{
2693 char *zTrace;
2694 int len;
2695 if( pDb->zTrace ){
2696 Tcl_Free(pDb->zTrace);
2697 }
2698 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2699 if( zTrace && len>0 ){
2700 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002701 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002702 }else{
2703 pDb->zTrace = 0;
2704 }
shanehbb201342011-02-09 19:55:20 +00002705#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drhb5a20d32003-04-23 12:25:23 +00002706 if( pDb->zTrace ){
2707 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002708 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002709 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002710 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002711 }
drh19e2d372005-08-29 23:00:03 +00002712#endif
drhb5a20d32003-04-23 12:25:23 +00002713 }
2714 break;
2715 }
2716
drh3d214232005-08-02 12:21:08 +00002717 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2718 **
2719 ** Start a new transaction (if we are not already in the midst of a
2720 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2721 ** completes, either commit the transaction or roll it back if SCRIPT
2722 ** throws an exception. Or if no new transation was started, do nothing.
2723 ** pass the exception on up the stack.
2724 **
2725 ** This command was inspired by Dave Thomas's talk on Ruby at the
2726 ** 2005 O'Reilly Open Source Convention (OSCON).
2727 */
2728 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00002729 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00002730 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00002731 if( objc!=3 && objc!=4 ){
2732 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2733 return TCL_ERROR;
2734 }
danielk1977cd38d522009-01-02 17:33:46 +00002735
dan4a4c11a2009-10-06 14:59:02 +00002736 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00002737 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002738 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002739 };
2740 enum TTYPE_enum {
2741 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2742 };
2743 int ttype;
drhb5555e72005-08-02 17:15:14 +00002744 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002745 0, &ttype) ){
2746 return TCL_ERROR;
2747 }
2748 switch( (enum TTYPE_enum)ttype ){
2749 case TTYPE_DEFERRED: /* no-op */; break;
2750 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2751 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2752 }
drh3d214232005-08-02 12:21:08 +00002753 }
danielk1977cd38d522009-01-02 17:33:46 +00002754 pScript = objv[objc-1];
2755
dan4a4c11a2009-10-06 14:59:02 +00002756 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00002757 pDb->disableAuth++;
2758 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2759 pDb->disableAuth--;
2760 if( rc!=SQLITE_OK ){
2761 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2762 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00002763 }
danielk1977cd38d522009-01-02 17:33:46 +00002764 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00002765
dan4a4c11a2009-10-06 14:59:02 +00002766 /* If using NRE, schedule a callback to invoke the script pScript, then
2767 ** a second callback to commit (or rollback) the transaction or savepoint
2768 ** opened above. If not using NRE, evaluate the script directly, then
2769 ** call function DbTransPostCmd() to commit (or rollback) the transaction
2770 ** or savepoint. */
2771 if( DbUseNre() ){
2772 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
drha47941f2013-12-20 18:57:44 +00002773 (void)Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00002774 }else{
dan4a4c11a2009-10-06 14:59:02 +00002775 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00002776 }
2777 break;
2778 }
2779
danielk197794eb6a12005-12-15 15:22:08 +00002780 /*
danielk1977404ca072009-03-16 13:19:36 +00002781 ** $db unlock_notify ?script?
2782 */
2783 case DB_UNLOCK_NOTIFY: {
2784#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2785 Tcl_AppendResult(interp, "unlock_notify not available in this build", 0);
2786 rc = TCL_ERROR;
2787#else
2788 if( objc!=2 && objc!=3 ){
2789 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2790 rc = TCL_ERROR;
2791 }else{
2792 void (*xNotify)(void **, int) = 0;
2793 void *pNotifyArg = 0;
2794
2795 if( pDb->pUnlockNotify ){
2796 Tcl_DecrRefCount(pDb->pUnlockNotify);
2797 pDb->pUnlockNotify = 0;
2798 }
2799
2800 if( objc==3 ){
2801 xNotify = DbUnlockNotify;
2802 pNotifyArg = (void *)pDb;
2803 pDb->pUnlockNotify = objv[2];
2804 Tcl_IncrRefCount(pDb->pUnlockNotify);
2805 }
2806
2807 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
2808 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2809 rc = TCL_ERROR;
2810 }
2811 }
2812#endif
2813 break;
2814 }
2815
2816 /*
drh833bf962010-04-28 14:42:19 +00002817 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002818 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002819 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002820 */
drh833bf962010-04-28 14:42:19 +00002821 case DB_WAL_HOOK:
danielk197771fd80b2005-12-16 06:54:01 +00002822 case DB_UPDATE_HOOK:
2823 case DB_ROLLBACK_HOOK: {
2824
2825 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2826 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2827 */
2828 Tcl_Obj **ppHook;
2829 if( choice==DB_UPDATE_HOOK ){
2830 ppHook = &pDb->pUpdateHook;
drh833bf962010-04-28 14:42:19 +00002831 }else if( choice==DB_WAL_HOOK ){
drh5def0842010-05-05 20:00:25 +00002832 ppHook = &pDb->pWalHook;
danielk197771fd80b2005-12-16 06:54:01 +00002833 }else{
2834 ppHook = &pDb->pRollbackHook;
2835 }
2836
danielk197794eb6a12005-12-15 15:22:08 +00002837 if( objc!=2 && objc!=3 ){
2838 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2839 return TCL_ERROR;
2840 }
danielk197771fd80b2005-12-16 06:54:01 +00002841 if( *ppHook ){
2842 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002843 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002844 Tcl_DecrRefCount(*ppHook);
2845 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00002846 }
2847 }
2848 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002849 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00002850 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00002851 *ppHook = objv[2];
2852 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002853 }
2854 }
danielk197771fd80b2005-12-16 06:54:01 +00002855
2856 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2857 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
drh5def0842010-05-05 20:00:25 +00002858 sqlite3_wal_hook(pDb->db,(pDb->pWalHook?DbWalHandler:0),pDb);
danielk197771fd80b2005-12-16 06:54:01 +00002859
danielk197794eb6a12005-12-15 15:22:08 +00002860 break;
2861 }
2862
danielk19774397de52005-01-12 12:44:03 +00002863 /* $db version
2864 **
2865 ** Return the version string for this database.
2866 */
2867 case DB_VERSION: {
2868 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2869 break;
2870 }
2871
tpoindex1067fe12004-12-17 15:41:11 +00002872
drh6d313162000-09-21 13:01:35 +00002873 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002874 return rc;
drh75897232000-05-29 14:26:00 +00002875}
2876
drha2c8a952009-10-13 18:38:34 +00002877#if SQLITE_TCL_NRE
2878/*
2879** Adaptor that provides an objCmd interface to the NRE-enabled
2880** interface implementation.
2881*/
2882static int DbObjCmdAdaptor(
2883 void *cd,
2884 Tcl_Interp *interp,
2885 int objc,
2886 Tcl_Obj *const*objv
2887){
2888 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
2889}
2890#endif /* SQLITE_TCL_NRE */
2891
drh75897232000-05-29 14:26:00 +00002892/*
drh3570ad92007-08-31 14:31:44 +00002893** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00002894** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00002895**
2896** This is the main Tcl command. When the "sqlite" Tcl command is
2897** invoked, this routine runs to process that command.
2898**
2899** The first argument, DBNAME, is an arbitrary name for a new
2900** database connection. This command creates a new command named
2901** DBNAME that is used to control that connection. The database
2902** connection is deleted when the DBNAME command is deleted.
2903**
drh3570ad92007-08-31 14:31:44 +00002904** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00002905**
drh75897232000-05-29 14:26:00 +00002906*/
drh22fbcb82004-02-01 01:22:50 +00002907static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002908 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002909 const char *zArg;
drh75897232000-05-29 14:26:00 +00002910 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00002911 int i;
drh22fbcb82004-02-01 01:22:50 +00002912 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00002913 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00002914 int flags;
drh882e8e42006-08-24 02:42:27 +00002915 Tcl_DString translatedFilename;
drhb07028f2011-10-14 21:49:18 +00002916#ifdef SQLITE_HAS_CODEC
2917 void *pKey = 0;
2918 int nKey = 0;
2919#endif
mistachkin540ebf82012-09-10 07:29:29 +00002920 int rc;
drhd9da78a2009-03-24 15:08:09 +00002921
2922 /* In normal use, each TCL interpreter runs in a single thread. So
2923 ** by default, we can turn of mutexing on SQLite database connections.
2924 ** However, for testing purposes it is useful to have mutexes turned
2925 ** on. So, by default, mutexes default off. But if compiled with
2926 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
2927 */
2928#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
2929 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
2930#else
2931 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
2932#endif
2933
drh22fbcb82004-02-01 01:22:50 +00002934 if( objc==2 ){
2935 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002936 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00002937 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00002938 return TCL_OK;
2939 }
drh9eb9e262004-02-11 02:18:05 +00002940 if( strcmp(zArg,"-has-codec")==0 ){
2941#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002942 Tcl_AppendResult(interp,"1",0);
2943#else
2944 Tcl_AppendResult(interp,"0",0);
2945#endif
2946 return TCL_OK;
2947 }
drhfbc3eab2001-04-06 16:13:42 +00002948 }
drh3570ad92007-08-31 14:31:44 +00002949 for(i=3; i+1<objc; i+=2){
2950 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00002951 if( strcmp(zArg,"-key")==0 ){
drhb07028f2011-10-14 21:49:18 +00002952#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00002953 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
drhb07028f2011-10-14 21:49:18 +00002954#endif
drh3570ad92007-08-31 14:31:44 +00002955 }else if( strcmp(zArg, "-vfs")==0 ){
dan3c3dd7b2010-06-22 11:10:40 +00002956 zVfs = Tcl_GetString(objv[i+1]);
drh3570ad92007-08-31 14:31:44 +00002957 }else if( strcmp(zArg, "-readonly")==0 ){
2958 int b;
2959 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2960 if( b ){
drh33f4e022007-09-03 15:19:34 +00002961 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00002962 flags |= SQLITE_OPEN_READONLY;
2963 }else{
2964 flags &= ~SQLITE_OPEN_READONLY;
2965 flags |= SQLITE_OPEN_READWRITE;
2966 }
2967 }else if( strcmp(zArg, "-create")==0 ){
2968 int b;
2969 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00002970 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00002971 flags |= SQLITE_OPEN_CREATE;
2972 }else{
2973 flags &= ~SQLITE_OPEN_CREATE;
2974 }
danielk19779a6284c2008-07-10 17:52:49 +00002975 }else if( strcmp(zArg, "-nomutex")==0 ){
2976 int b;
2977 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2978 if( b ){
2979 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00002980 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00002981 }else{
2982 flags &= ~SQLITE_OPEN_NOMUTEX;
2983 }
danc431fd52011-06-27 16:55:50 +00002984 }else if( strcmp(zArg, "-fullmutex")==0 ){
drh039963a2008-09-03 00:43:15 +00002985 int b;
2986 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2987 if( b ){
2988 flags |= SQLITE_OPEN_FULLMUTEX;
2989 flags &= ~SQLITE_OPEN_NOMUTEX;
2990 }else{
2991 flags &= ~SQLITE_OPEN_FULLMUTEX;
2992 }
drhf12b3f62011-12-21 14:42:29 +00002993 }else if( strcmp(zArg, "-uri")==0 ){
2994 int b;
2995 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2996 if( b ){
2997 flags |= SQLITE_OPEN_URI;
2998 }else{
2999 flags &= ~SQLITE_OPEN_URI;
3000 }
drh3570ad92007-08-31 14:31:44 +00003001 }else{
3002 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3003 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00003004 }
3005 }
drh3570ad92007-08-31 14:31:44 +00003006 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00003007 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00003008 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh68bd4aa2012-01-13 16:16:10 +00003009 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
drh9eb9e262004-02-11 02:18:05 +00003010#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00003011 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00003012#endif
3013 );
drh75897232000-05-29 14:26:00 +00003014 return TCL_ERROR;
3015 }
drh75897232000-05-29 14:26:00 +00003016 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003017 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00003018 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00003019 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
3020 return TCL_ERROR;
3021 }
3022 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00003023 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00003024 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003025 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00003026 Tcl_DStringFree(&translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003027 if( p->db ){
3028 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3029 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3030 sqlite3_close(p->db);
3031 p->db = 0;
3032 }
3033 }else{
mistachkin5dac8432012-09-11 02:00:25 +00003034 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
danielk197780290862004-05-22 09:21:21 +00003035 }
drh2011d5f2004-07-22 02:40:37 +00003036#ifdef SQLITE_HAS_CODEC
drhf3a65f72007-08-22 20:18:21 +00003037 if( p->db ){
3038 sqlite3_key(p->db, pKey, nKey);
3039 }
drheb8ed702004-02-11 10:37:23 +00003040#endif
drhbec3f402000-08-04 13:49:02 +00003041 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003042 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003043 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003044 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003045 return TCL_ERROR;
3046 }
drhfb7e7652005-01-24 00:28:42 +00003047 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00003048 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003049 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003050 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003051 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3052 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003053 }else{
3054 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3055 }
drh75897232000-05-29 14:26:00 +00003056 return TCL_OK;
3057}
3058
3059/*
drh90ca9752001-09-28 17:47:14 +00003060** Provide a dummy Tcl_InitStubs if we are using this as a static
3061** library.
3062*/
3063#ifndef USE_TCL_STUBS
3064# undef Tcl_InitStubs
drh0e85ccf2013-06-03 12:34:46 +00003065# define Tcl_InitStubs(a,b,c) TCL_VERSION
drh90ca9752001-09-28 17:47:14 +00003066#endif
3067
3068/*
drh29bc4612005-10-05 10:40:15 +00003069** Make sure we have a PACKAGE_VERSION macro defined. This will be
3070** defined automatically by the TEA makefile. But other makefiles
3071** do not define it.
3072*/
3073#ifndef PACKAGE_VERSION
3074# define PACKAGE_VERSION SQLITE_VERSION
3075#endif
3076
3077/*
drh75897232000-05-29 14:26:00 +00003078** Initialize this module.
3079**
3080** This Tcl module contains only a single new Tcl command named "sqlite".
3081** (Hence there is no namespace. There is no point in using a namespace
3082** if the extension only supplies one new name!) The "sqlite" command is
3083** used to open a new SQLite database. See the DbMain() routine above
3084** for additional information.
drhb652f432010-08-26 16:46:57 +00003085**
3086** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003087*/
drhb652f432010-08-26 16:46:57 +00003088EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh0e85ccf2013-06-03 12:34:46 +00003089 int rc = Tcl_InitStubs(interp, "8.4", 0)==0 ? TCL_ERROR : TCL_OK;
drh6dc8cbe2013-05-31 15:36:07 +00003090 if( rc==TCL_OK ){
3091 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh1cca0d22010-08-25 20:35:51 +00003092#ifndef SQLITE_3_SUFFIX_ONLY
drh6dc8cbe2013-05-31 15:36:07 +00003093 /* The "sqlite" alias is undocumented. It is here only to support
3094 ** legacy scripts. All new scripts should use only the "sqlite3"
3095 ** command. */
3096 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003097#endif
drh6dc8cbe2013-05-31 15:36:07 +00003098 rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3099 }
3100 return rc;
drh90ca9752001-09-28 17:47:14 +00003101}
drhb652f432010-08-26 16:46:57 +00003102EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
drhb652f432010-08-26 16:46:57 +00003103EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3104EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00003105
drhd878cab2012-03-20 15:10:42 +00003106/* Because it accesses the file-system and uses persistent state, SQLite
3107** is not considered appropriate for safe interpreters. Hence, we deliberately
3108** omit the _SafeInit() interfaces.
3109*/
drh49766d62005-01-08 18:42:28 +00003110
3111#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003112int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3113int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
dana3e63c42010-08-20 12:33:59 +00003114int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3115int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00003116#endif
drh75897232000-05-29 14:26:00 +00003117
drh3e27c022004-07-23 00:01:38 +00003118#ifdef TCLSH
3119/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003120** All of the code that follows is used to build standalone TCL interpreters
3121** that are statically linked with SQLite. Enable these by compiling
3122** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3123** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3124** analysis program.
drh75897232000-05-29 14:26:00 +00003125*/
drh348784e2000-05-29 20:41:49 +00003126
drh57a02272009-10-22 20:52:05 +00003127#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3128/*
3129 * This code implements the MD5 message-digest algorithm.
3130 * The algorithm is due to Ron Rivest. This code was
3131 * written by Colin Plumb in 1993, no copyright is claimed.
3132 * This code is in the public domain; do with it what you wish.
3133 *
3134 * Equivalent code is available from RSA Data Security, Inc.
3135 * This code has been tested against that, and is equivalent,
3136 * except that you don't need to include two pages of legalese
3137 * with every copy.
3138 *
3139 * To compute the message digest of a chunk of bytes, declare an
3140 * MD5Context structure, pass it to MD5Init, call MD5Update as
3141 * needed on buffers full of bytes, and then call MD5Final, which
3142 * will fill a supplied 16-byte array with the digest.
3143 */
3144
3145/*
3146 * If compiled on a machine that doesn't have a 32-bit integer,
3147 * you just set "uint32" to the appropriate datatype for an
3148 * unsigned 32-bit integer. For example:
3149 *
3150 * cc -Duint32='unsigned long' md5.c
3151 *
3152 */
3153#ifndef uint32
3154# define uint32 unsigned int
3155#endif
3156
3157struct MD5Context {
3158 int isInit;
3159 uint32 buf[4];
3160 uint32 bits[2];
3161 unsigned char in[64];
3162};
3163typedef struct MD5Context MD5Context;
3164
3165/*
3166 * Note: this code is harmless on little-endian machines.
3167 */
3168static void byteReverse (unsigned char *buf, unsigned longs){
3169 uint32 t;
3170 do {
3171 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3172 ((unsigned)buf[1]<<8 | buf[0]);
3173 *(uint32 *)buf = t;
3174 buf += 4;
3175 } while (--longs);
3176}
3177/* The four core functions - F1 is optimized somewhat */
3178
3179/* #define F1(x, y, z) (x & y | ~x & z) */
3180#define F1(x, y, z) (z ^ (x & (y ^ z)))
3181#define F2(x, y, z) F1(z, x, y)
3182#define F3(x, y, z) (x ^ y ^ z)
3183#define F4(x, y, z) (y ^ (x | ~z))
3184
3185/* This is the central step in the MD5 algorithm. */
3186#define MD5STEP(f, w, x, y, z, data, s) \
3187 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3188
3189/*
3190 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3191 * reflect the addition of 16 longwords of new data. MD5Update blocks
3192 * the data and converts bytes into longwords for this routine.
3193 */
3194static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3195 register uint32 a, b, c, d;
3196
3197 a = buf[0];
3198 b = buf[1];
3199 c = buf[2];
3200 d = buf[3];
3201
3202 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3203 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3204 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3205 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3206 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3207 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3208 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3209 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3210 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3211 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3212 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3213 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3214 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3215 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3216 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3217 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3218
3219 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3220 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3221 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3222 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3223 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3224 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3225 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3226 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3227 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3228 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3229 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3230 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3231 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3232 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3233 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3234 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3235
3236 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3237 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3238 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3239 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3240 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3241 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3242 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3243 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3244 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3245 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3246 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3247 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3248 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3249 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3250 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3251 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3252
3253 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3254 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3255 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3256 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3257 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3258 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3259 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3260 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3261 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3262 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3263 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3264 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3265 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3266 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3267 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3268 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3269
3270 buf[0] += a;
3271 buf[1] += b;
3272 buf[2] += c;
3273 buf[3] += d;
3274}
3275
3276/*
3277 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3278 * initialization constants.
3279 */
3280static void MD5Init(MD5Context *ctx){
3281 ctx->isInit = 1;
3282 ctx->buf[0] = 0x67452301;
3283 ctx->buf[1] = 0xefcdab89;
3284 ctx->buf[2] = 0x98badcfe;
3285 ctx->buf[3] = 0x10325476;
3286 ctx->bits[0] = 0;
3287 ctx->bits[1] = 0;
3288}
3289
3290/*
3291 * Update context to reflect the concatenation of another buffer full
3292 * of bytes.
3293 */
3294static
3295void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3296 uint32 t;
3297
3298 /* Update bitcount */
3299
3300 t = ctx->bits[0];
3301 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3302 ctx->bits[1]++; /* Carry from low to high */
3303 ctx->bits[1] += len >> 29;
3304
3305 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3306
3307 /* Handle any leading odd-sized chunks */
3308
3309 if ( t ) {
3310 unsigned char *p = (unsigned char *)ctx->in + t;
3311
3312 t = 64-t;
3313 if (len < t) {
3314 memcpy(p, buf, len);
3315 return;
3316 }
3317 memcpy(p, buf, t);
3318 byteReverse(ctx->in, 16);
3319 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3320 buf += t;
3321 len -= t;
3322 }
3323
3324 /* Process data in 64-byte chunks */
3325
3326 while (len >= 64) {
3327 memcpy(ctx->in, buf, 64);
3328 byteReverse(ctx->in, 16);
3329 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3330 buf += 64;
3331 len -= 64;
3332 }
3333
3334 /* Handle any remaining bytes of data. */
3335
3336 memcpy(ctx->in, buf, len);
3337}
3338
3339/*
3340 * Final wrapup - pad to 64-byte boundary with the bit pattern
3341 * 1 0* (64-bit count of bits processed, MSB-first)
3342 */
3343static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3344 unsigned count;
3345 unsigned char *p;
3346
3347 /* Compute number of bytes mod 64 */
3348 count = (ctx->bits[0] >> 3) & 0x3F;
3349
3350 /* Set the first char of padding to 0x80. This is safe since there is
3351 always at least one byte free */
3352 p = ctx->in + count;
3353 *p++ = 0x80;
3354
3355 /* Bytes of padding needed to make 64 bytes */
3356 count = 64 - 1 - count;
3357
3358 /* Pad out to 56 mod 64 */
3359 if (count < 8) {
3360 /* Two lots of padding: Pad the first block to 64 bytes */
3361 memset(p, 0, count);
3362 byteReverse(ctx->in, 16);
3363 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3364
3365 /* Now fill the next block with 56 bytes */
3366 memset(ctx->in, 0, 56);
3367 } else {
3368 /* Pad block to 56 bytes */
3369 memset(p, 0, count-8);
3370 }
3371 byteReverse(ctx->in, 14);
3372
3373 /* Append length in bits and transform */
drha47941f2013-12-20 18:57:44 +00003374 memcpy(ctx->in + 14*4, ctx->bits, 8);
drh57a02272009-10-22 20:52:05 +00003375
3376 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3377 byteReverse((unsigned char *)ctx->buf, 4);
3378 memcpy(digest, ctx->buf, 16);
drh57a02272009-10-22 20:52:05 +00003379}
3380
3381/*
3382** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3383*/
3384static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3385 static char const zEncode[] = "0123456789abcdef";
3386 int i, j;
3387
3388 for(j=i=0; i<16; i++){
3389 int a = digest[i];
3390 zBuf[j++] = zEncode[(a>>4)&0xf];
3391 zBuf[j++] = zEncode[a & 0xf];
3392 }
3393 zBuf[j] = 0;
3394}
3395
3396
3397/*
3398** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3399** each representing 16 bits of the digest and separated from each
3400** other by a "-" character.
3401*/
3402static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3403 int i, j;
3404 unsigned int x;
3405 for(i=j=0; i<16; i+=2){
3406 x = digest[i]*256 + digest[i+1];
3407 if( i>0 ) zDigest[j++] = '-';
3408 sprintf(&zDigest[j], "%05u", x);
3409 j += 5;
3410 }
3411 zDigest[j] = 0;
3412}
3413
3414/*
3415** A TCL command for md5. The argument is the text to be hashed. The
3416** Result is the hash in base64.
3417*/
3418static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3419 MD5Context ctx;
3420 unsigned char digest[16];
3421 char zBuf[50];
3422 void (*converter)(unsigned char*, char*);
3423
3424 if( argc!=2 ){
3425 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3426 " TEXT\"", 0);
3427 return TCL_ERROR;
3428 }
3429 MD5Init(&ctx);
3430 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3431 MD5Final(digest, &ctx);
3432 converter = (void(*)(unsigned char*,char*))cd;
3433 converter(digest, zBuf);
3434 Tcl_AppendResult(interp, zBuf, (char*)0);
3435 return TCL_OK;
3436}
3437
3438/*
3439** A TCL command to take the md5 hash of a file. The argument is the
3440** name of the file.
3441*/
3442static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3443 FILE *in;
3444 MD5Context ctx;
3445 void (*converter)(unsigned char*, char*);
3446 unsigned char digest[16];
3447 char zBuf[10240];
3448
3449 if( argc!=2 ){
3450 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3451 " FILENAME\"", 0);
3452 return TCL_ERROR;
3453 }
3454 in = fopen(argv[1],"rb");
3455 if( in==0 ){
3456 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
3457 "\" for reading", 0);
3458 return TCL_ERROR;
3459 }
3460 MD5Init(&ctx);
3461 for(;;){
3462 int n;
drh83cc1392012-04-19 18:04:28 +00003463 n = (int)fread(zBuf, 1, sizeof(zBuf), in);
drh57a02272009-10-22 20:52:05 +00003464 if( n<=0 ) break;
3465 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3466 }
3467 fclose(in);
3468 MD5Final(digest, &ctx);
3469 converter = (void(*)(unsigned char*,char*))cd;
3470 converter(digest, zBuf);
3471 Tcl_AppendResult(interp, zBuf, (char*)0);
3472 return TCL_OK;
3473}
3474
3475/*
3476** Register the four new TCL commands for generating MD5 checksums
3477** with the TCL interpreter.
3478*/
3479int Md5_Init(Tcl_Interp *interp){
3480 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3481 MD5DigestToBase16, 0);
3482 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3483 MD5DigestToBase10x8, 0);
3484 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3485 MD5DigestToBase16, 0);
3486 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3487 MD5DigestToBase10x8, 0);
3488 return TCL_OK;
3489}
3490#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3491
3492#if defined(SQLITE_TEST)
3493/*
3494** During testing, the special md5sum() aggregate function is available.
3495** inside SQLite. The following routines implement that function.
3496*/
3497static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3498 MD5Context *p;
3499 int i;
3500 if( argc<1 ) return;
3501 p = sqlite3_aggregate_context(context, sizeof(*p));
3502 if( p==0 ) return;
3503 if( !p->isInit ){
3504 MD5Init(p);
3505 }
3506 for(i=0; i<argc; i++){
3507 const char *zData = (char*)sqlite3_value_text(argv[i]);
3508 if( zData ){
drh83cc1392012-04-19 18:04:28 +00003509 MD5Update(p, (unsigned char*)zData, (int)strlen(zData));
drh57a02272009-10-22 20:52:05 +00003510 }
3511 }
3512}
3513static void md5finalize(sqlite3_context *context){
3514 MD5Context *p;
3515 unsigned char digest[16];
3516 char zBuf[33];
3517 p = sqlite3_aggregate_context(context, sizeof(*p));
3518 MD5Final(digest,p);
3519 MD5DigestToBase16(digest, zBuf);
3520 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3521}
3522int Md5_Register(sqlite3 *db){
3523 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
3524 md5step, md5finalize);
3525 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3526 return rc;
3527}
3528#endif /* defined(SQLITE_TEST) */
3529
3530
drh348784e2000-05-29 20:41:49 +00003531/*
drh3e27c022004-07-23 00:01:38 +00003532** If the macro TCLSH is one, then put in code this for the
3533** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003534** standard input, or if a file is named on the command line
3535** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003536*/
drh3e27c022004-07-23 00:01:38 +00003537#if TCLSH==1
dan0ae479d2011-09-21 16:43:07 +00003538static const char *tclsh_main_loop(void){
3539 static const char zMainloop[] =
3540 "set line {}\n"
3541 "while {![eof stdin]} {\n"
3542 "if {$line!=\"\"} {\n"
3543 "puts -nonewline \"> \"\n"
3544 "} else {\n"
3545 "puts -nonewline \"% \"\n"
drh348784e2000-05-29 20:41:49 +00003546 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003547 "flush stdout\n"
3548 "append line [gets stdin]\n"
3549 "if {[info complete $line]} {\n"
3550 "if {[catch {uplevel #0 $line} result]} {\n"
3551 "puts stderr \"Error: $result\"\n"
3552 "} elseif {$result!=\"\"} {\n"
3553 "puts $result\n"
3554 "}\n"
3555 "set line {}\n"
3556 "} else {\n"
3557 "append line \\n\n"
3558 "}\n"
drh348784e2000-05-29 20:41:49 +00003559 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003560 ;
3561 return zMainloop;
3562}
drh3e27c022004-07-23 00:01:38 +00003563#endif
drh3a0f13f2010-07-12 16:47:48 +00003564#if TCLSH==2
dan0ae479d2011-09-21 16:43:07 +00003565static const char *tclsh_main_loop(void);
drh3a0f13f2010-07-12 16:47:48 +00003566#endif
drh3e27c022004-07-23 00:01:38 +00003567
danc1a60c52010-06-07 14:28:16 +00003568#ifdef SQLITE_TEST
3569static void init_all(Tcl_Interp *);
3570static int init_all_cmd(
3571 ClientData cd,
3572 Tcl_Interp *interp,
3573 int objc,
3574 Tcl_Obj *CONST objv[]
3575){
danielk19770a549072009-02-17 16:29:10 +00003576
danc1a60c52010-06-07 14:28:16 +00003577 Tcl_Interp *slave;
3578 if( objc!=2 ){
3579 Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3580 return TCL_ERROR;
3581 }
3582
3583 slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3584 if( !slave ){
3585 return TCL_ERROR;
3586 }
3587
3588 init_all(slave);
3589 return TCL_OK;
3590}
danc431fd52011-06-27 16:55:50 +00003591
3592/*
3593** Tclcmd: db_use_legacy_prepare DB BOOLEAN
3594**
3595** The first argument to this command must be a database command created by
3596** [sqlite3]. If the second argument is true, then the handle is configured
3597** to use the sqlite3_prepare_v2() function to prepare statements. If it
3598** is false, sqlite3_prepare().
3599*/
3600static int db_use_legacy_prepare_cmd(
3601 ClientData cd,
3602 Tcl_Interp *interp,
3603 int objc,
3604 Tcl_Obj *CONST objv[]
3605){
3606 Tcl_CmdInfo cmdInfo;
3607 SqliteDb *pDb;
3608 int bPrepare;
3609
3610 if( objc!=3 ){
3611 Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
3612 return TCL_ERROR;
3613 }
3614
3615 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3616 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3617 return TCL_ERROR;
3618 }
3619 pDb = (SqliteDb*)cmdInfo.objClientData;
3620 if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
3621 return TCL_ERROR;
3622 }
3623
3624 pDb->bLegacyPrepare = bPrepare;
3625
3626 Tcl_ResetResult(interp);
3627 return TCL_OK;
3628}
danc1a60c52010-06-07 14:28:16 +00003629#endif
3630
3631/*
3632** Configure the interpreter passed as the first argument to have access
3633** to the commands and linked variables that make up:
3634**
3635** * the [sqlite3] extension itself,
3636**
3637** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
3638**
3639** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
3640** test suite.
3641*/
3642static void init_all(Tcl_Interp *interp){
drh38f82712004-06-18 17:10:16 +00003643 Sqlite3_Init(interp);
danc1a60c52010-06-07 14:28:16 +00003644
drh57a02272009-10-22 20:52:05 +00003645#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3646 Md5_Init(interp);
3647#endif
danc1a60c52010-06-07 14:28:16 +00003648
dan0ae479d2011-09-21 16:43:07 +00003649 /* Install the [register_dbstat_vtab] command to access the implementation
3650 ** of virtual table dbstat (source file test_stat.c). This command is
3651 ** required for testfixture and sqlite3_analyzer, but not by the production
3652 ** Tcl extension. */
3653#if defined(SQLITE_TEST) || TCLSH==2
3654 {
3655 extern int SqlitetestStat_Init(Tcl_Interp*);
3656 SqlitetestStat_Init(interp);
3657 }
3658#endif
3659
drhd9b02572001-04-15 00:37:09 +00003660#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00003661 {
drh2f999a62007-08-15 19:16:43 +00003662 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00003663 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00003664 extern int Sqlitetest2_Init(Tcl_Interp*);
3665 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00003666 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00003667 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00003668 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00003669 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00003670 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00003671 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00003672 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00003673 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
dan0a7a9152010-04-07 07:57:38 +00003674 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
drh984bfaa2008-03-19 16:08:53 +00003675 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00003676 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00003677 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003678 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00003679 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003680 extern int Sqlitetestschema_Init(Tcl_Interp*);
3681 extern int Sqlitetestsse_Init(Tcl_Interp*);
3682 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
dan9f5ff372013-01-11 09:58:54 +00003683 extern int Sqlitetestfs_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00003684 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00003685 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00003686 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00003687 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh522efc62009-11-10 17:24:37 +00003688 extern int Sqlitetestintarray_Init(Tcl_Interp*);
danc7991bd2010-05-05 19:04:59 +00003689 extern int Sqlitetestvfs_Init(Tcl_Interp *);
dan9508daa2010-08-28 18:58:00 +00003690 extern int Sqlitetestrtree_Init(Tcl_Interp*);
dan8cf35eb2010-09-01 11:40:05 +00003691 extern int Sqlitequota_Init(Tcl_Interp*);
shaneh8a922f72010-11-04 20:50:27 +00003692 extern int Sqlitemultiplex_Init(Tcl_Interp*);
dane336b002010-11-19 18:20:09 +00003693 extern int SqliteSuperlock_Init(Tcl_Interp*);
dan213ca0a2011-03-28 19:10:06 +00003694 extern int SqlitetestSyscall_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00003695
dan6764a702011-06-20 11:15:06 +00003696#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00003697 extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
3698#endif
3699
danb29010c2010-12-29 18:24:38 +00003700#ifdef SQLITE_ENABLE_ZIPVFS
3701 extern int Zipvfs_Init(Tcl_Interp*);
3702 Zipvfs_Init(interp);
3703#endif
3704
drh2f999a62007-08-15 19:16:43 +00003705 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00003706 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00003707 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00003708 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00003709 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00003710 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00003711 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00003712 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00003713 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00003714 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00003715 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00003716 Sqlitetest_autoext_Init(interp);
dan0a7a9152010-04-07 07:57:38 +00003717 Sqlitetest_demovfs_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00003718 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00003719 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00003720 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003721 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00003722 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003723 Sqlitetestschema_Init(interp);
3724 Sqlitetesttclvar_Init(interp);
dan9f5ff372013-01-11 09:58:54 +00003725 Sqlitetestfs_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00003726 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003727 SqlitetestOnefile_Init(interp);
danielk19775d1f5aa2008-04-10 14:51:00 +00003728 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00003729 Sqlitetestbackup_Init(interp);
drh522efc62009-11-10 17:24:37 +00003730 Sqlitetestintarray_Init(interp);
danc7991bd2010-05-05 19:04:59 +00003731 Sqlitetestvfs_Init(interp);
dan9508daa2010-08-28 18:58:00 +00003732 Sqlitetestrtree_Init(interp);
dan8cf35eb2010-09-01 11:40:05 +00003733 Sqlitequota_Init(interp);
shaneh8a922f72010-11-04 20:50:27 +00003734 Sqlitemultiplex_Init(interp);
dane336b002010-11-19 18:20:09 +00003735 SqliteSuperlock_Init(interp);
dan213ca0a2011-03-28 19:10:06 +00003736 SqlitetestSyscall_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003737
dan6764a702011-06-20 11:15:06 +00003738#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00003739 Sqlitetestfts3_Init(interp);
3740#endif
3741
danc431fd52011-06-27 16:55:50 +00003742 Tcl_CreateObjCommand(
3743 interp, "load_testfixture_extensions", init_all_cmd, 0, 0
3744 );
3745 Tcl_CreateObjCommand(
3746 interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
3747 );
danc1a60c52010-06-07 14:28:16 +00003748
drh89dec812005-04-28 19:03:37 +00003749#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00003750 Sqlitetestsse_Init(interp);
3751#endif
drhd1bf3512001-04-07 15:24:33 +00003752 }
3753#endif
danc1a60c52010-06-07 14:28:16 +00003754}
3755
3756#define TCLSH_MAIN main /* Needed to fake out mktclapp */
3757int TCLSH_MAIN(int argc, char **argv){
3758 Tcl_Interp *interp;
mistachkin1f28e072013-08-15 08:06:15 +00003759
3760#if !defined(_WIN32_WCE)
3761 if( getenv("BREAK") ){
3762 fprintf(stderr,
3763 "attach debugger to process %d and press any key to continue.\n",
3764 GETPID());
3765 fgetc(stdin);
3766 }
3767#endif
3768
danc1a60c52010-06-07 14:28:16 +00003769 /* Call sqlite3_shutdown() once before doing anything else. This is to
3770 ** test that sqlite3_shutdown() can be safely called by a process before
3771 ** sqlite3_initialize() is. */
3772 sqlite3_shutdown();
3773
dan0ae479d2011-09-21 16:43:07 +00003774 Tcl_FindExecutable(argv[0]);
3775 interp = Tcl_CreateInterp();
3776
drh3a0f13f2010-07-12 16:47:48 +00003777#if TCLSH==2
3778 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
3779#endif
danc1a60c52010-06-07 14:28:16 +00003780
danc1a60c52010-06-07 14:28:16 +00003781 init_all(interp);
drhc7285972009-11-10 01:13:25 +00003782 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00003783 int i;
shessad42c3a2006-08-22 23:53:46 +00003784 char zArgc[32];
3785 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
3786 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00003787 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
3788 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00003789 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00003790 Tcl_SetVar(interp, "argv", argv[i],
3791 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3792 }
drh3a0f13f2010-07-12 16:47:48 +00003793 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00003794 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00003795 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00003796 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00003797 return 1;
3798 }
drh3e27c022004-07-23 00:01:38 +00003799 }
drh3a0f13f2010-07-12 16:47:48 +00003800 if( TCLSH==2 || argc<=1 ){
dan0ae479d2011-09-21 16:43:07 +00003801 Tcl_GlobalEval(interp, tclsh_main_loop());
drh348784e2000-05-29 20:41:49 +00003802 }
3803 return 0;
3804}
3805#endif /* TCLSH */