blob: 9baf582c43b14f99caa3ae0e5ee2770945da6c84 [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**
drh29bc4612005-10-05 10:40:15 +000014** $Id: tclsqlite.c,v 1.133 2005/10/05 10:40:15 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
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 */
102 SqlCollate *pCollate; /* List of SQL collation functions */
103 int rc; /* Return code of most recent sqlite3_exec() */
104 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000105 SqlPreparedStmt *stmtList; /* List of prepared statements*/
106 SqlPreparedStmt *stmtLast; /* Last statement in the list */
107 int maxStmt; /* The next maximum number of stmtList */
108 int nStmt; /* Number of statements in stmtList */
drh98808ba2001-10-18 12:34:46 +0000109};
drh297ecf12001-04-05 15:57:13 +0000110
drh6d313162000-09-21 13:01:35 +0000111/*
drhd1e47332005-06-26 17:55:33 +0000112** Look at the script prefix in pCmd. We will be executing this script
113** after first appending one or more arguments. This routine analyzes
114** the script to see if it is safe to use Tcl_EvalObjv() on the script
115** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
116** faster.
117**
118** Scripts that are safe to use with Tcl_EvalObjv() consists of a
119** command name followed by zero or more arguments with no [...] or $
120** or {...} or ; to be seen anywhere. Most callback scripts consist
121** of just a single procedure name and they meet this requirement.
122*/
123static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
124 /* We could try to do something with Tcl_Parse(). But we will instead
125 ** just do a search for forbidden characters. If any of the forbidden
126 ** characters appear in pCmd, we will report the string as unsafe.
127 */
128 const char *z;
129 int n;
130 z = Tcl_GetStringFromObj(pCmd, &n);
131 while( n-- > 0 ){
132 int c = *(z++);
133 if( c=='$' || c=='[' || c==';' ) return 0;
134 }
135 return 1;
136}
137
138/*
139** Find an SqlFunc structure with the given name. Or create a new
140** one if an existing one cannot be found. Return a pointer to the
141** structure.
142*/
143static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
144 SqlFunc *p, *pNew;
145 int i;
146 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen(zName) + 1 );
147 pNew->zName = (char*)&pNew[1];
148 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
149 pNew->zName[i] = 0;
150 for(p=pDb->pFunc; p; p=p->pNext){
151 if( strcmp(p->zName, pNew->zName)==0 ){
152 Tcl_Free((char*)pNew);
153 return p;
154 }
155 }
156 pNew->interp = pDb->interp;
157 pNew->pScript = 0;
158 pNew->pNext = pDb->pFunc;
159 pDb->pFunc = pNew;
160 return pNew;
161}
162
163/*
drhfb7e7652005-01-24 00:28:42 +0000164** Finalize and free a list of prepared statements
165*/
166static void flushStmtCache( SqliteDb *pDb ){
167 SqlPreparedStmt *pPreStmt;
168
169 while( pDb->stmtList ){
170 sqlite3_finalize( pDb->stmtList->pStmt );
171 pPreStmt = pDb->stmtList;
172 pDb->stmtList = pDb->stmtList->pNext;
173 Tcl_Free( (char*)pPreStmt );
174 }
175 pDb->nStmt = 0;
176 pDb->stmtLast = 0;
177}
178
179/*
drh895d7472004-08-20 16:02:39 +0000180** TCL calls this procedure when an sqlite3 database command is
181** deleted.
drh75897232000-05-29 14:26:00 +0000182*/
183static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000184 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000185 flushStmtCache(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000186 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000187 while( pDb->pFunc ){
188 SqlFunc *pFunc = pDb->pFunc;
189 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000190 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000191 Tcl_Free((char*)pFunc);
192 }
danielk19770202b292004-06-09 09:55:16 +0000193 while( pDb->pCollate ){
194 SqlCollate *pCollate = pDb->pCollate;
195 pDb->pCollate = pCollate->pNext;
196 Tcl_Free((char*)pCollate);
197 }
drhbec3f402000-08-04 13:49:02 +0000198 if( pDb->zBusy ){
199 Tcl_Free(pDb->zBusy);
200 }
drhb5a20d32003-04-23 12:25:23 +0000201 if( pDb->zTrace ){
202 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000203 }
drh19e2d372005-08-29 23:00:03 +0000204 if( pDb->zProfile ){
205 Tcl_Free(pDb->zProfile);
206 }
drhe22a3342003-04-22 20:30:37 +0000207 if( pDb->zAuth ){
208 Tcl_Free(pDb->zAuth);
209 }
danielk197755c45f22005-04-03 23:54:43 +0000210 if( pDb->zNull ){
211 Tcl_Free(pDb->zNull);
212 }
drhbec3f402000-08-04 13:49:02 +0000213 Tcl_Free((char*)pDb);
214}
215
216/*
217** This routine is called when a database file is locked while trying
218** to execute SQL.
219*/
danielk19772a764eb2004-06-12 01:43:26 +0000220static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000221 SqliteDb *pDb = (SqliteDb*)cd;
222 int rc;
223 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000224
danielk19772a764eb2004-06-12 01:43:26 +0000225 sprintf(zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000226 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000227 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
228 return 0;
229 }
230 return 1;
drh75897232000-05-29 14:26:00 +0000231}
232
233/*
danielk1977348bb5d2003-10-18 09:37:26 +0000234** This routine is invoked as the 'progress callback' for the database.
235*/
236static int DbProgressHandler(void *cd){
237 SqliteDb *pDb = (SqliteDb*)cd;
238 int rc;
239
240 assert( pDb->zProgress );
241 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
242 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
243 return 1;
244 }
245 return 0;
246}
247
248/*
drhb5a20d32003-04-23 12:25:23 +0000249** This routine is called by the SQLite trace handler whenever a new
250** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000251*/
drhb5a20d32003-04-23 12:25:23 +0000252static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000253 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000254 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000255
drhb5a20d32003-04-23 12:25:23 +0000256 Tcl_DStringInit(&str);
257 Tcl_DStringAppend(&str, pDb->zTrace, -1);
258 Tcl_DStringAppendElement(&str, zSql);
259 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
260 Tcl_DStringFree(&str);
261 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000262}
263
264/*
drh19e2d372005-08-29 23:00:03 +0000265** This routine is called by the SQLite profile handler after a statement
266** SQL has executed. The TCL script in pDb->zProfile is evaluated.
267*/
268static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
269 SqliteDb *pDb = (SqliteDb*)cd;
270 Tcl_DString str;
271 char zTm[100];
272
273 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
274 Tcl_DStringInit(&str);
275 Tcl_DStringAppend(&str, pDb->zProfile, -1);
276 Tcl_DStringAppendElement(&str, zSql);
277 Tcl_DStringAppendElement(&str, zTm);
278 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
279 Tcl_DStringFree(&str);
280 Tcl_ResetResult(pDb->interp);
281}
282
283/*
drhaa940ea2004-01-15 02:44:03 +0000284** This routine is called when a transaction is committed. The
285** TCL script in pDb->zCommit is executed. If it returns non-zero or
286** if it throws an exception, the transaction is rolled back instead
287** of being committed.
288*/
289static int DbCommitHandler(void *cd){
290 SqliteDb *pDb = (SqliteDb*)cd;
291 int rc;
292
293 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
294 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
295 return 1;
296 }
297 return 0;
298}
299
danielk19777cedc8d2004-06-10 10:50:08 +0000300static void tclCollateNeeded(
301 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000302 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000303 int enc,
304 const char *zName
305){
306 SqliteDb *pDb = (SqliteDb *)pCtx;
307 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
308 Tcl_IncrRefCount(pScript);
309 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
310 Tcl_EvalObjEx(pDb->interp, pScript, 0);
311 Tcl_DecrRefCount(pScript);
312}
313
drhaa940ea2004-01-15 02:44:03 +0000314/*
danielk19770202b292004-06-09 09:55:16 +0000315** This routine is called to evaluate an SQL collation function implemented
316** using TCL script.
317*/
318static int tclSqlCollate(
319 void *pCtx,
320 int nA,
321 const void *zA,
322 int nB,
323 const void *zB
324){
325 SqlCollate *p = (SqlCollate *)pCtx;
326 Tcl_Obj *pCmd;
327
328 pCmd = Tcl_NewStringObj(p->zScript, -1);
329 Tcl_IncrRefCount(pCmd);
330 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
331 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000332 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000333 Tcl_DecrRefCount(pCmd);
334 return (atoi(Tcl_GetStringResult(p->interp)));
335}
336
337/*
drhcabb0812002-09-14 13:47:32 +0000338** This routine is called to evaluate an SQL function implemented
339** using TCL script.
340*/
drhfb7e7652005-01-24 00:28:42 +0000341static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000342 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000343 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000344 int i;
345 int rc;
346
drhd1e47332005-06-26 17:55:33 +0000347 if( argc==0 ){
348 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
349 ** script object directly. This allows the TCL compiler to generate
350 ** bytecode for the command on the first invocation and thus make
351 ** subsequent invocations much faster. */
352 pCmd = p->pScript;
353 Tcl_IncrRefCount(pCmd);
354 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
355 Tcl_DecrRefCount(pCmd);
356 }else{
357 /* If there are arguments to the function, make a shallow copy of the
358 ** script object, lappend the arguments, then evaluate the copy.
359 **
360 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
361 ** The new Tcl_Obj contains pointers to the original list elements.
362 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
363 ** of the list to tclCmdNameType, that alternate representation will
364 ** be preserved and reused on the next invocation.
365 */
366 Tcl_Obj **aArg;
367 int nArg;
368 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
369 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
370 return;
371 }
372 pCmd = Tcl_NewListObj(nArg, aArg);
373 Tcl_IncrRefCount(pCmd);
374 for(i=0; i<argc; i++){
375 sqlite3_value *pIn = argv[i];
376 Tcl_Obj *pVal;
377
378 /* Set pVal to contain the i'th column of this row. */
379 switch( sqlite3_value_type(pIn) ){
380 case SQLITE_BLOB: {
381 int bytes = sqlite3_value_bytes(pIn);
382 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
383 break;
384 }
385 case SQLITE_INTEGER: {
386 sqlite_int64 v = sqlite3_value_int64(pIn);
387 if( v>=-2147483647 && v<=2147483647 ){
388 pVal = Tcl_NewIntObj(v);
389 }else{
390 pVal = Tcl_NewWideIntObj(v);
391 }
392 break;
393 }
394 case SQLITE_FLOAT: {
395 double r = sqlite3_value_double(pIn);
396 pVal = Tcl_NewDoubleObj(r);
397 break;
398 }
399 case SQLITE_NULL: {
400 pVal = Tcl_NewStringObj("", 0);
401 break;
402 }
403 default: {
404 int bytes = sqlite3_value_bytes(pIn);
405 pVal = Tcl_NewStringObj(sqlite3_value_text(pIn), bytes);
406 break;
407 }
408 }
409 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
410 if( rc ){
411 Tcl_DecrRefCount(pCmd);
412 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
413 return;
414 }
danielk197751ad0ec2004-05-24 12:39:02 +0000415 }
drhd1e47332005-06-26 17:55:33 +0000416 if( !p->useEvalObjv ){
417 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
418 ** is a list without a string representation. To prevent this from
419 ** happening, make sure pCmd has a valid string representation */
420 Tcl_GetString(pCmd);
421 }
422 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
423 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000424 }
danielk1977562e8d32005-05-20 09:40:55 +0000425
drhc7f269d2005-05-05 10:30:29 +0000426 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000427 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000428 }else{
drhc7f269d2005-05-05 10:30:29 +0000429 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
430 int n;
431 u8 *data;
432 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
433 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000434 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000435 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000436 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000437 data = Tcl_GetByteArrayFromObj(pVar, &n);
438 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000439 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
440 (c=='i' && strcmp(zType,"int")==0) ){
441 Tcl_GetIntFromObj(0, pVar, &n);
442 sqlite3_result_int(context, n);
443 }else if( c=='d' && strcmp(zType,"double")==0 ){
444 double r;
445 Tcl_GetDoubleFromObj(0, pVar, &r);
446 sqlite3_result_double(context, r);
drhdf0bdda2005-06-25 19:31:48 +0000447 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
448 Tcl_WideInt v;
449 Tcl_GetWideIntFromObj(0, pVar, &v);
450 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000451 }else{
452 data = Tcl_GetStringFromObj(pVar, &n);
453 sqlite3_result_text(context, data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000454 }
drhcabb0812002-09-14 13:47:32 +0000455 }
456}
drh895d7472004-08-20 16:02:39 +0000457
drhe22a3342003-04-22 20:30:37 +0000458#ifndef SQLITE_OMIT_AUTHORIZATION
459/*
460** This is the authentication function. It appends the authentication
461** type code and the two arguments to zCmd[] then invokes the result
462** on the interpreter. The reply is examined to determine if the
463** authentication fails or succeeds.
464*/
465static int auth_callback(
466 void *pArg,
467 int code,
468 const char *zArg1,
469 const char *zArg2,
470 const char *zArg3,
471 const char *zArg4
472){
473 char *zCode;
474 Tcl_DString str;
475 int rc;
476 const char *zReply;
477 SqliteDb *pDb = (SqliteDb*)pArg;
478
479 switch( code ){
480 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
481 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
482 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
483 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
484 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
485 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
486 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
487 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
488 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
489 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
490 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
491 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
492 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
493 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
494 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
495 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
496 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
497 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
498 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
499 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
500 case SQLITE_READ : zCode="SQLITE_READ"; break;
501 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
502 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
503 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000504 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
505 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000506 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000507 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000508 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
drhe22a3342003-04-22 20:30:37 +0000509 default : zCode="????"; break;
510 }
511 Tcl_DStringInit(&str);
512 Tcl_DStringAppend(&str, pDb->zAuth, -1);
513 Tcl_DStringAppendElement(&str, zCode);
514 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
515 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
516 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
517 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
518 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
519 Tcl_DStringFree(&str);
520 zReply = Tcl_GetStringResult(pDb->interp);
521 if( strcmp(zReply,"SQLITE_OK")==0 ){
522 rc = SQLITE_OK;
523 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
524 rc = SQLITE_DENY;
525 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
526 rc = SQLITE_IGNORE;
527 }else{
528 rc = 999;
529 }
530 return rc;
531}
532#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000533
534/*
danielk1977ef2cb632004-05-29 02:37:19 +0000535** zText is a pointer to text obtained via an sqlite3_result_text()
536** or similar interface. This routine returns a Tcl string object,
537** reference count set to 0, containing the text. If a translation
538** between iso8859 and UTF-8 is required, it is preformed.
539*/
540static Tcl_Obj *dbTextToObj(char const *zText){
541 Tcl_Obj *pVal;
542#ifdef UTF_TRANSLATION_NEEDED
543 Tcl_DString dCol;
544 Tcl_DStringInit(&dCol);
545 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
546 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
547 Tcl_DStringFree(&dCol);
548#else
549 pVal = Tcl_NewStringObj(zText, -1);
550#endif
551 return pVal;
552}
553
554/*
tpoindex1067fe12004-12-17 15:41:11 +0000555** This routine reads a line of text from FILE in, stores
556** the text in memory obtained from malloc() and returns a pointer
557** to the text. NULL is returned at end of file, or if malloc()
558** fails.
559**
560** The interface is like "readline" but no command-line editing
561** is done.
562**
563** copied from shell.c from '.import' command
564*/
565static char *local_getline(char *zPrompt, FILE *in){
566 char *zLine;
567 int nLine;
568 int n;
569 int eol;
570
571 nLine = 100;
572 zLine = malloc( nLine );
573 if( zLine==0 ) return 0;
574 n = 0;
575 eol = 0;
576 while( !eol ){
577 if( n+100>nLine ){
578 nLine = nLine*2 + 100;
579 zLine = realloc(zLine, nLine);
580 if( zLine==0 ) return 0;
581 }
582 if( fgets(&zLine[n], nLine - n, in)==0 ){
583 if( n==0 ){
584 free(zLine);
585 return 0;
586 }
587 zLine[n] = 0;
588 eol = 1;
589 break;
590 }
591 while( zLine[n] ){ n++; }
592 if( n>0 && zLine[n-1]=='\n' ){
593 n--;
594 zLine[n] = 0;
595 eol = 1;
596 }
597 }
598 zLine = realloc( zLine, n+1 );
599 return zLine;
600}
601
602/*
drh75897232000-05-29 14:26:00 +0000603** The "sqlite" command below creates a new Tcl command for each
604** connection it opens to an SQLite database. This routine is invoked
605** whenever one of those connection-specific commands is executed
606** in Tcl. For example, if you run Tcl code like this:
607**
drh9bb575f2004-09-06 17:24:11 +0000608** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +0000609** db1 close
610**
611** The first command opens a connection to the "my_database" database
612** and calls that connection "db1". The second command causes this
613** subroutine to be invoked.
614*/
drh6d313162000-09-21 13:01:35 +0000615static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +0000616 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +0000617 int choice;
drh22fbcb82004-02-01 01:22:50 +0000618 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +0000619 static const char *DB_strs[] = {
drhfb7e7652005-01-24 00:28:42 +0000620 "authorizer", "busy", "cache",
621 "changes", "close", "collate",
622 "collation_needed", "commit_hook", "complete",
623 "copy", "errorcode", "eval",
danielk197755c45f22005-04-03 23:54:43 +0000624 "function", "last_insert_rowid", "nullvalue",
drh19e2d372005-08-29 23:00:03 +0000625 "onecolumn", "profile", "progress",
626 "rekey", "timeout", "total_changes",
627 "trace", "transaction", "version",
628 0
drh6d313162000-09-21 13:01:35 +0000629 };
drh411995d2002-06-25 19:31:18 +0000630 enum DB_enum {
drhfb7e7652005-01-24 00:28:42 +0000631 DB_AUTHORIZER, DB_BUSY, DB_CACHE,
632 DB_CHANGES, DB_CLOSE, DB_COLLATE,
633 DB_COLLATION_NEEDED, DB_COMMIT_HOOK, DB_COMPLETE,
634 DB_COPY, DB_ERRORCODE, DB_EVAL,
danielk197755c45f22005-04-03 23:54:43 +0000635 DB_FUNCTION, DB_LAST_INSERT_ROWID,DB_NULLVALUE,
drh19e2d372005-08-29 23:00:03 +0000636 DB_ONECOLUMN, DB_PROFILE, DB_PROGRESS,
637 DB_REKEY, DB_TIMEOUT, DB_TOTAL_CHANGES,
638 DB_TRACE, DB_TRANSACTION, DB_VERSION
drh6d313162000-09-21 13:01:35 +0000639 };
tpoindex1067fe12004-12-17 15:41:11 +0000640 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +0000641
642 if( objc<2 ){
643 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +0000644 return TCL_ERROR;
645 }
drh411995d2002-06-25 19:31:18 +0000646 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +0000647 return TCL_ERROR;
648 }
649
drh411995d2002-06-25 19:31:18 +0000650 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +0000651
drhe22a3342003-04-22 20:30:37 +0000652 /* $db authorizer ?CALLBACK?
653 **
654 ** Invoke the given callback to authorize each SQL operation as it is
655 ** compiled. 5 arguments are appended to the callback before it is
656 ** invoked:
657 **
658 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
659 ** (2) First descriptive name (depends on authorization type)
660 ** (3) Second descriptive name
661 ** (4) Name of the database (ex: "main", "temp")
662 ** (5) Name of trigger that is doing the access
663 **
664 ** The callback should return on of the following strings: SQLITE_OK,
665 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
666 **
667 ** If this method is invoked with no arguments, the current authorization
668 ** callback string is returned.
669 */
670 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +0000671#ifdef SQLITE_OMIT_AUTHORIZATION
672 Tcl_AppendResult(interp, "authorization not available in this build", 0);
673 return TCL_ERROR;
674#else
drhe22a3342003-04-22 20:30:37 +0000675 if( objc>3 ){
676 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +0000677 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +0000678 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +0000679 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +0000680 Tcl_AppendResult(interp, pDb->zAuth, 0);
681 }
682 }else{
683 char *zAuth;
684 int len;
685 if( pDb->zAuth ){
686 Tcl_Free(pDb->zAuth);
687 }
688 zAuth = Tcl_GetStringFromObj(objv[2], &len);
689 if( zAuth && len>0 ){
690 pDb->zAuth = Tcl_Alloc( len + 1 );
691 strcpy(pDb->zAuth, zAuth);
692 }else{
693 pDb->zAuth = 0;
694 }
drhe22a3342003-04-22 20:30:37 +0000695 if( pDb->zAuth ){
696 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000697 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +0000698 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000699 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +0000700 }
drhe22a3342003-04-22 20:30:37 +0000701 }
drh1211de32004-07-26 12:24:22 +0000702#endif
drhe22a3342003-04-22 20:30:37 +0000703 break;
704 }
705
drhbec3f402000-08-04 13:49:02 +0000706 /* $db busy ?CALLBACK?
707 **
708 ** Invoke the given callback if an SQL statement attempts to open
709 ** a locked database file.
710 */
drh6d313162000-09-21 13:01:35 +0000711 case DB_BUSY: {
712 if( objc>3 ){
713 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +0000714 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +0000715 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +0000716 if( pDb->zBusy ){
717 Tcl_AppendResult(interp, pDb->zBusy, 0);
718 }
719 }else{
drh6d313162000-09-21 13:01:35 +0000720 char *zBusy;
721 int len;
drhbec3f402000-08-04 13:49:02 +0000722 if( pDb->zBusy ){
723 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +0000724 }
drh6d313162000-09-21 13:01:35 +0000725 zBusy = Tcl_GetStringFromObj(objv[2], &len);
726 if( zBusy && len>0 ){
727 pDb->zBusy = Tcl_Alloc( len + 1 );
728 strcpy(pDb->zBusy, zBusy);
729 }else{
730 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +0000731 }
732 if( pDb->zBusy ){
733 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000734 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +0000735 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000736 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +0000737 }
738 }
drh6d313162000-09-21 13:01:35 +0000739 break;
740 }
drhbec3f402000-08-04 13:49:02 +0000741
drhfb7e7652005-01-24 00:28:42 +0000742 /* $db cache flush
743 ** $db cache size n
744 **
745 ** Flush the prepared statement cache, or set the maximum number of
746 ** cached statements.
747 */
748 case DB_CACHE: {
749 char *subCmd;
750 int n;
751
752 if( objc<=2 ){
753 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
754 return TCL_ERROR;
755 }
756 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
757 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
758 if( objc!=3 ){
759 Tcl_WrongNumArgs(interp, 2, objv, "flush");
760 return TCL_ERROR;
761 }else{
762 flushStmtCache( pDb );
763 }
764 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
765 if( objc!=4 ){
766 Tcl_WrongNumArgs(interp, 2, objv, "size n");
767 return TCL_ERROR;
768 }else{
769 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
770 Tcl_AppendResult( interp, "cannot convert \"",
771 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
772 return TCL_ERROR;
773 }else{
774 if( n<0 ){
775 flushStmtCache( pDb );
776 n = 0;
777 }else if( n>MAX_PREPARED_STMTS ){
778 n = MAX_PREPARED_STMTS;
779 }
780 pDb->maxStmt = n;
781 }
782 }
783 }else{
784 Tcl_AppendResult( interp, "bad option \"",
785 Tcl_GetStringFromObj(objv[0],0), "\": must be flush or size", 0);
786 return TCL_ERROR;
787 }
788 break;
789 }
790
danielk1977b28af712004-06-21 06:50:26 +0000791 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +0000792 **
793 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +0000794 ** the most recent INSERT, UPDATE or DELETE statement, not including
795 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +0000796 */
797 case DB_CHANGES: {
798 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +0000799 if( objc!=2 ){
800 Tcl_WrongNumArgs(interp, 2, objv, "");
801 return TCL_ERROR;
802 }
drhc8d30ac2002-04-12 10:08:59 +0000803 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +0000804 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +0000805 break;
806 }
807
drh75897232000-05-29 14:26:00 +0000808 /* $db close
809 **
810 ** Shutdown the database
811 */
drh6d313162000-09-21 13:01:35 +0000812 case DB_CLOSE: {
813 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
814 break;
815 }
drh75897232000-05-29 14:26:00 +0000816
drh0f14e2e2004-06-29 12:39:08 +0000817 /*
818 ** $db collate NAME SCRIPT
819 **
820 ** Create a new SQL collation function called NAME. Whenever
821 ** that function is called, invoke SCRIPT to evaluate the function.
822 */
823 case DB_COLLATE: {
824 SqlCollate *pCollate;
825 char *zName;
826 char *zScript;
827 int nScript;
828 if( objc!=4 ){
829 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
830 return TCL_ERROR;
831 }
832 zName = Tcl_GetStringFromObj(objv[2], 0);
833 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
834 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
835 if( pCollate==0 ) return TCL_ERROR;
836 pCollate->interp = interp;
837 pCollate->pNext = pDb->pCollate;
838 pCollate->zScript = (char*)&pCollate[1];
839 pDb->pCollate = pCollate;
840 strcpy(pCollate->zScript, zScript);
841 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
842 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +0000843 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +0000844 return TCL_ERROR;
845 }
846 break;
847 }
848
849 /*
850 ** $db collation_needed 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_COLLATION_NEEDED: {
856 if( objc!=3 ){
857 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
858 return TCL_ERROR;
859 }
860 if( pDb->pCollateNeeded ){
861 Tcl_DecrRefCount(pDb->pCollateNeeded);
862 }
863 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
864 Tcl_IncrRefCount(pDb->pCollateNeeded);
865 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
866 break;
867 }
868
drh19e2d372005-08-29 23:00:03 +0000869 /* $db commit_hook ?CALLBACK?
870 **
871 ** Invoke the given callback just before committing every SQL transaction.
872 ** If the callback throws an exception or returns non-zero, then the
873 ** transaction is aborted. If CALLBACK is an empty string, the callback
874 ** is disabled.
875 */
876 case DB_COMMIT_HOOK: {
877 if( objc>3 ){
878 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
879 return TCL_ERROR;
880 }else if( objc==2 ){
881 if( pDb->zCommit ){
882 Tcl_AppendResult(interp, pDb->zCommit, 0);
883 }
884 }else{
885 char *zCommit;
886 int len;
887 if( pDb->zCommit ){
888 Tcl_Free(pDb->zCommit);
889 }
890 zCommit = Tcl_GetStringFromObj(objv[2], &len);
891 if( zCommit && len>0 ){
892 pDb->zCommit = Tcl_Alloc( len + 1 );
893 strcpy(pDb->zCommit, zCommit);
894 }else{
895 pDb->zCommit = 0;
896 }
897 if( pDb->zCommit ){
898 pDb->interp = interp;
899 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
900 }else{
901 sqlite3_commit_hook(pDb->db, 0, 0);
902 }
903 }
904 break;
905 }
906
drh75897232000-05-29 14:26:00 +0000907 /* $db complete SQL
908 **
909 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
910 ** additional lines of input are needed. This is similar to the
911 ** built-in "info complete" command of Tcl.
912 */
drh6d313162000-09-21 13:01:35 +0000913 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +0000914#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +0000915 Tcl_Obj *pResult;
916 int isComplete;
917 if( objc!=3 ){
918 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +0000919 return TCL_ERROR;
920 }
danielk19776f8a5032004-05-10 10:34:51 +0000921 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +0000922 pResult = Tcl_GetObjResult(interp);
923 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +0000924#endif
drh6d313162000-09-21 13:01:35 +0000925 break;
926 }
drhdcd997e2003-01-31 17:21:49 +0000927
drh19e2d372005-08-29 23:00:03 +0000928 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
929 **
930 ** Copy data into table from filename, optionally using SEPARATOR
931 ** as column separators. If a column contains a null string, or the
932 ** value of NULLINDICATOR, a NULL is inserted for the column.
933 ** conflict-algorithm is one of the sqlite conflict algorithms:
934 ** rollback, abort, fail, ignore, replace
935 ** On success, return the number of lines processed, not necessarily same
936 ** as 'db changes' due to conflict-algorithm selected.
937 **
938 ** This code is basically an implementation/enhancement of
939 ** the sqlite3 shell.c ".import" command.
940 **
941 ** This command usage is equivalent to the sqlite2.x COPY statement,
942 ** which imports file data into a table using the PostgreSQL COPY file format:
943 ** $db copy $conflit_algo $table_name $filename \t \\N
944 */
945 case DB_COPY: {
946 char *zTable; /* Insert data into this table */
947 char *zFile; /* The file from which to extract data */
948 char *zConflict; /* The conflict algorithm to use */
949 sqlite3_stmt *pStmt; /* A statement */
950 int rc; /* Result code */
951 int nCol; /* Number of columns in the table */
952 int nByte; /* Number of bytes in an SQL string */
953 int i, j; /* Loop counters */
954 int nSep; /* Number of bytes in zSep[] */
955 int nNull; /* Number of bytes in zNull[] */
956 char *zSql; /* An SQL statement */
957 char *zLine; /* A single line of input from the file */
958 char **azCol; /* zLine[] broken up into columns */
959 char *zCommit; /* How to commit changes */
960 FILE *in; /* The input file */
961 int lineno = 0; /* Line number of input file */
962 char zLineNum[80]; /* Line number print buffer */
963 Tcl_Obj *pResult; /* interp result */
964
965 char *zSep;
966 char *zNull;
967 if( objc<5 || objc>7 ){
968 Tcl_WrongNumArgs(interp, 2, objv,
969 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
970 return TCL_ERROR;
971 }
972 if( objc>=6 ){
973 zSep = Tcl_GetStringFromObj(objv[5], 0);
974 }else{
975 zSep = "\t";
976 }
977 if( objc>=7 ){
978 zNull = Tcl_GetStringFromObj(objv[6], 0);
979 }else{
980 zNull = "";
981 }
982 zConflict = Tcl_GetStringFromObj(objv[2], 0);
983 zTable = Tcl_GetStringFromObj(objv[3], 0);
984 zFile = Tcl_GetStringFromObj(objv[4], 0);
985 nSep = strlen(zSep);
986 nNull = strlen(zNull);
987 if( nSep==0 ){
988 Tcl_AppendResult(interp, "Error: non-null separator required for copy", 0);
989 return TCL_ERROR;
990 }
991 if(sqlite3StrICmp(zConflict, "rollback") != 0 &&
992 sqlite3StrICmp(zConflict, "abort" ) != 0 &&
993 sqlite3StrICmp(zConflict, "fail" ) != 0 &&
994 sqlite3StrICmp(zConflict, "ignore" ) != 0 &&
995 sqlite3StrICmp(zConflict, "replace" ) != 0 ) {
996 Tcl_AppendResult(interp, "Error: \"", zConflict,
997 "\", conflict-algorithm must be one of: rollback, "
998 "abort, fail, ignore, or replace", 0);
999 return TCL_ERROR;
1000 }
1001 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1002 if( zSql==0 ){
1003 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1004 return TCL_ERROR;
1005 }
1006 nByte = strlen(zSql);
1007 rc = sqlite3_prepare(pDb->db, zSql, 0, &pStmt, 0);
1008 sqlite3_free(zSql);
1009 if( rc ){
1010 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1011 nCol = 0;
1012 }else{
1013 nCol = sqlite3_column_count(pStmt);
1014 }
1015 sqlite3_finalize(pStmt);
1016 if( nCol==0 ) {
1017 return TCL_ERROR;
1018 }
1019 zSql = malloc( nByte + 50 + nCol*2 );
1020 if( zSql==0 ) {
1021 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1022 return TCL_ERROR;
1023 }
1024 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1025 zConflict, zTable);
1026 j = strlen(zSql);
1027 for(i=1; i<nCol; i++){
1028 zSql[j++] = ',';
1029 zSql[j++] = '?';
1030 }
1031 zSql[j++] = ')';
1032 zSql[j] = 0;
1033 rc = sqlite3_prepare(pDb->db, zSql, 0, &pStmt, 0);
1034 free(zSql);
1035 if( rc ){
1036 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1037 sqlite3_finalize(pStmt);
1038 return TCL_ERROR;
1039 }
1040 in = fopen(zFile, "rb");
1041 if( in==0 ){
1042 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
1043 sqlite3_finalize(pStmt);
1044 return TCL_ERROR;
1045 }
1046 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1047 if( azCol==0 ) {
1048 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1049 return TCL_ERROR;
1050 }
1051 sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
1052 zCommit = "COMMIT";
1053 while( (zLine = local_getline(0, in))!=0 ){
1054 char *z;
1055 i = 0;
1056 lineno++;
1057 azCol[0] = zLine;
1058 for(i=0, z=zLine; *z; z++){
1059 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
1060 *z = 0;
1061 i++;
1062 if( i<nCol ){
1063 azCol[i] = &z[nSep];
1064 z += nSep-1;
1065 }
1066 }
1067 }
1068 if( i+1!=nCol ){
1069 char *zErr;
1070 zErr = malloc(200 + strlen(zFile));
1071 sprintf(zErr,"Error: %s line %d: expected %d columns of data but found %d",
1072 zFile, lineno, nCol, i+1);
1073 Tcl_AppendResult(interp, zErr, 0);
1074 free(zErr);
1075 zCommit = "ROLLBACK";
1076 break;
1077 }
1078 for(i=0; i<nCol; i++){
1079 /* check for null data, if so, bind as null */
1080 if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
1081 sqlite3_bind_null(pStmt, i+1);
1082 }else{
1083 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1084 }
1085 }
1086 sqlite3_step(pStmt);
1087 rc = sqlite3_reset(pStmt);
1088 free(zLine);
1089 if( rc!=SQLITE_OK ){
1090 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
1091 zCommit = "ROLLBACK";
1092 break;
1093 }
1094 }
1095 free(azCol);
1096 fclose(in);
1097 sqlite3_finalize(pStmt);
1098 sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
1099
1100 if( zCommit[0] == 'C' ){
1101 /* success, set result as number of lines processed */
1102 pResult = Tcl_GetObjResult(interp);
1103 Tcl_SetIntObj(pResult, lineno);
1104 rc = TCL_OK;
1105 }else{
1106 /* failure, append lineno where failed */
1107 sprintf(zLineNum,"%d",lineno);
1108 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
1109 rc = TCL_ERROR;
1110 }
1111 break;
1112 }
1113
drhdcd997e2003-01-31 17:21:49 +00001114 /*
1115 ** $db errorcode
1116 **
1117 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00001118 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00001119 */
1120 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00001121 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00001122 break;
1123 }
drh75897232000-05-29 14:26:00 +00001124
1125 /*
drh895d7472004-08-20 16:02:39 +00001126 ** $db eval $sql ?array? ?{ ...code... }?
drh1807ce32004-09-07 13:20:35 +00001127 ** $db onecolumn $sql
drh75897232000-05-29 14:26:00 +00001128 **
1129 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00001130 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00001131 ** If "array" and "code" are omitted, then no callback is every invoked.
1132 ** If "array" is an empty string, then the values are placed in variables
1133 ** that have the same name as the fields extracted by the query.
drh1807ce32004-09-07 13:20:35 +00001134 **
1135 ** The onecolumn method is the equivalent of:
1136 ** lindex [$db eval $sql] 0
drh75897232000-05-29 14:26:00 +00001137 */
drh1807ce32004-09-07 13:20:35 +00001138 case DB_ONECOLUMN:
drh6d313162000-09-21 13:01:35 +00001139 case DB_EVAL: {
drh9d74b4c2004-08-24 15:23:34 +00001140 char const *zSql; /* Next SQL statement to execute */
1141 char const *zLeft; /* What is left after first stmt in zSql */
1142 sqlite3_stmt *pStmt; /* Compiled SQL statment */
drh92febd92004-08-20 18:34:20 +00001143 Tcl_Obj *pArray; /* Name of array into which results are written */
1144 Tcl_Obj *pScript; /* Script to run for each result set */
drh1d895032004-08-26 00:56:05 +00001145 Tcl_Obj **apParm; /* Parameters that need a Tcl_DecrRefCount() */
1146 int nParm; /* Number of entries used in apParm[] */
1147 Tcl_Obj *aParm[10]; /* Static space for apParm[] in the common case */
drh1807ce32004-09-07 13:20:35 +00001148 Tcl_Obj *pRet; /* Value to be returned */
drhfb7e7652005-01-24 00:28:42 +00001149 SqlPreparedStmt *pPreStmt; /* Pointer to a prepared statement */
1150 int rc2;
danielk1977ef2cb632004-05-29 02:37:19 +00001151
drh1807ce32004-09-07 13:20:35 +00001152 if( choice==DB_ONECOLUMN ){
1153 if( objc!=3 ){
1154 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
1155 return TCL_ERROR;
1156 }
1157 pRet = 0;
1158 }else{
1159 if( objc<3 || objc>5 ){
1160 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
1161 return TCL_ERROR;
1162 }
1163 pRet = Tcl_NewObj();
1164 Tcl_IncrRefCount(pRet);
danielk197730ccda12004-05-27 12:11:31 +00001165 }
drh92febd92004-08-20 18:34:20 +00001166 if( objc==3 ){
1167 pArray = pScript = 0;
1168 }else if( objc==4 ){
1169 pArray = 0;
1170 pScript = objv[3];
1171 }else{
1172 pArray = objv[3];
1173 if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
1174 pScript = objv[4];
1175 }
danielk197730ccda12004-05-27 12:11:31 +00001176
drh1d895032004-08-26 00:56:05 +00001177 Tcl_IncrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001178 zSql = Tcl_GetStringFromObj(objv[2], 0);
drh90b6bb12004-09-13 13:16:31 +00001179 while( rc==TCL_OK && zSql[0] ){
drhfb7e7652005-01-24 00:28:42 +00001180 int i; /* Loop counter */
1181 int nVar; /* Number of bind parameters in the pStmt */
1182 int nCol; /* Number of columns in the result set */
drh92febd92004-08-20 18:34:20 +00001183 Tcl_Obj **apColName = 0; /* Array of column names */
drhfb7e7652005-01-24 00:28:42 +00001184 int len; /* String length of zSql */
danielk197730ccda12004-05-27 12:11:31 +00001185
drhfb7e7652005-01-24 00:28:42 +00001186 /* Try to find a SQL statement that has already been compiled and
1187 ** which matches the next sequence of SQL.
1188 */
1189 pStmt = 0;
1190 pPreStmt = pDb->stmtList;
1191 len = strlen(zSql);
1192 if( pPreStmt && sqlite3_expired(pPreStmt->pStmt) ){
1193 flushStmtCache(pDb);
1194 pPreStmt = 0;
danielk197730ccda12004-05-27 12:11:31 +00001195 }
drhfb7e7652005-01-24 00:28:42 +00001196 for(; pPreStmt; pPreStmt=pPreStmt->pNext){
1197 int n = pPreStmt->nSql;
1198 if( len>=n
1199 && memcmp(pPreStmt->zSql, zSql, n)==0
1200 && (zSql[n]==0 || zSql[n-1]==';')
1201 ){
1202 pStmt = pPreStmt->pStmt;
1203 zLeft = &zSql[pPreStmt->nSql];
1204
1205 /* When a prepared statement is found, unlink it from the
1206 ** cache list. It will later be added back to the beginning
1207 ** of the cache list in order to implement LRU replacement.
1208 */
1209 if( pPreStmt->pPrev ){
1210 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1211 }else{
1212 pDb->stmtList = pPreStmt->pNext;
1213 }
1214 if( pPreStmt->pNext ){
1215 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1216 }else{
1217 pDb->stmtLast = pPreStmt->pPrev;
1218 }
1219 pDb->nStmt--;
1220 break;
1221 }
1222 }
1223
1224 /* If no prepared statement was found. Compile the SQL text
1225 */
drh92febd92004-08-20 18:34:20 +00001226 if( pStmt==0 ){
drhfb7e7652005-01-24 00:28:42 +00001227 if( SQLITE_OK!=sqlite3_prepare(pDb->db, zSql, -1, &pStmt, &zLeft) ){
drh92febd92004-08-20 18:34:20 +00001228 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1229 rc = TCL_ERROR;
1230 break;
danielk197730ccda12004-05-27 12:11:31 +00001231 }
drhfb7e7652005-01-24 00:28:42 +00001232 if( pStmt==0 ){
1233 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1234 /* A compile-time error in the statement
1235 */
1236 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1237 rc = TCL_ERROR;
1238 break;
1239 }else{
1240 /* The statement was a no-op. Continue to the next statement
1241 ** in the SQL string.
1242 */
1243 zSql = zLeft;
1244 continue;
1245 }
1246 }
1247 assert( pPreStmt==0 );
danielk197730ccda12004-05-27 12:11:31 +00001248 }
1249
drhfb7e7652005-01-24 00:28:42 +00001250 /* Bind values to parameters that begin with $ or :
1251 */
drh92febd92004-08-20 18:34:20 +00001252 nVar = sqlite3_bind_parameter_count(pStmt);
drh1d895032004-08-26 00:56:05 +00001253 nParm = 0;
1254 if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
1255 apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
1256 }else{
1257 apParm = aParm;
1258 }
drh92febd92004-08-20 18:34:20 +00001259 for(i=1; i<=nVar; i++){
1260 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
drhc8f90792005-01-12 00:08:24 +00001261 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':') ){
drh92febd92004-08-20 18:34:20 +00001262 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1263 if( pVar ){
1264 int n;
1265 u8 *data;
1266 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
1267 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +00001268 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
1269 /* Only load a BLOB type if the Tcl variable is a bytearray and
1270 ** has no string representation. */
drh92febd92004-08-20 18:34:20 +00001271 data = Tcl_GetByteArrayFromObj(pVar, &n);
1272 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001273 Tcl_IncrRefCount(pVar);
1274 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001275 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
1276 (c=='i' && strcmp(zType,"int")==0) ){
1277 Tcl_GetIntFromObj(interp, pVar, &n);
1278 sqlite3_bind_int(pStmt, i, n);
1279 }else if( c=='d' && strcmp(zType,"double")==0 ){
1280 double r;
1281 Tcl_GetDoubleFromObj(interp, pVar, &r);
1282 sqlite3_bind_double(pStmt, i, r);
drhdf0bdda2005-06-25 19:31:48 +00001283 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
1284 Tcl_WideInt v;
1285 Tcl_GetWideIntFromObj(interp, pVar, &v);
1286 sqlite3_bind_int64(pStmt, i, v);
drh92febd92004-08-20 18:34:20 +00001287 }else{
1288 data = Tcl_GetStringFromObj(pVar, &n);
1289 sqlite3_bind_text(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001290 Tcl_IncrRefCount(pVar);
1291 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001292 }
drhfb7e7652005-01-24 00:28:42 +00001293 }else{
1294 sqlite3_bind_null( pStmt, i );
drh92febd92004-08-20 18:34:20 +00001295 }
1296 }
1297 }
drh92febd92004-08-20 18:34:20 +00001298
1299 /* Compute column names */
1300 nCol = sqlite3_column_count(pStmt);
1301 if( pScript ){
1302 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1303 if( apColName==0 ) break;
1304 for(i=0; i<nCol; i++){
1305 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1306 Tcl_IncrRefCount(apColName[i]);
1307 }
1308 }
1309
1310 /* If results are being stored in an array variable, then create
1311 ** the array(*) entry for that array
1312 */
1313 if( pArray ){
1314 Tcl_Obj *pColList = Tcl_NewObj();
drh3ced14a2005-03-31 18:26:20 +00001315 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
drh92febd92004-08-20 18:34:20 +00001316 Tcl_IncrRefCount(pColList);
1317 for(i=0; i<nCol; i++){
1318 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1319 }
drh3ced14a2005-03-31 18:26:20 +00001320 Tcl_ObjSetVar2(interp, pArray, pStar, pColList,0);
1321 Tcl_DecrRefCount(pColList);
1322 Tcl_DecrRefCount(pStar);
drh92febd92004-08-20 18:34:20 +00001323 }
1324
1325 /* Execute the SQL
1326 */
drh90b6bb12004-09-13 13:16:31 +00001327 while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
drh92febd92004-08-20 18:34:20 +00001328 for(i=0; i<nCol; i++){
danielk197730ccda12004-05-27 12:11:31 +00001329 Tcl_Obj *pVal;
1330
1331 /* Set pVal to contain the i'th column of this row. */
drh92febd92004-08-20 18:34:20 +00001332 switch( sqlite3_column_type(pStmt, i) ){
1333 case SQLITE_BLOB: {
1334 int bytes = sqlite3_column_bytes(pStmt, i);
1335 pVal = Tcl_NewByteArrayObj(sqlite3_column_blob(pStmt, i), bytes);
1336 break;
1337 }
1338 case SQLITE_INTEGER: {
1339 sqlite_int64 v = sqlite3_column_int64(pStmt, i);
1340 if( v>=-2147483647 && v<=2147483647 ){
1341 pVal = Tcl_NewIntObj(v);
1342 }else{
1343 pVal = Tcl_NewWideIntObj(v);
1344 }
1345 break;
1346 }
1347 case SQLITE_FLOAT: {
1348 double r = sqlite3_column_double(pStmt, i);
1349 pVal = Tcl_NewDoubleObj(r);
1350 break;
1351 }
danielk197755c45f22005-04-03 23:54:43 +00001352 case SQLITE_NULL: {
1353 pVal = dbTextToObj(pDb->zNull);
1354 break;
1355 }
drh92febd92004-08-20 18:34:20 +00001356 default: {
1357 pVal = dbTextToObj(sqlite3_column_text(pStmt, i));
1358 break;
1359 }
danielk197730ccda12004-05-27 12:11:31 +00001360 }
1361
drh92febd92004-08-20 18:34:20 +00001362 if( pScript ){
1363 if( pArray==0 ){
1364 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001365 }else{
drh92febd92004-08-20 18:34:20 +00001366 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001367 }
drh1807ce32004-09-07 13:20:35 +00001368 }else if( choice==DB_ONECOLUMN ){
1369 if( pRet==0 ){
1370 pRet = pVal;
1371 Tcl_IncrRefCount(pRet);
1372 }
drh90b6bb12004-09-13 13:16:31 +00001373 rc = TCL_BREAK;
danielk197730ccda12004-05-27 12:11:31 +00001374 }else{
danielk197730ccda12004-05-27 12:11:31 +00001375 Tcl_ListObjAppendElement(interp, pRet, pVal);
1376 }
1377 }
1378
drh92febd92004-08-20 18:34:20 +00001379 if( pScript ){
1380 rc = Tcl_EvalObjEx(interp, pScript, 0);
drh90b6bb12004-09-13 13:16:31 +00001381 if( rc==TCL_CONTINUE ){
1382 rc = TCL_OK;
1383 }
danielk197730ccda12004-05-27 12:11:31 +00001384 }
1385 }
drh90b6bb12004-09-13 13:16:31 +00001386 if( rc==TCL_BREAK ){
1387 rc = TCL_OK;
1388 }
drh92febd92004-08-20 18:34:20 +00001389
1390 /* Free the column name objects */
1391 if( pScript ){
1392 for(i=0; i<nCol; i++){
1393 Tcl_DecrRefCount(apColName[i]);
1394 }
1395 Tcl_Free((char*)apColName);
1396 }
1397
drh1d895032004-08-26 00:56:05 +00001398 /* Free the bound string and blob parameters */
1399 for(i=0; i<nParm; i++){
1400 Tcl_DecrRefCount(apParm[i]);
1401 }
1402 if( apParm!=aParm ){
1403 Tcl_Free((char*)apParm);
1404 }
1405
drhfb7e7652005-01-24 00:28:42 +00001406 /* Reset the statement. If the result code is SQLITE_SCHEMA, then
1407 ** flush the statement cache and try the statement again.
drh92febd92004-08-20 18:34:20 +00001408 */
drhfb7e7652005-01-24 00:28:42 +00001409 rc2 = sqlite3_reset(pStmt);
1410 if( SQLITE_SCHEMA==rc2 ){
1411 /* After a schema change, flush the cache and try to run the
1412 ** statement again
1413 */
1414 flushStmtCache( pDb );
1415 sqlite3_finalize(pStmt);
1416 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001417 continue;
drhfb7e7652005-01-24 00:28:42 +00001418 }else if( SQLITE_OK!=rc2 ){
1419 /* If a run-time error occurs, report the error and stop reading
1420 ** the SQL
1421 */
danielk1977ef2cb632004-05-29 02:37:19 +00001422 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
drhfb7e7652005-01-24 00:28:42 +00001423 sqlite3_finalize(pStmt);
danielk197730ccda12004-05-27 12:11:31 +00001424 rc = TCL_ERROR;
drhfb7e7652005-01-24 00:28:42 +00001425 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001426 break;
drhfb7e7652005-01-24 00:28:42 +00001427 }else if( pDb->maxStmt<=0 ){
1428 /* If the cache is turned off, deallocated the statement */
1429 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1430 sqlite3_finalize(pStmt);
1431 }else{
1432 /* Everything worked and the cache is operational.
1433 ** Create a new SqlPreparedStmt structure if we need one.
1434 ** (If we already have one we can just reuse it.)
1435 */
1436 if( pPreStmt==0 ){
1437 len = zLeft - zSql;
1438 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) + len );
1439 if( pPreStmt==0 ) return TCL_ERROR;
1440 pPreStmt->pStmt = pStmt;
1441 pPreStmt->nSql = len;
1442 memcpy(pPreStmt->zSql, zSql, len);
1443 pPreStmt->zSql[len] = 0;
1444 }
1445
1446 /* Add the prepared statement to the beginning of the cache list
1447 */
1448 pPreStmt->pNext = pDb->stmtList;
1449 pPreStmt->pPrev = 0;
1450 if( pDb->stmtList ){
1451 pDb->stmtList->pPrev = pPreStmt;
1452 }
1453 pDb->stmtList = pPreStmt;
1454 if( pDb->stmtLast==0 ){
1455 assert( pDb->nStmt==0 );
1456 pDb->stmtLast = pPreStmt;
1457 }else{
1458 assert( pDb->nStmt>0 );
1459 }
1460 pDb->nStmt++;
1461
1462 /* If we have too many statement in cache, remove the surplus from the
1463 ** end of the cache list.
1464 */
1465 while( pDb->nStmt>pDb->maxStmt ){
1466 sqlite3_finalize(pDb->stmtLast->pStmt);
1467 pDb->stmtLast = pDb->stmtLast->pPrev;
1468 Tcl_Free((char*)pDb->stmtLast->pNext);
1469 pDb->stmtLast->pNext = 0;
1470 pDb->nStmt--;
1471 }
danielk197730ccda12004-05-27 12:11:31 +00001472 }
1473
drhfb7e7652005-01-24 00:28:42 +00001474 /* Proceed to the next statement */
danielk197730ccda12004-05-27 12:11:31 +00001475 zSql = zLeft;
1476 }
drh1d895032004-08-26 00:56:05 +00001477 Tcl_DecrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001478
drh1807ce32004-09-07 13:20:35 +00001479 if( pRet ){
1480 if( rc==TCL_OK ){
1481 Tcl_SetObjResult(interp, pRet);
1482 }
1483 Tcl_DecrRefCount(pRet);
danielk197730ccda12004-05-27 12:11:31 +00001484 }
danielk197730ccda12004-05-27 12:11:31 +00001485 break;
1486 }
drhbec3f402000-08-04 13:49:02 +00001487
1488 /*
drhcabb0812002-09-14 13:47:32 +00001489 ** $db function NAME SCRIPT
1490 **
1491 ** Create a new SQL function called NAME. Whenever that function is
1492 ** called, invoke SCRIPT to evaluate the function.
1493 */
1494 case DB_FUNCTION: {
1495 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00001496 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00001497 char *zName;
drhcabb0812002-09-14 13:47:32 +00001498 if( objc!=4 ){
1499 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1500 return TCL_ERROR;
1501 }
1502 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00001503 pScript = objv[3];
1504 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00001505 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00001506 if( pFunc->pScript ){
1507 Tcl_DecrRefCount(pFunc->pScript);
1508 }
1509 pFunc->pScript = pScript;
1510 Tcl_IncrRefCount(pScript);
1511 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
danielk1977c8c11582004-06-29 13:41:21 +00001512 rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00001513 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00001514 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00001515 rc = TCL_ERROR;
1516 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00001517 }else{
1518 /* Must flush any cached statements */
1519 flushStmtCache( pDb );
1520 }
drhcabb0812002-09-14 13:47:32 +00001521 break;
1522 }
1523
1524 /*
drh19e2d372005-08-29 23:00:03 +00001525 ** $db nullvalue ?STRING?
1526 **
1527 ** Change text used when a NULL comes back from the database. If ?STRING?
1528 ** is not present, then the current string used for NULL is returned.
1529 ** If STRING is present, then STRING is returned.
1530 **
1531 */
1532 case DB_NULLVALUE: {
1533 if( objc!=2 && objc!=3 ){
1534 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
1535 return TCL_ERROR;
1536 }
1537 if( objc==3 ){
1538 int len;
1539 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
1540 if( pDb->zNull ){
1541 Tcl_Free(pDb->zNull);
1542 }
1543 if( zNull && len>0 ){
1544 pDb->zNull = Tcl_Alloc( len + 1 );
1545 strncpy(pDb->zNull, zNull, len);
1546 pDb->zNull[len] = '\0';
1547 }else{
1548 pDb->zNull = 0;
1549 }
1550 }
1551 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
1552 break;
1553 }
1554
1555 /*
drhaf9ff332002-01-16 21:00:27 +00001556 ** $db last_insert_rowid
1557 **
1558 ** Return an integer which is the ROWID for the most recent insert.
1559 */
1560 case DB_LAST_INSERT_ROWID: {
1561 Tcl_Obj *pResult;
1562 int rowid;
1563 if( objc!=2 ){
1564 Tcl_WrongNumArgs(interp, 2, objv, "");
1565 return TCL_ERROR;
1566 }
danielk19776f8a5032004-05-10 10:34:51 +00001567 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00001568 pResult = Tcl_GetObjResult(interp);
1569 Tcl_SetIntObj(pResult, rowid);
1570 break;
1571 }
1572
1573 /*
drh1807ce32004-09-07 13:20:35 +00001574 ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
drh5d9d7572003-08-19 14:31:01 +00001575 */
drh1807ce32004-09-07 13:20:35 +00001576
1577 /* $db progress ?N CALLBACK?
1578 **
1579 ** Invoke the given callback every N virtual machine opcodes while executing
1580 ** queries.
1581 */
1582 case DB_PROGRESS: {
1583 if( objc==2 ){
1584 if( pDb->zProgress ){
1585 Tcl_AppendResult(interp, pDb->zProgress, 0);
1586 }
1587 }else if( objc==4 ){
1588 char *zProgress;
1589 int len;
1590 int N;
1591 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
1592 return TCL_ERROR;
1593 };
1594 if( pDb->zProgress ){
1595 Tcl_Free(pDb->zProgress);
1596 }
1597 zProgress = Tcl_GetStringFromObj(objv[3], &len);
1598 if( zProgress && len>0 ){
1599 pDb->zProgress = Tcl_Alloc( len + 1 );
1600 strcpy(pDb->zProgress, zProgress);
1601 }else{
1602 pDb->zProgress = 0;
1603 }
1604#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1605 if( pDb->zProgress ){
1606 pDb->interp = interp;
1607 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
1608 }else{
1609 sqlite3_progress_handler(pDb->db, 0, 0, 0);
1610 }
1611#endif
1612 }else{
1613 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00001614 return TCL_ERROR;
1615 }
drh5d9d7572003-08-19 14:31:01 +00001616 break;
1617 }
1618
drh19e2d372005-08-29 23:00:03 +00001619 /* $db profile ?CALLBACK?
1620 **
1621 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
1622 ** that has run. The text of the SQL and the amount of elapse time are
1623 ** appended to CALLBACK before the script is run.
1624 */
1625 case DB_PROFILE: {
1626 if( objc>3 ){
1627 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1628 return TCL_ERROR;
1629 }else if( objc==2 ){
1630 if( pDb->zProfile ){
1631 Tcl_AppendResult(interp, pDb->zProfile, 0);
1632 }
1633 }else{
1634 char *zProfile;
1635 int len;
1636 if( pDb->zProfile ){
1637 Tcl_Free(pDb->zProfile);
1638 }
1639 zProfile = Tcl_GetStringFromObj(objv[2], &len);
1640 if( zProfile && len>0 ){
1641 pDb->zProfile = Tcl_Alloc( len + 1 );
1642 strcpy(pDb->zProfile, zProfile);
1643 }else{
1644 pDb->zProfile = 0;
1645 }
1646#ifndef SQLITE_OMIT_TRACE
1647 if( pDb->zProfile ){
1648 pDb->interp = interp;
1649 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
1650 }else{
1651 sqlite3_profile(pDb->db, 0, 0);
1652 }
1653#endif
1654 }
1655 break;
1656 }
1657
drh5d9d7572003-08-19 14:31:01 +00001658 /*
drh22fbcb82004-02-01 01:22:50 +00001659 ** $db rekey KEY
1660 **
1661 ** Change the encryption key on the currently open database.
1662 */
1663 case DB_REKEY: {
1664 int nKey;
1665 void *pKey;
1666 if( objc!=3 ){
1667 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
1668 return TCL_ERROR;
1669 }
1670 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00001671#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00001672 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00001673 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00001674 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00001675 rc = TCL_ERROR;
1676 }
1677#endif
1678 break;
1679 }
1680
1681 /*
drhbec3f402000-08-04 13:49:02 +00001682 ** $db timeout MILLESECONDS
1683 **
1684 ** Delay for the number of milliseconds specified when a file is locked.
1685 */
drh6d313162000-09-21 13:01:35 +00001686 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00001687 int ms;
drh6d313162000-09-21 13:01:35 +00001688 if( objc!=3 ){
1689 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00001690 return TCL_ERROR;
1691 }
drh6d313162000-09-21 13:01:35 +00001692 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00001693 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00001694 break;
drh75897232000-05-29 14:26:00 +00001695 }
danielk197755c45f22005-04-03 23:54:43 +00001696
1697 /*
drh0f14e2e2004-06-29 12:39:08 +00001698 ** $db total_changes
1699 **
1700 ** Return the number of rows that were modified, inserted, or deleted
1701 ** since the database handle was created.
1702 */
1703 case DB_TOTAL_CHANGES: {
1704 Tcl_Obj *pResult;
1705 if( objc!=2 ){
1706 Tcl_WrongNumArgs(interp, 2, objv, "");
1707 return TCL_ERROR;
1708 }
1709 pResult = Tcl_GetObjResult(interp);
1710 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
1711 break;
1712 }
1713
drhb5a20d32003-04-23 12:25:23 +00001714 /* $db trace ?CALLBACK?
1715 **
1716 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
1717 ** that is executed. The text of the SQL is appended to CALLBACK before
1718 ** it is executed.
1719 */
1720 case DB_TRACE: {
1721 if( objc>3 ){
1722 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00001723 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00001724 }else if( objc==2 ){
1725 if( pDb->zTrace ){
1726 Tcl_AppendResult(interp, pDb->zTrace, 0);
1727 }
1728 }else{
1729 char *zTrace;
1730 int len;
1731 if( pDb->zTrace ){
1732 Tcl_Free(pDb->zTrace);
1733 }
1734 zTrace = Tcl_GetStringFromObj(objv[2], &len);
1735 if( zTrace && len>0 ){
1736 pDb->zTrace = Tcl_Alloc( len + 1 );
1737 strcpy(pDb->zTrace, zTrace);
1738 }else{
1739 pDb->zTrace = 0;
1740 }
drh19e2d372005-08-29 23:00:03 +00001741#ifndef SQLITE_OMIT_TRACE
drhb5a20d32003-04-23 12:25:23 +00001742 if( pDb->zTrace ){
1743 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001744 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00001745 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001746 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00001747 }
drh19e2d372005-08-29 23:00:03 +00001748#endif
drhb5a20d32003-04-23 12:25:23 +00001749 }
1750 break;
1751 }
1752
drh3d214232005-08-02 12:21:08 +00001753 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1754 **
1755 ** Start a new transaction (if we are not already in the midst of a
1756 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
1757 ** completes, either commit the transaction or roll it back if SCRIPT
1758 ** throws an exception. Or if no new transation was started, do nothing.
1759 ** pass the exception on up the stack.
1760 **
1761 ** This command was inspired by Dave Thomas's talk on Ruby at the
1762 ** 2005 O'Reilly Open Source Convention (OSCON).
1763 */
1764 case DB_TRANSACTION: {
1765 int inTrans;
1766 Tcl_Obj *pScript;
1767 const char *zBegin = "BEGIN";
1768 if( objc!=3 && objc!=4 ){
1769 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
1770 return TCL_ERROR;
1771 }
1772 if( objc==3 ){
1773 pScript = objv[2];
1774 } else {
1775 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00001776 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00001777 };
1778 enum TTYPE_enum {
1779 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
1780 };
1781 int ttype;
drhb5555e72005-08-02 17:15:14 +00001782 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00001783 0, &ttype) ){
1784 return TCL_ERROR;
1785 }
1786 switch( (enum TTYPE_enum)ttype ){
1787 case TTYPE_DEFERRED: /* no-op */; break;
1788 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
1789 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
1790 }
1791 pScript = objv[3];
1792 }
1793 inTrans = !sqlite3_get_autocommit(pDb->db);
1794 if( !inTrans ){
1795 sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
1796 }
1797 rc = Tcl_EvalObjEx(interp, pScript, 0);
1798 if( !inTrans ){
1799 const char *zEnd;
1800 if( rc==TCL_ERROR ){
1801 zEnd = "ROLLBACK";
1802 } else {
1803 zEnd = "COMMIT";
1804 }
1805 sqlite3_exec(pDb->db, zEnd, 0, 0, 0);
1806 }
1807 break;
1808 }
1809
danielk19774397de52005-01-12 12:44:03 +00001810 /* $db version
1811 **
1812 ** Return the version string for this database.
1813 */
1814 case DB_VERSION: {
1815 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
1816 break;
1817 }
1818
tpoindex1067fe12004-12-17 15:41:11 +00001819
drh6d313162000-09-21 13:01:35 +00001820 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00001821 return rc;
drh75897232000-05-29 14:26:00 +00001822}
1823
1824/*
drh9bb575f2004-09-06 17:24:11 +00001825** sqlite3 DBNAME FILENAME ?MODE? ?-key KEY?
drh75897232000-05-29 14:26:00 +00001826**
1827** This is the main Tcl command. When the "sqlite" Tcl command is
1828** invoked, this routine runs to process that command.
1829**
1830** The first argument, DBNAME, is an arbitrary name for a new
1831** database connection. This command creates a new command named
1832** DBNAME that is used to control that connection. The database
1833** connection is deleted when the DBNAME command is deleted.
1834**
1835** The second argument is the name of the directory that contains
1836** the sqlite database that is to be accessed.
drhfbc3eab2001-04-06 16:13:42 +00001837**
1838** For testing purposes, we also support the following:
1839**
drh9bb575f2004-09-06 17:24:11 +00001840** sqlite3 -encoding
drhfbc3eab2001-04-06 16:13:42 +00001841**
1842** Return the encoding used by LIKE and GLOB operators. Choices
1843** are UTF-8 and iso8859.
1844**
drh9bb575f2004-09-06 17:24:11 +00001845** sqlite3 -version
drh647cb0e2002-11-04 19:32:25 +00001846**
1847** Return the version number of the SQLite library.
1848**
drh9bb575f2004-09-06 17:24:11 +00001849** sqlite3 -tcl-uses-utf
drhfbc3eab2001-04-06 16:13:42 +00001850**
1851** Return "1" if compiled with a Tcl uses UTF-8. Return "0" if
1852** not. Used by tests to make sure the library was compiled
1853** correctly.
drh75897232000-05-29 14:26:00 +00001854*/
drh22fbcb82004-02-01 01:22:50 +00001855static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001856 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00001857 void *pKey = 0;
1858 int nKey = 0;
1859 const char *zArg;
drh75897232000-05-29 14:26:00 +00001860 char *zErrMsg;
drh22fbcb82004-02-01 01:22:50 +00001861 const char *zFile;
drh06b27182002-06-26 20:06:05 +00001862 char zBuf[80];
drh22fbcb82004-02-01 01:22:50 +00001863 if( objc==2 ){
1864 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00001865 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00001866 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00001867 return TCL_OK;
1868 }
drh9eb9e262004-02-11 02:18:05 +00001869 if( strcmp(zArg,"-has-codec")==0 ){
1870#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00001871 Tcl_AppendResult(interp,"1",0);
1872#else
1873 Tcl_AppendResult(interp,"0",0);
1874#endif
1875 return TCL_OK;
1876 }
1877 if( strcmp(zArg,"-tcl-uses-utf")==0 ){
drhfbc3eab2001-04-06 16:13:42 +00001878#ifdef TCL_UTF_MAX
1879 Tcl_AppendResult(interp,"1",0);
1880#else
1881 Tcl_AppendResult(interp,"0",0);
1882#endif
1883 return TCL_OK;
1884 }
1885 }
drh22fbcb82004-02-01 01:22:50 +00001886 if( objc==5 || objc==6 ){
1887 zArg = Tcl_GetStringFromObj(objv[objc-2], 0);
1888 if( strcmp(zArg,"-key")==0 ){
1889 pKey = Tcl_GetByteArrayFromObj(objv[objc-1], &nKey);
1890 objc -= 2;
1891 }
1892 }
1893 if( objc!=3 && objc!=4 ){
1894 Tcl_WrongNumArgs(interp, 1, objv,
drh9eb9e262004-02-11 02:18:05 +00001895#ifdef SQLITE_HAS_CODEC
1896 "HANDLE FILENAME ?-key CODEC-KEY?"
drh22fbcb82004-02-01 01:22:50 +00001897#else
1898 "HANDLE FILENAME ?MODE?"
1899#endif
1900 );
drh75897232000-05-29 14:26:00 +00001901 return TCL_ERROR;
1902 }
drh75897232000-05-29 14:26:00 +00001903 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00001904 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00001905 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00001906 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
1907 return TCL_ERROR;
1908 }
1909 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00001910 zFile = Tcl_GetStringFromObj(objv[2], 0);
danielk19774f057f92004-06-08 00:02:33 +00001911 sqlite3_open(zFile, &p->db);
danielk197780290862004-05-22 09:21:21 +00001912 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
1913 zErrMsg = strdup(sqlite3_errmsg(p->db));
1914 sqlite3_close(p->db);
1915 p->db = 0;
1916 }
drh2011d5f2004-07-22 02:40:37 +00001917#ifdef SQLITE_HAS_CODEC
1918 sqlite3_key(p->db, pKey, nKey);
drheb8ed702004-02-11 10:37:23 +00001919#endif
drhbec3f402000-08-04 13:49:02 +00001920 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00001921 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00001922 Tcl_Free((char*)p);
drh75897232000-05-29 14:26:00 +00001923 free(zErrMsg);
1924 return TCL_ERROR;
1925 }
drhfb7e7652005-01-24 00:28:42 +00001926 p->maxStmt = NUM_PREPARED_STMTS;
drh22fbcb82004-02-01 01:22:50 +00001927 zArg = Tcl_GetStringFromObj(objv[1], 0);
1928 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
drhc22bd472002-05-10 13:14:07 +00001929
drh06b27182002-06-26 20:06:05 +00001930 /* The return value is the value of the sqlite* pointer
1931 */
1932 sprintf(zBuf, "%p", p->db);
drh5e5377f2002-07-07 17:12:36 +00001933 if( strncmp(zBuf,"0x",2) ){
1934 sprintf(zBuf, "0x%p", p->db);
1935 }
drh06b27182002-06-26 20:06:05 +00001936 Tcl_AppendResult(interp, zBuf, 0);
1937
drhc22bd472002-05-10 13:14:07 +00001938 /* If compiled with SQLITE_TEST turned on, then register the "md5sum"
drh06b27182002-06-26 20:06:05 +00001939 ** SQL function.
drhc22bd472002-05-10 13:14:07 +00001940 */
drh28b4e482002-03-11 02:06:13 +00001941#ifdef SQLITE_TEST
1942 {
drh9bb575f2004-09-06 17:24:11 +00001943 extern void Md5_Register(sqlite3*);
drh3b93bc82005-01-13 23:54:32 +00001944#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00001945 int mallocfail = sqlite3_iMallocFail;
1946 sqlite3_iMallocFail = 0;
danielk19775b59af82004-06-30 12:42:59 +00001947#endif
drhc22bd472002-05-10 13:14:07 +00001948 Md5_Register(p->db);
drh3b93bc82005-01-13 23:54:32 +00001949#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00001950 sqlite3_iMallocFail = mallocfail;
danielk19775b59af82004-06-30 12:42:59 +00001951#endif
drh06b27182002-06-26 20:06:05 +00001952 }
drh28b4e482002-03-11 02:06:13 +00001953#endif
danielk19777cedc8d2004-06-10 10:50:08 +00001954 p->interp = interp;
drh75897232000-05-29 14:26:00 +00001955 return TCL_OK;
1956}
1957
1958/*
drh90ca9752001-09-28 17:47:14 +00001959** Provide a dummy Tcl_InitStubs if we are using this as a static
1960** library.
1961*/
1962#ifndef USE_TCL_STUBS
1963# undef Tcl_InitStubs
1964# define Tcl_InitStubs(a,b,c)
1965#endif
1966
1967/*
drh29bc4612005-10-05 10:40:15 +00001968** Make sure we have a PACKAGE_VERSION macro defined. This will be
1969** defined automatically by the TEA makefile. But other makefiles
1970** do not define it.
1971*/
1972#ifndef PACKAGE_VERSION
1973# define PACKAGE_VERSION SQLITE_VERSION
1974#endif
1975
1976/*
drh75897232000-05-29 14:26:00 +00001977** Initialize this module.
1978**
1979** This Tcl module contains only a single new Tcl command named "sqlite".
1980** (Hence there is no namespace. There is no point in using a namespace
1981** if the extension only supplies one new name!) The "sqlite" command is
1982** used to open a new SQLite database. See the DbMain() routine above
1983** for additional information.
1984*/
drh29bc4612005-10-05 10:40:15 +00001985EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00001986 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00001987 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00001988 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh49766d62005-01-08 18:42:28 +00001989 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00001990 Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
drh90ca9752001-09-28 17:47:14 +00001991 return TCL_OK;
1992}
drh29bc4612005-10-05 10:40:15 +00001993EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
1994EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
1995EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00001996
1997#ifndef SQLITE_3_SUFFIX_ONLY
drh29bc4612005-10-05 10:40:15 +00001998EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
1999EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2000EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2001EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002002#endif
drh75897232000-05-29 14:26:00 +00002003
drh3e27c022004-07-23 00:01:38 +00002004#ifdef TCLSH
2005/*****************************************************************************
2006** The code that follows is used to build standalone TCL interpreters
drh75897232000-05-29 14:26:00 +00002007*/
drh348784e2000-05-29 20:41:49 +00002008
2009/*
drh3e27c022004-07-23 00:01:38 +00002010** If the macro TCLSH is one, then put in code this for the
2011** "main" routine that will initialize Tcl and take input from
2012** standard input.
drh348784e2000-05-29 20:41:49 +00002013*/
drh3e27c022004-07-23 00:01:38 +00002014#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00002015static char zMainloop[] =
2016 "set line {}\n"
2017 "while {![eof stdin]} {\n"
2018 "if {$line!=\"\"} {\n"
2019 "puts -nonewline \"> \"\n"
2020 "} else {\n"
2021 "puts -nonewline \"% \"\n"
2022 "}\n"
2023 "flush stdout\n"
2024 "append line [gets stdin]\n"
2025 "if {[info complete $line]} {\n"
2026 "if {[catch {uplevel #0 $line} result]} {\n"
2027 "puts stderr \"Error: $result\"\n"
2028 "} elseif {$result!=\"\"} {\n"
2029 "puts $result\n"
2030 "}\n"
2031 "set line {}\n"
2032 "} else {\n"
2033 "append line \\n\n"
2034 "}\n"
2035 "}\n"
2036;
drh3e27c022004-07-23 00:01:38 +00002037#endif
2038
2039/*
2040** If the macro TCLSH is two, then get the main loop code out of
2041** the separate file "spaceanal_tcl.h".
2042*/
2043#if TCLSH==2
2044static char zMainloop[] =
2045#include "spaceanal_tcl.h"
2046;
2047#endif
drh348784e2000-05-29 20:41:49 +00002048
2049#define TCLSH_MAIN main /* Needed to fake out mktclapp */
2050int TCLSH_MAIN(int argc, char **argv){
2051 Tcl_Interp *interp;
drh297ecf12001-04-05 15:57:13 +00002052 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00002053 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00002054 Sqlite3_Init(interp);
drhd9b02572001-04-15 00:37:09 +00002055#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00002056 {
2057 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00002058 extern int Sqlitetest2_Init(Tcl_Interp*);
2059 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00002060 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00002061 extern int Sqlitetest5_Init(Tcl_Interp*);
drhefc251d2001-07-01 22:12:01 +00002062 extern int Md5_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002063 extern int Sqlitetestsse_Init(Tcl_Interp*);
2064
danielk19776490beb2004-05-11 06:17:21 +00002065 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00002066 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00002067 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00002068 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00002069 Sqlitetest5_Init(interp);
drhefc251d2001-07-01 22:12:01 +00002070 Md5_Init(interp);
drh89dec812005-04-28 19:03:37 +00002071#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00002072 Sqlitetestsse_Init(interp);
2073#endif
drhd1bf3512001-04-07 15:24:33 +00002074 }
2075#endif
drh3e27c022004-07-23 00:01:38 +00002076 if( argc>=2 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002077 int i;
2078 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
2079 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00002080 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00002081 Tcl_SetVar(interp, "argv", argv[i],
2082 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
2083 }
drh3e27c022004-07-23 00:01:38 +00002084 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00002085 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drhc61053b2000-06-04 12:58:36 +00002086 if( zInfo==0 ) zInfo = interp->result;
2087 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00002088 return 1;
2089 }
drh3e27c022004-07-23 00:01:38 +00002090 }
2091 if( argc<=1 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002092 Tcl_GlobalEval(interp, zMainloop);
2093 }
2094 return 0;
2095}
2096#endif /* TCLSH */
drh6d313162000-09-21 13:01:35 +00002097
2098#endif /* !defined(NO_TCL) */