blob: 6a9434131e41c517435c2cde9244c2f82efd3ad4 [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**
danielk19778e556522007-11-13 10:30:24 +000015** $Id: tclsqlite.c,v 1.206 2007/11/13 10:30:26 danielk1977 Exp $
drh75897232000-05-29 14:26:00 +000016*/
drh17a68932001-01-31 13:28:08 +000017#include "tcl.h"
danielk1977b4e9af92007-05-01 17:49:49 +000018#include <errno.h>
drhbd08af42007-04-05 21:58:33 +000019
20/*
21** Some additional include files are needed if this file is not
22** appended to the amalgamation.
23*/
24#ifndef SQLITE_AMALGAMATION
25# include "sqliteInt.h"
drhbd08af42007-04-05 21:58:33 +000026# include <stdlib.h>
27# include <string.h>
28# include <assert.h>
29# include <ctype.h>
30#endif
drh75897232000-05-29 14:26:00 +000031
drhad6e1372006-07-10 21:15:51 +000032/*
33 * Windows needs to know which symbols to export. Unix does not.
34 * BUILD_sqlite should be undefined for Unix.
35 */
36#ifdef BUILD_sqlite
37#undef TCL_STORAGE_CLASS
38#define TCL_STORAGE_CLASS DLLEXPORT
39#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000040
danielk1977a21c6b62005-01-24 10:25:59 +000041#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000042#define MAX_PREPARED_STMTS 100
43
drh75897232000-05-29 14:26:00 +000044/*
drh98808ba2001-10-18 12:34:46 +000045** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
46** have to do a translation when going between the two. Set the
47** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
48** this translation.
49*/
50#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
51# define UTF_TRANSLATION_NEEDED 1
52#endif
53
54/*
drhcabb0812002-09-14 13:47:32 +000055** New SQL functions can be created as TCL scripts. Each such function
56** is described by an instance of the following structure.
57*/
58typedef struct SqlFunc SqlFunc;
59struct SqlFunc {
60 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000061 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
62 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
63 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000064 SqlFunc *pNext; /* Next function on the list of them all */
65};
66
67/*
danielk19770202b292004-06-09 09:55:16 +000068** New collation sequences function can be created as TCL scripts. Each such
69** function is described by an instance of the following structure.
70*/
71typedef struct SqlCollate SqlCollate;
72struct SqlCollate {
73 Tcl_Interp *interp; /* The TCL interpret to execute the function */
74 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000075 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000076};
77
78/*
drhfb7e7652005-01-24 00:28:42 +000079** Prepared statements are cached for faster execution. Each prepared
80** statement is described by an instance of the following structure.
81*/
82typedef struct SqlPreparedStmt SqlPreparedStmt;
83struct SqlPreparedStmt {
84 SqlPreparedStmt *pNext; /* Next in linked list */
85 SqlPreparedStmt *pPrev; /* Previous on the list */
86 sqlite3_stmt *pStmt; /* The prepared statement */
87 int nSql; /* chars in zSql[] */
88 char zSql[1]; /* Text of the SQL statement */
89};
90
danielk1977d04417962007-05-02 13:16:30 +000091typedef struct IncrblobChannel IncrblobChannel;
92
drhfb7e7652005-01-24 00:28:42 +000093/*
drhbec3f402000-08-04 13:49:02 +000094** There is one instance of this structure for each SQLite database
95** that has been opened by the SQLite TCL interface.
96*/
97typedef struct SqliteDb SqliteDb;
98struct SqliteDb {
drhdddca282006-01-03 00:33:50 +000099 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000100 Tcl_Interp *interp; /* The interpreter used for this database */
101 char *zBusy; /* The busy callback routine */
102 char *zCommit; /* The commit hook callback routine */
103 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +0000104 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000105 char *zProgress; /* The progress callback routine */
106 char *zAuth; /* The authorization callback routine */
107 char *zNull; /* Text to substitute for an SQL NULL value */
108 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000109 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000110 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drhd1e47332005-06-26 17:55:33 +0000111 SqlCollate *pCollate; /* List of SQL collation functions */
112 int rc; /* Return code of most recent sqlite3_exec() */
113 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000114 SqlPreparedStmt *stmtList; /* List of prepared statements*/
115 SqlPreparedStmt *stmtLast; /* Last statement in the list */
116 int maxStmt; /* The next maximum number of stmtList */
117 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000118 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh98808ba2001-10-18 12:34:46 +0000119};
drh297ecf12001-04-05 15:57:13 +0000120
danielk1977b4e9af92007-05-01 17:49:49 +0000121struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000122 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000123 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000124 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000125 Tcl_Channel channel; /* Channel identifier */
126 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
127 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000128};
129
danielk197732a0d8b2007-05-04 19:03:02 +0000130#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000131/*
danielk1977d04417962007-05-02 13:16:30 +0000132** Close all incrblob channels opened using database connection pDb.
133** This is called when shutting down the database connection.
134*/
135static void closeIncrblobChannels(SqliteDb *pDb){
136 IncrblobChannel *p;
137 IncrblobChannel *pNext;
138
139 for(p=pDb->pIncrblob; p; p=pNext){
140 pNext = p->pNext;
141
142 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
143 ** which deletes the IncrblobChannel structure at *p. So do not
144 ** call Tcl_Free() here.
145 */
146 Tcl_UnregisterChannel(pDb->interp, p->channel);
147 }
148}
149
150/*
danielk1977b4e9af92007-05-01 17:49:49 +0000151** Close an incremental blob channel.
152*/
153static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
154 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000155 int rc = sqlite3_blob_close(p->pBlob);
156 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000157
158 /* Remove the channel from the SqliteDb.pIncrblob list. */
159 if( p->pNext ){
160 p->pNext->pPrev = p->pPrev;
161 }
162 if( p->pPrev ){
163 p->pPrev->pNext = p->pNext;
164 }
165 if( p->pDb->pIncrblob==p ){
166 p->pDb->pIncrblob = p->pNext;
167 }
168
danielk197792d4d7a2007-05-04 12:05:56 +0000169 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000170 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000171
172 if( rc!=SQLITE_OK ){
173 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
174 return TCL_ERROR;
175 }
danielk1977b4e9af92007-05-01 17:49:49 +0000176 return TCL_OK;
177}
178
179/*
180** Read data from an incremental blob channel.
181*/
182static int incrblobInput(
183 ClientData instanceData,
184 char *buf,
185 int bufSize,
186 int *errorCodePtr
187){
188 IncrblobChannel *p = (IncrblobChannel *)instanceData;
189 int nRead = bufSize; /* Number of bytes to read */
190 int nBlob; /* Total size of the blob */
191 int rc; /* sqlite error code */
192
193 nBlob = sqlite3_blob_bytes(p->pBlob);
194 if( (p->iSeek+nRead)>nBlob ){
195 nRead = nBlob-p->iSeek;
196 }
197 if( nRead<=0 ){
198 return 0;
199 }
200
201 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
202 if( rc!=SQLITE_OK ){
203 *errorCodePtr = rc;
204 return -1;
205 }
206
207 p->iSeek += nRead;
208 return nRead;
209}
210
danielk1977d04417962007-05-02 13:16:30 +0000211/*
212** Write data to an incremental blob channel.
213*/
danielk1977b4e9af92007-05-01 17:49:49 +0000214static int incrblobOutput(
215 ClientData instanceData,
216 CONST char *buf,
217 int toWrite,
218 int *errorCodePtr
219){
220 IncrblobChannel *p = (IncrblobChannel *)instanceData;
221 int nWrite = toWrite; /* Number of bytes to write */
222 int nBlob; /* Total size of the blob */
223 int rc; /* sqlite error code */
224
225 nBlob = sqlite3_blob_bytes(p->pBlob);
226 if( (p->iSeek+nWrite)>nBlob ){
227 *errorCodePtr = EINVAL;
228 return -1;
229 }
230 if( nWrite<=0 ){
231 return 0;
232 }
233
234 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
235 if( rc!=SQLITE_OK ){
236 *errorCodePtr = EIO;
237 return -1;
238 }
239
240 p->iSeek += nWrite;
241 return nWrite;
242}
243
244/*
245** Seek an incremental blob channel.
246*/
247static int incrblobSeek(
248 ClientData instanceData,
249 long offset,
250 int seekMode,
251 int *errorCodePtr
252){
253 IncrblobChannel *p = (IncrblobChannel *)instanceData;
254
255 switch( seekMode ){
256 case SEEK_SET:
257 p->iSeek = offset;
258 break;
259 case SEEK_CUR:
260 p->iSeek += offset;
261 break;
262 case SEEK_END:
263 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
264 break;
265
266 default: assert(!"Bad seekMode");
267 }
268
269 return p->iSeek;
270}
271
272
273static void incrblobWatch(ClientData instanceData, int mode){
274 /* NO-OP */
275}
276static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
277 return TCL_ERROR;
278}
279
280static Tcl_ChannelType IncrblobChannelType = {
281 "incrblob", /* typeName */
282 TCL_CHANNEL_VERSION_2, /* version */
283 incrblobClose, /* closeProc */
284 incrblobInput, /* inputProc */
285 incrblobOutput, /* outputProc */
286 incrblobSeek, /* seekProc */
287 0, /* setOptionProc */
288 0, /* getOptionProc */
289 incrblobWatch, /* watchProc (this is a no-op) */
290 incrblobHandle, /* getHandleProc (always returns error) */
291 0, /* close2Proc */
292 0, /* blockModeProc */
293 0, /* flushProc */
294 0, /* handlerProc */
295 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000296};
297
298/*
299** Create a new incrblob channel.
300*/
301static int createIncrblobChannel(
302 Tcl_Interp *interp,
303 SqliteDb *pDb,
304 const char *zDb,
305 const char *zTable,
306 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000307 sqlite_int64 iRow,
308 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000309){
310 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000311 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000312 sqlite3_blob *pBlob;
313 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000314 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000315
316 /* This variable is used to name the channels: "incrblob_[incr count]" */
317 static int count = 0;
318 char zChannel[64];
319
danielk19778cbadb02007-05-03 16:31:26 +0000320 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000321 if( rc!=SQLITE_OK ){
322 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
323 return TCL_ERROR;
324 }
325
326 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
327 p->iSeek = 0;
328 p->pBlob = pBlob;
329
drh5bb3eb92007-05-04 13:15:55 +0000330 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000331 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
332 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000333
danielk1977d04417962007-05-02 13:16:30 +0000334 /* Link the new channel into the SqliteDb.pIncrblob list. */
335 p->pNext = pDb->pIncrblob;
336 p->pPrev = 0;
337 if( p->pNext ){
338 p->pNext->pPrev = p;
339 }
340 pDb->pIncrblob = p;
341 p->pDb = pDb;
342
343 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000344 return TCL_OK;
345}
danielk197732a0d8b2007-05-04 19:03:02 +0000346#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
347 #define closeIncrblobChannels(pDb)
348#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000349
drh6d313162000-09-21 13:01:35 +0000350/*
drhd1e47332005-06-26 17:55:33 +0000351** Look at the script prefix in pCmd. We will be executing this script
352** after first appending one or more arguments. This routine analyzes
353** the script to see if it is safe to use Tcl_EvalObjv() on the script
354** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
355** faster.
356**
357** Scripts that are safe to use with Tcl_EvalObjv() consists of a
358** command name followed by zero or more arguments with no [...] or $
359** or {...} or ; to be seen anywhere. Most callback scripts consist
360** of just a single procedure name and they meet this requirement.
361*/
362static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
363 /* We could try to do something with Tcl_Parse(). But we will instead
364 ** just do a search for forbidden characters. If any of the forbidden
365 ** characters appear in pCmd, we will report the string as unsafe.
366 */
367 const char *z;
368 int n;
369 z = Tcl_GetStringFromObj(pCmd, &n);
370 while( n-- > 0 ){
371 int c = *(z++);
372 if( c=='$' || c=='[' || c==';' ) return 0;
373 }
374 return 1;
375}
376
377/*
378** Find an SqlFunc structure with the given name. Or create a new
379** one if an existing one cannot be found. Return a pointer to the
380** structure.
381*/
382static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
383 SqlFunc *p, *pNew;
384 int i;
385 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen(zName) + 1 );
386 pNew->zName = (char*)&pNew[1];
387 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
388 pNew->zName[i] = 0;
389 for(p=pDb->pFunc; p; p=p->pNext){
390 if( strcmp(p->zName, pNew->zName)==0 ){
391 Tcl_Free((char*)pNew);
392 return p;
393 }
394 }
395 pNew->interp = pDb->interp;
396 pNew->pScript = 0;
397 pNew->pNext = pDb->pFunc;
398 pDb->pFunc = pNew;
399 return pNew;
400}
401
402/*
drhfb7e7652005-01-24 00:28:42 +0000403** Finalize and free a list of prepared statements
404*/
405static void flushStmtCache( SqliteDb *pDb ){
406 SqlPreparedStmt *pPreStmt;
407
408 while( pDb->stmtList ){
409 sqlite3_finalize( pDb->stmtList->pStmt );
410 pPreStmt = pDb->stmtList;
411 pDb->stmtList = pDb->stmtList->pNext;
412 Tcl_Free( (char*)pPreStmt );
413 }
414 pDb->nStmt = 0;
415 pDb->stmtLast = 0;
416}
417
418/*
drh895d7472004-08-20 16:02:39 +0000419** TCL calls this procedure when an sqlite3 database command is
420** deleted.
drh75897232000-05-29 14:26:00 +0000421*/
422static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000423 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000424 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000425 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000426 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000427 while( pDb->pFunc ){
428 SqlFunc *pFunc = pDb->pFunc;
429 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000430 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000431 Tcl_Free((char*)pFunc);
432 }
danielk19770202b292004-06-09 09:55:16 +0000433 while( pDb->pCollate ){
434 SqlCollate *pCollate = pDb->pCollate;
435 pDb->pCollate = pCollate->pNext;
436 Tcl_Free((char*)pCollate);
437 }
drhbec3f402000-08-04 13:49:02 +0000438 if( pDb->zBusy ){
439 Tcl_Free(pDb->zBusy);
440 }
drhb5a20d32003-04-23 12:25:23 +0000441 if( pDb->zTrace ){
442 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000443 }
drh19e2d372005-08-29 23:00:03 +0000444 if( pDb->zProfile ){
445 Tcl_Free(pDb->zProfile);
446 }
drhe22a3342003-04-22 20:30:37 +0000447 if( pDb->zAuth ){
448 Tcl_Free(pDb->zAuth);
449 }
danielk197755c45f22005-04-03 23:54:43 +0000450 if( pDb->zNull ){
451 Tcl_Free(pDb->zNull);
452 }
danielk197794eb6a12005-12-15 15:22:08 +0000453 if( pDb->pUpdateHook ){
454 Tcl_DecrRefCount(pDb->pUpdateHook);
455 }
danielk197771fd80b2005-12-16 06:54:01 +0000456 if( pDb->pRollbackHook ){
457 Tcl_DecrRefCount(pDb->pRollbackHook);
458 }
danielk197794eb6a12005-12-15 15:22:08 +0000459 if( pDb->pCollateNeeded ){
460 Tcl_DecrRefCount(pDb->pCollateNeeded);
461 }
drhbec3f402000-08-04 13:49:02 +0000462 Tcl_Free((char*)pDb);
463}
464
465/*
466** This routine is called when a database file is locked while trying
467** to execute SQL.
468*/
danielk19772a764eb2004-06-12 01:43:26 +0000469static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000470 SqliteDb *pDb = (SqliteDb*)cd;
471 int rc;
472 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000473
drh5bb3eb92007-05-04 13:15:55 +0000474 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000475 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000476 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
477 return 0;
478 }
479 return 1;
drh75897232000-05-29 14:26:00 +0000480}
481
482/*
danielk1977348bb5d2003-10-18 09:37:26 +0000483** This routine is invoked as the 'progress callback' for the database.
484*/
485static int DbProgressHandler(void *cd){
486 SqliteDb *pDb = (SqliteDb*)cd;
487 int rc;
488
489 assert( pDb->zProgress );
490 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
491 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
492 return 1;
493 }
494 return 0;
495}
496
drhd1167392006-01-23 13:00:35 +0000497#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000498/*
drhb5a20d32003-04-23 12:25:23 +0000499** This routine is called by the SQLite trace handler whenever a new
500** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000501*/
drhb5a20d32003-04-23 12:25:23 +0000502static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000503 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000504 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000505
drhb5a20d32003-04-23 12:25:23 +0000506 Tcl_DStringInit(&str);
507 Tcl_DStringAppend(&str, pDb->zTrace, -1);
508 Tcl_DStringAppendElement(&str, zSql);
509 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
510 Tcl_DStringFree(&str);
511 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000512}
drhd1167392006-01-23 13:00:35 +0000513#endif
drh0d1a6432003-04-03 15:46:04 +0000514
drhd1167392006-01-23 13:00:35 +0000515#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000516/*
drh19e2d372005-08-29 23:00:03 +0000517** This routine is called by the SQLite profile handler after a statement
518** SQL has executed. The TCL script in pDb->zProfile is evaluated.
519*/
520static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
521 SqliteDb *pDb = (SqliteDb*)cd;
522 Tcl_DString str;
523 char zTm[100];
524
525 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
526 Tcl_DStringInit(&str);
527 Tcl_DStringAppend(&str, pDb->zProfile, -1);
528 Tcl_DStringAppendElement(&str, zSql);
529 Tcl_DStringAppendElement(&str, zTm);
530 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
531 Tcl_DStringFree(&str);
532 Tcl_ResetResult(pDb->interp);
533}
drhd1167392006-01-23 13:00:35 +0000534#endif
drh19e2d372005-08-29 23:00:03 +0000535
536/*
drhaa940ea2004-01-15 02:44:03 +0000537** This routine is called when a transaction is committed. The
538** TCL script in pDb->zCommit is executed. If it returns non-zero or
539** if it throws an exception, the transaction is rolled back instead
540** of being committed.
541*/
542static int DbCommitHandler(void *cd){
543 SqliteDb *pDb = (SqliteDb*)cd;
544 int rc;
545
546 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
547 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
548 return 1;
549 }
550 return 0;
551}
552
danielk197771fd80b2005-12-16 06:54:01 +0000553static void DbRollbackHandler(void *clientData){
554 SqliteDb *pDb = (SqliteDb*)clientData;
555 assert(pDb->pRollbackHook);
556 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
557 Tcl_BackgroundError(pDb->interp);
558 }
559}
560
danielk197794eb6a12005-12-15 15:22:08 +0000561static void DbUpdateHandler(
562 void *p,
563 int op,
564 const char *zDb,
565 const char *zTbl,
566 sqlite_int64 rowid
567){
568 SqliteDb *pDb = (SqliteDb *)p;
569 Tcl_Obj *pCmd;
570
571 assert( pDb->pUpdateHook );
572 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
573
574 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
575 Tcl_IncrRefCount(pCmd);
576 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
577 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
578 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
579 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
580 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
581 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
582}
583
danielk19777cedc8d2004-06-10 10:50:08 +0000584static void tclCollateNeeded(
585 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000586 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000587 int enc,
588 const char *zName
589){
590 SqliteDb *pDb = (SqliteDb *)pCtx;
591 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
592 Tcl_IncrRefCount(pScript);
593 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
594 Tcl_EvalObjEx(pDb->interp, pScript, 0);
595 Tcl_DecrRefCount(pScript);
596}
597
drhaa940ea2004-01-15 02:44:03 +0000598/*
danielk19770202b292004-06-09 09:55:16 +0000599** This routine is called to evaluate an SQL collation function implemented
600** using TCL script.
601*/
602static int tclSqlCollate(
603 void *pCtx,
604 int nA,
605 const void *zA,
606 int nB,
607 const void *zB
608){
609 SqlCollate *p = (SqlCollate *)pCtx;
610 Tcl_Obj *pCmd;
611
612 pCmd = Tcl_NewStringObj(p->zScript, -1);
613 Tcl_IncrRefCount(pCmd);
614 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
615 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000616 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000617 Tcl_DecrRefCount(pCmd);
618 return (atoi(Tcl_GetStringResult(p->interp)));
619}
620
621/*
drhcabb0812002-09-14 13:47:32 +0000622** This routine is called to evaluate an SQL function implemented
623** using TCL script.
624*/
drhfb7e7652005-01-24 00:28:42 +0000625static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000626 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000627 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000628 int i;
629 int rc;
630
drhd1e47332005-06-26 17:55:33 +0000631 if( argc==0 ){
632 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
633 ** script object directly. This allows the TCL compiler to generate
634 ** bytecode for the command on the first invocation and thus make
635 ** subsequent invocations much faster. */
636 pCmd = p->pScript;
637 Tcl_IncrRefCount(pCmd);
638 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
639 Tcl_DecrRefCount(pCmd);
640 }else{
641 /* If there are arguments to the function, make a shallow copy of the
642 ** script object, lappend the arguments, then evaluate the copy.
643 **
644 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
645 ** The new Tcl_Obj contains pointers to the original list elements.
646 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
647 ** of the list to tclCmdNameType, that alternate representation will
648 ** be preserved and reused on the next invocation.
649 */
650 Tcl_Obj **aArg;
651 int nArg;
652 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
653 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
654 return;
655 }
656 pCmd = Tcl_NewListObj(nArg, aArg);
657 Tcl_IncrRefCount(pCmd);
658 for(i=0; i<argc; i++){
659 sqlite3_value *pIn = argv[i];
660 Tcl_Obj *pVal;
661
662 /* Set pVal to contain the i'th column of this row. */
663 switch( sqlite3_value_type(pIn) ){
664 case SQLITE_BLOB: {
665 int bytes = sqlite3_value_bytes(pIn);
666 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
667 break;
668 }
669 case SQLITE_INTEGER: {
670 sqlite_int64 v = sqlite3_value_int64(pIn);
671 if( v>=-2147483647 && v<=2147483647 ){
672 pVal = Tcl_NewIntObj(v);
673 }else{
674 pVal = Tcl_NewWideIntObj(v);
675 }
676 break;
677 }
678 case SQLITE_FLOAT: {
679 double r = sqlite3_value_double(pIn);
680 pVal = Tcl_NewDoubleObj(r);
681 break;
682 }
683 case SQLITE_NULL: {
684 pVal = Tcl_NewStringObj("", 0);
685 break;
686 }
687 default: {
688 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000689 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000690 break;
691 }
692 }
693 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
694 if( rc ){
695 Tcl_DecrRefCount(pCmd);
696 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
697 return;
698 }
danielk197751ad0ec2004-05-24 12:39:02 +0000699 }
drhd1e47332005-06-26 17:55:33 +0000700 if( !p->useEvalObjv ){
701 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
702 ** is a list without a string representation. To prevent this from
703 ** happening, make sure pCmd has a valid string representation */
704 Tcl_GetString(pCmd);
705 }
706 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
707 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000708 }
danielk1977562e8d32005-05-20 09:40:55 +0000709
drhc7f269d2005-05-05 10:30:29 +0000710 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000711 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000712 }else{
drhc7f269d2005-05-05 10:30:29 +0000713 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
714 int n;
715 u8 *data;
716 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
717 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000718 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000719 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000720 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000721 data = Tcl_GetByteArrayFromObj(pVar, &n);
722 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000723 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000724 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);
drh985e0c62007-06-26 22:55:37 +0000730 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
731 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000732 Tcl_WideInt v;
733 Tcl_GetWideIntFromObj(0, pVar, &v);
734 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000735 }else{
danielk197700fd9572005-12-07 06:27:43 +0000736 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
737 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000738 }
drhcabb0812002-09-14 13:47:32 +0000739 }
740}
drh895d7472004-08-20 16:02:39 +0000741
drhe22a3342003-04-22 20:30:37 +0000742#ifndef SQLITE_OMIT_AUTHORIZATION
743/*
744** This is the authentication function. It appends the authentication
745** type code and the two arguments to zCmd[] then invokes the result
746** on the interpreter. The reply is examined to determine if the
747** authentication fails or succeeds.
748*/
749static int auth_callback(
750 void *pArg,
751 int code,
752 const char *zArg1,
753 const char *zArg2,
754 const char *zArg3,
755 const char *zArg4
756){
757 char *zCode;
758 Tcl_DString str;
759 int rc;
760 const char *zReply;
761 SqliteDb *pDb = (SqliteDb*)pArg;
762
763 switch( code ){
764 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
765 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
766 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
767 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
768 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
769 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
770 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
771 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
772 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
773 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
774 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
775 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
776 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
777 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
778 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
779 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
780 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
781 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
782 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
783 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
784 case SQLITE_READ : zCode="SQLITE_READ"; break;
785 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
786 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
787 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000788 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
789 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000790 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000791 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000792 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000793 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
794 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000795 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
drhe22a3342003-04-22 20:30:37 +0000796 default : zCode="????"; break;
797 }
798 Tcl_DStringInit(&str);
799 Tcl_DStringAppend(&str, pDb->zAuth, -1);
800 Tcl_DStringAppendElement(&str, zCode);
801 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
802 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
803 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
804 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
805 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
806 Tcl_DStringFree(&str);
807 zReply = Tcl_GetStringResult(pDb->interp);
808 if( strcmp(zReply,"SQLITE_OK")==0 ){
809 rc = SQLITE_OK;
810 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
811 rc = SQLITE_DENY;
812 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
813 rc = SQLITE_IGNORE;
814 }else{
815 rc = 999;
816 }
817 return rc;
818}
819#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000820
821/*
danielk1977ef2cb632004-05-29 02:37:19 +0000822** zText is a pointer to text obtained via an sqlite3_result_text()
823** or similar interface. This routine returns a Tcl string object,
824** reference count set to 0, containing the text. If a translation
825** between iso8859 and UTF-8 is required, it is preformed.
826*/
827static Tcl_Obj *dbTextToObj(char const *zText){
828 Tcl_Obj *pVal;
829#ifdef UTF_TRANSLATION_NEEDED
830 Tcl_DString dCol;
831 Tcl_DStringInit(&dCol);
832 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
833 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
834 Tcl_DStringFree(&dCol);
835#else
836 pVal = Tcl_NewStringObj(zText, -1);
837#endif
838 return pVal;
839}
840
841/*
tpoindex1067fe12004-12-17 15:41:11 +0000842** This routine reads a line of text from FILE in, stores
843** the text in memory obtained from malloc() and returns a pointer
844** to the text. NULL is returned at end of file, or if malloc()
845** fails.
846**
847** The interface is like "readline" but no command-line editing
848** is done.
849**
850** copied from shell.c from '.import' command
851*/
852static char *local_getline(char *zPrompt, FILE *in){
853 char *zLine;
854 int nLine;
855 int n;
856 int eol;
857
858 nLine = 100;
859 zLine = malloc( nLine );
860 if( zLine==0 ) return 0;
861 n = 0;
862 eol = 0;
863 while( !eol ){
864 if( n+100>nLine ){
865 nLine = nLine*2 + 100;
866 zLine = realloc(zLine, nLine);
867 if( zLine==0 ) return 0;
868 }
869 if( fgets(&zLine[n], nLine - n, in)==0 ){
870 if( n==0 ){
871 free(zLine);
872 return 0;
873 }
874 zLine[n] = 0;
875 eol = 1;
876 break;
877 }
878 while( zLine[n] ){ n++; }
879 if( n>0 && zLine[n-1]=='\n' ){
880 n--;
881 zLine[n] = 0;
882 eol = 1;
883 }
884 }
885 zLine = realloc( zLine, n+1 );
886 return zLine;
887}
888
danielk19778e556522007-11-13 10:30:24 +0000889
890/*
891** Figure out the column names for the data returned by the statement
892** passed as the second argument.
893**
894** If parameter papColName is not NULL, then *papColName is set to point
895** at an array allocated using Tcl_Alloc(). It is the callers responsibility
896** to free this array using Tcl_Free(), and to decrement the reference
897** count of each Tcl_Obj* member of the array.
898**
899** The return value of this function is the number of columns of data
900** returned by pStmt (and hence the size of the *papColName array).
901**
902** If pArray is not NULL, then it contains the name of a Tcl array
903** variable. The "*" member of this array is set to a list containing
904** the names of the columns returned by the statement, in order from
905** left to right. e.g. if the names of the returned columns are a, b and
906** c, it does the equivalent of the tcl command:
907**
908** set ${pArray}(*) {a b c}
909*/
910static int
911computeColumnNames(
912 Tcl_Interp *interp,
913 sqlite3_stmt *pStmt, /* SQL statement */
914 Tcl_Obj ***papColName, /* OUT: Array of column names */
915 Tcl_Obj *pArray /* Name of array variable (may be null) */
916){
917 int nCol;
918
919 /* Compute column names */
920 nCol = sqlite3_column_count(pStmt);
921 if( papColName ){
922 int i;
923 Tcl_Obj **apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
924 for(i=0; i<nCol; i++){
925 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
926 Tcl_IncrRefCount(apColName[i]);
927 }
928
929 /* If results are being stored in an array variable, then create
930 ** the array(*) entry for that array
931 */
932 if( pArray ){
933 Tcl_Obj *pColList = Tcl_NewObj();
934 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
935 Tcl_IncrRefCount(pColList);
936 for(i=0; i<nCol; i++){
937 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
938 }
939 Tcl_IncrRefCount(pStar);
940 Tcl_ObjSetVar2(interp, pArray, pStar, pColList,0);
941 Tcl_DecrRefCount(pColList);
942 Tcl_DecrRefCount(pStar);
943 }
944 *papColName = apColName;
945 }
946
947 return nCol;
948}
949
tpoindex1067fe12004-12-17 15:41:11 +0000950/*
drh75897232000-05-29 14:26:00 +0000951** The "sqlite" command below creates a new Tcl command for each
952** connection it opens to an SQLite database. This routine is invoked
953** whenever one of those connection-specific commands is executed
954** in Tcl. For example, if you run Tcl code like this:
955**
drh9bb575f2004-09-06 17:24:11 +0000956** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +0000957** db1 close
958**
959** The first command opens a connection to the "my_database" database
960** and calls that connection "db1". The second command causes this
961** subroutine to be invoked.
962*/
drh6d313162000-09-21 13:01:35 +0000963static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +0000964 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +0000965 int choice;
drh22fbcb82004-02-01 01:22:50 +0000966 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +0000967 static const char *DB_strs[] = {
drhfb7e7652005-01-24 00:28:42 +0000968 "authorizer", "busy", "cache",
969 "changes", "close", "collate",
970 "collation_needed", "commit_hook", "complete",
drh41449052006-07-06 17:08:48 +0000971 "copy", "enable_load_extension","errorcode",
972 "eval", "exists", "function",
drh59fffd02007-06-19 17:48:57 +0000973 "incrblob", "interrupt", "last_insert_rowid",
974 "nullvalue", "onecolumn", "profile",
975 "progress", "rekey", "rollback_hook",
976 "timeout", "total_changes", "trace",
977 "transaction", "update_hook", "version",
978 0
drh6d313162000-09-21 13:01:35 +0000979 };
drh411995d2002-06-25 19:31:18 +0000980 enum DB_enum {
drhfb7e7652005-01-24 00:28:42 +0000981 DB_AUTHORIZER, DB_BUSY, DB_CACHE,
982 DB_CHANGES, DB_CLOSE, DB_COLLATE,
983 DB_COLLATION_NEEDED, DB_COMMIT_HOOK, DB_COMPLETE,
drh41449052006-07-06 17:08:48 +0000984 DB_COPY, DB_ENABLE_LOAD_EXTENSION,DB_ERRORCODE,
985 DB_EVAL, DB_EXISTS, DB_FUNCTION,
drh59fffd02007-06-19 17:48:57 +0000986 DB_INCRBLOB, DB_INTERRUPT, DB_LAST_INSERT_ROWID,
987 DB_NULLVALUE, DB_ONECOLUMN, DB_PROFILE,
988 DB_PROGRESS, DB_REKEY, DB_ROLLBACK_HOOK,
989 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
990 DB_TRANSACTION, DB_UPDATE_HOOK, DB_VERSION
drh6d313162000-09-21 13:01:35 +0000991 };
tpoindex1067fe12004-12-17 15:41:11 +0000992 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +0000993
994 if( objc<2 ){
995 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +0000996 return TCL_ERROR;
997 }
drh411995d2002-06-25 19:31:18 +0000998 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +0000999 return TCL_ERROR;
1000 }
1001
drh411995d2002-06-25 19:31:18 +00001002 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001003
drhe22a3342003-04-22 20:30:37 +00001004 /* $db authorizer ?CALLBACK?
1005 **
1006 ** Invoke the given callback to authorize each SQL operation as it is
1007 ** compiled. 5 arguments are appended to the callback before it is
1008 ** invoked:
1009 **
1010 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1011 ** (2) First descriptive name (depends on authorization type)
1012 ** (3) Second descriptive name
1013 ** (4) Name of the database (ex: "main", "temp")
1014 ** (5) Name of trigger that is doing the access
1015 **
1016 ** The callback should return on of the following strings: SQLITE_OK,
1017 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1018 **
1019 ** If this method is invoked with no arguments, the current authorization
1020 ** callback string is returned.
1021 */
1022 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001023#ifdef SQLITE_OMIT_AUTHORIZATION
1024 Tcl_AppendResult(interp, "authorization not available in this build", 0);
1025 return TCL_ERROR;
1026#else
drhe22a3342003-04-22 20:30:37 +00001027 if( objc>3 ){
1028 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001029 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001030 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001031 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +00001032 Tcl_AppendResult(interp, pDb->zAuth, 0);
1033 }
1034 }else{
1035 char *zAuth;
1036 int len;
1037 if( pDb->zAuth ){
1038 Tcl_Free(pDb->zAuth);
1039 }
1040 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1041 if( zAuth && len>0 ){
1042 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001043 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001044 }else{
1045 pDb->zAuth = 0;
1046 }
drhe22a3342003-04-22 20:30:37 +00001047 if( pDb->zAuth ){
1048 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001049 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +00001050 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001051 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001052 }
drhe22a3342003-04-22 20:30:37 +00001053 }
drh1211de32004-07-26 12:24:22 +00001054#endif
drhe22a3342003-04-22 20:30:37 +00001055 break;
1056 }
1057
drhbec3f402000-08-04 13:49:02 +00001058 /* $db busy ?CALLBACK?
1059 **
1060 ** Invoke the given callback if an SQL statement attempts to open
1061 ** a locked database file.
1062 */
drh6d313162000-09-21 13:01:35 +00001063 case DB_BUSY: {
1064 if( objc>3 ){
1065 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001066 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001067 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001068 if( pDb->zBusy ){
1069 Tcl_AppendResult(interp, pDb->zBusy, 0);
1070 }
1071 }else{
drh6d313162000-09-21 13:01:35 +00001072 char *zBusy;
1073 int len;
drhbec3f402000-08-04 13:49:02 +00001074 if( pDb->zBusy ){
1075 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001076 }
drh6d313162000-09-21 13:01:35 +00001077 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1078 if( zBusy && len>0 ){
1079 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001080 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001081 }else{
1082 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001083 }
1084 if( pDb->zBusy ){
1085 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001086 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001087 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001088 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001089 }
1090 }
drh6d313162000-09-21 13:01:35 +00001091 break;
1092 }
drhbec3f402000-08-04 13:49:02 +00001093
drhfb7e7652005-01-24 00:28:42 +00001094 /* $db cache flush
1095 ** $db cache size n
1096 **
1097 ** Flush the prepared statement cache, or set the maximum number of
1098 ** cached statements.
1099 */
1100 case DB_CACHE: {
1101 char *subCmd;
1102 int n;
1103
1104 if( objc<=2 ){
1105 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1106 return TCL_ERROR;
1107 }
1108 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1109 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1110 if( objc!=3 ){
1111 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1112 return TCL_ERROR;
1113 }else{
1114 flushStmtCache( pDb );
1115 }
1116 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1117 if( objc!=4 ){
1118 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1119 return TCL_ERROR;
1120 }else{
1121 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1122 Tcl_AppendResult( interp, "cannot convert \"",
1123 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1124 return TCL_ERROR;
1125 }else{
1126 if( n<0 ){
1127 flushStmtCache( pDb );
1128 n = 0;
1129 }else if( n>MAX_PREPARED_STMTS ){
1130 n = MAX_PREPARED_STMTS;
1131 }
1132 pDb->maxStmt = n;
1133 }
1134 }
1135 }else{
1136 Tcl_AppendResult( interp, "bad option \"",
danielk1977191fadc2007-10-23 08:17:48 +00001137 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
drhfb7e7652005-01-24 00:28:42 +00001138 return TCL_ERROR;
1139 }
1140 break;
1141 }
1142
danielk1977b28af712004-06-21 06:50:26 +00001143 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001144 **
1145 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001146 ** the most recent INSERT, UPDATE or DELETE statement, not including
1147 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001148 */
1149 case DB_CHANGES: {
1150 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001151 if( objc!=2 ){
1152 Tcl_WrongNumArgs(interp, 2, objv, "");
1153 return TCL_ERROR;
1154 }
drhc8d30ac2002-04-12 10:08:59 +00001155 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001156 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001157 break;
1158 }
1159
drh75897232000-05-29 14:26:00 +00001160 /* $db close
1161 **
1162 ** Shutdown the database
1163 */
drh6d313162000-09-21 13:01:35 +00001164 case DB_CLOSE: {
1165 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1166 break;
1167 }
drh75897232000-05-29 14:26:00 +00001168
drh0f14e2e2004-06-29 12:39:08 +00001169 /*
1170 ** $db collate NAME SCRIPT
1171 **
1172 ** Create a new SQL collation function called NAME. Whenever
1173 ** that function is called, invoke SCRIPT to evaluate the function.
1174 */
1175 case DB_COLLATE: {
1176 SqlCollate *pCollate;
1177 char *zName;
1178 char *zScript;
1179 int nScript;
1180 if( objc!=4 ){
1181 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1182 return TCL_ERROR;
1183 }
1184 zName = Tcl_GetStringFromObj(objv[2], 0);
1185 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1186 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1187 if( pCollate==0 ) return TCL_ERROR;
1188 pCollate->interp = interp;
1189 pCollate->pNext = pDb->pCollate;
1190 pCollate->zScript = (char*)&pCollate[1];
1191 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001192 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001193 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1194 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001195 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001196 return TCL_ERROR;
1197 }
1198 break;
1199 }
1200
1201 /*
1202 ** $db collation_needed SCRIPT
1203 **
1204 ** Create a new SQL collation function called NAME. Whenever
1205 ** that function is called, invoke SCRIPT to evaluate the function.
1206 */
1207 case DB_COLLATION_NEEDED: {
1208 if( objc!=3 ){
1209 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1210 return TCL_ERROR;
1211 }
1212 if( pDb->pCollateNeeded ){
1213 Tcl_DecrRefCount(pDb->pCollateNeeded);
1214 }
1215 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1216 Tcl_IncrRefCount(pDb->pCollateNeeded);
1217 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1218 break;
1219 }
1220
drh19e2d372005-08-29 23:00:03 +00001221 /* $db commit_hook ?CALLBACK?
1222 **
1223 ** Invoke the given callback just before committing every SQL transaction.
1224 ** If the callback throws an exception or returns non-zero, then the
1225 ** transaction is aborted. If CALLBACK is an empty string, the callback
1226 ** is disabled.
1227 */
1228 case DB_COMMIT_HOOK: {
1229 if( objc>3 ){
1230 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1231 return TCL_ERROR;
1232 }else if( objc==2 ){
1233 if( pDb->zCommit ){
1234 Tcl_AppendResult(interp, pDb->zCommit, 0);
1235 }
1236 }else{
1237 char *zCommit;
1238 int len;
1239 if( pDb->zCommit ){
1240 Tcl_Free(pDb->zCommit);
1241 }
1242 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1243 if( zCommit && len>0 ){
1244 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001245 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001246 }else{
1247 pDb->zCommit = 0;
1248 }
1249 if( pDb->zCommit ){
1250 pDb->interp = interp;
1251 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1252 }else{
1253 sqlite3_commit_hook(pDb->db, 0, 0);
1254 }
1255 }
1256 break;
1257 }
1258
drh75897232000-05-29 14:26:00 +00001259 /* $db complete SQL
1260 **
1261 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1262 ** additional lines of input are needed. This is similar to the
1263 ** built-in "info complete" command of Tcl.
1264 */
drh6d313162000-09-21 13:01:35 +00001265 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00001266#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00001267 Tcl_Obj *pResult;
1268 int isComplete;
1269 if( objc!=3 ){
1270 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00001271 return TCL_ERROR;
1272 }
danielk19776f8a5032004-05-10 10:34:51 +00001273 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00001274 pResult = Tcl_GetObjResult(interp);
1275 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00001276#endif
drh6d313162000-09-21 13:01:35 +00001277 break;
1278 }
drhdcd997e2003-01-31 17:21:49 +00001279
drh19e2d372005-08-29 23:00:03 +00001280 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1281 **
1282 ** Copy data into table from filename, optionally using SEPARATOR
1283 ** as column separators. If a column contains a null string, or the
1284 ** value of NULLINDICATOR, a NULL is inserted for the column.
1285 ** conflict-algorithm is one of the sqlite conflict algorithms:
1286 ** rollback, abort, fail, ignore, replace
1287 ** On success, return the number of lines processed, not necessarily same
1288 ** as 'db changes' due to conflict-algorithm selected.
1289 **
1290 ** This code is basically an implementation/enhancement of
1291 ** the sqlite3 shell.c ".import" command.
1292 **
1293 ** This command usage is equivalent to the sqlite2.x COPY statement,
1294 ** which imports file data into a table using the PostgreSQL COPY file format:
1295 ** $db copy $conflit_algo $table_name $filename \t \\N
1296 */
1297 case DB_COPY: {
1298 char *zTable; /* Insert data into this table */
1299 char *zFile; /* The file from which to extract data */
1300 char *zConflict; /* The conflict algorithm to use */
1301 sqlite3_stmt *pStmt; /* A statement */
1302 int rc; /* Result code */
1303 int nCol; /* Number of columns in the table */
1304 int nByte; /* Number of bytes in an SQL string */
1305 int i, j; /* Loop counters */
1306 int nSep; /* Number of bytes in zSep[] */
1307 int nNull; /* Number of bytes in zNull[] */
1308 char *zSql; /* An SQL statement */
1309 char *zLine; /* A single line of input from the file */
1310 char **azCol; /* zLine[] broken up into columns */
1311 char *zCommit; /* How to commit changes */
1312 FILE *in; /* The input file */
1313 int lineno = 0; /* Line number of input file */
1314 char zLineNum[80]; /* Line number print buffer */
1315 Tcl_Obj *pResult; /* interp result */
1316
1317 char *zSep;
1318 char *zNull;
1319 if( objc<5 || objc>7 ){
1320 Tcl_WrongNumArgs(interp, 2, objv,
1321 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1322 return TCL_ERROR;
1323 }
1324 if( objc>=6 ){
1325 zSep = Tcl_GetStringFromObj(objv[5], 0);
1326 }else{
1327 zSep = "\t";
1328 }
1329 if( objc>=7 ){
1330 zNull = Tcl_GetStringFromObj(objv[6], 0);
1331 }else{
1332 zNull = "";
1333 }
1334 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1335 zTable = Tcl_GetStringFromObj(objv[3], 0);
1336 zFile = Tcl_GetStringFromObj(objv[4], 0);
1337 nSep = strlen(zSep);
1338 nNull = strlen(zNull);
1339 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00001340 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00001341 return TCL_ERROR;
1342 }
1343 if(sqlite3StrICmp(zConflict, "rollback") != 0 &&
1344 sqlite3StrICmp(zConflict, "abort" ) != 0 &&
1345 sqlite3StrICmp(zConflict, "fail" ) != 0 &&
1346 sqlite3StrICmp(zConflict, "ignore" ) != 0 &&
1347 sqlite3StrICmp(zConflict, "replace" ) != 0 ) {
1348 Tcl_AppendResult(interp, "Error: \"", zConflict,
1349 "\", conflict-algorithm must be one of: rollback, "
1350 "abort, fail, ignore, or replace", 0);
1351 return TCL_ERROR;
1352 }
1353 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1354 if( zSql==0 ){
1355 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1356 return TCL_ERROR;
1357 }
1358 nByte = strlen(zSql);
drh3e701a12007-02-01 01:53:44 +00001359 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001360 sqlite3_free(zSql);
1361 if( rc ){
1362 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1363 nCol = 0;
1364 }else{
1365 nCol = sqlite3_column_count(pStmt);
1366 }
1367 sqlite3_finalize(pStmt);
1368 if( nCol==0 ) {
1369 return TCL_ERROR;
1370 }
1371 zSql = malloc( nByte + 50 + nCol*2 );
1372 if( zSql==0 ) {
1373 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1374 return TCL_ERROR;
1375 }
1376 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1377 zConflict, zTable);
1378 j = strlen(zSql);
1379 for(i=1; i<nCol; i++){
1380 zSql[j++] = ',';
1381 zSql[j++] = '?';
1382 }
1383 zSql[j++] = ')';
1384 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00001385 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001386 free(zSql);
1387 if( rc ){
1388 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1389 sqlite3_finalize(pStmt);
1390 return TCL_ERROR;
1391 }
1392 in = fopen(zFile, "rb");
1393 if( in==0 ){
1394 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
1395 sqlite3_finalize(pStmt);
1396 return TCL_ERROR;
1397 }
1398 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1399 if( azCol==0 ) {
1400 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00001401 fclose(in);
drh19e2d372005-08-29 23:00:03 +00001402 return TCL_ERROR;
1403 }
drh37527852006-03-16 16:19:56 +00001404 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001405 zCommit = "COMMIT";
1406 while( (zLine = local_getline(0, in))!=0 ){
1407 char *z;
1408 i = 0;
1409 lineno++;
1410 azCol[0] = zLine;
1411 for(i=0, z=zLine; *z; z++){
1412 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
1413 *z = 0;
1414 i++;
1415 if( i<nCol ){
1416 azCol[i] = &z[nSep];
1417 z += nSep-1;
1418 }
1419 }
1420 }
1421 if( i+1!=nCol ){
1422 char *zErr;
drh5bb3eb92007-05-04 13:15:55 +00001423 int nErr = strlen(zFile) + 200;
1424 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00001425 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00001426 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00001427 "Error: %s line %d: expected %d columns of data but found %d",
1428 zFile, lineno, nCol, i+1);
1429 Tcl_AppendResult(interp, zErr, 0);
1430 free(zErr);
1431 }
drh19e2d372005-08-29 23:00:03 +00001432 zCommit = "ROLLBACK";
1433 break;
1434 }
1435 for(i=0; i<nCol; i++){
1436 /* check for null data, if so, bind as null */
1437 if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
1438 sqlite3_bind_null(pStmt, i+1);
1439 }else{
1440 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1441 }
1442 }
1443 sqlite3_step(pStmt);
1444 rc = sqlite3_reset(pStmt);
1445 free(zLine);
1446 if( rc!=SQLITE_OK ){
1447 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
1448 zCommit = "ROLLBACK";
1449 break;
1450 }
1451 }
1452 free(azCol);
1453 fclose(in);
1454 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00001455 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001456
1457 if( zCommit[0] == 'C' ){
1458 /* success, set result as number of lines processed */
1459 pResult = Tcl_GetObjResult(interp);
1460 Tcl_SetIntObj(pResult, lineno);
1461 rc = TCL_OK;
1462 }else{
1463 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00001464 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00001465 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
1466 rc = TCL_ERROR;
1467 }
1468 break;
1469 }
1470
drhdcd997e2003-01-31 17:21:49 +00001471 /*
drh41449052006-07-06 17:08:48 +00001472 ** $db enable_load_extension BOOLEAN
1473 **
1474 ** Turn the extension loading feature on or off. It if off by
1475 ** default.
1476 */
1477 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00001478#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00001479 int onoff;
1480 if( objc!=3 ){
1481 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
1482 return TCL_ERROR;
1483 }
1484 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
1485 return TCL_ERROR;
1486 }
1487 sqlite3_enable_load_extension(pDb->db, onoff);
1488 break;
drhf533acc2006-12-19 18:57:11 +00001489#else
1490 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
1491 0);
1492 return TCL_ERROR;
1493#endif
drh41449052006-07-06 17:08:48 +00001494 }
1495
1496 /*
drhdcd997e2003-01-31 17:21:49 +00001497 ** $db errorcode
1498 **
1499 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00001500 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00001501 */
1502 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00001503 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00001504 break;
1505 }
drh75897232000-05-29 14:26:00 +00001506
1507 /*
drh895d7472004-08-20 16:02:39 +00001508 ** $db eval $sql ?array? ?{ ...code... }?
drh1807ce32004-09-07 13:20:35 +00001509 ** $db onecolumn $sql
drh75897232000-05-29 14:26:00 +00001510 **
1511 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00001512 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00001513 ** If "array" and "code" are omitted, then no callback is every invoked.
1514 ** If "array" is an empty string, then the values are placed in variables
1515 ** that have the same name as the fields extracted by the query.
drh1807ce32004-09-07 13:20:35 +00001516 **
1517 ** The onecolumn method is the equivalent of:
1518 ** lindex [$db eval $sql] 0
drh75897232000-05-29 14:26:00 +00001519 */
drh1807ce32004-09-07 13:20:35 +00001520 case DB_ONECOLUMN:
drh97f2ebc2005-12-10 21:19:04 +00001521 case DB_EVAL:
1522 case DB_EXISTS: {
drh9d74b4c2004-08-24 15:23:34 +00001523 char const *zSql; /* Next SQL statement to execute */
1524 char const *zLeft; /* What is left after first stmt in zSql */
1525 sqlite3_stmt *pStmt; /* Compiled SQL statment */
drh92febd92004-08-20 18:34:20 +00001526 Tcl_Obj *pArray; /* Name of array into which results are written */
1527 Tcl_Obj *pScript; /* Script to run for each result set */
drh1d895032004-08-26 00:56:05 +00001528 Tcl_Obj **apParm; /* Parameters that need a Tcl_DecrRefCount() */
1529 int nParm; /* Number of entries used in apParm[] */
1530 Tcl_Obj *aParm[10]; /* Static space for apParm[] in the common case */
drh1807ce32004-09-07 13:20:35 +00001531 Tcl_Obj *pRet; /* Value to be returned */
drhfb7e7652005-01-24 00:28:42 +00001532 SqlPreparedStmt *pPreStmt; /* Pointer to a prepared statement */
1533 int rc2;
danielk1977ef2cb632004-05-29 02:37:19 +00001534
drh97f2ebc2005-12-10 21:19:04 +00001535 if( choice==DB_EVAL ){
drh1807ce32004-09-07 13:20:35 +00001536 if( objc<3 || objc>5 ){
1537 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
1538 return TCL_ERROR;
1539 }
1540 pRet = Tcl_NewObj();
1541 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001542 }else{
1543 if( objc!=3 ){
1544 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
1545 return TCL_ERROR;
1546 }
drh97f2ebc2005-12-10 21:19:04 +00001547 if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001548 pRet = Tcl_NewBooleanObj(0);
1549 Tcl_IncrRefCount(pRet);
1550 }else{
1551 pRet = 0;
drh97f2ebc2005-12-10 21:19:04 +00001552 }
danielk197730ccda12004-05-27 12:11:31 +00001553 }
drh92febd92004-08-20 18:34:20 +00001554 if( objc==3 ){
1555 pArray = pScript = 0;
1556 }else if( objc==4 ){
1557 pArray = 0;
1558 pScript = objv[3];
1559 }else{
1560 pArray = objv[3];
1561 if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
1562 pScript = objv[4];
1563 }
danielk197730ccda12004-05-27 12:11:31 +00001564
drh1d895032004-08-26 00:56:05 +00001565 Tcl_IncrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001566 zSql = Tcl_GetStringFromObj(objv[2], 0);
drh90b6bb12004-09-13 13:16:31 +00001567 while( rc==TCL_OK && zSql[0] ){
drhfb7e7652005-01-24 00:28:42 +00001568 int i; /* Loop counter */
1569 int nVar; /* Number of bind parameters in the pStmt */
danielk19778e556522007-11-13 10:30:24 +00001570 int nCol = -1; /* Number of columns in the result set */
drh92febd92004-08-20 18:34:20 +00001571 Tcl_Obj **apColName = 0; /* Array of column names */
drhfb7e7652005-01-24 00:28:42 +00001572 int len; /* String length of zSql */
danielk197730ccda12004-05-27 12:11:31 +00001573
drhfb7e7652005-01-24 00:28:42 +00001574 /* Try to find a SQL statement that has already been compiled and
1575 ** which matches the next sequence of SQL.
1576 */
1577 pStmt = 0;
drhfb7e7652005-01-24 00:28:42 +00001578 len = strlen(zSql);
danielk19778e556522007-11-13 10:30:24 +00001579 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
drhfb7e7652005-01-24 00:28:42 +00001580 int n = pPreStmt->nSql;
1581 if( len>=n
1582 && memcmp(pPreStmt->zSql, zSql, n)==0
1583 && (zSql[n]==0 || zSql[n-1]==';')
1584 ){
1585 pStmt = pPreStmt->pStmt;
1586 zLeft = &zSql[pPreStmt->nSql];
1587
1588 /* When a prepared statement is found, unlink it from the
1589 ** cache list. It will later be added back to the beginning
1590 ** of the cache list in order to implement LRU replacement.
1591 */
1592 if( pPreStmt->pPrev ){
1593 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1594 }else{
1595 pDb->stmtList = pPreStmt->pNext;
1596 }
1597 if( pPreStmt->pNext ){
1598 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1599 }else{
1600 pDb->stmtLast = pPreStmt->pPrev;
1601 }
1602 pDb->nStmt--;
1603 break;
1604 }
1605 }
1606
1607 /* If no prepared statement was found. Compile the SQL text
1608 */
drh92febd92004-08-20 18:34:20 +00001609 if( pStmt==0 ){
danielk19778e556522007-11-13 10:30:24 +00001610 if( SQLITE_OK!=sqlite3_prepare_v2(pDb->db, zSql, -1, &pStmt, &zLeft) ){
drh92febd92004-08-20 18:34:20 +00001611 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1612 rc = TCL_ERROR;
1613 break;
danielk197730ccda12004-05-27 12:11:31 +00001614 }
drhfb7e7652005-01-24 00:28:42 +00001615 if( pStmt==0 ){
1616 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1617 /* A compile-time error in the statement
1618 */
1619 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1620 rc = TCL_ERROR;
1621 break;
1622 }else{
1623 /* The statement was a no-op. Continue to the next statement
1624 ** in the SQL string.
1625 */
1626 zSql = zLeft;
1627 continue;
1628 }
1629 }
1630 assert( pPreStmt==0 );
danielk197730ccda12004-05-27 12:11:31 +00001631 }
1632
drhfb7e7652005-01-24 00:28:42 +00001633 /* Bind values to parameters that begin with $ or :
1634 */
drh92febd92004-08-20 18:34:20 +00001635 nVar = sqlite3_bind_parameter_count(pStmt);
drh1d895032004-08-26 00:56:05 +00001636 nParm = 0;
1637 if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
1638 apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
1639 }else{
1640 apParm = aParm;
1641 }
drh92febd92004-08-20 18:34:20 +00001642 for(i=1; i<=nVar; i++){
1643 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
drh4f5e80f2007-06-19 17:15:46 +00001644 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
drh92febd92004-08-20 18:34:20 +00001645 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1646 if( pVar ){
1647 int n;
1648 u8 *data;
1649 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
1650 char c = zType[0];
drh1c747812007-06-19 23:01:41 +00001651 if( zVar[0]=='@' ||
1652 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1653 /* Load a BLOB type if the Tcl variable is a bytearray and
1654 ** it has no string representation or the host
drh4f5e80f2007-06-19 17:15:46 +00001655 ** parameter name begins with "@". */
drh92febd92004-08-20 18:34:20 +00001656 data = Tcl_GetByteArrayFromObj(pVar, &n);
1657 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001658 Tcl_IncrRefCount(pVar);
1659 apParm[nParm++] = pVar;
drh985e0c62007-06-26 22:55:37 +00001660 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drh92febd92004-08-20 18:34:20 +00001661 Tcl_GetIntFromObj(interp, pVar, &n);
1662 sqlite3_bind_int(pStmt, i, n);
1663 }else if( c=='d' && strcmp(zType,"double")==0 ){
1664 double r;
1665 Tcl_GetDoubleFromObj(interp, pVar, &r);
1666 sqlite3_bind_double(pStmt, i, r);
drh985e0c62007-06-26 22:55:37 +00001667 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1668 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +00001669 Tcl_WideInt v;
1670 Tcl_GetWideIntFromObj(interp, pVar, &v);
1671 sqlite3_bind_int64(pStmt, i, v);
drh92febd92004-08-20 18:34:20 +00001672 }else{
danielk197700fd9572005-12-07 06:27:43 +00001673 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1674 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001675 Tcl_IncrRefCount(pVar);
1676 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001677 }
drhfb7e7652005-01-24 00:28:42 +00001678 }else{
1679 sqlite3_bind_null( pStmt, i );
drh92febd92004-08-20 18:34:20 +00001680 }
1681 }
1682 }
drh92febd92004-08-20 18:34:20 +00001683
drh92febd92004-08-20 18:34:20 +00001684 /* Execute the SQL
1685 */
drh90b6bb12004-09-13 13:16:31 +00001686 while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
danielk19778e556522007-11-13 10:30:24 +00001687
1688 /* Compute column names. This must be done after the first successful
1689 ** call to sqlite3_step(), in case the query is recompiled and the
1690 ** number or names of the returned columns changes.
1691 */
1692 assert(!pArray||pScript);
1693 if (nCol < 0) {
1694 Tcl_Obj ***ap = (pScript?&apColName:0);
1695 nCol = computeColumnNames(interp, pStmt, ap, pArray);
1696 }
1697
drh92febd92004-08-20 18:34:20 +00001698 for(i=0; i<nCol; i++){
danielk197730ccda12004-05-27 12:11:31 +00001699 Tcl_Obj *pVal;
1700
1701 /* Set pVal to contain the i'th column of this row. */
drh92febd92004-08-20 18:34:20 +00001702 switch( sqlite3_column_type(pStmt, i) ){
1703 case SQLITE_BLOB: {
1704 int bytes = sqlite3_column_bytes(pStmt, i);
1705 pVal = Tcl_NewByteArrayObj(sqlite3_column_blob(pStmt, i), bytes);
1706 break;
1707 }
1708 case SQLITE_INTEGER: {
1709 sqlite_int64 v = sqlite3_column_int64(pStmt, i);
1710 if( v>=-2147483647 && v<=2147483647 ){
1711 pVal = Tcl_NewIntObj(v);
1712 }else{
1713 pVal = Tcl_NewWideIntObj(v);
1714 }
1715 break;
1716 }
1717 case SQLITE_FLOAT: {
1718 double r = sqlite3_column_double(pStmt, i);
1719 pVal = Tcl_NewDoubleObj(r);
1720 break;
1721 }
danielk197755c45f22005-04-03 23:54:43 +00001722 case SQLITE_NULL: {
1723 pVal = dbTextToObj(pDb->zNull);
1724 break;
1725 }
drh92febd92004-08-20 18:34:20 +00001726 default: {
danielk197700fd9572005-12-07 06:27:43 +00001727 pVal = dbTextToObj((char *)sqlite3_column_text(pStmt, i));
drh92febd92004-08-20 18:34:20 +00001728 break;
1729 }
danielk197730ccda12004-05-27 12:11:31 +00001730 }
1731
drh92febd92004-08-20 18:34:20 +00001732 if( pScript ){
1733 if( pArray==0 ){
1734 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001735 }else{
drh92febd92004-08-20 18:34:20 +00001736 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001737 }
drh1807ce32004-09-07 13:20:35 +00001738 }else if( choice==DB_ONECOLUMN ){
drh97f2ebc2005-12-10 21:19:04 +00001739 assert( pRet==0 );
drh1807ce32004-09-07 13:20:35 +00001740 if( pRet==0 ){
1741 pRet = pVal;
1742 Tcl_IncrRefCount(pRet);
1743 }
drh90b6bb12004-09-13 13:16:31 +00001744 rc = TCL_BREAK;
drh97f2ebc2005-12-10 21:19:04 +00001745 i = nCol;
1746 }else if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001747 Tcl_DecrRefCount(pRet);
1748 pRet = Tcl_NewBooleanObj(1);
1749 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001750 rc = TCL_BREAK;
1751 i = nCol;
danielk197730ccda12004-05-27 12:11:31 +00001752 }else{
danielk197730ccda12004-05-27 12:11:31 +00001753 Tcl_ListObjAppendElement(interp, pRet, pVal);
1754 }
1755 }
1756
drh92febd92004-08-20 18:34:20 +00001757 if( pScript ){
1758 rc = Tcl_EvalObjEx(interp, pScript, 0);
drh90b6bb12004-09-13 13:16:31 +00001759 if( rc==TCL_CONTINUE ){
1760 rc = TCL_OK;
1761 }
danielk197730ccda12004-05-27 12:11:31 +00001762 }
1763 }
drh90b6bb12004-09-13 13:16:31 +00001764 if( rc==TCL_BREAK ){
1765 rc = TCL_OK;
1766 }
drh92febd92004-08-20 18:34:20 +00001767
1768 /* Free the column name objects */
1769 if( pScript ){
danielk19778e556522007-11-13 10:30:24 +00001770 /* If the query returned no rows, but an array variable was
1771 ** specified, call computeColumnNames() now to populate the
1772 ** arrayname(*) variable.
1773 */
1774 if (pArray && nCol < 0) {
1775 Tcl_Obj ***ap = (pScript?&apColName:0);
1776 nCol = computeColumnNames(interp, pStmt, ap, pArray);
1777 }
drh92febd92004-08-20 18:34:20 +00001778 for(i=0; i<nCol; i++){
1779 Tcl_DecrRefCount(apColName[i]);
1780 }
1781 Tcl_Free((char*)apColName);
1782 }
1783
drh1d895032004-08-26 00:56:05 +00001784 /* Free the bound string and blob parameters */
1785 for(i=0; i<nParm; i++){
1786 Tcl_DecrRefCount(apParm[i]);
1787 }
1788 if( apParm!=aParm ){
1789 Tcl_Free((char*)apParm);
1790 }
1791
drhfb7e7652005-01-24 00:28:42 +00001792 /* Reset the statement. If the result code is SQLITE_SCHEMA, then
1793 ** flush the statement cache and try the statement again.
drh92febd92004-08-20 18:34:20 +00001794 */
drhfb7e7652005-01-24 00:28:42 +00001795 rc2 = sqlite3_reset(pStmt);
danielk19778e556522007-11-13 10:30:24 +00001796 if( SQLITE_OK!=rc2 ){
drhfb7e7652005-01-24 00:28:42 +00001797 /* If a run-time error occurs, report the error and stop reading
1798 ** the SQL
1799 */
danielk1977ef2cb632004-05-29 02:37:19 +00001800 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
drhfb7e7652005-01-24 00:28:42 +00001801 sqlite3_finalize(pStmt);
danielk197730ccda12004-05-27 12:11:31 +00001802 rc = TCL_ERROR;
drhfb7e7652005-01-24 00:28:42 +00001803 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001804 break;
drhfb7e7652005-01-24 00:28:42 +00001805 }else if( pDb->maxStmt<=0 ){
1806 /* If the cache is turned off, deallocated the statement */
1807 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1808 sqlite3_finalize(pStmt);
1809 }else{
1810 /* Everything worked and the cache is operational.
1811 ** Create a new SqlPreparedStmt structure if we need one.
1812 ** (If we already have one we can just reuse it.)
1813 */
1814 if( pPreStmt==0 ){
1815 len = zLeft - zSql;
1816 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) + len );
1817 if( pPreStmt==0 ) return TCL_ERROR;
1818 pPreStmt->pStmt = pStmt;
1819 pPreStmt->nSql = len;
1820 memcpy(pPreStmt->zSql, zSql, len);
1821 pPreStmt->zSql[len] = 0;
1822 }
1823
1824 /* Add the prepared statement to the beginning of the cache list
1825 */
1826 pPreStmt->pNext = pDb->stmtList;
1827 pPreStmt->pPrev = 0;
1828 if( pDb->stmtList ){
1829 pDb->stmtList->pPrev = pPreStmt;
1830 }
1831 pDb->stmtList = pPreStmt;
1832 if( pDb->stmtLast==0 ){
1833 assert( pDb->nStmt==0 );
1834 pDb->stmtLast = pPreStmt;
1835 }else{
1836 assert( pDb->nStmt>0 );
1837 }
1838 pDb->nStmt++;
1839
1840 /* If we have too many statement in cache, remove the surplus from the
1841 ** end of the cache list.
1842 */
1843 while( pDb->nStmt>pDb->maxStmt ){
1844 sqlite3_finalize(pDb->stmtLast->pStmt);
1845 pDb->stmtLast = pDb->stmtLast->pPrev;
1846 Tcl_Free((char*)pDb->stmtLast->pNext);
1847 pDb->stmtLast->pNext = 0;
1848 pDb->nStmt--;
1849 }
danielk197730ccda12004-05-27 12:11:31 +00001850 }
1851
drhfb7e7652005-01-24 00:28:42 +00001852 /* Proceed to the next statement */
danielk197730ccda12004-05-27 12:11:31 +00001853 zSql = zLeft;
1854 }
drh1d895032004-08-26 00:56:05 +00001855 Tcl_DecrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001856
drh1807ce32004-09-07 13:20:35 +00001857 if( pRet ){
1858 if( rc==TCL_OK ){
1859 Tcl_SetObjResult(interp, pRet);
1860 }
1861 Tcl_DecrRefCount(pRet);
drh050be322006-07-12 00:18:40 +00001862 }else if( rc==TCL_OK ){
1863 Tcl_ResetResult(interp);
danielk197730ccda12004-05-27 12:11:31 +00001864 }
danielk197730ccda12004-05-27 12:11:31 +00001865 break;
1866 }
drhbec3f402000-08-04 13:49:02 +00001867
1868 /*
drhcabb0812002-09-14 13:47:32 +00001869 ** $db function NAME SCRIPT
1870 **
1871 ** Create a new SQL function called NAME. Whenever that function is
1872 ** called, invoke SCRIPT to evaluate the function.
1873 */
1874 case DB_FUNCTION: {
1875 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00001876 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00001877 char *zName;
drhcabb0812002-09-14 13:47:32 +00001878 if( objc!=4 ){
1879 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1880 return TCL_ERROR;
1881 }
1882 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00001883 pScript = objv[3];
1884 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00001885 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00001886 if( pFunc->pScript ){
1887 Tcl_DecrRefCount(pFunc->pScript);
1888 }
1889 pFunc->pScript = pScript;
1890 Tcl_IncrRefCount(pScript);
1891 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
danielk1977c8c11582004-06-29 13:41:21 +00001892 rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00001893 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00001894 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00001895 rc = TCL_ERROR;
1896 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00001897 }
drhcabb0812002-09-14 13:47:32 +00001898 break;
1899 }
1900
1901 /*
danielk19778cbadb02007-05-03 16:31:26 +00001902 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00001903 */
1904 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00001905#ifdef SQLITE_OMIT_INCRBLOB
1906 Tcl_AppendResult(interp, "incrblob not available in this build", 0);
1907 return TCL_ERROR;
1908#else
danielk19778cbadb02007-05-03 16:31:26 +00001909 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00001910 const char *zDb = "main";
1911 const char *zTable;
1912 const char *zColumn;
1913 sqlite_int64 iRow;
1914
danielk19778cbadb02007-05-03 16:31:26 +00001915 /* Check for the -readonly option */
1916 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
1917 isReadonly = 1;
1918 }
1919
1920 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
1921 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00001922 return TCL_ERROR;
1923 }
1924
danielk19778cbadb02007-05-03 16:31:26 +00001925 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00001926 zDb = Tcl_GetString(objv[2]);
1927 }
1928 zTable = Tcl_GetString(objv[objc-3]);
1929 zColumn = Tcl_GetString(objv[objc-2]);
1930 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
1931
1932 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00001933 rc = createIncrblobChannel(
1934 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
1935 );
danielk1977b4e9af92007-05-01 17:49:49 +00001936 }
danielk197732a0d8b2007-05-04 19:03:02 +00001937#endif
danielk1977b4e9af92007-05-01 17:49:49 +00001938 break;
1939 }
1940
1941 /*
drhf11bded2006-07-17 00:02:44 +00001942 ** $db interrupt
1943 **
1944 ** Interrupt the execution of the inner-most SQL interpreter. This
1945 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
1946 */
1947 case DB_INTERRUPT: {
1948 sqlite3_interrupt(pDb->db);
1949 break;
1950 }
1951
1952 /*
drh19e2d372005-08-29 23:00:03 +00001953 ** $db nullvalue ?STRING?
1954 **
1955 ** Change text used when a NULL comes back from the database. If ?STRING?
1956 ** is not present, then the current string used for NULL is returned.
1957 ** If STRING is present, then STRING is returned.
1958 **
1959 */
1960 case DB_NULLVALUE: {
1961 if( objc!=2 && objc!=3 ){
1962 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
1963 return TCL_ERROR;
1964 }
1965 if( objc==3 ){
1966 int len;
1967 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
1968 if( pDb->zNull ){
1969 Tcl_Free(pDb->zNull);
1970 }
1971 if( zNull && len>0 ){
1972 pDb->zNull = Tcl_Alloc( len + 1 );
1973 strncpy(pDb->zNull, zNull, len);
1974 pDb->zNull[len] = '\0';
1975 }else{
1976 pDb->zNull = 0;
1977 }
1978 }
1979 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
1980 break;
1981 }
1982
1983 /*
drhaf9ff332002-01-16 21:00:27 +00001984 ** $db last_insert_rowid
1985 **
1986 ** Return an integer which is the ROWID for the most recent insert.
1987 */
1988 case DB_LAST_INSERT_ROWID: {
1989 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00001990 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00001991 if( objc!=2 ){
1992 Tcl_WrongNumArgs(interp, 2, objv, "");
1993 return TCL_ERROR;
1994 }
danielk19776f8a5032004-05-10 10:34:51 +00001995 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00001996 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00001997 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00001998 break;
1999 }
2000
2001 /*
drh1807ce32004-09-07 13:20:35 +00002002 ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
drh5d9d7572003-08-19 14:31:01 +00002003 */
drh1807ce32004-09-07 13:20:35 +00002004
2005 /* $db progress ?N CALLBACK?
2006 **
2007 ** Invoke the given callback every N virtual machine opcodes while executing
2008 ** queries.
2009 */
2010 case DB_PROGRESS: {
2011 if( objc==2 ){
2012 if( pDb->zProgress ){
2013 Tcl_AppendResult(interp, pDb->zProgress, 0);
2014 }
2015 }else if( objc==4 ){
2016 char *zProgress;
2017 int len;
2018 int N;
2019 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002020 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002021 };
2022 if( pDb->zProgress ){
2023 Tcl_Free(pDb->zProgress);
2024 }
2025 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2026 if( zProgress && len>0 ){
2027 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002028 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002029 }else{
2030 pDb->zProgress = 0;
2031 }
2032#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2033 if( pDb->zProgress ){
2034 pDb->interp = interp;
2035 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2036 }else{
2037 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2038 }
2039#endif
2040 }else{
2041 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002042 return TCL_ERROR;
2043 }
drh5d9d7572003-08-19 14:31:01 +00002044 break;
2045 }
2046
drh19e2d372005-08-29 23:00:03 +00002047 /* $db profile ?CALLBACK?
2048 **
2049 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2050 ** that has run. The text of the SQL and the amount of elapse time are
2051 ** appended to CALLBACK before the script is run.
2052 */
2053 case DB_PROFILE: {
2054 if( objc>3 ){
2055 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2056 return TCL_ERROR;
2057 }else if( objc==2 ){
2058 if( pDb->zProfile ){
2059 Tcl_AppendResult(interp, pDb->zProfile, 0);
2060 }
2061 }else{
2062 char *zProfile;
2063 int len;
2064 if( pDb->zProfile ){
2065 Tcl_Free(pDb->zProfile);
2066 }
2067 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2068 if( zProfile && len>0 ){
2069 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002070 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002071 }else{
2072 pDb->zProfile = 0;
2073 }
2074#ifndef SQLITE_OMIT_TRACE
2075 if( pDb->zProfile ){
2076 pDb->interp = interp;
2077 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2078 }else{
2079 sqlite3_profile(pDb->db, 0, 0);
2080 }
2081#endif
2082 }
2083 break;
2084 }
2085
drh5d9d7572003-08-19 14:31:01 +00002086 /*
drh22fbcb82004-02-01 01:22:50 +00002087 ** $db rekey KEY
2088 **
2089 ** Change the encryption key on the currently open database.
2090 */
2091 case DB_REKEY: {
2092 int nKey;
2093 void *pKey;
2094 if( objc!=3 ){
2095 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2096 return TCL_ERROR;
2097 }
2098 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00002099#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00002100 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002101 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00002102 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002103 rc = TCL_ERROR;
2104 }
2105#endif
2106 break;
2107 }
2108
2109 /*
drhbec3f402000-08-04 13:49:02 +00002110 ** $db timeout MILLESECONDS
2111 **
2112 ** Delay for the number of milliseconds specified when a file is locked.
2113 */
drh6d313162000-09-21 13:01:35 +00002114 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002115 int ms;
drh6d313162000-09-21 13:01:35 +00002116 if( objc!=3 ){
2117 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002118 return TCL_ERROR;
2119 }
drh6d313162000-09-21 13:01:35 +00002120 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002121 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002122 break;
drh75897232000-05-29 14:26:00 +00002123 }
danielk197755c45f22005-04-03 23:54:43 +00002124
2125 /*
drh0f14e2e2004-06-29 12:39:08 +00002126 ** $db total_changes
2127 **
2128 ** Return the number of rows that were modified, inserted, or deleted
2129 ** since the database handle was created.
2130 */
2131 case DB_TOTAL_CHANGES: {
2132 Tcl_Obj *pResult;
2133 if( objc!=2 ){
2134 Tcl_WrongNumArgs(interp, 2, objv, "");
2135 return TCL_ERROR;
2136 }
2137 pResult = Tcl_GetObjResult(interp);
2138 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2139 break;
2140 }
2141
drhb5a20d32003-04-23 12:25:23 +00002142 /* $db trace ?CALLBACK?
2143 **
2144 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2145 ** that is executed. The text of the SQL is appended to CALLBACK before
2146 ** it is executed.
2147 */
2148 case DB_TRACE: {
2149 if( objc>3 ){
2150 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002151 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002152 }else if( objc==2 ){
2153 if( pDb->zTrace ){
2154 Tcl_AppendResult(interp, pDb->zTrace, 0);
2155 }
2156 }else{
2157 char *zTrace;
2158 int len;
2159 if( pDb->zTrace ){
2160 Tcl_Free(pDb->zTrace);
2161 }
2162 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2163 if( zTrace && len>0 ){
2164 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002165 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002166 }else{
2167 pDb->zTrace = 0;
2168 }
drh19e2d372005-08-29 23:00:03 +00002169#ifndef SQLITE_OMIT_TRACE
drhb5a20d32003-04-23 12:25:23 +00002170 if( pDb->zTrace ){
2171 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002172 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002173 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002174 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002175 }
drh19e2d372005-08-29 23:00:03 +00002176#endif
drhb5a20d32003-04-23 12:25:23 +00002177 }
2178 break;
2179 }
2180
drh3d214232005-08-02 12:21:08 +00002181 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2182 **
2183 ** Start a new transaction (if we are not already in the midst of a
2184 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2185 ** completes, either commit the transaction or roll it back if SCRIPT
2186 ** throws an exception. Or if no new transation was started, do nothing.
2187 ** pass the exception on up the stack.
2188 **
2189 ** This command was inspired by Dave Thomas's talk on Ruby at the
2190 ** 2005 O'Reilly Open Source Convention (OSCON).
2191 */
2192 case DB_TRANSACTION: {
2193 int inTrans;
2194 Tcl_Obj *pScript;
2195 const char *zBegin = "BEGIN";
2196 if( objc!=3 && objc!=4 ){
2197 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2198 return TCL_ERROR;
2199 }
2200 if( objc==3 ){
2201 pScript = objv[2];
2202 } else {
2203 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002204 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002205 };
2206 enum TTYPE_enum {
2207 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2208 };
2209 int ttype;
drhb5555e72005-08-02 17:15:14 +00002210 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002211 0, &ttype) ){
2212 return TCL_ERROR;
2213 }
2214 switch( (enum TTYPE_enum)ttype ){
2215 case TTYPE_DEFERRED: /* no-op */; break;
2216 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2217 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2218 }
2219 pScript = objv[3];
2220 }
2221 inTrans = !sqlite3_get_autocommit(pDb->db);
2222 if( !inTrans ){
drh37527852006-03-16 16:19:56 +00002223 (void)sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
drh3d214232005-08-02 12:21:08 +00002224 }
2225 rc = Tcl_EvalObjEx(interp, pScript, 0);
2226 if( !inTrans ){
2227 const char *zEnd;
2228 if( rc==TCL_ERROR ){
2229 zEnd = "ROLLBACK";
2230 } else {
2231 zEnd = "COMMIT";
2232 }
drh109b4352007-06-12 18:50:13 +00002233 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
2234 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
2235 }
drh3d214232005-08-02 12:21:08 +00002236 }
2237 break;
2238 }
2239
danielk197794eb6a12005-12-15 15:22:08 +00002240 /*
2241 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002242 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002243 */
danielk197771fd80b2005-12-16 06:54:01 +00002244 case DB_UPDATE_HOOK:
2245 case DB_ROLLBACK_HOOK: {
2246
2247 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2248 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2249 */
2250 Tcl_Obj **ppHook;
2251 if( choice==DB_UPDATE_HOOK ){
2252 ppHook = &pDb->pUpdateHook;
2253 }else{
2254 ppHook = &pDb->pRollbackHook;
2255 }
2256
danielk197794eb6a12005-12-15 15:22:08 +00002257 if( objc!=2 && objc!=3 ){
2258 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2259 return TCL_ERROR;
2260 }
danielk197771fd80b2005-12-16 06:54:01 +00002261 if( *ppHook ){
2262 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002263 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002264 Tcl_DecrRefCount(*ppHook);
2265 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00002266 }
2267 }
2268 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002269 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00002270 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00002271 *ppHook = objv[2];
2272 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002273 }
2274 }
danielk197771fd80b2005-12-16 06:54:01 +00002275
2276 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2277 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
2278
danielk197794eb6a12005-12-15 15:22:08 +00002279 break;
2280 }
2281
danielk19774397de52005-01-12 12:44:03 +00002282 /* $db version
2283 **
2284 ** Return the version string for this database.
2285 */
2286 case DB_VERSION: {
2287 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2288 break;
2289 }
2290
tpoindex1067fe12004-12-17 15:41:11 +00002291
drh6d313162000-09-21 13:01:35 +00002292 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002293 return rc;
drh75897232000-05-29 14:26:00 +00002294}
2295
2296/*
drh3570ad92007-08-31 14:31:44 +00002297** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
2298** ?-create BOOLEAN?
drh75897232000-05-29 14:26:00 +00002299**
2300** This is the main Tcl command. When the "sqlite" Tcl command is
2301** invoked, this routine runs to process that command.
2302**
2303** The first argument, DBNAME, is an arbitrary name for a new
2304** database connection. This command creates a new command named
2305** DBNAME that is used to control that connection. The database
2306** connection is deleted when the DBNAME command is deleted.
2307**
drh3570ad92007-08-31 14:31:44 +00002308** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00002309**
drh75897232000-05-29 14:26:00 +00002310*/
drh22fbcb82004-02-01 01:22:50 +00002311static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002312 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002313 void *pKey = 0;
2314 int nKey = 0;
2315 const char *zArg;
drh75897232000-05-29 14:26:00 +00002316 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00002317 int i;
drh22fbcb82004-02-01 01:22:50 +00002318 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00002319 const char *zVfs = 0;
2320 int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
drh882e8e42006-08-24 02:42:27 +00002321 Tcl_DString translatedFilename;
drh22fbcb82004-02-01 01:22:50 +00002322 if( objc==2 ){
2323 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002324 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00002325 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00002326 return TCL_OK;
2327 }
drh9eb9e262004-02-11 02:18:05 +00002328 if( strcmp(zArg,"-has-codec")==0 ){
2329#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002330 Tcl_AppendResult(interp,"1",0);
2331#else
2332 Tcl_AppendResult(interp,"0",0);
2333#endif
2334 return TCL_OK;
2335 }
drhfbc3eab2001-04-06 16:13:42 +00002336 }
drh3570ad92007-08-31 14:31:44 +00002337 for(i=3; i+1<objc; i+=2){
2338 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00002339 if( strcmp(zArg,"-key")==0 ){
drh3570ad92007-08-31 14:31:44 +00002340 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
2341 }else if( strcmp(zArg, "-vfs")==0 ){
2342 i++;
2343 zVfs = Tcl_GetString(objv[i]);
2344 }else if( strcmp(zArg, "-readonly")==0 ){
2345 int b;
2346 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2347 if( b ){
drh33f4e022007-09-03 15:19:34 +00002348 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00002349 flags |= SQLITE_OPEN_READONLY;
2350 }else{
2351 flags &= ~SQLITE_OPEN_READONLY;
2352 flags |= SQLITE_OPEN_READWRITE;
2353 }
2354 }else if( strcmp(zArg, "-create")==0 ){
2355 int b;
2356 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00002357 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00002358 flags |= SQLITE_OPEN_CREATE;
2359 }else{
2360 flags &= ~SQLITE_OPEN_CREATE;
2361 }
2362 }else{
2363 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
2364 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00002365 }
2366 }
drh3570ad92007-08-31 14:31:44 +00002367 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00002368 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00002369 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh9eb9e262004-02-11 02:18:05 +00002370#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00002371 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00002372#endif
2373 );
drh75897232000-05-29 14:26:00 +00002374 return TCL_ERROR;
2375 }
drh75897232000-05-29 14:26:00 +00002376 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00002377 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00002378 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00002379 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
2380 return TCL_ERROR;
2381 }
2382 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00002383 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00002384 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
drh3570ad92007-08-31 14:31:44 +00002385 sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00002386 Tcl_DStringFree(&translatedFilename);
danielk197780290862004-05-22 09:21:21 +00002387 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
drh9404d502006-12-19 18:46:08 +00002388 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
danielk197780290862004-05-22 09:21:21 +00002389 sqlite3_close(p->db);
2390 p->db = 0;
2391 }
drhf3a65f72007-08-22 20:18:21 +00002392#ifdef SQLITE_TEST
2393 if( p->db ){
2394 extern int Md5_Register(sqlite3*);
2395 if( Md5_Register(p->db)==SQLITE_NOMEM ){
2396 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
2397 sqlite3_close(p->db);
2398 p->db = 0;
2399 }
2400 }
2401#endif
drh2011d5f2004-07-22 02:40:37 +00002402#ifdef SQLITE_HAS_CODEC
drhf3a65f72007-08-22 20:18:21 +00002403 if( p->db ){
2404 sqlite3_key(p->db, pKey, nKey);
2405 }
drheb8ed702004-02-11 10:37:23 +00002406#endif
drhbec3f402000-08-04 13:49:02 +00002407 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00002408 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00002409 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00002410 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00002411 return TCL_ERROR;
2412 }
drhfb7e7652005-01-24 00:28:42 +00002413 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00002414 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00002415 zArg = Tcl_GetStringFromObj(objv[1], 0);
2416 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
drh75897232000-05-29 14:26:00 +00002417 return TCL_OK;
2418}
2419
2420/*
drh90ca9752001-09-28 17:47:14 +00002421** Provide a dummy Tcl_InitStubs if we are using this as a static
2422** library.
2423*/
2424#ifndef USE_TCL_STUBS
2425# undef Tcl_InitStubs
2426# define Tcl_InitStubs(a,b,c)
2427#endif
2428
2429/*
drh29bc4612005-10-05 10:40:15 +00002430** Make sure we have a PACKAGE_VERSION macro defined. This will be
2431** defined automatically by the TEA makefile. But other makefiles
2432** do not define it.
2433*/
2434#ifndef PACKAGE_VERSION
2435# define PACKAGE_VERSION SQLITE_VERSION
2436#endif
2437
2438/*
drh75897232000-05-29 14:26:00 +00002439** Initialize this module.
2440**
2441** This Tcl module contains only a single new Tcl command named "sqlite".
2442** (Hence there is no namespace. There is no point in using a namespace
2443** if the extension only supplies one new name!) The "sqlite" command is
2444** used to open a new SQLite database. See the DbMain() routine above
2445** for additional information.
2446*/
drhad6e1372006-07-10 21:15:51 +00002447EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00002448 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00002449 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002450 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh49766d62005-01-08 18:42:28 +00002451 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002452 Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
drh90ca9752001-09-28 17:47:14 +00002453 return TCL_OK;
2454}
drhad6e1372006-07-10 21:15:51 +00002455EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2456EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2457EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002458
2459#ifndef SQLITE_3_SUFFIX_ONLY
drhad6e1372006-07-10 21:15:51 +00002460EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2461EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2462EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2463EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002464#endif
drh75897232000-05-29 14:26:00 +00002465
drh3e27c022004-07-23 00:01:38 +00002466#ifdef TCLSH
2467/*****************************************************************************
2468** The code that follows is used to build standalone TCL interpreters
drh3570ad92007-08-31 14:31:44 +00002469** that are statically linked with SQLite.
drh75897232000-05-29 14:26:00 +00002470*/
drh348784e2000-05-29 20:41:49 +00002471
2472/*
drh3e27c022004-07-23 00:01:38 +00002473** If the macro TCLSH is one, then put in code this for the
2474** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00002475** standard input, or if a file is named on the command line
2476** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00002477*/
drh3e27c022004-07-23 00:01:38 +00002478#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00002479static char zMainloop[] =
2480 "set line {}\n"
2481 "while {![eof stdin]} {\n"
2482 "if {$line!=\"\"} {\n"
2483 "puts -nonewline \"> \"\n"
2484 "} else {\n"
2485 "puts -nonewline \"% \"\n"
2486 "}\n"
2487 "flush stdout\n"
2488 "append line [gets stdin]\n"
2489 "if {[info complete $line]} {\n"
2490 "if {[catch {uplevel #0 $line} result]} {\n"
2491 "puts stderr \"Error: $result\"\n"
2492 "} elseif {$result!=\"\"} {\n"
2493 "puts $result\n"
2494 "}\n"
2495 "set line {}\n"
2496 "} else {\n"
2497 "append line \\n\n"
2498 "}\n"
2499 "}\n"
2500;
drh3e27c022004-07-23 00:01:38 +00002501#endif
2502
2503/*
2504** If the macro TCLSH is two, then get the main loop code out of
2505** the separate file "spaceanal_tcl.h".
2506*/
2507#if TCLSH==2
2508static char zMainloop[] =
2509#include "spaceanal_tcl.h"
2510;
2511#endif
drh348784e2000-05-29 20:41:49 +00002512
2513#define TCLSH_MAIN main /* Needed to fake out mktclapp */
2514int TCLSH_MAIN(int argc, char **argv){
2515 Tcl_Interp *interp;
drh297ecf12001-04-05 15:57:13 +00002516 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00002517 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00002518 Sqlite3_Init(interp);
drhd9b02572001-04-15 00:37:09 +00002519#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00002520 {
drh2f999a62007-08-15 19:16:43 +00002521 extern int Md5_Init(Tcl_Interp*);
2522 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00002523 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00002524 extern int Sqlitetest2_Init(Tcl_Interp*);
2525 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00002526 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00002527 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00002528 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00002529 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00002530 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00002531 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00002532 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00002533 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00002534 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00002535 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
2536 extern int Sqlitetestschema_Init(Tcl_Interp*);
2537 extern int Sqlitetestsse_Init(Tcl_Interp*);
2538 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00002539 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00002540 extern int SqlitetestOnefile_Init();
drh2e66f0b2005-04-28 17:18:48 +00002541
drh2f999a62007-08-15 19:16:43 +00002542 Md5_Init(interp);
2543 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00002544 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00002545 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00002546 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00002547 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00002548 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00002549 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00002550 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00002551 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00002552 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00002553 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00002554 Sqlitetest_autoext_Init(interp);
drh15926592007-04-06 15:02:13 +00002555 Sqlitetest_hexio_Init(interp);
drh2f999a62007-08-15 19:16:43 +00002556 Sqlitetest_malloc_Init(interp);
2557 Sqlitetestschema_Init(interp);
2558 Sqlitetesttclvar_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00002559 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00002560 SqlitetestOnefile_Init(interp);
2561
drh89dec812005-04-28 19:03:37 +00002562#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00002563 Sqlitetestsse_Init(interp);
2564#endif
drhd1bf3512001-04-07 15:24:33 +00002565 }
2566#endif
drh3e27c022004-07-23 00:01:38 +00002567 if( argc>=2 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002568 int i;
shessad42c3a2006-08-22 23:53:46 +00002569 char zArgc[32];
2570 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
2571 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00002572 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
2573 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00002574 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00002575 Tcl_SetVar(interp, "argv", argv[i],
2576 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
2577 }
drh3e27c022004-07-23 00:01:38 +00002578 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00002579 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drhc61053b2000-06-04 12:58:36 +00002580 if( zInfo==0 ) zInfo = interp->result;
2581 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00002582 return 1;
2583 }
drh3e27c022004-07-23 00:01:38 +00002584 }
2585 if( argc<=1 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002586 Tcl_GlobalEval(interp, zMainloop);
2587 }
2588 return 0;
2589}
2590#endif /* TCLSH */