blob: e7b2ac4677e372c1595d03dd849f557d62f9b937 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
drhbd08af42007-04-05 21:58:33 +000012** A TCL Interface to SQLite. Append this file to sqlite3.c and
13** compile the whole thing to build a TCL-enabled version of SQLite.
drh75897232000-05-29 14:26:00 +000014**
drhbd08af42007-04-05 21:58:33 +000015** $Id: tclsqlite.c,v 1.178 2007/04/05 21:58:33 drh Exp $
drh75897232000-05-29 14:26:00 +000016*/
drh17a68932001-01-31 13:28:08 +000017#include "tcl.h"
drhbd08af42007-04-05 21:58:33 +000018
19/*
20** Some additional include files are needed if this file is not
21** appended to the amalgamation.
22*/
23#ifndef SQLITE_AMALGAMATION
24# include "sqliteInt.h"
25# include "hash.h"
26# include <stdlib.h>
27# include <string.h>
28# include <assert.h>
29# include <ctype.h>
30#endif
drh75897232000-05-29 14:26:00 +000031
drhad6e1372006-07-10 21:15:51 +000032/*
33 * Windows needs to know which symbols to export. Unix does not.
34 * BUILD_sqlite should be undefined for Unix.
35 */
36#ifdef BUILD_sqlite
37#undef TCL_STORAGE_CLASS
38#define TCL_STORAGE_CLASS DLLEXPORT
39#endif /* BUILD_sqlite */
drh29bc4612005-10-05 10:40:15 +000040
danielk1977a21c6b62005-01-24 10:25:59 +000041#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000042#define MAX_PREPARED_STMTS 100
43
drh75897232000-05-29 14:26:00 +000044/*
drh98808ba2001-10-18 12:34:46 +000045** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
46** have to do a translation when going between the two. Set the
47** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
48** this translation.
49*/
50#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
51# define UTF_TRANSLATION_NEEDED 1
52#endif
53
54/*
drhcabb0812002-09-14 13:47:32 +000055** New SQL functions can be created as TCL scripts. Each such function
56** is described by an instance of the following structure.
57*/
58typedef struct SqlFunc SqlFunc;
59struct SqlFunc {
60 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000061 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
62 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
63 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000064 SqlFunc *pNext; /* Next function on the list of them all */
65};
66
67/*
danielk19770202b292004-06-09 09:55:16 +000068** New collation sequences function can be created as TCL scripts. Each such
69** function is described by an instance of the following structure.
70*/
71typedef struct SqlCollate SqlCollate;
72struct SqlCollate {
73 Tcl_Interp *interp; /* The TCL interpret to execute the function */
74 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000075 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000076};
77
78/*
drhfb7e7652005-01-24 00:28:42 +000079** Prepared statements are cached for faster execution. Each prepared
80** statement is described by an instance of the following structure.
81*/
82typedef struct SqlPreparedStmt SqlPreparedStmt;
83struct SqlPreparedStmt {
84 SqlPreparedStmt *pNext; /* Next in linked list */
85 SqlPreparedStmt *pPrev; /* Previous on the list */
86 sqlite3_stmt *pStmt; /* The prepared statement */
87 int nSql; /* chars in zSql[] */
88 char zSql[1]; /* Text of the SQL statement */
89};
90
91/*
drhbec3f402000-08-04 13:49:02 +000092** There is one instance of this structure for each SQLite database
93** that has been opened by the SQLite TCL interface.
94*/
95typedef struct SqliteDb SqliteDb;
96struct SqliteDb {
drhdddca282006-01-03 00:33:50 +000097 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +000098 Tcl_Interp *interp; /* The interpreter used for this database */
99 char *zBusy; /* The busy callback routine */
100 char *zCommit; /* The commit hook callback routine */
101 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +0000102 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +0000103 char *zProgress; /* The progress callback routine */
104 char *zAuth; /* The authorization callback routine */
105 char *zNull; /* Text to substitute for an SQL NULL value */
106 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000107 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000108 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drhd1e47332005-06-26 17:55:33 +0000109 SqlCollate *pCollate; /* List of SQL collation functions */
110 int rc; /* Return code of most recent sqlite3_exec() */
111 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000112 SqlPreparedStmt *stmtList; /* List of prepared statements*/
113 SqlPreparedStmt *stmtLast; /* Last statement in the list */
114 int maxStmt; /* The next maximum number of stmtList */
115 int nStmt; /* Number of statements in stmtList */
drh98808ba2001-10-18 12:34:46 +0000116};
drh297ecf12001-04-05 15:57:13 +0000117
drh6d313162000-09-21 13:01:35 +0000118/*
drhd1e47332005-06-26 17:55:33 +0000119** Look at the script prefix in pCmd. We will be executing this script
120** after first appending one or more arguments. This routine analyzes
121** the script to see if it is safe to use Tcl_EvalObjv() on the script
122** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
123** faster.
124**
125** Scripts that are safe to use with Tcl_EvalObjv() consists of a
126** command name followed by zero or more arguments with no [...] or $
127** or {...} or ; to be seen anywhere. Most callback scripts consist
128** of just a single procedure name and they meet this requirement.
129*/
130static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
131 /* We could try to do something with Tcl_Parse(). But we will instead
132 ** just do a search for forbidden characters. If any of the forbidden
133 ** characters appear in pCmd, we will report the string as unsafe.
134 */
135 const char *z;
136 int n;
137 z = Tcl_GetStringFromObj(pCmd, &n);
138 while( n-- > 0 ){
139 int c = *(z++);
140 if( c=='$' || c=='[' || c==';' ) return 0;
141 }
142 return 1;
143}
144
145/*
146** Find an SqlFunc structure with the given name. Or create a new
147** one if an existing one cannot be found. Return a pointer to the
148** structure.
149*/
150static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
151 SqlFunc *p, *pNew;
152 int i;
153 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen(zName) + 1 );
154 pNew->zName = (char*)&pNew[1];
155 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
156 pNew->zName[i] = 0;
157 for(p=pDb->pFunc; p; p=p->pNext){
158 if( strcmp(p->zName, pNew->zName)==0 ){
159 Tcl_Free((char*)pNew);
160 return p;
161 }
162 }
163 pNew->interp = pDb->interp;
164 pNew->pScript = 0;
165 pNew->pNext = pDb->pFunc;
166 pDb->pFunc = pNew;
167 return pNew;
168}
169
170/*
drhfb7e7652005-01-24 00:28:42 +0000171** Finalize and free a list of prepared statements
172*/
173static void flushStmtCache( SqliteDb *pDb ){
174 SqlPreparedStmt *pPreStmt;
175
176 while( pDb->stmtList ){
177 sqlite3_finalize( pDb->stmtList->pStmt );
178 pPreStmt = pDb->stmtList;
179 pDb->stmtList = pDb->stmtList->pNext;
180 Tcl_Free( (char*)pPreStmt );
181 }
182 pDb->nStmt = 0;
183 pDb->stmtLast = 0;
184}
185
186/*
drh895d7472004-08-20 16:02:39 +0000187** TCL calls this procedure when an sqlite3 database command is
188** deleted.
drh75897232000-05-29 14:26:00 +0000189*/
190static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000191 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000192 flushStmtCache(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000193 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000194 while( pDb->pFunc ){
195 SqlFunc *pFunc = pDb->pFunc;
196 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000197 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000198 Tcl_Free((char*)pFunc);
199 }
danielk19770202b292004-06-09 09:55:16 +0000200 while( pDb->pCollate ){
201 SqlCollate *pCollate = pDb->pCollate;
202 pDb->pCollate = pCollate->pNext;
203 Tcl_Free((char*)pCollate);
204 }
drhbec3f402000-08-04 13:49:02 +0000205 if( pDb->zBusy ){
206 Tcl_Free(pDb->zBusy);
207 }
drhb5a20d32003-04-23 12:25:23 +0000208 if( pDb->zTrace ){
209 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000210 }
drh19e2d372005-08-29 23:00:03 +0000211 if( pDb->zProfile ){
212 Tcl_Free(pDb->zProfile);
213 }
drhe22a3342003-04-22 20:30:37 +0000214 if( pDb->zAuth ){
215 Tcl_Free(pDb->zAuth);
216 }
danielk197755c45f22005-04-03 23:54:43 +0000217 if( pDb->zNull ){
218 Tcl_Free(pDb->zNull);
219 }
danielk197794eb6a12005-12-15 15:22:08 +0000220 if( pDb->pUpdateHook ){
221 Tcl_DecrRefCount(pDb->pUpdateHook);
222 }
danielk197771fd80b2005-12-16 06:54:01 +0000223 if( pDb->pRollbackHook ){
224 Tcl_DecrRefCount(pDb->pRollbackHook);
225 }
danielk197794eb6a12005-12-15 15:22:08 +0000226 if( pDb->pCollateNeeded ){
227 Tcl_DecrRefCount(pDb->pCollateNeeded);
228 }
drhbec3f402000-08-04 13:49:02 +0000229 Tcl_Free((char*)pDb);
230}
231
232/*
233** This routine is called when a database file is locked while trying
234** to execute SQL.
235*/
danielk19772a764eb2004-06-12 01:43:26 +0000236static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000237 SqliteDb *pDb = (SqliteDb*)cd;
238 int rc;
239 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000240
danielk19772a764eb2004-06-12 01:43:26 +0000241 sprintf(zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000242 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000243 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
244 return 0;
245 }
246 return 1;
drh75897232000-05-29 14:26:00 +0000247}
248
249/*
danielk1977348bb5d2003-10-18 09:37:26 +0000250** This routine is invoked as the 'progress callback' for the database.
251*/
252static int DbProgressHandler(void *cd){
253 SqliteDb *pDb = (SqliteDb*)cd;
254 int rc;
255
256 assert( pDb->zProgress );
257 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
258 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
259 return 1;
260 }
261 return 0;
262}
263
drhd1167392006-01-23 13:00:35 +0000264#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000265/*
drhb5a20d32003-04-23 12:25:23 +0000266** This routine is called by the SQLite trace handler whenever a new
267** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000268*/
drhb5a20d32003-04-23 12:25:23 +0000269static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000270 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000271 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000272
drhb5a20d32003-04-23 12:25:23 +0000273 Tcl_DStringInit(&str);
274 Tcl_DStringAppend(&str, pDb->zTrace, -1);
275 Tcl_DStringAppendElement(&str, zSql);
276 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
277 Tcl_DStringFree(&str);
278 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000279}
drhd1167392006-01-23 13:00:35 +0000280#endif
drh0d1a6432003-04-03 15:46:04 +0000281
drhd1167392006-01-23 13:00:35 +0000282#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000283/*
drh19e2d372005-08-29 23:00:03 +0000284** This routine is called by the SQLite profile handler after a statement
285** SQL has executed. The TCL script in pDb->zProfile is evaluated.
286*/
287static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
288 SqliteDb *pDb = (SqliteDb*)cd;
289 Tcl_DString str;
290 char zTm[100];
291
292 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
293 Tcl_DStringInit(&str);
294 Tcl_DStringAppend(&str, pDb->zProfile, -1);
295 Tcl_DStringAppendElement(&str, zSql);
296 Tcl_DStringAppendElement(&str, zTm);
297 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
298 Tcl_DStringFree(&str);
299 Tcl_ResetResult(pDb->interp);
300}
drhd1167392006-01-23 13:00:35 +0000301#endif
drh19e2d372005-08-29 23:00:03 +0000302
303/*
drhaa940ea2004-01-15 02:44:03 +0000304** This routine is called when a transaction is committed. The
305** TCL script in pDb->zCommit is executed. If it returns non-zero or
306** if it throws an exception, the transaction is rolled back instead
307** of being committed.
308*/
309static int DbCommitHandler(void *cd){
310 SqliteDb *pDb = (SqliteDb*)cd;
311 int rc;
312
313 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
314 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
315 return 1;
316 }
317 return 0;
318}
319
danielk197771fd80b2005-12-16 06:54:01 +0000320static void DbRollbackHandler(void *clientData){
321 SqliteDb *pDb = (SqliteDb*)clientData;
322 assert(pDb->pRollbackHook);
323 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
324 Tcl_BackgroundError(pDb->interp);
325 }
326}
327
danielk197794eb6a12005-12-15 15:22:08 +0000328static void DbUpdateHandler(
329 void *p,
330 int op,
331 const char *zDb,
332 const char *zTbl,
333 sqlite_int64 rowid
334){
335 SqliteDb *pDb = (SqliteDb *)p;
336 Tcl_Obj *pCmd;
337
338 assert( pDb->pUpdateHook );
339 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
340
341 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
342 Tcl_IncrRefCount(pCmd);
343 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
344 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
345 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
346 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
347 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
348 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
349}
350
danielk19777cedc8d2004-06-10 10:50:08 +0000351static void tclCollateNeeded(
352 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000353 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000354 int enc,
355 const char *zName
356){
357 SqliteDb *pDb = (SqliteDb *)pCtx;
358 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
359 Tcl_IncrRefCount(pScript);
360 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
361 Tcl_EvalObjEx(pDb->interp, pScript, 0);
362 Tcl_DecrRefCount(pScript);
363}
364
drhaa940ea2004-01-15 02:44:03 +0000365/*
danielk19770202b292004-06-09 09:55:16 +0000366** This routine is called to evaluate an SQL collation function implemented
367** using TCL script.
368*/
369static int tclSqlCollate(
370 void *pCtx,
371 int nA,
372 const void *zA,
373 int nB,
374 const void *zB
375){
376 SqlCollate *p = (SqlCollate *)pCtx;
377 Tcl_Obj *pCmd;
378
379 pCmd = Tcl_NewStringObj(p->zScript, -1);
380 Tcl_IncrRefCount(pCmd);
381 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
382 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000383 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000384 Tcl_DecrRefCount(pCmd);
385 return (atoi(Tcl_GetStringResult(p->interp)));
386}
387
388/*
drhcabb0812002-09-14 13:47:32 +0000389** This routine is called to evaluate an SQL function implemented
390** using TCL script.
391*/
drhfb7e7652005-01-24 00:28:42 +0000392static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000393 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000394 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000395 int i;
396 int rc;
397
drhd1e47332005-06-26 17:55:33 +0000398 if( argc==0 ){
399 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
400 ** script object directly. This allows the TCL compiler to generate
401 ** bytecode for the command on the first invocation and thus make
402 ** subsequent invocations much faster. */
403 pCmd = p->pScript;
404 Tcl_IncrRefCount(pCmd);
405 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
406 Tcl_DecrRefCount(pCmd);
407 }else{
408 /* If there are arguments to the function, make a shallow copy of the
409 ** script object, lappend the arguments, then evaluate the copy.
410 **
411 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
412 ** The new Tcl_Obj contains pointers to the original list elements.
413 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
414 ** of the list to tclCmdNameType, that alternate representation will
415 ** be preserved and reused on the next invocation.
416 */
417 Tcl_Obj **aArg;
418 int nArg;
419 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
420 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
421 return;
422 }
423 pCmd = Tcl_NewListObj(nArg, aArg);
424 Tcl_IncrRefCount(pCmd);
425 for(i=0; i<argc; i++){
426 sqlite3_value *pIn = argv[i];
427 Tcl_Obj *pVal;
428
429 /* Set pVal to contain the i'th column of this row. */
430 switch( sqlite3_value_type(pIn) ){
431 case SQLITE_BLOB: {
432 int bytes = sqlite3_value_bytes(pIn);
433 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
434 break;
435 }
436 case SQLITE_INTEGER: {
437 sqlite_int64 v = sqlite3_value_int64(pIn);
438 if( v>=-2147483647 && v<=2147483647 ){
439 pVal = Tcl_NewIntObj(v);
440 }else{
441 pVal = Tcl_NewWideIntObj(v);
442 }
443 break;
444 }
445 case SQLITE_FLOAT: {
446 double r = sqlite3_value_double(pIn);
447 pVal = Tcl_NewDoubleObj(r);
448 break;
449 }
450 case SQLITE_NULL: {
451 pVal = Tcl_NewStringObj("", 0);
452 break;
453 }
454 default: {
455 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000456 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000457 break;
458 }
459 }
460 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
461 if( rc ){
462 Tcl_DecrRefCount(pCmd);
463 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
464 return;
465 }
danielk197751ad0ec2004-05-24 12:39:02 +0000466 }
drhd1e47332005-06-26 17:55:33 +0000467 if( !p->useEvalObjv ){
468 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
469 ** is a list without a string representation. To prevent this from
470 ** happening, make sure pCmd has a valid string representation */
471 Tcl_GetString(pCmd);
472 }
473 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
474 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000475 }
danielk1977562e8d32005-05-20 09:40:55 +0000476
drhc7f269d2005-05-05 10:30:29 +0000477 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000478 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000479 }else{
drhc7f269d2005-05-05 10:30:29 +0000480 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
481 int n;
482 u8 *data;
483 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
484 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000485 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000486 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000487 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000488 data = Tcl_GetByteArrayFromObj(pVar, &n);
489 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000490 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
491 (c=='i' && strcmp(zType,"int")==0) ){
492 Tcl_GetIntFromObj(0, pVar, &n);
493 sqlite3_result_int(context, n);
494 }else if( c=='d' && strcmp(zType,"double")==0 ){
495 double r;
496 Tcl_GetDoubleFromObj(0, pVar, &r);
497 sqlite3_result_double(context, r);
drhdf0bdda2005-06-25 19:31:48 +0000498 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
499 Tcl_WideInt v;
500 Tcl_GetWideIntFromObj(0, pVar, &v);
501 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000502 }else{
danielk197700fd9572005-12-07 06:27:43 +0000503 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
504 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000505 }
drhcabb0812002-09-14 13:47:32 +0000506 }
507}
drh895d7472004-08-20 16:02:39 +0000508
drhe22a3342003-04-22 20:30:37 +0000509#ifndef SQLITE_OMIT_AUTHORIZATION
510/*
511** This is the authentication function. It appends the authentication
512** type code and the two arguments to zCmd[] then invokes the result
513** on the interpreter. The reply is examined to determine if the
514** authentication fails or succeeds.
515*/
516static int auth_callback(
517 void *pArg,
518 int code,
519 const char *zArg1,
520 const char *zArg2,
521 const char *zArg3,
522 const char *zArg4
523){
524 char *zCode;
525 Tcl_DString str;
526 int rc;
527 const char *zReply;
528 SqliteDb *pDb = (SqliteDb*)pArg;
529
530 switch( code ){
531 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
532 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
533 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
534 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
535 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
536 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
537 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
538 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
539 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
540 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
541 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
542 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
543 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
544 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
545 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
546 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
547 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
548 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
549 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
550 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
551 case SQLITE_READ : zCode="SQLITE_READ"; break;
552 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
553 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
554 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000555 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
556 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000557 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000558 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000559 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000560 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
561 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drh5169bbc2006-08-24 14:59:45 +0000562 case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break;
drhe22a3342003-04-22 20:30:37 +0000563 default : zCode="????"; break;
564 }
565 Tcl_DStringInit(&str);
566 Tcl_DStringAppend(&str, pDb->zAuth, -1);
567 Tcl_DStringAppendElement(&str, zCode);
568 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
569 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
570 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
571 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
572 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
573 Tcl_DStringFree(&str);
574 zReply = Tcl_GetStringResult(pDb->interp);
575 if( strcmp(zReply,"SQLITE_OK")==0 ){
576 rc = SQLITE_OK;
577 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
578 rc = SQLITE_DENY;
579 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
580 rc = SQLITE_IGNORE;
581 }else{
582 rc = 999;
583 }
584 return rc;
585}
586#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000587
588/*
danielk1977ef2cb632004-05-29 02:37:19 +0000589** zText is a pointer to text obtained via an sqlite3_result_text()
590** or similar interface. This routine returns a Tcl string object,
591** reference count set to 0, containing the text. If a translation
592** between iso8859 and UTF-8 is required, it is preformed.
593*/
594static Tcl_Obj *dbTextToObj(char const *zText){
595 Tcl_Obj *pVal;
596#ifdef UTF_TRANSLATION_NEEDED
597 Tcl_DString dCol;
598 Tcl_DStringInit(&dCol);
599 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
600 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
601 Tcl_DStringFree(&dCol);
602#else
603 pVal = Tcl_NewStringObj(zText, -1);
604#endif
605 return pVal;
606}
607
608/*
tpoindex1067fe12004-12-17 15:41:11 +0000609** This routine reads a line of text from FILE in, stores
610** the text in memory obtained from malloc() and returns a pointer
611** to the text. NULL is returned at end of file, or if malloc()
612** fails.
613**
614** The interface is like "readline" but no command-line editing
615** is done.
616**
617** copied from shell.c from '.import' command
618*/
619static char *local_getline(char *zPrompt, FILE *in){
620 char *zLine;
621 int nLine;
622 int n;
623 int eol;
624
625 nLine = 100;
626 zLine = malloc( nLine );
627 if( zLine==0 ) return 0;
628 n = 0;
629 eol = 0;
630 while( !eol ){
631 if( n+100>nLine ){
632 nLine = nLine*2 + 100;
633 zLine = realloc(zLine, nLine);
634 if( zLine==0 ) return 0;
635 }
636 if( fgets(&zLine[n], nLine - n, in)==0 ){
637 if( n==0 ){
638 free(zLine);
639 return 0;
640 }
641 zLine[n] = 0;
642 eol = 1;
643 break;
644 }
645 while( zLine[n] ){ n++; }
646 if( n>0 && zLine[n-1]=='\n' ){
647 n--;
648 zLine[n] = 0;
649 eol = 1;
650 }
651 }
652 zLine = realloc( zLine, n+1 );
653 return zLine;
654}
655
656/*
drh75897232000-05-29 14:26:00 +0000657** The "sqlite" command below creates a new Tcl command for each
658** connection it opens to an SQLite database. This routine is invoked
659** whenever one of those connection-specific commands is executed
660** in Tcl. For example, if you run Tcl code like this:
661**
drh9bb575f2004-09-06 17:24:11 +0000662** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +0000663** db1 close
664**
665** The first command opens a connection to the "my_database" database
666** and calls that connection "db1". The second command causes this
667** subroutine to be invoked.
668*/
drh6d313162000-09-21 13:01:35 +0000669static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +0000670 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +0000671 int choice;
drh22fbcb82004-02-01 01:22:50 +0000672 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +0000673 static const char *DB_strs[] = {
drhfb7e7652005-01-24 00:28:42 +0000674 "authorizer", "busy", "cache",
675 "changes", "close", "collate",
676 "collation_needed", "commit_hook", "complete",
drh41449052006-07-06 17:08:48 +0000677 "copy", "enable_load_extension","errorcode",
678 "eval", "exists", "function",
drhf11bded2006-07-17 00:02:44 +0000679 "interrupt", "last_insert_rowid", "nullvalue",
680 "onecolumn", "profile", "progress",
681 "rekey", "rollback_hook", "timeout",
682 "total_changes", "trace", "transaction",
683 "update_hook", "version", 0
drh6d313162000-09-21 13:01:35 +0000684 };
drh411995d2002-06-25 19:31:18 +0000685 enum DB_enum {
drhfb7e7652005-01-24 00:28:42 +0000686 DB_AUTHORIZER, DB_BUSY, DB_CACHE,
687 DB_CHANGES, DB_CLOSE, DB_COLLATE,
688 DB_COLLATION_NEEDED, DB_COMMIT_HOOK, DB_COMPLETE,
drh41449052006-07-06 17:08:48 +0000689 DB_COPY, DB_ENABLE_LOAD_EXTENSION,DB_ERRORCODE,
690 DB_EVAL, DB_EXISTS, DB_FUNCTION,
drhf11bded2006-07-17 00:02:44 +0000691 DB_INTERRUPT, DB_LAST_INSERT_ROWID,DB_NULLVALUE,
692 DB_ONECOLUMN, DB_PROFILE, DB_PROGRESS,
693 DB_REKEY, DB_ROLLBACK_HOOK, DB_TIMEOUT,
694 DB_TOTAL_CHANGES, DB_TRACE, DB_TRANSACTION,
695 DB_UPDATE_HOOK, DB_VERSION,
drh6d313162000-09-21 13:01:35 +0000696 };
tpoindex1067fe12004-12-17 15:41:11 +0000697 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +0000698
699 if( objc<2 ){
700 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +0000701 return TCL_ERROR;
702 }
drh411995d2002-06-25 19:31:18 +0000703 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +0000704 return TCL_ERROR;
705 }
706
drh411995d2002-06-25 19:31:18 +0000707 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +0000708
drhe22a3342003-04-22 20:30:37 +0000709 /* $db authorizer ?CALLBACK?
710 **
711 ** Invoke the given callback to authorize each SQL operation as it is
712 ** compiled. 5 arguments are appended to the callback before it is
713 ** invoked:
714 **
715 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
716 ** (2) First descriptive name (depends on authorization type)
717 ** (3) Second descriptive name
718 ** (4) Name of the database (ex: "main", "temp")
719 ** (5) Name of trigger that is doing the access
720 **
721 ** The callback should return on of the following strings: SQLITE_OK,
722 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
723 **
724 ** If this method is invoked with no arguments, the current authorization
725 ** callback string is returned.
726 */
727 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +0000728#ifdef SQLITE_OMIT_AUTHORIZATION
729 Tcl_AppendResult(interp, "authorization not available in this build", 0);
730 return TCL_ERROR;
731#else
drhe22a3342003-04-22 20:30:37 +0000732 if( objc>3 ){
733 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +0000734 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +0000735 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +0000736 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +0000737 Tcl_AppendResult(interp, pDb->zAuth, 0);
738 }
739 }else{
740 char *zAuth;
741 int len;
742 if( pDb->zAuth ){
743 Tcl_Free(pDb->zAuth);
744 }
745 zAuth = Tcl_GetStringFromObj(objv[2], &len);
746 if( zAuth && len>0 ){
747 pDb->zAuth = Tcl_Alloc( len + 1 );
748 strcpy(pDb->zAuth, zAuth);
749 }else{
750 pDb->zAuth = 0;
751 }
drhe22a3342003-04-22 20:30:37 +0000752 if( pDb->zAuth ){
753 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000754 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +0000755 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000756 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +0000757 }
drhe22a3342003-04-22 20:30:37 +0000758 }
drh1211de32004-07-26 12:24:22 +0000759#endif
drhe22a3342003-04-22 20:30:37 +0000760 break;
761 }
762
drhbec3f402000-08-04 13:49:02 +0000763 /* $db busy ?CALLBACK?
764 **
765 ** Invoke the given callback if an SQL statement attempts to open
766 ** a locked database file.
767 */
drh6d313162000-09-21 13:01:35 +0000768 case DB_BUSY: {
769 if( objc>3 ){
770 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +0000771 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +0000772 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +0000773 if( pDb->zBusy ){
774 Tcl_AppendResult(interp, pDb->zBusy, 0);
775 }
776 }else{
drh6d313162000-09-21 13:01:35 +0000777 char *zBusy;
778 int len;
drhbec3f402000-08-04 13:49:02 +0000779 if( pDb->zBusy ){
780 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +0000781 }
drh6d313162000-09-21 13:01:35 +0000782 zBusy = Tcl_GetStringFromObj(objv[2], &len);
783 if( zBusy && len>0 ){
784 pDb->zBusy = Tcl_Alloc( len + 1 );
785 strcpy(pDb->zBusy, zBusy);
786 }else{
787 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +0000788 }
789 if( pDb->zBusy ){
790 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000791 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +0000792 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000793 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +0000794 }
795 }
drh6d313162000-09-21 13:01:35 +0000796 break;
797 }
drhbec3f402000-08-04 13:49:02 +0000798
drhfb7e7652005-01-24 00:28:42 +0000799 /* $db cache flush
800 ** $db cache size n
801 **
802 ** Flush the prepared statement cache, or set the maximum number of
803 ** cached statements.
804 */
805 case DB_CACHE: {
806 char *subCmd;
807 int n;
808
809 if( objc<=2 ){
810 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
811 return TCL_ERROR;
812 }
813 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
814 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
815 if( objc!=3 ){
816 Tcl_WrongNumArgs(interp, 2, objv, "flush");
817 return TCL_ERROR;
818 }else{
819 flushStmtCache( pDb );
820 }
821 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
822 if( objc!=4 ){
823 Tcl_WrongNumArgs(interp, 2, objv, "size n");
824 return TCL_ERROR;
825 }else{
826 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
827 Tcl_AppendResult( interp, "cannot convert \"",
828 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
829 return TCL_ERROR;
830 }else{
831 if( n<0 ){
832 flushStmtCache( pDb );
833 n = 0;
834 }else if( n>MAX_PREPARED_STMTS ){
835 n = MAX_PREPARED_STMTS;
836 }
837 pDb->maxStmt = n;
838 }
839 }
840 }else{
841 Tcl_AppendResult( interp, "bad option \"",
842 Tcl_GetStringFromObj(objv[0],0), "\": must be flush or size", 0);
843 return TCL_ERROR;
844 }
845 break;
846 }
847
danielk1977b28af712004-06-21 06:50:26 +0000848 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +0000849 **
850 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +0000851 ** the most recent INSERT, UPDATE or DELETE statement, not including
852 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +0000853 */
854 case DB_CHANGES: {
855 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +0000856 if( objc!=2 ){
857 Tcl_WrongNumArgs(interp, 2, objv, "");
858 return TCL_ERROR;
859 }
drhc8d30ac2002-04-12 10:08:59 +0000860 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +0000861 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +0000862 break;
863 }
864
drh75897232000-05-29 14:26:00 +0000865 /* $db close
866 **
867 ** Shutdown the database
868 */
drh6d313162000-09-21 13:01:35 +0000869 case DB_CLOSE: {
870 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
871 break;
872 }
drh75897232000-05-29 14:26:00 +0000873
drh0f14e2e2004-06-29 12:39:08 +0000874 /*
875 ** $db collate NAME SCRIPT
876 **
877 ** Create a new SQL collation function called NAME. Whenever
878 ** that function is called, invoke SCRIPT to evaluate the function.
879 */
880 case DB_COLLATE: {
881 SqlCollate *pCollate;
882 char *zName;
883 char *zScript;
884 int nScript;
885 if( objc!=4 ){
886 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
887 return TCL_ERROR;
888 }
889 zName = Tcl_GetStringFromObj(objv[2], 0);
890 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
891 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
892 if( pCollate==0 ) return TCL_ERROR;
893 pCollate->interp = interp;
894 pCollate->pNext = pDb->pCollate;
895 pCollate->zScript = (char*)&pCollate[1];
896 pDb->pCollate = pCollate;
897 strcpy(pCollate->zScript, zScript);
898 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
899 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +0000900 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +0000901 return TCL_ERROR;
902 }
903 break;
904 }
905
906 /*
907 ** $db collation_needed SCRIPT
908 **
909 ** Create a new SQL collation function called NAME. Whenever
910 ** that function is called, invoke SCRIPT to evaluate the function.
911 */
912 case DB_COLLATION_NEEDED: {
913 if( objc!=3 ){
914 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
915 return TCL_ERROR;
916 }
917 if( pDb->pCollateNeeded ){
918 Tcl_DecrRefCount(pDb->pCollateNeeded);
919 }
920 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
921 Tcl_IncrRefCount(pDb->pCollateNeeded);
922 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
923 break;
924 }
925
drh19e2d372005-08-29 23:00:03 +0000926 /* $db commit_hook ?CALLBACK?
927 **
928 ** Invoke the given callback just before committing every SQL transaction.
929 ** If the callback throws an exception or returns non-zero, then the
930 ** transaction is aborted. If CALLBACK is an empty string, the callback
931 ** is disabled.
932 */
933 case DB_COMMIT_HOOK: {
934 if( objc>3 ){
935 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
936 return TCL_ERROR;
937 }else if( objc==2 ){
938 if( pDb->zCommit ){
939 Tcl_AppendResult(interp, pDb->zCommit, 0);
940 }
941 }else{
942 char *zCommit;
943 int len;
944 if( pDb->zCommit ){
945 Tcl_Free(pDb->zCommit);
946 }
947 zCommit = Tcl_GetStringFromObj(objv[2], &len);
948 if( zCommit && len>0 ){
949 pDb->zCommit = Tcl_Alloc( len + 1 );
950 strcpy(pDb->zCommit, zCommit);
951 }else{
952 pDb->zCommit = 0;
953 }
954 if( pDb->zCommit ){
955 pDb->interp = interp;
956 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
957 }else{
958 sqlite3_commit_hook(pDb->db, 0, 0);
959 }
960 }
961 break;
962 }
963
drh75897232000-05-29 14:26:00 +0000964 /* $db complete SQL
965 **
966 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
967 ** additional lines of input are needed. This is similar to the
968 ** built-in "info complete" command of Tcl.
969 */
drh6d313162000-09-21 13:01:35 +0000970 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +0000971#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +0000972 Tcl_Obj *pResult;
973 int isComplete;
974 if( objc!=3 ){
975 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +0000976 return TCL_ERROR;
977 }
danielk19776f8a5032004-05-10 10:34:51 +0000978 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +0000979 pResult = Tcl_GetObjResult(interp);
980 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +0000981#endif
drh6d313162000-09-21 13:01:35 +0000982 break;
983 }
drhdcd997e2003-01-31 17:21:49 +0000984
drh19e2d372005-08-29 23:00:03 +0000985 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
986 **
987 ** Copy data into table from filename, optionally using SEPARATOR
988 ** as column separators. If a column contains a null string, or the
989 ** value of NULLINDICATOR, a NULL is inserted for the column.
990 ** conflict-algorithm is one of the sqlite conflict algorithms:
991 ** rollback, abort, fail, ignore, replace
992 ** On success, return the number of lines processed, not necessarily same
993 ** as 'db changes' due to conflict-algorithm selected.
994 **
995 ** This code is basically an implementation/enhancement of
996 ** the sqlite3 shell.c ".import" command.
997 **
998 ** This command usage is equivalent to the sqlite2.x COPY statement,
999 ** which imports file data into a table using the PostgreSQL COPY file format:
1000 ** $db copy $conflit_algo $table_name $filename \t \\N
1001 */
1002 case DB_COPY: {
1003 char *zTable; /* Insert data into this table */
1004 char *zFile; /* The file from which to extract data */
1005 char *zConflict; /* The conflict algorithm to use */
1006 sqlite3_stmt *pStmt; /* A statement */
1007 int rc; /* Result code */
1008 int nCol; /* Number of columns in the table */
1009 int nByte; /* Number of bytes in an SQL string */
1010 int i, j; /* Loop counters */
1011 int nSep; /* Number of bytes in zSep[] */
1012 int nNull; /* Number of bytes in zNull[] */
1013 char *zSql; /* An SQL statement */
1014 char *zLine; /* A single line of input from the file */
1015 char **azCol; /* zLine[] broken up into columns */
1016 char *zCommit; /* How to commit changes */
1017 FILE *in; /* The input file */
1018 int lineno = 0; /* Line number of input file */
1019 char zLineNum[80]; /* Line number print buffer */
1020 Tcl_Obj *pResult; /* interp result */
1021
1022 char *zSep;
1023 char *zNull;
1024 if( objc<5 || objc>7 ){
1025 Tcl_WrongNumArgs(interp, 2, objv,
1026 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1027 return TCL_ERROR;
1028 }
1029 if( objc>=6 ){
1030 zSep = Tcl_GetStringFromObj(objv[5], 0);
1031 }else{
1032 zSep = "\t";
1033 }
1034 if( objc>=7 ){
1035 zNull = Tcl_GetStringFromObj(objv[6], 0);
1036 }else{
1037 zNull = "";
1038 }
1039 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1040 zTable = Tcl_GetStringFromObj(objv[3], 0);
1041 zFile = Tcl_GetStringFromObj(objv[4], 0);
1042 nSep = strlen(zSep);
1043 nNull = strlen(zNull);
1044 if( nSep==0 ){
drh1409be62006-08-23 20:07:20 +00001045 Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
drh19e2d372005-08-29 23:00:03 +00001046 return TCL_ERROR;
1047 }
1048 if(sqlite3StrICmp(zConflict, "rollback") != 0 &&
1049 sqlite3StrICmp(zConflict, "abort" ) != 0 &&
1050 sqlite3StrICmp(zConflict, "fail" ) != 0 &&
1051 sqlite3StrICmp(zConflict, "ignore" ) != 0 &&
1052 sqlite3StrICmp(zConflict, "replace" ) != 0 ) {
1053 Tcl_AppendResult(interp, "Error: \"", zConflict,
1054 "\", conflict-algorithm must be one of: rollback, "
1055 "abort, fail, ignore, or replace", 0);
1056 return TCL_ERROR;
1057 }
1058 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1059 if( zSql==0 ){
1060 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1061 return TCL_ERROR;
1062 }
1063 nByte = strlen(zSql);
drh3e701a12007-02-01 01:53:44 +00001064 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001065 sqlite3_free(zSql);
1066 if( rc ){
1067 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1068 nCol = 0;
1069 }else{
1070 nCol = sqlite3_column_count(pStmt);
1071 }
1072 sqlite3_finalize(pStmt);
1073 if( nCol==0 ) {
1074 return TCL_ERROR;
1075 }
1076 zSql = malloc( nByte + 50 + nCol*2 );
1077 if( zSql==0 ) {
1078 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1079 return TCL_ERROR;
1080 }
1081 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1082 zConflict, zTable);
1083 j = strlen(zSql);
1084 for(i=1; i<nCol; i++){
1085 zSql[j++] = ',';
1086 zSql[j++] = '?';
1087 }
1088 zSql[j++] = ')';
1089 zSql[j] = 0;
drh3e701a12007-02-01 01:53:44 +00001090 rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
drh19e2d372005-08-29 23:00:03 +00001091 free(zSql);
1092 if( rc ){
1093 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1094 sqlite3_finalize(pStmt);
1095 return TCL_ERROR;
1096 }
1097 in = fopen(zFile, "rb");
1098 if( in==0 ){
1099 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
1100 sqlite3_finalize(pStmt);
1101 return TCL_ERROR;
1102 }
1103 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1104 if( azCol==0 ) {
1105 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00001106 fclose(in);
drh19e2d372005-08-29 23:00:03 +00001107 return TCL_ERROR;
1108 }
drh37527852006-03-16 16:19:56 +00001109 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001110 zCommit = "COMMIT";
1111 while( (zLine = local_getline(0, in))!=0 ){
1112 char *z;
1113 i = 0;
1114 lineno++;
1115 azCol[0] = zLine;
1116 for(i=0, z=zLine; *z; z++){
1117 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
1118 *z = 0;
1119 i++;
1120 if( i<nCol ){
1121 azCol[i] = &z[nSep];
1122 z += nSep-1;
1123 }
1124 }
1125 }
1126 if( i+1!=nCol ){
1127 char *zErr;
1128 zErr = malloc(200 + strlen(zFile));
drhc1f44942006-05-10 14:39:13 +00001129 if( zErr ){
1130 sprintf(zErr,
1131 "Error: %s line %d: expected %d columns of data but found %d",
1132 zFile, lineno, nCol, i+1);
1133 Tcl_AppendResult(interp, zErr, 0);
1134 free(zErr);
1135 }
drh19e2d372005-08-29 23:00:03 +00001136 zCommit = "ROLLBACK";
1137 break;
1138 }
1139 for(i=0; i<nCol; i++){
1140 /* check for null data, if so, bind as null */
1141 if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
1142 sqlite3_bind_null(pStmt, i+1);
1143 }else{
1144 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1145 }
1146 }
1147 sqlite3_step(pStmt);
1148 rc = sqlite3_reset(pStmt);
1149 free(zLine);
1150 if( rc!=SQLITE_OK ){
1151 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
1152 zCommit = "ROLLBACK";
1153 break;
1154 }
1155 }
1156 free(azCol);
1157 fclose(in);
1158 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00001159 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001160
1161 if( zCommit[0] == 'C' ){
1162 /* success, set result as number of lines processed */
1163 pResult = Tcl_GetObjResult(interp);
1164 Tcl_SetIntObj(pResult, lineno);
1165 rc = TCL_OK;
1166 }else{
1167 /* failure, append lineno where failed */
1168 sprintf(zLineNum,"%d",lineno);
1169 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
1170 rc = TCL_ERROR;
1171 }
1172 break;
1173 }
1174
drhdcd997e2003-01-31 17:21:49 +00001175 /*
drh41449052006-07-06 17:08:48 +00001176 ** $db enable_load_extension BOOLEAN
1177 **
1178 ** Turn the extension loading feature on or off. It if off by
1179 ** default.
1180 */
1181 case DB_ENABLE_LOAD_EXTENSION: {
drhf533acc2006-12-19 18:57:11 +00001182#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh41449052006-07-06 17:08:48 +00001183 int onoff;
1184 if( objc!=3 ){
1185 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
1186 return TCL_ERROR;
1187 }
1188 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
1189 return TCL_ERROR;
1190 }
1191 sqlite3_enable_load_extension(pDb->db, onoff);
1192 break;
drhf533acc2006-12-19 18:57:11 +00001193#else
1194 Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
1195 0);
1196 return TCL_ERROR;
1197#endif
drh41449052006-07-06 17:08:48 +00001198 }
1199
1200 /*
drhdcd997e2003-01-31 17:21:49 +00001201 ** $db errorcode
1202 **
1203 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00001204 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00001205 */
1206 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00001207 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00001208 break;
1209 }
drh75897232000-05-29 14:26:00 +00001210
1211 /*
drh895d7472004-08-20 16:02:39 +00001212 ** $db eval $sql ?array? ?{ ...code... }?
drh1807ce32004-09-07 13:20:35 +00001213 ** $db onecolumn $sql
drh75897232000-05-29 14:26:00 +00001214 **
1215 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00001216 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00001217 ** If "array" and "code" are omitted, then no callback is every invoked.
1218 ** If "array" is an empty string, then the values are placed in variables
1219 ** that have the same name as the fields extracted by the query.
drh1807ce32004-09-07 13:20:35 +00001220 **
1221 ** The onecolumn method is the equivalent of:
1222 ** lindex [$db eval $sql] 0
drh75897232000-05-29 14:26:00 +00001223 */
drh1807ce32004-09-07 13:20:35 +00001224 case DB_ONECOLUMN:
drh97f2ebc2005-12-10 21:19:04 +00001225 case DB_EVAL:
1226 case DB_EXISTS: {
drh9d74b4c2004-08-24 15:23:34 +00001227 char const *zSql; /* Next SQL statement to execute */
1228 char const *zLeft; /* What is left after first stmt in zSql */
1229 sqlite3_stmt *pStmt; /* Compiled SQL statment */
drh92febd92004-08-20 18:34:20 +00001230 Tcl_Obj *pArray; /* Name of array into which results are written */
1231 Tcl_Obj *pScript; /* Script to run for each result set */
drh1d895032004-08-26 00:56:05 +00001232 Tcl_Obj **apParm; /* Parameters that need a Tcl_DecrRefCount() */
1233 int nParm; /* Number of entries used in apParm[] */
1234 Tcl_Obj *aParm[10]; /* Static space for apParm[] in the common case */
drh1807ce32004-09-07 13:20:35 +00001235 Tcl_Obj *pRet; /* Value to be returned */
drhfb7e7652005-01-24 00:28:42 +00001236 SqlPreparedStmt *pPreStmt; /* Pointer to a prepared statement */
1237 int rc2;
danielk1977ef2cb632004-05-29 02:37:19 +00001238
drh97f2ebc2005-12-10 21:19:04 +00001239 if( choice==DB_EVAL ){
drh1807ce32004-09-07 13:20:35 +00001240 if( objc<3 || objc>5 ){
1241 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
1242 return TCL_ERROR;
1243 }
1244 pRet = Tcl_NewObj();
1245 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001246 }else{
1247 if( objc!=3 ){
1248 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
1249 return TCL_ERROR;
1250 }
drh97f2ebc2005-12-10 21:19:04 +00001251 if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001252 pRet = Tcl_NewBooleanObj(0);
1253 Tcl_IncrRefCount(pRet);
1254 }else{
1255 pRet = 0;
drh97f2ebc2005-12-10 21:19:04 +00001256 }
danielk197730ccda12004-05-27 12:11:31 +00001257 }
drh92febd92004-08-20 18:34:20 +00001258 if( objc==3 ){
1259 pArray = pScript = 0;
1260 }else if( objc==4 ){
1261 pArray = 0;
1262 pScript = objv[3];
1263 }else{
1264 pArray = objv[3];
1265 if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
1266 pScript = objv[4];
1267 }
danielk197730ccda12004-05-27 12:11:31 +00001268
drh1d895032004-08-26 00:56:05 +00001269 Tcl_IncrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001270 zSql = Tcl_GetStringFromObj(objv[2], 0);
drh90b6bb12004-09-13 13:16:31 +00001271 while( rc==TCL_OK && zSql[0] ){
drhfb7e7652005-01-24 00:28:42 +00001272 int i; /* Loop counter */
1273 int nVar; /* Number of bind parameters in the pStmt */
1274 int nCol; /* Number of columns in the result set */
drh92febd92004-08-20 18:34:20 +00001275 Tcl_Obj **apColName = 0; /* Array of column names */
drhfb7e7652005-01-24 00:28:42 +00001276 int len; /* String length of zSql */
danielk197730ccda12004-05-27 12:11:31 +00001277
drhfb7e7652005-01-24 00:28:42 +00001278 /* Try to find a SQL statement that has already been compiled and
1279 ** which matches the next sequence of SQL.
1280 */
1281 pStmt = 0;
1282 pPreStmt = pDb->stmtList;
1283 len = strlen(zSql);
1284 if( pPreStmt && sqlite3_expired(pPreStmt->pStmt) ){
1285 flushStmtCache(pDb);
1286 pPreStmt = 0;
danielk197730ccda12004-05-27 12:11:31 +00001287 }
drhfb7e7652005-01-24 00:28:42 +00001288 for(; pPreStmt; pPreStmt=pPreStmt->pNext){
1289 int n = pPreStmt->nSql;
1290 if( len>=n
1291 && memcmp(pPreStmt->zSql, zSql, n)==0
1292 && (zSql[n]==0 || zSql[n-1]==';')
1293 ){
1294 pStmt = pPreStmt->pStmt;
1295 zLeft = &zSql[pPreStmt->nSql];
1296
1297 /* When a prepared statement is found, unlink it from the
1298 ** cache list. It will later be added back to the beginning
1299 ** of the cache list in order to implement LRU replacement.
1300 */
1301 if( pPreStmt->pPrev ){
1302 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1303 }else{
1304 pDb->stmtList = pPreStmt->pNext;
1305 }
1306 if( pPreStmt->pNext ){
1307 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1308 }else{
1309 pDb->stmtLast = pPreStmt->pPrev;
1310 }
1311 pDb->nStmt--;
1312 break;
1313 }
1314 }
1315
1316 /* If no prepared statement was found. Compile the SQL text
1317 */
drh92febd92004-08-20 18:34:20 +00001318 if( pStmt==0 ){
drhfb7e7652005-01-24 00:28:42 +00001319 if( SQLITE_OK!=sqlite3_prepare(pDb->db, zSql, -1, &pStmt, &zLeft) ){
drh92febd92004-08-20 18:34:20 +00001320 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1321 rc = TCL_ERROR;
1322 break;
danielk197730ccda12004-05-27 12:11:31 +00001323 }
drhfb7e7652005-01-24 00:28:42 +00001324 if( pStmt==0 ){
1325 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1326 /* A compile-time error in the statement
1327 */
1328 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1329 rc = TCL_ERROR;
1330 break;
1331 }else{
1332 /* The statement was a no-op. Continue to the next statement
1333 ** in the SQL string.
1334 */
1335 zSql = zLeft;
1336 continue;
1337 }
1338 }
1339 assert( pPreStmt==0 );
danielk197730ccda12004-05-27 12:11:31 +00001340 }
1341
drhfb7e7652005-01-24 00:28:42 +00001342 /* Bind values to parameters that begin with $ or :
1343 */
drh92febd92004-08-20 18:34:20 +00001344 nVar = sqlite3_bind_parameter_count(pStmt);
drh1d895032004-08-26 00:56:05 +00001345 nParm = 0;
1346 if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
1347 apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
1348 }else{
1349 apParm = aParm;
1350 }
drh92febd92004-08-20 18:34:20 +00001351 for(i=1; i<=nVar; i++){
1352 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
drhc8f90792005-01-12 00:08:24 +00001353 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':') ){
drh92febd92004-08-20 18:34:20 +00001354 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1355 if( pVar ){
1356 int n;
1357 u8 *data;
1358 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
1359 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +00001360 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
1361 /* Only load a BLOB type if the Tcl variable is a bytearray and
1362 ** has no string representation. */
drh92febd92004-08-20 18:34:20 +00001363 data = Tcl_GetByteArrayFromObj(pVar, &n);
1364 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001365 Tcl_IncrRefCount(pVar);
1366 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001367 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
1368 (c=='i' && strcmp(zType,"int")==0) ){
1369 Tcl_GetIntFromObj(interp, pVar, &n);
1370 sqlite3_bind_int(pStmt, i, n);
1371 }else if( c=='d' && strcmp(zType,"double")==0 ){
1372 double r;
1373 Tcl_GetDoubleFromObj(interp, pVar, &r);
1374 sqlite3_bind_double(pStmt, i, r);
drhdf0bdda2005-06-25 19:31:48 +00001375 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
1376 Tcl_WideInt v;
1377 Tcl_GetWideIntFromObj(interp, pVar, &v);
1378 sqlite3_bind_int64(pStmt, i, v);
drh92febd92004-08-20 18:34:20 +00001379 }else{
danielk197700fd9572005-12-07 06:27:43 +00001380 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1381 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001382 Tcl_IncrRefCount(pVar);
1383 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001384 }
drhfb7e7652005-01-24 00:28:42 +00001385 }else{
1386 sqlite3_bind_null( pStmt, i );
drh92febd92004-08-20 18:34:20 +00001387 }
1388 }
1389 }
drh92febd92004-08-20 18:34:20 +00001390
1391 /* Compute column names */
1392 nCol = sqlite3_column_count(pStmt);
1393 if( pScript ){
1394 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1395 if( apColName==0 ) break;
1396 for(i=0; i<nCol; i++){
1397 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1398 Tcl_IncrRefCount(apColName[i]);
1399 }
1400 }
1401
1402 /* If results are being stored in an array variable, then create
1403 ** the array(*) entry for that array
1404 */
1405 if( pArray ){
1406 Tcl_Obj *pColList = Tcl_NewObj();
drh3ced14a2005-03-31 18:26:20 +00001407 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
drh92febd92004-08-20 18:34:20 +00001408 Tcl_IncrRefCount(pColList);
1409 for(i=0; i<nCol; i++){
1410 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1411 }
drh3ced14a2005-03-31 18:26:20 +00001412 Tcl_ObjSetVar2(interp, pArray, pStar, pColList,0);
1413 Tcl_DecrRefCount(pColList);
1414 Tcl_DecrRefCount(pStar);
drh92febd92004-08-20 18:34:20 +00001415 }
1416
1417 /* Execute the SQL
1418 */
drh90b6bb12004-09-13 13:16:31 +00001419 while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
drh92febd92004-08-20 18:34:20 +00001420 for(i=0; i<nCol; i++){
danielk197730ccda12004-05-27 12:11:31 +00001421 Tcl_Obj *pVal;
1422
1423 /* Set pVal to contain the i'th column of this row. */
drh92febd92004-08-20 18:34:20 +00001424 switch( sqlite3_column_type(pStmt, i) ){
1425 case SQLITE_BLOB: {
1426 int bytes = sqlite3_column_bytes(pStmt, i);
1427 pVal = Tcl_NewByteArrayObj(sqlite3_column_blob(pStmt, i), bytes);
1428 break;
1429 }
1430 case SQLITE_INTEGER: {
1431 sqlite_int64 v = sqlite3_column_int64(pStmt, i);
1432 if( v>=-2147483647 && v<=2147483647 ){
1433 pVal = Tcl_NewIntObj(v);
1434 }else{
1435 pVal = Tcl_NewWideIntObj(v);
1436 }
1437 break;
1438 }
1439 case SQLITE_FLOAT: {
1440 double r = sqlite3_column_double(pStmt, i);
1441 pVal = Tcl_NewDoubleObj(r);
1442 break;
1443 }
danielk197755c45f22005-04-03 23:54:43 +00001444 case SQLITE_NULL: {
1445 pVal = dbTextToObj(pDb->zNull);
1446 break;
1447 }
drh92febd92004-08-20 18:34:20 +00001448 default: {
danielk197700fd9572005-12-07 06:27:43 +00001449 pVal = dbTextToObj((char *)sqlite3_column_text(pStmt, i));
drh92febd92004-08-20 18:34:20 +00001450 break;
1451 }
danielk197730ccda12004-05-27 12:11:31 +00001452 }
1453
drh92febd92004-08-20 18:34:20 +00001454 if( pScript ){
1455 if( pArray==0 ){
1456 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001457 }else{
drh92febd92004-08-20 18:34:20 +00001458 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001459 }
drh1807ce32004-09-07 13:20:35 +00001460 }else if( choice==DB_ONECOLUMN ){
drh97f2ebc2005-12-10 21:19:04 +00001461 assert( pRet==0 );
drh1807ce32004-09-07 13:20:35 +00001462 if( pRet==0 ){
1463 pRet = pVal;
1464 Tcl_IncrRefCount(pRet);
1465 }
drh90b6bb12004-09-13 13:16:31 +00001466 rc = TCL_BREAK;
drh97f2ebc2005-12-10 21:19:04 +00001467 i = nCol;
1468 }else if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001469 Tcl_DecrRefCount(pRet);
1470 pRet = Tcl_NewBooleanObj(1);
1471 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001472 rc = TCL_BREAK;
1473 i = nCol;
danielk197730ccda12004-05-27 12:11:31 +00001474 }else{
danielk197730ccda12004-05-27 12:11:31 +00001475 Tcl_ListObjAppendElement(interp, pRet, pVal);
1476 }
1477 }
1478
drh92febd92004-08-20 18:34:20 +00001479 if( pScript ){
1480 rc = Tcl_EvalObjEx(interp, pScript, 0);
drh90b6bb12004-09-13 13:16:31 +00001481 if( rc==TCL_CONTINUE ){
1482 rc = TCL_OK;
1483 }
danielk197730ccda12004-05-27 12:11:31 +00001484 }
1485 }
drh90b6bb12004-09-13 13:16:31 +00001486 if( rc==TCL_BREAK ){
1487 rc = TCL_OK;
1488 }
drh92febd92004-08-20 18:34:20 +00001489
1490 /* Free the column name objects */
1491 if( pScript ){
1492 for(i=0; i<nCol; i++){
1493 Tcl_DecrRefCount(apColName[i]);
1494 }
1495 Tcl_Free((char*)apColName);
1496 }
1497
drh1d895032004-08-26 00:56:05 +00001498 /* Free the bound string and blob parameters */
1499 for(i=0; i<nParm; i++){
1500 Tcl_DecrRefCount(apParm[i]);
1501 }
1502 if( apParm!=aParm ){
1503 Tcl_Free((char*)apParm);
1504 }
1505
drhfb7e7652005-01-24 00:28:42 +00001506 /* Reset the statement. If the result code is SQLITE_SCHEMA, then
1507 ** flush the statement cache and try the statement again.
drh92febd92004-08-20 18:34:20 +00001508 */
drhfb7e7652005-01-24 00:28:42 +00001509 rc2 = sqlite3_reset(pStmt);
1510 if( SQLITE_SCHEMA==rc2 ){
1511 /* After a schema change, flush the cache and try to run the
1512 ** statement again
1513 */
1514 flushStmtCache( pDb );
1515 sqlite3_finalize(pStmt);
1516 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001517 continue;
drhfb7e7652005-01-24 00:28:42 +00001518 }else if( SQLITE_OK!=rc2 ){
1519 /* If a run-time error occurs, report the error and stop reading
1520 ** the SQL
1521 */
danielk1977ef2cb632004-05-29 02:37:19 +00001522 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
drhfb7e7652005-01-24 00:28:42 +00001523 sqlite3_finalize(pStmt);
danielk197730ccda12004-05-27 12:11:31 +00001524 rc = TCL_ERROR;
drhfb7e7652005-01-24 00:28:42 +00001525 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001526 break;
drhfb7e7652005-01-24 00:28:42 +00001527 }else if( pDb->maxStmt<=0 ){
1528 /* If the cache is turned off, deallocated the statement */
1529 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1530 sqlite3_finalize(pStmt);
1531 }else{
1532 /* Everything worked and the cache is operational.
1533 ** Create a new SqlPreparedStmt structure if we need one.
1534 ** (If we already have one we can just reuse it.)
1535 */
1536 if( pPreStmt==0 ){
1537 len = zLeft - zSql;
1538 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) + len );
1539 if( pPreStmt==0 ) return TCL_ERROR;
1540 pPreStmt->pStmt = pStmt;
1541 pPreStmt->nSql = len;
1542 memcpy(pPreStmt->zSql, zSql, len);
1543 pPreStmt->zSql[len] = 0;
1544 }
1545
1546 /* Add the prepared statement to the beginning of the cache list
1547 */
1548 pPreStmt->pNext = pDb->stmtList;
1549 pPreStmt->pPrev = 0;
1550 if( pDb->stmtList ){
1551 pDb->stmtList->pPrev = pPreStmt;
1552 }
1553 pDb->stmtList = pPreStmt;
1554 if( pDb->stmtLast==0 ){
1555 assert( pDb->nStmt==0 );
1556 pDb->stmtLast = pPreStmt;
1557 }else{
1558 assert( pDb->nStmt>0 );
1559 }
1560 pDb->nStmt++;
1561
1562 /* If we have too many statement in cache, remove the surplus from the
1563 ** end of the cache list.
1564 */
1565 while( pDb->nStmt>pDb->maxStmt ){
1566 sqlite3_finalize(pDb->stmtLast->pStmt);
1567 pDb->stmtLast = pDb->stmtLast->pPrev;
1568 Tcl_Free((char*)pDb->stmtLast->pNext);
1569 pDb->stmtLast->pNext = 0;
1570 pDb->nStmt--;
1571 }
danielk197730ccda12004-05-27 12:11:31 +00001572 }
1573
drhfb7e7652005-01-24 00:28:42 +00001574 /* Proceed to the next statement */
danielk197730ccda12004-05-27 12:11:31 +00001575 zSql = zLeft;
1576 }
drh1d895032004-08-26 00:56:05 +00001577 Tcl_DecrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001578
drh1807ce32004-09-07 13:20:35 +00001579 if( pRet ){
1580 if( rc==TCL_OK ){
1581 Tcl_SetObjResult(interp, pRet);
1582 }
1583 Tcl_DecrRefCount(pRet);
drh050be322006-07-12 00:18:40 +00001584 }else if( rc==TCL_OK ){
1585 Tcl_ResetResult(interp);
danielk197730ccda12004-05-27 12:11:31 +00001586 }
danielk197730ccda12004-05-27 12:11:31 +00001587 break;
1588 }
drhbec3f402000-08-04 13:49:02 +00001589
1590 /*
drhcabb0812002-09-14 13:47:32 +00001591 ** $db function NAME SCRIPT
1592 **
1593 ** Create a new SQL function called NAME. Whenever that function is
1594 ** called, invoke SCRIPT to evaluate the function.
1595 */
1596 case DB_FUNCTION: {
1597 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00001598 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00001599 char *zName;
drhcabb0812002-09-14 13:47:32 +00001600 if( objc!=4 ){
1601 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1602 return TCL_ERROR;
1603 }
1604 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00001605 pScript = objv[3];
1606 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00001607 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00001608 if( pFunc->pScript ){
1609 Tcl_DecrRefCount(pFunc->pScript);
1610 }
1611 pFunc->pScript = pScript;
1612 Tcl_IncrRefCount(pScript);
1613 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
danielk1977c8c11582004-06-29 13:41:21 +00001614 rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00001615 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00001616 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00001617 rc = TCL_ERROR;
1618 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00001619 }else{
1620 /* Must flush any cached statements */
1621 flushStmtCache( pDb );
1622 }
drhcabb0812002-09-14 13:47:32 +00001623 break;
1624 }
1625
1626 /*
drhf11bded2006-07-17 00:02:44 +00001627 ** $db interrupt
1628 **
1629 ** Interrupt the execution of the inner-most SQL interpreter. This
1630 ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
1631 */
1632 case DB_INTERRUPT: {
1633 sqlite3_interrupt(pDb->db);
1634 break;
1635 }
1636
1637 /*
drh19e2d372005-08-29 23:00:03 +00001638 ** $db nullvalue ?STRING?
1639 **
1640 ** Change text used when a NULL comes back from the database. If ?STRING?
1641 ** is not present, then the current string used for NULL is returned.
1642 ** If STRING is present, then STRING is returned.
1643 **
1644 */
1645 case DB_NULLVALUE: {
1646 if( objc!=2 && objc!=3 ){
1647 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
1648 return TCL_ERROR;
1649 }
1650 if( objc==3 ){
1651 int len;
1652 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
1653 if( pDb->zNull ){
1654 Tcl_Free(pDb->zNull);
1655 }
1656 if( zNull && len>0 ){
1657 pDb->zNull = Tcl_Alloc( len + 1 );
1658 strncpy(pDb->zNull, zNull, len);
1659 pDb->zNull[len] = '\0';
1660 }else{
1661 pDb->zNull = 0;
1662 }
1663 }
1664 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
1665 break;
1666 }
1667
1668 /*
drhaf9ff332002-01-16 21:00:27 +00001669 ** $db last_insert_rowid
1670 **
1671 ** Return an integer which is the ROWID for the most recent insert.
1672 */
1673 case DB_LAST_INSERT_ROWID: {
1674 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00001675 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00001676 if( objc!=2 ){
1677 Tcl_WrongNumArgs(interp, 2, objv, "");
1678 return TCL_ERROR;
1679 }
danielk19776f8a5032004-05-10 10:34:51 +00001680 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00001681 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00001682 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00001683 break;
1684 }
1685
1686 /*
drh1807ce32004-09-07 13:20:35 +00001687 ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
drh5d9d7572003-08-19 14:31:01 +00001688 */
drh1807ce32004-09-07 13:20:35 +00001689
1690 /* $db progress ?N CALLBACK?
1691 **
1692 ** Invoke the given callback every N virtual machine opcodes while executing
1693 ** queries.
1694 */
1695 case DB_PROGRESS: {
1696 if( objc==2 ){
1697 if( pDb->zProgress ){
1698 Tcl_AppendResult(interp, pDb->zProgress, 0);
1699 }
1700 }else if( objc==4 ){
1701 char *zProgress;
1702 int len;
1703 int N;
1704 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
1705 return TCL_ERROR;
1706 };
1707 if( pDb->zProgress ){
1708 Tcl_Free(pDb->zProgress);
1709 }
1710 zProgress = Tcl_GetStringFromObj(objv[3], &len);
1711 if( zProgress && len>0 ){
1712 pDb->zProgress = Tcl_Alloc( len + 1 );
1713 strcpy(pDb->zProgress, zProgress);
1714 }else{
1715 pDb->zProgress = 0;
1716 }
1717#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1718 if( pDb->zProgress ){
1719 pDb->interp = interp;
1720 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
1721 }else{
1722 sqlite3_progress_handler(pDb->db, 0, 0, 0);
1723 }
1724#endif
1725 }else{
1726 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00001727 return TCL_ERROR;
1728 }
drh5d9d7572003-08-19 14:31:01 +00001729 break;
1730 }
1731
drh19e2d372005-08-29 23:00:03 +00001732 /* $db profile ?CALLBACK?
1733 **
1734 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
1735 ** that has run. The text of the SQL and the amount of elapse time are
1736 ** appended to CALLBACK before the script is run.
1737 */
1738 case DB_PROFILE: {
1739 if( objc>3 ){
1740 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1741 return TCL_ERROR;
1742 }else if( objc==2 ){
1743 if( pDb->zProfile ){
1744 Tcl_AppendResult(interp, pDb->zProfile, 0);
1745 }
1746 }else{
1747 char *zProfile;
1748 int len;
1749 if( pDb->zProfile ){
1750 Tcl_Free(pDb->zProfile);
1751 }
1752 zProfile = Tcl_GetStringFromObj(objv[2], &len);
1753 if( zProfile && len>0 ){
1754 pDb->zProfile = Tcl_Alloc( len + 1 );
1755 strcpy(pDb->zProfile, zProfile);
1756 }else{
1757 pDb->zProfile = 0;
1758 }
1759#ifndef SQLITE_OMIT_TRACE
1760 if( pDb->zProfile ){
1761 pDb->interp = interp;
1762 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
1763 }else{
1764 sqlite3_profile(pDb->db, 0, 0);
1765 }
1766#endif
1767 }
1768 break;
1769 }
1770
drh5d9d7572003-08-19 14:31:01 +00001771 /*
drh22fbcb82004-02-01 01:22:50 +00001772 ** $db rekey KEY
1773 **
1774 ** Change the encryption key on the currently open database.
1775 */
1776 case DB_REKEY: {
1777 int nKey;
1778 void *pKey;
1779 if( objc!=3 ){
1780 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
1781 return TCL_ERROR;
1782 }
1783 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00001784#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00001785 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00001786 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00001787 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00001788 rc = TCL_ERROR;
1789 }
1790#endif
1791 break;
1792 }
1793
1794 /*
drhbec3f402000-08-04 13:49:02 +00001795 ** $db timeout MILLESECONDS
1796 **
1797 ** Delay for the number of milliseconds specified when a file is locked.
1798 */
drh6d313162000-09-21 13:01:35 +00001799 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00001800 int ms;
drh6d313162000-09-21 13:01:35 +00001801 if( objc!=3 ){
1802 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00001803 return TCL_ERROR;
1804 }
drh6d313162000-09-21 13:01:35 +00001805 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00001806 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00001807 break;
drh75897232000-05-29 14:26:00 +00001808 }
danielk197755c45f22005-04-03 23:54:43 +00001809
1810 /*
drh0f14e2e2004-06-29 12:39:08 +00001811 ** $db total_changes
1812 **
1813 ** Return the number of rows that were modified, inserted, or deleted
1814 ** since the database handle was created.
1815 */
1816 case DB_TOTAL_CHANGES: {
1817 Tcl_Obj *pResult;
1818 if( objc!=2 ){
1819 Tcl_WrongNumArgs(interp, 2, objv, "");
1820 return TCL_ERROR;
1821 }
1822 pResult = Tcl_GetObjResult(interp);
1823 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
1824 break;
1825 }
1826
drhb5a20d32003-04-23 12:25:23 +00001827 /* $db trace ?CALLBACK?
1828 **
1829 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
1830 ** that is executed. The text of the SQL is appended to CALLBACK before
1831 ** it is executed.
1832 */
1833 case DB_TRACE: {
1834 if( objc>3 ){
1835 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00001836 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00001837 }else if( objc==2 ){
1838 if( pDb->zTrace ){
1839 Tcl_AppendResult(interp, pDb->zTrace, 0);
1840 }
1841 }else{
1842 char *zTrace;
1843 int len;
1844 if( pDb->zTrace ){
1845 Tcl_Free(pDb->zTrace);
1846 }
1847 zTrace = Tcl_GetStringFromObj(objv[2], &len);
1848 if( zTrace && len>0 ){
1849 pDb->zTrace = Tcl_Alloc( len + 1 );
1850 strcpy(pDb->zTrace, zTrace);
1851 }else{
1852 pDb->zTrace = 0;
1853 }
drh19e2d372005-08-29 23:00:03 +00001854#ifndef SQLITE_OMIT_TRACE
drhb5a20d32003-04-23 12:25:23 +00001855 if( pDb->zTrace ){
1856 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001857 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00001858 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001859 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00001860 }
drh19e2d372005-08-29 23:00:03 +00001861#endif
drhb5a20d32003-04-23 12:25:23 +00001862 }
1863 break;
1864 }
1865
drh3d214232005-08-02 12:21:08 +00001866 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1867 **
1868 ** Start a new transaction (if we are not already in the midst of a
1869 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
1870 ** completes, either commit the transaction or roll it back if SCRIPT
1871 ** throws an exception. Or if no new transation was started, do nothing.
1872 ** pass the exception on up the stack.
1873 **
1874 ** This command was inspired by Dave Thomas's talk on Ruby at the
1875 ** 2005 O'Reilly Open Source Convention (OSCON).
1876 */
1877 case DB_TRANSACTION: {
1878 int inTrans;
1879 Tcl_Obj *pScript;
1880 const char *zBegin = "BEGIN";
1881 if( objc!=3 && objc!=4 ){
1882 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
1883 return TCL_ERROR;
1884 }
1885 if( objc==3 ){
1886 pScript = objv[2];
1887 } else {
1888 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00001889 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00001890 };
1891 enum TTYPE_enum {
1892 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
1893 };
1894 int ttype;
drhb5555e72005-08-02 17:15:14 +00001895 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00001896 0, &ttype) ){
1897 return TCL_ERROR;
1898 }
1899 switch( (enum TTYPE_enum)ttype ){
1900 case TTYPE_DEFERRED: /* no-op */; break;
1901 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
1902 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
1903 }
1904 pScript = objv[3];
1905 }
1906 inTrans = !sqlite3_get_autocommit(pDb->db);
1907 if( !inTrans ){
drh37527852006-03-16 16:19:56 +00001908 (void)sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
drh3d214232005-08-02 12:21:08 +00001909 }
1910 rc = Tcl_EvalObjEx(interp, pScript, 0);
1911 if( !inTrans ){
1912 const char *zEnd;
1913 if( rc==TCL_ERROR ){
1914 zEnd = "ROLLBACK";
1915 } else {
1916 zEnd = "COMMIT";
1917 }
drh37527852006-03-16 16:19:56 +00001918 (void)sqlite3_exec(pDb->db, zEnd, 0, 0, 0);
drh3d214232005-08-02 12:21:08 +00001919 }
1920 break;
1921 }
1922
danielk197794eb6a12005-12-15 15:22:08 +00001923 /*
1924 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00001925 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00001926 */
danielk197771fd80b2005-12-16 06:54:01 +00001927 case DB_UPDATE_HOOK:
1928 case DB_ROLLBACK_HOOK: {
1929
1930 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
1931 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
1932 */
1933 Tcl_Obj **ppHook;
1934 if( choice==DB_UPDATE_HOOK ){
1935 ppHook = &pDb->pUpdateHook;
1936 }else{
1937 ppHook = &pDb->pRollbackHook;
1938 }
1939
danielk197794eb6a12005-12-15 15:22:08 +00001940 if( objc!=2 && objc!=3 ){
1941 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
1942 return TCL_ERROR;
1943 }
danielk197771fd80b2005-12-16 06:54:01 +00001944 if( *ppHook ){
1945 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00001946 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00001947 Tcl_DecrRefCount(*ppHook);
1948 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00001949 }
1950 }
1951 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00001952 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00001953 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00001954 *ppHook = objv[2];
1955 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00001956 }
1957 }
danielk197771fd80b2005-12-16 06:54:01 +00001958
1959 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1960 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
1961
danielk197794eb6a12005-12-15 15:22:08 +00001962 break;
1963 }
1964
danielk19774397de52005-01-12 12:44:03 +00001965 /* $db version
1966 **
1967 ** Return the version string for this database.
1968 */
1969 case DB_VERSION: {
1970 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
1971 break;
1972 }
1973
tpoindex1067fe12004-12-17 15:41:11 +00001974
drh6d313162000-09-21 13:01:35 +00001975 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00001976 return rc;
drh75897232000-05-29 14:26:00 +00001977}
1978
1979/*
drh9bb575f2004-09-06 17:24:11 +00001980** sqlite3 DBNAME FILENAME ?MODE? ?-key KEY?
drh75897232000-05-29 14:26:00 +00001981**
1982** This is the main Tcl command. When the "sqlite" Tcl command is
1983** invoked, this routine runs to process that command.
1984**
1985** The first argument, DBNAME, is an arbitrary name for a new
1986** database connection. This command creates a new command named
1987** DBNAME that is used to control that connection. The database
1988** connection is deleted when the DBNAME command is deleted.
1989**
1990** The second argument is the name of the directory that contains
1991** the sqlite database that is to be accessed.
drhfbc3eab2001-04-06 16:13:42 +00001992**
1993** For testing purposes, we also support the following:
1994**
drh9bb575f2004-09-06 17:24:11 +00001995** sqlite3 -encoding
drhfbc3eab2001-04-06 16:13:42 +00001996**
1997** Return the encoding used by LIKE and GLOB operators. Choices
1998** are UTF-8 and iso8859.
1999**
drh9bb575f2004-09-06 17:24:11 +00002000** sqlite3 -version
drh647cb0e2002-11-04 19:32:25 +00002001**
2002** Return the version number of the SQLite library.
2003**
drh9bb575f2004-09-06 17:24:11 +00002004** sqlite3 -tcl-uses-utf
drhfbc3eab2001-04-06 16:13:42 +00002005**
2006** Return "1" if compiled with a Tcl uses UTF-8. Return "0" if
2007** not. Used by tests to make sure the library was compiled
2008** correctly.
drh75897232000-05-29 14:26:00 +00002009*/
drh22fbcb82004-02-01 01:22:50 +00002010static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002011 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002012 void *pKey = 0;
2013 int nKey = 0;
2014 const char *zArg;
drh75897232000-05-29 14:26:00 +00002015 char *zErrMsg;
drh22fbcb82004-02-01 01:22:50 +00002016 const char *zFile;
drh882e8e42006-08-24 02:42:27 +00002017 Tcl_DString translatedFilename;
drh22fbcb82004-02-01 01:22:50 +00002018 if( objc==2 ){
2019 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002020 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00002021 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00002022 return TCL_OK;
2023 }
drh9eb9e262004-02-11 02:18:05 +00002024 if( strcmp(zArg,"-has-codec")==0 ){
2025#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002026 Tcl_AppendResult(interp,"1",0);
2027#else
2028 Tcl_AppendResult(interp,"0",0);
2029#endif
2030 return TCL_OK;
2031 }
2032 if( strcmp(zArg,"-tcl-uses-utf")==0 ){
drhfbc3eab2001-04-06 16:13:42 +00002033#ifdef TCL_UTF_MAX
2034 Tcl_AppendResult(interp,"1",0);
2035#else
2036 Tcl_AppendResult(interp,"0",0);
2037#endif
2038 return TCL_OK;
2039 }
2040 }
drh22fbcb82004-02-01 01:22:50 +00002041 if( objc==5 || objc==6 ){
2042 zArg = Tcl_GetStringFromObj(objv[objc-2], 0);
2043 if( strcmp(zArg,"-key")==0 ){
2044 pKey = Tcl_GetByteArrayFromObj(objv[objc-1], &nKey);
2045 objc -= 2;
2046 }
2047 }
2048 if( objc!=3 && objc!=4 ){
2049 Tcl_WrongNumArgs(interp, 1, objv,
drh9eb9e262004-02-11 02:18:05 +00002050#ifdef SQLITE_HAS_CODEC
2051 "HANDLE FILENAME ?-key CODEC-KEY?"
drh22fbcb82004-02-01 01:22:50 +00002052#else
2053 "HANDLE FILENAME ?MODE?"
2054#endif
2055 );
drh75897232000-05-29 14:26:00 +00002056 return TCL_ERROR;
2057 }
drh75897232000-05-29 14:26:00 +00002058 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00002059 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00002060 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00002061 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
2062 return TCL_ERROR;
2063 }
2064 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00002065 zFile = Tcl_GetStringFromObj(objv[2], 0);
drh882e8e42006-08-24 02:42:27 +00002066 zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
danielk19774f057f92004-06-08 00:02:33 +00002067 sqlite3_open(zFile, &p->db);
drh882e8e42006-08-24 02:42:27 +00002068 Tcl_DStringFree(&translatedFilename);
danielk197780290862004-05-22 09:21:21 +00002069 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
drh9404d502006-12-19 18:46:08 +00002070 zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
danielk197780290862004-05-22 09:21:21 +00002071 sqlite3_close(p->db);
2072 p->db = 0;
2073 }
drh2011d5f2004-07-22 02:40:37 +00002074#ifdef SQLITE_HAS_CODEC
2075 sqlite3_key(p->db, pKey, nKey);
drheb8ed702004-02-11 10:37:23 +00002076#endif
drhbec3f402000-08-04 13:49:02 +00002077 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00002078 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00002079 Tcl_Free((char*)p);
drh9404d502006-12-19 18:46:08 +00002080 sqlite3_free(zErrMsg);
drh75897232000-05-29 14:26:00 +00002081 return TCL_ERROR;
2082 }
drhfb7e7652005-01-24 00:28:42 +00002083 p->maxStmt = NUM_PREPARED_STMTS;
drh5169bbc2006-08-24 14:59:45 +00002084 p->interp = interp;
drh22fbcb82004-02-01 01:22:50 +00002085 zArg = Tcl_GetStringFromObj(objv[1], 0);
2086 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
drhc22bd472002-05-10 13:14:07 +00002087
2088 /* If compiled with SQLITE_TEST turned on, then register the "md5sum"
drh06b27182002-06-26 20:06:05 +00002089 ** SQL function.
drhc22bd472002-05-10 13:14:07 +00002090 */
drh28b4e482002-03-11 02:06:13 +00002091#ifdef SQLITE_TEST
2092 {
drh9bb575f2004-09-06 17:24:11 +00002093 extern void Md5_Register(sqlite3*);
drh3b93bc82005-01-13 23:54:32 +00002094#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00002095 int mallocfail = sqlite3_iMallocFail;
2096 sqlite3_iMallocFail = 0;
danielk19775b59af82004-06-30 12:42:59 +00002097#endif
drhc22bd472002-05-10 13:14:07 +00002098 Md5_Register(p->db);
drh3b93bc82005-01-13 23:54:32 +00002099#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00002100 sqlite3_iMallocFail = mallocfail;
danielk19775b59af82004-06-30 12:42:59 +00002101#endif
danielk19777ddad962005-12-12 06:53:03 +00002102 }
drh28b4e482002-03-11 02:06:13 +00002103#endif
drh75897232000-05-29 14:26:00 +00002104 return TCL_OK;
2105}
2106
2107/*
drh90ca9752001-09-28 17:47:14 +00002108** Provide a dummy Tcl_InitStubs if we are using this as a static
2109** library.
2110*/
2111#ifndef USE_TCL_STUBS
2112# undef Tcl_InitStubs
2113# define Tcl_InitStubs(a,b,c)
2114#endif
2115
2116/*
drh29bc4612005-10-05 10:40:15 +00002117** Make sure we have a PACKAGE_VERSION macro defined. This will be
2118** defined automatically by the TEA makefile. But other makefiles
2119** do not define it.
2120*/
2121#ifndef PACKAGE_VERSION
2122# define PACKAGE_VERSION SQLITE_VERSION
2123#endif
2124
2125/*
drh75897232000-05-29 14:26:00 +00002126** Initialize this module.
2127**
2128** This Tcl module contains only a single new Tcl command named "sqlite".
2129** (Hence there is no namespace. There is no point in using a namespace
2130** if the extension only supplies one new name!) The "sqlite" command is
2131** used to open a new SQLite database. See the DbMain() routine above
2132** for additional information.
2133*/
drhad6e1372006-07-10 21:15:51 +00002134EXTERN int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00002135 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00002136 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002137 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh49766d62005-01-08 18:42:28 +00002138 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002139 Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
drh90ca9752001-09-28 17:47:14 +00002140 return TCL_OK;
2141}
drhad6e1372006-07-10 21:15:51 +00002142EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2143EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2144EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002145
2146#ifndef SQLITE_3_SUFFIX_ONLY
drhad6e1372006-07-10 21:15:51 +00002147EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2148EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2149EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2150EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002151#endif
drh75897232000-05-29 14:26:00 +00002152
drh3e27c022004-07-23 00:01:38 +00002153#ifdef TCLSH
2154/*****************************************************************************
2155** The code that follows is used to build standalone TCL interpreters
drh75897232000-05-29 14:26:00 +00002156*/
drh348784e2000-05-29 20:41:49 +00002157
2158/*
drh3e27c022004-07-23 00:01:38 +00002159** If the macro TCLSH is one, then put in code this for the
2160** "main" routine that will initialize Tcl and take input from
2161** standard input.
drh348784e2000-05-29 20:41:49 +00002162*/
drh3e27c022004-07-23 00:01:38 +00002163#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00002164static char zMainloop[] =
2165 "set line {}\n"
2166 "while {![eof stdin]} {\n"
2167 "if {$line!=\"\"} {\n"
2168 "puts -nonewline \"> \"\n"
2169 "} else {\n"
2170 "puts -nonewline \"% \"\n"
2171 "}\n"
2172 "flush stdout\n"
2173 "append line [gets stdin]\n"
2174 "if {[info complete $line]} {\n"
2175 "if {[catch {uplevel #0 $line} result]} {\n"
2176 "puts stderr \"Error: $result\"\n"
2177 "} elseif {$result!=\"\"} {\n"
2178 "puts $result\n"
2179 "}\n"
2180 "set line {}\n"
2181 "} else {\n"
2182 "append line \\n\n"
2183 "}\n"
2184 "}\n"
2185;
drh3e27c022004-07-23 00:01:38 +00002186#endif
2187
2188/*
2189** If the macro TCLSH is two, then get the main loop code out of
2190** the separate file "spaceanal_tcl.h".
2191*/
2192#if TCLSH==2
2193static char zMainloop[] =
2194#include "spaceanal_tcl.h"
2195;
2196#endif
drh348784e2000-05-29 20:41:49 +00002197
2198#define TCLSH_MAIN main /* Needed to fake out mktclapp */
2199int TCLSH_MAIN(int argc, char **argv){
2200 Tcl_Interp *interp;
drh297ecf12001-04-05 15:57:13 +00002201 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00002202 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00002203 Sqlite3_Init(interp);
drhd9b02572001-04-15 00:37:09 +00002204#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00002205 {
2206 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00002207 extern int Sqlitetest2_Init(Tcl_Interp*);
2208 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00002209 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00002210 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00002211 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00002212 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00002213 extern int Sqlitetest8_Init(Tcl_Interp*);
danielk1977a713f2c2007-03-29 12:19:11 +00002214 extern int Sqlitetest9_Init(Tcl_Interp*);
drhefc251d2001-07-01 22:12:01 +00002215 extern int Md5_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002216 extern int Sqlitetestsse_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00002217 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh4be8b512006-06-13 23:51:34 +00002218 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk1977954ce992006-06-15 15:59:19 +00002219 extern int Sqlitetestschema_Init(Tcl_Interp*);
drh1409be62006-08-23 20:07:20 +00002220 extern int Sqlitetest_autoext_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002221
danielk19776490beb2004-05-11 06:17:21 +00002222 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00002223 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00002224 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00002225 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00002226 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00002227 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00002228 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00002229 Sqlitetest8_Init(interp);
danielk1977a713f2c2007-03-29 12:19:11 +00002230 Sqlitetest9_Init(interp);
drh23669402006-01-09 17:29:52 +00002231 Sqlitetestasync_Init(interp);
drh4be8b512006-06-13 23:51:34 +00002232 Sqlitetesttclvar_Init(interp);
danielk1977954ce992006-06-15 15:59:19 +00002233 Sqlitetestschema_Init(interp);
drh1409be62006-08-23 20:07:20 +00002234 Sqlitetest_autoext_Init(interp);
drhefc251d2001-07-01 22:12:01 +00002235 Md5_Init(interp);
drh89dec812005-04-28 19:03:37 +00002236#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00002237 Sqlitetestsse_Init(interp);
2238#endif
drhd1bf3512001-04-07 15:24:33 +00002239 }
2240#endif
drh3e27c022004-07-23 00:01:38 +00002241 if( argc>=2 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002242 int i;
shessad42c3a2006-08-22 23:53:46 +00002243 char zArgc[32];
2244 sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
2245 Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
drh348784e2000-05-29 20:41:49 +00002246 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
2247 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00002248 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00002249 Tcl_SetVar(interp, "argv", argv[i],
2250 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
2251 }
drh3e27c022004-07-23 00:01:38 +00002252 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00002253 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drhc61053b2000-06-04 12:58:36 +00002254 if( zInfo==0 ) zInfo = interp->result;
2255 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00002256 return 1;
2257 }
drh3e27c022004-07-23 00:01:38 +00002258 }
2259 if( argc<=1 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002260 Tcl_GlobalEval(interp, zMainloop);
2261 }
2262 return 0;
2263}
2264#endif /* TCLSH */