blob: 3196793e78dfeec15d3fa4eaa84905e6239e90f8 [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**
drhccae6022005-02-26 17:31:26 +000014** $Id: tclsqlite.c,v 1.119 2005/02/26 17:31:27 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
danielk1977a21c6b62005-01-24 10:25:59 +000025#define NUM_PREPARED_STMTS 10
drhfb7e7652005-01-24 00:28:42 +000026#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) ){
danielk19779636c4e2005-01-25 04:27:54 +0000699 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +0000700 return TCL_ERROR;
701 }
702 break;
703 }
704
705 /*
706 ** $db collation_needed SCRIPT
707 **
708 ** Create a new SQL collation function called NAME. Whenever
709 ** that function is called, invoke SCRIPT to evaluate the function.
710 */
711 case DB_COLLATION_NEEDED: {
712 if( objc!=3 ){
713 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
714 return TCL_ERROR;
715 }
716 if( pDb->pCollateNeeded ){
717 Tcl_DecrRefCount(pDb->pCollateNeeded);
718 }
719 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
720 Tcl_IncrRefCount(pDb->pCollateNeeded);
721 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
722 break;
723 }
724
drh75897232000-05-29 14:26:00 +0000725 /* $db complete SQL
726 **
727 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
728 ** additional lines of input are needed. This is similar to the
729 ** built-in "info complete" command of Tcl.
730 */
drh6d313162000-09-21 13:01:35 +0000731 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +0000732#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +0000733 Tcl_Obj *pResult;
734 int isComplete;
735 if( objc!=3 ){
736 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +0000737 return TCL_ERROR;
738 }
danielk19776f8a5032004-05-10 10:34:51 +0000739 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +0000740 pResult = Tcl_GetObjResult(interp);
741 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +0000742#endif
drh6d313162000-09-21 13:01:35 +0000743 break;
744 }
drhdcd997e2003-01-31 17:21:49 +0000745
746 /*
747 ** $db errorcode
748 **
749 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +0000750 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +0000751 */
752 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +0000753 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +0000754 break;
755 }
drh75897232000-05-29 14:26:00 +0000756
757 /*
drh895d7472004-08-20 16:02:39 +0000758 ** $db eval $sql ?array? ?{ ...code... }?
drh1807ce32004-09-07 13:20:35 +0000759 ** $db onecolumn $sql
drh75897232000-05-29 14:26:00 +0000760 **
761 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +0000762 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +0000763 ** If "array" and "code" are omitted, then no callback is every invoked.
764 ** If "array" is an empty string, then the values are placed in variables
765 ** that have the same name as the fields extracted by the query.
drh1807ce32004-09-07 13:20:35 +0000766 **
767 ** The onecolumn method is the equivalent of:
768 ** lindex [$db eval $sql] 0
drh75897232000-05-29 14:26:00 +0000769 */
drh1807ce32004-09-07 13:20:35 +0000770 case DB_ONECOLUMN:
drh6d313162000-09-21 13:01:35 +0000771 case DB_EVAL: {
drh9d74b4c2004-08-24 15:23:34 +0000772 char const *zSql; /* Next SQL statement to execute */
773 char const *zLeft; /* What is left after first stmt in zSql */
774 sqlite3_stmt *pStmt; /* Compiled SQL statment */
drh92febd92004-08-20 18:34:20 +0000775 Tcl_Obj *pArray; /* Name of array into which results are written */
776 Tcl_Obj *pScript; /* Script to run for each result set */
drh1d895032004-08-26 00:56:05 +0000777 Tcl_Obj **apParm; /* Parameters that need a Tcl_DecrRefCount() */
778 int nParm; /* Number of entries used in apParm[] */
779 Tcl_Obj *aParm[10]; /* Static space for apParm[] in the common case */
drh1807ce32004-09-07 13:20:35 +0000780 Tcl_Obj *pRet; /* Value to be returned */
drhfb7e7652005-01-24 00:28:42 +0000781 SqlPreparedStmt *pPreStmt; /* Pointer to a prepared statement */
782 int rc2;
danielk1977ef2cb632004-05-29 02:37:19 +0000783
drh1807ce32004-09-07 13:20:35 +0000784 if( choice==DB_ONECOLUMN ){
785 if( objc!=3 ){
786 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
787 return TCL_ERROR;
788 }
789 pRet = 0;
790 }else{
791 if( objc<3 || objc>5 ){
792 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
793 return TCL_ERROR;
794 }
795 pRet = Tcl_NewObj();
796 Tcl_IncrRefCount(pRet);
danielk197730ccda12004-05-27 12:11:31 +0000797 }
drh92febd92004-08-20 18:34:20 +0000798 if( objc==3 ){
799 pArray = pScript = 0;
800 }else if( objc==4 ){
801 pArray = 0;
802 pScript = objv[3];
803 }else{
804 pArray = objv[3];
805 if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
806 pScript = objv[4];
807 }
danielk197730ccda12004-05-27 12:11:31 +0000808
drh1d895032004-08-26 00:56:05 +0000809 Tcl_IncrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +0000810 zSql = Tcl_GetStringFromObj(objv[2], 0);
drh90b6bb12004-09-13 13:16:31 +0000811 while( rc==TCL_OK && zSql[0] ){
drhfb7e7652005-01-24 00:28:42 +0000812 int i; /* Loop counter */
813 int nVar; /* Number of bind parameters in the pStmt */
814 int nCol; /* Number of columns in the result set */
drh92febd92004-08-20 18:34:20 +0000815 Tcl_Obj **apColName = 0; /* Array of column names */
drhfb7e7652005-01-24 00:28:42 +0000816 int len; /* String length of zSql */
danielk197730ccda12004-05-27 12:11:31 +0000817
drhfb7e7652005-01-24 00:28:42 +0000818 /* Try to find a SQL statement that has already been compiled and
819 ** which matches the next sequence of SQL.
820 */
821 pStmt = 0;
822 pPreStmt = pDb->stmtList;
823 len = strlen(zSql);
824 if( pPreStmt && sqlite3_expired(pPreStmt->pStmt) ){
825 flushStmtCache(pDb);
826 pPreStmt = 0;
danielk197730ccda12004-05-27 12:11:31 +0000827 }
drhfb7e7652005-01-24 00:28:42 +0000828 for(; pPreStmt; pPreStmt=pPreStmt->pNext){
829 int n = pPreStmt->nSql;
830 if( len>=n
831 && memcmp(pPreStmt->zSql, zSql, n)==0
832 && (zSql[n]==0 || zSql[n-1]==';')
833 ){
834 pStmt = pPreStmt->pStmt;
835 zLeft = &zSql[pPreStmt->nSql];
836
837 /* When a prepared statement is found, unlink it from the
838 ** cache list. It will later be added back to the beginning
839 ** of the cache list in order to implement LRU replacement.
840 */
841 if( pPreStmt->pPrev ){
842 pPreStmt->pPrev->pNext = pPreStmt->pNext;
843 }else{
844 pDb->stmtList = pPreStmt->pNext;
845 }
846 if( pPreStmt->pNext ){
847 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
848 }else{
849 pDb->stmtLast = pPreStmt->pPrev;
850 }
851 pDb->nStmt--;
852 break;
853 }
854 }
855
856 /* If no prepared statement was found. Compile the SQL text
857 */
drh92febd92004-08-20 18:34:20 +0000858 if( pStmt==0 ){
drhfb7e7652005-01-24 00:28:42 +0000859 if( SQLITE_OK!=sqlite3_prepare(pDb->db, zSql, -1, &pStmt, &zLeft) ){
drh92febd92004-08-20 18:34:20 +0000860 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
861 rc = TCL_ERROR;
862 break;
danielk197730ccda12004-05-27 12:11:31 +0000863 }
drhfb7e7652005-01-24 00:28:42 +0000864 if( pStmt==0 ){
865 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
866 /* A compile-time error in the statement
867 */
868 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
869 rc = TCL_ERROR;
870 break;
871 }else{
872 /* The statement was a no-op. Continue to the next statement
873 ** in the SQL string.
874 */
875 zSql = zLeft;
876 continue;
877 }
878 }
879 assert( pPreStmt==0 );
danielk197730ccda12004-05-27 12:11:31 +0000880 }
881
drhfb7e7652005-01-24 00:28:42 +0000882 /* Bind values to parameters that begin with $ or :
883 */
drh92febd92004-08-20 18:34:20 +0000884 nVar = sqlite3_bind_parameter_count(pStmt);
drh1d895032004-08-26 00:56:05 +0000885 nParm = 0;
886 if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
887 apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
888 }else{
889 apParm = aParm;
890 }
drh92febd92004-08-20 18:34:20 +0000891 for(i=1; i<=nVar; i++){
892 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
drhc8f90792005-01-12 00:08:24 +0000893 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':') ){
drh92febd92004-08-20 18:34:20 +0000894 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
895 if( pVar ){
896 int n;
897 u8 *data;
898 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
899 char c = zType[0];
900 if( c=='b' && strcmp(zType,"bytearray")==0 ){
901 data = Tcl_GetByteArrayFromObj(pVar, &n);
902 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +0000903 Tcl_IncrRefCount(pVar);
904 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +0000905 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
906 (c=='i' && strcmp(zType,"int")==0) ){
907 Tcl_GetIntFromObj(interp, pVar, &n);
908 sqlite3_bind_int(pStmt, i, n);
909 }else if( c=='d' && strcmp(zType,"double")==0 ){
910 double r;
911 Tcl_GetDoubleFromObj(interp, pVar, &r);
912 sqlite3_bind_double(pStmt, i, r);
913 }else{
914 data = Tcl_GetStringFromObj(pVar, &n);
915 sqlite3_bind_text(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +0000916 Tcl_IncrRefCount(pVar);
917 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +0000918 }
drhfb7e7652005-01-24 00:28:42 +0000919 }else{
920 sqlite3_bind_null( pStmt, i );
drh92febd92004-08-20 18:34:20 +0000921 }
922 }
923 }
drh92febd92004-08-20 18:34:20 +0000924
925 /* Compute column names */
926 nCol = sqlite3_column_count(pStmt);
927 if( pScript ){
928 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
929 if( apColName==0 ) break;
930 for(i=0; i<nCol; i++){
931 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
932 Tcl_IncrRefCount(apColName[i]);
933 }
934 }
935
936 /* If results are being stored in an array variable, then create
937 ** the array(*) entry for that array
938 */
939 if( pArray ){
940 Tcl_Obj *pColList = Tcl_NewObj();
941 Tcl_IncrRefCount(pColList);
942 for(i=0; i<nCol; i++){
943 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
944 }
945 Tcl_ObjSetVar2(interp, pArray, Tcl_NewStringObj("*",-1), pColList,0);
946 }
947
948 /* Execute the SQL
949 */
drh90b6bb12004-09-13 13:16:31 +0000950 while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
drh92febd92004-08-20 18:34:20 +0000951 for(i=0; i<nCol; i++){
danielk197730ccda12004-05-27 12:11:31 +0000952 Tcl_Obj *pVal;
953
954 /* Set pVal to contain the i'th column of this row. */
drh92febd92004-08-20 18:34:20 +0000955 switch( sqlite3_column_type(pStmt, i) ){
956 case SQLITE_BLOB: {
957 int bytes = sqlite3_column_bytes(pStmt, i);
958 pVal = Tcl_NewByteArrayObj(sqlite3_column_blob(pStmt, i), bytes);
959 break;
960 }
961 case SQLITE_INTEGER: {
962 sqlite_int64 v = sqlite3_column_int64(pStmt, i);
963 if( v>=-2147483647 && v<=2147483647 ){
964 pVal = Tcl_NewIntObj(v);
965 }else{
966 pVal = Tcl_NewWideIntObj(v);
967 }
968 break;
969 }
970 case SQLITE_FLOAT: {
971 double r = sqlite3_column_double(pStmt, i);
972 pVal = Tcl_NewDoubleObj(r);
973 break;
974 }
975 default: {
976 pVal = dbTextToObj(sqlite3_column_text(pStmt, i));
977 break;
978 }
danielk197730ccda12004-05-27 12:11:31 +0000979 }
980
drh92febd92004-08-20 18:34:20 +0000981 if( pScript ){
982 if( pArray==0 ){
983 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +0000984 }else{
drh92febd92004-08-20 18:34:20 +0000985 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +0000986 }
drh1807ce32004-09-07 13:20:35 +0000987 }else if( choice==DB_ONECOLUMN ){
988 if( pRet==0 ){
989 pRet = pVal;
990 Tcl_IncrRefCount(pRet);
991 }
drh90b6bb12004-09-13 13:16:31 +0000992 rc = TCL_BREAK;
danielk197730ccda12004-05-27 12:11:31 +0000993 }else{
danielk197730ccda12004-05-27 12:11:31 +0000994 Tcl_ListObjAppendElement(interp, pRet, pVal);
995 }
996 }
997
drh92febd92004-08-20 18:34:20 +0000998 if( pScript ){
999 rc = Tcl_EvalObjEx(interp, pScript, 0);
drh90b6bb12004-09-13 13:16:31 +00001000 if( rc==TCL_CONTINUE ){
1001 rc = TCL_OK;
1002 }
danielk197730ccda12004-05-27 12:11:31 +00001003 }
1004 }
drh90b6bb12004-09-13 13:16:31 +00001005 if( rc==TCL_BREAK ){
1006 rc = TCL_OK;
1007 }
drh92febd92004-08-20 18:34:20 +00001008
1009 /* Free the column name objects */
1010 if( pScript ){
1011 for(i=0; i<nCol; i++){
1012 Tcl_DecrRefCount(apColName[i]);
1013 }
1014 Tcl_Free((char*)apColName);
1015 }
1016
drh1d895032004-08-26 00:56:05 +00001017 /* Free the bound string and blob parameters */
1018 for(i=0; i<nParm; i++){
1019 Tcl_DecrRefCount(apParm[i]);
1020 }
1021 if( apParm!=aParm ){
1022 Tcl_Free((char*)apParm);
1023 }
1024
drhfb7e7652005-01-24 00:28:42 +00001025 /* Reset the statement. If the result code is SQLITE_SCHEMA, then
1026 ** flush the statement cache and try the statement again.
drh92febd92004-08-20 18:34:20 +00001027 */
drhfb7e7652005-01-24 00:28:42 +00001028 rc2 = sqlite3_reset(pStmt);
1029 if( SQLITE_SCHEMA==rc2 ){
1030 /* After a schema change, flush the cache and try to run the
1031 ** statement again
1032 */
1033 flushStmtCache( pDb );
1034 sqlite3_finalize(pStmt);
1035 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001036 continue;
drhfb7e7652005-01-24 00:28:42 +00001037 }else if( SQLITE_OK!=rc2 ){
1038 /* If a run-time error occurs, report the error and stop reading
1039 ** the SQL
1040 */
danielk1977ef2cb632004-05-29 02:37:19 +00001041 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
drhfb7e7652005-01-24 00:28:42 +00001042 sqlite3_finalize(pStmt);
danielk197730ccda12004-05-27 12:11:31 +00001043 rc = TCL_ERROR;
drhfb7e7652005-01-24 00:28:42 +00001044 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001045 break;
drhfb7e7652005-01-24 00:28:42 +00001046 }else if( pDb->maxStmt<=0 ){
1047 /* If the cache is turned off, deallocated the statement */
1048 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1049 sqlite3_finalize(pStmt);
1050 }else{
1051 /* Everything worked and the cache is operational.
1052 ** Create a new SqlPreparedStmt structure if we need one.
1053 ** (If we already have one we can just reuse it.)
1054 */
1055 if( pPreStmt==0 ){
1056 len = zLeft - zSql;
1057 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) + len );
1058 if( pPreStmt==0 ) return TCL_ERROR;
1059 pPreStmt->pStmt = pStmt;
1060 pPreStmt->nSql = len;
1061 memcpy(pPreStmt->zSql, zSql, len);
1062 pPreStmt->zSql[len] = 0;
1063 }
1064
1065 /* Add the prepared statement to the beginning of the cache list
1066 */
1067 pPreStmt->pNext = pDb->stmtList;
1068 pPreStmt->pPrev = 0;
1069 if( pDb->stmtList ){
1070 pDb->stmtList->pPrev = pPreStmt;
1071 }
1072 pDb->stmtList = pPreStmt;
1073 if( pDb->stmtLast==0 ){
1074 assert( pDb->nStmt==0 );
1075 pDb->stmtLast = pPreStmt;
1076 }else{
1077 assert( pDb->nStmt>0 );
1078 }
1079 pDb->nStmt++;
1080
1081 /* If we have too many statement in cache, remove the surplus from the
1082 ** end of the cache list.
1083 */
1084 while( pDb->nStmt>pDb->maxStmt ){
1085 sqlite3_finalize(pDb->stmtLast->pStmt);
1086 pDb->stmtLast = pDb->stmtLast->pPrev;
1087 Tcl_Free((char*)pDb->stmtLast->pNext);
1088 pDb->stmtLast->pNext = 0;
1089 pDb->nStmt--;
1090 }
danielk197730ccda12004-05-27 12:11:31 +00001091 }
1092
drhfb7e7652005-01-24 00:28:42 +00001093 /* Proceed to the next statement */
danielk197730ccda12004-05-27 12:11:31 +00001094 zSql = zLeft;
1095 }
drh1d895032004-08-26 00:56:05 +00001096 Tcl_DecrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001097
drh1807ce32004-09-07 13:20:35 +00001098 if( pRet ){
1099 if( rc==TCL_OK ){
1100 Tcl_SetObjResult(interp, pRet);
1101 }
1102 Tcl_DecrRefCount(pRet);
danielk197730ccda12004-05-27 12:11:31 +00001103 }
danielk197730ccda12004-05-27 12:11:31 +00001104 break;
1105 }
drhbec3f402000-08-04 13:49:02 +00001106
1107 /*
drhcabb0812002-09-14 13:47:32 +00001108 ** $db function NAME SCRIPT
1109 **
1110 ** Create a new SQL function called NAME. Whenever that function is
1111 ** called, invoke SCRIPT to evaluate the function.
1112 */
1113 case DB_FUNCTION: {
1114 SqlFunc *pFunc;
1115 char *zName;
1116 char *zScript;
1117 int nScript;
1118 if( objc!=4 ){
1119 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1120 return TCL_ERROR;
1121 }
1122 zName = Tcl_GetStringFromObj(objv[2], 0);
1123 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1124 pFunc = (SqlFunc*)Tcl_Alloc( sizeof(*pFunc) + nScript + 1 );
1125 if( pFunc==0 ) return TCL_ERROR;
1126 pFunc->interp = interp;
1127 pFunc->pNext = pDb->pFunc;
1128 pFunc->zScript = (char*)&pFunc[1];
drh0f14e2e2004-06-29 12:39:08 +00001129 pDb->pFunc = pFunc;
drhcabb0812002-09-14 13:47:32 +00001130 strcpy(pFunc->zScript, zScript);
danielk1977c8c11582004-06-29 13:41:21 +00001131 rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00001132 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00001133 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00001134 rc = TCL_ERROR;
1135 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00001136 }else{
1137 /* Must flush any cached statements */
1138 flushStmtCache( pDb );
1139 }
drhcabb0812002-09-14 13:47:32 +00001140 break;
1141 }
1142
1143 /*
drhaf9ff332002-01-16 21:00:27 +00001144 ** $db last_insert_rowid
1145 **
1146 ** Return an integer which is the ROWID for the most recent insert.
1147 */
1148 case DB_LAST_INSERT_ROWID: {
1149 Tcl_Obj *pResult;
1150 int rowid;
1151 if( objc!=2 ){
1152 Tcl_WrongNumArgs(interp, 2, objv, "");
1153 return TCL_ERROR;
1154 }
danielk19776f8a5032004-05-10 10:34:51 +00001155 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00001156 pResult = Tcl_GetObjResult(interp);
1157 Tcl_SetIntObj(pResult, rowid);
1158 break;
1159 }
1160
1161 /*
drh1807ce32004-09-07 13:20:35 +00001162 ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
drh5d9d7572003-08-19 14:31:01 +00001163 */
drh1807ce32004-09-07 13:20:35 +00001164
1165 /* $db progress ?N CALLBACK?
1166 **
1167 ** Invoke the given callback every N virtual machine opcodes while executing
1168 ** queries.
1169 */
1170 case DB_PROGRESS: {
1171 if( objc==2 ){
1172 if( pDb->zProgress ){
1173 Tcl_AppendResult(interp, pDb->zProgress, 0);
1174 }
1175 }else if( objc==4 ){
1176 char *zProgress;
1177 int len;
1178 int N;
1179 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
1180 return TCL_ERROR;
1181 };
1182 if( pDb->zProgress ){
1183 Tcl_Free(pDb->zProgress);
1184 }
1185 zProgress = Tcl_GetStringFromObj(objv[3], &len);
1186 if( zProgress && len>0 ){
1187 pDb->zProgress = Tcl_Alloc( len + 1 );
1188 strcpy(pDb->zProgress, zProgress);
1189 }else{
1190 pDb->zProgress = 0;
1191 }
1192#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1193 if( pDb->zProgress ){
1194 pDb->interp = interp;
1195 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
1196 }else{
1197 sqlite3_progress_handler(pDb->db, 0, 0, 0);
1198 }
1199#endif
1200 }else{
1201 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00001202 return TCL_ERROR;
1203 }
drh5d9d7572003-08-19 14:31:01 +00001204 break;
1205 }
1206
1207 /*
drh22fbcb82004-02-01 01:22:50 +00001208 ** $db rekey KEY
1209 **
1210 ** Change the encryption key on the currently open database.
1211 */
1212 case DB_REKEY: {
1213 int nKey;
1214 void *pKey;
1215 if( objc!=3 ){
1216 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
1217 return TCL_ERROR;
1218 }
1219 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00001220#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00001221 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00001222 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00001223 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00001224 rc = TCL_ERROR;
1225 }
1226#endif
1227 break;
1228 }
1229
1230 /*
drhbec3f402000-08-04 13:49:02 +00001231 ** $db timeout MILLESECONDS
1232 **
1233 ** Delay for the number of milliseconds specified when a file is locked.
1234 */
drh6d313162000-09-21 13:01:35 +00001235 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00001236 int ms;
drh6d313162000-09-21 13:01:35 +00001237 if( objc!=3 ){
1238 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00001239 return TCL_ERROR;
1240 }
drh6d313162000-09-21 13:01:35 +00001241 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00001242 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00001243 break;
drh75897232000-05-29 14:26:00 +00001244 }
drhb5a20d32003-04-23 12:25:23 +00001245
drh0f14e2e2004-06-29 12:39:08 +00001246 /*
1247 ** $db total_changes
1248 **
1249 ** Return the number of rows that were modified, inserted, or deleted
1250 ** since the database handle was created.
1251 */
1252 case DB_TOTAL_CHANGES: {
1253 Tcl_Obj *pResult;
1254 if( objc!=2 ){
1255 Tcl_WrongNumArgs(interp, 2, objv, "");
1256 return TCL_ERROR;
1257 }
1258 pResult = Tcl_GetObjResult(interp);
1259 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
1260 break;
1261 }
1262
drhb5a20d32003-04-23 12:25:23 +00001263 /* $db trace ?CALLBACK?
1264 **
1265 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
1266 ** that is executed. The text of the SQL is appended to CALLBACK before
1267 ** it is executed.
1268 */
1269 case DB_TRACE: {
1270 if( objc>3 ){
1271 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00001272 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00001273 }else if( objc==2 ){
1274 if( pDb->zTrace ){
1275 Tcl_AppendResult(interp, pDb->zTrace, 0);
1276 }
1277 }else{
1278 char *zTrace;
1279 int len;
1280 if( pDb->zTrace ){
1281 Tcl_Free(pDb->zTrace);
1282 }
1283 zTrace = Tcl_GetStringFromObj(objv[2], &len);
1284 if( zTrace && len>0 ){
1285 pDb->zTrace = Tcl_Alloc( len + 1 );
1286 strcpy(pDb->zTrace, zTrace);
1287 }else{
1288 pDb->zTrace = 0;
1289 }
1290 if( pDb->zTrace ){
1291 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001292 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00001293 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001294 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00001295 }
1296 }
1297 break;
1298 }
1299
tpoindex1067fe12004-12-17 15:41:11 +00001300 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1301 **
1302 ** Copy data into table from filename, optionally using SEPARATOR
1303 ** as column separators. If a column contains a null string, or the
1304 ** value of NULLINDICATOR, a NULL is inserted for the column.
1305 ** conflict-algorithm is one of the sqlite conflict algorithms:
1306 ** rollback, abort, fail, ignore, replace
1307 ** On success, return the number of lines processed, not necessarily same
1308 ** as 'db changes' due to conflict-algorithm selected.
1309 **
1310 ** This code is basically an implementation/enhancement of
1311 ** the sqlite3 shell.c ".import" command.
1312 **
1313 ** This command usage is equivalent to the sqlite2.x COPY statement,
1314 ** which imports file data into a table using the PostgreSQL COPY file format:
1315 ** $db copy $conflit_algo $table_name $filename \t \\N
1316 */
1317 case DB_COPY: {
tpoindex1067fe12004-12-17 15:41:11 +00001318 char *zTable; /* Insert data into this table */
1319 char *zFile; /* The file from which to extract data */
1320 char *zConflict; /* The conflict algorithm to use */
1321 sqlite3_stmt *pStmt; /* A statement */
1322 int rc; /* Result code */
1323 int nCol; /* Number of columns in the table */
1324 int nByte; /* Number of bytes in an SQL string */
1325 int i, j; /* Loop counters */
1326 int nSep; /* Number of bytes in zSep[] */
1327 int nNull; /* Number of bytes in zNull[] */
1328 char *zSql; /* An SQL statement */
1329 char *zLine; /* A single line of input from the file */
1330 char **azCol; /* zLine[] broken up into columns */
1331 char *zCommit; /* How to commit changes */
1332 FILE *in; /* The input file */
1333 int lineno = 0; /* Line number of input file */
1334 char zLineNum[80]; /* Line number print buffer */
1335 Tcl_Obj *pResult; /* interp result */
1336
drh9ee3cdc2004-12-17 20:48:06 +00001337 char *zSep;
1338 char *zNull;
1339 if( objc<5 || objc>7 ){
1340 Tcl_WrongNumArgs(interp, 2, objv,
1341 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1342 return TCL_ERROR;
1343 }
1344 if( objc>=6 ){
1345 zSep = Tcl_GetStringFromObj(objv[5], 0);
1346 }else{
1347 zSep = "\t";
1348 }
1349 if( objc>=7 ){
1350 zNull = Tcl_GetStringFromObj(objv[6], 0);
1351 }else{
1352 zNull = "";
1353 }
tpoindex1067fe12004-12-17 15:41:11 +00001354 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1355 zTable = Tcl_GetStringFromObj(objv[3], 0);
1356 zFile = Tcl_GetStringFromObj(objv[4], 0);
1357 nSep = strlen(zSep);
1358 nNull = strlen(zNull);
1359 if( nSep==0 ){
1360 Tcl_AppendResult(interp, "Error: non-null separator required for copy", 0);
1361 return TCL_ERROR;
1362 }
1363 if(sqlite3StrICmp(zConflict, "rollback") != 0 &&
1364 sqlite3StrICmp(zConflict, "abort" ) != 0 &&
1365 sqlite3StrICmp(zConflict, "fail" ) != 0 &&
1366 sqlite3StrICmp(zConflict, "ignore" ) != 0 &&
1367 sqlite3StrICmp(zConflict, "replace" ) != 0 ) {
drh9ee3cdc2004-12-17 20:48:06 +00001368 Tcl_AppendResult(interp, "Error: \"", zConflict,
1369 "\", conflict-algorithm must be one of: rollback, "
1370 "abort, fail, ignore, or replace", 0);
tpoindex1067fe12004-12-17 15:41:11 +00001371 return TCL_ERROR;
1372 }
1373 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1374 if( zSql==0 ){
1375 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1376 return TCL_ERROR;
1377 }
1378 nByte = strlen(zSql);
1379 rc = sqlite3_prepare(pDb->db, zSql, 0, &pStmt, 0);
1380 sqlite3_free(zSql);
1381 if( rc ){
1382 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1383 nCol = 0;
1384 }else{
1385 nCol = sqlite3_column_count(pStmt);
1386 }
1387 sqlite3_finalize(pStmt);
1388 if( nCol==0 ) {
1389 return TCL_ERROR;
1390 }
1391 zSql = malloc( nByte + 50 + nCol*2 );
1392 if( zSql==0 ) {
1393 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1394 return TCL_ERROR;
1395 }
drh9ee3cdc2004-12-17 20:48:06 +00001396 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1397 zConflict, zTable);
tpoindex1067fe12004-12-17 15:41:11 +00001398 j = strlen(zSql);
1399 for(i=1; i<nCol; i++){
1400 zSql[j++] = ',';
1401 zSql[j++] = '?';
1402 }
1403 zSql[j++] = ')';
1404 zSql[j] = 0;
1405 rc = sqlite3_prepare(pDb->db, zSql, 0, &pStmt, 0);
1406 free(zSql);
1407 if( rc ){
1408 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1409 sqlite3_finalize(pStmt);
1410 return TCL_ERROR;
1411 }
1412 in = fopen(zFile, "rb");
1413 if( in==0 ){
1414 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
1415 sqlite3_finalize(pStmt);
1416 return TCL_ERROR;
1417 }
1418 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1419 if( azCol==0 ) {
1420 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1421 return TCL_ERROR;
1422 }
1423 sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
1424 zCommit = "COMMIT";
1425 while( (zLine = local_getline(0, in))!=0 ){
1426 char *z;
1427 i = 0;
1428 lineno++;
1429 azCol[0] = zLine;
1430 for(i=0, z=zLine; *z; z++){
1431 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
1432 *z = 0;
1433 i++;
1434 if( i<nCol ){
1435 azCol[i] = &z[nSep];
1436 z += nSep-1;
1437 }
1438 }
1439 }
1440 if( i+1!=nCol ){
1441 char *zErr;
1442 zErr = malloc(200 + strlen(zFile));
1443 sprintf(zErr,"Error: %s line %d: expected %d columns of data but found %d",
1444 zFile, lineno, nCol, i+1);
1445 Tcl_AppendResult(interp, zErr, 0);
1446 free(zErr);
1447 zCommit = "ROLLBACK";
1448 break;
1449 }
1450 for(i=0; i<nCol; i++){
1451 /* check for null data, if so, bind as null */
1452 if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
1453 sqlite3_bind_null(pStmt, i+1);
1454 }else{
1455 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1456 }
1457 }
1458 sqlite3_step(pStmt);
1459 rc = sqlite3_reset(pStmt);
1460 free(zLine);
1461 if( rc!=SQLITE_OK ){
1462 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
1463 zCommit = "ROLLBACK";
1464 break;
1465 }
1466 }
1467 free(azCol);
1468 fclose(in);
1469 sqlite3_finalize(pStmt);
1470 sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
1471
1472 if( zCommit[0] == 'C' ){
1473 /* success, set result as number of lines processed */
1474 pResult = Tcl_GetObjResult(interp);
1475 Tcl_SetIntObj(pResult, lineno);
1476 rc = TCL_OK;
1477 }else{
1478 /* failure, append lineno where failed */
1479 sprintf(zLineNum,"%d",lineno);
1480 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
1481 rc = TCL_ERROR;
1482 }
1483 break;
1484 }
1485
danielk19774397de52005-01-12 12:44:03 +00001486 /* $db version
1487 **
1488 ** Return the version string for this database.
1489 */
1490 case DB_VERSION: {
1491 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
1492 break;
1493 }
1494
tpoindex1067fe12004-12-17 15:41:11 +00001495
drh6d313162000-09-21 13:01:35 +00001496 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00001497 return rc;
drh75897232000-05-29 14:26:00 +00001498}
1499
1500/*
drh9bb575f2004-09-06 17:24:11 +00001501** sqlite3 DBNAME FILENAME ?MODE? ?-key KEY?
drh75897232000-05-29 14:26:00 +00001502**
1503** This is the main Tcl command. When the "sqlite" Tcl command is
1504** invoked, this routine runs to process that command.
1505**
1506** The first argument, DBNAME, is an arbitrary name for a new
1507** database connection. This command creates a new command named
1508** DBNAME that is used to control that connection. The database
1509** connection is deleted when the DBNAME command is deleted.
1510**
1511** The second argument is the name of the directory that contains
1512** the sqlite database that is to be accessed.
drhfbc3eab2001-04-06 16:13:42 +00001513**
1514** For testing purposes, we also support the following:
1515**
drh9bb575f2004-09-06 17:24:11 +00001516** sqlite3 -encoding
drhfbc3eab2001-04-06 16:13:42 +00001517**
1518** Return the encoding used by LIKE and GLOB operators. Choices
1519** are UTF-8 and iso8859.
1520**
drh9bb575f2004-09-06 17:24:11 +00001521** sqlite3 -version
drh647cb0e2002-11-04 19:32:25 +00001522**
1523** Return the version number of the SQLite library.
1524**
drh9bb575f2004-09-06 17:24:11 +00001525** sqlite3 -tcl-uses-utf
drhfbc3eab2001-04-06 16:13:42 +00001526**
1527** Return "1" if compiled with a Tcl uses UTF-8. Return "0" if
1528** not. Used by tests to make sure the library was compiled
1529** correctly.
drh75897232000-05-29 14:26:00 +00001530*/
drh22fbcb82004-02-01 01:22:50 +00001531static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001532 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00001533 void *pKey = 0;
1534 int nKey = 0;
1535 const char *zArg;
drh75897232000-05-29 14:26:00 +00001536 char *zErrMsg;
drh22fbcb82004-02-01 01:22:50 +00001537 const char *zFile;
drh06b27182002-06-26 20:06:05 +00001538 char zBuf[80];
drh22fbcb82004-02-01 01:22:50 +00001539 if( objc==2 ){
1540 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00001541 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00001542 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00001543 return TCL_OK;
1544 }
drh9eb9e262004-02-11 02:18:05 +00001545 if( strcmp(zArg,"-has-codec")==0 ){
1546#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00001547 Tcl_AppendResult(interp,"1",0);
1548#else
1549 Tcl_AppendResult(interp,"0",0);
1550#endif
1551 return TCL_OK;
1552 }
1553 if( strcmp(zArg,"-tcl-uses-utf")==0 ){
drhfbc3eab2001-04-06 16:13:42 +00001554#ifdef TCL_UTF_MAX
1555 Tcl_AppendResult(interp,"1",0);
1556#else
1557 Tcl_AppendResult(interp,"0",0);
1558#endif
1559 return TCL_OK;
1560 }
1561 }
drh22fbcb82004-02-01 01:22:50 +00001562 if( objc==5 || objc==6 ){
1563 zArg = Tcl_GetStringFromObj(objv[objc-2], 0);
1564 if( strcmp(zArg,"-key")==0 ){
1565 pKey = Tcl_GetByteArrayFromObj(objv[objc-1], &nKey);
1566 objc -= 2;
1567 }
1568 }
1569 if( objc!=3 && objc!=4 ){
1570 Tcl_WrongNumArgs(interp, 1, objv,
drh9eb9e262004-02-11 02:18:05 +00001571#ifdef SQLITE_HAS_CODEC
1572 "HANDLE FILENAME ?-key CODEC-KEY?"
drh22fbcb82004-02-01 01:22:50 +00001573#else
1574 "HANDLE FILENAME ?MODE?"
1575#endif
1576 );
drh75897232000-05-29 14:26:00 +00001577 return TCL_ERROR;
1578 }
drh75897232000-05-29 14:26:00 +00001579 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00001580 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00001581 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00001582 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
1583 return TCL_ERROR;
1584 }
1585 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00001586 zFile = Tcl_GetStringFromObj(objv[2], 0);
danielk19774f057f92004-06-08 00:02:33 +00001587 sqlite3_open(zFile, &p->db);
danielk197780290862004-05-22 09:21:21 +00001588 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
1589 zErrMsg = strdup(sqlite3_errmsg(p->db));
1590 sqlite3_close(p->db);
1591 p->db = 0;
1592 }
drh2011d5f2004-07-22 02:40:37 +00001593#ifdef SQLITE_HAS_CODEC
1594 sqlite3_key(p->db, pKey, nKey);
drheb8ed702004-02-11 10:37:23 +00001595#endif
drhbec3f402000-08-04 13:49:02 +00001596 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00001597 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00001598 Tcl_Free((char*)p);
drh75897232000-05-29 14:26:00 +00001599 free(zErrMsg);
1600 return TCL_ERROR;
1601 }
drhfb7e7652005-01-24 00:28:42 +00001602 p->maxStmt = NUM_PREPARED_STMTS;
drh22fbcb82004-02-01 01:22:50 +00001603 zArg = Tcl_GetStringFromObj(objv[1], 0);
1604 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
drhc22bd472002-05-10 13:14:07 +00001605
drh06b27182002-06-26 20:06:05 +00001606 /* The return value is the value of the sqlite* pointer
1607 */
1608 sprintf(zBuf, "%p", p->db);
drh5e5377f2002-07-07 17:12:36 +00001609 if( strncmp(zBuf,"0x",2) ){
1610 sprintf(zBuf, "0x%p", p->db);
1611 }
drh06b27182002-06-26 20:06:05 +00001612 Tcl_AppendResult(interp, zBuf, 0);
1613
drhc22bd472002-05-10 13:14:07 +00001614 /* If compiled with SQLITE_TEST turned on, then register the "md5sum"
drh06b27182002-06-26 20:06:05 +00001615 ** SQL function.
drhc22bd472002-05-10 13:14:07 +00001616 */
drh28b4e482002-03-11 02:06:13 +00001617#ifdef SQLITE_TEST
1618 {
drh9bb575f2004-09-06 17:24:11 +00001619 extern void Md5_Register(sqlite3*);
drh3b93bc82005-01-13 23:54:32 +00001620#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00001621 int mallocfail = sqlite3_iMallocFail;
1622 sqlite3_iMallocFail = 0;
danielk19775b59af82004-06-30 12:42:59 +00001623#endif
drhc22bd472002-05-10 13:14:07 +00001624 Md5_Register(p->db);
drh3b93bc82005-01-13 23:54:32 +00001625#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00001626 sqlite3_iMallocFail = mallocfail;
danielk19775b59af82004-06-30 12:42:59 +00001627#endif
drh06b27182002-06-26 20:06:05 +00001628 }
drh28b4e482002-03-11 02:06:13 +00001629#endif
danielk19777cedc8d2004-06-10 10:50:08 +00001630 p->interp = interp;
drh75897232000-05-29 14:26:00 +00001631 return TCL_OK;
1632}
1633
1634/*
drh90ca9752001-09-28 17:47:14 +00001635** Provide a dummy Tcl_InitStubs if we are using this as a static
1636** library.
1637*/
1638#ifndef USE_TCL_STUBS
1639# undef Tcl_InitStubs
1640# define Tcl_InitStubs(a,b,c)
1641#endif
1642
1643/*
drh75897232000-05-29 14:26:00 +00001644** Initialize this module.
1645**
1646** This Tcl module contains only a single new Tcl command named "sqlite".
1647** (Hence there is no namespace. There is no point in using a namespace
1648** if the extension only supplies one new name!) The "sqlite" command is
1649** used to open a new SQLite database. See the DbMain() routine above
1650** for additional information.
1651*/
drh38f82712004-06-18 17:10:16 +00001652int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00001653 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00001654 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
1655 Tcl_PkgProvide(interp, "sqlite3", "3.0");
drh49766d62005-01-08 18:42:28 +00001656 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
1657 Tcl_PkgProvide(interp, "sqlite", "3.0");
drh90ca9752001-09-28 17:47:14 +00001658 return TCL_OK;
1659}
drh49766d62005-01-08 18:42:28 +00001660int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
1661int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
1662int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
1663
1664#ifndef SQLITE_3_SUFFIX_ONLY
1665int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
1666int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
1667int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
1668int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
1669#endif
drh75897232000-05-29 14:26:00 +00001670
drh3e27c022004-07-23 00:01:38 +00001671#ifdef TCLSH
1672/*****************************************************************************
1673** The code that follows is used to build standalone TCL interpreters
drh75897232000-05-29 14:26:00 +00001674*/
drh348784e2000-05-29 20:41:49 +00001675
1676/*
drh3e27c022004-07-23 00:01:38 +00001677** If the macro TCLSH is one, then put in code this for the
1678** "main" routine that will initialize Tcl and take input from
1679** standard input.
drh348784e2000-05-29 20:41:49 +00001680*/
drh3e27c022004-07-23 00:01:38 +00001681#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00001682static char zMainloop[] =
1683 "set line {}\n"
1684 "while {![eof stdin]} {\n"
1685 "if {$line!=\"\"} {\n"
1686 "puts -nonewline \"> \"\n"
1687 "} else {\n"
1688 "puts -nonewline \"% \"\n"
1689 "}\n"
1690 "flush stdout\n"
1691 "append line [gets stdin]\n"
1692 "if {[info complete $line]} {\n"
1693 "if {[catch {uplevel #0 $line} result]} {\n"
1694 "puts stderr \"Error: $result\"\n"
1695 "} elseif {$result!=\"\"} {\n"
1696 "puts $result\n"
1697 "}\n"
1698 "set line {}\n"
1699 "} else {\n"
1700 "append line \\n\n"
1701 "}\n"
1702 "}\n"
1703;
drh3e27c022004-07-23 00:01:38 +00001704#endif
1705
1706/*
1707** If the macro TCLSH is two, then get the main loop code out of
1708** the separate file "spaceanal_tcl.h".
1709*/
1710#if TCLSH==2
1711static char zMainloop[] =
1712#include "spaceanal_tcl.h"
1713;
1714#endif
drh348784e2000-05-29 20:41:49 +00001715
1716#define TCLSH_MAIN main /* Needed to fake out mktclapp */
1717int TCLSH_MAIN(int argc, char **argv){
1718 Tcl_Interp *interp;
drh297ecf12001-04-05 15:57:13 +00001719 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00001720 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00001721 Sqlite3_Init(interp);
drhd9b02572001-04-15 00:37:09 +00001722#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00001723 {
1724 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00001725 extern int Sqlitetest2_Init(Tcl_Interp*);
1726 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00001727 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00001728 extern int Sqlitetest5_Init(Tcl_Interp*);
drhefc251d2001-07-01 22:12:01 +00001729 extern int Md5_Init(Tcl_Interp*);
danielk19776490beb2004-05-11 06:17:21 +00001730 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00001731 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00001732 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00001733 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00001734 Sqlitetest5_Init(interp);
drhefc251d2001-07-01 22:12:01 +00001735 Md5_Init(interp);
drhd1bf3512001-04-07 15:24:33 +00001736 }
1737#endif
drh3e27c022004-07-23 00:01:38 +00001738 if( argc>=2 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00001739 int i;
1740 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
1741 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00001742 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00001743 Tcl_SetVar(interp, "argv", argv[i],
1744 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
1745 }
drh3e27c022004-07-23 00:01:38 +00001746 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00001747 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drhc61053b2000-06-04 12:58:36 +00001748 if( zInfo==0 ) zInfo = interp->result;
1749 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00001750 return 1;
1751 }
drh3e27c022004-07-23 00:01:38 +00001752 }
1753 if( argc<=1 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00001754 Tcl_GlobalEval(interp, zMainloop);
1755 }
1756 return 0;
1757}
1758#endif /* TCLSH */
drh6d313162000-09-21 13:01:35 +00001759
1760#endif /* !defined(NO_TCL) */