blob: f780d9fac0836597dc351218ccb5871f94a28948 [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*************************************************************************
12** A TCL Interface to SQLite
13**
drhad6e1372006-07-10 21:15:51 +000014** $Id: tclsqlite.c,v 1.163 2006/07/10 21:15:52 drh Exp $
drh75897232000-05-29 14:26:00 +000015*/
drh6d313162000-09-21 13:01:35 +000016#ifndef NO_TCL /* Omit this whole file if TCL is unavailable */
17
drh06b27182002-06-26 20:06:05 +000018#include "sqliteInt.h"
drh895d7472004-08-20 16:02:39 +000019#include "hash.h"
drh17a68932001-01-31 13:28:08 +000020#include "tcl.h"
drh75897232000-05-29 14:26:00 +000021#include <stdlib.h>
22#include <string.h>
drhce927062001-11-09 13:41:09 +000023#include <assert.h>
drhd1e47332005-06-26 17:55:33 +000024#include <ctype.h>
drh75897232000-05-29 14:26:00 +000025
drhad6e1372006-07-10 21:15:51 +000026/*
27 * Windows needs to know which symbols to export. Unix does not.
28 * BUILD_sqlite should be undefined for Unix.
29 */
30#ifdef BUILD_sqlite
31#undef TCL_STORAGE_CLASS
32#define TCL_STORAGE_CLASS DLLEXPORT
33#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000034
danielk1977a21c6b62005-01-24 10:25:59 +000035#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000036#define MAX_PREPARED_STMTS 100
37
drh75897232000-05-29 14:26:00 +000038/*
drh98808ba2001-10-18 12:34:46 +000039** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
40** have to do a translation when going between the two. Set the
41** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
42** this translation.
43*/
44#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
45# define UTF_TRANSLATION_NEEDED 1
46#endif
47
48/*
drhcabb0812002-09-14 13:47:32 +000049** New SQL functions can be created as TCL scripts. Each such function
50** is described by an instance of the following structure.
51*/
52typedef struct SqlFunc SqlFunc;
53struct SqlFunc {
54 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000055 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
56 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
57 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000058 SqlFunc *pNext; /* Next function on the list of them all */
59};
60
61/*
danielk19770202b292004-06-09 09:55:16 +000062** New collation sequences function can be created as TCL scripts. Each such
63** function is described by an instance of the following structure.
64*/
65typedef struct SqlCollate SqlCollate;
66struct SqlCollate {
67 Tcl_Interp *interp; /* The TCL interpret to execute the function */
68 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000069 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000070};
71
72/*
drhfb7e7652005-01-24 00:28:42 +000073** Prepared statements are cached for faster execution. Each prepared
74** statement is described by an instance of the following structure.
75*/
76typedef struct SqlPreparedStmt SqlPreparedStmt;
77struct SqlPreparedStmt {
78 SqlPreparedStmt *pNext; /* Next in linked list */
79 SqlPreparedStmt *pPrev; /* Previous on the list */
80 sqlite3_stmt *pStmt; /* The prepared statement */
81 int nSql; /* chars in zSql[] */
82 char zSql[1]; /* Text of the SQL statement */
83};
84
85/*
drhbec3f402000-08-04 13:49:02 +000086** There is one instance of this structure for each SQLite database
87** that has been opened by the SQLite TCL interface.
88*/
89typedef struct SqliteDb SqliteDb;
90struct SqliteDb {
drhdddca282006-01-03 00:33:50 +000091 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +000092 Tcl_Interp *interp; /* The interpreter used for this database */
93 char *zBusy; /* The busy callback routine */
94 char *zCommit; /* The commit hook callback routine */
95 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +000096 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +000097 char *zProgress; /* The progress callback routine */
98 char *zAuth; /* The authorization callback routine */
99 char *zNull; /* Text to substitute for an SQL NULL value */
100 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000101 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000102 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drhd1e47332005-06-26 17:55:33 +0000103 SqlCollate *pCollate; /* List of SQL collation functions */
104 int rc; /* Return code of most recent sqlite3_exec() */
105 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000106 SqlPreparedStmt *stmtList; /* List of prepared statements*/
107 SqlPreparedStmt *stmtLast; /* Last statement in the list */
108 int maxStmt; /* The next maximum number of stmtList */
109 int nStmt; /* Number of statements in stmtList */
drh98808ba2001-10-18 12:34:46 +0000110};
drh297ecf12001-04-05 15:57:13 +0000111
drh6d313162000-09-21 13:01:35 +0000112/*
drhd1e47332005-06-26 17:55:33 +0000113** Look at the script prefix in pCmd. We will be executing this script
114** after first appending one or more arguments. This routine analyzes
115** the script to see if it is safe to use Tcl_EvalObjv() on the script
116** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
117** faster.
118**
119** Scripts that are safe to use with Tcl_EvalObjv() consists of a
120** command name followed by zero or more arguments with no [...] or $
121** or {...} or ; to be seen anywhere. Most callback scripts consist
122** of just a single procedure name and they meet this requirement.
123*/
124static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
125 /* We could try to do something with Tcl_Parse(). But we will instead
126 ** just do a search for forbidden characters. If any of the forbidden
127 ** characters appear in pCmd, we will report the string as unsafe.
128 */
129 const char *z;
130 int n;
131 z = Tcl_GetStringFromObj(pCmd, &n);
132 while( n-- > 0 ){
133 int c = *(z++);
134 if( c=='$' || c=='[' || c==';' ) return 0;
135 }
136 return 1;
137}
138
139/*
140** Find an SqlFunc structure with the given name. Or create a new
141** one if an existing one cannot be found. Return a pointer to the
142** structure.
143*/
144static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
145 SqlFunc *p, *pNew;
146 int i;
147 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen(zName) + 1 );
148 pNew->zName = (char*)&pNew[1];
149 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
150 pNew->zName[i] = 0;
151 for(p=pDb->pFunc; p; p=p->pNext){
152 if( strcmp(p->zName, pNew->zName)==0 ){
153 Tcl_Free((char*)pNew);
154 return p;
155 }
156 }
157 pNew->interp = pDb->interp;
158 pNew->pScript = 0;
159 pNew->pNext = pDb->pFunc;
160 pDb->pFunc = pNew;
161 return pNew;
162}
163
164/*
drhfb7e7652005-01-24 00:28:42 +0000165** Finalize and free a list of prepared statements
166*/
167static void flushStmtCache( SqliteDb *pDb ){
168 SqlPreparedStmt *pPreStmt;
169
170 while( pDb->stmtList ){
171 sqlite3_finalize( pDb->stmtList->pStmt );
172 pPreStmt = pDb->stmtList;
173 pDb->stmtList = pDb->stmtList->pNext;
174 Tcl_Free( (char*)pPreStmt );
175 }
176 pDb->nStmt = 0;
177 pDb->stmtLast = 0;
178}
179
180/*
drh895d7472004-08-20 16:02:39 +0000181** TCL calls this procedure when an sqlite3 database command is
182** deleted.
drh75897232000-05-29 14:26:00 +0000183*/
184static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000185 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000186 flushStmtCache(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000187 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000188 while( pDb->pFunc ){
189 SqlFunc *pFunc = pDb->pFunc;
190 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000191 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000192 Tcl_Free((char*)pFunc);
193 }
danielk19770202b292004-06-09 09:55:16 +0000194 while( pDb->pCollate ){
195 SqlCollate *pCollate = pDb->pCollate;
196 pDb->pCollate = pCollate->pNext;
197 Tcl_Free((char*)pCollate);
198 }
drhbec3f402000-08-04 13:49:02 +0000199 if( pDb->zBusy ){
200 Tcl_Free(pDb->zBusy);
201 }
drhb5a20d32003-04-23 12:25:23 +0000202 if( pDb->zTrace ){
203 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000204 }
drh19e2d372005-08-29 23:00:03 +0000205 if( pDb->zProfile ){
206 Tcl_Free(pDb->zProfile);
207 }
drhe22a3342003-04-22 20:30:37 +0000208 if( pDb->zAuth ){
209 Tcl_Free(pDb->zAuth);
210 }
danielk197755c45f22005-04-03 23:54:43 +0000211 if( pDb->zNull ){
212 Tcl_Free(pDb->zNull);
213 }
danielk197794eb6a12005-12-15 15:22:08 +0000214 if( pDb->pUpdateHook ){
215 Tcl_DecrRefCount(pDb->pUpdateHook);
216 }
danielk197771fd80b2005-12-16 06:54:01 +0000217 if( pDb->pRollbackHook ){
218 Tcl_DecrRefCount(pDb->pRollbackHook);
219 }
danielk197794eb6a12005-12-15 15:22:08 +0000220 if( pDb->pCollateNeeded ){
221 Tcl_DecrRefCount(pDb->pCollateNeeded);
222 }
drhbec3f402000-08-04 13:49:02 +0000223 Tcl_Free((char*)pDb);
224}
225
226/*
227** This routine is called when a database file is locked while trying
228** to execute SQL.
229*/
danielk19772a764eb2004-06-12 01:43:26 +0000230static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000231 SqliteDb *pDb = (SqliteDb*)cd;
232 int rc;
233 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000234
danielk19772a764eb2004-06-12 01:43:26 +0000235 sprintf(zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000236 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000237 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
238 return 0;
239 }
240 return 1;
drh75897232000-05-29 14:26:00 +0000241}
242
243/*
danielk1977348bb5d2003-10-18 09:37:26 +0000244** This routine is invoked as the 'progress callback' for the database.
245*/
246static int DbProgressHandler(void *cd){
247 SqliteDb *pDb = (SqliteDb*)cd;
248 int rc;
249
250 assert( pDb->zProgress );
251 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
252 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
253 return 1;
254 }
255 return 0;
256}
257
drhd1167392006-01-23 13:00:35 +0000258#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000259/*
drhb5a20d32003-04-23 12:25:23 +0000260** This routine is called by the SQLite trace handler whenever a new
261** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000262*/
drhb5a20d32003-04-23 12:25:23 +0000263static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000264 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000265 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000266
drhb5a20d32003-04-23 12:25:23 +0000267 Tcl_DStringInit(&str);
268 Tcl_DStringAppend(&str, pDb->zTrace, -1);
269 Tcl_DStringAppendElement(&str, zSql);
270 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
271 Tcl_DStringFree(&str);
272 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000273}
drhd1167392006-01-23 13:00:35 +0000274#endif
drh0d1a6432003-04-03 15:46:04 +0000275
drhd1167392006-01-23 13:00:35 +0000276#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000277/*
drh19e2d372005-08-29 23:00:03 +0000278** This routine is called by the SQLite profile handler after a statement
279** SQL has executed. The TCL script in pDb->zProfile is evaluated.
280*/
281static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
282 SqliteDb *pDb = (SqliteDb*)cd;
283 Tcl_DString str;
284 char zTm[100];
285
286 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
287 Tcl_DStringInit(&str);
288 Tcl_DStringAppend(&str, pDb->zProfile, -1);
289 Tcl_DStringAppendElement(&str, zSql);
290 Tcl_DStringAppendElement(&str, zTm);
291 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
292 Tcl_DStringFree(&str);
293 Tcl_ResetResult(pDb->interp);
294}
drhd1167392006-01-23 13:00:35 +0000295#endif
drh19e2d372005-08-29 23:00:03 +0000296
297/*
drhaa940ea2004-01-15 02:44:03 +0000298** This routine is called when a transaction is committed. The
299** TCL script in pDb->zCommit is executed. If it returns non-zero or
300** if it throws an exception, the transaction is rolled back instead
301** of being committed.
302*/
303static int DbCommitHandler(void *cd){
304 SqliteDb *pDb = (SqliteDb*)cd;
305 int rc;
306
307 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
308 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
309 return 1;
310 }
311 return 0;
312}
313
danielk197771fd80b2005-12-16 06:54:01 +0000314static void DbRollbackHandler(void *clientData){
315 SqliteDb *pDb = (SqliteDb*)clientData;
316 assert(pDb->pRollbackHook);
317 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
318 Tcl_BackgroundError(pDb->interp);
319 }
320}
321
danielk197794eb6a12005-12-15 15:22:08 +0000322static void DbUpdateHandler(
323 void *p,
324 int op,
325 const char *zDb,
326 const char *zTbl,
327 sqlite_int64 rowid
328){
329 SqliteDb *pDb = (SqliteDb *)p;
330 Tcl_Obj *pCmd;
331
332 assert( pDb->pUpdateHook );
333 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
334
335 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
336 Tcl_IncrRefCount(pCmd);
337 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
338 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
339 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
340 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
341 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
342 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
343}
344
danielk19777cedc8d2004-06-10 10:50:08 +0000345static void tclCollateNeeded(
346 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000347 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000348 int enc,
349 const char *zName
350){
351 SqliteDb *pDb = (SqliteDb *)pCtx;
352 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
353 Tcl_IncrRefCount(pScript);
354 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
355 Tcl_EvalObjEx(pDb->interp, pScript, 0);
356 Tcl_DecrRefCount(pScript);
357}
358
drhaa940ea2004-01-15 02:44:03 +0000359/*
danielk19770202b292004-06-09 09:55:16 +0000360** This routine is called to evaluate an SQL collation function implemented
361** using TCL script.
362*/
363static int tclSqlCollate(
364 void *pCtx,
365 int nA,
366 const void *zA,
367 int nB,
368 const void *zB
369){
370 SqlCollate *p = (SqlCollate *)pCtx;
371 Tcl_Obj *pCmd;
372
373 pCmd = Tcl_NewStringObj(p->zScript, -1);
374 Tcl_IncrRefCount(pCmd);
375 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
376 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000377 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000378 Tcl_DecrRefCount(pCmd);
379 return (atoi(Tcl_GetStringResult(p->interp)));
380}
381
382/*
drhcabb0812002-09-14 13:47:32 +0000383** This routine is called to evaluate an SQL function implemented
384** using TCL script.
385*/
drhfb7e7652005-01-24 00:28:42 +0000386static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000387 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000388 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000389 int i;
390 int rc;
391
drhd1e47332005-06-26 17:55:33 +0000392 if( argc==0 ){
393 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
394 ** script object directly. This allows the TCL compiler to generate
395 ** bytecode for the command on the first invocation and thus make
396 ** subsequent invocations much faster. */
397 pCmd = p->pScript;
398 Tcl_IncrRefCount(pCmd);
399 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
400 Tcl_DecrRefCount(pCmd);
401 }else{
402 /* If there are arguments to the function, make a shallow copy of the
403 ** script object, lappend the arguments, then evaluate the copy.
404 **
405 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
406 ** The new Tcl_Obj contains pointers to the original list elements.
407 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
408 ** of the list to tclCmdNameType, that alternate representation will
409 ** be preserved and reused on the next invocation.
410 */
411 Tcl_Obj **aArg;
412 int nArg;
413 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
414 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
415 return;
416 }
417 pCmd = Tcl_NewListObj(nArg, aArg);
418 Tcl_IncrRefCount(pCmd);
419 for(i=0; i<argc; i++){
420 sqlite3_value *pIn = argv[i];
421 Tcl_Obj *pVal;
422
423 /* Set pVal to contain the i'th column of this row. */
424 switch( sqlite3_value_type(pIn) ){
425 case SQLITE_BLOB: {
426 int bytes = sqlite3_value_bytes(pIn);
427 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
428 break;
429 }
430 case SQLITE_INTEGER: {
431 sqlite_int64 v = sqlite3_value_int64(pIn);
432 if( v>=-2147483647 && v<=2147483647 ){
433 pVal = Tcl_NewIntObj(v);
434 }else{
435 pVal = Tcl_NewWideIntObj(v);
436 }
437 break;
438 }
439 case SQLITE_FLOAT: {
440 double r = sqlite3_value_double(pIn);
441 pVal = Tcl_NewDoubleObj(r);
442 break;
443 }
444 case SQLITE_NULL: {
445 pVal = Tcl_NewStringObj("", 0);
446 break;
447 }
448 default: {
449 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000450 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000451 break;
452 }
453 }
454 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
455 if( rc ){
456 Tcl_DecrRefCount(pCmd);
457 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
458 return;
459 }
danielk197751ad0ec2004-05-24 12:39:02 +0000460 }
drhd1e47332005-06-26 17:55:33 +0000461 if( !p->useEvalObjv ){
462 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
463 ** is a list without a string representation. To prevent this from
464 ** happening, make sure pCmd has a valid string representation */
465 Tcl_GetString(pCmd);
466 }
467 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
468 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000469 }
danielk1977562e8d32005-05-20 09:40:55 +0000470
drhc7f269d2005-05-05 10:30:29 +0000471 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000472 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000473 }else{
drhc7f269d2005-05-05 10:30:29 +0000474 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
475 int n;
476 u8 *data;
477 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
478 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000479 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000480 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000481 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000482 data = Tcl_GetByteArrayFromObj(pVar, &n);
483 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000484 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
485 (c=='i' && strcmp(zType,"int")==0) ){
486 Tcl_GetIntFromObj(0, pVar, &n);
487 sqlite3_result_int(context, n);
488 }else if( c=='d' && strcmp(zType,"double")==0 ){
489 double r;
490 Tcl_GetDoubleFromObj(0, pVar, &r);
491 sqlite3_result_double(context, r);
drhdf0bdda2005-06-25 19:31:48 +0000492 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
493 Tcl_WideInt v;
494 Tcl_GetWideIntFromObj(0, pVar, &v);
495 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000496 }else{
danielk197700fd9572005-12-07 06:27:43 +0000497 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
498 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000499 }
drhcabb0812002-09-14 13:47:32 +0000500 }
501}
drh895d7472004-08-20 16:02:39 +0000502
drhe22a3342003-04-22 20:30:37 +0000503#ifndef SQLITE_OMIT_AUTHORIZATION
504/*
505** This is the authentication function. It appends the authentication
506** type code and the two arguments to zCmd[] then invokes the result
507** on the interpreter. The reply is examined to determine if the
508** authentication fails or succeeds.
509*/
510static int auth_callback(
511 void *pArg,
512 int code,
513 const char *zArg1,
514 const char *zArg2,
515 const char *zArg3,
516 const char *zArg4
517){
518 char *zCode;
519 Tcl_DString str;
520 int rc;
521 const char *zReply;
522 SqliteDb *pDb = (SqliteDb*)pArg;
523
524 switch( code ){
525 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
526 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
527 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
528 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
529 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
530 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
531 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
532 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
533 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
534 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
535 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
536 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
537 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
538 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
539 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
540 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
541 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
542 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
543 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
544 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
545 case SQLITE_READ : zCode="SQLITE_READ"; break;
546 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
547 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
548 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000549 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
550 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000551 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000552 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000553 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000554 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
555 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drhe22a3342003-04-22 20:30:37 +0000556 default : zCode="????"; break;
557 }
558 Tcl_DStringInit(&str);
559 Tcl_DStringAppend(&str, pDb->zAuth, -1);
560 Tcl_DStringAppendElement(&str, zCode);
561 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
562 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
563 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
564 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
565 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
566 Tcl_DStringFree(&str);
567 zReply = Tcl_GetStringResult(pDb->interp);
568 if( strcmp(zReply,"SQLITE_OK")==0 ){
569 rc = SQLITE_OK;
570 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
571 rc = SQLITE_DENY;
572 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
573 rc = SQLITE_IGNORE;
574 }else{
575 rc = 999;
576 }
577 return rc;
578}
579#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000580
581/*
danielk1977ef2cb632004-05-29 02:37:19 +0000582** zText is a pointer to text obtained via an sqlite3_result_text()
583** or similar interface. This routine returns a Tcl string object,
584** reference count set to 0, containing the text. If a translation
585** between iso8859 and UTF-8 is required, it is preformed.
586*/
587static Tcl_Obj *dbTextToObj(char const *zText){
588 Tcl_Obj *pVal;
589#ifdef UTF_TRANSLATION_NEEDED
590 Tcl_DString dCol;
591 Tcl_DStringInit(&dCol);
592 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
593 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
594 Tcl_DStringFree(&dCol);
595#else
596 pVal = Tcl_NewStringObj(zText, -1);
597#endif
598 return pVal;
599}
600
601/*
tpoindex1067fe12004-12-17 15:41:11 +0000602** This routine reads a line of text from FILE in, stores
603** the text in memory obtained from malloc() and returns a pointer
604** to the text. NULL is returned at end of file, or if malloc()
605** fails.
606**
607** The interface is like "readline" but no command-line editing
608** is done.
609**
610** copied from shell.c from '.import' command
611*/
612static char *local_getline(char *zPrompt, FILE *in){
613 char *zLine;
614 int nLine;
615 int n;
616 int eol;
617
618 nLine = 100;
619 zLine = malloc( nLine );
620 if( zLine==0 ) return 0;
621 n = 0;
622 eol = 0;
623 while( !eol ){
624 if( n+100>nLine ){
625 nLine = nLine*2 + 100;
626 zLine = realloc(zLine, nLine);
627 if( zLine==0 ) return 0;
628 }
629 if( fgets(&zLine[n], nLine - n, in)==0 ){
630 if( n==0 ){
631 free(zLine);
632 return 0;
633 }
634 zLine[n] = 0;
635 eol = 1;
636 break;
637 }
638 while( zLine[n] ){ n++; }
639 if( n>0 && zLine[n-1]=='\n' ){
640 n--;
641 zLine[n] = 0;
642 eol = 1;
643 }
644 }
645 zLine = realloc( zLine, n+1 );
646 return zLine;
647}
648
649/*
drh75897232000-05-29 14:26:00 +0000650** The "sqlite" command below creates a new Tcl command for each
651** connection it opens to an SQLite database. This routine is invoked
652** whenever one of those connection-specific commands is executed
653** in Tcl. For example, if you run Tcl code like this:
654**
drh9bb575f2004-09-06 17:24:11 +0000655** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +0000656** db1 close
657**
658** The first command opens a connection to the "my_database" database
659** and calls that connection "db1". The second command causes this
660** subroutine to be invoked.
661*/
drh6d313162000-09-21 13:01:35 +0000662static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +0000663 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +0000664 int choice;
drh22fbcb82004-02-01 01:22:50 +0000665 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +0000666 static const char *DB_strs[] = {
drhfb7e7652005-01-24 00:28:42 +0000667 "authorizer", "busy", "cache",
668 "changes", "close", "collate",
669 "collation_needed", "commit_hook", "complete",
drh41449052006-07-06 17:08:48 +0000670 "copy", "enable_load_extension","errorcode",
671 "eval", "exists", "function",
672 "last_insert_rowid", "nullvalue", "onecolumn",
673 "profile", "progress", "rekey",
674 "rollback_hook", "timeout", "total_changes",
675 "trace", "transaction", "update_hook",
676 "version", 0
drh6d313162000-09-21 13:01:35 +0000677 };
drh411995d2002-06-25 19:31:18 +0000678 enum DB_enum {
drhfb7e7652005-01-24 00:28:42 +0000679 DB_AUTHORIZER, DB_BUSY, DB_CACHE,
680 DB_CHANGES, DB_CLOSE, DB_COLLATE,
681 DB_COLLATION_NEEDED, DB_COMMIT_HOOK, DB_COMPLETE,
drh41449052006-07-06 17:08:48 +0000682 DB_COPY, DB_ENABLE_LOAD_EXTENSION,DB_ERRORCODE,
683 DB_EVAL, DB_EXISTS, DB_FUNCTION,
684 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
685 DB_PROFILE, DB_PROGRESS, DB_REKEY,
686 DB_ROLLBACK_HOOK, DB_TIMEOUT, DB_TOTAL_CHANGES,
687 DB_TRACE, DB_TRANSACTION, DB_UPDATE_HOOK,
688 DB_VERSION,
drh6d313162000-09-21 13:01:35 +0000689 };
tpoindex1067fe12004-12-17 15:41:11 +0000690 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +0000691
692 if( objc<2 ){
693 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +0000694 return TCL_ERROR;
695 }
drh411995d2002-06-25 19:31:18 +0000696 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +0000697 return TCL_ERROR;
698 }
699
drh411995d2002-06-25 19:31:18 +0000700 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +0000701
drhe22a3342003-04-22 20:30:37 +0000702 /* $db authorizer ?CALLBACK?
703 **
704 ** Invoke the given callback to authorize each SQL operation as it is
705 ** compiled. 5 arguments are appended to the callback before it is
706 ** invoked:
707 **
708 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
709 ** (2) First descriptive name (depends on authorization type)
710 ** (3) Second descriptive name
711 ** (4) Name of the database (ex: "main", "temp")
712 ** (5) Name of trigger that is doing the access
713 **
714 ** The callback should return on of the following strings: SQLITE_OK,
715 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
716 **
717 ** If this method is invoked with no arguments, the current authorization
718 ** callback string is returned.
719 */
720 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +0000721#ifdef SQLITE_OMIT_AUTHORIZATION
722 Tcl_AppendResult(interp, "authorization not available in this build", 0);
723 return TCL_ERROR;
724#else
drhe22a3342003-04-22 20:30:37 +0000725 if( objc>3 ){
726 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +0000727 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +0000728 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +0000729 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +0000730 Tcl_AppendResult(interp, pDb->zAuth, 0);
731 }
732 }else{
733 char *zAuth;
734 int len;
735 if( pDb->zAuth ){
736 Tcl_Free(pDb->zAuth);
737 }
738 zAuth = Tcl_GetStringFromObj(objv[2], &len);
739 if( zAuth && len>0 ){
740 pDb->zAuth = Tcl_Alloc( len + 1 );
741 strcpy(pDb->zAuth, zAuth);
742 }else{
743 pDb->zAuth = 0;
744 }
drhe22a3342003-04-22 20:30:37 +0000745 if( pDb->zAuth ){
746 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000747 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +0000748 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000749 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +0000750 }
drhe22a3342003-04-22 20:30:37 +0000751 }
drh1211de32004-07-26 12:24:22 +0000752#endif
drhe22a3342003-04-22 20:30:37 +0000753 break;
754 }
755
drhbec3f402000-08-04 13:49:02 +0000756 /* $db busy ?CALLBACK?
757 **
758 ** Invoke the given callback if an SQL statement attempts to open
759 ** a locked database file.
760 */
drh6d313162000-09-21 13:01:35 +0000761 case DB_BUSY: {
762 if( objc>3 ){
763 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +0000764 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +0000765 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +0000766 if( pDb->zBusy ){
767 Tcl_AppendResult(interp, pDb->zBusy, 0);
768 }
769 }else{
drh6d313162000-09-21 13:01:35 +0000770 char *zBusy;
771 int len;
drhbec3f402000-08-04 13:49:02 +0000772 if( pDb->zBusy ){
773 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +0000774 }
drh6d313162000-09-21 13:01:35 +0000775 zBusy = Tcl_GetStringFromObj(objv[2], &len);
776 if( zBusy && len>0 ){
777 pDb->zBusy = Tcl_Alloc( len + 1 );
778 strcpy(pDb->zBusy, zBusy);
779 }else{
780 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +0000781 }
782 if( pDb->zBusy ){
783 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000784 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +0000785 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000786 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +0000787 }
788 }
drh6d313162000-09-21 13:01:35 +0000789 break;
790 }
drhbec3f402000-08-04 13:49:02 +0000791
drhfb7e7652005-01-24 00:28:42 +0000792 /* $db cache flush
793 ** $db cache size n
794 **
795 ** Flush the prepared statement cache, or set the maximum number of
796 ** cached statements.
797 */
798 case DB_CACHE: {
799 char *subCmd;
800 int n;
801
802 if( objc<=2 ){
803 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
804 return TCL_ERROR;
805 }
806 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
807 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
808 if( objc!=3 ){
809 Tcl_WrongNumArgs(interp, 2, objv, "flush");
810 return TCL_ERROR;
811 }else{
812 flushStmtCache( pDb );
813 }
814 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
815 if( objc!=4 ){
816 Tcl_WrongNumArgs(interp, 2, objv, "size n");
817 return TCL_ERROR;
818 }else{
819 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
820 Tcl_AppendResult( interp, "cannot convert \"",
821 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
822 return TCL_ERROR;
823 }else{
824 if( n<0 ){
825 flushStmtCache( pDb );
826 n = 0;
827 }else if( n>MAX_PREPARED_STMTS ){
828 n = MAX_PREPARED_STMTS;
829 }
830 pDb->maxStmt = n;
831 }
832 }
833 }else{
834 Tcl_AppendResult( interp, "bad option \"",
835 Tcl_GetStringFromObj(objv[0],0), "\": must be flush or size", 0);
836 return TCL_ERROR;
837 }
838 break;
839 }
840
danielk1977b28af712004-06-21 06:50:26 +0000841 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +0000842 **
843 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +0000844 ** the most recent INSERT, UPDATE or DELETE statement, not including
845 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +0000846 */
847 case DB_CHANGES: {
848 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +0000849 if( objc!=2 ){
850 Tcl_WrongNumArgs(interp, 2, objv, "");
851 return TCL_ERROR;
852 }
drhc8d30ac2002-04-12 10:08:59 +0000853 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +0000854 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +0000855 break;
856 }
857
drh75897232000-05-29 14:26:00 +0000858 /* $db close
859 **
860 ** Shutdown the database
861 */
drh6d313162000-09-21 13:01:35 +0000862 case DB_CLOSE: {
863 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
864 break;
865 }
drh75897232000-05-29 14:26:00 +0000866
drh0f14e2e2004-06-29 12:39:08 +0000867 /*
868 ** $db collate NAME SCRIPT
869 **
870 ** Create a new SQL collation function called NAME. Whenever
871 ** that function is called, invoke SCRIPT to evaluate the function.
872 */
873 case DB_COLLATE: {
874 SqlCollate *pCollate;
875 char *zName;
876 char *zScript;
877 int nScript;
878 if( objc!=4 ){
879 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
880 return TCL_ERROR;
881 }
882 zName = Tcl_GetStringFromObj(objv[2], 0);
883 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
884 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
885 if( pCollate==0 ) return TCL_ERROR;
886 pCollate->interp = interp;
887 pCollate->pNext = pDb->pCollate;
888 pCollate->zScript = (char*)&pCollate[1];
889 pDb->pCollate = pCollate;
890 strcpy(pCollate->zScript, zScript);
891 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
892 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +0000893 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +0000894 return TCL_ERROR;
895 }
896 break;
897 }
898
899 /*
900 ** $db collation_needed SCRIPT
901 **
902 ** Create a new SQL collation function called NAME. Whenever
903 ** that function is called, invoke SCRIPT to evaluate the function.
904 */
905 case DB_COLLATION_NEEDED: {
906 if( objc!=3 ){
907 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
908 return TCL_ERROR;
909 }
910 if( pDb->pCollateNeeded ){
911 Tcl_DecrRefCount(pDb->pCollateNeeded);
912 }
913 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
914 Tcl_IncrRefCount(pDb->pCollateNeeded);
915 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
916 break;
917 }
918
drh19e2d372005-08-29 23:00:03 +0000919 /* $db commit_hook ?CALLBACK?
920 **
921 ** Invoke the given callback just before committing every SQL transaction.
922 ** If the callback throws an exception or returns non-zero, then the
923 ** transaction is aborted. If CALLBACK is an empty string, the callback
924 ** is disabled.
925 */
926 case DB_COMMIT_HOOK: {
927 if( objc>3 ){
928 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
929 return TCL_ERROR;
930 }else if( objc==2 ){
931 if( pDb->zCommit ){
932 Tcl_AppendResult(interp, pDb->zCommit, 0);
933 }
934 }else{
935 char *zCommit;
936 int len;
937 if( pDb->zCommit ){
938 Tcl_Free(pDb->zCommit);
939 }
940 zCommit = Tcl_GetStringFromObj(objv[2], &len);
941 if( zCommit && len>0 ){
942 pDb->zCommit = Tcl_Alloc( len + 1 );
943 strcpy(pDb->zCommit, zCommit);
944 }else{
945 pDb->zCommit = 0;
946 }
947 if( pDb->zCommit ){
948 pDb->interp = interp;
949 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
950 }else{
951 sqlite3_commit_hook(pDb->db, 0, 0);
952 }
953 }
954 break;
955 }
956
drh75897232000-05-29 14:26:00 +0000957 /* $db complete SQL
958 **
959 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
960 ** additional lines of input are needed. This is similar to the
961 ** built-in "info complete" command of Tcl.
962 */
drh6d313162000-09-21 13:01:35 +0000963 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +0000964#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +0000965 Tcl_Obj *pResult;
966 int isComplete;
967 if( objc!=3 ){
968 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +0000969 return TCL_ERROR;
970 }
danielk19776f8a5032004-05-10 10:34:51 +0000971 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +0000972 pResult = Tcl_GetObjResult(interp);
973 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +0000974#endif
drh6d313162000-09-21 13:01:35 +0000975 break;
976 }
drhdcd997e2003-01-31 17:21:49 +0000977
drh19e2d372005-08-29 23:00:03 +0000978 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
979 **
980 ** Copy data into table from filename, optionally using SEPARATOR
981 ** as column separators. If a column contains a null string, or the
982 ** value of NULLINDICATOR, a NULL is inserted for the column.
983 ** conflict-algorithm is one of the sqlite conflict algorithms:
984 ** rollback, abort, fail, ignore, replace
985 ** On success, return the number of lines processed, not necessarily same
986 ** as 'db changes' due to conflict-algorithm selected.
987 **
988 ** This code is basically an implementation/enhancement of
989 ** the sqlite3 shell.c ".import" command.
990 **
991 ** This command usage is equivalent to the sqlite2.x COPY statement,
992 ** which imports file data into a table using the PostgreSQL COPY file format:
993 ** $db copy $conflit_algo $table_name $filename \t \\N
994 */
995 case DB_COPY: {
996 char *zTable; /* Insert data into this table */
997 char *zFile; /* The file from which to extract data */
998 char *zConflict; /* The conflict algorithm to use */
999 sqlite3_stmt *pStmt; /* A statement */
1000 int rc; /* Result code */
1001 int nCol; /* Number of columns in the table */
1002 int nByte; /* Number of bytes in an SQL string */
1003 int i, j; /* Loop counters */
1004 int nSep; /* Number of bytes in zSep[] */
1005 int nNull; /* Number of bytes in zNull[] */
1006 char *zSql; /* An SQL statement */
1007 char *zLine; /* A single line of input from the file */
1008 char **azCol; /* zLine[] broken up into columns */
1009 char *zCommit; /* How to commit changes */
1010 FILE *in; /* The input file */
1011 int lineno = 0; /* Line number of input file */
1012 char zLineNum[80]; /* Line number print buffer */
1013 Tcl_Obj *pResult; /* interp result */
1014
1015 char *zSep;
1016 char *zNull;
1017 if( objc<5 || objc>7 ){
1018 Tcl_WrongNumArgs(interp, 2, objv,
1019 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1020 return TCL_ERROR;
1021 }
1022 if( objc>=6 ){
1023 zSep = Tcl_GetStringFromObj(objv[5], 0);
1024 }else{
1025 zSep = "\t";
1026 }
1027 if( objc>=7 ){
1028 zNull = Tcl_GetStringFromObj(objv[6], 0);
1029 }else{
1030 zNull = "";
1031 }
1032 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1033 zTable = Tcl_GetStringFromObj(objv[3], 0);
1034 zFile = Tcl_GetStringFromObj(objv[4], 0);
1035 nSep = strlen(zSep);
1036 nNull = strlen(zNull);
1037 if( nSep==0 ){
1038 Tcl_AppendResult(interp, "Error: non-null separator required for copy", 0);
1039 return TCL_ERROR;
1040 }
1041 if(sqlite3StrICmp(zConflict, "rollback") != 0 &&
1042 sqlite3StrICmp(zConflict, "abort" ) != 0 &&
1043 sqlite3StrICmp(zConflict, "fail" ) != 0 &&
1044 sqlite3StrICmp(zConflict, "ignore" ) != 0 &&
1045 sqlite3StrICmp(zConflict, "replace" ) != 0 ) {
1046 Tcl_AppendResult(interp, "Error: \"", zConflict,
1047 "\", conflict-algorithm must be one of: rollback, "
1048 "abort, fail, ignore, or replace", 0);
1049 return TCL_ERROR;
1050 }
1051 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1052 if( zSql==0 ){
1053 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1054 return TCL_ERROR;
1055 }
1056 nByte = strlen(zSql);
1057 rc = sqlite3_prepare(pDb->db, zSql, 0, &pStmt, 0);
1058 sqlite3_free(zSql);
1059 if( rc ){
1060 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1061 nCol = 0;
1062 }else{
1063 nCol = sqlite3_column_count(pStmt);
1064 }
1065 sqlite3_finalize(pStmt);
1066 if( nCol==0 ) {
1067 return TCL_ERROR;
1068 }
1069 zSql = malloc( nByte + 50 + nCol*2 );
1070 if( zSql==0 ) {
1071 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1072 return TCL_ERROR;
1073 }
1074 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1075 zConflict, zTable);
1076 j = strlen(zSql);
1077 for(i=1; i<nCol; i++){
1078 zSql[j++] = ',';
1079 zSql[j++] = '?';
1080 }
1081 zSql[j++] = ')';
1082 zSql[j] = 0;
1083 rc = sqlite3_prepare(pDb->db, zSql, 0, &pStmt, 0);
1084 free(zSql);
1085 if( rc ){
1086 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1087 sqlite3_finalize(pStmt);
1088 return TCL_ERROR;
1089 }
1090 in = fopen(zFile, "rb");
1091 if( in==0 ){
1092 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
1093 sqlite3_finalize(pStmt);
1094 return TCL_ERROR;
1095 }
1096 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1097 if( azCol==0 ) {
1098 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00001099 fclose(in);
drh19e2d372005-08-29 23:00:03 +00001100 return TCL_ERROR;
1101 }
drh37527852006-03-16 16:19:56 +00001102 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001103 zCommit = "COMMIT";
1104 while( (zLine = local_getline(0, in))!=0 ){
1105 char *z;
1106 i = 0;
1107 lineno++;
1108 azCol[0] = zLine;
1109 for(i=0, z=zLine; *z; z++){
1110 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
1111 *z = 0;
1112 i++;
1113 if( i<nCol ){
1114 azCol[i] = &z[nSep];
1115 z += nSep-1;
1116 }
1117 }
1118 }
1119 if( i+1!=nCol ){
1120 char *zErr;
1121 zErr = malloc(200 + strlen(zFile));
drhc1f44942006-05-10 14:39:13 +00001122 if( zErr ){
1123 sprintf(zErr,
1124 "Error: %s line %d: expected %d columns of data but found %d",
1125 zFile, lineno, nCol, i+1);
1126 Tcl_AppendResult(interp, zErr, 0);
1127 free(zErr);
1128 }
drh19e2d372005-08-29 23:00:03 +00001129 zCommit = "ROLLBACK";
1130 break;
1131 }
1132 for(i=0; i<nCol; i++){
1133 /* check for null data, if so, bind as null */
1134 if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
1135 sqlite3_bind_null(pStmt, i+1);
1136 }else{
1137 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1138 }
1139 }
1140 sqlite3_step(pStmt);
1141 rc = sqlite3_reset(pStmt);
1142 free(zLine);
1143 if( rc!=SQLITE_OK ){
1144 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
1145 zCommit = "ROLLBACK";
1146 break;
1147 }
1148 }
1149 free(azCol);
1150 fclose(in);
1151 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00001152 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001153
1154 if( zCommit[0] == 'C' ){
1155 /* success, set result as number of lines processed */
1156 pResult = Tcl_GetObjResult(interp);
1157 Tcl_SetIntObj(pResult, lineno);
1158 rc = TCL_OK;
1159 }else{
1160 /* failure, append lineno where failed */
1161 sprintf(zLineNum,"%d",lineno);
1162 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
1163 rc = TCL_ERROR;
1164 }
1165 break;
1166 }
1167
drhdcd997e2003-01-31 17:21:49 +00001168 /*
drh41449052006-07-06 17:08:48 +00001169 ** $db enable_load_extension BOOLEAN
1170 **
1171 ** Turn the extension loading feature on or off. It if off by
1172 ** default.
1173 */
1174 case DB_ENABLE_LOAD_EXTENSION: {
1175 int onoff;
1176 if( objc!=3 ){
1177 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
1178 return TCL_ERROR;
1179 }
1180 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
1181 return TCL_ERROR;
1182 }
1183 sqlite3_enable_load_extension(pDb->db, onoff);
1184 break;
1185 }
1186
1187 /*
drhdcd997e2003-01-31 17:21:49 +00001188 ** $db errorcode
1189 **
1190 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00001191 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00001192 */
1193 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00001194 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00001195 break;
1196 }
drh75897232000-05-29 14:26:00 +00001197
1198 /*
drh895d7472004-08-20 16:02:39 +00001199 ** $db eval $sql ?array? ?{ ...code... }?
drh1807ce32004-09-07 13:20:35 +00001200 ** $db onecolumn $sql
drh75897232000-05-29 14:26:00 +00001201 **
1202 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00001203 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00001204 ** If "array" and "code" are omitted, then no callback is every invoked.
1205 ** If "array" is an empty string, then the values are placed in variables
1206 ** that have the same name as the fields extracted by the query.
drh1807ce32004-09-07 13:20:35 +00001207 **
1208 ** The onecolumn method is the equivalent of:
1209 ** lindex [$db eval $sql] 0
drh75897232000-05-29 14:26:00 +00001210 */
drh1807ce32004-09-07 13:20:35 +00001211 case DB_ONECOLUMN:
drh97f2ebc2005-12-10 21:19:04 +00001212 case DB_EVAL:
1213 case DB_EXISTS: {
drh9d74b4c2004-08-24 15:23:34 +00001214 char const *zSql; /* Next SQL statement to execute */
1215 char const *zLeft; /* What is left after first stmt in zSql */
1216 sqlite3_stmt *pStmt; /* Compiled SQL statment */
drh92febd92004-08-20 18:34:20 +00001217 Tcl_Obj *pArray; /* Name of array into which results are written */
1218 Tcl_Obj *pScript; /* Script to run for each result set */
drh1d895032004-08-26 00:56:05 +00001219 Tcl_Obj **apParm; /* Parameters that need a Tcl_DecrRefCount() */
1220 int nParm; /* Number of entries used in apParm[] */
1221 Tcl_Obj *aParm[10]; /* Static space for apParm[] in the common case */
drh1807ce32004-09-07 13:20:35 +00001222 Tcl_Obj *pRet; /* Value to be returned */
drhfb7e7652005-01-24 00:28:42 +00001223 SqlPreparedStmt *pPreStmt; /* Pointer to a prepared statement */
1224 int rc2;
danielk1977ef2cb632004-05-29 02:37:19 +00001225
drh97f2ebc2005-12-10 21:19:04 +00001226 if( choice==DB_EVAL ){
drh1807ce32004-09-07 13:20:35 +00001227 if( objc<3 || objc>5 ){
1228 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
1229 return TCL_ERROR;
1230 }
1231 pRet = Tcl_NewObj();
1232 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001233 }else{
1234 if( objc!=3 ){
1235 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
1236 return TCL_ERROR;
1237 }
drh97f2ebc2005-12-10 21:19:04 +00001238 if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001239 pRet = Tcl_NewBooleanObj(0);
1240 Tcl_IncrRefCount(pRet);
1241 }else{
1242 pRet = 0;
drh97f2ebc2005-12-10 21:19:04 +00001243 }
danielk197730ccda12004-05-27 12:11:31 +00001244 }
drh92febd92004-08-20 18:34:20 +00001245 if( objc==3 ){
1246 pArray = pScript = 0;
1247 }else if( objc==4 ){
1248 pArray = 0;
1249 pScript = objv[3];
1250 }else{
1251 pArray = objv[3];
1252 if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
1253 pScript = objv[4];
1254 }
danielk197730ccda12004-05-27 12:11:31 +00001255
drh1d895032004-08-26 00:56:05 +00001256 Tcl_IncrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001257 zSql = Tcl_GetStringFromObj(objv[2], 0);
drh90b6bb12004-09-13 13:16:31 +00001258 while( rc==TCL_OK && zSql[0] ){
drhfb7e7652005-01-24 00:28:42 +00001259 int i; /* Loop counter */
1260 int nVar; /* Number of bind parameters in the pStmt */
1261 int nCol; /* Number of columns in the result set */
drh92febd92004-08-20 18:34:20 +00001262 Tcl_Obj **apColName = 0; /* Array of column names */
drhfb7e7652005-01-24 00:28:42 +00001263 int len; /* String length of zSql */
danielk197730ccda12004-05-27 12:11:31 +00001264
drhfb7e7652005-01-24 00:28:42 +00001265 /* Try to find a SQL statement that has already been compiled and
1266 ** which matches the next sequence of SQL.
1267 */
1268 pStmt = 0;
1269 pPreStmt = pDb->stmtList;
1270 len = strlen(zSql);
1271 if( pPreStmt && sqlite3_expired(pPreStmt->pStmt) ){
1272 flushStmtCache(pDb);
1273 pPreStmt = 0;
danielk197730ccda12004-05-27 12:11:31 +00001274 }
drhfb7e7652005-01-24 00:28:42 +00001275 for(; pPreStmt; pPreStmt=pPreStmt->pNext){
1276 int n = pPreStmt->nSql;
1277 if( len>=n
1278 && memcmp(pPreStmt->zSql, zSql, n)==0
1279 && (zSql[n]==0 || zSql[n-1]==';')
1280 ){
1281 pStmt = pPreStmt->pStmt;
1282 zLeft = &zSql[pPreStmt->nSql];
1283
1284 /* When a prepared statement is found, unlink it from the
1285 ** cache list. It will later be added back to the beginning
1286 ** of the cache list in order to implement LRU replacement.
1287 */
1288 if( pPreStmt->pPrev ){
1289 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1290 }else{
1291 pDb->stmtList = pPreStmt->pNext;
1292 }
1293 if( pPreStmt->pNext ){
1294 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1295 }else{
1296 pDb->stmtLast = pPreStmt->pPrev;
1297 }
1298 pDb->nStmt--;
1299 break;
1300 }
1301 }
1302
1303 /* If no prepared statement was found. Compile the SQL text
1304 */
drh92febd92004-08-20 18:34:20 +00001305 if( pStmt==0 ){
drhfb7e7652005-01-24 00:28:42 +00001306 if( SQLITE_OK!=sqlite3_prepare(pDb->db, zSql, -1, &pStmt, &zLeft) ){
drh92febd92004-08-20 18:34:20 +00001307 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1308 rc = TCL_ERROR;
1309 break;
danielk197730ccda12004-05-27 12:11:31 +00001310 }
drhfb7e7652005-01-24 00:28:42 +00001311 if( pStmt==0 ){
1312 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1313 /* A compile-time error in the statement
1314 */
1315 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1316 rc = TCL_ERROR;
1317 break;
1318 }else{
1319 /* The statement was a no-op. Continue to the next statement
1320 ** in the SQL string.
1321 */
1322 zSql = zLeft;
1323 continue;
1324 }
1325 }
1326 assert( pPreStmt==0 );
danielk197730ccda12004-05-27 12:11:31 +00001327 }
1328
drhfb7e7652005-01-24 00:28:42 +00001329 /* Bind values to parameters that begin with $ or :
1330 */
drh92febd92004-08-20 18:34:20 +00001331 nVar = sqlite3_bind_parameter_count(pStmt);
drh1d895032004-08-26 00:56:05 +00001332 nParm = 0;
1333 if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
1334 apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
1335 }else{
1336 apParm = aParm;
1337 }
drh92febd92004-08-20 18:34:20 +00001338 for(i=1; i<=nVar; i++){
1339 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
drhc8f90792005-01-12 00:08:24 +00001340 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':') ){
drh92febd92004-08-20 18:34:20 +00001341 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1342 if( pVar ){
1343 int n;
1344 u8 *data;
1345 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
1346 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +00001347 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
1348 /* Only load a BLOB type if the Tcl variable is a bytearray and
1349 ** has no string representation. */
drh92febd92004-08-20 18:34:20 +00001350 data = Tcl_GetByteArrayFromObj(pVar, &n);
1351 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001352 Tcl_IncrRefCount(pVar);
1353 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001354 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
1355 (c=='i' && strcmp(zType,"int")==0) ){
1356 Tcl_GetIntFromObj(interp, pVar, &n);
1357 sqlite3_bind_int(pStmt, i, n);
1358 }else if( c=='d' && strcmp(zType,"double")==0 ){
1359 double r;
1360 Tcl_GetDoubleFromObj(interp, pVar, &r);
1361 sqlite3_bind_double(pStmt, i, r);
drhdf0bdda2005-06-25 19:31:48 +00001362 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
1363 Tcl_WideInt v;
1364 Tcl_GetWideIntFromObj(interp, pVar, &v);
1365 sqlite3_bind_int64(pStmt, i, v);
drh92febd92004-08-20 18:34:20 +00001366 }else{
danielk197700fd9572005-12-07 06:27:43 +00001367 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1368 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001369 Tcl_IncrRefCount(pVar);
1370 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001371 }
drhfb7e7652005-01-24 00:28:42 +00001372 }else{
1373 sqlite3_bind_null( pStmt, i );
drh92febd92004-08-20 18:34:20 +00001374 }
1375 }
1376 }
drh92febd92004-08-20 18:34:20 +00001377
1378 /* Compute column names */
1379 nCol = sqlite3_column_count(pStmt);
1380 if( pScript ){
1381 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1382 if( apColName==0 ) break;
1383 for(i=0; i<nCol; i++){
1384 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1385 Tcl_IncrRefCount(apColName[i]);
1386 }
1387 }
1388
1389 /* If results are being stored in an array variable, then create
1390 ** the array(*) entry for that array
1391 */
1392 if( pArray ){
1393 Tcl_Obj *pColList = Tcl_NewObj();
drh3ced14a2005-03-31 18:26:20 +00001394 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
drh92febd92004-08-20 18:34:20 +00001395 Tcl_IncrRefCount(pColList);
1396 for(i=0; i<nCol; i++){
1397 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1398 }
drh3ced14a2005-03-31 18:26:20 +00001399 Tcl_ObjSetVar2(interp, pArray, pStar, pColList,0);
1400 Tcl_DecrRefCount(pColList);
1401 Tcl_DecrRefCount(pStar);
drh92febd92004-08-20 18:34:20 +00001402 }
1403
1404 /* Execute the SQL
1405 */
drh90b6bb12004-09-13 13:16:31 +00001406 while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
drh92febd92004-08-20 18:34:20 +00001407 for(i=0; i<nCol; i++){
danielk197730ccda12004-05-27 12:11:31 +00001408 Tcl_Obj *pVal;
1409
1410 /* Set pVal to contain the i'th column of this row. */
drh92febd92004-08-20 18:34:20 +00001411 switch( sqlite3_column_type(pStmt, i) ){
1412 case SQLITE_BLOB: {
1413 int bytes = sqlite3_column_bytes(pStmt, i);
1414 pVal = Tcl_NewByteArrayObj(sqlite3_column_blob(pStmt, i), bytes);
1415 break;
1416 }
1417 case SQLITE_INTEGER: {
1418 sqlite_int64 v = sqlite3_column_int64(pStmt, i);
1419 if( v>=-2147483647 && v<=2147483647 ){
1420 pVal = Tcl_NewIntObj(v);
1421 }else{
1422 pVal = Tcl_NewWideIntObj(v);
1423 }
1424 break;
1425 }
1426 case SQLITE_FLOAT: {
1427 double r = sqlite3_column_double(pStmt, i);
1428 pVal = Tcl_NewDoubleObj(r);
1429 break;
1430 }
danielk197755c45f22005-04-03 23:54:43 +00001431 case SQLITE_NULL: {
1432 pVal = dbTextToObj(pDb->zNull);
1433 break;
1434 }
drh92febd92004-08-20 18:34:20 +00001435 default: {
danielk197700fd9572005-12-07 06:27:43 +00001436 pVal = dbTextToObj((char *)sqlite3_column_text(pStmt, i));
drh92febd92004-08-20 18:34:20 +00001437 break;
1438 }
danielk197730ccda12004-05-27 12:11:31 +00001439 }
1440
drh92febd92004-08-20 18:34:20 +00001441 if( pScript ){
1442 if( pArray==0 ){
1443 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001444 }else{
drh92febd92004-08-20 18:34:20 +00001445 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001446 }
drh1807ce32004-09-07 13:20:35 +00001447 }else if( choice==DB_ONECOLUMN ){
drh97f2ebc2005-12-10 21:19:04 +00001448 assert( pRet==0 );
drh1807ce32004-09-07 13:20:35 +00001449 if( pRet==0 ){
1450 pRet = pVal;
1451 Tcl_IncrRefCount(pRet);
1452 }
drh90b6bb12004-09-13 13:16:31 +00001453 rc = TCL_BREAK;
drh97f2ebc2005-12-10 21:19:04 +00001454 i = nCol;
1455 }else if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001456 Tcl_DecrRefCount(pRet);
1457 pRet = Tcl_NewBooleanObj(1);
1458 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001459 rc = TCL_BREAK;
1460 i = nCol;
danielk197730ccda12004-05-27 12:11:31 +00001461 }else{
danielk197730ccda12004-05-27 12:11:31 +00001462 Tcl_ListObjAppendElement(interp, pRet, pVal);
1463 }
1464 }
1465
drh92febd92004-08-20 18:34:20 +00001466 if( pScript ){
1467 rc = Tcl_EvalObjEx(interp, pScript, 0);
drh90b6bb12004-09-13 13:16:31 +00001468 if( rc==TCL_CONTINUE ){
1469 rc = TCL_OK;
1470 }
danielk197730ccda12004-05-27 12:11:31 +00001471 }
1472 }
drh90b6bb12004-09-13 13:16:31 +00001473 if( rc==TCL_BREAK ){
1474 rc = TCL_OK;
1475 }
drh92febd92004-08-20 18:34:20 +00001476
1477 /* Free the column name objects */
1478 if( pScript ){
1479 for(i=0; i<nCol; i++){
1480 Tcl_DecrRefCount(apColName[i]);
1481 }
1482 Tcl_Free((char*)apColName);
1483 }
1484
drh1d895032004-08-26 00:56:05 +00001485 /* Free the bound string and blob parameters */
1486 for(i=0; i<nParm; i++){
1487 Tcl_DecrRefCount(apParm[i]);
1488 }
1489 if( apParm!=aParm ){
1490 Tcl_Free((char*)apParm);
1491 }
1492
drhfb7e7652005-01-24 00:28:42 +00001493 /* Reset the statement. If the result code is SQLITE_SCHEMA, then
1494 ** flush the statement cache and try the statement again.
drh92febd92004-08-20 18:34:20 +00001495 */
drhfb7e7652005-01-24 00:28:42 +00001496 rc2 = sqlite3_reset(pStmt);
1497 if( SQLITE_SCHEMA==rc2 ){
1498 /* After a schema change, flush the cache and try to run the
1499 ** statement again
1500 */
1501 flushStmtCache( pDb );
1502 sqlite3_finalize(pStmt);
1503 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001504 continue;
drhfb7e7652005-01-24 00:28:42 +00001505 }else if( SQLITE_OK!=rc2 ){
1506 /* If a run-time error occurs, report the error and stop reading
1507 ** the SQL
1508 */
danielk1977ef2cb632004-05-29 02:37:19 +00001509 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
drhfb7e7652005-01-24 00:28:42 +00001510 sqlite3_finalize(pStmt);
danielk197730ccda12004-05-27 12:11:31 +00001511 rc = TCL_ERROR;
drhfb7e7652005-01-24 00:28:42 +00001512 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001513 break;
drhfb7e7652005-01-24 00:28:42 +00001514 }else if( pDb->maxStmt<=0 ){
1515 /* If the cache is turned off, deallocated the statement */
1516 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1517 sqlite3_finalize(pStmt);
1518 }else{
1519 /* Everything worked and the cache is operational.
1520 ** Create a new SqlPreparedStmt structure if we need one.
1521 ** (If we already have one we can just reuse it.)
1522 */
1523 if( pPreStmt==0 ){
1524 len = zLeft - zSql;
1525 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) + len );
1526 if( pPreStmt==0 ) return TCL_ERROR;
1527 pPreStmt->pStmt = pStmt;
1528 pPreStmt->nSql = len;
1529 memcpy(pPreStmt->zSql, zSql, len);
1530 pPreStmt->zSql[len] = 0;
1531 }
1532
1533 /* Add the prepared statement to the beginning of the cache list
1534 */
1535 pPreStmt->pNext = pDb->stmtList;
1536 pPreStmt->pPrev = 0;
1537 if( pDb->stmtList ){
1538 pDb->stmtList->pPrev = pPreStmt;
1539 }
1540 pDb->stmtList = pPreStmt;
1541 if( pDb->stmtLast==0 ){
1542 assert( pDb->nStmt==0 );
1543 pDb->stmtLast = pPreStmt;
1544 }else{
1545 assert( pDb->nStmt>0 );
1546 }
1547 pDb->nStmt++;
1548
1549 /* If we have too many statement in cache, remove the surplus from the
1550 ** end of the cache list.
1551 */
1552 while( pDb->nStmt>pDb->maxStmt ){
1553 sqlite3_finalize(pDb->stmtLast->pStmt);
1554 pDb->stmtLast = pDb->stmtLast->pPrev;
1555 Tcl_Free((char*)pDb->stmtLast->pNext);
1556 pDb->stmtLast->pNext = 0;
1557 pDb->nStmt--;
1558 }
danielk197730ccda12004-05-27 12:11:31 +00001559 }
1560
drhfb7e7652005-01-24 00:28:42 +00001561 /* Proceed to the next statement */
danielk197730ccda12004-05-27 12:11:31 +00001562 zSql = zLeft;
1563 }
drh1d895032004-08-26 00:56:05 +00001564 Tcl_DecrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001565
drh1807ce32004-09-07 13:20:35 +00001566 if( pRet ){
1567 if( rc==TCL_OK ){
1568 Tcl_SetObjResult(interp, pRet);
1569 }
1570 Tcl_DecrRefCount(pRet);
danielk197730ccda12004-05-27 12:11:31 +00001571 }
danielk197730ccda12004-05-27 12:11:31 +00001572 break;
1573 }
drhbec3f402000-08-04 13:49:02 +00001574
1575 /*
drhcabb0812002-09-14 13:47:32 +00001576 ** $db function NAME SCRIPT
1577 **
1578 ** Create a new SQL function called NAME. Whenever that function is
1579 ** called, invoke SCRIPT to evaluate the function.
1580 */
1581 case DB_FUNCTION: {
1582 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00001583 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00001584 char *zName;
drhcabb0812002-09-14 13:47:32 +00001585 if( objc!=4 ){
1586 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1587 return TCL_ERROR;
1588 }
1589 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00001590 pScript = objv[3];
1591 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00001592 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00001593 if( pFunc->pScript ){
1594 Tcl_DecrRefCount(pFunc->pScript);
1595 }
1596 pFunc->pScript = pScript;
1597 Tcl_IncrRefCount(pScript);
1598 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
danielk1977c8c11582004-06-29 13:41:21 +00001599 rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00001600 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00001601 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00001602 rc = TCL_ERROR;
1603 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00001604 }else{
1605 /* Must flush any cached statements */
1606 flushStmtCache( pDb );
1607 }
drhcabb0812002-09-14 13:47:32 +00001608 break;
1609 }
1610
1611 /*
drh19e2d372005-08-29 23:00:03 +00001612 ** $db nullvalue ?STRING?
1613 **
1614 ** Change text used when a NULL comes back from the database. If ?STRING?
1615 ** is not present, then the current string used for NULL is returned.
1616 ** If STRING is present, then STRING is returned.
1617 **
1618 */
1619 case DB_NULLVALUE: {
1620 if( objc!=2 && objc!=3 ){
1621 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
1622 return TCL_ERROR;
1623 }
1624 if( objc==3 ){
1625 int len;
1626 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
1627 if( pDb->zNull ){
1628 Tcl_Free(pDb->zNull);
1629 }
1630 if( zNull && len>0 ){
1631 pDb->zNull = Tcl_Alloc( len + 1 );
1632 strncpy(pDb->zNull, zNull, len);
1633 pDb->zNull[len] = '\0';
1634 }else{
1635 pDb->zNull = 0;
1636 }
1637 }
1638 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
1639 break;
1640 }
1641
1642 /*
drhaf9ff332002-01-16 21:00:27 +00001643 ** $db last_insert_rowid
1644 **
1645 ** Return an integer which is the ROWID for the most recent insert.
1646 */
1647 case DB_LAST_INSERT_ROWID: {
1648 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00001649 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00001650 if( objc!=2 ){
1651 Tcl_WrongNumArgs(interp, 2, objv, "");
1652 return TCL_ERROR;
1653 }
danielk19776f8a5032004-05-10 10:34:51 +00001654 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00001655 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00001656 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00001657 break;
1658 }
1659
1660 /*
drh1807ce32004-09-07 13:20:35 +00001661 ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
drh5d9d7572003-08-19 14:31:01 +00001662 */
drh1807ce32004-09-07 13:20:35 +00001663
1664 /* $db progress ?N CALLBACK?
1665 **
1666 ** Invoke the given callback every N virtual machine opcodes while executing
1667 ** queries.
1668 */
1669 case DB_PROGRESS: {
1670 if( objc==2 ){
1671 if( pDb->zProgress ){
1672 Tcl_AppendResult(interp, pDb->zProgress, 0);
1673 }
1674 }else if( objc==4 ){
1675 char *zProgress;
1676 int len;
1677 int N;
1678 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
1679 return TCL_ERROR;
1680 };
1681 if( pDb->zProgress ){
1682 Tcl_Free(pDb->zProgress);
1683 }
1684 zProgress = Tcl_GetStringFromObj(objv[3], &len);
1685 if( zProgress && len>0 ){
1686 pDb->zProgress = Tcl_Alloc( len + 1 );
1687 strcpy(pDb->zProgress, zProgress);
1688 }else{
1689 pDb->zProgress = 0;
1690 }
1691#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1692 if( pDb->zProgress ){
1693 pDb->interp = interp;
1694 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
1695 }else{
1696 sqlite3_progress_handler(pDb->db, 0, 0, 0);
1697 }
1698#endif
1699 }else{
1700 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00001701 return TCL_ERROR;
1702 }
drh5d9d7572003-08-19 14:31:01 +00001703 break;
1704 }
1705
drh19e2d372005-08-29 23:00:03 +00001706 /* $db profile ?CALLBACK?
1707 **
1708 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
1709 ** that has run. The text of the SQL and the amount of elapse time are
1710 ** appended to CALLBACK before the script is run.
1711 */
1712 case DB_PROFILE: {
1713 if( objc>3 ){
1714 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1715 return TCL_ERROR;
1716 }else if( objc==2 ){
1717 if( pDb->zProfile ){
1718 Tcl_AppendResult(interp, pDb->zProfile, 0);
1719 }
1720 }else{
1721 char *zProfile;
1722 int len;
1723 if( pDb->zProfile ){
1724 Tcl_Free(pDb->zProfile);
1725 }
1726 zProfile = Tcl_GetStringFromObj(objv[2], &len);
1727 if( zProfile && len>0 ){
1728 pDb->zProfile = Tcl_Alloc( len + 1 );
1729 strcpy(pDb->zProfile, zProfile);
1730 }else{
1731 pDb->zProfile = 0;
1732 }
1733#ifndef SQLITE_OMIT_TRACE
1734 if( pDb->zProfile ){
1735 pDb->interp = interp;
1736 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
1737 }else{
1738 sqlite3_profile(pDb->db, 0, 0);
1739 }
1740#endif
1741 }
1742 break;
1743 }
1744
drh5d9d7572003-08-19 14:31:01 +00001745 /*
drh22fbcb82004-02-01 01:22:50 +00001746 ** $db rekey KEY
1747 **
1748 ** Change the encryption key on the currently open database.
1749 */
1750 case DB_REKEY: {
1751 int nKey;
1752 void *pKey;
1753 if( objc!=3 ){
1754 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
1755 return TCL_ERROR;
1756 }
1757 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00001758#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00001759 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00001760 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00001761 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00001762 rc = TCL_ERROR;
1763 }
1764#endif
1765 break;
1766 }
1767
1768 /*
drhbec3f402000-08-04 13:49:02 +00001769 ** $db timeout MILLESECONDS
1770 **
1771 ** Delay for the number of milliseconds specified when a file is locked.
1772 */
drh6d313162000-09-21 13:01:35 +00001773 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00001774 int ms;
drh6d313162000-09-21 13:01:35 +00001775 if( objc!=3 ){
1776 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00001777 return TCL_ERROR;
1778 }
drh6d313162000-09-21 13:01:35 +00001779 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00001780 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00001781 break;
drh75897232000-05-29 14:26:00 +00001782 }
danielk197755c45f22005-04-03 23:54:43 +00001783
1784 /*
drh0f14e2e2004-06-29 12:39:08 +00001785 ** $db total_changes
1786 **
1787 ** Return the number of rows that were modified, inserted, or deleted
1788 ** since the database handle was created.
1789 */
1790 case DB_TOTAL_CHANGES: {
1791 Tcl_Obj *pResult;
1792 if( objc!=2 ){
1793 Tcl_WrongNumArgs(interp, 2, objv, "");
1794 return TCL_ERROR;
1795 }
1796 pResult = Tcl_GetObjResult(interp);
1797 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
1798 break;
1799 }
1800
drhb5a20d32003-04-23 12:25:23 +00001801 /* $db trace ?CALLBACK?
1802 **
1803 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
1804 ** that is executed. The text of the SQL is appended to CALLBACK before
1805 ** it is executed.
1806 */
1807 case DB_TRACE: {
1808 if( objc>3 ){
1809 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00001810 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00001811 }else if( objc==2 ){
1812 if( pDb->zTrace ){
1813 Tcl_AppendResult(interp, pDb->zTrace, 0);
1814 }
1815 }else{
1816 char *zTrace;
1817 int len;
1818 if( pDb->zTrace ){
1819 Tcl_Free(pDb->zTrace);
1820 }
1821 zTrace = Tcl_GetStringFromObj(objv[2], &len);
1822 if( zTrace && len>0 ){
1823 pDb->zTrace = Tcl_Alloc( len + 1 );
1824 strcpy(pDb->zTrace, zTrace);
1825 }else{
1826 pDb->zTrace = 0;
1827 }
drh19e2d372005-08-29 23:00:03 +00001828#ifndef SQLITE_OMIT_TRACE
drhb5a20d32003-04-23 12:25:23 +00001829 if( pDb->zTrace ){
1830 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001831 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00001832 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001833 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00001834 }
drh19e2d372005-08-29 23:00:03 +00001835#endif
drhb5a20d32003-04-23 12:25:23 +00001836 }
1837 break;
1838 }
1839
drh3d214232005-08-02 12:21:08 +00001840 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1841 **
1842 ** Start a new transaction (if we are not already in the midst of a
1843 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
1844 ** completes, either commit the transaction or roll it back if SCRIPT
1845 ** throws an exception. Or if no new transation was started, do nothing.
1846 ** pass the exception on up the stack.
1847 **
1848 ** This command was inspired by Dave Thomas's talk on Ruby at the
1849 ** 2005 O'Reilly Open Source Convention (OSCON).
1850 */
1851 case DB_TRANSACTION: {
1852 int inTrans;
1853 Tcl_Obj *pScript;
1854 const char *zBegin = "BEGIN";
1855 if( objc!=3 && objc!=4 ){
1856 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
1857 return TCL_ERROR;
1858 }
1859 if( objc==3 ){
1860 pScript = objv[2];
1861 } else {
1862 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00001863 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00001864 };
1865 enum TTYPE_enum {
1866 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
1867 };
1868 int ttype;
drhb5555e72005-08-02 17:15:14 +00001869 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00001870 0, &ttype) ){
1871 return TCL_ERROR;
1872 }
1873 switch( (enum TTYPE_enum)ttype ){
1874 case TTYPE_DEFERRED: /* no-op */; break;
1875 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
1876 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
1877 }
1878 pScript = objv[3];
1879 }
1880 inTrans = !sqlite3_get_autocommit(pDb->db);
1881 if( !inTrans ){
drh37527852006-03-16 16:19:56 +00001882 (void)sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
drh3d214232005-08-02 12:21:08 +00001883 }
1884 rc = Tcl_EvalObjEx(interp, pScript, 0);
1885 if( !inTrans ){
1886 const char *zEnd;
1887 if( rc==TCL_ERROR ){
1888 zEnd = "ROLLBACK";
1889 } else {
1890 zEnd = "COMMIT";
1891 }
drh37527852006-03-16 16:19:56 +00001892 (void)sqlite3_exec(pDb->db, zEnd, 0, 0, 0);
drh3d214232005-08-02 12:21:08 +00001893 }
1894 break;
1895 }
1896
danielk197794eb6a12005-12-15 15:22:08 +00001897 /*
1898 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00001899 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00001900 */
danielk197771fd80b2005-12-16 06:54:01 +00001901 case DB_UPDATE_HOOK:
1902 case DB_ROLLBACK_HOOK: {
1903
1904 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
1905 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
1906 */
1907 Tcl_Obj **ppHook;
1908 if( choice==DB_UPDATE_HOOK ){
1909 ppHook = &pDb->pUpdateHook;
1910 }else{
1911 ppHook = &pDb->pRollbackHook;
1912 }
1913
danielk197794eb6a12005-12-15 15:22:08 +00001914 if( objc!=2 && objc!=3 ){
1915 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
1916 return TCL_ERROR;
1917 }
danielk197771fd80b2005-12-16 06:54:01 +00001918 if( *ppHook ){
1919 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00001920 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00001921 Tcl_DecrRefCount(*ppHook);
1922 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00001923 }
1924 }
1925 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00001926 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00001927 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00001928 *ppHook = objv[2];
1929 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00001930 }
1931 }
danielk197771fd80b2005-12-16 06:54:01 +00001932
1933 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1934 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
1935
danielk197794eb6a12005-12-15 15:22:08 +00001936 break;
1937 }
1938
danielk19774397de52005-01-12 12:44:03 +00001939 /* $db version
1940 **
1941 ** Return the version string for this database.
1942 */
1943 case DB_VERSION: {
1944 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
1945 break;
1946 }
1947
tpoindex1067fe12004-12-17 15:41:11 +00001948
drh6d313162000-09-21 13:01:35 +00001949 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00001950 return rc;
drh75897232000-05-29 14:26:00 +00001951}
1952
1953/*
drh9bb575f2004-09-06 17:24:11 +00001954** sqlite3 DBNAME FILENAME ?MODE? ?-key KEY?
drh75897232000-05-29 14:26:00 +00001955**
1956** This is the main Tcl command. When the "sqlite" Tcl command is
1957** invoked, this routine runs to process that command.
1958**
1959** The first argument, DBNAME, is an arbitrary name for a new
1960** database connection. This command creates a new command named
1961** DBNAME that is used to control that connection. The database
1962** connection is deleted when the DBNAME command is deleted.
1963**
1964** The second argument is the name of the directory that contains
1965** the sqlite database that is to be accessed.
drhfbc3eab2001-04-06 16:13:42 +00001966**
1967** For testing purposes, we also support the following:
1968**
drh9bb575f2004-09-06 17:24:11 +00001969** sqlite3 -encoding
drhfbc3eab2001-04-06 16:13:42 +00001970**
1971** Return the encoding used by LIKE and GLOB operators. Choices
1972** are UTF-8 and iso8859.
1973**
drh9bb575f2004-09-06 17:24:11 +00001974** sqlite3 -version
drh647cb0e2002-11-04 19:32:25 +00001975**
1976** Return the version number of the SQLite library.
1977**
drh9bb575f2004-09-06 17:24:11 +00001978** sqlite3 -tcl-uses-utf
drhfbc3eab2001-04-06 16:13:42 +00001979**
1980** Return "1" if compiled with a Tcl uses UTF-8. Return "0" if
1981** not. Used by tests to make sure the library was compiled
1982** correctly.
drh75897232000-05-29 14:26:00 +00001983*/
drh22fbcb82004-02-01 01:22:50 +00001984static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001985 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00001986 void *pKey = 0;
1987 int nKey = 0;
1988 const char *zArg;
drh75897232000-05-29 14:26:00 +00001989 char *zErrMsg;
drh22fbcb82004-02-01 01:22:50 +00001990 const char *zFile;
drh22fbcb82004-02-01 01:22:50 +00001991 if( objc==2 ){
1992 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00001993 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00001994 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00001995 return TCL_OK;
1996 }
drh9eb9e262004-02-11 02:18:05 +00001997 if( strcmp(zArg,"-has-codec")==0 ){
1998#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00001999 Tcl_AppendResult(interp,"1",0);
2000#else
2001 Tcl_AppendResult(interp,"0",0);
2002#endif
2003 return TCL_OK;
2004 }
2005 if( strcmp(zArg,"-tcl-uses-utf")==0 ){
drhfbc3eab2001-04-06 16:13:42 +00002006#ifdef TCL_UTF_MAX
2007 Tcl_AppendResult(interp,"1",0);
2008#else
2009 Tcl_AppendResult(interp,"0",0);
2010#endif
2011 return TCL_OK;
2012 }
2013 }
drh22fbcb82004-02-01 01:22:50 +00002014 if( objc==5 || objc==6 ){
2015 zArg = Tcl_GetStringFromObj(objv[objc-2], 0);
2016 if( strcmp(zArg,"-key")==0 ){
2017 pKey = Tcl_GetByteArrayFromObj(objv[objc-1], &nKey);
2018 objc -= 2;
2019 }
2020 }
2021 if( objc!=3 && objc!=4 ){
2022 Tcl_WrongNumArgs(interp, 1, objv,
drh9eb9e262004-02-11 02:18:05 +00002023#ifdef SQLITE_HAS_CODEC
2024 "HANDLE FILENAME ?-key CODEC-KEY?"
drh22fbcb82004-02-01 01:22:50 +00002025#else
2026 "HANDLE FILENAME ?MODE?"
2027#endif
2028 );
drh75897232000-05-29 14:26:00 +00002029 return TCL_ERROR;
2030 }
drh75897232000-05-29 14:26:00 +00002031 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00002032 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00002033 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00002034 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
2035 return TCL_ERROR;
2036 }
2037 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00002038 zFile = Tcl_GetStringFromObj(objv[2], 0);
danielk19774f057f92004-06-08 00:02:33 +00002039 sqlite3_open(zFile, &p->db);
danielk197780290862004-05-22 09:21:21 +00002040 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
2041 zErrMsg = strdup(sqlite3_errmsg(p->db));
2042 sqlite3_close(p->db);
2043 p->db = 0;
2044 }
drh2011d5f2004-07-22 02:40:37 +00002045#ifdef SQLITE_HAS_CODEC
2046 sqlite3_key(p->db, pKey, nKey);
drheb8ed702004-02-11 10:37:23 +00002047#endif
drhbec3f402000-08-04 13:49:02 +00002048 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00002049 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00002050 Tcl_Free((char*)p);
drh75897232000-05-29 14:26:00 +00002051 free(zErrMsg);
2052 return TCL_ERROR;
2053 }
drhfb7e7652005-01-24 00:28:42 +00002054 p->maxStmt = NUM_PREPARED_STMTS;
drh22fbcb82004-02-01 01:22:50 +00002055 zArg = Tcl_GetStringFromObj(objv[1], 0);
2056 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
drhc22bd472002-05-10 13:14:07 +00002057
2058 /* If compiled with SQLITE_TEST turned on, then register the "md5sum"
drh06b27182002-06-26 20:06:05 +00002059 ** SQL function.
drhc22bd472002-05-10 13:14:07 +00002060 */
drh28b4e482002-03-11 02:06:13 +00002061#ifdef SQLITE_TEST
2062 {
drh9bb575f2004-09-06 17:24:11 +00002063 extern void Md5_Register(sqlite3*);
drh3b93bc82005-01-13 23:54:32 +00002064#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00002065 int mallocfail = sqlite3_iMallocFail;
2066 sqlite3_iMallocFail = 0;
danielk19775b59af82004-06-30 12:42:59 +00002067#endif
drhc22bd472002-05-10 13:14:07 +00002068 Md5_Register(p->db);
drh3b93bc82005-01-13 23:54:32 +00002069#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00002070 sqlite3_iMallocFail = mallocfail;
danielk19775b59af82004-06-30 12:42:59 +00002071#endif
danielk19777ddad962005-12-12 06:53:03 +00002072 }
drh28b4e482002-03-11 02:06:13 +00002073#endif
danielk19777cedc8d2004-06-10 10:50:08 +00002074 p->interp = interp;
drh75897232000-05-29 14:26:00 +00002075 return TCL_OK;
2076}
2077
2078/*
drh90ca9752001-09-28 17:47:14 +00002079** Provide a dummy Tcl_InitStubs if we are using this as a static
2080** library.
2081*/
2082#ifndef USE_TCL_STUBS
2083# undef Tcl_InitStubs
2084# define Tcl_InitStubs(a,b,c)
2085#endif
2086
2087/*
drh29bc4612005-10-05 10:40:15 +00002088** Make sure we have a PACKAGE_VERSION macro defined. This will be
2089** defined automatically by the TEA makefile. But other makefiles
2090** do not define it.
2091*/
2092#ifndef PACKAGE_VERSION
2093# define PACKAGE_VERSION SQLITE_VERSION
2094#endif
2095
2096/*
drh75897232000-05-29 14:26:00 +00002097** Initialize this module.
2098**
2099** This Tcl module contains only a single new Tcl command named "sqlite".
2100** (Hence there is no namespace. There is no point in using a namespace
2101** if the extension only supplies one new name!) The "sqlite" command is
2102** used to open a new SQLite database. See the DbMain() routine above
2103** for additional information.
2104*/
drhad6e1372006-07-10 21:15:51 +00002105EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00002106 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00002107 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002108 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh49766d62005-01-08 18:42:28 +00002109 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002110 Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
drh90ca9752001-09-28 17:47:14 +00002111 return TCL_OK;
2112}
drhad6e1372006-07-10 21:15:51 +00002113EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2114EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2115EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002116
2117#ifndef SQLITE_3_SUFFIX_ONLY
drhad6e1372006-07-10 21:15:51 +00002118EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2119EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2120EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2121EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002122#endif
drh75897232000-05-29 14:26:00 +00002123
drh3e27c022004-07-23 00:01:38 +00002124#ifdef TCLSH
2125/*****************************************************************************
2126** The code that follows is used to build standalone TCL interpreters
drh75897232000-05-29 14:26:00 +00002127*/
drh348784e2000-05-29 20:41:49 +00002128
2129/*
drh3e27c022004-07-23 00:01:38 +00002130** If the macro TCLSH is one, then put in code this for the
2131** "main" routine that will initialize Tcl and take input from
2132** standard input.
drh348784e2000-05-29 20:41:49 +00002133*/
drh3e27c022004-07-23 00:01:38 +00002134#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00002135static char zMainloop[] =
2136 "set line {}\n"
2137 "while {![eof stdin]} {\n"
2138 "if {$line!=\"\"} {\n"
2139 "puts -nonewline \"> \"\n"
2140 "} else {\n"
2141 "puts -nonewline \"% \"\n"
2142 "}\n"
2143 "flush stdout\n"
2144 "append line [gets stdin]\n"
2145 "if {[info complete $line]} {\n"
2146 "if {[catch {uplevel #0 $line} result]} {\n"
2147 "puts stderr \"Error: $result\"\n"
2148 "} elseif {$result!=\"\"} {\n"
2149 "puts $result\n"
2150 "}\n"
2151 "set line {}\n"
2152 "} else {\n"
2153 "append line \\n\n"
2154 "}\n"
2155 "}\n"
2156;
drh3e27c022004-07-23 00:01:38 +00002157#endif
2158
2159/*
2160** If the macro TCLSH is two, then get the main loop code out of
2161** the separate file "spaceanal_tcl.h".
2162*/
2163#if TCLSH==2
2164static char zMainloop[] =
2165#include "spaceanal_tcl.h"
2166;
2167#endif
drh348784e2000-05-29 20:41:49 +00002168
2169#define TCLSH_MAIN main /* Needed to fake out mktclapp */
2170int TCLSH_MAIN(int argc, char **argv){
2171 Tcl_Interp *interp;
drh297ecf12001-04-05 15:57:13 +00002172 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00002173 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00002174 Sqlite3_Init(interp);
drhd9b02572001-04-15 00:37:09 +00002175#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00002176 {
2177 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00002178 extern int Sqlitetest2_Init(Tcl_Interp*);
2179 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00002180 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00002181 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00002182 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00002183 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00002184 extern int Sqlitetest8_Init(Tcl_Interp*);
drhefc251d2001-07-01 22:12:01 +00002185 extern int Md5_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002186 extern int Sqlitetestsse_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00002187 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh4be8b512006-06-13 23:51:34 +00002188 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk1977954ce992006-06-15 15:59:19 +00002189 extern int Sqlitetestschema_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002190
danielk19776490beb2004-05-11 06:17:21 +00002191 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00002192 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00002193 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00002194 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00002195 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00002196 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00002197 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00002198 Sqlitetest8_Init(interp);
drh23669402006-01-09 17:29:52 +00002199 Sqlitetestasync_Init(interp);
drh4be8b512006-06-13 23:51:34 +00002200 Sqlitetesttclvar_Init(interp);
danielk1977954ce992006-06-15 15:59:19 +00002201 Sqlitetestschema_Init(interp);
drhefc251d2001-07-01 22:12:01 +00002202 Md5_Init(interp);
drh89dec812005-04-28 19:03:37 +00002203#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00002204 Sqlitetestsse_Init(interp);
2205#endif
drhd1bf3512001-04-07 15:24:33 +00002206 }
2207#endif
drh3e27c022004-07-23 00:01:38 +00002208 if( argc>=2 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002209 int i;
2210 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
2211 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00002212 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00002213 Tcl_SetVar(interp, "argv", argv[i],
2214 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
2215 }
drh3e27c022004-07-23 00:01:38 +00002216 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00002217 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drhc61053b2000-06-04 12:58:36 +00002218 if( zInfo==0 ) zInfo = interp->result;
2219 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00002220 return 1;
2221 }
drh3e27c022004-07-23 00:01:38 +00002222 }
2223 if( argc<=1 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002224 Tcl_GlobalEval(interp, zMainloop);
2225 }
2226 return 0;
2227}
2228#endif /* TCLSH */
drh6d313162000-09-21 13:01:35 +00002229
2230#endif /* !defined(NO_TCL) */