blob: bc94a5ff7f15c4df07e7737e5363a214bf3fcf81 [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)
mistachkin52b1dbb2016-07-28 14:37:04 +000033# include "msvc.h"
mistachkin27b2f052015-01-12 19:49:46 +000034#endif
35
mistachkin52b1dbb2016-07-28 14:37:04 +000036#if defined(INCLUDE_SQLITE_TCL_H)
37# include "sqlite_tcl.h"
38#else
39# include "tcl.h"
mistachkin7617e4a2016-07-28 17:11:20 +000040# ifndef SQLITE_TCLAPI
41# define SQLITE_TCLAPI
42# endif
mistachkin52b1dbb2016-07-28 14:37:04 +000043#endif
danielk1977b4e9af92007-05-01 17:49:49 +000044#include <errno.h>
drhbd08af42007-04-05 21:58:33 +000045
46/*
47** Some additional include files are needed if this file is not
48** appended to the amalgamation.
49*/
50#ifndef SQLITE_AMALGAMATION
drh65e8c822009-12-01 13:57:48 +000051# include "sqlite3.h"
drhbd08af42007-04-05 21:58:33 +000052# include <stdlib.h>
53# include <string.h>
54# include <assert.h>
drh65e8c822009-12-01 13:57:48 +000055 typedef unsigned char u8;
drhbd08af42007-04-05 21:58:33 +000056#endif
drheb206382009-10-24 15:51:33 +000057#include <ctype.h>
drh75897232000-05-29 14:26:00 +000058
mistachkin1f28e072013-08-15 08:06:15 +000059/* Used to get the current process ID */
60#if !defined(_WIN32)
61# include <unistd.h>
62# define GETPID getpid
63#elif !defined(_WIN32_WCE)
64# ifndef SQLITE_AMALGAMATION
65# define WIN32_LEAN_AND_MEAN
66# include <windows.h>
67# endif
68# define GETPID (int)GetCurrentProcessId
69#endif
70
drhad6e1372006-07-10 21:15:51 +000071/*
72 * Windows needs to know which symbols to export. Unix does not.
73 * BUILD_sqlite should be undefined for Unix.
74 */
75#ifdef BUILD_sqlite
76#undef TCL_STORAGE_CLASS
77#define TCL_STORAGE_CLASS DLLEXPORT
78#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000079
danielk1977a21c6b62005-01-24 10:25:59 +000080#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000081#define MAX_PREPARED_STMTS 100
82
drhc45e6712012-10-03 11:02:33 +000083/* Forward declaration */
84typedef struct SqliteDb SqliteDb;
drh98808ba2001-10-18 12:34:46 +000085
86/*
drhcabb0812002-09-14 13:47:32 +000087** New SQL functions can be created as TCL scripts. Each such function
88** is described by an instance of the following structure.
89*/
90typedef struct SqlFunc SqlFunc;
91struct SqlFunc {
92 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000093 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
drhc45e6712012-10-03 11:02:33 +000094 SqliteDb *pDb; /* Database connection that owns this function */
drhd1e47332005-06-26 17:55:33 +000095 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
96 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000097 SqlFunc *pNext; /* Next function on the list of them all */
98};
99
100/*
danielk19770202b292004-06-09 09:55:16 +0000101** New collation sequences function can be created as TCL scripts. Each such
102** function is described by an instance of the following structure.
103*/
104typedef struct SqlCollate SqlCollate;
105struct SqlCollate {
106 Tcl_Interp *interp; /* The TCL interpret to execute the function */
107 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +0000108 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +0000109};
110
111/*
drhfb7e7652005-01-24 00:28:42 +0000112** Prepared statements are cached for faster execution. Each prepared
113** statement is described by an instance of the following structure.
114*/
115typedef struct SqlPreparedStmt SqlPreparedStmt;
116struct SqlPreparedStmt {
117 SqlPreparedStmt *pNext; /* Next in linked list */
118 SqlPreparedStmt *pPrev; /* Previous on the list */
119 sqlite3_stmt *pStmt; /* The prepared statement */
120 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +0000121 const char *zSql; /* Text of the SQL statement */
dan4a4c11a2009-10-06 14:59:02 +0000122 int nParm; /* Size of apParm array */
123 Tcl_Obj **apParm; /* Array of referenced object pointers */
drhfb7e7652005-01-24 00:28:42 +0000124};
125
danielk1977d04417962007-05-02 13:16:30 +0000126typedef struct IncrblobChannel IncrblobChannel;
127
drhfb7e7652005-01-24 00:28:42 +0000128/*
drhbec3f402000-08-04 13:49:02 +0000129** There is one instance of this structure for each SQLite database
130** that has been opened by the SQLite TCL interface.
danc431fd52011-06-27 16:55:50 +0000131**
132** If this module is built with SQLITE_TEST defined (to create the SQLite
133** testfixture executable), then it may be configured to use either
134** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
135** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
drhbec3f402000-08-04 13:49:02 +0000136*/
drhbec3f402000-08-04 13:49:02 +0000137struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000138 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000139 Tcl_Interp *interp; /* The interpreter used for this database */
140 char *zBusy; /* The busy callback routine */
141 char *zCommit; /* The commit hook callback routine */
142 char *zTrace; /* The trace callback routine */
mistachkinb56660f2016-07-14 21:26:09 +0000143 char *zTraceV2; /* The trace_v2 callback routine */
drh19e2d372005-08-29 23:00:03 +0000144 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000145 char *zProgress; /* The progress callback routine */
146 char *zAuth; /* The authorization callback routine */
drh1f1549f2008-08-26 21:33:34 +0000147 int disableAuth; /* Disable the authorizer if it exists */
drhd1e47332005-06-26 17:55:33 +0000148 char *zNull; /* Text to substitute for an SQL NULL value */
149 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000150 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
dan46c47d42011-03-01 18:42:07 +0000151 Tcl_Obj *pPreUpdateHook; /* Pre-update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000152 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drh5def0842010-05-05 20:00:25 +0000153 Tcl_Obj *pWalHook; /* WAL hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000154 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000155 SqlCollate *pCollate; /* List of SQL collation functions */
156 int rc; /* Return code of most recent sqlite3_exec() */
157 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000158 SqlPreparedStmt *stmtList; /* List of prepared statements*/
159 SqlPreparedStmt *stmtLast; /* Last statement in the list */
160 int maxStmt; /* The next maximum number of stmtList */
161 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000162 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh3c379b02010-04-07 19:31:59 +0000163 int nStep, nSort, nIndex; /* Statistics for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000164 int nTransaction; /* Number of nested [transaction] methods */
drh147ef392016-01-22 23:17:51 +0000165 int openFlags; /* Flags used to open. (SQLITE_OPEN_URI) */
danc431fd52011-06-27 16:55:50 +0000166#ifdef SQLITE_TEST
167 int bLegacyPrepare; /* True to use sqlite3_prepare() */
168#endif
drh98808ba2001-10-18 12:34:46 +0000169};
drh297ecf12001-04-05 15:57:13 +0000170
danielk1977b4e9af92007-05-01 17:49:49 +0000171struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000172 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000173 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000174 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000175 Tcl_Channel channel; /* Channel identifier */
176 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
177 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000178};
179
drhea678832008-12-10 19:26:22 +0000180/*
181** Compute a string length that is limited to what can be stored in
182** lower 30 bits of a 32-bit signed integer.
183*/
drh4f21c4a2008-12-10 22:15:00 +0000184static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000185 const char *z2 = z;
186 while( *z2 ){ z2++; }
187 return 0x3fffffff & (int)(z2 - z);
188}
drhea678832008-12-10 19:26:22 +0000189
190
danielk197732a0d8b2007-05-04 19:03:02 +0000191#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000192/*
danielk1977d04417962007-05-02 13:16:30 +0000193** Close all incrblob channels opened using database connection pDb.
194** This is called when shutting down the database connection.
195*/
196static void closeIncrblobChannels(SqliteDb *pDb){
197 IncrblobChannel *p;
198 IncrblobChannel *pNext;
199
200 for(p=pDb->pIncrblob; p; p=pNext){
201 pNext = p->pNext;
202
mistachkinb56660f2016-07-14 21:26:09 +0000203 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
danielk1977d04417962007-05-02 13:16:30 +0000204 ** which deletes the IncrblobChannel structure at *p. So do not
205 ** call Tcl_Free() here.
206 */
207 Tcl_UnregisterChannel(pDb->interp, p->channel);
208 }
209}
210
211/*
danielk1977b4e9af92007-05-01 17:49:49 +0000212** Close an incremental blob channel.
213*/
mistachkin7617e4a2016-07-28 17:11:20 +0000214static int SQLITE_TCLAPI incrblobClose(
215 ClientData instanceData,
216 Tcl_Interp *interp
217){
danielk1977b4e9af92007-05-01 17:49:49 +0000218 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000219 int rc = sqlite3_blob_close(p->pBlob);
220 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000221
222 /* Remove the channel from the SqliteDb.pIncrblob list. */
223 if( p->pNext ){
224 p->pNext->pPrev = p->pPrev;
225 }
226 if( p->pPrev ){
227 p->pPrev->pNext = p->pNext;
228 }
229 if( p->pDb->pIncrblob==p ){
230 p->pDb->pIncrblob = p->pNext;
231 }
232
danielk197792d4d7a2007-05-04 12:05:56 +0000233 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000234 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000235
236 if( rc!=SQLITE_OK ){
237 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
238 return TCL_ERROR;
239 }
danielk1977b4e9af92007-05-01 17:49:49 +0000240 return TCL_OK;
241}
242
243/*
244** Read data from an incremental blob channel.
245*/
mistachkin7617e4a2016-07-28 17:11:20 +0000246static int SQLITE_TCLAPI incrblobInput(
mistachkinb56660f2016-07-14 21:26:09 +0000247 ClientData instanceData,
248 char *buf,
danielk1977b4e9af92007-05-01 17:49:49 +0000249 int bufSize,
250 int *errorCodePtr
251){
252 IncrblobChannel *p = (IncrblobChannel *)instanceData;
253 int nRead = bufSize; /* Number of bytes to read */
254 int nBlob; /* Total size of the blob */
255 int rc; /* sqlite error code */
256
257 nBlob = sqlite3_blob_bytes(p->pBlob);
258 if( (p->iSeek+nRead)>nBlob ){
259 nRead = nBlob-p->iSeek;
260 }
261 if( nRead<=0 ){
262 return 0;
263 }
264
265 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
266 if( rc!=SQLITE_OK ){
267 *errorCodePtr = rc;
268 return -1;
269 }
270
271 p->iSeek += nRead;
272 return nRead;
273}
274
danielk1977d04417962007-05-02 13:16:30 +0000275/*
276** Write data to an incremental blob channel.
277*/
mistachkin7617e4a2016-07-28 17:11:20 +0000278static int SQLITE_TCLAPI incrblobOutput(
mistachkinb56660f2016-07-14 21:26:09 +0000279 ClientData instanceData,
280 CONST char *buf,
danielk1977b4e9af92007-05-01 17:49:49 +0000281 int toWrite,
282 int *errorCodePtr
283){
284 IncrblobChannel *p = (IncrblobChannel *)instanceData;
285 int nWrite = toWrite; /* Number of bytes to write */
286 int nBlob; /* Total size of the blob */
287 int rc; /* sqlite error code */
288
289 nBlob = sqlite3_blob_bytes(p->pBlob);
290 if( (p->iSeek+nWrite)>nBlob ){
291 *errorCodePtr = EINVAL;
292 return -1;
293 }
294 if( nWrite<=0 ){
295 return 0;
296 }
297
298 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
299 if( rc!=SQLITE_OK ){
300 *errorCodePtr = EIO;
301 return -1;
302 }
303
304 p->iSeek += nWrite;
305 return nWrite;
306}
307
308/*
309** Seek an incremental blob channel.
310*/
mistachkin7617e4a2016-07-28 17:11:20 +0000311static int SQLITE_TCLAPI incrblobSeek(
mistachkinb56660f2016-07-14 21:26:09 +0000312 ClientData instanceData,
danielk1977b4e9af92007-05-01 17:49:49 +0000313 long offset,
314 int seekMode,
315 int *errorCodePtr
316){
317 IncrblobChannel *p = (IncrblobChannel *)instanceData;
318
319 switch( seekMode ){
320 case SEEK_SET:
321 p->iSeek = offset;
322 break;
323 case SEEK_CUR:
324 p->iSeek += offset;
325 break;
326 case SEEK_END:
327 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
328 break;
329
330 default: assert(!"Bad seekMode");
331 }
332
333 return p->iSeek;
334}
335
336
mistachkin7617e4a2016-07-28 17:11:20 +0000337static void SQLITE_TCLAPI incrblobWatch(
338 ClientData instanceData,
339 int mode
340){
mistachkinb56660f2016-07-14 21:26:09 +0000341 /* NO-OP */
danielk1977b4e9af92007-05-01 17:49:49 +0000342}
mistachkin7617e4a2016-07-28 17:11:20 +0000343static int SQLITE_TCLAPI incrblobHandle(
344 ClientData instanceData,
345 int dir,
346 ClientData *hPtr
347){
danielk1977b4e9af92007-05-01 17:49:49 +0000348 return TCL_ERROR;
349}
350
351static Tcl_ChannelType IncrblobChannelType = {
352 "incrblob", /* typeName */
353 TCL_CHANNEL_VERSION_2, /* version */
354 incrblobClose, /* closeProc */
355 incrblobInput, /* inputProc */
356 incrblobOutput, /* outputProc */
357 incrblobSeek, /* seekProc */
358 0, /* setOptionProc */
359 0, /* getOptionProc */
360 incrblobWatch, /* watchProc (this is a no-op) */
361 incrblobHandle, /* getHandleProc (always returns error) */
362 0, /* close2Proc */
363 0, /* blockModeProc */
364 0, /* flushProc */
365 0, /* handlerProc */
366 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000367};
368
369/*
370** Create a new incrblob channel.
371*/
372static int createIncrblobChannel(
mistachkinb56660f2016-07-14 21:26:09 +0000373 Tcl_Interp *interp,
374 SqliteDb *pDb,
danielk1977b4e9af92007-05-01 17:49:49 +0000375 const char *zDb,
mistachkinb56660f2016-07-14 21:26:09 +0000376 const char *zTable,
377 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000378 sqlite_int64 iRow,
379 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000380){
381 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000382 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000383 sqlite3_blob *pBlob;
384 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000385 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000386
387 /* This variable is used to name the channels: "incrblob_[incr count]" */
388 static int count = 0;
389 char zChannel[64];
390
danielk19778cbadb02007-05-03 16:31:26 +0000391 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000392 if( rc!=SQLITE_OK ){
393 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
394 return TCL_ERROR;
395 }
396
397 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
398 p->iSeek = 0;
399 p->pBlob = pBlob;
400
drh5bb3eb92007-05-04 13:15:55 +0000401 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000402 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
403 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000404
danielk1977d04417962007-05-02 13:16:30 +0000405 /* Link the new channel into the SqliteDb.pIncrblob list. */
406 p->pNext = pDb->pIncrblob;
407 p->pPrev = 0;
408 if( p->pNext ){
409 p->pNext->pPrev = p;
410 }
411 pDb->pIncrblob = p;
412 p->pDb = pDb;
413
414 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000415 return TCL_OK;
416}
danielk197732a0d8b2007-05-04 19:03:02 +0000417#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
418 #define closeIncrblobChannels(pDb)
419#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000420
drh6d313162000-09-21 13:01:35 +0000421/*
drhd1e47332005-06-26 17:55:33 +0000422** Look at the script prefix in pCmd. We will be executing this script
423** after first appending one or more arguments. This routine analyzes
424** the script to see if it is safe to use Tcl_EvalObjv() on the script
425** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
426** faster.
427**
428** Scripts that are safe to use with Tcl_EvalObjv() consists of a
429** command name followed by zero or more arguments with no [...] or $
430** or {...} or ; to be seen anywhere. Most callback scripts consist
431** of just a single procedure name and they meet this requirement.
432*/
433static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
434 /* We could try to do something with Tcl_Parse(). But we will instead
435 ** just do a search for forbidden characters. If any of the forbidden
436 ** characters appear in pCmd, we will report the string as unsafe.
437 */
438 const char *z;
439 int n;
440 z = Tcl_GetStringFromObj(pCmd, &n);
441 while( n-- > 0 ){
442 int c = *(z++);
443 if( c=='$' || c=='[' || c==';' ) return 0;
444 }
445 return 1;
446}
447
448/*
449** Find an SqlFunc structure with the given name. Or create a new
450** one if an existing one cannot be found. Return a pointer to the
451** structure.
452*/
453static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
454 SqlFunc *p, *pNew;
drh0425f182013-11-26 16:48:04 +0000455 int nName = strlen30(zName);
456 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
drhd1e47332005-06-26 17:55:33 +0000457 pNew->zName = (char*)&pNew[1];
drh0425f182013-11-26 16:48:04 +0000458 memcpy(pNew->zName, zName, nName+1);
mistachkinb56660f2016-07-14 21:26:09 +0000459 for(p=pDb->pFunc; p; p=p->pNext){
drh0425f182013-11-26 16:48:04 +0000460 if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
drhd1e47332005-06-26 17:55:33 +0000461 Tcl_Free((char*)pNew);
462 return p;
463 }
464 }
465 pNew->interp = pDb->interp;
drhc45e6712012-10-03 11:02:33 +0000466 pNew->pDb = pDb;
drhd1e47332005-06-26 17:55:33 +0000467 pNew->pScript = 0;
468 pNew->pNext = pDb->pFunc;
469 pDb->pFunc = pNew;
470 return pNew;
471}
472
473/*
danc431fd52011-06-27 16:55:50 +0000474** Free a single SqlPreparedStmt object.
475*/
476static void dbFreeStmt(SqlPreparedStmt *pStmt){
477#ifdef SQLITE_TEST
478 if( sqlite3_sql(pStmt->pStmt)==0 ){
479 Tcl_Free((char *)pStmt->zSql);
480 }
481#endif
482 sqlite3_finalize(pStmt->pStmt);
483 Tcl_Free((char *)pStmt);
484}
485
486/*
drhfb7e7652005-01-24 00:28:42 +0000487** Finalize and free a list of prepared statements
488*/
danc431fd52011-06-27 16:55:50 +0000489static void flushStmtCache(SqliteDb *pDb){
drhfb7e7652005-01-24 00:28:42 +0000490 SqlPreparedStmt *pPreStmt;
danc431fd52011-06-27 16:55:50 +0000491 SqlPreparedStmt *pNext;
drhfb7e7652005-01-24 00:28:42 +0000492
danc431fd52011-06-27 16:55:50 +0000493 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
494 pNext = pPreStmt->pNext;
495 dbFreeStmt(pPreStmt);
drhfb7e7652005-01-24 00:28:42 +0000496 }
497 pDb->nStmt = 0;
498 pDb->stmtLast = 0;
danc431fd52011-06-27 16:55:50 +0000499 pDb->stmtList = 0;
drhfb7e7652005-01-24 00:28:42 +0000500}
501
502/*
drh895d7472004-08-20 16:02:39 +0000503** TCL calls this procedure when an sqlite3 database command is
504** deleted.
drh75897232000-05-29 14:26:00 +0000505*/
mistachkin7617e4a2016-07-28 17:11:20 +0000506static void SQLITE_TCLAPI DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000507 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000508 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000509 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000510 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000511 while( pDb->pFunc ){
512 SqlFunc *pFunc = pDb->pFunc;
513 pDb->pFunc = pFunc->pNext;
drhc45e6712012-10-03 11:02:33 +0000514 assert( pFunc->pDb==pDb );
drhd1e47332005-06-26 17:55:33 +0000515 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000516 Tcl_Free((char*)pFunc);
517 }
danielk19770202b292004-06-09 09:55:16 +0000518 while( pDb->pCollate ){
519 SqlCollate *pCollate = pDb->pCollate;
520 pDb->pCollate = pCollate->pNext;
521 Tcl_Free((char*)pCollate);
522 }
drhbec3f402000-08-04 13:49:02 +0000523 if( pDb->zBusy ){
524 Tcl_Free(pDb->zBusy);
525 }
drhb5a20d32003-04-23 12:25:23 +0000526 if( pDb->zTrace ){
527 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000528 }
mistachkinb56660f2016-07-14 21:26:09 +0000529 if( pDb->zTraceV2 ){
530 Tcl_Free(pDb->zTraceV2);
531 }
drh19e2d372005-08-29 23:00:03 +0000532 if( pDb->zProfile ){
533 Tcl_Free(pDb->zProfile);
534 }
drhe22a3342003-04-22 20:30:37 +0000535 if( pDb->zAuth ){
536 Tcl_Free(pDb->zAuth);
537 }
danielk197755c45f22005-04-03 23:54:43 +0000538 if( pDb->zNull ){
539 Tcl_Free(pDb->zNull);
540 }
danielk197794eb6a12005-12-15 15:22:08 +0000541 if( pDb->pUpdateHook ){
542 Tcl_DecrRefCount(pDb->pUpdateHook);
543 }
dan46c47d42011-03-01 18:42:07 +0000544 if( pDb->pPreUpdateHook ){
545 Tcl_DecrRefCount(pDb->pPreUpdateHook);
546 }
danielk197771fd80b2005-12-16 06:54:01 +0000547 if( pDb->pRollbackHook ){
548 Tcl_DecrRefCount(pDb->pRollbackHook);
549 }
drh5def0842010-05-05 20:00:25 +0000550 if( pDb->pWalHook ){
551 Tcl_DecrRefCount(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000552 }
danielk197794eb6a12005-12-15 15:22:08 +0000553 if( pDb->pCollateNeeded ){
554 Tcl_DecrRefCount(pDb->pCollateNeeded);
555 }
drhbec3f402000-08-04 13:49:02 +0000556 Tcl_Free((char*)pDb);
557}
558
559/*
560** This routine is called when a database file is locked while trying
561** to execute SQL.
562*/
danielk19772a764eb2004-06-12 01:43:26 +0000563static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000564 SqliteDb *pDb = (SqliteDb*)cd;
565 int rc;
566 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000567
drh5bb3eb92007-05-04 13:15:55 +0000568 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000569 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000570 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
571 return 0;
572 }
573 return 1;
drh75897232000-05-29 14:26:00 +0000574}
575
drh26e4a8b2008-05-01 17:16:52 +0000576#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000577/*
danielk1977348bb5d2003-10-18 09:37:26 +0000578** This routine is invoked as the 'progress callback' for the database.
579*/
580static int DbProgressHandler(void *cd){
581 SqliteDb *pDb = (SqliteDb*)cd;
582 int rc;
583
584 assert( pDb->zProgress );
585 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
586 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
587 return 1;
588 }
589 return 0;
590}
drh26e4a8b2008-05-01 17:16:52 +0000591#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000592
drhd1167392006-01-23 13:00:35 +0000593#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000594/*
drhb5a20d32003-04-23 12:25:23 +0000595** This routine is called by the SQLite trace handler whenever a new
596** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000597*/
drhb5a20d32003-04-23 12:25:23 +0000598static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000599 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000600 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000601
drhb5a20d32003-04-23 12:25:23 +0000602 Tcl_DStringInit(&str);
603 Tcl_DStringAppend(&str, pDb->zTrace, -1);
604 Tcl_DStringAppendElement(&str, zSql);
605 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
606 Tcl_DStringFree(&str);
607 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000608}
drhd1167392006-01-23 13:00:35 +0000609#endif
drh0d1a6432003-04-03 15:46:04 +0000610
drhd1167392006-01-23 13:00:35 +0000611#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000612/*
mistachkinb56660f2016-07-14 21:26:09 +0000613** This routine is called by the SQLite trace_v2 handler whenever a new
614** supported event is generated. Unsupported event types are ignored.
615** The TCL script in pDb->zTraceV2 is executed, with the arguments for
616** the event appended to it (as list elements).
617*/
618static int DbTraceV2Handler(
619 unsigned type, /* One of the SQLITE_TRACE_* event types. */
620 void *cd, /* The original context data pointer. */
621 void *pd, /* Primary event data, depends on event type. */
622 void *xd /* Extra event data, depends on event type. */
623){
624 SqliteDb *pDb = (SqliteDb*)cd;
625 Tcl_Obj *pCmd;
626
627 switch( type ){
628 case SQLITE_TRACE_STMT: {
629 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
630 char *zSql = (char *)xd;
631
632 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
633 Tcl_IncrRefCount(pCmd);
634 Tcl_ListObjAppendElement(pDb->interp, pCmd,
635 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
636 Tcl_ListObjAppendElement(pDb->interp, pCmd,
637 Tcl_NewStringObj(zSql, -1));
638 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
639 Tcl_DecrRefCount(pCmd);
640 Tcl_ResetResult(pDb->interp);
641 break;
642 }
643 case SQLITE_TRACE_PROFILE: {
644 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
645 sqlite3_int64 ns = (sqlite3_int64)xd;
646
647 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
648 Tcl_IncrRefCount(pCmd);
649 Tcl_ListObjAppendElement(pDb->interp, pCmd,
650 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
651 Tcl_ListObjAppendElement(pDb->interp, pCmd,
652 Tcl_NewWideIntObj((Tcl_WideInt)ns));
653 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
654 Tcl_DecrRefCount(pCmd);
655 Tcl_ResetResult(pDb->interp);
656 break;
657 }
658 case SQLITE_TRACE_ROW: {
659 sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
660
661 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
662 Tcl_IncrRefCount(pCmd);
663 Tcl_ListObjAppendElement(pDb->interp, pCmd,
664 Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
665 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
666 Tcl_DecrRefCount(pCmd);
667 Tcl_ResetResult(pDb->interp);
668 break;
669 }
670 case SQLITE_TRACE_CLOSE: {
671 sqlite3 *db = (sqlite3 *)pd;
672
673 pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
674 Tcl_IncrRefCount(pCmd);
675 Tcl_ListObjAppendElement(pDb->interp, pCmd,
676 Tcl_NewWideIntObj((Tcl_WideInt)db));
677 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
678 Tcl_DecrRefCount(pCmd);
679 Tcl_ResetResult(pDb->interp);
680 break;
681 }
682 }
683 return SQLITE_OK;
684}
685#endif
686
687#ifndef SQLITE_OMIT_TRACE
688/*
drh19e2d372005-08-29 23:00:03 +0000689** This routine is called by the SQLite profile handler after a statement
690** SQL has executed. The TCL script in pDb->zProfile is evaluated.
691*/
692static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
693 SqliteDb *pDb = (SqliteDb*)cd;
694 Tcl_DString str;
695 char zTm[100];
696
697 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
698 Tcl_DStringInit(&str);
699 Tcl_DStringAppend(&str, pDb->zProfile, -1);
700 Tcl_DStringAppendElement(&str, zSql);
701 Tcl_DStringAppendElement(&str, zTm);
702 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
703 Tcl_DStringFree(&str);
704 Tcl_ResetResult(pDb->interp);
705}
drhd1167392006-01-23 13:00:35 +0000706#endif
drh19e2d372005-08-29 23:00:03 +0000707
708/*
drhaa940ea2004-01-15 02:44:03 +0000709** This routine is called when a transaction is committed. The
710** TCL script in pDb->zCommit is executed. If it returns non-zero or
711** if it throws an exception, the transaction is rolled back instead
712** of being committed.
713*/
714static int DbCommitHandler(void *cd){
715 SqliteDb *pDb = (SqliteDb*)cd;
716 int rc;
717
718 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
719 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
720 return 1;
721 }
722 return 0;
723}
724
danielk197771fd80b2005-12-16 06:54:01 +0000725static void DbRollbackHandler(void *clientData){
726 SqliteDb *pDb = (SqliteDb*)clientData;
727 assert(pDb->pRollbackHook);
728 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
729 Tcl_BackgroundError(pDb->interp);
730 }
731}
732
drh5def0842010-05-05 20:00:25 +0000733/*
734** This procedure handles wal_hook callbacks.
735*/
736static int DbWalHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000737 void *clientData,
738 sqlite3 *db,
739 const char *zDb,
dan8d22a172010-04-19 18:03:51 +0000740 int nEntry
741){
drh5def0842010-05-05 20:00:25 +0000742 int ret = SQLITE_OK;
dan8d22a172010-04-19 18:03:51 +0000743 Tcl_Obj *p;
744 SqliteDb *pDb = (SqliteDb*)clientData;
745 Tcl_Interp *interp = pDb->interp;
drh5def0842010-05-05 20:00:25 +0000746 assert(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000747
dan6e45e0c2014-12-10 20:29:49 +0000748 assert( db==pDb->db );
drh5def0842010-05-05 20:00:25 +0000749 p = Tcl_DuplicateObj(pDb->pWalHook);
dan8d22a172010-04-19 18:03:51 +0000750 Tcl_IncrRefCount(p);
751 Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
752 Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
mistachkinb56660f2016-07-14 21:26:09 +0000753 if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
dan8d22a172010-04-19 18:03:51 +0000754 || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
755 ){
756 Tcl_BackgroundError(interp);
757 }
758 Tcl_DecrRefCount(p);
759
760 return ret;
761}
762
drhbcf4f482009-03-27 12:44:35 +0000763#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
danielk1977404ca072009-03-16 13:19:36 +0000764static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
765 char zBuf[64];
drh65545b52015-01-19 00:35:53 +0000766 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
danielk1977404ca072009-03-16 13:19:36 +0000767 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
drh65545b52015-01-19 00:35:53 +0000768 sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
danielk1977404ca072009-03-16 13:19:36 +0000769 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
770}
771#else
drhbcf4f482009-03-27 12:44:35 +0000772# define setTestUnlockNotifyVars(x,y,z)
danielk1977404ca072009-03-16 13:19:36 +0000773#endif
774
drh69910da2009-03-27 12:32:54 +0000775#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000776static void DbUnlockNotify(void **apArg, int nArg){
777 int i;
778 for(i=0; i<nArg; i++){
779 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
780 SqliteDb *pDb = (SqliteDb *)apArg[i];
781 setTestUnlockNotifyVars(pDb->interp, i, nArg);
782 assert( pDb->pUnlockNotify);
783 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
784 Tcl_DecrRefCount(pDb->pUnlockNotify);
785 pDb->pUnlockNotify = 0;
786 }
787}
drh69910da2009-03-27 12:32:54 +0000788#endif
danielk1977404ca072009-03-16 13:19:36 +0000789
drh9b1c62d2011-03-30 21:04:43 +0000790#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +0000791/*
792** Pre-update hook callback.
793*/
794static void DbPreUpdateHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000795 void *p,
dan46c47d42011-03-01 18:42:07 +0000796 sqlite3 *db,
797 int op,
mistachkinb56660f2016-07-14 21:26:09 +0000798 const char *zDb,
799 const char *zTbl,
dan46c47d42011-03-01 18:42:07 +0000800 sqlite_int64 iKey1,
801 sqlite_int64 iKey2
802){
803 SqliteDb *pDb = (SqliteDb *)p;
804 Tcl_Obj *pCmd;
805 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
806
807 assert( (SQLITE_DELETE-1)/9 == 0 );
808 assert( (SQLITE_INSERT-1)/9 == 1 );
809 assert( (SQLITE_UPDATE-1)/9 == 2 );
810 assert( pDb->pPreUpdateHook );
811 assert( db==pDb->db );
812 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
813
814 pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
815 Tcl_IncrRefCount(pCmd);
816 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
817 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
818 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
819 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
820 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
821 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
822 Tcl_DecrRefCount(pCmd);
823}
drh9b1c62d2011-03-30 21:04:43 +0000824#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +0000825
danielk197794eb6a12005-12-15 15:22:08 +0000826static void DbUpdateHandler(
mistachkinb56660f2016-07-14 21:26:09 +0000827 void *p,
danielk197794eb6a12005-12-15 15:22:08 +0000828 int op,
mistachkinb56660f2016-07-14 21:26:09 +0000829 const char *zDb,
830 const char *zTbl,
danielk197794eb6a12005-12-15 15:22:08 +0000831 sqlite_int64 rowid
832){
833 SqliteDb *pDb = (SqliteDb *)p;
834 Tcl_Obj *pCmd;
dan46c47d42011-03-01 18:42:07 +0000835 static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
836
837 assert( (SQLITE_DELETE-1)/9 == 0 );
838 assert( (SQLITE_INSERT-1)/9 == 1 );
839 assert( (SQLITE_UPDATE-1)/9 == 2 );
danielk197794eb6a12005-12-15 15:22:08 +0000840
841 assert( pDb->pUpdateHook );
842 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
843
844 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
845 Tcl_IncrRefCount(pCmd);
dan46c47d42011-03-01 18:42:07 +0000846 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
danielk197794eb6a12005-12-15 15:22:08 +0000847 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
848 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
849 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
850 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
drhefdde162010-10-27 15:36:21 +0000851 Tcl_DecrRefCount(pCmd);
danielk197794eb6a12005-12-15 15:22:08 +0000852}
853
danielk19777cedc8d2004-06-10 10:50:08 +0000854static void tclCollateNeeded(
855 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000856 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000857 int enc,
858 const char *zName
859){
860 SqliteDb *pDb = (SqliteDb *)pCtx;
861 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
862 Tcl_IncrRefCount(pScript);
863 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
864 Tcl_EvalObjEx(pDb->interp, pScript, 0);
865 Tcl_DecrRefCount(pScript);
866}
867
drhaa940ea2004-01-15 02:44:03 +0000868/*
danielk19770202b292004-06-09 09:55:16 +0000869** This routine is called to evaluate an SQL collation function implemented
870** using TCL script.
871*/
872static int tclSqlCollate(
873 void *pCtx,
874 int nA,
875 const void *zA,
876 int nB,
877 const void *zB
878){
879 SqlCollate *p = (SqlCollate *)pCtx;
880 Tcl_Obj *pCmd;
881
882 pCmd = Tcl_NewStringObj(p->zScript, -1);
883 Tcl_IncrRefCount(pCmd);
884 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
885 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000886 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000887 Tcl_DecrRefCount(pCmd);
888 return (atoi(Tcl_GetStringResult(p->interp)));
889}
890
891/*
drhcabb0812002-09-14 13:47:32 +0000892** This routine is called to evaluate an SQL function implemented
893** using TCL script.
894*/
drhfb7e7652005-01-24 00:28:42 +0000895static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000896 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000897 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000898 int i;
899 int rc;
900
drhd1e47332005-06-26 17:55:33 +0000901 if( argc==0 ){
902 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
903 ** script object directly. This allows the TCL compiler to generate
904 ** bytecode for the command on the first invocation and thus make
905 ** subsequent invocations much faster. */
906 pCmd = p->pScript;
907 Tcl_IncrRefCount(pCmd);
908 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
909 Tcl_DecrRefCount(pCmd);
910 }else{
911 /* If there are arguments to the function, make a shallow copy of the
912 ** script object, lappend the arguments, then evaluate the copy.
913 **
peter.d.reid60ec9142014-09-06 16:39:46 +0000914 ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
mistachkinb56660f2016-07-14 21:26:09 +0000915 ** The new Tcl_Obj contains pointers to the original list elements.
drhd1e47332005-06-26 17:55:33 +0000916 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
917 ** of the list to tclCmdNameType, that alternate representation will
918 ** be preserved and reused on the next invocation.
919 */
920 Tcl_Obj **aArg;
921 int nArg;
922 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
mistachkinb56660f2016-07-14 21:26:09 +0000923 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhd1e47332005-06-26 17:55:33 +0000924 return;
mistachkinb56660f2016-07-14 21:26:09 +0000925 }
drhd1e47332005-06-26 17:55:33 +0000926 pCmd = Tcl_NewListObj(nArg, aArg);
927 Tcl_IncrRefCount(pCmd);
928 for(i=0; i<argc; i++){
929 sqlite3_value *pIn = argv[i];
930 Tcl_Obj *pVal;
mistachkinb56660f2016-07-14 21:26:09 +0000931
drhd1e47332005-06-26 17:55:33 +0000932 /* Set pVal to contain the i'th column of this row. */
933 switch( sqlite3_value_type(pIn) ){
934 case SQLITE_BLOB: {
935 int bytes = sqlite3_value_bytes(pIn);
936 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
937 break;
938 }
939 case SQLITE_INTEGER: {
940 sqlite_int64 v = sqlite3_value_int64(pIn);
941 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +0000942 pVal = Tcl_NewIntObj((int)v);
drhd1e47332005-06-26 17:55:33 +0000943 }else{
944 pVal = Tcl_NewWideIntObj(v);
945 }
946 break;
947 }
948 case SQLITE_FLOAT: {
949 double r = sqlite3_value_double(pIn);
950 pVal = Tcl_NewDoubleObj(r);
951 break;
952 }
953 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +0000954 pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
drhd1e47332005-06-26 17:55:33 +0000955 break;
956 }
957 default: {
958 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000959 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000960 break;
961 }
962 }
963 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
964 if( rc ){
965 Tcl_DecrRefCount(pCmd);
mistachkinb56660f2016-07-14 21:26:09 +0000966 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhd1e47332005-06-26 17:55:33 +0000967 return;
968 }
danielk197751ad0ec2004-05-24 12:39:02 +0000969 }
drhd1e47332005-06-26 17:55:33 +0000970 if( !p->useEvalObjv ){
971 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
972 ** is a list without a string representation. To prevent this from
973 ** happening, make sure pCmd has a valid string representation */
974 Tcl_GetString(pCmd);
975 }
976 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
977 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000978 }
danielk1977562e8d32005-05-20 09:40:55 +0000979
drhc7f269d2005-05-05 10:30:29 +0000980 if( rc && rc!=TCL_RETURN ){
mistachkinb56660f2016-07-14 21:26:09 +0000981 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000982 }else{
drhc7f269d2005-05-05 10:30:29 +0000983 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
984 int n;
985 u8 *data;
dan4a4c11a2009-10-06 14:59:02 +0000986 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
drhc7f269d2005-05-05 10:30:29 +0000987 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000988 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000989 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000990 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000991 data = Tcl_GetByteArrayFromObj(pVar, &n);
992 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000993 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000994 Tcl_GetIntFromObj(0, pVar, &n);
995 sqlite3_result_int(context, n);
996 }else if( c=='d' && strcmp(zType,"double")==0 ){
997 double r;
998 Tcl_GetDoubleFromObj(0, pVar, &r);
999 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +00001000 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1001 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +00001002 Tcl_WideInt v;
1003 Tcl_GetWideIntFromObj(0, pVar, &v);
1004 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +00001005 }else{
danielk197700fd9572005-12-07 06:27:43 +00001006 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1007 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +00001008 }
drhcabb0812002-09-14 13:47:32 +00001009 }
1010}
drh895d7472004-08-20 16:02:39 +00001011
drhe22a3342003-04-22 20:30:37 +00001012#ifndef SQLITE_OMIT_AUTHORIZATION
1013/*
1014** This is the authentication function. It appends the authentication
1015** type code and the two arguments to zCmd[] then invokes the result
1016** on the interpreter. The reply is examined to determine if the
1017** authentication fails or succeeds.
1018*/
1019static int auth_callback(
1020 void *pArg,
1021 int code,
1022 const char *zArg1,
1023 const char *zArg2,
1024 const char *zArg3,
1025 const char *zArg4
drh32c6a482014-09-11 13:44:52 +00001026#ifdef SQLITE_USER_AUTHENTICATION
1027 ,const char *zArg5
1028#endif
drhe22a3342003-04-22 20:30:37 +00001029){
mistachkin6ef5e122014-01-24 17:03:55 +00001030 const char *zCode;
drhe22a3342003-04-22 20:30:37 +00001031 Tcl_DString str;
1032 int rc;
1033 const char *zReply;
1034 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +00001035 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +00001036
1037 switch( code ){
1038 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
1039 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
1040 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
1041 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
1042 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
1043 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
1044 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
1045 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
1046 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
1047 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
1048 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
1049 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
1050 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
1051 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
1052 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
1053 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
1054 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
1055 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
1056 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
1057 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
1058 case SQLITE_READ : zCode="SQLITE_READ"; break;
1059 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
1060 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
1061 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +00001062 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
1063 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +00001064 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +00001065 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +00001066 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +00001067 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
1068 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +00001069 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +00001070 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drh65a2aaa2014-01-16 22:40:02 +00001071 case SQLITE_RECURSIVE : zCode="SQLITE_RECURSIVE"; break;
drhe22a3342003-04-22 20:30:37 +00001072 default : zCode="????"; break;
1073 }
1074 Tcl_DStringInit(&str);
1075 Tcl_DStringAppend(&str, pDb->zAuth, -1);
1076 Tcl_DStringAppendElement(&str, zCode);
1077 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
1078 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
1079 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
1080 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
drh32c6a482014-09-11 13:44:52 +00001081#ifdef SQLITE_USER_AUTHENTICATION
1082 Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
mistachkinb56660f2016-07-14 21:26:09 +00001083#endif
drhe22a3342003-04-22 20:30:37 +00001084 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
1085 Tcl_DStringFree(&str);
drhb07028f2011-10-14 21:49:18 +00001086 zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
drhe22a3342003-04-22 20:30:37 +00001087 if( strcmp(zReply,"SQLITE_OK")==0 ){
1088 rc = SQLITE_OK;
1089 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
1090 rc = SQLITE_DENY;
1091 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
1092 rc = SQLITE_IGNORE;
1093 }else{
1094 rc = 999;
1095 }
1096 return rc;
1097}
1098#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +00001099
1100/*
tpoindex1067fe12004-12-17 15:41:11 +00001101** This routine reads a line of text from FILE in, stores
1102** the text in memory obtained from malloc() and returns a pointer
1103** to the text. NULL is returned at end of file, or if malloc()
1104** fails.
1105**
1106** The interface is like "readline" but no command-line editing
1107** is done.
1108**
1109** copied from shell.c from '.import' command
1110*/
1111static char *local_getline(char *zPrompt, FILE *in){
1112 char *zLine;
1113 int nLine;
1114 int n;
tpoindex1067fe12004-12-17 15:41:11 +00001115
1116 nLine = 100;
1117 zLine = malloc( nLine );
1118 if( zLine==0 ) return 0;
1119 n = 0;
drhb07028f2011-10-14 21:49:18 +00001120 while( 1 ){
tpoindex1067fe12004-12-17 15:41:11 +00001121 if( n+100>nLine ){
1122 nLine = nLine*2 + 100;
1123 zLine = realloc(zLine, nLine);
1124 if( zLine==0 ) return 0;
1125 }
1126 if( fgets(&zLine[n], nLine - n, in)==0 ){
1127 if( n==0 ){
1128 free(zLine);
1129 return 0;
1130 }
1131 zLine[n] = 0;
tpoindex1067fe12004-12-17 15:41:11 +00001132 break;
1133 }
1134 while( zLine[n] ){ n++; }
1135 if( n>0 && zLine[n-1]=='\n' ){
1136 n--;
1137 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +00001138 break;
tpoindex1067fe12004-12-17 15:41:11 +00001139 }
1140 }
1141 zLine = realloc( zLine, n+1 );
1142 return zLine;
1143}
1144
danielk19778e556522007-11-13 10:30:24 +00001145
1146/*
dan4a4c11a2009-10-06 14:59:02 +00001147** This function is part of the implementation of the command:
danielk19778e556522007-11-13 10:30:24 +00001148**
dan4a4c11a2009-10-06 14:59:02 +00001149** $db transaction [-deferred|-immediate|-exclusive] SCRIPT
danielk19778e556522007-11-13 10:30:24 +00001150**
dan4a4c11a2009-10-06 14:59:02 +00001151** It is invoked after evaluating the script SCRIPT to commit or rollback
1152** the transaction or savepoint opened by the [transaction] command.
1153*/
mistachkina121cc72016-07-28 18:06:52 +00001154static int SQLITE_TCLAPI DbTransPostCmd(
dan4a4c11a2009-10-06 14:59:02 +00001155 ClientData data[], /* data[0] is the Sqlite3Db* for $db */
1156 Tcl_Interp *interp, /* Tcl interpreter */
1157 int result /* Result of evaluating SCRIPT */
1158){
mistachkin6ef5e122014-01-24 17:03:55 +00001159 static const char *const azEnd[] = {
dan4a4c11a2009-10-06 14:59:02 +00001160 "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */
1161 "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */
1162 "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1163 "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */
1164 };
1165 SqliteDb *pDb = (SqliteDb*)data[0];
1166 int rc = result;
1167 const char *zEnd;
1168
1169 pDb->nTransaction--;
1170 zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1171
1172 pDb->disableAuth++;
1173 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1174 /* This is a tricky scenario to handle. The most likely cause of an
mistachkinb56660f2016-07-14 21:26:09 +00001175 ** error is that the exec() above was an attempt to commit the
dan4a4c11a2009-10-06 14:59:02 +00001176 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
mistachkin48864df2013-03-21 21:20:32 +00001177 ** that an IO-error has occurred. In either case, throw a Tcl exception
dan4a4c11a2009-10-06 14:59:02 +00001178 ** and try to rollback the transaction.
1179 **
mistachkinb56660f2016-07-14 21:26:09 +00001180 ** But it could also be that the user executed one or more BEGIN,
dan4a4c11a2009-10-06 14:59:02 +00001181 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1182 ** this method's logic. Not clear how this would be best handled.
1183 */
1184 if( rc!=TCL_ERROR ){
drha198f2b2014-02-07 19:26:13 +00001185 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
dan4a4c11a2009-10-06 14:59:02 +00001186 rc = TCL_ERROR;
1187 }
1188 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1189 }
1190 pDb->disableAuth--;
1191
1192 return rc;
1193}
1194
1195/*
danc431fd52011-06-27 16:55:50 +00001196** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1197** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1198** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
mistachkinb56660f2016-07-14 21:26:09 +00001199** on whether or not the [db_use_legacy_prepare] command has been used to
danc431fd52011-06-27 16:55:50 +00001200** configure the connection.
1201*/
1202static int dbPrepare(
1203 SqliteDb *pDb, /* Database object */
1204 const char *zSql, /* SQL to compile */
1205 sqlite3_stmt **ppStmt, /* OUT: Prepared statement */
1206 const char **pzOut /* OUT: Pointer to next SQL statement */
1207){
1208#ifdef SQLITE_TEST
1209 if( pDb->bLegacyPrepare ){
1210 return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1211 }
1212#endif
1213 return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut);
1214}
1215
1216/*
dan4a4c11a2009-10-06 14:59:02 +00001217** Search the cache for a prepared-statement object that implements the
1218** first SQL statement in the buffer pointed to by parameter zIn. If
1219** no such prepared-statement can be found, allocate and prepare a new
1220** one. In either case, bind the current values of the relevant Tcl
1221** variables to any $var, :var or @var variables in the statement. Before
1222** returning, set *ppPreStmt to point to the prepared-statement object.
1223**
1224** Output parameter *pzOut is set to point to the next SQL statement in
1225** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1226** next statement.
1227**
1228** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1229** and an error message loaded into interpreter pDb->interp.
1230*/
1231static int dbPrepareAndBind(
1232 SqliteDb *pDb, /* Database object */
1233 char const *zIn, /* SQL to compile */
1234 char const **pzOut, /* OUT: Pointer to next SQL statement */
1235 SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */
1236){
1237 const char *zSql = zIn; /* Pointer to first SQL statement in zIn */
mistachkin7bb22ac2015-01-12 19:59:12 +00001238 sqlite3_stmt *pStmt = 0; /* Prepared statement object */
dan4a4c11a2009-10-06 14:59:02 +00001239 SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */
1240 int nSql; /* Length of zSql in bytes */
mistachkin7bb22ac2015-01-12 19:59:12 +00001241 int nVar = 0; /* Number of variables in statement */
dan4a4c11a2009-10-06 14:59:02 +00001242 int iParm = 0; /* Next free entry in apParm */
drh0425f182013-11-26 16:48:04 +00001243 char c;
dan4a4c11a2009-10-06 14:59:02 +00001244 int i;
1245 Tcl_Interp *interp = pDb->interp;
1246
1247 *ppPreStmt = 0;
1248
1249 /* Trim spaces from the start of zSql and calculate the remaining length. */
drh0425f182013-11-26 16:48:04 +00001250 while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
dan4a4c11a2009-10-06 14:59:02 +00001251 nSql = strlen30(zSql);
1252
1253 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1254 int n = pPreStmt->nSql;
mistachkinb56660f2016-07-14 21:26:09 +00001255 if( nSql>=n
dan4a4c11a2009-10-06 14:59:02 +00001256 && memcmp(pPreStmt->zSql, zSql, n)==0
1257 && (zSql[n]==0 || zSql[n-1]==';')
1258 ){
1259 pStmt = pPreStmt->pStmt;
1260 *pzOut = &zSql[pPreStmt->nSql];
1261
1262 /* When a prepared statement is found, unlink it from the
1263 ** cache list. It will later be added back to the beginning
1264 ** of the cache list in order to implement LRU replacement.
1265 */
1266 if( pPreStmt->pPrev ){
1267 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1268 }else{
1269 pDb->stmtList = pPreStmt->pNext;
1270 }
1271 if( pPreStmt->pNext ){
1272 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1273 }else{
1274 pDb->stmtLast = pPreStmt->pPrev;
1275 }
1276 pDb->nStmt--;
1277 nVar = sqlite3_bind_parameter_count(pStmt);
1278 break;
1279 }
1280 }
mistachkinb56660f2016-07-14 21:26:09 +00001281
dan4a4c11a2009-10-06 14:59:02 +00001282 /* If no prepared statement was found. Compile the SQL text. Also allocate
1283 ** a new SqlPreparedStmt structure. */
1284 if( pPreStmt==0 ){
1285 int nByte;
1286
danc431fd52011-06-27 16:55:50 +00001287 if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
drhc45e6712012-10-03 11:02:33 +00001288 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001289 return TCL_ERROR;
1290 }
1291 if( pStmt==0 ){
1292 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1293 /* A compile-time error in the statement. */
drhc45e6712012-10-03 11:02:33 +00001294 Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001295 return TCL_ERROR;
1296 }else{
1297 /* The statement was a no-op. Continue to the next statement
1298 ** in the SQL string.
1299 */
1300 return TCL_OK;
1301 }
1302 }
1303
1304 assert( pPreStmt==0 );
1305 nVar = sqlite3_bind_parameter_count(pStmt);
1306 nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1307 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1308 memset(pPreStmt, 0, nByte);
1309
1310 pPreStmt->pStmt = pStmt;
drh7ed243b2012-04-19 17:19:51 +00001311 pPreStmt->nSql = (int)(*pzOut - zSql);
dan4a4c11a2009-10-06 14:59:02 +00001312 pPreStmt->zSql = sqlite3_sql(pStmt);
1313 pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
danc431fd52011-06-27 16:55:50 +00001314#ifdef SQLITE_TEST
1315 if( pPreStmt->zSql==0 ){
1316 char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1317 memcpy(zCopy, zSql, pPreStmt->nSql);
1318 zCopy[pPreStmt->nSql] = '\0';
1319 pPreStmt->zSql = zCopy;
1320 }
1321#endif
dan4a4c11a2009-10-06 14:59:02 +00001322 }
1323 assert( pPreStmt );
1324 assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1325 assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1326
mistachkinb56660f2016-07-14 21:26:09 +00001327 /* Bind values to parameters that begin with $ or : */
dan4a4c11a2009-10-06 14:59:02 +00001328 for(i=1; i<=nVar; i++){
1329 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1330 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1331 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1332 if( pVar ){
1333 int n;
1334 u8 *data;
1335 const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
mistachkin8e189222015-04-19 21:43:16 +00001336 c = zType[0];
dan4a4c11a2009-10-06 14:59:02 +00001337 if( zVar[0]=='@' ||
1338 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1339 /* Load a BLOB type if the Tcl variable is a bytearray and
1340 ** it has no string representation or the host
1341 ** parameter name begins with "@". */
1342 data = Tcl_GetByteArrayFromObj(pVar, &n);
1343 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1344 Tcl_IncrRefCount(pVar);
1345 pPreStmt->apParm[iParm++] = pVar;
1346 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1347 Tcl_GetIntFromObj(interp, pVar, &n);
1348 sqlite3_bind_int(pStmt, i, n);
1349 }else if( c=='d' && strcmp(zType,"double")==0 ){
1350 double r;
1351 Tcl_GetDoubleFromObj(interp, pVar, &r);
1352 sqlite3_bind_double(pStmt, i, r);
1353 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1354 (c=='i' && strcmp(zType,"int")==0) ){
1355 Tcl_WideInt v;
1356 Tcl_GetWideIntFromObj(interp, pVar, &v);
1357 sqlite3_bind_int64(pStmt, i, v);
1358 }else{
1359 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1360 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1361 Tcl_IncrRefCount(pVar);
1362 pPreStmt->apParm[iParm++] = pVar;
1363 }
1364 }else{
1365 sqlite3_bind_null(pStmt, i);
1366 }
1367 }
1368 }
1369 pPreStmt->nParm = iParm;
1370 *ppPreStmt = pPreStmt;
dan937d0de2009-10-15 18:35:38 +00001371
dan4a4c11a2009-10-06 14:59:02 +00001372 return TCL_OK;
1373}
1374
dan4a4c11a2009-10-06 14:59:02 +00001375/*
1376** Release a statement reference obtained by calling dbPrepareAndBind().
1377** There should be exactly one call to this function for each call to
1378** dbPrepareAndBind().
1379**
1380** If the discard parameter is non-zero, then the statement is deleted
1381** immediately. Otherwise it is added to the LRU list and may be returned
1382** by a subsequent call to dbPrepareAndBind().
1383*/
1384static void dbReleaseStmt(
1385 SqliteDb *pDb, /* Database handle */
1386 SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */
1387 int discard /* True to delete (not cache) the pPreStmt */
1388){
1389 int i;
1390
1391 /* Free the bound string and blob parameters */
1392 for(i=0; i<pPreStmt->nParm; i++){
1393 Tcl_DecrRefCount(pPreStmt->apParm[i]);
1394 }
1395 pPreStmt->nParm = 0;
1396
1397 if( pDb->maxStmt<=0 || discard ){
1398 /* If the cache is turned off, deallocated the statement */
danc431fd52011-06-27 16:55:50 +00001399 dbFreeStmt(pPreStmt);
dan4a4c11a2009-10-06 14:59:02 +00001400 }else{
1401 /* Add the prepared statement to the beginning of the cache list. */
1402 pPreStmt->pNext = pDb->stmtList;
1403 pPreStmt->pPrev = 0;
1404 if( pDb->stmtList ){
1405 pDb->stmtList->pPrev = pPreStmt;
1406 }
1407 pDb->stmtList = pPreStmt;
1408 if( pDb->stmtLast==0 ){
1409 assert( pDb->nStmt==0 );
1410 pDb->stmtLast = pPreStmt;
1411 }else{
1412 assert( pDb->nStmt>0 );
1413 }
1414 pDb->nStmt++;
mistachkinb56660f2016-07-14 21:26:09 +00001415
1416 /* If we have too many statement in cache, remove the surplus from
dan4a4c11a2009-10-06 14:59:02 +00001417 ** the end of the cache list. */
1418 while( pDb->nStmt>pDb->maxStmt ){
danc431fd52011-06-27 16:55:50 +00001419 SqlPreparedStmt *pLast = pDb->stmtLast;
1420 pDb->stmtLast = pLast->pPrev;
dan4a4c11a2009-10-06 14:59:02 +00001421 pDb->stmtLast->pNext = 0;
1422 pDb->nStmt--;
danc431fd52011-06-27 16:55:50 +00001423 dbFreeStmt(pLast);
dan4a4c11a2009-10-06 14:59:02 +00001424 }
1425 }
1426}
1427
1428/*
1429** Structure used with dbEvalXXX() functions:
1430**
1431** dbEvalInit()
1432** dbEvalStep()
1433** dbEvalFinalize()
1434** dbEvalRowInfo()
1435** dbEvalColumnValue()
1436*/
1437typedef struct DbEvalContext DbEvalContext;
1438struct DbEvalContext {
1439 SqliteDb *pDb; /* Database handle */
1440 Tcl_Obj *pSql; /* Object holding string zSql */
1441 const char *zSql; /* Remaining SQL to execute */
1442 SqlPreparedStmt *pPreStmt; /* Current statement */
1443 int nCol; /* Number of columns returned by pStmt */
1444 Tcl_Obj *pArray; /* Name of array variable */
1445 Tcl_Obj **apColName; /* Array of column names */
1446};
1447
1448/*
1449** Release any cache of column names currently held as part of
1450** the DbEvalContext structure passed as the first argument.
1451*/
1452static void dbReleaseColumnNames(DbEvalContext *p){
1453 if( p->apColName ){
1454 int i;
1455 for(i=0; i<p->nCol; i++){
1456 Tcl_DecrRefCount(p->apColName[i]);
1457 }
1458 Tcl_Free((char *)p->apColName);
1459 p->apColName = 0;
1460 }
1461 p->nCol = 0;
1462}
1463
1464/*
1465** Initialize a DbEvalContext structure.
danielk19778e556522007-11-13 10:30:24 +00001466**
1467** If pArray is not NULL, then it contains the name of a Tcl array
1468** variable. The "*" member of this array is set to a list containing
dan4a4c11a2009-10-06 14:59:02 +00001469** the names of the columns returned by the statement as part of each
mistachkinb56660f2016-07-14 21:26:09 +00001470** call to dbEvalStep(), in order from left to right. e.g. if the names
1471** of the returned columns are a, b and c, it does the equivalent of the
dan4a4c11a2009-10-06 14:59:02 +00001472** tcl command:
danielk19778e556522007-11-13 10:30:24 +00001473**
1474** set ${pArray}(*) {a b c}
1475*/
dan4a4c11a2009-10-06 14:59:02 +00001476static void dbEvalInit(
1477 DbEvalContext *p, /* Pointer to structure to initialize */
1478 SqliteDb *pDb, /* Database handle */
1479 Tcl_Obj *pSql, /* Object containing SQL script */
1480 Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */
danielk19778e556522007-11-13 10:30:24 +00001481){
dan4a4c11a2009-10-06 14:59:02 +00001482 memset(p, 0, sizeof(DbEvalContext));
1483 p->pDb = pDb;
1484 p->zSql = Tcl_GetString(pSql);
1485 p->pSql = pSql;
1486 Tcl_IncrRefCount(pSql);
1487 if( pArray ){
1488 p->pArray = pArray;
1489 Tcl_IncrRefCount(pArray);
1490 }
1491}
danielk19778e556522007-11-13 10:30:24 +00001492
dan4a4c11a2009-10-06 14:59:02 +00001493/*
1494** Obtain information about the row that the DbEvalContext passed as the
1495** first argument currently points to.
1496*/
1497static void dbEvalRowInfo(
1498 DbEvalContext *p, /* Evaluation context */
1499 int *pnCol, /* OUT: Number of column names */
1500 Tcl_Obj ***papColName /* OUT: Array of column names */
1501){
danielk19778e556522007-11-13 10:30:24 +00001502 /* Compute column names */
dan4a4c11a2009-10-06 14:59:02 +00001503 if( 0==p->apColName ){
1504 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1505 int i; /* Iterator variable */
1506 int nCol; /* Number of columns returned by pStmt */
1507 Tcl_Obj **apColName = 0; /* Array of column names */
1508
1509 p->nCol = nCol = sqlite3_column_count(pStmt);
1510 if( nCol>0 && (papColName || p->pArray) ){
1511 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1512 for(i=0; i<nCol; i++){
drhc45e6712012-10-03 11:02:33 +00001513 apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
dan4a4c11a2009-10-06 14:59:02 +00001514 Tcl_IncrRefCount(apColName[i]);
1515 }
1516 p->apColName = apColName;
danielk19778e556522007-11-13 10:30:24 +00001517 }
1518
1519 /* If results are being stored in an array variable, then create
1520 ** the array(*) entry for that array
1521 */
dan4a4c11a2009-10-06 14:59:02 +00001522 if( p->pArray ){
1523 Tcl_Interp *interp = p->pDb->interp;
danielk19778e556522007-11-13 10:30:24 +00001524 Tcl_Obj *pColList = Tcl_NewObj();
1525 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
dan4a4c11a2009-10-06 14:59:02 +00001526
danielk19778e556522007-11-13 10:30:24 +00001527 for(i=0; i<nCol; i++){
1528 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1529 }
1530 Tcl_IncrRefCount(pStar);
dan4a4c11a2009-10-06 14:59:02 +00001531 Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
danielk19778e556522007-11-13 10:30:24 +00001532 Tcl_DecrRefCount(pStar);
1533 }
danielk19778e556522007-11-13 10:30:24 +00001534 }
1535
dan4a4c11a2009-10-06 14:59:02 +00001536 if( papColName ){
1537 *papColName = p->apColName;
1538 }
1539 if( pnCol ){
1540 *pnCol = p->nCol;
1541 }
1542}
1543
1544/*
1545** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1546** returned, then an error message is stored in the interpreter before
1547** returning.
1548**
1549** A return value of TCL_OK means there is a row of data available. The
1550** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1551** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1552** is returned, then the SQL script has finished executing and there are
1553** no further rows available. This is similar to SQLITE_DONE.
1554*/
1555static int dbEvalStep(DbEvalContext *p){
danc431fd52011-06-27 16:55:50 +00001556 const char *zPrevSql = 0; /* Previous value of p->zSql */
1557
dan4a4c11a2009-10-06 14:59:02 +00001558 while( p->zSql[0] || p->pPreStmt ){
1559 int rc;
1560 if( p->pPreStmt==0 ){
danc431fd52011-06-27 16:55:50 +00001561 zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
dan4a4c11a2009-10-06 14:59:02 +00001562 rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1563 if( rc!=TCL_OK ) return rc;
1564 }else{
1565 int rcs;
1566 SqliteDb *pDb = p->pDb;
1567 SqlPreparedStmt *pPreStmt = p->pPreStmt;
1568 sqlite3_stmt *pStmt = pPreStmt->pStmt;
1569
1570 rcs = sqlite3_step(pStmt);
1571 if( rcs==SQLITE_ROW ){
1572 return TCL_OK;
1573 }
1574 if( p->pArray ){
1575 dbEvalRowInfo(p, 0, 0);
1576 }
1577 rcs = sqlite3_reset(pStmt);
1578
1579 pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1580 pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
drh3c379b02010-04-07 19:31:59 +00001581 pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
dan4a4c11a2009-10-06 14:59:02 +00001582 dbReleaseColumnNames(p);
1583 p->pPreStmt = 0;
1584
1585 if( rcs!=SQLITE_OK ){
1586 /* If a run-time error occurs, report the error and stop reading
1587 ** the SQL. */
dan4a4c11a2009-10-06 14:59:02 +00001588 dbReleaseStmt(pDb, pPreStmt, 1);
danc431fd52011-06-27 16:55:50 +00001589#if SQLITE_TEST
1590 if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1591 /* If the runtime error was an SQLITE_SCHEMA, and the database
mistachkinb56660f2016-07-14 21:26:09 +00001592 ** handle is configured to use the legacy sqlite3_prepare()
danc431fd52011-06-27 16:55:50 +00001593 ** interface, retry prepare()/step() on the same SQL statement.
1594 ** This only happens once. If there is a second SQLITE_SCHEMA
1595 ** error, the error will be returned to the caller. */
1596 p->zSql = zPrevSql;
1597 continue;
1598 }
1599#endif
drhc45e6712012-10-03 11:02:33 +00001600 Tcl_SetObjResult(pDb->interp,
1601 Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
dan4a4c11a2009-10-06 14:59:02 +00001602 return TCL_ERROR;
1603 }else{
1604 dbReleaseStmt(pDb, pPreStmt, 0);
1605 }
1606 }
1607 }
1608
1609 /* Finished */
1610 return TCL_BREAK;
1611}
1612
1613/*
1614** Free all resources currently held by the DbEvalContext structure passed
1615** as the first argument. There should be exactly one call to this function
1616** for each call to dbEvalInit().
1617*/
1618static void dbEvalFinalize(DbEvalContext *p){
1619 if( p->pPreStmt ){
1620 sqlite3_reset(p->pPreStmt->pStmt);
1621 dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1622 p->pPreStmt = 0;
1623 }
1624 if( p->pArray ){
1625 Tcl_DecrRefCount(p->pArray);
1626 p->pArray = 0;
1627 }
1628 Tcl_DecrRefCount(p->pSql);
1629 dbReleaseColumnNames(p);
1630}
1631
1632/*
1633** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1634** the value for the iCol'th column of the row currently pointed to by
1635** the DbEvalContext structure passed as the first argument.
1636*/
1637static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1638 sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1639 switch( sqlite3_column_type(pStmt, iCol) ){
1640 case SQLITE_BLOB: {
1641 int bytes = sqlite3_column_bytes(pStmt, iCol);
1642 const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1643 if( !zBlob ) bytes = 0;
1644 return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1645 }
1646 case SQLITE_INTEGER: {
1647 sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1648 if( v>=-2147483647 && v<=2147483647 ){
drh7fd33922011-06-20 19:00:30 +00001649 return Tcl_NewIntObj((int)v);
dan4a4c11a2009-10-06 14:59:02 +00001650 }else{
1651 return Tcl_NewWideIntObj(v);
1652 }
1653 }
1654 case SQLITE_FLOAT: {
1655 return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1656 }
1657 case SQLITE_NULL: {
drhc45e6712012-10-03 11:02:33 +00001658 return Tcl_NewStringObj(p->pDb->zNull, -1);
dan4a4c11a2009-10-06 14:59:02 +00001659 }
1660 }
1661
drh325eff52012-10-03 12:56:18 +00001662 return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
dan4a4c11a2009-10-06 14:59:02 +00001663}
1664
1665/*
1666** If using Tcl version 8.6 or greater, use the NR functions to avoid
1667** recursive evalution of scripts by the [db eval] and [db trans]
1668** commands. Even if the headers used while compiling the extension
1669** are 8.6 or newer, the code still tests the Tcl version at runtime.
1670** This allows stubs-enabled builds to be used with older Tcl libraries.
1671*/
1672#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
drha2c8a952009-10-13 18:38:34 +00001673# define SQLITE_TCL_NRE 1
dan4a4c11a2009-10-06 14:59:02 +00001674static int DbUseNre(void){
1675 int major, minor;
1676 Tcl_GetVersion(&major, &minor, 0, 0);
1677 return( (major==8 && minor>=6) || major>8 );
1678}
1679#else
mistachkinb56660f2016-07-14 21:26:09 +00001680/*
dan4a4c11a2009-10-06 14:59:02 +00001681** Compiling using headers earlier than 8.6. In this case NR cannot be
1682** used, so DbUseNre() to always return zero. Add #defines for the other
1683** Tcl_NRxxx() functions to prevent them from causing compilation errors,
mistachkinb56660f2016-07-14 21:26:09 +00001684** even though the only invocations of them are within conditional blocks
dan4a4c11a2009-10-06 14:59:02 +00001685** of the form:
1686**
1687** if( DbUseNre() ) { ... }
1688*/
drha2c8a952009-10-13 18:38:34 +00001689# define SQLITE_TCL_NRE 0
dan4a4c11a2009-10-06 14:59:02 +00001690# define DbUseNre() 0
drha47941f2013-12-20 18:57:44 +00001691# define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001692# define Tcl_NREvalObj(a,b,c) 0
drha47941f2013-12-20 18:57:44 +00001693# define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
dan4a4c11a2009-10-06 14:59:02 +00001694#endif
1695
1696/*
1697** This function is part of the implementation of the command:
1698**
1699** $db eval SQL ?ARRAYNAME? SCRIPT
1700*/
mistachkina121cc72016-07-28 18:06:52 +00001701static int SQLITE_TCLAPI DbEvalNextCmd(
dan4a4c11a2009-10-06 14:59:02 +00001702 ClientData data[], /* data[0] is the (DbEvalContext*) */
1703 Tcl_Interp *interp, /* Tcl interpreter */
1704 int result /* Result so far */
1705){
1706 int rc = result; /* Return code */
1707
1708 /* The first element of the data[] array is a pointer to a DbEvalContext
1709 ** structure allocated using Tcl_Alloc(). The second element of data[]
1710 ** is a pointer to a Tcl_Obj containing the script to run for each row
1711 ** returned by the queries encapsulated in data[0]. */
1712 DbEvalContext *p = (DbEvalContext *)data[0];
1713 Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1714 Tcl_Obj *pArray = p->pArray;
1715
1716 while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1717 int i;
1718 int nCol;
1719 Tcl_Obj **apColName;
1720 dbEvalRowInfo(p, &nCol, &apColName);
1721 for(i=0; i<nCol; i++){
1722 Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1723 if( pArray==0 ){
1724 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1725 }else{
1726 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1727 }
1728 }
1729
mistachkinb56660f2016-07-14 21:26:09 +00001730 /* The required interpreter variables are now populated with the data
dan4a4c11a2009-10-06 14:59:02 +00001731 ** from the current row. If using NRE, schedule callbacks to evaluate
1732 ** script pScript, then to invoke this function again to fetch the next
1733 ** row (or clean up if there is no next row or the script throws an
mistachkinb56660f2016-07-14 21:26:09 +00001734 ** exception). After scheduling the callbacks, return control to the
dan4a4c11a2009-10-06 14:59:02 +00001735 ** caller.
1736 **
1737 ** If not using NRE, evaluate pScript directly and continue with the
1738 ** next iteration of this while(...) loop. */
1739 if( DbUseNre() ){
1740 Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1741 return Tcl_NREvalObj(interp, pScript, 0);
1742 }else{
1743 rc = Tcl_EvalObjEx(interp, pScript, 0);
1744 }
1745 }
1746
1747 Tcl_DecrRefCount(pScript);
1748 dbEvalFinalize(p);
1749 Tcl_Free((char *)p);
1750
1751 if( rc==TCL_OK || rc==TCL_BREAK ){
1752 Tcl_ResetResult(interp);
1753 rc = TCL_OK;
1754 }
1755 return rc;
danielk19778e556522007-11-13 10:30:24 +00001756}
1757
tpoindex1067fe12004-12-17 15:41:11 +00001758/*
mistachkinb56660f2016-07-14 21:26:09 +00001759** This function is used by the implementations of the following database
dan46c47d42011-03-01 18:42:07 +00001760** handle sub-commands:
1761**
1762** $db update_hook ?SCRIPT?
1763** $db wal_hook ?SCRIPT?
1764** $db commit_hook ?SCRIPT?
1765** $db preupdate hook ?SCRIPT?
1766*/
1767static void DbHookCmd(
1768 Tcl_Interp *interp, /* Tcl interpreter */
1769 SqliteDb *pDb, /* Database handle */
1770 Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */
1771 Tcl_Obj **ppHook /* Pointer to member of SqliteDb */
1772){
1773 sqlite3 *db = pDb->db;
1774
1775 if( *ppHook ){
1776 Tcl_SetObjResult(interp, *ppHook);
1777 if( pArg ){
1778 Tcl_DecrRefCount(*ppHook);
1779 *ppHook = 0;
1780 }
1781 }
1782 if( pArg ){
1783 assert( !(*ppHook) );
1784 if( Tcl_GetCharLength(pArg)>0 ){
1785 *ppHook = pArg;
1786 Tcl_IncrRefCount(*ppHook);
1787 }
1788 }
1789
drh9b1c62d2011-03-30 21:04:43 +00001790#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dan46c47d42011-03-01 18:42:07 +00001791 sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
drh9b1c62d2011-03-30 21:04:43 +00001792#endif
dan46c47d42011-03-01 18:42:07 +00001793 sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1794 sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1795 sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
1796}
1797
1798/*
drh75897232000-05-29 14:26:00 +00001799** The "sqlite" command below creates a new Tcl command for each
1800** connection it opens to an SQLite database. This routine is invoked
1801** whenever one of those connection-specific commands is executed
1802** in Tcl. For example, if you run Tcl code like this:
1803**
drh9bb575f2004-09-06 17:24:11 +00001804** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001805** db1 close
1806**
1807** The first command opens a connection to the "my_database" database
1808** and calls that connection "db1". The second command causes this
1809** subroutine to be invoked.
1810*/
mistachkin7617e4a2016-07-28 17:11:20 +00001811static int SQLITE_TCLAPI DbObjCmd(
1812 void *cd,
1813 Tcl_Interp *interp,
1814 int objc,
1815 Tcl_Obj *const*objv
1816){
drhbec3f402000-08-04 13:49:02 +00001817 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001818 int choice;
drh22fbcb82004-02-01 01:22:50 +00001819 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001820 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001821 "authorizer", "backup", "busy",
1822 "cache", "changes", "close",
1823 "collate", "collation_needed", "commit_hook",
1824 "complete", "copy", "enable_load_extension",
1825 "errorcode", "eval", "exists",
1826 "function", "incrblob", "interrupt",
drh833bf962010-04-28 14:42:19 +00001827 "last_insert_rowid", "nullvalue", "onecolumn",
drh304637c2011-03-18 16:47:27 +00001828 "preupdate", "profile", "progress",
1829 "rekey", "restore", "rollback_hook",
1830 "status", "timeout", "total_changes",
mistachkinb56660f2016-07-14 21:26:09 +00001831 "trace", "trace_v2", "transaction",
1832 "unlock_notify", "update_hook", "version",
1833 "wal_hook",
1834 0
drh6d313162000-09-21 13:01:35 +00001835 };
drh411995d2002-06-25 19:31:18 +00001836 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001837 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1838 DB_CACHE, DB_CHANGES, DB_CLOSE,
1839 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1840 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1841 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1842 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
drh833bf962010-04-28 14:42:19 +00001843 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
drh304637c2011-03-18 16:47:27 +00001844 DB_PREUPDATE, DB_PROFILE, DB_PROGRESS,
1845 DB_REKEY, DB_RESTORE, DB_ROLLBACK_HOOK,
1846 DB_STATUS, DB_TIMEOUT, DB_TOTAL_CHANGES,
mistachkinb56660f2016-07-14 21:26:09 +00001847 DB_TRACE, DB_TRACE_V2, DB_TRANSACTION,
1848 DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK, DB_VERSION,
1849 DB_WAL_HOOK,
drh6d313162000-09-21 13:01:35 +00001850 };
tpoindex1067fe12004-12-17 15:41:11 +00001851 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001852
1853 if( objc<2 ){
1854 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001855 return TCL_ERROR;
1856 }
drh411995d2002-06-25 19:31:18 +00001857 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001858 return TCL_ERROR;
1859 }
1860
drh411995d2002-06-25 19:31:18 +00001861 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001862
drhe22a3342003-04-22 20:30:37 +00001863 /* $db authorizer ?CALLBACK?
1864 **
1865 ** Invoke the given callback to authorize each SQL operation as it is
1866 ** compiled. 5 arguments are appended to the callback before it is
1867 ** invoked:
1868 **
1869 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1870 ** (2) First descriptive name (depends on authorization type)
1871 ** (3) Second descriptive name
1872 ** (4) Name of the database (ex: "main", "temp")
1873 ** (5) Name of trigger that is doing the access
1874 **
1875 ** The callback should return on of the following strings: SQLITE_OK,
1876 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1877 **
1878 ** If this method is invoked with no arguments, the current authorization
1879 ** callback string is returned.
1880 */
1881 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001882#ifdef SQLITE_OMIT_AUTHORIZATION
drha198f2b2014-02-07 19:26:13 +00001883 Tcl_AppendResult(interp, "authorization not available in this build",
1884 (char*)0);
drh1211de32004-07-26 12:24:22 +00001885 return TCL_ERROR;
1886#else
drhe22a3342003-04-22 20:30:37 +00001887 if( objc>3 ){
1888 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001889 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001890 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001891 if( pDb->zAuth ){
drha198f2b2014-02-07 19:26:13 +00001892 Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
drhe22a3342003-04-22 20:30:37 +00001893 }
1894 }else{
1895 char *zAuth;
1896 int len;
1897 if( pDb->zAuth ){
1898 Tcl_Free(pDb->zAuth);
1899 }
1900 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1901 if( zAuth && len>0 ){
1902 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001903 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001904 }else{
1905 pDb->zAuth = 0;
1906 }
drhe22a3342003-04-22 20:30:37 +00001907 if( pDb->zAuth ){
drh32c6a482014-09-11 13:44:52 +00001908 typedef int (*sqlite3_auth_cb)(
1909 void*,int,const char*,const char*,
1910 const char*,const char*);
drhe22a3342003-04-22 20:30:37 +00001911 pDb->interp = interp;
drh32c6a482014-09-11 13:44:52 +00001912 sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
drhe22a3342003-04-22 20:30:37 +00001913 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001914 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001915 }
drhe22a3342003-04-22 20:30:37 +00001916 }
drh1211de32004-07-26 12:24:22 +00001917#endif
drhe22a3342003-04-22 20:30:37 +00001918 break;
1919 }
1920
drhdc2c4912009-02-04 22:46:47 +00001921 /* $db backup ?DATABASE? FILENAME
1922 **
1923 ** Open or create a database file named FILENAME. Transfer the
1924 ** content of local database DATABASE (default: "main") into the
1925 ** FILENAME database.
1926 */
1927 case DB_BACKUP: {
1928 const char *zDestFile;
1929 const char *zSrcDb;
1930 sqlite3 *pDest;
1931 sqlite3_backup *pBackup;
1932
1933 if( objc==3 ){
1934 zSrcDb = "main";
1935 zDestFile = Tcl_GetString(objv[2]);
1936 }else if( objc==4 ){
1937 zSrcDb = Tcl_GetString(objv[2]);
1938 zDestFile = Tcl_GetString(objv[3]);
1939 }else{
1940 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1941 return TCL_ERROR;
1942 }
drh147ef392016-01-22 23:17:51 +00001943 rc = sqlite3_open_v2(zDestFile, &pDest,
1944 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00001945 if( rc!=SQLITE_OK ){
1946 Tcl_AppendResult(interp, "cannot open target database: ",
1947 sqlite3_errmsg(pDest), (char*)0);
1948 sqlite3_close(pDest);
1949 return TCL_ERROR;
1950 }
1951 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1952 if( pBackup==0 ){
1953 Tcl_AppendResult(interp, "backup failed: ",
1954 sqlite3_errmsg(pDest), (char*)0);
1955 sqlite3_close(pDest);
1956 return TCL_ERROR;
1957 }
1958 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1959 sqlite3_backup_finish(pBackup);
1960 if( rc==SQLITE_DONE ){
1961 rc = TCL_OK;
1962 }else{
1963 Tcl_AppendResult(interp, "backup failed: ",
1964 sqlite3_errmsg(pDest), (char*)0);
1965 rc = TCL_ERROR;
1966 }
1967 sqlite3_close(pDest);
1968 break;
1969 }
1970
drhbec3f402000-08-04 13:49:02 +00001971 /* $db busy ?CALLBACK?
1972 **
1973 ** Invoke the given callback if an SQL statement attempts to open
1974 ** a locked database file.
1975 */
drh6d313162000-09-21 13:01:35 +00001976 case DB_BUSY: {
1977 if( objc>3 ){
1978 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001979 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001980 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001981 if( pDb->zBusy ){
drha198f2b2014-02-07 19:26:13 +00001982 Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
drhbec3f402000-08-04 13:49:02 +00001983 }
1984 }else{
drh6d313162000-09-21 13:01:35 +00001985 char *zBusy;
1986 int len;
drhbec3f402000-08-04 13:49:02 +00001987 if( pDb->zBusy ){
1988 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001989 }
drh6d313162000-09-21 13:01:35 +00001990 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1991 if( zBusy && len>0 ){
1992 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001993 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001994 }else{
1995 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001996 }
1997 if( pDb->zBusy ){
1998 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001999 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00002000 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002001 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00002002 }
2003 }
drh6d313162000-09-21 13:01:35 +00002004 break;
2005 }
drhbec3f402000-08-04 13:49:02 +00002006
drhfb7e7652005-01-24 00:28:42 +00002007 /* $db cache flush
2008 ** $db cache size n
2009 **
2010 ** Flush the prepared statement cache, or set the maximum number of
2011 ** cached statements.
2012 */
2013 case DB_CACHE: {
2014 char *subCmd;
2015 int n;
2016
2017 if( objc<=2 ){
2018 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
2019 return TCL_ERROR;
2020 }
2021 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
2022 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
2023 if( objc!=3 ){
2024 Tcl_WrongNumArgs(interp, 2, objv, "flush");
2025 return TCL_ERROR;
2026 }else{
2027 flushStmtCache( pDb );
2028 }
2029 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
2030 if( objc!=4 ){
2031 Tcl_WrongNumArgs(interp, 2, objv, "size n");
2032 return TCL_ERROR;
2033 }else{
2034 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
mistachkinb56660f2016-07-14 21:26:09 +00002035 Tcl_AppendResult( interp, "cannot convert \"",
drha198f2b2014-02-07 19:26:13 +00002036 Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
drhfb7e7652005-01-24 00:28:42 +00002037 return TCL_ERROR;
2038 }else{
2039 if( n<0 ){
2040 flushStmtCache( pDb );
2041 n = 0;
2042 }else if( n>MAX_PREPARED_STMTS ){
2043 n = MAX_PREPARED_STMTS;
2044 }
2045 pDb->maxStmt = n;
2046 }
2047 }
2048 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002049 Tcl_AppendResult( interp, "bad option \"",
drha198f2b2014-02-07 19:26:13 +00002050 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
2051 (char*)0);
drhfb7e7652005-01-24 00:28:42 +00002052 return TCL_ERROR;
2053 }
2054 break;
2055 }
2056
danielk1977b28af712004-06-21 06:50:26 +00002057 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00002058 **
2059 ** Return the number of rows that were modified, inserted, or deleted by
mistachkinb56660f2016-07-14 21:26:09 +00002060 ** the most recent INSERT, UPDATE or DELETE statement, not including
danielk1977b28af712004-06-21 06:50:26 +00002061 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00002062 */
2063 case DB_CHANGES: {
2064 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00002065 if( objc!=2 ){
2066 Tcl_WrongNumArgs(interp, 2, objv, "");
2067 return TCL_ERROR;
2068 }
drhc8d30ac2002-04-12 10:08:59 +00002069 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00002070 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00002071 break;
2072 }
2073
drh75897232000-05-29 14:26:00 +00002074 /* $db close
2075 **
2076 ** Shutdown the database
2077 */
drh6d313162000-09-21 13:01:35 +00002078 case DB_CLOSE: {
2079 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
2080 break;
2081 }
drh75897232000-05-29 14:26:00 +00002082
drh0f14e2e2004-06-29 12:39:08 +00002083 /*
2084 ** $db collate NAME SCRIPT
2085 **
2086 ** Create a new SQL collation function called NAME. Whenever
2087 ** that function is called, invoke SCRIPT to evaluate the function.
2088 */
2089 case DB_COLLATE: {
2090 SqlCollate *pCollate;
2091 char *zName;
2092 char *zScript;
2093 int nScript;
2094 if( objc!=4 ){
2095 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
2096 return TCL_ERROR;
2097 }
2098 zName = Tcl_GetStringFromObj(objv[2], 0);
2099 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
2100 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
2101 if( pCollate==0 ) return TCL_ERROR;
2102 pCollate->interp = interp;
2103 pCollate->pNext = pDb->pCollate;
2104 pCollate->zScript = (char*)&pCollate[1];
2105 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00002106 memcpy(pCollate->zScript, zScript, nScript+1);
mistachkinb56660f2016-07-14 21:26:09 +00002107 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
drh0f14e2e2004-06-29 12:39:08 +00002108 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00002109 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00002110 return TCL_ERROR;
2111 }
2112 break;
2113 }
2114
2115 /*
2116 ** $db collation_needed SCRIPT
2117 **
2118 ** Create a new SQL collation function called NAME. Whenever
2119 ** that function is called, invoke SCRIPT to evaluate the function.
2120 */
2121 case DB_COLLATION_NEEDED: {
2122 if( objc!=3 ){
2123 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
2124 return TCL_ERROR;
2125 }
2126 if( pDb->pCollateNeeded ){
2127 Tcl_DecrRefCount(pDb->pCollateNeeded);
2128 }
2129 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
2130 Tcl_IncrRefCount(pDb->pCollateNeeded);
2131 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
2132 break;
2133 }
2134
drh19e2d372005-08-29 23:00:03 +00002135 /* $db commit_hook ?CALLBACK?
2136 **
2137 ** Invoke the given callback just before committing every SQL transaction.
2138 ** If the callback throws an exception or returns non-zero, then the
2139 ** transaction is aborted. If CALLBACK is an empty string, the callback
2140 ** is disabled.
2141 */
2142 case DB_COMMIT_HOOK: {
2143 if( objc>3 ){
2144 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2145 return TCL_ERROR;
2146 }else if( objc==2 ){
2147 if( pDb->zCommit ){
drha198f2b2014-02-07 19:26:13 +00002148 Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002149 }
2150 }else{
mistachkin6ef5e122014-01-24 17:03:55 +00002151 const char *zCommit;
drh19e2d372005-08-29 23:00:03 +00002152 int len;
2153 if( pDb->zCommit ){
2154 Tcl_Free(pDb->zCommit);
2155 }
2156 zCommit = Tcl_GetStringFromObj(objv[2], &len);
2157 if( zCommit && len>0 ){
2158 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002159 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00002160 }else{
2161 pDb->zCommit = 0;
2162 }
2163 if( pDb->zCommit ){
2164 pDb->interp = interp;
2165 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
2166 }else{
2167 sqlite3_commit_hook(pDb->db, 0, 0);
2168 }
2169 }
2170 break;
2171 }
2172
drh75897232000-05-29 14:26:00 +00002173 /* $db complete SQL
2174 **
2175 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
2176 ** additional lines of input are needed. This is similar to the
2177 ** built-in "info complete" command of Tcl.
2178 */
drh6d313162000-09-21 13:01:35 +00002179 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00002180#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00002181 Tcl_Obj *pResult;
2182 int isComplete;
2183 if( objc!=3 ){
2184 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00002185 return TCL_ERROR;
2186 }
danielk19776f8a5032004-05-10 10:34:51 +00002187 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00002188 pResult = Tcl_GetObjResult(interp);
2189 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00002190#endif
drh6d313162000-09-21 13:01:35 +00002191 break;
2192 }
drhdcd997e2003-01-31 17:21:49 +00002193
drh19e2d372005-08-29 23:00:03 +00002194 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2195 **
2196 ** Copy data into table from filename, optionally using SEPARATOR
2197 ** as column separators. If a column contains a null string, or the
2198 ** value of NULLINDICATOR, a NULL is inserted for the column.
2199 ** conflict-algorithm is one of the sqlite conflict algorithms:
2200 ** rollback, abort, fail, ignore, replace
2201 ** On success, return the number of lines processed, not necessarily same
2202 ** as 'db changes' due to conflict-algorithm selected.
2203 **
2204 ** This code is basically an implementation/enhancement of
2205 ** the sqlite3 shell.c ".import" command.
2206 **
2207 ** This command usage is equivalent to the sqlite2.x COPY statement,
2208 ** which imports file data into a table using the PostgreSQL COPY file format:
2209 ** $db copy $conflit_algo $table_name $filename \t \\N
2210 */
2211 case DB_COPY: {
2212 char *zTable; /* Insert data into this table */
2213 char *zFile; /* The file from which to extract data */
2214 char *zConflict; /* The conflict algorithm to use */
2215 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00002216 int nCol; /* Number of columns in the table */
2217 int nByte; /* Number of bytes in an SQL string */
2218 int i, j; /* Loop counters */
2219 int nSep; /* Number of bytes in zSep[] */
2220 int nNull; /* Number of bytes in zNull[] */
2221 char *zSql; /* An SQL statement */
2222 char *zLine; /* A single line of input from the file */
2223 char **azCol; /* zLine[] broken up into columns */
mistachkin6ef5e122014-01-24 17:03:55 +00002224 const char *zCommit; /* How to commit changes */
drh19e2d372005-08-29 23:00:03 +00002225 FILE *in; /* The input file */
2226 int lineno = 0; /* Line number of input file */
2227 char zLineNum[80]; /* Line number print buffer */
2228 Tcl_Obj *pResult; /* interp result */
2229
mistachkin6ef5e122014-01-24 17:03:55 +00002230 const char *zSep;
2231 const char *zNull;
drh19e2d372005-08-29 23:00:03 +00002232 if( objc<5 || objc>7 ){
mistachkinb56660f2016-07-14 21:26:09 +00002233 Tcl_WrongNumArgs(interp, 2, objv,
drh19e2d372005-08-29 23:00:03 +00002234 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2235 return TCL_ERROR;
2236 }
2237 if( objc>=6 ){
2238 zSep = Tcl_GetStringFromObj(objv[5], 0);
2239 }else{
2240 zSep = "\t";
2241 }
2242 if( objc>=7 ){
2243 zNull = Tcl_GetStringFromObj(objv[6], 0);
2244 }else{
2245 zNull = "";
2246 }
2247 zConflict = Tcl_GetStringFromObj(objv[2], 0);
2248 zTable = Tcl_GetStringFromObj(objv[3], 0);
2249 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00002250 nSep = strlen30(zSep);
2251 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00002252 if( nSep==0 ){
drha198f2b2014-02-07 19:26:13 +00002253 Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2254 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002255 return TCL_ERROR;
2256 }
drh3e59c012008-09-23 10:12:13 +00002257 if(strcmp(zConflict, "rollback") != 0 &&
2258 strcmp(zConflict, "abort" ) != 0 &&
2259 strcmp(zConflict, "fail" ) != 0 &&
2260 strcmp(zConflict, "ignore" ) != 0 &&
2261 strcmp(zConflict, "replace" ) != 0 ) {
mistachkinb56660f2016-07-14 21:26:09 +00002262 Tcl_AppendResult(interp, "Error: \"", zConflict,
drh19e2d372005-08-29 23:00:03 +00002263 "\", conflict-algorithm must be one of: rollback, "
drha198f2b2014-02-07 19:26:13 +00002264 "abort, fail, ignore, or replace", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002265 return TCL_ERROR;
2266 }
2267 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2268 if( zSql==0 ){
drha198f2b2014-02-07 19:26:13 +00002269 Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002270 return TCL_ERROR;
2271 }
drh4f21c4a2008-12-10 22:15:00 +00002272 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00002273 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002274 sqlite3_free(zSql);
2275 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002276 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002277 nCol = 0;
2278 }else{
2279 nCol = sqlite3_column_count(pStmt);
2280 }
2281 sqlite3_finalize(pStmt);
2282 if( nCol==0 ) {
2283 return TCL_ERROR;
2284 }
2285 zSql = malloc( nByte + 50 + nCol*2 );
2286 if( zSql==0 ) {
drha198f2b2014-02-07 19:26:13 +00002287 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh19e2d372005-08-29 23:00:03 +00002288 return TCL_ERROR;
2289 }
2290 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2291 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00002292 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00002293 for(i=1; i<nCol; i++){
2294 zSql[j++] = ',';
2295 zSql[j++] = '?';
2296 }
2297 zSql[j++] = ')';
2298 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00002299 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00002300 free(zSql);
2301 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002302 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002303 sqlite3_finalize(pStmt);
2304 return TCL_ERROR;
2305 }
2306 in = fopen(zFile, "rb");
2307 if( in==0 ){
2308 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2309 sqlite3_finalize(pStmt);
2310 return TCL_ERROR;
2311 }
2312 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2313 if( azCol==0 ) {
drha198f2b2014-02-07 19:26:13 +00002314 Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
drh43617e92006-03-06 20:55:46 +00002315 fclose(in);
drh19e2d372005-08-29 23:00:03 +00002316 return TCL_ERROR;
2317 }
drh37527852006-03-16 16:19:56 +00002318 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002319 zCommit = "COMMIT";
2320 while( (zLine = local_getline(0, in))!=0 ){
2321 char *z;
drh19e2d372005-08-29 23:00:03 +00002322 lineno++;
2323 azCol[0] = zLine;
2324 for(i=0, z=zLine; *z; z++){
2325 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2326 *z = 0;
2327 i++;
2328 if( i<nCol ){
2329 azCol[i] = &z[nSep];
2330 z += nSep-1;
2331 }
2332 }
2333 }
2334 if( i+1!=nCol ){
2335 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00002336 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00002337 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00002338 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00002339 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00002340 "Error: %s line %d: expected %d columns of data but found %d",
2341 zFile, lineno, nCol, i+1);
drha198f2b2014-02-07 19:26:13 +00002342 Tcl_AppendResult(interp, zErr, (char*)0);
drhc1f44942006-05-10 14:39:13 +00002343 free(zErr);
2344 }
drh19e2d372005-08-29 23:00:03 +00002345 zCommit = "ROLLBACK";
2346 break;
2347 }
2348 for(i=0; i<nCol; i++){
2349 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00002350 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
mistachkinb56660f2016-07-14 21:26:09 +00002351 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00002352 ){
drh19e2d372005-08-29 23:00:03 +00002353 sqlite3_bind_null(pStmt, i+1);
2354 }else{
2355 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2356 }
2357 }
2358 sqlite3_step(pStmt);
2359 rc = sqlite3_reset(pStmt);
2360 free(zLine);
2361 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00002362 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
drh19e2d372005-08-29 23:00:03 +00002363 zCommit = "ROLLBACK";
2364 break;
2365 }
2366 }
2367 free(azCol);
2368 fclose(in);
2369 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00002370 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00002371
2372 if( zCommit[0] == 'C' ){
2373 /* success, set result as number of lines processed */
2374 pResult = Tcl_GetObjResult(interp);
2375 Tcl_SetIntObj(pResult, lineno);
2376 rc = TCL_OK;
2377 }else{
2378 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00002379 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drha198f2b2014-02-07 19:26:13 +00002380 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2381 (char*)0);
drh19e2d372005-08-29 23:00:03 +00002382 rc = TCL_ERROR;
2383 }
2384 break;
2385 }
2386
drhdcd997e2003-01-31 17:21:49 +00002387 /*
drh41449052006-07-06 17:08:48 +00002388 ** $db enable_load_extension BOOLEAN
2389 **
2390 ** Turn the extension loading feature on or off. It if off by
2391 ** default.
2392 */
2393 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00002394#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00002395 int onoff;
2396 if( objc!=3 ){
2397 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2398 return TCL_ERROR;
2399 }
2400 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2401 return TCL_ERROR;
2402 }
2403 sqlite3_enable_load_extension(pDb->db, onoff);
2404 break;
drhf533acc2006-12-19 18:57:11 +00002405#else
2406 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
drha198f2b2014-02-07 19:26:13 +00002407 (char*)0);
drhf533acc2006-12-19 18:57:11 +00002408 return TCL_ERROR;
2409#endif
drh41449052006-07-06 17:08:48 +00002410 }
2411
2412 /*
drhdcd997e2003-01-31 17:21:49 +00002413 ** $db errorcode
2414 **
2415 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00002416 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00002417 */
2418 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00002419 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00002420 break;
2421 }
dan4a4c11a2009-10-06 14:59:02 +00002422
2423 /*
2424 ** $db exists $sql
2425 ** $db onecolumn $sql
2426 **
2427 ** The onecolumn method is the equivalent of:
2428 ** lindex [$db eval $sql] 0
2429 */
mistachkinb56660f2016-07-14 21:26:09 +00002430 case DB_EXISTS:
dan4a4c11a2009-10-06 14:59:02 +00002431 case DB_ONECOLUMN: {
drhedc40242016-06-13 12:34:38 +00002432 Tcl_Obj *pResult = 0;
dan4a4c11a2009-10-06 14:59:02 +00002433 DbEvalContext sEval;
2434 if( objc!=3 ){
2435 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2436 return TCL_ERROR;
2437 }
2438
2439 dbEvalInit(&sEval, pDb, objv[2], 0);
2440 rc = dbEvalStep(&sEval);
2441 if( choice==DB_ONECOLUMN ){
2442 if( rc==TCL_OK ){
drhedc40242016-06-13 12:34:38 +00002443 pResult = dbEvalColumnValue(&sEval, 0);
dand5f12cd2011-08-18 17:47:57 +00002444 }else if( rc==TCL_BREAK ){
2445 Tcl_ResetResult(interp);
dan4a4c11a2009-10-06 14:59:02 +00002446 }
2447 }else if( rc==TCL_BREAK || rc==TCL_OK ){
drhedc40242016-06-13 12:34:38 +00002448 pResult = Tcl_NewBooleanObj(rc==TCL_OK);
dan4a4c11a2009-10-06 14:59:02 +00002449 }
2450 dbEvalFinalize(&sEval);
drhedc40242016-06-13 12:34:38 +00002451 if( pResult ) Tcl_SetObjResult(interp, pResult);
dan4a4c11a2009-10-06 14:59:02 +00002452
2453 if( rc==TCL_BREAK ){
2454 rc = TCL_OK;
2455 }
2456 break;
2457 }
mistachkinb56660f2016-07-14 21:26:09 +00002458
drh75897232000-05-29 14:26:00 +00002459 /*
drh895d7472004-08-20 16:02:39 +00002460 ** $db eval $sql ?array? ?{ ...code... }?
drh75897232000-05-29 14:26:00 +00002461 **
2462 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00002463 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00002464 ** If "array" and "code" are omitted, then no callback is every invoked.
2465 ** If "array" is an empty string, then the values are placed in variables
2466 ** that have the same name as the fields extracted by the query.
2467 */
dan4a4c11a2009-10-06 14:59:02 +00002468 case DB_EVAL: {
2469 if( objc<3 || objc>5 ){
2470 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2471 return TCL_ERROR;
danielk197730ccda12004-05-27 12:11:31 +00002472 }
dan4a4c11a2009-10-06 14:59:02 +00002473
drh92febd92004-08-20 18:34:20 +00002474 if( objc==3 ){
dan4a4c11a2009-10-06 14:59:02 +00002475 DbEvalContext sEval;
2476 Tcl_Obj *pRet = Tcl_NewObj();
2477 Tcl_IncrRefCount(pRet);
2478 dbEvalInit(&sEval, pDb, objv[2], 0);
2479 while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2480 int i;
2481 int nCol;
2482 dbEvalRowInfo(&sEval, &nCol, 0);
drh92febd92004-08-20 18:34:20 +00002483 for(i=0; i<nCol; i++){
dan4a4c11a2009-10-06 14:59:02 +00002484 Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
danielk197730ccda12004-05-27 12:11:31 +00002485 }
2486 }
dan4a4c11a2009-10-06 14:59:02 +00002487 dbEvalFinalize(&sEval);
drh90b6bb12004-09-13 13:16:31 +00002488 if( rc==TCL_BREAK ){
dan4a4c11a2009-10-06 14:59:02 +00002489 Tcl_SetObjResult(interp, pRet);
drh90b6bb12004-09-13 13:16:31 +00002490 rc = TCL_OK;
2491 }
drh1807ce32004-09-07 13:20:35 +00002492 Tcl_DecrRefCount(pRet);
dan4a4c11a2009-10-06 14:59:02 +00002493 }else{
mistachkin8e189222015-04-19 21:43:16 +00002494 ClientData cd2[2];
dan4a4c11a2009-10-06 14:59:02 +00002495 DbEvalContext *p;
2496 Tcl_Obj *pArray = 0;
2497 Tcl_Obj *pScript;
2498
2499 if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2500 pArray = objv[3];
2501 }
2502 pScript = objv[objc-1];
2503 Tcl_IncrRefCount(pScript);
mistachkinb56660f2016-07-14 21:26:09 +00002504
dan4a4c11a2009-10-06 14:59:02 +00002505 p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2506 dbEvalInit(p, pDb, objv[2], pArray);
2507
mistachkin8e189222015-04-19 21:43:16 +00002508 cd2[0] = (void *)p;
2509 cd2[1] = (void *)pScript;
2510 rc = DbEvalNextCmd(cd2, interp, TCL_OK);
danielk197730ccda12004-05-27 12:11:31 +00002511 }
danielk197730ccda12004-05-27 12:11:31 +00002512 break;
2513 }
drhbec3f402000-08-04 13:49:02 +00002514
2515 /*
dan3df30592015-03-13 08:31:54 +00002516 ** $db function NAME [-argcount N] [-deterministic] SCRIPT
drhcabb0812002-09-14 13:47:32 +00002517 **
2518 ** Create a new SQL function called NAME. Whenever that function is
2519 ** called, invoke SCRIPT to evaluate the function.
2520 */
2521 case DB_FUNCTION: {
dan3df30592015-03-13 08:31:54 +00002522 int flags = SQLITE_UTF8;
drhcabb0812002-09-14 13:47:32 +00002523 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00002524 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00002525 char *zName;
drhe3602be2008-09-09 12:31:33 +00002526 int nArg = -1;
dan3df30592015-03-13 08:31:54 +00002527 int i;
2528 if( objc<4 ){
2529 Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
2530 return TCL_ERROR;
2531 }
2532 for(i=3; i<(objc-1); i++){
2533 const char *z = Tcl_GetString(objv[i]);
drh4f21c4a2008-12-10 22:15:00 +00002534 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00002535 if( n>2 && strncmp(z, "-argcount",n)==0 ){
dan3df30592015-03-13 08:31:54 +00002536 if( i==(objc-2) ){
2537 Tcl_AppendResult(interp, "option requires an argument: ", z, 0);
2538 return TCL_ERROR;
2539 }
2540 if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002541 if( nArg<0 ){
2542 Tcl_AppendResult(interp, "number of arguments must be non-negative",
2543 (char*)0);
2544 return TCL_ERROR;
2545 }
dan3df30592015-03-13 08:31:54 +00002546 i++;
2547 }else
2548 if( n>2 && strncmp(z, "-deterministic",n)==0 ){
2549 flags |= SQLITE_DETERMINISTIC;
2550 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002551 Tcl_AppendResult(interp, "bad option \"", z,
dan3df30592015-03-13 08:31:54 +00002552 "\": must be -argcount or -deterministic", 0
2553 );
2554 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002555 }
drhcabb0812002-09-14 13:47:32 +00002556 }
dan3df30592015-03-13 08:31:54 +00002557
2558 pScript = objv[objc-1];
drhcabb0812002-09-14 13:47:32 +00002559 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002560 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002561 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002562 if( pFunc->pScript ){
2563 Tcl_DecrRefCount(pFunc->pScript);
2564 }
2565 pFunc->pScript = pScript;
2566 Tcl_IncrRefCount(pScript);
2567 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
dan3df30592015-03-13 08:31:54 +00002568 rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
danielk1977d8123362004-06-12 09:25:12 +00002569 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002570 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002571 rc = TCL_ERROR;
2572 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002573 }
drhcabb0812002-09-14 13:47:32 +00002574 break;
2575 }
2576
2577 /*
danielk19778cbadb02007-05-03 16:31:26 +00002578 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002579 */
2580 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002581#ifdef SQLITE_OMIT_INCRBLOB
drha198f2b2014-02-07 19:26:13 +00002582 Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
danielk197732a0d8b2007-05-04 19:03:02 +00002583 return TCL_ERROR;
2584#else
danielk19778cbadb02007-05-03 16:31:26 +00002585 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002586 const char *zDb = "main";
2587 const char *zTable;
2588 const char *zColumn;
drhb3f787f2012-09-29 14:45:54 +00002589 Tcl_WideInt iRow;
danielk1977b4e9af92007-05-01 17:49:49 +00002590
danielk19778cbadb02007-05-03 16:31:26 +00002591 /* Check for the -readonly option */
2592 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2593 isReadonly = 1;
2594 }
2595
2596 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2597 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002598 return TCL_ERROR;
2599 }
2600
danielk19778cbadb02007-05-03 16:31:26 +00002601 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002602 zDb = Tcl_GetString(objv[2]);
2603 }
2604 zTable = Tcl_GetString(objv[objc-3]);
2605 zColumn = Tcl_GetString(objv[objc-2]);
2606 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2607
2608 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002609 rc = createIncrblobChannel(
danedf5b162014-08-19 09:15:41 +00002610 interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
danielk19778cbadb02007-05-03 16:31:26 +00002611 );
danielk1977b4e9af92007-05-01 17:49:49 +00002612 }
danielk197732a0d8b2007-05-04 19:03:02 +00002613#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002614 break;
2615 }
2616
2617 /*
drhf11bded2006-07-17 00:02:44 +00002618 ** $db interrupt
2619 **
2620 ** Interrupt the execution of the inner-most SQL interpreter. This
2621 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2622 */
2623 case DB_INTERRUPT: {
2624 sqlite3_interrupt(pDb->db);
2625 break;
2626 }
2627
2628 /*
drh19e2d372005-08-29 23:00:03 +00002629 ** $db nullvalue ?STRING?
2630 **
2631 ** Change text used when a NULL comes back from the database. If ?STRING?
2632 ** is not present, then the current string used for NULL is returned.
2633 ** If STRING is present, then STRING is returned.
2634 **
2635 */
2636 case DB_NULLVALUE: {
2637 if( objc!=2 && objc!=3 ){
2638 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2639 return TCL_ERROR;
2640 }
2641 if( objc==3 ){
2642 int len;
2643 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2644 if( pDb->zNull ){
2645 Tcl_Free(pDb->zNull);
2646 }
2647 if( zNull && len>0 ){
2648 pDb->zNull = Tcl_Alloc( len + 1 );
drh7fd33922011-06-20 19:00:30 +00002649 memcpy(pDb->zNull, zNull, len);
drh19e2d372005-08-29 23:00:03 +00002650 pDb->zNull[len] = '\0';
2651 }else{
2652 pDb->zNull = 0;
2653 }
2654 }
drhc45e6712012-10-03 11:02:33 +00002655 Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
drh19e2d372005-08-29 23:00:03 +00002656 break;
2657 }
2658
2659 /*
mistachkinb56660f2016-07-14 21:26:09 +00002660 ** $db last_insert_rowid
drhaf9ff332002-01-16 21:00:27 +00002661 **
2662 ** Return an integer which is the ROWID for the most recent insert.
2663 */
2664 case DB_LAST_INSERT_ROWID: {
2665 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002666 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002667 if( objc!=2 ){
2668 Tcl_WrongNumArgs(interp, 2, objv, "");
2669 return TCL_ERROR;
2670 }
danielk19776f8a5032004-05-10 10:34:51 +00002671 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002672 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002673 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002674 break;
2675 }
2676
2677 /*
dan4a4c11a2009-10-06 14:59:02 +00002678 ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
drh5d9d7572003-08-19 14:31:01 +00002679 */
drh1807ce32004-09-07 13:20:35 +00002680
2681 /* $db progress ?N CALLBACK?
mistachkinb56660f2016-07-14 21:26:09 +00002682 **
drh1807ce32004-09-07 13:20:35 +00002683 ** Invoke the given callback every N virtual machine opcodes while executing
2684 ** queries.
2685 */
2686 case DB_PROGRESS: {
2687 if( objc==2 ){
2688 if( pDb->zProgress ){
drha198f2b2014-02-07 19:26:13 +00002689 Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
drh1807ce32004-09-07 13:20:35 +00002690 }
2691 }else if( objc==4 ){
2692 char *zProgress;
2693 int len;
2694 int N;
2695 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002696 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002697 };
2698 if( pDb->zProgress ){
2699 Tcl_Free(pDb->zProgress);
2700 }
2701 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2702 if( zProgress && len>0 ){
2703 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002704 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002705 }else{
2706 pDb->zProgress = 0;
2707 }
2708#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2709 if( pDb->zProgress ){
2710 pDb->interp = interp;
2711 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2712 }else{
2713 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2714 }
2715#endif
2716 }else{
2717 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002718 return TCL_ERROR;
2719 }
drh5d9d7572003-08-19 14:31:01 +00002720 break;
2721 }
2722
drh19e2d372005-08-29 23:00:03 +00002723 /* $db profile ?CALLBACK?
2724 **
2725 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2726 ** that has run. The text of the SQL and the amount of elapse time are
2727 ** appended to CALLBACK before the script is run.
2728 */
2729 case DB_PROFILE: {
2730 if( objc>3 ){
2731 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2732 return TCL_ERROR;
2733 }else if( objc==2 ){
2734 if( pDb->zProfile ){
drha198f2b2014-02-07 19:26:13 +00002735 Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
drh19e2d372005-08-29 23:00:03 +00002736 }
2737 }else{
2738 char *zProfile;
2739 int len;
2740 if( pDb->zProfile ){
2741 Tcl_Free(pDb->zProfile);
2742 }
2743 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2744 if( zProfile && len>0 ){
2745 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002746 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002747 }else{
2748 pDb->zProfile = 0;
2749 }
shanehbb201342011-02-09 19:55:20 +00002750#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh19e2d372005-08-29 23:00:03 +00002751 if( pDb->zProfile ){
2752 pDb->interp = interp;
2753 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2754 }else{
2755 sqlite3_profile(pDb->db, 0, 0);
2756 }
2757#endif
2758 }
2759 break;
2760 }
2761
drh5d9d7572003-08-19 14:31:01 +00002762 /*
drh22fbcb82004-02-01 01:22:50 +00002763 ** $db rekey KEY
2764 **
2765 ** Change the encryption key on the currently open database.
2766 */
2767 case DB_REKEY: {
drh32f57d42016-03-16 01:03:10 +00002768#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh22fbcb82004-02-01 01:22:50 +00002769 int nKey;
2770 void *pKey;
drhb07028f2011-10-14 21:49:18 +00002771#endif
drh22fbcb82004-02-01 01:22:50 +00002772 if( objc!=3 ){
2773 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2774 return TCL_ERROR;
2775 }
drh32f57d42016-03-16 01:03:10 +00002776#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00002777 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh2011d5f2004-07-22 02:40:37 +00002778 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002779 if( rc ){
drha198f2b2014-02-07 19:26:13 +00002780 Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
drh22fbcb82004-02-01 01:22:50 +00002781 rc = TCL_ERROR;
2782 }
2783#endif
2784 break;
2785 }
2786
drhdc2c4912009-02-04 22:46:47 +00002787 /* $db restore ?DATABASE? FILENAME
2788 **
mistachkinb56660f2016-07-14 21:26:09 +00002789 ** Open a database file named FILENAME. Transfer the content
drhdc2c4912009-02-04 22:46:47 +00002790 ** of FILENAME into the local database DATABASE (default: "main").
2791 */
2792 case DB_RESTORE: {
2793 const char *zSrcFile;
2794 const char *zDestDb;
2795 sqlite3 *pSrc;
2796 sqlite3_backup *pBackup;
2797 int nTimeout = 0;
2798
2799 if( objc==3 ){
2800 zDestDb = "main";
2801 zSrcFile = Tcl_GetString(objv[2]);
2802 }else if( objc==4 ){
2803 zDestDb = Tcl_GetString(objv[2]);
2804 zSrcFile = Tcl_GetString(objv[3]);
2805 }else{
2806 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2807 return TCL_ERROR;
2808 }
drh147ef392016-01-22 23:17:51 +00002809 rc = sqlite3_open_v2(zSrcFile, &pSrc,
2810 SQLITE_OPEN_READONLY | pDb->openFlags, 0);
drhdc2c4912009-02-04 22:46:47 +00002811 if( rc!=SQLITE_OK ){
2812 Tcl_AppendResult(interp, "cannot open source database: ",
2813 sqlite3_errmsg(pSrc), (char*)0);
2814 sqlite3_close(pSrc);
2815 return TCL_ERROR;
2816 }
2817 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2818 if( pBackup==0 ){
2819 Tcl_AppendResult(interp, "restore failed: ",
2820 sqlite3_errmsg(pDb->db), (char*)0);
2821 sqlite3_close(pSrc);
2822 return TCL_ERROR;
2823 }
2824 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2825 || rc==SQLITE_BUSY ){
2826 if( rc==SQLITE_BUSY ){
2827 if( nTimeout++ >= 3 ) break;
2828 sqlite3_sleep(100);
2829 }
2830 }
2831 sqlite3_backup_finish(pBackup);
2832 if( rc==SQLITE_DONE ){
2833 rc = TCL_OK;
2834 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2835 Tcl_AppendResult(interp, "restore failed: source database busy",
2836 (char*)0);
2837 rc = TCL_ERROR;
2838 }else{
2839 Tcl_AppendResult(interp, "restore failed: ",
2840 sqlite3_errmsg(pDb->db), (char*)0);
2841 rc = TCL_ERROR;
2842 }
2843 sqlite3_close(pSrc);
2844 break;
2845 }
2846
drh22fbcb82004-02-01 01:22:50 +00002847 /*
drh3c379b02010-04-07 19:31:59 +00002848 ** $db status (step|sort|autoindex)
drhd1d38482008-10-07 23:46:38 +00002849 **
mistachkinb56660f2016-07-14 21:26:09 +00002850 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
drhd1d38482008-10-07 23:46:38 +00002851 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2852 */
2853 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002854 int v;
2855 const char *zOp;
2856 if( objc!=3 ){
drh1c320a42010-08-01 22:41:32 +00002857 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
drhd1d38482008-10-07 23:46:38 +00002858 return TCL_ERROR;
2859 }
2860 zOp = Tcl_GetString(objv[2]);
2861 if( strcmp(zOp, "step")==0 ){
2862 v = pDb->nStep;
2863 }else if( strcmp(zOp, "sort")==0 ){
2864 v = pDb->nSort;
drh3c379b02010-04-07 19:31:59 +00002865 }else if( strcmp(zOp, "autoindex")==0 ){
2866 v = pDb->nIndex;
drhd1d38482008-10-07 23:46:38 +00002867 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002868 Tcl_AppendResult(interp,
2869 "bad argument: should be autoindex, step, or sort",
drhd1d38482008-10-07 23:46:38 +00002870 (char*)0);
2871 return TCL_ERROR;
2872 }
2873 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2874 break;
2875 }
mistachkinb56660f2016-07-14 21:26:09 +00002876
drhd1d38482008-10-07 23:46:38 +00002877 /*
drhbec3f402000-08-04 13:49:02 +00002878 ** $db timeout MILLESECONDS
2879 **
2880 ** Delay for the number of milliseconds specified when a file is locked.
2881 */
drh6d313162000-09-21 13:01:35 +00002882 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002883 int ms;
drh6d313162000-09-21 13:01:35 +00002884 if( objc!=3 ){
2885 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002886 return TCL_ERROR;
2887 }
drh6d313162000-09-21 13:01:35 +00002888 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002889 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002890 break;
drh75897232000-05-29 14:26:00 +00002891 }
mistachkinb56660f2016-07-14 21:26:09 +00002892
danielk197755c45f22005-04-03 23:54:43 +00002893 /*
drh0f14e2e2004-06-29 12:39:08 +00002894 ** $db total_changes
2895 **
mistachkinb56660f2016-07-14 21:26:09 +00002896 ** Return the number of rows that were modified, inserted, or deleted
drh0f14e2e2004-06-29 12:39:08 +00002897 ** since the database handle was created.
2898 */
2899 case DB_TOTAL_CHANGES: {
2900 Tcl_Obj *pResult;
2901 if( objc!=2 ){
2902 Tcl_WrongNumArgs(interp, 2, objv, "");
2903 return TCL_ERROR;
2904 }
2905 pResult = Tcl_GetObjResult(interp);
2906 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2907 break;
2908 }
2909
drhb5a20d32003-04-23 12:25:23 +00002910 /* $db trace ?CALLBACK?
2911 **
2912 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2913 ** that is executed. The text of the SQL is appended to CALLBACK before
2914 ** it is executed.
2915 */
2916 case DB_TRACE: {
2917 if( objc>3 ){
2918 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002919 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002920 }else if( objc==2 ){
2921 if( pDb->zTrace ){
drha198f2b2014-02-07 19:26:13 +00002922 Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
drhb5a20d32003-04-23 12:25:23 +00002923 }
2924 }else{
2925 char *zTrace;
2926 int len;
2927 if( pDb->zTrace ){
2928 Tcl_Free(pDb->zTrace);
2929 }
2930 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2931 if( zTrace && len>0 ){
2932 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002933 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002934 }else{
2935 pDb->zTrace = 0;
2936 }
drh087ec072016-07-25 00:05:56 +00002937#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) \
2938 && !defined(SQLITE_OMIT_DEPRECATED)
drhb5a20d32003-04-23 12:25:23 +00002939 if( pDb->zTrace ){
2940 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002941 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002942 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002943 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002944 }
drh19e2d372005-08-29 23:00:03 +00002945#endif
drhb5a20d32003-04-23 12:25:23 +00002946 }
2947 break;
2948 }
2949
mistachkinb56660f2016-07-14 21:26:09 +00002950 /* $db trace_v2 ?CALLBACK? ?MASK?
2951 **
2952 ** Make arrangements to invoke the CALLBACK routine for each trace event
2953 ** matching the mask that is generated. The parameters are appended to
2954 ** CALLBACK before it is executed.
2955 */
2956 case DB_TRACE_V2: {
2957 if( objc>4 ){
2958 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK? ?MASK?");
2959 return TCL_ERROR;
2960 }else if( objc==2 ){
2961 if( pDb->zTraceV2 ){
2962 Tcl_AppendResult(interp, pDb->zTraceV2, (char*)0);
2963 }
2964 }else{
mistachkinb56660f2016-07-14 21:26:09 +00002965 char *zTraceV2;
2966 int len;
mistachkinb52dcd82016-07-14 23:17:03 +00002967 Tcl_WideInt wMask = 0;
mistachkinb56660f2016-07-14 21:26:09 +00002968 if( objc==4 ){
mistachkinb52dcd82016-07-14 23:17:03 +00002969 static const char *TTYPE_strs[] = {
2970 "statement", "profile", "row", "close", 0
2971 };
2972 enum TTYPE_enum {
2973 TTYPE_STMT, TTYPE_PROFILE, TTYPE_ROW, TTYPE_CLOSE
2974 };
2975 int i;
2976 if( TCL_OK!=Tcl_ListObjLength(interp, objv[3], &len) ){
mistachkinb56660f2016-07-14 21:26:09 +00002977 return TCL_ERROR;
2978 }
mistachkinb52dcd82016-07-14 23:17:03 +00002979 for(i=0; i<len; i++){
2980 Tcl_Obj *pObj;
2981 int ttype;
2982 if( TCL_OK!=Tcl_ListObjIndex(interp, objv[3], i, &pObj) ){
2983 return TCL_ERROR;
2984 }
2985 if( Tcl_GetIndexFromObj(interp, pObj, TTYPE_strs, "trace type",
2986 0, &ttype)!=TCL_OK ){
2987 Tcl_WideInt wType;
2988 Tcl_Obj *pError = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
2989 Tcl_IncrRefCount(pError);
2990 if( TCL_OK==Tcl_GetWideIntFromObj(interp, pObj, &wType) ){
2991 Tcl_DecrRefCount(pError);
2992 wMask |= wType;
2993 }else{
2994 Tcl_SetObjResult(interp, pError);
2995 Tcl_DecrRefCount(pError);
2996 return TCL_ERROR;
2997 }
2998 }else{
2999 switch( (enum TTYPE_enum)ttype ){
3000 case TTYPE_STMT: wMask |= SQLITE_TRACE_STMT; break;
3001 case TTYPE_PROFILE: wMask |= SQLITE_TRACE_PROFILE; break;
3002 case TTYPE_ROW: wMask |= SQLITE_TRACE_ROW; break;
3003 case TTYPE_CLOSE: wMask |= SQLITE_TRACE_CLOSE; break;
3004 }
3005 }
3006 }
mistachkinb56660f2016-07-14 21:26:09 +00003007 }else{
mistachkinb52dcd82016-07-14 23:17:03 +00003008 wMask = SQLITE_TRACE_STMT; /* use the "legacy" default */
mistachkinb56660f2016-07-14 21:26:09 +00003009 }
3010 if( pDb->zTraceV2 ){
3011 Tcl_Free(pDb->zTraceV2);
3012 }
3013 zTraceV2 = Tcl_GetStringFromObj(objv[2], &len);
3014 if( zTraceV2 && len>0 ){
3015 pDb->zTraceV2 = Tcl_Alloc( len + 1 );
3016 memcpy(pDb->zTraceV2, zTraceV2, len+1);
3017 }else{
3018 pDb->zTraceV2 = 0;
3019 }
3020#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3021 if( pDb->zTraceV2 ){
3022 pDb->interp = interp;
3023 sqlite3_trace_v2(pDb->db, (unsigned)wMask, DbTraceV2Handler, pDb);
3024 }else{
3025 sqlite3_trace_v2(pDb->db, 0, 0, 0);
3026 }
3027#endif
3028 }
3029 break;
3030 }
3031
drh3d214232005-08-02 12:21:08 +00003032 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
3033 **
3034 ** Start a new transaction (if we are not already in the midst of a
3035 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
3036 ** completes, either commit the transaction or roll it back if SCRIPT
3037 ** throws an exception. Or if no new transation was started, do nothing.
3038 ** pass the exception on up the stack.
3039 **
3040 ** This command was inspired by Dave Thomas's talk on Ruby at the
3041 ** 2005 O'Reilly Open Source Convention (OSCON).
3042 */
3043 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00003044 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00003045 const char *zBegin = "SAVEPOINT _tcl_transaction";
drh3d214232005-08-02 12:21:08 +00003046 if( objc!=3 && objc!=4 ){
3047 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
3048 return TCL_ERROR;
3049 }
danielk1977cd38d522009-01-02 17:33:46 +00003050
dan4a4c11a2009-10-06 14:59:02 +00003051 if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00003052 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00003053 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00003054 };
3055 enum TTYPE_enum {
3056 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
3057 };
3058 int ttype;
drhb5555e72005-08-02 17:15:14 +00003059 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00003060 0, &ttype) ){
3061 return TCL_ERROR;
3062 }
3063 switch( (enum TTYPE_enum)ttype ){
3064 case TTYPE_DEFERRED: /* no-op */; break;
3065 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
3066 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
3067 }
drh3d214232005-08-02 12:21:08 +00003068 }
danielk1977cd38d522009-01-02 17:33:46 +00003069 pScript = objv[objc-1];
3070
dan4a4c11a2009-10-06 14:59:02 +00003071 /* Run the SQLite BEGIN command to open a transaction or savepoint. */
danielk1977cd38d522009-01-02 17:33:46 +00003072 pDb->disableAuth++;
3073 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
3074 pDb->disableAuth--;
3075 if( rc!=SQLITE_OK ){
drha198f2b2014-02-07 19:26:13 +00003076 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977cd38d522009-01-02 17:33:46 +00003077 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00003078 }
danielk1977cd38d522009-01-02 17:33:46 +00003079 pDb->nTransaction++;
danielk1977cd38d522009-01-02 17:33:46 +00003080
dan4a4c11a2009-10-06 14:59:02 +00003081 /* If using NRE, schedule a callback to invoke the script pScript, then
3082 ** a second callback to commit (or rollback) the transaction or savepoint
3083 ** opened above. If not using NRE, evaluate the script directly, then
mistachkinb56660f2016-07-14 21:26:09 +00003084 ** call function DbTransPostCmd() to commit (or rollback) the transaction
dan4a4c11a2009-10-06 14:59:02 +00003085 ** or savepoint. */
3086 if( DbUseNre() ){
3087 Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
drha47941f2013-12-20 18:57:44 +00003088 (void)Tcl_NREvalObj(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00003089 }else{
dan4a4c11a2009-10-06 14:59:02 +00003090 rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
drh3d214232005-08-02 12:21:08 +00003091 }
3092 break;
3093 }
3094
danielk197794eb6a12005-12-15 15:22:08 +00003095 /*
danielk1977404ca072009-03-16 13:19:36 +00003096 ** $db unlock_notify ?script?
3097 */
3098 case DB_UNLOCK_NOTIFY: {
3099#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
drha198f2b2014-02-07 19:26:13 +00003100 Tcl_AppendResult(interp, "unlock_notify not available in this build",
3101 (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00003102 rc = TCL_ERROR;
3103#else
3104 if( objc!=2 && objc!=3 ){
3105 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3106 rc = TCL_ERROR;
3107 }else{
3108 void (*xNotify)(void **, int) = 0;
3109 void *pNotifyArg = 0;
3110
3111 if( pDb->pUnlockNotify ){
3112 Tcl_DecrRefCount(pDb->pUnlockNotify);
3113 pDb->pUnlockNotify = 0;
3114 }
mistachkinb56660f2016-07-14 21:26:09 +00003115
danielk1977404ca072009-03-16 13:19:36 +00003116 if( objc==3 ){
3117 xNotify = DbUnlockNotify;
3118 pNotifyArg = (void *)pDb;
3119 pDb->pUnlockNotify = objv[2];
3120 Tcl_IncrRefCount(pDb->pUnlockNotify);
3121 }
mistachkinb56660f2016-07-14 21:26:09 +00003122
danielk1977404ca072009-03-16 13:19:36 +00003123 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
drha198f2b2014-02-07 19:26:13 +00003124 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
danielk1977404ca072009-03-16 13:19:36 +00003125 rc = TCL_ERROR;
3126 }
3127 }
3128#endif
3129 break;
3130 }
3131
drh304637c2011-03-18 16:47:27 +00003132 /*
3133 ** $db preupdate_hook count
3134 ** $db preupdate_hook hook ?SCRIPT?
3135 ** $db preupdate_hook new INDEX
3136 ** $db preupdate_hook old INDEX
3137 */
dan46c47d42011-03-01 18:42:07 +00003138 case DB_PREUPDATE: {
drh9b1c62d2011-03-30 21:04:43 +00003139#ifndef SQLITE_ENABLE_PREUPDATE_HOOK
3140 Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time");
3141 rc = TCL_ERROR;
3142#else
dan1e7a2d42011-03-22 18:45:29 +00003143 static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
dan46c47d42011-03-01 18:42:07 +00003144 enum DbPreupdateSubCmd {
dan1e7a2d42011-03-22 18:45:29 +00003145 PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
dan46c47d42011-03-01 18:42:07 +00003146 };
3147 int iSub;
3148
3149 if( objc<3 ){
3150 Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
3151 }
3152 if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
3153 return TCL_ERROR;
3154 }
3155
3156 switch( (enum DbPreupdateSubCmd)iSub ){
3157 case PRE_COUNT: {
3158 int nCol = sqlite3_preupdate_count(pDb->db);
3159 Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
3160 break;
3161 }
3162
3163 case PRE_HOOK: {
3164 if( objc>4 ){
3165 Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
3166 return TCL_ERROR;
3167 }
3168 DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
3169 break;
3170 }
3171
dan1e7a2d42011-03-22 18:45:29 +00003172 case PRE_DEPTH: {
3173 Tcl_Obj *pRet;
3174 if( objc!=3 ){
3175 Tcl_WrongNumArgs(interp, 3, objv, "");
3176 return TCL_ERROR;
3177 }
3178 pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
3179 Tcl_SetObjResult(interp, pRet);
3180 break;
3181 }
3182
dan37db03b2011-03-16 19:59:18 +00003183 case PRE_NEW:
dan46c47d42011-03-01 18:42:07 +00003184 case PRE_OLD: {
3185 int iIdx;
dan37db03b2011-03-16 19:59:18 +00003186 sqlite3_value *pValue;
dan46c47d42011-03-01 18:42:07 +00003187 if( objc!=4 ){
3188 Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
3189 return TCL_ERROR;
3190 }
3191 if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
3192 return TCL_ERROR;
3193 }
3194
dan37db03b2011-03-16 19:59:18 +00003195 if( iSub==PRE_OLD ){
dan46c47d42011-03-01 18:42:07 +00003196 rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
dan37db03b2011-03-16 19:59:18 +00003197 }else{
3198 assert( iSub==PRE_NEW );
3199 rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
dan46c47d42011-03-01 18:42:07 +00003200 }
3201
dan37db03b2011-03-16 19:59:18 +00003202 if( rc==SQLITE_OK ){
drh304637c2011-03-18 16:47:27 +00003203 Tcl_Obj *pObj;
3204 pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
dan37db03b2011-03-16 19:59:18 +00003205 Tcl_SetObjResult(interp, pObj);
3206 }else{
dan46c47d42011-03-01 18:42:07 +00003207 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
3208 return TCL_ERROR;
3209 }
3210 }
3211 }
drh9b1c62d2011-03-30 21:04:43 +00003212#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:07 +00003213 break;
3214 }
3215
danielk1977404ca072009-03-16 13:19:36 +00003216 /*
drh833bf962010-04-28 14:42:19 +00003217 ** $db wal_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003218 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00003219 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00003220 */
mistachkinb56660f2016-07-14 21:26:09 +00003221 case DB_WAL_HOOK:
3222 case DB_UPDATE_HOOK:
dan6566ebe2011-03-16 09:49:14 +00003223 case DB_ROLLBACK_HOOK: {
mistachkinb56660f2016-07-14 21:26:09 +00003224 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
danielk197771fd80b2005-12-16 06:54:01 +00003225 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3226 */
mistachkinb56660f2016-07-14 21:26:09 +00003227 Tcl_Obj **ppHook = 0;
dan46c47d42011-03-01 18:42:07 +00003228 if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
3229 if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
3230 if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
3231 if( objc>3 ){
danielk197794eb6a12005-12-15 15:22:08 +00003232 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3233 return TCL_ERROR;
3234 }
danielk197771fd80b2005-12-16 06:54:01 +00003235
dan46c47d42011-03-01 18:42:07 +00003236 DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00003237 break;
3238 }
3239
danielk19774397de52005-01-12 12:44:03 +00003240 /* $db version
3241 **
3242 ** Return the version string for this database.
3243 */
3244 case DB_VERSION: {
3245 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
3246 break;
3247 }
3248
tpoindex1067fe12004-12-17 15:41:11 +00003249
drh6d313162000-09-21 13:01:35 +00003250 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00003251 return rc;
drh75897232000-05-29 14:26:00 +00003252}
3253
drha2c8a952009-10-13 18:38:34 +00003254#if SQLITE_TCL_NRE
3255/*
3256** Adaptor that provides an objCmd interface to the NRE-enabled
3257** interface implementation.
3258*/
mistachkina121cc72016-07-28 18:06:52 +00003259static int SQLITE_TCLAPI DbObjCmdAdaptor(
drha2c8a952009-10-13 18:38:34 +00003260 void *cd,
3261 Tcl_Interp *interp,
3262 int objc,
3263 Tcl_Obj *const*objv
3264){
3265 return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
3266}
3267#endif /* SQLITE_TCL_NRE */
3268
drh75897232000-05-29 14:26:00 +00003269/*
drh3570ad92007-08-31 14:31:44 +00003270** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00003271** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00003272**
3273** This is the main Tcl command. When the "sqlite" Tcl command is
3274** invoked, this routine runs to process that command.
3275**
3276** The first argument, DBNAME, is an arbitrary name for a new
3277** database connection. This command creates a new command named
3278** DBNAME that is used to control that connection. The database
3279** connection is deleted when the DBNAME command is deleted.
3280**
drh3570ad92007-08-31 14:31:44 +00003281** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00003282**
drh75897232000-05-29 14:26:00 +00003283*/
mistachkin7617e4a2016-07-28 17:11:20 +00003284static int SQLITE_TCLAPI DbMain(
3285 void *cd,
3286 Tcl_Interp *interp,
3287 int objc,
3288 Tcl_Obj *const*objv
3289){
drhbec3f402000-08-04 13:49:02 +00003290 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00003291 const char *zArg;
drh75897232000-05-29 14:26:00 +00003292 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00003293 int i;
drh22fbcb82004-02-01 01:22:50 +00003294 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00003295 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00003296 int flags;
drh882e8e42006-08-24 02:42:27 +00003297 Tcl_DString translatedFilename;
drh32f57d42016-03-16 01:03:10 +00003298#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhb07028f2011-10-14 21:49:18 +00003299 void *pKey = 0;
3300 int nKey = 0;
3301#endif
mistachkin540ebf82012-09-10 07:29:29 +00003302 int rc;
drhd9da78a2009-03-24 15:08:09 +00003303
3304 /* In normal use, each TCL interpreter runs in a single thread. So
3305 ** by default, we can turn of mutexing on SQLite database connections.
3306 ** However, for testing purposes it is useful to have mutexes turned
3307 ** on. So, by default, mutexes default off. But if compiled with
3308 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3309 */
3310#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3311 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3312#else
3313 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3314#endif
3315
drh22fbcb82004-02-01 01:22:50 +00003316 if( objc==2 ){
3317 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00003318 if( strcmp(zArg,"-version")==0 ){
drha198f2b2014-02-07 19:26:13 +00003319 Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
drh647cb0e2002-11-04 19:32:25 +00003320 return TCL_OK;
3321 }
drh72bf6a32016-01-07 02:06:55 +00003322 if( strcmp(zArg,"-sourceid")==0 ){
3323 Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0);
3324 return TCL_OK;
3325 }
drh9eb9e262004-02-11 02:18:05 +00003326 if( strcmp(zArg,"-has-codec")==0 ){
drh32f57d42016-03-16 01:03:10 +00003327#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drha198f2b2014-02-07 19:26:13 +00003328 Tcl_AppendResult(interp,"1",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003329#else
drha198f2b2014-02-07 19:26:13 +00003330 Tcl_AppendResult(interp,"0",(char*)0);
drh22fbcb82004-02-01 01:22:50 +00003331#endif
3332 return TCL_OK;
3333 }
drhfbc3eab2001-04-06 16:13:42 +00003334 }
drh3570ad92007-08-31 14:31:44 +00003335 for(i=3; i+1<objc; i+=2){
3336 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00003337 if( strcmp(zArg,"-key")==0 ){
drh32f57d42016-03-16 01:03:10 +00003338#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh3570ad92007-08-31 14:31:44 +00003339 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
drhb07028f2011-10-14 21:49:18 +00003340#endif
drh3570ad92007-08-31 14:31:44 +00003341 }else if( strcmp(zArg, "-vfs")==0 ){
dan3c3dd7b2010-06-22 11:10:40 +00003342 zVfs = Tcl_GetString(objv[i+1]);
drh3570ad92007-08-31 14:31:44 +00003343 }else if( strcmp(zArg, "-readonly")==0 ){
3344 int b;
3345 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3346 if( b ){
drh33f4e022007-09-03 15:19:34 +00003347 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00003348 flags |= SQLITE_OPEN_READONLY;
3349 }else{
3350 flags &= ~SQLITE_OPEN_READONLY;
3351 flags |= SQLITE_OPEN_READWRITE;
3352 }
3353 }else if( strcmp(zArg, "-create")==0 ){
3354 int b;
3355 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00003356 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00003357 flags |= SQLITE_OPEN_CREATE;
3358 }else{
3359 flags &= ~SQLITE_OPEN_CREATE;
3360 }
danielk19779a6284c2008-07-10 17:52:49 +00003361 }else if( strcmp(zArg, "-nomutex")==0 ){
3362 int b;
3363 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3364 if( b ){
3365 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00003366 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00003367 }else{
3368 flags &= ~SQLITE_OPEN_NOMUTEX;
3369 }
danc431fd52011-06-27 16:55:50 +00003370 }else if( strcmp(zArg, "-fullmutex")==0 ){
drh039963a2008-09-03 00:43:15 +00003371 int b;
3372 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3373 if( b ){
3374 flags |= SQLITE_OPEN_FULLMUTEX;
3375 flags &= ~SQLITE_OPEN_NOMUTEX;
3376 }else{
3377 flags &= ~SQLITE_OPEN_FULLMUTEX;
3378 }
drhf12b3f62011-12-21 14:42:29 +00003379 }else if( strcmp(zArg, "-uri")==0 ){
3380 int b;
3381 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3382 if( b ){
3383 flags |= SQLITE_OPEN_URI;
3384 }else{
3385 flags &= ~SQLITE_OPEN_URI;
3386 }
drh3570ad92007-08-31 14:31:44 +00003387 }else{
3388 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3389 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00003390 }
3391 }
drh3570ad92007-08-31 14:31:44 +00003392 if( objc<3 || (objc&1)!=1 ){
mistachkinb56660f2016-07-14 21:26:09 +00003393 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00003394 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh68bd4aa2012-01-13 16:16:10 +00003395 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
drh32f57d42016-03-16 01:03:10 +00003396#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drh3570ad92007-08-31 14:31:44 +00003397 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00003398#endif
3399 );
drh75897232000-05-29 14:26:00 +00003400 return TCL_ERROR;
3401 }
drh75897232000-05-29 14:26:00 +00003402 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00003403 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00003404 if( p==0 ){
mistachkin6ef5e122014-01-24 17:03:55 +00003405 Tcl_SetResult(interp, (char *)"malloc failed", TCL_STATIC);
drhbec3f402000-08-04 13:49:02 +00003406 return TCL_ERROR;
3407 }
3408 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00003409 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00003410 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003411 rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00003412 Tcl_DStringFree(&translatedFilename);
mistachkin540ebf82012-09-10 07:29:29 +00003413 if( p->db ){
3414 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3415 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3416 sqlite3_close(p->db);
3417 p->db = 0;
3418 }
3419 }else{
mistachkin5dac8432012-09-11 02:00:25 +00003420 zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
danielk197780290862004-05-22 09:21:21 +00003421 }
drh32f57d42016-03-16 01:03:10 +00003422#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
drhf3a65f72007-08-22 20:18:21 +00003423 if( p->db ){
3424 sqlite3_key(p->db, pKey, nKey);
3425 }
drheb8ed702004-02-11 10:37:23 +00003426#endif
drhbec3f402000-08-04 13:49:02 +00003427 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00003428 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00003429 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00003430 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00003431 return TCL_ERROR;
3432 }
drhfb7e7652005-01-24 00:28:42 +00003433 p->maxStmt = NUM_PREPARED_STMTS;
drh147ef392016-01-22 23:17:51 +00003434 p->openFlags = flags & SQLITE_OPEN_URI;
drh5169bbc2006-08-24 14:59:45 +00003435 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00003436 zArg = Tcl_GetStringFromObj(objv[1], 0);
dan4a4c11a2009-10-06 14:59:02 +00003437 if( DbUseNre() ){
drha2c8a952009-10-13 18:38:34 +00003438 Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3439 (char*)p, DbDeleteCmd);
dan4a4c11a2009-10-06 14:59:02 +00003440 }else{
3441 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3442 }
drh75897232000-05-29 14:26:00 +00003443 return TCL_OK;
3444}
3445
3446/*
drh90ca9752001-09-28 17:47:14 +00003447** Provide a dummy Tcl_InitStubs if we are using this as a static
3448** library.
3449*/
3450#ifndef USE_TCL_STUBS
3451# undef Tcl_InitStubs
drh0e85ccf2013-06-03 12:34:46 +00003452# define Tcl_InitStubs(a,b,c) TCL_VERSION
drh90ca9752001-09-28 17:47:14 +00003453#endif
3454
3455/*
drh29bc4612005-10-05 10:40:15 +00003456** Make sure we have a PACKAGE_VERSION macro defined. This will be
3457** defined automatically by the TEA makefile. But other makefiles
3458** do not define it.
3459*/
3460#ifndef PACKAGE_VERSION
3461# define PACKAGE_VERSION SQLITE_VERSION
3462#endif
3463
3464/*
drh75897232000-05-29 14:26:00 +00003465** Initialize this module.
3466**
3467** This Tcl module contains only a single new Tcl command named "sqlite".
3468** (Hence there is no namespace. There is no point in using a namespace
3469** if the extension only supplies one new name!) The "sqlite" command is
3470** used to open a new SQLite database. See the DbMain() routine above
3471** for additional information.
drhb652f432010-08-26 16:46:57 +00003472**
3473** The EXTERN macros are required by TCL in order to work on windows.
drh75897232000-05-29 14:26:00 +00003474*/
drhb652f432010-08-26 16:46:57 +00003475EXTERN int Sqlite3_Init(Tcl_Interp *interp){
mistachkin27b2f052015-01-12 19:49:46 +00003476 int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
drh6dc8cbe2013-05-31 15:36:07 +00003477 if( rc==TCL_OK ){
3478 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh1cca0d22010-08-25 20:35:51 +00003479#ifndef SQLITE_3_SUFFIX_ONLY
drh6dc8cbe2013-05-31 15:36:07 +00003480 /* The "sqlite" alias is undocumented. It is here only to support
3481 ** legacy scripts. All new scripts should use only the "sqlite3"
3482 ** command. */
3483 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh4c0f1642010-08-25 19:39:19 +00003484#endif
drh6dc8cbe2013-05-31 15:36:07 +00003485 rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3486 }
3487 return rc;
drh90ca9752001-09-28 17:47:14 +00003488}
drhb652f432010-08-26 16:46:57 +00003489EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
drhb652f432010-08-26 16:46:57 +00003490EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3491EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00003492
drhd878cab2012-03-20 15:10:42 +00003493/* Because it accesses the file-system and uses persistent state, SQLite
drhe75a9eb2016-02-13 18:54:10 +00003494** is not considered appropriate for safe interpreters. Hence, we cause
3495** the _SafeInit() interfaces return TCL_ERROR.
drhd878cab2012-03-20 15:10:42 +00003496*/
drhe75a9eb2016-02-13 18:54:10 +00003497EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
3498EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
3499
3500
drh49766d62005-01-08 18:42:28 +00003501
3502#ifndef SQLITE_3_SUFFIX_ONLY
dana3e63c42010-08-20 12:33:59 +00003503int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3504int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
dana3e63c42010-08-20 12:33:59 +00003505int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3506int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00003507#endif
drh75897232000-05-29 14:26:00 +00003508
drh3e27c022004-07-23 00:01:38 +00003509#ifdef TCLSH
3510/*****************************************************************************
drh57a02272009-10-22 20:52:05 +00003511** All of the code that follows is used to build standalone TCL interpreters
3512** that are statically linked with SQLite. Enable these by compiling
3513** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard
3514** tclsh but with SQLite built in. An n of 2 generates the SQLite space
3515** analysis program.
drh75897232000-05-29 14:26:00 +00003516*/
drh348784e2000-05-29 20:41:49 +00003517
drh57a02272009-10-22 20:52:05 +00003518#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3519/*
3520 * This code implements the MD5 message-digest algorithm.
3521 * The algorithm is due to Ron Rivest. This code was
3522 * written by Colin Plumb in 1993, no copyright is claimed.
3523 * This code is in the public domain; do with it what you wish.
3524 *
3525 * Equivalent code is available from RSA Data Security, Inc.
3526 * This code has been tested against that, and is equivalent,
3527 * except that you don't need to include two pages of legalese
3528 * with every copy.
3529 *
3530 * To compute the message digest of a chunk of bytes, declare an
3531 * MD5Context structure, pass it to MD5Init, call MD5Update as
3532 * needed on buffers full of bytes, and then call MD5Final, which
3533 * will fill a supplied 16-byte array with the digest.
3534 */
3535
3536/*
3537 * If compiled on a machine that doesn't have a 32-bit integer,
3538 * you just set "uint32" to the appropriate datatype for an
3539 * unsigned 32-bit integer. For example:
3540 *
3541 * cc -Duint32='unsigned long' md5.c
3542 *
3543 */
3544#ifndef uint32
3545# define uint32 unsigned int
3546#endif
3547
3548struct MD5Context {
3549 int isInit;
3550 uint32 buf[4];
3551 uint32 bits[2];
3552 unsigned char in[64];
3553};
3554typedef struct MD5Context MD5Context;
3555
3556/*
3557 * Note: this code is harmless on little-endian machines.
3558 */
3559static void byteReverse (unsigned char *buf, unsigned longs){
3560 uint32 t;
3561 do {
3562 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3563 ((unsigned)buf[1]<<8 | buf[0]);
3564 *(uint32 *)buf = t;
3565 buf += 4;
3566 } while (--longs);
3567}
3568/* The four core functions - F1 is optimized somewhat */
3569
3570/* #define F1(x, y, z) (x & y | ~x & z) */
3571#define F1(x, y, z) (z ^ (x & (y ^ z)))
3572#define F2(x, y, z) F1(z, x, y)
3573#define F3(x, y, z) (x ^ y ^ z)
3574#define F4(x, y, z) (y ^ (x | ~z))
3575
3576/* This is the central step in the MD5 algorithm. */
3577#define MD5STEP(f, w, x, y, z, data, s) \
3578 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3579
3580/*
3581 * The core of the MD5 algorithm, this alters an existing MD5 hash to
3582 * reflect the addition of 16 longwords of new data. MD5Update blocks
3583 * the data and converts bytes into longwords for this routine.
3584 */
3585static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3586 register uint32 a, b, c, d;
3587
3588 a = buf[0];
3589 b = buf[1];
3590 c = buf[2];
3591 d = buf[3];
3592
3593 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
3594 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3595 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3596 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3597 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
3598 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3599 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3600 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3601 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
3602 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3603 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3604 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3605 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
3606 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3607 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3608 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3609
3610 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
3611 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
3612 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3613 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3614 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
3615 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
3616 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3617 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3618 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
3619 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
3620 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3621 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3622 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
3623 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
3624 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3625 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3626
3627 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
3628 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3629 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3630 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3631 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
3632 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3633 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3634 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3635 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
3636 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3637 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3638 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3639 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
3640 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3641 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3642 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3643
3644 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
3645 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3646 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3647 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3648 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
3649 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3650 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3651 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3652 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
3653 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3654 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3655 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3656 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
3657 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3658 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3659 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3660
3661 buf[0] += a;
3662 buf[1] += b;
3663 buf[2] += c;
3664 buf[3] += d;
3665}
3666
3667/*
3668 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3669 * initialization constants.
3670 */
3671static void MD5Init(MD5Context *ctx){
3672 ctx->isInit = 1;
3673 ctx->buf[0] = 0x67452301;
3674 ctx->buf[1] = 0xefcdab89;
3675 ctx->buf[2] = 0x98badcfe;
3676 ctx->buf[3] = 0x10325476;
3677 ctx->bits[0] = 0;
3678 ctx->bits[1] = 0;
3679}
3680
3681/*
3682 * Update context to reflect the concatenation of another buffer full
3683 * of bytes.
3684 */
mistachkinb56660f2016-07-14 21:26:09 +00003685static
drh57a02272009-10-22 20:52:05 +00003686void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3687 uint32 t;
3688
3689 /* Update bitcount */
3690
3691 t = ctx->bits[0];
3692 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3693 ctx->bits[1]++; /* Carry from low to high */
3694 ctx->bits[1] += len >> 29;
3695
3696 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
3697
3698 /* Handle any leading odd-sized chunks */
3699
3700 if ( t ) {
3701 unsigned char *p = (unsigned char *)ctx->in + t;
3702
3703 t = 64-t;
3704 if (len < t) {
3705 memcpy(p, buf, len);
3706 return;
3707 }
3708 memcpy(p, buf, t);
3709 byteReverse(ctx->in, 16);
3710 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3711 buf += t;
3712 len -= t;
3713 }
3714
3715 /* Process data in 64-byte chunks */
3716
3717 while (len >= 64) {
3718 memcpy(ctx->in, buf, 64);
3719 byteReverse(ctx->in, 16);
3720 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3721 buf += 64;
3722 len -= 64;
3723 }
3724
3725 /* Handle any remaining bytes of data. */
3726
3727 memcpy(ctx->in, buf, len);
3728}
3729
3730/*
mistachkinb56660f2016-07-14 21:26:09 +00003731 * Final wrapup - pad to 64-byte boundary with the bit pattern
drh57a02272009-10-22 20:52:05 +00003732 * 1 0* (64-bit count of bits processed, MSB-first)
3733 */
3734static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3735 unsigned count;
3736 unsigned char *p;
3737
3738 /* Compute number of bytes mod 64 */
3739 count = (ctx->bits[0] >> 3) & 0x3F;
3740
3741 /* Set the first char of padding to 0x80. This is safe since there is
3742 always at least one byte free */
3743 p = ctx->in + count;
3744 *p++ = 0x80;
3745
3746 /* Bytes of padding needed to make 64 bytes */
3747 count = 64 - 1 - count;
3748
3749 /* Pad out to 56 mod 64 */
3750 if (count < 8) {
3751 /* Two lots of padding: Pad the first block to 64 bytes */
3752 memset(p, 0, count);
3753 byteReverse(ctx->in, 16);
3754 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3755
3756 /* Now fill the next block with 56 bytes */
3757 memset(ctx->in, 0, 56);
3758 } else {
3759 /* Pad block to 56 bytes */
3760 memset(p, 0, count-8);
3761 }
3762 byteReverse(ctx->in, 14);
3763
3764 /* Append length in bits and transform */
drha47941f2013-12-20 18:57:44 +00003765 memcpy(ctx->in + 14*4, ctx->bits, 8);
drh57a02272009-10-22 20:52:05 +00003766
3767 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3768 byteReverse((unsigned char *)ctx->buf, 4);
3769 memcpy(digest, ctx->buf, 16);
drh57a02272009-10-22 20:52:05 +00003770}
3771
3772/*
3773** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3774*/
3775static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3776 static char const zEncode[] = "0123456789abcdef";
3777 int i, j;
3778
3779 for(j=i=0; i<16; i++){
3780 int a = digest[i];
3781 zBuf[j++] = zEncode[(a>>4)&0xf];
3782 zBuf[j++] = zEncode[a & 0xf];
3783 }
3784 zBuf[j] = 0;
3785}
3786
3787
3788/*
3789** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3790** each representing 16 bits of the digest and separated from each
3791** other by a "-" character.
3792*/
3793static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3794 int i, j;
3795 unsigned int x;
3796 for(i=j=0; i<16; i+=2){
3797 x = digest[i]*256 + digest[i+1];
3798 if( i>0 ) zDigest[j++] = '-';
drh05f6c672015-02-26 16:32:33 +00003799 sqlite3_snprintf(50-j, &zDigest[j], "%05u", x);
drh57a02272009-10-22 20:52:05 +00003800 j += 5;
3801 }
3802 zDigest[j] = 0;
3803}
3804
3805/*
3806** A TCL command for md5. The argument is the text to be hashed. The
mistachkinb56660f2016-07-14 21:26:09 +00003807** Result is the hash in base64.
drh57a02272009-10-22 20:52:05 +00003808*/
3809static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3810 MD5Context ctx;
3811 unsigned char digest[16];
3812 char zBuf[50];
3813 void (*converter)(unsigned char*, char*);
3814
3815 if( argc!=2 ){
mistachkinb56660f2016-07-14 21:26:09 +00003816 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
drha198f2b2014-02-07 19:26:13 +00003817 " TEXT\"", (char*)0);
drh57a02272009-10-22 20:52:05 +00003818 return TCL_ERROR;
3819 }
3820 MD5Init(&ctx);
3821 MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3822 MD5Final(digest, &ctx);
3823 converter = (void(*)(unsigned char*,char*))cd;
3824 converter(digest, zBuf);
3825 Tcl_AppendResult(interp, zBuf, (char*)0);
3826 return TCL_OK;
3827}
3828
3829/*
3830** A TCL command to take the md5 hash of a file. The argument is the
3831** name of the file.
3832*/
3833static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3834 FILE *in;
3835 MD5Context ctx;
3836 void (*converter)(unsigned char*, char*);
3837 unsigned char digest[16];
3838 char zBuf[10240];
3839
3840 if( argc!=2 ){
mistachkinb56660f2016-07-14 21:26:09 +00003841 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
drha198f2b2014-02-07 19:26:13 +00003842 " FILENAME\"", (char*)0);
drh57a02272009-10-22 20:52:05 +00003843 return TCL_ERROR;
3844 }
3845 in = fopen(argv[1],"rb");
3846 if( in==0 ){
mistachkinb56660f2016-07-14 21:26:09 +00003847 Tcl_AppendResult(interp,"unable to open file \"", argv[1],
drha198f2b2014-02-07 19:26:13 +00003848 "\" for reading", (char*)0);
drh57a02272009-10-22 20:52:05 +00003849 return TCL_ERROR;
3850 }
3851 MD5Init(&ctx);
3852 for(;;){
3853 int n;
drh83cc1392012-04-19 18:04:28 +00003854 n = (int)fread(zBuf, 1, sizeof(zBuf), in);
drh57a02272009-10-22 20:52:05 +00003855 if( n<=0 ) break;
3856 MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3857 }
3858 fclose(in);
3859 MD5Final(digest, &ctx);
3860 converter = (void(*)(unsigned char*,char*))cd;
3861 converter(digest, zBuf);
3862 Tcl_AppendResult(interp, zBuf, (char*)0);
3863 return TCL_OK;
3864}
3865
3866/*
3867** Register the four new TCL commands for generating MD5 checksums
3868** with the TCL interpreter.
3869*/
3870int Md5_Init(Tcl_Interp *interp){
3871 Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3872 MD5DigestToBase16, 0);
3873 Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3874 MD5DigestToBase10x8, 0);
3875 Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3876 MD5DigestToBase16, 0);
3877 Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3878 MD5DigestToBase10x8, 0);
3879 return TCL_OK;
3880}
3881#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3882
3883#if defined(SQLITE_TEST)
3884/*
3885** During testing, the special md5sum() aggregate function is available.
3886** inside SQLite. The following routines implement that function.
3887*/
3888static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3889 MD5Context *p;
3890 int i;
3891 if( argc<1 ) return;
3892 p = sqlite3_aggregate_context(context, sizeof(*p));
3893 if( p==0 ) return;
3894 if( !p->isInit ){
3895 MD5Init(p);
3896 }
3897 for(i=0; i<argc; i++){
3898 const char *zData = (char*)sqlite3_value_text(argv[i]);
3899 if( zData ){
drh83cc1392012-04-19 18:04:28 +00003900 MD5Update(p, (unsigned char*)zData, (int)strlen(zData));
drh57a02272009-10-22 20:52:05 +00003901 }
3902 }
3903}
3904static void md5finalize(sqlite3_context *context){
3905 MD5Context *p;
3906 unsigned char digest[16];
3907 char zBuf[33];
3908 p = sqlite3_aggregate_context(context, sizeof(*p));
3909 MD5Final(digest,p);
3910 MD5DigestToBase16(digest, zBuf);
3911 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3912}
3913int Md5_Register(sqlite3 *db){
mistachkinb56660f2016-07-14 21:26:09 +00003914 int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
drh57a02272009-10-22 20:52:05 +00003915 md5step, md5finalize);
3916 sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */
3917 return rc;
3918}
3919#endif /* defined(SQLITE_TEST) */
3920
3921
drh348784e2000-05-29 20:41:49 +00003922/*
drh3e27c022004-07-23 00:01:38 +00003923** If the macro TCLSH is one, then put in code this for the
3924** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00003925** standard input, or if a file is named on the command line
3926** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00003927*/
drh3e27c022004-07-23 00:01:38 +00003928#if TCLSH==1
dan0ae479d2011-09-21 16:43:07 +00003929static const char *tclsh_main_loop(void){
3930 static const char zMainloop[] =
3931 "set line {}\n"
3932 "while {![eof stdin]} {\n"
3933 "if {$line!=\"\"} {\n"
3934 "puts -nonewline \"> \"\n"
3935 "} else {\n"
3936 "puts -nonewline \"% \"\n"
drh348784e2000-05-29 20:41:49 +00003937 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003938 "flush stdout\n"
3939 "append line [gets stdin]\n"
3940 "if {[info complete $line]} {\n"
3941 "if {[catch {uplevel #0 $line} result]} {\n"
3942 "puts stderr \"Error: $result\"\n"
3943 "} elseif {$result!=\"\"} {\n"
3944 "puts $result\n"
3945 "}\n"
3946 "set line {}\n"
3947 "} else {\n"
3948 "append line \\n\n"
3949 "}\n"
drh348784e2000-05-29 20:41:49 +00003950 "}\n"
dan0ae479d2011-09-21 16:43:07 +00003951 ;
3952 return zMainloop;
3953}
drh3e27c022004-07-23 00:01:38 +00003954#endif
drh3a0f13f2010-07-12 16:47:48 +00003955#if TCLSH==2
dan0ae479d2011-09-21 16:43:07 +00003956static const char *tclsh_main_loop(void);
drh3a0f13f2010-07-12 16:47:48 +00003957#endif
drh3e27c022004-07-23 00:01:38 +00003958
danc1a60c52010-06-07 14:28:16 +00003959#ifdef SQLITE_TEST
3960static void init_all(Tcl_Interp *);
mistachkin7617e4a2016-07-28 17:11:20 +00003961static int SQLITE_TCLAPI init_all_cmd(
danc1a60c52010-06-07 14:28:16 +00003962 ClientData cd,
3963 Tcl_Interp *interp,
3964 int objc,
3965 Tcl_Obj *CONST objv[]
3966){
danielk19770a549072009-02-17 16:29:10 +00003967
danc1a60c52010-06-07 14:28:16 +00003968 Tcl_Interp *slave;
3969 if( objc!=2 ){
3970 Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3971 return TCL_ERROR;
3972 }
3973
3974 slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3975 if( !slave ){
3976 return TCL_ERROR;
3977 }
3978
3979 init_all(slave);
3980 return TCL_OK;
3981}
danc431fd52011-06-27 16:55:50 +00003982
3983/*
3984** Tclcmd: db_use_legacy_prepare DB BOOLEAN
3985**
3986** The first argument to this command must be a database command created by
3987** [sqlite3]. If the second argument is true, then the handle is configured
3988** to use the sqlite3_prepare_v2() function to prepare statements. If it
3989** is false, sqlite3_prepare().
3990*/
mistachkin7617e4a2016-07-28 17:11:20 +00003991static int SQLITE_TCLAPI db_use_legacy_prepare_cmd(
danc431fd52011-06-27 16:55:50 +00003992 ClientData cd,
3993 Tcl_Interp *interp,
3994 int objc,
3995 Tcl_Obj *CONST objv[]
3996){
3997 Tcl_CmdInfo cmdInfo;
3998 SqliteDb *pDb;
3999 int bPrepare;
4000
4001 if( objc!=3 ){
4002 Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
4003 return TCL_ERROR;
4004 }
4005
4006 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
4007 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
4008 return TCL_ERROR;
4009 }
4010 pDb = (SqliteDb*)cmdInfo.objClientData;
4011 if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
4012 return TCL_ERROR;
4013 }
4014
4015 pDb->bLegacyPrepare = bPrepare;
4016
4017 Tcl_ResetResult(interp);
4018 return TCL_OK;
4019}
dan04489b62014-10-31 20:11:32 +00004020
4021/*
4022** Tclcmd: db_last_stmt_ptr DB
4023**
4024** If the statement cache associated with database DB is not empty,
4025** return the text representation of the most recently used statement
4026** handle.
4027*/
mistachkin7617e4a2016-07-28 17:11:20 +00004028static int SQLITE_TCLAPI db_last_stmt_ptr(
dan04489b62014-10-31 20:11:32 +00004029 ClientData cd,
4030 Tcl_Interp *interp,
4031 int objc,
4032 Tcl_Obj *CONST objv[]
4033){
4034 extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
4035 Tcl_CmdInfo cmdInfo;
4036 SqliteDb *pDb;
4037 sqlite3_stmt *pStmt = 0;
4038 char zBuf[100];
4039
4040 if( objc!=2 ){
4041 Tcl_WrongNumArgs(interp, 1, objv, "DB");
4042 return TCL_ERROR;
4043 }
4044
4045 if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
4046 Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
4047 return TCL_ERROR;
4048 }
4049 pDb = (SqliteDb*)cmdInfo.objClientData;
4050
4051 if( pDb->stmtList ) pStmt = pDb->stmtList->pStmt;
4052 if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ){
4053 return TCL_ERROR;
4054 }
4055 Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
4056
4057 return TCL_OK;
4058}
drh1a4a6802015-05-04 18:31:09 +00004059#endif /* SQLITE_TEST */
4060
danc1a60c52010-06-07 14:28:16 +00004061/*
4062** Configure the interpreter passed as the first argument to have access
4063** to the commands and linked variables that make up:
4064**
mistachkinb56660f2016-07-14 21:26:09 +00004065** * the [sqlite3] extension itself,
danc1a60c52010-06-07 14:28:16 +00004066**
4067** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
4068**
4069** * If SQLITE_TEST is set, the various test interfaces used by the Tcl
4070** test suite.
4071*/
4072static void init_all(Tcl_Interp *interp){
drh38f82712004-06-18 17:10:16 +00004073 Sqlite3_Init(interp);
danc1a60c52010-06-07 14:28:16 +00004074
drh57a02272009-10-22 20:52:05 +00004075#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
4076 Md5_Init(interp);
4077#endif
danc1a60c52010-06-07 14:28:16 +00004078
drhd9b02572001-04-15 00:37:09 +00004079#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00004080 {
drh2f999a62007-08-15 19:16:43 +00004081 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00004082 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00004083 extern int Sqlitetest2_Init(Tcl_Interp*);
4084 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00004085 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00004086 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00004087 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00004088 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00004089 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00004090 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00004091 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00004092 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
danb391b942014-11-07 14:41:11 +00004093 extern int Sqlitetest_blob_Init(Tcl_Interp*);
dan0a7a9152010-04-07 07:57:38 +00004094 extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
drh984bfaa2008-03-19 16:08:53 +00004095 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00004096 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
dane1ab2192009-08-17 15:16:19 +00004097 extern int Sqlitetest_init_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00004098 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00004099 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00004100 extern int Sqlitetestschema_Init(Tcl_Interp*);
4101 extern int Sqlitetestsse_Init(Tcl_Interp*);
4102 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
dan9f5ff372013-01-11 09:58:54 +00004103 extern int Sqlitetestfs_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00004104 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00004105 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00004106 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00004107 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh522efc62009-11-10 17:24:37 +00004108 extern int Sqlitetestintarray_Init(Tcl_Interp*);
danc7991bd2010-05-05 19:04:59 +00004109 extern int Sqlitetestvfs_Init(Tcl_Interp *);
dan9508daa2010-08-28 18:58:00 +00004110 extern int Sqlitetestrtree_Init(Tcl_Interp*);
dan8cf35eb2010-09-01 11:40:05 +00004111 extern int Sqlitequota_Init(Tcl_Interp*);
shaneh8a922f72010-11-04 20:50:27 +00004112 extern int Sqlitemultiplex_Init(Tcl_Interp*);
dane336b002010-11-19 18:20:09 +00004113 extern int SqliteSuperlock_Init(Tcl_Interp*);
dan213ca0a2011-03-28 19:10:06 +00004114 extern int SqlitetestSyscall_Init(Tcl_Interp*);
drh9b1c62d2011-03-30 21:04:43 +00004115#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
dan4fccf432011-03-08 19:22:50 +00004116 extern int TestSession_Init(Tcl_Interp*);
4117#endif
dan89a89562014-12-01 20:05:00 +00004118 extern int Fts5tcl_Init(Tcl_Interp *);
drhcfb8f8d2015-07-23 20:44:49 +00004119 extern int SqliteRbu_Init(Tcl_Interp*);
dan8e4251b2016-03-01 18:07:43 +00004120 extern int Sqlitetesttcl_Init(Tcl_Interp*);
dan6764a702011-06-20 11:15:06 +00004121#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00004122 extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
4123#endif
4124
danb29010c2010-12-29 18:24:38 +00004125#ifdef SQLITE_ENABLE_ZIPVFS
4126 extern int Zipvfs_Init(Tcl_Interp*);
4127 Zipvfs_Init(interp);
4128#endif
4129
drh2f999a62007-08-15 19:16:43 +00004130 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00004131 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00004132 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00004133 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00004134 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00004135 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00004136 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00004137 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00004138 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00004139 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00004140 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00004141 Sqlitetest_autoext_Init(interp);
danb391b942014-11-07 14:41:11 +00004142 Sqlitetest_blob_Init(interp);
dan0a7a9152010-04-07 07:57:38 +00004143 Sqlitetest_demovfs_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00004144 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00004145 Sqlitetest_hexio_Init(interp);
dane1ab2192009-08-17 15:16:19 +00004146 Sqlitetest_init_Init(interp);
drh2f999a62007-08-15 19:16:43 +00004147 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00004148 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00004149 Sqlitetestschema_Init(interp);
4150 Sqlitetesttclvar_Init(interp);
dan9f5ff372013-01-11 09:58:54 +00004151 Sqlitetestfs_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00004152 SqlitetestThread_Init(interp);
mistachkin52b1dbb2016-07-28 14:37:04 +00004153 SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00004154 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00004155 Sqlitetestbackup_Init(interp);
drh522efc62009-11-10 17:24:37 +00004156 Sqlitetestintarray_Init(interp);
danc7991bd2010-05-05 19:04:59 +00004157 Sqlitetestvfs_Init(interp);
dan9508daa2010-08-28 18:58:00 +00004158 Sqlitetestrtree_Init(interp);
dan8cf35eb2010-09-01 11:40:05 +00004159 Sqlitequota_Init(interp);
shaneh8a922f72010-11-04 20:50:27 +00004160 Sqlitemultiplex_Init(interp);
dane336b002010-11-19 18:20:09 +00004161 SqliteSuperlock_Init(interp);
dan213ca0a2011-03-28 19:10:06 +00004162 SqlitetestSyscall_Init(interp);
drh9b1c62d2011-03-30 21:04:43 +00004163#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
dan4fccf432011-03-08 19:22:50 +00004164 TestSession_Init(interp);
4165#endif
dan89a89562014-12-01 20:05:00 +00004166 Fts5tcl_Init(interp);
drhcfb8f8d2015-07-23 20:44:49 +00004167 SqliteRbu_Init(interp);
dan8e4251b2016-03-01 18:07:43 +00004168 Sqlitetesttcl_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00004169
dan6764a702011-06-20 11:15:06 +00004170#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
dan99ebad92011-06-13 09:11:01 +00004171 Sqlitetestfts3_Init(interp);
4172#endif
drh2e66f0b2005-04-28 17:18:48 +00004173
danc431fd52011-06-27 16:55:50 +00004174 Tcl_CreateObjCommand(
4175 interp, "load_testfixture_extensions", init_all_cmd, 0, 0
4176 );
4177 Tcl_CreateObjCommand(
4178 interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
4179 );
dan04489b62014-10-31 20:11:32 +00004180 Tcl_CreateObjCommand(
4181 interp, "db_last_stmt_ptr", db_last_stmt_ptr, 0, 0
4182 );
danc1a60c52010-06-07 14:28:16 +00004183
drh3e27c022004-07-23 00:01:38 +00004184#ifdef SQLITE_SSE
drh348784e2000-05-29 20:41:49 +00004185 Sqlitetestsse_Init(interp);
4186#endif
4187 }
drh61212b62004-12-02 20:17:00 +00004188#endif
danc1a60c52010-06-07 14:28:16 +00004189}
4190
drhdb6bafa2015-01-09 21:54:58 +00004191/* Needed for the setrlimit() system call on unix */
4192#if defined(unix)
4193#include <sys/resource.h>
4194#endif
4195
danc1a60c52010-06-07 14:28:16 +00004196#define TCLSH_MAIN main /* Needed to fake out mktclapp */
mistachkin69def7f2016-07-28 04:14:37 +00004197int SQLITE_CDECL TCLSH_MAIN(int argc, char **argv){
danc1a60c52010-06-07 14:28:16 +00004198 Tcl_Interp *interp;
mistachkin1f28e072013-08-15 08:06:15 +00004199
4200#if !defined(_WIN32_WCE)
4201 if( getenv("BREAK") ){
4202 fprintf(stderr,
4203 "attach debugger to process %d and press any key to continue.\n",
4204 GETPID());
4205 fgetc(stdin);
4206 }
4207#endif
4208
drhdb6bafa2015-01-09 21:54:58 +00004209 /* Since the primary use case for this binary is testing of SQLite,
4210 ** be sure to generate core files if we crash */
4211#if defined(SQLITE_TEST) && defined(unix)
4212 { struct rlimit x;
4213 getrlimit(RLIMIT_CORE, &x);
4214 x.rlim_cur = x.rlim_max;
4215 setrlimit(RLIMIT_CORE, &x);
4216 }
4217#endif /* SQLITE_TEST && unix */
4218
4219
danc1a60c52010-06-07 14:28:16 +00004220 /* Call sqlite3_shutdown() once before doing anything else. This is to
4221 ** test that sqlite3_shutdown() can be safely called by a process before
4222 ** sqlite3_initialize() is. */
4223 sqlite3_shutdown();
4224
dan0ae479d2011-09-21 16:43:07 +00004225 Tcl_FindExecutable(argv[0]);
mistachkin2953ba92014-02-14 00:25:03 +00004226 Tcl_SetSystemEncoding(NULL, "utf-8");
dan0ae479d2011-09-21 16:43:07 +00004227 interp = Tcl_CreateInterp();
4228
drh3a0f13f2010-07-12 16:47:48 +00004229#if TCLSH==2
4230 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
4231#endif
danc1a60c52010-06-07 14:28:16 +00004232
danc1a60c52010-06-07 14:28:16 +00004233 init_all(interp);
drhc7285972009-11-10 01:13:25 +00004234 if( argc>=2 ){
drh348784e2000-05-29 20:41:49 +00004235 int i;
shessad42c3a2006-08-22 23:53:46 +00004236 char zArgc[32];
4237 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
4238 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00004239 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
4240 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
4241 for(i=3-TCLSH; i<argc; i++){
4242 Tcl_SetVar(interp, "argv", argv[i],
4243 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
4244 }
drh3a0f13f2010-07-12 16:47:48 +00004245 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00004246 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00004247 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00004248 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00004249 return 1;
4250 }
drh3e27c022004-07-23 00:01:38 +00004251 }
drh3a0f13f2010-07-12 16:47:48 +00004252 if( TCLSH==2 || argc<=1 ){
dan0ae479d2011-09-21 16:43:07 +00004253 Tcl_GlobalEval(interp, tclsh_main_loop());
drh348784e2000-05-29 20:41:49 +00004254 }
4255 return 0;
4256}
4257#endif /* TCLSH */