blob: 5a97da06946fbcedcd78641305f512a567f5f321 [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**
danielk1977aef0bf62005-12-30 16:28:01 +000014** $Id: tclsqlite.c,v 1.142 2005/12/30 16:28:02 danielk1977 Exp $
drh75897232000-05-29 14:26:00 +000015*/
drh6d313162000-09-21 13:01:35 +000016#ifndef NO_TCL /* Omit this whole file if TCL is unavailable */
17
drh06b27182002-06-26 20:06:05 +000018#include "sqliteInt.h"
drh895d7472004-08-20 16:02:39 +000019#include "hash.h"
drh17a68932001-01-31 13:28:08 +000020#include "tcl.h"
drh75897232000-05-29 14:26:00 +000021#include <stdlib.h>
22#include <string.h>
drhce927062001-11-09 13:41:09 +000023#include <assert.h>
drhd1e47332005-06-26 17:55:33 +000024#include <ctype.h>
drh75897232000-05-29 14:26:00 +000025
drh29bc4612005-10-05 10:40:15 +000026/*
27 * Windows needs to know which symbols to export. Unix does not.
28 * BUILD_sqlite should be undefined for Unix.
29 */
30
31#ifdef BUILD_sqlite
32#undef TCL_STORAGE_CLASS
33#define TCL_STORAGE_CLASS DLLEXPORT
34#endif /* BUILD_sqlite */
35
danielk1977a21c6b62005-01-24 10:25:59 +000036#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000037#define MAX_PREPARED_STMTS 100
38
drh75897232000-05-29 14:26:00 +000039/*
drh98808ba2001-10-18 12:34:46 +000040** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
41** have to do a translation when going between the two. Set the
42** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
43** this translation.
44*/
45#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
46# define UTF_TRANSLATION_NEEDED 1
47#endif
48
49/*
drhcabb0812002-09-14 13:47:32 +000050** New SQL functions can be created as TCL scripts. Each such function
51** is described by an instance of the following structure.
52*/
53typedef struct SqlFunc SqlFunc;
54struct SqlFunc {
55 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000056 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
57 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
58 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000059 SqlFunc *pNext; /* Next function on the list of them all */
60};
61
62/*
danielk19770202b292004-06-09 09:55:16 +000063** New collation sequences function can be created as TCL scripts. Each such
64** function is described by an instance of the following structure.
65*/
66typedef struct SqlCollate SqlCollate;
67struct SqlCollate {
68 Tcl_Interp *interp; /* The TCL interpret to execute the function */
69 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000070 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000071};
72
73/*
drhfb7e7652005-01-24 00:28:42 +000074** Prepared statements are cached for faster execution. Each prepared
75** statement is described by an instance of the following structure.
76*/
77typedef struct SqlPreparedStmt SqlPreparedStmt;
78struct SqlPreparedStmt {
79 SqlPreparedStmt *pNext; /* Next in linked list */
80 SqlPreparedStmt *pPrev; /* Previous on the list */
81 sqlite3_stmt *pStmt; /* The prepared statement */
82 int nSql; /* chars in zSql[] */
83 char zSql[1]; /* Text of the SQL statement */
84};
85
86/*
drhbec3f402000-08-04 13:49:02 +000087** There is one instance of this structure for each SQLite database
88** that has been opened by the SQLite TCL interface.
89*/
90typedef struct SqliteDb SqliteDb;
91struct SqliteDb {
drhd1e47332005-06-26 17:55:33 +000092 sqlite3 *db; /* The "real" database structure */
93 Tcl_Interp *interp; /* The interpreter used for this database */
94 char *zBusy; /* The busy callback routine */
95 char *zCommit; /* The commit hook callback routine */
96 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +000097 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +000098 char *zProgress; /* The progress callback routine */
99 char *zAuth; /* The authorization callback routine */
100 char *zNull; /* Text to substitute for an SQL NULL value */
101 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +0000102 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +0000103 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drhd1e47332005-06-26 17:55:33 +0000104 SqlCollate *pCollate; /* List of SQL collation functions */
105 int rc; /* Return code of most recent sqlite3_exec() */
106 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +0000107 SqlPreparedStmt *stmtList; /* List of prepared statements*/
108 SqlPreparedStmt *stmtLast; /* Last statement in the list */
109 int maxStmt; /* The next maximum number of stmtList */
110 int nStmt; /* Number of statements in stmtList */
drh98808ba2001-10-18 12:34:46 +0000111};
drh297ecf12001-04-05 15:57:13 +0000112
drh6d313162000-09-21 13:01:35 +0000113/*
drhd1e47332005-06-26 17:55:33 +0000114** Look at the script prefix in pCmd. We will be executing this script
115** after first appending one or more arguments. This routine analyzes
116** the script to see if it is safe to use Tcl_EvalObjv() on the script
117** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
118** faster.
119**
120** Scripts that are safe to use with Tcl_EvalObjv() consists of a
121** command name followed by zero or more arguments with no [...] or $
122** or {...} or ; to be seen anywhere. Most callback scripts consist
123** of just a single procedure name and they meet this requirement.
124*/
125static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
126 /* We could try to do something with Tcl_Parse(). But we will instead
127 ** just do a search for forbidden characters. If any of the forbidden
128 ** characters appear in pCmd, we will report the string as unsafe.
129 */
130 const char *z;
131 int n;
132 z = Tcl_GetStringFromObj(pCmd, &n);
133 while( n-- > 0 ){
134 int c = *(z++);
135 if( c=='$' || c=='[' || c==';' ) return 0;
136 }
137 return 1;
138}
139
140/*
141** Find an SqlFunc structure with the given name. Or create a new
142** one if an existing one cannot be found. Return a pointer to the
143** structure.
144*/
145static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
146 SqlFunc *p, *pNew;
147 int i;
148 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen(zName) + 1 );
149 pNew->zName = (char*)&pNew[1];
150 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
151 pNew->zName[i] = 0;
152 for(p=pDb->pFunc; p; p=p->pNext){
153 if( strcmp(p->zName, pNew->zName)==0 ){
154 Tcl_Free((char*)pNew);
155 return p;
156 }
157 }
158 pNew->interp = pDb->interp;
159 pNew->pScript = 0;
160 pNew->pNext = pDb->pFunc;
161 pDb->pFunc = pNew;
162 return pNew;
163}
164
165/*
drhfb7e7652005-01-24 00:28:42 +0000166** Finalize and free a list of prepared statements
167*/
168static void flushStmtCache( SqliteDb *pDb ){
169 SqlPreparedStmt *pPreStmt;
170
171 while( pDb->stmtList ){
172 sqlite3_finalize( pDb->stmtList->pStmt );
173 pPreStmt = pDb->stmtList;
174 pDb->stmtList = pDb->stmtList->pNext;
175 Tcl_Free( (char*)pPreStmt );
176 }
177 pDb->nStmt = 0;
178 pDb->stmtLast = 0;
179}
180
181/*
drh895d7472004-08-20 16:02:39 +0000182** TCL calls this procedure when an sqlite3 database command is
183** deleted.
drh75897232000-05-29 14:26:00 +0000184*/
185static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000186 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000187 flushStmtCache(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000188 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000189 while( pDb->pFunc ){
190 SqlFunc *pFunc = pDb->pFunc;
191 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000192 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000193 Tcl_Free((char*)pFunc);
194 }
danielk19770202b292004-06-09 09:55:16 +0000195 while( pDb->pCollate ){
196 SqlCollate *pCollate = pDb->pCollate;
197 pDb->pCollate = pCollate->pNext;
198 Tcl_Free((char*)pCollate);
199 }
drhbec3f402000-08-04 13:49:02 +0000200 if( pDb->zBusy ){
201 Tcl_Free(pDb->zBusy);
202 }
drhb5a20d32003-04-23 12:25:23 +0000203 if( pDb->zTrace ){
204 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000205 }
drh19e2d372005-08-29 23:00:03 +0000206 if( pDb->zProfile ){
207 Tcl_Free(pDb->zProfile);
208 }
drhe22a3342003-04-22 20:30:37 +0000209 if( pDb->zAuth ){
210 Tcl_Free(pDb->zAuth);
211 }
danielk197755c45f22005-04-03 23:54:43 +0000212 if( pDb->zNull ){
213 Tcl_Free(pDb->zNull);
214 }
danielk197794eb6a12005-12-15 15:22:08 +0000215 if( pDb->pUpdateHook ){
216 Tcl_DecrRefCount(pDb->pUpdateHook);
217 }
danielk197771fd80b2005-12-16 06:54:01 +0000218 if( pDb->pRollbackHook ){
219 Tcl_DecrRefCount(pDb->pRollbackHook);
220 }
danielk197794eb6a12005-12-15 15:22:08 +0000221 if( pDb->pCollateNeeded ){
222 Tcl_DecrRefCount(pDb->pCollateNeeded);
223 }
drhbec3f402000-08-04 13:49:02 +0000224 Tcl_Free((char*)pDb);
225}
226
227/*
228** This routine is called when a database file is locked while trying
229** to execute SQL.
230*/
danielk19772a764eb2004-06-12 01:43:26 +0000231static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000232 SqliteDb *pDb = (SqliteDb*)cd;
233 int rc;
234 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000235
danielk19772a764eb2004-06-12 01:43:26 +0000236 sprintf(zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000237 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000238 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
239 return 0;
240 }
241 return 1;
drh75897232000-05-29 14:26:00 +0000242}
243
244/*
danielk1977348bb5d2003-10-18 09:37:26 +0000245** This routine is invoked as the 'progress callback' for the database.
246*/
247static int DbProgressHandler(void *cd){
248 SqliteDb *pDb = (SqliteDb*)cd;
249 int rc;
250
251 assert( pDb->zProgress );
252 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
253 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
254 return 1;
255 }
256 return 0;
257}
258
259/*
drhb5a20d32003-04-23 12:25:23 +0000260** This routine is called by the SQLite trace handler whenever a new
261** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000262*/
drhb5a20d32003-04-23 12:25:23 +0000263static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000264 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000265 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000266
drhb5a20d32003-04-23 12:25:23 +0000267 Tcl_DStringInit(&str);
268 Tcl_DStringAppend(&str, pDb->zTrace, -1);
269 Tcl_DStringAppendElement(&str, zSql);
270 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
271 Tcl_DStringFree(&str);
272 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000273}
274
275/*
drh19e2d372005-08-29 23:00:03 +0000276** This routine is called by the SQLite profile handler after a statement
277** SQL has executed. The TCL script in pDb->zProfile is evaluated.
278*/
279static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
280 SqliteDb *pDb = (SqliteDb*)cd;
281 Tcl_DString str;
282 char zTm[100];
283
284 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
285 Tcl_DStringInit(&str);
286 Tcl_DStringAppend(&str, pDb->zProfile, -1);
287 Tcl_DStringAppendElement(&str, zSql);
288 Tcl_DStringAppendElement(&str, zTm);
289 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
290 Tcl_DStringFree(&str);
291 Tcl_ResetResult(pDb->interp);
292}
293
294/*
drhaa940ea2004-01-15 02:44:03 +0000295** This routine is called when a transaction is committed. The
296** TCL script in pDb->zCommit is executed. If it returns non-zero or
297** if it throws an exception, the transaction is rolled back instead
298** of being committed.
299*/
300static int DbCommitHandler(void *cd){
301 SqliteDb *pDb = (SqliteDb*)cd;
302 int rc;
303
304 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
305 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
306 return 1;
307 }
308 return 0;
309}
310
danielk197771fd80b2005-12-16 06:54:01 +0000311static void DbRollbackHandler(void *clientData){
312 SqliteDb *pDb = (SqliteDb*)clientData;
313 assert(pDb->pRollbackHook);
314 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
315 Tcl_BackgroundError(pDb->interp);
316 }
317}
318
danielk197794eb6a12005-12-15 15:22:08 +0000319static void DbUpdateHandler(
320 void *p,
321 int op,
322 const char *zDb,
323 const char *zTbl,
324 sqlite_int64 rowid
325){
326 SqliteDb *pDb = (SqliteDb *)p;
327 Tcl_Obj *pCmd;
328
329 assert( pDb->pUpdateHook );
330 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
331
332 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
333 Tcl_IncrRefCount(pCmd);
334 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
335 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
336 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
337 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
338 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
339 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
340}
341
danielk19777cedc8d2004-06-10 10:50:08 +0000342static void tclCollateNeeded(
343 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000344 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000345 int enc,
346 const char *zName
347){
348 SqliteDb *pDb = (SqliteDb *)pCtx;
349 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
350 Tcl_IncrRefCount(pScript);
351 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
352 Tcl_EvalObjEx(pDb->interp, pScript, 0);
353 Tcl_DecrRefCount(pScript);
354}
355
drhaa940ea2004-01-15 02:44:03 +0000356/*
danielk19770202b292004-06-09 09:55:16 +0000357** This routine is called to evaluate an SQL collation function implemented
358** using TCL script.
359*/
360static int tclSqlCollate(
361 void *pCtx,
362 int nA,
363 const void *zA,
364 int nB,
365 const void *zB
366){
367 SqlCollate *p = (SqlCollate *)pCtx;
368 Tcl_Obj *pCmd;
369
370 pCmd = Tcl_NewStringObj(p->zScript, -1);
371 Tcl_IncrRefCount(pCmd);
372 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
373 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000374 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000375 Tcl_DecrRefCount(pCmd);
376 return (atoi(Tcl_GetStringResult(p->interp)));
377}
378
379/*
drhcabb0812002-09-14 13:47:32 +0000380** This routine is called to evaluate an SQL function implemented
381** using TCL script.
382*/
drhfb7e7652005-01-24 00:28:42 +0000383static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000384 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000385 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000386 int i;
387 int rc;
388
drhd1e47332005-06-26 17:55:33 +0000389 if( argc==0 ){
390 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
391 ** script object directly. This allows the TCL compiler to generate
392 ** bytecode for the command on the first invocation and thus make
393 ** subsequent invocations much faster. */
394 pCmd = p->pScript;
395 Tcl_IncrRefCount(pCmd);
396 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
397 Tcl_DecrRefCount(pCmd);
398 }else{
399 /* If there are arguments to the function, make a shallow copy of the
400 ** script object, lappend the arguments, then evaluate the copy.
401 **
402 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
403 ** The new Tcl_Obj contains pointers to the original list elements.
404 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
405 ** of the list to tclCmdNameType, that alternate representation will
406 ** be preserved and reused on the next invocation.
407 */
408 Tcl_Obj **aArg;
409 int nArg;
410 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
411 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
412 return;
413 }
414 pCmd = Tcl_NewListObj(nArg, aArg);
415 Tcl_IncrRefCount(pCmd);
416 for(i=0; i<argc; i++){
417 sqlite3_value *pIn = argv[i];
418 Tcl_Obj *pVal;
419
420 /* Set pVal to contain the i'th column of this row. */
421 switch( sqlite3_value_type(pIn) ){
422 case SQLITE_BLOB: {
423 int bytes = sqlite3_value_bytes(pIn);
424 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
425 break;
426 }
427 case SQLITE_INTEGER: {
428 sqlite_int64 v = sqlite3_value_int64(pIn);
429 if( v>=-2147483647 && v<=2147483647 ){
430 pVal = Tcl_NewIntObj(v);
431 }else{
432 pVal = Tcl_NewWideIntObj(v);
433 }
434 break;
435 }
436 case SQLITE_FLOAT: {
437 double r = sqlite3_value_double(pIn);
438 pVal = Tcl_NewDoubleObj(r);
439 break;
440 }
441 case SQLITE_NULL: {
442 pVal = Tcl_NewStringObj("", 0);
443 break;
444 }
445 default: {
446 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000447 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000448 break;
449 }
450 }
451 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
452 if( rc ){
453 Tcl_DecrRefCount(pCmd);
454 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
455 return;
456 }
danielk197751ad0ec2004-05-24 12:39:02 +0000457 }
drhd1e47332005-06-26 17:55:33 +0000458 if( !p->useEvalObjv ){
459 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
460 ** is a list without a string representation. To prevent this from
461 ** happening, make sure pCmd has a valid string representation */
462 Tcl_GetString(pCmd);
463 }
464 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
465 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000466 }
danielk1977562e8d32005-05-20 09:40:55 +0000467
drhc7f269d2005-05-05 10:30:29 +0000468 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000469 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000470 }else{
drhc7f269d2005-05-05 10:30:29 +0000471 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
472 int n;
473 u8 *data;
474 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
475 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000476 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000477 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000478 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000479 data = Tcl_GetByteArrayFromObj(pVar, &n);
480 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000481 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
482 (c=='i' && strcmp(zType,"int")==0) ){
483 Tcl_GetIntFromObj(0, pVar, &n);
484 sqlite3_result_int(context, n);
485 }else if( c=='d' && strcmp(zType,"double")==0 ){
486 double r;
487 Tcl_GetDoubleFromObj(0, pVar, &r);
488 sqlite3_result_double(context, r);
drhdf0bdda2005-06-25 19:31:48 +0000489 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
490 Tcl_WideInt v;
491 Tcl_GetWideIntFromObj(0, pVar, &v);
492 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000493 }else{
danielk197700fd9572005-12-07 06:27:43 +0000494 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
495 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000496 }
drhcabb0812002-09-14 13:47:32 +0000497 }
498}
drh895d7472004-08-20 16:02:39 +0000499
drhe22a3342003-04-22 20:30:37 +0000500#ifndef SQLITE_OMIT_AUTHORIZATION
501/*
502** This is the authentication function. It appends the authentication
503** type code and the two arguments to zCmd[] then invokes the result
504** on the interpreter. The reply is examined to determine if the
505** authentication fails or succeeds.
506*/
507static int auth_callback(
508 void *pArg,
509 int code,
510 const char *zArg1,
511 const char *zArg2,
512 const char *zArg3,
513 const char *zArg4
514){
515 char *zCode;
516 Tcl_DString str;
517 int rc;
518 const char *zReply;
519 SqliteDb *pDb = (SqliteDb*)pArg;
520
521 switch( code ){
522 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
523 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
524 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
525 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
526 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
527 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
528 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
529 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
530 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
531 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
532 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
533 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
534 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
535 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
536 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
537 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
538 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
539 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
540 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
541 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
542 case SQLITE_READ : zCode="SQLITE_READ"; break;
543 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
544 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
545 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000546 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
547 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000548 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000549 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000550 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
drhe22a3342003-04-22 20:30:37 +0000551 default : zCode="????"; break;
552 }
553 Tcl_DStringInit(&str);
554 Tcl_DStringAppend(&str, pDb->zAuth, -1);
555 Tcl_DStringAppendElement(&str, zCode);
556 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
557 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
558 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
559 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
560 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
561 Tcl_DStringFree(&str);
562 zReply = Tcl_GetStringResult(pDb->interp);
563 if( strcmp(zReply,"SQLITE_OK")==0 ){
564 rc = SQLITE_OK;
565 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
566 rc = SQLITE_DENY;
567 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
568 rc = SQLITE_IGNORE;
569 }else{
570 rc = 999;
571 }
572 return rc;
573}
574#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000575
576/*
danielk1977ef2cb632004-05-29 02:37:19 +0000577** zText is a pointer to text obtained via an sqlite3_result_text()
578** or similar interface. This routine returns a Tcl string object,
579** reference count set to 0, containing the text. If a translation
580** between iso8859 and UTF-8 is required, it is preformed.
581*/
582static Tcl_Obj *dbTextToObj(char const *zText){
583 Tcl_Obj *pVal;
584#ifdef UTF_TRANSLATION_NEEDED
585 Tcl_DString dCol;
586 Tcl_DStringInit(&dCol);
587 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
588 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
589 Tcl_DStringFree(&dCol);
590#else
591 pVal = Tcl_NewStringObj(zText, -1);
592#endif
593 return pVal;
594}
595
596/*
tpoindex1067fe12004-12-17 15:41:11 +0000597** This routine reads a line of text from FILE in, stores
598** the text in memory obtained from malloc() and returns a pointer
599** to the text. NULL is returned at end of file, or if malloc()
600** fails.
601**
602** The interface is like "readline" but no command-line editing
603** is done.
604**
605** copied from shell.c from '.import' command
606*/
607static char *local_getline(char *zPrompt, FILE *in){
608 char *zLine;
609 int nLine;
610 int n;
611 int eol;
612
613 nLine = 100;
614 zLine = malloc( nLine );
615 if( zLine==0 ) return 0;
616 n = 0;
617 eol = 0;
618 while( !eol ){
619 if( n+100>nLine ){
620 nLine = nLine*2 + 100;
621 zLine = realloc(zLine, nLine);
622 if( zLine==0 ) return 0;
623 }
624 if( fgets(&zLine[n], nLine - n, in)==0 ){
625 if( n==0 ){
626 free(zLine);
627 return 0;
628 }
629 zLine[n] = 0;
630 eol = 1;
631 break;
632 }
633 while( zLine[n] ){ n++; }
634 if( n>0 && zLine[n-1]=='\n' ){
635 n--;
636 zLine[n] = 0;
637 eol = 1;
638 }
639 }
640 zLine = realloc( zLine, n+1 );
641 return zLine;
642}
643
644/*
drh75897232000-05-29 14:26:00 +0000645** The "sqlite" command below creates a new Tcl command for each
646** connection it opens to an SQLite database. This routine is invoked
647** whenever one of those connection-specific commands is executed
648** in Tcl. For example, if you run Tcl code like this:
649**
drh9bb575f2004-09-06 17:24:11 +0000650** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +0000651** db1 close
652**
653** The first command opens a connection to the "my_database" database
654** and calls that connection "db1". The second command causes this
655** subroutine to be invoked.
656*/
drh6d313162000-09-21 13:01:35 +0000657static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +0000658 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +0000659 int choice;
drh22fbcb82004-02-01 01:22:50 +0000660 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +0000661 static const char *DB_strs[] = {
drhfb7e7652005-01-24 00:28:42 +0000662 "authorizer", "busy", "cache",
663 "changes", "close", "collate",
664 "collation_needed", "commit_hook", "complete",
665 "copy", "errorcode", "eval",
drh97f2ebc2005-12-10 21:19:04 +0000666 "exists", "function", "last_insert_rowid",
667 "nullvalue", "onecolumn", "profile",
danielk197771fd80b2005-12-16 06:54:01 +0000668 "progress", "rekey", "rollback_hook",
danielk19770190d1d2005-12-19 14:18:11 +0000669 "release_memory", "soft_heap_limit", "timeout",
670 "total_changes", "trace", "transaction",
671 "update_hook", "version", 0
drh6d313162000-09-21 13:01:35 +0000672 };
drh411995d2002-06-25 19:31:18 +0000673 enum DB_enum {
drhfb7e7652005-01-24 00:28:42 +0000674 DB_AUTHORIZER, DB_BUSY, DB_CACHE,
675 DB_CHANGES, DB_CLOSE, DB_COLLATE,
676 DB_COLLATION_NEEDED, DB_COMMIT_HOOK, DB_COMPLETE,
677 DB_COPY, DB_ERRORCODE, DB_EVAL,
drh97f2ebc2005-12-10 21:19:04 +0000678 DB_EXISTS, DB_FUNCTION, DB_LAST_INSERT_ROWID,
679 DB_NULLVALUE, DB_ONECOLUMN, DB_PROFILE,
danielk197771fd80b2005-12-16 06:54:01 +0000680 DB_PROGRESS, DB_REKEY, DB_ROLLBACK_HOOK,
danielk19770190d1d2005-12-19 14:18:11 +0000681 DB_RELEASE_MEMORY, DB_SOFT_HEAP_LIMIT, DB_TIMEOUT,
682 DB_TOTAL_CHANGES, DB_TRACE, DB_TRANSACTION,
683 DB_UPDATE_HOOK, DB_VERSION
drh6d313162000-09-21 13:01:35 +0000684 };
tpoindex1067fe12004-12-17 15:41:11 +0000685 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +0000686
687 if( objc<2 ){
688 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +0000689 return TCL_ERROR;
690 }
drh411995d2002-06-25 19:31:18 +0000691 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +0000692 return TCL_ERROR;
693 }
694
drh411995d2002-06-25 19:31:18 +0000695 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +0000696
drhe22a3342003-04-22 20:30:37 +0000697 /* $db authorizer ?CALLBACK?
698 **
699 ** Invoke the given callback to authorize each SQL operation as it is
700 ** compiled. 5 arguments are appended to the callback before it is
701 ** invoked:
702 **
703 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
704 ** (2) First descriptive name (depends on authorization type)
705 ** (3) Second descriptive name
706 ** (4) Name of the database (ex: "main", "temp")
707 ** (5) Name of trigger that is doing the access
708 **
709 ** The callback should return on of the following strings: SQLITE_OK,
710 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
711 **
712 ** If this method is invoked with no arguments, the current authorization
713 ** callback string is returned.
714 */
715 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +0000716#ifdef SQLITE_OMIT_AUTHORIZATION
717 Tcl_AppendResult(interp, "authorization not available in this build", 0);
718 return TCL_ERROR;
719#else
drhe22a3342003-04-22 20:30:37 +0000720 if( objc>3 ){
721 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +0000722 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +0000723 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +0000724 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +0000725 Tcl_AppendResult(interp, pDb->zAuth, 0);
726 }
727 }else{
728 char *zAuth;
729 int len;
730 if( pDb->zAuth ){
731 Tcl_Free(pDb->zAuth);
732 }
733 zAuth = Tcl_GetStringFromObj(objv[2], &len);
734 if( zAuth && len>0 ){
735 pDb->zAuth = Tcl_Alloc( len + 1 );
736 strcpy(pDb->zAuth, zAuth);
737 }else{
738 pDb->zAuth = 0;
739 }
drhe22a3342003-04-22 20:30:37 +0000740 if( pDb->zAuth ){
741 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000742 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +0000743 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000744 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +0000745 }
drhe22a3342003-04-22 20:30:37 +0000746 }
drh1211de32004-07-26 12:24:22 +0000747#endif
drhe22a3342003-04-22 20:30:37 +0000748 break;
749 }
750
drhbec3f402000-08-04 13:49:02 +0000751 /* $db busy ?CALLBACK?
752 **
753 ** Invoke the given callback if an SQL statement attempts to open
754 ** a locked database file.
755 */
drh6d313162000-09-21 13:01:35 +0000756 case DB_BUSY: {
757 if( objc>3 ){
758 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +0000759 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +0000760 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +0000761 if( pDb->zBusy ){
762 Tcl_AppendResult(interp, pDb->zBusy, 0);
763 }
764 }else{
drh6d313162000-09-21 13:01:35 +0000765 char *zBusy;
766 int len;
drhbec3f402000-08-04 13:49:02 +0000767 if( pDb->zBusy ){
768 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +0000769 }
drh6d313162000-09-21 13:01:35 +0000770 zBusy = Tcl_GetStringFromObj(objv[2], &len);
771 if( zBusy && len>0 ){
772 pDb->zBusy = Tcl_Alloc( len + 1 );
773 strcpy(pDb->zBusy, zBusy);
774 }else{
775 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +0000776 }
777 if( pDb->zBusy ){
778 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000779 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +0000780 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000781 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +0000782 }
783 }
drh6d313162000-09-21 13:01:35 +0000784 break;
785 }
drhbec3f402000-08-04 13:49:02 +0000786
drhfb7e7652005-01-24 00:28:42 +0000787 /* $db cache flush
788 ** $db cache size n
789 **
790 ** Flush the prepared statement cache, or set the maximum number of
791 ** cached statements.
792 */
793 case DB_CACHE: {
794 char *subCmd;
795 int n;
796
797 if( objc<=2 ){
798 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
799 return TCL_ERROR;
800 }
801 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
802 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
803 if( objc!=3 ){
804 Tcl_WrongNumArgs(interp, 2, objv, "flush");
805 return TCL_ERROR;
806 }else{
807 flushStmtCache( pDb );
808 }
809 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
810 if( objc!=4 ){
811 Tcl_WrongNumArgs(interp, 2, objv, "size n");
812 return TCL_ERROR;
813 }else{
814 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
815 Tcl_AppendResult( interp, "cannot convert \"",
816 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
817 return TCL_ERROR;
818 }else{
819 if( n<0 ){
820 flushStmtCache( pDb );
821 n = 0;
822 }else if( n>MAX_PREPARED_STMTS ){
823 n = MAX_PREPARED_STMTS;
824 }
825 pDb->maxStmt = n;
826 }
827 }
828 }else{
829 Tcl_AppendResult( interp, "bad option \"",
830 Tcl_GetStringFromObj(objv[0],0), "\": must be flush or size", 0);
831 return TCL_ERROR;
832 }
833 break;
834 }
835
danielk1977b28af712004-06-21 06:50:26 +0000836 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +0000837 **
838 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +0000839 ** the most recent INSERT, UPDATE or DELETE statement, not including
840 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +0000841 */
842 case DB_CHANGES: {
843 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +0000844 if( objc!=2 ){
845 Tcl_WrongNumArgs(interp, 2, objv, "");
846 return TCL_ERROR;
847 }
drhc8d30ac2002-04-12 10:08:59 +0000848 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +0000849 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +0000850 break;
851 }
852
drh75897232000-05-29 14:26:00 +0000853 /* $db close
854 **
855 ** Shutdown the database
856 */
drh6d313162000-09-21 13:01:35 +0000857 case DB_CLOSE: {
858 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
859 break;
860 }
drh75897232000-05-29 14:26:00 +0000861
drh0f14e2e2004-06-29 12:39:08 +0000862 /*
863 ** $db collate NAME SCRIPT
864 **
865 ** Create a new SQL collation function called NAME. Whenever
866 ** that function is called, invoke SCRIPT to evaluate the function.
867 */
868 case DB_COLLATE: {
869 SqlCollate *pCollate;
870 char *zName;
871 char *zScript;
872 int nScript;
873 if( objc!=4 ){
874 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
875 return TCL_ERROR;
876 }
877 zName = Tcl_GetStringFromObj(objv[2], 0);
878 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
879 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
880 if( pCollate==0 ) return TCL_ERROR;
881 pCollate->interp = interp;
882 pCollate->pNext = pDb->pCollate;
883 pCollate->zScript = (char*)&pCollate[1];
884 pDb->pCollate = pCollate;
885 strcpy(pCollate->zScript, zScript);
886 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
887 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +0000888 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +0000889 return TCL_ERROR;
890 }
891 break;
892 }
893
894 /*
895 ** $db collation_needed SCRIPT
896 **
897 ** Create a new SQL collation function called NAME. Whenever
898 ** that function is called, invoke SCRIPT to evaluate the function.
899 */
900 case DB_COLLATION_NEEDED: {
901 if( objc!=3 ){
902 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
903 return TCL_ERROR;
904 }
905 if( pDb->pCollateNeeded ){
906 Tcl_DecrRefCount(pDb->pCollateNeeded);
907 }
908 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
909 Tcl_IncrRefCount(pDb->pCollateNeeded);
910 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
911 break;
912 }
913
drh19e2d372005-08-29 23:00:03 +0000914 /* $db commit_hook ?CALLBACK?
915 **
916 ** Invoke the given callback just before committing every SQL transaction.
917 ** If the callback throws an exception or returns non-zero, then the
918 ** transaction is aborted. If CALLBACK is an empty string, the callback
919 ** is disabled.
920 */
921 case DB_COMMIT_HOOK: {
922 if( objc>3 ){
923 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
924 return TCL_ERROR;
925 }else if( objc==2 ){
926 if( pDb->zCommit ){
927 Tcl_AppendResult(interp, pDb->zCommit, 0);
928 }
929 }else{
930 char *zCommit;
931 int len;
932 if( pDb->zCommit ){
933 Tcl_Free(pDb->zCommit);
934 }
935 zCommit = Tcl_GetStringFromObj(objv[2], &len);
936 if( zCommit && len>0 ){
937 pDb->zCommit = Tcl_Alloc( len + 1 );
938 strcpy(pDb->zCommit, zCommit);
939 }else{
940 pDb->zCommit = 0;
941 }
942 if( pDb->zCommit ){
943 pDb->interp = interp;
944 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
945 }else{
946 sqlite3_commit_hook(pDb->db, 0, 0);
947 }
948 }
949 break;
950 }
951
drh75897232000-05-29 14:26:00 +0000952 /* $db complete SQL
953 **
954 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
955 ** additional lines of input are needed. This is similar to the
956 ** built-in "info complete" command of Tcl.
957 */
drh6d313162000-09-21 13:01:35 +0000958 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +0000959#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +0000960 Tcl_Obj *pResult;
961 int isComplete;
962 if( objc!=3 ){
963 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +0000964 return TCL_ERROR;
965 }
danielk19776f8a5032004-05-10 10:34:51 +0000966 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +0000967 pResult = Tcl_GetObjResult(interp);
968 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +0000969#endif
drh6d313162000-09-21 13:01:35 +0000970 break;
971 }
drhdcd997e2003-01-31 17:21:49 +0000972
drh19e2d372005-08-29 23:00:03 +0000973 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
974 **
975 ** Copy data into table from filename, optionally using SEPARATOR
976 ** as column separators. If a column contains a null string, or the
977 ** value of NULLINDICATOR, a NULL is inserted for the column.
978 ** conflict-algorithm is one of the sqlite conflict algorithms:
979 ** rollback, abort, fail, ignore, replace
980 ** On success, return the number of lines processed, not necessarily same
981 ** as 'db changes' due to conflict-algorithm selected.
982 **
983 ** This code is basically an implementation/enhancement of
984 ** the sqlite3 shell.c ".import" command.
985 **
986 ** This command usage is equivalent to the sqlite2.x COPY statement,
987 ** which imports file data into a table using the PostgreSQL COPY file format:
988 ** $db copy $conflit_algo $table_name $filename \t \\N
989 */
990 case DB_COPY: {
991 char *zTable; /* Insert data into this table */
992 char *zFile; /* The file from which to extract data */
993 char *zConflict; /* The conflict algorithm to use */
994 sqlite3_stmt *pStmt; /* A statement */
995 int rc; /* Result code */
996 int nCol; /* Number of columns in the table */
997 int nByte; /* Number of bytes in an SQL string */
998 int i, j; /* Loop counters */
999 int nSep; /* Number of bytes in zSep[] */
1000 int nNull; /* Number of bytes in zNull[] */
1001 char *zSql; /* An SQL statement */
1002 char *zLine; /* A single line of input from the file */
1003 char **azCol; /* zLine[] broken up into columns */
1004 char *zCommit; /* How to commit changes */
1005 FILE *in; /* The input file */
1006 int lineno = 0; /* Line number of input file */
1007 char zLineNum[80]; /* Line number print buffer */
1008 Tcl_Obj *pResult; /* interp result */
1009
1010 char *zSep;
1011 char *zNull;
1012 if( objc<5 || objc>7 ){
1013 Tcl_WrongNumArgs(interp, 2, objv,
1014 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1015 return TCL_ERROR;
1016 }
1017 if( objc>=6 ){
1018 zSep = Tcl_GetStringFromObj(objv[5], 0);
1019 }else{
1020 zSep = "\t";
1021 }
1022 if( objc>=7 ){
1023 zNull = Tcl_GetStringFromObj(objv[6], 0);
1024 }else{
1025 zNull = "";
1026 }
1027 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1028 zTable = Tcl_GetStringFromObj(objv[3], 0);
1029 zFile = Tcl_GetStringFromObj(objv[4], 0);
1030 nSep = strlen(zSep);
1031 nNull = strlen(zNull);
1032 if( nSep==0 ){
1033 Tcl_AppendResult(interp, "Error: non-null separator required for copy", 0);
1034 return TCL_ERROR;
1035 }
1036 if(sqlite3StrICmp(zConflict, "rollback") != 0 &&
1037 sqlite3StrICmp(zConflict, "abort" ) != 0 &&
1038 sqlite3StrICmp(zConflict, "fail" ) != 0 &&
1039 sqlite3StrICmp(zConflict, "ignore" ) != 0 &&
1040 sqlite3StrICmp(zConflict, "replace" ) != 0 ) {
1041 Tcl_AppendResult(interp, "Error: \"", zConflict,
1042 "\", conflict-algorithm must be one of: rollback, "
1043 "abort, fail, ignore, or replace", 0);
1044 return TCL_ERROR;
1045 }
1046 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1047 if( zSql==0 ){
1048 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1049 return TCL_ERROR;
1050 }
1051 nByte = strlen(zSql);
1052 rc = sqlite3_prepare(pDb->db, zSql, 0, &pStmt, 0);
1053 sqlite3_free(zSql);
1054 if( rc ){
1055 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1056 nCol = 0;
1057 }else{
1058 nCol = sqlite3_column_count(pStmt);
1059 }
1060 sqlite3_finalize(pStmt);
1061 if( nCol==0 ) {
1062 return TCL_ERROR;
1063 }
1064 zSql = malloc( nByte + 50 + nCol*2 );
1065 if( zSql==0 ) {
1066 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1067 return TCL_ERROR;
1068 }
1069 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1070 zConflict, zTable);
1071 j = strlen(zSql);
1072 for(i=1; i<nCol; i++){
1073 zSql[j++] = ',';
1074 zSql[j++] = '?';
1075 }
1076 zSql[j++] = ')';
1077 zSql[j] = 0;
1078 rc = sqlite3_prepare(pDb->db, zSql, 0, &pStmt, 0);
1079 free(zSql);
1080 if( rc ){
1081 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1082 sqlite3_finalize(pStmt);
1083 return TCL_ERROR;
1084 }
1085 in = fopen(zFile, "rb");
1086 if( in==0 ){
1087 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
1088 sqlite3_finalize(pStmt);
1089 return TCL_ERROR;
1090 }
1091 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1092 if( azCol==0 ) {
1093 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1094 return TCL_ERROR;
1095 }
1096 sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
1097 zCommit = "COMMIT";
1098 while( (zLine = local_getline(0, in))!=0 ){
1099 char *z;
1100 i = 0;
1101 lineno++;
1102 azCol[0] = zLine;
1103 for(i=0, z=zLine; *z; z++){
1104 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
1105 *z = 0;
1106 i++;
1107 if( i<nCol ){
1108 azCol[i] = &z[nSep];
1109 z += nSep-1;
1110 }
1111 }
1112 }
1113 if( i+1!=nCol ){
1114 char *zErr;
1115 zErr = malloc(200 + strlen(zFile));
1116 sprintf(zErr,"Error: %s line %d: expected %d columns of data but found %d",
1117 zFile, lineno, nCol, i+1);
1118 Tcl_AppendResult(interp, zErr, 0);
1119 free(zErr);
1120 zCommit = "ROLLBACK";
1121 break;
1122 }
1123 for(i=0; i<nCol; i++){
1124 /* check for null data, if so, bind as null */
1125 if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
1126 sqlite3_bind_null(pStmt, i+1);
1127 }else{
1128 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1129 }
1130 }
1131 sqlite3_step(pStmt);
1132 rc = sqlite3_reset(pStmt);
1133 free(zLine);
1134 if( rc!=SQLITE_OK ){
1135 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
1136 zCommit = "ROLLBACK";
1137 break;
1138 }
1139 }
1140 free(azCol);
1141 fclose(in);
1142 sqlite3_finalize(pStmt);
1143 sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
1144
1145 if( zCommit[0] == 'C' ){
1146 /* success, set result as number of lines processed */
1147 pResult = Tcl_GetObjResult(interp);
1148 Tcl_SetIntObj(pResult, lineno);
1149 rc = TCL_OK;
1150 }else{
1151 /* failure, append lineno where failed */
1152 sprintf(zLineNum,"%d",lineno);
1153 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
1154 rc = TCL_ERROR;
1155 }
1156 break;
1157 }
1158
drhdcd997e2003-01-31 17:21:49 +00001159 /*
1160 ** $db errorcode
1161 **
1162 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00001163 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00001164 */
1165 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00001166 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00001167 break;
1168 }
drh75897232000-05-29 14:26:00 +00001169
1170 /*
drh895d7472004-08-20 16:02:39 +00001171 ** $db eval $sql ?array? ?{ ...code... }?
drh1807ce32004-09-07 13:20:35 +00001172 ** $db onecolumn $sql
drh75897232000-05-29 14:26:00 +00001173 **
1174 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00001175 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00001176 ** If "array" and "code" are omitted, then no callback is every invoked.
1177 ** If "array" is an empty string, then the values are placed in variables
1178 ** that have the same name as the fields extracted by the query.
drh1807ce32004-09-07 13:20:35 +00001179 **
1180 ** The onecolumn method is the equivalent of:
1181 ** lindex [$db eval $sql] 0
drh75897232000-05-29 14:26:00 +00001182 */
drh1807ce32004-09-07 13:20:35 +00001183 case DB_ONECOLUMN:
drh97f2ebc2005-12-10 21:19:04 +00001184 case DB_EVAL:
1185 case DB_EXISTS: {
drh9d74b4c2004-08-24 15:23:34 +00001186 char const *zSql; /* Next SQL statement to execute */
1187 char const *zLeft; /* What is left after first stmt in zSql */
1188 sqlite3_stmt *pStmt; /* Compiled SQL statment */
drh92febd92004-08-20 18:34:20 +00001189 Tcl_Obj *pArray; /* Name of array into which results are written */
1190 Tcl_Obj *pScript; /* Script to run for each result set */
drh1d895032004-08-26 00:56:05 +00001191 Tcl_Obj **apParm; /* Parameters that need a Tcl_DecrRefCount() */
1192 int nParm; /* Number of entries used in apParm[] */
1193 Tcl_Obj *aParm[10]; /* Static space for apParm[] in the common case */
drh1807ce32004-09-07 13:20:35 +00001194 Tcl_Obj *pRet; /* Value to be returned */
drhfb7e7652005-01-24 00:28:42 +00001195 SqlPreparedStmt *pPreStmt; /* Pointer to a prepared statement */
1196 int rc2;
danielk1977ef2cb632004-05-29 02:37:19 +00001197
drh97f2ebc2005-12-10 21:19:04 +00001198 if( choice==DB_EVAL ){
drh1807ce32004-09-07 13:20:35 +00001199 if( objc<3 || objc>5 ){
1200 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
1201 return TCL_ERROR;
1202 }
1203 pRet = Tcl_NewObj();
1204 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001205 }else{
1206 if( objc!=3 ){
1207 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
1208 return TCL_ERROR;
1209 }
1210 pRet = 0;
1211 if( choice==DB_EXISTS ){
1212 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(0));
1213 }
danielk197730ccda12004-05-27 12:11:31 +00001214 }
drh92febd92004-08-20 18:34:20 +00001215 if( objc==3 ){
1216 pArray = pScript = 0;
1217 }else if( objc==4 ){
1218 pArray = 0;
1219 pScript = objv[3];
1220 }else{
1221 pArray = objv[3];
1222 if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
1223 pScript = objv[4];
1224 }
danielk197730ccda12004-05-27 12:11:31 +00001225
drh1d895032004-08-26 00:56:05 +00001226 Tcl_IncrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001227 zSql = Tcl_GetStringFromObj(objv[2], 0);
drh90b6bb12004-09-13 13:16:31 +00001228 while( rc==TCL_OK && zSql[0] ){
drhfb7e7652005-01-24 00:28:42 +00001229 int i; /* Loop counter */
1230 int nVar; /* Number of bind parameters in the pStmt */
1231 int nCol; /* Number of columns in the result set */
drh92febd92004-08-20 18:34:20 +00001232 Tcl_Obj **apColName = 0; /* Array of column names */
drhfb7e7652005-01-24 00:28:42 +00001233 int len; /* String length of zSql */
danielk197730ccda12004-05-27 12:11:31 +00001234
drhfb7e7652005-01-24 00:28:42 +00001235 /* Try to find a SQL statement that has already been compiled and
1236 ** which matches the next sequence of SQL.
1237 */
1238 pStmt = 0;
1239 pPreStmt = pDb->stmtList;
1240 len = strlen(zSql);
1241 if( pPreStmt && sqlite3_expired(pPreStmt->pStmt) ){
1242 flushStmtCache(pDb);
1243 pPreStmt = 0;
danielk197730ccda12004-05-27 12:11:31 +00001244 }
drhfb7e7652005-01-24 00:28:42 +00001245 for(; pPreStmt; pPreStmt=pPreStmt->pNext){
1246 int n = pPreStmt->nSql;
1247 if( len>=n
1248 && memcmp(pPreStmt->zSql, zSql, n)==0
1249 && (zSql[n]==0 || zSql[n-1]==';')
1250 ){
1251 pStmt = pPreStmt->pStmt;
1252 zLeft = &zSql[pPreStmt->nSql];
1253
1254 /* When a prepared statement is found, unlink it from the
1255 ** cache list. It will later be added back to the beginning
1256 ** of the cache list in order to implement LRU replacement.
1257 */
1258 if( pPreStmt->pPrev ){
1259 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1260 }else{
1261 pDb->stmtList = pPreStmt->pNext;
1262 }
1263 if( pPreStmt->pNext ){
1264 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1265 }else{
1266 pDb->stmtLast = pPreStmt->pPrev;
1267 }
1268 pDb->nStmt--;
1269 break;
1270 }
1271 }
1272
1273 /* If no prepared statement was found. Compile the SQL text
1274 */
drh92febd92004-08-20 18:34:20 +00001275 if( pStmt==0 ){
drhfb7e7652005-01-24 00:28:42 +00001276 if( SQLITE_OK!=sqlite3_prepare(pDb->db, zSql, -1, &pStmt, &zLeft) ){
drh92febd92004-08-20 18:34:20 +00001277 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1278 rc = TCL_ERROR;
1279 break;
danielk197730ccda12004-05-27 12:11:31 +00001280 }
drhfb7e7652005-01-24 00:28:42 +00001281 if( pStmt==0 ){
1282 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1283 /* A compile-time error in the statement
1284 */
1285 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1286 rc = TCL_ERROR;
1287 break;
1288 }else{
1289 /* The statement was a no-op. Continue to the next statement
1290 ** in the SQL string.
1291 */
1292 zSql = zLeft;
1293 continue;
1294 }
1295 }
1296 assert( pPreStmt==0 );
danielk197730ccda12004-05-27 12:11:31 +00001297 }
1298
drhfb7e7652005-01-24 00:28:42 +00001299 /* Bind values to parameters that begin with $ or :
1300 */
drh92febd92004-08-20 18:34:20 +00001301 nVar = sqlite3_bind_parameter_count(pStmt);
drh1d895032004-08-26 00:56:05 +00001302 nParm = 0;
1303 if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
1304 apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
1305 }else{
1306 apParm = aParm;
1307 }
drh92febd92004-08-20 18:34:20 +00001308 for(i=1; i<=nVar; i++){
1309 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
drhc8f90792005-01-12 00:08:24 +00001310 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':') ){
drh92febd92004-08-20 18:34:20 +00001311 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1312 if( pVar ){
1313 int n;
1314 u8 *data;
1315 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
1316 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +00001317 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
1318 /* Only load a BLOB type if the Tcl variable is a bytearray and
1319 ** has no string representation. */
drh92febd92004-08-20 18:34:20 +00001320 data = Tcl_GetByteArrayFromObj(pVar, &n);
1321 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001322 Tcl_IncrRefCount(pVar);
1323 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001324 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
1325 (c=='i' && strcmp(zType,"int")==0) ){
1326 Tcl_GetIntFromObj(interp, pVar, &n);
1327 sqlite3_bind_int(pStmt, i, n);
1328 }else if( c=='d' && strcmp(zType,"double")==0 ){
1329 double r;
1330 Tcl_GetDoubleFromObj(interp, pVar, &r);
1331 sqlite3_bind_double(pStmt, i, r);
drhdf0bdda2005-06-25 19:31:48 +00001332 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
1333 Tcl_WideInt v;
1334 Tcl_GetWideIntFromObj(interp, pVar, &v);
1335 sqlite3_bind_int64(pStmt, i, v);
drh92febd92004-08-20 18:34:20 +00001336 }else{
danielk197700fd9572005-12-07 06:27:43 +00001337 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1338 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001339 Tcl_IncrRefCount(pVar);
1340 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001341 }
drhfb7e7652005-01-24 00:28:42 +00001342 }else{
1343 sqlite3_bind_null( pStmt, i );
drh92febd92004-08-20 18:34:20 +00001344 }
1345 }
1346 }
drh92febd92004-08-20 18:34:20 +00001347
1348 /* Compute column names */
1349 nCol = sqlite3_column_count(pStmt);
1350 if( pScript ){
1351 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1352 if( apColName==0 ) break;
1353 for(i=0; i<nCol; i++){
1354 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1355 Tcl_IncrRefCount(apColName[i]);
1356 }
1357 }
1358
1359 /* If results are being stored in an array variable, then create
1360 ** the array(*) entry for that array
1361 */
1362 if( pArray ){
1363 Tcl_Obj *pColList = Tcl_NewObj();
drh3ced14a2005-03-31 18:26:20 +00001364 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
drh92febd92004-08-20 18:34:20 +00001365 Tcl_IncrRefCount(pColList);
1366 for(i=0; i<nCol; i++){
1367 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1368 }
drh3ced14a2005-03-31 18:26:20 +00001369 Tcl_ObjSetVar2(interp, pArray, pStar, pColList,0);
1370 Tcl_DecrRefCount(pColList);
1371 Tcl_DecrRefCount(pStar);
drh92febd92004-08-20 18:34:20 +00001372 }
1373
1374 /* Execute the SQL
1375 */
drh90b6bb12004-09-13 13:16:31 +00001376 while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
drh92febd92004-08-20 18:34:20 +00001377 for(i=0; i<nCol; i++){
danielk197730ccda12004-05-27 12:11:31 +00001378 Tcl_Obj *pVal;
1379
1380 /* Set pVal to contain the i'th column of this row. */
drh92febd92004-08-20 18:34:20 +00001381 switch( sqlite3_column_type(pStmt, i) ){
1382 case SQLITE_BLOB: {
1383 int bytes = sqlite3_column_bytes(pStmt, i);
1384 pVal = Tcl_NewByteArrayObj(sqlite3_column_blob(pStmt, i), bytes);
1385 break;
1386 }
1387 case SQLITE_INTEGER: {
1388 sqlite_int64 v = sqlite3_column_int64(pStmt, i);
1389 if( v>=-2147483647 && v<=2147483647 ){
1390 pVal = Tcl_NewIntObj(v);
1391 }else{
1392 pVal = Tcl_NewWideIntObj(v);
1393 }
1394 break;
1395 }
1396 case SQLITE_FLOAT: {
1397 double r = sqlite3_column_double(pStmt, i);
1398 pVal = Tcl_NewDoubleObj(r);
1399 break;
1400 }
danielk197755c45f22005-04-03 23:54:43 +00001401 case SQLITE_NULL: {
1402 pVal = dbTextToObj(pDb->zNull);
1403 break;
1404 }
drh92febd92004-08-20 18:34:20 +00001405 default: {
danielk197700fd9572005-12-07 06:27:43 +00001406 pVal = dbTextToObj((char *)sqlite3_column_text(pStmt, i));
drh92febd92004-08-20 18:34:20 +00001407 break;
1408 }
danielk197730ccda12004-05-27 12:11:31 +00001409 }
1410
drh92febd92004-08-20 18:34:20 +00001411 if( pScript ){
1412 if( pArray==0 ){
1413 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001414 }else{
drh92febd92004-08-20 18:34:20 +00001415 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001416 }
drh1807ce32004-09-07 13:20:35 +00001417 }else if( choice==DB_ONECOLUMN ){
drh97f2ebc2005-12-10 21:19:04 +00001418 assert( pRet==0 );
drh1807ce32004-09-07 13:20:35 +00001419 if( pRet==0 ){
1420 pRet = pVal;
1421 Tcl_IncrRefCount(pRet);
1422 }
drh90b6bb12004-09-13 13:16:31 +00001423 rc = TCL_BREAK;
drh97f2ebc2005-12-10 21:19:04 +00001424 i = nCol;
1425 }else if( choice==DB_EXISTS ){
1426 assert( pRet==0 );
1427 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(1));
1428 rc = TCL_BREAK;
1429 i = nCol;
danielk197730ccda12004-05-27 12:11:31 +00001430 }else{
danielk197730ccda12004-05-27 12:11:31 +00001431 Tcl_ListObjAppendElement(interp, pRet, pVal);
1432 }
1433 }
1434
drh92febd92004-08-20 18:34:20 +00001435 if( pScript ){
1436 rc = Tcl_EvalObjEx(interp, pScript, 0);
drh90b6bb12004-09-13 13:16:31 +00001437 if( rc==TCL_CONTINUE ){
1438 rc = TCL_OK;
1439 }
danielk197730ccda12004-05-27 12:11:31 +00001440 }
1441 }
drh90b6bb12004-09-13 13:16:31 +00001442 if( rc==TCL_BREAK ){
1443 rc = TCL_OK;
1444 }
drh92febd92004-08-20 18:34:20 +00001445
1446 /* Free the column name objects */
1447 if( pScript ){
1448 for(i=0; i<nCol; i++){
1449 Tcl_DecrRefCount(apColName[i]);
1450 }
1451 Tcl_Free((char*)apColName);
1452 }
1453
drh1d895032004-08-26 00:56:05 +00001454 /* Free the bound string and blob parameters */
1455 for(i=0; i<nParm; i++){
1456 Tcl_DecrRefCount(apParm[i]);
1457 }
1458 if( apParm!=aParm ){
1459 Tcl_Free((char*)apParm);
1460 }
1461
drhfb7e7652005-01-24 00:28:42 +00001462 /* Reset the statement. If the result code is SQLITE_SCHEMA, then
1463 ** flush the statement cache and try the statement again.
drh92febd92004-08-20 18:34:20 +00001464 */
drhfb7e7652005-01-24 00:28:42 +00001465 rc2 = sqlite3_reset(pStmt);
1466 if( SQLITE_SCHEMA==rc2 ){
1467 /* After a schema change, flush the cache and try to run the
1468 ** statement again
1469 */
1470 flushStmtCache( pDb );
1471 sqlite3_finalize(pStmt);
1472 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001473 continue;
drhfb7e7652005-01-24 00:28:42 +00001474 }else if( SQLITE_OK!=rc2 ){
1475 /* If a run-time error occurs, report the error and stop reading
1476 ** the SQL
1477 */
danielk1977ef2cb632004-05-29 02:37:19 +00001478 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
drhfb7e7652005-01-24 00:28:42 +00001479 sqlite3_finalize(pStmt);
danielk197730ccda12004-05-27 12:11:31 +00001480 rc = TCL_ERROR;
drhfb7e7652005-01-24 00:28:42 +00001481 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001482 break;
drhfb7e7652005-01-24 00:28:42 +00001483 }else if( pDb->maxStmt<=0 ){
1484 /* If the cache is turned off, deallocated the statement */
1485 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1486 sqlite3_finalize(pStmt);
1487 }else{
1488 /* Everything worked and the cache is operational.
1489 ** Create a new SqlPreparedStmt structure if we need one.
1490 ** (If we already have one we can just reuse it.)
1491 */
1492 if( pPreStmt==0 ){
1493 len = zLeft - zSql;
1494 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) + len );
1495 if( pPreStmt==0 ) return TCL_ERROR;
1496 pPreStmt->pStmt = pStmt;
1497 pPreStmt->nSql = len;
1498 memcpy(pPreStmt->zSql, zSql, len);
1499 pPreStmt->zSql[len] = 0;
1500 }
1501
1502 /* Add the prepared statement to the beginning of the cache list
1503 */
1504 pPreStmt->pNext = pDb->stmtList;
1505 pPreStmt->pPrev = 0;
1506 if( pDb->stmtList ){
1507 pDb->stmtList->pPrev = pPreStmt;
1508 }
1509 pDb->stmtList = pPreStmt;
1510 if( pDb->stmtLast==0 ){
1511 assert( pDb->nStmt==0 );
1512 pDb->stmtLast = pPreStmt;
1513 }else{
1514 assert( pDb->nStmt>0 );
1515 }
1516 pDb->nStmt++;
1517
1518 /* If we have too many statement in cache, remove the surplus from the
1519 ** end of the cache list.
1520 */
1521 while( pDb->nStmt>pDb->maxStmt ){
1522 sqlite3_finalize(pDb->stmtLast->pStmt);
1523 pDb->stmtLast = pDb->stmtLast->pPrev;
1524 Tcl_Free((char*)pDb->stmtLast->pNext);
1525 pDb->stmtLast->pNext = 0;
1526 pDb->nStmt--;
1527 }
danielk197730ccda12004-05-27 12:11:31 +00001528 }
1529
drhfb7e7652005-01-24 00:28:42 +00001530 /* Proceed to the next statement */
danielk197730ccda12004-05-27 12:11:31 +00001531 zSql = zLeft;
1532 }
drh1d895032004-08-26 00:56:05 +00001533 Tcl_DecrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001534
drh1807ce32004-09-07 13:20:35 +00001535 if( pRet ){
1536 if( rc==TCL_OK ){
1537 Tcl_SetObjResult(interp, pRet);
1538 }
1539 Tcl_DecrRefCount(pRet);
danielk197730ccda12004-05-27 12:11:31 +00001540 }
danielk197730ccda12004-05-27 12:11:31 +00001541 break;
1542 }
drhbec3f402000-08-04 13:49:02 +00001543
1544 /*
drhcabb0812002-09-14 13:47:32 +00001545 ** $db function NAME SCRIPT
1546 **
1547 ** Create a new SQL function called NAME. Whenever that function is
1548 ** called, invoke SCRIPT to evaluate the function.
1549 */
1550 case DB_FUNCTION: {
1551 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00001552 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00001553 char *zName;
drhcabb0812002-09-14 13:47:32 +00001554 if( objc!=4 ){
1555 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1556 return TCL_ERROR;
1557 }
1558 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00001559 pScript = objv[3];
1560 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00001561 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00001562 if( pFunc->pScript ){
1563 Tcl_DecrRefCount(pFunc->pScript);
1564 }
1565 pFunc->pScript = pScript;
1566 Tcl_IncrRefCount(pScript);
1567 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
danielk1977c8c11582004-06-29 13:41:21 +00001568 rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00001569 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00001570 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00001571 rc = TCL_ERROR;
1572 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00001573 }else{
1574 /* Must flush any cached statements */
1575 flushStmtCache( pDb );
1576 }
drhcabb0812002-09-14 13:47:32 +00001577 break;
1578 }
1579
1580 /*
drh19e2d372005-08-29 23:00:03 +00001581 ** $db nullvalue ?STRING?
1582 **
1583 ** Change text used when a NULL comes back from the database. If ?STRING?
1584 ** is not present, then the current string used for NULL is returned.
1585 ** If STRING is present, then STRING is returned.
1586 **
1587 */
1588 case DB_NULLVALUE: {
1589 if( objc!=2 && objc!=3 ){
1590 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
1591 return TCL_ERROR;
1592 }
1593 if( objc==3 ){
1594 int len;
1595 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
1596 if( pDb->zNull ){
1597 Tcl_Free(pDb->zNull);
1598 }
1599 if( zNull && len>0 ){
1600 pDb->zNull = Tcl_Alloc( len + 1 );
1601 strncpy(pDb->zNull, zNull, len);
1602 pDb->zNull[len] = '\0';
1603 }else{
1604 pDb->zNull = 0;
1605 }
1606 }
1607 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
1608 break;
1609 }
1610
1611 /*
drhaf9ff332002-01-16 21:00:27 +00001612 ** $db last_insert_rowid
1613 **
1614 ** Return an integer which is the ROWID for the most recent insert.
1615 */
1616 case DB_LAST_INSERT_ROWID: {
1617 Tcl_Obj *pResult;
1618 int rowid;
1619 if( objc!=2 ){
1620 Tcl_WrongNumArgs(interp, 2, objv, "");
1621 return TCL_ERROR;
1622 }
danielk19776f8a5032004-05-10 10:34:51 +00001623 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00001624 pResult = Tcl_GetObjResult(interp);
1625 Tcl_SetIntObj(pResult, rowid);
1626 break;
1627 }
1628
1629 /*
drh1807ce32004-09-07 13:20:35 +00001630 ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
drh5d9d7572003-08-19 14:31:01 +00001631 */
drh1807ce32004-09-07 13:20:35 +00001632
1633 /* $db progress ?N CALLBACK?
1634 **
1635 ** Invoke the given callback every N virtual machine opcodes while executing
1636 ** queries.
1637 */
1638 case DB_PROGRESS: {
1639 if( objc==2 ){
1640 if( pDb->zProgress ){
1641 Tcl_AppendResult(interp, pDb->zProgress, 0);
1642 }
1643 }else if( objc==4 ){
1644 char *zProgress;
1645 int len;
1646 int N;
1647 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
1648 return TCL_ERROR;
1649 };
1650 if( pDb->zProgress ){
1651 Tcl_Free(pDb->zProgress);
1652 }
1653 zProgress = Tcl_GetStringFromObj(objv[3], &len);
1654 if( zProgress && len>0 ){
1655 pDb->zProgress = Tcl_Alloc( len + 1 );
1656 strcpy(pDb->zProgress, zProgress);
1657 }else{
1658 pDb->zProgress = 0;
1659 }
1660#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1661 if( pDb->zProgress ){
1662 pDb->interp = interp;
1663 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
1664 }else{
1665 sqlite3_progress_handler(pDb->db, 0, 0, 0);
1666 }
1667#endif
1668 }else{
1669 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00001670 return TCL_ERROR;
1671 }
drh5d9d7572003-08-19 14:31:01 +00001672 break;
1673 }
1674
drh19e2d372005-08-29 23:00:03 +00001675 /* $db profile ?CALLBACK?
1676 **
1677 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
1678 ** that has run. The text of the SQL and the amount of elapse time are
1679 ** appended to CALLBACK before the script is run.
1680 */
1681 case DB_PROFILE: {
1682 if( objc>3 ){
1683 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1684 return TCL_ERROR;
1685 }else if( objc==2 ){
1686 if( pDb->zProfile ){
1687 Tcl_AppendResult(interp, pDb->zProfile, 0);
1688 }
1689 }else{
1690 char *zProfile;
1691 int len;
1692 if( pDb->zProfile ){
1693 Tcl_Free(pDb->zProfile);
1694 }
1695 zProfile = Tcl_GetStringFromObj(objv[2], &len);
1696 if( zProfile && len>0 ){
1697 pDb->zProfile = Tcl_Alloc( len + 1 );
1698 strcpy(pDb->zProfile, zProfile);
1699 }else{
1700 pDb->zProfile = 0;
1701 }
1702#ifndef SQLITE_OMIT_TRACE
1703 if( pDb->zProfile ){
1704 pDb->interp = interp;
1705 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
1706 }else{
1707 sqlite3_profile(pDb->db, 0, 0);
1708 }
1709#endif
1710 }
1711 break;
1712 }
1713
drh5d9d7572003-08-19 14:31:01 +00001714 /*
drh22fbcb82004-02-01 01:22:50 +00001715 ** $db rekey KEY
1716 **
1717 ** Change the encryption key on the currently open database.
1718 */
1719 case DB_REKEY: {
1720 int nKey;
1721 void *pKey;
1722 if( objc!=3 ){
1723 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
1724 return TCL_ERROR;
1725 }
1726 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00001727#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00001728 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00001729 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00001730 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00001731 rc = TCL_ERROR;
1732 }
1733#endif
1734 break;
1735 }
1736
1737 /*
drhbec3f402000-08-04 13:49:02 +00001738 ** $db timeout MILLESECONDS
1739 **
1740 ** Delay for the number of milliseconds specified when a file is locked.
1741 */
drh6d313162000-09-21 13:01:35 +00001742 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00001743 int ms;
drh6d313162000-09-21 13:01:35 +00001744 if( objc!=3 ){
1745 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00001746 return TCL_ERROR;
1747 }
drh6d313162000-09-21 13:01:35 +00001748 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00001749 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00001750 break;
drh75897232000-05-29 14:26:00 +00001751 }
danielk19777ddad962005-12-12 06:53:03 +00001752
1753 /*
1754 ** $db soft_heap_limit N
1755 **
1756 ** Set the soft-heap-limit for this thread. Note that the limit is
danielk1977aef0bf62005-12-30 16:28:01 +00001757 ** per-thread, not per-database. The previous limit is returned.
danielk19777ddad962005-12-12 06:53:03 +00001758 */
1759 case DB_SOFT_HEAP_LIMIT: {
danielk19770190d1d2005-12-19 14:18:11 +00001760#ifndef SQLITE_OMIT_MEMORY_MANAGEMENT
danielk19777ddad962005-12-12 06:53:03 +00001761 int n;
danielk1977aef0bf62005-12-30 16:28:01 +00001762 int ret;
danielk19777ddad962005-12-12 06:53:03 +00001763 if( objc!=3 ){
1764 Tcl_WrongNumArgs(interp, 2, objv, "BYTES");
1765 return TCL_ERROR;
1766 }
1767 if( Tcl_GetIntFromObj(interp, objv[2], &n) ){
1768 return TCL_ERROR;
1769 }
danielk1977aef0bf62005-12-30 16:28:01 +00001770 ret = sqlite3Tsd()->nSoftHeapLimit;
danielk19777ddad962005-12-12 06:53:03 +00001771 sqlite3_soft_heap_limit(n);
danielk1977aef0bf62005-12-30 16:28:01 +00001772 Tcl_SetObjResult(interp, Tcl_NewIntObj(ret));
danielk19770190d1d2005-12-19 14:18:11 +00001773#endif
1774 break;
1775 }
1776
1777 /*
1778 ** $db release_memory ?N?
1779 **
1780 ** Try to release memory currently held (but not really required) by
1781 ** SQLite database connections opened by the current thread. If an
1782 ** integer argument is supplied, then SQLite stops trying to free memory
1783 ** after N bytes have been freed.
1784 **
1785 ** The value returned is the number of bytes actually freed.
1786 **/
1787 case DB_RELEASE_MEMORY: {
1788 int nRelease = 0;
1789 int N = -1;
1790 if( objc!=2 && objc!=3 ){
1791 Tcl_WrongNumArgs(interp, 2, objv, "?N?");
1792 return TCL_ERROR;
1793 }
1794#ifndef SQLITE_OMIT_MEMORY_MANAGEMENT
1795 if( objc==3 && TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
1796 return TCL_ERROR;
1797 }
1798 nRelease = sqlite3_release_memory(N);
1799#endif
1800 Tcl_SetObjResult(interp, Tcl_NewIntObj(nRelease));
danielk19777ddad962005-12-12 06:53:03 +00001801 break;
1802 }
danielk197755c45f22005-04-03 23:54:43 +00001803
1804 /*
drh0f14e2e2004-06-29 12:39:08 +00001805 ** $db total_changes
1806 **
1807 ** Return the number of rows that were modified, inserted, or deleted
1808 ** since the database handle was created.
1809 */
1810 case DB_TOTAL_CHANGES: {
1811 Tcl_Obj *pResult;
1812 if( objc!=2 ){
1813 Tcl_WrongNumArgs(interp, 2, objv, "");
1814 return TCL_ERROR;
1815 }
1816 pResult = Tcl_GetObjResult(interp);
1817 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
1818 break;
1819 }
1820
drhb5a20d32003-04-23 12:25:23 +00001821 /* $db trace ?CALLBACK?
1822 **
1823 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
1824 ** that is executed. The text of the SQL is appended to CALLBACK before
1825 ** it is executed.
1826 */
1827 case DB_TRACE: {
1828 if( objc>3 ){
1829 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00001830 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00001831 }else if( objc==2 ){
1832 if( pDb->zTrace ){
1833 Tcl_AppendResult(interp, pDb->zTrace, 0);
1834 }
1835 }else{
1836 char *zTrace;
1837 int len;
1838 if( pDb->zTrace ){
1839 Tcl_Free(pDb->zTrace);
1840 }
1841 zTrace = Tcl_GetStringFromObj(objv[2], &len);
1842 if( zTrace && len>0 ){
1843 pDb->zTrace = Tcl_Alloc( len + 1 );
1844 strcpy(pDb->zTrace, zTrace);
1845 }else{
1846 pDb->zTrace = 0;
1847 }
drh19e2d372005-08-29 23:00:03 +00001848#ifndef SQLITE_OMIT_TRACE
drhb5a20d32003-04-23 12:25:23 +00001849 if( pDb->zTrace ){
1850 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001851 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00001852 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001853 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00001854 }
drh19e2d372005-08-29 23:00:03 +00001855#endif
drhb5a20d32003-04-23 12:25:23 +00001856 }
1857 break;
1858 }
1859
drh3d214232005-08-02 12:21:08 +00001860 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1861 **
1862 ** Start a new transaction (if we are not already in the midst of a
1863 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
1864 ** completes, either commit the transaction or roll it back if SCRIPT
1865 ** throws an exception. Or if no new transation was started, do nothing.
1866 ** pass the exception on up the stack.
1867 **
1868 ** This command was inspired by Dave Thomas's talk on Ruby at the
1869 ** 2005 O'Reilly Open Source Convention (OSCON).
1870 */
1871 case DB_TRANSACTION: {
1872 int inTrans;
1873 Tcl_Obj *pScript;
1874 const char *zBegin = "BEGIN";
1875 if( objc!=3 && objc!=4 ){
1876 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
1877 return TCL_ERROR;
1878 }
1879 if( objc==3 ){
1880 pScript = objv[2];
1881 } else {
1882 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00001883 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00001884 };
1885 enum TTYPE_enum {
1886 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
1887 };
1888 int ttype;
drhb5555e72005-08-02 17:15:14 +00001889 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00001890 0, &ttype) ){
1891 return TCL_ERROR;
1892 }
1893 switch( (enum TTYPE_enum)ttype ){
1894 case TTYPE_DEFERRED: /* no-op */; break;
1895 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
1896 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
1897 }
1898 pScript = objv[3];
1899 }
1900 inTrans = !sqlite3_get_autocommit(pDb->db);
1901 if( !inTrans ){
1902 sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
1903 }
1904 rc = Tcl_EvalObjEx(interp, pScript, 0);
1905 if( !inTrans ){
1906 const char *zEnd;
1907 if( rc==TCL_ERROR ){
1908 zEnd = "ROLLBACK";
1909 } else {
1910 zEnd = "COMMIT";
1911 }
1912 sqlite3_exec(pDb->db, zEnd, 0, 0, 0);
1913 }
1914 break;
1915 }
1916
danielk197794eb6a12005-12-15 15:22:08 +00001917 /*
1918 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00001919 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00001920 */
danielk197771fd80b2005-12-16 06:54:01 +00001921 case DB_UPDATE_HOOK:
1922 case DB_ROLLBACK_HOOK: {
1923
1924 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
1925 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
1926 */
1927 Tcl_Obj **ppHook;
1928 if( choice==DB_UPDATE_HOOK ){
1929 ppHook = &pDb->pUpdateHook;
1930 }else{
1931 ppHook = &pDb->pRollbackHook;
1932 }
1933
danielk197794eb6a12005-12-15 15:22:08 +00001934 if( objc!=2 && objc!=3 ){
1935 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
1936 return TCL_ERROR;
1937 }
danielk197771fd80b2005-12-16 06:54:01 +00001938 if( *ppHook ){
1939 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00001940 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00001941 Tcl_DecrRefCount(*ppHook);
1942 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00001943 }
1944 }
1945 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00001946 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00001947 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00001948 *ppHook = objv[2];
1949 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00001950 }
1951 }
danielk197771fd80b2005-12-16 06:54:01 +00001952
1953 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1954 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
1955
danielk197794eb6a12005-12-15 15:22:08 +00001956 break;
1957 }
1958
danielk19774397de52005-01-12 12:44:03 +00001959 /* $db version
1960 **
1961 ** Return the version string for this database.
1962 */
1963 case DB_VERSION: {
1964 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
1965 break;
1966 }
1967
tpoindex1067fe12004-12-17 15:41:11 +00001968
drh6d313162000-09-21 13:01:35 +00001969 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00001970 return rc;
drh75897232000-05-29 14:26:00 +00001971}
1972
1973/*
drh9bb575f2004-09-06 17:24:11 +00001974** sqlite3 DBNAME FILENAME ?MODE? ?-key KEY?
drh75897232000-05-29 14:26:00 +00001975**
1976** This is the main Tcl command. When the "sqlite" Tcl command is
1977** invoked, this routine runs to process that command.
1978**
1979** The first argument, DBNAME, is an arbitrary name for a new
1980** database connection. This command creates a new command named
1981** DBNAME that is used to control that connection. The database
1982** connection is deleted when the DBNAME command is deleted.
1983**
1984** The second argument is the name of the directory that contains
1985** the sqlite database that is to be accessed.
drhfbc3eab2001-04-06 16:13:42 +00001986**
1987** For testing purposes, we also support the following:
1988**
drh9bb575f2004-09-06 17:24:11 +00001989** sqlite3 -encoding
drhfbc3eab2001-04-06 16:13:42 +00001990**
1991** Return the encoding used by LIKE and GLOB operators. Choices
1992** are UTF-8 and iso8859.
1993**
drh9bb575f2004-09-06 17:24:11 +00001994** sqlite3 -version
drh647cb0e2002-11-04 19:32:25 +00001995**
1996** Return the version number of the SQLite library.
1997**
drh9bb575f2004-09-06 17:24:11 +00001998** sqlite3 -tcl-uses-utf
drhfbc3eab2001-04-06 16:13:42 +00001999**
2000** Return "1" if compiled with a Tcl uses UTF-8. Return "0" if
2001** not. Used by tests to make sure the library was compiled
2002** correctly.
drh75897232000-05-29 14:26:00 +00002003*/
drh22fbcb82004-02-01 01:22:50 +00002004static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00002005 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00002006 void *pKey = 0;
2007 int nKey = 0;
2008 const char *zArg;
drh75897232000-05-29 14:26:00 +00002009 char *zErrMsg;
drh22fbcb82004-02-01 01:22:50 +00002010 const char *zFile;
drh06b27182002-06-26 20:06:05 +00002011 char zBuf[80];
drh22fbcb82004-02-01 01:22:50 +00002012 if( objc==2 ){
2013 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00002014 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00002015 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00002016 return TCL_OK;
2017 }
drh9eb9e262004-02-11 02:18:05 +00002018 if( strcmp(zArg,"-has-codec")==0 ){
2019#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00002020 Tcl_AppendResult(interp,"1",0);
2021#else
2022 Tcl_AppendResult(interp,"0",0);
2023#endif
2024 return TCL_OK;
2025 }
2026 if( strcmp(zArg,"-tcl-uses-utf")==0 ){
drhfbc3eab2001-04-06 16:13:42 +00002027#ifdef TCL_UTF_MAX
2028 Tcl_AppendResult(interp,"1",0);
2029#else
2030 Tcl_AppendResult(interp,"0",0);
2031#endif
2032 return TCL_OK;
2033 }
2034 }
drh22fbcb82004-02-01 01:22:50 +00002035 if( objc==5 || objc==6 ){
2036 zArg = Tcl_GetStringFromObj(objv[objc-2], 0);
2037 if( strcmp(zArg,"-key")==0 ){
2038 pKey = Tcl_GetByteArrayFromObj(objv[objc-1], &nKey);
2039 objc -= 2;
2040 }
2041 }
2042 if( objc!=3 && objc!=4 ){
2043 Tcl_WrongNumArgs(interp, 1, objv,
drh9eb9e262004-02-11 02:18:05 +00002044#ifdef SQLITE_HAS_CODEC
2045 "HANDLE FILENAME ?-key CODEC-KEY?"
drh22fbcb82004-02-01 01:22:50 +00002046#else
2047 "HANDLE FILENAME ?MODE?"
2048#endif
2049 );
drh75897232000-05-29 14:26:00 +00002050 return TCL_ERROR;
2051 }
drh75897232000-05-29 14:26:00 +00002052 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00002053 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00002054 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00002055 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
2056 return TCL_ERROR;
2057 }
2058 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00002059 zFile = Tcl_GetStringFromObj(objv[2], 0);
danielk19774f057f92004-06-08 00:02:33 +00002060 sqlite3_open(zFile, &p->db);
danielk197780290862004-05-22 09:21:21 +00002061 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
2062 zErrMsg = strdup(sqlite3_errmsg(p->db));
2063 sqlite3_close(p->db);
2064 p->db = 0;
2065 }
drh2011d5f2004-07-22 02:40:37 +00002066#ifdef SQLITE_HAS_CODEC
2067 sqlite3_key(p->db, pKey, nKey);
drheb8ed702004-02-11 10:37:23 +00002068#endif
drhbec3f402000-08-04 13:49:02 +00002069 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00002070 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00002071 Tcl_Free((char*)p);
drh75897232000-05-29 14:26:00 +00002072 free(zErrMsg);
2073 return TCL_ERROR;
2074 }
drhfb7e7652005-01-24 00:28:42 +00002075 p->maxStmt = NUM_PREPARED_STMTS;
drh22fbcb82004-02-01 01:22:50 +00002076 zArg = Tcl_GetStringFromObj(objv[1], 0);
2077 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
drhc22bd472002-05-10 13:14:07 +00002078
drh06b27182002-06-26 20:06:05 +00002079 /* The return value is the value of the sqlite* pointer
2080 */
2081 sprintf(zBuf, "%p", p->db);
drh5e5377f2002-07-07 17:12:36 +00002082 if( strncmp(zBuf,"0x",2) ){
2083 sprintf(zBuf, "0x%p", p->db);
2084 }
drh06b27182002-06-26 20:06:05 +00002085 Tcl_AppendResult(interp, zBuf, 0);
2086
drhc22bd472002-05-10 13:14:07 +00002087 /* If compiled with SQLITE_TEST turned on, then register the "md5sum"
drh06b27182002-06-26 20:06:05 +00002088 ** SQL function.
drhc22bd472002-05-10 13:14:07 +00002089 */
drh28b4e482002-03-11 02:06:13 +00002090#ifdef SQLITE_TEST
2091 {
drh9bb575f2004-09-06 17:24:11 +00002092 extern void Md5_Register(sqlite3*);
drh3b93bc82005-01-13 23:54:32 +00002093#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00002094 int mallocfail = sqlite3_iMallocFail;
2095 sqlite3_iMallocFail = 0;
danielk19775b59af82004-06-30 12:42:59 +00002096#endif
drhc22bd472002-05-10 13:14:07 +00002097 Md5_Register(p->db);
drh3b93bc82005-01-13 23:54:32 +00002098#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00002099 sqlite3_iMallocFail = mallocfail;
danielk19775b59af82004-06-30 12:42:59 +00002100#endif
danielk19777ddad962005-12-12 06:53:03 +00002101 }
drh28b4e482002-03-11 02:06:13 +00002102#endif
danielk19777cedc8d2004-06-10 10:50:08 +00002103 p->interp = interp;
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*/
drh29bc4612005-10-05 10:40:15 +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}
drh29bc4612005-10-05 10:40:15 +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
drh29bc4612005-10-05 10:40:15 +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*);
danielk197713a68c32005-12-15 10:11:30 +00002212 extern int Sqlitetestasync_Init(Tcl_Interp*);
drhefc251d2001-07-01 22:12:01 +00002213 extern int Md5_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002214 extern int Sqlitetestsse_Init(Tcl_Interp*);
2215
danielk19776490beb2004-05-11 06:17:21 +00002216 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00002217 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00002218 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00002219 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00002220 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00002221 Sqlitetest6_Init(interp);
danielk197771fd80b2005-12-16 06:54:01 +00002222 /* Sqlitetestasync_Init(interp); */
drhefc251d2001-07-01 22:12:01 +00002223 Md5_Init(interp);
drh89dec812005-04-28 19:03:37 +00002224#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00002225 Sqlitetestsse_Init(interp);
2226#endif
drhd1bf3512001-04-07 15:24:33 +00002227 }
2228#endif
drh3e27c022004-07-23 00:01:38 +00002229 if( argc>=2 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002230 int i;
2231 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
2232 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00002233 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00002234 Tcl_SetVar(interp, "argv", argv[i],
2235 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
2236 }
drh3e27c022004-07-23 00:01:38 +00002237 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00002238 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drhc61053b2000-06-04 12:58:36 +00002239 if( zInfo==0 ) zInfo = interp->result;
2240 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00002241 return 1;
2242 }
drh3e27c022004-07-23 00:01:38 +00002243 }
2244 if( argc<=1 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002245 Tcl_GlobalEval(interp, zMainloop);
2246 }
2247 return 0;
2248}
2249#endif /* TCLSH */
drh6d313162000-09-21 13:01:35 +00002250
2251#endif /* !defined(NO_TCL) */