blob: 7e6f32700eabef18edc9f02f216d0021e843d833 [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**
drh5bb3eb92007-05-04 13:15:55 +000015** $Id: tclsqlite.c,v 1.184 2007/05/04 13:15:56 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"
26# include "hash.h"
27# include <stdlib.h>
28# include <string.h>
29# include <assert.h>
30# include <ctype.h>
31#endif
drh75897232000-05-29 14:26:00 +000032
drhad6e1372006-07-10 21:15:51 +000033/*
34 * Windows needs to know which symbols to export. Unix does not.
35 * BUILD_sqlite should be undefined for Unix.
36 */
37#ifdef BUILD_sqlite
38#undef TCL_STORAGE_CLASS
39#define TCL_STORAGE_CLASS DLLEXPORT
40#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000041
danielk1977a21c6b62005-01-24 10:25:59 +000042#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000043#define MAX_PREPARED_STMTS 100
44
drh75897232000-05-29 14:26:00 +000045/*
drh98808ba2001-10-18 12:34:46 +000046** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
47** have to do a translation when going between the two. Set the
48** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
49** this translation.
50*/
51#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
52# define UTF_TRANSLATION_NEEDED 1
53#endif
54
55/*
drhcabb0812002-09-14 13:47:32 +000056** New SQL functions can be created as TCL scripts. Each such function
57** is described by an instance of the following structure.
58*/
59typedef struct SqlFunc SqlFunc;
60struct SqlFunc {
61 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000062 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
63 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
64 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000065 SqlFunc *pNext; /* Next function on the list of them all */
66};
67
68/*
danielk19770202b292004-06-09 09:55:16 +000069** New collation sequences function can be created as TCL scripts. Each such
70** function is described by an instance of the following structure.
71*/
72typedef struct SqlCollate SqlCollate;
73struct SqlCollate {
74 Tcl_Interp *interp; /* The TCL interpret to execute the function */
75 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000076 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000077};
78
79/*
drhfb7e7652005-01-24 00:28:42 +000080** Prepared statements are cached for faster execution. Each prepared
81** statement is described by an instance of the following structure.
82*/
83typedef struct SqlPreparedStmt SqlPreparedStmt;
84struct SqlPreparedStmt {
85 SqlPreparedStmt *pNext; /* Next in linked list */
86 SqlPreparedStmt *pPrev; /* Previous on the list */
87 sqlite3_stmt *pStmt; /* The prepared statement */
88 int nSql; /* chars in zSql[] */
89 char zSql[1]; /* Text of the SQL statement */
90};
91
danielk1977d04417962007-05-02 13:16:30 +000092typedef struct IncrblobChannel IncrblobChannel;
93
drhfb7e7652005-01-24 00:28:42 +000094/*
drhbec3f402000-08-04 13:49:02 +000095** There is one instance of this structure for each SQLite database
96** that has been opened by the SQLite TCL interface.
97*/
98typedef struct SqliteDb SqliteDb;
99struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000100 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000101 Tcl_Interp *interp; /* The interpreter used for this database */
102 char *zBusy; /* The busy callback routine */
103 char *zCommit; /* The commit hook callback routine */
104 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +0000105 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000106 char *zProgress; /* The progress callback routine */
107 char *zAuth; /* The authorization callback routine */
108 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) */
drhd1e47332005-06-26 17:55:33 +0000112 SqlCollate *pCollate; /* List of SQL collation functions */
113 int rc; /* Return code of most recent sqlite3_exec() */
114 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000115 SqlPreparedStmt *stmtList; /* List of prepared statements*/
116 SqlPreparedStmt *stmtLast; /* Last statement in the list */
117 int maxStmt; /* The next maximum number of stmtList */
118 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000119 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh98808ba2001-10-18 12:34:46 +0000120};
drh297ecf12001-04-05 15:57:13 +0000121
danielk1977b4e9af92007-05-01 17:49:49 +0000122struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000123 SqliteDb *pDb; /* Associated database connection */
124 sqlite3_blob *pBlob; /* sqlite3 blob handle */
125 int iSeek; /* Current seek offset */
126
127 Tcl_Channel channel; /* Channel identifier */
128 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
129 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000130};
131
132/*
danielk1977d04417962007-05-02 13:16:30 +0000133** Close all incrblob channels opened using database connection pDb.
134** This is called when shutting down the database connection.
135*/
136static void closeIncrblobChannels(SqliteDb *pDb){
137 IncrblobChannel *p;
138 IncrblobChannel *pNext;
139
140 for(p=pDb->pIncrblob; p; p=pNext){
141 pNext = p->pNext;
142
143 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
144 ** which deletes the IncrblobChannel structure at *p. So do not
145 ** call Tcl_Free() here.
146 */
147 Tcl_UnregisterChannel(pDb->interp, p->channel);
148 }
149}
150
151/*
danielk1977b4e9af92007-05-01 17:49:49 +0000152** Close an incremental blob channel.
153*/
154static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
155 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000156 int rc = sqlite3_blob_close(p->pBlob);
157 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000158
159 /* Remove the channel from the SqliteDb.pIncrblob list. */
160 if( p->pNext ){
161 p->pNext->pPrev = p->pPrev;
162 }
163 if( p->pPrev ){
164 p->pPrev->pNext = p->pNext;
165 }
166 if( p->pDb->pIncrblob==p ){
167 p->pDb->pIncrblob = p->pNext;
168 }
169
danielk197792d4d7a2007-05-04 12:05:56 +0000170 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000171 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000172
173 if( rc!=SQLITE_OK ){
174 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
175 return TCL_ERROR;
176 }
danielk1977b4e9af92007-05-01 17:49:49 +0000177 return TCL_OK;
178}
179
180/*
181** Read data from an incremental blob channel.
182*/
183static int incrblobInput(
184 ClientData instanceData,
185 char *buf,
186 int bufSize,
187 int *errorCodePtr
188){
189 IncrblobChannel *p = (IncrblobChannel *)instanceData;
190 int nRead = bufSize; /* Number of bytes to read */
191 int nBlob; /* Total size of the blob */
192 int rc; /* sqlite error code */
193
194 nBlob = sqlite3_blob_bytes(p->pBlob);
195 if( (p->iSeek+nRead)>nBlob ){
196 nRead = nBlob-p->iSeek;
197 }
198 if( nRead<=0 ){
199 return 0;
200 }
201
202 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
203 if( rc!=SQLITE_OK ){
204 *errorCodePtr = rc;
205 return -1;
206 }
207
208 p->iSeek += nRead;
209 return nRead;
210}
211
danielk1977d04417962007-05-02 13:16:30 +0000212/*
213** Write data to an incremental blob channel.
214*/
danielk1977b4e9af92007-05-01 17:49:49 +0000215static int incrblobOutput(
216 ClientData instanceData,
217 CONST char *buf,
218 int toWrite,
219 int *errorCodePtr
220){
221 IncrblobChannel *p = (IncrblobChannel *)instanceData;
222 int nWrite = toWrite; /* Number of bytes to write */
223 int nBlob; /* Total size of the blob */
224 int rc; /* sqlite error code */
225
226 nBlob = sqlite3_blob_bytes(p->pBlob);
227 if( (p->iSeek+nWrite)>nBlob ){
228 *errorCodePtr = EINVAL;
229 return -1;
230 }
231 if( nWrite<=0 ){
232 return 0;
233 }
234
235 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
236 if( rc!=SQLITE_OK ){
237 *errorCodePtr = EIO;
238 return -1;
239 }
240
241 p->iSeek += nWrite;
242 return nWrite;
243}
244
245/*
246** Seek an incremental blob channel.
247*/
248static int incrblobSeek(
249 ClientData instanceData,
250 long offset,
251 int seekMode,
252 int *errorCodePtr
253){
254 IncrblobChannel *p = (IncrblobChannel *)instanceData;
255
256 switch( seekMode ){
257 case SEEK_SET:
258 p->iSeek = offset;
259 break;
260 case SEEK_CUR:
261 p->iSeek += offset;
262 break;
263 case SEEK_END:
264 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
265 break;
266
267 default: assert(!"Bad seekMode");
268 }
269
270 return p->iSeek;
271}
272
273
274static void incrblobWatch(ClientData instanceData, int mode){
275 /* NO-OP */
276}
277static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
278 return TCL_ERROR;
279}
280
281static Tcl_ChannelType IncrblobChannelType = {
282 "incrblob", /* typeName */
283 TCL_CHANNEL_VERSION_2, /* version */
284 incrblobClose, /* closeProc */
285 incrblobInput, /* inputProc */
286 incrblobOutput, /* outputProc */
287 incrblobSeek, /* seekProc */
288 0, /* setOptionProc */
289 0, /* getOptionProc */
290 incrblobWatch, /* watchProc (this is a no-op) */
291 incrblobHandle, /* getHandleProc (always returns error) */
292 0, /* close2Proc */
293 0, /* blockModeProc */
294 0, /* flushProc */
295 0, /* handlerProc */
296 0, /* wideSeekProc */
297 0, /* threadActionProc */
298};
299
300/*
301** Create a new incrblob channel.
302*/
303static int createIncrblobChannel(
304 Tcl_Interp *interp,
305 SqliteDb *pDb,
306 const char *zDb,
307 const char *zTable,
308 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000309 sqlite_int64 iRow,
310 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000311){
312 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000313 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000314 sqlite3_blob *pBlob;
315 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000316 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000317
318 /* This variable is used to name the channels: "incrblob_[incr count]" */
319 static int count = 0;
320 char zChannel[64];
321
danielk19778cbadb02007-05-03 16:31:26 +0000322 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000323 if( rc!=SQLITE_OK ){
324 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
325 return TCL_ERROR;
326 }
327
328 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
329 p->iSeek = 0;
330 p->pBlob = pBlob;
331
drh5bb3eb92007-05-04 13:15:55 +0000332 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000333 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
334 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000335
danielk1977d04417962007-05-02 13:16:30 +0000336 /* Link the new channel into the SqliteDb.pIncrblob list. */
337 p->pNext = pDb->pIncrblob;
338 p->pPrev = 0;
339 if( p->pNext ){
340 p->pNext->pPrev = p;
341 }
342 pDb->pIncrblob = p;
343 p->pDb = pDb;
344
345 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000346 return TCL_OK;
347}
348
drh6d313162000-09-21 13:01:35 +0000349/*
drhd1e47332005-06-26 17:55:33 +0000350** Look at the script prefix in pCmd. We will be executing this script
351** after first appending one or more arguments. This routine analyzes
352** the script to see if it is safe to use Tcl_EvalObjv() on the script
353** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
354** faster.
355**
356** Scripts that are safe to use with Tcl_EvalObjv() consists of a
357** command name followed by zero or more arguments with no [...] or $
358** or {...} or ; to be seen anywhere. Most callback scripts consist
359** of just a single procedure name and they meet this requirement.
360*/
361static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
362 /* We could try to do something with Tcl_Parse(). But we will instead
363 ** just do a search for forbidden characters. If any of the forbidden
364 ** characters appear in pCmd, we will report the string as unsafe.
365 */
366 const char *z;
367 int n;
368 z = Tcl_GetStringFromObj(pCmd, &n);
369 while( n-- > 0 ){
370 int c = *(z++);
371 if( c=='$' || c=='[' || c==';' ) return 0;
372 }
373 return 1;
374}
375
376/*
377** Find an SqlFunc structure with the given name. Or create a new
378** one if an existing one cannot be found. Return a pointer to the
379** structure.
380*/
381static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
382 SqlFunc *p, *pNew;
383 int i;
384 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen(zName) + 1 );
385 pNew->zName = (char*)&pNew[1];
386 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
387 pNew->zName[i] = 0;
388 for(p=pDb->pFunc; p; p=p->pNext){
389 if( strcmp(p->zName, pNew->zName)==0 ){
390 Tcl_Free((char*)pNew);
391 return p;
392 }
393 }
394 pNew->interp = pDb->interp;
395 pNew->pScript = 0;
396 pNew->pNext = pDb->pFunc;
397 pDb->pFunc = pNew;
398 return pNew;
399}
400
401/*
drhfb7e7652005-01-24 00:28:42 +0000402** Finalize and free a list of prepared statements
403*/
404static void flushStmtCache( SqliteDb *pDb ){
405 SqlPreparedStmt *pPreStmt;
406
407 while( pDb->stmtList ){
408 sqlite3_finalize( pDb->stmtList->pStmt );
409 pPreStmt = pDb->stmtList;
410 pDb->stmtList = pDb->stmtList->pNext;
411 Tcl_Free( (char*)pPreStmt );
412 }
413 pDb->nStmt = 0;
414 pDb->stmtLast = 0;
415}
416
417/*
drh895d7472004-08-20 16:02:39 +0000418** TCL calls this procedure when an sqlite3 database command is
419** deleted.
drh75897232000-05-29 14:26:00 +0000420*/
421static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000422 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000423 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000424 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000425 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000426 while( pDb->pFunc ){
427 SqlFunc *pFunc = pDb->pFunc;
428 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000429 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000430 Tcl_Free((char*)pFunc);
431 }
danielk19770202b292004-06-09 09:55:16 +0000432 while( pDb->pCollate ){
433 SqlCollate *pCollate = pDb->pCollate;
434 pDb->pCollate = pCollate->pNext;
435 Tcl_Free((char*)pCollate);
436 }
drhbec3f402000-08-04 13:49:02 +0000437 if( pDb->zBusy ){
438 Tcl_Free(pDb->zBusy);
439 }
drhb5a20d32003-04-23 12:25:23 +0000440 if( pDb->zTrace ){
441 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000442 }
drh19e2d372005-08-29 23:00:03 +0000443 if( pDb->zProfile ){
444 Tcl_Free(pDb->zProfile);
445 }
drhe22a3342003-04-22 20:30:37 +0000446 if( pDb->zAuth ){
447 Tcl_Free(pDb->zAuth);
448 }
danielk197755c45f22005-04-03 23:54:43 +0000449 if( pDb->zNull ){
450 Tcl_Free(pDb->zNull);
451 }
danielk197794eb6a12005-12-15 15:22:08 +0000452 if( pDb->pUpdateHook ){
453 Tcl_DecrRefCount(pDb->pUpdateHook);
454 }
danielk197771fd80b2005-12-16 06:54:01 +0000455 if( pDb->pRollbackHook ){
456 Tcl_DecrRefCount(pDb->pRollbackHook);
457 }
danielk197794eb6a12005-12-15 15:22:08 +0000458 if( pDb->pCollateNeeded ){
459 Tcl_DecrRefCount(pDb->pCollateNeeded);
460 }
drhbec3f402000-08-04 13:49:02 +0000461 Tcl_Free((char*)pDb);
462}
463
464/*
465** This routine is called when a database file is locked while trying
466** to execute SQL.
467*/
danielk19772a764eb2004-06-12 01:43:26 +0000468static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000469 SqliteDb *pDb = (SqliteDb*)cd;
470 int rc;
471 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000472
drh5bb3eb92007-05-04 13:15:55 +0000473 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000474 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000475 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
476 return 0;
477 }
478 return 1;
drh75897232000-05-29 14:26:00 +0000479}
480
481/*
danielk1977348bb5d2003-10-18 09:37:26 +0000482** This routine is invoked as the 'progress callback' for the database.
483*/
484static int DbProgressHandler(void *cd){
485 SqliteDb *pDb = (SqliteDb*)cd;
486 int rc;
487
488 assert( pDb->zProgress );
489 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
490 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
491 return 1;
492 }
493 return 0;
494}
495
drhd1167392006-01-23 13:00:35 +0000496#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000497/*
drhb5a20d32003-04-23 12:25:23 +0000498** This routine is called by the SQLite trace handler whenever a new
499** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000500*/
drhb5a20d32003-04-23 12:25:23 +0000501static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000502 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000503 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000504
drhb5a20d32003-04-23 12:25:23 +0000505 Tcl_DStringInit(&str);
506 Tcl_DStringAppend(&str, pDb->zTrace, -1);
507 Tcl_DStringAppendElement(&str, zSql);
508 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
509 Tcl_DStringFree(&str);
510 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000511}
drhd1167392006-01-23 13:00:35 +0000512#endif
drh0d1a6432003-04-03 15:46:04 +0000513
drhd1167392006-01-23 13:00:35 +0000514#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000515/*
drh19e2d372005-08-29 23:00:03 +0000516** This routine is called by the SQLite profile handler after a statement
517** SQL has executed. The TCL script in pDb->zProfile is evaluated.
518*/
519static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
520 SqliteDb *pDb = (SqliteDb*)cd;
521 Tcl_DString str;
522 char zTm[100];
523
524 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
525 Tcl_DStringInit(&str);
526 Tcl_DStringAppend(&str, pDb->zProfile, -1);
527 Tcl_DStringAppendElement(&str, zSql);
528 Tcl_DStringAppendElement(&str, zTm);
529 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
530 Tcl_DStringFree(&str);
531 Tcl_ResetResult(pDb->interp);
532}
drhd1167392006-01-23 13:00:35 +0000533#endif
drh19e2d372005-08-29 23:00:03 +0000534
535/*
drhaa940ea2004-01-15 02:44:03 +0000536** This routine is called when a transaction is committed. The
537** TCL script in pDb->zCommit is executed. If it returns non-zero or
538** if it throws an exception, the transaction is rolled back instead
539** of being committed.
540*/
541static int DbCommitHandler(void *cd){
542 SqliteDb *pDb = (SqliteDb*)cd;
543 int rc;
544
545 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
546 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
547 return 1;
548 }
549 return 0;
550}
551
danielk197771fd80b2005-12-16 06:54:01 +0000552static void DbRollbackHandler(void *clientData){
553 SqliteDb *pDb = (SqliteDb*)clientData;
554 assert(pDb->pRollbackHook);
555 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
556 Tcl_BackgroundError(pDb->interp);
557 }
558}
559
danielk197794eb6a12005-12-15 15:22:08 +0000560static void DbUpdateHandler(
561 void *p,
562 int op,
563 const char *zDb,
564 const char *zTbl,
565 sqlite_int64 rowid
566){
567 SqliteDb *pDb = (SqliteDb *)p;
568 Tcl_Obj *pCmd;
569
570 assert( pDb->pUpdateHook );
571 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
572
573 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
574 Tcl_IncrRefCount(pCmd);
575 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
576 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
577 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
578 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
579 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
580 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
581}
582
danielk19777cedc8d2004-06-10 10:50:08 +0000583static void tclCollateNeeded(
584 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000585 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000586 int enc,
587 const char *zName
588){
589 SqliteDb *pDb = (SqliteDb *)pCtx;
590 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
591 Tcl_IncrRefCount(pScript);
592 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
593 Tcl_EvalObjEx(pDb->interp, pScript, 0);
594 Tcl_DecrRefCount(pScript);
595}
596
drhaa940ea2004-01-15 02:44:03 +0000597/*
danielk19770202b292004-06-09 09:55:16 +0000598** This routine is called to evaluate an SQL collation function implemented
599** using TCL script.
600*/
601static int tclSqlCollate(
602 void *pCtx,
603 int nA,
604 const void *zA,
605 int nB,
606 const void *zB
607){
608 SqlCollate *p = (SqlCollate *)pCtx;
609 Tcl_Obj *pCmd;
610
611 pCmd = Tcl_NewStringObj(p->zScript, -1);
612 Tcl_IncrRefCount(pCmd);
613 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
614 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000615 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000616 Tcl_DecrRefCount(pCmd);
617 return (atoi(Tcl_GetStringResult(p->interp)));
618}
619
620/*
drhcabb0812002-09-14 13:47:32 +0000621** This routine is called to evaluate an SQL function implemented
622** using TCL script.
623*/
drhfb7e7652005-01-24 00:28:42 +0000624static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000625 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000626 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000627 int i;
628 int rc;
629
drhd1e47332005-06-26 17:55:33 +0000630 if( argc==0 ){
631 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
632 ** script object directly. This allows the TCL compiler to generate
633 ** bytecode for the command on the first invocation and thus make
634 ** subsequent invocations much faster. */
635 pCmd = p->pScript;
636 Tcl_IncrRefCount(pCmd);
637 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
638 Tcl_DecrRefCount(pCmd);
639 }else{
640 /* If there are arguments to the function, make a shallow copy of the
641 ** script object, lappend the arguments, then evaluate the copy.
642 **
643 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
644 ** The new Tcl_Obj contains pointers to the original list elements.
645 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
646 ** of the list to tclCmdNameType, that alternate representation will
647 ** be preserved and reused on the next invocation.
648 */
649 Tcl_Obj **aArg;
650 int nArg;
651 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
652 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
653 return;
654 }
655 pCmd = Tcl_NewListObj(nArg, aArg);
656 Tcl_IncrRefCount(pCmd);
657 for(i=0; i<argc; i++){
658 sqlite3_value *pIn = argv[i];
659 Tcl_Obj *pVal;
660
661 /* Set pVal to contain the i'th column of this row. */
662 switch( sqlite3_value_type(pIn) ){
663 case SQLITE_BLOB: {
664 int bytes = sqlite3_value_bytes(pIn);
665 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
666 break;
667 }
668 case SQLITE_INTEGER: {
669 sqlite_int64 v = sqlite3_value_int64(pIn);
670 if( v>=-2147483647 && v<=2147483647 ){
671 pVal = Tcl_NewIntObj(v);
672 }else{
673 pVal = Tcl_NewWideIntObj(v);
674 }
675 break;
676 }
677 case SQLITE_FLOAT: {
678 double r = sqlite3_value_double(pIn);
679 pVal = Tcl_NewDoubleObj(r);
680 break;
681 }
682 case SQLITE_NULL: {
683 pVal = Tcl_NewStringObj("", 0);
684 break;
685 }
686 default: {
687 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000688 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000689 break;
690 }
691 }
692 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
693 if( rc ){
694 Tcl_DecrRefCount(pCmd);
695 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
696 return;
697 }
danielk197751ad0ec2004-05-24 12:39:02 +0000698 }
drhd1e47332005-06-26 17:55:33 +0000699 if( !p->useEvalObjv ){
700 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
701 ** is a list without a string representation. To prevent this from
702 ** happening, make sure pCmd has a valid string representation */
703 Tcl_GetString(pCmd);
704 }
705 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
706 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000707 }
danielk1977562e8d32005-05-20 09:40:55 +0000708
drhc7f269d2005-05-05 10:30:29 +0000709 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000710 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000711 }else{
drhc7f269d2005-05-05 10:30:29 +0000712 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
713 int n;
714 u8 *data;
715 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
716 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000717 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000718 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000719 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000720 data = Tcl_GetByteArrayFromObj(pVar, &n);
721 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000722 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
723 (c=='i' && strcmp(zType,"int")==0) ){
724 Tcl_GetIntFromObj(0, pVar, &n);
725 sqlite3_result_int(context, n);
726 }else if( c=='d' && strcmp(zType,"double")==0 ){
727 double r;
728 Tcl_GetDoubleFromObj(0, pVar, &r);
729 sqlite3_result_double(context, r);
drhdf0bdda2005-06-25 19:31:48 +0000730 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
731 Tcl_WideInt v;
732 Tcl_GetWideIntFromObj(0, pVar, &v);
733 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000734 }else{
danielk197700fd9572005-12-07 06:27:43 +0000735 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
736 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000737 }
drhcabb0812002-09-14 13:47:32 +0000738 }
739}
drh895d7472004-08-20 16:02:39 +0000740
drhe22a3342003-04-22 20:30:37 +0000741#ifndef SQLITE_OMIT_AUTHORIZATION
742/*
743** This is the authentication function. It appends the authentication
744** type code and the two arguments to zCmd[] then invokes the result
745** on the interpreter. The reply is examined to determine if the
746** authentication fails or succeeds.
747*/
748static int auth_callback(
749 void *pArg,
750 int code,
751 const char *zArg1,
752 const char *zArg2,
753 const char *zArg3,
754 const char *zArg4
755){
756 char *zCode;
757 Tcl_DString str;
758 int rc;
759 const char *zReply;
760 SqliteDb *pDb = (SqliteDb*)pArg;
761
762 switch( code ){
763 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
764 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
765 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
766 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
767 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
768 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
769 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
770 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
771 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
772 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
773 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
774 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
775 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
776 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
777 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
778 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
779 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
780 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
781 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
782 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
783 case SQLITE_READ : zCode="SQLITE_READ"; break;
784 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
785 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
786 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000787 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
788 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000789 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000790 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000791 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000792 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
793 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000794 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
drhe22a3342003-04-22 20:30:37 +0000795 default : zCode="????"; break;
796 }
797 Tcl_DStringInit(&str);
798 Tcl_DStringAppend(&str, pDb->zAuth, -1);
799 Tcl_DStringAppendElement(&str, zCode);
800 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
801 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
802 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
803 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
804 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
805 Tcl_DStringFree(&str);
806 zReply = Tcl_GetStringResult(pDb->interp);
807 if( strcmp(zReply,"SQLITE_OK")==0 ){
808 rc = SQLITE_OK;
809 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
810 rc = SQLITE_DENY;
811 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
812 rc = SQLITE_IGNORE;
813 }else{
814 rc = 999;
815 }
816 return rc;
817}
818#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000819
820/*
danielk1977ef2cb632004-05-29 02:37:19 +0000821** zText is a pointer to text obtained via an sqlite3_result_text()
822** or similar interface. This routine returns a Tcl string object,
823** reference count set to 0, containing the text. If a translation
824** between iso8859 and UTF-8 is required, it is preformed.
825*/
826static Tcl_Obj *dbTextToObj(char const *zText){
827 Tcl_Obj *pVal;
828#ifdef UTF_TRANSLATION_NEEDED
829 Tcl_DString dCol;
830 Tcl_DStringInit(&dCol);
831 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
832 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
833 Tcl_DStringFree(&dCol);
834#else
835 pVal = Tcl_NewStringObj(zText, -1);
836#endif
837 return pVal;
838}
839
840/*
tpoindex1067fe12004-12-17 15:41:11 +0000841** This routine reads a line of text from FILE in, stores
842** the text in memory obtained from malloc() and returns a pointer
843** to the text. NULL is returned at end of file, or if malloc()
844** fails.
845**
846** The interface is like "readline" but no command-line editing
847** is done.
848**
849** copied from shell.c from '.import' command
850*/
851static char *local_getline(char *zPrompt, FILE *in){
852 char *zLine;
853 int nLine;
854 int n;
855 int eol;
856
857 nLine = 100;
858 zLine = malloc( nLine );
859 if( zLine==0 ) return 0;
860 n = 0;
861 eol = 0;
862 while( !eol ){
863 if( n+100>nLine ){
864 nLine = nLine*2 + 100;
865 zLine = realloc(zLine, nLine);
866 if( zLine==0 ) return 0;
867 }
868 if( fgets(&zLine[n], nLine - n, in)==0 ){
869 if( n==0 ){
870 free(zLine);
871 return 0;
872 }
873 zLine[n] = 0;
874 eol = 1;
875 break;
876 }
877 while( zLine[n] ){ n++; }
878 if( n>0 && zLine[n-1]=='\n' ){
879 n--;
880 zLine[n] = 0;
881 eol = 1;
882 }
883 }
884 zLine = realloc( zLine, n+1 );
885 return zLine;
886}
887
888/*
drh75897232000-05-29 14:26:00 +0000889** The "sqlite" command below creates a new Tcl command for each
890** connection it opens to an SQLite database. This routine is invoked
891** whenever one of those connection-specific commands is executed
892** in Tcl. For example, if you run Tcl code like this:
893**
drh9bb575f2004-09-06 17:24:11 +0000894** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +0000895** db1 close
896**
897** The first command opens a connection to the "my_database" database
898** and calls that connection "db1". The second command causes this
899** subroutine to be invoked.
900*/
drh6d313162000-09-21 13:01:35 +0000901static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +0000902 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +0000903 int choice;
drh22fbcb82004-02-01 01:22:50 +0000904 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +0000905 static const char *DB_strs[] = {
drhfb7e7652005-01-24 00:28:42 +0000906 "authorizer", "busy", "cache",
907 "changes", "close", "collate",
908 "collation_needed", "commit_hook", "complete",
drh41449052006-07-06 17:08:48 +0000909 "copy", "enable_load_extension","errorcode",
910 "eval", "exists", "function",
danielk1977b4e9af92007-05-01 17:49:49 +0000911 "incrblob",
drhf11bded2006-07-17 00:02:44 +0000912 "interrupt", "last_insert_rowid", "nullvalue",
913 "onecolumn", "profile", "progress",
914 "rekey", "rollback_hook", "timeout",
915 "total_changes", "trace", "transaction",
916 "update_hook", "version", 0
drh6d313162000-09-21 13:01:35 +0000917 };
drh411995d2002-06-25 19:31:18 +0000918 enum DB_enum {
drhfb7e7652005-01-24 00:28:42 +0000919 DB_AUTHORIZER, DB_BUSY, DB_CACHE,
920 DB_CHANGES, DB_CLOSE, DB_COLLATE,
921 DB_COLLATION_NEEDED, DB_COMMIT_HOOK, DB_COMPLETE,
drh41449052006-07-06 17:08:48 +0000922 DB_COPY, DB_ENABLE_LOAD_EXTENSION,DB_ERRORCODE,
923 DB_EVAL, DB_EXISTS, DB_FUNCTION,
danielk1977b4e9af92007-05-01 17:49:49 +0000924 DB_INCRBLOB,
drhf11bded2006-07-17 00:02:44 +0000925 DB_INTERRUPT, DB_LAST_INSERT_ROWID,DB_NULLVALUE,
926 DB_ONECOLUMN, DB_PROFILE, DB_PROGRESS,
927 DB_REKEY, DB_ROLLBACK_HOOK, DB_TIMEOUT,
928 DB_TOTAL_CHANGES, DB_TRACE, DB_TRANSACTION,
929 DB_UPDATE_HOOK, DB_VERSION,
drh6d313162000-09-21 13:01:35 +0000930 };
tpoindex1067fe12004-12-17 15:41:11 +0000931 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +0000932
933 if( objc<2 ){
934 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +0000935 return TCL_ERROR;
936 }
drh411995d2002-06-25 19:31:18 +0000937 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +0000938 return TCL_ERROR;
939 }
940
drh411995d2002-06-25 19:31:18 +0000941 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +0000942
drhe22a3342003-04-22 20:30:37 +0000943 /* $db authorizer ?CALLBACK?
944 **
945 ** Invoke the given callback to authorize each SQL operation as it is
946 ** compiled. 5 arguments are appended to the callback before it is
947 ** invoked:
948 **
949 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
950 ** (2) First descriptive name (depends on authorization type)
951 ** (3) Second descriptive name
952 ** (4) Name of the database (ex: "main", "temp")
953 ** (5) Name of trigger that is doing the access
954 **
955 ** The callback should return on of the following strings: SQLITE_OK,
956 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
957 **
958 ** If this method is invoked with no arguments, the current authorization
959 ** callback string is returned.
960 */
961 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +0000962#ifdef SQLITE_OMIT_AUTHORIZATION
963 Tcl_AppendResult(interp, "authorization not available in this build", 0);
964 return TCL_ERROR;
965#else
drhe22a3342003-04-22 20:30:37 +0000966 if( objc>3 ){
967 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +0000968 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +0000969 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +0000970 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +0000971 Tcl_AppendResult(interp, pDb->zAuth, 0);
972 }
973 }else{
974 char *zAuth;
975 int len;
976 if( pDb->zAuth ){
977 Tcl_Free(pDb->zAuth);
978 }
979 zAuth = Tcl_GetStringFromObj(objv[2], &len);
980 if( zAuth && len>0 ){
981 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +0000982 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +0000983 }else{
984 pDb->zAuth = 0;
985 }
drhe22a3342003-04-22 20:30:37 +0000986 if( pDb->zAuth ){
987 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000988 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +0000989 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000990 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +0000991 }
drhe22a3342003-04-22 20:30:37 +0000992 }
drh1211de32004-07-26 12:24:22 +0000993#endif
drhe22a3342003-04-22 20:30:37 +0000994 break;
995 }
996
drhbec3f402000-08-04 13:49:02 +0000997 /* $db busy ?CALLBACK?
998 **
999 ** Invoke the given callback if an SQL statement attempts to open
1000 ** a locked database file.
1001 */
drh6d313162000-09-21 13:01:35 +00001002 case DB_BUSY: {
1003 if( objc>3 ){
1004 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001005 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001006 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001007 if( pDb->zBusy ){
1008 Tcl_AppendResult(interp, pDb->zBusy, 0);
1009 }
1010 }else{
drh6d313162000-09-21 13:01:35 +00001011 char *zBusy;
1012 int len;
drhbec3f402000-08-04 13:49:02 +00001013 if( pDb->zBusy ){
1014 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001015 }
drh6d313162000-09-21 13:01:35 +00001016 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1017 if( zBusy && len>0 ){
1018 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001019 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001020 }else{
1021 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001022 }
1023 if( pDb->zBusy ){
1024 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001025 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001026 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001027 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001028 }
1029 }
drh6d313162000-09-21 13:01:35 +00001030 break;
1031 }
drhbec3f402000-08-04 13:49:02 +00001032
drhfb7e7652005-01-24 00:28:42 +00001033 /* $db cache flush
1034 ** $db cache size n
1035 **
1036 ** Flush the prepared statement cache, or set the maximum number of
1037 ** cached statements.
1038 */
1039 case DB_CACHE: {
1040 char *subCmd;
1041 int n;
1042
1043 if( objc<=2 ){
1044 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1045 return TCL_ERROR;
1046 }
1047 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1048 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1049 if( objc!=3 ){
1050 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1051 return TCL_ERROR;
1052 }else{
1053 flushStmtCache( pDb );
1054 }
1055 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1056 if( objc!=4 ){
1057 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1058 return TCL_ERROR;
1059 }else{
1060 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1061 Tcl_AppendResult( interp, "cannot convert \"",
1062 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1063 return TCL_ERROR;
1064 }else{
1065 if( n<0 ){
1066 flushStmtCache( pDb );
1067 n = 0;
1068 }else if( n>MAX_PREPARED_STMTS ){
1069 n = MAX_PREPARED_STMTS;
1070 }
1071 pDb->maxStmt = n;
1072 }
1073 }
1074 }else{
1075 Tcl_AppendResult( interp, "bad option \"",
1076 Tcl_GetStringFromObj(objv[0],0), "\": must be flush or size", 0);
1077 return TCL_ERROR;
1078 }
1079 break;
1080 }
1081
danielk1977b28af712004-06-21 06:50:26 +00001082 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001083 **
1084 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001085 ** the most recent INSERT, UPDATE or DELETE statement, not including
1086 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001087 */
1088 case DB_CHANGES: {
1089 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001090 if( objc!=2 ){
1091 Tcl_WrongNumArgs(interp, 2, objv, "");
1092 return TCL_ERROR;
1093 }
drhc8d30ac2002-04-12 10:08:59 +00001094 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001095 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001096 break;
1097 }
1098
drh75897232000-05-29 14:26:00 +00001099 /* $db close
1100 **
1101 ** Shutdown the database
1102 */
drh6d313162000-09-21 13:01:35 +00001103 case DB_CLOSE: {
1104 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1105 break;
1106 }
drh75897232000-05-29 14:26:00 +00001107
drh0f14e2e2004-06-29 12:39:08 +00001108 /*
1109 ** $db collate NAME SCRIPT
1110 **
1111 ** Create a new SQL collation function called NAME. Whenever
1112 ** that function is called, invoke SCRIPT to evaluate the function.
1113 */
1114 case DB_COLLATE: {
1115 SqlCollate *pCollate;
1116 char *zName;
1117 char *zScript;
1118 int nScript;
1119 if( objc!=4 ){
1120 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1121 return TCL_ERROR;
1122 }
1123 zName = Tcl_GetStringFromObj(objv[2], 0);
1124 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1125 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1126 if( pCollate==0 ) return TCL_ERROR;
1127 pCollate->interp = interp;
1128 pCollate->pNext = pDb->pCollate;
1129 pCollate->zScript = (char*)&pCollate[1];
1130 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001131 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001132 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1133 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001134 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001135 return TCL_ERROR;
1136 }
1137 break;
1138 }
1139
1140 /*
1141 ** $db collation_needed SCRIPT
1142 **
1143 ** Create a new SQL collation function called NAME. Whenever
1144 ** that function is called, invoke SCRIPT to evaluate the function.
1145 */
1146 case DB_COLLATION_NEEDED: {
1147 if( objc!=3 ){
1148 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1149 return TCL_ERROR;
1150 }
1151 if( pDb->pCollateNeeded ){
1152 Tcl_DecrRefCount(pDb->pCollateNeeded);
1153 }
1154 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1155 Tcl_IncrRefCount(pDb->pCollateNeeded);
1156 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1157 break;
1158 }
1159
drh19e2d372005-08-29 23:00:03 +00001160 /* $db commit_hook ?CALLBACK?
1161 **
1162 ** Invoke the given callback just before committing every SQL transaction.
1163 ** If the callback throws an exception or returns non-zero, then the
1164 ** transaction is aborted. If CALLBACK is an empty string, the callback
1165 ** is disabled.
1166 */
1167 case DB_COMMIT_HOOK: {
1168 if( objc>3 ){
1169 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1170 return TCL_ERROR;
1171 }else if( objc==2 ){
1172 if( pDb->zCommit ){
1173 Tcl_AppendResult(interp, pDb->zCommit, 0);
1174 }
1175 }else{
1176 char *zCommit;
1177 int len;
1178 if( pDb->zCommit ){
1179 Tcl_Free(pDb->zCommit);
1180 }
1181 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1182 if( zCommit && len>0 ){
1183 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001184 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001185 }else{
1186 pDb->zCommit = 0;
1187 }
1188 if( pDb->zCommit ){
1189 pDb->interp = interp;
1190 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1191 }else{
1192 sqlite3_commit_hook(pDb->db, 0, 0);
1193 }
1194 }
1195 break;
1196 }
1197
drh75897232000-05-29 14:26:00 +00001198 /* $db complete SQL
1199 **
1200 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1201 ** additional lines of input are needed. This is similar to the
1202 ** built-in "info complete" command of Tcl.
1203 */
drh6d313162000-09-21 13:01:35 +00001204 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00001205#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00001206 Tcl_Obj *pResult;
1207 int isComplete;
1208 if( objc!=3 ){
1209 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00001210 return TCL_ERROR;
1211 }
danielk19776f8a5032004-05-10 10:34:51 +00001212 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00001213 pResult = Tcl_GetObjResult(interp);
1214 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00001215#endif
drh6d313162000-09-21 13:01:35 +00001216 break;
1217 }
drhdcd997e2003-01-31 17:21:49 +00001218
drh19e2d372005-08-29 23:00:03 +00001219 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1220 **
1221 ** Copy data into table from filename, optionally using SEPARATOR
1222 ** as column separators. If a column contains a null string, or the
1223 ** value of NULLINDICATOR, a NULL is inserted for the column.
1224 ** conflict-algorithm is one of the sqlite conflict algorithms:
1225 ** rollback, abort, fail, ignore, replace
1226 ** On success, return the number of lines processed, not necessarily same
1227 ** as 'db changes' due to conflict-algorithm selected.
1228 **
1229 ** This code is basically an implementation/enhancement of
1230 ** the sqlite3 shell.c ".import" command.
1231 **
1232 ** This command usage is equivalent to the sqlite2.x COPY statement,
1233 ** which imports file data into a table using the PostgreSQL COPY file format:
1234 ** $db copy $conflit_algo $table_name $filename \t \\N
1235 */
1236 case DB_COPY: {
1237 char *zTable; /* Insert data into this table */
1238 char *zFile; /* The file from which to extract data */
1239 char *zConflict; /* The conflict algorithm to use */
1240 sqlite3_stmt *pStmt; /* A statement */
1241 int rc; /* Result code */
1242 int nCol; /* Number of columns in the table */
1243 int nByte; /* Number of bytes in an SQL string */
1244 int i, j; /* Loop counters */
1245 int nSep; /* Number of bytes in zSep[] */
1246 int nNull; /* Number of bytes in zNull[] */
1247 char *zSql; /* An SQL statement */
1248 char *zLine; /* A single line of input from the file */
1249 char **azCol; /* zLine[] broken up into columns */
1250 char *zCommit; /* How to commit changes */
1251 FILE *in; /* The input file */
1252 int lineno = 0; /* Line number of input file */
1253 char zLineNum[80]; /* Line number print buffer */
1254 Tcl_Obj *pResult; /* interp result */
1255
1256 char *zSep;
1257 char *zNull;
1258 if( objc<5 || objc>7 ){
1259 Tcl_WrongNumArgs(interp, 2, objv,
1260 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1261 return TCL_ERROR;
1262 }
1263 if( objc>=6 ){
1264 zSep = Tcl_GetStringFromObj(objv[5], 0);
1265 }else{
1266 zSep = "\t";
1267 }
1268 if( objc>=7 ){
1269 zNull = Tcl_GetStringFromObj(objv[6], 0);
1270 }else{
1271 zNull = "";
1272 }
1273 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1274 zTable = Tcl_GetStringFromObj(objv[3], 0);
1275 zFile = Tcl_GetStringFromObj(objv[4], 0);
1276 nSep = strlen(zSep);
1277 nNull = strlen(zNull);
1278 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00001279 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00001280 return TCL_ERROR;
1281 }
1282 if(sqlite3StrICmp(zConflict, "rollback") != 0 &&
1283 sqlite3StrICmp(zConflict, "abort" ) != 0 &&
1284 sqlite3StrICmp(zConflict, "fail" ) != 0 &&
1285 sqlite3StrICmp(zConflict, "ignore" ) != 0 &&
1286 sqlite3StrICmp(zConflict, "replace" ) != 0 ) {
1287 Tcl_AppendResult(interp, "Error: \"", zConflict,
1288 "\", conflict-algorithm must be one of: rollback, "
1289 "abort, fail, ignore, or replace", 0);
1290 return TCL_ERROR;
1291 }
1292 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1293 if( zSql==0 ){
1294 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1295 return TCL_ERROR;
1296 }
1297 nByte = strlen(zSql);
drh3e701a12007-02-01 01:53:44 +00001298 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001299 sqlite3_free(zSql);
1300 if( rc ){
1301 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1302 nCol = 0;
1303 }else{
1304 nCol = sqlite3_column_count(pStmt);
1305 }
1306 sqlite3_finalize(pStmt);
1307 if( nCol==0 ) {
1308 return TCL_ERROR;
1309 }
1310 zSql = malloc( nByte + 50 + nCol*2 );
1311 if( zSql==0 ) {
1312 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1313 return TCL_ERROR;
1314 }
1315 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1316 zConflict, zTable);
1317 j = strlen(zSql);
1318 for(i=1; i<nCol; i++){
1319 zSql[j++] = ',';
1320 zSql[j++] = '?';
1321 }
1322 zSql[j++] = ')';
1323 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00001324 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001325 free(zSql);
1326 if( rc ){
1327 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1328 sqlite3_finalize(pStmt);
1329 return TCL_ERROR;
1330 }
1331 in = fopen(zFile, "rb");
1332 if( in==0 ){
1333 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
1334 sqlite3_finalize(pStmt);
1335 return TCL_ERROR;
1336 }
1337 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1338 if( azCol==0 ) {
1339 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00001340 fclose(in);
drh19e2d372005-08-29 23:00:03 +00001341 return TCL_ERROR;
1342 }
drh37527852006-03-16 16:19:56 +00001343 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001344 zCommit = "COMMIT";
1345 while( (zLine = local_getline(0, in))!=0 ){
1346 char *z;
1347 i = 0;
1348 lineno++;
1349 azCol[0] = zLine;
1350 for(i=0, z=zLine; *z; z++){
1351 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
1352 *z = 0;
1353 i++;
1354 if( i<nCol ){
1355 azCol[i] = &z[nSep];
1356 z += nSep-1;
1357 }
1358 }
1359 }
1360 if( i+1!=nCol ){
1361 char *zErr;
drh5bb3eb92007-05-04 13:15:55 +00001362 int nErr = strlen(zFile) + 200;
1363 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00001364 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00001365 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00001366 "Error: %s line %d: expected %d columns of data but found %d",
1367 zFile, lineno, nCol, i+1);
1368 Tcl_AppendResult(interp, zErr, 0);
1369 free(zErr);
1370 }
drh19e2d372005-08-29 23:00:03 +00001371 zCommit = "ROLLBACK";
1372 break;
1373 }
1374 for(i=0; i<nCol; i++){
1375 /* check for null data, if so, bind as null */
1376 if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
1377 sqlite3_bind_null(pStmt, i+1);
1378 }else{
1379 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1380 }
1381 }
1382 sqlite3_step(pStmt);
1383 rc = sqlite3_reset(pStmt);
1384 free(zLine);
1385 if( rc!=SQLITE_OK ){
1386 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
1387 zCommit = "ROLLBACK";
1388 break;
1389 }
1390 }
1391 free(azCol);
1392 fclose(in);
1393 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00001394 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001395
1396 if( zCommit[0] == 'C' ){
1397 /* success, set result as number of lines processed */
1398 pResult = Tcl_GetObjResult(interp);
1399 Tcl_SetIntObj(pResult, lineno);
1400 rc = TCL_OK;
1401 }else{
1402 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00001403 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00001404 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
1405 rc = TCL_ERROR;
1406 }
1407 break;
1408 }
1409
drhdcd997e2003-01-31 17:21:49 +00001410 /*
drh41449052006-07-06 17:08:48 +00001411 ** $db enable_load_extension BOOLEAN
1412 **
1413 ** Turn the extension loading feature on or off. It if off by
1414 ** default.
1415 */
1416 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00001417#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00001418 int onoff;
1419 if( objc!=3 ){
1420 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
1421 return TCL_ERROR;
1422 }
1423 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
1424 return TCL_ERROR;
1425 }
1426 sqlite3_enable_load_extension(pDb->db, onoff);
1427 break;
drhf533acc2006-12-19 18:57:11 +00001428#else
1429 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
1430 0);
1431 return TCL_ERROR;
1432#endif
drh41449052006-07-06 17:08:48 +00001433 }
1434
1435 /*
drhdcd997e2003-01-31 17:21:49 +00001436 ** $db errorcode
1437 **
1438 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00001439 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00001440 */
1441 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00001442 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00001443 break;
1444 }
drh75897232000-05-29 14:26:00 +00001445
1446 /*
drh895d7472004-08-20 16:02:39 +00001447 ** $db eval $sql ?array? ?{ ...code... }?
drh1807ce32004-09-07 13:20:35 +00001448 ** $db onecolumn $sql
drh75897232000-05-29 14:26:00 +00001449 **
1450 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00001451 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00001452 ** If "array" and "code" are omitted, then no callback is every invoked.
1453 ** If "array" is an empty string, then the values are placed in variables
1454 ** that have the same name as the fields extracted by the query.
drh1807ce32004-09-07 13:20:35 +00001455 **
1456 ** The onecolumn method is the equivalent of:
1457 ** lindex [$db eval $sql] 0
drh75897232000-05-29 14:26:00 +00001458 */
drh1807ce32004-09-07 13:20:35 +00001459 case DB_ONECOLUMN:
drh97f2ebc2005-12-10 21:19:04 +00001460 case DB_EVAL:
1461 case DB_EXISTS: {
drh9d74b4c2004-08-24 15:23:34 +00001462 char const *zSql; /* Next SQL statement to execute */
1463 char const *zLeft; /* What is left after first stmt in zSql */
1464 sqlite3_stmt *pStmt; /* Compiled SQL statment */
drh92febd92004-08-20 18:34:20 +00001465 Tcl_Obj *pArray; /* Name of array into which results are written */
1466 Tcl_Obj *pScript; /* Script to run for each result set */
drh1d895032004-08-26 00:56:05 +00001467 Tcl_Obj **apParm; /* Parameters that need a Tcl_DecrRefCount() */
1468 int nParm; /* Number of entries used in apParm[] */
1469 Tcl_Obj *aParm[10]; /* Static space for apParm[] in the common case */
drh1807ce32004-09-07 13:20:35 +00001470 Tcl_Obj *pRet; /* Value to be returned */
drhfb7e7652005-01-24 00:28:42 +00001471 SqlPreparedStmt *pPreStmt; /* Pointer to a prepared statement */
1472 int rc2;
danielk1977ef2cb632004-05-29 02:37:19 +00001473
drh97f2ebc2005-12-10 21:19:04 +00001474 if( choice==DB_EVAL ){
drh1807ce32004-09-07 13:20:35 +00001475 if( objc<3 || objc>5 ){
1476 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
1477 return TCL_ERROR;
1478 }
1479 pRet = Tcl_NewObj();
1480 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001481 }else{
1482 if( objc!=3 ){
1483 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
1484 return TCL_ERROR;
1485 }
drh97f2ebc2005-12-10 21:19:04 +00001486 if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001487 pRet = Tcl_NewBooleanObj(0);
1488 Tcl_IncrRefCount(pRet);
1489 }else{
1490 pRet = 0;
drh97f2ebc2005-12-10 21:19:04 +00001491 }
danielk197730ccda12004-05-27 12:11:31 +00001492 }
drh92febd92004-08-20 18:34:20 +00001493 if( objc==3 ){
1494 pArray = pScript = 0;
1495 }else if( objc==4 ){
1496 pArray = 0;
1497 pScript = objv[3];
1498 }else{
1499 pArray = objv[3];
1500 if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
1501 pScript = objv[4];
1502 }
danielk197730ccda12004-05-27 12:11:31 +00001503
drh1d895032004-08-26 00:56:05 +00001504 Tcl_IncrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001505 zSql = Tcl_GetStringFromObj(objv[2], 0);
drh90b6bb12004-09-13 13:16:31 +00001506 while( rc==TCL_OK && zSql[0] ){
drhfb7e7652005-01-24 00:28:42 +00001507 int i; /* Loop counter */
1508 int nVar; /* Number of bind parameters in the pStmt */
1509 int nCol; /* Number of columns in the result set */
drh92febd92004-08-20 18:34:20 +00001510 Tcl_Obj **apColName = 0; /* Array of column names */
drhfb7e7652005-01-24 00:28:42 +00001511 int len; /* String length of zSql */
danielk197730ccda12004-05-27 12:11:31 +00001512
drhfb7e7652005-01-24 00:28:42 +00001513 /* Try to find a SQL statement that has already been compiled and
1514 ** which matches the next sequence of SQL.
1515 */
1516 pStmt = 0;
1517 pPreStmt = pDb->stmtList;
1518 len = strlen(zSql);
1519 if( pPreStmt && sqlite3_expired(pPreStmt->pStmt) ){
1520 flushStmtCache(pDb);
1521 pPreStmt = 0;
danielk197730ccda12004-05-27 12:11:31 +00001522 }
drhfb7e7652005-01-24 00:28:42 +00001523 for(; pPreStmt; pPreStmt=pPreStmt->pNext){
1524 int n = pPreStmt->nSql;
1525 if( len>=n
1526 && memcmp(pPreStmt->zSql, zSql, n)==0
1527 && (zSql[n]==0 || zSql[n-1]==';')
1528 ){
1529 pStmt = pPreStmt->pStmt;
1530 zLeft = &zSql[pPreStmt->nSql];
1531
1532 /* When a prepared statement is found, unlink it from the
1533 ** cache list. It will later be added back to the beginning
1534 ** of the cache list in order to implement LRU replacement.
1535 */
1536 if( pPreStmt->pPrev ){
1537 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1538 }else{
1539 pDb->stmtList = pPreStmt->pNext;
1540 }
1541 if( pPreStmt->pNext ){
1542 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1543 }else{
1544 pDb->stmtLast = pPreStmt->pPrev;
1545 }
1546 pDb->nStmt--;
1547 break;
1548 }
1549 }
1550
1551 /* If no prepared statement was found. Compile the SQL text
1552 */
drh92febd92004-08-20 18:34:20 +00001553 if( pStmt==0 ){
drhfb7e7652005-01-24 00:28:42 +00001554 if( SQLITE_OK!=sqlite3_prepare(pDb->db, zSql, -1, &pStmt, &zLeft) ){
drh92febd92004-08-20 18:34:20 +00001555 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1556 rc = TCL_ERROR;
1557 break;
danielk197730ccda12004-05-27 12:11:31 +00001558 }
drhfb7e7652005-01-24 00:28:42 +00001559 if( pStmt==0 ){
1560 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1561 /* A compile-time error in the statement
1562 */
1563 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1564 rc = TCL_ERROR;
1565 break;
1566 }else{
1567 /* The statement was a no-op. Continue to the next statement
1568 ** in the SQL string.
1569 */
1570 zSql = zLeft;
1571 continue;
1572 }
1573 }
1574 assert( pPreStmt==0 );
danielk197730ccda12004-05-27 12:11:31 +00001575 }
1576
drhfb7e7652005-01-24 00:28:42 +00001577 /* Bind values to parameters that begin with $ or :
1578 */
drh92febd92004-08-20 18:34:20 +00001579 nVar = sqlite3_bind_parameter_count(pStmt);
drh1d895032004-08-26 00:56:05 +00001580 nParm = 0;
1581 if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
1582 apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
1583 }else{
1584 apParm = aParm;
1585 }
drh92febd92004-08-20 18:34:20 +00001586 for(i=1; i<=nVar; i++){
1587 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
drhc8f90792005-01-12 00:08:24 +00001588 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':') ){
drh92febd92004-08-20 18:34:20 +00001589 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1590 if( pVar ){
1591 int n;
1592 u8 *data;
1593 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
1594 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +00001595 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
1596 /* Only load a BLOB type if the Tcl variable is a bytearray and
1597 ** has no string representation. */
drh92febd92004-08-20 18:34:20 +00001598 data = Tcl_GetByteArrayFromObj(pVar, &n);
1599 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001600 Tcl_IncrRefCount(pVar);
1601 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001602 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
1603 (c=='i' && strcmp(zType,"int")==0) ){
1604 Tcl_GetIntFromObj(interp, pVar, &n);
1605 sqlite3_bind_int(pStmt, i, n);
1606 }else if( c=='d' && strcmp(zType,"double")==0 ){
1607 double r;
1608 Tcl_GetDoubleFromObj(interp, pVar, &r);
1609 sqlite3_bind_double(pStmt, i, r);
drhdf0bdda2005-06-25 19:31:48 +00001610 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
1611 Tcl_WideInt v;
1612 Tcl_GetWideIntFromObj(interp, pVar, &v);
1613 sqlite3_bind_int64(pStmt, i, v);
drh92febd92004-08-20 18:34:20 +00001614 }else{
danielk197700fd9572005-12-07 06:27:43 +00001615 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1616 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001617 Tcl_IncrRefCount(pVar);
1618 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001619 }
drhfb7e7652005-01-24 00:28:42 +00001620 }else{
1621 sqlite3_bind_null( pStmt, i );
drh92febd92004-08-20 18:34:20 +00001622 }
1623 }
1624 }
drh92febd92004-08-20 18:34:20 +00001625
1626 /* Compute column names */
1627 nCol = sqlite3_column_count(pStmt);
1628 if( pScript ){
1629 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1630 if( apColName==0 ) break;
1631 for(i=0; i<nCol; i++){
1632 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1633 Tcl_IncrRefCount(apColName[i]);
1634 }
1635 }
1636
1637 /* If results are being stored in an array variable, then create
1638 ** the array(*) entry for that array
1639 */
1640 if( pArray ){
1641 Tcl_Obj *pColList = Tcl_NewObj();
drh3ced14a2005-03-31 18:26:20 +00001642 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
drh92febd92004-08-20 18:34:20 +00001643 Tcl_IncrRefCount(pColList);
1644 for(i=0; i<nCol; i++){
1645 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1646 }
drh3ced14a2005-03-31 18:26:20 +00001647 Tcl_ObjSetVar2(interp, pArray, pStar, pColList,0);
1648 Tcl_DecrRefCount(pColList);
1649 Tcl_DecrRefCount(pStar);
drh92febd92004-08-20 18:34:20 +00001650 }
1651
1652 /* Execute the SQL
1653 */
drh90b6bb12004-09-13 13:16:31 +00001654 while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
drh92febd92004-08-20 18:34:20 +00001655 for(i=0; i<nCol; i++){
danielk197730ccda12004-05-27 12:11:31 +00001656 Tcl_Obj *pVal;
1657
1658 /* Set pVal to contain the i'th column of this row. */
drh92febd92004-08-20 18:34:20 +00001659 switch( sqlite3_column_type(pStmt, i) ){
1660 case SQLITE_BLOB: {
1661 int bytes = sqlite3_column_bytes(pStmt, i);
1662 pVal = Tcl_NewByteArrayObj(sqlite3_column_blob(pStmt, i), bytes);
1663 break;
1664 }
1665 case SQLITE_INTEGER: {
1666 sqlite_int64 v = sqlite3_column_int64(pStmt, i);
1667 if( v>=-2147483647 && v<=2147483647 ){
1668 pVal = Tcl_NewIntObj(v);
1669 }else{
1670 pVal = Tcl_NewWideIntObj(v);
1671 }
1672 break;
1673 }
1674 case SQLITE_FLOAT: {
1675 double r = sqlite3_column_double(pStmt, i);
1676 pVal = Tcl_NewDoubleObj(r);
1677 break;
1678 }
danielk197755c45f22005-04-03 23:54:43 +00001679 case SQLITE_NULL: {
1680 pVal = dbTextToObj(pDb->zNull);
1681 break;
1682 }
drh92febd92004-08-20 18:34:20 +00001683 default: {
danielk197700fd9572005-12-07 06:27:43 +00001684 pVal = dbTextToObj((char *)sqlite3_column_text(pStmt, i));
drh92febd92004-08-20 18:34:20 +00001685 break;
1686 }
danielk197730ccda12004-05-27 12:11:31 +00001687 }
1688
drh92febd92004-08-20 18:34:20 +00001689 if( pScript ){
1690 if( pArray==0 ){
1691 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001692 }else{
drh92febd92004-08-20 18:34:20 +00001693 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001694 }
drh1807ce32004-09-07 13:20:35 +00001695 }else if( choice==DB_ONECOLUMN ){
drh97f2ebc2005-12-10 21:19:04 +00001696 assert( pRet==0 );
drh1807ce32004-09-07 13:20:35 +00001697 if( pRet==0 ){
1698 pRet = pVal;
1699 Tcl_IncrRefCount(pRet);
1700 }
drh90b6bb12004-09-13 13:16:31 +00001701 rc = TCL_BREAK;
drh97f2ebc2005-12-10 21:19:04 +00001702 i = nCol;
1703 }else if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001704 Tcl_DecrRefCount(pRet);
1705 pRet = Tcl_NewBooleanObj(1);
1706 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001707 rc = TCL_BREAK;
1708 i = nCol;
danielk197730ccda12004-05-27 12:11:31 +00001709 }else{
danielk197730ccda12004-05-27 12:11:31 +00001710 Tcl_ListObjAppendElement(interp, pRet, pVal);
1711 }
1712 }
1713
drh92febd92004-08-20 18:34:20 +00001714 if( pScript ){
1715 rc = Tcl_EvalObjEx(interp, pScript, 0);
drh90b6bb12004-09-13 13:16:31 +00001716 if( rc==TCL_CONTINUE ){
1717 rc = TCL_OK;
1718 }
danielk197730ccda12004-05-27 12:11:31 +00001719 }
1720 }
drh90b6bb12004-09-13 13:16:31 +00001721 if( rc==TCL_BREAK ){
1722 rc = TCL_OK;
1723 }
drh92febd92004-08-20 18:34:20 +00001724
1725 /* Free the column name objects */
1726 if( pScript ){
1727 for(i=0; i<nCol; i++){
1728 Tcl_DecrRefCount(apColName[i]);
1729 }
1730 Tcl_Free((char*)apColName);
1731 }
1732
drh1d895032004-08-26 00:56:05 +00001733 /* Free the bound string and blob parameters */
1734 for(i=0; i<nParm; i++){
1735 Tcl_DecrRefCount(apParm[i]);
1736 }
1737 if( apParm!=aParm ){
1738 Tcl_Free((char*)apParm);
1739 }
1740
drhfb7e7652005-01-24 00:28:42 +00001741 /* Reset the statement. If the result code is SQLITE_SCHEMA, then
1742 ** flush the statement cache and try the statement again.
drh92febd92004-08-20 18:34:20 +00001743 */
drhfb7e7652005-01-24 00:28:42 +00001744 rc2 = sqlite3_reset(pStmt);
1745 if( SQLITE_SCHEMA==rc2 ){
1746 /* After a schema change, flush the cache and try to run the
1747 ** statement again
1748 */
1749 flushStmtCache( pDb );
1750 sqlite3_finalize(pStmt);
1751 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001752 continue;
drhfb7e7652005-01-24 00:28:42 +00001753 }else if( SQLITE_OK!=rc2 ){
1754 /* If a run-time error occurs, report the error and stop reading
1755 ** the SQL
1756 */
danielk1977ef2cb632004-05-29 02:37:19 +00001757 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
drhfb7e7652005-01-24 00:28:42 +00001758 sqlite3_finalize(pStmt);
danielk197730ccda12004-05-27 12:11:31 +00001759 rc = TCL_ERROR;
drhfb7e7652005-01-24 00:28:42 +00001760 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001761 break;
drhfb7e7652005-01-24 00:28:42 +00001762 }else if( pDb->maxStmt<=0 ){
1763 /* If the cache is turned off, deallocated the statement */
1764 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1765 sqlite3_finalize(pStmt);
1766 }else{
1767 /* Everything worked and the cache is operational.
1768 ** Create a new SqlPreparedStmt structure if we need one.
1769 ** (If we already have one we can just reuse it.)
1770 */
1771 if( pPreStmt==0 ){
1772 len = zLeft - zSql;
1773 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) + len );
1774 if( pPreStmt==0 ) return TCL_ERROR;
1775 pPreStmt->pStmt = pStmt;
1776 pPreStmt->nSql = len;
1777 memcpy(pPreStmt->zSql, zSql, len);
1778 pPreStmt->zSql[len] = 0;
1779 }
1780
1781 /* Add the prepared statement to the beginning of the cache list
1782 */
1783 pPreStmt->pNext = pDb->stmtList;
1784 pPreStmt->pPrev = 0;
1785 if( pDb->stmtList ){
1786 pDb->stmtList->pPrev = pPreStmt;
1787 }
1788 pDb->stmtList = pPreStmt;
1789 if( pDb->stmtLast==0 ){
1790 assert( pDb->nStmt==0 );
1791 pDb->stmtLast = pPreStmt;
1792 }else{
1793 assert( pDb->nStmt>0 );
1794 }
1795 pDb->nStmt++;
1796
1797 /* If we have too many statement in cache, remove the surplus from the
1798 ** end of the cache list.
1799 */
1800 while( pDb->nStmt>pDb->maxStmt ){
1801 sqlite3_finalize(pDb->stmtLast->pStmt);
1802 pDb->stmtLast = pDb->stmtLast->pPrev;
1803 Tcl_Free((char*)pDb->stmtLast->pNext);
1804 pDb->stmtLast->pNext = 0;
1805 pDb->nStmt--;
1806 }
danielk197730ccda12004-05-27 12:11:31 +00001807 }
1808
drhfb7e7652005-01-24 00:28:42 +00001809 /* Proceed to the next statement */
danielk197730ccda12004-05-27 12:11:31 +00001810 zSql = zLeft;
1811 }
drh1d895032004-08-26 00:56:05 +00001812 Tcl_DecrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001813
drh1807ce32004-09-07 13:20:35 +00001814 if( pRet ){
1815 if( rc==TCL_OK ){
1816 Tcl_SetObjResult(interp, pRet);
1817 }
1818 Tcl_DecrRefCount(pRet);
drh050be322006-07-12 00:18:40 +00001819 }else if( rc==TCL_OK ){
1820 Tcl_ResetResult(interp);
danielk197730ccda12004-05-27 12:11:31 +00001821 }
danielk197730ccda12004-05-27 12:11:31 +00001822 break;
1823 }
drhbec3f402000-08-04 13:49:02 +00001824
1825 /*
drhcabb0812002-09-14 13:47:32 +00001826 ** $db function NAME SCRIPT
1827 **
1828 ** Create a new SQL function called NAME. Whenever that function is
1829 ** called, invoke SCRIPT to evaluate the function.
1830 */
1831 case DB_FUNCTION: {
1832 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00001833 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00001834 char *zName;
drhcabb0812002-09-14 13:47:32 +00001835 if( objc!=4 ){
1836 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1837 return TCL_ERROR;
1838 }
1839 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00001840 pScript = objv[3];
1841 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00001842 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00001843 if( pFunc->pScript ){
1844 Tcl_DecrRefCount(pFunc->pScript);
1845 }
1846 pFunc->pScript = pScript;
1847 Tcl_IncrRefCount(pScript);
1848 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
danielk1977c8c11582004-06-29 13:41:21 +00001849 rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00001850 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00001851 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00001852 rc = TCL_ERROR;
1853 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00001854 }else{
1855 /* Must flush any cached statements */
1856 flushStmtCache( pDb );
1857 }
drhcabb0812002-09-14 13:47:32 +00001858 break;
1859 }
1860
1861 /*
danielk19778cbadb02007-05-03 16:31:26 +00001862 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00001863 */
1864 case DB_INCRBLOB: {
danielk19778cbadb02007-05-03 16:31:26 +00001865 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00001866 const char *zDb = "main";
1867 const char *zTable;
1868 const char *zColumn;
1869 sqlite_int64 iRow;
1870
danielk19778cbadb02007-05-03 16:31:26 +00001871 /* Check for the -readonly option */
1872 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
1873 isReadonly = 1;
1874 }
1875
1876 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
1877 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00001878 return TCL_ERROR;
1879 }
1880
danielk19778cbadb02007-05-03 16:31:26 +00001881 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00001882 zDb = Tcl_GetString(objv[2]);
1883 }
1884 zTable = Tcl_GetString(objv[objc-3]);
1885 zColumn = Tcl_GetString(objv[objc-2]);
1886 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
1887
1888 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00001889 rc = createIncrblobChannel(
1890 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
1891 );
danielk1977b4e9af92007-05-01 17:49:49 +00001892 }
1893 break;
1894 }
1895
1896 /*
drhf11bded2006-07-17 00:02:44 +00001897 ** $db interrupt
1898 **
1899 ** Interrupt the execution of the inner-most SQL interpreter. This
1900 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
1901 */
1902 case DB_INTERRUPT: {
1903 sqlite3_interrupt(pDb->db);
1904 break;
1905 }
1906
1907 /*
drh19e2d372005-08-29 23:00:03 +00001908 ** $db nullvalue ?STRING?
1909 **
1910 ** Change text used when a NULL comes back from the database. If ?STRING?
1911 ** is not present, then the current string used for NULL is returned.
1912 ** If STRING is present, then STRING is returned.
1913 **
1914 */
1915 case DB_NULLVALUE: {
1916 if( objc!=2 && objc!=3 ){
1917 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
1918 return TCL_ERROR;
1919 }
1920 if( objc==3 ){
1921 int len;
1922 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
1923 if( pDb->zNull ){
1924 Tcl_Free(pDb->zNull);
1925 }
1926 if( zNull && len>0 ){
1927 pDb->zNull = Tcl_Alloc( len + 1 );
1928 strncpy(pDb->zNull, zNull, len);
1929 pDb->zNull[len] = '\0';
1930 }else{
1931 pDb->zNull = 0;
1932 }
1933 }
1934 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
1935 break;
1936 }
1937
1938 /*
drhaf9ff332002-01-16 21:00:27 +00001939 ** $db last_insert_rowid
1940 **
1941 ** Return an integer which is the ROWID for the most recent insert.
1942 */
1943 case DB_LAST_INSERT_ROWID: {
1944 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00001945 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00001946 if( objc!=2 ){
1947 Tcl_WrongNumArgs(interp, 2, objv, "");
1948 return TCL_ERROR;
1949 }
danielk19776f8a5032004-05-10 10:34:51 +00001950 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00001951 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00001952 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00001953 break;
1954 }
1955
1956 /*
drh1807ce32004-09-07 13:20:35 +00001957 ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
drh5d9d7572003-08-19 14:31:01 +00001958 */
drh1807ce32004-09-07 13:20:35 +00001959
1960 /* $db progress ?N CALLBACK?
1961 **
1962 ** Invoke the given callback every N virtual machine opcodes while executing
1963 ** queries.
1964 */
1965 case DB_PROGRESS: {
1966 if( objc==2 ){
1967 if( pDb->zProgress ){
1968 Tcl_AppendResult(interp, pDb->zProgress, 0);
1969 }
1970 }else if( objc==4 ){
1971 char *zProgress;
1972 int len;
1973 int N;
1974 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
1975 return TCL_ERROR;
1976 };
1977 if( pDb->zProgress ){
1978 Tcl_Free(pDb->zProgress);
1979 }
1980 zProgress = Tcl_GetStringFromObj(objv[3], &len);
1981 if( zProgress && len>0 ){
1982 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001983 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00001984 }else{
1985 pDb->zProgress = 0;
1986 }
1987#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1988 if( pDb->zProgress ){
1989 pDb->interp = interp;
1990 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
1991 }else{
1992 sqlite3_progress_handler(pDb->db, 0, 0, 0);
1993 }
1994#endif
1995 }else{
1996 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00001997 return TCL_ERROR;
1998 }
drh5d9d7572003-08-19 14:31:01 +00001999 break;
2000 }
2001
drh19e2d372005-08-29 23:00:03 +00002002 /* $db profile ?CALLBACK?
2003 **
2004 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2005 ** that has run. The text of the SQL and the amount of elapse time are
2006 ** appended to CALLBACK before the script is run.
2007 */
2008 case DB_PROFILE: {
2009 if( objc>3 ){
2010 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2011 return TCL_ERROR;
2012 }else if( objc==2 ){
2013 if( pDb->zProfile ){
2014 Tcl_AppendResult(interp, pDb->zProfile, 0);
2015 }
2016 }else{
2017 char *zProfile;
2018 int len;
2019 if( pDb->zProfile ){
2020 Tcl_Free(pDb->zProfile);
2021 }
2022 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2023 if( zProfile && len>0 ){
2024 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002025 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002026 }else{
2027 pDb->zProfile = 0;
2028 }
2029#ifndef SQLITE_OMIT_TRACE
2030 if( pDb->zProfile ){
2031 pDb->interp = interp;
2032 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2033 }else{
2034 sqlite3_profile(pDb->db, 0, 0);
2035 }
2036#endif
2037 }
2038 break;
2039 }
2040
drh5d9d7572003-08-19 14:31:01 +00002041 /*
drh22fbcb82004-02-01 01:22:50 +00002042 ** $db rekey KEY
2043 **
2044 ** Change the encryption key on the currently open database.
2045 */
2046 case DB_REKEY: {
2047 int nKey;
2048 void *pKey;
2049 if( objc!=3 ){
2050 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2051 return TCL_ERROR;
2052 }
2053 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00002054#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00002055 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002056 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00002057 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002058 rc = TCL_ERROR;
2059 }
2060#endif
2061 break;
2062 }
2063
2064 /*
drhbec3f402000-08-04 13:49:02 +00002065 ** $db timeout MILLESECONDS
2066 **
2067 ** Delay for the number of milliseconds specified when a file is locked.
2068 */
drh6d313162000-09-21 13:01:35 +00002069 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002070 int ms;
drh6d313162000-09-21 13:01:35 +00002071 if( objc!=3 ){
2072 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002073 return TCL_ERROR;
2074 }
drh6d313162000-09-21 13:01:35 +00002075 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002076 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002077 break;
drh75897232000-05-29 14:26:00 +00002078 }
danielk197755c45f22005-04-03 23:54:43 +00002079
2080 /*
drh0f14e2e2004-06-29 12:39:08 +00002081 ** $db total_changes
2082 **
2083 ** Return the number of rows that were modified, inserted, or deleted
2084 ** since the database handle was created.
2085 */
2086 case DB_TOTAL_CHANGES: {
2087 Tcl_Obj *pResult;
2088 if( objc!=2 ){
2089 Tcl_WrongNumArgs(interp, 2, objv, "");
2090 return TCL_ERROR;
2091 }
2092 pResult = Tcl_GetObjResult(interp);
2093 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2094 break;
2095 }
2096
drhb5a20d32003-04-23 12:25:23 +00002097 /* $db trace ?CALLBACK?
2098 **
2099 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2100 ** that is executed. The text of the SQL is appended to CALLBACK before
2101 ** it is executed.
2102 */
2103 case DB_TRACE: {
2104 if( objc>3 ){
2105 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002106 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002107 }else if( objc==2 ){
2108 if( pDb->zTrace ){
2109 Tcl_AppendResult(interp, pDb->zTrace, 0);
2110 }
2111 }else{
2112 char *zTrace;
2113 int len;
2114 if( pDb->zTrace ){
2115 Tcl_Free(pDb->zTrace);
2116 }
2117 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2118 if( zTrace && len>0 ){
2119 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002120 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002121 }else{
2122 pDb->zTrace = 0;
2123 }
drh19e2d372005-08-29 23:00:03 +00002124#ifndef SQLITE_OMIT_TRACE
drhb5a20d32003-04-23 12:25:23 +00002125 if( pDb->zTrace ){
2126 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002127 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002128 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002129 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002130 }
drh19e2d372005-08-29 23:00:03 +00002131#endif
drhb5a20d32003-04-23 12:25:23 +00002132 }
2133 break;
2134 }
2135
drh3d214232005-08-02 12:21:08 +00002136 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2137 **
2138 ** Start a new transaction (if we are not already in the midst of a
2139 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2140 ** completes, either commit the transaction or roll it back if SCRIPT
2141 ** throws an exception. Or if no new transation was started, do nothing.
2142 ** pass the exception on up the stack.
2143 **
2144 ** This command was inspired by Dave Thomas's talk on Ruby at the
2145 ** 2005 O'Reilly Open Source Convention (OSCON).
2146 */
2147 case DB_TRANSACTION: {
2148 int inTrans;
2149 Tcl_Obj *pScript;
2150 const char *zBegin = "BEGIN";
2151 if( objc!=3 && objc!=4 ){
2152 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2153 return TCL_ERROR;
2154 }
2155 if( objc==3 ){
2156 pScript = objv[2];
2157 } else {
2158 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002159 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002160 };
2161 enum TTYPE_enum {
2162 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2163 };
2164 int ttype;
drhb5555e72005-08-02 17:15:14 +00002165 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002166 0, &ttype) ){
2167 return TCL_ERROR;
2168 }
2169 switch( (enum TTYPE_enum)ttype ){
2170 case TTYPE_DEFERRED: /* no-op */; break;
2171 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2172 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2173 }
2174 pScript = objv[3];
2175 }
2176 inTrans = !sqlite3_get_autocommit(pDb->db);
2177 if( !inTrans ){
drh37527852006-03-16 16:19:56 +00002178 (void)sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
drh3d214232005-08-02 12:21:08 +00002179 }
2180 rc = Tcl_EvalObjEx(interp, pScript, 0);
2181 if( !inTrans ){
2182 const char *zEnd;
2183 if( rc==TCL_ERROR ){
2184 zEnd = "ROLLBACK";
2185 } else {
2186 zEnd = "COMMIT";
2187 }
drh37527852006-03-16 16:19:56 +00002188 (void)sqlite3_exec(pDb->db, zEnd, 0, 0, 0);
drh3d214232005-08-02 12:21:08 +00002189 }
2190 break;
2191 }
2192
danielk197794eb6a12005-12-15 15:22:08 +00002193 /*
2194 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002195 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002196 */
danielk197771fd80b2005-12-16 06:54:01 +00002197 case DB_UPDATE_HOOK:
2198 case DB_ROLLBACK_HOOK: {
2199
2200 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2201 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2202 */
2203 Tcl_Obj **ppHook;
2204 if( choice==DB_UPDATE_HOOK ){
2205 ppHook = &pDb->pUpdateHook;
2206 }else{
2207 ppHook = &pDb->pRollbackHook;
2208 }
2209
danielk197794eb6a12005-12-15 15:22:08 +00002210 if( objc!=2 && objc!=3 ){
2211 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2212 return TCL_ERROR;
2213 }
danielk197771fd80b2005-12-16 06:54:01 +00002214 if( *ppHook ){
2215 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002216 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002217 Tcl_DecrRefCount(*ppHook);
2218 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00002219 }
2220 }
2221 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002222 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00002223 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00002224 *ppHook = objv[2];
2225 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002226 }
2227 }
danielk197771fd80b2005-12-16 06:54:01 +00002228
2229 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2230 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
2231
danielk197794eb6a12005-12-15 15:22:08 +00002232 break;
2233 }
2234
danielk19774397de52005-01-12 12:44:03 +00002235 /* $db version
2236 **
2237 ** Return the version string for this database.
2238 */
2239 case DB_VERSION: {
2240 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2241 break;
2242 }
2243
tpoindex1067fe12004-12-17 15:41:11 +00002244
drh6d313162000-09-21 13:01:35 +00002245 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002246 return rc;
drh75897232000-05-29 14:26:00 +00002247}
2248
2249/*
drh9bb575f2004-09-06 17:24:11 +00002250** sqlite3 DBNAME FILENAME ?MODE? ?-key KEY?
drh75897232000-05-29 14:26:00 +00002251**
2252** This is the main Tcl command. When the "sqlite" Tcl command is
2253** invoked, this routine runs to process that command.
2254**
2255** The first argument, DBNAME, is an arbitrary name for a new
2256** database connection. This command creates a new command named
2257** DBNAME that is used to control that connection. The database
2258** connection is deleted when the DBNAME command is deleted.
2259**
2260** The second argument is the name of the directory that contains
2261** the sqlite database that is to be accessed.
drhfbc3eab2001-04-06 16:13:42 +00002262**
2263** For testing purposes, we also support the following:
2264**
drh9bb575f2004-09-06 17:24:11 +00002265** sqlite3 -encoding
drhfbc3eab2001-04-06 16:13:42 +00002266**
2267** Return the encoding used by LIKE and GLOB operators. Choices
2268** are UTF-8 and iso8859.
2269**
drh9bb575f2004-09-06 17:24:11 +00002270** sqlite3 -version
drh647cb0e2002-11-04 19:32:25 +00002271**
2272** Return the version number of the SQLite library.
2273**
drh9bb575f2004-09-06 17:24:11 +00002274** sqlite3 -tcl-uses-utf
drhfbc3eab2001-04-06 16:13:42 +00002275**
2276** Return "1" if compiled with a Tcl uses UTF-8. Return "0" if
2277** not. Used by tests to make sure the library was compiled
2278** correctly.
drh75897232000-05-29 14:26:00 +00002279*/
drh22fbcb82004-02-01 01:22:50 +00002280static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002281 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002282 void *pKey = 0;
2283 int nKey = 0;
2284 const char *zArg;
drh75897232000-05-29 14:26:00 +00002285 char *zErrMsg;
drh22fbcb82004-02-01 01:22:50 +00002286 const char *zFile;
drh882e8e42006-08-24 02:42:27 +00002287 Tcl_DString translatedFilename;
drh22fbcb82004-02-01 01:22:50 +00002288 if( objc==2 ){
2289 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002290 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00002291 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00002292 return TCL_OK;
2293 }
drh9eb9e262004-02-11 02:18:05 +00002294 if( strcmp(zArg,"-has-codec")==0 ){
2295#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002296 Tcl_AppendResult(interp,"1",0);
2297#else
2298 Tcl_AppendResult(interp,"0",0);
2299#endif
2300 return TCL_OK;
2301 }
2302 if( strcmp(zArg,"-tcl-uses-utf")==0 ){
drhfbc3eab2001-04-06 16:13:42 +00002303#ifdef TCL_UTF_MAX
2304 Tcl_AppendResult(interp,"1",0);
2305#else
2306 Tcl_AppendResult(interp,"0",0);
2307#endif
2308 return TCL_OK;
2309 }
2310 }
drh22fbcb82004-02-01 01:22:50 +00002311 if( objc==5 || objc==6 ){
2312 zArg = Tcl_GetStringFromObj(objv[objc-2], 0);
2313 if( strcmp(zArg,"-key")==0 ){
2314 pKey = Tcl_GetByteArrayFromObj(objv[objc-1], &nKey);
2315 objc -= 2;
2316 }
2317 }
2318 if( objc!=3 && objc!=4 ){
2319 Tcl_WrongNumArgs(interp, 1, objv,
drh9eb9e262004-02-11 02:18:05 +00002320#ifdef SQLITE_HAS_CODEC
2321 "HANDLE FILENAME ?-key CODEC-KEY?"
drh22fbcb82004-02-01 01:22:50 +00002322#else
2323 "HANDLE FILENAME ?MODE?"
2324#endif
2325 );
drh75897232000-05-29 14:26:00 +00002326 return TCL_ERROR;
2327 }
drh75897232000-05-29 14:26:00 +00002328 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00002329 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00002330 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00002331 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
2332 return TCL_ERROR;
2333 }
2334 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00002335 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00002336 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
danielk19774f057f92004-06-08 00:02:33 +00002337 sqlite3_open(zFile, &p->db);
drh882e8e42006-08-24 02:42:27 +00002338 Tcl_DStringFree(&translatedFilename);
danielk197780290862004-05-22 09:21:21 +00002339 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
drh9404d502006-12-19 18:46:08 +00002340 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
danielk197780290862004-05-22 09:21:21 +00002341 sqlite3_close(p->db);
2342 p->db = 0;
2343 }
drh2011d5f2004-07-22 02:40:37 +00002344#ifdef SQLITE_HAS_CODEC
2345 sqlite3_key(p->db, pKey, nKey);
drheb8ed702004-02-11 10:37:23 +00002346#endif
drhbec3f402000-08-04 13:49:02 +00002347 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00002348 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00002349 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00002350 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00002351 return TCL_ERROR;
2352 }
drhfb7e7652005-01-24 00:28:42 +00002353 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00002354 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00002355 zArg = Tcl_GetStringFromObj(objv[1], 0);
2356 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
drhc22bd472002-05-10 13:14:07 +00002357
2358 /* If compiled with SQLITE_TEST turned on, then register the "md5sum"
drh06b27182002-06-26 20:06:05 +00002359 ** SQL function.
drhc22bd472002-05-10 13:14:07 +00002360 */
drh28b4e482002-03-11 02:06:13 +00002361#ifdef SQLITE_TEST
2362 {
drh9bb575f2004-09-06 17:24:11 +00002363 extern void Md5_Register(sqlite3*);
drh3b93bc82005-01-13 23:54:32 +00002364#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00002365 int mallocfail = sqlite3_iMallocFail;
2366 sqlite3_iMallocFail = 0;
danielk19775b59af82004-06-30 12:42:59 +00002367#endif
drhc22bd472002-05-10 13:14:07 +00002368 Md5_Register(p->db);
drh3b93bc82005-01-13 23:54:32 +00002369#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00002370 sqlite3_iMallocFail = mallocfail;
danielk19775b59af82004-06-30 12:42:59 +00002371#endif
danielk19777ddad962005-12-12 06:53:03 +00002372 }
drh28b4e482002-03-11 02:06:13 +00002373#endif
drh75897232000-05-29 14:26:00 +00002374 return TCL_OK;
2375}
2376
2377/*
drh90ca9752001-09-28 17:47:14 +00002378** Provide a dummy Tcl_InitStubs if we are using this as a static
2379** library.
2380*/
2381#ifndef USE_TCL_STUBS
2382# undef Tcl_InitStubs
2383# define Tcl_InitStubs(a,b,c)
2384#endif
2385
2386/*
drh29bc4612005-10-05 10:40:15 +00002387** Make sure we have a PACKAGE_VERSION macro defined. This will be
2388** defined automatically by the TEA makefile. But other makefiles
2389** do not define it.
2390*/
2391#ifndef PACKAGE_VERSION
2392# define PACKAGE_VERSION SQLITE_VERSION
2393#endif
2394
2395/*
drh75897232000-05-29 14:26:00 +00002396** Initialize this module.
2397**
2398** This Tcl module contains only a single new Tcl command named "sqlite".
2399** (Hence there is no namespace. There is no point in using a namespace
2400** if the extension only supplies one new name!) The "sqlite" command is
2401** used to open a new SQLite database. See the DbMain() routine above
2402** for additional information.
2403*/
drhad6e1372006-07-10 21:15:51 +00002404EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00002405 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00002406 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002407 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh49766d62005-01-08 18:42:28 +00002408 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002409 Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
drh90ca9752001-09-28 17:47:14 +00002410 return TCL_OK;
2411}
drhad6e1372006-07-10 21:15:51 +00002412EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2413EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2414EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002415
2416#ifndef SQLITE_3_SUFFIX_ONLY
drhad6e1372006-07-10 21:15:51 +00002417EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2418EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2419EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2420EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002421#endif
drh75897232000-05-29 14:26:00 +00002422
drh3e27c022004-07-23 00:01:38 +00002423#ifdef TCLSH
2424/*****************************************************************************
2425** The code that follows is used to build standalone TCL interpreters
drh75897232000-05-29 14:26:00 +00002426*/
drh348784e2000-05-29 20:41:49 +00002427
2428/*
drh3e27c022004-07-23 00:01:38 +00002429** If the macro TCLSH is one, then put in code this for the
2430** "main" routine that will initialize Tcl and take input from
2431** standard input.
drh348784e2000-05-29 20:41:49 +00002432*/
drh3e27c022004-07-23 00:01:38 +00002433#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00002434static char zMainloop[] =
2435 "set line {}\n"
2436 "while {![eof stdin]} {\n"
2437 "if {$line!=\"\"} {\n"
2438 "puts -nonewline \"> \"\n"
2439 "} else {\n"
2440 "puts -nonewline \"% \"\n"
2441 "}\n"
2442 "flush stdout\n"
2443 "append line [gets stdin]\n"
2444 "if {[info complete $line]} {\n"
2445 "if {[catch {uplevel #0 $line} result]} {\n"
2446 "puts stderr \"Error: $result\"\n"
2447 "} elseif {$result!=\"\"} {\n"
2448 "puts $result\n"
2449 "}\n"
2450 "set line {}\n"
2451 "} else {\n"
2452 "append line \\n\n"
2453 "}\n"
2454 "}\n"
2455;
drh3e27c022004-07-23 00:01:38 +00002456#endif
2457
2458/*
2459** If the macro TCLSH is two, then get the main loop code out of
2460** the separate file "spaceanal_tcl.h".
2461*/
2462#if TCLSH==2
2463static char zMainloop[] =
2464#include "spaceanal_tcl.h"
2465;
2466#endif
drh348784e2000-05-29 20:41:49 +00002467
2468#define TCLSH_MAIN main /* Needed to fake out mktclapp */
2469int TCLSH_MAIN(int argc, char **argv){
2470 Tcl_Interp *interp;
drh297ecf12001-04-05 15:57:13 +00002471 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00002472 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00002473 Sqlite3_Init(interp);
drhd9b02572001-04-15 00:37:09 +00002474#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00002475 {
2476 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00002477 extern int Sqlitetest2_Init(Tcl_Interp*);
2478 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00002479 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00002480 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00002481 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00002482 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00002483 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00002484 extern int Sqlitetest9_Init(Tcl_Interp*);
drhefc251d2001-07-01 22:12:01 +00002485 extern int Md5_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002486 extern int Sqlitetestsse_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00002487 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh4be8b512006-06-13 23:51:34 +00002488 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk1977954ce992006-06-15 15:59:19 +00002489 extern int Sqlitetestschema_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00002490 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00002491 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002492
danielk19776490beb2004-05-11 06:17:21 +00002493 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00002494 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00002495 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00002496 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00002497 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00002498 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00002499 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00002500 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00002501 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00002502 Sqlitetestasync_Init(interp);
drh4be8b512006-06-13 23:51:34 +00002503 Sqlitetesttclvar_Init(interp);
danielk1977954ce992006-06-15 15:59:19 +00002504 Sqlitetestschema_Init(interp);
drh1409be62006-08-23 20:07:20 +00002505 Sqlitetest_autoext_Init(interp);
drh15926592007-04-06 15:02:13 +00002506 Sqlitetest_hexio_Init(interp);
drhefc251d2001-07-01 22:12:01 +00002507 Md5_Init(interp);
drh89dec812005-04-28 19:03:37 +00002508#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00002509 Sqlitetestsse_Init(interp);
2510#endif
drhd1bf3512001-04-07 15:24:33 +00002511 }
2512#endif
drh3e27c022004-07-23 00:01:38 +00002513 if( argc>=2 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002514 int i;
shessad42c3a2006-08-22 23:53:46 +00002515 char zArgc[32];
2516 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
2517 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00002518 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
2519 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00002520 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00002521 Tcl_SetVar(interp, "argv", argv[i],
2522 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
2523 }
drh3e27c022004-07-23 00:01:38 +00002524 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00002525 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drhc61053b2000-06-04 12:58:36 +00002526 if( zInfo==0 ) zInfo = interp->result;
2527 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00002528 return 1;
2529 }
drh3e27c022004-07-23 00:01:38 +00002530 }
2531 if( argc<=1 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002532 Tcl_GlobalEval(interp, zMainloop);
2533 }
2534 return 0;
2535}
2536#endif /* TCLSH */