blob: 35a69b8c12989a321b5b39e2af1eb7cb022f12c9 [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**
danielk19779a6284c2008-07-10 17:52:49 +000015** $Id: tclsqlite.c,v 1.219 2008/07/10 17:52:49 danielk1977 Exp $
drh75897232000-05-29 14:26:00 +000016*/
drh17a68932001-01-31 13:28:08 +000017#include "tcl.h"
danielk1977b4e9af92007-05-01 17:49:49 +000018#include <errno.h>
drhbd08af42007-04-05 21:58:33 +000019
20/*
21** Some additional include files are needed if this file is not
22** appended to the amalgamation.
23*/
24#ifndef SQLITE_AMALGAMATION
25# include "sqliteInt.h"
drhbd08af42007-04-05 21:58:33 +000026# include <stdlib.h>
27# include <string.h>
28# include <assert.h>
29# include <ctype.h>
30#endif
drh75897232000-05-29 14:26:00 +000031
drhad6e1372006-07-10 21:15:51 +000032/*
33 * Windows needs to know which symbols to export. Unix does not.
34 * BUILD_sqlite should be undefined for Unix.
35 */
36#ifdef BUILD_sqlite
37#undef TCL_STORAGE_CLASS
38#define TCL_STORAGE_CLASS DLLEXPORT
39#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000040
danielk1977a21c6b62005-01-24 10:25:59 +000041#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000042#define MAX_PREPARED_STMTS 100
43
drh75897232000-05-29 14:26:00 +000044/*
drh98808ba2001-10-18 12:34:46 +000045** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
46** have to do a translation when going between the two. Set the
47** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
48** this translation.
49*/
50#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
51# define UTF_TRANSLATION_NEEDED 1
52#endif
53
54/*
drhcabb0812002-09-14 13:47:32 +000055** New SQL functions can be created as TCL scripts. Each such function
56** is described by an instance of the following structure.
57*/
58typedef struct SqlFunc SqlFunc;
59struct SqlFunc {
60 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000061 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
62 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
63 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000064 SqlFunc *pNext; /* Next function on the list of them all */
65};
66
67/*
danielk19770202b292004-06-09 09:55:16 +000068** New collation sequences function can be created as TCL scripts. Each such
69** function is described by an instance of the following structure.
70*/
71typedef struct SqlCollate SqlCollate;
72struct SqlCollate {
73 Tcl_Interp *interp; /* The TCL interpret to execute the function */
74 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000075 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000076};
77
78/*
drhfb7e7652005-01-24 00:28:42 +000079** Prepared statements are cached for faster execution. Each prepared
80** statement is described by an instance of the following structure.
81*/
82typedef struct SqlPreparedStmt SqlPreparedStmt;
83struct SqlPreparedStmt {
84 SqlPreparedStmt *pNext; /* Next in linked list */
85 SqlPreparedStmt *pPrev; /* Previous on the list */
86 sqlite3_stmt *pStmt; /* The prepared statement */
87 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +000088 const char *zSql; /* Text of the SQL statement */
drhfb7e7652005-01-24 00:28:42 +000089};
90
danielk1977d04417962007-05-02 13:16:30 +000091typedef struct IncrblobChannel IncrblobChannel;
92
drhfb7e7652005-01-24 00:28:42 +000093/*
drhbec3f402000-08-04 13:49:02 +000094** There is one instance of this structure for each SQLite database
95** that has been opened by the SQLite TCL interface.
96*/
97typedef struct SqliteDb SqliteDb;
98struct SqliteDb {
drhdddca282006-01-03 00:33:50 +000099 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000100 Tcl_Interp *interp; /* The interpreter used for this database */
101 char *zBusy; /* The busy callback routine */
102 char *zCommit; /* The commit hook callback routine */
103 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +0000104 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000105 char *zProgress; /* The progress callback routine */
106 char *zAuth; /* The authorization callback routine */
107 char *zNull; /* Text to substitute for an SQL NULL value */
108 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000109 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000110 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drhd1e47332005-06-26 17:55:33 +0000111 SqlCollate *pCollate; /* List of SQL collation functions */
112 int rc; /* Return code of most recent sqlite3_exec() */
113 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000114 SqlPreparedStmt *stmtList; /* List of prepared statements*/
115 SqlPreparedStmt *stmtLast; /* Last statement in the list */
116 int maxStmt; /* The next maximum number of stmtList */
117 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000118 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh98808ba2001-10-18 12:34:46 +0000119};
drh297ecf12001-04-05 15:57:13 +0000120
danielk1977b4e9af92007-05-01 17:49:49 +0000121struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000122 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000123 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000124 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000125 Tcl_Channel channel; /* Channel identifier */
126 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
127 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000128};
129
danielk197732a0d8b2007-05-04 19:03:02 +0000130#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000131/*
danielk1977d04417962007-05-02 13:16:30 +0000132** Close all incrblob channels opened using database connection pDb.
133** This is called when shutting down the database connection.
134*/
135static void closeIncrblobChannels(SqliteDb *pDb){
136 IncrblobChannel *p;
137 IncrblobChannel *pNext;
138
139 for(p=pDb->pIncrblob; p; p=pNext){
140 pNext = p->pNext;
141
142 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
143 ** which deletes the IncrblobChannel structure at *p. So do not
144 ** call Tcl_Free() here.
145 */
146 Tcl_UnregisterChannel(pDb->interp, p->channel);
147 }
148}
149
150/*
danielk1977b4e9af92007-05-01 17:49:49 +0000151** Close an incremental blob channel.
152*/
153static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
154 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000155 int rc = sqlite3_blob_close(p->pBlob);
156 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000157
158 /* Remove the channel from the SqliteDb.pIncrblob list. */
159 if( p->pNext ){
160 p->pNext->pPrev = p->pPrev;
161 }
162 if( p->pPrev ){
163 p->pPrev->pNext = p->pNext;
164 }
165 if( p->pDb->pIncrblob==p ){
166 p->pDb->pIncrblob = p->pNext;
167 }
168
danielk197792d4d7a2007-05-04 12:05:56 +0000169 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000170 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000171
172 if( rc!=SQLITE_OK ){
173 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
174 return TCL_ERROR;
175 }
danielk1977b4e9af92007-05-01 17:49:49 +0000176 return TCL_OK;
177}
178
179/*
180** Read data from an incremental blob channel.
181*/
182static int incrblobInput(
183 ClientData instanceData,
184 char *buf,
185 int bufSize,
186 int *errorCodePtr
187){
188 IncrblobChannel *p = (IncrblobChannel *)instanceData;
189 int nRead = bufSize; /* Number of bytes to read */
190 int nBlob; /* Total size of the blob */
191 int rc; /* sqlite error code */
192
193 nBlob = sqlite3_blob_bytes(p->pBlob);
194 if( (p->iSeek+nRead)>nBlob ){
195 nRead = nBlob-p->iSeek;
196 }
197 if( nRead<=0 ){
198 return 0;
199 }
200
201 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
202 if( rc!=SQLITE_OK ){
203 *errorCodePtr = rc;
204 return -1;
205 }
206
207 p->iSeek += nRead;
208 return nRead;
209}
210
danielk1977d04417962007-05-02 13:16:30 +0000211/*
212** Write data to an incremental blob channel.
213*/
danielk1977b4e9af92007-05-01 17:49:49 +0000214static int incrblobOutput(
215 ClientData instanceData,
216 CONST char *buf,
217 int toWrite,
218 int *errorCodePtr
219){
220 IncrblobChannel *p = (IncrblobChannel *)instanceData;
221 int nWrite = toWrite; /* Number of bytes to write */
222 int nBlob; /* Total size of the blob */
223 int rc; /* sqlite error code */
224
225 nBlob = sqlite3_blob_bytes(p->pBlob);
226 if( (p->iSeek+nWrite)>nBlob ){
227 *errorCodePtr = EINVAL;
228 return -1;
229 }
230 if( nWrite<=0 ){
231 return 0;
232 }
233
234 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
235 if( rc!=SQLITE_OK ){
236 *errorCodePtr = EIO;
237 return -1;
238 }
239
240 p->iSeek += nWrite;
241 return nWrite;
242}
243
244/*
245** Seek an incremental blob channel.
246*/
247static int incrblobSeek(
248 ClientData instanceData,
249 long offset,
250 int seekMode,
251 int *errorCodePtr
252){
253 IncrblobChannel *p = (IncrblobChannel *)instanceData;
254
255 switch( seekMode ){
256 case SEEK_SET:
257 p->iSeek = offset;
258 break;
259 case SEEK_CUR:
260 p->iSeek += offset;
261 break;
262 case SEEK_END:
263 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
264 break;
265
266 default: assert(!"Bad seekMode");
267 }
268
269 return p->iSeek;
270}
271
272
273static void incrblobWatch(ClientData instanceData, int mode){
274 /* NO-OP */
275}
276static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
277 return TCL_ERROR;
278}
279
280static Tcl_ChannelType IncrblobChannelType = {
281 "incrblob", /* typeName */
282 TCL_CHANNEL_VERSION_2, /* version */
283 incrblobClose, /* closeProc */
284 incrblobInput, /* inputProc */
285 incrblobOutput, /* outputProc */
286 incrblobSeek, /* seekProc */
287 0, /* setOptionProc */
288 0, /* getOptionProc */
289 incrblobWatch, /* watchProc (this is a no-op) */
290 incrblobHandle, /* getHandleProc (always returns error) */
291 0, /* close2Proc */
292 0, /* blockModeProc */
293 0, /* flushProc */
294 0, /* handlerProc */
295 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000296};
297
298/*
299** Create a new incrblob channel.
300*/
301static int createIncrblobChannel(
302 Tcl_Interp *interp,
303 SqliteDb *pDb,
304 const char *zDb,
305 const char *zTable,
306 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000307 sqlite_int64 iRow,
308 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000309){
310 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000311 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000312 sqlite3_blob *pBlob;
313 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000314 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000315
316 /* This variable is used to name the channels: "incrblob_[incr count]" */
317 static int count = 0;
318 char zChannel[64];
319
danielk19778cbadb02007-05-03 16:31:26 +0000320 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000321 if( rc!=SQLITE_OK ){
322 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
323 return TCL_ERROR;
324 }
325
326 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
327 p->iSeek = 0;
328 p->pBlob = pBlob;
329
drh5bb3eb92007-05-04 13:15:55 +0000330 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000331 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
332 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000333
danielk1977d04417962007-05-02 13:16:30 +0000334 /* Link the new channel into the SqliteDb.pIncrblob list. */
335 p->pNext = pDb->pIncrblob;
336 p->pPrev = 0;
337 if( p->pNext ){
338 p->pNext->pPrev = p;
339 }
340 pDb->pIncrblob = p;
341 p->pDb = pDb;
342
343 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000344 return TCL_OK;
345}
danielk197732a0d8b2007-05-04 19:03:02 +0000346#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
347 #define closeIncrblobChannels(pDb)
348#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000349
drh6d313162000-09-21 13:01:35 +0000350/*
drhd1e47332005-06-26 17:55:33 +0000351** Look at the script prefix in pCmd. We will be executing this script
352** after first appending one or more arguments. This routine analyzes
353** the script to see if it is safe to use Tcl_EvalObjv() on the script
354** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
355** faster.
356**
357** Scripts that are safe to use with Tcl_EvalObjv() consists of a
358** command name followed by zero or more arguments with no [...] or $
359** or {...} or ; to be seen anywhere. Most callback scripts consist
360** of just a single procedure name and they meet this requirement.
361*/
362static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
363 /* We could try to do something with Tcl_Parse(). But we will instead
364 ** just do a search for forbidden characters. If any of the forbidden
365 ** characters appear in pCmd, we will report the string as unsafe.
366 */
367 const char *z;
368 int n;
369 z = Tcl_GetStringFromObj(pCmd, &n);
370 while( n-- > 0 ){
371 int c = *(z++);
372 if( c=='$' || c=='[' || c==';' ) return 0;
373 }
374 return 1;
375}
376
377/*
378** Find an SqlFunc structure with the given name. Or create a new
379** one if an existing one cannot be found. Return a pointer to the
380** structure.
381*/
382static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
383 SqlFunc *p, *pNew;
384 int i;
385 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen(zName) + 1 );
386 pNew->zName = (char*)&pNew[1];
387 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
388 pNew->zName[i] = 0;
389 for(p=pDb->pFunc; p; p=p->pNext){
390 if( strcmp(p->zName, pNew->zName)==0 ){
391 Tcl_Free((char*)pNew);
392 return p;
393 }
394 }
395 pNew->interp = pDb->interp;
396 pNew->pScript = 0;
397 pNew->pNext = pDb->pFunc;
398 pDb->pFunc = pNew;
399 return pNew;
400}
401
402/*
drhfb7e7652005-01-24 00:28:42 +0000403** Finalize and free a list of prepared statements
404*/
405static void flushStmtCache( SqliteDb *pDb ){
406 SqlPreparedStmt *pPreStmt;
407
408 while( pDb->stmtList ){
409 sqlite3_finalize( pDb->stmtList->pStmt );
410 pPreStmt = pDb->stmtList;
411 pDb->stmtList = pDb->stmtList->pNext;
412 Tcl_Free( (char*)pPreStmt );
413 }
414 pDb->nStmt = 0;
415 pDb->stmtLast = 0;
416}
417
418/*
drh895d7472004-08-20 16:02:39 +0000419** TCL calls this procedure when an sqlite3 database command is
420** deleted.
drh75897232000-05-29 14:26:00 +0000421*/
422static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000423 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000424 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000425 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000426 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000427 while( pDb->pFunc ){
428 SqlFunc *pFunc = pDb->pFunc;
429 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000430 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000431 Tcl_Free((char*)pFunc);
432 }
danielk19770202b292004-06-09 09:55:16 +0000433 while( pDb->pCollate ){
434 SqlCollate *pCollate = pDb->pCollate;
435 pDb->pCollate = pCollate->pNext;
436 Tcl_Free((char*)pCollate);
437 }
drhbec3f402000-08-04 13:49:02 +0000438 if( pDb->zBusy ){
439 Tcl_Free(pDb->zBusy);
440 }
drhb5a20d32003-04-23 12:25:23 +0000441 if( pDb->zTrace ){
442 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000443 }
drh19e2d372005-08-29 23:00:03 +0000444 if( pDb->zProfile ){
445 Tcl_Free(pDb->zProfile);
446 }
drhe22a3342003-04-22 20:30:37 +0000447 if( pDb->zAuth ){
448 Tcl_Free(pDb->zAuth);
449 }
danielk197755c45f22005-04-03 23:54:43 +0000450 if( pDb->zNull ){
451 Tcl_Free(pDb->zNull);
452 }
danielk197794eb6a12005-12-15 15:22:08 +0000453 if( pDb->pUpdateHook ){
454 Tcl_DecrRefCount(pDb->pUpdateHook);
455 }
danielk197771fd80b2005-12-16 06:54:01 +0000456 if( pDb->pRollbackHook ){
457 Tcl_DecrRefCount(pDb->pRollbackHook);
458 }
danielk197794eb6a12005-12-15 15:22:08 +0000459 if( pDb->pCollateNeeded ){
460 Tcl_DecrRefCount(pDb->pCollateNeeded);
461 }
drhbec3f402000-08-04 13:49:02 +0000462 Tcl_Free((char*)pDb);
463}
464
465/*
466** This routine is called when a database file is locked while trying
467** to execute SQL.
468*/
danielk19772a764eb2004-06-12 01:43:26 +0000469static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000470 SqliteDb *pDb = (SqliteDb*)cd;
471 int rc;
472 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000473
drh5bb3eb92007-05-04 13:15:55 +0000474 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000475 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000476 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
477 return 0;
478 }
479 return 1;
drh75897232000-05-29 14:26:00 +0000480}
481
drh26e4a8b2008-05-01 17:16:52 +0000482#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000483/*
danielk1977348bb5d2003-10-18 09:37:26 +0000484** This routine is invoked as the 'progress callback' for the database.
485*/
486static int DbProgressHandler(void *cd){
487 SqliteDb *pDb = (SqliteDb*)cd;
488 int rc;
489
490 assert( pDb->zProgress );
491 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
492 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
493 return 1;
494 }
495 return 0;
496}
drh26e4a8b2008-05-01 17:16:52 +0000497#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000498
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);
drh985e0c62007-06-26 22:55:37 +0000725 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000726 Tcl_GetIntFromObj(0, pVar, &n);
727 sqlite3_result_int(context, n);
728 }else if( c=='d' && strcmp(zType,"double")==0 ){
729 double r;
730 Tcl_GetDoubleFromObj(0, pVar, &r);
731 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +0000732 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
733 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000734 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
danielk19778e556522007-11-13 10:30:24 +0000891
892/*
893** Figure out the column names for the data returned by the statement
894** passed as the second argument.
895**
896** If parameter papColName is not NULL, then *papColName is set to point
897** at an array allocated using Tcl_Alloc(). It is the callers responsibility
898** to free this array using Tcl_Free(), and to decrement the reference
899** count of each Tcl_Obj* member of the array.
900**
901** The return value of this function is the number of columns of data
902** returned by pStmt (and hence the size of the *papColName array).
903**
904** If pArray is not NULL, then it contains the name of a Tcl array
905** variable. The "*" member of this array is set to a list containing
906** the names of the columns returned by the statement, in order from
907** left to right. e.g. if the names of the returned columns are a, b and
908** c, it does the equivalent of the tcl command:
909**
910** set ${pArray}(*) {a b c}
911*/
912static int
913computeColumnNames(
914 Tcl_Interp *interp,
915 sqlite3_stmt *pStmt, /* SQL statement */
916 Tcl_Obj ***papColName, /* OUT: Array of column names */
917 Tcl_Obj *pArray /* Name of array variable (may be null) */
918){
919 int nCol;
920
921 /* Compute column names */
922 nCol = sqlite3_column_count(pStmt);
923 if( papColName ){
924 int i;
925 Tcl_Obj **apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
926 for(i=0; i<nCol; i++){
927 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
928 Tcl_IncrRefCount(apColName[i]);
929 }
930
931 /* If results are being stored in an array variable, then create
932 ** the array(*) entry for that array
933 */
934 if( pArray ){
935 Tcl_Obj *pColList = Tcl_NewObj();
936 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
937 Tcl_IncrRefCount(pColList);
938 for(i=0; i<nCol; i++){
939 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
940 }
941 Tcl_IncrRefCount(pStar);
942 Tcl_ObjSetVar2(interp, pArray, pStar, pColList,0);
943 Tcl_DecrRefCount(pColList);
944 Tcl_DecrRefCount(pStar);
945 }
946 *papColName = apColName;
947 }
948
949 return nCol;
950}
951
tpoindex1067fe12004-12-17 15:41:11 +0000952/*
drh75897232000-05-29 14:26:00 +0000953** The "sqlite" command below creates a new Tcl command for each
954** connection it opens to an SQLite database. This routine is invoked
955** whenever one of those connection-specific commands is executed
956** in Tcl. For example, if you run Tcl code like this:
957**
drh9bb575f2004-09-06 17:24:11 +0000958** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +0000959** db1 close
960**
961** The first command opens a connection to the "my_database" database
962** and calls that connection "db1". The second command causes this
963** subroutine to be invoked.
964*/
drh6d313162000-09-21 13:01:35 +0000965static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +0000966 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +0000967 int choice;
drh22fbcb82004-02-01 01:22:50 +0000968 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +0000969 static const char *DB_strs[] = {
drhfb7e7652005-01-24 00:28:42 +0000970 "authorizer", "busy", "cache",
971 "changes", "close", "collate",
972 "collation_needed", "commit_hook", "complete",
drh41449052006-07-06 17:08:48 +0000973 "copy", "enable_load_extension","errorcode",
974 "eval", "exists", "function",
drh59fffd02007-06-19 17:48:57 +0000975 "incrblob", "interrupt", "last_insert_rowid",
976 "nullvalue", "onecolumn", "profile",
977 "progress", "rekey", "rollback_hook",
978 "timeout", "total_changes", "trace",
979 "transaction", "update_hook", "version",
980 0
drh6d313162000-09-21 13:01:35 +0000981 };
drh411995d2002-06-25 19:31:18 +0000982 enum DB_enum {
drhfb7e7652005-01-24 00:28:42 +0000983 DB_AUTHORIZER, DB_BUSY, DB_CACHE,
984 DB_CHANGES, DB_CLOSE, DB_COLLATE,
985 DB_COLLATION_NEEDED, DB_COMMIT_HOOK, DB_COMPLETE,
drh41449052006-07-06 17:08:48 +0000986 DB_COPY, DB_ENABLE_LOAD_EXTENSION,DB_ERRORCODE,
987 DB_EVAL, DB_EXISTS, DB_FUNCTION,
drh59fffd02007-06-19 17:48:57 +0000988 DB_INCRBLOB, DB_INTERRUPT, DB_LAST_INSERT_ROWID,
989 DB_NULLVALUE, DB_ONECOLUMN, DB_PROFILE,
990 DB_PROGRESS, DB_REKEY, DB_ROLLBACK_HOOK,
991 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
992 DB_TRANSACTION, DB_UPDATE_HOOK, DB_VERSION
drh6d313162000-09-21 13:01:35 +0000993 };
tpoindex1067fe12004-12-17 15:41:11 +0000994 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +0000995
996 if( objc<2 ){
997 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +0000998 return TCL_ERROR;
999 }
drh411995d2002-06-25 19:31:18 +00001000 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001001 return TCL_ERROR;
1002 }
1003
drh411995d2002-06-25 19:31:18 +00001004 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001005
drhe22a3342003-04-22 20:30:37 +00001006 /* $db authorizer ?CALLBACK?
1007 **
1008 ** Invoke the given callback to authorize each SQL operation as it is
1009 ** compiled. 5 arguments are appended to the callback before it is
1010 ** invoked:
1011 **
1012 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1013 ** (2) First descriptive name (depends on authorization type)
1014 ** (3) Second descriptive name
1015 ** (4) Name of the database (ex: "main", "temp")
1016 ** (5) Name of trigger that is doing the access
1017 **
1018 ** The callback should return on of the following strings: SQLITE_OK,
1019 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1020 **
1021 ** If this method is invoked with no arguments, the current authorization
1022 ** callback string is returned.
1023 */
1024 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001025#ifdef SQLITE_OMIT_AUTHORIZATION
1026 Tcl_AppendResult(interp, "authorization not available in this build", 0);
1027 return TCL_ERROR;
1028#else
drhe22a3342003-04-22 20:30:37 +00001029 if( objc>3 ){
1030 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001031 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001032 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001033 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +00001034 Tcl_AppendResult(interp, pDb->zAuth, 0);
1035 }
1036 }else{
1037 char *zAuth;
1038 int len;
1039 if( pDb->zAuth ){
1040 Tcl_Free(pDb->zAuth);
1041 }
1042 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1043 if( zAuth && len>0 ){
1044 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001045 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001046 }else{
1047 pDb->zAuth = 0;
1048 }
drhe22a3342003-04-22 20:30:37 +00001049 if( pDb->zAuth ){
1050 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001051 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +00001052 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001053 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001054 }
drhe22a3342003-04-22 20:30:37 +00001055 }
drh1211de32004-07-26 12:24:22 +00001056#endif
drhe22a3342003-04-22 20:30:37 +00001057 break;
1058 }
1059
drhbec3f402000-08-04 13:49:02 +00001060 /* $db busy ?CALLBACK?
1061 **
1062 ** Invoke the given callback if an SQL statement attempts to open
1063 ** a locked database file.
1064 */
drh6d313162000-09-21 13:01:35 +00001065 case DB_BUSY: {
1066 if( objc>3 ){
1067 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001068 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001069 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001070 if( pDb->zBusy ){
1071 Tcl_AppendResult(interp, pDb->zBusy, 0);
1072 }
1073 }else{
drh6d313162000-09-21 13:01:35 +00001074 char *zBusy;
1075 int len;
drhbec3f402000-08-04 13:49:02 +00001076 if( pDb->zBusy ){
1077 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001078 }
drh6d313162000-09-21 13:01:35 +00001079 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1080 if( zBusy && len>0 ){
1081 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001082 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001083 }else{
1084 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001085 }
1086 if( pDb->zBusy ){
1087 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001088 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001089 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001090 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001091 }
1092 }
drh6d313162000-09-21 13:01:35 +00001093 break;
1094 }
drhbec3f402000-08-04 13:49:02 +00001095
drhfb7e7652005-01-24 00:28:42 +00001096 /* $db cache flush
1097 ** $db cache size n
1098 **
1099 ** Flush the prepared statement cache, or set the maximum number of
1100 ** cached statements.
1101 */
1102 case DB_CACHE: {
1103 char *subCmd;
1104 int n;
1105
1106 if( objc<=2 ){
1107 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1108 return TCL_ERROR;
1109 }
1110 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1111 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1112 if( objc!=3 ){
1113 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1114 return TCL_ERROR;
1115 }else{
1116 flushStmtCache( pDb );
1117 }
1118 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1119 if( objc!=4 ){
1120 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1121 return TCL_ERROR;
1122 }else{
1123 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1124 Tcl_AppendResult( interp, "cannot convert \"",
1125 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1126 return TCL_ERROR;
1127 }else{
1128 if( n<0 ){
1129 flushStmtCache( pDb );
1130 n = 0;
1131 }else if( n>MAX_PREPARED_STMTS ){
1132 n = MAX_PREPARED_STMTS;
1133 }
1134 pDb->maxStmt = n;
1135 }
1136 }
1137 }else{
1138 Tcl_AppendResult( interp, "bad option \"",
danielk1977191fadc2007-10-23 08:17:48 +00001139 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
drhfb7e7652005-01-24 00:28:42 +00001140 return TCL_ERROR;
1141 }
1142 break;
1143 }
1144
danielk1977b28af712004-06-21 06:50:26 +00001145 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001146 **
1147 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001148 ** the most recent INSERT, UPDATE or DELETE statement, not including
1149 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001150 */
1151 case DB_CHANGES: {
1152 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001153 if( objc!=2 ){
1154 Tcl_WrongNumArgs(interp, 2, objv, "");
1155 return TCL_ERROR;
1156 }
drhc8d30ac2002-04-12 10:08:59 +00001157 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001158 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001159 break;
1160 }
1161
drh75897232000-05-29 14:26:00 +00001162 /* $db close
1163 **
1164 ** Shutdown the database
1165 */
drh6d313162000-09-21 13:01:35 +00001166 case DB_CLOSE: {
1167 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1168 break;
1169 }
drh75897232000-05-29 14:26:00 +00001170
drh0f14e2e2004-06-29 12:39:08 +00001171 /*
1172 ** $db collate NAME SCRIPT
1173 **
1174 ** Create a new SQL collation function called NAME. Whenever
1175 ** that function is called, invoke SCRIPT to evaluate the function.
1176 */
1177 case DB_COLLATE: {
1178 SqlCollate *pCollate;
1179 char *zName;
1180 char *zScript;
1181 int nScript;
1182 if( objc!=4 ){
1183 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1184 return TCL_ERROR;
1185 }
1186 zName = Tcl_GetStringFromObj(objv[2], 0);
1187 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1188 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1189 if( pCollate==0 ) return TCL_ERROR;
1190 pCollate->interp = interp;
1191 pCollate->pNext = pDb->pCollate;
1192 pCollate->zScript = (char*)&pCollate[1];
1193 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001194 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001195 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1196 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001197 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001198 return TCL_ERROR;
1199 }
1200 break;
1201 }
1202
1203 /*
1204 ** $db collation_needed SCRIPT
1205 **
1206 ** Create a new SQL collation function called NAME. Whenever
1207 ** that function is called, invoke SCRIPT to evaluate the function.
1208 */
1209 case DB_COLLATION_NEEDED: {
1210 if( objc!=3 ){
1211 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1212 return TCL_ERROR;
1213 }
1214 if( pDb->pCollateNeeded ){
1215 Tcl_DecrRefCount(pDb->pCollateNeeded);
1216 }
1217 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1218 Tcl_IncrRefCount(pDb->pCollateNeeded);
1219 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1220 break;
1221 }
1222
drh19e2d372005-08-29 23:00:03 +00001223 /* $db commit_hook ?CALLBACK?
1224 **
1225 ** Invoke the given callback just before committing every SQL transaction.
1226 ** If the callback throws an exception or returns non-zero, then the
1227 ** transaction is aborted. If CALLBACK is an empty string, the callback
1228 ** is disabled.
1229 */
1230 case DB_COMMIT_HOOK: {
1231 if( objc>3 ){
1232 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1233 return TCL_ERROR;
1234 }else if( objc==2 ){
1235 if( pDb->zCommit ){
1236 Tcl_AppendResult(interp, pDb->zCommit, 0);
1237 }
1238 }else{
1239 char *zCommit;
1240 int len;
1241 if( pDb->zCommit ){
1242 Tcl_Free(pDb->zCommit);
1243 }
1244 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1245 if( zCommit && len>0 ){
1246 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001247 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001248 }else{
1249 pDb->zCommit = 0;
1250 }
1251 if( pDb->zCommit ){
1252 pDb->interp = interp;
1253 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1254 }else{
1255 sqlite3_commit_hook(pDb->db, 0, 0);
1256 }
1257 }
1258 break;
1259 }
1260
drh75897232000-05-29 14:26:00 +00001261 /* $db complete SQL
1262 **
1263 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1264 ** additional lines of input are needed. This is similar to the
1265 ** built-in "info complete" command of Tcl.
1266 */
drh6d313162000-09-21 13:01:35 +00001267 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00001268#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00001269 Tcl_Obj *pResult;
1270 int isComplete;
1271 if( objc!=3 ){
1272 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00001273 return TCL_ERROR;
1274 }
danielk19776f8a5032004-05-10 10:34:51 +00001275 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00001276 pResult = Tcl_GetObjResult(interp);
1277 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00001278#endif
drh6d313162000-09-21 13:01:35 +00001279 break;
1280 }
drhdcd997e2003-01-31 17:21:49 +00001281
drh19e2d372005-08-29 23:00:03 +00001282 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1283 **
1284 ** Copy data into table from filename, optionally using SEPARATOR
1285 ** as column separators. If a column contains a null string, or the
1286 ** value of NULLINDICATOR, a NULL is inserted for the column.
1287 ** conflict-algorithm is one of the sqlite conflict algorithms:
1288 ** rollback, abort, fail, ignore, replace
1289 ** On success, return the number of lines processed, not necessarily same
1290 ** as 'db changes' due to conflict-algorithm selected.
1291 **
1292 ** This code is basically an implementation/enhancement of
1293 ** the sqlite3 shell.c ".import" command.
1294 **
1295 ** This command usage is equivalent to the sqlite2.x COPY statement,
1296 ** which imports file data into a table using the PostgreSQL COPY file format:
1297 ** $db copy $conflit_algo $table_name $filename \t \\N
1298 */
1299 case DB_COPY: {
1300 char *zTable; /* Insert data into this table */
1301 char *zFile; /* The file from which to extract data */
1302 char *zConflict; /* The conflict algorithm to use */
1303 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00001304 int nCol; /* Number of columns in the table */
1305 int nByte; /* Number of bytes in an SQL string */
1306 int i, j; /* Loop counters */
1307 int nSep; /* Number of bytes in zSep[] */
1308 int nNull; /* Number of bytes in zNull[] */
1309 char *zSql; /* An SQL statement */
1310 char *zLine; /* A single line of input from the file */
1311 char **azCol; /* zLine[] broken up into columns */
1312 char *zCommit; /* How to commit changes */
1313 FILE *in; /* The input file */
1314 int lineno = 0; /* Line number of input file */
1315 char zLineNum[80]; /* Line number print buffer */
1316 Tcl_Obj *pResult; /* interp result */
1317
1318 char *zSep;
1319 char *zNull;
1320 if( objc<5 || objc>7 ){
1321 Tcl_WrongNumArgs(interp, 2, objv,
1322 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1323 return TCL_ERROR;
1324 }
1325 if( objc>=6 ){
1326 zSep = Tcl_GetStringFromObj(objv[5], 0);
1327 }else{
1328 zSep = "\t";
1329 }
1330 if( objc>=7 ){
1331 zNull = Tcl_GetStringFromObj(objv[6], 0);
1332 }else{
1333 zNull = "";
1334 }
1335 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1336 zTable = Tcl_GetStringFromObj(objv[3], 0);
1337 zFile = Tcl_GetStringFromObj(objv[4], 0);
1338 nSep = strlen(zSep);
1339 nNull = strlen(zNull);
1340 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00001341 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00001342 return TCL_ERROR;
1343 }
drhbd4d3972008-04-04 12:21:08 +00001344 if(strcasecmp(zConflict, "rollback") != 0 &&
1345 strcasecmp(zConflict, "abort" ) != 0 &&
1346 strcasecmp(zConflict, "fail" ) != 0 &&
1347 strcasecmp(zConflict, "ignore" ) != 0 &&
1348 strcasecmp(zConflict, "replace" ) != 0 ) {
drh19e2d372005-08-29 23:00:03 +00001349 Tcl_AppendResult(interp, "Error: \"", zConflict,
1350 "\", conflict-algorithm must be one of: rollback, "
1351 "abort, fail, ignore, or replace", 0);
1352 return TCL_ERROR;
1353 }
1354 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1355 if( zSql==0 ){
1356 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1357 return TCL_ERROR;
1358 }
1359 nByte = strlen(zSql);
drh3e701a12007-02-01 01:53:44 +00001360 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001361 sqlite3_free(zSql);
1362 if( rc ){
1363 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1364 nCol = 0;
1365 }else{
1366 nCol = sqlite3_column_count(pStmt);
1367 }
1368 sqlite3_finalize(pStmt);
1369 if( nCol==0 ) {
1370 return TCL_ERROR;
1371 }
1372 zSql = malloc( nByte + 50 + nCol*2 );
1373 if( zSql==0 ) {
1374 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1375 return TCL_ERROR;
1376 }
1377 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1378 zConflict, zTable);
1379 j = strlen(zSql);
1380 for(i=1; i<nCol; i++){
1381 zSql[j++] = ',';
1382 zSql[j++] = '?';
1383 }
1384 zSql[j++] = ')';
1385 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00001386 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001387 free(zSql);
1388 if( rc ){
1389 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1390 sqlite3_finalize(pStmt);
1391 return TCL_ERROR;
1392 }
1393 in = fopen(zFile, "rb");
1394 if( in==0 ){
1395 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
1396 sqlite3_finalize(pStmt);
1397 return TCL_ERROR;
1398 }
1399 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1400 if( azCol==0 ) {
1401 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00001402 fclose(in);
drh19e2d372005-08-29 23:00:03 +00001403 return TCL_ERROR;
1404 }
drh37527852006-03-16 16:19:56 +00001405 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001406 zCommit = "COMMIT";
1407 while( (zLine = local_getline(0, in))!=0 ){
1408 char *z;
1409 i = 0;
1410 lineno++;
1411 azCol[0] = zLine;
1412 for(i=0, z=zLine; *z; z++){
1413 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
1414 *z = 0;
1415 i++;
1416 if( i<nCol ){
1417 azCol[i] = &z[nSep];
1418 z += nSep-1;
1419 }
1420 }
1421 }
1422 if( i+1!=nCol ){
1423 char *zErr;
drh5bb3eb92007-05-04 13:15:55 +00001424 int nErr = strlen(zFile) + 200;
1425 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00001426 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00001427 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00001428 "Error: %s line %d: expected %d columns of data but found %d",
1429 zFile, lineno, nCol, i+1);
1430 Tcl_AppendResult(interp, zErr, 0);
1431 free(zErr);
1432 }
drh19e2d372005-08-29 23:00:03 +00001433 zCommit = "ROLLBACK";
1434 break;
1435 }
1436 for(i=0; i<nCol; i++){
1437 /* check for null data, if so, bind as null */
1438 if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
1439 sqlite3_bind_null(pStmt, i+1);
1440 }else{
1441 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1442 }
1443 }
1444 sqlite3_step(pStmt);
1445 rc = sqlite3_reset(pStmt);
1446 free(zLine);
1447 if( rc!=SQLITE_OK ){
1448 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
1449 zCommit = "ROLLBACK";
1450 break;
1451 }
1452 }
1453 free(azCol);
1454 fclose(in);
1455 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00001456 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001457
1458 if( zCommit[0] == 'C' ){
1459 /* success, set result as number of lines processed */
1460 pResult = Tcl_GetObjResult(interp);
1461 Tcl_SetIntObj(pResult, lineno);
1462 rc = TCL_OK;
1463 }else{
1464 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00001465 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00001466 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
1467 rc = TCL_ERROR;
1468 }
1469 break;
1470 }
1471
drhdcd997e2003-01-31 17:21:49 +00001472 /*
drh41449052006-07-06 17:08:48 +00001473 ** $db enable_load_extension BOOLEAN
1474 **
1475 ** Turn the extension loading feature on or off. It if off by
1476 ** default.
1477 */
1478 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00001479#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00001480 int onoff;
1481 if( objc!=3 ){
1482 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
1483 return TCL_ERROR;
1484 }
1485 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
1486 return TCL_ERROR;
1487 }
1488 sqlite3_enable_load_extension(pDb->db, onoff);
1489 break;
drhf533acc2006-12-19 18:57:11 +00001490#else
1491 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
1492 0);
1493 return TCL_ERROR;
1494#endif
drh41449052006-07-06 17:08:48 +00001495 }
1496
1497 /*
drhdcd997e2003-01-31 17:21:49 +00001498 ** $db errorcode
1499 **
1500 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00001501 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00001502 */
1503 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00001504 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00001505 break;
1506 }
drh75897232000-05-29 14:26:00 +00001507
1508 /*
drh895d7472004-08-20 16:02:39 +00001509 ** $db eval $sql ?array? ?{ ...code... }?
drh1807ce32004-09-07 13:20:35 +00001510 ** $db onecolumn $sql
drh75897232000-05-29 14:26:00 +00001511 **
1512 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00001513 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00001514 ** If "array" and "code" are omitted, then no callback is every invoked.
1515 ** If "array" is an empty string, then the values are placed in variables
1516 ** that have the same name as the fields extracted by the query.
drh1807ce32004-09-07 13:20:35 +00001517 **
1518 ** The onecolumn method is the equivalent of:
1519 ** lindex [$db eval $sql] 0
drh75897232000-05-29 14:26:00 +00001520 */
drh1807ce32004-09-07 13:20:35 +00001521 case DB_ONECOLUMN:
drh97f2ebc2005-12-10 21:19:04 +00001522 case DB_EVAL:
1523 case DB_EXISTS: {
drh9d74b4c2004-08-24 15:23:34 +00001524 char const *zSql; /* Next SQL statement to execute */
1525 char const *zLeft; /* What is left after first stmt in zSql */
1526 sqlite3_stmt *pStmt; /* Compiled SQL statment */
drh92febd92004-08-20 18:34:20 +00001527 Tcl_Obj *pArray; /* Name of array into which results are written */
1528 Tcl_Obj *pScript; /* Script to run for each result set */
drh1d895032004-08-26 00:56:05 +00001529 Tcl_Obj **apParm; /* Parameters that need a Tcl_DecrRefCount() */
1530 int nParm; /* Number of entries used in apParm[] */
1531 Tcl_Obj *aParm[10]; /* Static space for apParm[] in the common case */
drh1807ce32004-09-07 13:20:35 +00001532 Tcl_Obj *pRet; /* Value to be returned */
drhfb7e7652005-01-24 00:28:42 +00001533 SqlPreparedStmt *pPreStmt; /* Pointer to a prepared statement */
1534 int rc2;
danielk1977ef2cb632004-05-29 02:37:19 +00001535
drh97f2ebc2005-12-10 21:19:04 +00001536 if( choice==DB_EVAL ){
drh1807ce32004-09-07 13:20:35 +00001537 if( objc<3 || objc>5 ){
1538 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
1539 return TCL_ERROR;
1540 }
1541 pRet = Tcl_NewObj();
1542 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001543 }else{
1544 if( objc!=3 ){
1545 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
1546 return TCL_ERROR;
1547 }
drh97f2ebc2005-12-10 21:19:04 +00001548 if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001549 pRet = Tcl_NewBooleanObj(0);
1550 Tcl_IncrRefCount(pRet);
1551 }else{
1552 pRet = 0;
drh97f2ebc2005-12-10 21:19:04 +00001553 }
danielk197730ccda12004-05-27 12:11:31 +00001554 }
drh92febd92004-08-20 18:34:20 +00001555 if( objc==3 ){
1556 pArray = pScript = 0;
1557 }else if( objc==4 ){
1558 pArray = 0;
1559 pScript = objv[3];
1560 }else{
1561 pArray = objv[3];
1562 if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
1563 pScript = objv[4];
1564 }
danielk197730ccda12004-05-27 12:11:31 +00001565
drh1d895032004-08-26 00:56:05 +00001566 Tcl_IncrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001567 zSql = Tcl_GetStringFromObj(objv[2], 0);
drh90b6bb12004-09-13 13:16:31 +00001568 while( rc==TCL_OK && zSql[0] ){
drhfb7e7652005-01-24 00:28:42 +00001569 int i; /* Loop counter */
1570 int nVar; /* Number of bind parameters in the pStmt */
danielk19778e556522007-11-13 10:30:24 +00001571 int nCol = -1; /* Number of columns in the result set */
drh92febd92004-08-20 18:34:20 +00001572 Tcl_Obj **apColName = 0; /* Array of column names */
drhfb7e7652005-01-24 00:28:42 +00001573 int len; /* String length of zSql */
danielk197730ccda12004-05-27 12:11:31 +00001574
drhfb7e7652005-01-24 00:28:42 +00001575 /* Try to find a SQL statement that has already been compiled and
1576 ** which matches the next sequence of SQL.
1577 */
1578 pStmt = 0;
drhfb7e7652005-01-24 00:28:42 +00001579 len = strlen(zSql);
danielk19778e556522007-11-13 10:30:24 +00001580 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
drhfb7e7652005-01-24 00:28:42 +00001581 int n = pPreStmt->nSql;
1582 if( len>=n
1583 && memcmp(pPreStmt->zSql, zSql, n)==0
1584 && (zSql[n]==0 || zSql[n-1]==';')
1585 ){
1586 pStmt = pPreStmt->pStmt;
1587 zLeft = &zSql[pPreStmt->nSql];
1588
1589 /* When a prepared statement is found, unlink it from the
1590 ** cache list. It will later be added back to the beginning
1591 ** of the cache list in order to implement LRU replacement.
1592 */
1593 if( pPreStmt->pPrev ){
1594 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1595 }else{
1596 pDb->stmtList = pPreStmt->pNext;
1597 }
1598 if( pPreStmt->pNext ){
1599 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1600 }else{
1601 pDb->stmtLast = pPreStmt->pPrev;
1602 }
1603 pDb->nStmt--;
1604 break;
1605 }
1606 }
1607
1608 /* If no prepared statement was found. Compile the SQL text
1609 */
drh92febd92004-08-20 18:34:20 +00001610 if( pStmt==0 ){
danielk19778e556522007-11-13 10:30:24 +00001611 if( SQLITE_OK!=sqlite3_prepare_v2(pDb->db, zSql, -1, &pStmt, &zLeft) ){
drh92febd92004-08-20 18:34:20 +00001612 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1613 rc = TCL_ERROR;
1614 break;
danielk197730ccda12004-05-27 12:11:31 +00001615 }
drhfb7e7652005-01-24 00:28:42 +00001616 if( pStmt==0 ){
1617 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1618 /* A compile-time error in the statement
1619 */
1620 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1621 rc = TCL_ERROR;
1622 break;
1623 }else{
1624 /* The statement was a no-op. Continue to the next statement
1625 ** in the SQL string.
1626 */
1627 zSql = zLeft;
1628 continue;
1629 }
1630 }
1631 assert( pPreStmt==0 );
danielk197730ccda12004-05-27 12:11:31 +00001632 }
1633
drhfb7e7652005-01-24 00:28:42 +00001634 /* Bind values to parameters that begin with $ or :
1635 */
drh92febd92004-08-20 18:34:20 +00001636 nVar = sqlite3_bind_parameter_count(pStmt);
drh1d895032004-08-26 00:56:05 +00001637 nParm = 0;
1638 if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
1639 apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
1640 }else{
1641 apParm = aParm;
1642 }
drh92febd92004-08-20 18:34:20 +00001643 for(i=1; i<=nVar; i++){
1644 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
drh4f5e80f2007-06-19 17:15:46 +00001645 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
drh92febd92004-08-20 18:34:20 +00001646 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1647 if( pVar ){
1648 int n;
1649 u8 *data;
1650 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
1651 char c = zType[0];
drh1c747812007-06-19 23:01:41 +00001652 if( zVar[0]=='@' ||
1653 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1654 /* Load a BLOB type if the Tcl variable is a bytearray and
1655 ** it has no string representation or the host
drh4f5e80f2007-06-19 17:15:46 +00001656 ** parameter name begins with "@". */
drh92febd92004-08-20 18:34:20 +00001657 data = Tcl_GetByteArrayFromObj(pVar, &n);
1658 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001659 Tcl_IncrRefCount(pVar);
1660 apParm[nParm++] = pVar;
drh985e0c62007-06-26 22:55:37 +00001661 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drh92febd92004-08-20 18:34:20 +00001662 Tcl_GetIntFromObj(interp, pVar, &n);
1663 sqlite3_bind_int(pStmt, i, n);
1664 }else if( c=='d' && strcmp(zType,"double")==0 ){
1665 double r;
1666 Tcl_GetDoubleFromObj(interp, pVar, &r);
1667 sqlite3_bind_double(pStmt, i, r);
drh985e0c62007-06-26 22:55:37 +00001668 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1669 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +00001670 Tcl_WideInt v;
1671 Tcl_GetWideIntFromObj(interp, pVar, &v);
1672 sqlite3_bind_int64(pStmt, i, v);
drh92febd92004-08-20 18:34:20 +00001673 }else{
danielk197700fd9572005-12-07 06:27:43 +00001674 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
drhb08c2a72008-04-16 00:28:13 +00001675 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001676 Tcl_IncrRefCount(pVar);
1677 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001678 }
drhfb7e7652005-01-24 00:28:42 +00001679 }else{
1680 sqlite3_bind_null( pStmt, i );
drh92febd92004-08-20 18:34:20 +00001681 }
1682 }
1683 }
drh92febd92004-08-20 18:34:20 +00001684
drh92febd92004-08-20 18:34:20 +00001685 /* Execute the SQL
1686 */
drh90b6bb12004-09-13 13:16:31 +00001687 while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
danielk19778e556522007-11-13 10:30:24 +00001688
1689 /* Compute column names. This must be done after the first successful
1690 ** call to sqlite3_step(), in case the query is recompiled and the
1691 ** number or names of the returned columns changes.
1692 */
1693 assert(!pArray||pScript);
1694 if (nCol < 0) {
1695 Tcl_Obj ***ap = (pScript?&apColName:0);
1696 nCol = computeColumnNames(interp, pStmt, ap, pArray);
1697 }
1698
drh92febd92004-08-20 18:34:20 +00001699 for(i=0; i<nCol; i++){
danielk197730ccda12004-05-27 12:11:31 +00001700 Tcl_Obj *pVal;
1701
1702 /* Set pVal to contain the i'th column of this row. */
drh92febd92004-08-20 18:34:20 +00001703 switch( sqlite3_column_type(pStmt, i) ){
1704 case SQLITE_BLOB: {
1705 int bytes = sqlite3_column_bytes(pStmt, i);
drheee4c8c2008-02-18 22:24:57 +00001706 const char *zBlob = sqlite3_column_blob(pStmt, i);
danielk1977a7a8e142008-02-13 18:25:27 +00001707 if( !zBlob ) bytes = 0;
drheee4c8c2008-02-18 22:24:57 +00001708 pVal = Tcl_NewByteArrayObj((u8*)zBlob, bytes);
drh92febd92004-08-20 18:34:20 +00001709 break;
1710 }
1711 case SQLITE_INTEGER: {
1712 sqlite_int64 v = sqlite3_column_int64(pStmt, i);
1713 if( v>=-2147483647 && v<=2147483647 ){
1714 pVal = Tcl_NewIntObj(v);
1715 }else{
1716 pVal = Tcl_NewWideIntObj(v);
1717 }
1718 break;
1719 }
1720 case SQLITE_FLOAT: {
1721 double r = sqlite3_column_double(pStmt, i);
1722 pVal = Tcl_NewDoubleObj(r);
1723 break;
1724 }
danielk197755c45f22005-04-03 23:54:43 +00001725 case SQLITE_NULL: {
1726 pVal = dbTextToObj(pDb->zNull);
1727 break;
1728 }
drh92febd92004-08-20 18:34:20 +00001729 default: {
danielk197700fd9572005-12-07 06:27:43 +00001730 pVal = dbTextToObj((char *)sqlite3_column_text(pStmt, i));
drh92febd92004-08-20 18:34:20 +00001731 break;
1732 }
danielk197730ccda12004-05-27 12:11:31 +00001733 }
1734
drh92febd92004-08-20 18:34:20 +00001735 if( pScript ){
1736 if( pArray==0 ){
1737 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001738 }else{
drh92febd92004-08-20 18:34:20 +00001739 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001740 }
drh1807ce32004-09-07 13:20:35 +00001741 }else if( choice==DB_ONECOLUMN ){
drh97f2ebc2005-12-10 21:19:04 +00001742 assert( pRet==0 );
drh1807ce32004-09-07 13:20:35 +00001743 if( pRet==0 ){
1744 pRet = pVal;
1745 Tcl_IncrRefCount(pRet);
1746 }
drh90b6bb12004-09-13 13:16:31 +00001747 rc = TCL_BREAK;
drh97f2ebc2005-12-10 21:19:04 +00001748 i = nCol;
1749 }else if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001750 Tcl_DecrRefCount(pRet);
1751 pRet = Tcl_NewBooleanObj(1);
1752 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001753 rc = TCL_BREAK;
1754 i = nCol;
danielk197730ccda12004-05-27 12:11:31 +00001755 }else{
danielk197730ccda12004-05-27 12:11:31 +00001756 Tcl_ListObjAppendElement(interp, pRet, pVal);
1757 }
1758 }
1759
drh92febd92004-08-20 18:34:20 +00001760 if( pScript ){
1761 rc = Tcl_EvalObjEx(interp, pScript, 0);
drh90b6bb12004-09-13 13:16:31 +00001762 if( rc==TCL_CONTINUE ){
1763 rc = TCL_OK;
1764 }
danielk197730ccda12004-05-27 12:11:31 +00001765 }
1766 }
drh90b6bb12004-09-13 13:16:31 +00001767 if( rc==TCL_BREAK ){
1768 rc = TCL_OK;
1769 }
drh92febd92004-08-20 18:34:20 +00001770
1771 /* Free the column name objects */
1772 if( pScript ){
danielk19778e556522007-11-13 10:30:24 +00001773 /* If the query returned no rows, but an array variable was
1774 ** specified, call computeColumnNames() now to populate the
1775 ** arrayname(*) variable.
1776 */
1777 if (pArray && nCol < 0) {
1778 Tcl_Obj ***ap = (pScript?&apColName:0);
1779 nCol = computeColumnNames(interp, pStmt, ap, pArray);
1780 }
drh92febd92004-08-20 18:34:20 +00001781 for(i=0; i<nCol; i++){
1782 Tcl_DecrRefCount(apColName[i]);
1783 }
1784 Tcl_Free((char*)apColName);
1785 }
1786
drh1d895032004-08-26 00:56:05 +00001787 /* Free the bound string and blob parameters */
1788 for(i=0; i<nParm; i++){
1789 Tcl_DecrRefCount(apParm[i]);
1790 }
1791 if( apParm!=aParm ){
1792 Tcl_Free((char*)apParm);
1793 }
1794
drhfb7e7652005-01-24 00:28:42 +00001795 /* Reset the statement. If the result code is SQLITE_SCHEMA, then
1796 ** flush the statement cache and try the statement again.
drh92febd92004-08-20 18:34:20 +00001797 */
drhfb7e7652005-01-24 00:28:42 +00001798 rc2 = sqlite3_reset(pStmt);
danielk19778e556522007-11-13 10:30:24 +00001799 if( SQLITE_OK!=rc2 ){
drhfb7e7652005-01-24 00:28:42 +00001800 /* If a run-time error occurs, report the error and stop reading
1801 ** the SQL
1802 */
danielk1977ef2cb632004-05-29 02:37:19 +00001803 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
drhfb7e7652005-01-24 00:28:42 +00001804 sqlite3_finalize(pStmt);
danielk197730ccda12004-05-27 12:11:31 +00001805 rc = TCL_ERROR;
drhfb7e7652005-01-24 00:28:42 +00001806 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001807 break;
drhfb7e7652005-01-24 00:28:42 +00001808 }else if( pDb->maxStmt<=0 ){
1809 /* If the cache is turned off, deallocated the statement */
1810 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1811 sqlite3_finalize(pStmt);
1812 }else{
1813 /* Everything worked and the cache is operational.
1814 ** Create a new SqlPreparedStmt structure if we need one.
1815 ** (If we already have one we can just reuse it.)
1816 */
1817 if( pPreStmt==0 ){
1818 len = zLeft - zSql;
danielk1977d0e2a852007-11-14 06:48:48 +00001819 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) );
drhfb7e7652005-01-24 00:28:42 +00001820 if( pPreStmt==0 ) return TCL_ERROR;
1821 pPreStmt->pStmt = pStmt;
1822 pPreStmt->nSql = len;
danielk1977d0e2a852007-11-14 06:48:48 +00001823 pPreStmt->zSql = sqlite3_sql(pStmt);
1824 assert( strlen(pPreStmt->zSql)==len );
1825 assert( 0==memcmp(pPreStmt->zSql, zSql, len) );
drhfb7e7652005-01-24 00:28:42 +00001826 }
1827
1828 /* Add the prepared statement to the beginning of the cache list
1829 */
1830 pPreStmt->pNext = pDb->stmtList;
1831 pPreStmt->pPrev = 0;
1832 if( pDb->stmtList ){
1833 pDb->stmtList->pPrev = pPreStmt;
1834 }
1835 pDb->stmtList = pPreStmt;
1836 if( pDb->stmtLast==0 ){
1837 assert( pDb->nStmt==0 );
1838 pDb->stmtLast = pPreStmt;
1839 }else{
1840 assert( pDb->nStmt>0 );
1841 }
1842 pDb->nStmt++;
1843
1844 /* If we have too many statement in cache, remove the surplus from the
1845 ** end of the cache list.
1846 */
1847 while( pDb->nStmt>pDb->maxStmt ){
1848 sqlite3_finalize(pDb->stmtLast->pStmt);
1849 pDb->stmtLast = pDb->stmtLast->pPrev;
1850 Tcl_Free((char*)pDb->stmtLast->pNext);
1851 pDb->stmtLast->pNext = 0;
1852 pDb->nStmt--;
1853 }
danielk197730ccda12004-05-27 12:11:31 +00001854 }
1855
drhfb7e7652005-01-24 00:28:42 +00001856 /* Proceed to the next statement */
danielk197730ccda12004-05-27 12:11:31 +00001857 zSql = zLeft;
1858 }
drh1d895032004-08-26 00:56:05 +00001859 Tcl_DecrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001860
drh1807ce32004-09-07 13:20:35 +00001861 if( pRet ){
1862 if( rc==TCL_OK ){
1863 Tcl_SetObjResult(interp, pRet);
1864 }
1865 Tcl_DecrRefCount(pRet);
drh050be322006-07-12 00:18:40 +00001866 }else if( rc==TCL_OK ){
1867 Tcl_ResetResult(interp);
danielk197730ccda12004-05-27 12:11:31 +00001868 }
danielk197730ccda12004-05-27 12:11:31 +00001869 break;
1870 }
drhbec3f402000-08-04 13:49:02 +00001871
1872 /*
drhcabb0812002-09-14 13:47:32 +00001873 ** $db function NAME SCRIPT
1874 **
1875 ** Create a new SQL function called NAME. Whenever that function is
1876 ** called, invoke SCRIPT to evaluate the function.
1877 */
1878 case DB_FUNCTION: {
1879 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00001880 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00001881 char *zName;
drhcabb0812002-09-14 13:47:32 +00001882 if( objc!=4 ){
1883 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1884 return TCL_ERROR;
1885 }
1886 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00001887 pScript = objv[3];
1888 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00001889 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00001890 if( pFunc->pScript ){
1891 Tcl_DecrRefCount(pFunc->pScript);
1892 }
1893 pFunc->pScript = pScript;
1894 Tcl_IncrRefCount(pScript);
1895 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
danielk1977c8c11582004-06-29 13:41:21 +00001896 rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00001897 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00001898 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00001899 rc = TCL_ERROR;
1900 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00001901 }
drhcabb0812002-09-14 13:47:32 +00001902 break;
1903 }
1904
1905 /*
danielk19778cbadb02007-05-03 16:31:26 +00001906 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00001907 */
1908 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00001909#ifdef SQLITE_OMIT_INCRBLOB
1910 Tcl_AppendResult(interp, "incrblob not available in this build", 0);
1911 return TCL_ERROR;
1912#else
danielk19778cbadb02007-05-03 16:31:26 +00001913 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00001914 const char *zDb = "main";
1915 const char *zTable;
1916 const char *zColumn;
1917 sqlite_int64 iRow;
1918
danielk19778cbadb02007-05-03 16:31:26 +00001919 /* Check for the -readonly option */
1920 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
1921 isReadonly = 1;
1922 }
1923
1924 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
1925 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00001926 return TCL_ERROR;
1927 }
1928
danielk19778cbadb02007-05-03 16:31:26 +00001929 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00001930 zDb = Tcl_GetString(objv[2]);
1931 }
1932 zTable = Tcl_GetString(objv[objc-3]);
1933 zColumn = Tcl_GetString(objv[objc-2]);
1934 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
1935
1936 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00001937 rc = createIncrblobChannel(
1938 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
1939 );
danielk1977b4e9af92007-05-01 17:49:49 +00001940 }
danielk197732a0d8b2007-05-04 19:03:02 +00001941#endif
danielk1977b4e9af92007-05-01 17:49:49 +00001942 break;
1943 }
1944
1945 /*
drhf11bded2006-07-17 00:02:44 +00001946 ** $db interrupt
1947 **
1948 ** Interrupt the execution of the inner-most SQL interpreter. This
1949 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
1950 */
1951 case DB_INTERRUPT: {
1952 sqlite3_interrupt(pDb->db);
1953 break;
1954 }
1955
1956 /*
drh19e2d372005-08-29 23:00:03 +00001957 ** $db nullvalue ?STRING?
1958 **
1959 ** Change text used when a NULL comes back from the database. If ?STRING?
1960 ** is not present, then the current string used for NULL is returned.
1961 ** If STRING is present, then STRING is returned.
1962 **
1963 */
1964 case DB_NULLVALUE: {
1965 if( objc!=2 && objc!=3 ){
1966 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
1967 return TCL_ERROR;
1968 }
1969 if( objc==3 ){
1970 int len;
1971 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
1972 if( pDb->zNull ){
1973 Tcl_Free(pDb->zNull);
1974 }
1975 if( zNull && len>0 ){
1976 pDb->zNull = Tcl_Alloc( len + 1 );
1977 strncpy(pDb->zNull, zNull, len);
1978 pDb->zNull[len] = '\0';
1979 }else{
1980 pDb->zNull = 0;
1981 }
1982 }
1983 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
1984 break;
1985 }
1986
1987 /*
drhaf9ff332002-01-16 21:00:27 +00001988 ** $db last_insert_rowid
1989 **
1990 ** Return an integer which is the ROWID for the most recent insert.
1991 */
1992 case DB_LAST_INSERT_ROWID: {
1993 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00001994 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00001995 if( objc!=2 ){
1996 Tcl_WrongNumArgs(interp, 2, objv, "");
1997 return TCL_ERROR;
1998 }
danielk19776f8a5032004-05-10 10:34:51 +00001999 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002000 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002001 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002002 break;
2003 }
2004
2005 /*
drh1807ce32004-09-07 13:20:35 +00002006 ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
drh5d9d7572003-08-19 14:31:01 +00002007 */
drh1807ce32004-09-07 13:20:35 +00002008
2009 /* $db progress ?N CALLBACK?
2010 **
2011 ** Invoke the given callback every N virtual machine opcodes while executing
2012 ** queries.
2013 */
2014 case DB_PROGRESS: {
2015 if( objc==2 ){
2016 if( pDb->zProgress ){
2017 Tcl_AppendResult(interp, pDb->zProgress, 0);
2018 }
2019 }else if( objc==4 ){
2020 char *zProgress;
2021 int len;
2022 int N;
2023 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002024 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002025 };
2026 if( pDb->zProgress ){
2027 Tcl_Free(pDb->zProgress);
2028 }
2029 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2030 if( zProgress && len>0 ){
2031 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002032 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002033 }else{
2034 pDb->zProgress = 0;
2035 }
2036#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2037 if( pDb->zProgress ){
2038 pDb->interp = interp;
2039 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2040 }else{
2041 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2042 }
2043#endif
2044 }else{
2045 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002046 return TCL_ERROR;
2047 }
drh5d9d7572003-08-19 14:31:01 +00002048 break;
2049 }
2050
drh19e2d372005-08-29 23:00:03 +00002051 /* $db profile ?CALLBACK?
2052 **
2053 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2054 ** that has run. The text of the SQL and the amount of elapse time are
2055 ** appended to CALLBACK before the script is run.
2056 */
2057 case DB_PROFILE: {
2058 if( objc>3 ){
2059 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2060 return TCL_ERROR;
2061 }else if( objc==2 ){
2062 if( pDb->zProfile ){
2063 Tcl_AppendResult(interp, pDb->zProfile, 0);
2064 }
2065 }else{
2066 char *zProfile;
2067 int len;
2068 if( pDb->zProfile ){
2069 Tcl_Free(pDb->zProfile);
2070 }
2071 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2072 if( zProfile && len>0 ){
2073 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002074 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002075 }else{
2076 pDb->zProfile = 0;
2077 }
2078#ifndef SQLITE_OMIT_TRACE
2079 if( pDb->zProfile ){
2080 pDb->interp = interp;
2081 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2082 }else{
2083 sqlite3_profile(pDb->db, 0, 0);
2084 }
2085#endif
2086 }
2087 break;
2088 }
2089
drh5d9d7572003-08-19 14:31:01 +00002090 /*
drh22fbcb82004-02-01 01:22:50 +00002091 ** $db rekey KEY
2092 **
2093 ** Change the encryption key on the currently open database.
2094 */
2095 case DB_REKEY: {
2096 int nKey;
2097 void *pKey;
2098 if( objc!=3 ){
2099 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2100 return TCL_ERROR;
2101 }
2102 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00002103#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00002104 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002105 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00002106 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002107 rc = TCL_ERROR;
2108 }
2109#endif
2110 break;
2111 }
2112
2113 /*
drhbec3f402000-08-04 13:49:02 +00002114 ** $db timeout MILLESECONDS
2115 **
2116 ** Delay for the number of milliseconds specified when a file is locked.
2117 */
drh6d313162000-09-21 13:01:35 +00002118 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002119 int ms;
drh6d313162000-09-21 13:01:35 +00002120 if( objc!=3 ){
2121 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002122 return TCL_ERROR;
2123 }
drh6d313162000-09-21 13:01:35 +00002124 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002125 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002126 break;
drh75897232000-05-29 14:26:00 +00002127 }
danielk197755c45f22005-04-03 23:54:43 +00002128
2129 /*
drh0f14e2e2004-06-29 12:39:08 +00002130 ** $db total_changes
2131 **
2132 ** Return the number of rows that were modified, inserted, or deleted
2133 ** since the database handle was created.
2134 */
2135 case DB_TOTAL_CHANGES: {
2136 Tcl_Obj *pResult;
2137 if( objc!=2 ){
2138 Tcl_WrongNumArgs(interp, 2, objv, "");
2139 return TCL_ERROR;
2140 }
2141 pResult = Tcl_GetObjResult(interp);
2142 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2143 break;
2144 }
2145
drhb5a20d32003-04-23 12:25:23 +00002146 /* $db trace ?CALLBACK?
2147 **
2148 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2149 ** that is executed. The text of the SQL is appended to CALLBACK before
2150 ** it is executed.
2151 */
2152 case DB_TRACE: {
2153 if( objc>3 ){
2154 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002155 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002156 }else if( objc==2 ){
2157 if( pDb->zTrace ){
2158 Tcl_AppendResult(interp, pDb->zTrace, 0);
2159 }
2160 }else{
2161 char *zTrace;
2162 int len;
2163 if( pDb->zTrace ){
2164 Tcl_Free(pDb->zTrace);
2165 }
2166 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2167 if( zTrace && len>0 ){
2168 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002169 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002170 }else{
2171 pDb->zTrace = 0;
2172 }
drh19e2d372005-08-29 23:00:03 +00002173#ifndef SQLITE_OMIT_TRACE
drhb5a20d32003-04-23 12:25:23 +00002174 if( pDb->zTrace ){
2175 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002176 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002177 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002178 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002179 }
drh19e2d372005-08-29 23:00:03 +00002180#endif
drhb5a20d32003-04-23 12:25:23 +00002181 }
2182 break;
2183 }
2184
drh3d214232005-08-02 12:21:08 +00002185 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2186 **
2187 ** Start a new transaction (if we are not already in the midst of a
2188 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2189 ** completes, either commit the transaction or roll it back if SCRIPT
2190 ** throws an exception. Or if no new transation was started, do nothing.
2191 ** pass the exception on up the stack.
2192 **
2193 ** This command was inspired by Dave Thomas's talk on Ruby at the
2194 ** 2005 O'Reilly Open Source Convention (OSCON).
2195 */
2196 case DB_TRANSACTION: {
2197 int inTrans;
2198 Tcl_Obj *pScript;
2199 const char *zBegin = "BEGIN";
2200 if( objc!=3 && objc!=4 ){
2201 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2202 return TCL_ERROR;
2203 }
2204 if( objc==3 ){
2205 pScript = objv[2];
2206 } else {
2207 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002208 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002209 };
2210 enum TTYPE_enum {
2211 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2212 };
2213 int ttype;
drhb5555e72005-08-02 17:15:14 +00002214 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002215 0, &ttype) ){
2216 return TCL_ERROR;
2217 }
2218 switch( (enum TTYPE_enum)ttype ){
2219 case TTYPE_DEFERRED: /* no-op */; break;
2220 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2221 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2222 }
2223 pScript = objv[3];
2224 }
2225 inTrans = !sqlite3_get_autocommit(pDb->db);
2226 if( !inTrans ){
drh37527852006-03-16 16:19:56 +00002227 (void)sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
drh3d214232005-08-02 12:21:08 +00002228 }
2229 rc = Tcl_EvalObjEx(interp, pScript, 0);
2230 if( !inTrans ){
2231 const char *zEnd;
2232 if( rc==TCL_ERROR ){
2233 zEnd = "ROLLBACK";
2234 } else {
2235 zEnd = "COMMIT";
2236 }
drh109b4352007-06-12 18:50:13 +00002237 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
2238 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
2239 }
drh3d214232005-08-02 12:21:08 +00002240 }
2241 break;
2242 }
2243
danielk197794eb6a12005-12-15 15:22:08 +00002244 /*
2245 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002246 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002247 */
danielk197771fd80b2005-12-16 06:54:01 +00002248 case DB_UPDATE_HOOK:
2249 case DB_ROLLBACK_HOOK: {
2250
2251 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2252 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2253 */
2254 Tcl_Obj **ppHook;
2255 if( choice==DB_UPDATE_HOOK ){
2256 ppHook = &pDb->pUpdateHook;
2257 }else{
2258 ppHook = &pDb->pRollbackHook;
2259 }
2260
danielk197794eb6a12005-12-15 15:22:08 +00002261 if( objc!=2 && objc!=3 ){
2262 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2263 return TCL_ERROR;
2264 }
danielk197771fd80b2005-12-16 06:54:01 +00002265 if( *ppHook ){
2266 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002267 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002268 Tcl_DecrRefCount(*ppHook);
2269 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00002270 }
2271 }
2272 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002273 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00002274 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00002275 *ppHook = objv[2];
2276 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002277 }
2278 }
danielk197771fd80b2005-12-16 06:54:01 +00002279
2280 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2281 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
2282
danielk197794eb6a12005-12-15 15:22:08 +00002283 break;
2284 }
2285
danielk19774397de52005-01-12 12:44:03 +00002286 /* $db version
2287 **
2288 ** Return the version string for this database.
2289 */
2290 case DB_VERSION: {
2291 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2292 break;
2293 }
2294
tpoindex1067fe12004-12-17 15:41:11 +00002295
drh6d313162000-09-21 13:01:35 +00002296 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002297 return rc;
drh75897232000-05-29 14:26:00 +00002298}
2299
2300/*
drh3570ad92007-08-31 14:31:44 +00002301** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00002302** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00002303**
2304** This is the main Tcl command. When the "sqlite" Tcl command is
2305** invoked, this routine runs to process that command.
2306**
2307** The first argument, DBNAME, is an arbitrary name for a new
2308** database connection. This command creates a new command named
2309** DBNAME that is used to control that connection. The database
2310** connection is deleted when the DBNAME command is deleted.
2311**
drh3570ad92007-08-31 14:31:44 +00002312** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00002313**
drh75897232000-05-29 14:26:00 +00002314*/
drh22fbcb82004-02-01 01:22:50 +00002315static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002316 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002317 void *pKey = 0;
2318 int nKey = 0;
2319 const char *zArg;
drh75897232000-05-29 14:26:00 +00002320 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00002321 int i;
drh22fbcb82004-02-01 01:22:50 +00002322 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00002323 const char *zVfs = 0;
2324 int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
drh882e8e42006-08-24 02:42:27 +00002325 Tcl_DString translatedFilename;
drh22fbcb82004-02-01 01:22:50 +00002326 if( objc==2 ){
2327 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002328 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00002329 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00002330 return TCL_OK;
2331 }
drh9eb9e262004-02-11 02:18:05 +00002332 if( strcmp(zArg,"-has-codec")==0 ){
2333#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002334 Tcl_AppendResult(interp,"1",0);
2335#else
2336 Tcl_AppendResult(interp,"0",0);
2337#endif
2338 return TCL_OK;
2339 }
drhfbc3eab2001-04-06 16:13:42 +00002340 }
drh3570ad92007-08-31 14:31:44 +00002341 for(i=3; i+1<objc; i+=2){
2342 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00002343 if( strcmp(zArg,"-key")==0 ){
drh3570ad92007-08-31 14:31:44 +00002344 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
2345 }else if( strcmp(zArg, "-vfs")==0 ){
2346 i++;
2347 zVfs = Tcl_GetString(objv[i]);
2348 }else if( strcmp(zArg, "-readonly")==0 ){
2349 int b;
2350 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2351 if( b ){
drh33f4e022007-09-03 15:19:34 +00002352 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00002353 flags |= SQLITE_OPEN_READONLY;
2354 }else{
2355 flags &= ~SQLITE_OPEN_READONLY;
2356 flags |= SQLITE_OPEN_READWRITE;
2357 }
2358 }else if( strcmp(zArg, "-create")==0 ){
2359 int b;
2360 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00002361 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00002362 flags |= SQLITE_OPEN_CREATE;
2363 }else{
2364 flags &= ~SQLITE_OPEN_CREATE;
2365 }
danielk19779a6284c2008-07-10 17:52:49 +00002366 }else if( strcmp(zArg, "-nomutex")==0 ){
2367 int b;
2368 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2369 if( b ){
2370 flags |= SQLITE_OPEN_NOMUTEX;
2371 }else{
2372 flags &= ~SQLITE_OPEN_NOMUTEX;
2373 }
drh3570ad92007-08-31 14:31:44 +00002374 }else{
2375 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
2376 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00002377 }
2378 }
drh3570ad92007-08-31 14:31:44 +00002379 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00002380 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00002381 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
danielk19779a6284c2008-07-10 17:52:49 +00002382 " ?-nomutex BOOLEAN?"
drh9eb9e262004-02-11 02:18:05 +00002383#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00002384 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00002385#endif
2386 );
drh75897232000-05-29 14:26:00 +00002387 return TCL_ERROR;
2388 }
drh75897232000-05-29 14:26:00 +00002389 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00002390 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00002391 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00002392 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
2393 return TCL_ERROR;
2394 }
2395 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00002396 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00002397 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
drh3570ad92007-08-31 14:31:44 +00002398 sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00002399 Tcl_DStringFree(&translatedFilename);
danielk197780290862004-05-22 09:21:21 +00002400 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
drh9404d502006-12-19 18:46:08 +00002401 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
danielk197780290862004-05-22 09:21:21 +00002402 sqlite3_close(p->db);
2403 p->db = 0;
2404 }
drh2011d5f2004-07-22 02:40:37 +00002405#ifdef SQLITE_HAS_CODEC
drhf3a65f72007-08-22 20:18:21 +00002406 if( p->db ){
2407 sqlite3_key(p->db, pKey, nKey);
2408 }
drheb8ed702004-02-11 10:37:23 +00002409#endif
drhbec3f402000-08-04 13:49:02 +00002410 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00002411 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00002412 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00002413 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00002414 return TCL_ERROR;
2415 }
drhfb7e7652005-01-24 00:28:42 +00002416 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00002417 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00002418 zArg = Tcl_GetStringFromObj(objv[1], 0);
2419 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
drh75897232000-05-29 14:26:00 +00002420 return TCL_OK;
2421}
2422
2423/*
drh90ca9752001-09-28 17:47:14 +00002424** Provide a dummy Tcl_InitStubs if we are using this as a static
2425** library.
2426*/
2427#ifndef USE_TCL_STUBS
2428# undef Tcl_InitStubs
2429# define Tcl_InitStubs(a,b,c)
2430#endif
2431
2432/*
drh29bc4612005-10-05 10:40:15 +00002433** Make sure we have a PACKAGE_VERSION macro defined. This will be
2434** defined automatically by the TEA makefile. But other makefiles
2435** do not define it.
2436*/
2437#ifndef PACKAGE_VERSION
2438# define PACKAGE_VERSION SQLITE_VERSION
2439#endif
2440
2441/*
drh75897232000-05-29 14:26:00 +00002442** Initialize this module.
2443**
2444** This Tcl module contains only a single new Tcl command named "sqlite".
2445** (Hence there is no namespace. There is no point in using a namespace
2446** if the extension only supplies one new name!) The "sqlite" command is
2447** used to open a new SQLite database. See the DbMain() routine above
2448** for additional information.
2449*/
drhad6e1372006-07-10 21:15:51 +00002450EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00002451 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00002452 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002453 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh49766d62005-01-08 18:42:28 +00002454 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002455 Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
drh90ca9752001-09-28 17:47:14 +00002456 return TCL_OK;
2457}
drhad6e1372006-07-10 21:15:51 +00002458EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2459EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2460EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002461
2462#ifndef SQLITE_3_SUFFIX_ONLY
drhad6e1372006-07-10 21:15:51 +00002463EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2464EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2465EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2466EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002467#endif
drh75897232000-05-29 14:26:00 +00002468
drh3e27c022004-07-23 00:01:38 +00002469#ifdef TCLSH
2470/*****************************************************************************
2471** The code that follows is used to build standalone TCL interpreters
drh3570ad92007-08-31 14:31:44 +00002472** that are statically linked with SQLite.
drh75897232000-05-29 14:26:00 +00002473*/
drh348784e2000-05-29 20:41:49 +00002474
2475/*
drh3e27c022004-07-23 00:01:38 +00002476** If the macro TCLSH is one, then put in code this for the
2477** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00002478** standard input, or if a file is named on the command line
2479** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00002480*/
drh3e27c022004-07-23 00:01:38 +00002481#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00002482static char zMainloop[] =
2483 "set line {}\n"
2484 "while {![eof stdin]} {\n"
2485 "if {$line!=\"\"} {\n"
2486 "puts -nonewline \"> \"\n"
2487 "} else {\n"
2488 "puts -nonewline \"% \"\n"
2489 "}\n"
2490 "flush stdout\n"
2491 "append line [gets stdin]\n"
2492 "if {[info complete $line]} {\n"
2493 "if {[catch {uplevel #0 $line} result]} {\n"
2494 "puts stderr \"Error: $result\"\n"
2495 "} elseif {$result!=\"\"} {\n"
2496 "puts $result\n"
2497 "}\n"
2498 "set line {}\n"
2499 "} else {\n"
2500 "append line \\n\n"
2501 "}\n"
2502 "}\n"
2503;
drh3e27c022004-07-23 00:01:38 +00002504#endif
2505
2506/*
2507** If the macro TCLSH is two, then get the main loop code out of
2508** the separate file "spaceanal_tcl.h".
2509*/
2510#if TCLSH==2
2511static char zMainloop[] =
2512#include "spaceanal_tcl.h"
2513;
2514#endif
drh348784e2000-05-29 20:41:49 +00002515
2516#define TCLSH_MAIN main /* Needed to fake out mktclapp */
2517int TCLSH_MAIN(int argc, char **argv){
2518 Tcl_Interp *interp;
drh297ecf12001-04-05 15:57:13 +00002519 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00002520 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00002521 Sqlite3_Init(interp);
drhd9b02572001-04-15 00:37:09 +00002522#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00002523 {
drh2f999a62007-08-15 19:16:43 +00002524 extern int Md5_Init(Tcl_Interp*);
2525 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00002526 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00002527 extern int Sqlitetest2_Init(Tcl_Interp*);
2528 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00002529 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00002530 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00002531 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00002532 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00002533 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00002534 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00002535 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00002536 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
drh984bfaa2008-03-19 16:08:53 +00002537 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00002538 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00002539 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00002540 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00002541 extern int Sqlitetestschema_Init(Tcl_Interp*);
2542 extern int Sqlitetestsse_Init(Tcl_Interp*);
2543 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00002544 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00002545 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00002546 extern int SqlitetestOsinst_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002547
drh2f999a62007-08-15 19:16:43 +00002548 Md5_Init(interp);
2549 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00002550 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00002551 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00002552 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00002553 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00002554 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00002555 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00002556 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00002557 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00002558 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00002559 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00002560 Sqlitetest_autoext_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00002561 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00002562 Sqlitetest_hexio_Init(interp);
drh2f999a62007-08-15 19:16:43 +00002563 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00002564 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00002565 Sqlitetestschema_Init(interp);
2566 Sqlitetesttclvar_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00002567 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00002568 SqlitetestOnefile_Init(interp);
danielk19775d1f5aa2008-04-10 14:51:00 +00002569 SqlitetestOsinst_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00002570
drh89dec812005-04-28 19:03:37 +00002571#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00002572 Sqlitetestsse_Init(interp);
2573#endif
drhd1bf3512001-04-07 15:24:33 +00002574 }
2575#endif
drh3e27c022004-07-23 00:01:38 +00002576 if( argc>=2 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002577 int i;
shessad42c3a2006-08-22 23:53:46 +00002578 char zArgc[32];
2579 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
2580 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00002581 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
2582 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00002583 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00002584 Tcl_SetVar(interp, "argv", argv[i],
2585 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
2586 }
drh3e27c022004-07-23 00:01:38 +00002587 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00002588 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drhc61053b2000-06-04 12:58:36 +00002589 if( zInfo==0 ) zInfo = interp->result;
2590 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00002591 return 1;
2592 }
drh3e27c022004-07-23 00:01:38 +00002593 }
2594 if( argc<=1 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002595 Tcl_GlobalEval(interp, zMainloop);
2596 }
2597 return 0;
2598}
2599#endif /* TCLSH */