blob: 854bbb0f0c2e49ea94ae59664893179a7d25626d [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.
drh75897232000-05-29 14:26:00 +000014**
drh69910da2009-03-27 12:32:54 +000015** $Id: tclsqlite.c,v 1.240 2009/03/27 12:32:55 drh Exp $
drh75897232000-05-29 14:26:00 +000016*/
drh17a68932001-01-31 13:28:08 +000017#include "tcl.h"
danielk1977b4e9af92007-05-01 17:49:49 +000018#include <errno.h>
drhbd08af42007-04-05 21:58:33 +000019
20/*
21** Some additional include files are needed if this file is not
22** appended to the amalgamation.
23*/
24#ifndef SQLITE_AMALGAMATION
25# include "sqliteInt.h"
drhbd08af42007-04-05 21:58:33 +000026# include <stdlib.h>
27# include <string.h>
28# include <assert.h>
29# include <ctype.h>
30#endif
drh75897232000-05-29 14:26:00 +000031
drhad6e1372006-07-10 21:15:51 +000032/*
33 * Windows needs to know which symbols to export. Unix does not.
34 * BUILD_sqlite should be undefined for Unix.
35 */
36#ifdef BUILD_sqlite
37#undef TCL_STORAGE_CLASS
38#define TCL_STORAGE_CLASS DLLEXPORT
39#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000040
danielk1977a21c6b62005-01-24 10:25:59 +000041#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000042#define MAX_PREPARED_STMTS 100
43
drh75897232000-05-29 14:26:00 +000044/*
drh98808ba2001-10-18 12:34:46 +000045** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
46** have to do a translation when going between the two. Set the
47** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
48** this translation.
49*/
50#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
51# define UTF_TRANSLATION_NEEDED 1
52#endif
53
54/*
drhcabb0812002-09-14 13:47:32 +000055** New SQL functions can be created as TCL scripts. Each such function
56** is described by an instance of the following structure.
57*/
58typedef struct SqlFunc SqlFunc;
59struct SqlFunc {
60 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000061 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
62 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
63 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000064 SqlFunc *pNext; /* Next function on the list of them all */
65};
66
67/*
danielk19770202b292004-06-09 09:55:16 +000068** New collation sequences function can be created as TCL scripts. Each such
69** function is described by an instance of the following structure.
70*/
71typedef struct SqlCollate SqlCollate;
72struct SqlCollate {
73 Tcl_Interp *interp; /* The TCL interpret to execute the function */
74 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000075 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000076};
77
78/*
drhfb7e7652005-01-24 00:28:42 +000079** Prepared statements are cached for faster execution. Each prepared
80** statement is described by an instance of the following structure.
81*/
82typedef struct SqlPreparedStmt SqlPreparedStmt;
83struct SqlPreparedStmt {
84 SqlPreparedStmt *pNext; /* Next in linked list */
85 SqlPreparedStmt *pPrev; /* Previous on the list */
86 sqlite3_stmt *pStmt; /* The prepared statement */
87 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +000088 const char *zSql; /* Text of the SQL statement */
drhfb7e7652005-01-24 00:28:42 +000089};
90
danielk1977d04417962007-05-02 13:16:30 +000091typedef struct IncrblobChannel IncrblobChannel;
92
drhfb7e7652005-01-24 00:28:42 +000093/*
drhbec3f402000-08-04 13:49:02 +000094** There is one instance of this structure for each SQLite database
95** that has been opened by the SQLite TCL interface.
96*/
97typedef struct SqliteDb SqliteDb;
98struct SqliteDb {
drhdddca282006-01-03 00:33:50 +000099 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000100 Tcl_Interp *interp; /* The interpreter used for this database */
101 char *zBusy; /* The busy callback routine */
102 char *zCommit; /* The commit hook callback routine */
103 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +0000104 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000105 char *zProgress; /* The progress callback routine */
106 char *zAuth; /* The authorization callback routine */
drh1f1549f2008-08-26 21:33:34 +0000107 int disableAuth; /* Disable the authorizer if it exists */
drhd1e47332005-06-26 17:55:33 +0000108 char *zNull; /* Text to substitute for an SQL NULL value */
109 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000110 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000111 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
danielk1977404ca072009-03-16 13:19:36 +0000112 Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */
drhd1e47332005-06-26 17:55:33 +0000113 SqlCollate *pCollate; /* List of SQL collation functions */
114 int rc; /* Return code of most recent sqlite3_exec() */
115 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000116 SqlPreparedStmt *stmtList; /* List of prepared statements*/
117 SqlPreparedStmt *stmtLast; /* Last statement in the list */
118 int maxStmt; /* The next maximum number of stmtList */
119 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000120 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drhd1d38482008-10-07 23:46:38 +0000121 int nStep, nSort; /* Statistics for most recent operation */
danielk1977cd38d522009-01-02 17:33:46 +0000122 int nTransaction; /* Number of nested [transaction] methods */
drh98808ba2001-10-18 12:34:46 +0000123};
drh297ecf12001-04-05 15:57:13 +0000124
danielk1977b4e9af92007-05-01 17:49:49 +0000125struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000126 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000127 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000128 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000129 Tcl_Channel channel; /* Channel identifier */
130 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
131 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000132};
133
drhea678832008-12-10 19:26:22 +0000134/*
135** Compute a string length that is limited to what can be stored in
136** lower 30 bits of a 32-bit signed integer.
137*/
drh4f21c4a2008-12-10 22:15:00 +0000138static int strlen30(const char *z){
drhea678832008-12-10 19:26:22 +0000139 const char *z2 = z;
140 while( *z2 ){ z2++; }
141 return 0x3fffffff & (int)(z2 - z);
142}
drhea678832008-12-10 19:26:22 +0000143
144
danielk197732a0d8b2007-05-04 19:03:02 +0000145#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000146/*
danielk1977d04417962007-05-02 13:16:30 +0000147** Close all incrblob channels opened using database connection pDb.
148** This is called when shutting down the database connection.
149*/
150static void closeIncrblobChannels(SqliteDb *pDb){
151 IncrblobChannel *p;
152 IncrblobChannel *pNext;
153
154 for(p=pDb->pIncrblob; p; p=pNext){
155 pNext = p->pNext;
156
157 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
158 ** which deletes the IncrblobChannel structure at *p. So do not
159 ** call Tcl_Free() here.
160 */
161 Tcl_UnregisterChannel(pDb->interp, p->channel);
162 }
163}
164
165/*
danielk1977b4e9af92007-05-01 17:49:49 +0000166** Close an incremental blob channel.
167*/
168static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
169 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000170 int rc = sqlite3_blob_close(p->pBlob);
171 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000172
173 /* Remove the channel from the SqliteDb.pIncrblob list. */
174 if( p->pNext ){
175 p->pNext->pPrev = p->pPrev;
176 }
177 if( p->pPrev ){
178 p->pPrev->pNext = p->pNext;
179 }
180 if( p->pDb->pIncrblob==p ){
181 p->pDb->pIncrblob = p->pNext;
182 }
183
danielk197792d4d7a2007-05-04 12:05:56 +0000184 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000185 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000186
187 if( rc!=SQLITE_OK ){
188 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
189 return TCL_ERROR;
190 }
danielk1977b4e9af92007-05-01 17:49:49 +0000191 return TCL_OK;
192}
193
194/*
195** Read data from an incremental blob channel.
196*/
197static int incrblobInput(
198 ClientData instanceData,
199 char *buf,
200 int bufSize,
201 int *errorCodePtr
202){
203 IncrblobChannel *p = (IncrblobChannel *)instanceData;
204 int nRead = bufSize; /* Number of bytes to read */
205 int nBlob; /* Total size of the blob */
206 int rc; /* sqlite error code */
207
208 nBlob = sqlite3_blob_bytes(p->pBlob);
209 if( (p->iSeek+nRead)>nBlob ){
210 nRead = nBlob-p->iSeek;
211 }
212 if( nRead<=0 ){
213 return 0;
214 }
215
216 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
217 if( rc!=SQLITE_OK ){
218 *errorCodePtr = rc;
219 return -1;
220 }
221
222 p->iSeek += nRead;
223 return nRead;
224}
225
danielk1977d04417962007-05-02 13:16:30 +0000226/*
227** Write data to an incremental blob channel.
228*/
danielk1977b4e9af92007-05-01 17:49:49 +0000229static int incrblobOutput(
230 ClientData instanceData,
231 CONST char *buf,
232 int toWrite,
233 int *errorCodePtr
234){
235 IncrblobChannel *p = (IncrblobChannel *)instanceData;
236 int nWrite = toWrite; /* Number of bytes to write */
237 int nBlob; /* Total size of the blob */
238 int rc; /* sqlite error code */
239
240 nBlob = sqlite3_blob_bytes(p->pBlob);
241 if( (p->iSeek+nWrite)>nBlob ){
242 *errorCodePtr = EINVAL;
243 return -1;
244 }
245 if( nWrite<=0 ){
246 return 0;
247 }
248
249 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
250 if( rc!=SQLITE_OK ){
251 *errorCodePtr = EIO;
252 return -1;
253 }
254
255 p->iSeek += nWrite;
256 return nWrite;
257}
258
259/*
260** Seek an incremental blob channel.
261*/
262static int incrblobSeek(
263 ClientData instanceData,
264 long offset,
265 int seekMode,
266 int *errorCodePtr
267){
268 IncrblobChannel *p = (IncrblobChannel *)instanceData;
269
270 switch( seekMode ){
271 case SEEK_SET:
272 p->iSeek = offset;
273 break;
274 case SEEK_CUR:
275 p->iSeek += offset;
276 break;
277 case SEEK_END:
278 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
279 break;
280
281 default: assert(!"Bad seekMode");
282 }
283
284 return p->iSeek;
285}
286
287
288static void incrblobWatch(ClientData instanceData, int mode){
289 /* NO-OP */
290}
291static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
292 return TCL_ERROR;
293}
294
295static Tcl_ChannelType IncrblobChannelType = {
296 "incrblob", /* typeName */
297 TCL_CHANNEL_VERSION_2, /* version */
298 incrblobClose, /* closeProc */
299 incrblobInput, /* inputProc */
300 incrblobOutput, /* outputProc */
301 incrblobSeek, /* seekProc */
302 0, /* setOptionProc */
303 0, /* getOptionProc */
304 incrblobWatch, /* watchProc (this is a no-op) */
305 incrblobHandle, /* getHandleProc (always returns error) */
306 0, /* close2Proc */
307 0, /* blockModeProc */
308 0, /* flushProc */
309 0, /* handlerProc */
310 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000311};
312
313/*
314** Create a new incrblob channel.
315*/
316static int createIncrblobChannel(
317 Tcl_Interp *interp,
318 SqliteDb *pDb,
319 const char *zDb,
320 const char *zTable,
321 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000322 sqlite_int64 iRow,
323 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000324){
325 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000326 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000327 sqlite3_blob *pBlob;
328 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000329 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000330
331 /* This variable is used to name the channels: "incrblob_[incr count]" */
332 static int count = 0;
333 char zChannel[64];
334
danielk19778cbadb02007-05-03 16:31:26 +0000335 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000336 if( rc!=SQLITE_OK ){
337 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
338 return TCL_ERROR;
339 }
340
341 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
342 p->iSeek = 0;
343 p->pBlob = pBlob;
344
drh5bb3eb92007-05-04 13:15:55 +0000345 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000346 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
347 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000348
danielk1977d04417962007-05-02 13:16:30 +0000349 /* Link the new channel into the SqliteDb.pIncrblob list. */
350 p->pNext = pDb->pIncrblob;
351 p->pPrev = 0;
352 if( p->pNext ){
353 p->pNext->pPrev = p;
354 }
355 pDb->pIncrblob = p;
356 p->pDb = pDb;
357
358 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000359 return TCL_OK;
360}
danielk197732a0d8b2007-05-04 19:03:02 +0000361#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
362 #define closeIncrblobChannels(pDb)
363#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000364
drh6d313162000-09-21 13:01:35 +0000365/*
drhd1e47332005-06-26 17:55:33 +0000366** Look at the script prefix in pCmd. We will be executing this script
367** after first appending one or more arguments. This routine analyzes
368** the script to see if it is safe to use Tcl_EvalObjv() on the script
369** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
370** faster.
371**
372** Scripts that are safe to use with Tcl_EvalObjv() consists of a
373** command name followed by zero or more arguments with no [...] or $
374** or {...} or ; to be seen anywhere. Most callback scripts consist
375** of just a single procedure name and they meet this requirement.
376*/
377static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
378 /* We could try to do something with Tcl_Parse(). But we will instead
379 ** just do a search for forbidden characters. If any of the forbidden
380 ** characters appear in pCmd, we will report the string as unsafe.
381 */
382 const char *z;
383 int n;
384 z = Tcl_GetStringFromObj(pCmd, &n);
385 while( n-- > 0 ){
386 int c = *(z++);
387 if( c=='$' || c=='[' || c==';' ) return 0;
388 }
389 return 1;
390}
391
392/*
393** Find an SqlFunc structure with the given name. Or create a new
394** one if an existing one cannot be found. Return a pointer to the
395** structure.
396*/
397static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
398 SqlFunc *p, *pNew;
399 int i;
drh4f21c4a2008-12-10 22:15:00 +0000400 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen30(zName) + 1 );
drhd1e47332005-06-26 17:55:33 +0000401 pNew->zName = (char*)&pNew[1];
402 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
403 pNew->zName[i] = 0;
404 for(p=pDb->pFunc; p; p=p->pNext){
405 if( strcmp(p->zName, pNew->zName)==0 ){
406 Tcl_Free((char*)pNew);
407 return p;
408 }
409 }
410 pNew->interp = pDb->interp;
411 pNew->pScript = 0;
412 pNew->pNext = pDb->pFunc;
413 pDb->pFunc = pNew;
414 return pNew;
415}
416
417/*
drhfb7e7652005-01-24 00:28:42 +0000418** Finalize and free a list of prepared statements
419*/
420static void flushStmtCache( SqliteDb *pDb ){
421 SqlPreparedStmt *pPreStmt;
422
423 while( pDb->stmtList ){
424 sqlite3_finalize( pDb->stmtList->pStmt );
425 pPreStmt = pDb->stmtList;
426 pDb->stmtList = pDb->stmtList->pNext;
427 Tcl_Free( (char*)pPreStmt );
428 }
429 pDb->nStmt = 0;
430 pDb->stmtLast = 0;
431}
432
433/*
drh895d7472004-08-20 16:02:39 +0000434** TCL calls this procedure when an sqlite3 database command is
435** deleted.
drh75897232000-05-29 14:26:00 +0000436*/
437static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000438 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000439 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000440 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000441 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000442 while( pDb->pFunc ){
443 SqlFunc *pFunc = pDb->pFunc;
444 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000445 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000446 Tcl_Free((char*)pFunc);
447 }
danielk19770202b292004-06-09 09:55:16 +0000448 while( pDb->pCollate ){
449 SqlCollate *pCollate = pDb->pCollate;
450 pDb->pCollate = pCollate->pNext;
451 Tcl_Free((char*)pCollate);
452 }
drhbec3f402000-08-04 13:49:02 +0000453 if( pDb->zBusy ){
454 Tcl_Free(pDb->zBusy);
455 }
drhb5a20d32003-04-23 12:25:23 +0000456 if( pDb->zTrace ){
457 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000458 }
drh19e2d372005-08-29 23:00:03 +0000459 if( pDb->zProfile ){
460 Tcl_Free(pDb->zProfile);
461 }
drhe22a3342003-04-22 20:30:37 +0000462 if( pDb->zAuth ){
463 Tcl_Free(pDb->zAuth);
464 }
danielk197755c45f22005-04-03 23:54:43 +0000465 if( pDb->zNull ){
466 Tcl_Free(pDb->zNull);
467 }
danielk197794eb6a12005-12-15 15:22:08 +0000468 if( pDb->pUpdateHook ){
469 Tcl_DecrRefCount(pDb->pUpdateHook);
470 }
danielk197771fd80b2005-12-16 06:54:01 +0000471 if( pDb->pRollbackHook ){
472 Tcl_DecrRefCount(pDb->pRollbackHook);
473 }
danielk197794eb6a12005-12-15 15:22:08 +0000474 if( pDb->pCollateNeeded ){
475 Tcl_DecrRefCount(pDb->pCollateNeeded);
476 }
drhbec3f402000-08-04 13:49:02 +0000477 Tcl_Free((char*)pDb);
478}
479
480/*
481** This routine is called when a database file is locked while trying
482** to execute SQL.
483*/
danielk19772a764eb2004-06-12 01:43:26 +0000484static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000485 SqliteDb *pDb = (SqliteDb*)cd;
486 int rc;
487 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000488
drh5bb3eb92007-05-04 13:15:55 +0000489 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000490 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000491 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
492 return 0;
493 }
494 return 1;
drh75897232000-05-29 14:26:00 +0000495}
496
drh26e4a8b2008-05-01 17:16:52 +0000497#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000498/*
danielk1977348bb5d2003-10-18 09:37:26 +0000499** This routine is invoked as the 'progress callback' for the database.
500*/
501static int DbProgressHandler(void *cd){
502 SqliteDb *pDb = (SqliteDb*)cd;
503 int rc;
504
505 assert( pDb->zProgress );
506 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
507 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
508 return 1;
509 }
510 return 0;
511}
drh26e4a8b2008-05-01 17:16:52 +0000512#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000513
drhd1167392006-01-23 13:00:35 +0000514#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000515/*
drhb5a20d32003-04-23 12:25:23 +0000516** This routine is called by the SQLite trace handler whenever a new
517** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000518*/
drhb5a20d32003-04-23 12:25:23 +0000519static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000520 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000521 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000522
drhb5a20d32003-04-23 12:25:23 +0000523 Tcl_DStringInit(&str);
524 Tcl_DStringAppend(&str, pDb->zTrace, -1);
525 Tcl_DStringAppendElement(&str, zSql);
526 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
527 Tcl_DStringFree(&str);
528 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000529}
drhd1167392006-01-23 13:00:35 +0000530#endif
drh0d1a6432003-04-03 15:46:04 +0000531
drhd1167392006-01-23 13:00:35 +0000532#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000533/*
drh19e2d372005-08-29 23:00:03 +0000534** This routine is called by the SQLite profile handler after a statement
535** SQL has executed. The TCL script in pDb->zProfile is evaluated.
536*/
537static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
538 SqliteDb *pDb = (SqliteDb*)cd;
539 Tcl_DString str;
540 char zTm[100];
541
542 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
543 Tcl_DStringInit(&str);
544 Tcl_DStringAppend(&str, pDb->zProfile, -1);
545 Tcl_DStringAppendElement(&str, zSql);
546 Tcl_DStringAppendElement(&str, zTm);
547 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
548 Tcl_DStringFree(&str);
549 Tcl_ResetResult(pDb->interp);
550}
drhd1167392006-01-23 13:00:35 +0000551#endif
drh19e2d372005-08-29 23:00:03 +0000552
553/*
drhaa940ea2004-01-15 02:44:03 +0000554** This routine is called when a transaction is committed. The
555** TCL script in pDb->zCommit is executed. If it returns non-zero or
556** if it throws an exception, the transaction is rolled back instead
557** of being committed.
558*/
559static int DbCommitHandler(void *cd){
560 SqliteDb *pDb = (SqliteDb*)cd;
561 int rc;
562
563 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
564 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
565 return 1;
566 }
567 return 0;
568}
569
danielk197771fd80b2005-12-16 06:54:01 +0000570static void DbRollbackHandler(void *clientData){
571 SqliteDb *pDb = (SqliteDb*)clientData;
572 assert(pDb->pRollbackHook);
573 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
574 Tcl_BackgroundError(pDb->interp);
575 }
576}
577
danielk1977404ca072009-03-16 13:19:36 +0000578#ifdef SQLITE_TEST
579static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
580 char zBuf[64];
581 sprintf(zBuf, "%d", iArg);
582 Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
583 sprintf(zBuf, "%d", nArg);
584 Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
585}
586#else
587 #define setTestUnlockNotifyVars(x,y,z)
588#endif
589
drh69910da2009-03-27 12:32:54 +0000590#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
danielk1977404ca072009-03-16 13:19:36 +0000591static void DbUnlockNotify(void **apArg, int nArg){
592 int i;
593 for(i=0; i<nArg; i++){
594 const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
595 SqliteDb *pDb = (SqliteDb *)apArg[i];
596 setTestUnlockNotifyVars(pDb->interp, i, nArg);
597 assert( pDb->pUnlockNotify);
598 Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
599 Tcl_DecrRefCount(pDb->pUnlockNotify);
600 pDb->pUnlockNotify = 0;
601 }
602}
drh69910da2009-03-27 12:32:54 +0000603#endif
danielk1977404ca072009-03-16 13:19:36 +0000604
danielk197794eb6a12005-12-15 15:22:08 +0000605static void DbUpdateHandler(
606 void *p,
607 int op,
608 const char *zDb,
609 const char *zTbl,
610 sqlite_int64 rowid
611){
612 SqliteDb *pDb = (SqliteDb *)p;
613 Tcl_Obj *pCmd;
614
615 assert( pDb->pUpdateHook );
616 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
617
618 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
619 Tcl_IncrRefCount(pCmd);
620 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
621 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
622 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
623 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
624 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
625 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
626}
627
danielk19777cedc8d2004-06-10 10:50:08 +0000628static void tclCollateNeeded(
629 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000630 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000631 int enc,
632 const char *zName
633){
634 SqliteDb *pDb = (SqliteDb *)pCtx;
635 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
636 Tcl_IncrRefCount(pScript);
637 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
638 Tcl_EvalObjEx(pDb->interp, pScript, 0);
639 Tcl_DecrRefCount(pScript);
640}
641
drhaa940ea2004-01-15 02:44:03 +0000642/*
danielk19770202b292004-06-09 09:55:16 +0000643** This routine is called to evaluate an SQL collation function implemented
644** using TCL script.
645*/
646static int tclSqlCollate(
647 void *pCtx,
648 int nA,
649 const void *zA,
650 int nB,
651 const void *zB
652){
653 SqlCollate *p = (SqlCollate *)pCtx;
654 Tcl_Obj *pCmd;
655
656 pCmd = Tcl_NewStringObj(p->zScript, -1);
657 Tcl_IncrRefCount(pCmd);
658 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
659 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000660 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000661 Tcl_DecrRefCount(pCmd);
662 return (atoi(Tcl_GetStringResult(p->interp)));
663}
664
665/*
drhcabb0812002-09-14 13:47:32 +0000666** This routine is called to evaluate an SQL function implemented
667** using TCL script.
668*/
drhfb7e7652005-01-24 00:28:42 +0000669static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000670 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000671 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000672 int i;
673 int rc;
674
drhd1e47332005-06-26 17:55:33 +0000675 if( argc==0 ){
676 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
677 ** script object directly. This allows the TCL compiler to generate
678 ** bytecode for the command on the first invocation and thus make
679 ** subsequent invocations much faster. */
680 pCmd = p->pScript;
681 Tcl_IncrRefCount(pCmd);
682 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
683 Tcl_DecrRefCount(pCmd);
684 }else{
685 /* If there are arguments to the function, make a shallow copy of the
686 ** script object, lappend the arguments, then evaluate the copy.
687 **
688 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
689 ** The new Tcl_Obj contains pointers to the original list elements.
690 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
691 ** of the list to tclCmdNameType, that alternate representation will
692 ** be preserved and reused on the next invocation.
693 */
694 Tcl_Obj **aArg;
695 int nArg;
696 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
697 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
698 return;
699 }
700 pCmd = Tcl_NewListObj(nArg, aArg);
701 Tcl_IncrRefCount(pCmd);
702 for(i=0; i<argc; i++){
703 sqlite3_value *pIn = argv[i];
704 Tcl_Obj *pVal;
705
706 /* Set pVal to contain the i'th column of this row. */
707 switch( sqlite3_value_type(pIn) ){
708 case SQLITE_BLOB: {
709 int bytes = sqlite3_value_bytes(pIn);
710 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
711 break;
712 }
713 case SQLITE_INTEGER: {
714 sqlite_int64 v = sqlite3_value_int64(pIn);
715 if( v>=-2147483647 && v<=2147483647 ){
716 pVal = Tcl_NewIntObj(v);
717 }else{
718 pVal = Tcl_NewWideIntObj(v);
719 }
720 break;
721 }
722 case SQLITE_FLOAT: {
723 double r = sqlite3_value_double(pIn);
724 pVal = Tcl_NewDoubleObj(r);
725 break;
726 }
727 case SQLITE_NULL: {
728 pVal = Tcl_NewStringObj("", 0);
729 break;
730 }
731 default: {
732 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000733 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000734 break;
735 }
736 }
737 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
738 if( rc ){
739 Tcl_DecrRefCount(pCmd);
740 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
741 return;
742 }
danielk197751ad0ec2004-05-24 12:39:02 +0000743 }
drhd1e47332005-06-26 17:55:33 +0000744 if( !p->useEvalObjv ){
745 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
746 ** is a list without a string representation. To prevent this from
747 ** happening, make sure pCmd has a valid string representation */
748 Tcl_GetString(pCmd);
749 }
750 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
751 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000752 }
danielk1977562e8d32005-05-20 09:40:55 +0000753
drhc7f269d2005-05-05 10:30:29 +0000754 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000755 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000756 }else{
drhc7f269d2005-05-05 10:30:29 +0000757 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
758 int n;
759 u8 *data;
760 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
761 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000762 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000763 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000764 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000765 data = Tcl_GetByteArrayFromObj(pVar, &n);
766 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000767 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000768 Tcl_GetIntFromObj(0, pVar, &n);
769 sqlite3_result_int(context, n);
770 }else if( c=='d' && strcmp(zType,"double")==0 ){
771 double r;
772 Tcl_GetDoubleFromObj(0, pVar, &r);
773 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +0000774 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
775 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000776 Tcl_WideInt v;
777 Tcl_GetWideIntFromObj(0, pVar, &v);
778 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000779 }else{
danielk197700fd9572005-12-07 06:27:43 +0000780 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
781 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000782 }
drhcabb0812002-09-14 13:47:32 +0000783 }
784}
drh895d7472004-08-20 16:02:39 +0000785
drhe22a3342003-04-22 20:30:37 +0000786#ifndef SQLITE_OMIT_AUTHORIZATION
787/*
788** This is the authentication function. It appends the authentication
789** type code and the two arguments to zCmd[] then invokes the result
790** on the interpreter. The reply is examined to determine if the
791** authentication fails or succeeds.
792*/
793static int auth_callback(
794 void *pArg,
795 int code,
796 const char *zArg1,
797 const char *zArg2,
798 const char *zArg3,
799 const char *zArg4
800){
801 char *zCode;
802 Tcl_DString str;
803 int rc;
804 const char *zReply;
805 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +0000806 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +0000807
808 switch( code ){
809 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
810 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
811 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
812 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
813 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
814 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
815 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
816 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
817 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
818 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
819 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
820 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
821 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
822 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
823 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
824 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
825 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
826 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
827 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
828 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
829 case SQLITE_READ : zCode="SQLITE_READ"; break;
830 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
831 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
832 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000833 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
834 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000835 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000836 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000837 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000838 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
839 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000840 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
danielk1977ab9b7032008-12-30 06:24:58 +0000841 case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break;
drhe22a3342003-04-22 20:30:37 +0000842 default : zCode="????"; break;
843 }
844 Tcl_DStringInit(&str);
845 Tcl_DStringAppend(&str, pDb->zAuth, -1);
846 Tcl_DStringAppendElement(&str, zCode);
847 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
848 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
849 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
850 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
851 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
852 Tcl_DStringFree(&str);
853 zReply = Tcl_GetStringResult(pDb->interp);
854 if( strcmp(zReply,"SQLITE_OK")==0 ){
855 rc = SQLITE_OK;
856 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
857 rc = SQLITE_DENY;
858 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
859 rc = SQLITE_IGNORE;
860 }else{
861 rc = 999;
862 }
863 return rc;
864}
865#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000866
867/*
danielk1977ef2cb632004-05-29 02:37:19 +0000868** zText is a pointer to text obtained via an sqlite3_result_text()
869** or similar interface. This routine returns a Tcl string object,
870** reference count set to 0, containing the text. If a translation
871** between iso8859 and UTF-8 is required, it is preformed.
872*/
873static Tcl_Obj *dbTextToObj(char const *zText){
874 Tcl_Obj *pVal;
875#ifdef UTF_TRANSLATION_NEEDED
876 Tcl_DString dCol;
877 Tcl_DStringInit(&dCol);
878 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
879 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
880 Tcl_DStringFree(&dCol);
881#else
882 pVal = Tcl_NewStringObj(zText, -1);
883#endif
884 return pVal;
885}
886
887/*
tpoindex1067fe12004-12-17 15:41:11 +0000888** This routine reads a line of text from FILE in, stores
889** the text in memory obtained from malloc() and returns a pointer
890** to the text. NULL is returned at end of file, or if malloc()
891** fails.
892**
893** The interface is like "readline" but no command-line editing
894** is done.
895**
896** copied from shell.c from '.import' command
897*/
898static char *local_getline(char *zPrompt, FILE *in){
899 char *zLine;
900 int nLine;
901 int n;
902 int eol;
903
904 nLine = 100;
905 zLine = malloc( nLine );
906 if( zLine==0 ) return 0;
907 n = 0;
908 eol = 0;
909 while( !eol ){
910 if( n+100>nLine ){
911 nLine = nLine*2 + 100;
912 zLine = realloc(zLine, nLine);
913 if( zLine==0 ) return 0;
914 }
915 if( fgets(&zLine[n], nLine - n, in)==0 ){
916 if( n==0 ){
917 free(zLine);
918 return 0;
919 }
920 zLine[n] = 0;
921 eol = 1;
922 break;
923 }
924 while( zLine[n] ){ n++; }
925 if( n>0 && zLine[n-1]=='\n' ){
926 n--;
927 zLine[n] = 0;
928 eol = 1;
929 }
930 }
931 zLine = realloc( zLine, n+1 );
932 return zLine;
933}
934
danielk19778e556522007-11-13 10:30:24 +0000935
936/*
937** Figure out the column names for the data returned by the statement
938** passed as the second argument.
939**
940** If parameter papColName is not NULL, then *papColName is set to point
941** at an array allocated using Tcl_Alloc(). It is the callers responsibility
942** to free this array using Tcl_Free(), and to decrement the reference
943** count of each Tcl_Obj* member of the array.
944**
945** The return value of this function is the number of columns of data
946** returned by pStmt (and hence the size of the *papColName array).
947**
948** If pArray is not NULL, then it contains the name of a Tcl array
949** variable. The "*" member of this array is set to a list containing
950** the names of the columns returned by the statement, in order from
951** left to right. e.g. if the names of the returned columns are a, b and
952** c, it does the equivalent of the tcl command:
953**
954** set ${pArray}(*) {a b c}
955*/
956static int
957computeColumnNames(
958 Tcl_Interp *interp,
959 sqlite3_stmt *pStmt, /* SQL statement */
960 Tcl_Obj ***papColName, /* OUT: Array of column names */
961 Tcl_Obj *pArray /* Name of array variable (may be null) */
962){
963 int nCol;
964
965 /* Compute column names */
966 nCol = sqlite3_column_count(pStmt);
967 if( papColName ){
968 int i;
969 Tcl_Obj **apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
970 for(i=0; i<nCol; i++){
971 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
972 Tcl_IncrRefCount(apColName[i]);
973 }
974
975 /* If results are being stored in an array variable, then create
976 ** the array(*) entry for that array
977 */
978 if( pArray ){
979 Tcl_Obj *pColList = Tcl_NewObj();
980 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
981 Tcl_IncrRefCount(pColList);
982 for(i=0; i<nCol; i++){
983 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
984 }
985 Tcl_IncrRefCount(pStar);
986 Tcl_ObjSetVar2(interp, pArray, pStar, pColList,0);
987 Tcl_DecrRefCount(pColList);
988 Tcl_DecrRefCount(pStar);
989 }
990 *papColName = apColName;
991 }
992
993 return nCol;
994}
995
tpoindex1067fe12004-12-17 15:41:11 +0000996/*
drh75897232000-05-29 14:26:00 +0000997** The "sqlite" command below creates a new Tcl command for each
998** connection it opens to an SQLite database. This routine is invoked
999** whenever one of those connection-specific commands is executed
1000** in Tcl. For example, if you run Tcl code like this:
1001**
drh9bb575f2004-09-06 17:24:11 +00001002** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +00001003** db1 close
1004**
1005** The first command opens a connection to the "my_database" database
1006** and calls that connection "db1". The second command causes this
1007** subroutine to be invoked.
1008*/
drh6d313162000-09-21 13:01:35 +00001009static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001010 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +00001011 int choice;
drh22fbcb82004-02-01 01:22:50 +00001012 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +00001013 static const char *DB_strs[] = {
drhdc2c4912009-02-04 22:46:47 +00001014 "authorizer", "backup", "busy",
1015 "cache", "changes", "close",
1016 "collate", "collation_needed", "commit_hook",
1017 "complete", "copy", "enable_load_extension",
1018 "errorcode", "eval", "exists",
1019 "function", "incrblob", "interrupt",
1020 "last_insert_rowid", "nullvalue", "onecolumn",
1021 "profile", "progress", "rekey",
1022 "restore", "rollback_hook", "status",
1023 "timeout", "total_changes", "trace",
danielk1977404ca072009-03-16 13:19:36 +00001024 "transaction", "unlock_notify", "update_hook",
1025 "version", 0
drh6d313162000-09-21 13:01:35 +00001026 };
drh411995d2002-06-25 19:31:18 +00001027 enum DB_enum {
drhdc2c4912009-02-04 22:46:47 +00001028 DB_AUTHORIZER, DB_BACKUP, DB_BUSY,
1029 DB_CACHE, DB_CHANGES, DB_CLOSE,
1030 DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1031 DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION,
1032 DB_ERRORCODE, DB_EVAL, DB_EXISTS,
1033 DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT,
1034 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
1035 DB_PROFILE, DB_PROGRESS, DB_REKEY,
1036 DB_RESTORE, DB_ROLLBACK_HOOK, DB_STATUS,
1037 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
danielk1977404ca072009-03-16 13:19:36 +00001038 DB_TRANSACTION, DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK,
1039 DB_VERSION,
drh6d313162000-09-21 13:01:35 +00001040 };
tpoindex1067fe12004-12-17 15:41:11 +00001041 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +00001042
1043 if( objc<2 ){
1044 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001045 return TCL_ERROR;
1046 }
drh411995d2002-06-25 19:31:18 +00001047 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001048 return TCL_ERROR;
1049 }
1050
drh411995d2002-06-25 19:31:18 +00001051 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001052
drhe22a3342003-04-22 20:30:37 +00001053 /* $db authorizer ?CALLBACK?
1054 **
1055 ** Invoke the given callback to authorize each SQL operation as it is
1056 ** compiled. 5 arguments are appended to the callback before it is
1057 ** invoked:
1058 **
1059 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1060 ** (2) First descriptive name (depends on authorization type)
1061 ** (3) Second descriptive name
1062 ** (4) Name of the database (ex: "main", "temp")
1063 ** (5) Name of trigger that is doing the access
1064 **
1065 ** The callback should return on of the following strings: SQLITE_OK,
1066 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1067 **
1068 ** If this method is invoked with no arguments, the current authorization
1069 ** callback string is returned.
1070 */
1071 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001072#ifdef SQLITE_OMIT_AUTHORIZATION
1073 Tcl_AppendResult(interp, "authorization not available in this build", 0);
1074 return TCL_ERROR;
1075#else
drhe22a3342003-04-22 20:30:37 +00001076 if( objc>3 ){
1077 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001078 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001079 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001080 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +00001081 Tcl_AppendResult(interp, pDb->zAuth, 0);
1082 }
1083 }else{
1084 char *zAuth;
1085 int len;
1086 if( pDb->zAuth ){
1087 Tcl_Free(pDb->zAuth);
1088 }
1089 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1090 if( zAuth && len>0 ){
1091 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001092 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001093 }else{
1094 pDb->zAuth = 0;
1095 }
drhe22a3342003-04-22 20:30:37 +00001096 if( pDb->zAuth ){
1097 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001098 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +00001099 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001100 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001101 }
drhe22a3342003-04-22 20:30:37 +00001102 }
drh1211de32004-07-26 12:24:22 +00001103#endif
drhe22a3342003-04-22 20:30:37 +00001104 break;
1105 }
1106
drhdc2c4912009-02-04 22:46:47 +00001107 /* $db backup ?DATABASE? FILENAME
1108 **
1109 ** Open or create a database file named FILENAME. Transfer the
1110 ** content of local database DATABASE (default: "main") into the
1111 ** FILENAME database.
1112 */
1113 case DB_BACKUP: {
1114 const char *zDestFile;
1115 const char *zSrcDb;
1116 sqlite3 *pDest;
1117 sqlite3_backup *pBackup;
1118
1119 if( objc==3 ){
1120 zSrcDb = "main";
1121 zDestFile = Tcl_GetString(objv[2]);
1122 }else if( objc==4 ){
1123 zSrcDb = Tcl_GetString(objv[2]);
1124 zDestFile = Tcl_GetString(objv[3]);
1125 }else{
1126 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1127 return TCL_ERROR;
1128 }
1129 rc = sqlite3_open(zDestFile, &pDest);
1130 if( rc!=SQLITE_OK ){
1131 Tcl_AppendResult(interp, "cannot open target database: ",
1132 sqlite3_errmsg(pDest), (char*)0);
1133 sqlite3_close(pDest);
1134 return TCL_ERROR;
1135 }
1136 pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1137 if( pBackup==0 ){
1138 Tcl_AppendResult(interp, "backup failed: ",
1139 sqlite3_errmsg(pDest), (char*)0);
1140 sqlite3_close(pDest);
1141 return TCL_ERROR;
1142 }
1143 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1144 sqlite3_backup_finish(pBackup);
1145 if( rc==SQLITE_DONE ){
1146 rc = TCL_OK;
1147 }else{
1148 Tcl_AppendResult(interp, "backup failed: ",
1149 sqlite3_errmsg(pDest), (char*)0);
1150 rc = TCL_ERROR;
1151 }
1152 sqlite3_close(pDest);
1153 break;
1154 }
1155
drhbec3f402000-08-04 13:49:02 +00001156 /* $db busy ?CALLBACK?
1157 **
1158 ** Invoke the given callback if an SQL statement attempts to open
1159 ** a locked database file.
1160 */
drh6d313162000-09-21 13:01:35 +00001161 case DB_BUSY: {
1162 if( objc>3 ){
1163 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001164 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001165 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001166 if( pDb->zBusy ){
1167 Tcl_AppendResult(interp, pDb->zBusy, 0);
1168 }
1169 }else{
drh6d313162000-09-21 13:01:35 +00001170 char *zBusy;
1171 int len;
drhbec3f402000-08-04 13:49:02 +00001172 if( pDb->zBusy ){
1173 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001174 }
drh6d313162000-09-21 13:01:35 +00001175 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1176 if( zBusy && len>0 ){
1177 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001178 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001179 }else{
1180 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001181 }
1182 if( pDb->zBusy ){
1183 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001184 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001185 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001186 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001187 }
1188 }
drh6d313162000-09-21 13:01:35 +00001189 break;
1190 }
drhbec3f402000-08-04 13:49:02 +00001191
drhfb7e7652005-01-24 00:28:42 +00001192 /* $db cache flush
1193 ** $db cache size n
1194 **
1195 ** Flush the prepared statement cache, or set the maximum number of
1196 ** cached statements.
1197 */
1198 case DB_CACHE: {
1199 char *subCmd;
1200 int n;
1201
1202 if( objc<=2 ){
1203 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1204 return TCL_ERROR;
1205 }
1206 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1207 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1208 if( objc!=3 ){
1209 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1210 return TCL_ERROR;
1211 }else{
1212 flushStmtCache( pDb );
1213 }
1214 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1215 if( objc!=4 ){
1216 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1217 return TCL_ERROR;
1218 }else{
1219 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1220 Tcl_AppendResult( interp, "cannot convert \"",
1221 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1222 return TCL_ERROR;
1223 }else{
1224 if( n<0 ){
1225 flushStmtCache( pDb );
1226 n = 0;
1227 }else if( n>MAX_PREPARED_STMTS ){
1228 n = MAX_PREPARED_STMTS;
1229 }
1230 pDb->maxStmt = n;
1231 }
1232 }
1233 }else{
1234 Tcl_AppendResult( interp, "bad option \"",
danielk1977191fadc2007-10-23 08:17:48 +00001235 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
drhfb7e7652005-01-24 00:28:42 +00001236 return TCL_ERROR;
1237 }
1238 break;
1239 }
1240
danielk1977b28af712004-06-21 06:50:26 +00001241 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001242 **
1243 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001244 ** the most recent INSERT, UPDATE or DELETE statement, not including
1245 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001246 */
1247 case DB_CHANGES: {
1248 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001249 if( objc!=2 ){
1250 Tcl_WrongNumArgs(interp, 2, objv, "");
1251 return TCL_ERROR;
1252 }
drhc8d30ac2002-04-12 10:08:59 +00001253 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001254 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001255 break;
1256 }
1257
drh75897232000-05-29 14:26:00 +00001258 /* $db close
1259 **
1260 ** Shutdown the database
1261 */
drh6d313162000-09-21 13:01:35 +00001262 case DB_CLOSE: {
1263 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1264 break;
1265 }
drh75897232000-05-29 14:26:00 +00001266
drh0f14e2e2004-06-29 12:39:08 +00001267 /*
1268 ** $db collate NAME SCRIPT
1269 **
1270 ** Create a new SQL collation function called NAME. Whenever
1271 ** that function is called, invoke SCRIPT to evaluate the function.
1272 */
1273 case DB_COLLATE: {
1274 SqlCollate *pCollate;
1275 char *zName;
1276 char *zScript;
1277 int nScript;
1278 if( objc!=4 ){
1279 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1280 return TCL_ERROR;
1281 }
1282 zName = Tcl_GetStringFromObj(objv[2], 0);
1283 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1284 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1285 if( pCollate==0 ) return TCL_ERROR;
1286 pCollate->interp = interp;
1287 pCollate->pNext = pDb->pCollate;
1288 pCollate->zScript = (char*)&pCollate[1];
1289 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001290 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001291 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1292 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001293 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001294 return TCL_ERROR;
1295 }
1296 break;
1297 }
1298
1299 /*
1300 ** $db collation_needed SCRIPT
1301 **
1302 ** Create a new SQL collation function called NAME. Whenever
1303 ** that function is called, invoke SCRIPT to evaluate the function.
1304 */
1305 case DB_COLLATION_NEEDED: {
1306 if( objc!=3 ){
1307 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1308 return TCL_ERROR;
1309 }
1310 if( pDb->pCollateNeeded ){
1311 Tcl_DecrRefCount(pDb->pCollateNeeded);
1312 }
1313 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1314 Tcl_IncrRefCount(pDb->pCollateNeeded);
1315 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1316 break;
1317 }
1318
drh19e2d372005-08-29 23:00:03 +00001319 /* $db commit_hook ?CALLBACK?
1320 **
1321 ** Invoke the given callback just before committing every SQL transaction.
1322 ** If the callback throws an exception or returns non-zero, then the
1323 ** transaction is aborted. If CALLBACK is an empty string, the callback
1324 ** is disabled.
1325 */
1326 case DB_COMMIT_HOOK: {
1327 if( objc>3 ){
1328 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1329 return TCL_ERROR;
1330 }else if( objc==2 ){
1331 if( pDb->zCommit ){
1332 Tcl_AppendResult(interp, pDb->zCommit, 0);
1333 }
1334 }else{
1335 char *zCommit;
1336 int len;
1337 if( pDb->zCommit ){
1338 Tcl_Free(pDb->zCommit);
1339 }
1340 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1341 if( zCommit && len>0 ){
1342 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001343 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001344 }else{
1345 pDb->zCommit = 0;
1346 }
1347 if( pDb->zCommit ){
1348 pDb->interp = interp;
1349 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1350 }else{
1351 sqlite3_commit_hook(pDb->db, 0, 0);
1352 }
1353 }
1354 break;
1355 }
1356
drh75897232000-05-29 14:26:00 +00001357 /* $db complete SQL
1358 **
1359 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1360 ** additional lines of input are needed. This is similar to the
1361 ** built-in "info complete" command of Tcl.
1362 */
drh6d313162000-09-21 13:01:35 +00001363 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00001364#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00001365 Tcl_Obj *pResult;
1366 int isComplete;
1367 if( objc!=3 ){
1368 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00001369 return TCL_ERROR;
1370 }
danielk19776f8a5032004-05-10 10:34:51 +00001371 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00001372 pResult = Tcl_GetObjResult(interp);
1373 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00001374#endif
drh6d313162000-09-21 13:01:35 +00001375 break;
1376 }
drhdcd997e2003-01-31 17:21:49 +00001377
drh19e2d372005-08-29 23:00:03 +00001378 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1379 **
1380 ** Copy data into table from filename, optionally using SEPARATOR
1381 ** as column separators. If a column contains a null string, or the
1382 ** value of NULLINDICATOR, a NULL is inserted for the column.
1383 ** conflict-algorithm is one of the sqlite conflict algorithms:
1384 ** rollback, abort, fail, ignore, replace
1385 ** On success, return the number of lines processed, not necessarily same
1386 ** as 'db changes' due to conflict-algorithm selected.
1387 **
1388 ** This code is basically an implementation/enhancement of
1389 ** the sqlite3 shell.c ".import" command.
1390 **
1391 ** This command usage is equivalent to the sqlite2.x COPY statement,
1392 ** which imports file data into a table using the PostgreSQL COPY file format:
1393 ** $db copy $conflit_algo $table_name $filename \t \\N
1394 */
1395 case DB_COPY: {
1396 char *zTable; /* Insert data into this table */
1397 char *zFile; /* The file from which to extract data */
1398 char *zConflict; /* The conflict algorithm to use */
1399 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00001400 int nCol; /* Number of columns in the table */
1401 int nByte; /* Number of bytes in an SQL string */
1402 int i, j; /* Loop counters */
1403 int nSep; /* Number of bytes in zSep[] */
1404 int nNull; /* Number of bytes in zNull[] */
1405 char *zSql; /* An SQL statement */
1406 char *zLine; /* A single line of input from the file */
1407 char **azCol; /* zLine[] broken up into columns */
1408 char *zCommit; /* How to commit changes */
1409 FILE *in; /* The input file */
1410 int lineno = 0; /* Line number of input file */
1411 char zLineNum[80]; /* Line number print buffer */
1412 Tcl_Obj *pResult; /* interp result */
1413
1414 char *zSep;
1415 char *zNull;
1416 if( objc<5 || objc>7 ){
1417 Tcl_WrongNumArgs(interp, 2, objv,
1418 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1419 return TCL_ERROR;
1420 }
1421 if( objc>=6 ){
1422 zSep = Tcl_GetStringFromObj(objv[5], 0);
1423 }else{
1424 zSep = "\t";
1425 }
1426 if( objc>=7 ){
1427 zNull = Tcl_GetStringFromObj(objv[6], 0);
1428 }else{
1429 zNull = "";
1430 }
1431 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1432 zTable = Tcl_GetStringFromObj(objv[3], 0);
1433 zFile = Tcl_GetStringFromObj(objv[4], 0);
drh4f21c4a2008-12-10 22:15:00 +00001434 nSep = strlen30(zSep);
1435 nNull = strlen30(zNull);
drh19e2d372005-08-29 23:00:03 +00001436 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00001437 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00001438 return TCL_ERROR;
1439 }
drh3e59c012008-09-23 10:12:13 +00001440 if(strcmp(zConflict, "rollback") != 0 &&
1441 strcmp(zConflict, "abort" ) != 0 &&
1442 strcmp(zConflict, "fail" ) != 0 &&
1443 strcmp(zConflict, "ignore" ) != 0 &&
1444 strcmp(zConflict, "replace" ) != 0 ) {
drh19e2d372005-08-29 23:00:03 +00001445 Tcl_AppendResult(interp, "Error: \"", zConflict,
1446 "\", conflict-algorithm must be one of: rollback, "
1447 "abort, fail, ignore, or replace", 0);
1448 return TCL_ERROR;
1449 }
1450 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1451 if( zSql==0 ){
1452 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1453 return TCL_ERROR;
1454 }
drh4f21c4a2008-12-10 22:15:00 +00001455 nByte = strlen30(zSql);
drh3e701a12007-02-01 01:53:44 +00001456 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001457 sqlite3_free(zSql);
1458 if( rc ){
1459 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1460 nCol = 0;
1461 }else{
1462 nCol = sqlite3_column_count(pStmt);
1463 }
1464 sqlite3_finalize(pStmt);
1465 if( nCol==0 ) {
1466 return TCL_ERROR;
1467 }
1468 zSql = malloc( nByte + 50 + nCol*2 );
1469 if( zSql==0 ) {
1470 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1471 return TCL_ERROR;
1472 }
1473 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1474 zConflict, zTable);
drh4f21c4a2008-12-10 22:15:00 +00001475 j = strlen30(zSql);
drh19e2d372005-08-29 23:00:03 +00001476 for(i=1; i<nCol; i++){
1477 zSql[j++] = ',';
1478 zSql[j++] = '?';
1479 }
1480 zSql[j++] = ')';
1481 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00001482 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001483 free(zSql);
1484 if( rc ){
1485 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1486 sqlite3_finalize(pStmt);
1487 return TCL_ERROR;
1488 }
1489 in = fopen(zFile, "rb");
1490 if( in==0 ){
1491 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
1492 sqlite3_finalize(pStmt);
1493 return TCL_ERROR;
1494 }
1495 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1496 if( azCol==0 ) {
1497 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00001498 fclose(in);
drh19e2d372005-08-29 23:00:03 +00001499 return TCL_ERROR;
1500 }
drh37527852006-03-16 16:19:56 +00001501 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001502 zCommit = "COMMIT";
1503 while( (zLine = local_getline(0, in))!=0 ){
1504 char *z;
1505 i = 0;
1506 lineno++;
1507 azCol[0] = zLine;
1508 for(i=0, z=zLine; *z; z++){
1509 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
1510 *z = 0;
1511 i++;
1512 if( i<nCol ){
1513 azCol[i] = &z[nSep];
1514 z += nSep-1;
1515 }
1516 }
1517 }
1518 if( i+1!=nCol ){
1519 char *zErr;
drh4f21c4a2008-12-10 22:15:00 +00001520 int nErr = strlen30(zFile) + 200;
drh5bb3eb92007-05-04 13:15:55 +00001521 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00001522 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00001523 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00001524 "Error: %s line %d: expected %d columns of data but found %d",
1525 zFile, lineno, nCol, i+1);
1526 Tcl_AppendResult(interp, zErr, 0);
1527 free(zErr);
1528 }
drh19e2d372005-08-29 23:00:03 +00001529 zCommit = "ROLLBACK";
1530 break;
1531 }
1532 for(i=0; i<nCol; i++){
1533 /* check for null data, if so, bind as null */
drhea678832008-12-10 19:26:22 +00001534 if( (nNull>0 && strcmp(azCol[i], zNull)==0)
drh4f21c4a2008-12-10 22:15:00 +00001535 || strlen30(azCol[i])==0
drhea678832008-12-10 19:26:22 +00001536 ){
drh19e2d372005-08-29 23:00:03 +00001537 sqlite3_bind_null(pStmt, i+1);
1538 }else{
1539 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1540 }
1541 }
1542 sqlite3_step(pStmt);
1543 rc = sqlite3_reset(pStmt);
1544 free(zLine);
1545 if( rc!=SQLITE_OK ){
1546 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
1547 zCommit = "ROLLBACK";
1548 break;
1549 }
1550 }
1551 free(azCol);
1552 fclose(in);
1553 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00001554 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001555
1556 if( zCommit[0] == 'C' ){
1557 /* success, set result as number of lines processed */
1558 pResult = Tcl_GetObjResult(interp);
1559 Tcl_SetIntObj(pResult, lineno);
1560 rc = TCL_OK;
1561 }else{
1562 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00001563 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00001564 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
1565 rc = TCL_ERROR;
1566 }
1567 break;
1568 }
1569
drhdcd997e2003-01-31 17:21:49 +00001570 /*
drh41449052006-07-06 17:08:48 +00001571 ** $db enable_load_extension BOOLEAN
1572 **
1573 ** Turn the extension loading feature on or off. It if off by
1574 ** default.
1575 */
1576 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00001577#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00001578 int onoff;
1579 if( objc!=3 ){
1580 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
1581 return TCL_ERROR;
1582 }
1583 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
1584 return TCL_ERROR;
1585 }
1586 sqlite3_enable_load_extension(pDb->db, onoff);
1587 break;
drhf533acc2006-12-19 18:57:11 +00001588#else
1589 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
1590 0);
1591 return TCL_ERROR;
1592#endif
drh41449052006-07-06 17:08:48 +00001593 }
1594
1595 /*
drhdcd997e2003-01-31 17:21:49 +00001596 ** $db errorcode
1597 **
1598 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00001599 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00001600 */
1601 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00001602 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00001603 break;
1604 }
drh75897232000-05-29 14:26:00 +00001605
1606 /*
drh895d7472004-08-20 16:02:39 +00001607 ** $db eval $sql ?array? ?{ ...code... }?
drh1807ce32004-09-07 13:20:35 +00001608 ** $db onecolumn $sql
drh75897232000-05-29 14:26:00 +00001609 **
1610 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00001611 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00001612 ** If "array" and "code" are omitted, then no callback is every invoked.
1613 ** If "array" is an empty string, then the values are placed in variables
1614 ** that have the same name as the fields extracted by the query.
drh1807ce32004-09-07 13:20:35 +00001615 **
1616 ** The onecolumn method is the equivalent of:
1617 ** lindex [$db eval $sql] 0
drh75897232000-05-29 14:26:00 +00001618 */
drh1807ce32004-09-07 13:20:35 +00001619 case DB_ONECOLUMN:
drh97f2ebc2005-12-10 21:19:04 +00001620 case DB_EVAL:
1621 case DB_EXISTS: {
drh9d74b4c2004-08-24 15:23:34 +00001622 char const *zSql; /* Next SQL statement to execute */
1623 char const *zLeft; /* What is left after first stmt in zSql */
1624 sqlite3_stmt *pStmt; /* Compiled SQL statment */
drh92febd92004-08-20 18:34:20 +00001625 Tcl_Obj *pArray; /* Name of array into which results are written */
1626 Tcl_Obj *pScript; /* Script to run for each result set */
drh1d895032004-08-26 00:56:05 +00001627 Tcl_Obj **apParm; /* Parameters that need a Tcl_DecrRefCount() */
1628 int nParm; /* Number of entries used in apParm[] */
1629 Tcl_Obj *aParm[10]; /* Static space for apParm[] in the common case */
drh1807ce32004-09-07 13:20:35 +00001630 Tcl_Obj *pRet; /* Value to be returned */
drhfb7e7652005-01-24 00:28:42 +00001631 SqlPreparedStmt *pPreStmt; /* Pointer to a prepared statement */
1632 int rc2;
danielk1977ef2cb632004-05-29 02:37:19 +00001633
drh97f2ebc2005-12-10 21:19:04 +00001634 if( choice==DB_EVAL ){
drh1807ce32004-09-07 13:20:35 +00001635 if( objc<3 || objc>5 ){
1636 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
1637 return TCL_ERROR;
1638 }
1639 pRet = Tcl_NewObj();
1640 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001641 }else{
1642 if( objc!=3 ){
1643 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
1644 return TCL_ERROR;
1645 }
drh97f2ebc2005-12-10 21:19:04 +00001646 if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001647 pRet = Tcl_NewBooleanObj(0);
1648 Tcl_IncrRefCount(pRet);
1649 }else{
1650 pRet = 0;
drh97f2ebc2005-12-10 21:19:04 +00001651 }
danielk197730ccda12004-05-27 12:11:31 +00001652 }
drh92febd92004-08-20 18:34:20 +00001653 if( objc==3 ){
1654 pArray = pScript = 0;
1655 }else if( objc==4 ){
1656 pArray = 0;
1657 pScript = objv[3];
1658 }else{
1659 pArray = objv[3];
1660 if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
1661 pScript = objv[4];
1662 }
danielk197730ccda12004-05-27 12:11:31 +00001663
drh1d895032004-08-26 00:56:05 +00001664 Tcl_IncrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001665 zSql = Tcl_GetStringFromObj(objv[2], 0);
drh90b6bb12004-09-13 13:16:31 +00001666 while( rc==TCL_OK && zSql[0] ){
drhfb7e7652005-01-24 00:28:42 +00001667 int i; /* Loop counter */
1668 int nVar; /* Number of bind parameters in the pStmt */
danielk19778e556522007-11-13 10:30:24 +00001669 int nCol = -1; /* Number of columns in the result set */
drh92febd92004-08-20 18:34:20 +00001670 Tcl_Obj **apColName = 0; /* Array of column names */
drhfb7e7652005-01-24 00:28:42 +00001671 int len; /* String length of zSql */
danielk197730ccda12004-05-27 12:11:31 +00001672
drhfb7e7652005-01-24 00:28:42 +00001673 /* Try to find a SQL statement that has already been compiled and
1674 ** which matches the next sequence of SQL.
1675 */
1676 pStmt = 0;
drh4f21c4a2008-12-10 22:15:00 +00001677 len = strlen30(zSql);
danielk19778e556522007-11-13 10:30:24 +00001678 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
drhfb7e7652005-01-24 00:28:42 +00001679 int n = pPreStmt->nSql;
1680 if( len>=n
1681 && memcmp(pPreStmt->zSql, zSql, n)==0
1682 && (zSql[n]==0 || zSql[n-1]==';')
1683 ){
1684 pStmt = pPreStmt->pStmt;
1685 zLeft = &zSql[pPreStmt->nSql];
1686
1687 /* When a prepared statement is found, unlink it from the
1688 ** cache list. It will later be added back to the beginning
1689 ** of the cache list in order to implement LRU replacement.
1690 */
1691 if( pPreStmt->pPrev ){
1692 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1693 }else{
1694 pDb->stmtList = pPreStmt->pNext;
1695 }
1696 if( pPreStmt->pNext ){
1697 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1698 }else{
1699 pDb->stmtLast = pPreStmt->pPrev;
1700 }
1701 pDb->nStmt--;
1702 break;
1703 }
1704 }
1705
1706 /* If no prepared statement was found. Compile the SQL text
1707 */
drh92febd92004-08-20 18:34:20 +00001708 if( pStmt==0 ){
danielk19778e556522007-11-13 10:30:24 +00001709 if( SQLITE_OK!=sqlite3_prepare_v2(pDb->db, zSql, -1, &pStmt, &zLeft) ){
drh92febd92004-08-20 18:34:20 +00001710 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1711 rc = TCL_ERROR;
1712 break;
danielk197730ccda12004-05-27 12:11:31 +00001713 }
drhfb7e7652005-01-24 00:28:42 +00001714 if( pStmt==0 ){
1715 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1716 /* A compile-time error in the statement
1717 */
1718 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1719 rc = TCL_ERROR;
1720 break;
1721 }else{
1722 /* The statement was a no-op. Continue to the next statement
1723 ** in the SQL string.
1724 */
1725 zSql = zLeft;
1726 continue;
1727 }
1728 }
1729 assert( pPreStmt==0 );
danielk197730ccda12004-05-27 12:11:31 +00001730 }
1731
drhfb7e7652005-01-24 00:28:42 +00001732 /* Bind values to parameters that begin with $ or :
1733 */
drh92febd92004-08-20 18:34:20 +00001734 nVar = sqlite3_bind_parameter_count(pStmt);
drh1d895032004-08-26 00:56:05 +00001735 nParm = 0;
1736 if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
1737 apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
1738 }else{
1739 apParm = aParm;
1740 }
drh92febd92004-08-20 18:34:20 +00001741 for(i=1; i<=nVar; i++){
1742 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
drh4f5e80f2007-06-19 17:15:46 +00001743 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
drh92febd92004-08-20 18:34:20 +00001744 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1745 if( pVar ){
1746 int n;
1747 u8 *data;
1748 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
1749 char c = zType[0];
drh1c747812007-06-19 23:01:41 +00001750 if( zVar[0]=='@' ||
1751 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1752 /* Load a BLOB type if the Tcl variable is a bytearray and
1753 ** it has no string representation or the host
drh4f5e80f2007-06-19 17:15:46 +00001754 ** parameter name begins with "@". */
drh92febd92004-08-20 18:34:20 +00001755 data = Tcl_GetByteArrayFromObj(pVar, &n);
1756 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001757 Tcl_IncrRefCount(pVar);
1758 apParm[nParm++] = pVar;
drh985e0c62007-06-26 22:55:37 +00001759 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drh92febd92004-08-20 18:34:20 +00001760 Tcl_GetIntFromObj(interp, pVar, &n);
1761 sqlite3_bind_int(pStmt, i, n);
1762 }else if( c=='d' && strcmp(zType,"double")==0 ){
1763 double r;
1764 Tcl_GetDoubleFromObj(interp, pVar, &r);
1765 sqlite3_bind_double(pStmt, i, r);
drh985e0c62007-06-26 22:55:37 +00001766 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1767 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +00001768 Tcl_WideInt v;
1769 Tcl_GetWideIntFromObj(interp, pVar, &v);
1770 sqlite3_bind_int64(pStmt, i, v);
drh92febd92004-08-20 18:34:20 +00001771 }else{
danielk197700fd9572005-12-07 06:27:43 +00001772 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
drhb08c2a72008-04-16 00:28:13 +00001773 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001774 Tcl_IncrRefCount(pVar);
1775 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001776 }
drhfb7e7652005-01-24 00:28:42 +00001777 }else{
1778 sqlite3_bind_null( pStmt, i );
drh92febd92004-08-20 18:34:20 +00001779 }
1780 }
1781 }
drh92febd92004-08-20 18:34:20 +00001782
drh92febd92004-08-20 18:34:20 +00001783 /* Execute the SQL
1784 */
drh90b6bb12004-09-13 13:16:31 +00001785 while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
danielk19778e556522007-11-13 10:30:24 +00001786
1787 /* Compute column names. This must be done after the first successful
1788 ** call to sqlite3_step(), in case the query is recompiled and the
1789 ** number or names of the returned columns changes.
1790 */
1791 assert(!pArray||pScript);
1792 if (nCol < 0) {
1793 Tcl_Obj ***ap = (pScript?&apColName:0);
1794 nCol = computeColumnNames(interp, pStmt, ap, pArray);
1795 }
1796
drh92febd92004-08-20 18:34:20 +00001797 for(i=0; i<nCol; i++){
danielk197730ccda12004-05-27 12:11:31 +00001798 Tcl_Obj *pVal;
1799
1800 /* Set pVal to contain the i'th column of this row. */
drh92febd92004-08-20 18:34:20 +00001801 switch( sqlite3_column_type(pStmt, i) ){
1802 case SQLITE_BLOB: {
1803 int bytes = sqlite3_column_bytes(pStmt, i);
drheee4c8c2008-02-18 22:24:57 +00001804 const char *zBlob = sqlite3_column_blob(pStmt, i);
danielk1977a7a8e142008-02-13 18:25:27 +00001805 if( !zBlob ) bytes = 0;
drheee4c8c2008-02-18 22:24:57 +00001806 pVal = Tcl_NewByteArrayObj((u8*)zBlob, bytes);
drh92febd92004-08-20 18:34:20 +00001807 break;
1808 }
1809 case SQLITE_INTEGER: {
1810 sqlite_int64 v = sqlite3_column_int64(pStmt, i);
1811 if( v>=-2147483647 && v<=2147483647 ){
1812 pVal = Tcl_NewIntObj(v);
1813 }else{
1814 pVal = Tcl_NewWideIntObj(v);
1815 }
1816 break;
1817 }
1818 case SQLITE_FLOAT: {
1819 double r = sqlite3_column_double(pStmt, i);
1820 pVal = Tcl_NewDoubleObj(r);
1821 break;
1822 }
danielk197755c45f22005-04-03 23:54:43 +00001823 case SQLITE_NULL: {
1824 pVal = dbTextToObj(pDb->zNull);
1825 break;
1826 }
drh92febd92004-08-20 18:34:20 +00001827 default: {
danielk197700fd9572005-12-07 06:27:43 +00001828 pVal = dbTextToObj((char *)sqlite3_column_text(pStmt, i));
drh92febd92004-08-20 18:34:20 +00001829 break;
1830 }
danielk197730ccda12004-05-27 12:11:31 +00001831 }
1832
drh92febd92004-08-20 18:34:20 +00001833 if( pScript ){
1834 if( pArray==0 ){
1835 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001836 }else{
drh92febd92004-08-20 18:34:20 +00001837 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001838 }
drh1807ce32004-09-07 13:20:35 +00001839 }else if( choice==DB_ONECOLUMN ){
drh97f2ebc2005-12-10 21:19:04 +00001840 assert( pRet==0 );
drh1807ce32004-09-07 13:20:35 +00001841 if( pRet==0 ){
1842 pRet = pVal;
1843 Tcl_IncrRefCount(pRet);
1844 }
drh90b6bb12004-09-13 13:16:31 +00001845 rc = TCL_BREAK;
drh97f2ebc2005-12-10 21:19:04 +00001846 i = nCol;
1847 }else if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001848 Tcl_DecrRefCount(pRet);
1849 pRet = Tcl_NewBooleanObj(1);
1850 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001851 rc = TCL_BREAK;
1852 i = nCol;
danielk197730ccda12004-05-27 12:11:31 +00001853 }else{
danielk197730ccda12004-05-27 12:11:31 +00001854 Tcl_ListObjAppendElement(interp, pRet, pVal);
1855 }
1856 }
1857
drh92febd92004-08-20 18:34:20 +00001858 if( pScript ){
drhd1d38482008-10-07 23:46:38 +00001859 pDb->nStep = sqlite3_stmt_status(pStmt,
1860 SQLITE_STMTSTATUS_FULLSCAN_STEP, 0);
1861 pDb->nSort = sqlite3_stmt_status(pStmt,
1862 SQLITE_STMTSTATUS_SORT, 0);
drh92febd92004-08-20 18:34:20 +00001863 rc = Tcl_EvalObjEx(interp, pScript, 0);
drh90b6bb12004-09-13 13:16:31 +00001864 if( rc==TCL_CONTINUE ){
1865 rc = TCL_OK;
1866 }
danielk197730ccda12004-05-27 12:11:31 +00001867 }
1868 }
drh90b6bb12004-09-13 13:16:31 +00001869 if( rc==TCL_BREAK ){
1870 rc = TCL_OK;
1871 }
drh92febd92004-08-20 18:34:20 +00001872
1873 /* Free the column name objects */
1874 if( pScript ){
danielk19778e556522007-11-13 10:30:24 +00001875 /* If the query returned no rows, but an array variable was
1876 ** specified, call computeColumnNames() now to populate the
1877 ** arrayname(*) variable.
1878 */
1879 if (pArray && nCol < 0) {
1880 Tcl_Obj ***ap = (pScript?&apColName:0);
1881 nCol = computeColumnNames(interp, pStmt, ap, pArray);
1882 }
drh92febd92004-08-20 18:34:20 +00001883 for(i=0; i<nCol; i++){
1884 Tcl_DecrRefCount(apColName[i]);
1885 }
1886 Tcl_Free((char*)apColName);
1887 }
1888
drh1d895032004-08-26 00:56:05 +00001889 /* Free the bound string and blob parameters */
1890 for(i=0; i<nParm; i++){
1891 Tcl_DecrRefCount(apParm[i]);
1892 }
1893 if( apParm!=aParm ){
1894 Tcl_Free((char*)apParm);
1895 }
1896
drhfb7e7652005-01-24 00:28:42 +00001897 /* Reset the statement. If the result code is SQLITE_SCHEMA, then
1898 ** flush the statement cache and try the statement again.
drh92febd92004-08-20 18:34:20 +00001899 */
drhfb7e7652005-01-24 00:28:42 +00001900 rc2 = sqlite3_reset(pStmt);
drhd1d38482008-10-07 23:46:38 +00001901 pDb->nStep = sqlite3_stmt_status(pStmt,
1902 SQLITE_STMTSTATUS_FULLSCAN_STEP, 1);
1903 pDb->nSort = sqlite3_stmt_status(pStmt,
1904 SQLITE_STMTSTATUS_SORT, 1);
danielk19778e556522007-11-13 10:30:24 +00001905 if( SQLITE_OK!=rc2 ){
drhfb7e7652005-01-24 00:28:42 +00001906 /* If a run-time error occurs, report the error and stop reading
1907 ** the SQL
1908 */
danielk1977ef2cb632004-05-29 02:37:19 +00001909 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
drhfb7e7652005-01-24 00:28:42 +00001910 sqlite3_finalize(pStmt);
danielk197730ccda12004-05-27 12:11:31 +00001911 rc = TCL_ERROR;
drhfb7e7652005-01-24 00:28:42 +00001912 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001913 break;
drhfb7e7652005-01-24 00:28:42 +00001914 }else if( pDb->maxStmt<=0 ){
1915 /* If the cache is turned off, deallocated the statement */
1916 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1917 sqlite3_finalize(pStmt);
1918 }else{
1919 /* Everything worked and the cache is operational.
1920 ** Create a new SqlPreparedStmt structure if we need one.
1921 ** (If we already have one we can just reuse it.)
1922 */
1923 if( pPreStmt==0 ){
1924 len = zLeft - zSql;
danielk1977d0e2a852007-11-14 06:48:48 +00001925 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) );
drhfb7e7652005-01-24 00:28:42 +00001926 if( pPreStmt==0 ) return TCL_ERROR;
1927 pPreStmt->pStmt = pStmt;
1928 pPreStmt->nSql = len;
danielk1977d0e2a852007-11-14 06:48:48 +00001929 pPreStmt->zSql = sqlite3_sql(pStmt);
drh4f21c4a2008-12-10 22:15:00 +00001930 assert( strlen30(pPreStmt->zSql)==len );
danielk1977d0e2a852007-11-14 06:48:48 +00001931 assert( 0==memcmp(pPreStmt->zSql, zSql, len) );
drhfb7e7652005-01-24 00:28:42 +00001932 }
1933
1934 /* Add the prepared statement to the beginning of the cache list
1935 */
1936 pPreStmt->pNext = pDb->stmtList;
1937 pPreStmt->pPrev = 0;
1938 if( pDb->stmtList ){
1939 pDb->stmtList->pPrev = pPreStmt;
1940 }
1941 pDb->stmtList = pPreStmt;
1942 if( pDb->stmtLast==0 ){
1943 assert( pDb->nStmt==0 );
1944 pDb->stmtLast = pPreStmt;
1945 }else{
1946 assert( pDb->nStmt>0 );
1947 }
1948 pDb->nStmt++;
1949
1950 /* If we have too many statement in cache, remove the surplus from the
1951 ** end of the cache list.
1952 */
1953 while( pDb->nStmt>pDb->maxStmt ){
1954 sqlite3_finalize(pDb->stmtLast->pStmt);
1955 pDb->stmtLast = pDb->stmtLast->pPrev;
1956 Tcl_Free((char*)pDb->stmtLast->pNext);
1957 pDb->stmtLast->pNext = 0;
1958 pDb->nStmt--;
1959 }
danielk197730ccda12004-05-27 12:11:31 +00001960 }
1961
drhfb7e7652005-01-24 00:28:42 +00001962 /* Proceed to the next statement */
danielk197730ccda12004-05-27 12:11:31 +00001963 zSql = zLeft;
1964 }
drh1d895032004-08-26 00:56:05 +00001965 Tcl_DecrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001966
drh1807ce32004-09-07 13:20:35 +00001967 if( pRet ){
1968 if( rc==TCL_OK ){
1969 Tcl_SetObjResult(interp, pRet);
1970 }
1971 Tcl_DecrRefCount(pRet);
drh050be322006-07-12 00:18:40 +00001972 }else if( rc==TCL_OK ){
1973 Tcl_ResetResult(interp);
danielk197730ccda12004-05-27 12:11:31 +00001974 }
danielk197730ccda12004-05-27 12:11:31 +00001975 break;
1976 }
drhbec3f402000-08-04 13:49:02 +00001977
1978 /*
drhe3602be2008-09-09 12:31:33 +00001979 ** $db function NAME [-argcount N] SCRIPT
drhcabb0812002-09-14 13:47:32 +00001980 **
1981 ** Create a new SQL function called NAME. Whenever that function is
1982 ** called, invoke SCRIPT to evaluate the function.
1983 */
1984 case DB_FUNCTION: {
1985 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00001986 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00001987 char *zName;
drhe3602be2008-09-09 12:31:33 +00001988 int nArg = -1;
1989 if( objc==6 ){
1990 const char *z = Tcl_GetString(objv[3]);
drh4f21c4a2008-12-10 22:15:00 +00001991 int n = strlen30(z);
drhe3602be2008-09-09 12:31:33 +00001992 if( n>2 && strncmp(z, "-argcount",n)==0 ){
1993 if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
1994 if( nArg<0 ){
1995 Tcl_AppendResult(interp, "number of arguments must be non-negative",
1996 (char*)0);
1997 return TCL_ERROR;
1998 }
1999 }
2000 pScript = objv[5];
2001 }else if( objc!=4 ){
2002 Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
drhcabb0812002-09-14 13:47:32 +00002003 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00002004 }else{
2005 pScript = objv[3];
drhcabb0812002-09-14 13:47:32 +00002006 }
2007 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00002008 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00002009 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00002010 if( pFunc->pScript ){
2011 Tcl_DecrRefCount(pFunc->pScript);
2012 }
2013 pFunc->pScript = pScript;
2014 Tcl_IncrRefCount(pScript);
2015 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
drhe3602be2008-09-09 12:31:33 +00002016 rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00002017 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00002018 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00002019 rc = TCL_ERROR;
2020 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00002021 }
drhcabb0812002-09-14 13:47:32 +00002022 break;
2023 }
2024
2025 /*
danielk19778cbadb02007-05-03 16:31:26 +00002026 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00002027 */
2028 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00002029#ifdef SQLITE_OMIT_INCRBLOB
2030 Tcl_AppendResult(interp, "incrblob not available in this build", 0);
2031 return TCL_ERROR;
2032#else
danielk19778cbadb02007-05-03 16:31:26 +00002033 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00002034 const char *zDb = "main";
2035 const char *zTable;
2036 const char *zColumn;
2037 sqlite_int64 iRow;
2038
danielk19778cbadb02007-05-03 16:31:26 +00002039 /* Check for the -readonly option */
2040 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2041 isReadonly = 1;
2042 }
2043
2044 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2045 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00002046 return TCL_ERROR;
2047 }
2048
danielk19778cbadb02007-05-03 16:31:26 +00002049 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00002050 zDb = Tcl_GetString(objv[2]);
2051 }
2052 zTable = Tcl_GetString(objv[objc-3]);
2053 zColumn = Tcl_GetString(objv[objc-2]);
2054 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2055
2056 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00002057 rc = createIncrblobChannel(
2058 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
2059 );
danielk1977b4e9af92007-05-01 17:49:49 +00002060 }
danielk197732a0d8b2007-05-04 19:03:02 +00002061#endif
danielk1977b4e9af92007-05-01 17:49:49 +00002062 break;
2063 }
2064
2065 /*
drhf11bded2006-07-17 00:02:44 +00002066 ** $db interrupt
2067 **
2068 ** Interrupt the execution of the inner-most SQL interpreter. This
2069 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2070 */
2071 case DB_INTERRUPT: {
2072 sqlite3_interrupt(pDb->db);
2073 break;
2074 }
2075
2076 /*
drh19e2d372005-08-29 23:00:03 +00002077 ** $db nullvalue ?STRING?
2078 **
2079 ** Change text used when a NULL comes back from the database. If ?STRING?
2080 ** is not present, then the current string used for NULL is returned.
2081 ** If STRING is present, then STRING is returned.
2082 **
2083 */
2084 case DB_NULLVALUE: {
2085 if( objc!=2 && objc!=3 ){
2086 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2087 return TCL_ERROR;
2088 }
2089 if( objc==3 ){
2090 int len;
2091 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2092 if( pDb->zNull ){
2093 Tcl_Free(pDb->zNull);
2094 }
2095 if( zNull && len>0 ){
2096 pDb->zNull = Tcl_Alloc( len + 1 );
2097 strncpy(pDb->zNull, zNull, len);
2098 pDb->zNull[len] = '\0';
2099 }else{
2100 pDb->zNull = 0;
2101 }
2102 }
2103 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
2104 break;
2105 }
2106
2107 /*
drhaf9ff332002-01-16 21:00:27 +00002108 ** $db last_insert_rowid
2109 **
2110 ** Return an integer which is the ROWID for the most recent insert.
2111 */
2112 case DB_LAST_INSERT_ROWID: {
2113 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002114 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002115 if( objc!=2 ){
2116 Tcl_WrongNumArgs(interp, 2, objv, "");
2117 return TCL_ERROR;
2118 }
danielk19776f8a5032004-05-10 10:34:51 +00002119 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002120 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002121 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002122 break;
2123 }
2124
2125 /*
drh1807ce32004-09-07 13:20:35 +00002126 ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
drh5d9d7572003-08-19 14:31:01 +00002127 */
drh1807ce32004-09-07 13:20:35 +00002128
2129 /* $db progress ?N CALLBACK?
2130 **
2131 ** Invoke the given callback every N virtual machine opcodes while executing
2132 ** queries.
2133 */
2134 case DB_PROGRESS: {
2135 if( objc==2 ){
2136 if( pDb->zProgress ){
2137 Tcl_AppendResult(interp, pDb->zProgress, 0);
2138 }
2139 }else if( objc==4 ){
2140 char *zProgress;
2141 int len;
2142 int N;
2143 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002144 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002145 };
2146 if( pDb->zProgress ){
2147 Tcl_Free(pDb->zProgress);
2148 }
2149 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2150 if( zProgress && len>0 ){
2151 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002152 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002153 }else{
2154 pDb->zProgress = 0;
2155 }
2156#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2157 if( pDb->zProgress ){
2158 pDb->interp = interp;
2159 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2160 }else{
2161 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2162 }
2163#endif
2164 }else{
2165 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002166 return TCL_ERROR;
2167 }
drh5d9d7572003-08-19 14:31:01 +00002168 break;
2169 }
2170
drh19e2d372005-08-29 23:00:03 +00002171 /* $db profile ?CALLBACK?
2172 **
2173 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2174 ** that has run. The text of the SQL and the amount of elapse time are
2175 ** appended to CALLBACK before the script is run.
2176 */
2177 case DB_PROFILE: {
2178 if( objc>3 ){
2179 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2180 return TCL_ERROR;
2181 }else if( objc==2 ){
2182 if( pDb->zProfile ){
2183 Tcl_AppendResult(interp, pDb->zProfile, 0);
2184 }
2185 }else{
2186 char *zProfile;
2187 int len;
2188 if( pDb->zProfile ){
2189 Tcl_Free(pDb->zProfile);
2190 }
2191 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2192 if( zProfile && len>0 ){
2193 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002194 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002195 }else{
2196 pDb->zProfile = 0;
2197 }
2198#ifndef SQLITE_OMIT_TRACE
2199 if( pDb->zProfile ){
2200 pDb->interp = interp;
2201 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2202 }else{
2203 sqlite3_profile(pDb->db, 0, 0);
2204 }
2205#endif
2206 }
2207 break;
2208 }
2209
drh5d9d7572003-08-19 14:31:01 +00002210 /*
drh22fbcb82004-02-01 01:22:50 +00002211 ** $db rekey KEY
2212 **
2213 ** Change the encryption key on the currently open database.
2214 */
2215 case DB_REKEY: {
2216 int nKey;
2217 void *pKey;
2218 if( objc!=3 ){
2219 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2220 return TCL_ERROR;
2221 }
2222 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00002223#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00002224 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002225 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00002226 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002227 rc = TCL_ERROR;
2228 }
2229#endif
2230 break;
2231 }
2232
drhdc2c4912009-02-04 22:46:47 +00002233 /* $db restore ?DATABASE? FILENAME
2234 **
2235 ** Open a database file named FILENAME. Transfer the content
2236 ** of FILENAME into the local database DATABASE (default: "main").
2237 */
2238 case DB_RESTORE: {
2239 const char *zSrcFile;
2240 const char *zDestDb;
2241 sqlite3 *pSrc;
2242 sqlite3_backup *pBackup;
2243 int nTimeout = 0;
2244
2245 if( objc==3 ){
2246 zDestDb = "main";
2247 zSrcFile = Tcl_GetString(objv[2]);
2248 }else if( objc==4 ){
2249 zDestDb = Tcl_GetString(objv[2]);
2250 zSrcFile = Tcl_GetString(objv[3]);
2251 }else{
2252 Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2253 return TCL_ERROR;
2254 }
2255 rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
2256 if( rc!=SQLITE_OK ){
2257 Tcl_AppendResult(interp, "cannot open source database: ",
2258 sqlite3_errmsg(pSrc), (char*)0);
2259 sqlite3_close(pSrc);
2260 return TCL_ERROR;
2261 }
2262 pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2263 if( pBackup==0 ){
2264 Tcl_AppendResult(interp, "restore failed: ",
2265 sqlite3_errmsg(pDb->db), (char*)0);
2266 sqlite3_close(pSrc);
2267 return TCL_ERROR;
2268 }
2269 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2270 || rc==SQLITE_BUSY ){
2271 if( rc==SQLITE_BUSY ){
2272 if( nTimeout++ >= 3 ) break;
2273 sqlite3_sleep(100);
2274 }
2275 }
2276 sqlite3_backup_finish(pBackup);
2277 if( rc==SQLITE_DONE ){
2278 rc = TCL_OK;
2279 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2280 Tcl_AppendResult(interp, "restore failed: source database busy",
2281 (char*)0);
2282 rc = TCL_ERROR;
2283 }else{
2284 Tcl_AppendResult(interp, "restore failed: ",
2285 sqlite3_errmsg(pDb->db), (char*)0);
2286 rc = TCL_ERROR;
2287 }
2288 sqlite3_close(pSrc);
2289 break;
2290 }
2291
drh22fbcb82004-02-01 01:22:50 +00002292 /*
drhd1d38482008-10-07 23:46:38 +00002293 ** $db status (step|sort)
2294 **
2295 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2296 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2297 */
2298 case DB_STATUS: {
drhd1d38482008-10-07 23:46:38 +00002299 int v;
2300 const char *zOp;
2301 if( objc!=3 ){
2302 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort)");
2303 return TCL_ERROR;
2304 }
2305 zOp = Tcl_GetString(objv[2]);
2306 if( strcmp(zOp, "step")==0 ){
2307 v = pDb->nStep;
2308 }else if( strcmp(zOp, "sort")==0 ){
2309 v = pDb->nSort;
2310 }else{
2311 Tcl_AppendResult(interp, "bad argument: should be step or sort",
2312 (char*)0);
2313 return TCL_ERROR;
2314 }
2315 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2316 break;
2317 }
2318
2319 /*
drhbec3f402000-08-04 13:49:02 +00002320 ** $db timeout MILLESECONDS
2321 **
2322 ** Delay for the number of milliseconds specified when a file is locked.
2323 */
drh6d313162000-09-21 13:01:35 +00002324 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002325 int ms;
drh6d313162000-09-21 13:01:35 +00002326 if( objc!=3 ){
2327 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002328 return TCL_ERROR;
2329 }
drh6d313162000-09-21 13:01:35 +00002330 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002331 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002332 break;
drh75897232000-05-29 14:26:00 +00002333 }
danielk197755c45f22005-04-03 23:54:43 +00002334
2335 /*
drh0f14e2e2004-06-29 12:39:08 +00002336 ** $db total_changes
2337 **
2338 ** Return the number of rows that were modified, inserted, or deleted
2339 ** since the database handle was created.
2340 */
2341 case DB_TOTAL_CHANGES: {
2342 Tcl_Obj *pResult;
2343 if( objc!=2 ){
2344 Tcl_WrongNumArgs(interp, 2, objv, "");
2345 return TCL_ERROR;
2346 }
2347 pResult = Tcl_GetObjResult(interp);
2348 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2349 break;
2350 }
2351
drhb5a20d32003-04-23 12:25:23 +00002352 /* $db trace ?CALLBACK?
2353 **
2354 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2355 ** that is executed. The text of the SQL is appended to CALLBACK before
2356 ** it is executed.
2357 */
2358 case DB_TRACE: {
2359 if( objc>3 ){
2360 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002361 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002362 }else if( objc==2 ){
2363 if( pDb->zTrace ){
2364 Tcl_AppendResult(interp, pDb->zTrace, 0);
2365 }
2366 }else{
2367 char *zTrace;
2368 int len;
2369 if( pDb->zTrace ){
2370 Tcl_Free(pDb->zTrace);
2371 }
2372 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2373 if( zTrace && len>0 ){
2374 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002375 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002376 }else{
2377 pDb->zTrace = 0;
2378 }
drh19e2d372005-08-29 23:00:03 +00002379#ifndef SQLITE_OMIT_TRACE
drhb5a20d32003-04-23 12:25:23 +00002380 if( pDb->zTrace ){
2381 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002382 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002383 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002384 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002385 }
drh19e2d372005-08-29 23:00:03 +00002386#endif
drhb5a20d32003-04-23 12:25:23 +00002387 }
2388 break;
2389 }
2390
drh3d214232005-08-02 12:21:08 +00002391 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2392 **
2393 ** Start a new transaction (if we are not already in the midst of a
2394 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2395 ** completes, either commit the transaction or roll it back if SCRIPT
2396 ** throws an exception. Or if no new transation was started, do nothing.
2397 ** pass the exception on up the stack.
2398 **
2399 ** This command was inspired by Dave Thomas's talk on Ruby at the
2400 ** 2005 O'Reilly Open Source Convention (OSCON).
2401 */
2402 case DB_TRANSACTION: {
drh3d214232005-08-02 12:21:08 +00002403 Tcl_Obj *pScript;
danielk1977cd38d522009-01-02 17:33:46 +00002404 const char *zBegin = "SAVEPOINT _tcl_transaction";
2405 const char *zEnd;
drh3d214232005-08-02 12:21:08 +00002406 if( objc!=3 && objc!=4 ){
2407 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2408 return TCL_ERROR;
2409 }
danielk1977cd38d522009-01-02 17:33:46 +00002410
2411 if( pDb->nTransaction ){
2412 zBegin = "SAVEPOINT _tcl_transaction";
2413 }else if( pDb->nTransaction==0 && objc==4 ){
drh3d214232005-08-02 12:21:08 +00002414 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002415 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002416 };
2417 enum TTYPE_enum {
2418 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2419 };
2420 int ttype;
drhb5555e72005-08-02 17:15:14 +00002421 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002422 0, &ttype) ){
2423 return TCL_ERROR;
2424 }
2425 switch( (enum TTYPE_enum)ttype ){
2426 case TTYPE_DEFERRED: /* no-op */; break;
2427 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2428 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2429 }
drh3d214232005-08-02 12:21:08 +00002430 }
danielk1977cd38d522009-01-02 17:33:46 +00002431 pScript = objv[objc-1];
2432
2433 pDb->disableAuth++;
2434 rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2435 pDb->disableAuth--;
2436 if( rc!=SQLITE_OK ){
2437 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2438 return TCL_ERROR;
drh3d214232005-08-02 12:21:08 +00002439 }
danielk1977cd38d522009-01-02 17:33:46 +00002440
2441 pDb->nTransaction++;
drh3d214232005-08-02 12:21:08 +00002442 rc = Tcl_EvalObjEx(interp, pScript, 0);
danielk1977cd38d522009-01-02 17:33:46 +00002443 pDb->nTransaction--;
2444
2445 if( rc!=TCL_ERROR ){
2446 if( pDb->nTransaction ){
2447 zEnd = "RELEASE _tcl_transaction";
2448 }else{
drh3d214232005-08-02 12:21:08 +00002449 zEnd = "COMMIT";
2450 }
danielk1977cd38d522009-01-02 17:33:46 +00002451 }else{
2452 if( pDb->nTransaction ){
2453 zEnd = "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction";
2454 }else{
2455 zEnd = "ROLLBACK";
drh109b4352007-06-12 18:50:13 +00002456 }
drh3d214232005-08-02 12:21:08 +00002457 }
danielk1977cd38d522009-01-02 17:33:46 +00002458
2459 pDb->disableAuth++;
2460 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
2461 /* This is a tricky scenario to handle. The most likely cause of an
2462 ** error is that the exec() above was an attempt to commit the
2463 ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
2464 ** that an IO-error has occured. In either case, throw a Tcl exception
2465 ** and try to rollback the transaction.
2466 **
2467 ** But it could also be that the user executed one or more BEGIN,
2468 ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
2469 ** this method's logic. Not clear how this would be best handled.
2470 */
2471 if( rc!=TCL_ERROR ){
2472 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2473 rc = TCL_ERROR;
2474 }
2475 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
2476 }
2477 pDb->disableAuth--;
2478
drh3d214232005-08-02 12:21:08 +00002479 break;
2480 }
2481
danielk197794eb6a12005-12-15 15:22:08 +00002482 /*
danielk1977404ca072009-03-16 13:19:36 +00002483 ** $db unlock_notify ?script?
2484 */
2485 case DB_UNLOCK_NOTIFY: {
2486#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2487 Tcl_AppendResult(interp, "unlock_notify not available in this build", 0);
2488 rc = TCL_ERROR;
2489#else
2490 if( objc!=2 && objc!=3 ){
2491 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2492 rc = TCL_ERROR;
2493 }else{
2494 void (*xNotify)(void **, int) = 0;
2495 void *pNotifyArg = 0;
2496
2497 if( pDb->pUnlockNotify ){
2498 Tcl_DecrRefCount(pDb->pUnlockNotify);
2499 pDb->pUnlockNotify = 0;
2500 }
2501
2502 if( objc==3 ){
2503 xNotify = DbUnlockNotify;
2504 pNotifyArg = (void *)pDb;
2505 pDb->pUnlockNotify = objv[2];
2506 Tcl_IncrRefCount(pDb->pUnlockNotify);
2507 }
2508
2509 if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
2510 Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2511 rc = TCL_ERROR;
2512 }
2513 }
2514#endif
2515 break;
2516 }
2517
2518 /*
danielk197794eb6a12005-12-15 15:22:08 +00002519 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002520 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002521 */
danielk197771fd80b2005-12-16 06:54:01 +00002522 case DB_UPDATE_HOOK:
2523 case DB_ROLLBACK_HOOK: {
2524
2525 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2526 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2527 */
2528 Tcl_Obj **ppHook;
2529 if( choice==DB_UPDATE_HOOK ){
2530 ppHook = &pDb->pUpdateHook;
2531 }else{
2532 ppHook = &pDb->pRollbackHook;
2533 }
2534
danielk197794eb6a12005-12-15 15:22:08 +00002535 if( objc!=2 && objc!=3 ){
2536 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2537 return TCL_ERROR;
2538 }
danielk197771fd80b2005-12-16 06:54:01 +00002539 if( *ppHook ){
2540 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002541 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002542 Tcl_DecrRefCount(*ppHook);
2543 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00002544 }
2545 }
2546 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002547 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00002548 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00002549 *ppHook = objv[2];
2550 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002551 }
2552 }
danielk197771fd80b2005-12-16 06:54:01 +00002553
2554 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2555 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
2556
danielk197794eb6a12005-12-15 15:22:08 +00002557 break;
2558 }
2559
danielk19774397de52005-01-12 12:44:03 +00002560 /* $db version
2561 **
2562 ** Return the version string for this database.
2563 */
2564 case DB_VERSION: {
2565 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2566 break;
2567 }
2568
tpoindex1067fe12004-12-17 15:41:11 +00002569
drh6d313162000-09-21 13:01:35 +00002570 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002571 return rc;
drh75897232000-05-29 14:26:00 +00002572}
2573
2574/*
drh3570ad92007-08-31 14:31:44 +00002575** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00002576** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00002577**
2578** This is the main Tcl command. When the "sqlite" Tcl command is
2579** invoked, this routine runs to process that command.
2580**
2581** The first argument, DBNAME, is an arbitrary name for a new
2582** database connection. This command creates a new command named
2583** DBNAME that is used to control that connection. The database
2584** connection is deleted when the DBNAME command is deleted.
2585**
drh3570ad92007-08-31 14:31:44 +00002586** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00002587**
drh75897232000-05-29 14:26:00 +00002588*/
drh22fbcb82004-02-01 01:22:50 +00002589static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002590 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002591 void *pKey = 0;
2592 int nKey = 0;
2593 const char *zArg;
drh75897232000-05-29 14:26:00 +00002594 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00002595 int i;
drh22fbcb82004-02-01 01:22:50 +00002596 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00002597 const char *zVfs = 0;
drhd9da78a2009-03-24 15:08:09 +00002598 int flags;
drh882e8e42006-08-24 02:42:27 +00002599 Tcl_DString translatedFilename;
drhd9da78a2009-03-24 15:08:09 +00002600
2601 /* In normal use, each TCL interpreter runs in a single thread. So
2602 ** by default, we can turn of mutexing on SQLite database connections.
2603 ** However, for testing purposes it is useful to have mutexes turned
2604 ** on. So, by default, mutexes default off. But if compiled with
2605 ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
2606 */
2607#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
2608 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
2609#else
2610 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
2611#endif
2612
drh22fbcb82004-02-01 01:22:50 +00002613 if( objc==2 ){
2614 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002615 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00002616 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00002617 return TCL_OK;
2618 }
drh9eb9e262004-02-11 02:18:05 +00002619 if( strcmp(zArg,"-has-codec")==0 ){
2620#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002621 Tcl_AppendResult(interp,"1",0);
2622#else
2623 Tcl_AppendResult(interp,"0",0);
2624#endif
2625 return TCL_OK;
2626 }
drhfbc3eab2001-04-06 16:13:42 +00002627 }
drh3570ad92007-08-31 14:31:44 +00002628 for(i=3; i+1<objc; i+=2){
2629 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00002630 if( strcmp(zArg,"-key")==0 ){
drh3570ad92007-08-31 14:31:44 +00002631 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
2632 }else if( strcmp(zArg, "-vfs")==0 ){
2633 i++;
2634 zVfs = Tcl_GetString(objv[i]);
2635 }else if( strcmp(zArg, "-readonly")==0 ){
2636 int b;
2637 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2638 if( b ){
drh33f4e022007-09-03 15:19:34 +00002639 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00002640 flags |= SQLITE_OPEN_READONLY;
2641 }else{
2642 flags &= ~SQLITE_OPEN_READONLY;
2643 flags |= SQLITE_OPEN_READWRITE;
2644 }
2645 }else if( strcmp(zArg, "-create")==0 ){
2646 int b;
2647 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00002648 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00002649 flags |= SQLITE_OPEN_CREATE;
2650 }else{
2651 flags &= ~SQLITE_OPEN_CREATE;
2652 }
danielk19779a6284c2008-07-10 17:52:49 +00002653 }else if( strcmp(zArg, "-nomutex")==0 ){
2654 int b;
2655 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2656 if( b ){
2657 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00002658 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00002659 }else{
2660 flags &= ~SQLITE_OPEN_NOMUTEX;
2661 }
drh039963a2008-09-03 00:43:15 +00002662 }else if( strcmp(zArg, "-fullmutex")==0 ){
2663 int b;
2664 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2665 if( b ){
2666 flags |= SQLITE_OPEN_FULLMUTEX;
2667 flags &= ~SQLITE_OPEN_NOMUTEX;
2668 }else{
2669 flags &= ~SQLITE_OPEN_FULLMUTEX;
2670 }
drh3570ad92007-08-31 14:31:44 +00002671 }else{
2672 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
2673 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00002674 }
2675 }
drh3570ad92007-08-31 14:31:44 +00002676 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00002677 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00002678 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh039963a2008-09-03 00:43:15 +00002679 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN?"
drh9eb9e262004-02-11 02:18:05 +00002680#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00002681 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00002682#endif
2683 );
drh75897232000-05-29 14:26:00 +00002684 return TCL_ERROR;
2685 }
drh75897232000-05-29 14:26:00 +00002686 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00002687 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00002688 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00002689 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
2690 return TCL_ERROR;
2691 }
2692 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00002693 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00002694 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
drh3570ad92007-08-31 14:31:44 +00002695 sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00002696 Tcl_DStringFree(&translatedFilename);
danielk197780290862004-05-22 09:21:21 +00002697 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
drh9404d502006-12-19 18:46:08 +00002698 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
danielk197780290862004-05-22 09:21:21 +00002699 sqlite3_close(p->db);
2700 p->db = 0;
2701 }
drh2011d5f2004-07-22 02:40:37 +00002702#ifdef SQLITE_HAS_CODEC
drhf3a65f72007-08-22 20:18:21 +00002703 if( p->db ){
2704 sqlite3_key(p->db, pKey, nKey);
2705 }
drheb8ed702004-02-11 10:37:23 +00002706#endif
drhbec3f402000-08-04 13:49:02 +00002707 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00002708 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00002709 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00002710 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00002711 return TCL_ERROR;
2712 }
drhfb7e7652005-01-24 00:28:42 +00002713 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00002714 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00002715 zArg = Tcl_GetStringFromObj(objv[1], 0);
2716 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
drh75897232000-05-29 14:26:00 +00002717 return TCL_OK;
2718}
2719
2720/*
drh90ca9752001-09-28 17:47:14 +00002721** Provide a dummy Tcl_InitStubs if we are using this as a static
2722** library.
2723*/
2724#ifndef USE_TCL_STUBS
2725# undef Tcl_InitStubs
2726# define Tcl_InitStubs(a,b,c)
2727#endif
2728
2729/*
drh29bc4612005-10-05 10:40:15 +00002730** Make sure we have a PACKAGE_VERSION macro defined. This will be
2731** defined automatically by the TEA makefile. But other makefiles
2732** do not define it.
2733*/
2734#ifndef PACKAGE_VERSION
2735# define PACKAGE_VERSION SQLITE_VERSION
2736#endif
2737
2738/*
drh75897232000-05-29 14:26:00 +00002739** Initialize this module.
2740**
2741** This Tcl module contains only a single new Tcl command named "sqlite".
2742** (Hence there is no namespace. There is no point in using a namespace
2743** if the extension only supplies one new name!) The "sqlite" command is
2744** used to open a new SQLite database. See the DbMain() routine above
2745** for additional information.
2746*/
drhad6e1372006-07-10 21:15:51 +00002747EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00002748 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00002749 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002750 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh49766d62005-01-08 18:42:28 +00002751 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002752 Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
drh90ca9752001-09-28 17:47:14 +00002753 return TCL_OK;
2754}
drhad6e1372006-07-10 21:15:51 +00002755EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2756EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2757EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00002758EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2759EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2760EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2761EXTERN int Tclsqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
2762
drh49766d62005-01-08 18:42:28 +00002763
2764#ifndef SQLITE_3_SUFFIX_ONLY
drhad6e1372006-07-10 21:15:51 +00002765EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2766EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2767EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2768EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00002769EXTERN int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2770EXTERN int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2771EXTERN int Sqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2772EXTERN int Tclsqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
drh49766d62005-01-08 18:42:28 +00002773#endif
drh75897232000-05-29 14:26:00 +00002774
drh3e27c022004-07-23 00:01:38 +00002775#ifdef TCLSH
2776/*****************************************************************************
2777** The code that follows is used to build standalone TCL interpreters
drh3570ad92007-08-31 14:31:44 +00002778** that are statically linked with SQLite.
drh75897232000-05-29 14:26:00 +00002779*/
drh348784e2000-05-29 20:41:49 +00002780
2781/*
drh3e27c022004-07-23 00:01:38 +00002782** If the macro TCLSH is one, then put in code this for the
2783** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00002784** standard input, or if a file is named on the command line
2785** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00002786*/
drh3e27c022004-07-23 00:01:38 +00002787#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00002788static char zMainloop[] =
2789 "set line {}\n"
2790 "while {![eof stdin]} {\n"
2791 "if {$line!=\"\"} {\n"
2792 "puts -nonewline \"> \"\n"
2793 "} else {\n"
2794 "puts -nonewline \"% \"\n"
2795 "}\n"
2796 "flush stdout\n"
2797 "append line [gets stdin]\n"
2798 "if {[info complete $line]} {\n"
2799 "if {[catch {uplevel #0 $line} result]} {\n"
2800 "puts stderr \"Error: $result\"\n"
2801 "} elseif {$result!=\"\"} {\n"
2802 "puts $result\n"
2803 "}\n"
2804 "set line {}\n"
2805 "} else {\n"
2806 "append line \\n\n"
2807 "}\n"
2808 "}\n"
2809;
drh3e27c022004-07-23 00:01:38 +00002810#endif
2811
2812/*
2813** If the macro TCLSH is two, then get the main loop code out of
2814** the separate file "spaceanal_tcl.h".
2815*/
2816#if TCLSH==2
2817static char zMainloop[] =
2818#include "spaceanal_tcl.h"
2819;
2820#endif
drh348784e2000-05-29 20:41:49 +00002821
2822#define TCLSH_MAIN main /* Needed to fake out mktclapp */
2823int TCLSH_MAIN(int argc, char **argv){
2824 Tcl_Interp *interp;
danielk19770a549072009-02-17 16:29:10 +00002825
2826 /* Call sqlite3_shutdown() once before doing anything else. This is to
2827 ** test that sqlite3_shutdown() can be safely called by a process before
2828 ** sqlite3_initialize() is. */
2829 sqlite3_shutdown();
2830
drh297ecf12001-04-05 15:57:13 +00002831 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00002832 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00002833 Sqlite3_Init(interp);
drhd9b02572001-04-15 00:37:09 +00002834#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00002835 {
drh2f999a62007-08-15 19:16:43 +00002836 extern int Md5_Init(Tcl_Interp*);
2837 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00002838 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00002839 extern int Sqlitetest2_Init(Tcl_Interp*);
2840 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00002841 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00002842 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00002843 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00002844 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00002845 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00002846 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00002847 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00002848 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
drh984bfaa2008-03-19 16:08:53 +00002849 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00002850 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00002851 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00002852 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00002853 extern int Sqlitetestschema_Init(Tcl_Interp*);
2854 extern int Sqlitetestsse_Init(Tcl_Interp*);
2855 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00002856 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00002857 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00002858 extern int SqlitetestOsinst_Init(Tcl_Interp*);
danielk197704103022009-02-03 16:51:24 +00002859 extern int Sqlitetestbackup_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002860
drh2f999a62007-08-15 19:16:43 +00002861 Md5_Init(interp);
2862 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00002863 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00002864 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00002865 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00002866 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00002867 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00002868 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00002869 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00002870 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00002871 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00002872 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00002873 Sqlitetest_autoext_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00002874 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00002875 Sqlitetest_hexio_Init(interp);
drh2f999a62007-08-15 19:16:43 +00002876 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00002877 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00002878 Sqlitetestschema_Init(interp);
2879 Sqlitetesttclvar_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00002880 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00002881 SqlitetestOnefile_Init(interp);
danielk19775d1f5aa2008-04-10 14:51:00 +00002882 SqlitetestOsinst_Init(interp);
danielk197704103022009-02-03 16:51:24 +00002883 Sqlitetestbackup_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00002884
drh89dec812005-04-28 19:03:37 +00002885#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00002886 Sqlitetestsse_Init(interp);
2887#endif
drhd1bf3512001-04-07 15:24:33 +00002888 }
2889#endif
drh3e27c022004-07-23 00:01:38 +00002890 if( argc>=2 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002891 int i;
shessad42c3a2006-08-22 23:53:46 +00002892 char zArgc[32];
2893 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
2894 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00002895 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
2896 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00002897 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00002898 Tcl_SetVar(interp, "argv", argv[i],
2899 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
2900 }
drh3e27c022004-07-23 00:01:38 +00002901 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00002902 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drha81c64a2009-01-14 23:38:02 +00002903 if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
drhc61053b2000-06-04 12:58:36 +00002904 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00002905 return 1;
2906 }
drh3e27c022004-07-23 00:01:38 +00002907 }
2908 if( argc<=1 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002909 Tcl_GlobalEval(interp, zMainloop);
2910 }
2911 return 0;
2912}
2913#endif /* TCLSH */