blob: bca6ed398363dbbf37a1e7d7c0705cbaf8314584 [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**
drhc797d4d2007-05-08 01:08:49 +000015** $Id: tclsqlite.c,v 1.187 2007/05/08 01:08:49 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 */
297 0, /* threadActionProc */
298};
299
300/*
301** Create a new incrblob channel.
302*/
303static int createIncrblobChannel(
304 Tcl_Interp *interp,
305 SqliteDb *pDb,
306 const char *zDb,
307 const char *zTable,
308 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000309 sqlite_int64 iRow,
310 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000311){
312 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000313 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000314 sqlite3_blob *pBlob;
315 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000316 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000317
318 /* This variable is used to name the channels: "incrblob_[incr count]" */
319 static int count = 0;
320 char zChannel[64];
321
danielk19778cbadb02007-05-03 16:31:26 +0000322 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000323 if( rc!=SQLITE_OK ){
324 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
325 return TCL_ERROR;
326 }
327
328 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
329 p->iSeek = 0;
330 p->pBlob = pBlob;
331
drh5bb3eb92007-05-04 13:15:55 +0000332 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000333 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
334 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000335
danielk1977d04417962007-05-02 13:16:30 +0000336 /* Link the new channel into the SqliteDb.pIncrblob list. */
337 p->pNext = pDb->pIncrblob;
338 p->pPrev = 0;
339 if( p->pNext ){
340 p->pNext->pPrev = p;
341 }
342 pDb->pIncrblob = p;
343 p->pDb = pDb;
344
345 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000346 return TCL_OK;
347}
danielk197732a0d8b2007-05-04 19:03:02 +0000348#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
349 #define closeIncrblobChannels(pDb)
350#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000351
drh6d313162000-09-21 13:01:35 +0000352/*
drhd1e47332005-06-26 17:55:33 +0000353** Look at the script prefix in pCmd. We will be executing this script
354** after first appending one or more arguments. This routine analyzes
355** the script to see if it is safe to use Tcl_EvalObjv() on the script
356** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
357** faster.
358**
359** Scripts that are safe to use with Tcl_EvalObjv() consists of a
360** command name followed by zero or more arguments with no [...] or $
361** or {...} or ; to be seen anywhere. Most callback scripts consist
362** of just a single procedure name and they meet this requirement.
363*/
364static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
365 /* We could try to do something with Tcl_Parse(). But we will instead
366 ** just do a search for forbidden characters. If any of the forbidden
367 ** characters appear in pCmd, we will report the string as unsafe.
368 */
369 const char *z;
370 int n;
371 z = Tcl_GetStringFromObj(pCmd, &n);
372 while( n-- > 0 ){
373 int c = *(z++);
374 if( c=='$' || c=='[' || c==';' ) return 0;
375 }
376 return 1;
377}
378
379/*
380** Find an SqlFunc structure with the given name. Or create a new
381** one if an existing one cannot be found. Return a pointer to the
382** structure.
383*/
384static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
385 SqlFunc *p, *pNew;
386 int i;
387 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen(zName) + 1 );
388 pNew->zName = (char*)&pNew[1];
389 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
390 pNew->zName[i] = 0;
391 for(p=pDb->pFunc; p; p=p->pNext){
392 if( strcmp(p->zName, pNew->zName)==0 ){
393 Tcl_Free((char*)pNew);
394 return p;
395 }
396 }
397 pNew->interp = pDb->interp;
398 pNew->pScript = 0;
399 pNew->pNext = pDb->pFunc;
400 pDb->pFunc = pNew;
401 return pNew;
402}
403
404/*
drhfb7e7652005-01-24 00:28:42 +0000405** Finalize and free a list of prepared statements
406*/
407static void flushStmtCache( SqliteDb *pDb ){
408 SqlPreparedStmt *pPreStmt;
409
410 while( pDb->stmtList ){
411 sqlite3_finalize( pDb->stmtList->pStmt );
412 pPreStmt = pDb->stmtList;
413 pDb->stmtList = pDb->stmtList->pNext;
414 Tcl_Free( (char*)pPreStmt );
415 }
416 pDb->nStmt = 0;
417 pDb->stmtLast = 0;
418}
419
420/*
drh895d7472004-08-20 16:02:39 +0000421** TCL calls this procedure when an sqlite3 database command is
422** deleted.
drh75897232000-05-29 14:26:00 +0000423*/
424static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000425 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000426 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000427 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000428 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000429 while( pDb->pFunc ){
430 SqlFunc *pFunc = pDb->pFunc;
431 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000432 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000433 Tcl_Free((char*)pFunc);
434 }
danielk19770202b292004-06-09 09:55:16 +0000435 while( pDb->pCollate ){
436 SqlCollate *pCollate = pDb->pCollate;
437 pDb->pCollate = pCollate->pNext;
438 Tcl_Free((char*)pCollate);
439 }
drhbec3f402000-08-04 13:49:02 +0000440 if( pDb->zBusy ){
441 Tcl_Free(pDb->zBusy);
442 }
drhb5a20d32003-04-23 12:25:23 +0000443 if( pDb->zTrace ){
444 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000445 }
drh19e2d372005-08-29 23:00:03 +0000446 if( pDb->zProfile ){
447 Tcl_Free(pDb->zProfile);
448 }
drhe22a3342003-04-22 20:30:37 +0000449 if( pDb->zAuth ){
450 Tcl_Free(pDb->zAuth);
451 }
danielk197755c45f22005-04-03 23:54:43 +0000452 if( pDb->zNull ){
453 Tcl_Free(pDb->zNull);
454 }
danielk197794eb6a12005-12-15 15:22:08 +0000455 if( pDb->pUpdateHook ){
456 Tcl_DecrRefCount(pDb->pUpdateHook);
457 }
danielk197771fd80b2005-12-16 06:54:01 +0000458 if( pDb->pRollbackHook ){
459 Tcl_DecrRefCount(pDb->pRollbackHook);
460 }
danielk197794eb6a12005-12-15 15:22:08 +0000461 if( pDb->pCollateNeeded ){
462 Tcl_DecrRefCount(pDb->pCollateNeeded);
463 }
drhbec3f402000-08-04 13:49:02 +0000464 Tcl_Free((char*)pDb);
465}
466
467/*
468** This routine is called when a database file is locked while trying
469** to execute SQL.
470*/
danielk19772a764eb2004-06-12 01:43:26 +0000471static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000472 SqliteDb *pDb = (SqliteDb*)cd;
473 int rc;
474 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000475
drh5bb3eb92007-05-04 13:15:55 +0000476 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000477 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000478 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
479 return 0;
480 }
481 return 1;
drh75897232000-05-29 14:26:00 +0000482}
483
484/*
danielk1977348bb5d2003-10-18 09:37:26 +0000485** This routine is invoked as the 'progress callback' for the database.
486*/
487static int DbProgressHandler(void *cd){
488 SqliteDb *pDb = (SqliteDb*)cd;
489 int rc;
490
491 assert( pDb->zProgress );
492 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
493 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
494 return 1;
495 }
496 return 0;
497}
498
drhd1167392006-01-23 13:00:35 +0000499#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000500/*
drhb5a20d32003-04-23 12:25:23 +0000501** This routine is called by the SQLite trace handler whenever a new
502** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000503*/
drhb5a20d32003-04-23 12:25:23 +0000504static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000505 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000506 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000507
drhb5a20d32003-04-23 12:25:23 +0000508 Tcl_DStringInit(&str);
509 Tcl_DStringAppend(&str, pDb->zTrace, -1);
510 Tcl_DStringAppendElement(&str, zSql);
511 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
512 Tcl_DStringFree(&str);
513 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000514}
drhd1167392006-01-23 13:00:35 +0000515#endif
drh0d1a6432003-04-03 15:46:04 +0000516
drhd1167392006-01-23 13:00:35 +0000517#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000518/*
drh19e2d372005-08-29 23:00:03 +0000519** This routine is called by the SQLite profile handler after a statement
520** SQL has executed. The TCL script in pDb->zProfile is evaluated.
521*/
522static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
523 SqliteDb *pDb = (SqliteDb*)cd;
524 Tcl_DString str;
525 char zTm[100];
526
527 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
528 Tcl_DStringInit(&str);
529 Tcl_DStringAppend(&str, pDb->zProfile, -1);
530 Tcl_DStringAppendElement(&str, zSql);
531 Tcl_DStringAppendElement(&str, zTm);
532 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
533 Tcl_DStringFree(&str);
534 Tcl_ResetResult(pDb->interp);
535}
drhd1167392006-01-23 13:00:35 +0000536#endif
drh19e2d372005-08-29 23:00:03 +0000537
538/*
drhaa940ea2004-01-15 02:44:03 +0000539** This routine is called when a transaction is committed. The
540** TCL script in pDb->zCommit is executed. If it returns non-zero or
541** if it throws an exception, the transaction is rolled back instead
542** of being committed.
543*/
544static int DbCommitHandler(void *cd){
545 SqliteDb *pDb = (SqliteDb*)cd;
546 int rc;
547
548 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
549 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
550 return 1;
551 }
552 return 0;
553}
554
danielk197771fd80b2005-12-16 06:54:01 +0000555static void DbRollbackHandler(void *clientData){
556 SqliteDb *pDb = (SqliteDb*)clientData;
557 assert(pDb->pRollbackHook);
558 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
559 Tcl_BackgroundError(pDb->interp);
560 }
561}
562
danielk197794eb6a12005-12-15 15:22:08 +0000563static void DbUpdateHandler(
564 void *p,
565 int op,
566 const char *zDb,
567 const char *zTbl,
568 sqlite_int64 rowid
569){
570 SqliteDb *pDb = (SqliteDb *)p;
571 Tcl_Obj *pCmd;
572
573 assert( pDb->pUpdateHook );
574 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
575
576 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
577 Tcl_IncrRefCount(pCmd);
578 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
579 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
580 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
581 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
582 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
583 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
584}
585
danielk19777cedc8d2004-06-10 10:50:08 +0000586static void tclCollateNeeded(
587 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000588 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000589 int enc,
590 const char *zName
591){
592 SqliteDb *pDb = (SqliteDb *)pCtx;
593 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
594 Tcl_IncrRefCount(pScript);
595 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
596 Tcl_EvalObjEx(pDb->interp, pScript, 0);
597 Tcl_DecrRefCount(pScript);
598}
599
drhaa940ea2004-01-15 02:44:03 +0000600/*
danielk19770202b292004-06-09 09:55:16 +0000601** This routine is called to evaluate an SQL collation function implemented
602** using TCL script.
603*/
604static int tclSqlCollate(
605 void *pCtx,
606 int nA,
607 const void *zA,
608 int nB,
609 const void *zB
610){
611 SqlCollate *p = (SqlCollate *)pCtx;
612 Tcl_Obj *pCmd;
613
614 pCmd = Tcl_NewStringObj(p->zScript, -1);
615 Tcl_IncrRefCount(pCmd);
616 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
617 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000618 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000619 Tcl_DecrRefCount(pCmd);
620 return (atoi(Tcl_GetStringResult(p->interp)));
621}
622
623/*
drhcabb0812002-09-14 13:47:32 +0000624** This routine is called to evaluate an SQL function implemented
625** using TCL script.
626*/
drhfb7e7652005-01-24 00:28:42 +0000627static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000628 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000629 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000630 int i;
631 int rc;
632
drhd1e47332005-06-26 17:55:33 +0000633 if( argc==0 ){
634 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
635 ** script object directly. This allows the TCL compiler to generate
636 ** bytecode for the command on the first invocation and thus make
637 ** subsequent invocations much faster. */
638 pCmd = p->pScript;
639 Tcl_IncrRefCount(pCmd);
640 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
641 Tcl_DecrRefCount(pCmd);
642 }else{
643 /* If there are arguments to the function, make a shallow copy of the
644 ** script object, lappend the arguments, then evaluate the copy.
645 **
646 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
647 ** The new Tcl_Obj contains pointers to the original list elements.
648 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
649 ** of the list to tclCmdNameType, that alternate representation will
650 ** be preserved and reused on the next invocation.
651 */
652 Tcl_Obj **aArg;
653 int nArg;
654 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
655 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
656 return;
657 }
658 pCmd = Tcl_NewListObj(nArg, aArg);
659 Tcl_IncrRefCount(pCmd);
660 for(i=0; i<argc; i++){
661 sqlite3_value *pIn = argv[i];
662 Tcl_Obj *pVal;
663
664 /* Set pVal to contain the i'th column of this row. */
665 switch( sqlite3_value_type(pIn) ){
666 case SQLITE_BLOB: {
667 int bytes = sqlite3_value_bytes(pIn);
668 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
669 break;
670 }
671 case SQLITE_INTEGER: {
672 sqlite_int64 v = sqlite3_value_int64(pIn);
673 if( v>=-2147483647 && v<=2147483647 ){
674 pVal = Tcl_NewIntObj(v);
675 }else{
676 pVal = Tcl_NewWideIntObj(v);
677 }
678 break;
679 }
680 case SQLITE_FLOAT: {
681 double r = sqlite3_value_double(pIn);
682 pVal = Tcl_NewDoubleObj(r);
683 break;
684 }
685 case SQLITE_NULL: {
686 pVal = Tcl_NewStringObj("", 0);
687 break;
688 }
689 default: {
690 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000691 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000692 break;
693 }
694 }
695 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
696 if( rc ){
697 Tcl_DecrRefCount(pCmd);
698 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
699 return;
700 }
danielk197751ad0ec2004-05-24 12:39:02 +0000701 }
drhd1e47332005-06-26 17:55:33 +0000702 if( !p->useEvalObjv ){
703 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
704 ** is a list without a string representation. To prevent this from
705 ** happening, make sure pCmd has a valid string representation */
706 Tcl_GetString(pCmd);
707 }
708 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
709 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000710 }
danielk1977562e8d32005-05-20 09:40:55 +0000711
drhc7f269d2005-05-05 10:30:29 +0000712 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000713 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000714 }else{
drhc7f269d2005-05-05 10:30:29 +0000715 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
716 int n;
717 u8 *data;
718 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
719 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000720 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000721 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000722 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000723 data = Tcl_GetByteArrayFromObj(pVar, &n);
724 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000725 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
726 (c=='i' && strcmp(zType,"int")==0) ){
727 Tcl_GetIntFromObj(0, pVar, &n);
728 sqlite3_result_int(context, n);
729 }else if( c=='d' && strcmp(zType,"double")==0 ){
730 double r;
731 Tcl_GetDoubleFromObj(0, pVar, &r);
732 sqlite3_result_double(context, r);
drhdf0bdda2005-06-25 19:31:48 +0000733 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
734 Tcl_WideInt v;
735 Tcl_GetWideIntFromObj(0, pVar, &v);
736 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000737 }else{
danielk197700fd9572005-12-07 06:27:43 +0000738 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
739 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000740 }
drhcabb0812002-09-14 13:47:32 +0000741 }
742}
drh895d7472004-08-20 16:02:39 +0000743
drhe22a3342003-04-22 20:30:37 +0000744#ifndef SQLITE_OMIT_AUTHORIZATION
745/*
746** This is the authentication function. It appends the authentication
747** type code and the two arguments to zCmd[] then invokes the result
748** on the interpreter. The reply is examined to determine if the
749** authentication fails or succeeds.
750*/
751static int auth_callback(
752 void *pArg,
753 int code,
754 const char *zArg1,
755 const char *zArg2,
756 const char *zArg3,
757 const char *zArg4
758){
759 char *zCode;
760 Tcl_DString str;
761 int rc;
762 const char *zReply;
763 SqliteDb *pDb = (SqliteDb*)pArg;
764
765 switch( code ){
766 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
767 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
768 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
769 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
770 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
771 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
772 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
773 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
774 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
775 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
776 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
777 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
778 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
779 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
780 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
781 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
782 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
783 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
784 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
785 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
786 case SQLITE_READ : zCode="SQLITE_READ"; break;
787 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
788 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
789 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000790 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
791 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000792 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000793 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000794 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000795 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
796 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000797 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
drhe22a3342003-04-22 20:30:37 +0000798 default : zCode="????"; break;
799 }
800 Tcl_DStringInit(&str);
801 Tcl_DStringAppend(&str, pDb->zAuth, -1);
802 Tcl_DStringAppendElement(&str, zCode);
803 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
804 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
805 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
806 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
807 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
808 Tcl_DStringFree(&str);
809 zReply = Tcl_GetStringResult(pDb->interp);
810 if( strcmp(zReply,"SQLITE_OK")==0 ){
811 rc = SQLITE_OK;
812 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
813 rc = SQLITE_DENY;
814 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
815 rc = SQLITE_IGNORE;
816 }else{
817 rc = 999;
818 }
819 return rc;
820}
821#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000822
823/*
danielk1977ef2cb632004-05-29 02:37:19 +0000824** zText is a pointer to text obtained via an sqlite3_result_text()
825** or similar interface. This routine returns a Tcl string object,
826** reference count set to 0, containing the text. If a translation
827** between iso8859 and UTF-8 is required, it is preformed.
828*/
829static Tcl_Obj *dbTextToObj(char const *zText){
830 Tcl_Obj *pVal;
831#ifdef UTF_TRANSLATION_NEEDED
832 Tcl_DString dCol;
833 Tcl_DStringInit(&dCol);
834 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
835 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
836 Tcl_DStringFree(&dCol);
837#else
838 pVal = Tcl_NewStringObj(zText, -1);
839#endif
840 return pVal;
841}
842
843/*
tpoindex1067fe12004-12-17 15:41:11 +0000844** This routine reads a line of text from FILE in, stores
845** the text in memory obtained from malloc() and returns a pointer
846** to the text. NULL is returned at end of file, or if malloc()
847** fails.
848**
849** The interface is like "readline" but no command-line editing
850** is done.
851**
852** copied from shell.c from '.import' command
853*/
854static char *local_getline(char *zPrompt, FILE *in){
855 char *zLine;
856 int nLine;
857 int n;
858 int eol;
859
860 nLine = 100;
861 zLine = malloc( nLine );
862 if( zLine==0 ) return 0;
863 n = 0;
864 eol = 0;
865 while( !eol ){
866 if( n+100>nLine ){
867 nLine = nLine*2 + 100;
868 zLine = realloc(zLine, nLine);
869 if( zLine==0 ) return 0;
870 }
871 if( fgets(&zLine[n], nLine - n, in)==0 ){
872 if( n==0 ){
873 free(zLine);
874 return 0;
875 }
876 zLine[n] = 0;
877 eol = 1;
878 break;
879 }
880 while( zLine[n] ){ n++; }
881 if( n>0 && zLine[n-1]=='\n' ){
882 n--;
883 zLine[n] = 0;
884 eol = 1;
885 }
886 }
887 zLine = realloc( zLine, n+1 );
888 return zLine;
889}
890
891/*
drh75897232000-05-29 14:26:00 +0000892** The "sqlite" command below creates a new Tcl command for each
893** connection it opens to an SQLite database. This routine is invoked
894** whenever one of those connection-specific commands is executed
895** in Tcl. For example, if you run Tcl code like this:
896**
drh9bb575f2004-09-06 17:24:11 +0000897** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +0000898** db1 close
899**
900** The first command opens a connection to the "my_database" database
901** and calls that connection "db1". The second command causes this
902** subroutine to be invoked.
903*/
drh6d313162000-09-21 13:01:35 +0000904static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +0000905 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +0000906 int choice;
drh22fbcb82004-02-01 01:22:50 +0000907 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +0000908 static const char *DB_strs[] = {
drhfb7e7652005-01-24 00:28:42 +0000909 "authorizer", "busy", "cache",
910 "changes", "close", "collate",
911 "collation_needed", "commit_hook", "complete",
drh41449052006-07-06 17:08:48 +0000912 "copy", "enable_load_extension","errorcode",
913 "eval", "exists", "function",
danielk1977b4e9af92007-05-01 17:49:49 +0000914 "incrblob",
drhf11bded2006-07-17 00:02:44 +0000915 "interrupt", "last_insert_rowid", "nullvalue",
916 "onecolumn", "profile", "progress",
917 "rekey", "rollback_hook", "timeout",
918 "total_changes", "trace", "transaction",
919 "update_hook", "version", 0
drh6d313162000-09-21 13:01:35 +0000920 };
drh411995d2002-06-25 19:31:18 +0000921 enum DB_enum {
drhfb7e7652005-01-24 00:28:42 +0000922 DB_AUTHORIZER, DB_BUSY, DB_CACHE,
923 DB_CHANGES, DB_CLOSE, DB_COLLATE,
924 DB_COLLATION_NEEDED, DB_COMMIT_HOOK, DB_COMPLETE,
drh41449052006-07-06 17:08:48 +0000925 DB_COPY, DB_ENABLE_LOAD_EXTENSION,DB_ERRORCODE,
926 DB_EVAL, DB_EXISTS, DB_FUNCTION,
danielk1977b4e9af92007-05-01 17:49:49 +0000927 DB_INCRBLOB,
drhf11bded2006-07-17 00:02:44 +0000928 DB_INTERRUPT, DB_LAST_INSERT_ROWID,DB_NULLVALUE,
929 DB_ONECOLUMN, DB_PROFILE, DB_PROGRESS,
930 DB_REKEY, DB_ROLLBACK_HOOK, DB_TIMEOUT,
931 DB_TOTAL_CHANGES, DB_TRACE, DB_TRANSACTION,
932 DB_UPDATE_HOOK, DB_VERSION,
drh6d313162000-09-21 13:01:35 +0000933 };
tpoindex1067fe12004-12-17 15:41:11 +0000934 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +0000935
936 if( objc<2 ){
937 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +0000938 return TCL_ERROR;
939 }
drh411995d2002-06-25 19:31:18 +0000940 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +0000941 return TCL_ERROR;
942 }
943
drh411995d2002-06-25 19:31:18 +0000944 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +0000945
drhe22a3342003-04-22 20:30:37 +0000946 /* $db authorizer ?CALLBACK?
947 **
948 ** Invoke the given callback to authorize each SQL operation as it is
949 ** compiled. 5 arguments are appended to the callback before it is
950 ** invoked:
951 **
952 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
953 ** (2) First descriptive name (depends on authorization type)
954 ** (3) Second descriptive name
955 ** (4) Name of the database (ex: "main", "temp")
956 ** (5) Name of trigger that is doing the access
957 **
958 ** The callback should return on of the following strings: SQLITE_OK,
959 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
960 **
961 ** If this method is invoked with no arguments, the current authorization
962 ** callback string is returned.
963 */
964 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +0000965#ifdef SQLITE_OMIT_AUTHORIZATION
966 Tcl_AppendResult(interp, "authorization not available in this build", 0);
967 return TCL_ERROR;
968#else
drhe22a3342003-04-22 20:30:37 +0000969 if( objc>3 ){
970 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +0000971 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +0000972 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +0000973 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +0000974 Tcl_AppendResult(interp, pDb->zAuth, 0);
975 }
976 }else{
977 char *zAuth;
978 int len;
979 if( pDb->zAuth ){
980 Tcl_Free(pDb->zAuth);
981 }
982 zAuth = Tcl_GetStringFromObj(objv[2], &len);
983 if( zAuth && len>0 ){
984 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +0000985 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +0000986 }else{
987 pDb->zAuth = 0;
988 }
drhe22a3342003-04-22 20:30:37 +0000989 if( pDb->zAuth ){
990 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000991 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +0000992 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000993 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +0000994 }
drhe22a3342003-04-22 20:30:37 +0000995 }
drh1211de32004-07-26 12:24:22 +0000996#endif
drhe22a3342003-04-22 20:30:37 +0000997 break;
998 }
999
drhbec3f402000-08-04 13:49:02 +00001000 /* $db busy ?CALLBACK?
1001 **
1002 ** Invoke the given callback if an SQL statement attempts to open
1003 ** a locked database file.
1004 */
drh6d313162000-09-21 13:01:35 +00001005 case DB_BUSY: {
1006 if( objc>3 ){
1007 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001008 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001009 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001010 if( pDb->zBusy ){
1011 Tcl_AppendResult(interp, pDb->zBusy, 0);
1012 }
1013 }else{
drh6d313162000-09-21 13:01:35 +00001014 char *zBusy;
1015 int len;
drhbec3f402000-08-04 13:49:02 +00001016 if( pDb->zBusy ){
1017 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001018 }
drh6d313162000-09-21 13:01:35 +00001019 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1020 if( zBusy && len>0 ){
1021 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001022 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001023 }else{
1024 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001025 }
1026 if( pDb->zBusy ){
1027 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001028 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001029 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001030 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001031 }
1032 }
drh6d313162000-09-21 13:01:35 +00001033 break;
1034 }
drhbec3f402000-08-04 13:49:02 +00001035
drhfb7e7652005-01-24 00:28:42 +00001036 /* $db cache flush
1037 ** $db cache size n
1038 **
1039 ** Flush the prepared statement cache, or set the maximum number of
1040 ** cached statements.
1041 */
1042 case DB_CACHE: {
1043 char *subCmd;
1044 int n;
1045
1046 if( objc<=2 ){
1047 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1048 return TCL_ERROR;
1049 }
1050 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1051 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1052 if( objc!=3 ){
1053 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1054 return TCL_ERROR;
1055 }else{
1056 flushStmtCache( pDb );
1057 }
1058 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1059 if( objc!=4 ){
1060 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1061 return TCL_ERROR;
1062 }else{
1063 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1064 Tcl_AppendResult( interp, "cannot convert \"",
1065 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1066 return TCL_ERROR;
1067 }else{
1068 if( n<0 ){
1069 flushStmtCache( pDb );
1070 n = 0;
1071 }else if( n>MAX_PREPARED_STMTS ){
1072 n = MAX_PREPARED_STMTS;
1073 }
1074 pDb->maxStmt = n;
1075 }
1076 }
1077 }else{
1078 Tcl_AppendResult( interp, "bad option \"",
1079 Tcl_GetStringFromObj(objv[0],0), "\": must be flush or size", 0);
1080 return TCL_ERROR;
1081 }
1082 break;
1083 }
1084
danielk1977b28af712004-06-21 06:50:26 +00001085 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001086 **
1087 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001088 ** the most recent INSERT, UPDATE or DELETE statement, not including
1089 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001090 */
1091 case DB_CHANGES: {
1092 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001093 if( objc!=2 ){
1094 Tcl_WrongNumArgs(interp, 2, objv, "");
1095 return TCL_ERROR;
1096 }
drhc8d30ac2002-04-12 10:08:59 +00001097 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001098 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001099 break;
1100 }
1101
drh75897232000-05-29 14:26:00 +00001102 /* $db close
1103 **
1104 ** Shutdown the database
1105 */
drh6d313162000-09-21 13:01:35 +00001106 case DB_CLOSE: {
1107 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1108 break;
1109 }
drh75897232000-05-29 14:26:00 +00001110
drh0f14e2e2004-06-29 12:39:08 +00001111 /*
1112 ** $db collate NAME SCRIPT
1113 **
1114 ** Create a new SQL collation function called NAME. Whenever
1115 ** that function is called, invoke SCRIPT to evaluate the function.
1116 */
1117 case DB_COLLATE: {
1118 SqlCollate *pCollate;
1119 char *zName;
1120 char *zScript;
1121 int nScript;
1122 if( objc!=4 ){
1123 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1124 return TCL_ERROR;
1125 }
1126 zName = Tcl_GetStringFromObj(objv[2], 0);
1127 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1128 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1129 if( pCollate==0 ) return TCL_ERROR;
1130 pCollate->interp = interp;
1131 pCollate->pNext = pDb->pCollate;
1132 pCollate->zScript = (char*)&pCollate[1];
1133 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001134 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001135 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1136 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001137 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001138 return TCL_ERROR;
1139 }
1140 break;
1141 }
1142
1143 /*
1144 ** $db collation_needed SCRIPT
1145 **
1146 ** Create a new SQL collation function called NAME. Whenever
1147 ** that function is called, invoke SCRIPT to evaluate the function.
1148 */
1149 case DB_COLLATION_NEEDED: {
1150 if( objc!=3 ){
1151 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1152 return TCL_ERROR;
1153 }
1154 if( pDb->pCollateNeeded ){
1155 Tcl_DecrRefCount(pDb->pCollateNeeded);
1156 }
1157 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1158 Tcl_IncrRefCount(pDb->pCollateNeeded);
1159 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1160 break;
1161 }
1162
drh19e2d372005-08-29 23:00:03 +00001163 /* $db commit_hook ?CALLBACK?
1164 **
1165 ** Invoke the given callback just before committing every SQL transaction.
1166 ** If the callback throws an exception or returns non-zero, then the
1167 ** transaction is aborted. If CALLBACK is an empty string, the callback
1168 ** is disabled.
1169 */
1170 case DB_COMMIT_HOOK: {
1171 if( objc>3 ){
1172 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1173 return TCL_ERROR;
1174 }else if( objc==2 ){
1175 if( pDb->zCommit ){
1176 Tcl_AppendResult(interp, pDb->zCommit, 0);
1177 }
1178 }else{
1179 char *zCommit;
1180 int len;
1181 if( pDb->zCommit ){
1182 Tcl_Free(pDb->zCommit);
1183 }
1184 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1185 if( zCommit && len>0 ){
1186 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001187 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001188 }else{
1189 pDb->zCommit = 0;
1190 }
1191 if( pDb->zCommit ){
1192 pDb->interp = interp;
1193 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1194 }else{
1195 sqlite3_commit_hook(pDb->db, 0, 0);
1196 }
1197 }
1198 break;
1199 }
1200
drh75897232000-05-29 14:26:00 +00001201 /* $db complete SQL
1202 **
1203 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1204 ** additional lines of input are needed. This is similar to the
1205 ** built-in "info complete" command of Tcl.
1206 */
drh6d313162000-09-21 13:01:35 +00001207 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00001208#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00001209 Tcl_Obj *pResult;
1210 int isComplete;
1211 if( objc!=3 ){
1212 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00001213 return TCL_ERROR;
1214 }
danielk19776f8a5032004-05-10 10:34:51 +00001215 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00001216 pResult = Tcl_GetObjResult(interp);
1217 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00001218#endif
drh6d313162000-09-21 13:01:35 +00001219 break;
1220 }
drhdcd997e2003-01-31 17:21:49 +00001221
drh19e2d372005-08-29 23:00:03 +00001222 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1223 **
1224 ** Copy data into table from filename, optionally using SEPARATOR
1225 ** as column separators. If a column contains a null string, or the
1226 ** value of NULLINDICATOR, a NULL is inserted for the column.
1227 ** conflict-algorithm is one of the sqlite conflict algorithms:
1228 ** rollback, abort, fail, ignore, replace
1229 ** On success, return the number of lines processed, not necessarily same
1230 ** as 'db changes' due to conflict-algorithm selected.
1231 **
1232 ** This code is basically an implementation/enhancement of
1233 ** the sqlite3 shell.c ".import" command.
1234 **
1235 ** This command usage is equivalent to the sqlite2.x COPY statement,
1236 ** which imports file data into a table using the PostgreSQL COPY file format:
1237 ** $db copy $conflit_algo $table_name $filename \t \\N
1238 */
1239 case DB_COPY: {
1240 char *zTable; /* Insert data into this table */
1241 char *zFile; /* The file from which to extract data */
1242 char *zConflict; /* The conflict algorithm to use */
1243 sqlite3_stmt *pStmt; /* A statement */
1244 int rc; /* Result code */
1245 int nCol; /* Number of columns in the table */
1246 int nByte; /* Number of bytes in an SQL string */
1247 int i, j; /* Loop counters */
1248 int nSep; /* Number of bytes in zSep[] */
1249 int nNull; /* Number of bytes in zNull[] */
1250 char *zSql; /* An SQL statement */
1251 char *zLine; /* A single line of input from the file */
1252 char **azCol; /* zLine[] broken up into columns */
1253 char *zCommit; /* How to commit changes */
1254 FILE *in; /* The input file */
1255 int lineno = 0; /* Line number of input file */
1256 char zLineNum[80]; /* Line number print buffer */
1257 Tcl_Obj *pResult; /* interp result */
1258
1259 char *zSep;
1260 char *zNull;
1261 if( objc<5 || objc>7 ){
1262 Tcl_WrongNumArgs(interp, 2, objv,
1263 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1264 return TCL_ERROR;
1265 }
1266 if( objc>=6 ){
1267 zSep = Tcl_GetStringFromObj(objv[5], 0);
1268 }else{
1269 zSep = "\t";
1270 }
1271 if( objc>=7 ){
1272 zNull = Tcl_GetStringFromObj(objv[6], 0);
1273 }else{
1274 zNull = "";
1275 }
1276 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1277 zTable = Tcl_GetStringFromObj(objv[3], 0);
1278 zFile = Tcl_GetStringFromObj(objv[4], 0);
1279 nSep = strlen(zSep);
1280 nNull = strlen(zNull);
1281 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00001282 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00001283 return TCL_ERROR;
1284 }
1285 if(sqlite3StrICmp(zConflict, "rollback") != 0 &&
1286 sqlite3StrICmp(zConflict, "abort" ) != 0 &&
1287 sqlite3StrICmp(zConflict, "fail" ) != 0 &&
1288 sqlite3StrICmp(zConflict, "ignore" ) != 0 &&
1289 sqlite3StrICmp(zConflict, "replace" ) != 0 ) {
1290 Tcl_AppendResult(interp, "Error: \"", zConflict,
1291 "\", conflict-algorithm must be one of: rollback, "
1292 "abort, fail, ignore, or replace", 0);
1293 return TCL_ERROR;
1294 }
1295 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1296 if( zSql==0 ){
1297 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1298 return TCL_ERROR;
1299 }
1300 nByte = strlen(zSql);
drh3e701a12007-02-01 01:53:44 +00001301 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001302 sqlite3_free(zSql);
1303 if( rc ){
1304 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1305 nCol = 0;
1306 }else{
1307 nCol = sqlite3_column_count(pStmt);
1308 }
1309 sqlite3_finalize(pStmt);
1310 if( nCol==0 ) {
1311 return TCL_ERROR;
1312 }
1313 zSql = malloc( nByte + 50 + nCol*2 );
1314 if( zSql==0 ) {
1315 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1316 return TCL_ERROR;
1317 }
1318 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1319 zConflict, zTable);
1320 j = strlen(zSql);
1321 for(i=1; i<nCol; i++){
1322 zSql[j++] = ',';
1323 zSql[j++] = '?';
1324 }
1325 zSql[j++] = ')';
1326 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00001327 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001328 free(zSql);
1329 if( rc ){
1330 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1331 sqlite3_finalize(pStmt);
1332 return TCL_ERROR;
1333 }
1334 in = fopen(zFile, "rb");
1335 if( in==0 ){
1336 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
1337 sqlite3_finalize(pStmt);
1338 return TCL_ERROR;
1339 }
1340 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1341 if( azCol==0 ) {
1342 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00001343 fclose(in);
drh19e2d372005-08-29 23:00:03 +00001344 return TCL_ERROR;
1345 }
drh37527852006-03-16 16:19:56 +00001346 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001347 zCommit = "COMMIT";
1348 while( (zLine = local_getline(0, in))!=0 ){
1349 char *z;
1350 i = 0;
1351 lineno++;
1352 azCol[0] = zLine;
1353 for(i=0, z=zLine; *z; z++){
1354 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
1355 *z = 0;
1356 i++;
1357 if( i<nCol ){
1358 azCol[i] = &z[nSep];
1359 z += nSep-1;
1360 }
1361 }
1362 }
1363 if( i+1!=nCol ){
1364 char *zErr;
drh5bb3eb92007-05-04 13:15:55 +00001365 int nErr = strlen(zFile) + 200;
1366 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00001367 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00001368 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00001369 "Error: %s line %d: expected %d columns of data but found %d",
1370 zFile, lineno, nCol, i+1);
1371 Tcl_AppendResult(interp, zErr, 0);
1372 free(zErr);
1373 }
drh19e2d372005-08-29 23:00:03 +00001374 zCommit = "ROLLBACK";
1375 break;
1376 }
1377 for(i=0; i<nCol; i++){
1378 /* check for null data, if so, bind as null */
1379 if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
1380 sqlite3_bind_null(pStmt, i+1);
1381 }else{
1382 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1383 }
1384 }
1385 sqlite3_step(pStmt);
1386 rc = sqlite3_reset(pStmt);
1387 free(zLine);
1388 if( rc!=SQLITE_OK ){
1389 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
1390 zCommit = "ROLLBACK";
1391 break;
1392 }
1393 }
1394 free(azCol);
1395 fclose(in);
1396 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00001397 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001398
1399 if( zCommit[0] == 'C' ){
1400 /* success, set result as number of lines processed */
1401 pResult = Tcl_GetObjResult(interp);
1402 Tcl_SetIntObj(pResult, lineno);
1403 rc = TCL_OK;
1404 }else{
1405 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00001406 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00001407 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
1408 rc = TCL_ERROR;
1409 }
1410 break;
1411 }
1412
drhdcd997e2003-01-31 17:21:49 +00001413 /*
drh41449052006-07-06 17:08:48 +00001414 ** $db enable_load_extension BOOLEAN
1415 **
1416 ** Turn the extension loading feature on or off. It if off by
1417 ** default.
1418 */
1419 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00001420#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00001421 int onoff;
1422 if( objc!=3 ){
1423 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
1424 return TCL_ERROR;
1425 }
1426 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
1427 return TCL_ERROR;
1428 }
1429 sqlite3_enable_load_extension(pDb->db, onoff);
1430 break;
drhf533acc2006-12-19 18:57:11 +00001431#else
1432 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
1433 0);
1434 return TCL_ERROR;
1435#endif
drh41449052006-07-06 17:08:48 +00001436 }
1437
1438 /*
drhdcd997e2003-01-31 17:21:49 +00001439 ** $db errorcode
1440 **
1441 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00001442 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00001443 */
1444 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00001445 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00001446 break;
1447 }
drh75897232000-05-29 14:26:00 +00001448
1449 /*
drh895d7472004-08-20 16:02:39 +00001450 ** $db eval $sql ?array? ?{ ...code... }?
drh1807ce32004-09-07 13:20:35 +00001451 ** $db onecolumn $sql
drh75897232000-05-29 14:26:00 +00001452 **
1453 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00001454 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00001455 ** If "array" and "code" are omitted, then no callback is every invoked.
1456 ** If "array" is an empty string, then the values are placed in variables
1457 ** that have the same name as the fields extracted by the query.
drh1807ce32004-09-07 13:20:35 +00001458 **
1459 ** The onecolumn method is the equivalent of:
1460 ** lindex [$db eval $sql] 0
drh75897232000-05-29 14:26:00 +00001461 */
drh1807ce32004-09-07 13:20:35 +00001462 case DB_ONECOLUMN:
drh97f2ebc2005-12-10 21:19:04 +00001463 case DB_EVAL:
1464 case DB_EXISTS: {
drh9d74b4c2004-08-24 15:23:34 +00001465 char const *zSql; /* Next SQL statement to execute */
1466 char const *zLeft; /* What is left after first stmt in zSql */
1467 sqlite3_stmt *pStmt; /* Compiled SQL statment */
drh92febd92004-08-20 18:34:20 +00001468 Tcl_Obj *pArray; /* Name of array into which results are written */
1469 Tcl_Obj *pScript; /* Script to run for each result set */
drh1d895032004-08-26 00:56:05 +00001470 Tcl_Obj **apParm; /* Parameters that need a Tcl_DecrRefCount() */
1471 int nParm; /* Number of entries used in apParm[] */
1472 Tcl_Obj *aParm[10]; /* Static space for apParm[] in the common case */
drh1807ce32004-09-07 13:20:35 +00001473 Tcl_Obj *pRet; /* Value to be returned */
drhfb7e7652005-01-24 00:28:42 +00001474 SqlPreparedStmt *pPreStmt; /* Pointer to a prepared statement */
1475 int rc2;
danielk1977ef2cb632004-05-29 02:37:19 +00001476
drh97f2ebc2005-12-10 21:19:04 +00001477 if( choice==DB_EVAL ){
drh1807ce32004-09-07 13:20:35 +00001478 if( objc<3 || objc>5 ){
1479 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
1480 return TCL_ERROR;
1481 }
1482 pRet = Tcl_NewObj();
1483 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001484 }else{
1485 if( objc!=3 ){
1486 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
1487 return TCL_ERROR;
1488 }
drh97f2ebc2005-12-10 21:19:04 +00001489 if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001490 pRet = Tcl_NewBooleanObj(0);
1491 Tcl_IncrRefCount(pRet);
1492 }else{
1493 pRet = 0;
drh97f2ebc2005-12-10 21:19:04 +00001494 }
danielk197730ccda12004-05-27 12:11:31 +00001495 }
drh92febd92004-08-20 18:34:20 +00001496 if( objc==3 ){
1497 pArray = pScript = 0;
1498 }else if( objc==4 ){
1499 pArray = 0;
1500 pScript = objv[3];
1501 }else{
1502 pArray = objv[3];
1503 if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
1504 pScript = objv[4];
1505 }
danielk197730ccda12004-05-27 12:11:31 +00001506
drh1d895032004-08-26 00:56:05 +00001507 Tcl_IncrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001508 zSql = Tcl_GetStringFromObj(objv[2], 0);
drh90b6bb12004-09-13 13:16:31 +00001509 while( rc==TCL_OK && zSql[0] ){
drhfb7e7652005-01-24 00:28:42 +00001510 int i; /* Loop counter */
1511 int nVar; /* Number of bind parameters in the pStmt */
1512 int nCol; /* Number of columns in the result set */
drh92febd92004-08-20 18:34:20 +00001513 Tcl_Obj **apColName = 0; /* Array of column names */
drhfb7e7652005-01-24 00:28:42 +00001514 int len; /* String length of zSql */
danielk197730ccda12004-05-27 12:11:31 +00001515
drhfb7e7652005-01-24 00:28:42 +00001516 /* Try to find a SQL statement that has already been compiled and
1517 ** which matches the next sequence of SQL.
1518 */
1519 pStmt = 0;
1520 pPreStmt = pDb->stmtList;
1521 len = strlen(zSql);
1522 if( pPreStmt && sqlite3_expired(pPreStmt->pStmt) ){
1523 flushStmtCache(pDb);
1524 pPreStmt = 0;
danielk197730ccda12004-05-27 12:11:31 +00001525 }
drhfb7e7652005-01-24 00:28:42 +00001526 for(; pPreStmt; pPreStmt=pPreStmt->pNext){
1527 int n = pPreStmt->nSql;
1528 if( len>=n
1529 && memcmp(pPreStmt->zSql, zSql, n)==0
1530 && (zSql[n]==0 || zSql[n-1]==';')
1531 ){
1532 pStmt = pPreStmt->pStmt;
1533 zLeft = &zSql[pPreStmt->nSql];
1534
1535 /* When a prepared statement is found, unlink it from the
1536 ** cache list. It will later be added back to the beginning
1537 ** of the cache list in order to implement LRU replacement.
1538 */
1539 if( pPreStmt->pPrev ){
1540 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1541 }else{
1542 pDb->stmtList = pPreStmt->pNext;
1543 }
1544 if( pPreStmt->pNext ){
1545 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1546 }else{
1547 pDb->stmtLast = pPreStmt->pPrev;
1548 }
1549 pDb->nStmt--;
1550 break;
1551 }
1552 }
1553
1554 /* If no prepared statement was found. Compile the SQL text
1555 */
drh92febd92004-08-20 18:34:20 +00001556 if( pStmt==0 ){
drhfb7e7652005-01-24 00:28:42 +00001557 if( SQLITE_OK!=sqlite3_prepare(pDb->db, zSql, -1, &pStmt, &zLeft) ){
drh92febd92004-08-20 18:34:20 +00001558 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1559 rc = TCL_ERROR;
1560 break;
danielk197730ccda12004-05-27 12:11:31 +00001561 }
drhfb7e7652005-01-24 00:28:42 +00001562 if( pStmt==0 ){
1563 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1564 /* A compile-time error in the statement
1565 */
1566 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1567 rc = TCL_ERROR;
1568 break;
1569 }else{
1570 /* The statement was a no-op. Continue to the next statement
1571 ** in the SQL string.
1572 */
1573 zSql = zLeft;
1574 continue;
1575 }
1576 }
1577 assert( pPreStmt==0 );
danielk197730ccda12004-05-27 12:11:31 +00001578 }
1579
drhfb7e7652005-01-24 00:28:42 +00001580 /* Bind values to parameters that begin with $ or :
1581 */
drh92febd92004-08-20 18:34:20 +00001582 nVar = sqlite3_bind_parameter_count(pStmt);
drh1d895032004-08-26 00:56:05 +00001583 nParm = 0;
1584 if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
1585 apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
1586 }else{
1587 apParm = aParm;
1588 }
drh92febd92004-08-20 18:34:20 +00001589 for(i=1; i<=nVar; i++){
1590 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
drhc8f90792005-01-12 00:08:24 +00001591 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':') ){
drh92febd92004-08-20 18:34:20 +00001592 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1593 if( pVar ){
1594 int n;
1595 u8 *data;
1596 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
1597 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +00001598 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
1599 /* Only load a BLOB type if the Tcl variable is a bytearray and
1600 ** has no string representation. */
drh92febd92004-08-20 18:34:20 +00001601 data = Tcl_GetByteArrayFromObj(pVar, &n);
1602 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001603 Tcl_IncrRefCount(pVar);
1604 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001605 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
1606 (c=='i' && strcmp(zType,"int")==0) ){
1607 Tcl_GetIntFromObj(interp, pVar, &n);
1608 sqlite3_bind_int(pStmt, i, n);
1609 }else if( c=='d' && strcmp(zType,"double")==0 ){
1610 double r;
1611 Tcl_GetDoubleFromObj(interp, pVar, &r);
1612 sqlite3_bind_double(pStmt, i, r);
drhdf0bdda2005-06-25 19:31:48 +00001613 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
1614 Tcl_WideInt v;
1615 Tcl_GetWideIntFromObj(interp, pVar, &v);
1616 sqlite3_bind_int64(pStmt, i, v);
drh92febd92004-08-20 18:34:20 +00001617 }else{
danielk197700fd9572005-12-07 06:27:43 +00001618 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1619 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001620 Tcl_IncrRefCount(pVar);
1621 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001622 }
drhfb7e7652005-01-24 00:28:42 +00001623 }else{
1624 sqlite3_bind_null( pStmt, i );
drh92febd92004-08-20 18:34:20 +00001625 }
1626 }
1627 }
drh92febd92004-08-20 18:34:20 +00001628
1629 /* Compute column names */
1630 nCol = sqlite3_column_count(pStmt);
1631 if( pScript ){
1632 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1633 if( apColName==0 ) break;
1634 for(i=0; i<nCol; i++){
1635 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1636 Tcl_IncrRefCount(apColName[i]);
1637 }
1638 }
1639
1640 /* If results are being stored in an array variable, then create
1641 ** the array(*) entry for that array
1642 */
1643 if( pArray ){
1644 Tcl_Obj *pColList = Tcl_NewObj();
drh3ced14a2005-03-31 18:26:20 +00001645 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
drh92febd92004-08-20 18:34:20 +00001646 Tcl_IncrRefCount(pColList);
1647 for(i=0; i<nCol; i++){
1648 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1649 }
drh3ced14a2005-03-31 18:26:20 +00001650 Tcl_ObjSetVar2(interp, pArray, pStar, pColList,0);
1651 Tcl_DecrRefCount(pColList);
1652 Tcl_DecrRefCount(pStar);
drh92febd92004-08-20 18:34:20 +00001653 }
1654
1655 /* Execute the SQL
1656 */
drh90b6bb12004-09-13 13:16:31 +00001657 while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
drh92febd92004-08-20 18:34:20 +00001658 for(i=0; i<nCol; i++){
danielk197730ccda12004-05-27 12:11:31 +00001659 Tcl_Obj *pVal;
1660
1661 /* Set pVal to contain the i'th column of this row. */
drh92febd92004-08-20 18:34:20 +00001662 switch( sqlite3_column_type(pStmt, i) ){
1663 case SQLITE_BLOB: {
1664 int bytes = sqlite3_column_bytes(pStmt, i);
1665 pVal = Tcl_NewByteArrayObj(sqlite3_column_blob(pStmt, i), bytes);
1666 break;
1667 }
1668 case SQLITE_INTEGER: {
1669 sqlite_int64 v = sqlite3_column_int64(pStmt, i);
1670 if( v>=-2147483647 && v<=2147483647 ){
1671 pVal = Tcl_NewIntObj(v);
1672 }else{
1673 pVal = Tcl_NewWideIntObj(v);
1674 }
1675 break;
1676 }
1677 case SQLITE_FLOAT: {
1678 double r = sqlite3_column_double(pStmt, i);
1679 pVal = Tcl_NewDoubleObj(r);
1680 break;
1681 }
danielk197755c45f22005-04-03 23:54:43 +00001682 case SQLITE_NULL: {
1683 pVal = dbTextToObj(pDb->zNull);
1684 break;
1685 }
drh92febd92004-08-20 18:34:20 +00001686 default: {
danielk197700fd9572005-12-07 06:27:43 +00001687 pVal = dbTextToObj((char *)sqlite3_column_text(pStmt, i));
drh92febd92004-08-20 18:34:20 +00001688 break;
1689 }
danielk197730ccda12004-05-27 12:11:31 +00001690 }
1691
drh92febd92004-08-20 18:34:20 +00001692 if( pScript ){
1693 if( pArray==0 ){
1694 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001695 }else{
drh92febd92004-08-20 18:34:20 +00001696 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001697 }
drh1807ce32004-09-07 13:20:35 +00001698 }else if( choice==DB_ONECOLUMN ){
drh97f2ebc2005-12-10 21:19:04 +00001699 assert( pRet==0 );
drh1807ce32004-09-07 13:20:35 +00001700 if( pRet==0 ){
1701 pRet = pVal;
1702 Tcl_IncrRefCount(pRet);
1703 }
drh90b6bb12004-09-13 13:16:31 +00001704 rc = TCL_BREAK;
drh97f2ebc2005-12-10 21:19:04 +00001705 i = nCol;
1706 }else if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001707 Tcl_DecrRefCount(pRet);
1708 pRet = Tcl_NewBooleanObj(1);
1709 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001710 rc = TCL_BREAK;
1711 i = nCol;
danielk197730ccda12004-05-27 12:11:31 +00001712 }else{
danielk197730ccda12004-05-27 12:11:31 +00001713 Tcl_ListObjAppendElement(interp, pRet, pVal);
1714 }
1715 }
1716
drh92febd92004-08-20 18:34:20 +00001717 if( pScript ){
1718 rc = Tcl_EvalObjEx(interp, pScript, 0);
drh90b6bb12004-09-13 13:16:31 +00001719 if( rc==TCL_CONTINUE ){
1720 rc = TCL_OK;
1721 }
danielk197730ccda12004-05-27 12:11:31 +00001722 }
1723 }
drh90b6bb12004-09-13 13:16:31 +00001724 if( rc==TCL_BREAK ){
1725 rc = TCL_OK;
1726 }
drh92febd92004-08-20 18:34:20 +00001727
1728 /* Free the column name objects */
1729 if( pScript ){
1730 for(i=0; i<nCol; i++){
1731 Tcl_DecrRefCount(apColName[i]);
1732 }
1733 Tcl_Free((char*)apColName);
1734 }
1735
drh1d895032004-08-26 00:56:05 +00001736 /* Free the bound string and blob parameters */
1737 for(i=0; i<nParm; i++){
1738 Tcl_DecrRefCount(apParm[i]);
1739 }
1740 if( apParm!=aParm ){
1741 Tcl_Free((char*)apParm);
1742 }
1743
drhfb7e7652005-01-24 00:28:42 +00001744 /* Reset the statement. If the result code is SQLITE_SCHEMA, then
1745 ** flush the statement cache and try the statement again.
drh92febd92004-08-20 18:34:20 +00001746 */
drhfb7e7652005-01-24 00:28:42 +00001747 rc2 = sqlite3_reset(pStmt);
1748 if( SQLITE_SCHEMA==rc2 ){
1749 /* After a schema change, flush the cache and try to run the
1750 ** statement again
1751 */
1752 flushStmtCache( pDb );
1753 sqlite3_finalize(pStmt);
1754 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001755 continue;
drhfb7e7652005-01-24 00:28:42 +00001756 }else if( SQLITE_OK!=rc2 ){
1757 /* If a run-time error occurs, report the error and stop reading
1758 ** the SQL
1759 */
danielk1977ef2cb632004-05-29 02:37:19 +00001760 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
drhfb7e7652005-01-24 00:28:42 +00001761 sqlite3_finalize(pStmt);
danielk197730ccda12004-05-27 12:11:31 +00001762 rc = TCL_ERROR;
drhfb7e7652005-01-24 00:28:42 +00001763 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001764 break;
drhfb7e7652005-01-24 00:28:42 +00001765 }else if( pDb->maxStmt<=0 ){
1766 /* If the cache is turned off, deallocated the statement */
1767 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1768 sqlite3_finalize(pStmt);
1769 }else{
1770 /* Everything worked and the cache is operational.
1771 ** Create a new SqlPreparedStmt structure if we need one.
1772 ** (If we already have one we can just reuse it.)
1773 */
1774 if( pPreStmt==0 ){
1775 len = zLeft - zSql;
1776 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) + len );
1777 if( pPreStmt==0 ) return TCL_ERROR;
1778 pPreStmt->pStmt = pStmt;
1779 pPreStmt->nSql = len;
1780 memcpy(pPreStmt->zSql, zSql, len);
1781 pPreStmt->zSql[len] = 0;
1782 }
1783
1784 /* Add the prepared statement to the beginning of the cache list
1785 */
1786 pPreStmt->pNext = pDb->stmtList;
1787 pPreStmt->pPrev = 0;
1788 if( pDb->stmtList ){
1789 pDb->stmtList->pPrev = pPreStmt;
1790 }
1791 pDb->stmtList = pPreStmt;
1792 if( pDb->stmtLast==0 ){
1793 assert( pDb->nStmt==0 );
1794 pDb->stmtLast = pPreStmt;
1795 }else{
1796 assert( pDb->nStmt>0 );
1797 }
1798 pDb->nStmt++;
1799
1800 /* If we have too many statement in cache, remove the surplus from the
1801 ** end of the cache list.
1802 */
1803 while( pDb->nStmt>pDb->maxStmt ){
1804 sqlite3_finalize(pDb->stmtLast->pStmt);
1805 pDb->stmtLast = pDb->stmtLast->pPrev;
1806 Tcl_Free((char*)pDb->stmtLast->pNext);
1807 pDb->stmtLast->pNext = 0;
1808 pDb->nStmt--;
1809 }
danielk197730ccda12004-05-27 12:11:31 +00001810 }
1811
drhfb7e7652005-01-24 00:28:42 +00001812 /* Proceed to the next statement */
danielk197730ccda12004-05-27 12:11:31 +00001813 zSql = zLeft;
1814 }
drh1d895032004-08-26 00:56:05 +00001815 Tcl_DecrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001816
drh1807ce32004-09-07 13:20:35 +00001817 if( pRet ){
1818 if( rc==TCL_OK ){
1819 Tcl_SetObjResult(interp, pRet);
1820 }
1821 Tcl_DecrRefCount(pRet);
drh050be322006-07-12 00:18:40 +00001822 }else if( rc==TCL_OK ){
1823 Tcl_ResetResult(interp);
danielk197730ccda12004-05-27 12:11:31 +00001824 }
danielk197730ccda12004-05-27 12:11:31 +00001825 break;
1826 }
drhbec3f402000-08-04 13:49:02 +00001827
1828 /*
drhcabb0812002-09-14 13:47:32 +00001829 ** $db function NAME SCRIPT
1830 **
1831 ** Create a new SQL function called NAME. Whenever that function is
1832 ** called, invoke SCRIPT to evaluate the function.
1833 */
1834 case DB_FUNCTION: {
1835 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00001836 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00001837 char *zName;
drhcabb0812002-09-14 13:47:32 +00001838 if( objc!=4 ){
1839 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1840 return TCL_ERROR;
1841 }
1842 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00001843 pScript = objv[3];
1844 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00001845 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00001846 if( pFunc->pScript ){
1847 Tcl_DecrRefCount(pFunc->pScript);
1848 }
1849 pFunc->pScript = pScript;
1850 Tcl_IncrRefCount(pScript);
1851 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
danielk1977c8c11582004-06-29 13:41:21 +00001852 rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00001853 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00001854 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00001855 rc = TCL_ERROR;
1856 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00001857 }else{
1858 /* Must flush any cached statements */
1859 flushStmtCache( pDb );
1860 }
drhcabb0812002-09-14 13:47:32 +00001861 break;
1862 }
1863
1864 /*
danielk19778cbadb02007-05-03 16:31:26 +00001865 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00001866 */
1867 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00001868#ifdef SQLITE_OMIT_INCRBLOB
1869 Tcl_AppendResult(interp, "incrblob not available in this build", 0);
1870 return TCL_ERROR;
1871#else
danielk19778cbadb02007-05-03 16:31:26 +00001872 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00001873 const char *zDb = "main";
1874 const char *zTable;
1875 const char *zColumn;
1876 sqlite_int64 iRow;
1877
danielk19778cbadb02007-05-03 16:31:26 +00001878 /* Check for the -readonly option */
1879 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
1880 isReadonly = 1;
1881 }
1882
1883 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
1884 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00001885 return TCL_ERROR;
1886 }
1887
danielk19778cbadb02007-05-03 16:31:26 +00001888 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00001889 zDb = Tcl_GetString(objv[2]);
1890 }
1891 zTable = Tcl_GetString(objv[objc-3]);
1892 zColumn = Tcl_GetString(objv[objc-2]);
1893 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
1894
1895 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00001896 rc = createIncrblobChannel(
1897 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
1898 );
danielk1977b4e9af92007-05-01 17:49:49 +00001899 }
danielk197732a0d8b2007-05-04 19:03:02 +00001900#endif
danielk1977b4e9af92007-05-01 17:49:49 +00001901 break;
1902 }
1903
1904 /*
drhf11bded2006-07-17 00:02:44 +00001905 ** $db interrupt
1906 **
1907 ** Interrupt the execution of the inner-most SQL interpreter. This
1908 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
1909 */
1910 case DB_INTERRUPT: {
1911 sqlite3_interrupt(pDb->db);
1912 break;
1913 }
1914
1915 /*
drh19e2d372005-08-29 23:00:03 +00001916 ** $db nullvalue ?STRING?
1917 **
1918 ** Change text used when a NULL comes back from the database. If ?STRING?
1919 ** is not present, then the current string used for NULL is returned.
1920 ** If STRING is present, then STRING is returned.
1921 **
1922 */
1923 case DB_NULLVALUE: {
1924 if( objc!=2 && objc!=3 ){
1925 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
1926 return TCL_ERROR;
1927 }
1928 if( objc==3 ){
1929 int len;
1930 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
1931 if( pDb->zNull ){
1932 Tcl_Free(pDb->zNull);
1933 }
1934 if( zNull && len>0 ){
1935 pDb->zNull = Tcl_Alloc( len + 1 );
1936 strncpy(pDb->zNull, zNull, len);
1937 pDb->zNull[len] = '\0';
1938 }else{
1939 pDb->zNull = 0;
1940 }
1941 }
1942 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
1943 break;
1944 }
1945
1946 /*
drhaf9ff332002-01-16 21:00:27 +00001947 ** $db last_insert_rowid
1948 **
1949 ** Return an integer which is the ROWID for the most recent insert.
1950 */
1951 case DB_LAST_INSERT_ROWID: {
1952 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00001953 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00001954 if( objc!=2 ){
1955 Tcl_WrongNumArgs(interp, 2, objv, "");
1956 return TCL_ERROR;
1957 }
danielk19776f8a5032004-05-10 10:34:51 +00001958 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00001959 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00001960 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00001961 break;
1962 }
1963
1964 /*
drh1807ce32004-09-07 13:20:35 +00001965 ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
drh5d9d7572003-08-19 14:31:01 +00001966 */
drh1807ce32004-09-07 13:20:35 +00001967
1968 /* $db progress ?N CALLBACK?
1969 **
1970 ** Invoke the given callback every N virtual machine opcodes while executing
1971 ** queries.
1972 */
1973 case DB_PROGRESS: {
1974 if( objc==2 ){
1975 if( pDb->zProgress ){
1976 Tcl_AppendResult(interp, pDb->zProgress, 0);
1977 }
1978 }else if( objc==4 ){
1979 char *zProgress;
1980 int len;
1981 int N;
1982 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
1983 return TCL_ERROR;
1984 };
1985 if( pDb->zProgress ){
1986 Tcl_Free(pDb->zProgress);
1987 }
1988 zProgress = Tcl_GetStringFromObj(objv[3], &len);
1989 if( zProgress && len>0 ){
1990 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001991 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00001992 }else{
1993 pDb->zProgress = 0;
1994 }
1995#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1996 if( pDb->zProgress ){
1997 pDb->interp = interp;
1998 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
1999 }else{
2000 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2001 }
2002#endif
2003 }else{
2004 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002005 return TCL_ERROR;
2006 }
drh5d9d7572003-08-19 14:31:01 +00002007 break;
2008 }
2009
drh19e2d372005-08-29 23:00:03 +00002010 /* $db profile ?CALLBACK?
2011 **
2012 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2013 ** that has run. The text of the SQL and the amount of elapse time are
2014 ** appended to CALLBACK before the script is run.
2015 */
2016 case DB_PROFILE: {
2017 if( objc>3 ){
2018 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2019 return TCL_ERROR;
2020 }else if( objc==2 ){
2021 if( pDb->zProfile ){
2022 Tcl_AppendResult(interp, pDb->zProfile, 0);
2023 }
2024 }else{
2025 char *zProfile;
2026 int len;
2027 if( pDb->zProfile ){
2028 Tcl_Free(pDb->zProfile);
2029 }
2030 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2031 if( zProfile && len>0 ){
2032 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002033 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002034 }else{
2035 pDb->zProfile = 0;
2036 }
2037#ifndef SQLITE_OMIT_TRACE
2038 if( pDb->zProfile ){
2039 pDb->interp = interp;
2040 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2041 }else{
2042 sqlite3_profile(pDb->db, 0, 0);
2043 }
2044#endif
2045 }
2046 break;
2047 }
2048
drh5d9d7572003-08-19 14:31:01 +00002049 /*
drh22fbcb82004-02-01 01:22:50 +00002050 ** $db rekey KEY
2051 **
2052 ** Change the encryption key on the currently open database.
2053 */
2054 case DB_REKEY: {
2055 int nKey;
2056 void *pKey;
2057 if( objc!=3 ){
2058 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2059 return TCL_ERROR;
2060 }
2061 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00002062#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00002063 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002064 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00002065 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002066 rc = TCL_ERROR;
2067 }
2068#endif
2069 break;
2070 }
2071
2072 /*
drhbec3f402000-08-04 13:49:02 +00002073 ** $db timeout MILLESECONDS
2074 **
2075 ** Delay for the number of milliseconds specified when a file is locked.
2076 */
drh6d313162000-09-21 13:01:35 +00002077 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002078 int ms;
drh6d313162000-09-21 13:01:35 +00002079 if( objc!=3 ){
2080 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002081 return TCL_ERROR;
2082 }
drh6d313162000-09-21 13:01:35 +00002083 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002084 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002085 break;
drh75897232000-05-29 14:26:00 +00002086 }
danielk197755c45f22005-04-03 23:54:43 +00002087
2088 /*
drh0f14e2e2004-06-29 12:39:08 +00002089 ** $db total_changes
2090 **
2091 ** Return the number of rows that were modified, inserted, or deleted
2092 ** since the database handle was created.
2093 */
2094 case DB_TOTAL_CHANGES: {
2095 Tcl_Obj *pResult;
2096 if( objc!=2 ){
2097 Tcl_WrongNumArgs(interp, 2, objv, "");
2098 return TCL_ERROR;
2099 }
2100 pResult = Tcl_GetObjResult(interp);
2101 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2102 break;
2103 }
2104
drhb5a20d32003-04-23 12:25:23 +00002105 /* $db trace ?CALLBACK?
2106 **
2107 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2108 ** that is executed. The text of the SQL is appended to CALLBACK before
2109 ** it is executed.
2110 */
2111 case DB_TRACE: {
2112 if( objc>3 ){
2113 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002114 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002115 }else if( objc==2 ){
2116 if( pDb->zTrace ){
2117 Tcl_AppendResult(interp, pDb->zTrace, 0);
2118 }
2119 }else{
2120 char *zTrace;
2121 int len;
2122 if( pDb->zTrace ){
2123 Tcl_Free(pDb->zTrace);
2124 }
2125 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2126 if( zTrace && len>0 ){
2127 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002128 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002129 }else{
2130 pDb->zTrace = 0;
2131 }
drh19e2d372005-08-29 23:00:03 +00002132#ifndef SQLITE_OMIT_TRACE
drhb5a20d32003-04-23 12:25:23 +00002133 if( pDb->zTrace ){
2134 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002135 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002136 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002137 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002138 }
drh19e2d372005-08-29 23:00:03 +00002139#endif
drhb5a20d32003-04-23 12:25:23 +00002140 }
2141 break;
2142 }
2143
drh3d214232005-08-02 12:21:08 +00002144 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2145 **
2146 ** Start a new transaction (if we are not already in the midst of a
2147 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2148 ** completes, either commit the transaction or roll it back if SCRIPT
2149 ** throws an exception. Or if no new transation was started, do nothing.
2150 ** pass the exception on up the stack.
2151 **
2152 ** This command was inspired by Dave Thomas's talk on Ruby at the
2153 ** 2005 O'Reilly Open Source Convention (OSCON).
2154 */
2155 case DB_TRANSACTION: {
2156 int inTrans;
2157 Tcl_Obj *pScript;
2158 const char *zBegin = "BEGIN";
2159 if( objc!=3 && objc!=4 ){
2160 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2161 return TCL_ERROR;
2162 }
2163 if( objc==3 ){
2164 pScript = objv[2];
2165 } else {
2166 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002167 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002168 };
2169 enum TTYPE_enum {
2170 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2171 };
2172 int ttype;
drhb5555e72005-08-02 17:15:14 +00002173 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002174 0, &ttype) ){
2175 return TCL_ERROR;
2176 }
2177 switch( (enum TTYPE_enum)ttype ){
2178 case TTYPE_DEFERRED: /* no-op */; break;
2179 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2180 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2181 }
2182 pScript = objv[3];
2183 }
2184 inTrans = !sqlite3_get_autocommit(pDb->db);
2185 if( !inTrans ){
drh37527852006-03-16 16:19:56 +00002186 (void)sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
drh3d214232005-08-02 12:21:08 +00002187 }
2188 rc = Tcl_EvalObjEx(interp, pScript, 0);
2189 if( !inTrans ){
2190 const char *zEnd;
2191 if( rc==TCL_ERROR ){
2192 zEnd = "ROLLBACK";
2193 } else {
2194 zEnd = "COMMIT";
2195 }
drh37527852006-03-16 16:19:56 +00002196 (void)sqlite3_exec(pDb->db, zEnd, 0, 0, 0);
drh3d214232005-08-02 12:21:08 +00002197 }
2198 break;
2199 }
2200
danielk197794eb6a12005-12-15 15:22:08 +00002201 /*
2202 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002203 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002204 */
danielk197771fd80b2005-12-16 06:54:01 +00002205 case DB_UPDATE_HOOK:
2206 case DB_ROLLBACK_HOOK: {
2207
2208 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2209 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2210 */
2211 Tcl_Obj **ppHook;
2212 if( choice==DB_UPDATE_HOOK ){
2213 ppHook = &pDb->pUpdateHook;
2214 }else{
2215 ppHook = &pDb->pRollbackHook;
2216 }
2217
danielk197794eb6a12005-12-15 15:22:08 +00002218 if( objc!=2 && objc!=3 ){
2219 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2220 return TCL_ERROR;
2221 }
danielk197771fd80b2005-12-16 06:54:01 +00002222 if( *ppHook ){
2223 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002224 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002225 Tcl_DecrRefCount(*ppHook);
2226 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00002227 }
2228 }
2229 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002230 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00002231 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00002232 *ppHook = objv[2];
2233 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002234 }
2235 }
danielk197771fd80b2005-12-16 06:54:01 +00002236
2237 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2238 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
2239
danielk197794eb6a12005-12-15 15:22:08 +00002240 break;
2241 }
2242
danielk19774397de52005-01-12 12:44:03 +00002243 /* $db version
2244 **
2245 ** Return the version string for this database.
2246 */
2247 case DB_VERSION: {
2248 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2249 break;
2250 }
2251
tpoindex1067fe12004-12-17 15:41:11 +00002252
drh6d313162000-09-21 13:01:35 +00002253 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002254 return rc;
drh75897232000-05-29 14:26:00 +00002255}
2256
2257/*
drh9bb575f2004-09-06 17:24:11 +00002258** sqlite3 DBNAME FILENAME ?MODE? ?-key KEY?
drh75897232000-05-29 14:26:00 +00002259**
2260** This is the main Tcl command. When the "sqlite" Tcl command is
2261** invoked, this routine runs to process that command.
2262**
2263** The first argument, DBNAME, is an arbitrary name for a new
2264** database connection. This command creates a new command named
2265** DBNAME that is used to control that connection. The database
2266** connection is deleted when the DBNAME command is deleted.
2267**
2268** The second argument is the name of the directory that contains
2269** the sqlite database that is to be accessed.
drhfbc3eab2001-04-06 16:13:42 +00002270**
2271** For testing purposes, we also support the following:
2272**
drh9bb575f2004-09-06 17:24:11 +00002273** sqlite3 -encoding
drhfbc3eab2001-04-06 16:13:42 +00002274**
2275** Return the encoding used by LIKE and GLOB operators. Choices
2276** are UTF-8 and iso8859.
2277**
drh9bb575f2004-09-06 17:24:11 +00002278** sqlite3 -version
drh647cb0e2002-11-04 19:32:25 +00002279**
2280** Return the version number of the SQLite library.
2281**
drh9bb575f2004-09-06 17:24:11 +00002282** sqlite3 -tcl-uses-utf
drhfbc3eab2001-04-06 16:13:42 +00002283**
2284** Return "1" if compiled with a Tcl uses UTF-8. Return "0" if
2285** not. Used by tests to make sure the library was compiled
2286** correctly.
drh75897232000-05-29 14:26:00 +00002287*/
drh22fbcb82004-02-01 01:22:50 +00002288static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002289 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002290 void *pKey = 0;
2291 int nKey = 0;
2292 const char *zArg;
drh75897232000-05-29 14:26:00 +00002293 char *zErrMsg;
drh22fbcb82004-02-01 01:22:50 +00002294 const char *zFile;
drh882e8e42006-08-24 02:42:27 +00002295 Tcl_DString translatedFilename;
drh22fbcb82004-02-01 01:22:50 +00002296 if( objc==2 ){
2297 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002298 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00002299 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00002300 return TCL_OK;
2301 }
drh9eb9e262004-02-11 02:18:05 +00002302 if( strcmp(zArg,"-has-codec")==0 ){
2303#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002304 Tcl_AppendResult(interp,"1",0);
2305#else
2306 Tcl_AppendResult(interp,"0",0);
2307#endif
2308 return TCL_OK;
2309 }
2310 if( strcmp(zArg,"-tcl-uses-utf")==0 ){
drhfbc3eab2001-04-06 16:13:42 +00002311#ifdef TCL_UTF_MAX
2312 Tcl_AppendResult(interp,"1",0);
2313#else
2314 Tcl_AppendResult(interp,"0",0);
2315#endif
2316 return TCL_OK;
2317 }
2318 }
drh22fbcb82004-02-01 01:22:50 +00002319 if( objc==5 || objc==6 ){
2320 zArg = Tcl_GetStringFromObj(objv[objc-2], 0);
2321 if( strcmp(zArg,"-key")==0 ){
2322 pKey = Tcl_GetByteArrayFromObj(objv[objc-1], &nKey);
2323 objc -= 2;
2324 }
2325 }
2326 if( objc!=3 && objc!=4 ){
2327 Tcl_WrongNumArgs(interp, 1, objv,
drh9eb9e262004-02-11 02:18:05 +00002328#ifdef SQLITE_HAS_CODEC
2329 "HANDLE FILENAME ?-key CODEC-KEY?"
drh22fbcb82004-02-01 01:22:50 +00002330#else
2331 "HANDLE FILENAME ?MODE?"
2332#endif
2333 );
drh75897232000-05-29 14:26:00 +00002334 return TCL_ERROR;
2335 }
drh75897232000-05-29 14:26:00 +00002336 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00002337 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00002338 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00002339 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
2340 return TCL_ERROR;
2341 }
2342 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00002343 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00002344 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
danielk19774f057f92004-06-08 00:02:33 +00002345 sqlite3_open(zFile, &p->db);
drh882e8e42006-08-24 02:42:27 +00002346 Tcl_DStringFree(&translatedFilename);
danielk197780290862004-05-22 09:21:21 +00002347 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
drh9404d502006-12-19 18:46:08 +00002348 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
danielk197780290862004-05-22 09:21:21 +00002349 sqlite3_close(p->db);
2350 p->db = 0;
2351 }
drh2011d5f2004-07-22 02:40:37 +00002352#ifdef SQLITE_HAS_CODEC
2353 sqlite3_key(p->db, pKey, nKey);
drheb8ed702004-02-11 10:37:23 +00002354#endif
drhbec3f402000-08-04 13:49:02 +00002355 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00002356 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00002357 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00002358 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00002359 return TCL_ERROR;
2360 }
drhfb7e7652005-01-24 00:28:42 +00002361 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00002362 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00002363 zArg = Tcl_GetStringFromObj(objv[1], 0);
2364 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
drhc22bd472002-05-10 13:14:07 +00002365
2366 /* If compiled with SQLITE_TEST turned on, then register the "md5sum"
drh06b27182002-06-26 20:06:05 +00002367 ** SQL function.
drhc22bd472002-05-10 13:14:07 +00002368 */
drh28b4e482002-03-11 02:06:13 +00002369#ifdef SQLITE_TEST
2370 {
drh9bb575f2004-09-06 17:24:11 +00002371 extern void Md5_Register(sqlite3*);
drh3b93bc82005-01-13 23:54:32 +00002372#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00002373 int mallocfail = sqlite3_iMallocFail;
2374 sqlite3_iMallocFail = 0;
danielk19775b59af82004-06-30 12:42:59 +00002375#endif
drhc22bd472002-05-10 13:14:07 +00002376 Md5_Register(p->db);
drh3b93bc82005-01-13 23:54:32 +00002377#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00002378 sqlite3_iMallocFail = mallocfail;
danielk19775b59af82004-06-30 12:42:59 +00002379#endif
danielk19777ddad962005-12-12 06:53:03 +00002380 }
drh28b4e482002-03-11 02:06:13 +00002381#endif
drh75897232000-05-29 14:26:00 +00002382 return TCL_OK;
2383}
2384
2385/*
drh90ca9752001-09-28 17:47:14 +00002386** Provide a dummy Tcl_InitStubs if we are using this as a static
2387** library.
2388*/
2389#ifndef USE_TCL_STUBS
2390# undef Tcl_InitStubs
2391# define Tcl_InitStubs(a,b,c)
2392#endif
2393
2394/*
drh29bc4612005-10-05 10:40:15 +00002395** Make sure we have a PACKAGE_VERSION macro defined. This will be
2396** defined automatically by the TEA makefile. But other makefiles
2397** do not define it.
2398*/
2399#ifndef PACKAGE_VERSION
2400# define PACKAGE_VERSION SQLITE_VERSION
2401#endif
2402
2403/*
drh75897232000-05-29 14:26:00 +00002404** Initialize this module.
2405**
2406** This Tcl module contains only a single new Tcl command named "sqlite".
2407** (Hence there is no namespace. There is no point in using a namespace
2408** if the extension only supplies one new name!) The "sqlite" command is
2409** used to open a new SQLite database. See the DbMain() routine above
2410** for additional information.
2411*/
drhad6e1372006-07-10 21:15:51 +00002412EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00002413 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00002414 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002415 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh49766d62005-01-08 18:42:28 +00002416 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002417 Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
drh90ca9752001-09-28 17:47:14 +00002418 return TCL_OK;
2419}
drhad6e1372006-07-10 21:15:51 +00002420EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2421EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2422EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002423
2424#ifndef SQLITE_3_SUFFIX_ONLY
drhad6e1372006-07-10 21:15:51 +00002425EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2426EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2427EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2428EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002429#endif
drh75897232000-05-29 14:26:00 +00002430
drh3e27c022004-07-23 00:01:38 +00002431#ifdef TCLSH
2432/*****************************************************************************
2433** The code that follows is used to build standalone TCL interpreters
drh75897232000-05-29 14:26:00 +00002434*/
drh348784e2000-05-29 20:41:49 +00002435
2436/*
drh3e27c022004-07-23 00:01:38 +00002437** If the macro TCLSH is one, then put in code this for the
2438** "main" routine that will initialize Tcl and take input from
2439** standard input.
drh348784e2000-05-29 20:41:49 +00002440*/
drh3e27c022004-07-23 00:01:38 +00002441#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00002442static char zMainloop[] =
2443 "set line {}\n"
2444 "while {![eof stdin]} {\n"
2445 "if {$line!=\"\"} {\n"
2446 "puts -nonewline \"> \"\n"
2447 "} else {\n"
2448 "puts -nonewline \"% \"\n"
2449 "}\n"
2450 "flush stdout\n"
2451 "append line [gets stdin]\n"
2452 "if {[info complete $line]} {\n"
2453 "if {[catch {uplevel #0 $line} result]} {\n"
2454 "puts stderr \"Error: $result\"\n"
2455 "} elseif {$result!=\"\"} {\n"
2456 "puts $result\n"
2457 "}\n"
2458 "set line {}\n"
2459 "} else {\n"
2460 "append line \\n\n"
2461 "}\n"
2462 "}\n"
2463;
drh3e27c022004-07-23 00:01:38 +00002464#endif
2465
2466/*
2467** If the macro TCLSH is two, then get the main loop code out of
2468** the separate file "spaceanal_tcl.h".
2469*/
2470#if TCLSH==2
2471static char zMainloop[] =
2472#include "spaceanal_tcl.h"
2473;
2474#endif
drh348784e2000-05-29 20:41:49 +00002475
2476#define TCLSH_MAIN main /* Needed to fake out mktclapp */
2477int TCLSH_MAIN(int argc, char **argv){
2478 Tcl_Interp *interp;
drh297ecf12001-04-05 15:57:13 +00002479 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00002480 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00002481 Sqlite3_Init(interp);
drhd9b02572001-04-15 00:37:09 +00002482#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00002483 {
2484 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00002485 extern int Sqlitetest2_Init(Tcl_Interp*);
2486 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00002487 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00002488 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00002489 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00002490 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00002491 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00002492 extern int Sqlitetest9_Init(Tcl_Interp*);
drhefc251d2001-07-01 22:12:01 +00002493 extern int Md5_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002494 extern int Sqlitetestsse_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00002495 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh4be8b512006-06-13 23:51:34 +00002496 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk1977954ce992006-06-15 15:59:19 +00002497 extern int Sqlitetestschema_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00002498 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00002499 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
drhc797d4d2007-05-08 01:08:49 +00002500 extern int Sqliteconfig_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002501
danielk19776490beb2004-05-11 06:17:21 +00002502 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00002503 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00002504 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00002505 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00002506 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00002507 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00002508 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00002509 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00002510 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00002511 Sqlitetestasync_Init(interp);
drh4be8b512006-06-13 23:51:34 +00002512 Sqlitetesttclvar_Init(interp);
danielk1977954ce992006-06-15 15:59:19 +00002513 Sqlitetestschema_Init(interp);
drh1409be62006-08-23 20:07:20 +00002514 Sqlitetest_autoext_Init(interp);
drh15926592007-04-06 15:02:13 +00002515 Sqlitetest_hexio_Init(interp);
drhc797d4d2007-05-08 01:08:49 +00002516 Sqliteconfig_Init(interp);
drhefc251d2001-07-01 22:12:01 +00002517 Md5_Init(interp);
drh89dec812005-04-28 19:03:37 +00002518#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00002519 Sqlitetestsse_Init(interp);
2520#endif
drhd1bf3512001-04-07 15:24:33 +00002521 }
2522#endif
drh3e27c022004-07-23 00:01:38 +00002523 if( argc>=2 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002524 int i;
shessad42c3a2006-08-22 23:53:46 +00002525 char zArgc[32];
2526 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
2527 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00002528 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
2529 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00002530 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00002531 Tcl_SetVar(interp, "argv", argv[i],
2532 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
2533 }
drh3e27c022004-07-23 00:01:38 +00002534 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00002535 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drhc61053b2000-06-04 12:58:36 +00002536 if( zInfo==0 ) zInfo = interp->result;
2537 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00002538 return 1;
2539 }
drh3e27c022004-07-23 00:01:38 +00002540 }
2541 if( argc<=1 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002542 Tcl_GlobalEval(interp, zMainloop);
2543 }
2544 return 0;
2545}
2546#endif /* TCLSH */