blob: 476bdf235e98c10d0c5d567c4e6303840a1b725f [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*/
mistachkin27b2f052015-01-12 19:49:46 +000028
29/*
30** If requested, include the SQLite compiler options file for MSVC.
31*/
32#if defined(INCLUDE_MSVC_H)
33#include "msvc.h"
34#endif
35
drh17a68932001-01-31 13:28:08 +000036#include "tcl.h"
danielk1977b4e9af92007-05-01 17:49:49 +000037#include <errno.h>
drhbd08af42007-04-05 21:58:33 +000038
39/*
40** Some additional include files are needed if this file is not
41** appended to the amalgamation.
42*/
43#ifndef SQLITE_AMALGAMATION
drh65e8c822009-12-01 13:57:48 +000044# include "sqlite3.h"
drhbd08af42007-04-05 21:58:33 +000045# include <stdlib.h>
46# include <string.h>
47# include <assert.h>
drh65e8c822009-12-01 13:57:48 +000048 typedef unsigned char u8;
drhbd08af42007-04-05 21:58:33 +000049#endif
drheb206382009-10-24 15:51:33 +000050#include <ctype.h>
drh75897232000-05-29 14:26:00 +000051
mistachkin1f28e072013-08-15 08:06:15 +000052/* Used to get the current process ID */
53#if !defined(_WIN32)
54# include <unistd.h>
55# define GETPID getpid
56#elif !defined(_WIN32_WCE)
57# ifndef SQLITE_AMALGAMATION
58# define WIN32_LEAN_AND_MEAN
59# include <windows.h>
60# endif
61# define GETPID (int)GetCurrentProcessId
62#endif
63
drhad6e1372006-07-10 21:15:51 +000064/*
65 * Windows needs to know which symbols to export. Unix does not.
66 * BUILD_sqlite should be undefined for Unix.
67 */
68#ifdef BUILD_sqlite
69#undef TCL_STORAGE_CLASS
70#define TCL_STORAGE_CLASS DLLEXPORT
71#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000072
danielk1977a21c6b62005-01-24 10:25:59 +000073#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000074#define MAX_PREPARED_STMTS 100
75
drhc45e6712012-10-03 11:02:33 +000076/* Forward declaration */
77typedef struct SqliteDb SqliteDb;
drh98808ba2001-10-18 12:34:46 +000078
79/*
drhcabb0812002-09-14 13:47:32 +000080** New SQL functions can be created as TCL scripts. Each such function
81** is described by an instance of the following structure.
82*/
83typedef struct SqlFunc SqlFunc;
84struct SqlFunc {
85 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000086 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
drhc45e6712012-10-03 11:02:33 +000087 SqliteDb *pDb; /* Database connection that owns this function */
drhd1e47332005-06-26 17:55:33 +000088 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
89 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000090 SqlFunc *pNext; /* Next function on the list of them all */
91};
92
93/*
danielk19770202b292004-06-09 09:55:16 +000094** New collation sequences function can be created as TCL scripts. Each such
95** function is described by an instance of the following structure.
96*/
97typedef struct SqlCollate SqlCollate;
98struct SqlCollate {
99 Tcl_Interp *interp; /* The TCL interpret to execute the function */
100 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +0000101 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +0000102};
103
104/*
drhfb7e7652005-01-24 00:28:42 +0000105** Prepared statements are cached for faster execution. Each prepared
106** statement is described by an instance of the following structure.
107*/
108typedef struct SqlPreparedStmt SqlPreparedStmt;
109struct SqlPreparedStmt {
110 SqlPreparedStmt *pNext; /* Next in linked list */
111 SqlPreparedStmt *pPrev; /* Previous on the list */
112 sqlite3_stmt *pStmt; /* The prepared statement */
113 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +0000114 const char *zSql; /* Text of the SQL statement */
dan4a4c11a2009-10-06 14:59:02 +0000115 int nParm; /* Size of apParm array */
116 Tcl_Obj **apParm; /* Array of referenced object pointers */
drhfb7e7652005-01-24 00:28:42 +0000117};
118
danielk1977d04417962007-05-02 13:16:30 +0000119typedef struct IncrblobChannel IncrblobChannel;
120
drhfb7e7652005-01-24 00:28:42 +0000121/*
drhbec3f402000-08-04 13:49:02 +0000122** There is one instance of this structure for each SQLite database
123** that has been opened by the SQLite TCL interface.
danc431fd52011-06-27 16:55:50 +0000124**
125** If this module is built with SQLITE_TEST defined (to create the SQLite
126** testfixture executable), then it may be configured to use either
127** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
128** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
drhbec3f402000-08-04 13:49:02 +0000129*/
drhbec3f402000-08-04 13:49:02 +0000130struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000131 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000132 Tcl_Interp *interp; /* The interpreter used for this database */
133 char *zBusy; /* The busy callback routine */
134 char *zCommit; /* The commit hook callback routine */
135 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +0000136 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000137 char *zProgress; /* The progress callback routine */
138 char *zAuth; /* The authorization callback routine */
drh1f1549f2008-08-26 21:33:34 +0000139 int disableAuth; /* Disable the authorizer if it exists */
drhd1e47332005-06-26 17:55:33 +0000140 char *zNull; /* Text to substitute for an SQL NULL value */
141 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000142 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
dan46c47d42011-03-01 18:42:07 +0000143 Tcl_Obj *pPreUpdateHook; /* Pre-update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000144 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drh5def0842010-05-05 20:00:25 +0000145 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000146 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000147 SqlCollate *pCollate; /* List of SQL collation functions */
148 int rc; /* Return code of most recent sqlite3_exec() */
149 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000150 SqlPreparedStmt *stmtList; /* List of prepared statements*/
151 SqlPreparedStmt *stmtLast; /* Last statement in the list */
152 int maxStmt; /* The next maximum number of stmtList */
153 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000154 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh3c379b02010-04-07 19:31:59 +0000155 int nStep, nSort, nIndex; /* Statistics for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000156 int nTransaction; /* Number of nested [transaction] methods */
drh147ef392016-01-22 23:17:51 +0000157 int openFlags; /* Flags used to open. (SQLITE_OPEN_URI) */
danc431fd52011-06-27 16:55:50 +0000158#ifdef SQLITE_TEST
159 int bLegacyPrepare; /* True to use sqlite3_prepare() */
160#endif
drh98808ba2001-10-18 12:34:46 +0000161};
drh297ecf12001-04-05 15:57:13 +0000162
danielk1977b4e9af92007-05-01 17:49:49 +0000163struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000164 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000165 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000166 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000167 Tcl_Channel channel; /* Channel identifier */
168 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
169 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000170};
171
drhea678832008-12-10 19:26:22 +0000172/*
173** Compute a string length that is limited to what can be stored in
174** lower 30 bits of a 32-bit signed integer.
175*/
drh4f21c4a2008-12-10 22:15:00 +0000176static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000177 const char *z2 = z;
178 while( *z2 ){ z2++; }
179 return 0x3fffffff & (int)(z2 - z);
180}
drhea678832008-12-10 19:26:22 +0000181
182
danielk197732a0d8b2007-05-04 19:03:02 +0000183#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000184/*
danielk1977d04417962007-05-02 13:16:30 +0000185** Close all incrblob channels opened using database connection pDb.
186** This is called when shutting down the database connection.
187*/
188static void closeIncrblobChannels(SqliteDb *pDb){
189 IncrblobChannel *p;
190 IncrblobChannel *pNext;
191
192 for(p=pDb->pIncrblob; p; p=pNext){
193 pNext = p->pNext;
194
195 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
196 ** which deletes the IncrblobChannel structure at *p. So do not
197 ** call Tcl_Free() here.
198 */
199 Tcl_UnregisterChannel(pDb->interp, p->channel);
200 }
201}
202
203/*
danielk1977b4e9af92007-05-01 17:49:49 +0000204** Close an incremental blob channel.
205*/
206static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
207 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000208 int rc = sqlite3_blob_close(p->pBlob);
209 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000210
211 /* Remove the channel from the SqliteDb.pIncrblob list. */
212 if( p->pNext ){
213 p->pNext->pPrev = p->pPrev;
214 }
215 if( p->pPrev ){
216 p->pPrev->pNext = p->pNext;
217 }
218 if( p->pDb->pIncrblob==p ){
219 p->pDb->pIncrblob = p->pNext;
220 }
221
danielk197792d4d7a2007-05-04 12:05:56 +0000222 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000223 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000224
225 if( rc!=SQLITE_OK ){
226 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
227 return TCL_ERROR;
228 }
danielk1977b4e9af92007-05-01 17:49:49 +0000229 return TCL_OK;
230}
231
232/*
233** Read data from an incremental blob channel.
234*/
235static int incrblobInput(
236 ClientData instanceData,
237 char *buf,
238 int bufSize,
239 int *errorCodePtr
240){
241 IncrblobChannel *p = (IncrblobChannel *)instanceData;
242 int nRead = bufSize; /* Number of bytes to read */
243 int nBlob; /* Total size of the blob */
244 int rc; /* sqlite error code */
245
246 nBlob = sqlite3_blob_bytes(p->pBlob);
247 if( (p->iSeek+nRead)>nBlob ){
248 nRead = nBlob-p->iSeek;
249 }
250 if( nRead<=0 ){
251 return 0;
252 }
253
254 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
255 if( rc!=SQLITE_OK ){
256 *errorCodePtr = rc;
257 return -1;
258 }
259
260 p->iSeek += nRead;
261 return nRead;
262}
263
danielk1977d04417962007-05-02 13:16:30 +0000264/*
265** Write data to an incremental blob channel.
266*/
danielk1977b4e9af92007-05-01 17:49:49 +0000267static int incrblobOutput(
268 ClientData instanceData,
269 CONST char *buf,
270 int toWrite,
271 int *errorCodePtr
272){
273 IncrblobChannel *p = (IncrblobChannel *)instanceData;
274 int nWrite = toWrite; /* Number of bytes to write */
275 int nBlob; /* Total size of the blob */
276 int rc; /* sqlite error code */
277
278 nBlob = sqlite3_blob_bytes(p->pBlob);
279 if( (p->iSeek+nWrite)>nBlob ){
280 *errorCodePtr = EINVAL;
281 return -1;
282 }
283 if( nWrite<=0 ){
284 return 0;
285 }
286
287 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
288 if( rc!=SQLITE_OK ){
289 *errorCodePtr = EIO;
290 return -1;
291 }
292
293 p->iSeek += nWrite;
294 return nWrite;
295}
296
297/*
298** Seek an incremental blob channel.
299*/
300static int incrblobSeek(
301 ClientData instanceData,
302 long offset,
303 int seekMode,
304 int *errorCodePtr
305){
306 IncrblobChannel *p = (IncrblobChannel *)instanceData;
307
308 switch( seekMode ){
309 case SEEK_SET:
310 p->iSeek = offset;
311 break;
312 case SEEK_CUR:
313 p->iSeek += offset;
314 break;
315 case SEEK_END:
316 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
317 break;
318
319 default: assert(!"Bad seekMode");
320 }
321
322 return p->iSeek;
323}
324
325
326static void incrblobWatch(ClientData instanceData, int mode){
327 /* NO-OP */
328}
329static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
330 return TCL_ERROR;
331}
332
333static Tcl_ChannelType IncrblobChannelType = {
334 "incrblob", /* typeName */
335 TCL_CHANNEL_VERSION_2, /* version */
336 incrblobClose, /* closeProc */
337 incrblobInput, /* inputProc */
338 incrblobOutput, /* outputProc */
339 incrblobSeek, /* seekProc */
340 0, /* setOptionProc */
341 0, /* getOptionProc */
342 incrblobWatch, /* watchProc (this is a no-op) */
343 incrblobHandle, /* getHandleProc (always returns error) */
344 0, /* close2Proc */
345 0, /* blockModeProc */
346 0, /* flushProc */
347 0, /* handlerProc */
348 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000349};
350
351/*
352** Create a new incrblob channel.
353*/
354static int createIncrblobChannel(
355 Tcl_Interp *interp,
356 SqliteDb *pDb,
357 const char *zDb,
358 const char *zTable,
359 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000360 sqlite_int64 iRow,
361 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000362){
363 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000364 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000365 sqlite3_blob *pBlob;
366 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000367 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000368
369 /* This variable is used to name the channels: "incrblob_[incr count]" */
370 static int count = 0;
371 char zChannel[64];
372
danielk19778cbadb02007-05-03 16:31:26 +0000373 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000374 if( rc!=SQLITE_OK ){
375 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
376 return TCL_ERROR;
377 }
378
379 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
380 p->iSeek = 0;
381 p->pBlob = pBlob;
382
drh5bb3eb92007-05-04 13:15:55 +0000383 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000384 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
385 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000386
danielk1977d04417962007-05-02 13:16:30 +0000387 /* Link the new channel into the SqliteDb.pIncrblob list. */
388 p->pNext = pDb->pIncrblob;
389 p->pPrev = 0;
390 if( p->pNext ){
391 p->pNext->pPrev = p;
392 }
393 pDb->pIncrblob = p;
394 p->pDb = pDb;
395
396 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000397 return TCL_OK;
398}
danielk197732a0d8b2007-05-04 19:03:02 +0000399#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
400 #define closeIncrblobChannels(pDb)
401#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000402
drh6d313162000-09-21 13:01:35 +0000403/*
drhd1e47332005-06-26 17:55:33 +0000404** Look at the script prefix in pCmd. We will be executing this script
405** after first appending one or more arguments. This routine analyzes
406** the script to see if it is safe to use Tcl_EvalObjv() on the script
407** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
408** faster.
409**
410** Scripts that are safe to use with Tcl_EvalObjv() consists of a
411** command name followed by zero or more arguments with no [...] or $
412** or {...} or ; to be seen anywhere. Most callback scripts consist
413** of just a single procedure name and they meet this requirement.
414*/
415static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
416 /* We could try to do something with Tcl_Parse(). But we will instead
417 ** just do a search for forbidden characters. If any of the forbidden
418 ** characters appear in pCmd, we will report the string as unsafe.
419 */
420 const char *z;
421 int n;
422 z = Tcl_GetStringFromObj(pCmd, &n);
423 while( n-- > 0 ){
424 int c = *(z++);
425 if( c=='$' || c=='[' || c==';' ) return 0;
426 }
427 return 1;
428}
429
430/*
431** Find an SqlFunc structure with the given name. Or create a new
432** one if an existing one cannot be found. Return a pointer to the
433** structure.
434*/
435static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
436 SqlFunc *p, *pNew;
drh0425f182013-11-26 16:48:04 +0000437 int nName = strlen30(zName);
438 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
drhd1e47332005-06-26 17:55:33 +0000439 pNew->zName = (char*)&pNew[1];
drh0425f182013-11-26 16:48:04 +0000440 memcpy(pNew->zName, zName, nName+1);
drhd1e47332005-06-26 17:55:33 +0000441 for(p=pDb->pFunc; p; p=p->pNext){
drh0425f182013-11-26 16:48:04 +0000442 if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
drhd1e47332005-06-26 17:55:33 +0000443 Tcl_Free((char*)pNew);
444 return p;
445 }
446 }
447 pNew->interp = pDb->interp;
drhc45e6712012-10-03 11:02:33 +0000448 pNew->pDb = pDb;
drhd1e47332005-06-26 17:55:33 +0000449 pNew->pScript = 0;
450 pNew->pNext = pDb->pFunc;
451 pDb->pFunc = pNew;
452 return pNew;
453}
454
455/*
danc431fd52011-06-27 16:55:50 +0000456** Free a single SqlPreparedStmt object.
457*/
458static void dbFreeStmt(SqlPreparedStmt *pStmt){
459#ifdef SQLITE_TEST
460 if( sqlite3_sql(pStmt->pStmt)==0 ){
461 Tcl_Free((char *)pStmt->zSql);
462 }
463#endif
464 sqlite3_finalize(pStmt->pStmt);
465 Tcl_Free((char *)pStmt);
466}
467
468/*
drhfb7e7652005-01-24 00:28:42 +0000469** Finalize and free a list of prepared statements
470*/
danc431fd52011-06-27 16:55:50 +0000471static void flushStmtCache(SqliteDb *pDb){
drhfb7e7652005-01-24 00:28:42 +0000472 SqlPreparedStmt *pPreStmt;
danc431fd52011-06-27 16:55:50 +0000473 SqlPreparedStmt *pNext;
drhfb7e7652005-01-24 00:28:42 +0000474
danc431fd52011-06-27 16:55:50 +0000475 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
476 pNext = pPreStmt->pNext;
477 dbFreeStmt(pPreStmt);
drhfb7e7652005-01-24 00:28:42 +0000478 }
479 pDb->nStmt = 0;
480 pDb->stmtLast = 0;
danc431fd52011-06-27 16:55:50 +0000481 pDb->stmtList = 0;
drhfb7e7652005-01-24 00:28:42 +0000482}
483
484/*
drh895d7472004-08-20 16:02:39 +0000485** TCL calls this procedure when an sqlite3 database command is
486** deleted.
drh75897232000-05-29 14:26:00 +0000487*/
488static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000489 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000490 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000491 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000492 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000493 while( pDb->pFunc ){
494 SqlFunc *pFunc = pDb->pFunc;
495 pDb->pFunc = pFunc->pNext;
drhc45e6712012-10-03 11:02:33 +0000496 assert( pFunc->pDb==pDb );
drhd1e47332005-06-26 17:55:33 +0000497 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000498 Tcl_Free((char*)pFunc);
499 }
danielk19770202b292004-06-09 09:55:16 +0000500 while( pDb->pCollate ){
501 SqlCollate *pCollate = pDb->pCollate;
502 pDb->pCollate = pCollate->pNext;
503 Tcl_Free((char*)pCollate);
504 }
drhbec3f402000-08-04 13:49:02 +0000505 if( pDb->zBusy ){
506 Tcl_Free(pDb->zBusy);
507 }
drhb5a20d32003-04-23 12:25:23 +0000508 if( pDb->zTrace ){
509 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000510 }
drh19e2d372005-08-29 23:00:03 +0000511 if( pDb->zProfile ){
512 Tcl_Free(pDb->zProfile);
513 }
drhe22a3342003-04-22 20:30:37 +0000514 if( pDb->zAuth ){
515 Tcl_Free(pDb->zAuth);
516 }
danielk197755c45f22005-04-03 23:54:43 +0000517 if( pDb->zNull ){
518 Tcl_Free(pDb->zNull);
519 }
danielk197794eb6a12005-12-15 15:22:08 +0000520 if( pDb->pUpdateHook ){
521 Tcl_DecrRefCount(pDb->pUpdateHook);
522 }
dan46c47d42011-03-01 18:42:07 +0000523 if( pDb->pPreUpdateHook ){
524 Tcl_DecrRefCount(pDb->pPreUpdateHook);
525 }
danielk197771fd80b2005-12-16 06:54:01 +0000526 if( pDb->pRollbackHook ){
527 Tcl_DecrRefCount(pDb->pRollbackHook);
528 }
drh5def0842010-05-05 20:00:25 +0000529 if( pDb->pWalHook ){
530 Tcl_DecrRefCount(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000531 }
danielk197794eb6a12005-12-15 15:22:08 +0000532 if( pDb->pCollateNeeded ){
533 Tcl_DecrRefCount(pDb->pCollateNeeded);
534 }
drhbec3f402000-08-04 13:49:02 +0000535 Tcl_Free((char*)pDb);
536}
537
538/*
539** This routine is called when a database file is locked while trying
540** to execute SQL.
541*/
danielk19772a764eb2004-06-12 01:43:26 +0000542static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000543 SqliteDb *pDb = (SqliteDb*)cd;
544 int rc;
545 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000546
drh5bb3eb92007-05-04 13:15:55 +0000547 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000548 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000549 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
550 return 0;
551 }
552 return 1;
drh75897232000-05-29 14:26:00 +0000553}
554
drh26e4a8b2008-05-01 17:16:52 +0000555#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000556/*
danielk1977348bb5d2003-10-18 09:37:26 +0000557** This routine is invoked as the 'progress callback' for the database.
558*/
559static int DbProgressHandler(void *cd){
560 SqliteDb *pDb = (SqliteDb*)cd;
561 int rc;
562
563 assert( pDb->zProgress );
564 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
565 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
566 return 1;
567 }
568 return 0;
569}
drh26e4a8b2008-05-01 17:16:52 +0000570#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000571
drhd1167392006-01-23 13:00:35 +0000572#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000573/*
drhb5a20d32003-04-23 12:25:23 +0000574** This routine is called by the SQLite trace handler whenever a new
575** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000576*/
drhb5a20d32003-04-23 12:25:23 +0000577static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000578 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000579 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000580
drhb5a20d32003-04-23 12:25:23 +0000581 Tcl_DStringInit(&str);
582 Tcl_DStringAppend(&str, pDb->zTrace, -1);
583 Tcl_DStringAppendElement(&str, zSql);
584 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
585 Tcl_DStringFree(&str);
586 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000587}
drhd1167392006-01-23 13:00:35 +0000588#endif
drh0d1a6432003-04-03 15:46:04 +0000589
drhd1167392006-01-23 13:00:35 +0000590#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000591/*
drh19e2d372005-08-29 23:00:03 +0000592** This routine is called by the SQLite profile handler after a statement
593** SQL has executed. The TCL script in pDb->zProfile is evaluated.
594*/
595static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
596 SqliteDb *pDb = (SqliteDb*)cd;
597 Tcl_DString str;
598 char zTm[100];
599
600 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
601 Tcl_DStringInit(&str);
602 Tcl_DStringAppend(&str, pDb->zProfile, -1);
603 Tcl_DStringAppendElement(&str, zSql);
604 Tcl_DStringAppendElement(&str, zTm);
605 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
606 Tcl_DStringFree(&str);
607 Tcl_ResetResult(pDb->interp);
608}
drhd1167392006-01-23 13:00:35 +0000609#endif
drh19e2d372005-08-29 23:00:03 +0000610
611/*
drhaa940ea2004-01-15 02:44:03 +0000612** This routine is called when a transaction is committed. The
613** TCL script in pDb->zCommit is executed. If it returns non-zero or
614** if it throws an exception, the transaction is rolled back instead
615** of being committed.
616*/
617static int DbCommitHandler(void *cd){
618 SqliteDb *pDb = (SqliteDb*)cd;
619 int rc;
620
621 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
622 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
623 return 1;
624 }
625 return 0;
626}
627
danielk197771fd80b2005-12-16 06:54:01 +0000628static void DbRollbackHandler(void *clientData){
629 SqliteDb *pDb = (SqliteDb*)clientData;
630 assert(pDb->pRollbackHook);
631 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
632 Tcl_BackgroundError(pDb->interp);
633 }
634}
635
drh5def0842010-05-05 20:00:25 +0000636/*
637** This procedure handles wal_hook callbacks.
638*/
639static int DbWalHandler(
dan8d22a172010-04-19 18:03:51 +0000640 void *clientData,
641 sqlite3 *db,
642 const char *zDb,
643 int nEntry
644){
drh5def0842010-05-05 20:00:25 +0000645 int ret = SQLITE_OK;
dan8d22a172010-04-19 18:03:51 +0000646 Tcl_Obj *p;
647 SqliteDb *pDb = (SqliteDb*)clientData;
648 Tcl_Interp *interp = pDb->interp;
drh5def0842010-05-05 20:00:25 +0000649 assert(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000650
dan6e45e0c2014-12-10 20:29:49 +0000651 assert( db==pDb->db );
drh5def0842010-05-05 20:00:25 +0000652 p = Tcl_DuplicateObj(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000653 Tcl_IncrRefCount(p);
654 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
655 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
656 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
657 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
658 ){
659 Tcl_BackgroundError(interp);
660 }
661 Tcl_DecrRefCount(p);
662
663 return ret;
664}
665
drhbcf4f482009-03-27 12:44:35 +0000666#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000667static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
668 char zBuf[64];
drh65545b52015-01-19 00:35:53 +0000669 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
danielk1977404ca072009-03-16 13:19:36 +0000670 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
drh65545b52015-01-19 00:35:53 +0000671 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
danielk1977404ca072009-03-16 13:19:36 +0000672 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
673}
674#else
drhbcf4f482009-03-27 12:44:35 +0000675# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000676#endif
677
drh69910da2009-03-27 12:32:54 +0000678#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000679static void DbUnlockNotify(void **apArg, int nArg){
680 int i;
681 for(i=0; i<nArg; i++){
682 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
683 SqliteDb *pDb = (SqliteDb *)apArg[i];
684 setTestUnlockNotifyVars(pDb->interp, i, nArg);
685 assert( pDb->pUnlockNotify);
686 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
687 Tcl_DecrRefCount(pDb->pUnlockNotify);
688 pDb->pUnlockNotify = 0;
689 }
690}
drh69910da2009-03-27 12:32:54 +0000691#endif
danielk1977404ca072009-03-16 13:19:36 +0000692
drh9b1c62d2011-03-30 21:04:43 +0000693#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +0000694/*
695** Pre-update hook callback.
696*/
697static void DbPreUpdateHandler(
698 void *p,
699 sqlite3 *db,
700 int op,
701 const char *zDb,
702 const char *zTbl,
703 sqlite_int64 iKey1,
704 sqlite_int64 iKey2
705){
706 SqliteDb *pDb = (SqliteDb *)p;
707 Tcl_Obj *pCmd;
708 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
709
710 assert( (SQLITE_DELETE-1)/9 == 0 );
711 assert( (SQLITE_INSERT-1)/9 == 1 );
712 assert( (SQLITE_UPDATE-1)/9 == 2 );
713 assert( pDb->pPreUpdateHook );
714 assert( db==pDb->db );
715 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
716
717 pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
718 Tcl_IncrRefCount(pCmd);
719 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
720 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
721 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
722 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
723 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
724 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
725 Tcl_DecrRefCount(pCmd);
726}
drh9b1c62d2011-03-30 21:04:43 +0000727#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +0000728
danielk197794eb6a12005-12-15 15:22:08 +0000729static void DbUpdateHandler(
730 void *p,
731 int op,
732 const char *zDb,
733 const char *zTbl,
734 sqlite_int64 rowid
735){
736 SqliteDb *pDb = (SqliteDb *)p;
737 Tcl_Obj *pCmd;
dan46c47d42011-03-01 18:42:07 +0000738 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
739
740 assert( (SQLITE_DELETE-1)/9 == 0 );
741 assert( (SQLITE_INSERT-1)/9 == 1 );
742 assert( (SQLITE_UPDATE-1)/9 == 2 );
danielk197794eb6a12005-12-15 15:22:08 +0000743
744 assert( pDb->pUpdateHook );
745 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
746
747 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
748 Tcl_IncrRefCount(pCmd);
dan46c47d42011-03-01 18:42:07 +0000749 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
danielk197794eb6a12005-12-15 15:22:08 +0000750 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
751 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
752 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
753 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
drhefdde162010-10-27 15:36:21 +0000754 Tcl_DecrRefCount(pCmd);
danielk197794eb6a12005-12-15 15:22:08 +0000755}
756
danielk19777cedc8d2004-06-10 10:50:08 +0000757static void tclCollateNeeded(
758 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000759 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000760 int enc,
761 const char *zName
762){
763 SqliteDb *pDb = (SqliteDb *)pCtx;
764 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
765 Tcl_IncrRefCount(pScript);
766 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
767 Tcl_EvalObjEx(pDb->interp, pScript, 0);
768 Tcl_DecrRefCount(pScript);
769}
770
drhaa940ea2004-01-15 02:44:03 +0000771/*
danielk19770202b292004-06-09 09:55:16 +0000772** This routine is called to evaluate an SQL collation function implemented
773** using TCL script.
774*/
775static int tclSqlCollate(
776 void *pCtx,
777 int nA,
778 const void *zA,
779 int nB,
780 const void *zB
781){
782 SqlCollate *p = (SqlCollate *)pCtx;
783 Tcl_Obj *pCmd;
784
785 pCmd = Tcl_NewStringObj(p->zScript, -1);
786 Tcl_IncrRefCount(pCmd);
787 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
788 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000789 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000790 Tcl_DecrRefCount(pCmd);
791 return (atoi(Tcl_GetStringResult(p->interp)));
792}
793
794/*
drhcabb0812002-09-14 13:47:32 +0000795** This routine is called to evaluate an SQL function implemented
796** using TCL script.
797*/
drhfb7e7652005-01-24 00:28:42 +0000798static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000799 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000800 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000801 int i;
802 int rc;
803
drhd1e47332005-06-26 17:55:33 +0000804 if( argc==0 ){
805 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
806 ** script object directly. This allows the TCL compiler to generate
807 ** bytecode for the command on the first invocation and thus make
808 ** subsequent invocations much faster. */
809 pCmd = p->pScript;
810 Tcl_IncrRefCount(pCmd);
811 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
812 Tcl_DecrRefCount(pCmd);
813 }else{
814 /* If there are arguments to the function, make a shallow copy of the
815 ** script object, lappend the arguments, then evaluate the copy.
816 **
peter.d.reid60ec9142014-09-06 16:39:46 +0000817 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
drhd1e47332005-06-26 17:55:33 +0000818 ** The new Tcl_Obj contains pointers to the original list elements.
819 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
820 ** of the list to tclCmdNameType, that alternate representation will
821 ** be preserved and reused on the next invocation.
822 */
823 Tcl_Obj **aArg;
824 int nArg;
825 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
826 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
827 return;
828 }
829 pCmd = Tcl_NewListObj(nArg, aArg);
830 Tcl_IncrRefCount(pCmd);
831 for(i=0; i<argc; i++){
832 sqlite3_value *pIn = argv[i];
833 Tcl_Obj *pVal;
834
835 /* Set pVal to contain the i'th column of this row. */
836 switch( sqlite3_value_type(pIn) ){
837 case SQLITE_BLOB: {
838 int bytes = sqlite3_value_bytes(pIn);
839 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
840 break;
841 }
842 case SQLITE_INTEGER: {
843 sqlite_int64 v = sqlite3_value_int64(pIn);
844 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +0000845 pVal = Tcl_NewIntObj((int)v);
drhd1e47332005-06-26 17:55:33 +0000846 }else{
847 pVal = Tcl_NewWideIntObj(v);
848 }
849 break;
850 }
851 case SQLITE_FLOAT: {
852 double r = sqlite3_value_double(pIn);
853 pVal = Tcl_NewDoubleObj(r);
854 break;
855 }
856 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +0000857 pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
drhd1e47332005-06-26 17:55:33 +0000858 break;
859 }
860 default: {
861 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000862 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000863 break;
864 }
865 }
866 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
867 if( rc ){
868 Tcl_DecrRefCount(pCmd);
869 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
870 return;
871 }
danielk197751ad0ec2004-05-24 12:39:02 +0000872 }
drhd1e47332005-06-26 17:55:33 +0000873 if( !p->useEvalObjv ){
874 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
875 ** is a list without a string representation. To prevent this from
876 ** happening, make sure pCmd has a valid string representation */
877 Tcl_GetString(pCmd);
878 }
879 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
880 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000881 }
danielk1977562e8d32005-05-20 09:40:55 +0000882
drhc7f269d2005-05-05 10:30:29 +0000883 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000884 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000885 }else{
drhc7f269d2005-05-05 10:30:29 +0000886 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
887 int n;
888 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000889 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000890 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000891 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000892 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000893 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000894 data = Tcl_GetByteArrayFromObj(pVar, &n);
895 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000896 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000897 Tcl_GetIntFromObj(0, pVar, &n);
898 sqlite3_result_int(context, n);
899 }else if( c=='d' && strcmp(zType,"double")==0 ){
900 double r;
901 Tcl_GetDoubleFromObj(0, pVar, &r);
902 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +0000903 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
904 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000905 Tcl_WideInt v;
906 Tcl_GetWideIntFromObj(0, pVar, &v);
907 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000908 }else{
danielk197700fd9572005-12-07 06:27:43 +0000909 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
910 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000911 }
drhcabb0812002-09-14 13:47:32 +0000912 }
913}
drh895d7472004-08-20 16:02:39 +0000914
drhe22a3342003-04-22 20:30:37 +0000915#ifndef SQLITE_OMIT_AUTHORIZATION
916/*
917** This is the authentication function. It appends the authentication
918** type code and the two arguments to zCmd[] then invokes the result
919** on the interpreter. The reply is examined to determine if the
920** authentication fails or succeeds.
921*/
922static int auth_callback(
923 void *pArg,
924 int code,
925 const char *zArg1,
926 const char *zArg2,
927 const char *zArg3,
928 const char *zArg4
drh32c6a482014-09-11 13:44:52 +0000929#ifdef SQLITE_USER_AUTHENTICATION
930 ,const char *zArg5
931#endif
drhe22a3342003-04-22 20:30:37 +0000932){
mistachkin6ef5e122014-01-24 17:03:55 +0000933 const char *zCode;
drhe22a3342003-04-22 20:30:37 +0000934 Tcl_DString str;
935 int rc;
936 const char *zReply;
937 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +0000938 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +0000939
940 switch( code ){
941 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
942 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
943 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
944 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
945 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
946 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
947 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
948 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
949 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
950 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
951 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
952 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
953 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
954 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
955 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
956 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
957 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
958 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
959 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
960 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
961 case SQLITE_READ : zCode="SQLITE_READ"; break;
962 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
963 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
964 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000965 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
966 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000967 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000968 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000969 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000970 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
971 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000972 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +0000973 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drh65a2aaa2014-01-16 22:40:02 +0000974 case SQLITE_RECURSIVE : zCode="SQLITE_RECURSIVE"; break;
drhe22a3342003-04-22 20:30:37 +0000975 default : zCode="????"; break;
976 }
977 Tcl_DStringInit(&str);
978 Tcl_DStringAppend(&str, pDb->zAuth, -1);
979 Tcl_DStringAppendElement(&str, zCode);
980 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
981 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
982 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
983 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
drh32c6a482014-09-11 13:44:52 +0000984#ifdef SQLITE_USER_AUTHENTICATION
985 Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
986#endif
drhe22a3342003-04-22 20:30:37 +0000987 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
988 Tcl_DStringFree(&str);
drhb07028f2011-10-14 21:49:18 +0000989 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
drhe22a3342003-04-22 20:30:37 +0000990 if( strcmp(zReply,"SQLITE_OK")==0 ){
991 rc = SQLITE_OK;
992 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
993 rc = SQLITE_DENY;
994 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
995 rc = SQLITE_IGNORE;
996 }else{
997 rc = 999;
998 }
999 return rc;
1000}
1001#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +00001002
1003/*
tpoindex1067fe12004-12-17 15:41:11 +00001004** This routine reads a line of text from FILE in, stores
1005** the text in memory obtained from malloc() and returns a pointer
1006** to the text. NULL is returned at end of file, or if malloc()
1007** fails.
1008**
1009** The interface is like "readline" but no command-line editing
1010** is done.
1011**
1012** copied from shell.c from '.import' command
1013*/
1014static char *local_getline(char *zPrompt, FILE *in){
1015 char *zLine;
1016 int nLine;
1017 int n;
tpoindex1067fe12004-12-17 15:41:11 +00001018
1019 nLine = 100;
1020 zLine = malloc( nLine );
1021 if( zLine==0 ) return 0;
1022 n = 0;
drhb07028f2011-10-14 21:49:18 +00001023 while( 1 ){
tpoindex1067fe12004-12-17 15:41:11 +00001024 if( n+100>nLine ){
1025 nLine = nLine*2 + 100;
1026 zLine = realloc(zLine, nLine);
1027 if( zLine==0 ) return 0;
1028 }
1029 if( fgets(&zLine[n], nLine - n, in)==0 ){
1030 if( n==0 ){
1031 free(zLine);
1032 return 0;
1033 }
1034 zLine[n] = 0;
tpoindex1067fe12004-12-17 15:41:11 +00001035 break;
1036 }
1037 while( zLine[n] ){ n++; }
1038 if( n>0 && zLine[n-1]=='\n' ){
1039 n--;
1040 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +00001041 break;
tpoindex1067fe12004-12-17 15:41:11 +00001042 }
1043 }
1044 zLine = realloc( zLine, n+1 );
1045 return zLine;
1046}
1047
danielk19778e556522007-11-13 10:30:24 +00001048
1049/*
dan4a4c11a2009-10-06 14:59:02 +00001050** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +00001051**
dan4a4c11a2009-10-06 14:59:02 +00001052** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +00001053**
dan4a4c11a2009-10-06 14:59:02 +00001054** It is invoked after evaluating the script SCRIPT to commit or rollback
1055** the transaction or savepoint opened by the [transaction] command.
1056*/
1057static int DbTransPostCmd(
1058 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1059 Tcl_Interp *interp, /* Tcl interpreter */
1060 int result /* Result of evaluating SCRIPT */
1061){
mistachkin6ef5e122014-01-24 17:03:55 +00001062 static const char *const azEnd[] = {
dan4a4c11a2009-10-06 14:59:02 +00001063 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1064 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1065 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1066 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1067 };
1068 SqliteDb *pDb = (SqliteDb*)data[0];
1069 int rc = result;
1070 const char *zEnd;
1071
1072 pDb->nTransaction--;
1073 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1074
1075 pDb->disableAuth++;
1076 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1077 /* This is a tricky scenario to handle. The most likely cause of an
1078 ** error is that the exec() above was an attempt to commit the
1079 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
mistachkin48864df2013-03-21 21:20:32 +00001080 ** that an IO-error has occurred. In either case, throw a Tcl exception
dan4a4c11a2009-10-06 14:59:02 +00001081 ** and try to rollback the transaction.
1082 **
1083 ** But it could also be that the user executed one or more BEGIN,
1084 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1085 ** this method's logic. Not clear how this would be best handled.
1086 */
1087 if( rc!=TCL_ERROR ){
drha198f2b2014-02-07 19:26:13 +00001088 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
dan4a4c11a2009-10-06 14:59:02 +00001089 rc = TCL_ERROR;
1090 }
1091 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1092 }
1093 pDb->disableAuth--;
1094
1095 return rc;
1096}
1097
1098/*
danc431fd52011-06-27 16:55:50 +00001099** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1100** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1101** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1102** on whether or not the [db_use_legacy_prepare] command has been used to
1103** configure the connection.
1104*/
1105static int dbPrepare(
1106 SqliteDb *pDb, /* Database object */
1107 const char *zSql, /* SQL to compile */
1108 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1109 const char **pzOut /* OUT: Pointer to next SQL statement */
1110){
1111#ifdef SQLITE_TEST
1112 if( pDb->bLegacyPrepare ){
1113 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1114 }
1115#endif
1116 return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut);
1117}
1118
1119/*
dan4a4c11a2009-10-06 14:59:02 +00001120** Search the cache for a prepared-statement object that implements the
1121** first SQL statement in the buffer pointed to by parameter zIn. If
1122** no such prepared-statement can be found, allocate and prepare a new
1123** one. In either case, bind the current values of the relevant Tcl
1124** variables to any $var, :var or @var variables in the statement. Before
1125** returning, set *ppPreStmt to point to the prepared-statement object.
1126**
1127** Output parameter *pzOut is set to point to the next SQL statement in
1128** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1129** next statement.
1130**
1131** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1132** and an error message loaded into interpreter pDb->interp.
1133*/
1134static int dbPrepareAndBind(
1135 SqliteDb *pDb, /* Database object */
1136 char const *zIn, /* SQL to compile */
1137 char const **pzOut, /* OUT: Pointer to next SQL statement */
1138 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1139){
1140 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
mistachkin7bb22ac2015-01-12 19:59:12 +00001141 sqlite3_stmt *pStmt = 0; /* Prepared statement object */
dan4a4c11a2009-10-06 14:59:02 +00001142 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1143 int nSql; /* Length of zSql in bytes */
mistachkin7bb22ac2015-01-12 19:59:12 +00001144 int nVar = 0; /* Number of variables in statement */
dan4a4c11a2009-10-06 14:59:02 +00001145 int iParm = 0; /* Next free entry in apParm */
drh0425f182013-11-26 16:48:04 +00001146 char c;
dan4a4c11a2009-10-06 14:59:02 +00001147 int i;
1148 Tcl_Interp *interp = pDb->interp;
1149
1150 *ppPreStmt = 0;
1151
1152 /* Trim spaces from the start of zSql and calculate the remaining length. */
drh0425f182013-11-26 16:48:04 +00001153 while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
dan4a4c11a2009-10-06 14:59:02 +00001154 nSql = strlen30(zSql);
1155
1156 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1157 int n = pPreStmt->nSql;
1158 if( nSql>=n
1159 && memcmp(pPreStmt->zSql, zSql, n)==0
1160 && (zSql[n]==0 || zSql[n-1]==';')
1161 ){
1162 pStmt = pPreStmt->pStmt;
1163 *pzOut = &zSql[pPreStmt->nSql];
1164
1165 /* When a prepared statement is found, unlink it from the
1166 ** cache list. It will later be added back to the beginning
1167 ** of the cache list in order to implement LRU replacement.
1168 */
1169 if( pPreStmt->pPrev ){
1170 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1171 }else{
1172 pDb->stmtList = pPreStmt->pNext;
1173 }
1174 if( pPreStmt->pNext ){
1175 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1176 }else{
1177 pDb->stmtLast = pPreStmt->pPrev;
1178 }
1179 pDb->nStmt--;
1180 nVar = sqlite3_bind_parameter_count(pStmt);
1181 break;
1182 }
1183 }
1184
1185 /* If no prepared statement was found. Compile the SQL text. Also allocate
1186 ** a new SqlPreparedStmt structure. */
1187 if( pPreStmt==0 ){
1188 int nByte;
1189
danc431fd52011-06-27 16:55:50 +00001190 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
drhc45e6712012-10-03 11:02:33 +00001191 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001192 return TCL_ERROR;
1193 }
1194 if( pStmt==0 ){
1195 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1196 /* A compile-time error in the statement. */
drhc45e6712012-10-03 11:02:33 +00001197 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001198 return TCL_ERROR;
1199 }else{
1200 /* The statement was a no-op. Continue to the next statement
1201 ** in the SQL string.
1202 */
1203 return TCL_OK;
1204 }
1205 }
1206
1207 assert( pPreStmt==0 );
1208 nVar = sqlite3_bind_parameter_count(pStmt);
1209 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1210 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1211 memset(pPreStmt, 0, nByte);
1212
1213 pPreStmt->pStmt = pStmt;
drh7ed243b2012-04-19 17:19:51 +00001214 pPreStmt->nSql = (int)(*pzOut - zSql);
dan4a4c11a2009-10-06 14:59:02 +00001215 pPreStmt->zSql = sqlite3_sql(pStmt);
1216 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
danc431fd52011-06-27 16:55:50 +00001217#ifdef SQLITE_TEST
1218 if( pPreStmt->zSql==0 ){
1219 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1220 memcpy(zCopy, zSql, pPreStmt->nSql);
1221 zCopy[pPreStmt->nSql] = '\0';
1222 pPreStmt->zSql = zCopy;
1223 }
1224#endif
dan4a4c11a2009-10-06 14:59:02 +00001225 }
1226 assert( pPreStmt );
1227 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1228 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1229
1230 /* Bind values to parameters that begin with $ or : */
1231 for(i=1; i<=nVar; i++){
1232 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1233 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1234 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1235 if( pVar ){
1236 int n;
1237 u8 *data;
1238 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
mistachkin8e189222015-04-19 21:43:16 +00001239 c = zType[0];
dan4a4c11a2009-10-06 14:59:02 +00001240 if( zVar[0]=='@' ||
1241 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1242 /* Load a BLOB type if the Tcl variable is a bytearray and
1243 ** it has no string representation or the host
1244 ** parameter name begins with "@". */
1245 data = Tcl_GetByteArrayFromObj(pVar, &n);
1246 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1247 Tcl_IncrRefCount(pVar);
1248 pPreStmt->apParm[iParm++] = pVar;
1249 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1250 Tcl_GetIntFromObj(interp, pVar, &n);
1251 sqlite3_bind_int(pStmt, i, n);
1252 }else if( c=='d' && strcmp(zType,"double")==0 ){
1253 double r;
1254 Tcl_GetDoubleFromObj(interp, pVar, &r);
1255 sqlite3_bind_double(pStmt, i, r);
1256 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1257 (c=='i' && strcmp(zType,"int")==0) ){
1258 Tcl_WideInt v;
1259 Tcl_GetWideIntFromObj(interp, pVar, &v);
1260 sqlite3_bind_int64(pStmt, i, v);
1261 }else{
1262 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1263 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1264 Tcl_IncrRefCount(pVar);
1265 pPreStmt->apParm[iParm++] = pVar;
1266 }
1267 }else{
1268 sqlite3_bind_null(pStmt, i);
1269 }
1270 }
1271 }
1272 pPreStmt->nParm = iParm;
1273 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001274
dan4a4c11a2009-10-06 14:59:02 +00001275 return TCL_OK;
1276}
1277
dan4a4c11a2009-10-06 14:59:02 +00001278/*
1279** Release a statement reference obtained by calling dbPrepareAndBind().
1280** There should be exactly one call to this function for each call to
1281** dbPrepareAndBind().
1282**
1283** If the discard parameter is non-zero, then the statement is deleted
1284** immediately. Otherwise it is added to the LRU list and may be returned
1285** by a subsequent call to dbPrepareAndBind().
1286*/
1287static void dbReleaseStmt(
1288 SqliteDb *pDb, /* Database handle */
1289 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1290 int discard /* True to delete (not cache) the pPreStmt */
1291){
1292 int i;
1293
1294 /* Free the bound string and blob parameters */
1295 for(i=0; i<pPreStmt->nParm; i++){
1296 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1297 }
1298 pPreStmt->nParm = 0;
1299
1300 if( pDb->maxStmt<=0 || discard ){
1301 /* If the cache is turned off, deallocated the statement */
danc431fd52011-06-27 16:55:50 +00001302 dbFreeStmt(pPreStmt);
dan4a4c11a2009-10-06 14:59:02 +00001303 }else{
1304 /* Add the prepared statement to the beginning of the cache list. */
1305 pPreStmt->pNext = pDb->stmtList;
1306 pPreStmt->pPrev = 0;
1307 if( pDb->stmtList ){
1308 pDb->stmtList->pPrev = pPreStmt;
1309 }
1310 pDb->stmtList = pPreStmt;
1311 if( pDb->stmtLast==0 ){
1312 assert( pDb->nStmt==0 );
1313 pDb->stmtLast = pPreStmt;
1314 }else{
1315 assert( pDb->nStmt>0 );
1316 }
1317 pDb->nStmt++;
1318
1319 /* If we have too many statement in cache, remove the surplus from
1320 ** the end of the cache list. */
1321 while( pDb->nStmt>pDb->maxStmt ){
danc431fd52011-06-27 16:55:50 +00001322 SqlPreparedStmt *pLast = pDb->stmtLast;
1323 pDb->stmtLast = pLast->pPrev;
dan4a4c11a2009-10-06 14:59:02 +00001324 pDb->stmtLast->pNext = 0;
1325 pDb->nStmt--;
danc431fd52011-06-27 16:55:50 +00001326 dbFreeStmt(pLast);
dan4a4c11a2009-10-06 14:59:02 +00001327 }
1328 }
1329}
1330
1331/*
1332** Structure used with dbEvalXXX() functions:
1333**
1334** dbEvalInit()
1335** dbEvalStep()
1336** dbEvalFinalize()
1337** dbEvalRowInfo()
1338** dbEvalColumnValue()
1339*/
1340typedef struct DbEvalContext DbEvalContext;
1341struct DbEvalContext {
1342 SqliteDb *pDb; /* Database handle */
1343 Tcl_Obj *pSql; /* Object holding string zSql */
1344 const char *zSql; /* Remaining SQL to execute */
1345 SqlPreparedStmt *pPreStmt; /* Current statement */
1346 int nCol; /* Number of columns returned by pStmt */
1347 Tcl_Obj *pArray; /* Name of array variable */
1348 Tcl_Obj **apColName; /* Array of column names */
1349};
1350
1351/*
1352** Release any cache of column names currently held as part of
1353** the DbEvalContext structure passed as the first argument.
1354*/
1355static void dbReleaseColumnNames(DbEvalContext *p){
1356 if( p->apColName ){
1357 int i;
1358 for(i=0; i<p->nCol; i++){
1359 Tcl_DecrRefCount(p->apColName[i]);
1360 }
1361 Tcl_Free((char *)p->apColName);
1362 p->apColName = 0;
1363 }
1364 p->nCol = 0;
1365}
1366
1367/*
1368** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001369**
1370** If pArray is not NULL, then it contains the name of a Tcl array
1371** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001372** the names of the columns returned by the statement as part of each
1373** call to dbEvalStep(), in order from left to right. e.g. if the names
1374** of the returned columns are a, b and c, it does the equivalent of the
1375** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001376**
1377** set ${pArray}(*) {a b c}
1378*/
dan4a4c11a2009-10-06 14:59:02 +00001379static void dbEvalInit(
1380 DbEvalContext *p, /* Pointer to structure to initialize */
1381 SqliteDb *pDb, /* Database handle */
1382 Tcl_Obj *pSql, /* Object containing SQL script */
1383 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001384){
dan4a4c11a2009-10-06 14:59:02 +00001385 memset(p, 0, sizeof(DbEvalContext));
1386 p->pDb = pDb;
1387 p->zSql = Tcl_GetString(pSql);
1388 p->pSql = pSql;
1389 Tcl_IncrRefCount(pSql);
1390 if( pArray ){
1391 p->pArray = pArray;
1392 Tcl_IncrRefCount(pArray);
1393 }
1394}
danielk19778e556522007-11-13 10:30:24 +00001395
dan4a4c11a2009-10-06 14:59:02 +00001396/*
1397** Obtain information about the row that the DbEvalContext passed as the
1398** first argument currently points to.
1399*/
1400static void dbEvalRowInfo(
1401 DbEvalContext *p, /* Evaluation context */
1402 int *pnCol, /* OUT: Number of column names */
1403 Tcl_Obj ***papColName /* OUT: Array of column names */
1404){
danielk19778e556522007-11-13 10:30:24 +00001405 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001406 if( 0==p->apColName ){
1407 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1408 int i; /* Iterator variable */
1409 int nCol; /* Number of columns returned by pStmt */
1410 Tcl_Obj **apColName = 0; /* Array of column names */
1411
1412 p->nCol = nCol = sqlite3_column_count(pStmt);
1413 if( nCol>0 && (papColName || p->pArray) ){
1414 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1415 for(i=0; i<nCol; i++){
drhc45e6712012-10-03 11:02:33 +00001416 apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
dan4a4c11a2009-10-06 14:59:02 +00001417 Tcl_IncrRefCount(apColName[i]);
1418 }
1419 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001420 }
1421
1422 /* If results are being stored in an array variable, then create
1423 ** the array(*) entry for that array
1424 */
dan4a4c11a2009-10-06 14:59:02 +00001425 if( p->pArray ){
1426 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001427 Tcl_Obj *pColList = Tcl_NewObj();
1428 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001429
danielk19778e556522007-11-13 10:30:24 +00001430 for(i=0; i<nCol; i++){
1431 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1432 }
1433 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001434 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001435 Tcl_DecrRefCount(pStar);
1436 }
danielk19778e556522007-11-13 10:30:24 +00001437 }
1438
dan4a4c11a2009-10-06 14:59:02 +00001439 if( papColName ){
1440 *papColName = p->apColName;
1441 }
1442 if( pnCol ){
1443 *pnCol = p->nCol;
1444 }
1445}
1446
1447/*
1448** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1449** returned, then an error message is stored in the interpreter before
1450** returning.
1451**
1452** A return value of TCL_OK means there is a row of data available. The
1453** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1454** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1455** is returned, then the SQL script has finished executing and there are
1456** no further rows available. This is similar to SQLITE_DONE.
1457*/
1458static int dbEvalStep(DbEvalContext *p){
danc431fd52011-06-27 16:55:50 +00001459 const char *zPrevSql = 0; /* Previous value of p->zSql */
1460
dan4a4c11a2009-10-06 14:59:02 +00001461 while( p->zSql[0] || p->pPreStmt ){
1462 int rc;
1463 if( p->pPreStmt==0 ){
danc431fd52011-06-27 16:55:50 +00001464 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
dan4a4c11a2009-10-06 14:59:02 +00001465 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1466 if( rc!=TCL_OK ) return rc;
1467 }else{
1468 int rcs;
1469 SqliteDb *pDb = p->pDb;
1470 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1471 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1472
1473 rcs = sqlite3_step(pStmt);
1474 if( rcs==SQLITE_ROW ){
1475 return TCL_OK;
1476 }
1477 if( p->pArray ){
1478 dbEvalRowInfo(p, 0, 0);
1479 }
1480 rcs = sqlite3_reset(pStmt);
1481
1482 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1483 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001484 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
dan4a4c11a2009-10-06 14:59:02 +00001485 dbReleaseColumnNames(p);
1486 p->pPreStmt = 0;
1487
1488 if( rcs!=SQLITE_OK ){
1489 /* If a run-time error occurs, report the error and stop reading
1490 ** the SQL. */
dan4a4c11a2009-10-06 14:59:02 +00001491 dbReleaseStmt(pDb, pPreStmt, 1);
danc431fd52011-06-27 16:55:50 +00001492#if SQLITE_TEST
1493 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1494 /* If the runtime error was an SQLITE_SCHEMA, and the database
1495 ** handle is configured to use the legacy sqlite3_prepare()
1496 ** interface, retry prepare()/step() on the same SQL statement.
1497 ** This only happens once. If there is a second SQLITE_SCHEMA
1498 ** error, the error will be returned to the caller. */
1499 p->zSql = zPrevSql;
1500 continue;
1501 }
1502#endif
drhc45e6712012-10-03 11:02:33 +00001503 Tcl_SetObjResult(pDb->interp,
1504 Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001505 return TCL_ERROR;
1506 }else{
1507 dbReleaseStmt(pDb, pPreStmt, 0);
1508 }
1509 }
1510 }
1511
1512 /* Finished */
1513 return TCL_BREAK;
1514}
1515
1516/*
1517** Free all resources currently held by the DbEvalContext structure passed
1518** as the first argument. There should be exactly one call to this function
1519** for each call to dbEvalInit().
1520*/
1521static void dbEvalFinalize(DbEvalContext *p){
1522 if( p->pPreStmt ){
1523 sqlite3_reset(p->pPreStmt->pStmt);
1524 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1525 p->pPreStmt = 0;
1526 }
1527 if( p->pArray ){
1528 Tcl_DecrRefCount(p->pArray);
1529 p->pArray = 0;
1530 }
1531 Tcl_DecrRefCount(p->pSql);
1532 dbReleaseColumnNames(p);
1533}
1534
1535/*
1536** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1537** the value for the iCol'th column of the row currently pointed to by
1538** the DbEvalContext structure passed as the first argument.
1539*/
1540static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1541 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1542 switch( sqlite3_column_type(pStmt, iCol) ){
1543 case SQLITE_BLOB: {
1544 int bytes = sqlite3_column_bytes(pStmt, iCol);
1545 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1546 if( !zBlob ) bytes = 0;
1547 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1548 }
1549 case SQLITE_INTEGER: {
1550 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1551 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +00001552 return Tcl_NewIntObj((int)v);
dan4a4c11a2009-10-06 14:59:02 +00001553 }else{
1554 return Tcl_NewWideIntObj(v);
1555 }
1556 }
1557 case SQLITE_FLOAT: {
1558 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1559 }
1560 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +00001561 return Tcl_NewStringObj(p->pDb->zNull, -1);
dan4a4c11a2009-10-06 14:59:02 +00001562 }
1563 }
1564
drh325eff52012-10-03 12:56:18 +00001565 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
dan4a4c11a2009-10-06 14:59:02 +00001566}
1567
1568/*
1569** If using Tcl version 8.6 or greater, use the NR functions to avoid
1570** recursive evalution of scripts by the [db eval] and [db trans]
1571** commands. Even if the headers used while compiling the extension
1572** are 8.6 or newer, the code still tests the Tcl version at runtime.
1573** This allows stubs-enabled builds to be used with older Tcl libraries.
1574*/
1575#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001576# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001577static int DbUseNre(void){
1578 int major, minor;
1579 Tcl_GetVersion(&major, &minor, 0, 0);
1580 return( (major==8 && minor>=6) || major>8 );
1581}
1582#else
1583/*
1584** Compiling using headers earlier than 8.6. In this case NR cannot be
1585** used, so DbUseNre() to always return zero. Add #defines for the other
1586** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1587** even though the only invocations of them are within conditional blocks
1588** of the form:
1589**
1590** if( DbUseNre() ) { ... }
1591*/
drha2c8a952009-10-13 18:38:34 +00001592# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001593# define DbUseNre() 0
drha47941f2013-12-20 18:57:44 +00001594# define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001595# define Tcl_NREvalObj(a,b,c) 0
drha47941f2013-12-20 18:57:44 +00001596# define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001597#endif
1598
1599/*
1600** This function is part of the implementation of the command:
1601**
1602** $db eval SQL ?ARRAYNAME? SCRIPT
1603*/
1604static int DbEvalNextCmd(
1605 ClientData data[], /* data[0] is the (DbEvalContext*) */
1606 Tcl_Interp *interp, /* Tcl interpreter */
1607 int result /* Result so far */
1608){
1609 int rc = result; /* Return code */
1610
1611 /* The first element of the data[] array is a pointer to a DbEvalContext
1612 ** structure allocated using Tcl_Alloc(). The second element of data[]
1613 ** is a pointer to a Tcl_Obj containing the script to run for each row
1614 ** returned by the queries encapsulated in data[0]. */
1615 DbEvalContext *p = (DbEvalContext *)data[0];
1616 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1617 Tcl_Obj *pArray = p->pArray;
1618
1619 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1620 int i;
1621 int nCol;
1622 Tcl_Obj **apColName;
1623 dbEvalRowInfo(p, &nCol, &apColName);
1624 for(i=0; i<nCol; i++){
1625 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1626 if( pArray==0 ){
1627 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1628 }else{
1629 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1630 }
1631 }
1632
1633 /* The required interpreter variables are now populated with the data
1634 ** from the current row. If using NRE, schedule callbacks to evaluate
1635 ** script pScript, then to invoke this function again to fetch the next
1636 ** row (or clean up if there is no next row or the script throws an
1637 ** exception). After scheduling the callbacks, return control to the
1638 ** caller.
1639 **
1640 ** If not using NRE, evaluate pScript directly and continue with the
1641 ** next iteration of this while(...) loop. */
1642 if( DbUseNre() ){
1643 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1644 return Tcl_NREvalObj(interp, pScript, 0);
1645 }else{
1646 rc = Tcl_EvalObjEx(interp, pScript, 0);
1647 }
1648 }
1649
1650 Tcl_DecrRefCount(pScript);
1651 dbEvalFinalize(p);
1652 Tcl_Free((char *)p);
1653
1654 if( rc==TCL_OK || rc==TCL_BREAK ){
1655 Tcl_ResetResult(interp);
1656 rc = TCL_OK;
1657 }
1658 return rc;
danielk19778e556522007-11-13 10:30:24 +00001659}
1660
tpoindex1067fe12004-12-17 15:41:11 +00001661/*
dan46c47d42011-03-01 18:42:07 +00001662** This function is used by the implementations of the following database
1663** handle sub-commands:
1664**
1665** $db update_hook ?SCRIPT?
1666** $db wal_hook ?SCRIPT?
1667** $db commit_hook ?SCRIPT?
1668** $db preupdate hook ?SCRIPT?
1669*/
1670static void DbHookCmd(
1671 Tcl_Interp *interp, /* Tcl interpreter */
1672 SqliteDb *pDb, /* Database handle */
1673 Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */
1674 Tcl_Obj **ppHook /* Pointer to member of SqliteDb */
1675){
1676 sqlite3 *db = pDb->db;
1677
1678 if( *ppHook ){
1679 Tcl_SetObjResult(interp, *ppHook);
1680 if( pArg ){
1681 Tcl_DecrRefCount(*ppHook);
1682 *ppHook = 0;
1683 }
1684 }
1685 if( pArg ){
1686 assert( !(*ppHook) );
1687 if( Tcl_GetCharLength(pArg)>0 ){
1688 *ppHook = pArg;
1689 Tcl_IncrRefCount(*ppHook);
1690 }
1691 }
1692
drh9b1c62d2011-03-30 21:04:43 +00001693#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +00001694 sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
drh9b1c62d2011-03-30 21:04:43 +00001695#endif
dan46c47d42011-03-01 18:42:07 +00001696 sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1697 sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1698 sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
1699}
1700
1701/*
drh75897232000-05-29 14:26:00 +00001702** The "sqlite" command below creates a new Tcl command for each
1703** connection it opens to an SQLite database. This routine is invoked
1704** whenever one of those connection-specific commands is executed
1705** in Tcl. For example, if you run Tcl code like this:
1706**
drh9bb575f2004-09-06 17:24:11 +00001707** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001708** db1 close
1709**
1710** The first command opens a connection to the "my_database" database
1711** and calls that connection "db1". The second command causes this
1712** subroutine to be invoked.
1713*/
drh6d313162000-09-21 13:01:35 +00001714static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001715 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001716 int choice;
drh22fbcb82004-02-01 01:22:50 +00001717 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001718 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001719 "authorizer", "backup", "busy",
1720 "cache", "changes", "close",
1721 "collate", "collation_needed", "commit_hook",
1722 "complete", "copy", "enable_load_extension",
1723 "errorcode", "eval", "exists",
1724 "function", "incrblob", "interrupt",
drh833bf962010-04-28 14:42:19 +00001725 "last_insert_rowid", "nullvalue", "onecolumn",
drh304637c2011-03-18 16:47:27 +00001726 "preupdate", "profile", "progress",
1727 "rekey", "restore", "rollback_hook",
1728 "status", "timeout", "total_changes",
1729 "trace", "transaction", "unlock_notify",
1730 "update_hook", "version", "wal_hook",
1731 0
drh6d313162000-09-21 13:01:35 +00001732 };
drh411995d2002-06-25 19:31:18 +00001733 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001734 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1735 DB_CACHE, DB_CHANGES, DB_CLOSE,
1736 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1737 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1738 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1739 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
drh833bf962010-04-28 14:42:19 +00001740 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
drh304637c2011-03-18 16:47:27 +00001741 DB_PREUPDATE, DB_PROFILE, DB_PROGRESS,
1742 DB_REKEY, DB_RESTORE, DB_ROLLBACK_HOOK,
1743 DB_STATUS, DB_TIMEOUT, DB_TOTAL_CHANGES,
1744 DB_TRACE, DB_TRANSACTION, DB_UNLOCK_NOTIFY,
1745 DB_UPDATE_HOOK, DB_VERSION, DB_WAL_HOOK,
drh6d313162000-09-21 13:01:35 +00001746 };
tpoindex1067fe12004-12-17 15:41:11 +00001747 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001748
1749 if( objc<2 ){
1750 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001751 return TCL_ERROR;
1752 }
drh411995d2002-06-25 19:31:18 +00001753 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001754 return TCL_ERROR;
1755 }
1756
drh411995d2002-06-25 19:31:18 +00001757 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001758
drhe22a3342003-04-22 20:30:37 +00001759 /* $db authorizer ?CALLBACK?
1760 **
1761 ** Invoke the given callback to authorize each SQL operation as it is
1762 ** compiled. 5 arguments are appended to the callback before it is
1763 ** invoked:
1764 **
1765 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1766 ** (2) First descriptive name (depends on authorization type)
1767 ** (3) Second descriptive name
1768 ** (4) Name of the database (ex: "main", "temp")
1769 ** (5) Name of trigger that is doing the access
1770 **
1771 ** The callback should return on of the following strings: SQLITE_OK,
1772 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1773 **
1774 ** If this method is invoked with no arguments, the current authorization
1775 ** callback string is returned.
1776 */
1777 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001778#ifdef SQLITE_OMIT_AUTHORIZATION
drha198f2b2014-02-07 19:26:13 +00001779 Tcl_AppendResult(interp, "authorization not available in this build",
1780 (char*)0);
drh1211de32004-07-26 12:24:22 +00001781 return TCL_ERROR;
1782#else
drhe22a3342003-04-22 20:30:37 +00001783 if( objc>3 ){
1784 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001785 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001786 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001787 if( pDb->zAuth ){
drha198f2b2014-02-07 19:26:13 +00001788 Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
drhe22a3342003-04-22 20:30:37 +00001789 }
1790 }else{
1791 char *zAuth;
1792 int len;
1793 if( pDb->zAuth ){
1794 Tcl_Free(pDb->zAuth);
1795 }
1796 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1797 if( zAuth && len>0 ){
1798 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001799 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001800 }else{
1801 pDb->zAuth = 0;
1802 }
drhe22a3342003-04-22 20:30:37 +00001803 if( pDb->zAuth ){
drh32c6a482014-09-11 13:44:52 +00001804 typedef int (*sqlite3_auth_cb)(
1805 void*,int,const char*,const char*,
1806 const char*,const char*);
drhe22a3342003-04-22 20:30:37 +00001807 pDb->interp = interp;
drh32c6a482014-09-11 13:44:52 +00001808 sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
drhe22a3342003-04-22 20:30:37 +00001809 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001810 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001811 }
drhe22a3342003-04-22 20:30:37 +00001812 }
drh1211de32004-07-26 12:24:22 +00001813#endif
drhe22a3342003-04-22 20:30:37 +00001814 break;
1815 }
1816
drhdc2c4912009-02-04 22:46:47 +00001817 /* $db backup ?DATABASE? FILENAME
1818 **
1819 ** Open or create a database file named FILENAME. Transfer the
1820 ** content of local database DATABASE (default: "main") into the
1821 ** FILENAME database.
1822 */
1823 case DB_BACKUP: {
1824 const char *zDestFile;
1825 const char *zSrcDb;
1826 sqlite3 *pDest;
1827 sqlite3_backup *pBackup;
1828
1829 if( objc==3 ){
1830 zSrcDb = "main";
1831 zDestFile = Tcl_GetString(objv[2]);
1832 }else if( objc==4 ){
1833 zSrcDb = Tcl_GetString(objv[2]);
1834 zDestFile = Tcl_GetString(objv[3]);
1835 }else{
1836 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1837 return TCL_ERROR;
1838 }
drh147ef392016-01-22 23:17:51 +00001839 rc = sqlite3_open_v2(zDestFile, &pDest,
1840 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00001841 if( rc!=SQLITE_OK ){
1842 Tcl_AppendResult(interp, "cannot open target database: ",
1843 sqlite3_errmsg(pDest), (char*)0);
1844 sqlite3_close(pDest);
1845 return TCL_ERROR;
1846 }
1847 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1848 if( pBackup==0 ){
1849 Tcl_AppendResult(interp, "backup failed: ",
1850 sqlite3_errmsg(pDest), (char*)0);
1851 sqlite3_close(pDest);
1852 return TCL_ERROR;
1853 }
1854 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1855 sqlite3_backup_finish(pBackup);
1856 if( rc==SQLITE_DONE ){
1857 rc = TCL_OK;
1858 }else{
1859 Tcl_AppendResult(interp, "backup failed: ",
1860 sqlite3_errmsg(pDest), (char*)0);
1861 rc = TCL_ERROR;
1862 }
1863 sqlite3_close(pDest);
1864 break;
1865 }
1866
drhbec3f402000-08-04 13:49:02 +00001867 /* $db busy ?CALLBACK?
1868 **
1869 ** Invoke the given callback if an SQL statement attempts to open
1870 ** a locked database file.
1871 */
drh6d313162000-09-21 13:01:35 +00001872 case DB_BUSY: {
1873 if( objc>3 ){
1874 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001875 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001876 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001877 if( pDb->zBusy ){
drha198f2b2014-02-07 19:26:13 +00001878 Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
drhbec3f402000-08-04 13:49:02 +00001879 }
1880 }else{
drh6d313162000-09-21 13:01:35 +00001881 char *zBusy;
1882 int len;
drhbec3f402000-08-04 13:49:02 +00001883 if( pDb->zBusy ){
1884 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001885 }
drh6d313162000-09-21 13:01:35 +00001886 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1887 if( zBusy && len>0 ){
1888 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001889 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001890 }else{
1891 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001892 }
1893 if( pDb->zBusy ){
1894 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001895 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001896 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001897 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001898 }
1899 }
drh6d313162000-09-21 13:01:35 +00001900 break;
1901 }
drhbec3f402000-08-04 13:49:02 +00001902
drhfb7e7652005-01-24 00:28:42 +00001903 /* $db cache flush
1904 ** $db cache size n
1905 **
1906 ** Flush the prepared statement cache, or set the maximum number of
1907 ** cached statements.
1908 */
1909 case DB_CACHE: {
1910 char *subCmd;
1911 int n;
1912
1913 if( objc<=2 ){
1914 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1915 return TCL_ERROR;
1916 }
1917 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1918 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1919 if( objc!=3 ){
1920 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1921 return TCL_ERROR;
1922 }else{
1923 flushStmtCache( pDb );
1924 }
1925 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1926 if( objc!=4 ){
1927 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1928 return TCL_ERROR;
1929 }else{
1930 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1931 Tcl_AppendResult( interp, "cannot convert \"",
drha198f2b2014-02-07 19:26:13 +00001932 Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
drhfb7e7652005-01-24 00:28:42 +00001933 return TCL_ERROR;
1934 }else{
1935 if( n<0 ){
1936 flushStmtCache( pDb );
1937 n = 0;
1938 }else if( n>MAX_PREPARED_STMTS ){
1939 n = MAX_PREPARED_STMTS;
1940 }
1941 pDb->maxStmt = n;
1942 }
1943 }
1944 }else{
1945 Tcl_AppendResult( interp, "bad option \"",
drha198f2b2014-02-07 19:26:13 +00001946 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
1947 (char*)0);
drhfb7e7652005-01-24 00:28:42 +00001948 return TCL_ERROR;
1949 }
1950 break;
1951 }
1952
danielk1977b28af712004-06-21 06:50:26 +00001953 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001954 **
1955 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001956 ** the most recent INSERT, UPDATE or DELETE statement, not including
1957 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001958 */
1959 case DB_CHANGES: {
1960 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001961 if( objc!=2 ){
1962 Tcl_WrongNumArgs(interp, 2, objv, "");
1963 return TCL_ERROR;
1964 }
drhc8d30ac2002-04-12 10:08:59 +00001965 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001966 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001967 break;
1968 }
1969
drh75897232000-05-29 14:26:00 +00001970 /* $db close
1971 **
1972 ** Shutdown the database
1973 */
drh6d313162000-09-21 13:01:35 +00001974 case DB_CLOSE: {
1975 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1976 break;
1977 }
drh75897232000-05-29 14:26:00 +00001978
drh0f14e2e2004-06-29 12:39:08 +00001979 /*
1980 ** $db collate NAME SCRIPT
1981 **
1982 ** Create a new SQL collation function called NAME. Whenever
1983 ** that function is called, invoke SCRIPT to evaluate the function.
1984 */
1985 case DB_COLLATE: {
1986 SqlCollate *pCollate;
1987 char *zName;
1988 char *zScript;
1989 int nScript;
1990 if( objc!=4 ){
1991 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1992 return TCL_ERROR;
1993 }
1994 zName = Tcl_GetStringFromObj(objv[2], 0);
1995 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1996 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1997 if( pCollate==0 ) return TCL_ERROR;
1998 pCollate->interp = interp;
1999 pCollate->pNext = pDb->pCollate;
2000 pCollate->zScript = (char*)&pCollate[1];
2001 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00002002 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00002003 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
2004 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00002005 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00002006 return TCL_ERROR;
2007 }
2008 break;
2009 }
2010
2011 /*
2012 ** $db collation_needed SCRIPT
2013 **
2014 ** Create a new SQL collation function called NAME. Whenever
2015 ** that function is called, invoke SCRIPT to evaluate the function.
2016 */
2017 case DB_COLLATION_NEEDED: {
2018 if( objc!=3 ){
2019 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
2020 return TCL_ERROR;
2021 }
2022 if( pDb->pCollateNeeded ){
2023 Tcl_DecrRefCount(pDb->pCollateNeeded);
2024 }
2025 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
2026 Tcl_IncrRefCount(pDb->pCollateNeeded);
2027 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
2028 break;
2029 }
2030
drh19e2d372005-08-29 23:00:03 +00002031 /* $db commit_hook ?CALLBACK?
2032 **
2033 ** Invoke the given callback just before committing every SQL transaction.
2034 ** If the callback throws an exception or returns non-zero, then the
2035 ** transaction is aborted. If CALLBACK is an empty string, the callback
2036 ** is disabled.
2037 */
2038 case DB_COMMIT_HOOK: {
2039 if( objc>3 ){
2040 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2041 return TCL_ERROR;
2042 }else if( objc==2 ){
2043 if( pDb->zCommit ){
drha198f2b2014-02-07 19:26:13 +00002044 Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002045 }
2046 }else{
mistachkin6ef5e122014-01-24 17:03:55 +00002047 const char *zCommit;
drh19e2d372005-08-29 23:00:03 +00002048 int len;
2049 if( pDb->zCommit ){
2050 Tcl_Free(pDb->zCommit);
2051 }
2052 zCommit = Tcl_GetStringFromObj(objv[2], &len);
2053 if( zCommit && len>0 ){
2054 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002055 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00002056 }else{
2057 pDb->zCommit = 0;
2058 }
2059 if( pDb->zCommit ){
2060 pDb->interp = interp;
2061 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
2062 }else{
2063 sqlite3_commit_hook(pDb->db, 0, 0);
2064 }
2065 }
2066 break;
2067 }
2068
drh75897232000-05-29 14:26:00 +00002069 /* $db complete SQL
2070 **
2071 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2072 ** additional lines of input are needed. This is similar to the
2073 ** built-in "info complete" command of Tcl.
2074 */
drh6d313162000-09-21 13:01:35 +00002075 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00002076#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00002077 Tcl_Obj *pResult;
2078 int isComplete;
2079 if( objc!=3 ){
2080 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00002081 return TCL_ERROR;
2082 }
danielk19776f8a5032004-05-10 10:34:51 +00002083 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00002084 pResult = Tcl_GetObjResult(interp);
2085 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00002086#endif
drh6d313162000-09-21 13:01:35 +00002087 break;
2088 }
drhdcd997e2003-01-31 17:21:49 +00002089
drh19e2d372005-08-29 23:00:03 +00002090 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2091 **
2092 ** Copy data into table from filename, optionally using SEPARATOR
2093 ** as column separators. If a column contains a null string, or the
2094 ** value of NULLINDICATOR, a NULL is inserted for the column.
2095 ** conflict-algorithm is one of the sqlite conflict algorithms:
2096 ** rollback, abort, fail, ignore, replace
2097 ** On success, return the number of lines processed, not necessarily same
2098 ** as 'db changes' due to conflict-algorithm selected.
2099 **
2100 ** This code is basically an implementation/enhancement of
2101 ** the sqlite3 shell.c ".import" command.
2102 **
2103 ** This command usage is equivalent to the sqlite2.x COPY statement,
2104 ** which imports file data into a table using the PostgreSQL COPY file format:
2105 ** $db copy $conflit_algo $table_name $filename \t \\N
2106 */
2107 case DB_COPY: {
2108 char *zTable; /* Insert data into this table */
2109 char *zFile; /* The file from which to extract data */
2110 char *zConflict; /* The conflict algorithm to use */
2111 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00002112 int nCol; /* Number of columns in the table */
2113 int nByte; /* Number of bytes in an SQL string */
2114 int i, j; /* Loop counters */
2115 int nSep; /* Number of bytes in zSep[] */
2116 int nNull; /* Number of bytes in zNull[] */
2117 char *zSql; /* An SQL statement */
2118 char *zLine; /* A single line of input from the file */
2119 char **azCol; /* zLine[] broken up into columns */
mistachkin6ef5e122014-01-24 17:03:55 +00002120 const char *zCommit; /* How to commit changes */
drh19e2d372005-08-29 23:00:03 +00002121 FILE *in; /* The input file */
2122 int lineno = 0; /* Line number of input file */
2123 char zLineNum[80]; /* Line number print buffer */
2124 Tcl_Obj *pResult; /* interp result */
2125
mistachkin6ef5e122014-01-24 17:03:55 +00002126 const char *zSep;
2127 const char *zNull;
drh19e2d372005-08-29 23:00:03 +00002128 if( objc<5 || objc>7 ){
2129 Tcl_WrongNumArgs(interp, 2, objv,
2130 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2131 return TCL_ERROR;
2132 }
2133 if( objc>=6 ){
2134 zSep = Tcl_GetStringFromObj(objv[5], 0);
2135 }else{
2136 zSep = "\t";
2137 }
2138 if( objc>=7 ){
2139 zNull = Tcl_GetStringFromObj(objv[6], 0);
2140 }else{
2141 zNull = "";
2142 }
2143 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2144 zTable = Tcl_GetStringFromObj(objv[3], 0);
2145 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002146 nSep = strlen30(zSep);
2147 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002148 if( nSep==0 ){
drha198f2b2014-02-07 19:26:13 +00002149 Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2150 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002151 return TCL_ERROR;
2152 }
drh3e59c012008-09-23 10:12:13 +00002153 if(strcmp(zConflict, "rollback") != 0 &&
2154 strcmp(zConflict, "abort" ) != 0 &&
2155 strcmp(zConflict, "fail" ) != 0 &&
2156 strcmp(zConflict, "ignore" ) != 0 &&
2157 strcmp(zConflict, "replace" ) != 0 ) {
drh19e2d372005-08-29 23:00:03 +00002158 Tcl_AppendResult(interp, "Error: \"", zConflict,
2159 "\", conflict-algorithm must be one of: rollback, "
drha198f2b2014-02-07 19:26:13 +00002160 "abort, fail, ignore, or replace", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002161 return TCL_ERROR;
2162 }
2163 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2164 if( zSql==0 ){
drha198f2b2014-02-07 19:26:13 +00002165 Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002166 return TCL_ERROR;
2167 }
drh4f21c4a2008-12-10 22:15:00 +00002168 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002169 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002170 sqlite3_free(zSql);
2171 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002172 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002173 nCol = 0;
2174 }else{
2175 nCol = sqlite3_column_count(pStmt);
2176 }
2177 sqlite3_finalize(pStmt);
2178 if( nCol==0 ) {
2179 return TCL_ERROR;
2180 }
2181 zSql = malloc( nByte + 50 + nCol*2 );
2182 if( zSql==0 ) {
drha198f2b2014-02-07 19:26:13 +00002183 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002184 return TCL_ERROR;
2185 }
2186 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2187 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002188 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002189 for(i=1; i<nCol; i++){
2190 zSql[j++] = ',';
2191 zSql[j++] = '?';
2192 }
2193 zSql[j++] = ')';
2194 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002195 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002196 free(zSql);
2197 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002198 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002199 sqlite3_finalize(pStmt);
2200 return TCL_ERROR;
2201 }
2202 in = fopen(zFile, "rb");
2203 if( in==0 ){
2204 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2205 sqlite3_finalize(pStmt);
2206 return TCL_ERROR;
2207 }
2208 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2209 if( azCol==0 ) {
drha198f2b2014-02-07 19:26:13 +00002210 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh43617e92006-03-06 20:55:46 +00002211 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002212 return TCL_ERROR;
2213 }
drh37527852006-03-16 16:19:56 +00002214 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002215 zCommit = "COMMIT";
2216 while( (zLine = local_getline(0, in))!=0 ){
2217 char *z;
drh19e2d372005-08-29 23:00:03 +00002218 lineno++;
2219 azCol[0] = zLine;
2220 for(i=0, z=zLine; *z; z++){
2221 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2222 *z = 0;
2223 i++;
2224 if( i<nCol ){
2225 azCol[i] = &z[nSep];
2226 z += nSep-1;
2227 }
2228 }
2229 }
2230 if( i+1!=nCol ){
2231 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002232 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002233 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002234 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002235 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002236 "Error: %s line %d: expected %d columns of data but found %d",
2237 zFile, lineno, nCol, i+1);
drha198f2b2014-02-07 19:26:13 +00002238 Tcl_AppendResult(interp, zErr, (char*)0);
drhc1f44942006-05-10 14:39:13 +00002239 free(zErr);
2240 }
drh19e2d372005-08-29 23:00:03 +00002241 zCommit = "ROLLBACK";
2242 break;
2243 }
2244 for(i=0; i<nCol; i++){
2245 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002246 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
drh4f21c4a2008-12-10 22:15:00 +00002247 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002248 ){
drh19e2d372005-08-29 23:00:03 +00002249 sqlite3_bind_null(pStmt, i+1);
2250 }else{
2251 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2252 }
2253 }
2254 sqlite3_step(pStmt);
2255 rc = sqlite3_reset(pStmt);
2256 free(zLine);
2257 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00002258 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002259 zCommit = "ROLLBACK";
2260 break;
2261 }
2262 }
2263 free(azCol);
2264 fclose(in);
2265 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002266 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002267
2268 if( zCommit[0] == 'C' ){
2269 /* success, set result as number of lines processed */
2270 pResult = Tcl_GetObjResult(interp);
2271 Tcl_SetIntObj(pResult, lineno);
2272 rc = TCL_OK;
2273 }else{
2274 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002275 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drha198f2b2014-02-07 19:26:13 +00002276 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2277 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002278 rc = TCL_ERROR;
2279 }
2280 break;
2281 }
2282
drhdcd997e2003-01-31 17:21:49 +00002283 /*
drh41449052006-07-06 17:08:48 +00002284 ** $db enable_load_extension BOOLEAN
2285 **
2286 ** Turn the extension loading feature on or off. It if off by
2287 ** default.
2288 */
2289 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002290#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002291 int onoff;
2292 if( objc!=3 ){
2293 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2294 return TCL_ERROR;
2295 }
2296 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2297 return TCL_ERROR;
2298 }
2299 sqlite3_enable_load_extension(pDb->db, onoff);
2300 break;
drhf533acc2006-12-19 18:57:11 +00002301#else
2302 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
drha198f2b2014-02-07 19:26:13 +00002303 (char*)0);
drhf533acc2006-12-19 18:57:11 +00002304 return TCL_ERROR;
2305#endif
drh41449052006-07-06 17:08:48 +00002306 }
2307
2308 /*
drhdcd997e2003-01-31 17:21:49 +00002309 ** $db errorcode
2310 **
2311 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002312 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002313 */
2314 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002315 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002316 break;
2317 }
dan4a4c11a2009-10-06 14:59:02 +00002318
2319 /*
2320 ** $db exists $sql
2321 ** $db onecolumn $sql
2322 **
2323 ** The onecolumn method is the equivalent of:
2324 ** lindex [$db eval $sql] 0
2325 */
2326 case DB_EXISTS:
2327 case DB_ONECOLUMN: {
drhedc40242016-06-13 12:34:38 +00002328 Tcl_Obj *pResult = 0;
dan4a4c11a2009-10-06 14:59:02 +00002329 DbEvalContext sEval;
2330 if( objc!=3 ){
2331 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2332 return TCL_ERROR;
2333 }
2334
2335 dbEvalInit(&sEval, pDb, objv[2], 0);
2336 rc = dbEvalStep(&sEval);
2337 if( choice==DB_ONECOLUMN ){
2338 if( rc==TCL_OK ){
drhedc40242016-06-13 12:34:38 +00002339 pResult = dbEvalColumnValue(&sEval, 0);
dand5f12cd2011-08-18 17:47:57 +00002340 }else if( rc==TCL_BREAK ){
2341 Tcl_ResetResult(interp);
dan4a4c11a2009-10-06 14:59:02 +00002342 }
2343 }else if( rc==TCL_BREAK || rc==TCL_OK ){
drhedc40242016-06-13 12:34:38 +00002344 pResult = Tcl_NewBooleanObj(rc==TCL_OK);
dan4a4c11a2009-10-06 14:59:02 +00002345 }
2346 dbEvalFinalize(&sEval);
drhedc40242016-06-13 12:34:38 +00002347 if( pResult ) Tcl_SetObjResult(interp, pResult);
dan4a4c11a2009-10-06 14:59:02 +00002348
2349 if( rc==TCL_BREAK ){
2350 rc = TCL_OK;
2351 }
2352 break;
2353 }
drh75897232000-05-29 14:26:00 +00002354
2355 /*
drh895d7472004-08-20 16:02:39 +00002356 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002357 **
2358 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002359 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002360 ** If "array" and "code" are omitted, then no callback is every invoked.
2361 ** If "array" is an empty string, then the values are placed in variables
2362 ** that have the same name as the fields extracted by the query.
2363 */
dan4a4c11a2009-10-06 14:59:02 +00002364 case DB_EVAL: {
2365 if( objc<3 || objc>5 ){
2366 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2367 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002368 }
dan4a4c11a2009-10-06 14:59:02 +00002369
drh92febd92004-08-20 18:34:20 +00002370 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002371 DbEvalContext sEval;
2372 Tcl_Obj *pRet = Tcl_NewObj();
2373 Tcl_IncrRefCount(pRet);
2374 dbEvalInit(&sEval, pDb, objv[2], 0);
2375 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2376 int i;
2377 int nCol;
2378 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002379 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002380 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002381 }
2382 }
dan4a4c11a2009-10-06 14:59:02 +00002383 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002384 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002385 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002386 rc = TCL_OK;
2387 }
drh1807ce32004-09-07 13:20:35 +00002388 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002389 }else{
mistachkin8e189222015-04-19 21:43:16 +00002390 ClientData cd2[2];
dan4a4c11a2009-10-06 14:59:02 +00002391 DbEvalContext *p;
2392 Tcl_Obj *pArray = 0;
2393 Tcl_Obj *pScript;
2394
2395 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2396 pArray = objv[3];
2397 }
2398 pScript = objv[objc-1];
2399 Tcl_IncrRefCount(pScript);
2400
2401 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2402 dbEvalInit(p, pDb, objv[2], pArray);
2403
mistachkin8e189222015-04-19 21:43:16 +00002404 cd2[0] = (void *)p;
2405 cd2[1] = (void *)pScript;
2406 rc = DbEvalNextCmd(cd2, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002407 }
danielk197730ccda12004-05-27 12:11:31 +00002408 break;
2409 }
drhbec3f402000-08-04 13:49:02 +00002410
2411 /*
dan3df30592015-03-13 08:31:54 +00002412 ** $db function NAME [-argcount N] [-deterministic] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002413 **
2414 ** Create a new SQL function called NAME. Whenever that function is
2415 ** called, invoke SCRIPT to evaluate the function.
2416 */
2417 case DB_FUNCTION: {
dan3df30592015-03-13 08:31:54 +00002418 int flags = SQLITE_UTF8;
drhcabb0812002-09-14 13:47:32 +00002419 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002420 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002421 char *zName;
drhe3602be2008-09-09 12:31:33 +00002422 int nArg = -1;
dan3df30592015-03-13 08:31:54 +00002423 int i;
2424 if( objc<4 ){
2425 Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
2426 return TCL_ERROR;
2427 }
2428 for(i=3; i<(objc-1); i++){
2429 const char *z = Tcl_GetString(objv[i]);
drh4f21c4a2008-12-10 22:15:00 +00002430 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002431 if( n>2 && strncmp(z, "-argcount",n)==0 ){
dan3df30592015-03-13 08:31:54 +00002432 if( i==(objc-2) ){
2433 Tcl_AppendResult(interp, "option requires an argument: ", z, 0);
2434 return TCL_ERROR;
2435 }
2436 if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002437 if( nArg<0 ){
2438 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2439 (char*)0);
2440 return TCL_ERROR;
2441 }
dan3df30592015-03-13 08:31:54 +00002442 i++;
2443 }else
2444 if( n>2 && strncmp(z, "-deterministic",n)==0 ){
2445 flags |= SQLITE_DETERMINISTIC;
2446 }else{
2447 Tcl_AppendResult(interp, "bad option \"", z,
2448 "\": must be -argcount or -deterministic", 0
2449 );
2450 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002451 }
drhcabb0812002-09-14 13:47:32 +00002452 }
dan3df30592015-03-13 08:31:54 +00002453
2454 pScript = objv[objc-1];
drhcabb0812002-09-14 13:47:32 +00002455 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002456 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002457 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002458 if( pFunc->pScript ){
2459 Tcl_DecrRefCount(pFunc->pScript);
2460 }
2461 pFunc->pScript = pScript;
2462 Tcl_IncrRefCount(pScript);
2463 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
dan3df30592015-03-13 08:31:54 +00002464 rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
danielk1977d8123362004-06-12 09:25:12 +00002465 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002466 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002467 rc = TCL_ERROR;
2468 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002469 }
drhcabb0812002-09-14 13:47:32 +00002470 break;
2471 }
2472
2473 /*
danielk19778cbadb02007-05-03 16:31:26 +00002474 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002475 */
2476 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002477#ifdef SQLITE_OMIT_INCRBLOB
drha198f2b2014-02-07 19:26:13 +00002478 Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
danielk197732a0d8b2007-05-04 19:03:02 +00002479 return TCL_ERROR;
2480#else
danielk19778cbadb02007-05-03 16:31:26 +00002481 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002482 const char *zDb = "main";
2483 const char *zTable;
2484 const char *zColumn;
drhb3f787f2012-09-29 14:45:54 +00002485 Tcl_WideInt iRow;
danielk1977b4e9af92007-05-01 17:49:49 +00002486
danielk19778cbadb02007-05-03 16:31:26 +00002487 /* Check for the -readonly option */
2488 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2489 isReadonly = 1;
2490 }
2491
2492 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2493 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002494 return TCL_ERROR;
2495 }
2496
danielk19778cbadb02007-05-03 16:31:26 +00002497 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002498 zDb = Tcl_GetString(objv[2]);
2499 }
2500 zTable = Tcl_GetString(objv[objc-3]);
2501 zColumn = Tcl_GetString(objv[objc-2]);
2502 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2503
2504 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002505 rc = createIncrblobChannel(
danedf5b162014-08-19 09:15:41 +00002506 interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
danielk19778cbadb02007-05-03 16:31:26 +00002507 );
danielk1977b4e9af92007-05-01 17:49:49 +00002508 }
danielk197732a0d8b2007-05-04 19:03:02 +00002509#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002510 break;
2511 }
2512
2513 /*
drhf11bded2006-07-17 00:02:44 +00002514 ** $db interrupt
2515 **
2516 ** Interrupt the execution of the inner-most SQL interpreter. This
2517 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2518 */
2519 case DB_INTERRUPT: {
2520 sqlite3_interrupt(pDb->db);
2521 break;
2522 }
2523
2524 /*
drh19e2d372005-08-29 23:00:03 +00002525 ** $db nullvalue ?STRING?
2526 **
2527 ** Change text used when a NULL comes back from the database. If ?STRING?
2528 ** is not present, then the current string used for NULL is returned.
2529 ** If STRING is present, then STRING is returned.
2530 **
2531 */
2532 case DB_NULLVALUE: {
2533 if( objc!=2 && objc!=3 ){
2534 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2535 return TCL_ERROR;
2536 }
2537 if( objc==3 ){
2538 int len;
2539 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2540 if( pDb->zNull ){
2541 Tcl_Free(pDb->zNull);
2542 }
2543 if( zNull && len>0 ){
2544 pDb->zNull = Tcl_Alloc( len + 1 );
drh7fd33922011-06-20 19:00:30 +00002545 memcpy(pDb->zNull, zNull, len);
drh19e2d372005-08-29 23:00:03 +00002546 pDb->zNull[len] = '\0';
2547 }else{
2548 pDb->zNull = 0;
2549 }
2550 }
drhc45e6712012-10-03 11:02:33 +00002551 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
drh19e2d372005-08-29 23:00:03 +00002552 break;
2553 }
2554
2555 /*
drhaf9ff332002-01-16 21:00:27 +00002556 ** $db last_insert_rowid
2557 **
2558 ** Return an integer which is the ROWID for the most recent insert.
2559 */
2560 case DB_LAST_INSERT_ROWID: {
2561 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002562 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002563 if( objc!=2 ){
2564 Tcl_WrongNumArgs(interp, 2, objv, "");
2565 return TCL_ERROR;
2566 }
danielk19776f8a5032004-05-10 10:34:51 +00002567 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002568 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002569 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002570 break;
2571 }
2572
2573 /*
dan4a4c11a2009-10-06 14:59:02 +00002574 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002575 */
drh1807ce32004-09-07 13:20:35 +00002576
2577 /* $db progress ?N CALLBACK?
2578 **
2579 ** Invoke the given callback every N virtual machine opcodes while executing
2580 ** queries.
2581 */
2582 case DB_PROGRESS: {
2583 if( objc==2 ){
2584 if( pDb->zProgress ){
drha198f2b2014-02-07 19:26:13 +00002585 Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
drh1807ce32004-09-07 13:20:35 +00002586 }
2587 }else if( objc==4 ){
2588 char *zProgress;
2589 int len;
2590 int N;
2591 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002592 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002593 };
2594 if( pDb->zProgress ){
2595 Tcl_Free(pDb->zProgress);
2596 }
2597 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2598 if( zProgress && len>0 ){
2599 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002600 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002601 }else{
2602 pDb->zProgress = 0;
2603 }
2604#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2605 if( pDb->zProgress ){
2606 pDb->interp = interp;
2607 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2608 }else{
2609 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2610 }
2611#endif
2612 }else{
2613 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002614 return TCL_ERROR;
2615 }
drh5d9d7572003-08-19 14:31:01 +00002616 break;
2617 }
2618
drh19e2d372005-08-29 23:00:03 +00002619 /* $db profile ?CALLBACK?
2620 **
2621 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2622 ** that has run. The text of the SQL and the amount of elapse time are
2623 ** appended to CALLBACK before the script is run.
2624 */
2625 case DB_PROFILE: {
2626 if( objc>3 ){
2627 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2628 return TCL_ERROR;
2629 }else if( objc==2 ){
2630 if( pDb->zProfile ){
drha198f2b2014-02-07 19:26:13 +00002631 Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002632 }
2633 }else{
2634 char *zProfile;
2635 int len;
2636 if( pDb->zProfile ){
2637 Tcl_Free(pDb->zProfile);
2638 }
2639 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2640 if( zProfile && len>0 ){
2641 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002642 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002643 }else{
2644 pDb->zProfile = 0;
2645 }
shanehbb201342011-02-09 19:55:20 +00002646#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh19e2d372005-08-29 23:00:03 +00002647 if( pDb->zProfile ){
2648 pDb->interp = interp;
2649 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2650 }else{
2651 sqlite3_profile(pDb->db, 0, 0);
2652 }
2653#endif
2654 }
2655 break;
2656 }
2657
drh5d9d7572003-08-19 14:31:01 +00002658 /*
drh22fbcb82004-02-01 01:22:50 +00002659 ** $db rekey KEY
2660 **
2661 ** Change the encryption key on the currently open database.
2662 */
2663 case DB_REKEY: {
drh32f57d42016-03-16 01:03:10 +00002664#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh22fbcb82004-02-01 01:22:50 +00002665 int nKey;
2666 void *pKey;
drhb07028f2011-10-14 21:49:18 +00002667#endif
drh22fbcb82004-02-01 01:22:50 +00002668 if( objc!=3 ){
2669 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2670 return TCL_ERROR;
2671 }
drh32f57d42016-03-16 01:03:10 +00002672#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00002673 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh2011d5f2004-07-22 02:40:37 +00002674 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002675 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002676 Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
drh22fbcb82004-02-01 01:22:50 +00002677 rc = TCL_ERROR;
2678 }
2679#endif
2680 break;
2681 }
2682
drhdc2c4912009-02-04 22:46:47 +00002683 /* $db restore ?DATABASE? FILENAME
2684 **
2685 ** Open a database file named FILENAME. Transfer the content
2686 ** of FILENAME into the local database DATABASE (default: "main").
2687 */
2688 case DB_RESTORE: {
2689 const char *zSrcFile;
2690 const char *zDestDb;
2691 sqlite3 *pSrc;
2692 sqlite3_backup *pBackup;
2693 int nTimeout = 0;
2694
2695 if( objc==3 ){
2696 zDestDb = "main";
2697 zSrcFile = Tcl_GetString(objv[2]);
2698 }else if( objc==4 ){
2699 zDestDb = Tcl_GetString(objv[2]);
2700 zSrcFile = Tcl_GetString(objv[3]);
2701 }else{
2702 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2703 return TCL_ERROR;
2704 }
drh147ef392016-01-22 23:17:51 +00002705 rc = sqlite3_open_v2(zSrcFile, &pSrc,
2706 SQLITE_OPEN_READONLY | pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00002707 if( rc!=SQLITE_OK ){
2708 Tcl_AppendResult(interp, "cannot open source database: ",
2709 sqlite3_errmsg(pSrc), (char*)0);
2710 sqlite3_close(pSrc);
2711 return TCL_ERROR;
2712 }
2713 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2714 if( pBackup==0 ){
2715 Tcl_AppendResult(interp, "restore failed: ",
2716 sqlite3_errmsg(pDb->db), (char*)0);
2717 sqlite3_close(pSrc);
2718 return TCL_ERROR;
2719 }
2720 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2721 || rc==SQLITE_BUSY ){
2722 if( rc==SQLITE_BUSY ){
2723 if( nTimeout++ >= 3 ) break;
2724 sqlite3_sleep(100);
2725 }
2726 }
2727 sqlite3_backup_finish(pBackup);
2728 if( rc==SQLITE_DONE ){
2729 rc = TCL_OK;
2730 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2731 Tcl_AppendResult(interp, "restore failed: source database busy",
2732 (char*)0);
2733 rc = TCL_ERROR;
2734 }else{
2735 Tcl_AppendResult(interp, "restore failed: ",
2736 sqlite3_errmsg(pDb->db), (char*)0);
2737 rc = TCL_ERROR;
2738 }
2739 sqlite3_close(pSrc);
2740 break;
2741 }
2742
drh22fbcb82004-02-01 01:22:50 +00002743 /*
drh3c379b02010-04-07 19:31:59 +00002744 ** $db status (step|sort|autoindex)
drhd1d38482008-10-07 23:46:38 +00002745 **
2746 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2747 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2748 */
2749 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002750 int v;
2751 const char *zOp;
2752 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00002753 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00002754 return TCL_ERROR;
2755 }
2756 zOp = Tcl_GetString(objv[2]);
2757 if( strcmp(zOp, "step")==0 ){
2758 v = pDb->nStep;
2759 }else if( strcmp(zOp, "sort")==0 ){
2760 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002761 }else if( strcmp(zOp, "autoindex")==0 ){
2762 v = pDb->nIndex;
drhd1d38482008-10-07 23:46:38 +00002763 }else{
drh3c379b02010-04-07 19:31:59 +00002764 Tcl_AppendResult(interp,
2765 "bad argument: should be autoindex, step, or sort",
drhd1d38482008-10-07 23:46:38 +00002766 (char*)0);
2767 return TCL_ERROR;
2768 }
2769 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2770 break;
2771 }
2772
2773 /*
drhbec3f402000-08-04 13:49:02 +00002774 ** $db timeout MILLESECONDS
2775 **
2776 ** Delay for the number of milliseconds specified when a file is locked.
2777 */
drh6d313162000-09-21 13:01:35 +00002778 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002779 int ms;
drh6d313162000-09-21 13:01:35 +00002780 if( objc!=3 ){
2781 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002782 return TCL_ERROR;
2783 }
drh6d313162000-09-21 13:01:35 +00002784 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002785 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002786 break;
drh75897232000-05-29 14:26:00 +00002787 }
danielk197755c45f22005-04-03 23:54:43 +00002788
2789 /*
drh0f14e2e2004-06-29 12:39:08 +00002790 ** $db total_changes
2791 **
2792 ** Return the number of rows that were modified, inserted, or deleted
2793 ** since the database handle was created.
2794 */
2795 case DB_TOTAL_CHANGES: {
2796 Tcl_Obj *pResult;
2797 if( objc!=2 ){
2798 Tcl_WrongNumArgs(interp, 2, objv, "");
2799 return TCL_ERROR;
2800 }
2801 pResult = Tcl_GetObjResult(interp);
2802 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2803 break;
2804 }
2805
drhb5a20d32003-04-23 12:25:23 +00002806 /* $db trace ?CALLBACK?
2807 **
2808 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2809 ** that is executed. The text of the SQL is appended to CALLBACK before
2810 ** it is executed.
2811 */
2812 case DB_TRACE: {
2813 if( objc>3 ){
2814 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002815 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002816 }else if( objc==2 ){
2817 if( pDb->zTrace ){
drha198f2b2014-02-07 19:26:13 +00002818 Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
drhb5a20d32003-04-23 12:25:23 +00002819 }
2820 }else{
2821 char *zTrace;
2822 int len;
2823 if( pDb->zTrace ){
2824 Tcl_Free(pDb->zTrace);
2825 }
2826 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2827 if( zTrace && len>0 ){
2828 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002829 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002830 }else{
2831 pDb->zTrace = 0;
2832 }
shanehbb201342011-02-09 19:55:20 +00002833#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drhb5a20d32003-04-23 12:25:23 +00002834 if( pDb->zTrace ){
2835 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002836 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002837 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002838 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002839 }
drh19e2d372005-08-29 23:00:03 +00002840#endif
drhb5a20d32003-04-23 12:25:23 +00002841 }
2842 break;
2843 }
2844
drh3d214232005-08-02 12:21:08 +00002845 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2846 **
2847 ** Start a new transaction (if we are not already in the midst of a
2848 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2849 ** completes, either commit the transaction or roll it back if SCRIPT
2850 ** throws an exception. Or if no new transation was started, do nothing.
2851 ** pass the exception on up the stack.
2852 **
2853 ** This command was inspired by Dave Thomas's talk on Ruby at the
2854 ** 2005 O'Reilly Open Source Convention (OSCON).
2855 */
2856 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00002857 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00002858 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00002859 if( objc!=3 && objc!=4 ){
2860 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2861 return TCL_ERROR;
2862 }
danielk1977cd38d522009-01-02 17:33:46 +00002863
dan4a4c11a2009-10-06 14:59:02 +00002864 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00002865 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002866 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002867 };
2868 enum TTYPE_enum {
2869 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2870 };
2871 int ttype;
drhb5555e72005-08-02 17:15:14 +00002872 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002873 0, &ttype) ){
2874 return TCL_ERROR;
2875 }
2876 switch( (enum TTYPE_enum)ttype ){
2877 case TTYPE_DEFERRED: /* no-op */; break;
2878 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2879 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2880 }
drh3d214232005-08-02 12:21:08 +00002881 }
danielk1977cd38d522009-01-02 17:33:46 +00002882 pScript = objv[objc-1];
2883
dan4a4c11a2009-10-06 14:59:02 +00002884 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00002885 pDb->disableAuth++;
2886 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2887 pDb->disableAuth--;
2888 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00002889 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977cd38d522009-01-02 17:33:46 +00002890 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00002891 }
danielk1977cd38d522009-01-02 17:33:46 +00002892 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00002893
dan4a4c11a2009-10-06 14:59:02 +00002894 /* If using NRE, schedule a callback to invoke the script pScript, then
2895 ** a second callback to commit (or rollback) the transaction or savepoint
2896 ** opened above. If not using NRE, evaluate the script directly, then
2897 ** call function DbTransPostCmd() to commit (or rollback) the transaction
2898 ** or savepoint. */
2899 if( DbUseNre() ){
2900 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
drha47941f2013-12-20 18:57:44 +00002901 (void)Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00002902 }else{
dan4a4c11a2009-10-06 14:59:02 +00002903 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00002904 }
2905 break;
2906 }
2907
danielk197794eb6a12005-12-15 15:22:08 +00002908 /*
danielk1977404ca072009-03-16 13:19:36 +00002909 ** $db unlock_notify ?script?
2910 */
2911 case DB_UNLOCK_NOTIFY: {
2912#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
drha198f2b2014-02-07 19:26:13 +00002913 Tcl_AppendResult(interp, "unlock_notify not available in this build",
2914 (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00002915 rc = TCL_ERROR;
2916#else
2917 if( objc!=2 && objc!=3 ){
2918 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2919 rc = TCL_ERROR;
2920 }else{
2921 void (*xNotify)(void **, int) = 0;
2922 void *pNotifyArg = 0;
2923
2924 if( pDb->pUnlockNotify ){
2925 Tcl_DecrRefCount(pDb->pUnlockNotify);
2926 pDb->pUnlockNotify = 0;
2927 }
2928
2929 if( objc==3 ){
2930 xNotify = DbUnlockNotify;
2931 pNotifyArg = (void *)pDb;
2932 pDb->pUnlockNotify = objv[2];
2933 Tcl_IncrRefCount(pDb->pUnlockNotify);
2934 }
2935
2936 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
drha198f2b2014-02-07 19:26:13 +00002937 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00002938 rc = TCL_ERROR;
2939 }
2940 }
2941#endif
2942 break;
2943 }
2944
drh304637c2011-03-18 16:47:27 +00002945 /*
2946 ** $db preupdate_hook count
2947 ** $db preupdate_hook hook ?SCRIPT?
2948 ** $db preupdate_hook new INDEX
2949 ** $db preupdate_hook old INDEX
2950 */
dan46c47d42011-03-01 18:42:07 +00002951 case DB_PREUPDATE: {
drh9b1c62d2011-03-30 21:04:43 +00002952#ifndef SQLITE_ENABLE_PREUPDATE_HOOK
2953 Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time");
2954 rc = TCL_ERROR;
2955#else
dan1e7a2d42011-03-22 18:45:29 +00002956 static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
dan46c47d42011-03-01 18:42:07 +00002957 enum DbPreupdateSubCmd {
dan1e7a2d42011-03-22 18:45:29 +00002958 PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
dan46c47d42011-03-01 18:42:07 +00002959 };
2960 int iSub;
2961
2962 if( objc<3 ){
2963 Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
2964 }
2965 if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
2966 return TCL_ERROR;
2967 }
2968
2969 switch( (enum DbPreupdateSubCmd)iSub ){
2970 case PRE_COUNT: {
2971 int nCol = sqlite3_preupdate_count(pDb->db);
2972 Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
2973 break;
2974 }
2975
2976 case PRE_HOOK: {
2977 if( objc>4 ){
2978 Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
2979 return TCL_ERROR;
2980 }
2981 DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
2982 break;
2983 }
2984
dan1e7a2d42011-03-22 18:45:29 +00002985 case PRE_DEPTH: {
2986 Tcl_Obj *pRet;
2987 if( objc!=3 ){
2988 Tcl_WrongNumArgs(interp, 3, objv, "");
2989 return TCL_ERROR;
2990 }
2991 pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
2992 Tcl_SetObjResult(interp, pRet);
2993 break;
2994 }
2995
dan37db03b2011-03-16 19:59:18 +00002996 case PRE_NEW:
dan46c47d42011-03-01 18:42:07 +00002997 case PRE_OLD: {
2998 int iIdx;
dan37db03b2011-03-16 19:59:18 +00002999 sqlite3_value *pValue;
dan46c47d42011-03-01 18:42:07 +00003000 if( objc!=4 ){
3001 Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
3002 return TCL_ERROR;
3003 }
3004 if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
3005 return TCL_ERROR;
3006 }
3007
dan37db03b2011-03-16 19:59:18 +00003008 if( iSub==PRE_OLD ){
dan46c47d42011-03-01 18:42:07 +00003009 rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
dan37db03b2011-03-16 19:59:18 +00003010 }else{
3011 assert( iSub==PRE_NEW );
3012 rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
dan46c47d42011-03-01 18:42:07 +00003013 }
3014
dan37db03b2011-03-16 19:59:18 +00003015 if( rc==SQLITE_OK ){
drh304637c2011-03-18 16:47:27 +00003016 Tcl_Obj *pObj;
3017 pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
dan37db03b2011-03-16 19:59:18 +00003018 Tcl_SetObjResult(interp, pObj);
3019 }else{
dan46c47d42011-03-01 18:42:07 +00003020 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
3021 return TCL_ERROR;
3022 }
3023 }
3024 }
drh9b1c62d2011-03-30 21:04:43 +00003025#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +00003026 break;
3027 }
3028
danielk1977404ca072009-03-16 13:19:36 +00003029 /*
drh833bf962010-04-28 14:42:19 +00003030 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003031 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00003032 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003033 */
drh833bf962010-04-28 14:42:19 +00003034 case DB_WAL_HOOK:
danielk197771fd80b2005-12-16 06:54:01 +00003035 case DB_UPDATE_HOOK:
dan6566ebe2011-03-16 09:49:14 +00003036 case DB_ROLLBACK_HOOK: {
danielk197771fd80b2005-12-16 06:54:01 +00003037 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
3038 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3039 */
mistachkinc5896b52016-04-12 20:15:12 +00003040 Tcl_Obj **ppHook = 0;
dan46c47d42011-03-01 18:42:07 +00003041 if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
3042 if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
3043 if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
3044 if( objc>3 ){
danielk197794eb6a12005-12-15 15:22:08 +00003045 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3046 return TCL_ERROR;
3047 }
danielk197771fd80b2005-12-16 06:54:01 +00003048
dan46c47d42011-03-01 18:42:07 +00003049 DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00003050 break;
3051 }
3052
danielk19774397de52005-01-12 12:44:03 +00003053 /* $db version
3054 **
3055 ** Return the version string for this database.
3056 */
3057 case DB_VERSION: {
3058 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
3059 break;
3060 }
3061
tpoindex1067fe12004-12-17 15:41:11 +00003062
drh6d313162000-09-21 13:01:35 +00003063 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00003064 return rc;
drh75897232000-05-29 14:26:00 +00003065}
3066
drha2c8a952009-10-13 18:38:34 +00003067#if SQLITE_TCL_NRE
3068/*
3069** Adaptor that provides an objCmd interface to the NRE-enabled
3070** interface implementation.
3071*/
3072static int DbObjCmdAdaptor(
3073 void *cd,
3074 Tcl_Interp *interp,
3075 int objc,
3076 Tcl_Obj *const*objv
3077){
3078 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
3079}
3080#endif /* SQLITE_TCL_NRE */
3081
drh75897232000-05-29 14:26:00 +00003082/*
drh3570ad92007-08-31 14:31:44 +00003083** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00003084** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00003085**
3086** This is the main Tcl command. When the "sqlite" Tcl command is
3087** invoked, this routine runs to process that command.
3088**
3089** The first argument, DBNAME, is an arbitrary name for a new
3090** database connection. This command creates a new command named
3091** DBNAME that is used to control that connection. The database
3092** connection is deleted when the DBNAME command is deleted.
3093**
drh3570ad92007-08-31 14:31:44 +00003094** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00003095**
drh75897232000-05-29 14:26:00 +00003096*/
drh22fbcb82004-02-01 01:22:50 +00003097static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00003098 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00003099 const char *zArg;
drh75897232000-05-29 14:26:00 +00003100 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00003101 int i;
drh22fbcb82004-02-01 01:22:50 +00003102 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00003103 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00003104 int flags;
drh882e8e42006-08-24 02:42:27 +00003105 Tcl_DString translatedFilename;
drh32f57d42016-03-16 01:03:10 +00003106#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00003107 void *pKey = 0;
3108 int nKey = 0;
3109#endif
mistachkin540ebf82012-09-10 07:29:29 +00003110 int rc;
drhd9da78a2009-03-24 15:08:09 +00003111
3112 /* In normal use, each TCL interpreter runs in a single thread. So
3113 ** by default, we can turn of mutexing on SQLite database connections.
3114 ** However, for testing purposes it is useful to have mutexes turned
3115 ** on. So, by default, mutexes default off. But if compiled with
3116 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3117 */
3118#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3119 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3120#else
3121 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3122#endif
3123
drh22fbcb82004-02-01 01:22:50 +00003124 if( objc==2 ){
3125 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00003126 if( strcmp(zArg,"-version")==0 ){
drha198f2b2014-02-07 19:26:13 +00003127 Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
drh647cb0e2002-11-04 19:32:25 +00003128 return TCL_OK;
3129 }
drh72bf6a32016-01-07 02:06:55 +00003130 if( strcmp(zArg,"-sourceid")==0 ){
3131 Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0);
3132 return TCL_OK;
3133 }
drh9eb9e262004-02-11 02:18:05 +00003134 if( strcmp(zArg,"-has-codec")==0 ){
drh32f57d42016-03-16 01:03:10 +00003135#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drha198f2b2014-02-07 19:26:13 +00003136 Tcl_AppendResult(interp,"1",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003137#else
drha198f2b2014-02-07 19:26:13 +00003138 Tcl_AppendResult(interp,"0",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003139#endif
3140 return TCL_OK;
3141 }
drhfbc3eab2001-04-06 16:13:42 +00003142 }
drh3570ad92007-08-31 14:31:44 +00003143 for(i=3; i+1<objc; i+=2){
3144 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00003145 if( strcmp(zArg,"-key")==0 ){
drh32f57d42016-03-16 01:03:10 +00003146#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh3570ad92007-08-31 14:31:44 +00003147 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
drhb07028f2011-10-14 21:49:18 +00003148#endif
drh3570ad92007-08-31 14:31:44 +00003149 }else if( strcmp(zArg, "-vfs")==0 ){
dan3c3dd7b2010-06-22 11:10:40 +00003150 zVfs = Tcl_GetString(objv[i+1]);
drh3570ad92007-08-31 14:31:44 +00003151 }else if( strcmp(zArg, "-readonly")==0 ){
3152 int b;
3153 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3154 if( b ){
drh33f4e022007-09-03 15:19:34 +00003155 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00003156 flags |= SQLITE_OPEN_READONLY;
3157 }else{
3158 flags &= ~SQLITE_OPEN_READONLY;
3159 flags |= SQLITE_OPEN_READWRITE;
3160 }
3161 }else if( strcmp(zArg, "-create")==0 ){
3162 int b;
3163 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00003164 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00003165 flags |= SQLITE_OPEN_CREATE;
3166 }else{
3167 flags &= ~SQLITE_OPEN_CREATE;
3168 }
danielk19779a6284c2008-07-10 17:52:49 +00003169 }else if( strcmp(zArg, "-nomutex")==0 ){
3170 int b;
3171 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3172 if( b ){
3173 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00003174 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00003175 }else{
3176 flags &= ~SQLITE_OPEN_NOMUTEX;
3177 }
danc431fd52011-06-27 16:55:50 +00003178 }else if( strcmp(zArg, "-fullmutex")==0 ){
drh039963a2008-09-03 00:43:15 +00003179 int b;
3180 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3181 if( b ){
3182 flags |= SQLITE_OPEN_FULLMUTEX;
3183 flags &= ~SQLITE_OPEN_NOMUTEX;
3184 }else{
3185 flags &= ~SQLITE_OPEN_FULLMUTEX;
3186 }
drhf12b3f62011-12-21 14:42:29 +00003187 }else if( strcmp(zArg, "-uri")==0 ){
3188 int b;
3189 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3190 if( b ){
3191 flags |= SQLITE_OPEN_URI;
3192 }else{
3193 flags &= ~SQLITE_OPEN_URI;
3194 }
drh3570ad92007-08-31 14:31:44 +00003195 }else{
3196 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3197 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00003198 }
3199 }
drh3570ad92007-08-31 14:31:44 +00003200 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00003201 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00003202 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh68bd4aa2012-01-13 16:16:10 +00003203 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
drh32f57d42016-03-16 01:03:10 +00003204#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh3570ad92007-08-31 14:31:44 +00003205 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00003206#endif
3207 );
drh75897232000-05-29 14:26:00 +00003208 return TCL_ERROR;
3209 }
drh75897232000-05-29 14:26:00 +00003210 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003211 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00003212 if( p==0 ){
mistachkin6ef5e122014-01-24 17:03:55 +00003213 Tcl_SetResult(interp, (char *)"malloc failed", TCL_STATIC);
drhbec3f402000-08-04 13:49:02 +00003214 return TCL_ERROR;
3215 }
3216 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00003217 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00003218 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003219 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00003220 Tcl_DStringFree(&translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003221 if( p->db ){
3222 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3223 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3224 sqlite3_close(p->db);
3225 p->db = 0;
3226 }
3227 }else{
mistachkin5dac8432012-09-11 02:00:25 +00003228 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
danielk197780290862004-05-22 09:21:21 +00003229 }
drh32f57d42016-03-16 01:03:10 +00003230#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhf3a65f72007-08-22 20:18:21 +00003231 if( p->db ){
3232 sqlite3_key(p->db, pKey, nKey);
3233 }
drheb8ed702004-02-11 10:37:23 +00003234#endif
drhbec3f402000-08-04 13:49:02 +00003235 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003236 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003237 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003238 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003239 return TCL_ERROR;
3240 }
drhfb7e7652005-01-24 00:28:42 +00003241 p->maxStmt = NUM_PREPARED_STMTS;
drh147ef392016-01-22 23:17:51 +00003242 p->openFlags = flags & SQLITE_OPEN_URI;
drh5169bbc2006-08-24 14:59:45 +00003243 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003244 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003245 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003246 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3247 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003248 }else{
3249 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3250 }
drh75897232000-05-29 14:26:00 +00003251 return TCL_OK;
3252}
3253
3254/*
drh90ca9752001-09-28 17:47:14 +00003255** Provide a dummy Tcl_InitStubs if we are using this as a static
3256** library.
3257*/
3258#ifndef USE_TCL_STUBS
3259# undef Tcl_InitStubs
drh0e85ccf2013-06-03 12:34:46 +00003260# define Tcl_InitStubs(a,b,c) TCL_VERSION
drh90ca9752001-09-28 17:47:14 +00003261#endif
3262
3263/*
drh29bc4612005-10-05 10:40:15 +00003264** Make sure we have a PACKAGE_VERSION macro defined. This will be
3265** defined automatically by the TEA makefile. But other makefiles
3266** do not define it.
3267*/
3268#ifndef PACKAGE_VERSION
3269# define PACKAGE_VERSION SQLITE_VERSION
3270#endif
3271
3272/*
drh75897232000-05-29 14:26:00 +00003273** Initialize this module.
3274**
3275** This Tcl module contains only a single new Tcl command named "sqlite".
3276** (Hence there is no namespace. There is no point in using a namespace
3277** if the extension only supplies one new name!) The "sqlite" command is
3278** used to open a new SQLite database. See the DbMain() routine above
3279** for additional information.
drhb652f432010-08-26 16:46:57 +00003280**
3281** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003282*/
drhb652f432010-08-26 16:46:57 +00003283EXTERN int Sqlite3_Init(Tcl_Interp *interp){
mistachkin27b2f052015-01-12 19:49:46 +00003284 int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
drh6dc8cbe2013-05-31 15:36:07 +00003285 if( rc==TCL_OK ){
3286 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh1cca0d22010-08-25 20:35:51 +00003287#ifndef SQLITE_3_SUFFIX_ONLY
drh6dc8cbe2013-05-31 15:36:07 +00003288 /* The "sqlite" alias is undocumented. It is here only to support
3289 ** legacy scripts. All new scripts should use only the "sqlite3"
3290 ** command. */
3291 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003292#endif
drh6dc8cbe2013-05-31 15:36:07 +00003293 rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3294 }
3295 return rc;
drh90ca9752001-09-28 17:47:14 +00003296}
drhb652f432010-08-26 16:46:57 +00003297EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
drhb652f432010-08-26 16:46:57 +00003298EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3299EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00003300
drhd878cab2012-03-20 15:10:42 +00003301/* Because it accesses the file-system and uses persistent state, SQLite
drhe75a9eb2016-02-13 18:54:10 +00003302** is not considered appropriate for safe interpreters. Hence, we cause
3303** the _SafeInit() interfaces return TCL_ERROR.
drhd878cab2012-03-20 15:10:42 +00003304*/
drhe75a9eb2016-02-13 18:54:10 +00003305EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
3306EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
3307
3308
drh49766d62005-01-08 18:42:28 +00003309
3310#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003311int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3312int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
dana3e63c42010-08-20 12:33:59 +00003313int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3314int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00003315#endif
drh75897232000-05-29 14:26:00 +00003316
drh3e27c022004-07-23 00:01:38 +00003317#ifdef TCLSH
3318/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003319** All of the code that follows is used to build standalone TCL interpreters
3320** that are statically linked with SQLite. Enable these by compiling
3321** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3322** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3323** analysis program.
drh75897232000-05-29 14:26:00 +00003324*/
drh348784e2000-05-29 20:41:49 +00003325
drh57a02272009-10-22 20:52:05 +00003326#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3327/*
3328 * This code implements the MD5 message-digest algorithm.
3329 * The algorithm is due to Ron Rivest. This code was
3330 * written by Colin Plumb in 1993, no copyright is claimed.
3331 * This code is in the public domain; do with it what you wish.
3332 *
3333 * Equivalent code is available from RSA Data Security, Inc.
3334 * This code has been tested against that, and is equivalent,
3335 * except that you don't need to include two pages of legalese
3336 * with every copy.
3337 *
3338 * To compute the message digest of a chunk of bytes, declare an
3339 * MD5Context structure, pass it to MD5Init, call MD5Update as
3340 * needed on buffers full of bytes, and then call MD5Final, which
3341 * will fill a supplied 16-byte array with the digest.
3342 */
3343
3344/*
3345 * If compiled on a machine that doesn't have a 32-bit integer,
3346 * you just set "uint32" to the appropriate datatype for an
3347 * unsigned 32-bit integer. For example:
3348 *
3349 * cc -Duint32='unsigned long' md5.c
3350 *
3351 */
3352#ifndef uint32
3353# define uint32 unsigned int
3354#endif
3355
3356struct MD5Context {
3357 int isInit;
3358 uint32 buf[4];
3359 uint32 bits[2];
3360 unsigned char in[64];
3361};
3362typedef struct MD5Context MD5Context;
3363
3364/*
3365 * Note: this code is harmless on little-endian machines.
3366 */
3367static void byteReverse (unsigned char *buf, unsigned longs){
3368 uint32 t;
3369 do {
3370 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3371 ((unsigned)buf[1]<<8 | buf[0]);
3372 *(uint32 *)buf = t;
3373 buf += 4;
3374 } while (--longs);
3375}
3376/* The four core functions - F1 is optimized somewhat */
3377
3378/* #define F1(x, y, z) (x & y | ~x & z) */
3379#define F1(x, y, z) (z ^ (x & (y ^ z)))
3380#define F2(x, y, z) F1(z, x, y)
3381#define F3(x, y, z) (x ^ y ^ z)
3382#define F4(x, y, z) (y ^ (x | ~z))
3383
3384/* This is the central step in the MD5 algorithm. */
3385#define MD5STEP(f, w, x, y, z, data, s) \
3386 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3387
3388/*
3389 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3390 * reflect the addition of 16 longwords of new data. MD5Update blocks
3391 * the data and converts bytes into longwords for this routine.
3392 */
3393static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3394 register uint32 a, b, c, d;
3395
3396 a = buf[0];
3397 b = buf[1];
3398 c = buf[2];
3399 d = buf[3];
3400
3401 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3402 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3403 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3404 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3405 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3406 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3407 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3408 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3409 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3410 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3411 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3412 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3413 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3414 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3415 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3416 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3417
3418 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3419 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3420 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3421 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3422 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3423 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3424 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3425 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3426 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3427 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3428 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3429 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3430 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3431 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3432 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3433 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3434
3435 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3436 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3437 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3438 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3439 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3440 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3441 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3442 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3443 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3444 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3445 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3446 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3447 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3448 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3449 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3450 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3451
3452 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3453 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3454 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3455 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3456 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3457 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3458 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3459 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3460 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3461 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3462 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3463 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3464 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3465 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3466 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3467 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3468
3469 buf[0] += a;
3470 buf[1] += b;
3471 buf[2] += c;
3472 buf[3] += d;
3473}
3474
3475/*
3476 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3477 * initialization constants.
3478 */
3479static void MD5Init(MD5Context *ctx){
3480 ctx->isInit = 1;
3481 ctx->buf[0] = 0x67452301;
3482 ctx->buf[1] = 0xefcdab89;
3483 ctx->buf[2] = 0x98badcfe;
3484 ctx->buf[3] = 0x10325476;
3485 ctx->bits[0] = 0;
3486 ctx->bits[1] = 0;
3487}
3488
3489/*
3490 * Update context to reflect the concatenation of another buffer full
3491 * of bytes.
3492 */
3493static
3494void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3495 uint32 t;
3496
3497 /* Update bitcount */
3498
3499 t = ctx->bits[0];
3500 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3501 ctx->bits[1]++; /* Carry from low to high */
3502 ctx->bits[1] += len >> 29;
3503
3504 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3505
3506 /* Handle any leading odd-sized chunks */
3507
3508 if ( t ) {
3509 unsigned char *p = (unsigned char *)ctx->in + t;
3510
3511 t = 64-t;
3512 if (len < t) {
3513 memcpy(p, buf, len);
3514 return;
3515 }
3516 memcpy(p, buf, t);
3517 byteReverse(ctx->in, 16);
3518 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3519 buf += t;
3520 len -= t;
3521 }
3522
3523 /* Process data in 64-byte chunks */
3524
3525 while (len >= 64) {
3526 memcpy(ctx->in, buf, 64);
3527 byteReverse(ctx->in, 16);
3528 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3529 buf += 64;
3530 len -= 64;
3531 }
3532
3533 /* Handle any remaining bytes of data. */
3534
3535 memcpy(ctx->in, buf, len);
3536}
3537
3538/*
3539 * Final wrapup - pad to 64-byte boundary with the bit pattern
3540 * 1 0* (64-bit count of bits processed, MSB-first)
3541 */
3542static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3543 unsigned count;
3544 unsigned char *p;
3545
3546 /* Compute number of bytes mod 64 */
3547 count = (ctx->bits[0] >> 3) & 0x3F;
3548
3549 /* Set the first char of padding to 0x80. This is safe since there is
3550 always at least one byte free */
3551 p = ctx->in + count;
3552 *p++ = 0x80;
3553
3554 /* Bytes of padding needed to make 64 bytes */
3555 count = 64 - 1 - count;
3556
3557 /* Pad out to 56 mod 64 */
3558 if (count < 8) {
3559 /* Two lots of padding: Pad the first block to 64 bytes */
3560 memset(p, 0, count);
3561 byteReverse(ctx->in, 16);
3562 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3563
3564 /* Now fill the next block with 56 bytes */
3565 memset(ctx->in, 0, 56);
3566 } else {
3567 /* Pad block to 56 bytes */
3568 memset(p, 0, count-8);
3569 }
3570 byteReverse(ctx->in, 14);
3571
3572 /* Append length in bits and transform */
drha47941f2013-12-20 18:57:44 +00003573 memcpy(ctx->in + 14*4, ctx->bits, 8);
drh57a02272009-10-22 20:52:05 +00003574
3575 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3576 byteReverse((unsigned char *)ctx->buf, 4);
3577 memcpy(digest, ctx->buf, 16);
drh57a02272009-10-22 20:52:05 +00003578}
3579
3580/*
3581** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3582*/
3583static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3584 static char const zEncode[] = "0123456789abcdef";
3585 int i, j;
3586
3587 for(j=i=0; i<16; i++){
3588 int a = digest[i];
3589 zBuf[j++] = zEncode[(a>>4)&0xf];
3590 zBuf[j++] = zEncode[a & 0xf];
3591 }
3592 zBuf[j] = 0;
3593}
3594
3595
3596/*
3597** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3598** each representing 16 bits of the digest and separated from each
3599** other by a "-" character.
3600*/
3601static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3602 int i, j;
3603 unsigned int x;
3604 for(i=j=0; i<16; i+=2){
3605 x = digest[i]*256 + digest[i+1];
3606 if( i>0 ) zDigest[j++] = '-';
drh05f6c672015-02-26 16:32:33 +00003607 sqlite3_snprintf(50-j, &zDigest[j], "%05u", x);
drh57a02272009-10-22 20:52:05 +00003608 j += 5;
3609 }
3610 zDigest[j] = 0;
3611}
3612
3613/*
3614** A TCL command for md5. The argument is the text to be hashed. The
3615** Result is the hash in base64.
3616*/
3617static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3618 MD5Context ctx;
3619 unsigned char digest[16];
3620 char zBuf[50];
3621 void (*converter)(unsigned char*, char*);
3622
3623 if( argc!=2 ){
3624 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
drha198f2b2014-02-07 19:26:13 +00003625 " TEXT\"", (char*)0);
drh57a02272009-10-22 20:52:05 +00003626 return TCL_ERROR;
3627 }
3628 MD5Init(&ctx);
3629 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3630 MD5Final(digest, &ctx);
3631 converter = (void(*)(unsigned char*,char*))cd;
3632 converter(digest, zBuf);
3633 Tcl_AppendResult(interp, zBuf, (char*)0);
3634 return TCL_OK;
3635}
3636
3637/*
3638** A TCL command to take the md5 hash of a file. The argument is the
3639** name of the file.
3640*/
3641static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3642 FILE *in;
3643 MD5Context ctx;
3644 void (*converter)(unsigned char*, char*);
3645 unsigned char digest[16];
3646 char zBuf[10240];
3647
3648 if( argc!=2 ){
3649 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
drha198f2b2014-02-07 19:26:13 +00003650 " FILENAME\"", (char*)0);
drh57a02272009-10-22 20:52:05 +00003651 return TCL_ERROR;
3652 }
3653 in = fopen(argv[1],"rb");
3654 if( in==0 ){
3655 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
drha198f2b2014-02-07 19:26:13 +00003656 "\" for reading", (char*)0);
drh57a02272009-10-22 20:52:05 +00003657 return TCL_ERROR;
3658 }
3659 MD5Init(&ctx);
3660 for(;;){
3661 int n;
drh83cc1392012-04-19 18:04:28 +00003662 n = (int)fread(zBuf, 1, sizeof(zBuf), in);
drh57a02272009-10-22 20:52:05 +00003663 if( n<=0 ) break;
3664 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3665 }
3666 fclose(in);
3667 MD5Final(digest, &ctx);
3668 converter = (void(*)(unsigned char*,char*))cd;
3669 converter(digest, zBuf);
3670 Tcl_AppendResult(interp, zBuf, (char*)0);
3671 return TCL_OK;
3672}
3673
3674/*
3675** Register the four new TCL commands for generating MD5 checksums
3676** with the TCL interpreter.
3677*/
3678int Md5_Init(Tcl_Interp *interp){
3679 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3680 MD5DigestToBase16, 0);
3681 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3682 MD5DigestToBase10x8, 0);
3683 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3684 MD5DigestToBase16, 0);
3685 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3686 MD5DigestToBase10x8, 0);
3687 return TCL_OK;
3688}
3689#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3690
3691#if defined(SQLITE_TEST)
3692/*
3693** During testing, the special md5sum() aggregate function is available.
3694** inside SQLite. The following routines implement that function.
3695*/
3696static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3697 MD5Context *p;
3698 int i;
3699 if( argc<1 ) return;
3700 p = sqlite3_aggregate_context(context, sizeof(*p));
3701 if( p==0 ) return;
3702 if( !p->isInit ){
3703 MD5Init(p);
3704 }
3705 for(i=0; i<argc; i++){
3706 const char *zData = (char*)sqlite3_value_text(argv[i]);
3707 if( zData ){
drh83cc1392012-04-19 18:04:28 +00003708 MD5Update(p, (unsigned char*)zData, (int)strlen(zData));
drh57a02272009-10-22 20:52:05 +00003709 }
3710 }
3711}
3712static void md5finalize(sqlite3_context *context){
3713 MD5Context *p;
3714 unsigned char digest[16];
3715 char zBuf[33];
3716 p = sqlite3_aggregate_context(context, sizeof(*p));
3717 MD5Final(digest,p);
3718 MD5DigestToBase16(digest, zBuf);
3719 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3720}
3721int Md5_Register(sqlite3 *db){
3722 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
3723 md5step, md5finalize);
3724 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3725 return rc;
3726}
3727#endif /* defined(SQLITE_TEST) */
3728
3729
drh348784e2000-05-29 20:41:49 +00003730/*
drh3e27c022004-07-23 00:01:38 +00003731** If the macro TCLSH is one, then put in code this for the
3732** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003733** standard input, or if a file is named on the command line
3734** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003735*/
drh3e27c022004-07-23 00:01:38 +00003736#if TCLSH==1
dan0ae479d2011-09-21 16:43:07 +00003737static const char *tclsh_main_loop(void){
3738 static const char zMainloop[] =
3739 "set line {}\n"
3740 "while {![eof stdin]} {\n"
3741 "if {$line!=\"\"} {\n"
3742 "puts -nonewline \"> \"\n"
3743 "} else {\n"
3744 "puts -nonewline \"% \"\n"
drh348784e2000-05-29 20:41:49 +00003745 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003746 "flush stdout\n"
3747 "append line [gets stdin]\n"
3748 "if {[info complete $line]} {\n"
3749 "if {[catch {uplevel #0 $line} result]} {\n"
3750 "puts stderr \"Error: $result\"\n"
3751 "} elseif {$result!=\"\"} {\n"
3752 "puts $result\n"
3753 "}\n"
3754 "set line {}\n"
3755 "} else {\n"
3756 "append line \\n\n"
3757 "}\n"
drh348784e2000-05-29 20:41:49 +00003758 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003759 ;
3760 return zMainloop;
3761}
drh3e27c022004-07-23 00:01:38 +00003762#endif
drh3a0f13f2010-07-12 16:47:48 +00003763#if TCLSH==2
dan0ae479d2011-09-21 16:43:07 +00003764static const char *tclsh_main_loop(void);
drh3a0f13f2010-07-12 16:47:48 +00003765#endif
drh3e27c022004-07-23 00:01:38 +00003766
danc1a60c52010-06-07 14:28:16 +00003767#ifdef SQLITE_TEST
3768static void init_all(Tcl_Interp *);
3769static int init_all_cmd(
3770 ClientData cd,
3771 Tcl_Interp *interp,
3772 int objc,
3773 Tcl_Obj *CONST objv[]
3774){
danielk19770a549072009-02-17 16:29:10 +00003775
danc1a60c52010-06-07 14:28:16 +00003776 Tcl_Interp *slave;
3777 if( objc!=2 ){
3778 Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3779 return TCL_ERROR;
3780 }
3781
3782 slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3783 if( !slave ){
3784 return TCL_ERROR;
3785 }
3786
3787 init_all(slave);
3788 return TCL_OK;
3789}
danc431fd52011-06-27 16:55:50 +00003790
3791/*
3792** Tclcmd: db_use_legacy_prepare DB BOOLEAN
3793**
3794** The first argument to this command must be a database command created by
3795** [sqlite3]. If the second argument is true, then the handle is configured
3796** to use the sqlite3_prepare_v2() function to prepare statements. If it
3797** is false, sqlite3_prepare().
3798*/
3799static int db_use_legacy_prepare_cmd(
3800 ClientData cd,
3801 Tcl_Interp *interp,
3802 int objc,
3803 Tcl_Obj *CONST objv[]
3804){
3805 Tcl_CmdInfo cmdInfo;
3806 SqliteDb *pDb;
3807 int bPrepare;
3808
3809 if( objc!=3 ){
3810 Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
3811 return TCL_ERROR;
3812 }
3813
3814 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3815 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3816 return TCL_ERROR;
3817 }
3818 pDb = (SqliteDb*)cmdInfo.objClientData;
3819 if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
3820 return TCL_ERROR;
3821 }
3822
3823 pDb->bLegacyPrepare = bPrepare;
3824
3825 Tcl_ResetResult(interp);
3826 return TCL_OK;
3827}
dan04489b62014-10-31 20:11:32 +00003828
3829/*
3830** Tclcmd: db_last_stmt_ptr DB
3831**
3832** If the statement cache associated with database DB is not empty,
3833** return the text representation of the most recently used statement
3834** handle.
3835*/
3836static int db_last_stmt_ptr(
3837 ClientData cd,
3838 Tcl_Interp *interp,
3839 int objc,
3840 Tcl_Obj *CONST objv[]
3841){
3842 extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
3843 Tcl_CmdInfo cmdInfo;
3844 SqliteDb *pDb;
3845 sqlite3_stmt *pStmt = 0;
3846 char zBuf[100];
3847
3848 if( objc!=2 ){
3849 Tcl_WrongNumArgs(interp, 1, objv, "DB");
3850 return TCL_ERROR;
3851 }
3852
3853 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3854 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3855 return TCL_ERROR;
3856 }
3857 pDb = (SqliteDb*)cmdInfo.objClientData;
3858
3859 if( pDb->stmtList ) pStmt = pDb->stmtList->pStmt;
3860 if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ){
3861 return TCL_ERROR;
3862 }
3863 Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
3864
3865 return TCL_OK;
3866}
drh1a4a6802015-05-04 18:31:09 +00003867#endif /* SQLITE_TEST */
3868
danc1a60c52010-06-07 14:28:16 +00003869/*
3870** Configure the interpreter passed as the first argument to have access
3871** to the commands and linked variables that make up:
3872**
3873** * the [sqlite3] extension itself,
3874**
3875** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
3876**
3877** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
3878** test suite.
3879*/
3880static void init_all(Tcl_Interp *interp){
drh38f82712004-06-18 17:10:16 +00003881 Sqlite3_Init(interp);
danc1a60c52010-06-07 14:28:16 +00003882
drh57a02272009-10-22 20:52:05 +00003883#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3884 Md5_Init(interp);
3885#endif
danc1a60c52010-06-07 14:28:16 +00003886
drhd9b02572001-04-15 00:37:09 +00003887#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00003888 {
drh2f999a62007-08-15 19:16:43 +00003889 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00003890 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00003891 extern int Sqlitetest2_Init(Tcl_Interp*);
3892 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00003893 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00003894 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00003895 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00003896 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00003897 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00003898 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00003899 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00003900 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
danb391b942014-11-07 14:41:11 +00003901 extern int Sqlitetest_blob_Init(Tcl_Interp*);
dan0a7a9152010-04-07 07:57:38 +00003902 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
drh984bfaa2008-03-19 16:08:53 +00003903 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00003904 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00003905 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003906 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00003907 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00003908 extern int Sqlitetestschema_Init(Tcl_Interp*);
3909 extern int Sqlitetestsse_Init(Tcl_Interp*);
3910 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
dan9f5ff372013-01-11 09:58:54 +00003911 extern int Sqlitetestfs_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00003912 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00003913 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00003914 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00003915 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh522efc62009-11-10 17:24:37 +00003916 extern int Sqlitetestintarray_Init(Tcl_Interp*);
danc7991bd2010-05-05 19:04:59 +00003917 extern int Sqlitetestvfs_Init(Tcl_Interp *);
dan9508daa2010-08-28 18:58:00 +00003918 extern int Sqlitetestrtree_Init(Tcl_Interp*);
dan8cf35eb2010-09-01 11:40:05 +00003919 extern int Sqlitequota_Init(Tcl_Interp*);
shaneh8a922f72010-11-04 20:50:27 +00003920 extern int Sqlitemultiplex_Init(Tcl_Interp*);
dane336b002010-11-19 18:20:09 +00003921 extern int SqliteSuperlock_Init(Tcl_Interp*);
dan213ca0a2011-03-28 19:10:06 +00003922 extern int SqlitetestSyscall_Init(Tcl_Interp*);
drh9b1c62d2011-03-30 21:04:43 +00003923#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
dan4fccf432011-03-08 19:22:50 +00003924 extern int TestSession_Init(Tcl_Interp*);
3925#endif
dan89a89562014-12-01 20:05:00 +00003926 extern int Fts5tcl_Init(Tcl_Interp *);
drhcfb8f8d2015-07-23 20:44:49 +00003927 extern int SqliteRbu_Init(Tcl_Interp*);
dan8e4251b2016-03-01 18:07:43 +00003928 extern int Sqlitetesttcl_Init(Tcl_Interp*);
dan6764a702011-06-20 11:15:06 +00003929#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00003930 extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
3931#endif
3932
danb29010c2010-12-29 18:24:38 +00003933#ifdef SQLITE_ENABLE_ZIPVFS
3934 extern int Zipvfs_Init(Tcl_Interp*);
3935 Zipvfs_Init(interp);
3936#endif
3937
drh2f999a62007-08-15 19:16:43 +00003938 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00003939 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00003940 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00003941 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00003942 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00003943 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00003944 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00003945 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00003946 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00003947 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00003948 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00003949 Sqlitetest_autoext_Init(interp);
danb391b942014-11-07 14:41:11 +00003950 Sqlitetest_blob_Init(interp);
dan0a7a9152010-04-07 07:57:38 +00003951 Sqlitetest_demovfs_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00003952 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00003953 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00003954 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003955 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00003956 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00003957 Sqlitetestschema_Init(interp);
3958 Sqlitetesttclvar_Init(interp);
dan9f5ff372013-01-11 09:58:54 +00003959 Sqlitetestfs_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00003960 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003961 SqlitetestOnefile_Init(interp);
danielk19775d1f5aa2008-04-10 14:51:00 +00003962 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00003963 Sqlitetestbackup_Init(interp);
drh522efc62009-11-10 17:24:37 +00003964 Sqlitetestintarray_Init(interp);
danc7991bd2010-05-05 19:04:59 +00003965 Sqlitetestvfs_Init(interp);
dan9508daa2010-08-28 18:58:00 +00003966 Sqlitetestrtree_Init(interp);
dan8cf35eb2010-09-01 11:40:05 +00003967 Sqlitequota_Init(interp);
shaneh8a922f72010-11-04 20:50:27 +00003968 Sqlitemultiplex_Init(interp);
dane336b002010-11-19 18:20:09 +00003969 SqliteSuperlock_Init(interp);
dan213ca0a2011-03-28 19:10:06 +00003970 SqlitetestSyscall_Init(interp);
drh9b1c62d2011-03-30 21:04:43 +00003971#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
dan4fccf432011-03-08 19:22:50 +00003972 TestSession_Init(interp);
3973#endif
dan89a89562014-12-01 20:05:00 +00003974 Fts5tcl_Init(interp);
drhcfb8f8d2015-07-23 20:44:49 +00003975 SqliteRbu_Init(interp);
dan8e4251b2016-03-01 18:07:43 +00003976 Sqlitetesttcl_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00003977
dan6764a702011-06-20 11:15:06 +00003978#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00003979 Sqlitetestfts3_Init(interp);
3980#endif
drh2e66f0b2005-04-28 17:18:48 +00003981
danc431fd52011-06-27 16:55:50 +00003982 Tcl_CreateObjCommand(
3983 interp, "load_testfixture_extensions", init_all_cmd, 0, 0
3984 );
3985 Tcl_CreateObjCommand(
3986 interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
3987 );
dan04489b62014-10-31 20:11:32 +00003988 Tcl_CreateObjCommand(
3989 interp, "db_last_stmt_ptr", db_last_stmt_ptr, 0, 0
3990 );
danc1a60c52010-06-07 14:28:16 +00003991
drh3e27c022004-07-23 00:01:38 +00003992#ifdef SQLITE_SSE
drh348784e2000-05-29 20:41:49 +00003993 Sqlitetestsse_Init(interp);
3994#endif
3995 }
drh61212b62004-12-02 20:17:00 +00003996#endif
danc1a60c52010-06-07 14:28:16 +00003997}
3998
drhdb6bafa2015-01-09 21:54:58 +00003999/* Needed for the setrlimit() system call on unix */
4000#if defined(unix)
4001#include <sys/resource.h>
4002#endif
4003
danc1a60c52010-06-07 14:28:16 +00004004#define TCLSH_MAIN main /* Needed to fake out mktclapp */
4005int TCLSH_MAIN(int argc, char **argv){
4006 Tcl_Interp *interp;
mistachkin1f28e072013-08-15 08:06:15 +00004007
4008#if !defined(_WIN32_WCE)
4009 if( getenv("BREAK") ){
4010 fprintf(stderr,
4011 "attach debugger to process %d and press any key to continue.\n",
4012 GETPID());
4013 fgetc(stdin);
4014 }
4015#endif
4016
drhdb6bafa2015-01-09 21:54:58 +00004017 /* Since the primary use case for this binary is testing of SQLite,
4018 ** be sure to generate core files if we crash */
4019#if defined(SQLITE_TEST) && defined(unix)
4020 { struct rlimit x;
4021 getrlimit(RLIMIT_CORE, &x);
4022 x.rlim_cur = x.rlim_max;
4023 setrlimit(RLIMIT_CORE, &x);
4024 }
4025#endif /* SQLITE_TEST && unix */
4026
4027
danc1a60c52010-06-07 14:28:16 +00004028 /* Call sqlite3_shutdown() once before doing anything else. This is to
4029 ** test that sqlite3_shutdown() can be safely called by a process before
4030 ** sqlite3_initialize() is. */
4031 sqlite3_shutdown();
4032
dan0ae479d2011-09-21 16:43:07 +00004033 Tcl_FindExecutable(argv[0]);
mistachkin2953ba92014-02-14 00:25:03 +00004034 Tcl_SetSystemEncoding(NULL, "utf-8");
dan0ae479d2011-09-21 16:43:07 +00004035 interp = Tcl_CreateInterp();
4036
drh3a0f13f2010-07-12 16:47:48 +00004037#if TCLSH==2
4038 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
4039#endif
danc1a60c52010-06-07 14:28:16 +00004040
danc1a60c52010-06-07 14:28:16 +00004041 init_all(interp);
drhc7285972009-11-10 01:13:25 +00004042 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00004043 int i;
shessad42c3a2006-08-22 23:53:46 +00004044 char zArgc[32];
4045 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
4046 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00004047 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
4048 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
4049 for(i=3-TCLSH; i<argc; i++){
4050 Tcl_SetVar(interp, "argv", argv[i],
4051 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
4052 }
drh3a0f13f2010-07-12 16:47:48 +00004053 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00004054 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00004055 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00004056 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00004057 return 1;
4058 }
drh3e27c022004-07-23 00:01:38 +00004059 }
drh3a0f13f2010-07-12 16:47:48 +00004060 if( TCLSH==2 || argc<=1 ){
dan0ae479d2011-09-21 16:43:07 +00004061 Tcl_GlobalEval(interp, tclsh_main_loop());
drh348784e2000-05-29 20:41:49 +00004062 }
4063 return 0;
4064}
4065#endif /* TCLSH */