blob: b862df3f0a3b32e9f4d7bc9e8d6df88531af3ea3 [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**
danielk197794eb6a12005-12-15 15:22:08 +000014** $Id: tclsqlite.c,v 1.139 2005/12/15 15:22:10 danielk1977 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
drh29bc4612005-10-05 10:40:15 +000026/*
27 * Windows needs to know which symbols to export. Unix does not.
28 * BUILD_sqlite should be undefined for Unix.
29 */
30
31#ifdef BUILD_sqlite
32#undef TCL_STORAGE_CLASS
33#define TCL_STORAGE_CLASS DLLEXPORT
34#endif /* BUILD_sqlite */
35
danielk1977a21c6b62005-01-24 10:25:59 +000036#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000037#define MAX_PREPARED_STMTS 100
38
drh75897232000-05-29 14:26:00 +000039/*
drh98808ba2001-10-18 12:34:46 +000040** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
41** have to do a translation when going between the two. Set the
42** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
43** this translation.
44*/
45#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
46# define UTF_TRANSLATION_NEEDED 1
47#endif
48
49/*
drhcabb0812002-09-14 13:47:32 +000050** New SQL functions can be created as TCL scripts. Each such function
51** is described by an instance of the following structure.
52*/
53typedef struct SqlFunc SqlFunc;
54struct SqlFunc {
55 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000056 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
57 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
58 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000059 SqlFunc *pNext; /* Next function on the list of them all */
60};
61
62/*
danielk19770202b292004-06-09 09:55:16 +000063** New collation sequences function can be created as TCL scripts. Each such
64** function is described by an instance of the following structure.
65*/
66typedef struct SqlCollate SqlCollate;
67struct SqlCollate {
68 Tcl_Interp *interp; /* The TCL interpret to execute the function */
69 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000070 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000071};
72
73/*
drhfb7e7652005-01-24 00:28:42 +000074** Prepared statements are cached for faster execution. Each prepared
75** statement is described by an instance of the following structure.
76*/
77typedef struct SqlPreparedStmt SqlPreparedStmt;
78struct SqlPreparedStmt {
79 SqlPreparedStmt *pNext; /* Next in linked list */
80 SqlPreparedStmt *pPrev; /* Previous on the list */
81 sqlite3_stmt *pStmt; /* The prepared statement */
82 int nSql; /* chars in zSql[] */
83 char zSql[1]; /* Text of the SQL statement */
84};
85
86/*
drhbec3f402000-08-04 13:49:02 +000087** There is one instance of this structure for each SQLite database
88** that has been opened by the SQLite TCL interface.
89*/
90typedef struct SqliteDb SqliteDb;
91struct SqliteDb {
drhd1e47332005-06-26 17:55:33 +000092 sqlite3 *db; /* The "real" database structure */
93 Tcl_Interp *interp; /* The interpreter used for this database */
94 char *zBusy; /* The busy callback routine */
95 char *zCommit; /* The commit hook callback routine */
96 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +000097 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +000098 char *zProgress; /* The progress callback routine */
99 char *zAuth; /* The authorization callback routine */
100 char *zNull; /* Text to substitute for an SQL NULL value */
101 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000102 Tcl_Obj *pUpdateHook; /* Update 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 }
217 if( pDb->pCollateNeeded ){
218 Tcl_DecrRefCount(pDb->pCollateNeeded);
219 }
drhbec3f402000-08-04 13:49:02 +0000220 Tcl_Free((char*)pDb);
221}
222
223/*
224** This routine is called when a database file is locked while trying
225** to execute SQL.
226*/
danielk19772a764eb2004-06-12 01:43:26 +0000227static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000228 SqliteDb *pDb = (SqliteDb*)cd;
229 int rc;
230 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000231
danielk19772a764eb2004-06-12 01:43:26 +0000232 sprintf(zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000233 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000234 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
235 return 0;
236 }
237 return 1;
drh75897232000-05-29 14:26:00 +0000238}
239
240/*
danielk1977348bb5d2003-10-18 09:37:26 +0000241** This routine is invoked as the 'progress callback' for the database.
242*/
243static int DbProgressHandler(void *cd){
244 SqliteDb *pDb = (SqliteDb*)cd;
245 int rc;
246
247 assert( pDb->zProgress );
248 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
249 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
250 return 1;
251 }
252 return 0;
253}
254
255/*
drhb5a20d32003-04-23 12:25:23 +0000256** This routine is called by the SQLite trace handler whenever a new
257** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000258*/
drhb5a20d32003-04-23 12:25:23 +0000259static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000260 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000261 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000262
drhb5a20d32003-04-23 12:25:23 +0000263 Tcl_DStringInit(&str);
264 Tcl_DStringAppend(&str, pDb->zTrace, -1);
265 Tcl_DStringAppendElement(&str, zSql);
266 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
267 Tcl_DStringFree(&str);
268 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000269}
270
271/*
drh19e2d372005-08-29 23:00:03 +0000272** This routine is called by the SQLite profile handler after a statement
273** SQL has executed. The TCL script in pDb->zProfile is evaluated.
274*/
275static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
276 SqliteDb *pDb = (SqliteDb*)cd;
277 Tcl_DString str;
278 char zTm[100];
279
280 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
281 Tcl_DStringInit(&str);
282 Tcl_DStringAppend(&str, pDb->zProfile, -1);
283 Tcl_DStringAppendElement(&str, zSql);
284 Tcl_DStringAppendElement(&str, zTm);
285 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
286 Tcl_DStringFree(&str);
287 Tcl_ResetResult(pDb->interp);
288}
289
290/*
drhaa940ea2004-01-15 02:44:03 +0000291** This routine is called when a transaction is committed. The
292** TCL script in pDb->zCommit is executed. If it returns non-zero or
293** if it throws an exception, the transaction is rolled back instead
294** of being committed.
295*/
296static int DbCommitHandler(void *cd){
297 SqliteDb *pDb = (SqliteDb*)cd;
298 int rc;
299
300 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
301 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
302 return 1;
303 }
304 return 0;
305}
306
danielk197794eb6a12005-12-15 15:22:08 +0000307static void DbUpdateHandler(
308 void *p,
309 int op,
310 const char *zDb,
311 const char *zTbl,
312 sqlite_int64 rowid
313){
314 SqliteDb *pDb = (SqliteDb *)p;
315 Tcl_Obj *pCmd;
316
317 assert( pDb->pUpdateHook );
318 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
319
320 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
321 Tcl_IncrRefCount(pCmd);
322 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
323 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
324 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
325 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
326 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
327 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
328}
329
danielk19777cedc8d2004-06-10 10:50:08 +0000330static void tclCollateNeeded(
331 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000332 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000333 int enc,
334 const char *zName
335){
336 SqliteDb *pDb = (SqliteDb *)pCtx;
337 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
338 Tcl_IncrRefCount(pScript);
339 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
340 Tcl_EvalObjEx(pDb->interp, pScript, 0);
341 Tcl_DecrRefCount(pScript);
342}
343
drhaa940ea2004-01-15 02:44:03 +0000344/*
danielk19770202b292004-06-09 09:55:16 +0000345** This routine is called to evaluate an SQL collation function implemented
346** using TCL script.
347*/
348static int tclSqlCollate(
349 void *pCtx,
350 int nA,
351 const void *zA,
352 int nB,
353 const void *zB
354){
355 SqlCollate *p = (SqlCollate *)pCtx;
356 Tcl_Obj *pCmd;
357
358 pCmd = Tcl_NewStringObj(p->zScript, -1);
359 Tcl_IncrRefCount(pCmd);
360 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
361 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000362 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000363 Tcl_DecrRefCount(pCmd);
364 return (atoi(Tcl_GetStringResult(p->interp)));
365}
366
367/*
drhcabb0812002-09-14 13:47:32 +0000368** This routine is called to evaluate an SQL function implemented
369** using TCL script.
370*/
drhfb7e7652005-01-24 00:28:42 +0000371static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000372 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000373 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000374 int i;
375 int rc;
376
drhd1e47332005-06-26 17:55:33 +0000377 if( argc==0 ){
378 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
379 ** script object directly. This allows the TCL compiler to generate
380 ** bytecode for the command on the first invocation and thus make
381 ** subsequent invocations much faster. */
382 pCmd = p->pScript;
383 Tcl_IncrRefCount(pCmd);
384 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
385 Tcl_DecrRefCount(pCmd);
386 }else{
387 /* If there are arguments to the function, make a shallow copy of the
388 ** script object, lappend the arguments, then evaluate the copy.
389 **
390 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
391 ** The new Tcl_Obj contains pointers to the original list elements.
392 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
393 ** of the list to tclCmdNameType, that alternate representation will
394 ** be preserved and reused on the next invocation.
395 */
396 Tcl_Obj **aArg;
397 int nArg;
398 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
399 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
400 return;
401 }
402 pCmd = Tcl_NewListObj(nArg, aArg);
403 Tcl_IncrRefCount(pCmd);
404 for(i=0; i<argc; i++){
405 sqlite3_value *pIn = argv[i];
406 Tcl_Obj *pVal;
407
408 /* Set pVal to contain the i'th column of this row. */
409 switch( sqlite3_value_type(pIn) ){
410 case SQLITE_BLOB: {
411 int bytes = sqlite3_value_bytes(pIn);
412 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
413 break;
414 }
415 case SQLITE_INTEGER: {
416 sqlite_int64 v = sqlite3_value_int64(pIn);
417 if( v>=-2147483647 && v<=2147483647 ){
418 pVal = Tcl_NewIntObj(v);
419 }else{
420 pVal = Tcl_NewWideIntObj(v);
421 }
422 break;
423 }
424 case SQLITE_FLOAT: {
425 double r = sqlite3_value_double(pIn);
426 pVal = Tcl_NewDoubleObj(r);
427 break;
428 }
429 case SQLITE_NULL: {
430 pVal = Tcl_NewStringObj("", 0);
431 break;
432 }
433 default: {
434 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000435 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000436 break;
437 }
438 }
439 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
440 if( rc ){
441 Tcl_DecrRefCount(pCmd);
442 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
443 return;
444 }
danielk197751ad0ec2004-05-24 12:39:02 +0000445 }
drhd1e47332005-06-26 17:55:33 +0000446 if( !p->useEvalObjv ){
447 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
448 ** is a list without a string representation. To prevent this from
449 ** happening, make sure pCmd has a valid string representation */
450 Tcl_GetString(pCmd);
451 }
452 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
453 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000454 }
danielk1977562e8d32005-05-20 09:40:55 +0000455
drhc7f269d2005-05-05 10:30:29 +0000456 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000457 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000458 }else{
drhc7f269d2005-05-05 10:30:29 +0000459 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
460 int n;
461 u8 *data;
462 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
463 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000464 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000465 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000466 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000467 data = Tcl_GetByteArrayFromObj(pVar, &n);
468 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000469 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
470 (c=='i' && strcmp(zType,"int")==0) ){
471 Tcl_GetIntFromObj(0, pVar, &n);
472 sqlite3_result_int(context, n);
473 }else if( c=='d' && strcmp(zType,"double")==0 ){
474 double r;
475 Tcl_GetDoubleFromObj(0, pVar, &r);
476 sqlite3_result_double(context, r);
drhdf0bdda2005-06-25 19:31:48 +0000477 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
478 Tcl_WideInt v;
479 Tcl_GetWideIntFromObj(0, pVar, &v);
480 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000481 }else{
danielk197700fd9572005-12-07 06:27:43 +0000482 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
483 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000484 }
drhcabb0812002-09-14 13:47:32 +0000485 }
486}
drh895d7472004-08-20 16:02:39 +0000487
drhe22a3342003-04-22 20:30:37 +0000488#ifndef SQLITE_OMIT_AUTHORIZATION
489/*
490** This is the authentication function. It appends the authentication
491** type code and the two arguments to zCmd[] then invokes the result
492** on the interpreter. The reply is examined to determine if the
493** authentication fails or succeeds.
494*/
495static int auth_callback(
496 void *pArg,
497 int code,
498 const char *zArg1,
499 const char *zArg2,
500 const char *zArg3,
501 const char *zArg4
502){
503 char *zCode;
504 Tcl_DString str;
505 int rc;
506 const char *zReply;
507 SqliteDb *pDb = (SqliteDb*)pArg;
508
509 switch( code ){
510 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
511 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
512 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
513 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
514 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
515 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
516 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
517 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
518 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
519 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
520 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
521 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
522 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
523 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
524 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
525 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
526 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
527 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
528 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
529 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
530 case SQLITE_READ : zCode="SQLITE_READ"; break;
531 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
532 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
533 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000534 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
535 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000536 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000537 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000538 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
drhe22a3342003-04-22 20:30:37 +0000539 default : zCode="????"; break;
540 }
541 Tcl_DStringInit(&str);
542 Tcl_DStringAppend(&str, pDb->zAuth, -1);
543 Tcl_DStringAppendElement(&str, zCode);
544 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
545 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
546 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
547 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
548 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
549 Tcl_DStringFree(&str);
550 zReply = Tcl_GetStringResult(pDb->interp);
551 if( strcmp(zReply,"SQLITE_OK")==0 ){
552 rc = SQLITE_OK;
553 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
554 rc = SQLITE_DENY;
555 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
556 rc = SQLITE_IGNORE;
557 }else{
558 rc = 999;
559 }
560 return rc;
561}
562#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000563
564/*
danielk1977ef2cb632004-05-29 02:37:19 +0000565** zText is a pointer to text obtained via an sqlite3_result_text()
566** or similar interface. This routine returns a Tcl string object,
567** reference count set to 0, containing the text. If a translation
568** between iso8859 and UTF-8 is required, it is preformed.
569*/
570static Tcl_Obj *dbTextToObj(char const *zText){
571 Tcl_Obj *pVal;
572#ifdef UTF_TRANSLATION_NEEDED
573 Tcl_DString dCol;
574 Tcl_DStringInit(&dCol);
575 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
576 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
577 Tcl_DStringFree(&dCol);
578#else
579 pVal = Tcl_NewStringObj(zText, -1);
580#endif
581 return pVal;
582}
583
584/*
tpoindex1067fe12004-12-17 15:41:11 +0000585** This routine reads a line of text from FILE in, stores
586** the text in memory obtained from malloc() and returns a pointer
587** to the text. NULL is returned at end of file, or if malloc()
588** fails.
589**
590** The interface is like "readline" but no command-line editing
591** is done.
592**
593** copied from shell.c from '.import' command
594*/
595static char *local_getline(char *zPrompt, FILE *in){
596 char *zLine;
597 int nLine;
598 int n;
599 int eol;
600
601 nLine = 100;
602 zLine = malloc( nLine );
603 if( zLine==0 ) return 0;
604 n = 0;
605 eol = 0;
606 while( !eol ){
607 if( n+100>nLine ){
608 nLine = nLine*2 + 100;
609 zLine = realloc(zLine, nLine);
610 if( zLine==0 ) return 0;
611 }
612 if( fgets(&zLine[n], nLine - n, in)==0 ){
613 if( n==0 ){
614 free(zLine);
615 return 0;
616 }
617 zLine[n] = 0;
618 eol = 1;
619 break;
620 }
621 while( zLine[n] ){ n++; }
622 if( n>0 && zLine[n-1]=='\n' ){
623 n--;
624 zLine[n] = 0;
625 eol = 1;
626 }
627 }
628 zLine = realloc( zLine, n+1 );
629 return zLine;
630}
631
632/*
drh75897232000-05-29 14:26:00 +0000633** The "sqlite" command below creates a new Tcl command for each
634** connection it opens to an SQLite database. This routine is invoked
635** whenever one of those connection-specific commands is executed
636** in Tcl. For example, if you run Tcl code like this:
637**
drh9bb575f2004-09-06 17:24:11 +0000638** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +0000639** db1 close
640**
641** The first command opens a connection to the "my_database" database
642** and calls that connection "db1". The second command causes this
643** subroutine to be invoked.
644*/
drh6d313162000-09-21 13:01:35 +0000645static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +0000646 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +0000647 int choice;
drh22fbcb82004-02-01 01:22:50 +0000648 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +0000649 static const char *DB_strs[] = {
drhfb7e7652005-01-24 00:28:42 +0000650 "authorizer", "busy", "cache",
651 "changes", "close", "collate",
652 "collation_needed", "commit_hook", "complete",
653 "copy", "errorcode", "eval",
drh97f2ebc2005-12-10 21:19:04 +0000654 "exists", "function", "last_insert_rowid",
655 "nullvalue", "onecolumn", "profile",
danielk19777ddad962005-12-12 06:53:03 +0000656 "progress", "rekey", "soft_heap_limit",
657 "timeout", "total_changes", "trace",
danielk197794eb6a12005-12-15 15:22:08 +0000658 "transaction", "update_hook", "version",
659 0
drh6d313162000-09-21 13:01:35 +0000660 };
drh411995d2002-06-25 19:31:18 +0000661 enum DB_enum {
drhfb7e7652005-01-24 00:28:42 +0000662 DB_AUTHORIZER, DB_BUSY, DB_CACHE,
663 DB_CHANGES, DB_CLOSE, DB_COLLATE,
664 DB_COLLATION_NEEDED, DB_COMMIT_HOOK, DB_COMPLETE,
665 DB_COPY, DB_ERRORCODE, DB_EVAL,
drh97f2ebc2005-12-10 21:19:04 +0000666 DB_EXISTS, DB_FUNCTION, DB_LAST_INSERT_ROWID,
667 DB_NULLVALUE, DB_ONECOLUMN, DB_PROFILE,
danielk19777ddad962005-12-12 06:53:03 +0000668 DB_PROGRESS, DB_REKEY, DB_SOFT_HEAP_LIMIT,
669 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
danielk197794eb6a12005-12-15 15:22:08 +0000670 DB_TRANSACTION, DB_UPDATE_HOOK, DB_VERSION
drh6d313162000-09-21 13:01:35 +0000671 };
tpoindex1067fe12004-12-17 15:41:11 +0000672 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +0000673
674 if( objc<2 ){
675 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +0000676 return TCL_ERROR;
677 }
drh411995d2002-06-25 19:31:18 +0000678 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +0000679 return TCL_ERROR;
680 }
681
drh411995d2002-06-25 19:31:18 +0000682 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +0000683
drhe22a3342003-04-22 20:30:37 +0000684 /* $db authorizer ?CALLBACK?
685 **
686 ** Invoke the given callback to authorize each SQL operation as it is
687 ** compiled. 5 arguments are appended to the callback before it is
688 ** invoked:
689 **
690 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
691 ** (2) First descriptive name (depends on authorization type)
692 ** (3) Second descriptive name
693 ** (4) Name of the database (ex: "main", "temp")
694 ** (5) Name of trigger that is doing the access
695 **
696 ** The callback should return on of the following strings: SQLITE_OK,
697 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
698 **
699 ** If this method is invoked with no arguments, the current authorization
700 ** callback string is returned.
701 */
702 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +0000703#ifdef SQLITE_OMIT_AUTHORIZATION
704 Tcl_AppendResult(interp, "authorization not available in this build", 0);
705 return TCL_ERROR;
706#else
drhe22a3342003-04-22 20:30:37 +0000707 if( objc>3 ){
708 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +0000709 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +0000710 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +0000711 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +0000712 Tcl_AppendResult(interp, pDb->zAuth, 0);
713 }
714 }else{
715 char *zAuth;
716 int len;
717 if( pDb->zAuth ){
718 Tcl_Free(pDb->zAuth);
719 }
720 zAuth = Tcl_GetStringFromObj(objv[2], &len);
721 if( zAuth && len>0 ){
722 pDb->zAuth = Tcl_Alloc( len + 1 );
723 strcpy(pDb->zAuth, zAuth);
724 }else{
725 pDb->zAuth = 0;
726 }
drhe22a3342003-04-22 20:30:37 +0000727 if( pDb->zAuth ){
728 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000729 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +0000730 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000731 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +0000732 }
drhe22a3342003-04-22 20:30:37 +0000733 }
drh1211de32004-07-26 12:24:22 +0000734#endif
drhe22a3342003-04-22 20:30:37 +0000735 break;
736 }
737
drhbec3f402000-08-04 13:49:02 +0000738 /* $db busy ?CALLBACK?
739 **
740 ** Invoke the given callback if an SQL statement attempts to open
741 ** a locked database file.
742 */
drh6d313162000-09-21 13:01:35 +0000743 case DB_BUSY: {
744 if( objc>3 ){
745 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +0000746 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +0000747 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +0000748 if( pDb->zBusy ){
749 Tcl_AppendResult(interp, pDb->zBusy, 0);
750 }
751 }else{
drh6d313162000-09-21 13:01:35 +0000752 char *zBusy;
753 int len;
drhbec3f402000-08-04 13:49:02 +0000754 if( pDb->zBusy ){
755 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +0000756 }
drh6d313162000-09-21 13:01:35 +0000757 zBusy = Tcl_GetStringFromObj(objv[2], &len);
758 if( zBusy && len>0 ){
759 pDb->zBusy = Tcl_Alloc( len + 1 );
760 strcpy(pDb->zBusy, zBusy);
761 }else{
762 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +0000763 }
764 if( pDb->zBusy ){
765 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000766 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +0000767 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000768 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +0000769 }
770 }
drh6d313162000-09-21 13:01:35 +0000771 break;
772 }
drhbec3f402000-08-04 13:49:02 +0000773
drhfb7e7652005-01-24 00:28:42 +0000774 /* $db cache flush
775 ** $db cache size n
776 **
777 ** Flush the prepared statement cache, or set the maximum number of
778 ** cached statements.
779 */
780 case DB_CACHE: {
781 char *subCmd;
782 int n;
783
784 if( objc<=2 ){
785 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
786 return TCL_ERROR;
787 }
788 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
789 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
790 if( objc!=3 ){
791 Tcl_WrongNumArgs(interp, 2, objv, "flush");
792 return TCL_ERROR;
793 }else{
794 flushStmtCache( pDb );
795 }
796 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
797 if( objc!=4 ){
798 Tcl_WrongNumArgs(interp, 2, objv, "size n");
799 return TCL_ERROR;
800 }else{
801 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
802 Tcl_AppendResult( interp, "cannot convert \"",
803 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
804 return TCL_ERROR;
805 }else{
806 if( n<0 ){
807 flushStmtCache( pDb );
808 n = 0;
809 }else if( n>MAX_PREPARED_STMTS ){
810 n = MAX_PREPARED_STMTS;
811 }
812 pDb->maxStmt = n;
813 }
814 }
815 }else{
816 Tcl_AppendResult( interp, "bad option \"",
817 Tcl_GetStringFromObj(objv[0],0), "\": must be flush or size", 0);
818 return TCL_ERROR;
819 }
820 break;
821 }
822
danielk1977b28af712004-06-21 06:50:26 +0000823 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +0000824 **
825 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +0000826 ** the most recent INSERT, UPDATE or DELETE statement, not including
827 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +0000828 */
829 case DB_CHANGES: {
830 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +0000831 if( objc!=2 ){
832 Tcl_WrongNumArgs(interp, 2, objv, "");
833 return TCL_ERROR;
834 }
drhc8d30ac2002-04-12 10:08:59 +0000835 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +0000836 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +0000837 break;
838 }
839
drh75897232000-05-29 14:26:00 +0000840 /* $db close
841 **
842 ** Shutdown the database
843 */
drh6d313162000-09-21 13:01:35 +0000844 case DB_CLOSE: {
845 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
846 break;
847 }
drh75897232000-05-29 14:26:00 +0000848
drh0f14e2e2004-06-29 12:39:08 +0000849 /*
850 ** $db collate NAME SCRIPT
851 **
852 ** Create a new SQL collation function called NAME. Whenever
853 ** that function is called, invoke SCRIPT to evaluate the function.
854 */
855 case DB_COLLATE: {
856 SqlCollate *pCollate;
857 char *zName;
858 char *zScript;
859 int nScript;
860 if( objc!=4 ){
861 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
862 return TCL_ERROR;
863 }
864 zName = Tcl_GetStringFromObj(objv[2], 0);
865 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
866 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
867 if( pCollate==0 ) return TCL_ERROR;
868 pCollate->interp = interp;
869 pCollate->pNext = pDb->pCollate;
870 pCollate->zScript = (char*)&pCollate[1];
871 pDb->pCollate = pCollate;
872 strcpy(pCollate->zScript, zScript);
873 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
874 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +0000875 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +0000876 return TCL_ERROR;
877 }
878 break;
879 }
880
881 /*
882 ** $db collation_needed SCRIPT
883 **
884 ** Create a new SQL collation function called NAME. Whenever
885 ** that function is called, invoke SCRIPT to evaluate the function.
886 */
887 case DB_COLLATION_NEEDED: {
888 if( objc!=3 ){
889 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
890 return TCL_ERROR;
891 }
892 if( pDb->pCollateNeeded ){
893 Tcl_DecrRefCount(pDb->pCollateNeeded);
894 }
895 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
896 Tcl_IncrRefCount(pDb->pCollateNeeded);
897 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
898 break;
899 }
900
drh19e2d372005-08-29 23:00:03 +0000901 /* $db commit_hook ?CALLBACK?
902 **
903 ** Invoke the given callback just before committing every SQL transaction.
904 ** If the callback throws an exception or returns non-zero, then the
905 ** transaction is aborted. If CALLBACK is an empty string, the callback
906 ** is disabled.
907 */
908 case DB_COMMIT_HOOK: {
909 if( objc>3 ){
910 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
911 return TCL_ERROR;
912 }else if( objc==2 ){
913 if( pDb->zCommit ){
914 Tcl_AppendResult(interp, pDb->zCommit, 0);
915 }
916 }else{
917 char *zCommit;
918 int len;
919 if( pDb->zCommit ){
920 Tcl_Free(pDb->zCommit);
921 }
922 zCommit = Tcl_GetStringFromObj(objv[2], &len);
923 if( zCommit && len>0 ){
924 pDb->zCommit = Tcl_Alloc( len + 1 );
925 strcpy(pDb->zCommit, zCommit);
926 }else{
927 pDb->zCommit = 0;
928 }
929 if( pDb->zCommit ){
930 pDb->interp = interp;
931 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
932 }else{
933 sqlite3_commit_hook(pDb->db, 0, 0);
934 }
935 }
936 break;
937 }
938
drh75897232000-05-29 14:26:00 +0000939 /* $db complete SQL
940 **
941 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
942 ** additional lines of input are needed. This is similar to the
943 ** built-in "info complete" command of Tcl.
944 */
drh6d313162000-09-21 13:01:35 +0000945 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +0000946#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +0000947 Tcl_Obj *pResult;
948 int isComplete;
949 if( objc!=3 ){
950 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +0000951 return TCL_ERROR;
952 }
danielk19776f8a5032004-05-10 10:34:51 +0000953 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +0000954 pResult = Tcl_GetObjResult(interp);
955 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +0000956#endif
drh6d313162000-09-21 13:01:35 +0000957 break;
958 }
drhdcd997e2003-01-31 17:21:49 +0000959
drh19e2d372005-08-29 23:00:03 +0000960 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
961 **
962 ** Copy data into table from filename, optionally using SEPARATOR
963 ** as column separators. If a column contains a null string, or the
964 ** value of NULLINDICATOR, a NULL is inserted for the column.
965 ** conflict-algorithm is one of the sqlite conflict algorithms:
966 ** rollback, abort, fail, ignore, replace
967 ** On success, return the number of lines processed, not necessarily same
968 ** as 'db changes' due to conflict-algorithm selected.
969 **
970 ** This code is basically an implementation/enhancement of
971 ** the sqlite3 shell.c ".import" command.
972 **
973 ** This command usage is equivalent to the sqlite2.x COPY statement,
974 ** which imports file data into a table using the PostgreSQL COPY file format:
975 ** $db copy $conflit_algo $table_name $filename \t \\N
976 */
977 case DB_COPY: {
978 char *zTable; /* Insert data into this table */
979 char *zFile; /* The file from which to extract data */
980 char *zConflict; /* The conflict algorithm to use */
981 sqlite3_stmt *pStmt; /* A statement */
982 int rc; /* Result code */
983 int nCol; /* Number of columns in the table */
984 int nByte; /* Number of bytes in an SQL string */
985 int i, j; /* Loop counters */
986 int nSep; /* Number of bytes in zSep[] */
987 int nNull; /* Number of bytes in zNull[] */
988 char *zSql; /* An SQL statement */
989 char *zLine; /* A single line of input from the file */
990 char **azCol; /* zLine[] broken up into columns */
991 char *zCommit; /* How to commit changes */
992 FILE *in; /* The input file */
993 int lineno = 0; /* Line number of input file */
994 char zLineNum[80]; /* Line number print buffer */
995 Tcl_Obj *pResult; /* interp result */
996
997 char *zSep;
998 char *zNull;
999 if( objc<5 || objc>7 ){
1000 Tcl_WrongNumArgs(interp, 2, objv,
1001 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1002 return TCL_ERROR;
1003 }
1004 if( objc>=6 ){
1005 zSep = Tcl_GetStringFromObj(objv[5], 0);
1006 }else{
1007 zSep = "\t";
1008 }
1009 if( objc>=7 ){
1010 zNull = Tcl_GetStringFromObj(objv[6], 0);
1011 }else{
1012 zNull = "";
1013 }
1014 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1015 zTable = Tcl_GetStringFromObj(objv[3], 0);
1016 zFile = Tcl_GetStringFromObj(objv[4], 0);
1017 nSep = strlen(zSep);
1018 nNull = strlen(zNull);
1019 if( nSep==0 ){
1020 Tcl_AppendResult(interp, "Error: non-null separator required for copy", 0);
1021 return TCL_ERROR;
1022 }
1023 if(sqlite3StrICmp(zConflict, "rollback") != 0 &&
1024 sqlite3StrICmp(zConflict, "abort" ) != 0 &&
1025 sqlite3StrICmp(zConflict, "fail" ) != 0 &&
1026 sqlite3StrICmp(zConflict, "ignore" ) != 0 &&
1027 sqlite3StrICmp(zConflict, "replace" ) != 0 ) {
1028 Tcl_AppendResult(interp, "Error: \"", zConflict,
1029 "\", conflict-algorithm must be one of: rollback, "
1030 "abort, fail, ignore, or replace", 0);
1031 return TCL_ERROR;
1032 }
1033 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1034 if( zSql==0 ){
1035 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1036 return TCL_ERROR;
1037 }
1038 nByte = strlen(zSql);
1039 rc = sqlite3_prepare(pDb->db, zSql, 0, &pStmt, 0);
1040 sqlite3_free(zSql);
1041 if( rc ){
1042 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1043 nCol = 0;
1044 }else{
1045 nCol = sqlite3_column_count(pStmt);
1046 }
1047 sqlite3_finalize(pStmt);
1048 if( nCol==0 ) {
1049 return TCL_ERROR;
1050 }
1051 zSql = malloc( nByte + 50 + nCol*2 );
1052 if( zSql==0 ) {
1053 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1054 return TCL_ERROR;
1055 }
1056 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1057 zConflict, zTable);
1058 j = strlen(zSql);
1059 for(i=1; i<nCol; i++){
1060 zSql[j++] = ',';
1061 zSql[j++] = '?';
1062 }
1063 zSql[j++] = ')';
1064 zSql[j] = 0;
1065 rc = sqlite3_prepare(pDb->db, zSql, 0, &pStmt, 0);
1066 free(zSql);
1067 if( rc ){
1068 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1069 sqlite3_finalize(pStmt);
1070 return TCL_ERROR;
1071 }
1072 in = fopen(zFile, "rb");
1073 if( in==0 ){
1074 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
1075 sqlite3_finalize(pStmt);
1076 return TCL_ERROR;
1077 }
1078 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1079 if( azCol==0 ) {
1080 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1081 return TCL_ERROR;
1082 }
1083 sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
1084 zCommit = "COMMIT";
1085 while( (zLine = local_getline(0, in))!=0 ){
1086 char *z;
1087 i = 0;
1088 lineno++;
1089 azCol[0] = zLine;
1090 for(i=0, z=zLine; *z; z++){
1091 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
1092 *z = 0;
1093 i++;
1094 if( i<nCol ){
1095 azCol[i] = &z[nSep];
1096 z += nSep-1;
1097 }
1098 }
1099 }
1100 if( i+1!=nCol ){
1101 char *zErr;
1102 zErr = malloc(200 + strlen(zFile));
1103 sprintf(zErr,"Error: %s line %d: expected %d columns of data but found %d",
1104 zFile, lineno, nCol, i+1);
1105 Tcl_AppendResult(interp, zErr, 0);
1106 free(zErr);
1107 zCommit = "ROLLBACK";
1108 break;
1109 }
1110 for(i=0; i<nCol; i++){
1111 /* check for null data, if so, bind as null */
1112 if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
1113 sqlite3_bind_null(pStmt, i+1);
1114 }else{
1115 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1116 }
1117 }
1118 sqlite3_step(pStmt);
1119 rc = sqlite3_reset(pStmt);
1120 free(zLine);
1121 if( rc!=SQLITE_OK ){
1122 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
1123 zCommit = "ROLLBACK";
1124 break;
1125 }
1126 }
1127 free(azCol);
1128 fclose(in);
1129 sqlite3_finalize(pStmt);
1130 sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
1131
1132 if( zCommit[0] == 'C' ){
1133 /* success, set result as number of lines processed */
1134 pResult = Tcl_GetObjResult(interp);
1135 Tcl_SetIntObj(pResult, lineno);
1136 rc = TCL_OK;
1137 }else{
1138 /* failure, append lineno where failed */
1139 sprintf(zLineNum,"%d",lineno);
1140 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
1141 rc = TCL_ERROR;
1142 }
1143 break;
1144 }
1145
drhdcd997e2003-01-31 17:21:49 +00001146 /*
1147 ** $db errorcode
1148 **
1149 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00001150 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00001151 */
1152 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00001153 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00001154 break;
1155 }
drh75897232000-05-29 14:26:00 +00001156
1157 /*
drh895d7472004-08-20 16:02:39 +00001158 ** $db eval $sql ?array? ?{ ...code... }?
drh1807ce32004-09-07 13:20:35 +00001159 ** $db onecolumn $sql
drh75897232000-05-29 14:26:00 +00001160 **
1161 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00001162 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00001163 ** If "array" and "code" are omitted, then no callback is every invoked.
1164 ** If "array" is an empty string, then the values are placed in variables
1165 ** that have the same name as the fields extracted by the query.
drh1807ce32004-09-07 13:20:35 +00001166 **
1167 ** The onecolumn method is the equivalent of:
1168 ** lindex [$db eval $sql] 0
drh75897232000-05-29 14:26:00 +00001169 */
drh1807ce32004-09-07 13:20:35 +00001170 case DB_ONECOLUMN:
drh97f2ebc2005-12-10 21:19:04 +00001171 case DB_EVAL:
1172 case DB_EXISTS: {
drh9d74b4c2004-08-24 15:23:34 +00001173 char const *zSql; /* Next SQL statement to execute */
1174 char const *zLeft; /* What is left after first stmt in zSql */
1175 sqlite3_stmt *pStmt; /* Compiled SQL statment */
drh92febd92004-08-20 18:34:20 +00001176 Tcl_Obj *pArray; /* Name of array into which results are written */
1177 Tcl_Obj *pScript; /* Script to run for each result set */
drh1d895032004-08-26 00:56:05 +00001178 Tcl_Obj **apParm; /* Parameters that need a Tcl_DecrRefCount() */
1179 int nParm; /* Number of entries used in apParm[] */
1180 Tcl_Obj *aParm[10]; /* Static space for apParm[] in the common case */
drh1807ce32004-09-07 13:20:35 +00001181 Tcl_Obj *pRet; /* Value to be returned */
drhfb7e7652005-01-24 00:28:42 +00001182 SqlPreparedStmt *pPreStmt; /* Pointer to a prepared statement */
1183 int rc2;
danielk1977ef2cb632004-05-29 02:37:19 +00001184
drh97f2ebc2005-12-10 21:19:04 +00001185 if( choice==DB_EVAL ){
drh1807ce32004-09-07 13:20:35 +00001186 if( objc<3 || objc>5 ){
1187 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
1188 return TCL_ERROR;
1189 }
1190 pRet = Tcl_NewObj();
1191 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001192 }else{
1193 if( objc!=3 ){
1194 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
1195 return TCL_ERROR;
1196 }
1197 pRet = 0;
1198 if( choice==DB_EXISTS ){
1199 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(0));
1200 }
danielk197730ccda12004-05-27 12:11:31 +00001201 }
drh92febd92004-08-20 18:34:20 +00001202 if( objc==3 ){
1203 pArray = pScript = 0;
1204 }else if( objc==4 ){
1205 pArray = 0;
1206 pScript = objv[3];
1207 }else{
1208 pArray = objv[3];
1209 if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
1210 pScript = objv[4];
1211 }
danielk197730ccda12004-05-27 12:11:31 +00001212
drh1d895032004-08-26 00:56:05 +00001213 Tcl_IncrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001214 zSql = Tcl_GetStringFromObj(objv[2], 0);
drh90b6bb12004-09-13 13:16:31 +00001215 while( rc==TCL_OK && zSql[0] ){
drhfb7e7652005-01-24 00:28:42 +00001216 int i; /* Loop counter */
1217 int nVar; /* Number of bind parameters in the pStmt */
1218 int nCol; /* Number of columns in the result set */
drh92febd92004-08-20 18:34:20 +00001219 Tcl_Obj **apColName = 0; /* Array of column names */
drhfb7e7652005-01-24 00:28:42 +00001220 int len; /* String length of zSql */
danielk197730ccda12004-05-27 12:11:31 +00001221
drhfb7e7652005-01-24 00:28:42 +00001222 /* Try to find a SQL statement that has already been compiled and
1223 ** which matches the next sequence of SQL.
1224 */
1225 pStmt = 0;
1226 pPreStmt = pDb->stmtList;
1227 len = strlen(zSql);
1228 if( pPreStmt && sqlite3_expired(pPreStmt->pStmt) ){
1229 flushStmtCache(pDb);
1230 pPreStmt = 0;
danielk197730ccda12004-05-27 12:11:31 +00001231 }
drhfb7e7652005-01-24 00:28:42 +00001232 for(; pPreStmt; pPreStmt=pPreStmt->pNext){
1233 int n = pPreStmt->nSql;
1234 if( len>=n
1235 && memcmp(pPreStmt->zSql, zSql, n)==0
1236 && (zSql[n]==0 || zSql[n-1]==';')
1237 ){
1238 pStmt = pPreStmt->pStmt;
1239 zLeft = &zSql[pPreStmt->nSql];
1240
1241 /* When a prepared statement is found, unlink it from the
1242 ** cache list. It will later be added back to the beginning
1243 ** of the cache list in order to implement LRU replacement.
1244 */
1245 if( pPreStmt->pPrev ){
1246 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1247 }else{
1248 pDb->stmtList = pPreStmt->pNext;
1249 }
1250 if( pPreStmt->pNext ){
1251 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1252 }else{
1253 pDb->stmtLast = pPreStmt->pPrev;
1254 }
1255 pDb->nStmt--;
1256 break;
1257 }
1258 }
1259
1260 /* If no prepared statement was found. Compile the SQL text
1261 */
drh92febd92004-08-20 18:34:20 +00001262 if( pStmt==0 ){
drhfb7e7652005-01-24 00:28:42 +00001263 if( SQLITE_OK!=sqlite3_prepare(pDb->db, zSql, -1, &pStmt, &zLeft) ){
drh92febd92004-08-20 18:34:20 +00001264 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1265 rc = TCL_ERROR;
1266 break;
danielk197730ccda12004-05-27 12:11:31 +00001267 }
drhfb7e7652005-01-24 00:28:42 +00001268 if( pStmt==0 ){
1269 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1270 /* A compile-time error in the statement
1271 */
1272 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1273 rc = TCL_ERROR;
1274 break;
1275 }else{
1276 /* The statement was a no-op. Continue to the next statement
1277 ** in the SQL string.
1278 */
1279 zSql = zLeft;
1280 continue;
1281 }
1282 }
1283 assert( pPreStmt==0 );
danielk197730ccda12004-05-27 12:11:31 +00001284 }
1285
drhfb7e7652005-01-24 00:28:42 +00001286 /* Bind values to parameters that begin with $ or :
1287 */
drh92febd92004-08-20 18:34:20 +00001288 nVar = sqlite3_bind_parameter_count(pStmt);
drh1d895032004-08-26 00:56:05 +00001289 nParm = 0;
1290 if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
1291 apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
1292 }else{
1293 apParm = aParm;
1294 }
drh92febd92004-08-20 18:34:20 +00001295 for(i=1; i<=nVar; i++){
1296 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
drhc8f90792005-01-12 00:08:24 +00001297 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':') ){
drh92febd92004-08-20 18:34:20 +00001298 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1299 if( pVar ){
1300 int n;
1301 u8 *data;
1302 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
1303 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +00001304 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
1305 /* Only load a BLOB type if the Tcl variable is a bytearray and
1306 ** has no string representation. */
drh92febd92004-08-20 18:34:20 +00001307 data = Tcl_GetByteArrayFromObj(pVar, &n);
1308 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001309 Tcl_IncrRefCount(pVar);
1310 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001311 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
1312 (c=='i' && strcmp(zType,"int")==0) ){
1313 Tcl_GetIntFromObj(interp, pVar, &n);
1314 sqlite3_bind_int(pStmt, i, n);
1315 }else if( c=='d' && strcmp(zType,"double")==0 ){
1316 double r;
1317 Tcl_GetDoubleFromObj(interp, pVar, &r);
1318 sqlite3_bind_double(pStmt, i, r);
drhdf0bdda2005-06-25 19:31:48 +00001319 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
1320 Tcl_WideInt v;
1321 Tcl_GetWideIntFromObj(interp, pVar, &v);
1322 sqlite3_bind_int64(pStmt, i, v);
drh92febd92004-08-20 18:34:20 +00001323 }else{
danielk197700fd9572005-12-07 06:27:43 +00001324 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1325 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001326 Tcl_IncrRefCount(pVar);
1327 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001328 }
drhfb7e7652005-01-24 00:28:42 +00001329 }else{
1330 sqlite3_bind_null( pStmt, i );
drh92febd92004-08-20 18:34:20 +00001331 }
1332 }
1333 }
drh92febd92004-08-20 18:34:20 +00001334
1335 /* Compute column names */
1336 nCol = sqlite3_column_count(pStmt);
1337 if( pScript ){
1338 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1339 if( apColName==0 ) break;
1340 for(i=0; i<nCol; i++){
1341 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1342 Tcl_IncrRefCount(apColName[i]);
1343 }
1344 }
1345
1346 /* If results are being stored in an array variable, then create
1347 ** the array(*) entry for that array
1348 */
1349 if( pArray ){
1350 Tcl_Obj *pColList = Tcl_NewObj();
drh3ced14a2005-03-31 18:26:20 +00001351 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
drh92febd92004-08-20 18:34:20 +00001352 Tcl_IncrRefCount(pColList);
1353 for(i=0; i<nCol; i++){
1354 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1355 }
drh3ced14a2005-03-31 18:26:20 +00001356 Tcl_ObjSetVar2(interp, pArray, pStar, pColList,0);
1357 Tcl_DecrRefCount(pColList);
1358 Tcl_DecrRefCount(pStar);
drh92febd92004-08-20 18:34:20 +00001359 }
1360
1361 /* Execute the SQL
1362 */
drh90b6bb12004-09-13 13:16:31 +00001363 while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
drh92febd92004-08-20 18:34:20 +00001364 for(i=0; i<nCol; i++){
danielk197730ccda12004-05-27 12:11:31 +00001365 Tcl_Obj *pVal;
1366
1367 /* Set pVal to contain the i'th column of this row. */
drh92febd92004-08-20 18:34:20 +00001368 switch( sqlite3_column_type(pStmt, i) ){
1369 case SQLITE_BLOB: {
1370 int bytes = sqlite3_column_bytes(pStmt, i);
1371 pVal = Tcl_NewByteArrayObj(sqlite3_column_blob(pStmt, i), bytes);
1372 break;
1373 }
1374 case SQLITE_INTEGER: {
1375 sqlite_int64 v = sqlite3_column_int64(pStmt, i);
1376 if( v>=-2147483647 && v<=2147483647 ){
1377 pVal = Tcl_NewIntObj(v);
1378 }else{
1379 pVal = Tcl_NewWideIntObj(v);
1380 }
1381 break;
1382 }
1383 case SQLITE_FLOAT: {
1384 double r = sqlite3_column_double(pStmt, i);
1385 pVal = Tcl_NewDoubleObj(r);
1386 break;
1387 }
danielk197755c45f22005-04-03 23:54:43 +00001388 case SQLITE_NULL: {
1389 pVal = dbTextToObj(pDb->zNull);
1390 break;
1391 }
drh92febd92004-08-20 18:34:20 +00001392 default: {
danielk197700fd9572005-12-07 06:27:43 +00001393 pVal = dbTextToObj((char *)sqlite3_column_text(pStmt, i));
drh92febd92004-08-20 18:34:20 +00001394 break;
1395 }
danielk197730ccda12004-05-27 12:11:31 +00001396 }
1397
drh92febd92004-08-20 18:34:20 +00001398 if( pScript ){
1399 if( pArray==0 ){
1400 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001401 }else{
drh92febd92004-08-20 18:34:20 +00001402 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001403 }
drh1807ce32004-09-07 13:20:35 +00001404 }else if( choice==DB_ONECOLUMN ){
drh97f2ebc2005-12-10 21:19:04 +00001405 assert( pRet==0 );
drh1807ce32004-09-07 13:20:35 +00001406 if( pRet==0 ){
1407 pRet = pVal;
1408 Tcl_IncrRefCount(pRet);
1409 }
drh90b6bb12004-09-13 13:16:31 +00001410 rc = TCL_BREAK;
drh97f2ebc2005-12-10 21:19:04 +00001411 i = nCol;
1412 }else if( choice==DB_EXISTS ){
1413 assert( pRet==0 );
1414 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(1));
1415 rc = TCL_BREAK;
1416 i = nCol;
danielk197730ccda12004-05-27 12:11:31 +00001417 }else{
danielk197730ccda12004-05-27 12:11:31 +00001418 Tcl_ListObjAppendElement(interp, pRet, pVal);
1419 }
1420 }
1421
drh92febd92004-08-20 18:34:20 +00001422 if( pScript ){
1423 rc = Tcl_EvalObjEx(interp, pScript, 0);
drh90b6bb12004-09-13 13:16:31 +00001424 if( rc==TCL_CONTINUE ){
1425 rc = TCL_OK;
1426 }
danielk197730ccda12004-05-27 12:11:31 +00001427 }
1428 }
drh90b6bb12004-09-13 13:16:31 +00001429 if( rc==TCL_BREAK ){
1430 rc = TCL_OK;
1431 }
drh92febd92004-08-20 18:34:20 +00001432
1433 /* Free the column name objects */
1434 if( pScript ){
1435 for(i=0; i<nCol; i++){
1436 Tcl_DecrRefCount(apColName[i]);
1437 }
1438 Tcl_Free((char*)apColName);
1439 }
1440
drh1d895032004-08-26 00:56:05 +00001441 /* Free the bound string and blob parameters */
1442 for(i=0; i<nParm; i++){
1443 Tcl_DecrRefCount(apParm[i]);
1444 }
1445 if( apParm!=aParm ){
1446 Tcl_Free((char*)apParm);
1447 }
1448
drhfb7e7652005-01-24 00:28:42 +00001449 /* Reset the statement. If the result code is SQLITE_SCHEMA, then
1450 ** flush the statement cache and try the statement again.
drh92febd92004-08-20 18:34:20 +00001451 */
drhfb7e7652005-01-24 00:28:42 +00001452 rc2 = sqlite3_reset(pStmt);
1453 if( SQLITE_SCHEMA==rc2 ){
1454 /* After a schema change, flush the cache and try to run the
1455 ** statement again
1456 */
1457 flushStmtCache( pDb );
1458 sqlite3_finalize(pStmt);
1459 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001460 continue;
drhfb7e7652005-01-24 00:28:42 +00001461 }else if( SQLITE_OK!=rc2 ){
1462 /* If a run-time error occurs, report the error and stop reading
1463 ** the SQL
1464 */
danielk1977ef2cb632004-05-29 02:37:19 +00001465 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
drhfb7e7652005-01-24 00:28:42 +00001466 sqlite3_finalize(pStmt);
danielk197730ccda12004-05-27 12:11:31 +00001467 rc = TCL_ERROR;
drhfb7e7652005-01-24 00:28:42 +00001468 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001469 break;
drhfb7e7652005-01-24 00:28:42 +00001470 }else if( pDb->maxStmt<=0 ){
1471 /* If the cache is turned off, deallocated the statement */
1472 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1473 sqlite3_finalize(pStmt);
1474 }else{
1475 /* Everything worked and the cache is operational.
1476 ** Create a new SqlPreparedStmt structure if we need one.
1477 ** (If we already have one we can just reuse it.)
1478 */
1479 if( pPreStmt==0 ){
1480 len = zLeft - zSql;
1481 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) + len );
1482 if( pPreStmt==0 ) return TCL_ERROR;
1483 pPreStmt->pStmt = pStmt;
1484 pPreStmt->nSql = len;
1485 memcpy(pPreStmt->zSql, zSql, len);
1486 pPreStmt->zSql[len] = 0;
1487 }
1488
1489 /* Add the prepared statement to the beginning of the cache list
1490 */
1491 pPreStmt->pNext = pDb->stmtList;
1492 pPreStmt->pPrev = 0;
1493 if( pDb->stmtList ){
1494 pDb->stmtList->pPrev = pPreStmt;
1495 }
1496 pDb->stmtList = pPreStmt;
1497 if( pDb->stmtLast==0 ){
1498 assert( pDb->nStmt==0 );
1499 pDb->stmtLast = pPreStmt;
1500 }else{
1501 assert( pDb->nStmt>0 );
1502 }
1503 pDb->nStmt++;
1504
1505 /* If we have too many statement in cache, remove the surplus from the
1506 ** end of the cache list.
1507 */
1508 while( pDb->nStmt>pDb->maxStmt ){
1509 sqlite3_finalize(pDb->stmtLast->pStmt);
1510 pDb->stmtLast = pDb->stmtLast->pPrev;
1511 Tcl_Free((char*)pDb->stmtLast->pNext);
1512 pDb->stmtLast->pNext = 0;
1513 pDb->nStmt--;
1514 }
danielk197730ccda12004-05-27 12:11:31 +00001515 }
1516
drhfb7e7652005-01-24 00:28:42 +00001517 /* Proceed to the next statement */
danielk197730ccda12004-05-27 12:11:31 +00001518 zSql = zLeft;
1519 }
drh1d895032004-08-26 00:56:05 +00001520 Tcl_DecrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001521
drh1807ce32004-09-07 13:20:35 +00001522 if( pRet ){
1523 if( rc==TCL_OK ){
1524 Tcl_SetObjResult(interp, pRet);
1525 }
1526 Tcl_DecrRefCount(pRet);
danielk197730ccda12004-05-27 12:11:31 +00001527 }
danielk197730ccda12004-05-27 12:11:31 +00001528 break;
1529 }
drhbec3f402000-08-04 13:49:02 +00001530
1531 /*
drhcabb0812002-09-14 13:47:32 +00001532 ** $db function NAME SCRIPT
1533 **
1534 ** Create a new SQL function called NAME. Whenever that function is
1535 ** called, invoke SCRIPT to evaluate the function.
1536 */
1537 case DB_FUNCTION: {
1538 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00001539 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00001540 char *zName;
drhcabb0812002-09-14 13:47:32 +00001541 if( objc!=4 ){
1542 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1543 return TCL_ERROR;
1544 }
1545 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00001546 pScript = objv[3];
1547 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00001548 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00001549 if( pFunc->pScript ){
1550 Tcl_DecrRefCount(pFunc->pScript);
1551 }
1552 pFunc->pScript = pScript;
1553 Tcl_IncrRefCount(pScript);
1554 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
danielk1977c8c11582004-06-29 13:41:21 +00001555 rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00001556 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00001557 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00001558 rc = TCL_ERROR;
1559 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00001560 }else{
1561 /* Must flush any cached statements */
1562 flushStmtCache( pDb );
1563 }
drhcabb0812002-09-14 13:47:32 +00001564 break;
1565 }
1566
1567 /*
drh19e2d372005-08-29 23:00:03 +00001568 ** $db nullvalue ?STRING?
1569 **
1570 ** Change text used when a NULL comes back from the database. If ?STRING?
1571 ** is not present, then the current string used for NULL is returned.
1572 ** If STRING is present, then STRING is returned.
1573 **
1574 */
1575 case DB_NULLVALUE: {
1576 if( objc!=2 && objc!=3 ){
1577 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
1578 return TCL_ERROR;
1579 }
1580 if( objc==3 ){
1581 int len;
1582 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
1583 if( pDb->zNull ){
1584 Tcl_Free(pDb->zNull);
1585 }
1586 if( zNull && len>0 ){
1587 pDb->zNull = Tcl_Alloc( len + 1 );
1588 strncpy(pDb->zNull, zNull, len);
1589 pDb->zNull[len] = '\0';
1590 }else{
1591 pDb->zNull = 0;
1592 }
1593 }
1594 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
1595 break;
1596 }
1597
1598 /*
drhaf9ff332002-01-16 21:00:27 +00001599 ** $db last_insert_rowid
1600 **
1601 ** Return an integer which is the ROWID for the most recent insert.
1602 */
1603 case DB_LAST_INSERT_ROWID: {
1604 Tcl_Obj *pResult;
1605 int rowid;
1606 if( objc!=2 ){
1607 Tcl_WrongNumArgs(interp, 2, objv, "");
1608 return TCL_ERROR;
1609 }
danielk19776f8a5032004-05-10 10:34:51 +00001610 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00001611 pResult = Tcl_GetObjResult(interp);
1612 Tcl_SetIntObj(pResult, rowid);
1613 break;
1614 }
1615
1616 /*
drh1807ce32004-09-07 13:20:35 +00001617 ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
drh5d9d7572003-08-19 14:31:01 +00001618 */
drh1807ce32004-09-07 13:20:35 +00001619
1620 /* $db progress ?N CALLBACK?
1621 **
1622 ** Invoke the given callback every N virtual machine opcodes while executing
1623 ** queries.
1624 */
1625 case DB_PROGRESS: {
1626 if( objc==2 ){
1627 if( pDb->zProgress ){
1628 Tcl_AppendResult(interp, pDb->zProgress, 0);
1629 }
1630 }else if( objc==4 ){
1631 char *zProgress;
1632 int len;
1633 int N;
1634 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
1635 return TCL_ERROR;
1636 };
1637 if( pDb->zProgress ){
1638 Tcl_Free(pDb->zProgress);
1639 }
1640 zProgress = Tcl_GetStringFromObj(objv[3], &len);
1641 if( zProgress && len>0 ){
1642 pDb->zProgress = Tcl_Alloc( len + 1 );
1643 strcpy(pDb->zProgress, zProgress);
1644 }else{
1645 pDb->zProgress = 0;
1646 }
1647#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1648 if( pDb->zProgress ){
1649 pDb->interp = interp;
1650 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
1651 }else{
1652 sqlite3_progress_handler(pDb->db, 0, 0, 0);
1653 }
1654#endif
1655 }else{
1656 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00001657 return TCL_ERROR;
1658 }
drh5d9d7572003-08-19 14:31:01 +00001659 break;
1660 }
1661
drh19e2d372005-08-29 23:00:03 +00001662 /* $db profile ?CALLBACK?
1663 **
1664 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
1665 ** that has run. The text of the SQL and the amount of elapse time are
1666 ** appended to CALLBACK before the script is run.
1667 */
1668 case DB_PROFILE: {
1669 if( objc>3 ){
1670 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1671 return TCL_ERROR;
1672 }else if( objc==2 ){
1673 if( pDb->zProfile ){
1674 Tcl_AppendResult(interp, pDb->zProfile, 0);
1675 }
1676 }else{
1677 char *zProfile;
1678 int len;
1679 if( pDb->zProfile ){
1680 Tcl_Free(pDb->zProfile);
1681 }
1682 zProfile = Tcl_GetStringFromObj(objv[2], &len);
1683 if( zProfile && len>0 ){
1684 pDb->zProfile = Tcl_Alloc( len + 1 );
1685 strcpy(pDb->zProfile, zProfile);
1686 }else{
1687 pDb->zProfile = 0;
1688 }
1689#ifndef SQLITE_OMIT_TRACE
1690 if( pDb->zProfile ){
1691 pDb->interp = interp;
1692 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
1693 }else{
1694 sqlite3_profile(pDb->db, 0, 0);
1695 }
1696#endif
1697 }
1698 break;
1699 }
1700
drh5d9d7572003-08-19 14:31:01 +00001701 /*
drh22fbcb82004-02-01 01:22:50 +00001702 ** $db rekey KEY
1703 **
1704 ** Change the encryption key on the currently open database.
1705 */
1706 case DB_REKEY: {
1707 int nKey;
1708 void *pKey;
1709 if( objc!=3 ){
1710 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
1711 return TCL_ERROR;
1712 }
1713 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00001714#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00001715 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00001716 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00001717 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00001718 rc = TCL_ERROR;
1719 }
1720#endif
1721 break;
1722 }
1723
1724 /*
drhbec3f402000-08-04 13:49:02 +00001725 ** $db timeout MILLESECONDS
1726 **
1727 ** Delay for the number of milliseconds specified when a file is locked.
1728 */
drh6d313162000-09-21 13:01:35 +00001729 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00001730 int ms;
drh6d313162000-09-21 13:01:35 +00001731 if( objc!=3 ){
1732 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00001733 return TCL_ERROR;
1734 }
drh6d313162000-09-21 13:01:35 +00001735 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00001736 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00001737 break;
drh75897232000-05-29 14:26:00 +00001738 }
danielk19777ddad962005-12-12 06:53:03 +00001739
1740 /*
1741 ** $db soft_heap_limit N
1742 **
1743 ** Set the soft-heap-limit for this thread. Note that the limit is
1744 ** per-thread, not per-database.
1745 */
1746 case DB_SOFT_HEAP_LIMIT: {
1747 int n;
1748 if( objc!=3 ){
1749 Tcl_WrongNumArgs(interp, 2, objv, "BYTES");
1750 return TCL_ERROR;
1751 }
1752 if( Tcl_GetIntFromObj(interp, objv[2], &n) ){
1753 return TCL_ERROR;
1754 }
1755 sqlite3_soft_heap_limit(n);
1756 Tcl_ResetResult(interp);
1757 break;
1758 }
danielk197755c45f22005-04-03 23:54:43 +00001759
1760 /*
drh0f14e2e2004-06-29 12:39:08 +00001761 ** $db total_changes
1762 **
1763 ** Return the number of rows that were modified, inserted, or deleted
1764 ** since the database handle was created.
1765 */
1766 case DB_TOTAL_CHANGES: {
1767 Tcl_Obj *pResult;
1768 if( objc!=2 ){
1769 Tcl_WrongNumArgs(interp, 2, objv, "");
1770 return TCL_ERROR;
1771 }
1772 pResult = Tcl_GetObjResult(interp);
1773 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
1774 break;
1775 }
1776
drhb5a20d32003-04-23 12:25:23 +00001777 /* $db trace ?CALLBACK?
1778 **
1779 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
1780 ** that is executed. The text of the SQL is appended to CALLBACK before
1781 ** it is executed.
1782 */
1783 case DB_TRACE: {
1784 if( objc>3 ){
1785 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00001786 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00001787 }else if( objc==2 ){
1788 if( pDb->zTrace ){
1789 Tcl_AppendResult(interp, pDb->zTrace, 0);
1790 }
1791 }else{
1792 char *zTrace;
1793 int len;
1794 if( pDb->zTrace ){
1795 Tcl_Free(pDb->zTrace);
1796 }
1797 zTrace = Tcl_GetStringFromObj(objv[2], &len);
1798 if( zTrace && len>0 ){
1799 pDb->zTrace = Tcl_Alloc( len + 1 );
1800 strcpy(pDb->zTrace, zTrace);
1801 }else{
1802 pDb->zTrace = 0;
1803 }
drh19e2d372005-08-29 23:00:03 +00001804#ifndef SQLITE_OMIT_TRACE
drhb5a20d32003-04-23 12:25:23 +00001805 if( pDb->zTrace ){
1806 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001807 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00001808 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001809 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00001810 }
drh19e2d372005-08-29 23:00:03 +00001811#endif
drhb5a20d32003-04-23 12:25:23 +00001812 }
1813 break;
1814 }
1815
drh3d214232005-08-02 12:21:08 +00001816 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1817 **
1818 ** Start a new transaction (if we are not already in the midst of a
1819 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
1820 ** completes, either commit the transaction or roll it back if SCRIPT
1821 ** throws an exception. Or if no new transation was started, do nothing.
1822 ** pass the exception on up the stack.
1823 **
1824 ** This command was inspired by Dave Thomas's talk on Ruby at the
1825 ** 2005 O'Reilly Open Source Convention (OSCON).
1826 */
1827 case DB_TRANSACTION: {
1828 int inTrans;
1829 Tcl_Obj *pScript;
1830 const char *zBegin = "BEGIN";
1831 if( objc!=3 && objc!=4 ){
1832 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
1833 return TCL_ERROR;
1834 }
1835 if( objc==3 ){
1836 pScript = objv[2];
1837 } else {
1838 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00001839 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00001840 };
1841 enum TTYPE_enum {
1842 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
1843 };
1844 int ttype;
drhb5555e72005-08-02 17:15:14 +00001845 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00001846 0, &ttype) ){
1847 return TCL_ERROR;
1848 }
1849 switch( (enum TTYPE_enum)ttype ){
1850 case TTYPE_DEFERRED: /* no-op */; break;
1851 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
1852 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
1853 }
1854 pScript = objv[3];
1855 }
1856 inTrans = !sqlite3_get_autocommit(pDb->db);
1857 if( !inTrans ){
1858 sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
1859 }
1860 rc = Tcl_EvalObjEx(interp, pScript, 0);
1861 if( !inTrans ){
1862 const char *zEnd;
1863 if( rc==TCL_ERROR ){
1864 zEnd = "ROLLBACK";
1865 } else {
1866 zEnd = "COMMIT";
1867 }
1868 sqlite3_exec(pDb->db, zEnd, 0, 0, 0);
1869 }
1870 break;
1871 }
1872
danielk197794eb6a12005-12-15 15:22:08 +00001873 /*
1874 ** $db update_hook ?script?
1875 */
1876 case DB_UPDATE_HOOK: {
1877 if( objc!=2 && objc!=3 ){
1878 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
1879 return TCL_ERROR;
1880 }
1881 if( pDb->pUpdateHook ){
1882 Tcl_SetObjResult(interp, pDb->pUpdateHook);
1883 if( objc==3 ){
1884 Tcl_DecrRefCount(pDb->pUpdateHook);
1885 pDb->pUpdateHook = 0;
1886 }
1887 }
1888 if( objc==3 ){
1889 if( Tcl_GetCharLength(objv[2])>0 ){
1890 pDb->pUpdateHook = objv[2];
1891 Tcl_IncrRefCount(pDb->pUpdateHook);
1892 sqlite3_update_hook(pDb->db, DbUpdateHandler, pDb);
1893 }else{
1894 sqlite3_update_hook(pDb->db, 0, 0);
1895 }
1896 }
1897 break;
1898 }
1899
danielk19774397de52005-01-12 12:44:03 +00001900 /* $db version
1901 **
1902 ** Return the version string for this database.
1903 */
1904 case DB_VERSION: {
1905 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
1906 break;
1907 }
1908
tpoindex1067fe12004-12-17 15:41:11 +00001909
drh6d313162000-09-21 13:01:35 +00001910 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00001911 return rc;
drh75897232000-05-29 14:26:00 +00001912}
1913
1914/*
drh9bb575f2004-09-06 17:24:11 +00001915** sqlite3 DBNAME FILENAME ?MODE? ?-key KEY?
drh75897232000-05-29 14:26:00 +00001916**
1917** This is the main Tcl command. When the "sqlite" Tcl command is
1918** invoked, this routine runs to process that command.
1919**
1920** The first argument, DBNAME, is an arbitrary name for a new
1921** database connection. This command creates a new command named
1922** DBNAME that is used to control that connection. The database
1923** connection is deleted when the DBNAME command is deleted.
1924**
1925** The second argument is the name of the directory that contains
1926** the sqlite database that is to be accessed.
drhfbc3eab2001-04-06 16:13:42 +00001927**
1928** For testing purposes, we also support the following:
1929**
drh9bb575f2004-09-06 17:24:11 +00001930** sqlite3 -encoding
drhfbc3eab2001-04-06 16:13:42 +00001931**
1932** Return the encoding used by LIKE and GLOB operators. Choices
1933** are UTF-8 and iso8859.
1934**
drh9bb575f2004-09-06 17:24:11 +00001935** sqlite3 -version
drh647cb0e2002-11-04 19:32:25 +00001936**
1937** Return the version number of the SQLite library.
1938**
drh9bb575f2004-09-06 17:24:11 +00001939** sqlite3 -tcl-uses-utf
drhfbc3eab2001-04-06 16:13:42 +00001940**
1941** Return "1" if compiled with a Tcl uses UTF-8. Return "0" if
1942** not. Used by tests to make sure the library was compiled
1943** correctly.
drh75897232000-05-29 14:26:00 +00001944*/
drh22fbcb82004-02-01 01:22:50 +00001945static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001946 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00001947 void *pKey = 0;
1948 int nKey = 0;
1949 const char *zArg;
drh75897232000-05-29 14:26:00 +00001950 char *zErrMsg;
drh22fbcb82004-02-01 01:22:50 +00001951 const char *zFile;
drh06b27182002-06-26 20:06:05 +00001952 char zBuf[80];
drh22fbcb82004-02-01 01:22:50 +00001953 if( objc==2 ){
1954 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00001955 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00001956 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00001957 return TCL_OK;
1958 }
drh9eb9e262004-02-11 02:18:05 +00001959 if( strcmp(zArg,"-has-codec")==0 ){
1960#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00001961 Tcl_AppendResult(interp,"1",0);
1962#else
1963 Tcl_AppendResult(interp,"0",0);
1964#endif
1965 return TCL_OK;
1966 }
1967 if( strcmp(zArg,"-tcl-uses-utf")==0 ){
drhfbc3eab2001-04-06 16:13:42 +00001968#ifdef TCL_UTF_MAX
1969 Tcl_AppendResult(interp,"1",0);
1970#else
1971 Tcl_AppendResult(interp,"0",0);
1972#endif
1973 return TCL_OK;
1974 }
1975 }
drh22fbcb82004-02-01 01:22:50 +00001976 if( objc==5 || objc==6 ){
1977 zArg = Tcl_GetStringFromObj(objv[objc-2], 0);
1978 if( strcmp(zArg,"-key")==0 ){
1979 pKey = Tcl_GetByteArrayFromObj(objv[objc-1], &nKey);
1980 objc -= 2;
1981 }
1982 }
1983 if( objc!=3 && objc!=4 ){
1984 Tcl_WrongNumArgs(interp, 1, objv,
drh9eb9e262004-02-11 02:18:05 +00001985#ifdef SQLITE_HAS_CODEC
1986 "HANDLE FILENAME ?-key CODEC-KEY?"
drh22fbcb82004-02-01 01:22:50 +00001987#else
1988 "HANDLE FILENAME ?MODE?"
1989#endif
1990 );
drh75897232000-05-29 14:26:00 +00001991 return TCL_ERROR;
1992 }
drh75897232000-05-29 14:26:00 +00001993 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00001994 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00001995 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00001996 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
1997 return TCL_ERROR;
1998 }
1999 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00002000 zFile = Tcl_GetStringFromObj(objv[2], 0);
danielk19774f057f92004-06-08 00:02:33 +00002001 sqlite3_open(zFile, &p->db);
danielk197780290862004-05-22 09:21:21 +00002002 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
2003 zErrMsg = strdup(sqlite3_errmsg(p->db));
2004 sqlite3_close(p->db);
2005 p->db = 0;
2006 }
drh2011d5f2004-07-22 02:40:37 +00002007#ifdef SQLITE_HAS_CODEC
2008 sqlite3_key(p->db, pKey, nKey);
drheb8ed702004-02-11 10:37:23 +00002009#endif
drhbec3f402000-08-04 13:49:02 +00002010 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00002011 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00002012 Tcl_Free((char*)p);
drh75897232000-05-29 14:26:00 +00002013 free(zErrMsg);
2014 return TCL_ERROR;
2015 }
drhfb7e7652005-01-24 00:28:42 +00002016 p->maxStmt = NUM_PREPARED_STMTS;
drh22fbcb82004-02-01 01:22:50 +00002017 zArg = Tcl_GetStringFromObj(objv[1], 0);
2018 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
drhc22bd472002-05-10 13:14:07 +00002019
drh06b27182002-06-26 20:06:05 +00002020 /* The return value is the value of the sqlite* pointer
2021 */
2022 sprintf(zBuf, "%p", p->db);
drh5e5377f2002-07-07 17:12:36 +00002023 if( strncmp(zBuf,"0x",2) ){
2024 sprintf(zBuf, "0x%p", p->db);
2025 }
drh06b27182002-06-26 20:06:05 +00002026 Tcl_AppendResult(interp, zBuf, 0);
2027
drhc22bd472002-05-10 13:14:07 +00002028 /* If compiled with SQLITE_TEST turned on, then register the "md5sum"
drh06b27182002-06-26 20:06:05 +00002029 ** SQL function.
drhc22bd472002-05-10 13:14:07 +00002030 */
drh28b4e482002-03-11 02:06:13 +00002031#ifdef SQLITE_TEST
2032 {
drh9bb575f2004-09-06 17:24:11 +00002033 extern void Md5_Register(sqlite3*);
drh3b93bc82005-01-13 23:54:32 +00002034#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00002035 int mallocfail = sqlite3_iMallocFail;
2036 sqlite3_iMallocFail = 0;
danielk19775b59af82004-06-30 12:42:59 +00002037#endif
drhc22bd472002-05-10 13:14:07 +00002038 Md5_Register(p->db);
drh3b93bc82005-01-13 23:54:32 +00002039#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00002040 sqlite3_iMallocFail = mallocfail;
danielk19775b59af82004-06-30 12:42:59 +00002041#endif
danielk19777ddad962005-12-12 06:53:03 +00002042 }
drh28b4e482002-03-11 02:06:13 +00002043#endif
danielk19777cedc8d2004-06-10 10:50:08 +00002044 p->interp = interp;
drh75897232000-05-29 14:26:00 +00002045 return TCL_OK;
2046}
2047
2048/*
drh90ca9752001-09-28 17:47:14 +00002049** Provide a dummy Tcl_InitStubs if we are using this as a static
2050** library.
2051*/
2052#ifndef USE_TCL_STUBS
2053# undef Tcl_InitStubs
2054# define Tcl_InitStubs(a,b,c)
2055#endif
2056
2057/*
drh29bc4612005-10-05 10:40:15 +00002058** Make sure we have a PACKAGE_VERSION macro defined. This will be
2059** defined automatically by the TEA makefile. But other makefiles
2060** do not define it.
2061*/
2062#ifndef PACKAGE_VERSION
2063# define PACKAGE_VERSION SQLITE_VERSION
2064#endif
2065
2066/*
drh75897232000-05-29 14:26:00 +00002067** Initialize this module.
2068**
2069** This Tcl module contains only a single new Tcl command named "sqlite".
2070** (Hence there is no namespace. There is no point in using a namespace
2071** if the extension only supplies one new name!) The "sqlite" command is
2072** used to open a new SQLite database. See the DbMain() routine above
2073** for additional information.
2074*/
drh29bc4612005-10-05 10:40:15 +00002075EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00002076 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00002077 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002078 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh49766d62005-01-08 18:42:28 +00002079 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002080 Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
drh90ca9752001-09-28 17:47:14 +00002081 return TCL_OK;
2082}
drh29bc4612005-10-05 10:40:15 +00002083EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2084EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2085EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002086
2087#ifndef SQLITE_3_SUFFIX_ONLY
drh29bc4612005-10-05 10:40:15 +00002088EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2089EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2090EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2091EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002092#endif
drh75897232000-05-29 14:26:00 +00002093
drh3e27c022004-07-23 00:01:38 +00002094#ifdef TCLSH
2095/*****************************************************************************
2096** The code that follows is used to build standalone TCL interpreters
drh75897232000-05-29 14:26:00 +00002097*/
drh348784e2000-05-29 20:41:49 +00002098
2099/*
drh3e27c022004-07-23 00:01:38 +00002100** If the macro TCLSH is one, then put in code this for the
2101** "main" routine that will initialize Tcl and take input from
2102** standard input.
drh348784e2000-05-29 20:41:49 +00002103*/
drh3e27c022004-07-23 00:01:38 +00002104#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00002105static char zMainloop[] =
2106 "set line {}\n"
2107 "while {![eof stdin]} {\n"
2108 "if {$line!=\"\"} {\n"
2109 "puts -nonewline \"> \"\n"
2110 "} else {\n"
2111 "puts -nonewline \"% \"\n"
2112 "}\n"
2113 "flush stdout\n"
2114 "append line [gets stdin]\n"
2115 "if {[info complete $line]} {\n"
2116 "if {[catch {uplevel #0 $line} result]} {\n"
2117 "puts stderr \"Error: $result\"\n"
2118 "} elseif {$result!=\"\"} {\n"
2119 "puts $result\n"
2120 "}\n"
2121 "set line {}\n"
2122 "} else {\n"
2123 "append line \\n\n"
2124 "}\n"
2125 "}\n"
2126;
drh3e27c022004-07-23 00:01:38 +00002127#endif
2128
2129/*
2130** If the macro TCLSH is two, then get the main loop code out of
2131** the separate file "spaceanal_tcl.h".
2132*/
2133#if TCLSH==2
2134static char zMainloop[] =
2135#include "spaceanal_tcl.h"
2136;
2137#endif
drh348784e2000-05-29 20:41:49 +00002138
2139#define TCLSH_MAIN main /* Needed to fake out mktclapp */
2140int TCLSH_MAIN(int argc, char **argv){
2141 Tcl_Interp *interp;
drh297ecf12001-04-05 15:57:13 +00002142 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00002143 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00002144 Sqlite3_Init(interp);
drhd9b02572001-04-15 00:37:09 +00002145#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00002146 {
2147 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00002148 extern int Sqlitetest2_Init(Tcl_Interp*);
2149 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00002150 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00002151 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00002152 extern int Sqlitetest6_Init(Tcl_Interp*);
danielk197713a68c32005-12-15 10:11:30 +00002153 extern int Sqlitetestasync_Init(Tcl_Interp*);
drhefc251d2001-07-01 22:12:01 +00002154 extern int Md5_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002155 extern int Sqlitetestsse_Init(Tcl_Interp*);
2156
danielk19776490beb2004-05-11 06:17:21 +00002157 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00002158 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00002159 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00002160 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00002161 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00002162 Sqlitetest6_Init(interp);
danielk197713a68c32005-12-15 10:11:30 +00002163 Sqlitetestasync_Init(interp);
drhefc251d2001-07-01 22:12:01 +00002164 Md5_Init(interp);
drh89dec812005-04-28 19:03:37 +00002165#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00002166 Sqlitetestsse_Init(interp);
2167#endif
drhd1bf3512001-04-07 15:24:33 +00002168 }
2169#endif
drh3e27c022004-07-23 00:01:38 +00002170 if( argc>=2 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002171 int i;
2172 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
2173 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00002174 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00002175 Tcl_SetVar(interp, "argv", argv[i],
2176 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
2177 }
drh3e27c022004-07-23 00:01:38 +00002178 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00002179 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drhc61053b2000-06-04 12:58:36 +00002180 if( zInfo==0 ) zInfo = interp->result;
2181 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00002182 return 1;
2183 }
drh3e27c022004-07-23 00:01:38 +00002184 }
2185 if( argc<=1 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002186 Tcl_GlobalEval(interp, zMainloop);
2187 }
2188 return 0;
2189}
2190#endif /* TCLSH */
drh6d313162000-09-21 13:01:35 +00002191
2192#endif /* !defined(NO_TCL) */