blob: 6230330bce72b6dda200df6540fddc26000e39c6 [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**
drhd1d38482008-10-07 23:46:38 +000015** $Id: tclsqlite.c,v 1.227 2008/10/07 23:46:38 drh Exp $
drh75897232000-05-29 14:26:00 +000016*/
drh17a68932001-01-31 13:28:08 +000017#include "tcl.h"
danielk1977b4e9af92007-05-01 17:49:49 +000018#include <errno.h>
drhbd08af42007-04-05 21:58:33 +000019
20/*
21** Some additional include files are needed if this file is not
22** appended to the amalgamation.
23*/
24#ifndef SQLITE_AMALGAMATION
25# include "sqliteInt.h"
drhbd08af42007-04-05 21:58:33 +000026# include <stdlib.h>
27# include <string.h>
28# include <assert.h>
29# include <ctype.h>
30#endif
drh75897232000-05-29 14:26:00 +000031
drhad6e1372006-07-10 21:15:51 +000032/*
33 * Windows needs to know which symbols to export. Unix does not.
34 * BUILD_sqlite should be undefined for Unix.
35 */
36#ifdef BUILD_sqlite
37#undef TCL_STORAGE_CLASS
38#define TCL_STORAGE_CLASS DLLEXPORT
39#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000040
danielk1977a21c6b62005-01-24 10:25:59 +000041#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000042#define MAX_PREPARED_STMTS 100
43
drh75897232000-05-29 14:26:00 +000044/*
drh98808ba2001-10-18 12:34:46 +000045** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
46** have to do a translation when going between the two. Set the
47** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
48** this translation.
49*/
50#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
51# define UTF_TRANSLATION_NEEDED 1
52#endif
53
54/*
drhcabb0812002-09-14 13:47:32 +000055** New SQL functions can be created as TCL scripts. Each such function
56** is described by an instance of the following structure.
57*/
58typedef struct SqlFunc SqlFunc;
59struct SqlFunc {
60 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000061 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
62 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
63 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000064 SqlFunc *pNext; /* Next function on the list of them all */
65};
66
67/*
danielk19770202b292004-06-09 09:55:16 +000068** New collation sequences function can be created as TCL scripts. Each such
69** function is described by an instance of the following structure.
70*/
71typedef struct SqlCollate SqlCollate;
72struct SqlCollate {
73 Tcl_Interp *interp; /* The TCL interpret to execute the function */
74 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000075 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000076};
77
78/*
drhfb7e7652005-01-24 00:28:42 +000079** Prepared statements are cached for faster execution. Each prepared
80** statement is described by an instance of the following structure.
81*/
82typedef struct SqlPreparedStmt SqlPreparedStmt;
83struct SqlPreparedStmt {
84 SqlPreparedStmt *pNext; /* Next in linked list */
85 SqlPreparedStmt *pPrev; /* Previous on the list */
86 sqlite3_stmt *pStmt; /* The prepared statement */
87 int nSql; /* chars in zSql[] */
danielk1977d0e2a852007-11-14 06:48:48 +000088 const char *zSql; /* Text of the SQL statement */
drhfb7e7652005-01-24 00:28:42 +000089};
90
danielk1977d04417962007-05-02 13:16:30 +000091typedef struct IncrblobChannel IncrblobChannel;
92
drhfb7e7652005-01-24 00:28:42 +000093/*
drhbec3f402000-08-04 13:49:02 +000094** There is one instance of this structure for each SQLite database
95** that has been opened by the SQLite TCL interface.
96*/
97typedef struct SqliteDb SqliteDb;
98struct SqliteDb {
drhdddca282006-01-03 00:33:50 +000099 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000100 Tcl_Interp *interp; /* The interpreter used for this database */
101 char *zBusy; /* The busy callback routine */
102 char *zCommit; /* The commit hook callback routine */
103 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +0000104 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000105 char *zProgress; /* The progress callback routine */
106 char *zAuth; /* The authorization callback routine */
drh1f1549f2008-08-26 21:33:34 +0000107 int disableAuth; /* Disable the authorizer if it exists */
drhd1e47332005-06-26 17:55:33 +0000108 char *zNull; /* Text to substitute for an SQL NULL value */
109 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000110 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000111 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drhd1e47332005-06-26 17:55:33 +0000112 SqlCollate *pCollate; /* List of SQL collation functions */
113 int rc; /* Return code of most recent sqlite3_exec() */
114 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000115 SqlPreparedStmt *stmtList; /* List of prepared statements*/
116 SqlPreparedStmt *stmtLast; /* Last statement in the list */
117 int maxStmt; /* The next maximum number of stmtList */
118 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000119 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drhd1d38482008-10-07 23:46:38 +0000120 int nStep, nSort; /* Statistics for most recent operation */
drh98808ba2001-10-18 12:34:46 +0000121};
drh297ecf12001-04-05 15:57:13 +0000122
danielk1977b4e9af92007-05-01 17:49:49 +0000123struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000124 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000125 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000126 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000127 Tcl_Channel channel; /* Channel identifier */
128 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
129 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000130};
131
danielk197732a0d8b2007-05-04 19:03:02 +0000132#ifndef SQLITE_OMIT_INCRBLOB
danielk1977b4e9af92007-05-01 17:49:49 +0000133/*
danielk1977d04417962007-05-02 13:16:30 +0000134** Close all incrblob channels opened using database connection pDb.
135** This is called when shutting down the database connection.
136*/
137static void closeIncrblobChannels(SqliteDb *pDb){
138 IncrblobChannel *p;
139 IncrblobChannel *pNext;
140
141 for(p=pDb->pIncrblob; p; p=pNext){
142 pNext = p->pNext;
143
144 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
145 ** which deletes the IncrblobChannel structure at *p. So do not
146 ** call Tcl_Free() here.
147 */
148 Tcl_UnregisterChannel(pDb->interp, p->channel);
149 }
150}
151
152/*
danielk1977b4e9af92007-05-01 17:49:49 +0000153** Close an incremental blob channel.
154*/
155static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
156 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000157 int rc = sqlite3_blob_close(p->pBlob);
158 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000159
160 /* Remove the channel from the SqliteDb.pIncrblob list. */
161 if( p->pNext ){
162 p->pNext->pPrev = p->pPrev;
163 }
164 if( p->pPrev ){
165 p->pPrev->pNext = p->pNext;
166 }
167 if( p->pDb->pIncrblob==p ){
168 p->pDb->pIncrblob = p->pNext;
169 }
170
danielk197792d4d7a2007-05-04 12:05:56 +0000171 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000172 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000173
174 if( rc!=SQLITE_OK ){
175 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
176 return TCL_ERROR;
177 }
danielk1977b4e9af92007-05-01 17:49:49 +0000178 return TCL_OK;
179}
180
181/*
182** Read data from an incremental blob channel.
183*/
184static int incrblobInput(
185 ClientData instanceData,
186 char *buf,
187 int bufSize,
188 int *errorCodePtr
189){
190 IncrblobChannel *p = (IncrblobChannel *)instanceData;
191 int nRead = bufSize; /* Number of bytes to read */
192 int nBlob; /* Total size of the blob */
193 int rc; /* sqlite error code */
194
195 nBlob = sqlite3_blob_bytes(p->pBlob);
196 if( (p->iSeek+nRead)>nBlob ){
197 nRead = nBlob-p->iSeek;
198 }
199 if( nRead<=0 ){
200 return 0;
201 }
202
203 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
204 if( rc!=SQLITE_OK ){
205 *errorCodePtr = rc;
206 return -1;
207 }
208
209 p->iSeek += nRead;
210 return nRead;
211}
212
danielk1977d04417962007-05-02 13:16:30 +0000213/*
214** Write data to an incremental blob channel.
215*/
danielk1977b4e9af92007-05-01 17:49:49 +0000216static int incrblobOutput(
217 ClientData instanceData,
218 CONST char *buf,
219 int toWrite,
220 int *errorCodePtr
221){
222 IncrblobChannel *p = (IncrblobChannel *)instanceData;
223 int nWrite = toWrite; /* Number of bytes to write */
224 int nBlob; /* Total size of the blob */
225 int rc; /* sqlite error code */
226
227 nBlob = sqlite3_blob_bytes(p->pBlob);
228 if( (p->iSeek+nWrite)>nBlob ){
229 *errorCodePtr = EINVAL;
230 return -1;
231 }
232 if( nWrite<=0 ){
233 return 0;
234 }
235
236 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
237 if( rc!=SQLITE_OK ){
238 *errorCodePtr = EIO;
239 return -1;
240 }
241
242 p->iSeek += nWrite;
243 return nWrite;
244}
245
246/*
247** Seek an incremental blob channel.
248*/
249static int incrblobSeek(
250 ClientData instanceData,
251 long offset,
252 int seekMode,
253 int *errorCodePtr
254){
255 IncrblobChannel *p = (IncrblobChannel *)instanceData;
256
257 switch( seekMode ){
258 case SEEK_SET:
259 p->iSeek = offset;
260 break;
261 case SEEK_CUR:
262 p->iSeek += offset;
263 break;
264 case SEEK_END:
265 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
266 break;
267
268 default: assert(!"Bad seekMode");
269 }
270
271 return p->iSeek;
272}
273
274
275static void incrblobWatch(ClientData instanceData, int mode){
276 /* NO-OP */
277}
278static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
279 return TCL_ERROR;
280}
281
282static Tcl_ChannelType IncrblobChannelType = {
283 "incrblob", /* typeName */
284 TCL_CHANNEL_VERSION_2, /* version */
285 incrblobClose, /* closeProc */
286 incrblobInput, /* inputProc */
287 incrblobOutput, /* outputProc */
288 incrblobSeek, /* seekProc */
289 0, /* setOptionProc */
290 0, /* getOptionProc */
291 incrblobWatch, /* watchProc (this is a no-op) */
292 incrblobHandle, /* getHandleProc (always returns error) */
293 0, /* close2Proc */
294 0, /* blockModeProc */
295 0, /* flushProc */
296 0, /* handlerProc */
297 0, /* wideSeekProc */
danielk1977b4e9af92007-05-01 17:49:49 +0000298};
299
300/*
301** Create a new incrblob channel.
302*/
303static int createIncrblobChannel(
304 Tcl_Interp *interp,
305 SqliteDb *pDb,
306 const char *zDb,
307 const char *zTable,
308 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000309 sqlite_int64 iRow,
310 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000311){
312 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000313 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000314 sqlite3_blob *pBlob;
315 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000316 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000317
318 /* This variable is used to name the channels: "incrblob_[incr count]" */
319 static int count = 0;
320 char zChannel[64];
321
danielk19778cbadb02007-05-03 16:31:26 +0000322 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000323 if( rc!=SQLITE_OK ){
324 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
325 return TCL_ERROR;
326 }
327
328 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
329 p->iSeek = 0;
330 p->pBlob = pBlob;
331
drh5bb3eb92007-05-04 13:15:55 +0000332 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000333 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
334 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000335
danielk1977d04417962007-05-02 13:16:30 +0000336 /* Link the new channel into the SqliteDb.pIncrblob list. */
337 p->pNext = pDb->pIncrblob;
338 p->pPrev = 0;
339 if( p->pNext ){
340 p->pNext->pPrev = p;
341 }
342 pDb->pIncrblob = p;
343 p->pDb = pDb;
344
345 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000346 return TCL_OK;
347}
danielk197732a0d8b2007-05-04 19:03:02 +0000348#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
349 #define closeIncrblobChannels(pDb)
350#endif
danielk1977b4e9af92007-05-01 17:49:49 +0000351
drh6d313162000-09-21 13:01:35 +0000352/*
drhd1e47332005-06-26 17:55:33 +0000353** Look at the script prefix in pCmd. We will be executing this script
354** after first appending one or more arguments. This routine analyzes
355** the script to see if it is safe to use Tcl_EvalObjv() on the script
356** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
357** faster.
358**
359** Scripts that are safe to use with Tcl_EvalObjv() consists of a
360** command name followed by zero or more arguments with no [...] or $
361** or {...} or ; to be seen anywhere. Most callback scripts consist
362** of just a single procedure name and they meet this requirement.
363*/
364static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
365 /* We could try to do something with Tcl_Parse(). But we will instead
366 ** just do a search for forbidden characters. If any of the forbidden
367 ** characters appear in pCmd, we will report the string as unsafe.
368 */
369 const char *z;
370 int n;
371 z = Tcl_GetStringFromObj(pCmd, &n);
372 while( n-- > 0 ){
373 int c = *(z++);
374 if( c=='$' || c=='[' || c==';' ) return 0;
375 }
376 return 1;
377}
378
379/*
380** Find an SqlFunc structure with the given name. Or create a new
381** one if an existing one cannot be found. Return a pointer to the
382** structure.
383*/
384static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
385 SqlFunc *p, *pNew;
386 int i;
387 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen(zName) + 1 );
388 pNew->zName = (char*)&pNew[1];
389 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
390 pNew->zName[i] = 0;
391 for(p=pDb->pFunc; p; p=p->pNext){
392 if( strcmp(p->zName, pNew->zName)==0 ){
393 Tcl_Free((char*)pNew);
394 return p;
395 }
396 }
397 pNew->interp = pDb->interp;
398 pNew->pScript = 0;
399 pNew->pNext = pDb->pFunc;
400 pDb->pFunc = pNew;
401 return pNew;
402}
403
404/*
drhfb7e7652005-01-24 00:28:42 +0000405** Finalize and free a list of prepared statements
406*/
407static void flushStmtCache( SqliteDb *pDb ){
408 SqlPreparedStmt *pPreStmt;
409
410 while( pDb->stmtList ){
411 sqlite3_finalize( pDb->stmtList->pStmt );
412 pPreStmt = pDb->stmtList;
413 pDb->stmtList = pDb->stmtList->pNext;
414 Tcl_Free( (char*)pPreStmt );
415 }
416 pDb->nStmt = 0;
417 pDb->stmtLast = 0;
418}
419
420/*
drh895d7472004-08-20 16:02:39 +0000421** TCL calls this procedure when an sqlite3 database command is
422** deleted.
drh75897232000-05-29 14:26:00 +0000423*/
424static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000425 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000426 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000427 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000428 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000429 while( pDb->pFunc ){
430 SqlFunc *pFunc = pDb->pFunc;
431 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000432 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000433 Tcl_Free((char*)pFunc);
434 }
danielk19770202b292004-06-09 09:55:16 +0000435 while( pDb->pCollate ){
436 SqlCollate *pCollate = pDb->pCollate;
437 pDb->pCollate = pCollate->pNext;
438 Tcl_Free((char*)pCollate);
439 }
drhbec3f402000-08-04 13:49:02 +0000440 if( pDb->zBusy ){
441 Tcl_Free(pDb->zBusy);
442 }
drhb5a20d32003-04-23 12:25:23 +0000443 if( pDb->zTrace ){
444 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000445 }
drh19e2d372005-08-29 23:00:03 +0000446 if( pDb->zProfile ){
447 Tcl_Free(pDb->zProfile);
448 }
drhe22a3342003-04-22 20:30:37 +0000449 if( pDb->zAuth ){
450 Tcl_Free(pDb->zAuth);
451 }
danielk197755c45f22005-04-03 23:54:43 +0000452 if( pDb->zNull ){
453 Tcl_Free(pDb->zNull);
454 }
danielk197794eb6a12005-12-15 15:22:08 +0000455 if( pDb->pUpdateHook ){
456 Tcl_DecrRefCount(pDb->pUpdateHook);
457 }
danielk197771fd80b2005-12-16 06:54:01 +0000458 if( pDb->pRollbackHook ){
459 Tcl_DecrRefCount(pDb->pRollbackHook);
460 }
danielk197794eb6a12005-12-15 15:22:08 +0000461 if( pDb->pCollateNeeded ){
462 Tcl_DecrRefCount(pDb->pCollateNeeded);
463 }
drhbec3f402000-08-04 13:49:02 +0000464 Tcl_Free((char*)pDb);
465}
466
467/*
468** This routine is called when a database file is locked while trying
469** to execute SQL.
470*/
danielk19772a764eb2004-06-12 01:43:26 +0000471static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000472 SqliteDb *pDb = (SqliteDb*)cd;
473 int rc;
474 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000475
drh5bb3eb92007-05-04 13:15:55 +0000476 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000477 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000478 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
479 return 0;
480 }
481 return 1;
drh75897232000-05-29 14:26:00 +0000482}
483
drh26e4a8b2008-05-01 17:16:52 +0000484#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh75897232000-05-29 14:26:00 +0000485/*
danielk1977348bb5d2003-10-18 09:37:26 +0000486** This routine is invoked as the 'progress callback' for the database.
487*/
488static int DbProgressHandler(void *cd){
489 SqliteDb *pDb = (SqliteDb*)cd;
490 int rc;
491
492 assert( pDb->zProgress );
493 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
494 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
495 return 1;
496 }
497 return 0;
498}
drh26e4a8b2008-05-01 17:16:52 +0000499#endif
danielk1977348bb5d2003-10-18 09:37:26 +0000500
drhd1167392006-01-23 13:00:35 +0000501#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000502/*
drhb5a20d32003-04-23 12:25:23 +0000503** This routine is called by the SQLite trace handler whenever a new
504** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000505*/
drhb5a20d32003-04-23 12:25:23 +0000506static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000507 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000508 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000509
drhb5a20d32003-04-23 12:25:23 +0000510 Tcl_DStringInit(&str);
511 Tcl_DStringAppend(&str, pDb->zTrace, -1);
512 Tcl_DStringAppendElement(&str, zSql);
513 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
514 Tcl_DStringFree(&str);
515 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000516}
drhd1167392006-01-23 13:00:35 +0000517#endif
drh0d1a6432003-04-03 15:46:04 +0000518
drhd1167392006-01-23 13:00:35 +0000519#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000520/*
drh19e2d372005-08-29 23:00:03 +0000521** This routine is called by the SQLite profile handler after a statement
522** SQL has executed. The TCL script in pDb->zProfile is evaluated.
523*/
524static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
525 SqliteDb *pDb = (SqliteDb*)cd;
526 Tcl_DString str;
527 char zTm[100];
528
529 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
530 Tcl_DStringInit(&str);
531 Tcl_DStringAppend(&str, pDb->zProfile, -1);
532 Tcl_DStringAppendElement(&str, zSql);
533 Tcl_DStringAppendElement(&str, zTm);
534 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
535 Tcl_DStringFree(&str);
536 Tcl_ResetResult(pDb->interp);
537}
drhd1167392006-01-23 13:00:35 +0000538#endif
drh19e2d372005-08-29 23:00:03 +0000539
540/*
drhaa940ea2004-01-15 02:44:03 +0000541** This routine is called when a transaction is committed. The
542** TCL script in pDb->zCommit is executed. If it returns non-zero or
543** if it throws an exception, the transaction is rolled back instead
544** of being committed.
545*/
546static int DbCommitHandler(void *cd){
547 SqliteDb *pDb = (SqliteDb*)cd;
548 int rc;
549
550 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
551 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
552 return 1;
553 }
554 return 0;
555}
556
danielk197771fd80b2005-12-16 06:54:01 +0000557static void DbRollbackHandler(void *clientData){
558 SqliteDb *pDb = (SqliteDb*)clientData;
559 assert(pDb->pRollbackHook);
560 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
561 Tcl_BackgroundError(pDb->interp);
562 }
563}
564
danielk197794eb6a12005-12-15 15:22:08 +0000565static void DbUpdateHandler(
566 void *p,
567 int op,
568 const char *zDb,
569 const char *zTbl,
570 sqlite_int64 rowid
571){
572 SqliteDb *pDb = (SqliteDb *)p;
573 Tcl_Obj *pCmd;
574
575 assert( pDb->pUpdateHook );
576 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
577
578 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
579 Tcl_IncrRefCount(pCmd);
580 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
581 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
582 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
583 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
584 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
585 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
586}
587
danielk19777cedc8d2004-06-10 10:50:08 +0000588static void tclCollateNeeded(
589 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000590 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000591 int enc,
592 const char *zName
593){
594 SqliteDb *pDb = (SqliteDb *)pCtx;
595 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
596 Tcl_IncrRefCount(pScript);
597 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
598 Tcl_EvalObjEx(pDb->interp, pScript, 0);
599 Tcl_DecrRefCount(pScript);
600}
601
drhaa940ea2004-01-15 02:44:03 +0000602/*
danielk19770202b292004-06-09 09:55:16 +0000603** This routine is called to evaluate an SQL collation function implemented
604** using TCL script.
605*/
606static int tclSqlCollate(
607 void *pCtx,
608 int nA,
609 const void *zA,
610 int nB,
611 const void *zB
612){
613 SqlCollate *p = (SqlCollate *)pCtx;
614 Tcl_Obj *pCmd;
615
616 pCmd = Tcl_NewStringObj(p->zScript, -1);
617 Tcl_IncrRefCount(pCmd);
618 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
619 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000620 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000621 Tcl_DecrRefCount(pCmd);
622 return (atoi(Tcl_GetStringResult(p->interp)));
623}
624
625/*
drhcabb0812002-09-14 13:47:32 +0000626** This routine is called to evaluate an SQL function implemented
627** using TCL script.
628*/
drhfb7e7652005-01-24 00:28:42 +0000629static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000630 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000631 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000632 int i;
633 int rc;
634
drhd1e47332005-06-26 17:55:33 +0000635 if( argc==0 ){
636 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
637 ** script object directly. This allows the TCL compiler to generate
638 ** bytecode for the command on the first invocation and thus make
639 ** subsequent invocations much faster. */
640 pCmd = p->pScript;
641 Tcl_IncrRefCount(pCmd);
642 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
643 Tcl_DecrRefCount(pCmd);
644 }else{
645 /* If there are arguments to the function, make a shallow copy of the
646 ** script object, lappend the arguments, then evaluate the copy.
647 **
648 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
649 ** The new Tcl_Obj contains pointers to the original list elements.
650 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
651 ** of the list to tclCmdNameType, that alternate representation will
652 ** be preserved and reused on the next invocation.
653 */
654 Tcl_Obj **aArg;
655 int nArg;
656 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
657 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
658 return;
659 }
660 pCmd = Tcl_NewListObj(nArg, aArg);
661 Tcl_IncrRefCount(pCmd);
662 for(i=0; i<argc; i++){
663 sqlite3_value *pIn = argv[i];
664 Tcl_Obj *pVal;
665
666 /* Set pVal to contain the i'th column of this row. */
667 switch( sqlite3_value_type(pIn) ){
668 case SQLITE_BLOB: {
669 int bytes = sqlite3_value_bytes(pIn);
670 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
671 break;
672 }
673 case SQLITE_INTEGER: {
674 sqlite_int64 v = sqlite3_value_int64(pIn);
675 if( v>=-2147483647 && v<=2147483647 ){
676 pVal = Tcl_NewIntObj(v);
677 }else{
678 pVal = Tcl_NewWideIntObj(v);
679 }
680 break;
681 }
682 case SQLITE_FLOAT: {
683 double r = sqlite3_value_double(pIn);
684 pVal = Tcl_NewDoubleObj(r);
685 break;
686 }
687 case SQLITE_NULL: {
688 pVal = Tcl_NewStringObj("", 0);
689 break;
690 }
691 default: {
692 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000693 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000694 break;
695 }
696 }
697 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
698 if( rc ){
699 Tcl_DecrRefCount(pCmd);
700 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
701 return;
702 }
danielk197751ad0ec2004-05-24 12:39:02 +0000703 }
drhd1e47332005-06-26 17:55:33 +0000704 if( !p->useEvalObjv ){
705 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
706 ** is a list without a string representation. To prevent this from
707 ** happening, make sure pCmd has a valid string representation */
708 Tcl_GetString(pCmd);
709 }
710 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
711 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000712 }
danielk1977562e8d32005-05-20 09:40:55 +0000713
drhc7f269d2005-05-05 10:30:29 +0000714 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000715 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000716 }else{
drhc7f269d2005-05-05 10:30:29 +0000717 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
718 int n;
719 u8 *data;
720 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
721 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000722 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000723 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000724 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000725 data = Tcl_GetByteArrayFromObj(pVar, &n);
726 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drh985e0c62007-06-26 22:55:37 +0000727 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drhc7f269d2005-05-05 10:30:29 +0000728 Tcl_GetIntFromObj(0, pVar, &n);
729 sqlite3_result_int(context, n);
730 }else if( c=='d' && strcmp(zType,"double")==0 ){
731 double r;
732 Tcl_GetDoubleFromObj(0, pVar, &r);
733 sqlite3_result_double(context, r);
drh985e0c62007-06-26 22:55:37 +0000734 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
735 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +0000736 Tcl_WideInt v;
737 Tcl_GetWideIntFromObj(0, pVar, &v);
738 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000739 }else{
danielk197700fd9572005-12-07 06:27:43 +0000740 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
741 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000742 }
drhcabb0812002-09-14 13:47:32 +0000743 }
744}
drh895d7472004-08-20 16:02:39 +0000745
drhe22a3342003-04-22 20:30:37 +0000746#ifndef SQLITE_OMIT_AUTHORIZATION
747/*
748** This is the authentication function. It appends the authentication
749** type code and the two arguments to zCmd[] then invokes the result
750** on the interpreter. The reply is examined to determine if the
751** authentication fails or succeeds.
752*/
753static int auth_callback(
754 void *pArg,
755 int code,
756 const char *zArg1,
757 const char *zArg2,
758 const char *zArg3,
759 const char *zArg4
760){
761 char *zCode;
762 Tcl_DString str;
763 int rc;
764 const char *zReply;
765 SqliteDb *pDb = (SqliteDb*)pArg;
drh1f1549f2008-08-26 21:33:34 +0000766 if( pDb->disableAuth ) return SQLITE_OK;
drhe22a3342003-04-22 20:30:37 +0000767
768 switch( code ){
769 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
770 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
771 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
772 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
773 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
774 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
775 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
776 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
777 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
778 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
779 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
780 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
781 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
782 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
783 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
784 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
785 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
786 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
787 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
788 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
789 case SQLITE_READ : zCode="SQLITE_READ"; break;
790 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
791 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
792 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000793 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
794 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000795 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000796 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000797 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000798 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
799 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000800 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
drhe22a3342003-04-22 20:30:37 +0000801 default : zCode="????"; break;
802 }
803 Tcl_DStringInit(&str);
804 Tcl_DStringAppend(&str, pDb->zAuth, -1);
805 Tcl_DStringAppendElement(&str, zCode);
806 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
807 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
808 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
809 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
810 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
811 Tcl_DStringFree(&str);
812 zReply = Tcl_GetStringResult(pDb->interp);
813 if( strcmp(zReply,"SQLITE_OK")==0 ){
814 rc = SQLITE_OK;
815 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
816 rc = SQLITE_DENY;
817 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
818 rc = SQLITE_IGNORE;
819 }else{
820 rc = 999;
821 }
822 return rc;
823}
824#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000825
826/*
danielk1977ef2cb632004-05-29 02:37:19 +0000827** zText is a pointer to text obtained via an sqlite3_result_text()
828** or similar interface. This routine returns a Tcl string object,
829** reference count set to 0, containing the text. If a translation
830** between iso8859 and UTF-8 is required, it is preformed.
831*/
832static Tcl_Obj *dbTextToObj(char const *zText){
833 Tcl_Obj *pVal;
834#ifdef UTF_TRANSLATION_NEEDED
835 Tcl_DString dCol;
836 Tcl_DStringInit(&dCol);
837 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
838 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
839 Tcl_DStringFree(&dCol);
840#else
841 pVal = Tcl_NewStringObj(zText, -1);
842#endif
843 return pVal;
844}
845
846/*
tpoindex1067fe12004-12-17 15:41:11 +0000847** This routine reads a line of text from FILE in, stores
848** the text in memory obtained from malloc() and returns a pointer
849** to the text. NULL is returned at end of file, or if malloc()
850** fails.
851**
852** The interface is like "readline" but no command-line editing
853** is done.
854**
855** copied from shell.c from '.import' command
856*/
857static char *local_getline(char *zPrompt, FILE *in){
858 char *zLine;
859 int nLine;
860 int n;
861 int eol;
862
863 nLine = 100;
864 zLine = malloc( nLine );
865 if( zLine==0 ) return 0;
866 n = 0;
867 eol = 0;
868 while( !eol ){
869 if( n+100>nLine ){
870 nLine = nLine*2 + 100;
871 zLine = realloc(zLine, nLine);
872 if( zLine==0 ) return 0;
873 }
874 if( fgets(&zLine[n], nLine - n, in)==0 ){
875 if( n==0 ){
876 free(zLine);
877 return 0;
878 }
879 zLine[n] = 0;
880 eol = 1;
881 break;
882 }
883 while( zLine[n] ){ n++; }
884 if( n>0 && zLine[n-1]=='\n' ){
885 n--;
886 zLine[n] = 0;
887 eol = 1;
888 }
889 }
890 zLine = realloc( zLine, n+1 );
891 return zLine;
892}
893
danielk19778e556522007-11-13 10:30:24 +0000894
895/*
896** Figure out the column names for the data returned by the statement
897** passed as the second argument.
898**
899** If parameter papColName is not NULL, then *papColName is set to point
900** at an array allocated using Tcl_Alloc(). It is the callers responsibility
901** to free this array using Tcl_Free(), and to decrement the reference
902** count of each Tcl_Obj* member of the array.
903**
904** The return value of this function is the number of columns of data
905** returned by pStmt (and hence the size of the *papColName array).
906**
907** If pArray is not NULL, then it contains the name of a Tcl array
908** variable. The "*" member of this array is set to a list containing
909** the names of the columns returned by the statement, in order from
910** left to right. e.g. if the names of the returned columns are a, b and
911** c, it does the equivalent of the tcl command:
912**
913** set ${pArray}(*) {a b c}
914*/
915static int
916computeColumnNames(
917 Tcl_Interp *interp,
918 sqlite3_stmt *pStmt, /* SQL statement */
919 Tcl_Obj ***papColName, /* OUT: Array of column names */
920 Tcl_Obj *pArray /* Name of array variable (may be null) */
921){
922 int nCol;
923
924 /* Compute column names */
925 nCol = sqlite3_column_count(pStmt);
926 if( papColName ){
927 int i;
928 Tcl_Obj **apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
929 for(i=0; i<nCol; i++){
930 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
931 Tcl_IncrRefCount(apColName[i]);
932 }
933
934 /* If results are being stored in an array variable, then create
935 ** the array(*) entry for that array
936 */
937 if( pArray ){
938 Tcl_Obj *pColList = Tcl_NewObj();
939 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
940 Tcl_IncrRefCount(pColList);
941 for(i=0; i<nCol; i++){
942 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
943 }
944 Tcl_IncrRefCount(pStar);
945 Tcl_ObjSetVar2(interp, pArray, pStar, pColList,0);
946 Tcl_DecrRefCount(pColList);
947 Tcl_DecrRefCount(pStar);
948 }
949 *papColName = apColName;
950 }
951
952 return nCol;
953}
954
tpoindex1067fe12004-12-17 15:41:11 +0000955/*
drh75897232000-05-29 14:26:00 +0000956** The "sqlite" command below creates a new Tcl command for each
957** connection it opens to an SQLite database. This routine is invoked
958** whenever one of those connection-specific commands is executed
959** in Tcl. For example, if you run Tcl code like this:
960**
drh9bb575f2004-09-06 17:24:11 +0000961** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +0000962** db1 close
963**
964** The first command opens a connection to the "my_database" database
965** and calls that connection "db1". The second command causes this
966** subroutine to be invoked.
967*/
drh6d313162000-09-21 13:01:35 +0000968static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +0000969 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +0000970 int choice;
drh22fbcb82004-02-01 01:22:50 +0000971 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +0000972 static const char *DB_strs[] = {
drhfb7e7652005-01-24 00:28:42 +0000973 "authorizer", "busy", "cache",
974 "changes", "close", "collate",
975 "collation_needed", "commit_hook", "complete",
drh41449052006-07-06 17:08:48 +0000976 "copy", "enable_load_extension","errorcode",
977 "eval", "exists", "function",
drh59fffd02007-06-19 17:48:57 +0000978 "incrblob", "interrupt", "last_insert_rowid",
979 "nullvalue", "onecolumn", "profile",
980 "progress", "rekey", "rollback_hook",
drhd1d38482008-10-07 23:46:38 +0000981 "status", "timeout", "total_changes",
982 "trace", "transaction", "update_hook",
983 "version", 0
drh6d313162000-09-21 13:01:35 +0000984 };
drh411995d2002-06-25 19:31:18 +0000985 enum DB_enum {
drhfb7e7652005-01-24 00:28:42 +0000986 DB_AUTHORIZER, DB_BUSY, DB_CACHE,
987 DB_CHANGES, DB_CLOSE, DB_COLLATE,
988 DB_COLLATION_NEEDED, DB_COMMIT_HOOK, DB_COMPLETE,
drh41449052006-07-06 17:08:48 +0000989 DB_COPY, DB_ENABLE_LOAD_EXTENSION,DB_ERRORCODE,
990 DB_EVAL, DB_EXISTS, DB_FUNCTION,
drh59fffd02007-06-19 17:48:57 +0000991 DB_INCRBLOB, DB_INTERRUPT, DB_LAST_INSERT_ROWID,
992 DB_NULLVALUE, DB_ONECOLUMN, DB_PROFILE,
993 DB_PROGRESS, DB_REKEY, DB_ROLLBACK_HOOK,
drhd1d38482008-10-07 23:46:38 +0000994 DB_STATUS, DB_TIMEOUT, DB_TOTAL_CHANGES,
995 DB_TRACE, DB_TRANSACTION, DB_UPDATE_HOOK,
996 DB_VERSION
drh6d313162000-09-21 13:01:35 +0000997 };
tpoindex1067fe12004-12-17 15:41:11 +0000998 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +0000999
1000 if( objc<2 ){
1001 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +00001002 return TCL_ERROR;
1003 }
drh411995d2002-06-25 19:31:18 +00001004 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +00001005 return TCL_ERROR;
1006 }
1007
drh411995d2002-06-25 19:31:18 +00001008 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +00001009
drhe22a3342003-04-22 20:30:37 +00001010 /* $db authorizer ?CALLBACK?
1011 **
1012 ** Invoke the given callback to authorize each SQL operation as it is
1013 ** compiled. 5 arguments are appended to the callback before it is
1014 ** invoked:
1015 **
1016 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1017 ** (2) First descriptive name (depends on authorization type)
1018 ** (3) Second descriptive name
1019 ** (4) Name of the database (ex: "main", "temp")
1020 ** (5) Name of trigger that is doing the access
1021 **
1022 ** The callback should return on of the following strings: SQLITE_OK,
1023 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
1024 **
1025 ** If this method is invoked with no arguments, the current authorization
1026 ** callback string is returned.
1027 */
1028 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +00001029#ifdef SQLITE_OMIT_AUTHORIZATION
1030 Tcl_AppendResult(interp, "authorization not available in this build", 0);
1031 return TCL_ERROR;
1032#else
drhe22a3342003-04-22 20:30:37 +00001033 if( objc>3 ){
1034 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +00001035 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +00001036 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +00001037 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +00001038 Tcl_AppendResult(interp, pDb->zAuth, 0);
1039 }
1040 }else{
1041 char *zAuth;
1042 int len;
1043 if( pDb->zAuth ){
1044 Tcl_Free(pDb->zAuth);
1045 }
1046 zAuth = Tcl_GetStringFromObj(objv[2], &len);
1047 if( zAuth && len>0 ){
1048 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001049 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +00001050 }else{
1051 pDb->zAuth = 0;
1052 }
drhe22a3342003-04-22 20:30:37 +00001053 if( pDb->zAuth ){
1054 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001055 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +00001056 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001057 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +00001058 }
drhe22a3342003-04-22 20:30:37 +00001059 }
drh1211de32004-07-26 12:24:22 +00001060#endif
drhe22a3342003-04-22 20:30:37 +00001061 break;
1062 }
1063
drhbec3f402000-08-04 13:49:02 +00001064 /* $db busy ?CALLBACK?
1065 **
1066 ** Invoke the given callback if an SQL statement attempts to open
1067 ** a locked database file.
1068 */
drh6d313162000-09-21 13:01:35 +00001069 case DB_BUSY: {
1070 if( objc>3 ){
1071 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001072 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001073 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001074 if( pDb->zBusy ){
1075 Tcl_AppendResult(interp, pDb->zBusy, 0);
1076 }
1077 }else{
drh6d313162000-09-21 13:01:35 +00001078 char *zBusy;
1079 int len;
drhbec3f402000-08-04 13:49:02 +00001080 if( pDb->zBusy ){
1081 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001082 }
drh6d313162000-09-21 13:01:35 +00001083 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1084 if( zBusy && len>0 ){
1085 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001086 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001087 }else{
1088 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001089 }
1090 if( pDb->zBusy ){
1091 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001092 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001093 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001094 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001095 }
1096 }
drh6d313162000-09-21 13:01:35 +00001097 break;
1098 }
drhbec3f402000-08-04 13:49:02 +00001099
drhfb7e7652005-01-24 00:28:42 +00001100 /* $db cache flush
1101 ** $db cache size n
1102 **
1103 ** Flush the prepared statement cache, or set the maximum number of
1104 ** cached statements.
1105 */
1106 case DB_CACHE: {
1107 char *subCmd;
1108 int n;
1109
1110 if( objc<=2 ){
1111 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1112 return TCL_ERROR;
1113 }
1114 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1115 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1116 if( objc!=3 ){
1117 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1118 return TCL_ERROR;
1119 }else{
1120 flushStmtCache( pDb );
1121 }
1122 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1123 if( objc!=4 ){
1124 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1125 return TCL_ERROR;
1126 }else{
1127 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1128 Tcl_AppendResult( interp, "cannot convert \"",
1129 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1130 return TCL_ERROR;
1131 }else{
1132 if( n<0 ){
1133 flushStmtCache( pDb );
1134 n = 0;
1135 }else if( n>MAX_PREPARED_STMTS ){
1136 n = MAX_PREPARED_STMTS;
1137 }
1138 pDb->maxStmt = n;
1139 }
1140 }
1141 }else{
1142 Tcl_AppendResult( interp, "bad option \"",
danielk1977191fadc2007-10-23 08:17:48 +00001143 Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
drhfb7e7652005-01-24 00:28:42 +00001144 return TCL_ERROR;
1145 }
1146 break;
1147 }
1148
danielk1977b28af712004-06-21 06:50:26 +00001149 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001150 **
1151 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001152 ** the most recent INSERT, UPDATE or DELETE statement, not including
1153 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001154 */
1155 case DB_CHANGES: {
1156 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001157 if( objc!=2 ){
1158 Tcl_WrongNumArgs(interp, 2, objv, "");
1159 return TCL_ERROR;
1160 }
drhc8d30ac2002-04-12 10:08:59 +00001161 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001162 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001163 break;
1164 }
1165
drh75897232000-05-29 14:26:00 +00001166 /* $db close
1167 **
1168 ** Shutdown the database
1169 */
drh6d313162000-09-21 13:01:35 +00001170 case DB_CLOSE: {
1171 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1172 break;
1173 }
drh75897232000-05-29 14:26:00 +00001174
drh0f14e2e2004-06-29 12:39:08 +00001175 /*
1176 ** $db collate NAME SCRIPT
1177 **
1178 ** Create a new SQL collation function called NAME. Whenever
1179 ** that function is called, invoke SCRIPT to evaluate the function.
1180 */
1181 case DB_COLLATE: {
1182 SqlCollate *pCollate;
1183 char *zName;
1184 char *zScript;
1185 int nScript;
1186 if( objc!=4 ){
1187 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1188 return TCL_ERROR;
1189 }
1190 zName = Tcl_GetStringFromObj(objv[2], 0);
1191 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1192 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1193 if( pCollate==0 ) return TCL_ERROR;
1194 pCollate->interp = interp;
1195 pCollate->pNext = pDb->pCollate;
1196 pCollate->zScript = (char*)&pCollate[1];
1197 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001198 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001199 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1200 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001201 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001202 return TCL_ERROR;
1203 }
1204 break;
1205 }
1206
1207 /*
1208 ** $db collation_needed SCRIPT
1209 **
1210 ** Create a new SQL collation function called NAME. Whenever
1211 ** that function is called, invoke SCRIPT to evaluate the function.
1212 */
1213 case DB_COLLATION_NEEDED: {
1214 if( objc!=3 ){
1215 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1216 return TCL_ERROR;
1217 }
1218 if( pDb->pCollateNeeded ){
1219 Tcl_DecrRefCount(pDb->pCollateNeeded);
1220 }
1221 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1222 Tcl_IncrRefCount(pDb->pCollateNeeded);
1223 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1224 break;
1225 }
1226
drh19e2d372005-08-29 23:00:03 +00001227 /* $db commit_hook ?CALLBACK?
1228 **
1229 ** Invoke the given callback just before committing every SQL transaction.
1230 ** If the callback throws an exception or returns non-zero, then the
1231 ** transaction is aborted. If CALLBACK is an empty string, the callback
1232 ** is disabled.
1233 */
1234 case DB_COMMIT_HOOK: {
1235 if( objc>3 ){
1236 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1237 return TCL_ERROR;
1238 }else if( objc==2 ){
1239 if( pDb->zCommit ){
1240 Tcl_AppendResult(interp, pDb->zCommit, 0);
1241 }
1242 }else{
1243 char *zCommit;
1244 int len;
1245 if( pDb->zCommit ){
1246 Tcl_Free(pDb->zCommit);
1247 }
1248 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1249 if( zCommit && len>0 ){
1250 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001251 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001252 }else{
1253 pDb->zCommit = 0;
1254 }
1255 if( pDb->zCommit ){
1256 pDb->interp = interp;
1257 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1258 }else{
1259 sqlite3_commit_hook(pDb->db, 0, 0);
1260 }
1261 }
1262 break;
1263 }
1264
drh75897232000-05-29 14:26:00 +00001265 /* $db complete SQL
1266 **
1267 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1268 ** additional lines of input are needed. This is similar to the
1269 ** built-in "info complete" command of Tcl.
1270 */
drh6d313162000-09-21 13:01:35 +00001271 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00001272#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00001273 Tcl_Obj *pResult;
1274 int isComplete;
1275 if( objc!=3 ){
1276 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00001277 return TCL_ERROR;
1278 }
danielk19776f8a5032004-05-10 10:34:51 +00001279 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00001280 pResult = Tcl_GetObjResult(interp);
1281 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00001282#endif
drh6d313162000-09-21 13:01:35 +00001283 break;
1284 }
drhdcd997e2003-01-31 17:21:49 +00001285
drh19e2d372005-08-29 23:00:03 +00001286 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1287 **
1288 ** Copy data into table from filename, optionally using SEPARATOR
1289 ** as column separators. If a column contains a null string, or the
1290 ** value of NULLINDICATOR, a NULL is inserted for the column.
1291 ** conflict-algorithm is one of the sqlite conflict algorithms:
1292 ** rollback, abort, fail, ignore, replace
1293 ** On success, return the number of lines processed, not necessarily same
1294 ** as 'db changes' due to conflict-algorithm selected.
1295 **
1296 ** This code is basically an implementation/enhancement of
1297 ** the sqlite3 shell.c ".import" command.
1298 **
1299 ** This command usage is equivalent to the sqlite2.x COPY statement,
1300 ** which imports file data into a table using the PostgreSQL COPY file format:
1301 ** $db copy $conflit_algo $table_name $filename \t \\N
1302 */
1303 case DB_COPY: {
1304 char *zTable; /* Insert data into this table */
1305 char *zFile; /* The file from which to extract data */
1306 char *zConflict; /* The conflict algorithm to use */
1307 sqlite3_stmt *pStmt; /* A statement */
drh19e2d372005-08-29 23:00:03 +00001308 int nCol; /* Number of columns in the table */
1309 int nByte; /* Number of bytes in an SQL string */
1310 int i, j; /* Loop counters */
1311 int nSep; /* Number of bytes in zSep[] */
1312 int nNull; /* Number of bytes in zNull[] */
1313 char *zSql; /* An SQL statement */
1314 char *zLine; /* A single line of input from the file */
1315 char **azCol; /* zLine[] broken up into columns */
1316 char *zCommit; /* How to commit changes */
1317 FILE *in; /* The input file */
1318 int lineno = 0; /* Line number of input file */
1319 char zLineNum[80]; /* Line number print buffer */
1320 Tcl_Obj *pResult; /* interp result */
1321
1322 char *zSep;
1323 char *zNull;
1324 if( objc<5 || objc>7 ){
1325 Tcl_WrongNumArgs(interp, 2, objv,
1326 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1327 return TCL_ERROR;
1328 }
1329 if( objc>=6 ){
1330 zSep = Tcl_GetStringFromObj(objv[5], 0);
1331 }else{
1332 zSep = "\t";
1333 }
1334 if( objc>=7 ){
1335 zNull = Tcl_GetStringFromObj(objv[6], 0);
1336 }else{
1337 zNull = "";
1338 }
1339 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1340 zTable = Tcl_GetStringFromObj(objv[3], 0);
1341 zFile = Tcl_GetStringFromObj(objv[4], 0);
1342 nSep = strlen(zSep);
1343 nNull = strlen(zNull);
1344 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00001345 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00001346 return TCL_ERROR;
1347 }
drh3e59c012008-09-23 10:12:13 +00001348 if(strcmp(zConflict, "rollback") != 0 &&
1349 strcmp(zConflict, "abort" ) != 0 &&
1350 strcmp(zConflict, "fail" ) != 0 &&
1351 strcmp(zConflict, "ignore" ) != 0 &&
1352 strcmp(zConflict, "replace" ) != 0 ) {
drh19e2d372005-08-29 23:00:03 +00001353 Tcl_AppendResult(interp, "Error: \"", zConflict,
1354 "\", conflict-algorithm must be one of: rollback, "
1355 "abort, fail, ignore, or replace", 0);
1356 return TCL_ERROR;
1357 }
1358 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1359 if( zSql==0 ){
1360 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1361 return TCL_ERROR;
1362 }
1363 nByte = strlen(zSql);
drh3e701a12007-02-01 01:53:44 +00001364 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001365 sqlite3_free(zSql);
1366 if( rc ){
1367 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1368 nCol = 0;
1369 }else{
1370 nCol = sqlite3_column_count(pStmt);
1371 }
1372 sqlite3_finalize(pStmt);
1373 if( nCol==0 ) {
1374 return TCL_ERROR;
1375 }
1376 zSql = malloc( nByte + 50 + nCol*2 );
1377 if( zSql==0 ) {
1378 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1379 return TCL_ERROR;
1380 }
1381 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1382 zConflict, zTable);
1383 j = strlen(zSql);
1384 for(i=1; i<nCol; i++){
1385 zSql[j++] = ',';
1386 zSql[j++] = '?';
1387 }
1388 zSql[j++] = ')';
1389 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00001390 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001391 free(zSql);
1392 if( rc ){
1393 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1394 sqlite3_finalize(pStmt);
1395 return TCL_ERROR;
1396 }
1397 in = fopen(zFile, "rb");
1398 if( in==0 ){
1399 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
1400 sqlite3_finalize(pStmt);
1401 return TCL_ERROR;
1402 }
1403 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1404 if( azCol==0 ) {
1405 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00001406 fclose(in);
drh19e2d372005-08-29 23:00:03 +00001407 return TCL_ERROR;
1408 }
drh37527852006-03-16 16:19:56 +00001409 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001410 zCommit = "COMMIT";
1411 while( (zLine = local_getline(0, in))!=0 ){
1412 char *z;
1413 i = 0;
1414 lineno++;
1415 azCol[0] = zLine;
1416 for(i=0, z=zLine; *z; z++){
1417 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
1418 *z = 0;
1419 i++;
1420 if( i<nCol ){
1421 azCol[i] = &z[nSep];
1422 z += nSep-1;
1423 }
1424 }
1425 }
1426 if( i+1!=nCol ){
1427 char *zErr;
drh5bb3eb92007-05-04 13:15:55 +00001428 int nErr = strlen(zFile) + 200;
1429 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00001430 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00001431 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00001432 "Error: %s line %d: expected %d columns of data but found %d",
1433 zFile, lineno, nCol, i+1);
1434 Tcl_AppendResult(interp, zErr, 0);
1435 free(zErr);
1436 }
drh19e2d372005-08-29 23:00:03 +00001437 zCommit = "ROLLBACK";
1438 break;
1439 }
1440 for(i=0; i<nCol; i++){
1441 /* check for null data, if so, bind as null */
1442 if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
1443 sqlite3_bind_null(pStmt, i+1);
1444 }else{
1445 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1446 }
1447 }
1448 sqlite3_step(pStmt);
1449 rc = sqlite3_reset(pStmt);
1450 free(zLine);
1451 if( rc!=SQLITE_OK ){
1452 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
1453 zCommit = "ROLLBACK";
1454 break;
1455 }
1456 }
1457 free(azCol);
1458 fclose(in);
1459 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00001460 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001461
1462 if( zCommit[0] == 'C' ){
1463 /* success, set result as number of lines processed */
1464 pResult = Tcl_GetObjResult(interp);
1465 Tcl_SetIntObj(pResult, lineno);
1466 rc = TCL_OK;
1467 }else{
1468 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00001469 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00001470 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
1471 rc = TCL_ERROR;
1472 }
1473 break;
1474 }
1475
drhdcd997e2003-01-31 17:21:49 +00001476 /*
drh41449052006-07-06 17:08:48 +00001477 ** $db enable_load_extension BOOLEAN
1478 **
1479 ** Turn the extension loading feature on or off. It if off by
1480 ** default.
1481 */
1482 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00001483#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00001484 int onoff;
1485 if( objc!=3 ){
1486 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
1487 return TCL_ERROR;
1488 }
1489 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
1490 return TCL_ERROR;
1491 }
1492 sqlite3_enable_load_extension(pDb->db, onoff);
1493 break;
drhf533acc2006-12-19 18:57:11 +00001494#else
1495 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
1496 0);
1497 return TCL_ERROR;
1498#endif
drh41449052006-07-06 17:08:48 +00001499 }
1500
1501 /*
drhdcd997e2003-01-31 17:21:49 +00001502 ** $db errorcode
1503 **
1504 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00001505 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00001506 */
1507 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00001508 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00001509 break;
1510 }
drh75897232000-05-29 14:26:00 +00001511
1512 /*
drh895d7472004-08-20 16:02:39 +00001513 ** $db eval $sql ?array? ?{ ...code... }?
drh1807ce32004-09-07 13:20:35 +00001514 ** $db onecolumn $sql
drh75897232000-05-29 14:26:00 +00001515 **
1516 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00001517 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00001518 ** If "array" and "code" are omitted, then no callback is every invoked.
1519 ** If "array" is an empty string, then the values are placed in variables
1520 ** that have the same name as the fields extracted by the query.
drh1807ce32004-09-07 13:20:35 +00001521 **
1522 ** The onecolumn method is the equivalent of:
1523 ** lindex [$db eval $sql] 0
drh75897232000-05-29 14:26:00 +00001524 */
drh1807ce32004-09-07 13:20:35 +00001525 case DB_ONECOLUMN:
drh97f2ebc2005-12-10 21:19:04 +00001526 case DB_EVAL:
1527 case DB_EXISTS: {
drh9d74b4c2004-08-24 15:23:34 +00001528 char const *zSql; /* Next SQL statement to execute */
1529 char const *zLeft; /* What is left after first stmt in zSql */
1530 sqlite3_stmt *pStmt; /* Compiled SQL statment */
drh92febd92004-08-20 18:34:20 +00001531 Tcl_Obj *pArray; /* Name of array into which results are written */
1532 Tcl_Obj *pScript; /* Script to run for each result set */
drh1d895032004-08-26 00:56:05 +00001533 Tcl_Obj **apParm; /* Parameters that need a Tcl_DecrRefCount() */
1534 int nParm; /* Number of entries used in apParm[] */
1535 Tcl_Obj *aParm[10]; /* Static space for apParm[] in the common case */
drh1807ce32004-09-07 13:20:35 +00001536 Tcl_Obj *pRet; /* Value to be returned */
drhfb7e7652005-01-24 00:28:42 +00001537 SqlPreparedStmt *pPreStmt; /* Pointer to a prepared statement */
1538 int rc2;
danielk1977ef2cb632004-05-29 02:37:19 +00001539
drh97f2ebc2005-12-10 21:19:04 +00001540 if( choice==DB_EVAL ){
drh1807ce32004-09-07 13:20:35 +00001541 if( objc<3 || objc>5 ){
1542 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
1543 return TCL_ERROR;
1544 }
1545 pRet = Tcl_NewObj();
1546 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001547 }else{
1548 if( objc!=3 ){
1549 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
1550 return TCL_ERROR;
1551 }
drh97f2ebc2005-12-10 21:19:04 +00001552 if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001553 pRet = Tcl_NewBooleanObj(0);
1554 Tcl_IncrRefCount(pRet);
1555 }else{
1556 pRet = 0;
drh97f2ebc2005-12-10 21:19:04 +00001557 }
danielk197730ccda12004-05-27 12:11:31 +00001558 }
drh92febd92004-08-20 18:34:20 +00001559 if( objc==3 ){
1560 pArray = pScript = 0;
1561 }else if( objc==4 ){
1562 pArray = 0;
1563 pScript = objv[3];
1564 }else{
1565 pArray = objv[3];
1566 if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
1567 pScript = objv[4];
1568 }
danielk197730ccda12004-05-27 12:11:31 +00001569
drh1d895032004-08-26 00:56:05 +00001570 Tcl_IncrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001571 zSql = Tcl_GetStringFromObj(objv[2], 0);
drh90b6bb12004-09-13 13:16:31 +00001572 while( rc==TCL_OK && zSql[0] ){
drhfb7e7652005-01-24 00:28:42 +00001573 int i; /* Loop counter */
1574 int nVar; /* Number of bind parameters in the pStmt */
danielk19778e556522007-11-13 10:30:24 +00001575 int nCol = -1; /* Number of columns in the result set */
drh92febd92004-08-20 18:34:20 +00001576 Tcl_Obj **apColName = 0; /* Array of column names */
drhfb7e7652005-01-24 00:28:42 +00001577 int len; /* String length of zSql */
danielk197730ccda12004-05-27 12:11:31 +00001578
drhfb7e7652005-01-24 00:28:42 +00001579 /* Try to find a SQL statement that has already been compiled and
1580 ** which matches the next sequence of SQL.
1581 */
1582 pStmt = 0;
drhfb7e7652005-01-24 00:28:42 +00001583 len = strlen(zSql);
danielk19778e556522007-11-13 10:30:24 +00001584 for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
drhfb7e7652005-01-24 00:28:42 +00001585 int n = pPreStmt->nSql;
1586 if( len>=n
1587 && memcmp(pPreStmt->zSql, zSql, n)==0
1588 && (zSql[n]==0 || zSql[n-1]==';')
1589 ){
1590 pStmt = pPreStmt->pStmt;
1591 zLeft = &zSql[pPreStmt->nSql];
1592
1593 /* When a prepared statement is found, unlink it from the
1594 ** cache list. It will later be added back to the beginning
1595 ** of the cache list in order to implement LRU replacement.
1596 */
1597 if( pPreStmt->pPrev ){
1598 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1599 }else{
1600 pDb->stmtList = pPreStmt->pNext;
1601 }
1602 if( pPreStmt->pNext ){
1603 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1604 }else{
1605 pDb->stmtLast = pPreStmt->pPrev;
1606 }
1607 pDb->nStmt--;
1608 break;
1609 }
1610 }
1611
1612 /* If no prepared statement was found. Compile the SQL text
1613 */
drh92febd92004-08-20 18:34:20 +00001614 if( pStmt==0 ){
danielk19778e556522007-11-13 10:30:24 +00001615 if( SQLITE_OK!=sqlite3_prepare_v2(pDb->db, zSql, -1, &pStmt, &zLeft) ){
drh92febd92004-08-20 18:34:20 +00001616 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1617 rc = TCL_ERROR;
1618 break;
danielk197730ccda12004-05-27 12:11:31 +00001619 }
drhfb7e7652005-01-24 00:28:42 +00001620 if( pStmt==0 ){
1621 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1622 /* A compile-time error in the statement
1623 */
1624 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1625 rc = TCL_ERROR;
1626 break;
1627 }else{
1628 /* The statement was a no-op. Continue to the next statement
1629 ** in the SQL string.
1630 */
1631 zSql = zLeft;
1632 continue;
1633 }
1634 }
1635 assert( pPreStmt==0 );
danielk197730ccda12004-05-27 12:11:31 +00001636 }
1637
drhfb7e7652005-01-24 00:28:42 +00001638 /* Bind values to parameters that begin with $ or :
1639 */
drh92febd92004-08-20 18:34:20 +00001640 nVar = sqlite3_bind_parameter_count(pStmt);
drh1d895032004-08-26 00:56:05 +00001641 nParm = 0;
1642 if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
1643 apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
1644 }else{
1645 apParm = aParm;
1646 }
drh92febd92004-08-20 18:34:20 +00001647 for(i=1; i<=nVar; i++){
1648 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
drh4f5e80f2007-06-19 17:15:46 +00001649 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
drh92febd92004-08-20 18:34:20 +00001650 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1651 if( pVar ){
1652 int n;
1653 u8 *data;
1654 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
1655 char c = zType[0];
drh1c747812007-06-19 23:01:41 +00001656 if( zVar[0]=='@' ||
1657 (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1658 /* Load a BLOB type if the Tcl variable is a bytearray and
1659 ** it has no string representation or the host
drh4f5e80f2007-06-19 17:15:46 +00001660 ** parameter name begins with "@". */
drh92febd92004-08-20 18:34:20 +00001661 data = Tcl_GetByteArrayFromObj(pVar, &n);
1662 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001663 Tcl_IncrRefCount(pVar);
1664 apParm[nParm++] = pVar;
drh985e0c62007-06-26 22:55:37 +00001665 }else if( c=='b' && strcmp(zType,"boolean")==0 ){
drh92febd92004-08-20 18:34:20 +00001666 Tcl_GetIntFromObj(interp, pVar, &n);
1667 sqlite3_bind_int(pStmt, i, n);
1668 }else if( c=='d' && strcmp(zType,"double")==0 ){
1669 double r;
1670 Tcl_GetDoubleFromObj(interp, pVar, &r);
1671 sqlite3_bind_double(pStmt, i, r);
drh985e0c62007-06-26 22:55:37 +00001672 }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1673 (c=='i' && strcmp(zType,"int")==0) ){
drhdf0bdda2005-06-25 19:31:48 +00001674 Tcl_WideInt v;
1675 Tcl_GetWideIntFromObj(interp, pVar, &v);
1676 sqlite3_bind_int64(pStmt, i, v);
drh92febd92004-08-20 18:34:20 +00001677 }else{
danielk197700fd9572005-12-07 06:27:43 +00001678 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
drhb08c2a72008-04-16 00:28:13 +00001679 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001680 Tcl_IncrRefCount(pVar);
1681 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001682 }
drhfb7e7652005-01-24 00:28:42 +00001683 }else{
1684 sqlite3_bind_null( pStmt, i );
drh92febd92004-08-20 18:34:20 +00001685 }
1686 }
1687 }
drh92febd92004-08-20 18:34:20 +00001688
drh92febd92004-08-20 18:34:20 +00001689 /* Execute the SQL
1690 */
drh90b6bb12004-09-13 13:16:31 +00001691 while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
danielk19778e556522007-11-13 10:30:24 +00001692
1693 /* Compute column names. This must be done after the first successful
1694 ** call to sqlite3_step(), in case the query is recompiled and the
1695 ** number or names of the returned columns changes.
1696 */
1697 assert(!pArray||pScript);
1698 if (nCol < 0) {
1699 Tcl_Obj ***ap = (pScript?&apColName:0);
1700 nCol = computeColumnNames(interp, pStmt, ap, pArray);
1701 }
1702
drh92febd92004-08-20 18:34:20 +00001703 for(i=0; i<nCol; i++){
danielk197730ccda12004-05-27 12:11:31 +00001704 Tcl_Obj *pVal;
1705
1706 /* Set pVal to contain the i'th column of this row. */
drh92febd92004-08-20 18:34:20 +00001707 switch( sqlite3_column_type(pStmt, i) ){
1708 case SQLITE_BLOB: {
1709 int bytes = sqlite3_column_bytes(pStmt, i);
drheee4c8c2008-02-18 22:24:57 +00001710 const char *zBlob = sqlite3_column_blob(pStmt, i);
danielk1977a7a8e142008-02-13 18:25:27 +00001711 if( !zBlob ) bytes = 0;
drheee4c8c2008-02-18 22:24:57 +00001712 pVal = Tcl_NewByteArrayObj((u8*)zBlob, bytes);
drh92febd92004-08-20 18:34:20 +00001713 break;
1714 }
1715 case SQLITE_INTEGER: {
1716 sqlite_int64 v = sqlite3_column_int64(pStmt, i);
1717 if( v>=-2147483647 && v<=2147483647 ){
1718 pVal = Tcl_NewIntObj(v);
1719 }else{
1720 pVal = Tcl_NewWideIntObj(v);
1721 }
1722 break;
1723 }
1724 case SQLITE_FLOAT: {
1725 double r = sqlite3_column_double(pStmt, i);
1726 pVal = Tcl_NewDoubleObj(r);
1727 break;
1728 }
danielk197755c45f22005-04-03 23:54:43 +00001729 case SQLITE_NULL: {
1730 pVal = dbTextToObj(pDb->zNull);
1731 break;
1732 }
drh92febd92004-08-20 18:34:20 +00001733 default: {
danielk197700fd9572005-12-07 06:27:43 +00001734 pVal = dbTextToObj((char *)sqlite3_column_text(pStmt, i));
drh92febd92004-08-20 18:34:20 +00001735 break;
1736 }
danielk197730ccda12004-05-27 12:11:31 +00001737 }
1738
drh92febd92004-08-20 18:34:20 +00001739 if( pScript ){
1740 if( pArray==0 ){
1741 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001742 }else{
drh92febd92004-08-20 18:34:20 +00001743 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001744 }
drh1807ce32004-09-07 13:20:35 +00001745 }else if( choice==DB_ONECOLUMN ){
drh97f2ebc2005-12-10 21:19:04 +00001746 assert( pRet==0 );
drh1807ce32004-09-07 13:20:35 +00001747 if( pRet==0 ){
1748 pRet = pVal;
1749 Tcl_IncrRefCount(pRet);
1750 }
drh90b6bb12004-09-13 13:16:31 +00001751 rc = TCL_BREAK;
drh97f2ebc2005-12-10 21:19:04 +00001752 i = nCol;
1753 }else if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001754 Tcl_DecrRefCount(pRet);
1755 pRet = Tcl_NewBooleanObj(1);
1756 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001757 rc = TCL_BREAK;
1758 i = nCol;
danielk197730ccda12004-05-27 12:11:31 +00001759 }else{
danielk197730ccda12004-05-27 12:11:31 +00001760 Tcl_ListObjAppendElement(interp, pRet, pVal);
1761 }
1762 }
1763
drh92febd92004-08-20 18:34:20 +00001764 if( pScript ){
drhd1d38482008-10-07 23:46:38 +00001765 pDb->nStep = sqlite3_stmt_status(pStmt,
1766 SQLITE_STMTSTATUS_FULLSCAN_STEP, 0);
1767 pDb->nSort = sqlite3_stmt_status(pStmt,
1768 SQLITE_STMTSTATUS_SORT, 0);
drh92febd92004-08-20 18:34:20 +00001769 rc = Tcl_EvalObjEx(interp, pScript, 0);
drh90b6bb12004-09-13 13:16:31 +00001770 if( rc==TCL_CONTINUE ){
1771 rc = TCL_OK;
1772 }
danielk197730ccda12004-05-27 12:11:31 +00001773 }
1774 }
drh90b6bb12004-09-13 13:16:31 +00001775 if( rc==TCL_BREAK ){
1776 rc = TCL_OK;
1777 }
drh92febd92004-08-20 18:34:20 +00001778
1779 /* Free the column name objects */
1780 if( pScript ){
danielk19778e556522007-11-13 10:30:24 +00001781 /* If the query returned no rows, but an array variable was
1782 ** specified, call computeColumnNames() now to populate the
1783 ** arrayname(*) variable.
1784 */
1785 if (pArray && nCol < 0) {
1786 Tcl_Obj ***ap = (pScript?&apColName:0);
1787 nCol = computeColumnNames(interp, pStmt, ap, pArray);
1788 }
drh92febd92004-08-20 18:34:20 +00001789 for(i=0; i<nCol; i++){
1790 Tcl_DecrRefCount(apColName[i]);
1791 }
1792 Tcl_Free((char*)apColName);
1793 }
1794
drh1d895032004-08-26 00:56:05 +00001795 /* Free the bound string and blob parameters */
1796 for(i=0; i<nParm; i++){
1797 Tcl_DecrRefCount(apParm[i]);
1798 }
1799 if( apParm!=aParm ){
1800 Tcl_Free((char*)apParm);
1801 }
1802
drhfb7e7652005-01-24 00:28:42 +00001803 /* Reset the statement. If the result code is SQLITE_SCHEMA, then
1804 ** flush the statement cache and try the statement again.
drh92febd92004-08-20 18:34:20 +00001805 */
drhfb7e7652005-01-24 00:28:42 +00001806 rc2 = sqlite3_reset(pStmt);
drhd1d38482008-10-07 23:46:38 +00001807 pDb->nStep = sqlite3_stmt_status(pStmt,
1808 SQLITE_STMTSTATUS_FULLSCAN_STEP, 1);
1809 pDb->nSort = sqlite3_stmt_status(pStmt,
1810 SQLITE_STMTSTATUS_SORT, 1);
danielk19778e556522007-11-13 10:30:24 +00001811 if( SQLITE_OK!=rc2 ){
drhfb7e7652005-01-24 00:28:42 +00001812 /* If a run-time error occurs, report the error and stop reading
1813 ** the SQL
1814 */
danielk1977ef2cb632004-05-29 02:37:19 +00001815 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
drhfb7e7652005-01-24 00:28:42 +00001816 sqlite3_finalize(pStmt);
danielk197730ccda12004-05-27 12:11:31 +00001817 rc = TCL_ERROR;
drhfb7e7652005-01-24 00:28:42 +00001818 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001819 break;
drhfb7e7652005-01-24 00:28:42 +00001820 }else if( pDb->maxStmt<=0 ){
1821 /* If the cache is turned off, deallocated the statement */
1822 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1823 sqlite3_finalize(pStmt);
1824 }else{
1825 /* Everything worked and the cache is operational.
1826 ** Create a new SqlPreparedStmt structure if we need one.
1827 ** (If we already have one we can just reuse it.)
1828 */
1829 if( pPreStmt==0 ){
1830 len = zLeft - zSql;
danielk1977d0e2a852007-11-14 06:48:48 +00001831 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) );
drhfb7e7652005-01-24 00:28:42 +00001832 if( pPreStmt==0 ) return TCL_ERROR;
1833 pPreStmt->pStmt = pStmt;
1834 pPreStmt->nSql = len;
danielk1977d0e2a852007-11-14 06:48:48 +00001835 pPreStmt->zSql = sqlite3_sql(pStmt);
1836 assert( strlen(pPreStmt->zSql)==len );
1837 assert( 0==memcmp(pPreStmt->zSql, zSql, len) );
drhfb7e7652005-01-24 00:28:42 +00001838 }
1839
1840 /* Add the prepared statement to the beginning of the cache list
1841 */
1842 pPreStmt->pNext = pDb->stmtList;
1843 pPreStmt->pPrev = 0;
1844 if( pDb->stmtList ){
1845 pDb->stmtList->pPrev = pPreStmt;
1846 }
1847 pDb->stmtList = pPreStmt;
1848 if( pDb->stmtLast==0 ){
1849 assert( pDb->nStmt==0 );
1850 pDb->stmtLast = pPreStmt;
1851 }else{
1852 assert( pDb->nStmt>0 );
1853 }
1854 pDb->nStmt++;
1855
1856 /* If we have too many statement in cache, remove the surplus from the
1857 ** end of the cache list.
1858 */
1859 while( pDb->nStmt>pDb->maxStmt ){
1860 sqlite3_finalize(pDb->stmtLast->pStmt);
1861 pDb->stmtLast = pDb->stmtLast->pPrev;
1862 Tcl_Free((char*)pDb->stmtLast->pNext);
1863 pDb->stmtLast->pNext = 0;
1864 pDb->nStmt--;
1865 }
danielk197730ccda12004-05-27 12:11:31 +00001866 }
1867
drhfb7e7652005-01-24 00:28:42 +00001868 /* Proceed to the next statement */
danielk197730ccda12004-05-27 12:11:31 +00001869 zSql = zLeft;
1870 }
drh1d895032004-08-26 00:56:05 +00001871 Tcl_DecrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001872
drh1807ce32004-09-07 13:20:35 +00001873 if( pRet ){
1874 if( rc==TCL_OK ){
1875 Tcl_SetObjResult(interp, pRet);
1876 }
1877 Tcl_DecrRefCount(pRet);
drh050be322006-07-12 00:18:40 +00001878 }else if( rc==TCL_OK ){
1879 Tcl_ResetResult(interp);
danielk197730ccda12004-05-27 12:11:31 +00001880 }
danielk197730ccda12004-05-27 12:11:31 +00001881 break;
1882 }
drhbec3f402000-08-04 13:49:02 +00001883
1884 /*
drhe3602be2008-09-09 12:31:33 +00001885 ** $db function NAME [-argcount N] SCRIPT
drhcabb0812002-09-14 13:47:32 +00001886 **
1887 ** Create a new SQL function called NAME. Whenever that function is
1888 ** called, invoke SCRIPT to evaluate the function.
1889 */
1890 case DB_FUNCTION: {
1891 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00001892 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00001893 char *zName;
drhe3602be2008-09-09 12:31:33 +00001894 int nArg = -1;
1895 if( objc==6 ){
1896 const char *z = Tcl_GetString(objv[3]);
1897 int n = strlen(z);
1898 if( n>2 && strncmp(z, "-argcount",n)==0 ){
1899 if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
1900 if( nArg<0 ){
1901 Tcl_AppendResult(interp, "number of arguments must be non-negative",
1902 (char*)0);
1903 return TCL_ERROR;
1904 }
1905 }
1906 pScript = objv[5];
1907 }else if( objc!=4 ){
1908 Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
drhcabb0812002-09-14 13:47:32 +00001909 return TCL_ERROR;
drhe3602be2008-09-09 12:31:33 +00001910 }else{
1911 pScript = objv[3];
drhcabb0812002-09-14 13:47:32 +00001912 }
1913 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00001914 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00001915 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00001916 if( pFunc->pScript ){
1917 Tcl_DecrRefCount(pFunc->pScript);
1918 }
1919 pFunc->pScript = pScript;
1920 Tcl_IncrRefCount(pScript);
1921 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
drhe3602be2008-09-09 12:31:33 +00001922 rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00001923 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00001924 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00001925 rc = TCL_ERROR;
1926 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00001927 }
drhcabb0812002-09-14 13:47:32 +00001928 break;
1929 }
1930
1931 /*
danielk19778cbadb02007-05-03 16:31:26 +00001932 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00001933 */
1934 case DB_INCRBLOB: {
danielk197732a0d8b2007-05-04 19:03:02 +00001935#ifdef SQLITE_OMIT_INCRBLOB
1936 Tcl_AppendResult(interp, "incrblob not available in this build", 0);
1937 return TCL_ERROR;
1938#else
danielk19778cbadb02007-05-03 16:31:26 +00001939 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00001940 const char *zDb = "main";
1941 const char *zTable;
1942 const char *zColumn;
1943 sqlite_int64 iRow;
1944
danielk19778cbadb02007-05-03 16:31:26 +00001945 /* Check for the -readonly option */
1946 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
1947 isReadonly = 1;
1948 }
1949
1950 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
1951 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00001952 return TCL_ERROR;
1953 }
1954
danielk19778cbadb02007-05-03 16:31:26 +00001955 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00001956 zDb = Tcl_GetString(objv[2]);
1957 }
1958 zTable = Tcl_GetString(objv[objc-3]);
1959 zColumn = Tcl_GetString(objv[objc-2]);
1960 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
1961
1962 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00001963 rc = createIncrblobChannel(
1964 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
1965 );
danielk1977b4e9af92007-05-01 17:49:49 +00001966 }
danielk197732a0d8b2007-05-04 19:03:02 +00001967#endif
danielk1977b4e9af92007-05-01 17:49:49 +00001968 break;
1969 }
1970
1971 /*
drhf11bded2006-07-17 00:02:44 +00001972 ** $db interrupt
1973 **
1974 ** Interrupt the execution of the inner-most SQL interpreter. This
1975 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
1976 */
1977 case DB_INTERRUPT: {
1978 sqlite3_interrupt(pDb->db);
1979 break;
1980 }
1981
1982 /*
drh19e2d372005-08-29 23:00:03 +00001983 ** $db nullvalue ?STRING?
1984 **
1985 ** Change text used when a NULL comes back from the database. If ?STRING?
1986 ** is not present, then the current string used for NULL is returned.
1987 ** If STRING is present, then STRING is returned.
1988 **
1989 */
1990 case DB_NULLVALUE: {
1991 if( objc!=2 && objc!=3 ){
1992 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
1993 return TCL_ERROR;
1994 }
1995 if( objc==3 ){
1996 int len;
1997 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
1998 if( pDb->zNull ){
1999 Tcl_Free(pDb->zNull);
2000 }
2001 if( zNull && len>0 ){
2002 pDb->zNull = Tcl_Alloc( len + 1 );
2003 strncpy(pDb->zNull, zNull, len);
2004 pDb->zNull[len] = '\0';
2005 }else{
2006 pDb->zNull = 0;
2007 }
2008 }
2009 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
2010 break;
2011 }
2012
2013 /*
drhaf9ff332002-01-16 21:00:27 +00002014 ** $db last_insert_rowid
2015 **
2016 ** Return an integer which is the ROWID for the most recent insert.
2017 */
2018 case DB_LAST_INSERT_ROWID: {
2019 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00002020 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00002021 if( objc!=2 ){
2022 Tcl_WrongNumArgs(interp, 2, objv, "");
2023 return TCL_ERROR;
2024 }
danielk19776f8a5032004-05-10 10:34:51 +00002025 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00002026 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00002027 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00002028 break;
2029 }
2030
2031 /*
drh1807ce32004-09-07 13:20:35 +00002032 ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
drh5d9d7572003-08-19 14:31:01 +00002033 */
drh1807ce32004-09-07 13:20:35 +00002034
2035 /* $db progress ?N CALLBACK?
2036 **
2037 ** Invoke the given callback every N virtual machine opcodes while executing
2038 ** queries.
2039 */
2040 case DB_PROGRESS: {
2041 if( objc==2 ){
2042 if( pDb->zProgress ){
2043 Tcl_AppendResult(interp, pDb->zProgress, 0);
2044 }
2045 }else if( objc==4 ){
2046 char *zProgress;
2047 int len;
2048 int N;
2049 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
drhfd131da2007-08-07 17:13:03 +00002050 return TCL_ERROR;
drh1807ce32004-09-07 13:20:35 +00002051 };
2052 if( pDb->zProgress ){
2053 Tcl_Free(pDb->zProgress);
2054 }
2055 zProgress = Tcl_GetStringFromObj(objv[3], &len);
2056 if( zProgress && len>0 ){
2057 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002058 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00002059 }else{
2060 pDb->zProgress = 0;
2061 }
2062#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2063 if( pDb->zProgress ){
2064 pDb->interp = interp;
2065 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2066 }else{
2067 sqlite3_progress_handler(pDb->db, 0, 0, 0);
2068 }
2069#endif
2070 }else{
2071 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00002072 return TCL_ERROR;
2073 }
drh5d9d7572003-08-19 14:31:01 +00002074 break;
2075 }
2076
drh19e2d372005-08-29 23:00:03 +00002077 /* $db profile ?CALLBACK?
2078 **
2079 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2080 ** that has run. The text of the SQL and the amount of elapse time are
2081 ** appended to CALLBACK before the script is run.
2082 */
2083 case DB_PROFILE: {
2084 if( objc>3 ){
2085 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2086 return TCL_ERROR;
2087 }else if( objc==2 ){
2088 if( pDb->zProfile ){
2089 Tcl_AppendResult(interp, pDb->zProfile, 0);
2090 }
2091 }else{
2092 char *zProfile;
2093 int len;
2094 if( pDb->zProfile ){
2095 Tcl_Free(pDb->zProfile);
2096 }
2097 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2098 if( zProfile && len>0 ){
2099 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002100 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002101 }else{
2102 pDb->zProfile = 0;
2103 }
2104#ifndef SQLITE_OMIT_TRACE
2105 if( pDb->zProfile ){
2106 pDb->interp = interp;
2107 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2108 }else{
2109 sqlite3_profile(pDb->db, 0, 0);
2110 }
2111#endif
2112 }
2113 break;
2114 }
2115
drh5d9d7572003-08-19 14:31:01 +00002116 /*
drh22fbcb82004-02-01 01:22:50 +00002117 ** $db rekey KEY
2118 **
2119 ** Change the encryption key on the currently open database.
2120 */
2121 case DB_REKEY: {
2122 int nKey;
2123 void *pKey;
2124 if( objc!=3 ){
2125 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2126 return TCL_ERROR;
2127 }
2128 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00002129#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00002130 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002131 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00002132 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002133 rc = TCL_ERROR;
2134 }
2135#endif
2136 break;
2137 }
2138
2139 /*
drhd1d38482008-10-07 23:46:38 +00002140 ** $db status (step|sort)
2141 **
2142 ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2143 ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2144 */
2145 case DB_STATUS: {
2146 int ms;
2147 int v;
2148 const char *zOp;
2149 if( objc!=3 ){
2150 Tcl_WrongNumArgs(interp, 2, objv, "(step|sort)");
2151 return TCL_ERROR;
2152 }
2153 zOp = Tcl_GetString(objv[2]);
2154 if( strcmp(zOp, "step")==0 ){
2155 v = pDb->nStep;
2156 }else if( strcmp(zOp, "sort")==0 ){
2157 v = pDb->nSort;
2158 }else{
2159 Tcl_AppendResult(interp, "bad argument: should be step or sort",
2160 (char*)0);
2161 return TCL_ERROR;
2162 }
2163 Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2164 break;
2165 }
2166
2167 /*
drhbec3f402000-08-04 13:49:02 +00002168 ** $db timeout MILLESECONDS
2169 **
2170 ** Delay for the number of milliseconds specified when a file is locked.
2171 */
drh6d313162000-09-21 13:01:35 +00002172 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002173 int ms;
drh6d313162000-09-21 13:01:35 +00002174 if( objc!=3 ){
2175 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002176 return TCL_ERROR;
2177 }
drh6d313162000-09-21 13:01:35 +00002178 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002179 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002180 break;
drh75897232000-05-29 14:26:00 +00002181 }
danielk197755c45f22005-04-03 23:54:43 +00002182
2183 /*
drh0f14e2e2004-06-29 12:39:08 +00002184 ** $db total_changes
2185 **
2186 ** Return the number of rows that were modified, inserted, or deleted
2187 ** since the database handle was created.
2188 */
2189 case DB_TOTAL_CHANGES: {
2190 Tcl_Obj *pResult;
2191 if( objc!=2 ){
2192 Tcl_WrongNumArgs(interp, 2, objv, "");
2193 return TCL_ERROR;
2194 }
2195 pResult = Tcl_GetObjResult(interp);
2196 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2197 break;
2198 }
2199
drhb5a20d32003-04-23 12:25:23 +00002200 /* $db trace ?CALLBACK?
2201 **
2202 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2203 ** that is executed. The text of the SQL is appended to CALLBACK before
2204 ** it is executed.
2205 */
2206 case DB_TRACE: {
2207 if( objc>3 ){
2208 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002209 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002210 }else if( objc==2 ){
2211 if( pDb->zTrace ){
2212 Tcl_AppendResult(interp, pDb->zTrace, 0);
2213 }
2214 }else{
2215 char *zTrace;
2216 int len;
2217 if( pDb->zTrace ){
2218 Tcl_Free(pDb->zTrace);
2219 }
2220 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2221 if( zTrace && len>0 ){
2222 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002223 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002224 }else{
2225 pDb->zTrace = 0;
2226 }
drh19e2d372005-08-29 23:00:03 +00002227#ifndef SQLITE_OMIT_TRACE
drhb5a20d32003-04-23 12:25:23 +00002228 if( pDb->zTrace ){
2229 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002230 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002231 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002232 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002233 }
drh19e2d372005-08-29 23:00:03 +00002234#endif
drhb5a20d32003-04-23 12:25:23 +00002235 }
2236 break;
2237 }
2238
drh3d214232005-08-02 12:21:08 +00002239 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2240 **
2241 ** Start a new transaction (if we are not already in the midst of a
2242 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2243 ** completes, either commit the transaction or roll it back if SCRIPT
2244 ** throws an exception. Or if no new transation was started, do nothing.
2245 ** pass the exception on up the stack.
2246 **
2247 ** This command was inspired by Dave Thomas's talk on Ruby at the
2248 ** 2005 O'Reilly Open Source Convention (OSCON).
2249 */
2250 case DB_TRANSACTION: {
2251 int inTrans;
2252 Tcl_Obj *pScript;
2253 const char *zBegin = "BEGIN";
2254 if( objc!=3 && objc!=4 ){
2255 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2256 return TCL_ERROR;
2257 }
2258 if( objc==3 ){
2259 pScript = objv[2];
2260 } else {
2261 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002262 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002263 };
2264 enum TTYPE_enum {
2265 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2266 };
2267 int ttype;
drhb5555e72005-08-02 17:15:14 +00002268 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002269 0, &ttype) ){
2270 return TCL_ERROR;
2271 }
2272 switch( (enum TTYPE_enum)ttype ){
2273 case TTYPE_DEFERRED: /* no-op */; break;
2274 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2275 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2276 }
2277 pScript = objv[3];
2278 }
2279 inTrans = !sqlite3_get_autocommit(pDb->db);
2280 if( !inTrans ){
drh1f1549f2008-08-26 21:33:34 +00002281 pDb->disableAuth++;
drh37527852006-03-16 16:19:56 +00002282 (void)sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
drh1f1549f2008-08-26 21:33:34 +00002283 pDb->disableAuth--;
drh3d214232005-08-02 12:21:08 +00002284 }
2285 rc = Tcl_EvalObjEx(interp, pScript, 0);
2286 if( !inTrans ){
2287 const char *zEnd;
2288 if( rc==TCL_ERROR ){
2289 zEnd = "ROLLBACK";
2290 } else {
2291 zEnd = "COMMIT";
2292 }
drh1f1549f2008-08-26 21:33:34 +00002293 pDb->disableAuth++;
drh109b4352007-06-12 18:50:13 +00002294 if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
2295 sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
2296 }
drh1f1549f2008-08-26 21:33:34 +00002297 pDb->disableAuth--;
drh3d214232005-08-02 12:21:08 +00002298 }
2299 break;
2300 }
2301
danielk197794eb6a12005-12-15 15:22:08 +00002302 /*
2303 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002304 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002305 */
danielk197771fd80b2005-12-16 06:54:01 +00002306 case DB_UPDATE_HOOK:
2307 case DB_ROLLBACK_HOOK: {
2308
2309 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2310 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2311 */
2312 Tcl_Obj **ppHook;
2313 if( choice==DB_UPDATE_HOOK ){
2314 ppHook = &pDb->pUpdateHook;
2315 }else{
2316 ppHook = &pDb->pRollbackHook;
2317 }
2318
danielk197794eb6a12005-12-15 15:22:08 +00002319 if( objc!=2 && objc!=3 ){
2320 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2321 return TCL_ERROR;
2322 }
danielk197771fd80b2005-12-16 06:54:01 +00002323 if( *ppHook ){
2324 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002325 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002326 Tcl_DecrRefCount(*ppHook);
2327 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00002328 }
2329 }
2330 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002331 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00002332 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00002333 *ppHook = objv[2];
2334 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002335 }
2336 }
danielk197771fd80b2005-12-16 06:54:01 +00002337
2338 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2339 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
2340
danielk197794eb6a12005-12-15 15:22:08 +00002341 break;
2342 }
2343
danielk19774397de52005-01-12 12:44:03 +00002344 /* $db version
2345 **
2346 ** Return the version string for this database.
2347 */
2348 case DB_VERSION: {
2349 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2350 break;
2351 }
2352
tpoindex1067fe12004-12-17 15:41:11 +00002353
drh6d313162000-09-21 13:01:35 +00002354 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002355 return rc;
drh75897232000-05-29 14:26:00 +00002356}
2357
2358/*
drh3570ad92007-08-31 14:31:44 +00002359** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
danielk19779a6284c2008-07-10 17:52:49 +00002360** ?-create BOOLEAN? ?-nomutex BOOLEAN?
drh75897232000-05-29 14:26:00 +00002361**
2362** This is the main Tcl command. When the "sqlite" Tcl command is
2363** invoked, this routine runs to process that command.
2364**
2365** The first argument, DBNAME, is an arbitrary name for a new
2366** database connection. This command creates a new command named
2367** DBNAME that is used to control that connection. The database
2368** connection is deleted when the DBNAME command is deleted.
2369**
drh3570ad92007-08-31 14:31:44 +00002370** The second argument is the name of the database file.
drhfbc3eab2001-04-06 16:13:42 +00002371**
drh75897232000-05-29 14:26:00 +00002372*/
drh22fbcb82004-02-01 01:22:50 +00002373static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002374 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002375 void *pKey = 0;
2376 int nKey = 0;
2377 const char *zArg;
drh75897232000-05-29 14:26:00 +00002378 char *zErrMsg;
drh3570ad92007-08-31 14:31:44 +00002379 int i;
drh22fbcb82004-02-01 01:22:50 +00002380 const char *zFile;
drh3570ad92007-08-31 14:31:44 +00002381 const char *zVfs = 0;
drhcc91e7f2008-09-03 01:08:00 +00002382 int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
drh882e8e42006-08-24 02:42:27 +00002383 Tcl_DString translatedFilename;
drh22fbcb82004-02-01 01:22:50 +00002384 if( objc==2 ){
2385 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002386 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00002387 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00002388 return TCL_OK;
2389 }
drh9eb9e262004-02-11 02:18:05 +00002390 if( strcmp(zArg,"-has-codec")==0 ){
2391#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002392 Tcl_AppendResult(interp,"1",0);
2393#else
2394 Tcl_AppendResult(interp,"0",0);
2395#endif
2396 return TCL_OK;
2397 }
drhfbc3eab2001-04-06 16:13:42 +00002398 }
drh3570ad92007-08-31 14:31:44 +00002399 for(i=3; i+1<objc; i+=2){
2400 zArg = Tcl_GetString(objv[i]);
drh22fbcb82004-02-01 01:22:50 +00002401 if( strcmp(zArg,"-key")==0 ){
drh3570ad92007-08-31 14:31:44 +00002402 pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
2403 }else if( strcmp(zArg, "-vfs")==0 ){
2404 i++;
2405 zVfs = Tcl_GetString(objv[i]);
2406 }else if( strcmp(zArg, "-readonly")==0 ){
2407 int b;
2408 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2409 if( b ){
drh33f4e022007-09-03 15:19:34 +00002410 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
drh3570ad92007-08-31 14:31:44 +00002411 flags |= SQLITE_OPEN_READONLY;
2412 }else{
2413 flags &= ~SQLITE_OPEN_READONLY;
2414 flags |= SQLITE_OPEN_READWRITE;
2415 }
2416 }else if( strcmp(zArg, "-create")==0 ){
2417 int b;
2418 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
drh33f4e022007-09-03 15:19:34 +00002419 if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
drh3570ad92007-08-31 14:31:44 +00002420 flags |= SQLITE_OPEN_CREATE;
2421 }else{
2422 flags &= ~SQLITE_OPEN_CREATE;
2423 }
danielk19779a6284c2008-07-10 17:52:49 +00002424 }else if( strcmp(zArg, "-nomutex")==0 ){
2425 int b;
2426 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2427 if( b ){
2428 flags |= SQLITE_OPEN_NOMUTEX;
drh039963a2008-09-03 00:43:15 +00002429 flags &= ~SQLITE_OPEN_FULLMUTEX;
danielk19779a6284c2008-07-10 17:52:49 +00002430 }else{
2431 flags &= ~SQLITE_OPEN_NOMUTEX;
2432 }
drh039963a2008-09-03 00:43:15 +00002433 }else if( strcmp(zArg, "-fullmutex")==0 ){
2434 int b;
2435 if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2436 if( b ){
2437 flags |= SQLITE_OPEN_FULLMUTEX;
2438 flags &= ~SQLITE_OPEN_NOMUTEX;
2439 }else{
2440 flags &= ~SQLITE_OPEN_FULLMUTEX;
2441 }
drh3570ad92007-08-31 14:31:44 +00002442 }else{
2443 Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
2444 return TCL_ERROR;
drh22fbcb82004-02-01 01:22:50 +00002445 }
2446 }
drh3570ad92007-08-31 14:31:44 +00002447 if( objc<3 || (objc&1)!=1 ){
drh22fbcb82004-02-01 01:22:50 +00002448 Tcl_WrongNumArgs(interp, 1, objv,
drh3570ad92007-08-31 14:31:44 +00002449 "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
drh039963a2008-09-03 00:43:15 +00002450 " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN?"
drh9eb9e262004-02-11 02:18:05 +00002451#ifdef SQLITE_HAS_CODEC
drh3570ad92007-08-31 14:31:44 +00002452 " ?-key CODECKEY?"
drh22fbcb82004-02-01 01:22:50 +00002453#endif
2454 );
drh75897232000-05-29 14:26:00 +00002455 return TCL_ERROR;
2456 }
drh75897232000-05-29 14:26:00 +00002457 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00002458 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00002459 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00002460 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
2461 return TCL_ERROR;
2462 }
2463 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00002464 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00002465 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
drh3570ad92007-08-31 14:31:44 +00002466 sqlite3_open_v2(zFile, &p->db, flags, zVfs);
drh882e8e42006-08-24 02:42:27 +00002467 Tcl_DStringFree(&translatedFilename);
danielk197780290862004-05-22 09:21:21 +00002468 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
drh9404d502006-12-19 18:46:08 +00002469 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
danielk197780290862004-05-22 09:21:21 +00002470 sqlite3_close(p->db);
2471 p->db = 0;
2472 }
drh2011d5f2004-07-22 02:40:37 +00002473#ifdef SQLITE_HAS_CODEC
drhf3a65f72007-08-22 20:18:21 +00002474 if( p->db ){
2475 sqlite3_key(p->db, pKey, nKey);
2476 }
drheb8ed702004-02-11 10:37:23 +00002477#endif
drhbec3f402000-08-04 13:49:02 +00002478 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00002479 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00002480 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00002481 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00002482 return TCL_ERROR;
2483 }
drhfb7e7652005-01-24 00:28:42 +00002484 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00002485 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00002486 zArg = Tcl_GetStringFromObj(objv[1], 0);
2487 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
drh75897232000-05-29 14:26:00 +00002488 return TCL_OK;
2489}
2490
2491/*
drh90ca9752001-09-28 17:47:14 +00002492** Provide a dummy Tcl_InitStubs if we are using this as a static
2493** library.
2494*/
2495#ifndef USE_TCL_STUBS
2496# undef Tcl_InitStubs
2497# define Tcl_InitStubs(a,b,c)
2498#endif
2499
2500/*
drh29bc4612005-10-05 10:40:15 +00002501** Make sure we have a PACKAGE_VERSION macro defined. This will be
2502** defined automatically by the TEA makefile. But other makefiles
2503** do not define it.
2504*/
2505#ifndef PACKAGE_VERSION
2506# define PACKAGE_VERSION SQLITE_VERSION
2507#endif
2508
2509/*
drh75897232000-05-29 14:26:00 +00002510** Initialize this module.
2511**
2512** This Tcl module contains only a single new Tcl command named "sqlite".
2513** (Hence there is no namespace. There is no point in using a namespace
2514** if the extension only supplies one new name!) The "sqlite" command is
2515** used to open a new SQLite database. See the DbMain() routine above
2516** for additional information.
2517*/
drhad6e1372006-07-10 21:15:51 +00002518EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00002519 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00002520 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002521 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh49766d62005-01-08 18:42:28 +00002522 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002523 Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
drh90ca9752001-09-28 17:47:14 +00002524 return TCL_OK;
2525}
drhad6e1372006-07-10 21:15:51 +00002526EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2527EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2528EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00002529EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2530EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2531EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2532EXTERN int Tclsqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
2533
drh49766d62005-01-08 18:42:28 +00002534
2535#ifndef SQLITE_3_SUFFIX_ONLY
drhad6e1372006-07-10 21:15:51 +00002536EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2537EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2538EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2539EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drhe2c3a652008-09-23 09:58:46 +00002540EXTERN int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2541EXTERN int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2542EXTERN int Sqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2543EXTERN int Tclsqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
drh49766d62005-01-08 18:42:28 +00002544#endif
drh75897232000-05-29 14:26:00 +00002545
drh3e27c022004-07-23 00:01:38 +00002546#ifdef TCLSH
2547/*****************************************************************************
2548** The code that follows is used to build standalone TCL interpreters
drh3570ad92007-08-31 14:31:44 +00002549** that are statically linked with SQLite.
drh75897232000-05-29 14:26:00 +00002550*/
drh348784e2000-05-29 20:41:49 +00002551
2552/*
drh3e27c022004-07-23 00:01:38 +00002553** If the macro TCLSH is one, then put in code this for the
2554** "main" routine that will initialize Tcl and take input from
drh3570ad92007-08-31 14:31:44 +00002555** standard input, or if a file is named on the command line
2556** the TCL interpreter reads and evaluates that file.
drh348784e2000-05-29 20:41:49 +00002557*/
drh3e27c022004-07-23 00:01:38 +00002558#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00002559static char zMainloop[] =
2560 "set line {}\n"
2561 "while {![eof stdin]} {\n"
2562 "if {$line!=\"\"} {\n"
2563 "puts -nonewline \"> \"\n"
2564 "} else {\n"
2565 "puts -nonewline \"% \"\n"
2566 "}\n"
2567 "flush stdout\n"
2568 "append line [gets stdin]\n"
2569 "if {[info complete $line]} {\n"
2570 "if {[catch {uplevel #0 $line} result]} {\n"
2571 "puts stderr \"Error: $result\"\n"
2572 "} elseif {$result!=\"\"} {\n"
2573 "puts $result\n"
2574 "}\n"
2575 "set line {}\n"
2576 "} else {\n"
2577 "append line \\n\n"
2578 "}\n"
2579 "}\n"
2580;
drh3e27c022004-07-23 00:01:38 +00002581#endif
2582
2583/*
2584** If the macro TCLSH is two, then get the main loop code out of
2585** the separate file "spaceanal_tcl.h".
2586*/
2587#if TCLSH==2
2588static char zMainloop[] =
2589#include "spaceanal_tcl.h"
2590;
2591#endif
drh348784e2000-05-29 20:41:49 +00002592
2593#define TCLSH_MAIN main /* Needed to fake out mktclapp */
2594int TCLSH_MAIN(int argc, char **argv){
2595 Tcl_Interp *interp;
drh297ecf12001-04-05 15:57:13 +00002596 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00002597 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00002598 Sqlite3_Init(interp);
drhd9b02572001-04-15 00:37:09 +00002599#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00002600 {
drh2f999a62007-08-15 19:16:43 +00002601 extern int Md5_Init(Tcl_Interp*);
2602 extern int Sqliteconfig_Init(Tcl_Interp*);
drhd1bf3512001-04-07 15:24:33 +00002603 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00002604 extern int Sqlitetest2_Init(Tcl_Interp*);
2605 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00002606 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00002607 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00002608 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00002609 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00002610 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00002611 extern int Sqlitetest9_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00002612 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00002613 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
drh984bfaa2008-03-19 16:08:53 +00002614 extern int Sqlitetest_func_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00002615 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00002616 extern int Sqlitetest_malloc_Init(Tcl_Interp*);
danielk19771a9ed0b2008-06-18 09:45:56 +00002617 extern int Sqlitetest_mutex_Init(Tcl_Interp*);
drh2f999a62007-08-15 19:16:43 +00002618 extern int Sqlitetestschema_Init(Tcl_Interp*);
2619 extern int Sqlitetestsse_Init(Tcl_Interp*);
2620 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk197744918fa2007-09-07 11:29:25 +00002621 extern int SqlitetestThread_Init(Tcl_Interp*);
danielk1977a15db352007-09-14 16:20:00 +00002622 extern int SqlitetestOnefile_Init();
danielk19775d1f5aa2008-04-10 14:51:00 +00002623 extern int SqlitetestOsinst_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002624
drh2f999a62007-08-15 19:16:43 +00002625 Md5_Init(interp);
2626 Sqliteconfig_Init(interp);
danielk19776490beb2004-05-11 06:17:21 +00002627 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00002628 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00002629 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00002630 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00002631 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00002632 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00002633 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00002634 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00002635 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00002636 Sqlitetestasync_Init(interp);
drh1409be62006-08-23 20:07:20 +00002637 Sqlitetest_autoext_Init(interp);
drh984bfaa2008-03-19 16:08:53 +00002638 Sqlitetest_func_Init(interp);
drh15926592007-04-06 15:02:13 +00002639 Sqlitetest_hexio_Init(interp);
drh2f999a62007-08-15 19:16:43 +00002640 Sqlitetest_malloc_Init(interp);
danielk19771a9ed0b2008-06-18 09:45:56 +00002641 Sqlitetest_mutex_Init(interp);
drh2f999a62007-08-15 19:16:43 +00002642 Sqlitetestschema_Init(interp);
2643 Sqlitetesttclvar_Init(interp);
danielk197744918fa2007-09-07 11:29:25 +00002644 SqlitetestThread_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00002645 SqlitetestOnefile_Init(interp);
danielk19775d1f5aa2008-04-10 14:51:00 +00002646 SqlitetestOsinst_Init(interp);
danielk1977a15db352007-09-14 16:20:00 +00002647
drh89dec812005-04-28 19:03:37 +00002648#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00002649 Sqlitetestsse_Init(interp);
2650#endif
drhd1bf3512001-04-07 15:24:33 +00002651 }
2652#endif
drh3e27c022004-07-23 00:01:38 +00002653 if( argc>=2 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002654 int i;
shessad42c3a2006-08-22 23:53:46 +00002655 char zArgc[32];
2656 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
2657 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00002658 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
2659 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00002660 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00002661 Tcl_SetVar(interp, "argv", argv[i],
2662 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
2663 }
drh3e27c022004-07-23 00:01:38 +00002664 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00002665 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drhc61053b2000-06-04 12:58:36 +00002666 if( zInfo==0 ) zInfo = interp->result;
2667 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00002668 return 1;
2669 }
drh3e27c022004-07-23 00:01:38 +00002670 }
2671 if( argc<=1 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002672 Tcl_GlobalEval(interp, zMainloop);
2673 }
2674 return 0;
2675}
2676#endif /* TCLSH */