blob: 1f4c5901f50c674fde61e3fe0a737b20095168bd [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**
drh41449052006-07-06 17:08:48 +000014** $Id: tclsqlite.c,v 1.162 2006/07/06 17:08:48 drh Exp $
drh75897232000-05-29 14:26:00 +000015*/
drh6d313162000-09-21 13:01:35 +000016#ifndef NO_TCL /* Omit this whole file if TCL is unavailable */
17
drh06b27182002-06-26 20:06:05 +000018#include "sqliteInt.h"
drh895d7472004-08-20 16:02:39 +000019#include "hash.h"
drh17a68932001-01-31 13:28:08 +000020#include "tcl.h"
drh75897232000-05-29 14:26:00 +000021#include <stdlib.h>
22#include <string.h>
drhce927062001-11-09 13:41:09 +000023#include <assert.h>
drhd1e47332005-06-26 17:55:33 +000024#include <ctype.h>
drh75897232000-05-29 14:26:00 +000025
drh29bc4612005-10-05 10:40:15 +000026
danielk1977a21c6b62005-01-24 10:25:59 +000027#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000028#define MAX_PREPARED_STMTS 100
29
drh75897232000-05-29 14:26:00 +000030/*
drh98808ba2001-10-18 12:34:46 +000031** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
32** have to do a translation when going between the two. Set the
33** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
34** this translation.
35*/
36#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
37# define UTF_TRANSLATION_NEEDED 1
38#endif
39
40/*
drhcabb0812002-09-14 13:47:32 +000041** New SQL functions can be created as TCL scripts. Each such function
42** is described by an instance of the following structure.
43*/
44typedef struct SqlFunc SqlFunc;
45struct SqlFunc {
46 Tcl_Interp *interp; /* The TCL interpret to execute the function */
drhd1e47332005-06-26 17:55:33 +000047 Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */
48 int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */
49 char *zName; /* Name of this function */
drhcabb0812002-09-14 13:47:32 +000050 SqlFunc *pNext; /* Next function on the list of them all */
51};
52
53/*
danielk19770202b292004-06-09 09:55:16 +000054** New collation sequences function can be created as TCL scripts. Each such
55** function is described by an instance of the following structure.
56*/
57typedef struct SqlCollate SqlCollate;
58struct SqlCollate {
59 Tcl_Interp *interp; /* The TCL interpret to execute the function */
60 char *zScript; /* The script to be run */
drhd1e47332005-06-26 17:55:33 +000061 SqlCollate *pNext; /* Next function on the list of them all */
danielk19770202b292004-06-09 09:55:16 +000062};
63
64/*
drhfb7e7652005-01-24 00:28:42 +000065** Prepared statements are cached for faster execution. Each prepared
66** statement is described by an instance of the following structure.
67*/
68typedef struct SqlPreparedStmt SqlPreparedStmt;
69struct SqlPreparedStmt {
70 SqlPreparedStmt *pNext; /* Next in linked list */
71 SqlPreparedStmt *pPrev; /* Previous on the list */
72 sqlite3_stmt *pStmt; /* The prepared statement */
73 int nSql; /* chars in zSql[] */
74 char zSql[1]; /* Text of the SQL statement */
75};
76
77/*
drhbec3f402000-08-04 13:49:02 +000078** There is one instance of this structure for each SQLite database
79** that has been opened by the SQLite TCL interface.
80*/
81typedef struct SqliteDb SqliteDb;
82struct SqliteDb {
drhdddca282006-01-03 00:33:50 +000083 sqlite3 *db; /* The "real" database structure. MUST BE FIRST */
drhd1e47332005-06-26 17:55:33 +000084 Tcl_Interp *interp; /* The interpreter used for this database */
85 char *zBusy; /* The busy callback routine */
86 char *zCommit; /* The commit hook callback routine */
87 char *zTrace; /* The trace callback routine */
drh19e2d372005-08-29 23:00:03 +000088 char *zProfile; /* The profile callback routine */
drhd1e47332005-06-26 17:55:33 +000089 char *zProgress; /* The progress callback routine */
90 char *zAuth; /* The authorization callback routine */
91 char *zNull; /* Text to substitute for an SQL NULL value */
92 SqlFunc *pFunc; /* List of SQL functions */
danielk197794eb6a12005-12-15 15:22:08 +000093 Tcl_Obj *pUpdateHook; /* Update hook script (if any) */
danielk197771fd80b2005-12-16 06:54:01 +000094 Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */
drhd1e47332005-06-26 17:55:33 +000095 SqlCollate *pCollate; /* List of SQL collation functions */
96 int rc; /* Return code of most recent sqlite3_exec() */
97 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +000098 SqlPreparedStmt *stmtList; /* List of prepared statements*/
99 SqlPreparedStmt *stmtLast; /* Last statement in the list */
100 int maxStmt; /* The next maximum number of stmtList */
101 int nStmt; /* Number of statements in stmtList */
drh98808ba2001-10-18 12:34:46 +0000102};
drh297ecf12001-04-05 15:57:13 +0000103
drh6d313162000-09-21 13:01:35 +0000104/*
drhd1e47332005-06-26 17:55:33 +0000105** Look at the script prefix in pCmd. We will be executing this script
106** after first appending one or more arguments. This routine analyzes
107** the script to see if it is safe to use Tcl_EvalObjv() on the script
108** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much
109** faster.
110**
111** Scripts that are safe to use with Tcl_EvalObjv() consists of a
112** command name followed by zero or more arguments with no [...] or $
113** or {...} or ; to be seen anywhere. Most callback scripts consist
114** of just a single procedure name and they meet this requirement.
115*/
116static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
117 /* We could try to do something with Tcl_Parse(). But we will instead
118 ** just do a search for forbidden characters. If any of the forbidden
119 ** characters appear in pCmd, we will report the string as unsafe.
120 */
121 const char *z;
122 int n;
123 z = Tcl_GetStringFromObj(pCmd, &n);
124 while( n-- > 0 ){
125 int c = *(z++);
126 if( c=='$' || c=='[' || c==';' ) return 0;
127 }
128 return 1;
129}
130
131/*
132** Find an SqlFunc structure with the given name. Or create a new
133** one if an existing one cannot be found. Return a pointer to the
134** structure.
135*/
136static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
137 SqlFunc *p, *pNew;
138 int i;
139 pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen(zName) + 1 );
140 pNew->zName = (char*)&pNew[1];
141 for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
142 pNew->zName[i] = 0;
143 for(p=pDb->pFunc; p; p=p->pNext){
144 if( strcmp(p->zName, pNew->zName)==0 ){
145 Tcl_Free((char*)pNew);
146 return p;
147 }
148 }
149 pNew->interp = pDb->interp;
150 pNew->pScript = 0;
151 pNew->pNext = pDb->pFunc;
152 pDb->pFunc = pNew;
153 return pNew;
154}
155
156/*
drhfb7e7652005-01-24 00:28:42 +0000157** Finalize and free a list of prepared statements
158*/
159static void flushStmtCache( SqliteDb *pDb ){
160 SqlPreparedStmt *pPreStmt;
161
162 while( pDb->stmtList ){
163 sqlite3_finalize( pDb->stmtList->pStmt );
164 pPreStmt = pDb->stmtList;
165 pDb->stmtList = pDb->stmtList->pNext;
166 Tcl_Free( (char*)pPreStmt );
167 }
168 pDb->nStmt = 0;
169 pDb->stmtLast = 0;
170}
171
172/*
drh895d7472004-08-20 16:02:39 +0000173** TCL calls this procedure when an sqlite3 database command is
174** deleted.
drh75897232000-05-29 14:26:00 +0000175*/
176static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000177 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000178 flushStmtCache(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000179 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000180 while( pDb->pFunc ){
181 SqlFunc *pFunc = pDb->pFunc;
182 pDb->pFunc = pFunc->pNext;
drhd1e47332005-06-26 17:55:33 +0000183 Tcl_DecrRefCount(pFunc->pScript);
drhcabb0812002-09-14 13:47:32 +0000184 Tcl_Free((char*)pFunc);
185 }
danielk19770202b292004-06-09 09:55:16 +0000186 while( pDb->pCollate ){
187 SqlCollate *pCollate = pDb->pCollate;
188 pDb->pCollate = pCollate->pNext;
189 Tcl_Free((char*)pCollate);
190 }
drhbec3f402000-08-04 13:49:02 +0000191 if( pDb->zBusy ){
192 Tcl_Free(pDb->zBusy);
193 }
drhb5a20d32003-04-23 12:25:23 +0000194 if( pDb->zTrace ){
195 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000196 }
drh19e2d372005-08-29 23:00:03 +0000197 if( pDb->zProfile ){
198 Tcl_Free(pDb->zProfile);
199 }
drhe22a3342003-04-22 20:30:37 +0000200 if( pDb->zAuth ){
201 Tcl_Free(pDb->zAuth);
202 }
danielk197755c45f22005-04-03 23:54:43 +0000203 if( pDb->zNull ){
204 Tcl_Free(pDb->zNull);
205 }
danielk197794eb6a12005-12-15 15:22:08 +0000206 if( pDb->pUpdateHook ){
207 Tcl_DecrRefCount(pDb->pUpdateHook);
208 }
danielk197771fd80b2005-12-16 06:54:01 +0000209 if( pDb->pRollbackHook ){
210 Tcl_DecrRefCount(pDb->pRollbackHook);
211 }
danielk197794eb6a12005-12-15 15:22:08 +0000212 if( pDb->pCollateNeeded ){
213 Tcl_DecrRefCount(pDb->pCollateNeeded);
214 }
drhbec3f402000-08-04 13:49:02 +0000215 Tcl_Free((char*)pDb);
216}
217
218/*
219** This routine is called when a database file is locked while trying
220** to execute SQL.
221*/
danielk19772a764eb2004-06-12 01:43:26 +0000222static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000223 SqliteDb *pDb = (SqliteDb*)cd;
224 int rc;
225 char zVal[30];
drhbec3f402000-08-04 13:49:02 +0000226
danielk19772a764eb2004-06-12 01:43:26 +0000227 sprintf(zVal, "%d", nTries);
drhd1e47332005-06-26 17:55:33 +0000228 rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
drhbec3f402000-08-04 13:49:02 +0000229 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
230 return 0;
231 }
232 return 1;
drh75897232000-05-29 14:26:00 +0000233}
234
235/*
danielk1977348bb5d2003-10-18 09:37:26 +0000236** This routine is invoked as the 'progress callback' for the database.
237*/
238static int DbProgressHandler(void *cd){
239 SqliteDb *pDb = (SqliteDb*)cd;
240 int rc;
241
242 assert( pDb->zProgress );
243 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
244 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
245 return 1;
246 }
247 return 0;
248}
249
drhd1167392006-01-23 13:00:35 +0000250#ifndef SQLITE_OMIT_TRACE
danielk1977348bb5d2003-10-18 09:37:26 +0000251/*
drhb5a20d32003-04-23 12:25:23 +0000252** This routine is called by the SQLite trace handler whenever a new
253** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000254*/
drhb5a20d32003-04-23 12:25:23 +0000255static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000256 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000257 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000258
drhb5a20d32003-04-23 12:25:23 +0000259 Tcl_DStringInit(&str);
260 Tcl_DStringAppend(&str, pDb->zTrace, -1);
261 Tcl_DStringAppendElement(&str, zSql);
262 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
263 Tcl_DStringFree(&str);
264 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000265}
drhd1167392006-01-23 13:00:35 +0000266#endif
drh0d1a6432003-04-03 15:46:04 +0000267
drhd1167392006-01-23 13:00:35 +0000268#ifndef SQLITE_OMIT_TRACE
drh0d1a6432003-04-03 15:46:04 +0000269/*
drh19e2d372005-08-29 23:00:03 +0000270** This routine is called by the SQLite profile handler after a statement
271** SQL has executed. The TCL script in pDb->zProfile is evaluated.
272*/
273static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
274 SqliteDb *pDb = (SqliteDb*)cd;
275 Tcl_DString str;
276 char zTm[100];
277
278 sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
279 Tcl_DStringInit(&str);
280 Tcl_DStringAppend(&str, pDb->zProfile, -1);
281 Tcl_DStringAppendElement(&str, zSql);
282 Tcl_DStringAppendElement(&str, zTm);
283 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
284 Tcl_DStringFree(&str);
285 Tcl_ResetResult(pDb->interp);
286}
drhd1167392006-01-23 13:00:35 +0000287#endif
drh19e2d372005-08-29 23:00:03 +0000288
289/*
drhaa940ea2004-01-15 02:44:03 +0000290** This routine is called when a transaction is committed. The
291** TCL script in pDb->zCommit is executed. If it returns non-zero or
292** if it throws an exception, the transaction is rolled back instead
293** of being committed.
294*/
295static int DbCommitHandler(void *cd){
296 SqliteDb *pDb = (SqliteDb*)cd;
297 int rc;
298
299 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
300 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
301 return 1;
302 }
303 return 0;
304}
305
danielk197771fd80b2005-12-16 06:54:01 +0000306static void DbRollbackHandler(void *clientData){
307 SqliteDb *pDb = (SqliteDb*)clientData;
308 assert(pDb->pRollbackHook);
309 if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
310 Tcl_BackgroundError(pDb->interp);
311 }
312}
313
danielk197794eb6a12005-12-15 15:22:08 +0000314static void DbUpdateHandler(
315 void *p,
316 int op,
317 const char *zDb,
318 const char *zTbl,
319 sqlite_int64 rowid
320){
321 SqliteDb *pDb = (SqliteDb *)p;
322 Tcl_Obj *pCmd;
323
324 assert( pDb->pUpdateHook );
325 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
326
327 pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
328 Tcl_IncrRefCount(pCmd);
329 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
330 ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
331 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
332 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
333 Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
334 Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
335}
336
danielk19777cedc8d2004-06-10 10:50:08 +0000337static void tclCollateNeeded(
338 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000339 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000340 int enc,
341 const char *zName
342){
343 SqliteDb *pDb = (SqliteDb *)pCtx;
344 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
345 Tcl_IncrRefCount(pScript);
346 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
347 Tcl_EvalObjEx(pDb->interp, pScript, 0);
348 Tcl_DecrRefCount(pScript);
349}
350
drhaa940ea2004-01-15 02:44:03 +0000351/*
danielk19770202b292004-06-09 09:55:16 +0000352** This routine is called to evaluate an SQL collation function implemented
353** using TCL script.
354*/
355static int tclSqlCollate(
356 void *pCtx,
357 int nA,
358 const void *zA,
359 int nB,
360 const void *zB
361){
362 SqlCollate *p = (SqlCollate *)pCtx;
363 Tcl_Obj *pCmd;
364
365 pCmd = Tcl_NewStringObj(p->zScript, -1);
366 Tcl_IncrRefCount(pCmd);
367 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
368 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
drhd1e47332005-06-26 17:55:33 +0000369 Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
danielk19770202b292004-06-09 09:55:16 +0000370 Tcl_DecrRefCount(pCmd);
371 return (atoi(Tcl_GetStringResult(p->interp)));
372}
373
374/*
drhcabb0812002-09-14 13:47:32 +0000375** This routine is called to evaluate an SQL function implemented
376** using TCL script.
377*/
drhfb7e7652005-01-24 00:28:42 +0000378static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000379 SqlFunc *p = sqlite3_user_data(context);
drhd1e47332005-06-26 17:55:33 +0000380 Tcl_Obj *pCmd;
drhcabb0812002-09-14 13:47:32 +0000381 int i;
382 int rc;
383
drhd1e47332005-06-26 17:55:33 +0000384 if( argc==0 ){
385 /* If there are no arguments to the function, call Tcl_EvalObjEx on the
386 ** script object directly. This allows the TCL compiler to generate
387 ** bytecode for the command on the first invocation and thus make
388 ** subsequent invocations much faster. */
389 pCmd = p->pScript;
390 Tcl_IncrRefCount(pCmd);
391 rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
392 Tcl_DecrRefCount(pCmd);
393 }else{
394 /* If there are arguments to the function, make a shallow copy of the
395 ** script object, lappend the arguments, then evaluate the copy.
396 **
397 ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
398 ** The new Tcl_Obj contains pointers to the original list elements.
399 ** That way, when Tcl_EvalObjv() is run and shimmers the first element
400 ** of the list to tclCmdNameType, that alternate representation will
401 ** be preserved and reused on the next invocation.
402 */
403 Tcl_Obj **aArg;
404 int nArg;
405 if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
406 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
407 return;
408 }
409 pCmd = Tcl_NewListObj(nArg, aArg);
410 Tcl_IncrRefCount(pCmd);
411 for(i=0; i<argc; i++){
412 sqlite3_value *pIn = argv[i];
413 Tcl_Obj *pVal;
414
415 /* Set pVal to contain the i'th column of this row. */
416 switch( sqlite3_value_type(pIn) ){
417 case SQLITE_BLOB: {
418 int bytes = sqlite3_value_bytes(pIn);
419 pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
420 break;
421 }
422 case SQLITE_INTEGER: {
423 sqlite_int64 v = sqlite3_value_int64(pIn);
424 if( v>=-2147483647 && v<=2147483647 ){
425 pVal = Tcl_NewIntObj(v);
426 }else{
427 pVal = Tcl_NewWideIntObj(v);
428 }
429 break;
430 }
431 case SQLITE_FLOAT: {
432 double r = sqlite3_value_double(pIn);
433 pVal = Tcl_NewDoubleObj(r);
434 break;
435 }
436 case SQLITE_NULL: {
437 pVal = Tcl_NewStringObj("", 0);
438 break;
439 }
440 default: {
441 int bytes = sqlite3_value_bytes(pIn);
danielk197700fd9572005-12-07 06:27:43 +0000442 pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
drhd1e47332005-06-26 17:55:33 +0000443 break;
444 }
445 }
446 rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
447 if( rc ){
448 Tcl_DecrRefCount(pCmd);
449 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
450 return;
451 }
danielk197751ad0ec2004-05-24 12:39:02 +0000452 }
drhd1e47332005-06-26 17:55:33 +0000453 if( !p->useEvalObjv ){
454 /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
455 ** is a list without a string representation. To prevent this from
456 ** happening, make sure pCmd has a valid string representation */
457 Tcl_GetString(pCmd);
458 }
459 rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
460 Tcl_DecrRefCount(pCmd);
drhcabb0812002-09-14 13:47:32 +0000461 }
danielk1977562e8d32005-05-20 09:40:55 +0000462
drhc7f269d2005-05-05 10:30:29 +0000463 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000464 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000465 }else{
drhc7f269d2005-05-05 10:30:29 +0000466 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
467 int n;
468 u8 *data;
469 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
470 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000471 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
drhd1e47332005-06-26 17:55:33 +0000472 /* Only return a BLOB type if the Tcl variable is a bytearray and
drhdf0bdda2005-06-25 19:31:48 +0000473 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000474 data = Tcl_GetByteArrayFromObj(pVar, &n);
475 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000476 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
477 (c=='i' && strcmp(zType,"int")==0) ){
478 Tcl_GetIntFromObj(0, pVar, &n);
479 sqlite3_result_int(context, n);
480 }else if( c=='d' && strcmp(zType,"double")==0 ){
481 double r;
482 Tcl_GetDoubleFromObj(0, pVar, &r);
483 sqlite3_result_double(context, r);
drhdf0bdda2005-06-25 19:31:48 +0000484 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
485 Tcl_WideInt v;
486 Tcl_GetWideIntFromObj(0, pVar, &v);
487 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000488 }else{
danielk197700fd9572005-12-07 06:27:43 +0000489 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
490 sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000491 }
drhcabb0812002-09-14 13:47:32 +0000492 }
493}
drh895d7472004-08-20 16:02:39 +0000494
drhe22a3342003-04-22 20:30:37 +0000495#ifndef SQLITE_OMIT_AUTHORIZATION
496/*
497** This is the authentication function. It appends the authentication
498** type code and the two arguments to zCmd[] then invokes the result
499** on the interpreter. The reply is examined to determine if the
500** authentication fails or succeeds.
501*/
502static int auth_callback(
503 void *pArg,
504 int code,
505 const char *zArg1,
506 const char *zArg2,
507 const char *zArg3,
508 const char *zArg4
509){
510 char *zCode;
511 Tcl_DString str;
512 int rc;
513 const char *zReply;
514 SqliteDb *pDb = (SqliteDb*)pArg;
515
516 switch( code ){
517 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
518 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
519 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
520 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
521 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
522 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
523 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
524 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
525 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
526 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
527 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
528 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
529 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
530 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
531 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
532 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
533 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
534 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
535 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
536 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
537 case SQLITE_READ : zCode="SQLITE_READ"; break;
538 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
539 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
540 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000541 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
542 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000543 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000544 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe6e04962005-07-23 02:17:03 +0000545 case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break;
danielk1977f1a381e2006-06-16 08:01:02 +0000546 case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break;
547 case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break;
drhe22a3342003-04-22 20:30:37 +0000548 default : zCode="????"; break;
549 }
550 Tcl_DStringInit(&str);
551 Tcl_DStringAppend(&str, pDb->zAuth, -1);
552 Tcl_DStringAppendElement(&str, zCode);
553 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
554 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
555 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
556 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
557 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
558 Tcl_DStringFree(&str);
559 zReply = Tcl_GetStringResult(pDb->interp);
560 if( strcmp(zReply,"SQLITE_OK")==0 ){
561 rc = SQLITE_OK;
562 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
563 rc = SQLITE_DENY;
564 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
565 rc = SQLITE_IGNORE;
566 }else{
567 rc = 999;
568 }
569 return rc;
570}
571#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000572
573/*
danielk1977ef2cb632004-05-29 02:37:19 +0000574** zText is a pointer to text obtained via an sqlite3_result_text()
575** or similar interface. This routine returns a Tcl string object,
576** reference count set to 0, containing the text. If a translation
577** between iso8859 and UTF-8 is required, it is preformed.
578*/
579static Tcl_Obj *dbTextToObj(char const *zText){
580 Tcl_Obj *pVal;
581#ifdef UTF_TRANSLATION_NEEDED
582 Tcl_DString dCol;
583 Tcl_DStringInit(&dCol);
584 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
585 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
586 Tcl_DStringFree(&dCol);
587#else
588 pVal = Tcl_NewStringObj(zText, -1);
589#endif
590 return pVal;
591}
592
593/*
tpoindex1067fe12004-12-17 15:41:11 +0000594** This routine reads a line of text from FILE in, stores
595** the text in memory obtained from malloc() and returns a pointer
596** to the text. NULL is returned at end of file, or if malloc()
597** fails.
598**
599** The interface is like "readline" but no command-line editing
600** is done.
601**
602** copied from shell.c from '.import' command
603*/
604static char *local_getline(char *zPrompt, FILE *in){
605 char *zLine;
606 int nLine;
607 int n;
608 int eol;
609
610 nLine = 100;
611 zLine = malloc( nLine );
612 if( zLine==0 ) return 0;
613 n = 0;
614 eol = 0;
615 while( !eol ){
616 if( n+100>nLine ){
617 nLine = nLine*2 + 100;
618 zLine = realloc(zLine, nLine);
619 if( zLine==0 ) return 0;
620 }
621 if( fgets(&zLine[n], nLine - n, in)==0 ){
622 if( n==0 ){
623 free(zLine);
624 return 0;
625 }
626 zLine[n] = 0;
627 eol = 1;
628 break;
629 }
630 while( zLine[n] ){ n++; }
631 if( n>0 && zLine[n-1]=='\n' ){
632 n--;
633 zLine[n] = 0;
634 eol = 1;
635 }
636 }
637 zLine = realloc( zLine, n+1 );
638 return zLine;
639}
640
641/*
drh75897232000-05-29 14:26:00 +0000642** The "sqlite" command below creates a new Tcl command for each
643** connection it opens to an SQLite database. This routine is invoked
644** whenever one of those connection-specific commands is executed
645** in Tcl. For example, if you run Tcl code like this:
646**
drh9bb575f2004-09-06 17:24:11 +0000647** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +0000648** db1 close
649**
650** The first command opens a connection to the "my_database" database
651** and calls that connection "db1". The second command causes this
652** subroutine to be invoked.
653*/
drh6d313162000-09-21 13:01:35 +0000654static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +0000655 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +0000656 int choice;
drh22fbcb82004-02-01 01:22:50 +0000657 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +0000658 static const char *DB_strs[] = {
drhfb7e7652005-01-24 00:28:42 +0000659 "authorizer", "busy", "cache",
660 "changes", "close", "collate",
661 "collation_needed", "commit_hook", "complete",
drh41449052006-07-06 17:08:48 +0000662 "copy", "enable_load_extension","errorcode",
663 "eval", "exists", "function",
664 "last_insert_rowid", "nullvalue", "onecolumn",
665 "profile", "progress", "rekey",
666 "rollback_hook", "timeout", "total_changes",
667 "trace", "transaction", "update_hook",
668 "version", 0
drh6d313162000-09-21 13:01:35 +0000669 };
drh411995d2002-06-25 19:31:18 +0000670 enum DB_enum {
drhfb7e7652005-01-24 00:28:42 +0000671 DB_AUTHORIZER, DB_BUSY, DB_CACHE,
672 DB_CHANGES, DB_CLOSE, DB_COLLATE,
673 DB_COLLATION_NEEDED, DB_COMMIT_HOOK, DB_COMPLETE,
drh41449052006-07-06 17:08:48 +0000674 DB_COPY, DB_ENABLE_LOAD_EXTENSION,DB_ERRORCODE,
675 DB_EVAL, DB_EXISTS, DB_FUNCTION,
676 DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN,
677 DB_PROFILE, DB_PROGRESS, DB_REKEY,
678 DB_ROLLBACK_HOOK, DB_TIMEOUT, DB_TOTAL_CHANGES,
679 DB_TRACE, DB_TRANSACTION, DB_UPDATE_HOOK,
680 DB_VERSION,
drh6d313162000-09-21 13:01:35 +0000681 };
tpoindex1067fe12004-12-17 15:41:11 +0000682 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +0000683
684 if( objc<2 ){
685 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +0000686 return TCL_ERROR;
687 }
drh411995d2002-06-25 19:31:18 +0000688 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +0000689 return TCL_ERROR;
690 }
691
drh411995d2002-06-25 19:31:18 +0000692 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +0000693
drhe22a3342003-04-22 20:30:37 +0000694 /* $db authorizer ?CALLBACK?
695 **
696 ** Invoke the given callback to authorize each SQL operation as it is
697 ** compiled. 5 arguments are appended to the callback before it is
698 ** invoked:
699 **
700 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
701 ** (2) First descriptive name (depends on authorization type)
702 ** (3) Second descriptive name
703 ** (4) Name of the database (ex: "main", "temp")
704 ** (5) Name of trigger that is doing the access
705 **
706 ** The callback should return on of the following strings: SQLITE_OK,
707 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
708 **
709 ** If this method is invoked with no arguments, the current authorization
710 ** callback string is returned.
711 */
712 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +0000713#ifdef SQLITE_OMIT_AUTHORIZATION
714 Tcl_AppendResult(interp, "authorization not available in this build", 0);
715 return TCL_ERROR;
716#else
drhe22a3342003-04-22 20:30:37 +0000717 if( objc>3 ){
718 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +0000719 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +0000720 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +0000721 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +0000722 Tcl_AppendResult(interp, pDb->zAuth, 0);
723 }
724 }else{
725 char *zAuth;
726 int len;
727 if( pDb->zAuth ){
728 Tcl_Free(pDb->zAuth);
729 }
730 zAuth = Tcl_GetStringFromObj(objv[2], &len);
731 if( zAuth && len>0 ){
732 pDb->zAuth = Tcl_Alloc( len + 1 );
733 strcpy(pDb->zAuth, zAuth);
734 }else{
735 pDb->zAuth = 0;
736 }
drhe22a3342003-04-22 20:30:37 +0000737 if( pDb->zAuth ){
738 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000739 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +0000740 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000741 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +0000742 }
drhe22a3342003-04-22 20:30:37 +0000743 }
drh1211de32004-07-26 12:24:22 +0000744#endif
drhe22a3342003-04-22 20:30:37 +0000745 break;
746 }
747
drhbec3f402000-08-04 13:49:02 +0000748 /* $db busy ?CALLBACK?
749 **
750 ** Invoke the given callback if an SQL statement attempts to open
751 ** a locked database file.
752 */
drh6d313162000-09-21 13:01:35 +0000753 case DB_BUSY: {
754 if( objc>3 ){
755 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +0000756 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +0000757 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +0000758 if( pDb->zBusy ){
759 Tcl_AppendResult(interp, pDb->zBusy, 0);
760 }
761 }else{
drh6d313162000-09-21 13:01:35 +0000762 char *zBusy;
763 int len;
drhbec3f402000-08-04 13:49:02 +0000764 if( pDb->zBusy ){
765 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +0000766 }
drh6d313162000-09-21 13:01:35 +0000767 zBusy = Tcl_GetStringFromObj(objv[2], &len);
768 if( zBusy && len>0 ){
769 pDb->zBusy = Tcl_Alloc( len + 1 );
770 strcpy(pDb->zBusy, zBusy);
771 }else{
772 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +0000773 }
774 if( pDb->zBusy ){
775 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000776 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +0000777 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000778 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +0000779 }
780 }
drh6d313162000-09-21 13:01:35 +0000781 break;
782 }
drhbec3f402000-08-04 13:49:02 +0000783
drhfb7e7652005-01-24 00:28:42 +0000784 /* $db cache flush
785 ** $db cache size n
786 **
787 ** Flush the prepared statement cache, or set the maximum number of
788 ** cached statements.
789 */
790 case DB_CACHE: {
791 char *subCmd;
792 int n;
793
794 if( objc<=2 ){
795 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
796 return TCL_ERROR;
797 }
798 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
799 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
800 if( objc!=3 ){
801 Tcl_WrongNumArgs(interp, 2, objv, "flush");
802 return TCL_ERROR;
803 }else{
804 flushStmtCache( pDb );
805 }
806 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
807 if( objc!=4 ){
808 Tcl_WrongNumArgs(interp, 2, objv, "size n");
809 return TCL_ERROR;
810 }else{
811 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
812 Tcl_AppendResult( interp, "cannot convert \"",
813 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
814 return TCL_ERROR;
815 }else{
816 if( n<0 ){
817 flushStmtCache( pDb );
818 n = 0;
819 }else if( n>MAX_PREPARED_STMTS ){
820 n = MAX_PREPARED_STMTS;
821 }
822 pDb->maxStmt = n;
823 }
824 }
825 }else{
826 Tcl_AppendResult( interp, "bad option \"",
827 Tcl_GetStringFromObj(objv[0],0), "\": must be flush or size", 0);
828 return TCL_ERROR;
829 }
830 break;
831 }
832
danielk1977b28af712004-06-21 06:50:26 +0000833 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +0000834 **
835 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +0000836 ** the most recent INSERT, UPDATE or DELETE statement, not including
837 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +0000838 */
839 case DB_CHANGES: {
840 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +0000841 if( objc!=2 ){
842 Tcl_WrongNumArgs(interp, 2, objv, "");
843 return TCL_ERROR;
844 }
drhc8d30ac2002-04-12 10:08:59 +0000845 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +0000846 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +0000847 break;
848 }
849
drh75897232000-05-29 14:26:00 +0000850 /* $db close
851 **
852 ** Shutdown the database
853 */
drh6d313162000-09-21 13:01:35 +0000854 case DB_CLOSE: {
855 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
856 break;
857 }
drh75897232000-05-29 14:26:00 +0000858
drh0f14e2e2004-06-29 12:39:08 +0000859 /*
860 ** $db collate NAME SCRIPT
861 **
862 ** Create a new SQL collation function called NAME. Whenever
863 ** that function is called, invoke SCRIPT to evaluate the function.
864 */
865 case DB_COLLATE: {
866 SqlCollate *pCollate;
867 char *zName;
868 char *zScript;
869 int nScript;
870 if( objc!=4 ){
871 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
872 return TCL_ERROR;
873 }
874 zName = Tcl_GetStringFromObj(objv[2], 0);
875 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
876 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
877 if( pCollate==0 ) return TCL_ERROR;
878 pCollate->interp = interp;
879 pCollate->pNext = pDb->pCollate;
880 pCollate->zScript = (char*)&pCollate[1];
881 pDb->pCollate = pCollate;
882 strcpy(pCollate->zScript, zScript);
883 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
884 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +0000885 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +0000886 return TCL_ERROR;
887 }
888 break;
889 }
890
891 /*
892 ** $db collation_needed SCRIPT
893 **
894 ** Create a new SQL collation function called NAME. Whenever
895 ** that function is called, invoke SCRIPT to evaluate the function.
896 */
897 case DB_COLLATION_NEEDED: {
898 if( objc!=3 ){
899 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
900 return TCL_ERROR;
901 }
902 if( pDb->pCollateNeeded ){
903 Tcl_DecrRefCount(pDb->pCollateNeeded);
904 }
905 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
906 Tcl_IncrRefCount(pDb->pCollateNeeded);
907 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
908 break;
909 }
910
drh19e2d372005-08-29 23:00:03 +0000911 /* $db commit_hook ?CALLBACK?
912 **
913 ** Invoke the given callback just before committing every SQL transaction.
914 ** If the callback throws an exception or returns non-zero, then the
915 ** transaction is aborted. If CALLBACK is an empty string, the callback
916 ** is disabled.
917 */
918 case DB_COMMIT_HOOK: {
919 if( objc>3 ){
920 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
921 return TCL_ERROR;
922 }else if( objc==2 ){
923 if( pDb->zCommit ){
924 Tcl_AppendResult(interp, pDb->zCommit, 0);
925 }
926 }else{
927 char *zCommit;
928 int len;
929 if( pDb->zCommit ){
930 Tcl_Free(pDb->zCommit);
931 }
932 zCommit = Tcl_GetStringFromObj(objv[2], &len);
933 if( zCommit && len>0 ){
934 pDb->zCommit = Tcl_Alloc( len + 1 );
935 strcpy(pDb->zCommit, zCommit);
936 }else{
937 pDb->zCommit = 0;
938 }
939 if( pDb->zCommit ){
940 pDb->interp = interp;
941 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
942 }else{
943 sqlite3_commit_hook(pDb->db, 0, 0);
944 }
945 }
946 break;
947 }
948
drh75897232000-05-29 14:26:00 +0000949 /* $db complete SQL
950 **
951 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
952 ** additional lines of input are needed. This is similar to the
953 ** built-in "info complete" command of Tcl.
954 */
drh6d313162000-09-21 13:01:35 +0000955 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +0000956#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +0000957 Tcl_Obj *pResult;
958 int isComplete;
959 if( objc!=3 ){
960 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +0000961 return TCL_ERROR;
962 }
danielk19776f8a5032004-05-10 10:34:51 +0000963 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +0000964 pResult = Tcl_GetObjResult(interp);
965 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +0000966#endif
drh6d313162000-09-21 13:01:35 +0000967 break;
968 }
drhdcd997e2003-01-31 17:21:49 +0000969
drh19e2d372005-08-29 23:00:03 +0000970 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
971 **
972 ** Copy data into table from filename, optionally using SEPARATOR
973 ** as column separators. If a column contains a null string, or the
974 ** value of NULLINDICATOR, a NULL is inserted for the column.
975 ** conflict-algorithm is one of the sqlite conflict algorithms:
976 ** rollback, abort, fail, ignore, replace
977 ** On success, return the number of lines processed, not necessarily same
978 ** as 'db changes' due to conflict-algorithm selected.
979 **
980 ** This code is basically an implementation/enhancement of
981 ** the sqlite3 shell.c ".import" command.
982 **
983 ** This command usage is equivalent to the sqlite2.x COPY statement,
984 ** which imports file data into a table using the PostgreSQL COPY file format:
985 ** $db copy $conflit_algo $table_name $filename \t \\N
986 */
987 case DB_COPY: {
988 char *zTable; /* Insert data into this table */
989 char *zFile; /* The file from which to extract data */
990 char *zConflict; /* The conflict algorithm to use */
991 sqlite3_stmt *pStmt; /* A statement */
992 int rc; /* Result code */
993 int nCol; /* Number of columns in the table */
994 int nByte; /* Number of bytes in an SQL string */
995 int i, j; /* Loop counters */
996 int nSep; /* Number of bytes in zSep[] */
997 int nNull; /* Number of bytes in zNull[] */
998 char *zSql; /* An SQL statement */
999 char *zLine; /* A single line of input from the file */
1000 char **azCol; /* zLine[] broken up into columns */
1001 char *zCommit; /* How to commit changes */
1002 FILE *in; /* The input file */
1003 int lineno = 0; /* Line number of input file */
1004 char zLineNum[80]; /* Line number print buffer */
1005 Tcl_Obj *pResult; /* interp result */
1006
1007 char *zSep;
1008 char *zNull;
1009 if( objc<5 || objc>7 ){
1010 Tcl_WrongNumArgs(interp, 2, objv,
1011 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1012 return TCL_ERROR;
1013 }
1014 if( objc>=6 ){
1015 zSep = Tcl_GetStringFromObj(objv[5], 0);
1016 }else{
1017 zSep = "\t";
1018 }
1019 if( objc>=7 ){
1020 zNull = Tcl_GetStringFromObj(objv[6], 0);
1021 }else{
1022 zNull = "";
1023 }
1024 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1025 zTable = Tcl_GetStringFromObj(objv[3], 0);
1026 zFile = Tcl_GetStringFromObj(objv[4], 0);
1027 nSep = strlen(zSep);
1028 nNull = strlen(zNull);
1029 if( nSep==0 ){
1030 Tcl_AppendResult(interp, "Error: non-null separator required for copy", 0);
1031 return TCL_ERROR;
1032 }
1033 if(sqlite3StrICmp(zConflict, "rollback") != 0 &&
1034 sqlite3StrICmp(zConflict, "abort" ) != 0 &&
1035 sqlite3StrICmp(zConflict, "fail" ) != 0 &&
1036 sqlite3StrICmp(zConflict, "ignore" ) != 0 &&
1037 sqlite3StrICmp(zConflict, "replace" ) != 0 ) {
1038 Tcl_AppendResult(interp, "Error: \"", zConflict,
1039 "\", conflict-algorithm must be one of: rollback, "
1040 "abort, fail, ignore, or replace", 0);
1041 return TCL_ERROR;
1042 }
1043 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1044 if( zSql==0 ){
1045 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1046 return TCL_ERROR;
1047 }
1048 nByte = strlen(zSql);
1049 rc = sqlite3_prepare(pDb->db, zSql, 0, &pStmt, 0);
1050 sqlite3_free(zSql);
1051 if( rc ){
1052 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1053 nCol = 0;
1054 }else{
1055 nCol = sqlite3_column_count(pStmt);
1056 }
1057 sqlite3_finalize(pStmt);
1058 if( nCol==0 ) {
1059 return TCL_ERROR;
1060 }
1061 zSql = malloc( nByte + 50 + nCol*2 );
1062 if( zSql==0 ) {
1063 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1064 return TCL_ERROR;
1065 }
1066 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1067 zConflict, zTable);
1068 j = strlen(zSql);
1069 for(i=1; i<nCol; i++){
1070 zSql[j++] = ',';
1071 zSql[j++] = '?';
1072 }
1073 zSql[j++] = ')';
1074 zSql[j] = 0;
1075 rc = sqlite3_prepare(pDb->db, zSql, 0, &pStmt, 0);
1076 free(zSql);
1077 if( rc ){
1078 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1079 sqlite3_finalize(pStmt);
1080 return TCL_ERROR;
1081 }
1082 in = fopen(zFile, "rb");
1083 if( in==0 ){
1084 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
1085 sqlite3_finalize(pStmt);
1086 return TCL_ERROR;
1087 }
1088 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1089 if( azCol==0 ) {
1090 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
drh43617e92006-03-06 20:55:46 +00001091 fclose(in);
drh19e2d372005-08-29 23:00:03 +00001092 return TCL_ERROR;
1093 }
drh37527852006-03-16 16:19:56 +00001094 (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001095 zCommit = "COMMIT";
1096 while( (zLine = local_getline(0, in))!=0 ){
1097 char *z;
1098 i = 0;
1099 lineno++;
1100 azCol[0] = zLine;
1101 for(i=0, z=zLine; *z; z++){
1102 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
1103 *z = 0;
1104 i++;
1105 if( i<nCol ){
1106 azCol[i] = &z[nSep];
1107 z += nSep-1;
1108 }
1109 }
1110 }
1111 if( i+1!=nCol ){
1112 char *zErr;
1113 zErr = malloc(200 + strlen(zFile));
drhc1f44942006-05-10 14:39:13 +00001114 if( zErr ){
1115 sprintf(zErr,
1116 "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 }
drh19e2d372005-08-29 23:00:03 +00001121 zCommit = "ROLLBACK";
1122 break;
1123 }
1124 for(i=0; i<nCol; i++){
1125 /* check for null data, if so, bind as null */
1126 if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
1127 sqlite3_bind_null(pStmt, i+1);
1128 }else{
1129 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1130 }
1131 }
1132 sqlite3_step(pStmt);
1133 rc = sqlite3_reset(pStmt);
1134 free(zLine);
1135 if( rc!=SQLITE_OK ){
1136 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
1137 zCommit = "ROLLBACK";
1138 break;
1139 }
1140 }
1141 free(azCol);
1142 fclose(in);
1143 sqlite3_finalize(pStmt);
drh37527852006-03-16 16:19:56 +00001144 (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
drh19e2d372005-08-29 23:00:03 +00001145
1146 if( zCommit[0] == 'C' ){
1147 /* success, set result as number of lines processed */
1148 pResult = Tcl_GetObjResult(interp);
1149 Tcl_SetIntObj(pResult, lineno);
1150 rc = TCL_OK;
1151 }else{
1152 /* failure, append lineno where failed */
1153 sprintf(zLineNum,"%d",lineno);
1154 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
1155 rc = TCL_ERROR;
1156 }
1157 break;
1158 }
1159
drhdcd997e2003-01-31 17:21:49 +00001160 /*
drh41449052006-07-06 17:08:48 +00001161 ** $db enable_load_extension BOOLEAN
1162 **
1163 ** Turn the extension loading feature on or off. It if off by
1164 ** default.
1165 */
1166 case DB_ENABLE_LOAD_EXTENSION: {
1167 int onoff;
1168 if( objc!=3 ){
1169 Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
1170 return TCL_ERROR;
1171 }
1172 if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
1173 return TCL_ERROR;
1174 }
1175 sqlite3_enable_load_extension(pDb->db, onoff);
1176 break;
1177 }
1178
1179 /*
drhdcd997e2003-01-31 17:21:49 +00001180 ** $db errorcode
1181 **
1182 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +00001183 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +00001184 */
1185 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +00001186 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +00001187 break;
1188 }
drh75897232000-05-29 14:26:00 +00001189
1190 /*
drh895d7472004-08-20 16:02:39 +00001191 ** $db eval $sql ?array? ?{ ...code... }?
drh1807ce32004-09-07 13:20:35 +00001192 ** $db onecolumn $sql
drh75897232000-05-29 14:26:00 +00001193 **
1194 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +00001195 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +00001196 ** If "array" and "code" are omitted, then no callback is every invoked.
1197 ** If "array" is an empty string, then the values are placed in variables
1198 ** that have the same name as the fields extracted by the query.
drh1807ce32004-09-07 13:20:35 +00001199 **
1200 ** The onecolumn method is the equivalent of:
1201 ** lindex [$db eval $sql] 0
drh75897232000-05-29 14:26:00 +00001202 */
drh1807ce32004-09-07 13:20:35 +00001203 case DB_ONECOLUMN:
drh97f2ebc2005-12-10 21:19:04 +00001204 case DB_EVAL:
1205 case DB_EXISTS: {
drh9d74b4c2004-08-24 15:23:34 +00001206 char const *zSql; /* Next SQL statement to execute */
1207 char const *zLeft; /* What is left after first stmt in zSql */
1208 sqlite3_stmt *pStmt; /* Compiled SQL statment */
drh92febd92004-08-20 18:34:20 +00001209 Tcl_Obj *pArray; /* Name of array into which results are written */
1210 Tcl_Obj *pScript; /* Script to run for each result set */
drh1d895032004-08-26 00:56:05 +00001211 Tcl_Obj **apParm; /* Parameters that need a Tcl_DecrRefCount() */
1212 int nParm; /* Number of entries used in apParm[] */
1213 Tcl_Obj *aParm[10]; /* Static space for apParm[] in the common case */
drh1807ce32004-09-07 13:20:35 +00001214 Tcl_Obj *pRet; /* Value to be returned */
drhfb7e7652005-01-24 00:28:42 +00001215 SqlPreparedStmt *pPreStmt; /* Pointer to a prepared statement */
1216 int rc2;
danielk1977ef2cb632004-05-29 02:37:19 +00001217
drh97f2ebc2005-12-10 21:19:04 +00001218 if( choice==DB_EVAL ){
drh1807ce32004-09-07 13:20:35 +00001219 if( objc<3 || objc>5 ){
1220 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
1221 return TCL_ERROR;
1222 }
1223 pRet = Tcl_NewObj();
1224 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001225 }else{
1226 if( objc!=3 ){
1227 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
1228 return TCL_ERROR;
1229 }
drh97f2ebc2005-12-10 21:19:04 +00001230 if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001231 pRet = Tcl_NewBooleanObj(0);
1232 Tcl_IncrRefCount(pRet);
1233 }else{
1234 pRet = 0;
drh97f2ebc2005-12-10 21:19:04 +00001235 }
danielk197730ccda12004-05-27 12:11:31 +00001236 }
drh92febd92004-08-20 18:34:20 +00001237 if( objc==3 ){
1238 pArray = pScript = 0;
1239 }else if( objc==4 ){
1240 pArray = 0;
1241 pScript = objv[3];
1242 }else{
1243 pArray = objv[3];
1244 if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
1245 pScript = objv[4];
1246 }
danielk197730ccda12004-05-27 12:11:31 +00001247
drh1d895032004-08-26 00:56:05 +00001248 Tcl_IncrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001249 zSql = Tcl_GetStringFromObj(objv[2], 0);
drh90b6bb12004-09-13 13:16:31 +00001250 while( rc==TCL_OK && zSql[0] ){
drhfb7e7652005-01-24 00:28:42 +00001251 int i; /* Loop counter */
1252 int nVar; /* Number of bind parameters in the pStmt */
1253 int nCol; /* Number of columns in the result set */
drh92febd92004-08-20 18:34:20 +00001254 Tcl_Obj **apColName = 0; /* Array of column names */
drhfb7e7652005-01-24 00:28:42 +00001255 int len; /* String length of zSql */
danielk197730ccda12004-05-27 12:11:31 +00001256
drhfb7e7652005-01-24 00:28:42 +00001257 /* Try to find a SQL statement that has already been compiled and
1258 ** which matches the next sequence of SQL.
1259 */
1260 pStmt = 0;
1261 pPreStmt = pDb->stmtList;
1262 len = strlen(zSql);
1263 if( pPreStmt && sqlite3_expired(pPreStmt->pStmt) ){
1264 flushStmtCache(pDb);
1265 pPreStmt = 0;
danielk197730ccda12004-05-27 12:11:31 +00001266 }
drhfb7e7652005-01-24 00:28:42 +00001267 for(; pPreStmt; pPreStmt=pPreStmt->pNext){
1268 int n = pPreStmt->nSql;
1269 if( len>=n
1270 && memcmp(pPreStmt->zSql, zSql, n)==0
1271 && (zSql[n]==0 || zSql[n-1]==';')
1272 ){
1273 pStmt = pPreStmt->pStmt;
1274 zLeft = &zSql[pPreStmt->nSql];
1275
1276 /* When a prepared statement is found, unlink it from the
1277 ** cache list. It will later be added back to the beginning
1278 ** of the cache list in order to implement LRU replacement.
1279 */
1280 if( pPreStmt->pPrev ){
1281 pPreStmt->pPrev->pNext = pPreStmt->pNext;
1282 }else{
1283 pDb->stmtList = pPreStmt->pNext;
1284 }
1285 if( pPreStmt->pNext ){
1286 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1287 }else{
1288 pDb->stmtLast = pPreStmt->pPrev;
1289 }
1290 pDb->nStmt--;
1291 break;
1292 }
1293 }
1294
1295 /* If no prepared statement was found. Compile the SQL text
1296 */
drh92febd92004-08-20 18:34:20 +00001297 if( pStmt==0 ){
drhfb7e7652005-01-24 00:28:42 +00001298 if( SQLITE_OK!=sqlite3_prepare(pDb->db, zSql, -1, &pStmt, &zLeft) ){
drh92febd92004-08-20 18:34:20 +00001299 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1300 rc = TCL_ERROR;
1301 break;
danielk197730ccda12004-05-27 12:11:31 +00001302 }
drhfb7e7652005-01-24 00:28:42 +00001303 if( pStmt==0 ){
1304 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1305 /* A compile-time error in the statement
1306 */
1307 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
1308 rc = TCL_ERROR;
1309 break;
1310 }else{
1311 /* The statement was a no-op. Continue to the next statement
1312 ** in the SQL string.
1313 */
1314 zSql = zLeft;
1315 continue;
1316 }
1317 }
1318 assert( pPreStmt==0 );
danielk197730ccda12004-05-27 12:11:31 +00001319 }
1320
drhfb7e7652005-01-24 00:28:42 +00001321 /* Bind values to parameters that begin with $ or :
1322 */
drh92febd92004-08-20 18:34:20 +00001323 nVar = sqlite3_bind_parameter_count(pStmt);
drh1d895032004-08-26 00:56:05 +00001324 nParm = 0;
1325 if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
1326 apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
1327 }else{
1328 apParm = aParm;
1329 }
drh92febd92004-08-20 18:34:20 +00001330 for(i=1; i<=nVar; i++){
1331 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
drhc8f90792005-01-12 00:08:24 +00001332 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':') ){
drh92febd92004-08-20 18:34:20 +00001333 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1334 if( pVar ){
1335 int n;
1336 u8 *data;
1337 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
1338 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +00001339 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
1340 /* Only load a BLOB type if the Tcl variable is a bytearray and
1341 ** has no string representation. */
drh92febd92004-08-20 18:34:20 +00001342 data = Tcl_GetByteArrayFromObj(pVar, &n);
1343 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001344 Tcl_IncrRefCount(pVar);
1345 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001346 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
1347 (c=='i' && strcmp(zType,"int")==0) ){
1348 Tcl_GetIntFromObj(interp, pVar, &n);
1349 sqlite3_bind_int(pStmt, i, n);
1350 }else if( c=='d' && strcmp(zType,"double")==0 ){
1351 double r;
1352 Tcl_GetDoubleFromObj(interp, pVar, &r);
1353 sqlite3_bind_double(pStmt, i, r);
drhdf0bdda2005-06-25 19:31:48 +00001354 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
1355 Tcl_WideInt v;
1356 Tcl_GetWideIntFromObj(interp, pVar, &v);
1357 sqlite3_bind_int64(pStmt, i, v);
drh92febd92004-08-20 18:34:20 +00001358 }else{
danielk197700fd9572005-12-07 06:27:43 +00001359 data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1360 sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +00001361 Tcl_IncrRefCount(pVar);
1362 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +00001363 }
drhfb7e7652005-01-24 00:28:42 +00001364 }else{
1365 sqlite3_bind_null( pStmt, i );
drh92febd92004-08-20 18:34:20 +00001366 }
1367 }
1368 }
drh92febd92004-08-20 18:34:20 +00001369
1370 /* Compute column names */
1371 nCol = sqlite3_column_count(pStmt);
1372 if( pScript ){
1373 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1374 if( apColName==0 ) break;
1375 for(i=0; i<nCol; i++){
1376 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
1377 Tcl_IncrRefCount(apColName[i]);
1378 }
1379 }
1380
1381 /* If results are being stored in an array variable, then create
1382 ** the array(*) entry for that array
1383 */
1384 if( pArray ){
1385 Tcl_Obj *pColList = Tcl_NewObj();
drh3ced14a2005-03-31 18:26:20 +00001386 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
drh92febd92004-08-20 18:34:20 +00001387 Tcl_IncrRefCount(pColList);
1388 for(i=0; i<nCol; i++){
1389 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1390 }
drh3ced14a2005-03-31 18:26:20 +00001391 Tcl_ObjSetVar2(interp, pArray, pStar, pColList,0);
1392 Tcl_DecrRefCount(pColList);
1393 Tcl_DecrRefCount(pStar);
drh92febd92004-08-20 18:34:20 +00001394 }
1395
1396 /* Execute the SQL
1397 */
drh90b6bb12004-09-13 13:16:31 +00001398 while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
drh92febd92004-08-20 18:34:20 +00001399 for(i=0; i<nCol; i++){
danielk197730ccda12004-05-27 12:11:31 +00001400 Tcl_Obj *pVal;
1401
1402 /* Set pVal to contain the i'th column of this row. */
drh92febd92004-08-20 18:34:20 +00001403 switch( sqlite3_column_type(pStmt, i) ){
1404 case SQLITE_BLOB: {
1405 int bytes = sqlite3_column_bytes(pStmt, i);
1406 pVal = Tcl_NewByteArrayObj(sqlite3_column_blob(pStmt, i), bytes);
1407 break;
1408 }
1409 case SQLITE_INTEGER: {
1410 sqlite_int64 v = sqlite3_column_int64(pStmt, i);
1411 if( v>=-2147483647 && v<=2147483647 ){
1412 pVal = Tcl_NewIntObj(v);
1413 }else{
1414 pVal = Tcl_NewWideIntObj(v);
1415 }
1416 break;
1417 }
1418 case SQLITE_FLOAT: {
1419 double r = sqlite3_column_double(pStmt, i);
1420 pVal = Tcl_NewDoubleObj(r);
1421 break;
1422 }
danielk197755c45f22005-04-03 23:54:43 +00001423 case SQLITE_NULL: {
1424 pVal = dbTextToObj(pDb->zNull);
1425 break;
1426 }
drh92febd92004-08-20 18:34:20 +00001427 default: {
danielk197700fd9572005-12-07 06:27:43 +00001428 pVal = dbTextToObj((char *)sqlite3_column_text(pStmt, i));
drh92febd92004-08-20 18:34:20 +00001429 break;
1430 }
danielk197730ccda12004-05-27 12:11:31 +00001431 }
1432
drh92febd92004-08-20 18:34:20 +00001433 if( pScript ){
1434 if( pArray==0 ){
1435 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001436 }else{
drh92febd92004-08-20 18:34:20 +00001437 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001438 }
drh1807ce32004-09-07 13:20:35 +00001439 }else if( choice==DB_ONECOLUMN ){
drh97f2ebc2005-12-10 21:19:04 +00001440 assert( pRet==0 );
drh1807ce32004-09-07 13:20:35 +00001441 if( pRet==0 ){
1442 pRet = pVal;
1443 Tcl_IncrRefCount(pRet);
1444 }
drh90b6bb12004-09-13 13:16:31 +00001445 rc = TCL_BREAK;
drh97f2ebc2005-12-10 21:19:04 +00001446 i = nCol;
1447 }else if( choice==DB_EXISTS ){
drh446a9b82006-01-04 18:13:26 +00001448 Tcl_DecrRefCount(pRet);
1449 pRet = Tcl_NewBooleanObj(1);
1450 Tcl_IncrRefCount(pRet);
drh97f2ebc2005-12-10 21:19:04 +00001451 rc = TCL_BREAK;
1452 i = nCol;
danielk197730ccda12004-05-27 12:11:31 +00001453 }else{
danielk197730ccda12004-05-27 12:11:31 +00001454 Tcl_ListObjAppendElement(interp, pRet, pVal);
1455 }
1456 }
1457
drh92febd92004-08-20 18:34:20 +00001458 if( pScript ){
1459 rc = Tcl_EvalObjEx(interp, pScript, 0);
drh90b6bb12004-09-13 13:16:31 +00001460 if( rc==TCL_CONTINUE ){
1461 rc = TCL_OK;
1462 }
danielk197730ccda12004-05-27 12:11:31 +00001463 }
1464 }
drh90b6bb12004-09-13 13:16:31 +00001465 if( rc==TCL_BREAK ){
1466 rc = TCL_OK;
1467 }
drh92febd92004-08-20 18:34:20 +00001468
1469 /* Free the column name objects */
1470 if( pScript ){
1471 for(i=0; i<nCol; i++){
1472 Tcl_DecrRefCount(apColName[i]);
1473 }
1474 Tcl_Free((char*)apColName);
1475 }
1476
drh1d895032004-08-26 00:56:05 +00001477 /* Free the bound string and blob parameters */
1478 for(i=0; i<nParm; i++){
1479 Tcl_DecrRefCount(apParm[i]);
1480 }
1481 if( apParm!=aParm ){
1482 Tcl_Free((char*)apParm);
1483 }
1484
drhfb7e7652005-01-24 00:28:42 +00001485 /* Reset the statement. If the result code is SQLITE_SCHEMA, then
1486 ** flush the statement cache and try the statement again.
drh92febd92004-08-20 18:34:20 +00001487 */
drhfb7e7652005-01-24 00:28:42 +00001488 rc2 = sqlite3_reset(pStmt);
1489 if( SQLITE_SCHEMA==rc2 ){
1490 /* After a schema change, flush the cache and try to run the
1491 ** statement again
1492 */
1493 flushStmtCache( pDb );
1494 sqlite3_finalize(pStmt);
1495 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001496 continue;
drhfb7e7652005-01-24 00:28:42 +00001497 }else if( SQLITE_OK!=rc2 ){
1498 /* If a run-time error occurs, report the error and stop reading
1499 ** the SQL
1500 */
danielk1977ef2cb632004-05-29 02:37:19 +00001501 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
drhfb7e7652005-01-24 00:28:42 +00001502 sqlite3_finalize(pStmt);
danielk197730ccda12004-05-27 12:11:31 +00001503 rc = TCL_ERROR;
drhfb7e7652005-01-24 00:28:42 +00001504 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001505 break;
drhfb7e7652005-01-24 00:28:42 +00001506 }else if( pDb->maxStmt<=0 ){
1507 /* If the cache is turned off, deallocated the statement */
1508 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1509 sqlite3_finalize(pStmt);
1510 }else{
1511 /* Everything worked and the cache is operational.
1512 ** Create a new SqlPreparedStmt structure if we need one.
1513 ** (If we already have one we can just reuse it.)
1514 */
1515 if( pPreStmt==0 ){
1516 len = zLeft - zSql;
1517 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) + len );
1518 if( pPreStmt==0 ) return TCL_ERROR;
1519 pPreStmt->pStmt = pStmt;
1520 pPreStmt->nSql = len;
1521 memcpy(pPreStmt->zSql, zSql, len);
1522 pPreStmt->zSql[len] = 0;
1523 }
1524
1525 /* Add the prepared statement to the beginning of the cache list
1526 */
1527 pPreStmt->pNext = pDb->stmtList;
1528 pPreStmt->pPrev = 0;
1529 if( pDb->stmtList ){
1530 pDb->stmtList->pPrev = pPreStmt;
1531 }
1532 pDb->stmtList = pPreStmt;
1533 if( pDb->stmtLast==0 ){
1534 assert( pDb->nStmt==0 );
1535 pDb->stmtLast = pPreStmt;
1536 }else{
1537 assert( pDb->nStmt>0 );
1538 }
1539 pDb->nStmt++;
1540
1541 /* If we have too many statement in cache, remove the surplus from the
1542 ** end of the cache list.
1543 */
1544 while( pDb->nStmt>pDb->maxStmt ){
1545 sqlite3_finalize(pDb->stmtLast->pStmt);
1546 pDb->stmtLast = pDb->stmtLast->pPrev;
1547 Tcl_Free((char*)pDb->stmtLast->pNext);
1548 pDb->stmtLast->pNext = 0;
1549 pDb->nStmt--;
1550 }
danielk197730ccda12004-05-27 12:11:31 +00001551 }
1552
drhfb7e7652005-01-24 00:28:42 +00001553 /* Proceed to the next statement */
danielk197730ccda12004-05-27 12:11:31 +00001554 zSql = zLeft;
1555 }
drh1d895032004-08-26 00:56:05 +00001556 Tcl_DecrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001557
drh1807ce32004-09-07 13:20:35 +00001558 if( pRet ){
1559 if( rc==TCL_OK ){
1560 Tcl_SetObjResult(interp, pRet);
1561 }
1562 Tcl_DecrRefCount(pRet);
danielk197730ccda12004-05-27 12:11:31 +00001563 }
danielk197730ccda12004-05-27 12:11:31 +00001564 break;
1565 }
drhbec3f402000-08-04 13:49:02 +00001566
1567 /*
drhcabb0812002-09-14 13:47:32 +00001568 ** $db function NAME SCRIPT
1569 **
1570 ** Create a new SQL function called NAME. Whenever that function is
1571 ** called, invoke SCRIPT to evaluate the function.
1572 */
1573 case DB_FUNCTION: {
1574 SqlFunc *pFunc;
drhd1e47332005-06-26 17:55:33 +00001575 Tcl_Obj *pScript;
drhcabb0812002-09-14 13:47:32 +00001576 char *zName;
drhcabb0812002-09-14 13:47:32 +00001577 if( objc!=4 ){
1578 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1579 return TCL_ERROR;
1580 }
1581 zName = Tcl_GetStringFromObj(objv[2], 0);
drhd1e47332005-06-26 17:55:33 +00001582 pScript = objv[3];
1583 pFunc = findSqlFunc(pDb, zName);
drhcabb0812002-09-14 13:47:32 +00001584 if( pFunc==0 ) return TCL_ERROR;
drhd1e47332005-06-26 17:55:33 +00001585 if( pFunc->pScript ){
1586 Tcl_DecrRefCount(pFunc->pScript);
1587 }
1588 pFunc->pScript = pScript;
1589 Tcl_IncrRefCount(pScript);
1590 pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
danielk1977c8c11582004-06-29 13:41:21 +00001591 rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00001592 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00001593 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00001594 rc = TCL_ERROR;
1595 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00001596 }else{
1597 /* Must flush any cached statements */
1598 flushStmtCache( pDb );
1599 }
drhcabb0812002-09-14 13:47:32 +00001600 break;
1601 }
1602
1603 /*
drh19e2d372005-08-29 23:00:03 +00001604 ** $db nullvalue ?STRING?
1605 **
1606 ** Change text used when a NULL comes back from the database. If ?STRING?
1607 ** is not present, then the current string used for NULL is returned.
1608 ** If STRING is present, then STRING is returned.
1609 **
1610 */
1611 case DB_NULLVALUE: {
1612 if( objc!=2 && objc!=3 ){
1613 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
1614 return TCL_ERROR;
1615 }
1616 if( objc==3 ){
1617 int len;
1618 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
1619 if( pDb->zNull ){
1620 Tcl_Free(pDb->zNull);
1621 }
1622 if( zNull && len>0 ){
1623 pDb->zNull = Tcl_Alloc( len + 1 );
1624 strncpy(pDb->zNull, zNull, len);
1625 pDb->zNull[len] = '\0';
1626 }else{
1627 pDb->zNull = 0;
1628 }
1629 }
1630 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
1631 break;
1632 }
1633
1634 /*
drhaf9ff332002-01-16 21:00:27 +00001635 ** $db last_insert_rowid
1636 **
1637 ** Return an integer which is the ROWID for the most recent insert.
1638 */
1639 case DB_LAST_INSERT_ROWID: {
1640 Tcl_Obj *pResult;
drhf7e678d2006-06-21 19:30:34 +00001641 Tcl_WideInt rowid;
drhaf9ff332002-01-16 21:00:27 +00001642 if( objc!=2 ){
1643 Tcl_WrongNumArgs(interp, 2, objv, "");
1644 return TCL_ERROR;
1645 }
danielk19776f8a5032004-05-10 10:34:51 +00001646 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00001647 pResult = Tcl_GetObjResult(interp);
drhf7e678d2006-06-21 19:30:34 +00001648 Tcl_SetWideIntObj(pResult, rowid);
drhaf9ff332002-01-16 21:00:27 +00001649 break;
1650 }
1651
1652 /*
drh1807ce32004-09-07 13:20:35 +00001653 ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
drh5d9d7572003-08-19 14:31:01 +00001654 */
drh1807ce32004-09-07 13:20:35 +00001655
1656 /* $db progress ?N CALLBACK?
1657 **
1658 ** Invoke the given callback every N virtual machine opcodes while executing
1659 ** queries.
1660 */
1661 case DB_PROGRESS: {
1662 if( objc==2 ){
1663 if( pDb->zProgress ){
1664 Tcl_AppendResult(interp, pDb->zProgress, 0);
1665 }
1666 }else if( objc==4 ){
1667 char *zProgress;
1668 int len;
1669 int N;
1670 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
1671 return TCL_ERROR;
1672 };
1673 if( pDb->zProgress ){
1674 Tcl_Free(pDb->zProgress);
1675 }
1676 zProgress = Tcl_GetStringFromObj(objv[3], &len);
1677 if( zProgress && len>0 ){
1678 pDb->zProgress = Tcl_Alloc( len + 1 );
1679 strcpy(pDb->zProgress, zProgress);
1680 }else{
1681 pDb->zProgress = 0;
1682 }
1683#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1684 if( pDb->zProgress ){
1685 pDb->interp = interp;
1686 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
1687 }else{
1688 sqlite3_progress_handler(pDb->db, 0, 0, 0);
1689 }
1690#endif
1691 }else{
1692 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00001693 return TCL_ERROR;
1694 }
drh5d9d7572003-08-19 14:31:01 +00001695 break;
1696 }
1697
drh19e2d372005-08-29 23:00:03 +00001698 /* $db profile ?CALLBACK?
1699 **
1700 ** Make arrangements to invoke the CALLBACK routine after each SQL statement
1701 ** that has run. The text of the SQL and the amount of elapse time are
1702 ** appended to CALLBACK before the script is run.
1703 */
1704 case DB_PROFILE: {
1705 if( objc>3 ){
1706 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1707 return TCL_ERROR;
1708 }else if( objc==2 ){
1709 if( pDb->zProfile ){
1710 Tcl_AppendResult(interp, pDb->zProfile, 0);
1711 }
1712 }else{
1713 char *zProfile;
1714 int len;
1715 if( pDb->zProfile ){
1716 Tcl_Free(pDb->zProfile);
1717 }
1718 zProfile = Tcl_GetStringFromObj(objv[2], &len);
1719 if( zProfile && len>0 ){
1720 pDb->zProfile = Tcl_Alloc( len + 1 );
1721 strcpy(pDb->zProfile, zProfile);
1722 }else{
1723 pDb->zProfile = 0;
1724 }
1725#ifndef SQLITE_OMIT_TRACE
1726 if( pDb->zProfile ){
1727 pDb->interp = interp;
1728 sqlite3_profile(pDb->db, DbProfileHandler, pDb);
1729 }else{
1730 sqlite3_profile(pDb->db, 0, 0);
1731 }
1732#endif
1733 }
1734 break;
1735 }
1736
drh5d9d7572003-08-19 14:31:01 +00001737 /*
drh22fbcb82004-02-01 01:22:50 +00001738 ** $db rekey KEY
1739 **
1740 ** Change the encryption key on the currently open database.
1741 */
1742 case DB_REKEY: {
1743 int nKey;
1744 void *pKey;
1745 if( objc!=3 ){
1746 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
1747 return TCL_ERROR;
1748 }
1749 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00001750#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00001751 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00001752 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00001753 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00001754 rc = TCL_ERROR;
1755 }
1756#endif
1757 break;
1758 }
1759
1760 /*
drhbec3f402000-08-04 13:49:02 +00001761 ** $db timeout MILLESECONDS
1762 **
1763 ** Delay for the number of milliseconds specified when a file is locked.
1764 */
drh6d313162000-09-21 13:01:35 +00001765 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00001766 int ms;
drh6d313162000-09-21 13:01:35 +00001767 if( objc!=3 ){
1768 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00001769 return TCL_ERROR;
1770 }
drh6d313162000-09-21 13:01:35 +00001771 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00001772 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00001773 break;
drh75897232000-05-29 14:26:00 +00001774 }
danielk197755c45f22005-04-03 23:54:43 +00001775
1776 /*
drh0f14e2e2004-06-29 12:39:08 +00001777 ** $db total_changes
1778 **
1779 ** Return the number of rows that were modified, inserted, or deleted
1780 ** since the database handle was created.
1781 */
1782 case DB_TOTAL_CHANGES: {
1783 Tcl_Obj *pResult;
1784 if( objc!=2 ){
1785 Tcl_WrongNumArgs(interp, 2, objv, "");
1786 return TCL_ERROR;
1787 }
1788 pResult = Tcl_GetObjResult(interp);
1789 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
1790 break;
1791 }
1792
drhb5a20d32003-04-23 12:25:23 +00001793 /* $db trace ?CALLBACK?
1794 **
1795 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
1796 ** that is executed. The text of the SQL is appended to CALLBACK before
1797 ** it is executed.
1798 */
1799 case DB_TRACE: {
1800 if( objc>3 ){
1801 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00001802 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00001803 }else if( objc==2 ){
1804 if( pDb->zTrace ){
1805 Tcl_AppendResult(interp, pDb->zTrace, 0);
1806 }
1807 }else{
1808 char *zTrace;
1809 int len;
1810 if( pDb->zTrace ){
1811 Tcl_Free(pDb->zTrace);
1812 }
1813 zTrace = Tcl_GetStringFromObj(objv[2], &len);
1814 if( zTrace && len>0 ){
1815 pDb->zTrace = Tcl_Alloc( len + 1 );
1816 strcpy(pDb->zTrace, zTrace);
1817 }else{
1818 pDb->zTrace = 0;
1819 }
drh19e2d372005-08-29 23:00:03 +00001820#ifndef SQLITE_OMIT_TRACE
drhb5a20d32003-04-23 12:25:23 +00001821 if( pDb->zTrace ){
1822 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001823 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00001824 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001825 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00001826 }
drh19e2d372005-08-29 23:00:03 +00001827#endif
drhb5a20d32003-04-23 12:25:23 +00001828 }
1829 break;
1830 }
1831
drh3d214232005-08-02 12:21:08 +00001832 /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1833 **
1834 ** Start a new transaction (if we are not already in the midst of a
1835 ** transaction) and execute the TCL script SCRIPT. After SCRIPT
1836 ** completes, either commit the transaction or roll it back if SCRIPT
1837 ** throws an exception. Or if no new transation was started, do nothing.
1838 ** pass the exception on up the stack.
1839 **
1840 ** This command was inspired by Dave Thomas's talk on Ruby at the
1841 ** 2005 O'Reilly Open Source Convention (OSCON).
1842 */
1843 case DB_TRANSACTION: {
1844 int inTrans;
1845 Tcl_Obj *pScript;
1846 const char *zBegin = "BEGIN";
1847 if( objc!=3 && objc!=4 ){
1848 Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
1849 return TCL_ERROR;
1850 }
1851 if( objc==3 ){
1852 pScript = objv[2];
1853 } else {
1854 static const char *TTYPE_strs[] = {
drhce604012005-08-16 11:11:34 +00001855 "deferred", "exclusive", "immediate", 0
drh3d214232005-08-02 12:21:08 +00001856 };
1857 enum TTYPE_enum {
1858 TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
1859 };
1860 int ttype;
drhb5555e72005-08-02 17:15:14 +00001861 if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
drh3d214232005-08-02 12:21:08 +00001862 0, &ttype) ){
1863 return TCL_ERROR;
1864 }
1865 switch( (enum TTYPE_enum)ttype ){
1866 case TTYPE_DEFERRED: /* no-op */; break;
1867 case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break;
1868 case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break;
1869 }
1870 pScript = objv[3];
1871 }
1872 inTrans = !sqlite3_get_autocommit(pDb->db);
1873 if( !inTrans ){
drh37527852006-03-16 16:19:56 +00001874 (void)sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
drh3d214232005-08-02 12:21:08 +00001875 }
1876 rc = Tcl_EvalObjEx(interp, pScript, 0);
1877 if( !inTrans ){
1878 const char *zEnd;
1879 if( rc==TCL_ERROR ){
1880 zEnd = "ROLLBACK";
1881 } else {
1882 zEnd = "COMMIT";
1883 }
drh37527852006-03-16 16:19:56 +00001884 (void)sqlite3_exec(pDb->db, zEnd, 0, 0, 0);
drh3d214232005-08-02 12:21:08 +00001885 }
1886 break;
1887 }
1888
danielk197794eb6a12005-12-15 15:22:08 +00001889 /*
1890 ** $db update_hook ?script?
danielk197771fd80b2005-12-16 06:54:01 +00001891 ** $db rollback_hook ?script?
danielk197794eb6a12005-12-15 15:22:08 +00001892 */
danielk197771fd80b2005-12-16 06:54:01 +00001893 case DB_UPDATE_HOOK:
1894 case DB_ROLLBACK_HOOK: {
1895
1896 /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
1897 ** whether [$db update_hook] or [$db rollback_hook] was invoked.
1898 */
1899 Tcl_Obj **ppHook;
1900 if( choice==DB_UPDATE_HOOK ){
1901 ppHook = &pDb->pUpdateHook;
1902 }else{
1903 ppHook = &pDb->pRollbackHook;
1904 }
1905
danielk197794eb6a12005-12-15 15:22:08 +00001906 if( objc!=2 && objc!=3 ){
1907 Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
1908 return TCL_ERROR;
1909 }
danielk197771fd80b2005-12-16 06:54:01 +00001910 if( *ppHook ){
1911 Tcl_SetObjResult(interp, *ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00001912 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00001913 Tcl_DecrRefCount(*ppHook);
1914 *ppHook = 0;
danielk197794eb6a12005-12-15 15:22:08 +00001915 }
1916 }
1917 if( objc==3 ){
danielk197771fd80b2005-12-16 06:54:01 +00001918 assert( !(*ppHook) );
danielk197794eb6a12005-12-15 15:22:08 +00001919 if( Tcl_GetCharLength(objv[2])>0 ){
danielk197771fd80b2005-12-16 06:54:01 +00001920 *ppHook = objv[2];
1921 Tcl_IncrRefCount(*ppHook);
danielk197794eb6a12005-12-15 15:22:08 +00001922 }
1923 }
danielk197771fd80b2005-12-16 06:54:01 +00001924
1925 sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1926 sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
1927
danielk197794eb6a12005-12-15 15:22:08 +00001928 break;
1929 }
1930
danielk19774397de52005-01-12 12:44:03 +00001931 /* $db version
1932 **
1933 ** Return the version string for this database.
1934 */
1935 case DB_VERSION: {
1936 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
1937 break;
1938 }
1939
tpoindex1067fe12004-12-17 15:41:11 +00001940
drh6d313162000-09-21 13:01:35 +00001941 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00001942 return rc;
drh75897232000-05-29 14:26:00 +00001943}
1944
1945/*
drh9bb575f2004-09-06 17:24:11 +00001946** sqlite3 DBNAME FILENAME ?MODE? ?-key KEY?
drh75897232000-05-29 14:26:00 +00001947**
1948** This is the main Tcl command. When the "sqlite" Tcl command is
1949** invoked, this routine runs to process that command.
1950**
1951** The first argument, DBNAME, is an arbitrary name for a new
1952** database connection. This command creates a new command named
1953** DBNAME that is used to control that connection. The database
1954** connection is deleted when the DBNAME command is deleted.
1955**
1956** The second argument is the name of the directory that contains
1957** the sqlite database that is to be accessed.
drhfbc3eab2001-04-06 16:13:42 +00001958**
1959** For testing purposes, we also support the following:
1960**
drh9bb575f2004-09-06 17:24:11 +00001961** sqlite3 -encoding
drhfbc3eab2001-04-06 16:13:42 +00001962**
1963** Return the encoding used by LIKE and GLOB operators. Choices
1964** are UTF-8 and iso8859.
1965**
drh9bb575f2004-09-06 17:24:11 +00001966** sqlite3 -version
drh647cb0e2002-11-04 19:32:25 +00001967**
1968** Return the version number of the SQLite library.
1969**
drh9bb575f2004-09-06 17:24:11 +00001970** sqlite3 -tcl-uses-utf
drhfbc3eab2001-04-06 16:13:42 +00001971**
1972** Return "1" if compiled with a Tcl uses UTF-8. Return "0" if
1973** not. Used by tests to make sure the library was compiled
1974** correctly.
drh75897232000-05-29 14:26:00 +00001975*/
drh22fbcb82004-02-01 01:22:50 +00001976static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001977 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00001978 void *pKey = 0;
1979 int nKey = 0;
1980 const char *zArg;
drh75897232000-05-29 14:26:00 +00001981 char *zErrMsg;
drh22fbcb82004-02-01 01:22:50 +00001982 const char *zFile;
drh22fbcb82004-02-01 01:22:50 +00001983 if( objc==2 ){
1984 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00001985 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00001986 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00001987 return TCL_OK;
1988 }
drh9eb9e262004-02-11 02:18:05 +00001989 if( strcmp(zArg,"-has-codec")==0 ){
1990#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00001991 Tcl_AppendResult(interp,"1",0);
1992#else
1993 Tcl_AppendResult(interp,"0",0);
1994#endif
1995 return TCL_OK;
1996 }
1997 if( strcmp(zArg,"-tcl-uses-utf")==0 ){
drhfbc3eab2001-04-06 16:13:42 +00001998#ifdef TCL_UTF_MAX
1999 Tcl_AppendResult(interp,"1",0);
2000#else
2001 Tcl_AppendResult(interp,"0",0);
2002#endif
2003 return TCL_OK;
2004 }
2005 }
drh22fbcb82004-02-01 01:22:50 +00002006 if( objc==5 || objc==6 ){
2007 zArg = Tcl_GetStringFromObj(objv[objc-2], 0);
2008 if( strcmp(zArg,"-key")==0 ){
2009 pKey = Tcl_GetByteArrayFromObj(objv[objc-1], &nKey);
2010 objc -= 2;
2011 }
2012 }
2013 if( objc!=3 && objc!=4 ){
2014 Tcl_WrongNumArgs(interp, 1, objv,
drh9eb9e262004-02-11 02:18:05 +00002015#ifdef SQLITE_HAS_CODEC
2016 "HANDLE FILENAME ?-key CODEC-KEY?"
drh22fbcb82004-02-01 01:22:50 +00002017#else
2018 "HANDLE FILENAME ?MODE?"
2019#endif
2020 );
drh75897232000-05-29 14:26:00 +00002021 return TCL_ERROR;
2022 }
drh75897232000-05-29 14:26:00 +00002023 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00002024 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00002025 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00002026 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
2027 return TCL_ERROR;
2028 }
2029 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00002030 zFile = Tcl_GetStringFromObj(objv[2], 0);
danielk19774f057f92004-06-08 00:02:33 +00002031 sqlite3_open(zFile, &p->db);
danielk197780290862004-05-22 09:21:21 +00002032 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
2033 zErrMsg = strdup(sqlite3_errmsg(p->db));
2034 sqlite3_close(p->db);
2035 p->db = 0;
2036 }
drh2011d5f2004-07-22 02:40:37 +00002037#ifdef SQLITE_HAS_CODEC
2038 sqlite3_key(p->db, pKey, nKey);
drheb8ed702004-02-11 10:37:23 +00002039#endif
drhbec3f402000-08-04 13:49:02 +00002040 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00002041 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00002042 Tcl_Free((char*)p);
drh75897232000-05-29 14:26:00 +00002043 free(zErrMsg);
2044 return TCL_ERROR;
2045 }
drhfb7e7652005-01-24 00:28:42 +00002046 p->maxStmt = NUM_PREPARED_STMTS;
drh22fbcb82004-02-01 01:22:50 +00002047 zArg = Tcl_GetStringFromObj(objv[1], 0);
2048 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
drhc22bd472002-05-10 13:14:07 +00002049
2050 /* If compiled with SQLITE_TEST turned on, then register the "md5sum"
drh06b27182002-06-26 20:06:05 +00002051 ** SQL function.
drhc22bd472002-05-10 13:14:07 +00002052 */
drh28b4e482002-03-11 02:06:13 +00002053#ifdef SQLITE_TEST
2054 {
drh9bb575f2004-09-06 17:24:11 +00002055 extern void Md5_Register(sqlite3*);
drh3b93bc82005-01-13 23:54:32 +00002056#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00002057 int mallocfail = sqlite3_iMallocFail;
2058 sqlite3_iMallocFail = 0;
danielk19775b59af82004-06-30 12:42:59 +00002059#endif
drhc22bd472002-05-10 13:14:07 +00002060 Md5_Register(p->db);
drh3b93bc82005-01-13 23:54:32 +00002061#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00002062 sqlite3_iMallocFail = mallocfail;
danielk19775b59af82004-06-30 12:42:59 +00002063#endif
danielk19777ddad962005-12-12 06:53:03 +00002064 }
drh28b4e482002-03-11 02:06:13 +00002065#endif
danielk19777cedc8d2004-06-10 10:50:08 +00002066 p->interp = interp;
drh75897232000-05-29 14:26:00 +00002067 return TCL_OK;
2068}
2069
2070/*
drh90ca9752001-09-28 17:47:14 +00002071** Provide a dummy Tcl_InitStubs if we are using this as a static
2072** library.
2073*/
2074#ifndef USE_TCL_STUBS
2075# undef Tcl_InitStubs
2076# define Tcl_InitStubs(a,b,c)
2077#endif
2078
2079/*
drh29bc4612005-10-05 10:40:15 +00002080** Make sure we have a PACKAGE_VERSION macro defined. This will be
2081** defined automatically by the TEA makefile. But other makefiles
2082** do not define it.
2083*/
2084#ifndef PACKAGE_VERSION
2085# define PACKAGE_VERSION SQLITE_VERSION
2086#endif
2087
2088/*
drh75897232000-05-29 14:26:00 +00002089** Initialize this module.
2090**
2091** This Tcl module contains only a single new Tcl command named "sqlite".
2092** (Hence there is no namespace. There is no point in using a namespace
2093** if the extension only supplies one new name!) The "sqlite" command is
2094** used to open a new SQLite database. See the DbMain() routine above
2095** for additional information.
2096*/
drh86b7f572006-03-06 23:30:51 +00002097extern int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00002098 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00002099 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002100 Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
drh49766d62005-01-08 18:42:28 +00002101 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
drh29bc4612005-10-05 10:40:15 +00002102 Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
drh90ca9752001-09-28 17:47:14 +00002103 return TCL_OK;
2104}
drh86b7f572006-03-06 23:30:51 +00002105extern int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2106extern int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2107extern int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002108
2109#ifndef SQLITE_3_SUFFIX_ONLY
drh86b7f572006-03-06 23:30:51 +00002110extern int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2111extern int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2112extern int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2113extern int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
drh49766d62005-01-08 18:42:28 +00002114#endif
drh75897232000-05-29 14:26:00 +00002115
drh3e27c022004-07-23 00:01:38 +00002116#ifdef TCLSH
2117/*****************************************************************************
2118** The code that follows is used to build standalone TCL interpreters
drh75897232000-05-29 14:26:00 +00002119*/
drh348784e2000-05-29 20:41:49 +00002120
2121/*
drh3e27c022004-07-23 00:01:38 +00002122** If the macro TCLSH is one, then put in code this for the
2123** "main" routine that will initialize Tcl and take input from
2124** standard input.
drh348784e2000-05-29 20:41:49 +00002125*/
drh3e27c022004-07-23 00:01:38 +00002126#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00002127static char zMainloop[] =
2128 "set line {}\n"
2129 "while {![eof stdin]} {\n"
2130 "if {$line!=\"\"} {\n"
2131 "puts -nonewline \"> \"\n"
2132 "} else {\n"
2133 "puts -nonewline \"% \"\n"
2134 "}\n"
2135 "flush stdout\n"
2136 "append line [gets stdin]\n"
2137 "if {[info complete $line]} {\n"
2138 "if {[catch {uplevel #0 $line} result]} {\n"
2139 "puts stderr \"Error: $result\"\n"
2140 "} elseif {$result!=\"\"} {\n"
2141 "puts $result\n"
2142 "}\n"
2143 "set line {}\n"
2144 "} else {\n"
2145 "append line \\n\n"
2146 "}\n"
2147 "}\n"
2148;
drh3e27c022004-07-23 00:01:38 +00002149#endif
2150
2151/*
2152** If the macro TCLSH is two, then get the main loop code out of
2153** the separate file "spaceanal_tcl.h".
2154*/
2155#if TCLSH==2
2156static char zMainloop[] =
2157#include "spaceanal_tcl.h"
2158;
2159#endif
drh348784e2000-05-29 20:41:49 +00002160
2161#define TCLSH_MAIN main /* Needed to fake out mktclapp */
2162int TCLSH_MAIN(int argc, char **argv){
2163 Tcl_Interp *interp;
drh297ecf12001-04-05 15:57:13 +00002164 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00002165 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00002166 Sqlite3_Init(interp);
drhd9b02572001-04-15 00:37:09 +00002167#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00002168 {
2169 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00002170 extern int Sqlitetest2_Init(Tcl_Interp*);
2171 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00002172 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00002173 extern int Sqlitetest5_Init(Tcl_Interp*);
drh9c06c952005-11-26 00:25:00 +00002174 extern int Sqlitetest6_Init(Tcl_Interp*);
drh29c636b2006-01-09 23:40:25 +00002175 extern int Sqlitetest7_Init(Tcl_Interp*);
drhb9bb7c12006-06-11 23:41:55 +00002176 extern int Sqlitetest8_Init(Tcl_Interp*);
drhefc251d2001-07-01 22:12:01 +00002177 extern int Md5_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002178 extern int Sqlitetestsse_Init(Tcl_Interp*);
drh23669402006-01-09 17:29:52 +00002179 extern int Sqlitetestasync_Init(Tcl_Interp*);
drh4be8b512006-06-13 23:51:34 +00002180 extern int Sqlitetesttclvar_Init(Tcl_Interp*);
danielk1977954ce992006-06-15 15:59:19 +00002181 extern int Sqlitetestschema_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00002182
danielk19776490beb2004-05-11 06:17:21 +00002183 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00002184 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00002185 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00002186 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00002187 Sqlitetest5_Init(interp);
drh9c06c952005-11-26 00:25:00 +00002188 Sqlitetest6_Init(interp);
drh29c636b2006-01-09 23:40:25 +00002189 Sqlitetest7_Init(interp);
drhb9bb7c12006-06-11 23:41:55 +00002190 Sqlitetest8_Init(interp);
drh23669402006-01-09 17:29:52 +00002191 Sqlitetestasync_Init(interp);
drh4be8b512006-06-13 23:51:34 +00002192 Sqlitetesttclvar_Init(interp);
danielk1977954ce992006-06-15 15:59:19 +00002193 Sqlitetestschema_Init(interp);
drhefc251d2001-07-01 22:12:01 +00002194 Md5_Init(interp);
drh89dec812005-04-28 19:03:37 +00002195#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00002196 Sqlitetestsse_Init(interp);
2197#endif
drhd1bf3512001-04-07 15:24:33 +00002198 }
2199#endif
drh3e27c022004-07-23 00:01:38 +00002200 if( argc>=2 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002201 int i;
2202 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
2203 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00002204 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00002205 Tcl_SetVar(interp, "argv", argv[i],
2206 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
2207 }
drh3e27c022004-07-23 00:01:38 +00002208 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00002209 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drhc61053b2000-06-04 12:58:36 +00002210 if( zInfo==0 ) zInfo = interp->result;
2211 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00002212 return 1;
2213 }
drh3e27c022004-07-23 00:01:38 +00002214 }
2215 if( argc<=1 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00002216 Tcl_GlobalEval(interp, zMainloop);
2217 }
2218 return 0;
2219}
2220#endif /* TCLSH */
drh6d313162000-09-21 13:01:35 +00002221
2222#endif /* !defined(NO_TCL) */