blob: 7210faed620c7662a0fdad68125c370e88fef7f5 [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**
drhbd4d3972008-04-04 12:21:08 +000015** $Id: tclsqlite.c,v 1.213 2008/04/04 12:21:09 drh Exp $
drh75897232000-05-29 14:26:00 +000016*/
drh17a68932001-01-31 13:28:08 +000017#include "tcl.h"
danielk1977b4e9af92007-05-01 17:49:49 +000018#include <errno.h>
drhbd08af42007-04-05 21:58:33 +000019
20/*
21** Some additional include files are needed if this file is not
22** appended to the amalgamation.
23*/
24#ifndef SQLITE_AMALGAMATION
25# include "sqliteInt.h"
drhbd08af42007-04-05 21:58:33 +000026# include <stdlib.h>
27# include <string.h>
28# include <assert.h>
29# include <ctype.h>
30#endif
drh75897232000-05-29 14:26:00 +000031
drhad6e1372006-07-10 21:15:51 +000032/*
33 * Windows needs to know which symbols to export. Unix does not.
34 * BUILD_sqlite should be undefined for Unix.
35 */
36#ifdef BUILD_sqlite
37#undef TCL_STORAGE_CLASS
38#define TCL_STORAGE_CLASS DLLEXPORT
39#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000040
danielk1977a21c6b62005-01-24 10:25:59 +000041#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000042#define MAX_PREPARED_STMTS 100
43
drh75897232000-05-29 14:26:00 +000044/*
drh98808ba2001-10-18 12:34:46 +000045** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
46** have to do a translation when going between the two. Set the
47** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
48** this translation.
49*/
50#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
51# define UTF_TRANSLATION_NEEDED 1
52#endif
53
54/*
drhcabb0812002-09-14 13:47:32 +000055** New SQL functions can be created as TCL scripts. Each such function
56** is described by an instance of the following structure.
57*/
58typedef struct SqlFunc SqlFunc;
59struct SqlFunc {
60 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000061 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
62 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
63 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000064 SqlFunc *pNext; /* Next function on the list of them all */
65};
66
67/*
danielk19770202b292004-06-09 09:55:16 +000068** New collation sequences function can be created as TCL scripts. Each such
69** function is described by an instance of the following structure.
70*/
71typedef struct SqlCollate SqlCollate;
72struct SqlCollate {
73 Tcl_Interp *interp; /* The TCL interpret to execute the function */
74 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000075 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000076};
77
78/*
drhfb7e7652005-01-24 00:28:42 +000079** Prepared statements are cached for faster execution. Each prepared
80** statement is described by an instance of the following structure.
81*/
82typedef struct SqlPreparedStmt SqlPreparedStmt;
83struct SqlPreparedStmt {
84 SqlPreparedStmt *pNext; /* Next in linked list */
85 SqlPreparedStmt *pPrev; /* Previous on the list */
86 sqlite3_stmt *pStmt; /* The prepared statement */
87 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +000088 const char *zSql; /* Text of the SQL statement */
drhfb7e7652005-01-24 00:28:42 +000089};
90
danielk1977d04417962007-05-02 13:16:30 +000091typedef struct IncrblobChannel IncrblobChannel;
92
drhfb7e7652005-01-24 00:28:42 +000093/*
drhbec3f402000-08-04 13:49:02 +000094** There is one instance of this structure for each SQLite database
95** that has been opened by the SQLite TCL interface.
96*/
97typedef struct SqliteDb SqliteDb;
98struct SqliteDb {
drhdddca282006-01-03 00:33:50 +000099 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000100 Tcl_Interp *interp; /* The interpreter used for this database */
101 char *zBusy; /* The busy callback routine */
102 char *zCommit; /* The commit hook callback routine */
103 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +0000104 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000105 char *zProgress; /* The progress callback routine */
106 char *zAuth; /* The authorization callback routine */
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 }
drhbd4d3972008-04-04 12:21:08 +00001343 if(strcasecmp(zConflict, "rollback") != 0 &&
1344 strcasecmp(zConflict, "abort" ) != 0 &&
1345 strcasecmp(zConflict, "fail" ) != 0 &&
1346 strcasecmp(zConflict, "ignore" ) != 0 &&
1347 strcasecmp(zConflict, "replace" ) != 0 ) {
drh19e2d372005-08-29 23:00:03 +00001348 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);
danielk19774e1ddde2008-03-25 16:16:29 +00001674 sqlite3_bind_text(pStmt, i, (char *)data, n+1, 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);
drheee4c8c2008-02-18 22:24:57 +00001705 const char *zBlob = sqlite3_column_blob(pStmt, i);
danielk1977a7a8e142008-02-13 18:25:27 +00001706 if( !zBlob ) bytes = 0;
drheee4c8c2008-02-18 22:24:57 +00001707 pVal = Tcl_NewByteArrayObj((u8*)zBlob, bytes);
drh92febd92004-08-20 18:34:20 +00001708 break;
1709 }
1710 case SQLITE_INTEGER: {
1711 sqlite_int64 v = sqlite3_column_int64(pStmt, i);
1712 if( v>=-2147483647 && v<=2147483647 ){
1713 pVal = Tcl_NewIntObj(v);
1714 }else{
1715 pVal = Tcl_NewWideIntObj(v);
1716 }
1717 break;
1718 }
1719 case SQLITE_FLOAT: {
1720 double r = sqlite3_column_double(pStmt, i);
1721 pVal = Tcl_NewDoubleObj(r);
1722 break;
1723 }
danielk197755c45f22005-04-03 23:54:43 +00001724 case SQLITE_NULL: {
1725 pVal = dbTextToObj(pDb->zNull);
1726 break;
1727 }
drh92febd92004-08-20 18:34:20 +00001728 default: {
danielk197700fd9572005-12-07 06:27:43 +00001729 pVal = dbTextToObj((char *)sqlite3_column_text(pStmt, i));
drh92febd92004-08-20 18:34:20 +00001730 break;
1731 }
danielk197730ccda12004-05-27 12:11:31 +00001732 }
1733
drh92febd92004-08-20 18:34:20 +00001734 if( pScript ){
1735 if( pArray==0 ){
1736 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001737 }else{
drh92febd92004-08-20 18:34:20 +00001738 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001739 }
drh1807ce32004-09-07 13:20:35 +00001740 }else if( choice==DB_ONECOLUMN ){
drh97f2ebc2005-12-10 21:19:04 +00001741 assert( pRet==0 );
drh1807ce32004-09-07 13:20:35 +00001742 if( pRet==0 ){
1743 pRet = pVal;
1744 Tcl_IncrRefCount(pRet);
1745 }
drh90b6bb12004-09-13 13:16:31 +00001746 rc = TCL_BREAK;
drh97f2ebc2005-12-10 21:19:04 +00001747 i = nCol;
1748 }else if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001749 Tcl_DecrRefCount(pRet);
1750 pRet = Tcl_NewBooleanObj(1);
1751 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001752 rc = TCL_BREAK;
1753 i = nCol;
danielk197730ccda12004-05-27 12:11:31 +00001754 }else{
danielk197730ccda12004-05-27 12:11:31 +00001755 Tcl_ListObjAppendElement(interp, pRet, pVal);
1756 }
1757 }
1758
drh92febd92004-08-20 18:34:20 +00001759 if( pScript ){
1760 rc = Tcl_EvalObjEx(interp, pScript, 0);
drh90b6bb12004-09-13 13:16:31 +00001761 if( rc==TCL_CONTINUE ){
1762 rc = TCL_OK;
1763 }
danielk197730ccda12004-05-27 12:11:31 +00001764 }
1765 }
drh90b6bb12004-09-13 13:16:31 +00001766 if( rc==TCL_BREAK ){
1767 rc = TCL_OK;
1768 }
drh92febd92004-08-20 18:34:20 +00001769
1770 /* Free the column name objects */
1771 if( pScript ){
danielk19778e556522007-11-13 10:30:24 +00001772 /* If the query returned no rows, but an array variable was
1773 ** specified, call computeColumnNames() now to populate the
1774 ** arrayname(*) variable.
1775 */
1776 if (pArray && nCol < 0) {
1777 Tcl_Obj ***ap = (pScript?&apColName:0);
1778 nCol = computeColumnNames(interp, pStmt, ap, pArray);
1779 }
drh92febd92004-08-20 18:34:20 +00001780 for(i=0; i<nCol; i++){
1781 Tcl_DecrRefCount(apColName[i]);
1782 }
1783 Tcl_Free((char*)apColName);
1784 }
1785
drh1d895032004-08-26 00:56:05 +00001786 /* Free the bound string and blob parameters */
1787 for(i=0; i<nParm; i++){
1788 Tcl_DecrRefCount(apParm[i]);
1789 }
1790 if( apParm!=aParm ){
1791 Tcl_Free((char*)apParm);
1792 }
1793
drhfb7e7652005-01-24 00:28:42 +00001794 /* Reset the statement. If the result code is SQLITE_SCHEMA, then
1795 ** flush the statement cache and try the statement again.
drh92febd92004-08-20 18:34:20 +00001796 */
drhfb7e7652005-01-24 00:28:42 +00001797 rc2 = sqlite3_reset(pStmt);
danielk19778e556522007-11-13 10:30:24 +00001798 if( SQLITE_OK!=rc2 ){
drhfb7e7652005-01-24 00:28:42 +00001799 /* If a run-time error occurs, report the error and stop reading
1800 ** the SQL
1801 */
danielk1977ef2cb632004-05-29 02:37:19 +00001802 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
drhfb7e7652005-01-24 00:28:42 +00001803 sqlite3_finalize(pStmt);
danielk197730ccda12004-05-27 12:11:31 +00001804 rc = TCL_ERROR;
drhfb7e7652005-01-24 00:28:42 +00001805 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001806 break;
drhfb7e7652005-01-24 00:28:42 +00001807 }else if( pDb->maxStmt<=0 ){
1808 /* If the cache is turned off, deallocated the statement */
1809 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1810 sqlite3_finalize(pStmt);
1811 }else{
1812 /* Everything worked and the cache is operational.
1813 ** Create a new SqlPreparedStmt structure if we need one.
1814 ** (If we already have one we can just reuse it.)
1815 */
1816 if( pPreStmt==0 ){
1817 len = zLeft - zSql;
danielk1977d0e2a852007-11-14 06:48:48 +00001818 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) );
drhfb7e7652005-01-24 00:28:42 +00001819 if( pPreStmt==0 ) return TCL_ERROR;
1820 pPreStmt->pStmt = pStmt;
1821 pPreStmt->nSql = len;
danielk1977d0e2a852007-11-14 06:48:48 +00001822 pPreStmt->zSql = sqlite3_sql(pStmt);
1823 assert( strlen(pPreStmt->zSql)==len );
1824 assert( 0==memcmp(pPreStmt->zSql, zSql, len) );
drhfb7e7652005-01-24 00:28:42 +00001825 }
1826
1827 /* Add the prepared statement to the beginning of the cache list
1828 */
1829 pPreStmt->pNext = pDb->stmtList;
1830 pPreStmt->pPrev = 0;
1831 if( pDb->stmtList ){
1832 pDb->stmtList->pPrev = pPreStmt;
1833 }
1834 pDb->stmtList = pPreStmt;
1835 if( pDb->stmtLast==0 ){
1836 assert( pDb->nStmt==0 );
1837 pDb->stmtLast = pPreStmt;
1838 }else{
1839 assert( pDb->nStmt>0 );
1840 }
1841 pDb->nStmt++;
1842
1843 /* If we have too many statement in cache, remove the surplus from the
1844 ** end of the cache list.
1845 */
1846 while( pDb->nStmt>pDb->maxStmt ){
1847 sqlite3_finalize(pDb->stmtLast->pStmt);
1848 pDb->stmtLast = pDb->stmtLast->pPrev;
1849 Tcl_Free((char*)pDb->stmtLast->pNext);
1850 pDb->stmtLast->pNext = 0;
1851 pDb->nStmt--;
1852 }
danielk197730ccda12004-05-27 12:11:31 +00001853 }
1854
drhfb7e7652005-01-24 00:28:42 +00001855 /* Proceed to the next statement */
danielk197730ccda12004-05-27 12:11:31 +00001856 zSql = zLeft;
1857 }
drh1d895032004-08-26 00:56:05 +00001858 Tcl_DecrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001859
drh1807ce32004-09-07 13:20:35 +00001860 if( pRet ){
1861 if( rc==TCL_OK ){
1862 Tcl_SetObjResult(interp, pRet);
1863 }
1864 Tcl_DecrRefCount(pRet);
drh050be322006-07-12 00:18:40 +00001865 }else if( rc==TCL_OK ){
1866 Tcl_ResetResult(interp);
danielk197730ccda12004-05-27 12:11:31 +00001867 }
danielk197730ccda12004-05-27 12:11:31 +00001868 break;
1869 }
drhbec3f402000-08-04 13:49:02 +00001870
1871 /*
drhcabb0812002-09-14 13:47:32 +00001872 ** $db function NAME SCRIPT
1873 **
1874 ** Create a new SQL function called NAME. Whenever that function is
1875 ** called, invoke SCRIPT to evaluate the function.
1876 */
1877 case DB_FUNCTION: {
1878 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00001879 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00001880 char *zName;
drhcabb0812002-09-14 13:47:32 +00001881 if( objc!=4 ){
1882 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1883 return TCL_ERROR;
1884 }
1885 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00001886 pScript = objv[3];
1887 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00001888 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00001889 if( pFunc->pScript ){
1890 Tcl_DecrRefCount(pFunc->pScript);
1891 }
1892 pFunc->pScript = pScript;
1893 Tcl_IncrRefCount(pScript);
1894 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
danielk1977c8c11582004-06-29 13:41:21 +00001895 rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00001896 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00001897 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00001898 rc = TCL_ERROR;
1899 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00001900 }
drhcabb0812002-09-14 13:47:32 +00001901 break;
1902 }
1903
1904 /*
danielk19778cbadb02007-05-03 16:31:26 +00001905 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00001906 */
1907 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00001908#ifdef SQLITE_OMIT_INCRBLOB
1909 Tcl_AppendResult(interp, "incrblob not available in this build", 0);
1910 return TCL_ERROR;
1911#else
danielk19778cbadb02007-05-03 16:31:26 +00001912 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00001913 const char *zDb = "main";
1914 const char *zTable;
1915 const char *zColumn;
1916 sqlite_int64 iRow;
1917
danielk19778cbadb02007-05-03 16:31:26 +00001918 /* Check for the -readonly option */
1919 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
1920 isReadonly = 1;
1921 }
1922
1923 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
1924 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00001925 return TCL_ERROR;
1926 }
1927
danielk19778cbadb02007-05-03 16:31:26 +00001928 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00001929 zDb = Tcl_GetString(objv[2]);
1930 }
1931 zTable = Tcl_GetString(objv[objc-3]);
1932 zColumn = Tcl_GetString(objv[objc-2]);
1933 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
1934
1935 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00001936 rc = createIncrblobChannel(
1937 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
1938 );
danielk1977b4e9af92007-05-01 17:49:49 +00001939 }
danielk197732a0d8b2007-05-04 19:03:02 +00001940#endif
danielk1977b4e9af92007-05-01 17:49:49 +00001941 break;
1942 }
1943
1944 /*
drhf11bded2006-07-17 00:02:44 +00001945 ** $db interrupt
1946 **
1947 ** Interrupt the execution of the inner-most SQL interpreter. This
1948 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
1949 */
1950 case DB_INTERRUPT: {
1951 sqlite3_interrupt(pDb->db);
1952 break;
1953 }
1954
1955 /*
drh19e2d372005-08-29 23:00:03 +00001956 ** $db nullvalue ?STRING?
1957 **
1958 ** Change text used when a NULL comes back from the database. If ?STRING?
1959 ** is not present, then the current string used for NULL is returned.
1960 ** If STRING is present, then STRING is returned.
1961 **
1962 */
1963 case DB_NULLVALUE: {
1964 if( objc!=2 && objc!=3 ){
1965 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
1966 return TCL_ERROR;
1967 }
1968 if( objc==3 ){
1969 int len;
1970 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
1971 if( pDb->zNull ){
1972 Tcl_Free(pDb->zNull);
1973 }
1974 if( zNull && len>0 ){
1975 pDb->zNull = Tcl_Alloc( len + 1 );
1976 strncpy(pDb->zNull, zNull, len);
1977 pDb->zNull[len] = '\0';
1978 }else{
1979 pDb->zNull = 0;
1980 }
1981 }
1982 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
1983 break;
1984 }
1985
1986 /*
drhaf9ff332002-01-16 21:00:27 +00001987 ** $db last_insert_rowid
1988 **
1989 ** Return an integer which is the ROWID for the most recent insert.
1990 */
1991 case DB_LAST_INSERT_ROWID: {
1992 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00001993 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00001994 if( objc!=2 ){
1995 Tcl_WrongNumArgs(interp, 2, objv, "");
1996 return TCL_ERROR;
1997 }
danielk19776f8a5032004-05-10 10:34:51 +00001998 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00001999 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002000 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002001 break;
2002 }
2003
2004 /*
drh1807ce32004-09-07 13:20:35 +00002005 ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
drh5d9d7572003-08-19 14:31:01 +00002006 */
drh1807ce32004-09-07 13:20:35 +00002007
2008 /* $db progress ?N CALLBACK?
2009 **
2010 ** Invoke the given callback every N virtual machine opcodes while executing
2011 ** queries.
2012 */
2013 case DB_PROGRESS: {
2014 if( objc==2 ){
2015 if( pDb->zProgress ){
2016 Tcl_AppendResult(interp, pDb->zProgress, 0);
2017 }
2018 }else if( objc==4 ){
2019 char *zProgress;
2020 int len;
2021 int N;
2022 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002023 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002024 };
2025 if( pDb->zProgress ){
2026 Tcl_Free(pDb->zProgress);
2027 }
2028 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2029 if( zProgress && len>0 ){
2030 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002031 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002032 }else{
2033 pDb->zProgress = 0;
2034 }
2035#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2036 if( pDb->zProgress ){
2037 pDb->interp = interp;
2038 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2039 }else{
2040 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2041 }
2042#endif
2043 }else{
2044 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002045 return TCL_ERROR;
2046 }
drh5d9d7572003-08-19 14:31:01 +00002047 break;
2048 }
2049
drh19e2d372005-08-29 23:00:03 +00002050 /* $db profile ?CALLBACK?
2051 **
2052 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2053 ** that has run. The text of the SQL and the amount of elapse time are
2054 ** appended to CALLBACK before the script is run.
2055 */
2056 case DB_PROFILE: {
2057 if( objc>3 ){
2058 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2059 return TCL_ERROR;
2060 }else if( objc==2 ){
2061 if( pDb->zProfile ){
2062 Tcl_AppendResult(interp, pDb->zProfile, 0);
2063 }
2064 }else{
2065 char *zProfile;
2066 int len;
2067 if( pDb->zProfile ){
2068 Tcl_Free(pDb->zProfile);
2069 }
2070 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2071 if( zProfile && len>0 ){
2072 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002073 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002074 }else{
2075 pDb->zProfile = 0;
2076 }
2077#ifndef SQLITE_OMIT_TRACE
2078 if( pDb->zProfile ){
2079 pDb->interp = interp;
2080 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2081 }else{
2082 sqlite3_profile(pDb->db, 0, 0);
2083 }
2084#endif
2085 }
2086 break;
2087 }
2088
drh5d9d7572003-08-19 14:31:01 +00002089 /*
drh22fbcb82004-02-01 01:22:50 +00002090 ** $db rekey KEY
2091 **
2092 ** Change the encryption key on the currently open database.
2093 */
2094 case DB_REKEY: {
2095 int nKey;
2096 void *pKey;
2097 if( objc!=3 ){
2098 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2099 return TCL_ERROR;
2100 }
2101 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00002102#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00002103 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002104 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00002105 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002106 rc = TCL_ERROR;
2107 }
2108#endif
2109 break;
2110 }
2111
2112 /*
drhbec3f402000-08-04 13:49:02 +00002113 ** $db timeout MILLESECONDS
2114 **
2115 ** Delay for the number of milliseconds specified when a file is locked.
2116 */
drh6d313162000-09-21 13:01:35 +00002117 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002118 int ms;
drh6d313162000-09-21 13:01:35 +00002119 if( objc!=3 ){
2120 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002121 return TCL_ERROR;
2122 }
drh6d313162000-09-21 13:01:35 +00002123 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002124 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002125 break;
drh75897232000-05-29 14:26:00 +00002126 }
danielk197755c45f22005-04-03 23:54:43 +00002127
2128 /*
drh0f14e2e2004-06-29 12:39:08 +00002129 ** $db total_changes
2130 **
2131 ** Return the number of rows that were modified, inserted, or deleted
2132 ** since the database handle was created.
2133 */
2134 case DB_TOTAL_CHANGES: {
2135 Tcl_Obj *pResult;
2136 if( objc!=2 ){
2137 Tcl_WrongNumArgs(interp, 2, objv, "");
2138 return TCL_ERROR;
2139 }
2140 pResult = Tcl_GetObjResult(interp);
2141 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2142 break;
2143 }
2144
drhb5a20d32003-04-23 12:25:23 +00002145 /* $db trace ?CALLBACK?
2146 **
2147 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2148 ** that is executed. The text of the SQL is appended to CALLBACK before
2149 ** it is executed.
2150 */
2151 case DB_TRACE: {
2152 if( objc>3 ){
2153 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002154 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002155 }else if( objc==2 ){
2156 if( pDb->zTrace ){
2157 Tcl_AppendResult(interp, pDb->zTrace, 0);
2158 }
2159 }else{
2160 char *zTrace;
2161 int len;
2162 if( pDb->zTrace ){
2163 Tcl_Free(pDb->zTrace);
2164 }
2165 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2166 if( zTrace && len>0 ){
2167 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002168 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002169 }else{
2170 pDb->zTrace = 0;
2171 }
drh19e2d372005-08-29 23:00:03 +00002172#ifndef SQLITE_OMIT_TRACE
drhb5a20d32003-04-23 12:25:23 +00002173 if( pDb->zTrace ){
2174 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002175 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002176 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002177 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002178 }
drh19e2d372005-08-29 23:00:03 +00002179#endif
drhb5a20d32003-04-23 12:25:23 +00002180 }
2181 break;
2182 }
2183
drh3d214232005-08-02 12:21:08 +00002184 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2185 **
2186 ** Start a new transaction (if we are not already in the midst of a
2187 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2188 ** completes, either commit the transaction or roll it back if SCRIPT
2189 ** throws an exception. Or if no new transation was started, do nothing.
2190 ** pass the exception on up the stack.
2191 **
2192 ** This command was inspired by Dave Thomas's talk on Ruby at the
2193 ** 2005 O'Reilly Open Source Convention (OSCON).
2194 */
2195 case DB_TRANSACTION: {
2196 int inTrans;
2197 Tcl_Obj *pScript;
2198 const char *zBegin = "BEGIN";
2199 if( objc!=3 && objc!=4 ){
2200 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2201 return TCL_ERROR;
2202 }
2203 if( objc==3 ){
2204 pScript = objv[2];
2205 } else {
2206 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002207 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002208 };
2209 enum TTYPE_enum {
2210 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2211 };
2212 int ttype;
drhb5555e72005-08-02 17:15:14 +00002213 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002214 0, &ttype) ){
2215 return TCL_ERROR;
2216 }
2217 switch( (enum TTYPE_enum)ttype ){
2218 case TTYPE_DEFERRED: /* no-op */; break;
2219 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2220 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2221 }
2222 pScript = objv[3];
2223 }
2224 inTrans = !sqlite3_get_autocommit(pDb->db);
2225 if( !inTrans ){
drh37527852006-03-16 16:19:56 +00002226 (void)sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
drh3d214232005-08-02 12:21:08 +00002227 }
2228 rc = Tcl_EvalObjEx(interp, pScript, 0);
2229 if( !inTrans ){
2230 const char *zEnd;
2231 if( rc==TCL_ERROR ){
2232 zEnd = "ROLLBACK";
2233 } else {
2234 zEnd = "COMMIT";
2235 }
drh109b4352007-06-12 18:50:13 +00002236 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
2237 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
2238 }
drh3d214232005-08-02 12:21:08 +00002239 }
2240 break;
2241 }
2242
danielk197794eb6a12005-12-15 15:22:08 +00002243 /*
2244 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002245 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002246 */
danielk197771fd80b2005-12-16 06:54:01 +00002247 case DB_UPDATE_HOOK:
2248 case DB_ROLLBACK_HOOK: {
2249
2250 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2251 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2252 */
2253 Tcl_Obj **ppHook;
2254 if( choice==DB_UPDATE_HOOK ){
2255 ppHook = &pDb->pUpdateHook;
2256 }else{
2257 ppHook = &pDb->pRollbackHook;
2258 }
2259
danielk197794eb6a12005-12-15 15:22:08 +00002260 if( objc!=2 && objc!=3 ){
2261 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2262 return TCL_ERROR;
2263 }
danielk197771fd80b2005-12-16 06:54:01 +00002264 if( *ppHook ){
2265 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002266 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002267 Tcl_DecrRefCount(*ppHook);
2268 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00002269 }
2270 }
2271 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002272 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00002273 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00002274 *ppHook = objv[2];
2275 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002276 }
2277 }
danielk197771fd80b2005-12-16 06:54:01 +00002278
2279 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2280 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
2281
danielk197794eb6a12005-12-15 15:22:08 +00002282 break;
2283 }
2284
danielk19774397de52005-01-12 12:44:03 +00002285 /* $db version
2286 **
2287 ** Return the version string for this database.
2288 */
2289 case DB_VERSION: {
2290 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2291 break;
2292 }
2293
tpoindex1067fe12004-12-17 15:41:11 +00002294
drh6d313162000-09-21 13:01:35 +00002295 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002296 return rc;
drh75897232000-05-29 14:26:00 +00002297}
2298
2299/*
drh3570ad92007-08-31 14:31:44 +00002300** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
2301** ?-create BOOLEAN?
drh75897232000-05-29 14:26:00 +00002302**
2303** This is the main Tcl command. When the "sqlite" Tcl command is
2304** invoked, this routine runs to process that command.
2305**
2306** The first argument, DBNAME, is an arbitrary name for a new
2307** database connection. This command creates a new command named
2308** DBNAME that is used to control that connection. The database
2309** connection is deleted when the DBNAME command is deleted.
2310**
drh3570ad92007-08-31 14:31:44 +00002311** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00002312**
drh75897232000-05-29 14:26:00 +00002313*/
drh22fbcb82004-02-01 01:22:50 +00002314static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002315 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002316 void *pKey = 0;
2317 int nKey = 0;
2318 const char *zArg;
drh75897232000-05-29 14:26:00 +00002319 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00002320 int i;
drh22fbcb82004-02-01 01:22:50 +00002321 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00002322 const char *zVfs = 0;
2323 int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
drh882e8e42006-08-24 02:42:27 +00002324 Tcl_DString translatedFilename;
drh22fbcb82004-02-01 01:22:50 +00002325 if( objc==2 ){
2326 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002327 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00002328 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00002329 return TCL_OK;
2330 }
drh9eb9e262004-02-11 02:18:05 +00002331 if( strcmp(zArg,"-has-codec")==0 ){
2332#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002333 Tcl_AppendResult(interp,"1",0);
2334#else
2335 Tcl_AppendResult(interp,"0",0);
2336#endif
2337 return TCL_OK;
2338 }
drhfbc3eab2001-04-06 16:13:42 +00002339 }
drh3570ad92007-08-31 14:31:44 +00002340 for(i=3; i+1<objc; i+=2){
2341 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00002342 if( strcmp(zArg,"-key")==0 ){
drh3570ad92007-08-31 14:31:44 +00002343 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
2344 }else if( strcmp(zArg, "-vfs")==0 ){
2345 i++;
2346 zVfs = Tcl_GetString(objv[i]);
2347 }else if( strcmp(zArg, "-readonly")==0 ){
2348 int b;
2349 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2350 if( b ){
drh33f4e022007-09-03 15:19:34 +00002351 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00002352 flags |= SQLITE_OPEN_READONLY;
2353 }else{
2354 flags &= ~SQLITE_OPEN_READONLY;
2355 flags |= SQLITE_OPEN_READWRITE;
2356 }
2357 }else if( strcmp(zArg, "-create")==0 ){
2358 int b;
2359 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00002360 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00002361 flags |= SQLITE_OPEN_CREATE;
2362 }else{
2363 flags &= ~SQLITE_OPEN_CREATE;
2364 }
2365 }else{
2366 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
2367 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00002368 }
2369 }
drh3570ad92007-08-31 14:31:44 +00002370 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00002371 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00002372 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh9eb9e262004-02-11 02:18:05 +00002373#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00002374 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00002375#endif
2376 );
drh75897232000-05-29 14:26:00 +00002377 return TCL_ERROR;
2378 }
drh75897232000-05-29 14:26:00 +00002379 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00002380 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00002381 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00002382 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
2383 return TCL_ERROR;
2384 }
2385 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00002386 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00002387 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
drh3570ad92007-08-31 14:31:44 +00002388 sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00002389 Tcl_DStringFree(&translatedFilename);
danielk197780290862004-05-22 09:21:21 +00002390 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
drh9404d502006-12-19 18:46:08 +00002391 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
danielk197780290862004-05-22 09:21:21 +00002392 sqlite3_close(p->db);
2393 p->db = 0;
2394 }
drh2011d5f2004-07-22 02:40:37 +00002395#ifdef SQLITE_HAS_CODEC
drhf3a65f72007-08-22 20:18:21 +00002396 if( p->db ){
2397 sqlite3_key(p->db, pKey, nKey);
2398 }
drheb8ed702004-02-11 10:37:23 +00002399#endif
drhbec3f402000-08-04 13:49:02 +00002400 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00002401 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00002402 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00002403 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00002404 return TCL_ERROR;
2405 }
drhfb7e7652005-01-24 00:28:42 +00002406 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00002407 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00002408 zArg = Tcl_GetStringFromObj(objv[1], 0);
2409 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
drh75897232000-05-29 14:26:00 +00002410 return TCL_OK;
2411}
2412
2413/*
drh90ca9752001-09-28 17:47:14 +00002414** Provide a dummy Tcl_InitStubs if we are using this as a static
2415** library.
2416*/
2417#ifndef USE_TCL_STUBS
2418# undef Tcl_InitStubs
2419# define Tcl_InitStubs(a,b,c)
2420#endif
2421
2422/*
drh29bc4612005-10-05 10:40:15 +00002423** Make sure we have a PACKAGE_VERSION macro defined. This will be
2424** defined automatically by the TEA makefile. But other makefiles
2425** do not define it.
2426*/
2427#ifndef PACKAGE_VERSION
2428# define PACKAGE_VERSION SQLITE_VERSION
2429#endif
2430
2431/*
drh75897232000-05-29 14:26:00 +00002432** Initialize this module.
2433**
2434** This Tcl module contains only a single new Tcl command named "sqlite".
2435** (Hence there is no namespace. There is no point in using a namespace
2436** if the extension only supplies one new name!) The "sqlite" command is
2437** used to open a new SQLite database. See the DbMain() routine above
2438** for additional information.
2439*/
drhad6e1372006-07-10 21:15:51 +00002440EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00002441 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00002442 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002443 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh49766d62005-01-08 18:42:28 +00002444 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002445 Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
drh90ca9752001-09-28 17:47:14 +00002446 return TCL_OK;
2447}
drhad6e1372006-07-10 21:15:51 +00002448EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2449EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2450EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002451
2452#ifndef SQLITE_3_SUFFIX_ONLY
drhad6e1372006-07-10 21:15:51 +00002453EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2454EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2455EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2456EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002457#endif
drh75897232000-05-29 14:26:00 +00002458
drh3e27c022004-07-23 00:01:38 +00002459#ifdef TCLSH
2460/*****************************************************************************
2461** The code that follows is used to build standalone TCL interpreters
drh3570ad92007-08-31 14:31:44 +00002462** that are statically linked with SQLite.
drh75897232000-05-29 14:26:00 +00002463*/
drh348784e2000-05-29 20:41:49 +00002464
2465/*
drh3e27c022004-07-23 00:01:38 +00002466** If the macro TCLSH is one, then put in code this for the
2467** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00002468** standard input, or if a file is named on the command line
2469** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00002470*/
drh3e27c022004-07-23 00:01:38 +00002471#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00002472static char zMainloop[] =
2473 "set line {}\n"
2474 "while {![eof stdin]} {\n"
2475 "if {$line!=\"\"} {\n"
2476 "puts -nonewline \"> \"\n"
2477 "} else {\n"
2478 "puts -nonewline \"% \"\n"
2479 "}\n"
2480 "flush stdout\n"
2481 "append line [gets stdin]\n"
2482 "if {[info complete $line]} {\n"
2483 "if {[catch {uplevel #0 $line} result]} {\n"
2484 "puts stderr \"Error: $result\"\n"
2485 "} elseif {$result!=\"\"} {\n"
2486 "puts $result\n"
2487 "}\n"
2488 "set line {}\n"
2489 "} else {\n"
2490 "append line \\n\n"
2491 "}\n"
2492 "}\n"
2493;
drh3e27c022004-07-23 00:01:38 +00002494#endif
2495
2496/*
2497** If the macro TCLSH is two, then get the main loop code out of
2498** the separate file "spaceanal_tcl.h".
2499*/
2500#if TCLSH==2
2501static char zMainloop[] =
2502#include "spaceanal_tcl.h"
2503;
2504#endif
drh348784e2000-05-29 20:41:49 +00002505
2506#define TCLSH_MAIN main /* Needed to fake out mktclapp */
2507int TCLSH_MAIN(int argc, char **argv){
2508 Tcl_Interp *interp;
drh297ecf12001-04-05 15:57:13 +00002509 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00002510 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00002511 Sqlite3_Init(interp);
drhd9b02572001-04-15 00:37:09 +00002512#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00002513 {
drh2f999a62007-08-15 19:16:43 +00002514 extern int Md5_Init(Tcl_Interp*);
2515 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00002516 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00002517 extern int Sqlitetest2_Init(Tcl_Interp*);
2518 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00002519 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00002520 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00002521 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00002522 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00002523 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00002524 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00002525 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00002526 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
drh984bfaa2008-03-19 16:08:53 +00002527 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00002528 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00002529 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
2530 extern int Sqlitetestschema_Init(Tcl_Interp*);
2531 extern int Sqlitetestsse_Init(Tcl_Interp*);
2532 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00002533 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00002534 extern int SqlitetestOnefile_Init();
drh2e66f0b2005-04-28 17:18:48 +00002535
drh2f999a62007-08-15 19:16:43 +00002536 Md5_Init(interp);
2537 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00002538 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00002539 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00002540 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00002541 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00002542 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00002543 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00002544 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00002545 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00002546 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00002547 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00002548 Sqlitetest_autoext_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00002549 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00002550 Sqlitetest_hexio_Init(interp);
drh2f999a62007-08-15 19:16:43 +00002551 Sqlitetest_malloc_Init(interp);
2552 Sqlitetestschema_Init(interp);
2553 Sqlitetesttclvar_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00002554 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00002555 SqlitetestOnefile_Init(interp);
2556
drh89dec812005-04-28 19:03:37 +00002557#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00002558 Sqlitetestsse_Init(interp);
2559#endif
drhd1bf3512001-04-07 15:24:33 +00002560 }
2561#endif
drh3e27c022004-07-23 00:01:38 +00002562 if( argc>=2 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002563 int i;
shessad42c3a2006-08-22 23:53:46 +00002564 char zArgc[32];
2565 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
2566 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00002567 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
2568 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00002569 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00002570 Tcl_SetVar(interp, "argv", argv[i],
2571 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
2572 }
drh3e27c022004-07-23 00:01:38 +00002573 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00002574 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drhc61053b2000-06-04 12:58:36 +00002575 if( zInfo==0 ) zInfo = interp->result;
2576 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00002577 return 1;
2578 }
drh3e27c022004-07-23 00:01:38 +00002579 }
2580 if( argc<=1 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002581 Tcl_GlobalEval(interp, zMainloop);
2582 }
2583 return 0;
2584}
2585#endif /* TCLSH */