blob: 4eb131970ad228f06cd946f0b795ad562f84d690 [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**
drh4f5e80f2007-06-19 17:15:46 +000015** $Id: tclsqlite.c,v 1.190 2007/06/19 17:15:47 drh Exp $
drh75897232000-05-29 14:26:00 +000016*/
drh17a68932001-01-31 13:28:08 +000017#include "tcl.h"
danielk1977b4e9af92007-05-01 17:49:49 +000018#include <errno.h>
drhbd08af42007-04-05 21:58:33 +000019
20/*
21** Some additional include files are needed if this file is not
22** appended to the amalgamation.
23*/
24#ifndef SQLITE_AMALGAMATION
25# include "sqliteInt.h"
26# include "hash.h"
27# include <stdlib.h>
28# include <string.h>
29# include <assert.h>
30# include <ctype.h>
31#endif
drh75897232000-05-29 14:26:00 +000032
drhad6e1372006-07-10 21:15:51 +000033/*
34 * Windows needs to know which symbols to export. Unix does not.
35 * BUILD_sqlite should be undefined for Unix.
36 */
37#ifdef BUILD_sqlite
38#undef TCL_STORAGE_CLASS
39#define TCL_STORAGE_CLASS DLLEXPORT
40#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000041
danielk1977a21c6b62005-01-24 10:25:59 +000042#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000043#define MAX_PREPARED_STMTS 100
44
drh75897232000-05-29 14:26:00 +000045/*
drh98808ba2001-10-18 12:34:46 +000046** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
47** have to do a translation when going between the two. Set the
48** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
49** this translation.
50*/
51#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
52# define UTF_TRANSLATION_NEEDED 1
53#endif
54
55/*
drhcabb0812002-09-14 13:47:32 +000056** New SQL functions can be created as TCL scripts. Each such function
57** is described by an instance of the following structure.
58*/
59typedef struct SqlFunc SqlFunc;
60struct SqlFunc {
61 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000062 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
63 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
64 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000065 SqlFunc *pNext; /* Next function on the list of them all */
66};
67
68/*
danielk19770202b292004-06-09 09:55:16 +000069** New collation sequences function can be created as TCL scripts. Each such
70** function is described by an instance of the following structure.
71*/
72typedef struct SqlCollate SqlCollate;
73struct SqlCollate {
74 Tcl_Interp *interp; /* The TCL interpret to execute the function */
75 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000076 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000077};
78
79/*
drhfb7e7652005-01-24 00:28:42 +000080** Prepared statements are cached for faster execution. Each prepared
81** statement is described by an instance of the following structure.
82*/
83typedef struct SqlPreparedStmt SqlPreparedStmt;
84struct SqlPreparedStmt {
85 SqlPreparedStmt *pNext; /* Next in linked list */
86 SqlPreparedStmt *pPrev; /* Previous on the list */
87 sqlite3_stmt *pStmt; /* The prepared statement */
88 int nSql; /* chars in zSql[] */
89 char zSql[1]; /* Text of the SQL statement */
90};
91
danielk1977d04417962007-05-02 13:16:30 +000092typedef struct IncrblobChannel IncrblobChannel;
93
drhfb7e7652005-01-24 00:28:42 +000094/*
drhbec3f402000-08-04 13:49:02 +000095** There is one instance of this structure for each SQLite database
96** that has been opened by the SQLite TCL interface.
97*/
98typedef struct SqliteDb SqliteDb;
99struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000100 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000101 Tcl_Interp *interp; /* The interpreter used for this database */
102 char *zBusy; /* The busy callback routine */
103 char *zCommit; /* The commit hook callback routine */
104 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +0000105 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000106 char *zProgress; /* The progress callback routine */
107 char *zAuth; /* The authorization callback routine */
108 char *zNull; /* Text to substitute for an SQL NULL value */
109 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000110 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000111 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drhd1e47332005-06-26 17:55:33 +0000112 SqlCollate *pCollate; /* List of SQL collation functions */
113 int rc; /* Return code of most recent sqlite3_exec() */
114 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000115 SqlPreparedStmt *stmtList; /* List of prepared statements*/
116 SqlPreparedStmt *stmtLast; /* Last statement in the list */
117 int maxStmt; /* The next maximum number of stmtList */
118 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000119 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh98808ba2001-10-18 12:34:46 +0000120};
drh297ecf12001-04-05 15:57:13 +0000121
danielk1977b4e9af92007-05-01 17:49:49 +0000122struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000123 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000124 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000125 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000126 Tcl_Channel channel; /* Channel identifier */
127 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
128 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000129};
130
danielk197732a0d8b2007-05-04 19:03:02 +0000131#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000132/*
danielk1977d04417962007-05-02 13:16:30 +0000133** Close all incrblob channels opened using database connection pDb.
134** This is called when shutting down the database connection.
135*/
136static void closeIncrblobChannels(SqliteDb *pDb){
137 IncrblobChannel *p;
138 IncrblobChannel *pNext;
139
140 for(p=pDb->pIncrblob; p; p=pNext){
141 pNext = p->pNext;
142
143 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
144 ** which deletes the IncrblobChannel structure at *p. So do not
145 ** call Tcl_Free() here.
146 */
147 Tcl_UnregisterChannel(pDb->interp, p->channel);
148 }
149}
150
151/*
danielk1977b4e9af92007-05-01 17:49:49 +0000152** Close an incremental blob channel.
153*/
154static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
155 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000156 int rc = sqlite3_blob_close(p->pBlob);
157 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000158
159 /* Remove the channel from the SqliteDb.pIncrblob list. */
160 if( p->pNext ){
161 p->pNext->pPrev = p->pPrev;
162 }
163 if( p->pPrev ){
164 p->pPrev->pNext = p->pNext;
165 }
166 if( p->pDb->pIncrblob==p ){
167 p->pDb->pIncrblob = p->pNext;
168 }
169
danielk197792d4d7a2007-05-04 12:05:56 +0000170 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000171 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000172
173 if( rc!=SQLITE_OK ){
174 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
175 return TCL_ERROR;
176 }
danielk1977b4e9af92007-05-01 17:49:49 +0000177 return TCL_OK;
178}
179
180/*
181** Read data from an incremental blob channel.
182*/
183static int incrblobInput(
184 ClientData instanceData,
185 char *buf,
186 int bufSize,
187 int *errorCodePtr
188){
189 IncrblobChannel *p = (IncrblobChannel *)instanceData;
190 int nRead = bufSize; /* Number of bytes to read */
191 int nBlob; /* Total size of the blob */
192 int rc; /* sqlite error code */
193
194 nBlob = sqlite3_blob_bytes(p->pBlob);
195 if( (p->iSeek+nRead)>nBlob ){
196 nRead = nBlob-p->iSeek;
197 }
198 if( nRead<=0 ){
199 return 0;
200 }
201
202 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
203 if( rc!=SQLITE_OK ){
204 *errorCodePtr = rc;
205 return -1;
206 }
207
208 p->iSeek += nRead;
209 return nRead;
210}
211
danielk1977d04417962007-05-02 13:16:30 +0000212/*
213** Write data to an incremental blob channel.
214*/
danielk1977b4e9af92007-05-01 17:49:49 +0000215static int incrblobOutput(
216 ClientData instanceData,
217 CONST char *buf,
218 int toWrite,
219 int *errorCodePtr
220){
221 IncrblobChannel *p = (IncrblobChannel *)instanceData;
222 int nWrite = toWrite; /* Number of bytes to write */
223 int nBlob; /* Total size of the blob */
224 int rc; /* sqlite error code */
225
226 nBlob = sqlite3_blob_bytes(p->pBlob);
227 if( (p->iSeek+nWrite)>nBlob ){
228 *errorCodePtr = EINVAL;
229 return -1;
230 }
231 if( nWrite<=0 ){
232 return 0;
233 }
234
235 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
236 if( rc!=SQLITE_OK ){
237 *errorCodePtr = EIO;
238 return -1;
239 }
240
241 p->iSeek += nWrite;
242 return nWrite;
243}
244
245/*
246** Seek an incremental blob channel.
247*/
248static int incrblobSeek(
249 ClientData instanceData,
250 long offset,
251 int seekMode,
252 int *errorCodePtr
253){
254 IncrblobChannel *p = (IncrblobChannel *)instanceData;
255
256 switch( seekMode ){
257 case SEEK_SET:
258 p->iSeek = offset;
259 break;
260 case SEEK_CUR:
261 p->iSeek += offset;
262 break;
263 case SEEK_END:
264 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
265 break;
266
267 default: assert(!"Bad seekMode");
268 }
269
270 return p->iSeek;
271}
272
273
274static void incrblobWatch(ClientData instanceData, int mode){
275 /* NO-OP */
276}
277static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
278 return TCL_ERROR;
279}
280
281static Tcl_ChannelType IncrblobChannelType = {
282 "incrblob", /* typeName */
283 TCL_CHANNEL_VERSION_2, /* version */
284 incrblobClose, /* closeProc */
285 incrblobInput, /* inputProc */
286 incrblobOutput, /* outputProc */
287 incrblobSeek, /* seekProc */
288 0, /* setOptionProc */
289 0, /* getOptionProc */
290 incrblobWatch, /* watchProc (this is a no-op) */
291 incrblobHandle, /* getHandleProc (always returns error) */
292 0, /* close2Proc */
293 0, /* blockModeProc */
294 0, /* flushProc */
295 0, /* handlerProc */
296 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000297};
298
299/*
300** Create a new incrblob channel.
301*/
302static int createIncrblobChannel(
303 Tcl_Interp *interp,
304 SqliteDb *pDb,
305 const char *zDb,
306 const char *zTable,
307 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000308 sqlite_int64 iRow,
309 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000310){
311 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000312 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000313 sqlite3_blob *pBlob;
314 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000315 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000316
317 /* This variable is used to name the channels: "incrblob_[incr count]" */
318 static int count = 0;
319 char zChannel[64];
320
danielk19778cbadb02007-05-03 16:31:26 +0000321 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000322 if( rc!=SQLITE_OK ){
323 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
324 return TCL_ERROR;
325 }
326
327 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
328 p->iSeek = 0;
329 p->pBlob = pBlob;
330
drh5bb3eb92007-05-04 13:15:55 +0000331 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000332 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
333 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000334
danielk1977d04417962007-05-02 13:16:30 +0000335 /* Link the new channel into the SqliteDb.pIncrblob list. */
336 p->pNext = pDb->pIncrblob;
337 p->pPrev = 0;
338 if( p->pNext ){
339 p->pNext->pPrev = p;
340 }
341 pDb->pIncrblob = p;
342 p->pDb = pDb;
343
344 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000345 return TCL_OK;
346}
danielk197732a0d8b2007-05-04 19:03:02 +0000347#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
348 #define closeIncrblobChannels(pDb)
349#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000350
drh6d313162000-09-21 13:01:35 +0000351/*
drhd1e47332005-06-26 17:55:33 +0000352** Look at the script prefix in pCmd. We will be executing this script
353** after first appending one or more arguments. This routine analyzes
354** the script to see if it is safe to use Tcl_EvalObjv() on the script
355** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
356** faster.
357**
358** Scripts that are safe to use with Tcl_EvalObjv() consists of a
359** command name followed by zero or more arguments with no [...] or $
360** or {...} or ; to be seen anywhere. Most callback scripts consist
361** of just a single procedure name and they meet this requirement.
362*/
363static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
364 /* We could try to do something with Tcl_Parse(). But we will instead
365 ** just do a search for forbidden characters. If any of the forbidden
366 ** characters appear in pCmd, we will report the string as unsafe.
367 */
368 const char *z;
369 int n;
370 z = Tcl_GetStringFromObj(pCmd, &n);
371 while( n-- > 0 ){
372 int c = *(z++);
373 if( c=='$' || c=='[' || c==';' ) return 0;
374 }
375 return 1;
376}
377
378/*
379** Find an SqlFunc structure with the given name. Or create a new
380** one if an existing one cannot be found. Return a pointer to the
381** structure.
382*/
383static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
384 SqlFunc *p, *pNew;
385 int i;
386 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen(zName) + 1 );
387 pNew->zName = (char*)&pNew[1];
388 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
389 pNew->zName[i] = 0;
390 for(p=pDb->pFunc; p; p=p->pNext){
391 if( strcmp(p->zName, pNew->zName)==0 ){
392 Tcl_Free((char*)pNew);
393 return p;
394 }
395 }
396 pNew->interp = pDb->interp;
397 pNew->pScript = 0;
398 pNew->pNext = pDb->pFunc;
399 pDb->pFunc = pNew;
400 return pNew;
401}
402
403/*
drhfb7e7652005-01-24 00:28:42 +0000404** Finalize and free a list of prepared statements
405*/
406static void flushStmtCache( SqliteDb *pDb ){
407 SqlPreparedStmt *pPreStmt;
408
409 while( pDb->stmtList ){
410 sqlite3_finalize( pDb->stmtList->pStmt );
411 pPreStmt = pDb->stmtList;
412 pDb->stmtList = pDb->stmtList->pNext;
413 Tcl_Free( (char*)pPreStmt );
414 }
415 pDb->nStmt = 0;
416 pDb->stmtLast = 0;
417}
418
419/*
drh895d7472004-08-20 16:02:39 +0000420** TCL calls this procedure when an sqlite3 database command is
421** deleted.
drh75897232000-05-29 14:26:00 +0000422*/
423static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000424 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000425 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000426 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000427 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000428 while( pDb->pFunc ){
429 SqlFunc *pFunc = pDb->pFunc;
430 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000431 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000432 Tcl_Free((char*)pFunc);
433 }
danielk19770202b292004-06-09 09:55:16 +0000434 while( pDb->pCollate ){
435 SqlCollate *pCollate = pDb->pCollate;
436 pDb->pCollate = pCollate->pNext;
437 Tcl_Free((char*)pCollate);
438 }
drhbec3f402000-08-04 13:49:02 +0000439 if( pDb->zBusy ){
440 Tcl_Free(pDb->zBusy);
441 }
drhb5a20d32003-04-23 12:25:23 +0000442 if( pDb->zTrace ){
443 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000444 }
drh19e2d372005-08-29 23:00:03 +0000445 if( pDb->zProfile ){
446 Tcl_Free(pDb->zProfile);
447 }
drhe22a3342003-04-22 20:30:37 +0000448 if( pDb->zAuth ){
449 Tcl_Free(pDb->zAuth);
450 }
danielk197755c45f22005-04-03 23:54:43 +0000451 if( pDb->zNull ){
452 Tcl_Free(pDb->zNull);
453 }
danielk197794eb6a12005-12-15 15:22:08 +0000454 if( pDb->pUpdateHook ){
455 Tcl_DecrRefCount(pDb->pUpdateHook);
456 }
danielk197771fd80b2005-12-16 06:54:01 +0000457 if( pDb->pRollbackHook ){
458 Tcl_DecrRefCount(pDb->pRollbackHook);
459 }
danielk197794eb6a12005-12-15 15:22:08 +0000460 if( pDb->pCollateNeeded ){
461 Tcl_DecrRefCount(pDb->pCollateNeeded);
462 }
drhbec3f402000-08-04 13:49:02 +0000463 Tcl_Free((char*)pDb);
464}
465
466/*
467** This routine is called when a database file is locked while trying
468** to execute SQL.
469*/
danielk19772a764eb2004-06-12 01:43:26 +0000470static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000471 SqliteDb *pDb = (SqliteDb*)cd;
472 int rc;
473 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000474
drh5bb3eb92007-05-04 13:15:55 +0000475 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000476 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000477 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
478 return 0;
479 }
480 return 1;
drh75897232000-05-29 14:26:00 +0000481}
482
483/*
danielk1977348bb5d2003-10-18 09:37:26 +0000484** This routine is invoked as the 'progress callback' for the database.
485*/
486static int DbProgressHandler(void *cd){
487 SqliteDb *pDb = (SqliteDb*)cd;
488 int rc;
489
490 assert( pDb->zProgress );
491 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
492 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
493 return 1;
494 }
495 return 0;
496}
497
drhd1167392006-01-23 13:00:35 +0000498#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000499/*
drhb5a20d32003-04-23 12:25:23 +0000500** This routine is called by the SQLite trace handler whenever a new
501** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000502*/
drhb5a20d32003-04-23 12:25:23 +0000503static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000504 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000505 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000506
drhb5a20d32003-04-23 12:25:23 +0000507 Tcl_DStringInit(&str);
508 Tcl_DStringAppend(&str, pDb->zTrace, -1);
509 Tcl_DStringAppendElement(&str, zSql);
510 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
511 Tcl_DStringFree(&str);
512 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000513}
drhd1167392006-01-23 13:00:35 +0000514#endif
drh0d1a6432003-04-03 15:46:04 +0000515
drhd1167392006-01-23 13:00:35 +0000516#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000517/*
drh19e2d372005-08-29 23:00:03 +0000518** This routine is called by the SQLite profile handler after a statement
519** SQL has executed. The TCL script in pDb->zProfile is evaluated.
520*/
521static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
522 SqliteDb *pDb = (SqliteDb*)cd;
523 Tcl_DString str;
524 char zTm[100];
525
526 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
527 Tcl_DStringInit(&str);
528 Tcl_DStringAppend(&str, pDb->zProfile, -1);
529 Tcl_DStringAppendElement(&str, zSql);
530 Tcl_DStringAppendElement(&str, zTm);
531 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
532 Tcl_DStringFree(&str);
533 Tcl_ResetResult(pDb->interp);
534}
drhd1167392006-01-23 13:00:35 +0000535#endif
drh19e2d372005-08-29 23:00:03 +0000536
537/*
drhaa940ea2004-01-15 02:44:03 +0000538** This routine is called when a transaction is committed. The
539** TCL script in pDb->zCommit is executed. If it returns non-zero or
540** if it throws an exception, the transaction is rolled back instead
541** of being committed.
542*/
543static int DbCommitHandler(void *cd){
544 SqliteDb *pDb = (SqliteDb*)cd;
545 int rc;
546
547 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
548 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
549 return 1;
550 }
551 return 0;
552}
553
danielk197771fd80b2005-12-16 06:54:01 +0000554static void DbRollbackHandler(void *clientData){
555 SqliteDb *pDb = (SqliteDb*)clientData;
556 assert(pDb->pRollbackHook);
557 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
558 Tcl_BackgroundError(pDb->interp);
559 }
560}
561
danielk197794eb6a12005-12-15 15:22:08 +0000562static void DbUpdateHandler(
563 void *p,
564 int op,
565 const char *zDb,
566 const char *zTbl,
567 sqlite_int64 rowid
568){
569 SqliteDb *pDb = (SqliteDb *)p;
570 Tcl_Obj *pCmd;
571
572 assert( pDb->pUpdateHook );
573 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
574
575 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
576 Tcl_IncrRefCount(pCmd);
577 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
578 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
579 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
580 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
581 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
582 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
583}
584
danielk19777cedc8d2004-06-10 10:50:08 +0000585static void tclCollateNeeded(
586 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000587 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000588 int enc,
589 const char *zName
590){
591 SqliteDb *pDb = (SqliteDb *)pCtx;
592 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
593 Tcl_IncrRefCount(pScript);
594 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
595 Tcl_EvalObjEx(pDb->interp, pScript, 0);
596 Tcl_DecrRefCount(pScript);
597}
598
drhaa940ea2004-01-15 02:44:03 +0000599/*
danielk19770202b292004-06-09 09:55:16 +0000600** This routine is called to evaluate an SQL collation function implemented
601** using TCL script.
602*/
603static int tclSqlCollate(
604 void *pCtx,
605 int nA,
606 const void *zA,
607 int nB,
608 const void *zB
609){
610 SqlCollate *p = (SqlCollate *)pCtx;
611 Tcl_Obj *pCmd;
612
613 pCmd = Tcl_NewStringObj(p->zScript, -1);
614 Tcl_IncrRefCount(pCmd);
615 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
616 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000617 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000618 Tcl_DecrRefCount(pCmd);
619 return (atoi(Tcl_GetStringResult(p->interp)));
620}
621
622/*
drhcabb0812002-09-14 13:47:32 +0000623** This routine is called to evaluate an SQL function implemented
624** using TCL script.
625*/
drhfb7e7652005-01-24 00:28:42 +0000626static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000627 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000628 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000629 int i;
630 int rc;
631
drhd1e47332005-06-26 17:55:33 +0000632 if( argc==0 ){
633 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
634 ** script object directly. This allows the TCL compiler to generate
635 ** bytecode for the command on the first invocation and thus make
636 ** subsequent invocations much faster. */
637 pCmd = p->pScript;
638 Tcl_IncrRefCount(pCmd);
639 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
640 Tcl_DecrRefCount(pCmd);
641 }else{
642 /* If there are arguments to the function, make a shallow copy of the
643 ** script object, lappend the arguments, then evaluate the copy.
644 **
645 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
646 ** The new Tcl_Obj contains pointers to the original list elements.
647 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
648 ** of the list to tclCmdNameType, that alternate representation will
649 ** be preserved and reused on the next invocation.
650 */
651 Tcl_Obj **aArg;
652 int nArg;
653 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
654 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
655 return;
656 }
657 pCmd = Tcl_NewListObj(nArg, aArg);
658 Tcl_IncrRefCount(pCmd);
659 for(i=0; i<argc; i++){
660 sqlite3_value *pIn = argv[i];
661 Tcl_Obj *pVal;
662
663 /* Set pVal to contain the i'th column of this row. */
664 switch( sqlite3_value_type(pIn) ){
665 case SQLITE_BLOB: {
666 int bytes = sqlite3_value_bytes(pIn);
667 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
668 break;
669 }
670 case SQLITE_INTEGER: {
671 sqlite_int64 v = sqlite3_value_int64(pIn);
672 if( v>=-2147483647 && v<=2147483647 ){
673 pVal = Tcl_NewIntObj(v);
674 }else{
675 pVal = Tcl_NewWideIntObj(v);
676 }
677 break;
678 }
679 case SQLITE_FLOAT: {
680 double r = sqlite3_value_double(pIn);
681 pVal = Tcl_NewDoubleObj(r);
682 break;
683 }
684 case SQLITE_NULL: {
685 pVal = Tcl_NewStringObj("", 0);
686 break;
687 }
688 default: {
689 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000690 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000691 break;
692 }
693 }
694 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
695 if( rc ){
696 Tcl_DecrRefCount(pCmd);
697 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
698 return;
699 }
danielk197751ad0ec2004-05-24 12:39:02 +0000700 }
drhd1e47332005-06-26 17:55:33 +0000701 if( !p->useEvalObjv ){
702 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
703 ** is a list without a string representation. To prevent this from
704 ** happening, make sure pCmd has a valid string representation */
705 Tcl_GetString(pCmd);
706 }
707 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
708 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000709 }
danielk1977562e8d32005-05-20 09:40:55 +0000710
drhc7f269d2005-05-05 10:30:29 +0000711 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000712 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000713 }else{
drhc7f269d2005-05-05 10:30:29 +0000714 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
715 int n;
716 u8 *data;
717 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
718 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000719 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000720 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000721 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000722 data = Tcl_GetByteArrayFromObj(pVar, &n);
723 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000724 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
725 (c=='i' && strcmp(zType,"int")==0) ){
726 Tcl_GetIntFromObj(0, pVar, &n);
727 sqlite3_result_int(context, n);
728 }else if( c=='d' && strcmp(zType,"double")==0 ){
729 double r;
730 Tcl_GetDoubleFromObj(0, pVar, &r);
731 sqlite3_result_double(context, r);
drhdf0bdda2005-06-25 19:31:48 +0000732 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
733 Tcl_WideInt v;
734 Tcl_GetWideIntFromObj(0, pVar, &v);
735 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000736 }else{
danielk197700fd9572005-12-07 06:27:43 +0000737 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
738 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000739 }
drhcabb0812002-09-14 13:47:32 +0000740 }
741}
drh895d7472004-08-20 16:02:39 +0000742
drhe22a3342003-04-22 20:30:37 +0000743#ifndef SQLITE_OMIT_AUTHORIZATION
744/*
745** This is the authentication function. It appends the authentication
746** type code and the two arguments to zCmd[] then invokes the result
747** on the interpreter. The reply is examined to determine if the
748** authentication fails or succeeds.
749*/
750static int auth_callback(
751 void *pArg,
752 int code,
753 const char *zArg1,
754 const char *zArg2,
755 const char *zArg3,
756 const char *zArg4
757){
758 char *zCode;
759 Tcl_DString str;
760 int rc;
761 const char *zReply;
762 SqliteDb *pDb = (SqliteDb*)pArg;
763
764 switch( code ){
765 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
766 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
767 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
768 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
769 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
770 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
771 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
772 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
773 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
774 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
775 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
776 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
777 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
778 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
779 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
780 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
781 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
782 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
783 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
784 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
785 case SQLITE_READ : zCode="SQLITE_READ"; break;
786 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
787 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
788 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000789 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
790 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000791 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000792 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000793 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000794 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
795 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000796 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
drhe22a3342003-04-22 20:30:37 +0000797 default : zCode="????"; break;
798 }
799 Tcl_DStringInit(&str);
800 Tcl_DStringAppend(&str, pDb->zAuth, -1);
801 Tcl_DStringAppendElement(&str, zCode);
802 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
803 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
804 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
805 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
806 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
807 Tcl_DStringFree(&str);
808 zReply = Tcl_GetStringResult(pDb->interp);
809 if( strcmp(zReply,"SQLITE_OK")==0 ){
810 rc = SQLITE_OK;
811 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
812 rc = SQLITE_DENY;
813 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
814 rc = SQLITE_IGNORE;
815 }else{
816 rc = 999;
817 }
818 return rc;
819}
820#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000821
822/*
danielk1977ef2cb632004-05-29 02:37:19 +0000823** zText is a pointer to text obtained via an sqlite3_result_text()
824** or similar interface. This routine returns a Tcl string object,
825** reference count set to 0, containing the text. If a translation
826** between iso8859 and UTF-8 is required, it is preformed.
827*/
828static Tcl_Obj *dbTextToObj(char const *zText){
829 Tcl_Obj *pVal;
830#ifdef UTF_TRANSLATION_NEEDED
831 Tcl_DString dCol;
832 Tcl_DStringInit(&dCol);
833 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
834 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
835 Tcl_DStringFree(&dCol);
836#else
837 pVal = Tcl_NewStringObj(zText, -1);
838#endif
839 return pVal;
840}
841
842/*
tpoindex1067fe12004-12-17 15:41:11 +0000843** This routine reads a line of text from FILE in, stores
844** the text in memory obtained from malloc() and returns a pointer
845** to the text. NULL is returned at end of file, or if malloc()
846** fails.
847**
848** The interface is like "readline" but no command-line editing
849** is done.
850**
851** copied from shell.c from '.import' command
852*/
853static char *local_getline(char *zPrompt, FILE *in){
854 char *zLine;
855 int nLine;
856 int n;
857 int eol;
858
859 nLine = 100;
860 zLine = malloc( nLine );
861 if( zLine==0 ) return 0;
862 n = 0;
863 eol = 0;
864 while( !eol ){
865 if( n+100>nLine ){
866 nLine = nLine*2 + 100;
867 zLine = realloc(zLine, nLine);
868 if( zLine==0 ) return 0;
869 }
870 if( fgets(&zLine[n], nLine - n, in)==0 ){
871 if( n==0 ){
872 free(zLine);
873 return 0;
874 }
875 zLine[n] = 0;
876 eol = 1;
877 break;
878 }
879 while( zLine[n] ){ n++; }
880 if( n>0 && zLine[n-1]=='\n' ){
881 n--;
882 zLine[n] = 0;
883 eol = 1;
884 }
885 }
886 zLine = realloc( zLine, n+1 );
887 return zLine;
888}
889
890/*
drh75897232000-05-29 14:26:00 +0000891** The "sqlite" command below creates a new Tcl command for each
892** connection it opens to an SQLite database. This routine is invoked
893** whenever one of those connection-specific commands is executed
894** in Tcl. For example, if you run Tcl code like this:
895**
drh9bb575f2004-09-06 17:24:11 +0000896** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +0000897** db1 close
898**
899** The first command opens a connection to the "my_database" database
900** and calls that connection "db1". The second command causes this
901** subroutine to be invoked.
902*/
drh6d313162000-09-21 13:01:35 +0000903static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +0000904 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +0000905 int choice;
drh22fbcb82004-02-01 01:22:50 +0000906 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +0000907 static const char *DB_strs[] = {
drhfb7e7652005-01-24 00:28:42 +0000908 "authorizer", "busy", "cache",
909 "changes", "close", "collate",
910 "collation_needed", "commit_hook", "complete",
drh41449052006-07-06 17:08:48 +0000911 "copy", "enable_load_extension","errorcode",
912 "eval", "exists", "function",
danielk1977b4e9af92007-05-01 17:49:49 +0000913 "incrblob",
drhf11bded2006-07-17 00:02:44 +0000914 "interrupt", "last_insert_rowid", "nullvalue",
915 "onecolumn", "profile", "progress",
916 "rekey", "rollback_hook", "timeout",
917 "total_changes", "trace", "transaction",
918 "update_hook", "version", 0
drh6d313162000-09-21 13:01:35 +0000919 };
drh411995d2002-06-25 19:31:18 +0000920 enum DB_enum {
drhfb7e7652005-01-24 00:28:42 +0000921 DB_AUTHORIZER, DB_BUSY, DB_CACHE,
922 DB_CHANGES, DB_CLOSE, DB_COLLATE,
923 DB_COLLATION_NEEDED, DB_COMMIT_HOOK, DB_COMPLETE,
drh41449052006-07-06 17:08:48 +0000924 DB_COPY, DB_ENABLE_LOAD_EXTENSION,DB_ERRORCODE,
925 DB_EVAL, DB_EXISTS, DB_FUNCTION,
danielk1977b4e9af92007-05-01 17:49:49 +0000926 DB_INCRBLOB,
drhf11bded2006-07-17 00:02:44 +0000927 DB_INTERRUPT, DB_LAST_INSERT_ROWID,DB_NULLVALUE,
928 DB_ONECOLUMN, DB_PROFILE, DB_PROGRESS,
929 DB_REKEY, DB_ROLLBACK_HOOK, DB_TIMEOUT,
930 DB_TOTAL_CHANGES, DB_TRACE, DB_TRANSACTION,
931 DB_UPDATE_HOOK, DB_VERSION,
drh6d313162000-09-21 13:01:35 +0000932 };
tpoindex1067fe12004-12-17 15:41:11 +0000933 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +0000934
935 if( objc<2 ){
936 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +0000937 return TCL_ERROR;
938 }
drh411995d2002-06-25 19:31:18 +0000939 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +0000940 return TCL_ERROR;
941 }
942
drh411995d2002-06-25 19:31:18 +0000943 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +0000944
drhe22a3342003-04-22 20:30:37 +0000945 /* $db authorizer ?CALLBACK?
946 **
947 ** Invoke the given callback to authorize each SQL operation as it is
948 ** compiled. 5 arguments are appended to the callback before it is
949 ** invoked:
950 **
951 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
952 ** (2) First descriptive name (depends on authorization type)
953 ** (3) Second descriptive name
954 ** (4) Name of the database (ex: "main", "temp")
955 ** (5) Name of trigger that is doing the access
956 **
957 ** The callback should return on of the following strings: SQLITE_OK,
958 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
959 **
960 ** If this method is invoked with no arguments, the current authorization
961 ** callback string is returned.
962 */
963 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +0000964#ifdef SQLITE_OMIT_AUTHORIZATION
965 Tcl_AppendResult(interp, "authorization not available in this build", 0);
966 return TCL_ERROR;
967#else
drhe22a3342003-04-22 20:30:37 +0000968 if( objc>3 ){
969 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +0000970 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +0000971 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +0000972 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +0000973 Tcl_AppendResult(interp, pDb->zAuth, 0);
974 }
975 }else{
976 char *zAuth;
977 int len;
978 if( pDb->zAuth ){
979 Tcl_Free(pDb->zAuth);
980 }
981 zAuth = Tcl_GetStringFromObj(objv[2], &len);
982 if( zAuth && len>0 ){
983 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +0000984 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +0000985 }else{
986 pDb->zAuth = 0;
987 }
drhe22a3342003-04-22 20:30:37 +0000988 if( pDb->zAuth ){
989 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000990 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +0000991 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000992 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +0000993 }
drhe22a3342003-04-22 20:30:37 +0000994 }
drh1211de32004-07-26 12:24:22 +0000995#endif
drhe22a3342003-04-22 20:30:37 +0000996 break;
997 }
998
drhbec3f402000-08-04 13:49:02 +0000999 /* $db busy ?CALLBACK?
1000 **
1001 ** Invoke the given callback if an SQL statement attempts to open
1002 ** a locked database file.
1003 */
drh6d313162000-09-21 13:01:35 +00001004 case DB_BUSY: {
1005 if( objc>3 ){
1006 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001007 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001008 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001009 if( pDb->zBusy ){
1010 Tcl_AppendResult(interp, pDb->zBusy, 0);
1011 }
1012 }else{
drh6d313162000-09-21 13:01:35 +00001013 char *zBusy;
1014 int len;
drhbec3f402000-08-04 13:49:02 +00001015 if( pDb->zBusy ){
1016 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001017 }
drh6d313162000-09-21 13:01:35 +00001018 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1019 if( zBusy && len>0 ){
1020 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001021 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001022 }else{
1023 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001024 }
1025 if( pDb->zBusy ){
1026 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001027 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001028 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001029 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001030 }
1031 }
drh6d313162000-09-21 13:01:35 +00001032 break;
1033 }
drhbec3f402000-08-04 13:49:02 +00001034
drhfb7e7652005-01-24 00:28:42 +00001035 /* $db cache flush
1036 ** $db cache size n
1037 **
1038 ** Flush the prepared statement cache, or set the maximum number of
1039 ** cached statements.
1040 */
1041 case DB_CACHE: {
1042 char *subCmd;
1043 int n;
1044
1045 if( objc<=2 ){
1046 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1047 return TCL_ERROR;
1048 }
1049 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1050 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1051 if( objc!=3 ){
1052 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1053 return TCL_ERROR;
1054 }else{
1055 flushStmtCache( pDb );
1056 }
1057 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1058 if( objc!=4 ){
1059 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1060 return TCL_ERROR;
1061 }else{
1062 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1063 Tcl_AppendResult( interp, "cannot convert \"",
1064 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1065 return TCL_ERROR;
1066 }else{
1067 if( n<0 ){
1068 flushStmtCache( pDb );
1069 n = 0;
1070 }else if( n>MAX_PREPARED_STMTS ){
1071 n = MAX_PREPARED_STMTS;
1072 }
1073 pDb->maxStmt = n;
1074 }
1075 }
1076 }else{
1077 Tcl_AppendResult( interp, "bad option \"",
1078 Tcl_GetStringFromObj(objv[0],0), "\": must be flush or size", 0);
1079 return TCL_ERROR;
1080 }
1081 break;
1082 }
1083
danielk1977b28af712004-06-21 06:50:26 +00001084 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001085 **
1086 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001087 ** the most recent INSERT, UPDATE or DELETE statement, not including
1088 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001089 */
1090 case DB_CHANGES: {
1091 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001092 if( objc!=2 ){
1093 Tcl_WrongNumArgs(interp, 2, objv, "");
1094 return TCL_ERROR;
1095 }
drhc8d30ac2002-04-12 10:08:59 +00001096 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001097 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001098 break;
1099 }
1100
drh75897232000-05-29 14:26:00 +00001101 /* $db close
1102 **
1103 ** Shutdown the database
1104 */
drh6d313162000-09-21 13:01:35 +00001105 case DB_CLOSE: {
1106 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1107 break;
1108 }
drh75897232000-05-29 14:26:00 +00001109
drh0f14e2e2004-06-29 12:39:08 +00001110 /*
1111 ** $db collate NAME SCRIPT
1112 **
1113 ** Create a new SQL collation function called NAME. Whenever
1114 ** that function is called, invoke SCRIPT to evaluate the function.
1115 */
1116 case DB_COLLATE: {
1117 SqlCollate *pCollate;
1118 char *zName;
1119 char *zScript;
1120 int nScript;
1121 if( objc!=4 ){
1122 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1123 return TCL_ERROR;
1124 }
1125 zName = Tcl_GetStringFromObj(objv[2], 0);
1126 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1127 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1128 if( pCollate==0 ) return TCL_ERROR;
1129 pCollate->interp = interp;
1130 pCollate->pNext = pDb->pCollate;
1131 pCollate->zScript = (char*)&pCollate[1];
1132 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001133 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001134 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1135 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001136 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001137 return TCL_ERROR;
1138 }
1139 break;
1140 }
1141
1142 /*
1143 ** $db collation_needed SCRIPT
1144 **
1145 ** Create a new SQL collation function called NAME. Whenever
1146 ** that function is called, invoke SCRIPT to evaluate the function.
1147 */
1148 case DB_COLLATION_NEEDED: {
1149 if( objc!=3 ){
1150 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1151 return TCL_ERROR;
1152 }
1153 if( pDb->pCollateNeeded ){
1154 Tcl_DecrRefCount(pDb->pCollateNeeded);
1155 }
1156 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1157 Tcl_IncrRefCount(pDb->pCollateNeeded);
1158 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1159 break;
1160 }
1161
drh19e2d372005-08-29 23:00:03 +00001162 /* $db commit_hook ?CALLBACK?
1163 **
1164 ** Invoke the given callback just before committing every SQL transaction.
1165 ** If the callback throws an exception or returns non-zero, then the
1166 ** transaction is aborted. If CALLBACK is an empty string, the callback
1167 ** is disabled.
1168 */
1169 case DB_COMMIT_HOOK: {
1170 if( objc>3 ){
1171 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1172 return TCL_ERROR;
1173 }else if( objc==2 ){
1174 if( pDb->zCommit ){
1175 Tcl_AppendResult(interp, pDb->zCommit, 0);
1176 }
1177 }else{
1178 char *zCommit;
1179 int len;
1180 if( pDb->zCommit ){
1181 Tcl_Free(pDb->zCommit);
1182 }
1183 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1184 if( zCommit && len>0 ){
1185 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001186 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001187 }else{
1188 pDb->zCommit = 0;
1189 }
1190 if( pDb->zCommit ){
1191 pDb->interp = interp;
1192 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1193 }else{
1194 sqlite3_commit_hook(pDb->db, 0, 0);
1195 }
1196 }
1197 break;
1198 }
1199
drh75897232000-05-29 14:26:00 +00001200 /* $db complete SQL
1201 **
1202 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1203 ** additional lines of input are needed. This is similar to the
1204 ** built-in "info complete" command of Tcl.
1205 */
drh6d313162000-09-21 13:01:35 +00001206 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00001207#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00001208 Tcl_Obj *pResult;
1209 int isComplete;
1210 if( objc!=3 ){
1211 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00001212 return TCL_ERROR;
1213 }
danielk19776f8a5032004-05-10 10:34:51 +00001214 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00001215 pResult = Tcl_GetObjResult(interp);
1216 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00001217#endif
drh6d313162000-09-21 13:01:35 +00001218 break;
1219 }
drhdcd997e2003-01-31 17:21:49 +00001220
drh19e2d372005-08-29 23:00:03 +00001221 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1222 **
1223 ** Copy data into table from filename, optionally using SEPARATOR
1224 ** as column separators. If a column contains a null string, or the
1225 ** value of NULLINDICATOR, a NULL is inserted for the column.
1226 ** conflict-algorithm is one of the sqlite conflict algorithms:
1227 ** rollback, abort, fail, ignore, replace
1228 ** On success, return the number of lines processed, not necessarily same
1229 ** as 'db changes' due to conflict-algorithm selected.
1230 **
1231 ** This code is basically an implementation/enhancement of
1232 ** the sqlite3 shell.c ".import" command.
1233 **
1234 ** This command usage is equivalent to the sqlite2.x COPY statement,
1235 ** which imports file data into a table using the PostgreSQL COPY file format:
1236 ** $db copy $conflit_algo $table_name $filename \t \\N
1237 */
1238 case DB_COPY: {
1239 char *zTable; /* Insert data into this table */
1240 char *zFile; /* The file from which to extract data */
1241 char *zConflict; /* The conflict algorithm to use */
1242 sqlite3_stmt *pStmt; /* A statement */
1243 int rc; /* Result code */
1244 int nCol; /* Number of columns in the table */
1245 int nByte; /* Number of bytes in an SQL string */
1246 int i, j; /* Loop counters */
1247 int nSep; /* Number of bytes in zSep[] */
1248 int nNull; /* Number of bytes in zNull[] */
1249 char *zSql; /* An SQL statement */
1250 char *zLine; /* A single line of input from the file */
1251 char **azCol; /* zLine[] broken up into columns */
1252 char *zCommit; /* How to commit changes */
1253 FILE *in; /* The input file */
1254 int lineno = 0; /* Line number of input file */
1255 char zLineNum[80]; /* Line number print buffer */
1256 Tcl_Obj *pResult; /* interp result */
1257
1258 char *zSep;
1259 char *zNull;
1260 if( objc<5 || objc>7 ){
1261 Tcl_WrongNumArgs(interp, 2, objv,
1262 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1263 return TCL_ERROR;
1264 }
1265 if( objc>=6 ){
1266 zSep = Tcl_GetStringFromObj(objv[5], 0);
1267 }else{
1268 zSep = "\t";
1269 }
1270 if( objc>=7 ){
1271 zNull = Tcl_GetStringFromObj(objv[6], 0);
1272 }else{
1273 zNull = "";
1274 }
1275 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1276 zTable = Tcl_GetStringFromObj(objv[3], 0);
1277 zFile = Tcl_GetStringFromObj(objv[4], 0);
1278 nSep = strlen(zSep);
1279 nNull = strlen(zNull);
1280 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00001281 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00001282 return TCL_ERROR;
1283 }
1284 if(sqlite3StrICmp(zConflict, "rollback") != 0 &&
1285 sqlite3StrICmp(zConflict, "abort" ) != 0 &&
1286 sqlite3StrICmp(zConflict, "fail" ) != 0 &&
1287 sqlite3StrICmp(zConflict, "ignore" ) != 0 &&
1288 sqlite3StrICmp(zConflict, "replace" ) != 0 ) {
1289 Tcl_AppendResult(interp, "Error: \"", zConflict,
1290 "\", conflict-algorithm must be one of: rollback, "
1291 "abort, fail, ignore, or replace", 0);
1292 return TCL_ERROR;
1293 }
1294 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1295 if( zSql==0 ){
1296 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1297 return TCL_ERROR;
1298 }
1299 nByte = strlen(zSql);
drh3e701a12007-02-01 01:53:44 +00001300 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001301 sqlite3_free(zSql);
1302 if( rc ){
1303 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1304 nCol = 0;
1305 }else{
1306 nCol = sqlite3_column_count(pStmt);
1307 }
1308 sqlite3_finalize(pStmt);
1309 if( nCol==0 ) {
1310 return TCL_ERROR;
1311 }
1312 zSql = malloc( nByte + 50 + nCol*2 );
1313 if( zSql==0 ) {
1314 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1315 return TCL_ERROR;
1316 }
1317 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1318 zConflict, zTable);
1319 j = strlen(zSql);
1320 for(i=1; i<nCol; i++){
1321 zSql[j++] = ',';
1322 zSql[j++] = '?';
1323 }
1324 zSql[j++] = ')';
1325 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00001326 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001327 free(zSql);
1328 if( rc ){
1329 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1330 sqlite3_finalize(pStmt);
1331 return TCL_ERROR;
1332 }
1333 in = fopen(zFile, "rb");
1334 if( in==0 ){
1335 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
1336 sqlite3_finalize(pStmt);
1337 return TCL_ERROR;
1338 }
1339 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1340 if( azCol==0 ) {
1341 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00001342 fclose(in);
drh19e2d372005-08-29 23:00:03 +00001343 return TCL_ERROR;
1344 }
drh37527852006-03-16 16:19:56 +00001345 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001346 zCommit = "COMMIT";
1347 while( (zLine = local_getline(0, in))!=0 ){
1348 char *z;
1349 i = 0;
1350 lineno++;
1351 azCol[0] = zLine;
1352 for(i=0, z=zLine; *z; z++){
1353 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
1354 *z = 0;
1355 i++;
1356 if( i<nCol ){
1357 azCol[i] = &z[nSep];
1358 z += nSep-1;
1359 }
1360 }
1361 }
1362 if( i+1!=nCol ){
1363 char *zErr;
drh5bb3eb92007-05-04 13:15:55 +00001364 int nErr = strlen(zFile) + 200;
1365 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00001366 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00001367 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00001368 "Error: %s line %d: expected %d columns of data but found %d",
1369 zFile, lineno, nCol, i+1);
1370 Tcl_AppendResult(interp, zErr, 0);
1371 free(zErr);
1372 }
drh19e2d372005-08-29 23:00:03 +00001373 zCommit = "ROLLBACK";
1374 break;
1375 }
1376 for(i=0; i<nCol; i++){
1377 /* check for null data, if so, bind as null */
1378 if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
1379 sqlite3_bind_null(pStmt, i+1);
1380 }else{
1381 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1382 }
1383 }
1384 sqlite3_step(pStmt);
1385 rc = sqlite3_reset(pStmt);
1386 free(zLine);
1387 if( rc!=SQLITE_OK ){
1388 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
1389 zCommit = "ROLLBACK";
1390 break;
1391 }
1392 }
1393 free(azCol);
1394 fclose(in);
1395 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00001396 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001397
1398 if( zCommit[0] == 'C' ){
1399 /* success, set result as number of lines processed */
1400 pResult = Tcl_GetObjResult(interp);
1401 Tcl_SetIntObj(pResult, lineno);
1402 rc = TCL_OK;
1403 }else{
1404 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00001405 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00001406 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
1407 rc = TCL_ERROR;
1408 }
1409 break;
1410 }
1411
drhdcd997e2003-01-31 17:21:49 +00001412 /*
drh41449052006-07-06 17:08:48 +00001413 ** $db enable_load_extension BOOLEAN
1414 **
1415 ** Turn the extension loading feature on or off. It if off by
1416 ** default.
1417 */
1418 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00001419#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00001420 int onoff;
1421 if( objc!=3 ){
1422 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
1423 return TCL_ERROR;
1424 }
1425 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
1426 return TCL_ERROR;
1427 }
1428 sqlite3_enable_load_extension(pDb->db, onoff);
1429 break;
drhf533acc2006-12-19 18:57:11 +00001430#else
1431 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
1432 0);
1433 return TCL_ERROR;
1434#endif
drh41449052006-07-06 17:08:48 +00001435 }
1436
1437 /*
drhdcd997e2003-01-31 17:21:49 +00001438 ** $db errorcode
1439 **
1440 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00001441 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00001442 */
1443 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00001444 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00001445 break;
1446 }
drh75897232000-05-29 14:26:00 +00001447
1448 /*
drh895d7472004-08-20 16:02:39 +00001449 ** $db eval $sql ?array? ?{ ...code... }?
drh1807ce32004-09-07 13:20:35 +00001450 ** $db onecolumn $sql
drh75897232000-05-29 14:26:00 +00001451 **
1452 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00001453 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00001454 ** If "array" and "code" are omitted, then no callback is every invoked.
1455 ** If "array" is an empty string, then the values are placed in variables
1456 ** that have the same name as the fields extracted by the query.
drh1807ce32004-09-07 13:20:35 +00001457 **
1458 ** The onecolumn method is the equivalent of:
1459 ** lindex [$db eval $sql] 0
drh75897232000-05-29 14:26:00 +00001460 */
drh1807ce32004-09-07 13:20:35 +00001461 case DB_ONECOLUMN:
drh97f2ebc2005-12-10 21:19:04 +00001462 case DB_EVAL:
1463 case DB_EXISTS: {
drh9d74b4c2004-08-24 15:23:34 +00001464 char const *zSql; /* Next SQL statement to execute */
1465 char const *zLeft; /* What is left after first stmt in zSql */
1466 sqlite3_stmt *pStmt; /* Compiled SQL statment */
drh92febd92004-08-20 18:34:20 +00001467 Tcl_Obj *pArray; /* Name of array into which results are written */
1468 Tcl_Obj *pScript; /* Script to run for each result set */
drh1d895032004-08-26 00:56:05 +00001469 Tcl_Obj **apParm; /* Parameters that need a Tcl_DecrRefCount() */
1470 int nParm; /* Number of entries used in apParm[] */
1471 Tcl_Obj *aParm[10]; /* Static space for apParm[] in the common case */
drh1807ce32004-09-07 13:20:35 +00001472 Tcl_Obj *pRet; /* Value to be returned */
drhfb7e7652005-01-24 00:28:42 +00001473 SqlPreparedStmt *pPreStmt; /* Pointer to a prepared statement */
1474 int rc2;
danielk1977ef2cb632004-05-29 02:37:19 +00001475
drh97f2ebc2005-12-10 21:19:04 +00001476 if( choice==DB_EVAL ){
drh1807ce32004-09-07 13:20:35 +00001477 if( objc<3 || objc>5 ){
1478 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
1479 return TCL_ERROR;
1480 }
1481 pRet = Tcl_NewObj();
1482 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001483 }else{
1484 if( objc!=3 ){
1485 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
1486 return TCL_ERROR;
1487 }
drh97f2ebc2005-12-10 21:19:04 +00001488 if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001489 pRet = Tcl_NewBooleanObj(0);
1490 Tcl_IncrRefCount(pRet);
1491 }else{
1492 pRet = 0;
drh97f2ebc2005-12-10 21:19:04 +00001493 }
danielk197730ccda12004-05-27 12:11:31 +00001494 }
drh92febd92004-08-20 18:34:20 +00001495 if( objc==3 ){
1496 pArray = pScript = 0;
1497 }else if( objc==4 ){
1498 pArray = 0;
1499 pScript = objv[3];
1500 }else{
1501 pArray = objv[3];
1502 if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
1503 pScript = objv[4];
1504 }
danielk197730ccda12004-05-27 12:11:31 +00001505
drh1d895032004-08-26 00:56:05 +00001506 Tcl_IncrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001507 zSql = Tcl_GetStringFromObj(objv[2], 0);
drh90b6bb12004-09-13 13:16:31 +00001508 while( rc==TCL_OK && zSql[0] ){
drhfb7e7652005-01-24 00:28:42 +00001509 int i; /* Loop counter */
1510 int nVar; /* Number of bind parameters in the pStmt */
1511 int nCol; /* Number of columns in the result set */
drh92febd92004-08-20 18:34:20 +00001512 Tcl_Obj **apColName = 0; /* Array of column names */
drhfb7e7652005-01-24 00:28:42 +00001513 int len; /* String length of zSql */
danielk197730ccda12004-05-27 12:11:31 +00001514
drhfb7e7652005-01-24 00:28:42 +00001515 /* Try to find a SQL statement that has already been compiled and
1516 ** which matches the next sequence of SQL.
1517 */
1518 pStmt = 0;
1519 pPreStmt = pDb->stmtList;
1520 len = strlen(zSql);
1521 if( pPreStmt && sqlite3_expired(pPreStmt->pStmt) ){
1522 flushStmtCache(pDb);
1523 pPreStmt = 0;
danielk197730ccda12004-05-27 12:11:31 +00001524 }
drhfb7e7652005-01-24 00:28:42 +00001525 for(; pPreStmt; pPreStmt=pPreStmt->pNext){
1526 int n = pPreStmt->nSql;
1527 if( len>=n
1528 && memcmp(pPreStmt->zSql, zSql, n)==0
1529 && (zSql[n]==0 || zSql[n-1]==';')
1530 ){
1531 pStmt = pPreStmt->pStmt;
1532 zLeft = &zSql[pPreStmt->nSql];
1533
1534 /* When a prepared statement is found, unlink it from the
1535 ** cache list. It will later be added back to the beginning
1536 ** of the cache list in order to implement LRU replacement.
1537 */
1538 if( pPreStmt->pPrev ){
1539 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1540 }else{
1541 pDb->stmtList = pPreStmt->pNext;
1542 }
1543 if( pPreStmt->pNext ){
1544 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1545 }else{
1546 pDb->stmtLast = pPreStmt->pPrev;
1547 }
1548 pDb->nStmt--;
1549 break;
1550 }
1551 }
1552
1553 /* If no prepared statement was found. Compile the SQL text
1554 */
drh92febd92004-08-20 18:34:20 +00001555 if( pStmt==0 ){
drhfb7e7652005-01-24 00:28:42 +00001556 if( SQLITE_OK!=sqlite3_prepare(pDb->db, zSql, -1, &pStmt, &zLeft) ){
drh92febd92004-08-20 18:34:20 +00001557 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1558 rc = TCL_ERROR;
1559 break;
danielk197730ccda12004-05-27 12:11:31 +00001560 }
drhfb7e7652005-01-24 00:28:42 +00001561 if( pStmt==0 ){
1562 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1563 /* A compile-time error in the statement
1564 */
1565 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1566 rc = TCL_ERROR;
1567 break;
1568 }else{
1569 /* The statement was a no-op. Continue to the next statement
1570 ** in the SQL string.
1571 */
1572 zSql = zLeft;
1573 continue;
1574 }
1575 }
1576 assert( pPreStmt==0 );
danielk197730ccda12004-05-27 12:11:31 +00001577 }
1578
drhfb7e7652005-01-24 00:28:42 +00001579 /* Bind values to parameters that begin with $ or :
1580 */
drh92febd92004-08-20 18:34:20 +00001581 nVar = sqlite3_bind_parameter_count(pStmt);
drh1d895032004-08-26 00:56:05 +00001582 nParm = 0;
1583 if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
1584 apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
1585 }else{
1586 apParm = aParm;
1587 }
drh92febd92004-08-20 18:34:20 +00001588 for(i=1; i<=nVar; i++){
1589 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
drh4f5e80f2007-06-19 17:15:46 +00001590 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
drh92febd92004-08-20 18:34:20 +00001591 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1592 if( pVar ){
1593 int n;
1594 u8 *data;
1595 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
1596 char c = zType[0];
drh4f5e80f2007-06-19 17:15:46 +00001597 if( c=='b' && strcmp(zType,"bytearray")==0
1598 && (pVar->bytes==0 || zVar[0]=='@') ){
drhdf0bdda2005-06-25 19:31:48 +00001599 /* Only load a BLOB type if the Tcl variable is a bytearray and
drh4f5e80f2007-06-19 17:15:46 +00001600 ** either it has no string representation or the host
1601 ** parameter name begins with "@". */
drh92febd92004-08-20 18:34:20 +00001602 data = Tcl_GetByteArrayFromObj(pVar, &n);
1603 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001604 Tcl_IncrRefCount(pVar);
1605 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001606 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
1607 (c=='i' && strcmp(zType,"int")==0) ){
1608 Tcl_GetIntFromObj(interp, pVar, &n);
1609 sqlite3_bind_int(pStmt, i, n);
1610 }else if( c=='d' && strcmp(zType,"double")==0 ){
1611 double r;
1612 Tcl_GetDoubleFromObj(interp, pVar, &r);
1613 sqlite3_bind_double(pStmt, i, r);
drhdf0bdda2005-06-25 19:31:48 +00001614 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
1615 Tcl_WideInt v;
1616 Tcl_GetWideIntFromObj(interp, pVar, &v);
1617 sqlite3_bind_int64(pStmt, i, v);
drh92febd92004-08-20 18:34:20 +00001618 }else{
danielk197700fd9572005-12-07 06:27:43 +00001619 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1620 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001621 Tcl_IncrRefCount(pVar);
1622 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001623 }
drhfb7e7652005-01-24 00:28:42 +00001624 }else{
1625 sqlite3_bind_null( pStmt, i );
drh92febd92004-08-20 18:34:20 +00001626 }
1627 }
1628 }
drh92febd92004-08-20 18:34:20 +00001629
1630 /* Compute column names */
1631 nCol = sqlite3_column_count(pStmt);
1632 if( pScript ){
1633 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1634 if( apColName==0 ) break;
1635 for(i=0; i<nCol; i++){
1636 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1637 Tcl_IncrRefCount(apColName[i]);
1638 }
1639 }
1640
1641 /* If results are being stored in an array variable, then create
1642 ** the array(*) entry for that array
1643 */
1644 if( pArray ){
1645 Tcl_Obj *pColList = Tcl_NewObj();
drh3ced14a2005-03-31 18:26:20 +00001646 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
drh92febd92004-08-20 18:34:20 +00001647 Tcl_IncrRefCount(pColList);
1648 for(i=0; i<nCol; i++){
1649 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1650 }
drh3ced14a2005-03-31 18:26:20 +00001651 Tcl_ObjSetVar2(interp, pArray, pStar, pColList,0);
1652 Tcl_DecrRefCount(pColList);
1653 Tcl_DecrRefCount(pStar);
drh92febd92004-08-20 18:34:20 +00001654 }
1655
1656 /* Execute the SQL
1657 */
drh90b6bb12004-09-13 13:16:31 +00001658 while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
drh92febd92004-08-20 18:34:20 +00001659 for(i=0; i<nCol; i++){
danielk197730ccda12004-05-27 12:11:31 +00001660 Tcl_Obj *pVal;
1661
1662 /* Set pVal to contain the i'th column of this row. */
drh92febd92004-08-20 18:34:20 +00001663 switch( sqlite3_column_type(pStmt, i) ){
1664 case SQLITE_BLOB: {
1665 int bytes = sqlite3_column_bytes(pStmt, i);
1666 pVal = Tcl_NewByteArrayObj(sqlite3_column_blob(pStmt, i), bytes);
1667 break;
1668 }
1669 case SQLITE_INTEGER: {
1670 sqlite_int64 v = sqlite3_column_int64(pStmt, i);
1671 if( v>=-2147483647 && v<=2147483647 ){
1672 pVal = Tcl_NewIntObj(v);
1673 }else{
1674 pVal = Tcl_NewWideIntObj(v);
1675 }
1676 break;
1677 }
1678 case SQLITE_FLOAT: {
1679 double r = sqlite3_column_double(pStmt, i);
1680 pVal = Tcl_NewDoubleObj(r);
1681 break;
1682 }
danielk197755c45f22005-04-03 23:54:43 +00001683 case SQLITE_NULL: {
1684 pVal = dbTextToObj(pDb->zNull);
1685 break;
1686 }
drh92febd92004-08-20 18:34:20 +00001687 default: {
danielk197700fd9572005-12-07 06:27:43 +00001688 pVal = dbTextToObj((char *)sqlite3_column_text(pStmt, i));
drh92febd92004-08-20 18:34:20 +00001689 break;
1690 }
danielk197730ccda12004-05-27 12:11:31 +00001691 }
1692
drh92febd92004-08-20 18:34:20 +00001693 if( pScript ){
1694 if( pArray==0 ){
1695 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001696 }else{
drh92febd92004-08-20 18:34:20 +00001697 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001698 }
drh1807ce32004-09-07 13:20:35 +00001699 }else if( choice==DB_ONECOLUMN ){
drh97f2ebc2005-12-10 21:19:04 +00001700 assert( pRet==0 );
drh1807ce32004-09-07 13:20:35 +00001701 if( pRet==0 ){
1702 pRet = pVal;
1703 Tcl_IncrRefCount(pRet);
1704 }
drh90b6bb12004-09-13 13:16:31 +00001705 rc = TCL_BREAK;
drh97f2ebc2005-12-10 21:19:04 +00001706 i = nCol;
1707 }else if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001708 Tcl_DecrRefCount(pRet);
1709 pRet = Tcl_NewBooleanObj(1);
1710 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001711 rc = TCL_BREAK;
1712 i = nCol;
danielk197730ccda12004-05-27 12:11:31 +00001713 }else{
danielk197730ccda12004-05-27 12:11:31 +00001714 Tcl_ListObjAppendElement(interp, pRet, pVal);
1715 }
1716 }
1717
drh92febd92004-08-20 18:34:20 +00001718 if( pScript ){
1719 rc = Tcl_EvalObjEx(interp, pScript, 0);
drh90b6bb12004-09-13 13:16:31 +00001720 if( rc==TCL_CONTINUE ){
1721 rc = TCL_OK;
1722 }
danielk197730ccda12004-05-27 12:11:31 +00001723 }
1724 }
drh90b6bb12004-09-13 13:16:31 +00001725 if( rc==TCL_BREAK ){
1726 rc = TCL_OK;
1727 }
drh92febd92004-08-20 18:34:20 +00001728
1729 /* Free the column name objects */
1730 if( pScript ){
1731 for(i=0; i<nCol; i++){
1732 Tcl_DecrRefCount(apColName[i]);
1733 }
1734 Tcl_Free((char*)apColName);
1735 }
1736
drh1d895032004-08-26 00:56:05 +00001737 /* Free the bound string and blob parameters */
1738 for(i=0; i<nParm; i++){
1739 Tcl_DecrRefCount(apParm[i]);
1740 }
1741 if( apParm!=aParm ){
1742 Tcl_Free((char*)apParm);
1743 }
1744
drhfb7e7652005-01-24 00:28:42 +00001745 /* Reset the statement. If the result code is SQLITE_SCHEMA, then
1746 ** flush the statement cache and try the statement again.
drh92febd92004-08-20 18:34:20 +00001747 */
drhfb7e7652005-01-24 00:28:42 +00001748 rc2 = sqlite3_reset(pStmt);
1749 if( SQLITE_SCHEMA==rc2 ){
1750 /* After a schema change, flush the cache and try to run the
1751 ** statement again
1752 */
1753 flushStmtCache( pDb );
1754 sqlite3_finalize(pStmt);
1755 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001756 continue;
drhfb7e7652005-01-24 00:28:42 +00001757 }else if( SQLITE_OK!=rc2 ){
1758 /* If a run-time error occurs, report the error and stop reading
1759 ** the SQL
1760 */
danielk1977ef2cb632004-05-29 02:37:19 +00001761 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
drhfb7e7652005-01-24 00:28:42 +00001762 sqlite3_finalize(pStmt);
danielk197730ccda12004-05-27 12:11:31 +00001763 rc = TCL_ERROR;
drhfb7e7652005-01-24 00:28:42 +00001764 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001765 break;
drhfb7e7652005-01-24 00:28:42 +00001766 }else if( pDb->maxStmt<=0 ){
1767 /* If the cache is turned off, deallocated the statement */
1768 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1769 sqlite3_finalize(pStmt);
1770 }else{
1771 /* Everything worked and the cache is operational.
1772 ** Create a new SqlPreparedStmt structure if we need one.
1773 ** (If we already have one we can just reuse it.)
1774 */
1775 if( pPreStmt==0 ){
1776 len = zLeft - zSql;
1777 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) + len );
1778 if( pPreStmt==0 ) return TCL_ERROR;
1779 pPreStmt->pStmt = pStmt;
1780 pPreStmt->nSql = len;
1781 memcpy(pPreStmt->zSql, zSql, len);
1782 pPreStmt->zSql[len] = 0;
1783 }
1784
1785 /* Add the prepared statement to the beginning of the cache list
1786 */
1787 pPreStmt->pNext = pDb->stmtList;
1788 pPreStmt->pPrev = 0;
1789 if( pDb->stmtList ){
1790 pDb->stmtList->pPrev = pPreStmt;
1791 }
1792 pDb->stmtList = pPreStmt;
1793 if( pDb->stmtLast==0 ){
1794 assert( pDb->nStmt==0 );
1795 pDb->stmtLast = pPreStmt;
1796 }else{
1797 assert( pDb->nStmt>0 );
1798 }
1799 pDb->nStmt++;
1800
1801 /* If we have too many statement in cache, remove the surplus from the
1802 ** end of the cache list.
1803 */
1804 while( pDb->nStmt>pDb->maxStmt ){
1805 sqlite3_finalize(pDb->stmtLast->pStmt);
1806 pDb->stmtLast = pDb->stmtLast->pPrev;
1807 Tcl_Free((char*)pDb->stmtLast->pNext);
1808 pDb->stmtLast->pNext = 0;
1809 pDb->nStmt--;
1810 }
danielk197730ccda12004-05-27 12:11:31 +00001811 }
1812
drhfb7e7652005-01-24 00:28:42 +00001813 /* Proceed to the next statement */
danielk197730ccda12004-05-27 12:11:31 +00001814 zSql = zLeft;
1815 }
drh1d895032004-08-26 00:56:05 +00001816 Tcl_DecrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001817
drh1807ce32004-09-07 13:20:35 +00001818 if( pRet ){
1819 if( rc==TCL_OK ){
1820 Tcl_SetObjResult(interp, pRet);
1821 }
1822 Tcl_DecrRefCount(pRet);
drh050be322006-07-12 00:18:40 +00001823 }else if( rc==TCL_OK ){
1824 Tcl_ResetResult(interp);
danielk197730ccda12004-05-27 12:11:31 +00001825 }
danielk197730ccda12004-05-27 12:11:31 +00001826 break;
1827 }
drhbec3f402000-08-04 13:49:02 +00001828
1829 /*
drhcabb0812002-09-14 13:47:32 +00001830 ** $db function NAME SCRIPT
1831 **
1832 ** Create a new SQL function called NAME. Whenever that function is
1833 ** called, invoke SCRIPT to evaluate the function.
1834 */
1835 case DB_FUNCTION: {
1836 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00001837 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00001838 char *zName;
drhcabb0812002-09-14 13:47:32 +00001839 if( objc!=4 ){
1840 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1841 return TCL_ERROR;
1842 }
1843 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00001844 pScript = objv[3];
1845 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00001846 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00001847 if( pFunc->pScript ){
1848 Tcl_DecrRefCount(pFunc->pScript);
1849 }
1850 pFunc->pScript = pScript;
1851 Tcl_IncrRefCount(pScript);
1852 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
danielk1977c8c11582004-06-29 13:41:21 +00001853 rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00001854 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00001855 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00001856 rc = TCL_ERROR;
1857 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00001858 }else{
1859 /* Must flush any cached statements */
1860 flushStmtCache( pDb );
1861 }
drhcabb0812002-09-14 13:47:32 +00001862 break;
1863 }
1864
1865 /*
danielk19778cbadb02007-05-03 16:31:26 +00001866 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00001867 */
1868 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00001869#ifdef SQLITE_OMIT_INCRBLOB
1870 Tcl_AppendResult(interp, "incrblob not available in this build", 0);
1871 return TCL_ERROR;
1872#else
danielk19778cbadb02007-05-03 16:31:26 +00001873 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00001874 const char *zDb = "main";
1875 const char *zTable;
1876 const char *zColumn;
1877 sqlite_int64 iRow;
1878
danielk19778cbadb02007-05-03 16:31:26 +00001879 /* Check for the -readonly option */
1880 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
1881 isReadonly = 1;
1882 }
1883
1884 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
1885 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00001886 return TCL_ERROR;
1887 }
1888
danielk19778cbadb02007-05-03 16:31:26 +00001889 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00001890 zDb = Tcl_GetString(objv[2]);
1891 }
1892 zTable = Tcl_GetString(objv[objc-3]);
1893 zColumn = Tcl_GetString(objv[objc-2]);
1894 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
1895
1896 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00001897 rc = createIncrblobChannel(
1898 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
1899 );
danielk1977b4e9af92007-05-01 17:49:49 +00001900 }
danielk197732a0d8b2007-05-04 19:03:02 +00001901#endif
danielk1977b4e9af92007-05-01 17:49:49 +00001902 break;
1903 }
1904
1905 /*
drhf11bded2006-07-17 00:02:44 +00001906 ** $db interrupt
1907 **
1908 ** Interrupt the execution of the inner-most SQL interpreter. This
1909 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
1910 */
1911 case DB_INTERRUPT: {
1912 sqlite3_interrupt(pDb->db);
1913 break;
1914 }
1915
1916 /*
drh19e2d372005-08-29 23:00:03 +00001917 ** $db nullvalue ?STRING?
1918 **
1919 ** Change text used when a NULL comes back from the database. If ?STRING?
1920 ** is not present, then the current string used for NULL is returned.
1921 ** If STRING is present, then STRING is returned.
1922 **
1923 */
1924 case DB_NULLVALUE: {
1925 if( objc!=2 && objc!=3 ){
1926 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
1927 return TCL_ERROR;
1928 }
1929 if( objc==3 ){
1930 int len;
1931 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
1932 if( pDb->zNull ){
1933 Tcl_Free(pDb->zNull);
1934 }
1935 if( zNull && len>0 ){
1936 pDb->zNull = Tcl_Alloc( len + 1 );
1937 strncpy(pDb->zNull, zNull, len);
1938 pDb->zNull[len] = '\0';
1939 }else{
1940 pDb->zNull = 0;
1941 }
1942 }
1943 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
1944 break;
1945 }
1946
1947 /*
drhaf9ff332002-01-16 21:00:27 +00001948 ** $db last_insert_rowid
1949 **
1950 ** Return an integer which is the ROWID for the most recent insert.
1951 */
1952 case DB_LAST_INSERT_ROWID: {
1953 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00001954 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00001955 if( objc!=2 ){
1956 Tcl_WrongNumArgs(interp, 2, objv, "");
1957 return TCL_ERROR;
1958 }
danielk19776f8a5032004-05-10 10:34:51 +00001959 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00001960 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00001961 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00001962 break;
1963 }
1964
1965 /*
drh1807ce32004-09-07 13:20:35 +00001966 ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
drh5d9d7572003-08-19 14:31:01 +00001967 */
drh1807ce32004-09-07 13:20:35 +00001968
1969 /* $db progress ?N CALLBACK?
1970 **
1971 ** Invoke the given callback every N virtual machine opcodes while executing
1972 ** queries.
1973 */
1974 case DB_PROGRESS: {
1975 if( objc==2 ){
1976 if( pDb->zProgress ){
1977 Tcl_AppendResult(interp, pDb->zProgress, 0);
1978 }
1979 }else if( objc==4 ){
1980 char *zProgress;
1981 int len;
1982 int N;
1983 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
1984 return TCL_ERROR;
1985 };
1986 if( pDb->zProgress ){
1987 Tcl_Free(pDb->zProgress);
1988 }
1989 zProgress = Tcl_GetStringFromObj(objv[3], &len);
1990 if( zProgress && len>0 ){
1991 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001992 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00001993 }else{
1994 pDb->zProgress = 0;
1995 }
1996#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1997 if( pDb->zProgress ){
1998 pDb->interp = interp;
1999 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2000 }else{
2001 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2002 }
2003#endif
2004 }else{
2005 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002006 return TCL_ERROR;
2007 }
drh5d9d7572003-08-19 14:31:01 +00002008 break;
2009 }
2010
drh19e2d372005-08-29 23:00:03 +00002011 /* $db profile ?CALLBACK?
2012 **
2013 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2014 ** that has run. The text of the SQL and the amount of elapse time are
2015 ** appended to CALLBACK before the script is run.
2016 */
2017 case DB_PROFILE: {
2018 if( objc>3 ){
2019 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2020 return TCL_ERROR;
2021 }else if( objc==2 ){
2022 if( pDb->zProfile ){
2023 Tcl_AppendResult(interp, pDb->zProfile, 0);
2024 }
2025 }else{
2026 char *zProfile;
2027 int len;
2028 if( pDb->zProfile ){
2029 Tcl_Free(pDb->zProfile);
2030 }
2031 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2032 if( zProfile && len>0 ){
2033 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002034 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002035 }else{
2036 pDb->zProfile = 0;
2037 }
2038#ifndef SQLITE_OMIT_TRACE
2039 if( pDb->zProfile ){
2040 pDb->interp = interp;
2041 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2042 }else{
2043 sqlite3_profile(pDb->db, 0, 0);
2044 }
2045#endif
2046 }
2047 break;
2048 }
2049
drh5d9d7572003-08-19 14:31:01 +00002050 /*
drh22fbcb82004-02-01 01:22:50 +00002051 ** $db rekey KEY
2052 **
2053 ** Change the encryption key on the currently open database.
2054 */
2055 case DB_REKEY: {
2056 int nKey;
2057 void *pKey;
2058 if( objc!=3 ){
2059 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2060 return TCL_ERROR;
2061 }
2062 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00002063#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00002064 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002065 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00002066 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002067 rc = TCL_ERROR;
2068 }
2069#endif
2070 break;
2071 }
2072
2073 /*
drhbec3f402000-08-04 13:49:02 +00002074 ** $db timeout MILLESECONDS
2075 **
2076 ** Delay for the number of milliseconds specified when a file is locked.
2077 */
drh6d313162000-09-21 13:01:35 +00002078 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002079 int ms;
drh6d313162000-09-21 13:01:35 +00002080 if( objc!=3 ){
2081 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002082 return TCL_ERROR;
2083 }
drh6d313162000-09-21 13:01:35 +00002084 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002085 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002086 break;
drh75897232000-05-29 14:26:00 +00002087 }
danielk197755c45f22005-04-03 23:54:43 +00002088
2089 /*
drh0f14e2e2004-06-29 12:39:08 +00002090 ** $db total_changes
2091 **
2092 ** Return the number of rows that were modified, inserted, or deleted
2093 ** since the database handle was created.
2094 */
2095 case DB_TOTAL_CHANGES: {
2096 Tcl_Obj *pResult;
2097 if( objc!=2 ){
2098 Tcl_WrongNumArgs(interp, 2, objv, "");
2099 return TCL_ERROR;
2100 }
2101 pResult = Tcl_GetObjResult(interp);
2102 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2103 break;
2104 }
2105
drhb5a20d32003-04-23 12:25:23 +00002106 /* $db trace ?CALLBACK?
2107 **
2108 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2109 ** that is executed. The text of the SQL is appended to CALLBACK before
2110 ** it is executed.
2111 */
2112 case DB_TRACE: {
2113 if( objc>3 ){
2114 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002115 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002116 }else if( objc==2 ){
2117 if( pDb->zTrace ){
2118 Tcl_AppendResult(interp, pDb->zTrace, 0);
2119 }
2120 }else{
2121 char *zTrace;
2122 int len;
2123 if( pDb->zTrace ){
2124 Tcl_Free(pDb->zTrace);
2125 }
2126 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2127 if( zTrace && len>0 ){
2128 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002129 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002130 }else{
2131 pDb->zTrace = 0;
2132 }
drh19e2d372005-08-29 23:00:03 +00002133#ifndef SQLITE_OMIT_TRACE
drhb5a20d32003-04-23 12:25:23 +00002134 if( pDb->zTrace ){
2135 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002136 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002137 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002138 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002139 }
drh19e2d372005-08-29 23:00:03 +00002140#endif
drhb5a20d32003-04-23 12:25:23 +00002141 }
2142 break;
2143 }
2144
drh3d214232005-08-02 12:21:08 +00002145 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2146 **
2147 ** Start a new transaction (if we are not already in the midst of a
2148 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2149 ** completes, either commit the transaction or roll it back if SCRIPT
2150 ** throws an exception. Or if no new transation was started, do nothing.
2151 ** pass the exception on up the stack.
2152 **
2153 ** This command was inspired by Dave Thomas's talk on Ruby at the
2154 ** 2005 O'Reilly Open Source Convention (OSCON).
2155 */
2156 case DB_TRANSACTION: {
2157 int inTrans;
2158 Tcl_Obj *pScript;
2159 const char *zBegin = "BEGIN";
2160 if( objc!=3 && objc!=4 ){
2161 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2162 return TCL_ERROR;
2163 }
2164 if( objc==3 ){
2165 pScript = objv[2];
2166 } else {
2167 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002168 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002169 };
2170 enum TTYPE_enum {
2171 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2172 };
2173 int ttype;
drhb5555e72005-08-02 17:15:14 +00002174 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002175 0, &ttype) ){
2176 return TCL_ERROR;
2177 }
2178 switch( (enum TTYPE_enum)ttype ){
2179 case TTYPE_DEFERRED: /* no-op */; break;
2180 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2181 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2182 }
2183 pScript = objv[3];
2184 }
2185 inTrans = !sqlite3_get_autocommit(pDb->db);
2186 if( !inTrans ){
drh37527852006-03-16 16:19:56 +00002187 (void)sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
drh3d214232005-08-02 12:21:08 +00002188 }
2189 rc = Tcl_EvalObjEx(interp, pScript, 0);
2190 if( !inTrans ){
2191 const char *zEnd;
2192 if( rc==TCL_ERROR ){
2193 zEnd = "ROLLBACK";
2194 } else {
2195 zEnd = "COMMIT";
2196 }
drh109b4352007-06-12 18:50:13 +00002197 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
2198 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
2199 }
drh3d214232005-08-02 12:21:08 +00002200 }
2201 break;
2202 }
2203
danielk197794eb6a12005-12-15 15:22:08 +00002204 /*
2205 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002206 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002207 */
danielk197771fd80b2005-12-16 06:54:01 +00002208 case DB_UPDATE_HOOK:
2209 case DB_ROLLBACK_HOOK: {
2210
2211 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2212 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2213 */
2214 Tcl_Obj **ppHook;
2215 if( choice==DB_UPDATE_HOOK ){
2216 ppHook = &pDb->pUpdateHook;
2217 }else{
2218 ppHook = &pDb->pRollbackHook;
2219 }
2220
danielk197794eb6a12005-12-15 15:22:08 +00002221 if( objc!=2 && objc!=3 ){
2222 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2223 return TCL_ERROR;
2224 }
danielk197771fd80b2005-12-16 06:54:01 +00002225 if( *ppHook ){
2226 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002227 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002228 Tcl_DecrRefCount(*ppHook);
2229 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00002230 }
2231 }
2232 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002233 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00002234 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00002235 *ppHook = objv[2];
2236 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002237 }
2238 }
danielk197771fd80b2005-12-16 06:54:01 +00002239
2240 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2241 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
2242
danielk197794eb6a12005-12-15 15:22:08 +00002243 break;
2244 }
2245
danielk19774397de52005-01-12 12:44:03 +00002246 /* $db version
2247 **
2248 ** Return the version string for this database.
2249 */
2250 case DB_VERSION: {
2251 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2252 break;
2253 }
2254
tpoindex1067fe12004-12-17 15:41:11 +00002255
drh6d313162000-09-21 13:01:35 +00002256 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002257 return rc;
drh75897232000-05-29 14:26:00 +00002258}
2259
2260/*
drh9bb575f2004-09-06 17:24:11 +00002261** sqlite3 DBNAME FILENAME ?MODE? ?-key KEY?
drh75897232000-05-29 14:26:00 +00002262**
2263** This is the main Tcl command. When the "sqlite" Tcl command is
2264** invoked, this routine runs to process that command.
2265**
2266** The first argument, DBNAME, is an arbitrary name for a new
2267** database connection. This command creates a new command named
2268** DBNAME that is used to control that connection. The database
2269** connection is deleted when the DBNAME command is deleted.
2270**
2271** The second argument is the name of the directory that contains
2272** the sqlite database that is to be accessed.
drhfbc3eab2001-04-06 16:13:42 +00002273**
2274** For testing purposes, we also support the following:
2275**
drh9bb575f2004-09-06 17:24:11 +00002276** sqlite3 -encoding
drhfbc3eab2001-04-06 16:13:42 +00002277**
2278** Return the encoding used by LIKE and GLOB operators. Choices
2279** are UTF-8 and iso8859.
2280**
drh9bb575f2004-09-06 17:24:11 +00002281** sqlite3 -version
drh647cb0e2002-11-04 19:32:25 +00002282**
2283** Return the version number of the SQLite library.
2284**
drh9bb575f2004-09-06 17:24:11 +00002285** sqlite3 -tcl-uses-utf
drhfbc3eab2001-04-06 16:13:42 +00002286**
2287** Return "1" if compiled with a Tcl uses UTF-8. Return "0" if
2288** not. Used by tests to make sure the library was compiled
2289** correctly.
drh75897232000-05-29 14:26:00 +00002290*/
drh22fbcb82004-02-01 01:22:50 +00002291static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002292 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002293 void *pKey = 0;
2294 int nKey = 0;
2295 const char *zArg;
drh75897232000-05-29 14:26:00 +00002296 char *zErrMsg;
drh22fbcb82004-02-01 01:22:50 +00002297 const char *zFile;
drh882e8e42006-08-24 02:42:27 +00002298 Tcl_DString translatedFilename;
drh22fbcb82004-02-01 01:22:50 +00002299 if( objc==2 ){
2300 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002301 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00002302 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00002303 return TCL_OK;
2304 }
drh9eb9e262004-02-11 02:18:05 +00002305 if( strcmp(zArg,"-has-codec")==0 ){
2306#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002307 Tcl_AppendResult(interp,"1",0);
2308#else
2309 Tcl_AppendResult(interp,"0",0);
2310#endif
2311 return TCL_OK;
2312 }
2313 if( strcmp(zArg,"-tcl-uses-utf")==0 ){
drhfbc3eab2001-04-06 16:13:42 +00002314#ifdef TCL_UTF_MAX
2315 Tcl_AppendResult(interp,"1",0);
2316#else
2317 Tcl_AppendResult(interp,"0",0);
2318#endif
2319 return TCL_OK;
2320 }
2321 }
drh22fbcb82004-02-01 01:22:50 +00002322 if( objc==5 || objc==6 ){
2323 zArg = Tcl_GetStringFromObj(objv[objc-2], 0);
2324 if( strcmp(zArg,"-key")==0 ){
2325 pKey = Tcl_GetByteArrayFromObj(objv[objc-1], &nKey);
2326 objc -= 2;
2327 }
2328 }
2329 if( objc!=3 && objc!=4 ){
2330 Tcl_WrongNumArgs(interp, 1, objv,
drh9eb9e262004-02-11 02:18:05 +00002331#ifdef SQLITE_HAS_CODEC
2332 "HANDLE FILENAME ?-key CODEC-KEY?"
drh22fbcb82004-02-01 01:22:50 +00002333#else
2334 "HANDLE FILENAME ?MODE?"
2335#endif
2336 );
drh75897232000-05-29 14:26:00 +00002337 return TCL_ERROR;
2338 }
drh75897232000-05-29 14:26:00 +00002339 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00002340 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00002341 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00002342 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
2343 return TCL_ERROR;
2344 }
2345 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00002346 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00002347 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
danielk19774f057f92004-06-08 00:02:33 +00002348 sqlite3_open(zFile, &p->db);
drh882e8e42006-08-24 02:42:27 +00002349 Tcl_DStringFree(&translatedFilename);
danielk197780290862004-05-22 09:21:21 +00002350 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
drh9404d502006-12-19 18:46:08 +00002351 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
danielk197780290862004-05-22 09:21:21 +00002352 sqlite3_close(p->db);
2353 p->db = 0;
2354 }
drh2011d5f2004-07-22 02:40:37 +00002355#ifdef SQLITE_HAS_CODEC
2356 sqlite3_key(p->db, pKey, nKey);
drheb8ed702004-02-11 10:37:23 +00002357#endif
drhbec3f402000-08-04 13:49:02 +00002358 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00002359 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00002360 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00002361 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00002362 return TCL_ERROR;
2363 }
drhfb7e7652005-01-24 00:28:42 +00002364 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00002365 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00002366 zArg = Tcl_GetStringFromObj(objv[1], 0);
2367 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
drhc22bd472002-05-10 13:14:07 +00002368
2369 /* If compiled with SQLITE_TEST turned on, then register the "md5sum"
drh06b27182002-06-26 20:06:05 +00002370 ** SQL function.
drhc22bd472002-05-10 13:14:07 +00002371 */
drh28b4e482002-03-11 02:06:13 +00002372#ifdef SQLITE_TEST
2373 {
drh9bb575f2004-09-06 17:24:11 +00002374 extern void Md5_Register(sqlite3*);
drh3b93bc82005-01-13 23:54:32 +00002375#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00002376 int mallocfail = sqlite3_iMallocFail;
2377 sqlite3_iMallocFail = 0;
danielk19775b59af82004-06-30 12:42:59 +00002378#endif
drhc22bd472002-05-10 13:14:07 +00002379 Md5_Register(p->db);
drh3b93bc82005-01-13 23:54:32 +00002380#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00002381 sqlite3_iMallocFail = mallocfail;
danielk19775b59af82004-06-30 12:42:59 +00002382#endif
danielk19777ddad962005-12-12 06:53:03 +00002383 }
drh28b4e482002-03-11 02:06:13 +00002384#endif
drh75897232000-05-29 14:26:00 +00002385 return TCL_OK;
2386}
2387
2388/*
drh90ca9752001-09-28 17:47:14 +00002389** Provide a dummy Tcl_InitStubs if we are using this as a static
2390** library.
2391*/
2392#ifndef USE_TCL_STUBS
2393# undef Tcl_InitStubs
2394# define Tcl_InitStubs(a,b,c)
2395#endif
2396
2397/*
drh29bc4612005-10-05 10:40:15 +00002398** Make sure we have a PACKAGE_VERSION macro defined. This will be
2399** defined automatically by the TEA makefile. But other makefiles
2400** do not define it.
2401*/
2402#ifndef PACKAGE_VERSION
2403# define PACKAGE_VERSION SQLITE_VERSION
2404#endif
2405
2406/*
drh75897232000-05-29 14:26:00 +00002407** Initialize this module.
2408**
2409** This Tcl module contains only a single new Tcl command named "sqlite".
2410** (Hence there is no namespace. There is no point in using a namespace
2411** if the extension only supplies one new name!) The "sqlite" command is
2412** used to open a new SQLite database. See the DbMain() routine above
2413** for additional information.
2414*/
drhad6e1372006-07-10 21:15:51 +00002415EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00002416 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00002417 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002418 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh49766d62005-01-08 18:42:28 +00002419 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002420 Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
drh90ca9752001-09-28 17:47:14 +00002421 return TCL_OK;
2422}
drhad6e1372006-07-10 21:15:51 +00002423EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2424EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2425EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002426
2427#ifndef SQLITE_3_SUFFIX_ONLY
drhad6e1372006-07-10 21:15:51 +00002428EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2429EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2430EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2431EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002432#endif
drh75897232000-05-29 14:26:00 +00002433
drh3e27c022004-07-23 00:01:38 +00002434#ifdef TCLSH
2435/*****************************************************************************
2436** The code that follows is used to build standalone TCL interpreters
drh75897232000-05-29 14:26:00 +00002437*/
drh348784e2000-05-29 20:41:49 +00002438
2439/*
drh3e27c022004-07-23 00:01:38 +00002440** If the macro TCLSH is one, then put in code this for the
2441** "main" routine that will initialize Tcl and take input from
2442** standard input.
drh348784e2000-05-29 20:41:49 +00002443*/
drh3e27c022004-07-23 00:01:38 +00002444#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00002445static char zMainloop[] =
2446 "set line {}\n"
2447 "while {![eof stdin]} {\n"
2448 "if {$line!=\"\"} {\n"
2449 "puts -nonewline \"> \"\n"
2450 "} else {\n"
2451 "puts -nonewline \"% \"\n"
2452 "}\n"
2453 "flush stdout\n"
2454 "append line [gets stdin]\n"
2455 "if {[info complete $line]} {\n"
2456 "if {[catch {uplevel #0 $line} result]} {\n"
2457 "puts stderr \"Error: $result\"\n"
2458 "} elseif {$result!=\"\"} {\n"
2459 "puts $result\n"
2460 "}\n"
2461 "set line {}\n"
2462 "} else {\n"
2463 "append line \\n\n"
2464 "}\n"
2465 "}\n"
2466;
drh3e27c022004-07-23 00:01:38 +00002467#endif
2468
2469/*
2470** If the macro TCLSH is two, then get the main loop code out of
2471** the separate file "spaceanal_tcl.h".
2472*/
2473#if TCLSH==2
2474static char zMainloop[] =
2475#include "spaceanal_tcl.h"
2476;
2477#endif
drh348784e2000-05-29 20:41:49 +00002478
2479#define TCLSH_MAIN main /* Needed to fake out mktclapp */
2480int TCLSH_MAIN(int argc, char **argv){
2481 Tcl_Interp *interp;
drh297ecf12001-04-05 15:57:13 +00002482 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00002483 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00002484 Sqlite3_Init(interp);
drhd9b02572001-04-15 00:37:09 +00002485#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00002486 {
2487 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00002488 extern int Sqlitetest2_Init(Tcl_Interp*);
2489 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00002490 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00002491 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00002492 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00002493 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00002494 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00002495 extern int Sqlitetest9_Init(Tcl_Interp*);
drhefc251d2001-07-01 22:12:01 +00002496 extern int Md5_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002497 extern int Sqlitetestsse_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00002498 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh4be8b512006-06-13 23:51:34 +00002499 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk1977954ce992006-06-15 15:59:19 +00002500 extern int Sqlitetestschema_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00002501 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00002502 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
drhc797d4d2007-05-08 01:08:49 +00002503 extern int Sqliteconfig_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002504
danielk19776490beb2004-05-11 06:17:21 +00002505 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00002506 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00002507 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00002508 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00002509 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00002510 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00002511 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00002512 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00002513 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00002514 Sqlitetestasync_Init(interp);
drh4be8b512006-06-13 23:51:34 +00002515 Sqlitetesttclvar_Init(interp);
danielk1977954ce992006-06-15 15:59:19 +00002516 Sqlitetestschema_Init(interp);
drh1409be62006-08-23 20:07:20 +00002517 Sqlitetest_autoext_Init(interp);
drh15926592007-04-06 15:02:13 +00002518 Sqlitetest_hexio_Init(interp);
drhc797d4d2007-05-08 01:08:49 +00002519 Sqliteconfig_Init(interp);
drhefc251d2001-07-01 22:12:01 +00002520 Md5_Init(interp);
drh89dec812005-04-28 19:03:37 +00002521#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00002522 Sqlitetestsse_Init(interp);
2523#endif
drhd1bf3512001-04-07 15:24:33 +00002524 }
2525#endif
drh3e27c022004-07-23 00:01:38 +00002526 if( argc>=2 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002527 int i;
shessad42c3a2006-08-22 23:53:46 +00002528 char zArgc[32];
2529 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
2530 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00002531 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
2532 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00002533 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00002534 Tcl_SetVar(interp, "argv", argv[i],
2535 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
2536 }
drh3e27c022004-07-23 00:01:38 +00002537 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00002538 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drhc61053b2000-06-04 12:58:36 +00002539 if( zInfo==0 ) zInfo = interp->result;
2540 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00002541 return 1;
2542 }
drh3e27c022004-07-23 00:01:38 +00002543 }
2544 if( argc<=1 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002545 Tcl_GlobalEval(interp, zMainloop);
2546 }
2547 return 0;
2548}
2549#endif /* TCLSH */