blob: 3d7ff9444075119cab30f8e2692c07efdce70b86 [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**
danielk1977dcbb5d32007-05-04 18:36:44 +000015** $Id: tclsqlite.c,v 1.185 2007/05/04 18:36:45 danielk1977 Exp $
drh75897232000-05-29 14:26:00 +000016*/
drh17a68932001-01-31 13:28:08 +000017#include "tcl.h"
danielk1977b4e9af92007-05-01 17:49:49 +000018#include <errno.h>
drhbd08af42007-04-05 21:58:33 +000019
20/*
21** Some additional include files are needed if this file is not
22** appended to the amalgamation.
23*/
24#ifndef SQLITE_AMALGAMATION
25# include "sqliteInt.h"
26# include "hash.h"
27# include <stdlib.h>
28# include <string.h>
29# include <assert.h>
30# include <ctype.h>
31#endif
drh75897232000-05-29 14:26:00 +000032
drhad6e1372006-07-10 21:15:51 +000033/*
34 * Windows needs to know which symbols to export. Unix does not.
35 * BUILD_sqlite should be undefined for Unix.
36 */
37#ifdef BUILD_sqlite
38#undef TCL_STORAGE_CLASS
39#define TCL_STORAGE_CLASS DLLEXPORT
40#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000041
danielk1977a21c6b62005-01-24 10:25:59 +000042#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000043#define MAX_PREPARED_STMTS 100
44
drh75897232000-05-29 14:26:00 +000045/*
drh98808ba2001-10-18 12:34:46 +000046** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
47** have to do a translation when going between the two. Set the
48** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
49** this translation.
50*/
51#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
52# define UTF_TRANSLATION_NEEDED 1
53#endif
54
55/*
drhcabb0812002-09-14 13:47:32 +000056** New SQL functions can be created as TCL scripts. Each such function
57** is described by an instance of the following structure.
58*/
59typedef struct SqlFunc SqlFunc;
60struct SqlFunc {
61 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000062 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
63 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
64 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000065 SqlFunc *pNext; /* Next function on the list of them all */
66};
67
68/*
danielk19770202b292004-06-09 09:55:16 +000069** New collation sequences function can be created as TCL scripts. Each such
70** function is described by an instance of the following structure.
71*/
72typedef struct SqlCollate SqlCollate;
73struct SqlCollate {
74 Tcl_Interp *interp; /* The TCL interpret to execute the function */
75 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000076 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000077};
78
79/*
drhfb7e7652005-01-24 00:28:42 +000080** Prepared statements are cached for faster execution. Each prepared
81** statement is described by an instance of the following structure.
82*/
83typedef struct SqlPreparedStmt SqlPreparedStmt;
84struct SqlPreparedStmt {
85 SqlPreparedStmt *pNext; /* Next in linked list */
86 SqlPreparedStmt *pPrev; /* Previous on the list */
87 sqlite3_stmt *pStmt; /* The prepared statement */
88 int nSql; /* chars in zSql[] */
89 char zSql[1]; /* Text of the SQL statement */
90};
91
danielk1977d04417962007-05-02 13:16:30 +000092typedef struct IncrblobChannel IncrblobChannel;
93
drhfb7e7652005-01-24 00:28:42 +000094/*
drhbec3f402000-08-04 13:49:02 +000095** There is one instance of this structure for each SQLite database
96** that has been opened by the SQLite TCL interface.
97*/
98typedef struct SqliteDb SqliteDb;
99struct SqliteDb {
drhdddca282006-01-03 00:33:50 +0000100 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +0000101 Tcl_Interp *interp; /* The interpreter used for this database */
102 char *zBusy; /* The busy callback routine */
103 char *zCommit; /* The commit hook callback routine */
104 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +0000105 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000106 char *zProgress; /* The progress callback routine */
107 char *zAuth; /* The authorization callback routine */
108 char *zNull; /* Text to substitute for an SQL NULL value */
109 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000110 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000111 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drhd1e47332005-06-26 17:55:33 +0000112 SqlCollate *pCollate; /* List of SQL collation functions */
113 int rc; /* Return code of most recent sqlite3_exec() */
114 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000115 SqlPreparedStmt *stmtList; /* List of prepared statements*/
116 SqlPreparedStmt *stmtLast; /* Last statement in the list */
117 int maxStmt; /* The next maximum number of stmtList */
118 int nStmt; /* Number of statements in stmtList */
danielk1977d04417962007-05-02 13:16:30 +0000119 IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
drh98808ba2001-10-18 12:34:46 +0000120};
drh297ecf12001-04-05 15:57:13 +0000121
danielk1977b4e9af92007-05-01 17:49:49 +0000122struct IncrblobChannel {
danielk1977d04417962007-05-02 13:16:30 +0000123 sqlite3_blob *pBlob; /* sqlite3 blob handle */
danielk1977dcbb5d32007-05-04 18:36:44 +0000124 SqliteDb *pDb; /* Associated database connection */
danielk1977d04417962007-05-02 13:16:30 +0000125 int iSeek; /* Current seek offset */
danielk1977d04417962007-05-02 13:16:30 +0000126 Tcl_Channel channel; /* Channel identifier */
127 IncrblobChannel *pNext; /* Linked list of all open incrblob channels */
128 IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */
danielk1977b4e9af92007-05-01 17:49:49 +0000129};
130
131/*
danielk1977d04417962007-05-02 13:16:30 +0000132** Close all incrblob channels opened using database connection pDb.
133** This is called when shutting down the database connection.
134*/
135static void closeIncrblobChannels(SqliteDb *pDb){
136 IncrblobChannel *p;
137 IncrblobChannel *pNext;
138
139 for(p=pDb->pIncrblob; p; p=pNext){
140 pNext = p->pNext;
141
142 /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
143 ** which deletes the IncrblobChannel structure at *p. So do not
144 ** call Tcl_Free() here.
145 */
146 Tcl_UnregisterChannel(pDb->interp, p->channel);
147 }
148}
149
150/*
danielk1977b4e9af92007-05-01 17:49:49 +0000151** Close an incremental blob channel.
152*/
153static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
154 IncrblobChannel *p = (IncrblobChannel *)instanceData;
danielk197792d4d7a2007-05-04 12:05:56 +0000155 int rc = sqlite3_blob_close(p->pBlob);
156 sqlite3 *db = p->pDb->db;
danielk1977d04417962007-05-02 13:16:30 +0000157
158 /* Remove the channel from the SqliteDb.pIncrblob list. */
159 if( p->pNext ){
160 p->pNext->pPrev = p->pPrev;
161 }
162 if( p->pPrev ){
163 p->pPrev->pNext = p->pNext;
164 }
165 if( p->pDb->pIncrblob==p ){
166 p->pDb->pIncrblob = p->pNext;
167 }
168
danielk197792d4d7a2007-05-04 12:05:56 +0000169 /* Free the IncrblobChannel structure */
danielk1977b4e9af92007-05-01 17:49:49 +0000170 Tcl_Free((char *)p);
danielk197792d4d7a2007-05-04 12:05:56 +0000171
172 if( rc!=SQLITE_OK ){
173 Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
174 return TCL_ERROR;
175 }
danielk1977b4e9af92007-05-01 17:49:49 +0000176 return TCL_OK;
177}
178
179/*
180** Read data from an incremental blob channel.
181*/
182static int incrblobInput(
183 ClientData instanceData,
184 char *buf,
185 int bufSize,
186 int *errorCodePtr
187){
188 IncrblobChannel *p = (IncrblobChannel *)instanceData;
189 int nRead = bufSize; /* Number of bytes to read */
190 int nBlob; /* Total size of the blob */
191 int rc; /* sqlite error code */
192
193 nBlob = sqlite3_blob_bytes(p->pBlob);
194 if( (p->iSeek+nRead)>nBlob ){
195 nRead = nBlob-p->iSeek;
196 }
197 if( nRead<=0 ){
198 return 0;
199 }
200
201 rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
202 if( rc!=SQLITE_OK ){
203 *errorCodePtr = rc;
204 return -1;
205 }
206
207 p->iSeek += nRead;
208 return nRead;
209}
210
danielk1977d04417962007-05-02 13:16:30 +0000211/*
212** Write data to an incremental blob channel.
213*/
danielk1977b4e9af92007-05-01 17:49:49 +0000214static int incrblobOutput(
215 ClientData instanceData,
216 CONST char *buf,
217 int toWrite,
218 int *errorCodePtr
219){
220 IncrblobChannel *p = (IncrblobChannel *)instanceData;
221 int nWrite = toWrite; /* Number of bytes to write */
222 int nBlob; /* Total size of the blob */
223 int rc; /* sqlite error code */
224
225 nBlob = sqlite3_blob_bytes(p->pBlob);
226 if( (p->iSeek+nWrite)>nBlob ){
227 *errorCodePtr = EINVAL;
228 return -1;
229 }
230 if( nWrite<=0 ){
231 return 0;
232 }
233
234 rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
235 if( rc!=SQLITE_OK ){
236 *errorCodePtr = EIO;
237 return -1;
238 }
239
240 p->iSeek += nWrite;
241 return nWrite;
242}
243
244/*
245** Seek an incremental blob channel.
246*/
247static int incrblobSeek(
248 ClientData instanceData,
249 long offset,
250 int seekMode,
251 int *errorCodePtr
252){
253 IncrblobChannel *p = (IncrblobChannel *)instanceData;
254
255 switch( seekMode ){
256 case SEEK_SET:
257 p->iSeek = offset;
258 break;
259 case SEEK_CUR:
260 p->iSeek += offset;
261 break;
262 case SEEK_END:
263 p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
264 break;
265
266 default: assert(!"Bad seekMode");
267 }
268
269 return p->iSeek;
270}
271
272
273static void incrblobWatch(ClientData instanceData, int mode){
274 /* NO-OP */
275}
276static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
277 return TCL_ERROR;
278}
279
280static Tcl_ChannelType IncrblobChannelType = {
281 "incrblob", /* typeName */
282 TCL_CHANNEL_VERSION_2, /* version */
283 incrblobClose, /* closeProc */
284 incrblobInput, /* inputProc */
285 incrblobOutput, /* outputProc */
286 incrblobSeek, /* seekProc */
287 0, /* setOptionProc */
288 0, /* getOptionProc */
289 incrblobWatch, /* watchProc (this is a no-op) */
290 incrblobHandle, /* getHandleProc (always returns error) */
291 0, /* close2Proc */
292 0, /* blockModeProc */
293 0, /* flushProc */
294 0, /* handlerProc */
295 0, /* wideSeekProc */
296 0, /* threadActionProc */
297};
298
299/*
300** Create a new incrblob channel.
301*/
302static int createIncrblobChannel(
303 Tcl_Interp *interp,
304 SqliteDb *pDb,
305 const char *zDb,
306 const char *zTable,
307 const char *zColumn,
danielk19778cbadb02007-05-03 16:31:26 +0000308 sqlite_int64 iRow,
309 int isReadonly
danielk1977b4e9af92007-05-01 17:49:49 +0000310){
311 IncrblobChannel *p;
danielk19778cbadb02007-05-03 16:31:26 +0000312 sqlite3 *db = pDb->db;
danielk1977b4e9af92007-05-01 17:49:49 +0000313 sqlite3_blob *pBlob;
314 int rc;
danielk19778cbadb02007-05-03 16:31:26 +0000315 int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
danielk1977b4e9af92007-05-01 17:49:49 +0000316
317 /* This variable is used to name the channels: "incrblob_[incr count]" */
318 static int count = 0;
319 char zChannel[64];
320
danielk19778cbadb02007-05-03 16:31:26 +0000321 rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
danielk1977b4e9af92007-05-01 17:49:49 +0000322 if( rc!=SQLITE_OK ){
323 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
324 return TCL_ERROR;
325 }
326
327 p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
328 p->iSeek = 0;
329 p->pBlob = pBlob;
330
drh5bb3eb92007-05-04 13:15:55 +0000331 sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
danielk1977d04417962007-05-02 13:16:30 +0000332 p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
333 Tcl_RegisterChannel(interp, p->channel);
danielk1977b4e9af92007-05-01 17:49:49 +0000334
danielk1977d04417962007-05-02 13:16:30 +0000335 /* Link the new channel into the SqliteDb.pIncrblob list. */
336 p->pNext = pDb->pIncrblob;
337 p->pPrev = 0;
338 if( p->pNext ){
339 p->pNext->pPrev = p;
340 }
341 pDb->pIncrblob = p;
342 p->pDb = pDb;
343
344 Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
danielk1977b4e9af92007-05-01 17:49:49 +0000345 return TCL_OK;
346}
347
drh6d313162000-09-21 13:01:35 +0000348/*
drhd1e47332005-06-26 17:55:33 +0000349** Look at the script prefix in pCmd. We will be executing this script
350** after first appending one or more arguments. This routine analyzes
351** the script to see if it is safe to use Tcl_EvalObjv() on the script
352** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
353** faster.
354**
355** Scripts that are safe to use with Tcl_EvalObjv() consists of a
356** command name followed by zero or more arguments with no [...] or $
357** or {...} or ; to be seen anywhere. Most callback scripts consist
358** of just a single procedure name and they meet this requirement.
359*/
360static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
361 /* We could try to do something with Tcl_Parse(). But we will instead
362 ** just do a search for forbidden characters. If any of the forbidden
363 ** characters appear in pCmd, we will report the string as unsafe.
364 */
365 const char *z;
366 int n;
367 z = Tcl_GetStringFromObj(pCmd, &n);
368 while( n-- > 0 ){
369 int c = *(z++);
370 if( c=='$' || c=='[' || c==';' ) return 0;
371 }
372 return 1;
373}
374
375/*
376** Find an SqlFunc structure with the given name. Or create a new
377** one if an existing one cannot be found. Return a pointer to the
378** structure.
379*/
380static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
381 SqlFunc *p, *pNew;
382 int i;
383 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen(zName) + 1 );
384 pNew->zName = (char*)&pNew[1];
385 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
386 pNew->zName[i] = 0;
387 for(p=pDb->pFunc; p; p=p->pNext){
388 if( strcmp(p->zName, pNew->zName)==0 ){
389 Tcl_Free((char*)pNew);
390 return p;
391 }
392 }
393 pNew->interp = pDb->interp;
394 pNew->pScript = 0;
395 pNew->pNext = pDb->pFunc;
396 pDb->pFunc = pNew;
397 return pNew;
398}
399
400/*
drhfb7e7652005-01-24 00:28:42 +0000401** Finalize and free a list of prepared statements
402*/
403static void flushStmtCache( SqliteDb *pDb ){
404 SqlPreparedStmt *pPreStmt;
405
406 while( pDb->stmtList ){
407 sqlite3_finalize( pDb->stmtList->pStmt );
408 pPreStmt = pDb->stmtList;
409 pDb->stmtList = pDb->stmtList->pNext;
410 Tcl_Free( (char*)pPreStmt );
411 }
412 pDb->nStmt = 0;
413 pDb->stmtLast = 0;
414}
415
416/*
drh895d7472004-08-20 16:02:39 +0000417** TCL calls this procedure when an sqlite3 database command is
418** deleted.
drh75897232000-05-29 14:26:00 +0000419*/
420static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000421 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000422 flushStmtCache(pDb);
danielk1977d04417962007-05-02 13:16:30 +0000423 closeIncrblobChannels(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000424 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000425 while( pDb->pFunc ){
426 SqlFunc *pFunc = pDb->pFunc;
427 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000428 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000429 Tcl_Free((char*)pFunc);
430 }
danielk19770202b292004-06-09 09:55:16 +0000431 while( pDb->pCollate ){
432 SqlCollate *pCollate = pDb->pCollate;
433 pDb->pCollate = pCollate->pNext;
434 Tcl_Free((char*)pCollate);
435 }
drhbec3f402000-08-04 13:49:02 +0000436 if( pDb->zBusy ){
437 Tcl_Free(pDb->zBusy);
438 }
drhb5a20d32003-04-23 12:25:23 +0000439 if( pDb->zTrace ){
440 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000441 }
drh19e2d372005-08-29 23:00:03 +0000442 if( pDb->zProfile ){
443 Tcl_Free(pDb->zProfile);
444 }
drhe22a3342003-04-22 20:30:37 +0000445 if( pDb->zAuth ){
446 Tcl_Free(pDb->zAuth);
447 }
danielk197755c45f22005-04-03 23:54:43 +0000448 if( pDb->zNull ){
449 Tcl_Free(pDb->zNull);
450 }
danielk197794eb6a12005-12-15 15:22:08 +0000451 if( pDb->pUpdateHook ){
452 Tcl_DecrRefCount(pDb->pUpdateHook);
453 }
danielk197771fd80b2005-12-16 06:54:01 +0000454 if( pDb->pRollbackHook ){
455 Tcl_DecrRefCount(pDb->pRollbackHook);
456 }
danielk197794eb6a12005-12-15 15:22:08 +0000457 if( pDb->pCollateNeeded ){
458 Tcl_DecrRefCount(pDb->pCollateNeeded);
459 }
drhbec3f402000-08-04 13:49:02 +0000460 Tcl_Free((char*)pDb);
461}
462
463/*
464** This routine is called when a database file is locked while trying
465** to execute SQL.
466*/
danielk19772a764eb2004-06-12 01:43:26 +0000467static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000468 SqliteDb *pDb = (SqliteDb*)cd;
469 int rc;
470 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000471
drh5bb3eb92007-05-04 13:15:55 +0000472 sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000473 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000474 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
475 return 0;
476 }
477 return 1;
drh75897232000-05-29 14:26:00 +0000478}
479
480/*
danielk1977348bb5d2003-10-18 09:37:26 +0000481** This routine is invoked as the 'progress callback' for the database.
482*/
483static int DbProgressHandler(void *cd){
484 SqliteDb *pDb = (SqliteDb*)cd;
485 int rc;
486
487 assert( pDb->zProgress );
488 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
489 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
490 return 1;
491 }
492 return 0;
493}
494
drhd1167392006-01-23 13:00:35 +0000495#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000496/*
drhb5a20d32003-04-23 12:25:23 +0000497** This routine is called by the SQLite trace handler whenever a new
498** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000499*/
drhb5a20d32003-04-23 12:25:23 +0000500static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000501 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000502 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000503
drhb5a20d32003-04-23 12:25:23 +0000504 Tcl_DStringInit(&str);
505 Tcl_DStringAppend(&str, pDb->zTrace, -1);
506 Tcl_DStringAppendElement(&str, zSql);
507 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
508 Tcl_DStringFree(&str);
509 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000510}
drhd1167392006-01-23 13:00:35 +0000511#endif
drh0d1a6432003-04-03 15:46:04 +0000512
drhd1167392006-01-23 13:00:35 +0000513#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000514/*
drh19e2d372005-08-29 23:00:03 +0000515** This routine is called by the SQLite profile handler after a statement
516** SQL has executed. The TCL script in pDb->zProfile is evaluated.
517*/
518static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
519 SqliteDb *pDb = (SqliteDb*)cd;
520 Tcl_DString str;
521 char zTm[100];
522
523 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
524 Tcl_DStringInit(&str);
525 Tcl_DStringAppend(&str, pDb->zProfile, -1);
526 Tcl_DStringAppendElement(&str, zSql);
527 Tcl_DStringAppendElement(&str, zTm);
528 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
529 Tcl_DStringFree(&str);
530 Tcl_ResetResult(pDb->interp);
531}
drhd1167392006-01-23 13:00:35 +0000532#endif
drh19e2d372005-08-29 23:00:03 +0000533
534/*
drhaa940ea2004-01-15 02:44:03 +0000535** This routine is called when a transaction is committed. The
536** TCL script in pDb->zCommit is executed. If it returns non-zero or
537** if it throws an exception, the transaction is rolled back instead
538** of being committed.
539*/
540static int DbCommitHandler(void *cd){
541 SqliteDb *pDb = (SqliteDb*)cd;
542 int rc;
543
544 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
545 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
546 return 1;
547 }
548 return 0;
549}
550
danielk197771fd80b2005-12-16 06:54:01 +0000551static void DbRollbackHandler(void *clientData){
552 SqliteDb *pDb = (SqliteDb*)clientData;
553 assert(pDb->pRollbackHook);
554 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
555 Tcl_BackgroundError(pDb->interp);
556 }
557}
558
danielk197794eb6a12005-12-15 15:22:08 +0000559static void DbUpdateHandler(
560 void *p,
561 int op,
562 const char *zDb,
563 const char *zTbl,
564 sqlite_int64 rowid
565){
566 SqliteDb *pDb = (SqliteDb *)p;
567 Tcl_Obj *pCmd;
568
569 assert( pDb->pUpdateHook );
570 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
571
572 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
573 Tcl_IncrRefCount(pCmd);
574 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
575 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
576 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
577 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
578 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
579 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
580}
581
danielk19777cedc8d2004-06-10 10:50:08 +0000582static void tclCollateNeeded(
583 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000584 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000585 int enc,
586 const char *zName
587){
588 SqliteDb *pDb = (SqliteDb *)pCtx;
589 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
590 Tcl_IncrRefCount(pScript);
591 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
592 Tcl_EvalObjEx(pDb->interp, pScript, 0);
593 Tcl_DecrRefCount(pScript);
594}
595
drhaa940ea2004-01-15 02:44:03 +0000596/*
danielk19770202b292004-06-09 09:55:16 +0000597** This routine is called to evaluate an SQL collation function implemented
598** using TCL script.
599*/
600static int tclSqlCollate(
601 void *pCtx,
602 int nA,
603 const void *zA,
604 int nB,
605 const void *zB
606){
607 SqlCollate *p = (SqlCollate *)pCtx;
608 Tcl_Obj *pCmd;
609
610 pCmd = Tcl_NewStringObj(p->zScript, -1);
611 Tcl_IncrRefCount(pCmd);
612 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
613 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000614 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000615 Tcl_DecrRefCount(pCmd);
616 return (atoi(Tcl_GetStringResult(p->interp)));
617}
618
619/*
drhcabb0812002-09-14 13:47:32 +0000620** This routine is called to evaluate an SQL function implemented
621** using TCL script.
622*/
drhfb7e7652005-01-24 00:28:42 +0000623static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000624 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000625 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000626 int i;
627 int rc;
628
drhd1e47332005-06-26 17:55:33 +0000629 if( argc==0 ){
630 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
631 ** script object directly. This allows the TCL compiler to generate
632 ** bytecode for the command on the first invocation and thus make
633 ** subsequent invocations much faster. */
634 pCmd = p->pScript;
635 Tcl_IncrRefCount(pCmd);
636 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
637 Tcl_DecrRefCount(pCmd);
638 }else{
639 /* If there are arguments to the function, make a shallow copy of the
640 ** script object, lappend the arguments, then evaluate the copy.
641 **
642 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
643 ** The new Tcl_Obj contains pointers to the original list elements.
644 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
645 ** of the list to tclCmdNameType, that alternate representation will
646 ** be preserved and reused on the next invocation.
647 */
648 Tcl_Obj **aArg;
649 int nArg;
650 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
651 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
652 return;
653 }
654 pCmd = Tcl_NewListObj(nArg, aArg);
655 Tcl_IncrRefCount(pCmd);
656 for(i=0; i<argc; i++){
657 sqlite3_value *pIn = argv[i];
658 Tcl_Obj *pVal;
659
660 /* Set pVal to contain the i'th column of this row. */
661 switch( sqlite3_value_type(pIn) ){
662 case SQLITE_BLOB: {
663 int bytes = sqlite3_value_bytes(pIn);
664 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
665 break;
666 }
667 case SQLITE_INTEGER: {
668 sqlite_int64 v = sqlite3_value_int64(pIn);
669 if( v>=-2147483647 && v<=2147483647 ){
670 pVal = Tcl_NewIntObj(v);
671 }else{
672 pVal = Tcl_NewWideIntObj(v);
673 }
674 break;
675 }
676 case SQLITE_FLOAT: {
677 double r = sqlite3_value_double(pIn);
678 pVal = Tcl_NewDoubleObj(r);
679 break;
680 }
681 case SQLITE_NULL: {
682 pVal = Tcl_NewStringObj("", 0);
683 break;
684 }
685 default: {
686 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000687 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000688 break;
689 }
690 }
691 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
692 if( rc ){
693 Tcl_DecrRefCount(pCmd);
694 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
695 return;
696 }
danielk197751ad0ec2004-05-24 12:39:02 +0000697 }
drhd1e47332005-06-26 17:55:33 +0000698 if( !p->useEvalObjv ){
699 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
700 ** is a list without a string representation. To prevent this from
701 ** happening, make sure pCmd has a valid string representation */
702 Tcl_GetString(pCmd);
703 }
704 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
705 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000706 }
danielk1977562e8d32005-05-20 09:40:55 +0000707
drhc7f269d2005-05-05 10:30:29 +0000708 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000709 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000710 }else{
drhc7f269d2005-05-05 10:30:29 +0000711 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
712 int n;
713 u8 *data;
714 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
715 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000716 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000717 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000718 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000719 data = Tcl_GetByteArrayFromObj(pVar, &n);
720 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000721 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
722 (c=='i' && strcmp(zType,"int")==0) ){
723 Tcl_GetIntFromObj(0, pVar, &n);
724 sqlite3_result_int(context, n);
725 }else if( c=='d' && strcmp(zType,"double")==0 ){
726 double r;
727 Tcl_GetDoubleFromObj(0, pVar, &r);
728 sqlite3_result_double(context, r);
drhdf0bdda2005-06-25 19:31:48 +0000729 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
730 Tcl_WideInt v;
731 Tcl_GetWideIntFromObj(0, pVar, &v);
732 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000733 }else{
danielk197700fd9572005-12-07 06:27:43 +0000734 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
735 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000736 }
drhcabb0812002-09-14 13:47:32 +0000737 }
738}
drh895d7472004-08-20 16:02:39 +0000739
drhe22a3342003-04-22 20:30:37 +0000740#ifndef SQLITE_OMIT_AUTHORIZATION
741/*
742** This is the authentication function. It appends the authentication
743** type code and the two arguments to zCmd[] then invokes the result
744** on the interpreter. The reply is examined to determine if the
745** authentication fails or succeeds.
746*/
747static int auth_callback(
748 void *pArg,
749 int code,
750 const char *zArg1,
751 const char *zArg2,
752 const char *zArg3,
753 const char *zArg4
754){
755 char *zCode;
756 Tcl_DString str;
757 int rc;
758 const char *zReply;
759 SqliteDb *pDb = (SqliteDb*)pArg;
760
761 switch( code ){
762 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
763 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
764 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
765 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
766 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
767 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
768 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
769 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
770 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
771 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
772 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
773 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
774 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
775 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
776 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
777 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
778 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
779 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
780 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
781 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
782 case SQLITE_READ : zCode="SQLITE_READ"; break;
783 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
784 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
785 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000786 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
787 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000788 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000789 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000790 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000791 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
792 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000793 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
drhe22a3342003-04-22 20:30:37 +0000794 default : zCode="????"; break;
795 }
796 Tcl_DStringInit(&str);
797 Tcl_DStringAppend(&str, pDb->zAuth, -1);
798 Tcl_DStringAppendElement(&str, zCode);
799 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
800 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
801 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
802 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
803 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
804 Tcl_DStringFree(&str);
805 zReply = Tcl_GetStringResult(pDb->interp);
806 if( strcmp(zReply,"SQLITE_OK")==0 ){
807 rc = SQLITE_OK;
808 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
809 rc = SQLITE_DENY;
810 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
811 rc = SQLITE_IGNORE;
812 }else{
813 rc = 999;
814 }
815 return rc;
816}
817#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000818
819/*
danielk1977ef2cb632004-05-29 02:37:19 +0000820** zText is a pointer to text obtained via an sqlite3_result_text()
821** or similar interface. This routine returns a Tcl string object,
822** reference count set to 0, containing the text. If a translation
823** between iso8859 and UTF-8 is required, it is preformed.
824*/
825static Tcl_Obj *dbTextToObj(char const *zText){
826 Tcl_Obj *pVal;
827#ifdef UTF_TRANSLATION_NEEDED
828 Tcl_DString dCol;
829 Tcl_DStringInit(&dCol);
830 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
831 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
832 Tcl_DStringFree(&dCol);
833#else
834 pVal = Tcl_NewStringObj(zText, -1);
835#endif
836 return pVal;
837}
838
839/*
tpoindex1067fe12004-12-17 15:41:11 +0000840** This routine reads a line of text from FILE in, stores
841** the text in memory obtained from malloc() and returns a pointer
842** to the text. NULL is returned at end of file, or if malloc()
843** fails.
844**
845** The interface is like "readline" but no command-line editing
846** is done.
847**
848** copied from shell.c from '.import' command
849*/
850static char *local_getline(char *zPrompt, FILE *in){
851 char *zLine;
852 int nLine;
853 int n;
854 int eol;
855
856 nLine = 100;
857 zLine = malloc( nLine );
858 if( zLine==0 ) return 0;
859 n = 0;
860 eol = 0;
861 while( !eol ){
862 if( n+100>nLine ){
863 nLine = nLine*2 + 100;
864 zLine = realloc(zLine, nLine);
865 if( zLine==0 ) return 0;
866 }
867 if( fgets(&zLine[n], nLine - n, in)==0 ){
868 if( n==0 ){
869 free(zLine);
870 return 0;
871 }
872 zLine[n] = 0;
873 eol = 1;
874 break;
875 }
876 while( zLine[n] ){ n++; }
877 if( n>0 && zLine[n-1]=='\n' ){
878 n--;
879 zLine[n] = 0;
880 eol = 1;
881 }
882 }
883 zLine = realloc( zLine, n+1 );
884 return zLine;
885}
886
887/*
drh75897232000-05-29 14:26:00 +0000888** The "sqlite" command below creates a new Tcl command for each
889** connection it opens to an SQLite database. This routine is invoked
890** whenever one of those connection-specific commands is executed
891** in Tcl. For example, if you run Tcl code like this:
892**
drh9bb575f2004-09-06 17:24:11 +0000893** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +0000894** db1 close
895**
896** The first command opens a connection to the "my_database" database
897** and calls that connection "db1". The second command causes this
898** subroutine to be invoked.
899*/
drh6d313162000-09-21 13:01:35 +0000900static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +0000901 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +0000902 int choice;
drh22fbcb82004-02-01 01:22:50 +0000903 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +0000904 static const char *DB_strs[] = {
drhfb7e7652005-01-24 00:28:42 +0000905 "authorizer", "busy", "cache",
906 "changes", "close", "collate",
907 "collation_needed", "commit_hook", "complete",
drh41449052006-07-06 17:08:48 +0000908 "copy", "enable_load_extension","errorcode",
909 "eval", "exists", "function",
danielk1977b4e9af92007-05-01 17:49:49 +0000910 "incrblob",
drhf11bded2006-07-17 00:02:44 +0000911 "interrupt", "last_insert_rowid", "nullvalue",
912 "onecolumn", "profile", "progress",
913 "rekey", "rollback_hook", "timeout",
914 "total_changes", "trace", "transaction",
915 "update_hook", "version", 0
drh6d313162000-09-21 13:01:35 +0000916 };
drh411995d2002-06-25 19:31:18 +0000917 enum DB_enum {
drhfb7e7652005-01-24 00:28:42 +0000918 DB_AUTHORIZER, DB_BUSY, DB_CACHE,
919 DB_CHANGES, DB_CLOSE, DB_COLLATE,
920 DB_COLLATION_NEEDED, DB_COMMIT_HOOK, DB_COMPLETE,
drh41449052006-07-06 17:08:48 +0000921 DB_COPY, DB_ENABLE_LOAD_EXTENSION,DB_ERRORCODE,
922 DB_EVAL, DB_EXISTS, DB_FUNCTION,
danielk1977b4e9af92007-05-01 17:49:49 +0000923 DB_INCRBLOB,
drhf11bded2006-07-17 00:02:44 +0000924 DB_INTERRUPT, DB_LAST_INSERT_ROWID,DB_NULLVALUE,
925 DB_ONECOLUMN, DB_PROFILE, DB_PROGRESS,
926 DB_REKEY, DB_ROLLBACK_HOOK, DB_TIMEOUT,
927 DB_TOTAL_CHANGES, DB_TRACE, DB_TRANSACTION,
928 DB_UPDATE_HOOK, DB_VERSION,
drh6d313162000-09-21 13:01:35 +0000929 };
tpoindex1067fe12004-12-17 15:41:11 +0000930 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +0000931
932 if( objc<2 ){
933 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +0000934 return TCL_ERROR;
935 }
drh411995d2002-06-25 19:31:18 +0000936 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +0000937 return TCL_ERROR;
938 }
939
drh411995d2002-06-25 19:31:18 +0000940 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +0000941
drhe22a3342003-04-22 20:30:37 +0000942 /* $db authorizer ?CALLBACK?
943 **
944 ** Invoke the given callback to authorize each SQL operation as it is
945 ** compiled. 5 arguments are appended to the callback before it is
946 ** invoked:
947 **
948 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
949 ** (2) First descriptive name (depends on authorization type)
950 ** (3) Second descriptive name
951 ** (4) Name of the database (ex: "main", "temp")
952 ** (5) Name of trigger that is doing the access
953 **
954 ** The callback should return on of the following strings: SQLITE_OK,
955 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
956 **
957 ** If this method is invoked with no arguments, the current authorization
958 ** callback string is returned.
959 */
960 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +0000961#ifdef SQLITE_OMIT_AUTHORIZATION
962 Tcl_AppendResult(interp, "authorization not available in this build", 0);
963 return TCL_ERROR;
964#else
drhe22a3342003-04-22 20:30:37 +0000965 if( objc>3 ){
966 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +0000967 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +0000968 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +0000969 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +0000970 Tcl_AppendResult(interp, pDb->zAuth, 0);
971 }
972 }else{
973 char *zAuth;
974 int len;
975 if( pDb->zAuth ){
976 Tcl_Free(pDb->zAuth);
977 }
978 zAuth = Tcl_GetStringFromObj(objv[2], &len);
979 if( zAuth && len>0 ){
980 pDb->zAuth = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +0000981 memcpy(pDb->zAuth, zAuth, len+1);
drhe22a3342003-04-22 20:30:37 +0000982 }else{
983 pDb->zAuth = 0;
984 }
drhe22a3342003-04-22 20:30:37 +0000985 if( pDb->zAuth ){
986 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000987 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +0000988 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000989 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +0000990 }
drhe22a3342003-04-22 20:30:37 +0000991 }
drh1211de32004-07-26 12:24:22 +0000992#endif
drhe22a3342003-04-22 20:30:37 +0000993 break;
994 }
995
drhbec3f402000-08-04 13:49:02 +0000996 /* $db busy ?CALLBACK?
997 **
998 ** Invoke the given callback if an SQL statement attempts to open
999 ** a locked database file.
1000 */
drh6d313162000-09-21 13:01:35 +00001001 case DB_BUSY: {
1002 if( objc>3 ){
1003 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +00001004 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +00001005 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +00001006 if( pDb->zBusy ){
1007 Tcl_AppendResult(interp, pDb->zBusy, 0);
1008 }
1009 }else{
drh6d313162000-09-21 13:01:35 +00001010 char *zBusy;
1011 int len;
drhbec3f402000-08-04 13:49:02 +00001012 if( pDb->zBusy ){
1013 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +00001014 }
drh6d313162000-09-21 13:01:35 +00001015 zBusy = Tcl_GetStringFromObj(objv[2], &len);
1016 if( zBusy && len>0 ){
1017 pDb->zBusy = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001018 memcpy(pDb->zBusy, zBusy, len+1);
drh6d313162000-09-21 13:01:35 +00001019 }else{
1020 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +00001021 }
1022 if( pDb->zBusy ){
1023 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001024 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +00001025 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001026 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +00001027 }
1028 }
drh6d313162000-09-21 13:01:35 +00001029 break;
1030 }
drhbec3f402000-08-04 13:49:02 +00001031
drhfb7e7652005-01-24 00:28:42 +00001032 /* $db cache flush
1033 ** $db cache size n
1034 **
1035 ** Flush the prepared statement cache, or set the maximum number of
1036 ** cached statements.
1037 */
1038 case DB_CACHE: {
1039 char *subCmd;
1040 int n;
1041
1042 if( objc<=2 ){
1043 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1044 return TCL_ERROR;
1045 }
1046 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1047 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1048 if( objc!=3 ){
1049 Tcl_WrongNumArgs(interp, 2, objv, "flush");
1050 return TCL_ERROR;
1051 }else{
1052 flushStmtCache( pDb );
1053 }
1054 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1055 if( objc!=4 ){
1056 Tcl_WrongNumArgs(interp, 2, objv, "size n");
1057 return TCL_ERROR;
1058 }else{
1059 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1060 Tcl_AppendResult( interp, "cannot convert \"",
1061 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1062 return TCL_ERROR;
1063 }else{
1064 if( n<0 ){
1065 flushStmtCache( pDb );
1066 n = 0;
1067 }else if( n>MAX_PREPARED_STMTS ){
1068 n = MAX_PREPARED_STMTS;
1069 }
1070 pDb->maxStmt = n;
1071 }
1072 }
1073 }else{
1074 Tcl_AppendResult( interp, "bad option \"",
1075 Tcl_GetStringFromObj(objv[0],0), "\": must be flush or size", 0);
1076 return TCL_ERROR;
1077 }
1078 break;
1079 }
1080
danielk1977b28af712004-06-21 06:50:26 +00001081 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +00001082 **
1083 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +00001084 ** the most recent INSERT, UPDATE or DELETE statement, not including
1085 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +00001086 */
1087 case DB_CHANGES: {
1088 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +00001089 if( objc!=2 ){
1090 Tcl_WrongNumArgs(interp, 2, objv, "");
1091 return TCL_ERROR;
1092 }
drhc8d30ac2002-04-12 10:08:59 +00001093 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +00001094 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +00001095 break;
1096 }
1097
drh75897232000-05-29 14:26:00 +00001098 /* $db close
1099 **
1100 ** Shutdown the database
1101 */
drh6d313162000-09-21 13:01:35 +00001102 case DB_CLOSE: {
1103 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1104 break;
1105 }
drh75897232000-05-29 14:26:00 +00001106
drh0f14e2e2004-06-29 12:39:08 +00001107 /*
1108 ** $db collate NAME SCRIPT
1109 **
1110 ** Create a new SQL collation function called NAME. Whenever
1111 ** that function is called, invoke SCRIPT to evaluate the function.
1112 */
1113 case DB_COLLATE: {
1114 SqlCollate *pCollate;
1115 char *zName;
1116 char *zScript;
1117 int nScript;
1118 if( objc!=4 ){
1119 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1120 return TCL_ERROR;
1121 }
1122 zName = Tcl_GetStringFromObj(objv[2], 0);
1123 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1124 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1125 if( pCollate==0 ) return TCL_ERROR;
1126 pCollate->interp = interp;
1127 pCollate->pNext = pDb->pCollate;
1128 pCollate->zScript = (char*)&pCollate[1];
1129 pDb->pCollate = pCollate;
drh5bb3eb92007-05-04 13:15:55 +00001130 memcpy(pCollate->zScript, zScript, nScript+1);
drh0f14e2e2004-06-29 12:39:08 +00001131 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1132 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +00001133 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +00001134 return TCL_ERROR;
1135 }
1136 break;
1137 }
1138
1139 /*
1140 ** $db collation_needed SCRIPT
1141 **
1142 ** Create a new SQL collation function called NAME. Whenever
1143 ** that function is called, invoke SCRIPT to evaluate the function.
1144 */
1145 case DB_COLLATION_NEEDED: {
1146 if( objc!=3 ){
1147 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1148 return TCL_ERROR;
1149 }
1150 if( pDb->pCollateNeeded ){
1151 Tcl_DecrRefCount(pDb->pCollateNeeded);
1152 }
1153 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1154 Tcl_IncrRefCount(pDb->pCollateNeeded);
1155 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1156 break;
1157 }
1158
drh19e2d372005-08-29 23:00:03 +00001159 /* $db commit_hook ?CALLBACK?
1160 **
1161 ** Invoke the given callback just before committing every SQL transaction.
1162 ** If the callback throws an exception or returns non-zero, then the
1163 ** transaction is aborted. If CALLBACK is an empty string, the callback
1164 ** is disabled.
1165 */
1166 case DB_COMMIT_HOOK: {
1167 if( objc>3 ){
1168 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1169 return TCL_ERROR;
1170 }else if( objc==2 ){
1171 if( pDb->zCommit ){
1172 Tcl_AppendResult(interp, pDb->zCommit, 0);
1173 }
1174 }else{
1175 char *zCommit;
1176 int len;
1177 if( pDb->zCommit ){
1178 Tcl_Free(pDb->zCommit);
1179 }
1180 zCommit = Tcl_GetStringFromObj(objv[2], &len);
1181 if( zCommit && len>0 ){
1182 pDb->zCommit = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001183 memcpy(pDb->zCommit, zCommit, len+1);
drh19e2d372005-08-29 23:00:03 +00001184 }else{
1185 pDb->zCommit = 0;
1186 }
1187 if( pDb->zCommit ){
1188 pDb->interp = interp;
1189 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1190 }else{
1191 sqlite3_commit_hook(pDb->db, 0, 0);
1192 }
1193 }
1194 break;
1195 }
1196
drh75897232000-05-29 14:26:00 +00001197 /* $db complete SQL
1198 **
1199 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
1200 ** additional lines of input are needed. This is similar to the
1201 ** built-in "info complete" command of Tcl.
1202 */
drh6d313162000-09-21 13:01:35 +00001203 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +00001204#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +00001205 Tcl_Obj *pResult;
1206 int isComplete;
1207 if( objc!=3 ){
1208 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +00001209 return TCL_ERROR;
1210 }
danielk19776f8a5032004-05-10 10:34:51 +00001211 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +00001212 pResult = Tcl_GetObjResult(interp);
1213 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +00001214#endif
drh6d313162000-09-21 13:01:35 +00001215 break;
1216 }
drhdcd997e2003-01-31 17:21:49 +00001217
drh19e2d372005-08-29 23:00:03 +00001218 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1219 **
1220 ** Copy data into table from filename, optionally using SEPARATOR
1221 ** as column separators. If a column contains a null string, or the
1222 ** value of NULLINDICATOR, a NULL is inserted for the column.
1223 ** conflict-algorithm is one of the sqlite conflict algorithms:
1224 ** rollback, abort, fail, ignore, replace
1225 ** On success, return the number of lines processed, not necessarily same
1226 ** as 'db changes' due to conflict-algorithm selected.
1227 **
1228 ** This code is basically an implementation/enhancement of
1229 ** the sqlite3 shell.c ".import" command.
1230 **
1231 ** This command usage is equivalent to the sqlite2.x COPY statement,
1232 ** which imports file data into a table using the PostgreSQL COPY file format:
1233 ** $db copy $conflit_algo $table_name $filename \t \\N
1234 */
1235 case DB_COPY: {
1236 char *zTable; /* Insert data into this table */
1237 char *zFile; /* The file from which to extract data */
1238 char *zConflict; /* The conflict algorithm to use */
1239 sqlite3_stmt *pStmt; /* A statement */
1240 int rc; /* Result code */
1241 int nCol; /* Number of columns in the table */
1242 int nByte; /* Number of bytes in an SQL string */
1243 int i, j; /* Loop counters */
1244 int nSep; /* Number of bytes in zSep[] */
1245 int nNull; /* Number of bytes in zNull[] */
1246 char *zSql; /* An SQL statement */
1247 char *zLine; /* A single line of input from the file */
1248 char **azCol; /* zLine[] broken up into columns */
1249 char *zCommit; /* How to commit changes */
1250 FILE *in; /* The input file */
1251 int lineno = 0; /* Line number of input file */
1252 char zLineNum[80]; /* Line number print buffer */
1253 Tcl_Obj *pResult; /* interp result */
1254
1255 char *zSep;
1256 char *zNull;
1257 if( objc<5 || objc>7 ){
1258 Tcl_WrongNumArgs(interp, 2, objv,
1259 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1260 return TCL_ERROR;
1261 }
1262 if( objc>=6 ){
1263 zSep = Tcl_GetStringFromObj(objv[5], 0);
1264 }else{
1265 zSep = "\t";
1266 }
1267 if( objc>=7 ){
1268 zNull = Tcl_GetStringFromObj(objv[6], 0);
1269 }else{
1270 zNull = "";
1271 }
1272 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1273 zTable = Tcl_GetStringFromObj(objv[3], 0);
1274 zFile = Tcl_GetStringFromObj(objv[4], 0);
1275 nSep = strlen(zSep);
1276 nNull = strlen(zNull);
1277 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00001278 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00001279 return TCL_ERROR;
1280 }
1281 if(sqlite3StrICmp(zConflict, "rollback") != 0 &&
1282 sqlite3StrICmp(zConflict, "abort" ) != 0 &&
1283 sqlite3StrICmp(zConflict, "fail" ) != 0 &&
1284 sqlite3StrICmp(zConflict, "ignore" ) != 0 &&
1285 sqlite3StrICmp(zConflict, "replace" ) != 0 ) {
1286 Tcl_AppendResult(interp, "Error: \"", zConflict,
1287 "\", conflict-algorithm must be one of: rollback, "
1288 "abort, fail, ignore, or replace", 0);
1289 return TCL_ERROR;
1290 }
1291 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1292 if( zSql==0 ){
1293 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1294 return TCL_ERROR;
1295 }
1296 nByte = strlen(zSql);
drh3e701a12007-02-01 01:53:44 +00001297 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001298 sqlite3_free(zSql);
1299 if( rc ){
1300 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1301 nCol = 0;
1302 }else{
1303 nCol = sqlite3_column_count(pStmt);
1304 }
1305 sqlite3_finalize(pStmt);
1306 if( nCol==0 ) {
1307 return TCL_ERROR;
1308 }
1309 zSql = malloc( nByte + 50 + nCol*2 );
1310 if( zSql==0 ) {
1311 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1312 return TCL_ERROR;
1313 }
1314 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1315 zConflict, zTable);
1316 j = strlen(zSql);
1317 for(i=1; i<nCol; i++){
1318 zSql[j++] = ',';
1319 zSql[j++] = '?';
1320 }
1321 zSql[j++] = ')';
1322 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00001323 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001324 free(zSql);
1325 if( rc ){
1326 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1327 sqlite3_finalize(pStmt);
1328 return TCL_ERROR;
1329 }
1330 in = fopen(zFile, "rb");
1331 if( in==0 ){
1332 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
1333 sqlite3_finalize(pStmt);
1334 return TCL_ERROR;
1335 }
1336 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1337 if( azCol==0 ) {
1338 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00001339 fclose(in);
drh19e2d372005-08-29 23:00:03 +00001340 return TCL_ERROR;
1341 }
drh37527852006-03-16 16:19:56 +00001342 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001343 zCommit = "COMMIT";
1344 while( (zLine = local_getline(0, in))!=0 ){
1345 char *z;
1346 i = 0;
1347 lineno++;
1348 azCol[0] = zLine;
1349 for(i=0, z=zLine; *z; z++){
1350 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
1351 *z = 0;
1352 i++;
1353 if( i<nCol ){
1354 azCol[i] = &z[nSep];
1355 z += nSep-1;
1356 }
1357 }
1358 }
1359 if( i+1!=nCol ){
1360 char *zErr;
drh5bb3eb92007-05-04 13:15:55 +00001361 int nErr = strlen(zFile) + 200;
1362 zErr = malloc(nErr);
drhc1f44942006-05-10 14:39:13 +00001363 if( zErr ){
drh5bb3eb92007-05-04 13:15:55 +00001364 sqlite3_snprintf(nErr, zErr,
drhc1f44942006-05-10 14:39:13 +00001365 "Error: %s line %d: expected %d columns of data but found %d",
1366 zFile, lineno, nCol, i+1);
1367 Tcl_AppendResult(interp, zErr, 0);
1368 free(zErr);
1369 }
drh19e2d372005-08-29 23:00:03 +00001370 zCommit = "ROLLBACK";
1371 break;
1372 }
1373 for(i=0; i<nCol; i++){
1374 /* check for null data, if so, bind as null */
1375 if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
1376 sqlite3_bind_null(pStmt, i+1);
1377 }else{
1378 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1379 }
1380 }
1381 sqlite3_step(pStmt);
1382 rc = sqlite3_reset(pStmt);
1383 free(zLine);
1384 if( rc!=SQLITE_OK ){
1385 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
1386 zCommit = "ROLLBACK";
1387 break;
1388 }
1389 }
1390 free(azCol);
1391 fclose(in);
1392 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00001393 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001394
1395 if( zCommit[0] == 'C' ){
1396 /* success, set result as number of lines processed */
1397 pResult = Tcl_GetObjResult(interp);
1398 Tcl_SetIntObj(pResult, lineno);
1399 rc = TCL_OK;
1400 }else{
1401 /* failure, append lineno where failed */
drh5bb3eb92007-05-04 13:15:55 +00001402 sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
drh19e2d372005-08-29 23:00:03 +00001403 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
1404 rc = TCL_ERROR;
1405 }
1406 break;
1407 }
1408
drhdcd997e2003-01-31 17:21:49 +00001409 /*
drh41449052006-07-06 17:08:48 +00001410 ** $db enable_load_extension BOOLEAN
1411 **
1412 ** Turn the extension loading feature on or off. It if off by
1413 ** default.
1414 */
1415 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00001416#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00001417 int onoff;
1418 if( objc!=3 ){
1419 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
1420 return TCL_ERROR;
1421 }
1422 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
1423 return TCL_ERROR;
1424 }
1425 sqlite3_enable_load_extension(pDb->db, onoff);
1426 break;
drhf533acc2006-12-19 18:57:11 +00001427#else
1428 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
1429 0);
1430 return TCL_ERROR;
1431#endif
drh41449052006-07-06 17:08:48 +00001432 }
1433
1434 /*
drhdcd997e2003-01-31 17:21:49 +00001435 ** $db errorcode
1436 **
1437 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00001438 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00001439 */
1440 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00001441 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00001442 break;
1443 }
drh75897232000-05-29 14:26:00 +00001444
1445 /*
drh895d7472004-08-20 16:02:39 +00001446 ** $db eval $sql ?array? ?{ ...code... }?
drh1807ce32004-09-07 13:20:35 +00001447 ** $db onecolumn $sql
drh75897232000-05-29 14:26:00 +00001448 **
1449 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00001450 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00001451 ** If "array" and "code" are omitted, then no callback is every invoked.
1452 ** If "array" is an empty string, then the values are placed in variables
1453 ** that have the same name as the fields extracted by the query.
drh1807ce32004-09-07 13:20:35 +00001454 **
1455 ** The onecolumn method is the equivalent of:
1456 ** lindex [$db eval $sql] 0
drh75897232000-05-29 14:26:00 +00001457 */
drh1807ce32004-09-07 13:20:35 +00001458 case DB_ONECOLUMN:
drh97f2ebc2005-12-10 21:19:04 +00001459 case DB_EVAL:
1460 case DB_EXISTS: {
drh9d74b4c2004-08-24 15:23:34 +00001461 char const *zSql; /* Next SQL statement to execute */
1462 char const *zLeft; /* What is left after first stmt in zSql */
1463 sqlite3_stmt *pStmt; /* Compiled SQL statment */
drh92febd92004-08-20 18:34:20 +00001464 Tcl_Obj *pArray; /* Name of array into which results are written */
1465 Tcl_Obj *pScript; /* Script to run for each result set */
drh1d895032004-08-26 00:56:05 +00001466 Tcl_Obj **apParm; /* Parameters that need a Tcl_DecrRefCount() */
1467 int nParm; /* Number of entries used in apParm[] */
1468 Tcl_Obj *aParm[10]; /* Static space for apParm[] in the common case */
drh1807ce32004-09-07 13:20:35 +00001469 Tcl_Obj *pRet; /* Value to be returned */
drhfb7e7652005-01-24 00:28:42 +00001470 SqlPreparedStmt *pPreStmt; /* Pointer to a prepared statement */
1471 int rc2;
danielk1977ef2cb632004-05-29 02:37:19 +00001472
drh97f2ebc2005-12-10 21:19:04 +00001473 if( choice==DB_EVAL ){
drh1807ce32004-09-07 13:20:35 +00001474 if( objc<3 || objc>5 ){
1475 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
1476 return TCL_ERROR;
1477 }
1478 pRet = Tcl_NewObj();
1479 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001480 }else{
1481 if( objc!=3 ){
1482 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
1483 return TCL_ERROR;
1484 }
drh97f2ebc2005-12-10 21:19:04 +00001485 if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001486 pRet = Tcl_NewBooleanObj(0);
1487 Tcl_IncrRefCount(pRet);
1488 }else{
1489 pRet = 0;
drh97f2ebc2005-12-10 21:19:04 +00001490 }
danielk197730ccda12004-05-27 12:11:31 +00001491 }
drh92febd92004-08-20 18:34:20 +00001492 if( objc==3 ){
1493 pArray = pScript = 0;
1494 }else if( objc==4 ){
1495 pArray = 0;
1496 pScript = objv[3];
1497 }else{
1498 pArray = objv[3];
1499 if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
1500 pScript = objv[4];
1501 }
danielk197730ccda12004-05-27 12:11:31 +00001502
drh1d895032004-08-26 00:56:05 +00001503 Tcl_IncrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001504 zSql = Tcl_GetStringFromObj(objv[2], 0);
drh90b6bb12004-09-13 13:16:31 +00001505 while( rc==TCL_OK && zSql[0] ){
drhfb7e7652005-01-24 00:28:42 +00001506 int i; /* Loop counter */
1507 int nVar; /* Number of bind parameters in the pStmt */
1508 int nCol; /* Number of columns in the result set */
drh92febd92004-08-20 18:34:20 +00001509 Tcl_Obj **apColName = 0; /* Array of column names */
drhfb7e7652005-01-24 00:28:42 +00001510 int len; /* String length of zSql */
danielk197730ccda12004-05-27 12:11:31 +00001511
drhfb7e7652005-01-24 00:28:42 +00001512 /* Try to find a SQL statement that has already been compiled and
1513 ** which matches the next sequence of SQL.
1514 */
1515 pStmt = 0;
1516 pPreStmt = pDb->stmtList;
1517 len = strlen(zSql);
1518 if( pPreStmt && sqlite3_expired(pPreStmt->pStmt) ){
1519 flushStmtCache(pDb);
1520 pPreStmt = 0;
danielk197730ccda12004-05-27 12:11:31 +00001521 }
drhfb7e7652005-01-24 00:28:42 +00001522 for(; pPreStmt; pPreStmt=pPreStmt->pNext){
1523 int n = pPreStmt->nSql;
1524 if( len>=n
1525 && memcmp(pPreStmt->zSql, zSql, n)==0
1526 && (zSql[n]==0 || zSql[n-1]==';')
1527 ){
1528 pStmt = pPreStmt->pStmt;
1529 zLeft = &zSql[pPreStmt->nSql];
1530
1531 /* When a prepared statement is found, unlink it from the
1532 ** cache list. It will later be added back to the beginning
1533 ** of the cache list in order to implement LRU replacement.
1534 */
1535 if( pPreStmt->pPrev ){
1536 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1537 }else{
1538 pDb->stmtList = pPreStmt->pNext;
1539 }
1540 if( pPreStmt->pNext ){
1541 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1542 }else{
1543 pDb->stmtLast = pPreStmt->pPrev;
1544 }
1545 pDb->nStmt--;
1546 break;
1547 }
1548 }
1549
1550 /* If no prepared statement was found. Compile the SQL text
1551 */
drh92febd92004-08-20 18:34:20 +00001552 if( pStmt==0 ){
drhfb7e7652005-01-24 00:28:42 +00001553 if( SQLITE_OK!=sqlite3_prepare(pDb->db, zSql, -1, &pStmt, &zLeft) ){
drh92febd92004-08-20 18:34:20 +00001554 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1555 rc = TCL_ERROR;
1556 break;
danielk197730ccda12004-05-27 12:11:31 +00001557 }
drhfb7e7652005-01-24 00:28:42 +00001558 if( pStmt==0 ){
1559 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1560 /* A compile-time error in the statement
1561 */
1562 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1563 rc = TCL_ERROR;
1564 break;
1565 }else{
1566 /* The statement was a no-op. Continue to the next statement
1567 ** in the SQL string.
1568 */
1569 zSql = zLeft;
1570 continue;
1571 }
1572 }
1573 assert( pPreStmt==0 );
danielk197730ccda12004-05-27 12:11:31 +00001574 }
1575
drhfb7e7652005-01-24 00:28:42 +00001576 /* Bind values to parameters that begin with $ or :
1577 */
drh92febd92004-08-20 18:34:20 +00001578 nVar = sqlite3_bind_parameter_count(pStmt);
drh1d895032004-08-26 00:56:05 +00001579 nParm = 0;
1580 if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
1581 apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
1582 }else{
1583 apParm = aParm;
1584 }
drh92febd92004-08-20 18:34:20 +00001585 for(i=1; i<=nVar; i++){
1586 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
drhc8f90792005-01-12 00:08:24 +00001587 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':') ){
drh92febd92004-08-20 18:34:20 +00001588 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1589 if( pVar ){
1590 int n;
1591 u8 *data;
1592 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
1593 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +00001594 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
1595 /* Only load a BLOB type if the Tcl variable is a bytearray and
1596 ** has no string representation. */
drh92febd92004-08-20 18:34:20 +00001597 data = Tcl_GetByteArrayFromObj(pVar, &n);
1598 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001599 Tcl_IncrRefCount(pVar);
1600 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001601 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
1602 (c=='i' && strcmp(zType,"int")==0) ){
1603 Tcl_GetIntFromObj(interp, pVar, &n);
1604 sqlite3_bind_int(pStmt, i, n);
1605 }else if( c=='d' && strcmp(zType,"double")==0 ){
1606 double r;
1607 Tcl_GetDoubleFromObj(interp, pVar, &r);
1608 sqlite3_bind_double(pStmt, i, r);
drhdf0bdda2005-06-25 19:31:48 +00001609 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
1610 Tcl_WideInt v;
1611 Tcl_GetWideIntFromObj(interp, pVar, &v);
1612 sqlite3_bind_int64(pStmt, i, v);
drh92febd92004-08-20 18:34:20 +00001613 }else{
danielk197700fd9572005-12-07 06:27:43 +00001614 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1615 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001616 Tcl_IncrRefCount(pVar);
1617 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001618 }
drhfb7e7652005-01-24 00:28:42 +00001619 }else{
1620 sqlite3_bind_null( pStmt, i );
drh92febd92004-08-20 18:34:20 +00001621 }
1622 }
1623 }
drh92febd92004-08-20 18:34:20 +00001624
1625 /* Compute column names */
1626 nCol = sqlite3_column_count(pStmt);
1627 if( pScript ){
1628 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1629 if( apColName==0 ) break;
1630 for(i=0; i<nCol; i++){
1631 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1632 Tcl_IncrRefCount(apColName[i]);
1633 }
1634 }
1635
1636 /* If results are being stored in an array variable, then create
1637 ** the array(*) entry for that array
1638 */
1639 if( pArray ){
1640 Tcl_Obj *pColList = Tcl_NewObj();
drh3ced14a2005-03-31 18:26:20 +00001641 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
drh92febd92004-08-20 18:34:20 +00001642 Tcl_IncrRefCount(pColList);
1643 for(i=0; i<nCol; i++){
1644 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1645 }
drh3ced14a2005-03-31 18:26:20 +00001646 Tcl_ObjSetVar2(interp, pArray, pStar, pColList,0);
1647 Tcl_DecrRefCount(pColList);
1648 Tcl_DecrRefCount(pStar);
drh92febd92004-08-20 18:34:20 +00001649 }
1650
1651 /* Execute the SQL
1652 */
drh90b6bb12004-09-13 13:16:31 +00001653 while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
drh92febd92004-08-20 18:34:20 +00001654 for(i=0; i<nCol; i++){
danielk197730ccda12004-05-27 12:11:31 +00001655 Tcl_Obj *pVal;
1656
1657 /* Set pVal to contain the i'th column of this row. */
drh92febd92004-08-20 18:34:20 +00001658 switch( sqlite3_column_type(pStmt, i) ){
1659 case SQLITE_BLOB: {
1660 int bytes = sqlite3_column_bytes(pStmt, i);
1661 pVal = Tcl_NewByteArrayObj(sqlite3_column_blob(pStmt, i), bytes);
1662 break;
1663 }
1664 case SQLITE_INTEGER: {
1665 sqlite_int64 v = sqlite3_column_int64(pStmt, i);
1666 if( v>=-2147483647 && v<=2147483647 ){
1667 pVal = Tcl_NewIntObj(v);
1668 }else{
1669 pVal = Tcl_NewWideIntObj(v);
1670 }
1671 break;
1672 }
1673 case SQLITE_FLOAT: {
1674 double r = sqlite3_column_double(pStmt, i);
1675 pVal = Tcl_NewDoubleObj(r);
1676 break;
1677 }
danielk197755c45f22005-04-03 23:54:43 +00001678 case SQLITE_NULL: {
1679 pVal = dbTextToObj(pDb->zNull);
1680 break;
1681 }
drh92febd92004-08-20 18:34:20 +00001682 default: {
danielk197700fd9572005-12-07 06:27:43 +00001683 pVal = dbTextToObj((char *)sqlite3_column_text(pStmt, i));
drh92febd92004-08-20 18:34:20 +00001684 break;
1685 }
danielk197730ccda12004-05-27 12:11:31 +00001686 }
1687
drh92febd92004-08-20 18:34:20 +00001688 if( pScript ){
1689 if( pArray==0 ){
1690 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001691 }else{
drh92febd92004-08-20 18:34:20 +00001692 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001693 }
drh1807ce32004-09-07 13:20:35 +00001694 }else if( choice==DB_ONECOLUMN ){
drh97f2ebc2005-12-10 21:19:04 +00001695 assert( pRet==0 );
drh1807ce32004-09-07 13:20:35 +00001696 if( pRet==0 ){
1697 pRet = pVal;
1698 Tcl_IncrRefCount(pRet);
1699 }
drh90b6bb12004-09-13 13:16:31 +00001700 rc = TCL_BREAK;
drh97f2ebc2005-12-10 21:19:04 +00001701 i = nCol;
1702 }else if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001703 Tcl_DecrRefCount(pRet);
1704 pRet = Tcl_NewBooleanObj(1);
1705 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001706 rc = TCL_BREAK;
1707 i = nCol;
danielk197730ccda12004-05-27 12:11:31 +00001708 }else{
danielk197730ccda12004-05-27 12:11:31 +00001709 Tcl_ListObjAppendElement(interp, pRet, pVal);
1710 }
1711 }
1712
drh92febd92004-08-20 18:34:20 +00001713 if( pScript ){
1714 rc = Tcl_EvalObjEx(interp, pScript, 0);
drh90b6bb12004-09-13 13:16:31 +00001715 if( rc==TCL_CONTINUE ){
1716 rc = TCL_OK;
1717 }
danielk197730ccda12004-05-27 12:11:31 +00001718 }
1719 }
drh90b6bb12004-09-13 13:16:31 +00001720 if( rc==TCL_BREAK ){
1721 rc = TCL_OK;
1722 }
drh92febd92004-08-20 18:34:20 +00001723
1724 /* Free the column name objects */
1725 if( pScript ){
1726 for(i=0; i<nCol; i++){
1727 Tcl_DecrRefCount(apColName[i]);
1728 }
1729 Tcl_Free((char*)apColName);
1730 }
1731
drh1d895032004-08-26 00:56:05 +00001732 /* Free the bound string and blob parameters */
1733 for(i=0; i<nParm; i++){
1734 Tcl_DecrRefCount(apParm[i]);
1735 }
1736 if( apParm!=aParm ){
1737 Tcl_Free((char*)apParm);
1738 }
1739
drhfb7e7652005-01-24 00:28:42 +00001740 /* Reset the statement. If the result code is SQLITE_SCHEMA, then
1741 ** flush the statement cache and try the statement again.
drh92febd92004-08-20 18:34:20 +00001742 */
drhfb7e7652005-01-24 00:28:42 +00001743 rc2 = sqlite3_reset(pStmt);
1744 if( SQLITE_SCHEMA==rc2 ){
1745 /* After a schema change, flush the cache and try to run the
1746 ** statement again
1747 */
1748 flushStmtCache( pDb );
1749 sqlite3_finalize(pStmt);
1750 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001751 continue;
drhfb7e7652005-01-24 00:28:42 +00001752 }else if( SQLITE_OK!=rc2 ){
1753 /* If a run-time error occurs, report the error and stop reading
1754 ** the SQL
1755 */
danielk1977ef2cb632004-05-29 02:37:19 +00001756 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
drhfb7e7652005-01-24 00:28:42 +00001757 sqlite3_finalize(pStmt);
danielk197730ccda12004-05-27 12:11:31 +00001758 rc = TCL_ERROR;
drhfb7e7652005-01-24 00:28:42 +00001759 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001760 break;
drhfb7e7652005-01-24 00:28:42 +00001761 }else if( pDb->maxStmt<=0 ){
1762 /* If the cache is turned off, deallocated the statement */
1763 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1764 sqlite3_finalize(pStmt);
1765 }else{
1766 /* Everything worked and the cache is operational.
1767 ** Create a new SqlPreparedStmt structure if we need one.
1768 ** (If we already have one we can just reuse it.)
1769 */
1770 if( pPreStmt==0 ){
1771 len = zLeft - zSql;
1772 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) + len );
1773 if( pPreStmt==0 ) return TCL_ERROR;
1774 pPreStmt->pStmt = pStmt;
1775 pPreStmt->nSql = len;
1776 memcpy(pPreStmt->zSql, zSql, len);
1777 pPreStmt->zSql[len] = 0;
1778 }
1779
1780 /* Add the prepared statement to the beginning of the cache list
1781 */
1782 pPreStmt->pNext = pDb->stmtList;
1783 pPreStmt->pPrev = 0;
1784 if( pDb->stmtList ){
1785 pDb->stmtList->pPrev = pPreStmt;
1786 }
1787 pDb->stmtList = pPreStmt;
1788 if( pDb->stmtLast==0 ){
1789 assert( pDb->nStmt==0 );
1790 pDb->stmtLast = pPreStmt;
1791 }else{
1792 assert( pDb->nStmt>0 );
1793 }
1794 pDb->nStmt++;
1795
1796 /* If we have too many statement in cache, remove the surplus from the
1797 ** end of the cache list.
1798 */
1799 while( pDb->nStmt>pDb->maxStmt ){
1800 sqlite3_finalize(pDb->stmtLast->pStmt);
1801 pDb->stmtLast = pDb->stmtLast->pPrev;
1802 Tcl_Free((char*)pDb->stmtLast->pNext);
1803 pDb->stmtLast->pNext = 0;
1804 pDb->nStmt--;
1805 }
danielk197730ccda12004-05-27 12:11:31 +00001806 }
1807
drhfb7e7652005-01-24 00:28:42 +00001808 /* Proceed to the next statement */
danielk197730ccda12004-05-27 12:11:31 +00001809 zSql = zLeft;
1810 }
drh1d895032004-08-26 00:56:05 +00001811 Tcl_DecrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001812
drh1807ce32004-09-07 13:20:35 +00001813 if( pRet ){
1814 if( rc==TCL_OK ){
1815 Tcl_SetObjResult(interp, pRet);
1816 }
1817 Tcl_DecrRefCount(pRet);
drh050be322006-07-12 00:18:40 +00001818 }else if( rc==TCL_OK ){
1819 Tcl_ResetResult(interp);
danielk197730ccda12004-05-27 12:11:31 +00001820 }
danielk197730ccda12004-05-27 12:11:31 +00001821 break;
1822 }
drhbec3f402000-08-04 13:49:02 +00001823
1824 /*
drhcabb0812002-09-14 13:47:32 +00001825 ** $db function NAME SCRIPT
1826 **
1827 ** Create a new SQL function called NAME. Whenever that function is
1828 ** called, invoke SCRIPT to evaluate the function.
1829 */
1830 case DB_FUNCTION: {
1831 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00001832 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00001833 char *zName;
drhcabb0812002-09-14 13:47:32 +00001834 if( objc!=4 ){
1835 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1836 return TCL_ERROR;
1837 }
1838 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00001839 pScript = objv[3];
1840 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00001841 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00001842 if( pFunc->pScript ){
1843 Tcl_DecrRefCount(pFunc->pScript);
1844 }
1845 pFunc->pScript = pScript;
1846 Tcl_IncrRefCount(pScript);
1847 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
danielk1977c8c11582004-06-29 13:41:21 +00001848 rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00001849 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00001850 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00001851 rc = TCL_ERROR;
1852 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00001853 }else{
1854 /* Must flush any cached statements */
1855 flushStmtCache( pDb );
1856 }
drhcabb0812002-09-14 13:47:32 +00001857 break;
1858 }
1859
1860 /*
danielk19778cbadb02007-05-03 16:31:26 +00001861 ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
danielk1977b4e9af92007-05-01 17:49:49 +00001862 */
1863 case DB_INCRBLOB: {
danielk19778cbadb02007-05-03 16:31:26 +00001864 int isReadonly = 0;
danielk1977b4e9af92007-05-01 17:49:49 +00001865 const char *zDb = "main";
1866 const char *zTable;
1867 const char *zColumn;
1868 sqlite_int64 iRow;
1869
danielk19778cbadb02007-05-03 16:31:26 +00001870 /* Check for the -readonly option */
1871 if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
1872 isReadonly = 1;
1873 }
1874
1875 if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
1876 Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
danielk1977b4e9af92007-05-01 17:49:49 +00001877 return TCL_ERROR;
1878 }
1879
danielk19778cbadb02007-05-03 16:31:26 +00001880 if( objc==(6+isReadonly) ){
danielk1977b4e9af92007-05-01 17:49:49 +00001881 zDb = Tcl_GetString(objv[2]);
1882 }
1883 zTable = Tcl_GetString(objv[objc-3]);
1884 zColumn = Tcl_GetString(objv[objc-2]);
1885 rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
1886
1887 if( rc==TCL_OK ){
danielk19778cbadb02007-05-03 16:31:26 +00001888 rc = createIncrblobChannel(
1889 interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
1890 );
danielk1977b4e9af92007-05-01 17:49:49 +00001891 }
1892 break;
1893 }
1894
1895 /*
drhf11bded2006-07-17 00:02:44 +00001896 ** $db interrupt
1897 **
1898 ** Interrupt the execution of the inner-most SQL interpreter. This
1899 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
1900 */
1901 case DB_INTERRUPT: {
1902 sqlite3_interrupt(pDb->db);
1903 break;
1904 }
1905
1906 /*
drh19e2d372005-08-29 23:00:03 +00001907 ** $db nullvalue ?STRING?
1908 **
1909 ** Change text used when a NULL comes back from the database. If ?STRING?
1910 ** is not present, then the current string used for NULL is returned.
1911 ** If STRING is present, then STRING is returned.
1912 **
1913 */
1914 case DB_NULLVALUE: {
1915 if( objc!=2 && objc!=3 ){
1916 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
1917 return TCL_ERROR;
1918 }
1919 if( objc==3 ){
1920 int len;
1921 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
1922 if( pDb->zNull ){
1923 Tcl_Free(pDb->zNull);
1924 }
1925 if( zNull && len>0 ){
1926 pDb->zNull = Tcl_Alloc( len + 1 );
1927 strncpy(pDb->zNull, zNull, len);
1928 pDb->zNull[len] = '\0';
1929 }else{
1930 pDb->zNull = 0;
1931 }
1932 }
1933 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
1934 break;
1935 }
1936
1937 /*
drhaf9ff332002-01-16 21:00:27 +00001938 ** $db last_insert_rowid
1939 **
1940 ** Return an integer which is the ROWID for the most recent insert.
1941 */
1942 case DB_LAST_INSERT_ROWID: {
1943 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00001944 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00001945 if( objc!=2 ){
1946 Tcl_WrongNumArgs(interp, 2, objv, "");
1947 return TCL_ERROR;
1948 }
danielk19776f8a5032004-05-10 10:34:51 +00001949 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00001950 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00001951 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00001952 break;
1953 }
1954
1955 /*
drh1807ce32004-09-07 13:20:35 +00001956 ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
drh5d9d7572003-08-19 14:31:01 +00001957 */
drh1807ce32004-09-07 13:20:35 +00001958
1959 /* $db progress ?N CALLBACK?
1960 **
1961 ** Invoke the given callback every N virtual machine opcodes while executing
1962 ** queries.
1963 */
1964 case DB_PROGRESS: {
1965 if( objc==2 ){
1966 if( pDb->zProgress ){
1967 Tcl_AppendResult(interp, pDb->zProgress, 0);
1968 }
1969 }else if( objc==4 ){
1970 char *zProgress;
1971 int len;
1972 int N;
1973 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
1974 return TCL_ERROR;
1975 };
1976 if( pDb->zProgress ){
1977 Tcl_Free(pDb->zProgress);
1978 }
1979 zProgress = Tcl_GetStringFromObj(objv[3], &len);
1980 if( zProgress && len>0 ){
1981 pDb->zProgress = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00001982 memcpy(pDb->zProgress, zProgress, len+1);
drh1807ce32004-09-07 13:20:35 +00001983 }else{
1984 pDb->zProgress = 0;
1985 }
1986#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1987 if( pDb->zProgress ){
1988 pDb->interp = interp;
1989 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
1990 }else{
1991 sqlite3_progress_handler(pDb->db, 0, 0, 0);
1992 }
1993#endif
1994 }else{
1995 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00001996 return TCL_ERROR;
1997 }
drh5d9d7572003-08-19 14:31:01 +00001998 break;
1999 }
2000
drh19e2d372005-08-29 23:00:03 +00002001 /* $db profile ?CALLBACK?
2002 **
2003 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2004 ** that has run. The text of the SQL and the amount of elapse time are
2005 ** appended to CALLBACK before the script is run.
2006 */
2007 case DB_PROFILE: {
2008 if( objc>3 ){
2009 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2010 return TCL_ERROR;
2011 }else if( objc==2 ){
2012 if( pDb->zProfile ){
2013 Tcl_AppendResult(interp, pDb->zProfile, 0);
2014 }
2015 }else{
2016 char *zProfile;
2017 int len;
2018 if( pDb->zProfile ){
2019 Tcl_Free(pDb->zProfile);
2020 }
2021 zProfile = Tcl_GetStringFromObj(objv[2], &len);
2022 if( zProfile && len>0 ){
2023 pDb->zProfile = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002024 memcpy(pDb->zProfile, zProfile, len+1);
drh19e2d372005-08-29 23:00:03 +00002025 }else{
2026 pDb->zProfile = 0;
2027 }
2028#ifndef SQLITE_OMIT_TRACE
2029 if( pDb->zProfile ){
2030 pDb->interp = interp;
2031 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2032 }else{
2033 sqlite3_profile(pDb->db, 0, 0);
2034 }
2035#endif
2036 }
2037 break;
2038 }
2039
drh5d9d7572003-08-19 14:31:01 +00002040 /*
drh22fbcb82004-02-01 01:22:50 +00002041 ** $db rekey KEY
2042 **
2043 ** Change the encryption key on the currently open database.
2044 */
2045 case DB_REKEY: {
2046 int nKey;
2047 void *pKey;
2048 if( objc!=3 ){
2049 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2050 return TCL_ERROR;
2051 }
2052 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00002053#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00002054 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00002055 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00002056 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00002057 rc = TCL_ERROR;
2058 }
2059#endif
2060 break;
2061 }
2062
2063 /*
drhbec3f402000-08-04 13:49:02 +00002064 ** $db timeout MILLESECONDS
2065 **
2066 ** Delay for the number of milliseconds specified when a file is locked.
2067 */
drh6d313162000-09-21 13:01:35 +00002068 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00002069 int ms;
drh6d313162000-09-21 13:01:35 +00002070 if( objc!=3 ){
2071 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00002072 return TCL_ERROR;
2073 }
drh6d313162000-09-21 13:01:35 +00002074 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00002075 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00002076 break;
drh75897232000-05-29 14:26:00 +00002077 }
danielk197755c45f22005-04-03 23:54:43 +00002078
2079 /*
drh0f14e2e2004-06-29 12:39:08 +00002080 ** $db total_changes
2081 **
2082 ** Return the number of rows that were modified, inserted, or deleted
2083 ** since the database handle was created.
2084 */
2085 case DB_TOTAL_CHANGES: {
2086 Tcl_Obj *pResult;
2087 if( objc!=2 ){
2088 Tcl_WrongNumArgs(interp, 2, objv, "");
2089 return TCL_ERROR;
2090 }
2091 pResult = Tcl_GetObjResult(interp);
2092 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2093 break;
2094 }
2095
drhb5a20d32003-04-23 12:25:23 +00002096 /* $db trace ?CALLBACK?
2097 **
2098 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2099 ** that is executed. The text of the SQL is appended to CALLBACK before
2100 ** it is executed.
2101 */
2102 case DB_TRACE: {
2103 if( objc>3 ){
2104 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00002105 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00002106 }else if( objc==2 ){
2107 if( pDb->zTrace ){
2108 Tcl_AppendResult(interp, pDb->zTrace, 0);
2109 }
2110 }else{
2111 char *zTrace;
2112 int len;
2113 if( pDb->zTrace ){
2114 Tcl_Free(pDb->zTrace);
2115 }
2116 zTrace = Tcl_GetStringFromObj(objv[2], &len);
2117 if( zTrace && len>0 ){
2118 pDb->zTrace = Tcl_Alloc( len + 1 );
drh5bb3eb92007-05-04 13:15:55 +00002119 memcpy(pDb->zTrace, zTrace, len+1);
drhb5a20d32003-04-23 12:25:23 +00002120 }else{
2121 pDb->zTrace = 0;
2122 }
drh19e2d372005-08-29 23:00:03 +00002123#ifndef SQLITE_OMIT_TRACE
drhb5a20d32003-04-23 12:25:23 +00002124 if( pDb->zTrace ){
2125 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00002126 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00002127 }else{
danielk19776f8a5032004-05-10 10:34:51 +00002128 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00002129 }
drh19e2d372005-08-29 23:00:03 +00002130#endif
drhb5a20d32003-04-23 12:25:23 +00002131 }
2132 break;
2133 }
2134
drh3d214232005-08-02 12:21:08 +00002135 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2136 **
2137 ** Start a new transaction (if we are not already in the midst of a
2138 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
2139 ** completes, either commit the transaction or roll it back if SCRIPT
2140 ** throws an exception. Or if no new transation was started, do nothing.
2141 ** pass the exception on up the stack.
2142 **
2143 ** This command was inspired by Dave Thomas's talk on Ruby at the
2144 ** 2005 O'Reilly Open Source Convention (OSCON).
2145 */
2146 case DB_TRANSACTION: {
2147 int inTrans;
2148 Tcl_Obj *pScript;
2149 const char *zBegin = "BEGIN";
2150 if( objc!=3 && objc!=4 ){
2151 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2152 return TCL_ERROR;
2153 }
2154 if( objc==3 ){
2155 pScript = objv[2];
2156 } else {
2157 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00002158 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00002159 };
2160 enum TTYPE_enum {
2161 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2162 };
2163 int ttype;
drhb5555e72005-08-02 17:15:14 +00002164 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00002165 0, &ttype) ){
2166 return TCL_ERROR;
2167 }
2168 switch( (enum TTYPE_enum)ttype ){
2169 case TTYPE_DEFERRED: /* no-op */; break;
2170 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
2171 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
2172 }
2173 pScript = objv[3];
2174 }
2175 inTrans = !sqlite3_get_autocommit(pDb->db);
2176 if( !inTrans ){
drh37527852006-03-16 16:19:56 +00002177 (void)sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
drh3d214232005-08-02 12:21:08 +00002178 }
2179 rc = Tcl_EvalObjEx(interp, pScript, 0);
2180 if( !inTrans ){
2181 const char *zEnd;
2182 if( rc==TCL_ERROR ){
2183 zEnd = "ROLLBACK";
2184 } else {
2185 zEnd = "COMMIT";
2186 }
drh37527852006-03-16 16:19:56 +00002187 (void)sqlite3_exec(pDb->db, zEnd, 0, 0, 0);
drh3d214232005-08-02 12:21:08 +00002188 }
2189 break;
2190 }
2191
danielk197794eb6a12005-12-15 15:22:08 +00002192 /*
2193 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00002194 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00002195 */
danielk197771fd80b2005-12-16 06:54:01 +00002196 case DB_UPDATE_HOOK:
2197 case DB_ROLLBACK_HOOK: {
2198
2199 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2200 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2201 */
2202 Tcl_Obj **ppHook;
2203 if( choice==DB_UPDATE_HOOK ){
2204 ppHook = &pDb->pUpdateHook;
2205 }else{
2206 ppHook = &pDb->pRollbackHook;
2207 }
2208
danielk197794eb6a12005-12-15 15:22:08 +00002209 if( objc!=2 && objc!=3 ){
2210 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2211 return TCL_ERROR;
2212 }
danielk197771fd80b2005-12-16 06:54:01 +00002213 if( *ppHook ){
2214 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002215 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002216 Tcl_DecrRefCount(*ppHook);
2217 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00002218 }
2219 }
2220 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00002221 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00002222 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00002223 *ppHook = objv[2];
2224 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00002225 }
2226 }
danielk197771fd80b2005-12-16 06:54:01 +00002227
2228 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2229 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
2230
danielk197794eb6a12005-12-15 15:22:08 +00002231 break;
2232 }
2233
danielk19774397de52005-01-12 12:44:03 +00002234 /* $db version
2235 **
2236 ** Return the version string for this database.
2237 */
2238 case DB_VERSION: {
2239 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2240 break;
2241 }
2242
tpoindex1067fe12004-12-17 15:41:11 +00002243
drh6d313162000-09-21 13:01:35 +00002244 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00002245 return rc;
drh75897232000-05-29 14:26:00 +00002246}
2247
2248/*
drh9bb575f2004-09-06 17:24:11 +00002249** sqlite3 DBNAME FILENAME ?MODE? ?-key KEY?
drh75897232000-05-29 14:26:00 +00002250**
2251** This is the main Tcl command. When the "sqlite" Tcl command is
2252** invoked, this routine runs to process that command.
2253**
2254** The first argument, DBNAME, is an arbitrary name for a new
2255** database connection. This command creates a new command named
2256** DBNAME that is used to control that connection. The database
2257** connection is deleted when the DBNAME command is deleted.
2258**
2259** The second argument is the name of the directory that contains
2260** the sqlite database that is to be accessed.
drhfbc3eab2001-04-06 16:13:42 +00002261**
2262** For testing purposes, we also support the following:
2263**
drh9bb575f2004-09-06 17:24:11 +00002264** sqlite3 -encoding
drhfbc3eab2001-04-06 16:13:42 +00002265**
2266** Return the encoding used by LIKE and GLOB operators. Choices
2267** are UTF-8 and iso8859.
2268**
drh9bb575f2004-09-06 17:24:11 +00002269** sqlite3 -version
drh647cb0e2002-11-04 19:32:25 +00002270**
2271** Return the version number of the SQLite library.
2272**
drh9bb575f2004-09-06 17:24:11 +00002273** sqlite3 -tcl-uses-utf
drhfbc3eab2001-04-06 16:13:42 +00002274**
2275** Return "1" if compiled with a Tcl uses UTF-8. Return "0" if
2276** not. Used by tests to make sure the library was compiled
2277** correctly.
drh75897232000-05-29 14:26:00 +00002278*/
drh22fbcb82004-02-01 01:22:50 +00002279static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002280 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002281 void *pKey = 0;
2282 int nKey = 0;
2283 const char *zArg;
drh75897232000-05-29 14:26:00 +00002284 char *zErrMsg;
drh22fbcb82004-02-01 01:22:50 +00002285 const char *zFile;
drh882e8e42006-08-24 02:42:27 +00002286 Tcl_DString translatedFilename;
drh22fbcb82004-02-01 01:22:50 +00002287 if( objc==2 ){
2288 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002289 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00002290 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00002291 return TCL_OK;
2292 }
drh9eb9e262004-02-11 02:18:05 +00002293 if( strcmp(zArg,"-has-codec")==0 ){
2294#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002295 Tcl_AppendResult(interp,"1",0);
2296#else
2297 Tcl_AppendResult(interp,"0",0);
2298#endif
2299 return TCL_OK;
2300 }
2301 if( strcmp(zArg,"-tcl-uses-utf")==0 ){
drhfbc3eab2001-04-06 16:13:42 +00002302#ifdef TCL_UTF_MAX
2303 Tcl_AppendResult(interp,"1",0);
2304#else
2305 Tcl_AppendResult(interp,"0",0);
2306#endif
2307 return TCL_OK;
2308 }
2309 }
drh22fbcb82004-02-01 01:22:50 +00002310 if( objc==5 || objc==6 ){
2311 zArg = Tcl_GetStringFromObj(objv[objc-2], 0);
2312 if( strcmp(zArg,"-key")==0 ){
2313 pKey = Tcl_GetByteArrayFromObj(objv[objc-1], &nKey);
2314 objc -= 2;
2315 }
2316 }
2317 if( objc!=3 && objc!=4 ){
2318 Tcl_WrongNumArgs(interp, 1, objv,
drh9eb9e262004-02-11 02:18:05 +00002319#ifdef SQLITE_HAS_CODEC
2320 "HANDLE FILENAME ?-key CODEC-KEY?"
drh22fbcb82004-02-01 01:22:50 +00002321#else
2322 "HANDLE FILENAME ?MODE?"
2323#endif
2324 );
drh75897232000-05-29 14:26:00 +00002325 return TCL_ERROR;
2326 }
drh75897232000-05-29 14:26:00 +00002327 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00002328 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00002329 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00002330 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
2331 return TCL_ERROR;
2332 }
2333 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00002334 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00002335 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
danielk19774f057f92004-06-08 00:02:33 +00002336 sqlite3_open(zFile, &p->db);
drh882e8e42006-08-24 02:42:27 +00002337 Tcl_DStringFree(&translatedFilename);
danielk197780290862004-05-22 09:21:21 +00002338 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
drh9404d502006-12-19 18:46:08 +00002339 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
danielk197780290862004-05-22 09:21:21 +00002340 sqlite3_close(p->db);
2341 p->db = 0;
2342 }
drh2011d5f2004-07-22 02:40:37 +00002343#ifdef SQLITE_HAS_CODEC
2344 sqlite3_key(p->db, pKey, nKey);
drheb8ed702004-02-11 10:37:23 +00002345#endif
drhbec3f402000-08-04 13:49:02 +00002346 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00002347 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00002348 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00002349 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00002350 return TCL_ERROR;
2351 }
drhfb7e7652005-01-24 00:28:42 +00002352 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00002353 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00002354 zArg = Tcl_GetStringFromObj(objv[1], 0);
2355 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
drhc22bd472002-05-10 13:14:07 +00002356
2357 /* If compiled with SQLITE_TEST turned on, then register the "md5sum"
drh06b27182002-06-26 20:06:05 +00002358 ** SQL function.
drhc22bd472002-05-10 13:14:07 +00002359 */
drh28b4e482002-03-11 02:06:13 +00002360#ifdef SQLITE_TEST
2361 {
drh9bb575f2004-09-06 17:24:11 +00002362 extern void Md5_Register(sqlite3*);
drh3b93bc82005-01-13 23:54:32 +00002363#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00002364 int mallocfail = sqlite3_iMallocFail;
2365 sqlite3_iMallocFail = 0;
danielk19775b59af82004-06-30 12:42:59 +00002366#endif
drhc22bd472002-05-10 13:14:07 +00002367 Md5_Register(p->db);
drh3b93bc82005-01-13 23:54:32 +00002368#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00002369 sqlite3_iMallocFail = mallocfail;
danielk19775b59af82004-06-30 12:42:59 +00002370#endif
danielk19777ddad962005-12-12 06:53:03 +00002371 }
drh28b4e482002-03-11 02:06:13 +00002372#endif
drh75897232000-05-29 14:26:00 +00002373 return TCL_OK;
2374}
2375
2376/*
drh90ca9752001-09-28 17:47:14 +00002377** Provide a dummy Tcl_InitStubs if we are using this as a static
2378** library.
2379*/
2380#ifndef USE_TCL_STUBS
2381# undef Tcl_InitStubs
2382# define Tcl_InitStubs(a,b,c)
2383#endif
2384
2385/*
drh29bc4612005-10-05 10:40:15 +00002386** Make sure we have a PACKAGE_VERSION macro defined. This will be
2387** defined automatically by the TEA makefile. But other makefiles
2388** do not define it.
2389*/
2390#ifndef PACKAGE_VERSION
2391# define PACKAGE_VERSION SQLITE_VERSION
2392#endif
2393
2394/*
drh75897232000-05-29 14:26:00 +00002395** Initialize this module.
2396**
2397** This Tcl module contains only a single new Tcl command named "sqlite".
2398** (Hence there is no namespace. There is no point in using a namespace
2399** if the extension only supplies one new name!) The "sqlite" command is
2400** used to open a new SQLite database. See the DbMain() routine above
2401** for additional information.
2402*/
drhad6e1372006-07-10 21:15:51 +00002403EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00002404 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00002405 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002406 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh49766d62005-01-08 18:42:28 +00002407 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002408 Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
drh90ca9752001-09-28 17:47:14 +00002409 return TCL_OK;
2410}
drhad6e1372006-07-10 21:15:51 +00002411EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2412EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2413EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002414
2415#ifndef SQLITE_3_SUFFIX_ONLY
drhad6e1372006-07-10 21:15:51 +00002416EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2417EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2418EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2419EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002420#endif
drh75897232000-05-29 14:26:00 +00002421
drh3e27c022004-07-23 00:01:38 +00002422#ifdef TCLSH
2423/*****************************************************************************
2424** The code that follows is used to build standalone TCL interpreters
drh75897232000-05-29 14:26:00 +00002425*/
drh348784e2000-05-29 20:41:49 +00002426
2427/*
drh3e27c022004-07-23 00:01:38 +00002428** If the macro TCLSH is one, then put in code this for the
2429** "main" routine that will initialize Tcl and take input from
2430** standard input.
drh348784e2000-05-29 20:41:49 +00002431*/
drh3e27c022004-07-23 00:01:38 +00002432#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00002433static char zMainloop[] =
2434 "set line {}\n"
2435 "while {![eof stdin]} {\n"
2436 "if {$line!=\"\"} {\n"
2437 "puts -nonewline \"> \"\n"
2438 "} else {\n"
2439 "puts -nonewline \"% \"\n"
2440 "}\n"
2441 "flush stdout\n"
2442 "append line [gets stdin]\n"
2443 "if {[info complete $line]} {\n"
2444 "if {[catch {uplevel #0 $line} result]} {\n"
2445 "puts stderr \"Error: $result\"\n"
2446 "} elseif {$result!=\"\"} {\n"
2447 "puts $result\n"
2448 "}\n"
2449 "set line {}\n"
2450 "} else {\n"
2451 "append line \\n\n"
2452 "}\n"
2453 "}\n"
2454;
drh3e27c022004-07-23 00:01:38 +00002455#endif
2456
2457/*
2458** If the macro TCLSH is two, then get the main loop code out of
2459** the separate file "spaceanal_tcl.h".
2460*/
2461#if TCLSH==2
2462static char zMainloop[] =
2463#include "spaceanal_tcl.h"
2464;
2465#endif
drh348784e2000-05-29 20:41:49 +00002466
2467#define TCLSH_MAIN main /* Needed to fake out mktclapp */
2468int TCLSH_MAIN(int argc, char **argv){
2469 Tcl_Interp *interp;
drh297ecf12001-04-05 15:57:13 +00002470 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00002471 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00002472 Sqlite3_Init(interp);
drhd9b02572001-04-15 00:37:09 +00002473#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00002474 {
2475 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00002476 extern int Sqlitetest2_Init(Tcl_Interp*);
2477 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00002478 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00002479 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00002480 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00002481 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00002482 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00002483 extern int Sqlitetest9_Init(Tcl_Interp*);
drhefc251d2001-07-01 22:12:01 +00002484 extern int Md5_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002485 extern int Sqlitetestsse_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00002486 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh4be8b512006-06-13 23:51:34 +00002487 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk1977954ce992006-06-15 15:59:19 +00002488 extern int Sqlitetestschema_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00002489 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
drh15926592007-04-06 15:02:13 +00002490 extern int Sqlitetest_hexio_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002491
danielk19776490beb2004-05-11 06:17:21 +00002492 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00002493 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00002494 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00002495 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00002496 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00002497 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00002498 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00002499 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00002500 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00002501 Sqlitetestasync_Init(interp);
drh4be8b512006-06-13 23:51:34 +00002502 Sqlitetesttclvar_Init(interp);
danielk1977954ce992006-06-15 15:59:19 +00002503 Sqlitetestschema_Init(interp);
drh1409be62006-08-23 20:07:20 +00002504 Sqlitetest_autoext_Init(interp);
drh15926592007-04-06 15:02:13 +00002505 Sqlitetest_hexio_Init(interp);
drhefc251d2001-07-01 22:12:01 +00002506 Md5_Init(interp);
drh89dec812005-04-28 19:03:37 +00002507#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00002508 Sqlitetestsse_Init(interp);
2509#endif
drhd1bf3512001-04-07 15:24:33 +00002510 }
2511#endif
drh3e27c022004-07-23 00:01:38 +00002512 if( argc>=2 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002513 int i;
shessad42c3a2006-08-22 23:53:46 +00002514 char zArgc[32];
2515 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
2516 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00002517 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
2518 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00002519 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00002520 Tcl_SetVar(interp, "argv", argv[i],
2521 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
2522 }
drh3e27c022004-07-23 00:01:38 +00002523 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00002524 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drhc61053b2000-06-04 12:58:36 +00002525 if( zInfo==0 ) zInfo = interp->result;
2526 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00002527 return 1;
2528 }
drh3e27c022004-07-23 00:01:38 +00002529 }
2530 if( argc<=1 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002531 Tcl_GlobalEval(interp, zMainloop);
2532 }
2533 return 0;
2534}
2535#endif /* TCLSH */