blob: 177ad4066bf3dad84fd89b2d2a311b2928bb8e16 [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**
drhfb7e7652005-01-24 00:28:42 +000014** $Id: tclsqlite.c,v 1.116 2005/01/24 00:28:43 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>
drh75897232000-05-29 14:26:00 +000024
drhfb7e7652005-01-24 00:28:42 +000025#define NUM_PREPARED_STMTS 0
26#define MAX_PREPARED_STMTS 100
27
drh75897232000-05-29 14:26:00 +000028/*
drh98808ba2001-10-18 12:34:46 +000029** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
30** have to do a translation when going between the two. Set the
31** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
32** this translation.
33*/
34#if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
35# define UTF_TRANSLATION_NEEDED 1
36#endif
37
38/*
drhcabb0812002-09-14 13:47:32 +000039** New SQL functions can be created as TCL scripts. Each such function
40** is described by an instance of the following structure.
41*/
42typedef struct SqlFunc SqlFunc;
43struct SqlFunc {
44 Tcl_Interp *interp; /* The TCL interpret to execute the function */
45 char *zScript; /* The script to be run */
46 SqlFunc *pNext; /* Next function on the list of them all */
47};
48
49/*
danielk19770202b292004-06-09 09:55:16 +000050** New collation sequences function can be created as TCL scripts. Each such
51** function is described by an instance of the following structure.
52*/
53typedef struct SqlCollate SqlCollate;
54struct SqlCollate {
55 Tcl_Interp *interp; /* The TCL interpret to execute the function */
56 char *zScript; /* The script to be run */
57 SqlCollate *pNext; /* Next function on the list of them all */
58};
59
60/*
drhfb7e7652005-01-24 00:28:42 +000061** Prepared statements are cached for faster execution. Each prepared
62** statement is described by an instance of the following structure.
63*/
64typedef struct SqlPreparedStmt SqlPreparedStmt;
65struct SqlPreparedStmt {
66 SqlPreparedStmt *pNext; /* Next in linked list */
67 SqlPreparedStmt *pPrev; /* Previous on the list */
68 sqlite3_stmt *pStmt; /* The prepared statement */
69 int nSql; /* chars in zSql[] */
70 char zSql[1]; /* Text of the SQL statement */
71};
72
73/*
drhbec3f402000-08-04 13:49:02 +000074** There is one instance of this structure for each SQLite database
75** that has been opened by the SQLite TCL interface.
76*/
77typedef struct SqliteDb SqliteDb;
78struct SqliteDb {
drh895d7472004-08-20 16:02:39 +000079 sqlite3 *db; /* The "real" database structure */
drhbec3f402000-08-04 13:49:02 +000080 Tcl_Interp *interp; /* The interpreter used for this database */
drh6d313162000-09-21 13:01:35 +000081 char *zBusy; /* The busy callback routine */
drhaa940ea2004-01-15 02:44:03 +000082 char *zCommit; /* The commit hook callback routine */
drhb5a20d32003-04-23 12:25:23 +000083 char *zTrace; /* The trace callback routine */
danielk1977348bb5d2003-10-18 09:37:26 +000084 char *zProgress; /* The progress callback routine */
drhe22a3342003-04-22 20:30:37 +000085 char *zAuth; /* The authorization callback routine */
drhcabb0812002-09-14 13:47:32 +000086 SqlFunc *pFunc; /* List of SQL functions */
danielk19770202b292004-06-09 09:55:16 +000087 SqlCollate *pCollate; /* List of SQL collation functions */
danielk19776f8a5032004-05-10 10:34:51 +000088 int rc; /* Return code of most recent sqlite3_exec() */
danielk19777cedc8d2004-06-10 10:50:08 +000089 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +000090 SqlPreparedStmt *stmtList; /* List of prepared statements*/
91 SqlPreparedStmt *stmtLast; /* Last statement in the list */
92 int maxStmt; /* The next maximum number of stmtList */
93 int nStmt; /* Number of statements in stmtList */
drh98808ba2001-10-18 12:34:46 +000094};
drh297ecf12001-04-05 15:57:13 +000095
drh6d313162000-09-21 13:01:35 +000096/*
drhfb7e7652005-01-24 00:28:42 +000097** Finalize and free a list of prepared statements
98*/
99static void flushStmtCache( SqliteDb *pDb ){
100 SqlPreparedStmt *pPreStmt;
101
102 while( pDb->stmtList ){
103 sqlite3_finalize( pDb->stmtList->pStmt );
104 pPreStmt = pDb->stmtList;
105 pDb->stmtList = pDb->stmtList->pNext;
106 Tcl_Free( (char*)pPreStmt );
107 }
108 pDb->nStmt = 0;
109 pDb->stmtLast = 0;
110}
111
112/*
drh895d7472004-08-20 16:02:39 +0000113** TCL calls this procedure when an sqlite3 database command is
114** deleted.
drh75897232000-05-29 14:26:00 +0000115*/
116static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000117 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000118 flushStmtCache(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000119 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000120 while( pDb->pFunc ){
121 SqlFunc *pFunc = pDb->pFunc;
122 pDb->pFunc = pFunc->pNext;
123 Tcl_Free((char*)pFunc);
124 }
danielk19770202b292004-06-09 09:55:16 +0000125 while( pDb->pCollate ){
126 SqlCollate *pCollate = pDb->pCollate;
127 pDb->pCollate = pCollate->pNext;
128 Tcl_Free((char*)pCollate);
129 }
drhbec3f402000-08-04 13:49:02 +0000130 if( pDb->zBusy ){
131 Tcl_Free(pDb->zBusy);
132 }
drhb5a20d32003-04-23 12:25:23 +0000133 if( pDb->zTrace ){
134 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000135 }
drhe22a3342003-04-22 20:30:37 +0000136 if( pDb->zAuth ){
137 Tcl_Free(pDb->zAuth);
138 }
drhbec3f402000-08-04 13:49:02 +0000139 Tcl_Free((char*)pDb);
140}
141
142/*
143** This routine is called when a database file is locked while trying
144** to execute SQL.
145*/
danielk19772a764eb2004-06-12 01:43:26 +0000146static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000147 SqliteDb *pDb = (SqliteDb*)cd;
148 int rc;
149 char zVal[30];
150 char *zCmd;
drhbec3f402000-08-04 13:49:02 +0000151 Tcl_DString cmd;
152
153 Tcl_DStringInit(&cmd);
154 Tcl_DStringAppend(&cmd, pDb->zBusy, -1);
danielk19772a764eb2004-06-12 01:43:26 +0000155 sprintf(zVal, "%d", nTries);
156 Tcl_DStringAppendElement(&cmd, zVal);
drhbec3f402000-08-04 13:49:02 +0000157 zCmd = Tcl_DStringValue(&cmd);
158 rc = Tcl_Eval(pDb->interp, zCmd);
159 Tcl_DStringFree(&cmd);
160 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
161 return 0;
162 }
163 return 1;
drh75897232000-05-29 14:26:00 +0000164}
165
166/*
danielk1977348bb5d2003-10-18 09:37:26 +0000167** This routine is invoked as the 'progress callback' for the database.
168*/
169static int DbProgressHandler(void *cd){
170 SqliteDb *pDb = (SqliteDb*)cd;
171 int rc;
172
173 assert( pDb->zProgress );
174 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
175 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
176 return 1;
177 }
178 return 0;
179}
180
181/*
drhb5a20d32003-04-23 12:25:23 +0000182** This routine is called by the SQLite trace handler whenever a new
183** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000184*/
drhb5a20d32003-04-23 12:25:23 +0000185static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000186 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000187 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000188
drhb5a20d32003-04-23 12:25:23 +0000189 Tcl_DStringInit(&str);
190 Tcl_DStringAppend(&str, pDb->zTrace, -1);
191 Tcl_DStringAppendElement(&str, zSql);
192 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
193 Tcl_DStringFree(&str);
194 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000195}
196
197/*
drhaa940ea2004-01-15 02:44:03 +0000198** This routine is called when a transaction is committed. The
199** TCL script in pDb->zCommit is executed. If it returns non-zero or
200** if it throws an exception, the transaction is rolled back instead
201** of being committed.
202*/
203static int DbCommitHandler(void *cd){
204 SqliteDb *pDb = (SqliteDb*)cd;
205 int rc;
206
207 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
208 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
209 return 1;
210 }
211 return 0;
212}
213
danielk19777cedc8d2004-06-10 10:50:08 +0000214static void tclCollateNeeded(
215 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000216 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000217 int enc,
218 const char *zName
219){
220 SqliteDb *pDb = (SqliteDb *)pCtx;
221 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
222 Tcl_IncrRefCount(pScript);
223 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
224 Tcl_EvalObjEx(pDb->interp, pScript, 0);
225 Tcl_DecrRefCount(pScript);
226}
227
drhaa940ea2004-01-15 02:44:03 +0000228/*
danielk19770202b292004-06-09 09:55:16 +0000229** This routine is called to evaluate an SQL collation function implemented
230** using TCL script.
231*/
232static int tclSqlCollate(
233 void *pCtx,
234 int nA,
235 const void *zA,
236 int nB,
237 const void *zB
238){
239 SqlCollate *p = (SqlCollate *)pCtx;
240 Tcl_Obj *pCmd;
241
242 pCmd = Tcl_NewStringObj(p->zScript, -1);
243 Tcl_IncrRefCount(pCmd);
244 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
245 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
246 Tcl_EvalObjEx(p->interp, pCmd, 0);
247 Tcl_DecrRefCount(pCmd);
248 return (atoi(Tcl_GetStringResult(p->interp)));
249}
250
251/*
drhcabb0812002-09-14 13:47:32 +0000252** This routine is called to evaluate an SQL function implemented
253** using TCL script.
254*/
drhfb7e7652005-01-24 00:28:42 +0000255static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000256 SqlFunc *p = sqlite3_user_data(context);
drhcabb0812002-09-14 13:47:32 +0000257 Tcl_DString cmd;
258 int i;
259 int rc;
260
261 Tcl_DStringInit(&cmd);
262 Tcl_DStringAppend(&cmd, p->zScript, -1);
263 for(i=0; i<argc; i++){
drh9c054832004-05-31 18:51:57 +0000264 if( SQLITE_NULL==sqlite3_value_type(argv[i]) ){
danielk197751ad0ec2004-05-24 12:39:02 +0000265 Tcl_DStringAppendElement(&cmd, "");
266 }else{
drh4f26d6c2004-05-26 23:25:30 +0000267 Tcl_DStringAppendElement(&cmd, sqlite3_value_text(argv[i]));
danielk197751ad0ec2004-05-24 12:39:02 +0000268 }
drhcabb0812002-09-14 13:47:32 +0000269 }
270 rc = Tcl_Eval(p->interp, Tcl_DStringValue(&cmd));
271 if( rc ){
danielk19777e18c252004-05-25 11:47:24 +0000272 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000273 }else{
danielk1977d8123362004-06-12 09:25:12 +0000274 sqlite3_result_text(context, Tcl_GetStringResult(p->interp), -1,
275 SQLITE_TRANSIENT);
drhcabb0812002-09-14 13:47:32 +0000276 }
277}
drh895d7472004-08-20 16:02:39 +0000278
drhe22a3342003-04-22 20:30:37 +0000279#ifndef SQLITE_OMIT_AUTHORIZATION
280/*
281** This is the authentication function. It appends the authentication
282** type code and the two arguments to zCmd[] then invokes the result
283** on the interpreter. The reply is examined to determine if the
284** authentication fails or succeeds.
285*/
286static int auth_callback(
287 void *pArg,
288 int code,
289 const char *zArg1,
290 const char *zArg2,
291 const char *zArg3,
292 const char *zArg4
293){
294 char *zCode;
295 Tcl_DString str;
296 int rc;
297 const char *zReply;
298 SqliteDb *pDb = (SqliteDb*)pArg;
299
300 switch( code ){
301 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
302 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
303 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
304 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
305 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
306 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
307 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
308 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
309 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
310 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
311 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
312 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
313 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
314 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
315 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
316 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
317 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
318 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
319 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
320 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
321 case SQLITE_READ : zCode="SQLITE_READ"; break;
322 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
323 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
324 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000325 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
326 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000327 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000328 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe22a3342003-04-22 20:30:37 +0000329 default : zCode="????"; break;
330 }
331 Tcl_DStringInit(&str);
332 Tcl_DStringAppend(&str, pDb->zAuth, -1);
333 Tcl_DStringAppendElement(&str, zCode);
334 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
335 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
336 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
337 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
338 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
339 Tcl_DStringFree(&str);
340 zReply = Tcl_GetStringResult(pDb->interp);
341 if( strcmp(zReply,"SQLITE_OK")==0 ){
342 rc = SQLITE_OK;
343 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
344 rc = SQLITE_DENY;
345 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
346 rc = SQLITE_IGNORE;
347 }else{
348 rc = 999;
349 }
350 return rc;
351}
352#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000353
354/*
danielk1977ef2cb632004-05-29 02:37:19 +0000355** zText is a pointer to text obtained via an sqlite3_result_text()
356** or similar interface. This routine returns a Tcl string object,
357** reference count set to 0, containing the text. If a translation
358** between iso8859 and UTF-8 is required, it is preformed.
359*/
360static Tcl_Obj *dbTextToObj(char const *zText){
361 Tcl_Obj *pVal;
362#ifdef UTF_TRANSLATION_NEEDED
363 Tcl_DString dCol;
364 Tcl_DStringInit(&dCol);
365 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
366 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
367 Tcl_DStringFree(&dCol);
368#else
369 pVal = Tcl_NewStringObj(zText, -1);
370#endif
371 return pVal;
372}
373
374/*
tpoindex1067fe12004-12-17 15:41:11 +0000375** This routine reads a line of text from FILE in, stores
376** the text in memory obtained from malloc() and returns a pointer
377** to the text. NULL is returned at end of file, or if malloc()
378** fails.
379**
380** The interface is like "readline" but no command-line editing
381** is done.
382**
383** copied from shell.c from '.import' command
384*/
385static char *local_getline(char *zPrompt, FILE *in){
386 char *zLine;
387 int nLine;
388 int n;
389 int eol;
390
391 nLine = 100;
392 zLine = malloc( nLine );
393 if( zLine==0 ) return 0;
394 n = 0;
395 eol = 0;
396 while( !eol ){
397 if( n+100>nLine ){
398 nLine = nLine*2 + 100;
399 zLine = realloc(zLine, nLine);
400 if( zLine==0 ) return 0;
401 }
402 if( fgets(&zLine[n], nLine - n, in)==0 ){
403 if( n==0 ){
404 free(zLine);
405 return 0;
406 }
407 zLine[n] = 0;
408 eol = 1;
409 break;
410 }
411 while( zLine[n] ){ n++; }
412 if( n>0 && zLine[n-1]=='\n' ){
413 n--;
414 zLine[n] = 0;
415 eol = 1;
416 }
417 }
418 zLine = realloc( zLine, n+1 );
419 return zLine;
420}
421
422/*
drh75897232000-05-29 14:26:00 +0000423** The "sqlite" command below creates a new Tcl command for each
424** connection it opens to an SQLite database. This routine is invoked
425** whenever one of those connection-specific commands is executed
426** in Tcl. For example, if you run Tcl code like this:
427**
drh9bb575f2004-09-06 17:24:11 +0000428** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +0000429** db1 close
430**
431** The first command opens a connection to the "my_database" database
432** and calls that connection "db1". The second command causes this
433** subroutine to be invoked.
434*/
drh6d313162000-09-21 13:01:35 +0000435static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +0000436 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +0000437 int choice;
drh22fbcb82004-02-01 01:22:50 +0000438 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +0000439 static const char *DB_strs[] = {
drhfb7e7652005-01-24 00:28:42 +0000440 "authorizer", "busy", "cache",
441 "changes", "close", "collate",
442 "collation_needed", "commit_hook", "complete",
443 "copy", "errorcode", "eval",
444 "function", "last_insert_rowid", "onecolumn",
445 "progress", "rekey", "timeout",
446 "total_changes", "trace", "version",
drh0f14e2e2004-06-29 12:39:08 +0000447 0
drh6d313162000-09-21 13:01:35 +0000448 };
drh411995d2002-06-25 19:31:18 +0000449 enum DB_enum {
drhfb7e7652005-01-24 00:28:42 +0000450 DB_AUTHORIZER, DB_BUSY, DB_CACHE,
451 DB_CHANGES, DB_CLOSE, DB_COLLATE,
452 DB_COLLATION_NEEDED, DB_COMMIT_HOOK, DB_COMPLETE,
453 DB_COPY, DB_ERRORCODE, DB_EVAL,
454 DB_FUNCTION, DB_LAST_INSERT_ROWID,DB_ONECOLUMN,
455 DB_PROGRESS, DB_REKEY, DB_TIMEOUT,
456 DB_TOTAL_CHANGES, DB_TRACE, DB_VERSION
drh6d313162000-09-21 13:01:35 +0000457 };
tpoindex1067fe12004-12-17 15:41:11 +0000458 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +0000459
460 if( objc<2 ){
461 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +0000462 return TCL_ERROR;
463 }
drh411995d2002-06-25 19:31:18 +0000464 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +0000465 return TCL_ERROR;
466 }
467
drh411995d2002-06-25 19:31:18 +0000468 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +0000469
drhe22a3342003-04-22 20:30:37 +0000470 /* $db authorizer ?CALLBACK?
471 **
472 ** Invoke the given callback to authorize each SQL operation as it is
473 ** compiled. 5 arguments are appended to the callback before it is
474 ** invoked:
475 **
476 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
477 ** (2) First descriptive name (depends on authorization type)
478 ** (3) Second descriptive name
479 ** (4) Name of the database (ex: "main", "temp")
480 ** (5) Name of trigger that is doing the access
481 **
482 ** The callback should return on of the following strings: SQLITE_OK,
483 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
484 **
485 ** If this method is invoked with no arguments, the current authorization
486 ** callback string is returned.
487 */
488 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +0000489#ifdef SQLITE_OMIT_AUTHORIZATION
490 Tcl_AppendResult(interp, "authorization not available in this build", 0);
491 return TCL_ERROR;
492#else
drhe22a3342003-04-22 20:30:37 +0000493 if( objc>3 ){
494 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +0000495 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +0000496 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +0000497 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +0000498 Tcl_AppendResult(interp, pDb->zAuth, 0);
499 }
500 }else{
501 char *zAuth;
502 int len;
503 if( pDb->zAuth ){
504 Tcl_Free(pDb->zAuth);
505 }
506 zAuth = Tcl_GetStringFromObj(objv[2], &len);
507 if( zAuth && len>0 ){
508 pDb->zAuth = Tcl_Alloc( len + 1 );
509 strcpy(pDb->zAuth, zAuth);
510 }else{
511 pDb->zAuth = 0;
512 }
drhe22a3342003-04-22 20:30:37 +0000513 if( pDb->zAuth ){
514 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000515 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +0000516 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000517 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +0000518 }
drhe22a3342003-04-22 20:30:37 +0000519 }
drh1211de32004-07-26 12:24:22 +0000520#endif
drhe22a3342003-04-22 20:30:37 +0000521 break;
522 }
523
drhbec3f402000-08-04 13:49:02 +0000524 /* $db busy ?CALLBACK?
525 **
526 ** Invoke the given callback if an SQL statement attempts to open
527 ** a locked database file.
528 */
drh6d313162000-09-21 13:01:35 +0000529 case DB_BUSY: {
530 if( objc>3 ){
531 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +0000532 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +0000533 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +0000534 if( pDb->zBusy ){
535 Tcl_AppendResult(interp, pDb->zBusy, 0);
536 }
537 }else{
drh6d313162000-09-21 13:01:35 +0000538 char *zBusy;
539 int len;
drhbec3f402000-08-04 13:49:02 +0000540 if( pDb->zBusy ){
541 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +0000542 }
drh6d313162000-09-21 13:01:35 +0000543 zBusy = Tcl_GetStringFromObj(objv[2], &len);
544 if( zBusy && len>0 ){
545 pDb->zBusy = Tcl_Alloc( len + 1 );
546 strcpy(pDb->zBusy, zBusy);
547 }else{
548 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +0000549 }
550 if( pDb->zBusy ){
551 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000552 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +0000553 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000554 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +0000555 }
556 }
drh6d313162000-09-21 13:01:35 +0000557 break;
558 }
drhbec3f402000-08-04 13:49:02 +0000559
drhfb7e7652005-01-24 00:28:42 +0000560 /* $db cache flush
561 ** $db cache size n
562 **
563 ** Flush the prepared statement cache, or set the maximum number of
564 ** cached statements.
565 */
566 case DB_CACHE: {
567 char *subCmd;
568 int n;
569
570 if( objc<=2 ){
571 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
572 return TCL_ERROR;
573 }
574 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
575 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
576 if( objc!=3 ){
577 Tcl_WrongNumArgs(interp, 2, objv, "flush");
578 return TCL_ERROR;
579 }else{
580 flushStmtCache( pDb );
581 }
582 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
583 if( objc!=4 ){
584 Tcl_WrongNumArgs(interp, 2, objv, "size n");
585 return TCL_ERROR;
586 }else{
587 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
588 Tcl_AppendResult( interp, "cannot convert \"",
589 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
590 return TCL_ERROR;
591 }else{
592 if( n<0 ){
593 flushStmtCache( pDb );
594 n = 0;
595 }else if( n>MAX_PREPARED_STMTS ){
596 n = MAX_PREPARED_STMTS;
597 }
598 pDb->maxStmt = n;
599 }
600 }
601 }else{
602 Tcl_AppendResult( interp, "bad option \"",
603 Tcl_GetStringFromObj(objv[0],0), "\": must be flush or size", 0);
604 return TCL_ERROR;
605 }
606 break;
607 }
608
danielk1977b28af712004-06-21 06:50:26 +0000609 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +0000610 **
611 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +0000612 ** the most recent INSERT, UPDATE or DELETE statement, not including
613 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +0000614 */
615 case DB_CHANGES: {
616 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +0000617 if( objc!=2 ){
618 Tcl_WrongNumArgs(interp, 2, objv, "");
619 return TCL_ERROR;
620 }
drhc8d30ac2002-04-12 10:08:59 +0000621 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +0000622 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +0000623 break;
624 }
625
drh75897232000-05-29 14:26:00 +0000626 /* $db close
627 **
628 ** Shutdown the database
629 */
drh6d313162000-09-21 13:01:35 +0000630 case DB_CLOSE: {
631 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
632 break;
633 }
drh75897232000-05-29 14:26:00 +0000634
drhaa940ea2004-01-15 02:44:03 +0000635 /* $db commit_hook ?CALLBACK?
636 **
637 ** Invoke the given callback just before committing every SQL transaction.
638 ** If the callback throws an exception or returns non-zero, then the
639 ** transaction is aborted. If CALLBACK is an empty string, the callback
640 ** is disabled.
641 */
642 case DB_COMMIT_HOOK: {
643 if( objc>3 ){
644 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +0000645 return TCL_ERROR;
drhaa940ea2004-01-15 02:44:03 +0000646 }else if( objc==2 ){
647 if( pDb->zCommit ){
648 Tcl_AppendResult(interp, pDb->zCommit, 0);
649 }
650 }else{
651 char *zCommit;
652 int len;
653 if( pDb->zCommit ){
654 Tcl_Free(pDb->zCommit);
655 }
656 zCommit = Tcl_GetStringFromObj(objv[2], &len);
657 if( zCommit && len>0 ){
658 pDb->zCommit = Tcl_Alloc( len + 1 );
659 strcpy(pDb->zCommit, zCommit);
660 }else{
661 pDb->zCommit = 0;
662 }
663 if( pDb->zCommit ){
664 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000665 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
drhaa940ea2004-01-15 02:44:03 +0000666 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000667 sqlite3_commit_hook(pDb->db, 0, 0);
drhaa940ea2004-01-15 02:44:03 +0000668 }
669 }
670 break;
671 }
672
drh0f14e2e2004-06-29 12:39:08 +0000673 /*
674 ** $db collate NAME SCRIPT
675 **
676 ** Create a new SQL collation function called NAME. Whenever
677 ** that function is called, invoke SCRIPT to evaluate the function.
678 */
679 case DB_COLLATE: {
680 SqlCollate *pCollate;
681 char *zName;
682 char *zScript;
683 int nScript;
684 if( objc!=4 ){
685 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
686 return TCL_ERROR;
687 }
688 zName = Tcl_GetStringFromObj(objv[2], 0);
689 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
690 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
691 if( pCollate==0 ) return TCL_ERROR;
692 pCollate->interp = interp;
693 pCollate->pNext = pDb->pCollate;
694 pCollate->zScript = (char*)&pCollate[1];
695 pDb->pCollate = pCollate;
696 strcpy(pCollate->zScript, zScript);
697 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
698 pCollate, tclSqlCollate) ){
699 return TCL_ERROR;
700 }
701 break;
702 }
703
704 /*
705 ** $db collation_needed SCRIPT
706 **
707 ** Create a new SQL collation function called NAME. Whenever
708 ** that function is called, invoke SCRIPT to evaluate the function.
709 */
710 case DB_COLLATION_NEEDED: {
711 if( objc!=3 ){
712 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
713 return TCL_ERROR;
714 }
715 if( pDb->pCollateNeeded ){
716 Tcl_DecrRefCount(pDb->pCollateNeeded);
717 }
718 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
719 Tcl_IncrRefCount(pDb->pCollateNeeded);
720 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
721 break;
722 }
723
drh75897232000-05-29 14:26:00 +0000724 /* $db complete SQL
725 **
726 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
727 ** additional lines of input are needed. This is similar to the
728 ** built-in "info complete" command of Tcl.
729 */
drh6d313162000-09-21 13:01:35 +0000730 case DB_COMPLETE: {
731 Tcl_Obj *pResult;
732 int isComplete;
733 if( objc!=3 ){
734 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +0000735 return TCL_ERROR;
736 }
danielk19776f8a5032004-05-10 10:34:51 +0000737 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +0000738 pResult = Tcl_GetObjResult(interp);
739 Tcl_SetBooleanObj(pResult, isComplete);
740 break;
741 }
drhdcd997e2003-01-31 17:21:49 +0000742
743 /*
744 ** $db errorcode
745 **
746 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +0000747 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +0000748 */
749 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +0000750 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +0000751 break;
752 }
drh75897232000-05-29 14:26:00 +0000753
754 /*
drh895d7472004-08-20 16:02:39 +0000755 ** $db eval $sql ?array? ?{ ...code... }?
drh1807ce32004-09-07 13:20:35 +0000756 ** $db onecolumn $sql
drh75897232000-05-29 14:26:00 +0000757 **
758 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +0000759 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +0000760 ** If "array" and "code" are omitted, then no callback is every invoked.
761 ** If "array" is an empty string, then the values are placed in variables
762 ** that have the same name as the fields extracted by the query.
drh1807ce32004-09-07 13:20:35 +0000763 **
764 ** The onecolumn method is the equivalent of:
765 ** lindex [$db eval $sql] 0
drh75897232000-05-29 14:26:00 +0000766 */
drh1807ce32004-09-07 13:20:35 +0000767 case DB_ONECOLUMN:
drh6d313162000-09-21 13:01:35 +0000768 case DB_EVAL: {
drh9d74b4c2004-08-24 15:23:34 +0000769 char const *zSql; /* Next SQL statement to execute */
770 char const *zLeft; /* What is left after first stmt in zSql */
771 sqlite3_stmt *pStmt; /* Compiled SQL statment */
drh92febd92004-08-20 18:34:20 +0000772 Tcl_Obj *pArray; /* Name of array into which results are written */
773 Tcl_Obj *pScript; /* Script to run for each result set */
drh1d895032004-08-26 00:56:05 +0000774 Tcl_Obj **apParm; /* Parameters that need a Tcl_DecrRefCount() */
775 int nParm; /* Number of entries used in apParm[] */
776 Tcl_Obj *aParm[10]; /* Static space for apParm[] in the common case */
drh1807ce32004-09-07 13:20:35 +0000777 Tcl_Obj *pRet; /* Value to be returned */
drhfb7e7652005-01-24 00:28:42 +0000778 SqlPreparedStmt *pPreStmt; /* Pointer to a prepared statement */
779 int rc2;
danielk1977ef2cb632004-05-29 02:37:19 +0000780
drh1807ce32004-09-07 13:20:35 +0000781 if( choice==DB_ONECOLUMN ){
782 if( objc!=3 ){
783 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
784 return TCL_ERROR;
785 }
786 pRet = 0;
787 }else{
788 if( objc<3 || objc>5 ){
789 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
790 return TCL_ERROR;
791 }
792 pRet = Tcl_NewObj();
793 Tcl_IncrRefCount(pRet);
danielk197730ccda12004-05-27 12:11:31 +0000794 }
drh92febd92004-08-20 18:34:20 +0000795 if( objc==3 ){
796 pArray = pScript = 0;
797 }else if( objc==4 ){
798 pArray = 0;
799 pScript = objv[3];
800 }else{
801 pArray = objv[3];
802 if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
803 pScript = objv[4];
804 }
danielk197730ccda12004-05-27 12:11:31 +0000805
drh1d895032004-08-26 00:56:05 +0000806 Tcl_IncrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +0000807 zSql = Tcl_GetStringFromObj(objv[2], 0);
drh90b6bb12004-09-13 13:16:31 +0000808 while( rc==TCL_OK && zSql[0] ){
drhfb7e7652005-01-24 00:28:42 +0000809 int i; /* Loop counter */
810 int nVar; /* Number of bind parameters in the pStmt */
811 int nCol; /* Number of columns in the result set */
drh92febd92004-08-20 18:34:20 +0000812 Tcl_Obj **apColName = 0; /* Array of column names */
drhfb7e7652005-01-24 00:28:42 +0000813 int len; /* String length of zSql */
danielk197730ccda12004-05-27 12:11:31 +0000814
drhfb7e7652005-01-24 00:28:42 +0000815 /* Try to find a SQL statement that has already been compiled and
816 ** which matches the next sequence of SQL.
817 */
818 pStmt = 0;
819 pPreStmt = pDb->stmtList;
820 len = strlen(zSql);
821 if( pPreStmt && sqlite3_expired(pPreStmt->pStmt) ){
822 flushStmtCache(pDb);
823 pPreStmt = 0;
danielk197730ccda12004-05-27 12:11:31 +0000824 }
drhfb7e7652005-01-24 00:28:42 +0000825 for(; pPreStmt; pPreStmt=pPreStmt->pNext){
826 int n = pPreStmt->nSql;
827 if( len>=n
828 && memcmp(pPreStmt->zSql, zSql, n)==0
829 && (zSql[n]==0 || zSql[n-1]==';')
830 ){
831 pStmt = pPreStmt->pStmt;
832 zLeft = &zSql[pPreStmt->nSql];
833
834 /* When a prepared statement is found, unlink it from the
835 ** cache list. It will later be added back to the beginning
836 ** of the cache list in order to implement LRU replacement.
837 */
838 if( pPreStmt->pPrev ){
839 pPreStmt->pPrev->pNext = pPreStmt->pNext;
840 }else{
841 pDb->stmtList = pPreStmt->pNext;
842 }
843 if( pPreStmt->pNext ){
844 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
845 }else{
846 pDb->stmtLast = pPreStmt->pPrev;
847 }
848 pDb->nStmt--;
849 break;
850 }
851 }
852
853 /* If no prepared statement was found. Compile the SQL text
854 */
drh92febd92004-08-20 18:34:20 +0000855 if( pStmt==0 ){
drhfb7e7652005-01-24 00:28:42 +0000856 if( SQLITE_OK!=sqlite3_prepare(pDb->db, zSql, -1, &pStmt, &zLeft) ){
drh92febd92004-08-20 18:34:20 +0000857 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
858 rc = TCL_ERROR;
859 break;
danielk197730ccda12004-05-27 12:11:31 +0000860 }
drhfb7e7652005-01-24 00:28:42 +0000861 if( pStmt==0 ){
862 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
863 /* A compile-time error in the statement
864 */
865 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
866 rc = TCL_ERROR;
867 break;
868 }else{
869 /* The statement was a no-op. Continue to the next statement
870 ** in the SQL string.
871 */
872 zSql = zLeft;
873 continue;
874 }
875 }
876 assert( pPreStmt==0 );
danielk197730ccda12004-05-27 12:11:31 +0000877 }
878
drhfb7e7652005-01-24 00:28:42 +0000879 /* Bind values to parameters that begin with $ or :
880 */
drh92febd92004-08-20 18:34:20 +0000881 nVar = sqlite3_bind_parameter_count(pStmt);
drh1d895032004-08-26 00:56:05 +0000882 nParm = 0;
883 if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
884 apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
885 }else{
886 apParm = aParm;
887 }
drh92febd92004-08-20 18:34:20 +0000888 for(i=1; i<=nVar; i++){
889 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
drhc8f90792005-01-12 00:08:24 +0000890 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':') ){
drh92febd92004-08-20 18:34:20 +0000891 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
892 if( pVar ){
893 int n;
894 u8 *data;
895 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
896 char c = zType[0];
897 if( c=='b' && strcmp(zType,"bytearray")==0 ){
898 data = Tcl_GetByteArrayFromObj(pVar, &n);
899 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +0000900 Tcl_IncrRefCount(pVar);
901 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +0000902 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
903 (c=='i' && strcmp(zType,"int")==0) ){
904 Tcl_GetIntFromObj(interp, pVar, &n);
905 sqlite3_bind_int(pStmt, i, n);
906 }else if( c=='d' && strcmp(zType,"double")==0 ){
907 double r;
908 Tcl_GetDoubleFromObj(interp, pVar, &r);
909 sqlite3_bind_double(pStmt, i, r);
910 }else{
911 data = Tcl_GetStringFromObj(pVar, &n);
912 sqlite3_bind_text(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +0000913 Tcl_IncrRefCount(pVar);
914 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +0000915 }
drhfb7e7652005-01-24 00:28:42 +0000916 }else{
917 sqlite3_bind_null( pStmt, i );
drh92febd92004-08-20 18:34:20 +0000918 }
919 }
920 }
drh92febd92004-08-20 18:34:20 +0000921
922 /* Compute column names */
923 nCol = sqlite3_column_count(pStmt);
924 if( pScript ){
925 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
926 if( apColName==0 ) break;
927 for(i=0; i<nCol; i++){
928 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
929 Tcl_IncrRefCount(apColName[i]);
930 }
931 }
932
933 /* If results are being stored in an array variable, then create
934 ** the array(*) entry for that array
935 */
936 if( pArray ){
937 Tcl_Obj *pColList = Tcl_NewObj();
938 Tcl_IncrRefCount(pColList);
939 for(i=0; i<nCol; i++){
940 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
941 }
942 Tcl_ObjSetVar2(interp, pArray, Tcl_NewStringObj("*",-1), pColList,0);
943 }
944
945 /* Execute the SQL
946 */
drh90b6bb12004-09-13 13:16:31 +0000947 while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
drh92febd92004-08-20 18:34:20 +0000948 for(i=0; i<nCol; i++){
danielk197730ccda12004-05-27 12:11:31 +0000949 Tcl_Obj *pVal;
950
951 /* Set pVal to contain the i'th column of this row. */
drh92febd92004-08-20 18:34:20 +0000952 switch( sqlite3_column_type(pStmt, i) ){
953 case SQLITE_BLOB: {
954 int bytes = sqlite3_column_bytes(pStmt, i);
955 pVal = Tcl_NewByteArrayObj(sqlite3_column_blob(pStmt, i), bytes);
956 break;
957 }
958 case SQLITE_INTEGER: {
959 sqlite_int64 v = sqlite3_column_int64(pStmt, i);
960 if( v>=-2147483647 && v<=2147483647 ){
961 pVal = Tcl_NewIntObj(v);
962 }else{
963 pVal = Tcl_NewWideIntObj(v);
964 }
965 break;
966 }
967 case SQLITE_FLOAT: {
968 double r = sqlite3_column_double(pStmt, i);
969 pVal = Tcl_NewDoubleObj(r);
970 break;
971 }
972 default: {
973 pVal = dbTextToObj(sqlite3_column_text(pStmt, i));
974 break;
975 }
danielk197730ccda12004-05-27 12:11:31 +0000976 }
977
drh92febd92004-08-20 18:34:20 +0000978 if( pScript ){
979 if( pArray==0 ){
980 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +0000981 }else{
drh92febd92004-08-20 18:34:20 +0000982 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +0000983 }
drh1807ce32004-09-07 13:20:35 +0000984 }else if( choice==DB_ONECOLUMN ){
985 if( pRet==0 ){
986 pRet = pVal;
987 Tcl_IncrRefCount(pRet);
988 }
drh90b6bb12004-09-13 13:16:31 +0000989 rc = TCL_BREAK;
danielk197730ccda12004-05-27 12:11:31 +0000990 }else{
danielk197730ccda12004-05-27 12:11:31 +0000991 Tcl_ListObjAppendElement(interp, pRet, pVal);
992 }
993 }
994
drh92febd92004-08-20 18:34:20 +0000995 if( pScript ){
996 rc = Tcl_EvalObjEx(interp, pScript, 0);
drh90b6bb12004-09-13 13:16:31 +0000997 if( rc==TCL_CONTINUE ){
998 rc = TCL_OK;
999 }
danielk197730ccda12004-05-27 12:11:31 +00001000 }
1001 }
drh90b6bb12004-09-13 13:16:31 +00001002 if( rc==TCL_BREAK ){
1003 rc = TCL_OK;
1004 }
drh92febd92004-08-20 18:34:20 +00001005
1006 /* Free the column name objects */
1007 if( pScript ){
1008 for(i=0; i<nCol; i++){
1009 Tcl_DecrRefCount(apColName[i]);
1010 }
1011 Tcl_Free((char*)apColName);
1012 }
1013
drh1d895032004-08-26 00:56:05 +00001014 /* Free the bound string and blob parameters */
1015 for(i=0; i<nParm; i++){
1016 Tcl_DecrRefCount(apParm[i]);
1017 }
1018 if( apParm!=aParm ){
1019 Tcl_Free((char*)apParm);
1020 }
1021
drhfb7e7652005-01-24 00:28:42 +00001022 /* Reset the statement. If the result code is SQLITE_SCHEMA, then
1023 ** flush the statement cache and try the statement again.
drh92febd92004-08-20 18:34:20 +00001024 */
drhfb7e7652005-01-24 00:28:42 +00001025 rc2 = sqlite3_reset(pStmt);
1026 if( SQLITE_SCHEMA==rc2 ){
1027 /* After a schema change, flush the cache and try to run the
1028 ** statement again
1029 */
1030 flushStmtCache( pDb );
1031 sqlite3_finalize(pStmt);
1032 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001033 continue;
drhfb7e7652005-01-24 00:28:42 +00001034 }else if( SQLITE_OK!=rc2 ){
1035 /* If a run-time error occurs, report the error and stop reading
1036 ** the SQL
1037 */
danielk1977ef2cb632004-05-29 02:37:19 +00001038 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
drhfb7e7652005-01-24 00:28:42 +00001039 sqlite3_finalize(pStmt);
danielk197730ccda12004-05-27 12:11:31 +00001040 rc = TCL_ERROR;
drhfb7e7652005-01-24 00:28:42 +00001041 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001042 break;
drhfb7e7652005-01-24 00:28:42 +00001043 }else if( pDb->maxStmt<=0 ){
1044 /* If the cache is turned off, deallocated the statement */
1045 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1046 sqlite3_finalize(pStmt);
1047 }else{
1048 /* Everything worked and the cache is operational.
1049 ** Create a new SqlPreparedStmt structure if we need one.
1050 ** (If we already have one we can just reuse it.)
1051 */
1052 if( pPreStmt==0 ){
1053 len = zLeft - zSql;
1054 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) + len );
1055 if( pPreStmt==0 ) return TCL_ERROR;
1056 pPreStmt->pStmt = pStmt;
1057 pPreStmt->nSql = len;
1058 memcpy(pPreStmt->zSql, zSql, len);
1059 pPreStmt->zSql[len] = 0;
1060 }
1061
1062 /* Add the prepared statement to the beginning of the cache list
1063 */
1064 pPreStmt->pNext = pDb->stmtList;
1065 pPreStmt->pPrev = 0;
1066 if( pDb->stmtList ){
1067 pDb->stmtList->pPrev = pPreStmt;
1068 }
1069 pDb->stmtList = pPreStmt;
1070 if( pDb->stmtLast==0 ){
1071 assert( pDb->nStmt==0 );
1072 pDb->stmtLast = pPreStmt;
1073 }else{
1074 assert( pDb->nStmt>0 );
1075 }
1076 pDb->nStmt++;
1077
1078 /* If we have too many statement in cache, remove the surplus from the
1079 ** end of the cache list.
1080 */
1081 while( pDb->nStmt>pDb->maxStmt ){
1082 sqlite3_finalize(pDb->stmtLast->pStmt);
1083 pDb->stmtLast = pDb->stmtLast->pPrev;
1084 Tcl_Free((char*)pDb->stmtLast->pNext);
1085 pDb->stmtLast->pNext = 0;
1086 pDb->nStmt--;
1087 }
danielk197730ccda12004-05-27 12:11:31 +00001088 }
1089
drhfb7e7652005-01-24 00:28:42 +00001090 /* Proceed to the next statement */
danielk197730ccda12004-05-27 12:11:31 +00001091 zSql = zLeft;
1092 }
drh1d895032004-08-26 00:56:05 +00001093 Tcl_DecrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001094
drh1807ce32004-09-07 13:20:35 +00001095 if( pRet ){
1096 if( rc==TCL_OK ){
1097 Tcl_SetObjResult(interp, pRet);
1098 }
1099 Tcl_DecrRefCount(pRet);
danielk197730ccda12004-05-27 12:11:31 +00001100 }
danielk197730ccda12004-05-27 12:11:31 +00001101 break;
1102 }
drhbec3f402000-08-04 13:49:02 +00001103
1104 /*
drhcabb0812002-09-14 13:47:32 +00001105 ** $db function NAME SCRIPT
1106 **
1107 ** Create a new SQL function called NAME. Whenever that function is
1108 ** called, invoke SCRIPT to evaluate the function.
1109 */
1110 case DB_FUNCTION: {
1111 SqlFunc *pFunc;
1112 char *zName;
1113 char *zScript;
1114 int nScript;
1115 if( objc!=4 ){
1116 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1117 return TCL_ERROR;
1118 }
1119 zName = Tcl_GetStringFromObj(objv[2], 0);
1120 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1121 pFunc = (SqlFunc*)Tcl_Alloc( sizeof(*pFunc) + nScript + 1 );
1122 if( pFunc==0 ) return TCL_ERROR;
1123 pFunc->interp = interp;
1124 pFunc->pNext = pDb->pFunc;
1125 pFunc->zScript = (char*)&pFunc[1];
drh0f14e2e2004-06-29 12:39:08 +00001126 pDb->pFunc = pFunc;
drhcabb0812002-09-14 13:47:32 +00001127 strcpy(pFunc->zScript, zScript);
danielk1977c8c11582004-06-29 13:41:21 +00001128 rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00001129 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00001130 if( rc!=SQLITE_OK ){
1131 rc = TCL_ERROR;
1132 }else{
1133 /* Must flush any cached statements */
1134 flushStmtCache( pDb );
1135 }
drhcabb0812002-09-14 13:47:32 +00001136 break;
1137 }
1138
1139 /*
drhaf9ff332002-01-16 21:00:27 +00001140 ** $db last_insert_rowid
1141 **
1142 ** Return an integer which is the ROWID for the most recent insert.
1143 */
1144 case DB_LAST_INSERT_ROWID: {
1145 Tcl_Obj *pResult;
1146 int rowid;
1147 if( objc!=2 ){
1148 Tcl_WrongNumArgs(interp, 2, objv, "");
1149 return TCL_ERROR;
1150 }
danielk19776f8a5032004-05-10 10:34:51 +00001151 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00001152 pResult = Tcl_GetObjResult(interp);
1153 Tcl_SetIntObj(pResult, rowid);
1154 break;
1155 }
1156
1157 /*
drh1807ce32004-09-07 13:20:35 +00001158 ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
drh5d9d7572003-08-19 14:31:01 +00001159 */
drh1807ce32004-09-07 13:20:35 +00001160
1161 /* $db progress ?N CALLBACK?
1162 **
1163 ** Invoke the given callback every N virtual machine opcodes while executing
1164 ** queries.
1165 */
1166 case DB_PROGRESS: {
1167 if( objc==2 ){
1168 if( pDb->zProgress ){
1169 Tcl_AppendResult(interp, pDb->zProgress, 0);
1170 }
1171 }else if( objc==4 ){
1172 char *zProgress;
1173 int len;
1174 int N;
1175 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
1176 return TCL_ERROR;
1177 };
1178 if( pDb->zProgress ){
1179 Tcl_Free(pDb->zProgress);
1180 }
1181 zProgress = Tcl_GetStringFromObj(objv[3], &len);
1182 if( zProgress && len>0 ){
1183 pDb->zProgress = Tcl_Alloc( len + 1 );
1184 strcpy(pDb->zProgress, zProgress);
1185 }else{
1186 pDb->zProgress = 0;
1187 }
1188#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1189 if( pDb->zProgress ){
1190 pDb->interp = interp;
1191 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
1192 }else{
1193 sqlite3_progress_handler(pDb->db, 0, 0, 0);
1194 }
1195#endif
1196 }else{
1197 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00001198 return TCL_ERROR;
1199 }
drh5d9d7572003-08-19 14:31:01 +00001200 break;
1201 }
1202
1203 /*
drh22fbcb82004-02-01 01:22:50 +00001204 ** $db rekey KEY
1205 **
1206 ** Change the encryption key on the currently open database.
1207 */
1208 case DB_REKEY: {
1209 int nKey;
1210 void *pKey;
1211 if( objc!=3 ){
1212 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
1213 return TCL_ERROR;
1214 }
1215 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00001216#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00001217 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00001218 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00001219 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00001220 rc = TCL_ERROR;
1221 }
1222#endif
1223 break;
1224 }
1225
1226 /*
drhbec3f402000-08-04 13:49:02 +00001227 ** $db timeout MILLESECONDS
1228 **
1229 ** Delay for the number of milliseconds specified when a file is locked.
1230 */
drh6d313162000-09-21 13:01:35 +00001231 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00001232 int ms;
drh6d313162000-09-21 13:01:35 +00001233 if( objc!=3 ){
1234 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00001235 return TCL_ERROR;
1236 }
drh6d313162000-09-21 13:01:35 +00001237 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00001238 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00001239 break;
drh75897232000-05-29 14:26:00 +00001240 }
drhb5a20d32003-04-23 12:25:23 +00001241
drh0f14e2e2004-06-29 12:39:08 +00001242 /*
1243 ** $db total_changes
1244 **
1245 ** Return the number of rows that were modified, inserted, or deleted
1246 ** since the database handle was created.
1247 */
1248 case DB_TOTAL_CHANGES: {
1249 Tcl_Obj *pResult;
1250 if( objc!=2 ){
1251 Tcl_WrongNumArgs(interp, 2, objv, "");
1252 return TCL_ERROR;
1253 }
1254 pResult = Tcl_GetObjResult(interp);
1255 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
1256 break;
1257 }
1258
drhb5a20d32003-04-23 12:25:23 +00001259 /* $db trace ?CALLBACK?
1260 **
1261 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
1262 ** that is executed. The text of the SQL is appended to CALLBACK before
1263 ** it is executed.
1264 */
1265 case DB_TRACE: {
1266 if( objc>3 ){
1267 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00001268 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00001269 }else if( objc==2 ){
1270 if( pDb->zTrace ){
1271 Tcl_AppendResult(interp, pDb->zTrace, 0);
1272 }
1273 }else{
1274 char *zTrace;
1275 int len;
1276 if( pDb->zTrace ){
1277 Tcl_Free(pDb->zTrace);
1278 }
1279 zTrace = Tcl_GetStringFromObj(objv[2], &len);
1280 if( zTrace && len>0 ){
1281 pDb->zTrace = Tcl_Alloc( len + 1 );
1282 strcpy(pDb->zTrace, zTrace);
1283 }else{
1284 pDb->zTrace = 0;
1285 }
1286 if( pDb->zTrace ){
1287 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001288 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00001289 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001290 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00001291 }
1292 }
1293 break;
1294 }
1295
tpoindex1067fe12004-12-17 15:41:11 +00001296 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1297 **
1298 ** Copy data into table from filename, optionally using SEPARATOR
1299 ** as column separators. If a column contains a null string, or the
1300 ** value of NULLINDICATOR, a NULL is inserted for the column.
1301 ** conflict-algorithm is one of the sqlite conflict algorithms:
1302 ** rollback, abort, fail, ignore, replace
1303 ** On success, return the number of lines processed, not necessarily same
1304 ** as 'db changes' due to conflict-algorithm selected.
1305 **
1306 ** This code is basically an implementation/enhancement of
1307 ** the sqlite3 shell.c ".import" command.
1308 **
1309 ** This command usage is equivalent to the sqlite2.x COPY statement,
1310 ** which imports file data into a table using the PostgreSQL COPY file format:
1311 ** $db copy $conflit_algo $table_name $filename \t \\N
1312 */
1313 case DB_COPY: {
tpoindex1067fe12004-12-17 15:41:11 +00001314 char *zTable; /* Insert data into this table */
1315 char *zFile; /* The file from which to extract data */
1316 char *zConflict; /* The conflict algorithm to use */
1317 sqlite3_stmt *pStmt; /* A statement */
1318 int rc; /* Result code */
1319 int nCol; /* Number of columns in the table */
1320 int nByte; /* Number of bytes in an SQL string */
1321 int i, j; /* Loop counters */
1322 int nSep; /* Number of bytes in zSep[] */
1323 int nNull; /* Number of bytes in zNull[] */
1324 char *zSql; /* An SQL statement */
1325 char *zLine; /* A single line of input from the file */
1326 char **azCol; /* zLine[] broken up into columns */
1327 char *zCommit; /* How to commit changes */
1328 FILE *in; /* The input file */
1329 int lineno = 0; /* Line number of input file */
1330 char zLineNum[80]; /* Line number print buffer */
1331 Tcl_Obj *pResult; /* interp result */
1332
drh9ee3cdc2004-12-17 20:48:06 +00001333 char *zSep;
1334 char *zNull;
1335 if( objc<5 || objc>7 ){
1336 Tcl_WrongNumArgs(interp, 2, objv,
1337 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1338 return TCL_ERROR;
1339 }
1340 if( objc>=6 ){
1341 zSep = Tcl_GetStringFromObj(objv[5], 0);
1342 }else{
1343 zSep = "\t";
1344 }
1345 if( objc>=7 ){
1346 zNull = Tcl_GetStringFromObj(objv[6], 0);
1347 }else{
1348 zNull = "";
1349 }
tpoindex1067fe12004-12-17 15:41:11 +00001350 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1351 zTable = Tcl_GetStringFromObj(objv[3], 0);
1352 zFile = Tcl_GetStringFromObj(objv[4], 0);
1353 nSep = strlen(zSep);
1354 nNull = strlen(zNull);
1355 if( nSep==0 ){
1356 Tcl_AppendResult(interp, "Error: non-null separator required for copy", 0);
1357 return TCL_ERROR;
1358 }
1359 if(sqlite3StrICmp(zConflict, "rollback") != 0 &&
1360 sqlite3StrICmp(zConflict, "abort" ) != 0 &&
1361 sqlite3StrICmp(zConflict, "fail" ) != 0 &&
1362 sqlite3StrICmp(zConflict, "ignore" ) != 0 &&
1363 sqlite3StrICmp(zConflict, "replace" ) != 0 ) {
drh9ee3cdc2004-12-17 20:48:06 +00001364 Tcl_AppendResult(interp, "Error: \"", zConflict,
1365 "\", conflict-algorithm must be one of: rollback, "
1366 "abort, fail, ignore, or replace", 0);
tpoindex1067fe12004-12-17 15:41:11 +00001367 return TCL_ERROR;
1368 }
1369 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1370 if( zSql==0 ){
1371 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1372 return TCL_ERROR;
1373 }
1374 nByte = strlen(zSql);
1375 rc = sqlite3_prepare(pDb->db, zSql, 0, &pStmt, 0);
1376 sqlite3_free(zSql);
1377 if( rc ){
1378 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1379 nCol = 0;
1380 }else{
1381 nCol = sqlite3_column_count(pStmt);
1382 }
1383 sqlite3_finalize(pStmt);
1384 if( nCol==0 ) {
1385 return TCL_ERROR;
1386 }
1387 zSql = malloc( nByte + 50 + nCol*2 );
1388 if( zSql==0 ) {
1389 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1390 return TCL_ERROR;
1391 }
drh9ee3cdc2004-12-17 20:48:06 +00001392 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1393 zConflict, zTable);
tpoindex1067fe12004-12-17 15:41:11 +00001394 j = strlen(zSql);
1395 for(i=1; i<nCol; i++){
1396 zSql[j++] = ',';
1397 zSql[j++] = '?';
1398 }
1399 zSql[j++] = ')';
1400 zSql[j] = 0;
1401 rc = sqlite3_prepare(pDb->db, zSql, 0, &pStmt, 0);
1402 free(zSql);
1403 if( rc ){
1404 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1405 sqlite3_finalize(pStmt);
1406 return TCL_ERROR;
1407 }
1408 in = fopen(zFile, "rb");
1409 if( in==0 ){
1410 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
1411 sqlite3_finalize(pStmt);
1412 return TCL_ERROR;
1413 }
1414 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1415 if( azCol==0 ) {
1416 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1417 return TCL_ERROR;
1418 }
1419 sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
1420 zCommit = "COMMIT";
1421 while( (zLine = local_getline(0, in))!=0 ){
1422 char *z;
1423 i = 0;
1424 lineno++;
1425 azCol[0] = zLine;
1426 for(i=0, z=zLine; *z; z++){
1427 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
1428 *z = 0;
1429 i++;
1430 if( i<nCol ){
1431 azCol[i] = &z[nSep];
1432 z += nSep-1;
1433 }
1434 }
1435 }
1436 if( i+1!=nCol ){
1437 char *zErr;
1438 zErr = malloc(200 + strlen(zFile));
1439 sprintf(zErr,"Error: %s line %d: expected %d columns of data but found %d",
1440 zFile, lineno, nCol, i+1);
1441 Tcl_AppendResult(interp, zErr, 0);
1442 free(zErr);
1443 zCommit = "ROLLBACK";
1444 break;
1445 }
1446 for(i=0; i<nCol; i++){
1447 /* check for null data, if so, bind as null */
1448 if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
1449 sqlite3_bind_null(pStmt, i+1);
1450 }else{
1451 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1452 }
1453 }
1454 sqlite3_step(pStmt);
1455 rc = sqlite3_reset(pStmt);
1456 free(zLine);
1457 if( rc!=SQLITE_OK ){
1458 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
1459 zCommit = "ROLLBACK";
1460 break;
1461 }
1462 }
1463 free(azCol);
1464 fclose(in);
1465 sqlite3_finalize(pStmt);
1466 sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
1467
1468 if( zCommit[0] == 'C' ){
1469 /* success, set result as number of lines processed */
1470 pResult = Tcl_GetObjResult(interp);
1471 Tcl_SetIntObj(pResult, lineno);
1472 rc = TCL_OK;
1473 }else{
1474 /* failure, append lineno where failed */
1475 sprintf(zLineNum,"%d",lineno);
1476 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
1477 rc = TCL_ERROR;
1478 }
1479 break;
1480 }
1481
danielk19774397de52005-01-12 12:44:03 +00001482 /* $db version
1483 **
1484 ** Return the version string for this database.
1485 */
1486 case DB_VERSION: {
1487 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
1488 break;
1489 }
1490
tpoindex1067fe12004-12-17 15:41:11 +00001491
drh6d313162000-09-21 13:01:35 +00001492 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00001493 return rc;
drh75897232000-05-29 14:26:00 +00001494}
1495
1496/*
drh9bb575f2004-09-06 17:24:11 +00001497** sqlite3 DBNAME FILENAME ?MODE? ?-key KEY?
drh75897232000-05-29 14:26:00 +00001498**
1499** This is the main Tcl command. When the "sqlite" Tcl command is
1500** invoked, this routine runs to process that command.
1501**
1502** The first argument, DBNAME, is an arbitrary name for a new
1503** database connection. This command creates a new command named
1504** DBNAME that is used to control that connection. The database
1505** connection is deleted when the DBNAME command is deleted.
1506**
1507** The second argument is the name of the directory that contains
1508** the sqlite database that is to be accessed.
drhfbc3eab2001-04-06 16:13:42 +00001509**
1510** For testing purposes, we also support the following:
1511**
drh9bb575f2004-09-06 17:24:11 +00001512** sqlite3 -encoding
drhfbc3eab2001-04-06 16:13:42 +00001513**
1514** Return the encoding used by LIKE and GLOB operators. Choices
1515** are UTF-8 and iso8859.
1516**
drh9bb575f2004-09-06 17:24:11 +00001517** sqlite3 -version
drh647cb0e2002-11-04 19:32:25 +00001518**
1519** Return the version number of the SQLite library.
1520**
drh9bb575f2004-09-06 17:24:11 +00001521** sqlite3 -tcl-uses-utf
drhfbc3eab2001-04-06 16:13:42 +00001522**
1523** Return "1" if compiled with a Tcl uses UTF-8. Return "0" if
1524** not. Used by tests to make sure the library was compiled
1525** correctly.
drh75897232000-05-29 14:26:00 +00001526*/
drh22fbcb82004-02-01 01:22:50 +00001527static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001528 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00001529 void *pKey = 0;
1530 int nKey = 0;
1531 const char *zArg;
drh75897232000-05-29 14:26:00 +00001532 char *zErrMsg;
drh22fbcb82004-02-01 01:22:50 +00001533 const char *zFile;
drh06b27182002-06-26 20:06:05 +00001534 char zBuf[80];
drh22fbcb82004-02-01 01:22:50 +00001535 if( objc==2 ){
1536 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00001537 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00001538 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00001539 return TCL_OK;
1540 }
drh9eb9e262004-02-11 02:18:05 +00001541 if( strcmp(zArg,"-has-codec")==0 ){
1542#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00001543 Tcl_AppendResult(interp,"1",0);
1544#else
1545 Tcl_AppendResult(interp,"0",0);
1546#endif
1547 return TCL_OK;
1548 }
1549 if( strcmp(zArg,"-tcl-uses-utf")==0 ){
drhfbc3eab2001-04-06 16:13:42 +00001550#ifdef TCL_UTF_MAX
1551 Tcl_AppendResult(interp,"1",0);
1552#else
1553 Tcl_AppendResult(interp,"0",0);
1554#endif
1555 return TCL_OK;
1556 }
1557 }
drh22fbcb82004-02-01 01:22:50 +00001558 if( objc==5 || objc==6 ){
1559 zArg = Tcl_GetStringFromObj(objv[objc-2], 0);
1560 if( strcmp(zArg,"-key")==0 ){
1561 pKey = Tcl_GetByteArrayFromObj(objv[objc-1], &nKey);
1562 objc -= 2;
1563 }
1564 }
1565 if( objc!=3 && objc!=4 ){
1566 Tcl_WrongNumArgs(interp, 1, objv,
drh9eb9e262004-02-11 02:18:05 +00001567#ifdef SQLITE_HAS_CODEC
1568 "HANDLE FILENAME ?-key CODEC-KEY?"
drh22fbcb82004-02-01 01:22:50 +00001569#else
1570 "HANDLE FILENAME ?MODE?"
1571#endif
1572 );
drh75897232000-05-29 14:26:00 +00001573 return TCL_ERROR;
1574 }
drh75897232000-05-29 14:26:00 +00001575 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00001576 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00001577 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00001578 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
1579 return TCL_ERROR;
1580 }
1581 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00001582 zFile = Tcl_GetStringFromObj(objv[2], 0);
danielk19774f057f92004-06-08 00:02:33 +00001583 sqlite3_open(zFile, &p->db);
danielk197780290862004-05-22 09:21:21 +00001584 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
1585 zErrMsg = strdup(sqlite3_errmsg(p->db));
1586 sqlite3_close(p->db);
1587 p->db = 0;
1588 }
drh2011d5f2004-07-22 02:40:37 +00001589#ifdef SQLITE_HAS_CODEC
1590 sqlite3_key(p->db, pKey, nKey);
drheb8ed702004-02-11 10:37:23 +00001591#endif
drhbec3f402000-08-04 13:49:02 +00001592 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00001593 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00001594 Tcl_Free((char*)p);
drh75897232000-05-29 14:26:00 +00001595 free(zErrMsg);
1596 return TCL_ERROR;
1597 }
drhfb7e7652005-01-24 00:28:42 +00001598 p->maxStmt = NUM_PREPARED_STMTS;
drh22fbcb82004-02-01 01:22:50 +00001599 zArg = Tcl_GetStringFromObj(objv[1], 0);
1600 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
drhc22bd472002-05-10 13:14:07 +00001601
drh06b27182002-06-26 20:06:05 +00001602 /* The return value is the value of the sqlite* pointer
1603 */
1604 sprintf(zBuf, "%p", p->db);
drh5e5377f2002-07-07 17:12:36 +00001605 if( strncmp(zBuf,"0x",2) ){
1606 sprintf(zBuf, "0x%p", p->db);
1607 }
drh06b27182002-06-26 20:06:05 +00001608 Tcl_AppendResult(interp, zBuf, 0);
1609
drhc22bd472002-05-10 13:14:07 +00001610 /* If compiled with SQLITE_TEST turned on, then register the "md5sum"
drh06b27182002-06-26 20:06:05 +00001611 ** SQL function.
drhc22bd472002-05-10 13:14:07 +00001612 */
drh28b4e482002-03-11 02:06:13 +00001613#ifdef SQLITE_TEST
1614 {
drh9bb575f2004-09-06 17:24:11 +00001615 extern void Md5_Register(sqlite3*);
drh3b93bc82005-01-13 23:54:32 +00001616#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00001617 int mallocfail = sqlite3_iMallocFail;
1618 sqlite3_iMallocFail = 0;
danielk19775b59af82004-06-30 12:42:59 +00001619#endif
drhc22bd472002-05-10 13:14:07 +00001620 Md5_Register(p->db);
drh3b93bc82005-01-13 23:54:32 +00001621#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00001622 sqlite3_iMallocFail = mallocfail;
danielk19775b59af82004-06-30 12:42:59 +00001623#endif
drh06b27182002-06-26 20:06:05 +00001624 }
drh28b4e482002-03-11 02:06:13 +00001625#endif
danielk19777cedc8d2004-06-10 10:50:08 +00001626 p->interp = interp;
drh75897232000-05-29 14:26:00 +00001627 return TCL_OK;
1628}
1629
1630/*
drh90ca9752001-09-28 17:47:14 +00001631** Provide a dummy Tcl_InitStubs if we are using this as a static
1632** library.
1633*/
1634#ifndef USE_TCL_STUBS
1635# undef Tcl_InitStubs
1636# define Tcl_InitStubs(a,b,c)
1637#endif
1638
1639/*
drh75897232000-05-29 14:26:00 +00001640** Initialize this module.
1641**
1642** This Tcl module contains only a single new Tcl command named "sqlite".
1643** (Hence there is no namespace. There is no point in using a namespace
1644** if the extension only supplies one new name!) The "sqlite" command is
1645** used to open a new SQLite database. See the DbMain() routine above
1646** for additional information.
1647*/
drh38f82712004-06-18 17:10:16 +00001648int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00001649 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00001650 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
1651 Tcl_PkgProvide(interp, "sqlite3", "3.0");
drh49766d62005-01-08 18:42:28 +00001652 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
1653 Tcl_PkgProvide(interp, "sqlite", "3.0");
drh90ca9752001-09-28 17:47:14 +00001654 return TCL_OK;
1655}
drh49766d62005-01-08 18:42:28 +00001656int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
1657int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
1658int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
1659
1660#ifndef SQLITE_3_SUFFIX_ONLY
1661int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
1662int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
1663int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
1664int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
1665#endif
drh75897232000-05-29 14:26:00 +00001666
drh3e27c022004-07-23 00:01:38 +00001667#ifdef TCLSH
1668/*****************************************************************************
1669** The code that follows is used to build standalone TCL interpreters
drh75897232000-05-29 14:26:00 +00001670*/
drh348784e2000-05-29 20:41:49 +00001671
1672/*
drh3e27c022004-07-23 00:01:38 +00001673** If the macro TCLSH is one, then put in code this for the
1674** "main" routine that will initialize Tcl and take input from
1675** standard input.
drh348784e2000-05-29 20:41:49 +00001676*/
drh3e27c022004-07-23 00:01:38 +00001677#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00001678static char zMainloop[] =
1679 "set line {}\n"
1680 "while {![eof stdin]} {\n"
1681 "if {$line!=\"\"} {\n"
1682 "puts -nonewline \"> \"\n"
1683 "} else {\n"
1684 "puts -nonewline \"% \"\n"
1685 "}\n"
1686 "flush stdout\n"
1687 "append line [gets stdin]\n"
1688 "if {[info complete $line]} {\n"
1689 "if {[catch {uplevel #0 $line} result]} {\n"
1690 "puts stderr \"Error: $result\"\n"
1691 "} elseif {$result!=\"\"} {\n"
1692 "puts $result\n"
1693 "}\n"
1694 "set line {}\n"
1695 "} else {\n"
1696 "append line \\n\n"
1697 "}\n"
1698 "}\n"
1699;
drh3e27c022004-07-23 00:01:38 +00001700#endif
1701
1702/*
1703** If the macro TCLSH is two, then get the main loop code out of
1704** the separate file "spaceanal_tcl.h".
1705*/
1706#if TCLSH==2
1707static char zMainloop[] =
1708#include "spaceanal_tcl.h"
1709;
1710#endif
drh348784e2000-05-29 20:41:49 +00001711
1712#define TCLSH_MAIN main /* Needed to fake out mktclapp */
1713int TCLSH_MAIN(int argc, char **argv){
1714 Tcl_Interp *interp;
drh297ecf12001-04-05 15:57:13 +00001715 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00001716 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00001717 Sqlite3_Init(interp);
drhd9b02572001-04-15 00:37:09 +00001718#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00001719 {
1720 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00001721 extern int Sqlitetest2_Init(Tcl_Interp*);
1722 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00001723 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00001724 extern int Sqlitetest5_Init(Tcl_Interp*);
drhefc251d2001-07-01 22:12:01 +00001725 extern int Md5_Init(Tcl_Interp*);
danielk19776490beb2004-05-11 06:17:21 +00001726 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00001727 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00001728 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00001729 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00001730 Sqlitetest5_Init(interp);
drhefc251d2001-07-01 22:12:01 +00001731 Md5_Init(interp);
drhd1bf3512001-04-07 15:24:33 +00001732 }
1733#endif
drh3e27c022004-07-23 00:01:38 +00001734 if( argc>=2 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00001735 int i;
1736 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
1737 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00001738 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00001739 Tcl_SetVar(interp, "argv", argv[i],
1740 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
1741 }
drh3e27c022004-07-23 00:01:38 +00001742 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00001743 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drhc61053b2000-06-04 12:58:36 +00001744 if( zInfo==0 ) zInfo = interp->result;
1745 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00001746 return 1;
1747 }
drh3e27c022004-07-23 00:01:38 +00001748 }
1749 if( argc<=1 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00001750 Tcl_GlobalEval(interp, zMainloop);
1751 }
1752 return 0;
1753}
1754#endif /* TCLSH */
drh6d313162000-09-21 13:01:35 +00001755
1756#endif /* !defined(NO_TCL) */