blob: f1e80e5ff9e7848ce0c080dc818b4c717a5a3369 [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**
drhdf0bdda2005-06-25 19:31:48 +000014** $Id: tclsqlite.c,v 1.126 2005/06/25 19:31:48 drh Exp $
drh75897232000-05-29 14:26:00 +000015*/
drh6d313162000-09-21 13:01:35 +000016#ifndef NO_TCL /* Omit this whole file if TCL is unavailable */
17
drh06b27182002-06-26 20:06:05 +000018#include "sqliteInt.h"
drh895d7472004-08-20 16:02:39 +000019#include "hash.h"
drh17a68932001-01-31 13:28:08 +000020#include "tcl.h"
drh75897232000-05-29 14:26:00 +000021#include <stdlib.h>
22#include <string.h>
drhce927062001-11-09 13:41:09 +000023#include <assert.h>
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 */
danielk197755c45f22005-04-03 23:54:43 +000086 char *zNull; /* Text to substitute for an SQL NULL value */
drhcabb0812002-09-14 13:47:32 +000087 SqlFunc *pFunc; /* List of SQL functions */
danielk19770202b292004-06-09 09:55:16 +000088 SqlCollate *pCollate; /* List of SQL collation functions */
danielk19776f8a5032004-05-10 10:34:51 +000089 int rc; /* Return code of most recent sqlite3_exec() */
danielk19777cedc8d2004-06-10 10:50:08 +000090 Tcl_Obj *pCollateNeeded; /* Collation needed script */
drhfb7e7652005-01-24 00:28:42 +000091 SqlPreparedStmt *stmtList; /* List of prepared statements*/
92 SqlPreparedStmt *stmtLast; /* Last statement in the list */
93 int maxStmt; /* The next maximum number of stmtList */
94 int nStmt; /* Number of statements in stmtList */
drh98808ba2001-10-18 12:34:46 +000095};
drh297ecf12001-04-05 15:57:13 +000096
drh6d313162000-09-21 13:01:35 +000097/*
drhfb7e7652005-01-24 00:28:42 +000098** Finalize and free a list of prepared statements
99*/
100static void flushStmtCache( SqliteDb *pDb ){
101 SqlPreparedStmt *pPreStmt;
102
103 while( pDb->stmtList ){
104 sqlite3_finalize( pDb->stmtList->pStmt );
105 pPreStmt = pDb->stmtList;
106 pDb->stmtList = pDb->stmtList->pNext;
107 Tcl_Free( (char*)pPreStmt );
108 }
109 pDb->nStmt = 0;
110 pDb->stmtLast = 0;
111}
112
113/*
drh895d7472004-08-20 16:02:39 +0000114** TCL calls this procedure when an sqlite3 database command is
115** deleted.
drh75897232000-05-29 14:26:00 +0000116*/
117static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000118 SqliteDb *pDb = (SqliteDb*)db;
drhfb7e7652005-01-24 00:28:42 +0000119 flushStmtCache(pDb);
danielk19776f8a5032004-05-10 10:34:51 +0000120 sqlite3_close(pDb->db);
drhcabb0812002-09-14 13:47:32 +0000121 while( pDb->pFunc ){
122 SqlFunc *pFunc = pDb->pFunc;
123 pDb->pFunc = pFunc->pNext;
124 Tcl_Free((char*)pFunc);
125 }
danielk19770202b292004-06-09 09:55:16 +0000126 while( pDb->pCollate ){
127 SqlCollate *pCollate = pDb->pCollate;
128 pDb->pCollate = pCollate->pNext;
129 Tcl_Free((char*)pCollate);
130 }
drhbec3f402000-08-04 13:49:02 +0000131 if( pDb->zBusy ){
132 Tcl_Free(pDb->zBusy);
133 }
drhb5a20d32003-04-23 12:25:23 +0000134 if( pDb->zTrace ){
135 Tcl_Free(pDb->zTrace);
drh0d1a6432003-04-03 15:46:04 +0000136 }
drhe22a3342003-04-22 20:30:37 +0000137 if( pDb->zAuth ){
138 Tcl_Free(pDb->zAuth);
139 }
danielk197755c45f22005-04-03 23:54:43 +0000140 if( pDb->zNull ){
141 Tcl_Free(pDb->zNull);
142 }
drhbec3f402000-08-04 13:49:02 +0000143 Tcl_Free((char*)pDb);
144}
145
146/*
147** This routine is called when a database file is locked while trying
148** to execute SQL.
149*/
danielk19772a764eb2004-06-12 01:43:26 +0000150static int DbBusyHandler(void *cd, int nTries){
drhbec3f402000-08-04 13:49:02 +0000151 SqliteDb *pDb = (SqliteDb*)cd;
152 int rc;
153 char zVal[30];
154 char *zCmd;
drhbec3f402000-08-04 13:49:02 +0000155 Tcl_DString cmd;
156
157 Tcl_DStringInit(&cmd);
158 Tcl_DStringAppend(&cmd, pDb->zBusy, -1);
danielk19772a764eb2004-06-12 01:43:26 +0000159 sprintf(zVal, "%d", nTries);
160 Tcl_DStringAppendElement(&cmd, zVal);
drhbec3f402000-08-04 13:49:02 +0000161 zCmd = Tcl_DStringValue(&cmd);
162 rc = Tcl_Eval(pDb->interp, zCmd);
163 Tcl_DStringFree(&cmd);
164 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
165 return 0;
166 }
167 return 1;
drh75897232000-05-29 14:26:00 +0000168}
169
170/*
danielk1977348bb5d2003-10-18 09:37:26 +0000171** This routine is invoked as the 'progress callback' for the database.
172*/
173static int DbProgressHandler(void *cd){
174 SqliteDb *pDb = (SqliteDb*)cd;
175 int rc;
176
177 assert( pDb->zProgress );
178 rc = Tcl_Eval(pDb->interp, pDb->zProgress);
179 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
180 return 1;
181 }
182 return 0;
183}
184
185/*
drhb5a20d32003-04-23 12:25:23 +0000186** This routine is called by the SQLite trace handler whenever a new
187** block of SQL is executed. The TCL script in pDb->zTrace is executed.
drh0d1a6432003-04-03 15:46:04 +0000188*/
drhb5a20d32003-04-23 12:25:23 +0000189static void DbTraceHandler(void *cd, const char *zSql){
drh0d1a6432003-04-03 15:46:04 +0000190 SqliteDb *pDb = (SqliteDb*)cd;
drhb5a20d32003-04-23 12:25:23 +0000191 Tcl_DString str;
drh0d1a6432003-04-03 15:46:04 +0000192
drhb5a20d32003-04-23 12:25:23 +0000193 Tcl_DStringInit(&str);
194 Tcl_DStringAppend(&str, pDb->zTrace, -1);
195 Tcl_DStringAppendElement(&str, zSql);
196 Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
197 Tcl_DStringFree(&str);
198 Tcl_ResetResult(pDb->interp);
drh0d1a6432003-04-03 15:46:04 +0000199}
200
201/*
drhaa940ea2004-01-15 02:44:03 +0000202** This routine is called when a transaction is committed. The
203** TCL script in pDb->zCommit is executed. If it returns non-zero or
204** if it throws an exception, the transaction is rolled back instead
205** of being committed.
206*/
207static int DbCommitHandler(void *cd){
208 SqliteDb *pDb = (SqliteDb*)cd;
209 int rc;
210
211 rc = Tcl_Eval(pDb->interp, pDb->zCommit);
212 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
213 return 1;
214 }
215 return 0;
216}
217
danielk19777cedc8d2004-06-10 10:50:08 +0000218static void tclCollateNeeded(
219 void *pCtx,
drh9bb575f2004-09-06 17:24:11 +0000220 sqlite3 *db,
danielk19777cedc8d2004-06-10 10:50:08 +0000221 int enc,
222 const char *zName
223){
224 SqliteDb *pDb = (SqliteDb *)pCtx;
225 Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
226 Tcl_IncrRefCount(pScript);
227 Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
228 Tcl_EvalObjEx(pDb->interp, pScript, 0);
229 Tcl_DecrRefCount(pScript);
230}
231
drhaa940ea2004-01-15 02:44:03 +0000232/*
danielk19770202b292004-06-09 09:55:16 +0000233** This routine is called to evaluate an SQL collation function implemented
234** using TCL script.
235*/
236static int tclSqlCollate(
237 void *pCtx,
238 int nA,
239 const void *zA,
240 int nB,
241 const void *zB
242){
243 SqlCollate *p = (SqlCollate *)pCtx;
244 Tcl_Obj *pCmd;
245
246 pCmd = Tcl_NewStringObj(p->zScript, -1);
247 Tcl_IncrRefCount(pCmd);
248 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
249 Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
250 Tcl_EvalObjEx(p->interp, pCmd, 0);
251 Tcl_DecrRefCount(pCmd);
252 return (atoi(Tcl_GetStringResult(p->interp)));
253}
254
255/*
drhcabb0812002-09-14 13:47:32 +0000256** This routine is called to evaluate an SQL function implemented
257** using TCL script.
258*/
drhfb7e7652005-01-24 00:28:42 +0000259static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
danielk19776f8a5032004-05-10 10:34:51 +0000260 SqlFunc *p = sqlite3_user_data(context);
drhcabb0812002-09-14 13:47:32 +0000261 Tcl_DString cmd;
262 int i;
263 int rc;
264
265 Tcl_DStringInit(&cmd);
266 Tcl_DStringAppend(&cmd, p->zScript, -1);
267 for(i=0; i<argc; i++){
drh9c054832004-05-31 18:51:57 +0000268 if( SQLITE_NULL==sqlite3_value_type(argv[i]) ){
danielk197751ad0ec2004-05-24 12:39:02 +0000269 Tcl_DStringAppendElement(&cmd, "");
270 }else{
drh4f26d6c2004-05-26 23:25:30 +0000271 Tcl_DStringAppendElement(&cmd, sqlite3_value_text(argv[i]));
danielk197751ad0ec2004-05-24 12:39:02 +0000272 }
drhcabb0812002-09-14 13:47:32 +0000273 }
drhc7f269d2005-05-05 10:30:29 +0000274 rc = Tcl_EvalEx(p->interp, Tcl_DStringValue(&cmd), Tcl_DStringLength(&cmd),
275 TCL_EVAL_DIRECT);
danielk1977562e8d32005-05-20 09:40:55 +0000276 Tcl_DStringFree(&cmd);
277
drhc7f269d2005-05-05 10:30:29 +0000278 if( rc && rc!=TCL_RETURN ){
danielk19777e18c252004-05-25 11:47:24 +0000279 sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
drhcabb0812002-09-14 13:47:32 +0000280 }else{
drhc7f269d2005-05-05 10:30:29 +0000281 Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
282 int n;
283 u8 *data;
284 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
285 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000286 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
287 /* Only load a BLOB type if the Tcl variable is a bytearray and
288 ** has no string representation. */
drhc7f269d2005-05-05 10:30:29 +0000289 data = Tcl_GetByteArrayFromObj(pVar, &n);
290 sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000291 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
292 (c=='i' && strcmp(zType,"int")==0) ){
293 Tcl_GetIntFromObj(0, pVar, &n);
294 sqlite3_result_int(context, n);
295 }else if( c=='d' && strcmp(zType,"double")==0 ){
296 double r;
297 Tcl_GetDoubleFromObj(0, pVar, &r);
298 sqlite3_result_double(context, r);
drhdf0bdda2005-06-25 19:31:48 +0000299 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
300 Tcl_WideInt v;
301 Tcl_GetWideIntFromObj(0, pVar, &v);
302 sqlite3_result_int64(context, v);
drhc7f269d2005-05-05 10:30:29 +0000303 }else{
304 data = Tcl_GetStringFromObj(pVar, &n);
305 sqlite3_result_text(context, data, n, SQLITE_TRANSIENT);
drhc7f269d2005-05-05 10:30:29 +0000306 }
drhcabb0812002-09-14 13:47:32 +0000307 }
308}
drh895d7472004-08-20 16:02:39 +0000309
drhe22a3342003-04-22 20:30:37 +0000310#ifndef SQLITE_OMIT_AUTHORIZATION
311/*
312** This is the authentication function. It appends the authentication
313** type code and the two arguments to zCmd[] then invokes the result
314** on the interpreter. The reply is examined to determine if the
315** authentication fails or succeeds.
316*/
317static int auth_callback(
318 void *pArg,
319 int code,
320 const char *zArg1,
321 const char *zArg2,
322 const char *zArg3,
323 const char *zArg4
324){
325 char *zCode;
326 Tcl_DString str;
327 int rc;
328 const char *zReply;
329 SqliteDb *pDb = (SqliteDb*)pArg;
330
331 switch( code ){
332 case SQLITE_COPY : zCode="SQLITE_COPY"; break;
333 case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break;
334 case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break;
335 case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
336 case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
337 case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
338 case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
339 case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break;
340 case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break;
341 case SQLITE_DELETE : zCode="SQLITE_DELETE"; break;
342 case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break;
343 case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break;
344 case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break;
345 case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break;
346 case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
347 case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break;
348 case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break;
349 case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break;
350 case SQLITE_INSERT : zCode="SQLITE_INSERT"; break;
351 case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break;
352 case SQLITE_READ : zCode="SQLITE_READ"; break;
353 case SQLITE_SELECT : zCode="SQLITE_SELECT"; break;
354 case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break;
355 case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break;
drh81e293b2003-06-06 19:00:42 +0000356 case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break;
357 case SQLITE_DETACH : zCode="SQLITE_DETACH"; break;
danielk19771c8c23c2004-11-12 15:53:37 +0000358 case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break;
danielk19771d54df82004-11-23 15:41:16 +0000359 case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break;
drhe22a3342003-04-22 20:30:37 +0000360 default : zCode="????"; break;
361 }
362 Tcl_DStringInit(&str);
363 Tcl_DStringAppend(&str, pDb->zAuth, -1);
364 Tcl_DStringAppendElement(&str, zCode);
365 Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
366 Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
367 Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
368 Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
369 rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
370 Tcl_DStringFree(&str);
371 zReply = Tcl_GetStringResult(pDb->interp);
372 if( strcmp(zReply,"SQLITE_OK")==0 ){
373 rc = SQLITE_OK;
374 }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
375 rc = SQLITE_DENY;
376 }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
377 rc = SQLITE_IGNORE;
378 }else{
379 rc = 999;
380 }
381 return rc;
382}
383#endif /* SQLITE_OMIT_AUTHORIZATION */
drhcabb0812002-09-14 13:47:32 +0000384
385/*
danielk1977ef2cb632004-05-29 02:37:19 +0000386** zText is a pointer to text obtained via an sqlite3_result_text()
387** or similar interface. This routine returns a Tcl string object,
388** reference count set to 0, containing the text. If a translation
389** between iso8859 and UTF-8 is required, it is preformed.
390*/
391static Tcl_Obj *dbTextToObj(char const *zText){
392 Tcl_Obj *pVal;
393#ifdef UTF_TRANSLATION_NEEDED
394 Tcl_DString dCol;
395 Tcl_DStringInit(&dCol);
396 Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
397 pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
398 Tcl_DStringFree(&dCol);
399#else
400 pVal = Tcl_NewStringObj(zText, -1);
401#endif
402 return pVal;
403}
404
405/*
tpoindex1067fe12004-12-17 15:41:11 +0000406** This routine reads a line of text from FILE in, stores
407** the text in memory obtained from malloc() and returns a pointer
408** to the text. NULL is returned at end of file, or if malloc()
409** fails.
410**
411** The interface is like "readline" but no command-line editing
412** is done.
413**
414** copied from shell.c from '.import' command
415*/
416static char *local_getline(char *zPrompt, FILE *in){
417 char *zLine;
418 int nLine;
419 int n;
420 int eol;
421
422 nLine = 100;
423 zLine = malloc( nLine );
424 if( zLine==0 ) return 0;
425 n = 0;
426 eol = 0;
427 while( !eol ){
428 if( n+100>nLine ){
429 nLine = nLine*2 + 100;
430 zLine = realloc(zLine, nLine);
431 if( zLine==0 ) return 0;
432 }
433 if( fgets(&zLine[n], nLine - n, in)==0 ){
434 if( n==0 ){
435 free(zLine);
436 return 0;
437 }
438 zLine[n] = 0;
439 eol = 1;
440 break;
441 }
442 while( zLine[n] ){ n++; }
443 if( n>0 && zLine[n-1]=='\n' ){
444 n--;
445 zLine[n] = 0;
446 eol = 1;
447 }
448 }
449 zLine = realloc( zLine, n+1 );
450 return zLine;
451}
452
453/*
drh75897232000-05-29 14:26:00 +0000454** The "sqlite" command below creates a new Tcl command for each
455** connection it opens to an SQLite database. This routine is invoked
456** whenever one of those connection-specific commands is executed
457** in Tcl. For example, if you run Tcl code like this:
458**
drh9bb575f2004-09-06 17:24:11 +0000459** sqlite3 db1 "my_database"
drh75897232000-05-29 14:26:00 +0000460** db1 close
461**
462** The first command opens a connection to the "my_database" database
463** and calls that connection "db1". The second command causes this
464** subroutine to be invoked.
465*/
drh6d313162000-09-21 13:01:35 +0000466static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +0000467 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +0000468 int choice;
drh22fbcb82004-02-01 01:22:50 +0000469 int rc = TCL_OK;
drh0de8c112002-07-06 16:32:14 +0000470 static const char *DB_strs[] = {
drhfb7e7652005-01-24 00:28:42 +0000471 "authorizer", "busy", "cache",
472 "changes", "close", "collate",
473 "collation_needed", "commit_hook", "complete",
474 "copy", "errorcode", "eval",
danielk197755c45f22005-04-03 23:54:43 +0000475 "function", "last_insert_rowid", "nullvalue",
476 "onecolumn", "progress", "rekey",
477 "timeout", "total_changes", "trace",
478 "version",
drh0f14e2e2004-06-29 12:39:08 +0000479 0
drh6d313162000-09-21 13:01:35 +0000480 };
drh411995d2002-06-25 19:31:18 +0000481 enum DB_enum {
drhfb7e7652005-01-24 00:28:42 +0000482 DB_AUTHORIZER, DB_BUSY, DB_CACHE,
483 DB_CHANGES, DB_CLOSE, DB_COLLATE,
484 DB_COLLATION_NEEDED, DB_COMMIT_HOOK, DB_COMPLETE,
485 DB_COPY, DB_ERRORCODE, DB_EVAL,
danielk197755c45f22005-04-03 23:54:43 +0000486 DB_FUNCTION, DB_LAST_INSERT_ROWID,DB_NULLVALUE,
487 DB_ONECOLUMN, DB_PROGRESS, DB_REKEY,
488 DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE,
489 DB_VERSION
drh6d313162000-09-21 13:01:35 +0000490 };
tpoindex1067fe12004-12-17 15:41:11 +0000491 /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
drh6d313162000-09-21 13:01:35 +0000492
493 if( objc<2 ){
494 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +0000495 return TCL_ERROR;
496 }
drh411995d2002-06-25 19:31:18 +0000497 if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
drh6d313162000-09-21 13:01:35 +0000498 return TCL_ERROR;
499 }
500
drh411995d2002-06-25 19:31:18 +0000501 switch( (enum DB_enum)choice ){
drh75897232000-05-29 14:26:00 +0000502
drhe22a3342003-04-22 20:30:37 +0000503 /* $db authorizer ?CALLBACK?
504 **
505 ** Invoke the given callback to authorize each SQL operation as it is
506 ** compiled. 5 arguments are appended to the callback before it is
507 ** invoked:
508 **
509 ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
510 ** (2) First descriptive name (depends on authorization type)
511 ** (3) Second descriptive name
512 ** (4) Name of the database (ex: "main", "temp")
513 ** (5) Name of trigger that is doing the access
514 **
515 ** The callback should return on of the following strings: SQLITE_OK,
516 ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error.
517 **
518 ** If this method is invoked with no arguments, the current authorization
519 ** callback string is returned.
520 */
521 case DB_AUTHORIZER: {
drh1211de32004-07-26 12:24:22 +0000522#ifdef SQLITE_OMIT_AUTHORIZATION
523 Tcl_AppendResult(interp, "authorization not available in this build", 0);
524 return TCL_ERROR;
525#else
drhe22a3342003-04-22 20:30:37 +0000526 if( objc>3 ){
527 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +0000528 return TCL_ERROR;
drhe22a3342003-04-22 20:30:37 +0000529 }else if( objc==2 ){
drhb5a20d32003-04-23 12:25:23 +0000530 if( pDb->zAuth ){
drhe22a3342003-04-22 20:30:37 +0000531 Tcl_AppendResult(interp, pDb->zAuth, 0);
532 }
533 }else{
534 char *zAuth;
535 int len;
536 if( pDb->zAuth ){
537 Tcl_Free(pDb->zAuth);
538 }
539 zAuth = Tcl_GetStringFromObj(objv[2], &len);
540 if( zAuth && len>0 ){
541 pDb->zAuth = Tcl_Alloc( len + 1 );
542 strcpy(pDb->zAuth, zAuth);
543 }else{
544 pDb->zAuth = 0;
545 }
drhe22a3342003-04-22 20:30:37 +0000546 if( pDb->zAuth ){
547 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000548 sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
drhe22a3342003-04-22 20:30:37 +0000549 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000550 sqlite3_set_authorizer(pDb->db, 0, 0);
drhe22a3342003-04-22 20:30:37 +0000551 }
drhe22a3342003-04-22 20:30:37 +0000552 }
drh1211de32004-07-26 12:24:22 +0000553#endif
drhe22a3342003-04-22 20:30:37 +0000554 break;
555 }
556
drhbec3f402000-08-04 13:49:02 +0000557 /* $db busy ?CALLBACK?
558 **
559 ** Invoke the given callback if an SQL statement attempts to open
560 ** a locked database file.
561 */
drh6d313162000-09-21 13:01:35 +0000562 case DB_BUSY: {
563 if( objc>3 ){
564 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +0000565 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +0000566 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +0000567 if( pDb->zBusy ){
568 Tcl_AppendResult(interp, pDb->zBusy, 0);
569 }
570 }else{
drh6d313162000-09-21 13:01:35 +0000571 char *zBusy;
572 int len;
drhbec3f402000-08-04 13:49:02 +0000573 if( pDb->zBusy ){
574 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +0000575 }
drh6d313162000-09-21 13:01:35 +0000576 zBusy = Tcl_GetStringFromObj(objv[2], &len);
577 if( zBusy && len>0 ){
578 pDb->zBusy = Tcl_Alloc( len + 1 );
579 strcpy(pDb->zBusy, zBusy);
580 }else{
581 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +0000582 }
583 if( pDb->zBusy ){
584 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000585 sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +0000586 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000587 sqlite3_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +0000588 }
589 }
drh6d313162000-09-21 13:01:35 +0000590 break;
591 }
drhbec3f402000-08-04 13:49:02 +0000592
drhfb7e7652005-01-24 00:28:42 +0000593 /* $db cache flush
594 ** $db cache size n
595 **
596 ** Flush the prepared statement cache, or set the maximum number of
597 ** cached statements.
598 */
599 case DB_CACHE: {
600 char *subCmd;
601 int n;
602
603 if( objc<=2 ){
604 Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
605 return TCL_ERROR;
606 }
607 subCmd = Tcl_GetStringFromObj( objv[2], 0 );
608 if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
609 if( objc!=3 ){
610 Tcl_WrongNumArgs(interp, 2, objv, "flush");
611 return TCL_ERROR;
612 }else{
613 flushStmtCache( pDb );
614 }
615 }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
616 if( objc!=4 ){
617 Tcl_WrongNumArgs(interp, 2, objv, "size n");
618 return TCL_ERROR;
619 }else{
620 if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
621 Tcl_AppendResult( interp, "cannot convert \"",
622 Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
623 return TCL_ERROR;
624 }else{
625 if( n<0 ){
626 flushStmtCache( pDb );
627 n = 0;
628 }else if( n>MAX_PREPARED_STMTS ){
629 n = MAX_PREPARED_STMTS;
630 }
631 pDb->maxStmt = n;
632 }
633 }
634 }else{
635 Tcl_AppendResult( interp, "bad option \"",
636 Tcl_GetStringFromObj(objv[0],0), "\": must be flush or size", 0);
637 return TCL_ERROR;
638 }
639 break;
640 }
641
danielk1977b28af712004-06-21 06:50:26 +0000642 /* $db changes
drhc8d30ac2002-04-12 10:08:59 +0000643 **
644 ** Return the number of rows that were modified, inserted, or deleted by
danielk1977b28af712004-06-21 06:50:26 +0000645 ** the most recent INSERT, UPDATE or DELETE statement, not including
646 ** any changes made by trigger programs.
drhc8d30ac2002-04-12 10:08:59 +0000647 */
648 case DB_CHANGES: {
649 Tcl_Obj *pResult;
drhc8d30ac2002-04-12 10:08:59 +0000650 if( objc!=2 ){
651 Tcl_WrongNumArgs(interp, 2, objv, "");
652 return TCL_ERROR;
653 }
drhc8d30ac2002-04-12 10:08:59 +0000654 pResult = Tcl_GetObjResult(interp);
danielk1977b28af712004-06-21 06:50:26 +0000655 Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
rdcf146a772004-02-25 22:51:06 +0000656 break;
657 }
658
drh75897232000-05-29 14:26:00 +0000659 /* $db close
660 **
661 ** Shutdown the database
662 */
drh6d313162000-09-21 13:01:35 +0000663 case DB_CLOSE: {
664 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
665 break;
666 }
drh75897232000-05-29 14:26:00 +0000667
drhaa940ea2004-01-15 02:44:03 +0000668 /* $db commit_hook ?CALLBACK?
669 **
670 ** Invoke the given callback just before committing every SQL transaction.
671 ** If the callback throws an exception or returns non-zero, then the
672 ** transaction is aborted. If CALLBACK is an empty string, the callback
673 ** is disabled.
674 */
675 case DB_COMMIT_HOOK: {
676 if( objc>3 ){
677 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drh0f14e2e2004-06-29 12:39:08 +0000678 return TCL_ERROR;
drhaa940ea2004-01-15 02:44:03 +0000679 }else if( objc==2 ){
680 if( pDb->zCommit ){
681 Tcl_AppendResult(interp, pDb->zCommit, 0);
682 }
683 }else{
684 char *zCommit;
685 int len;
686 if( pDb->zCommit ){
687 Tcl_Free(pDb->zCommit);
688 }
689 zCommit = Tcl_GetStringFromObj(objv[2], &len);
690 if( zCommit && len>0 ){
691 pDb->zCommit = Tcl_Alloc( len + 1 );
692 strcpy(pDb->zCommit, zCommit);
693 }else{
694 pDb->zCommit = 0;
695 }
696 if( pDb->zCommit ){
697 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +0000698 sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
drhaa940ea2004-01-15 02:44:03 +0000699 }else{
danielk19776f8a5032004-05-10 10:34:51 +0000700 sqlite3_commit_hook(pDb->db, 0, 0);
drhaa940ea2004-01-15 02:44:03 +0000701 }
702 }
703 break;
704 }
705
drh0f14e2e2004-06-29 12:39:08 +0000706 /*
707 ** $db collate NAME SCRIPT
708 **
709 ** Create a new SQL collation function called NAME. Whenever
710 ** that function is called, invoke SCRIPT to evaluate the function.
711 */
712 case DB_COLLATE: {
713 SqlCollate *pCollate;
714 char *zName;
715 char *zScript;
716 int nScript;
717 if( objc!=4 ){
718 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
719 return TCL_ERROR;
720 }
721 zName = Tcl_GetStringFromObj(objv[2], 0);
722 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
723 pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
724 if( pCollate==0 ) return TCL_ERROR;
725 pCollate->interp = interp;
726 pCollate->pNext = pDb->pCollate;
727 pCollate->zScript = (char*)&pCollate[1];
728 pDb->pCollate = pCollate;
729 strcpy(pCollate->zScript, zScript);
730 if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
731 pCollate, tclSqlCollate) ){
danielk19779636c4e2005-01-25 04:27:54 +0000732 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drh0f14e2e2004-06-29 12:39:08 +0000733 return TCL_ERROR;
734 }
735 break;
736 }
737
738 /*
739 ** $db collation_needed SCRIPT
740 **
741 ** Create a new SQL collation function called NAME. Whenever
742 ** that function is called, invoke SCRIPT to evaluate the function.
743 */
744 case DB_COLLATION_NEEDED: {
745 if( objc!=3 ){
746 Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
747 return TCL_ERROR;
748 }
749 if( pDb->pCollateNeeded ){
750 Tcl_DecrRefCount(pDb->pCollateNeeded);
751 }
752 pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
753 Tcl_IncrRefCount(pDb->pCollateNeeded);
754 sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
755 break;
756 }
757
drh75897232000-05-29 14:26:00 +0000758 /* $db complete SQL
759 **
760 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
761 ** additional lines of input are needed. This is similar to the
762 ** built-in "info complete" command of Tcl.
763 */
drh6d313162000-09-21 13:01:35 +0000764 case DB_COMPLETE: {
drhccae6022005-02-26 17:31:26 +0000765#ifndef SQLITE_OMIT_COMPLETE
drh6d313162000-09-21 13:01:35 +0000766 Tcl_Obj *pResult;
767 int isComplete;
768 if( objc!=3 ){
769 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +0000770 return TCL_ERROR;
771 }
danielk19776f8a5032004-05-10 10:34:51 +0000772 isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
drh6d313162000-09-21 13:01:35 +0000773 pResult = Tcl_GetObjResult(interp);
774 Tcl_SetBooleanObj(pResult, isComplete);
drhccae6022005-02-26 17:31:26 +0000775#endif
drh6d313162000-09-21 13:01:35 +0000776 break;
777 }
drhdcd997e2003-01-31 17:21:49 +0000778
779 /*
780 ** $db errorcode
781 **
782 ** Return the numeric error code that was returned by the most recent
danielk19776f8a5032004-05-10 10:34:51 +0000783 ** call to sqlite3_exec().
drhdcd997e2003-01-31 17:21:49 +0000784 */
785 case DB_ERRORCODE: {
danielk1977f3ce83f2004-06-14 11:43:46 +0000786 Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
drhdcd997e2003-01-31 17:21:49 +0000787 break;
788 }
drh75897232000-05-29 14:26:00 +0000789
790 /*
drh895d7472004-08-20 16:02:39 +0000791 ** $db eval $sql ?array? ?{ ...code... }?
drh1807ce32004-09-07 13:20:35 +0000792 ** $db onecolumn $sql
drh75897232000-05-29 14:26:00 +0000793 **
794 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +0000795 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +0000796 ** If "array" and "code" are omitted, then no callback is every invoked.
797 ** If "array" is an empty string, then the values are placed in variables
798 ** that have the same name as the fields extracted by the query.
drh1807ce32004-09-07 13:20:35 +0000799 **
800 ** The onecolumn method is the equivalent of:
801 ** lindex [$db eval $sql] 0
drh75897232000-05-29 14:26:00 +0000802 */
drh1807ce32004-09-07 13:20:35 +0000803 case DB_ONECOLUMN:
drh6d313162000-09-21 13:01:35 +0000804 case DB_EVAL: {
drh9d74b4c2004-08-24 15:23:34 +0000805 char const *zSql; /* Next SQL statement to execute */
806 char const *zLeft; /* What is left after first stmt in zSql */
807 sqlite3_stmt *pStmt; /* Compiled SQL statment */
drh92febd92004-08-20 18:34:20 +0000808 Tcl_Obj *pArray; /* Name of array into which results are written */
809 Tcl_Obj *pScript; /* Script to run for each result set */
drh1d895032004-08-26 00:56:05 +0000810 Tcl_Obj **apParm; /* Parameters that need a Tcl_DecrRefCount() */
811 int nParm; /* Number of entries used in apParm[] */
812 Tcl_Obj *aParm[10]; /* Static space for apParm[] in the common case */
drh1807ce32004-09-07 13:20:35 +0000813 Tcl_Obj *pRet; /* Value to be returned */
drhfb7e7652005-01-24 00:28:42 +0000814 SqlPreparedStmt *pPreStmt; /* Pointer to a prepared statement */
815 int rc2;
danielk1977ef2cb632004-05-29 02:37:19 +0000816
drh1807ce32004-09-07 13:20:35 +0000817 if( choice==DB_ONECOLUMN ){
818 if( objc!=3 ){
819 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
820 return TCL_ERROR;
821 }
822 pRet = 0;
823 }else{
824 if( objc<3 || objc>5 ){
825 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
826 return TCL_ERROR;
827 }
828 pRet = Tcl_NewObj();
829 Tcl_IncrRefCount(pRet);
danielk197730ccda12004-05-27 12:11:31 +0000830 }
drh92febd92004-08-20 18:34:20 +0000831 if( objc==3 ){
832 pArray = pScript = 0;
833 }else if( objc==4 ){
834 pArray = 0;
835 pScript = objv[3];
836 }else{
837 pArray = objv[3];
838 if( Tcl_GetString(pArray)[0]==0 ) pArray = 0;
839 pScript = objv[4];
840 }
danielk197730ccda12004-05-27 12:11:31 +0000841
drh1d895032004-08-26 00:56:05 +0000842 Tcl_IncrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +0000843 zSql = Tcl_GetStringFromObj(objv[2], 0);
drh90b6bb12004-09-13 13:16:31 +0000844 while( rc==TCL_OK && zSql[0] ){
drhfb7e7652005-01-24 00:28:42 +0000845 int i; /* Loop counter */
846 int nVar; /* Number of bind parameters in the pStmt */
847 int nCol; /* Number of columns in the result set */
drh92febd92004-08-20 18:34:20 +0000848 Tcl_Obj **apColName = 0; /* Array of column names */
drhfb7e7652005-01-24 00:28:42 +0000849 int len; /* String length of zSql */
danielk197730ccda12004-05-27 12:11:31 +0000850
drhfb7e7652005-01-24 00:28:42 +0000851 /* Try to find a SQL statement that has already been compiled and
852 ** which matches the next sequence of SQL.
853 */
854 pStmt = 0;
855 pPreStmt = pDb->stmtList;
856 len = strlen(zSql);
857 if( pPreStmt && sqlite3_expired(pPreStmt->pStmt) ){
858 flushStmtCache(pDb);
859 pPreStmt = 0;
danielk197730ccda12004-05-27 12:11:31 +0000860 }
drhfb7e7652005-01-24 00:28:42 +0000861 for(; pPreStmt; pPreStmt=pPreStmt->pNext){
862 int n = pPreStmt->nSql;
863 if( len>=n
864 && memcmp(pPreStmt->zSql, zSql, n)==0
865 && (zSql[n]==0 || zSql[n-1]==';')
866 ){
867 pStmt = pPreStmt->pStmt;
868 zLeft = &zSql[pPreStmt->nSql];
869
870 /* When a prepared statement is found, unlink it from the
871 ** cache list. It will later be added back to the beginning
872 ** of the cache list in order to implement LRU replacement.
873 */
874 if( pPreStmt->pPrev ){
875 pPreStmt->pPrev->pNext = pPreStmt->pNext;
876 }else{
877 pDb->stmtList = pPreStmt->pNext;
878 }
879 if( pPreStmt->pNext ){
880 pPreStmt->pNext->pPrev = pPreStmt->pPrev;
881 }else{
882 pDb->stmtLast = pPreStmt->pPrev;
883 }
884 pDb->nStmt--;
885 break;
886 }
887 }
888
889 /* If no prepared statement was found. Compile the SQL text
890 */
drh92febd92004-08-20 18:34:20 +0000891 if( pStmt==0 ){
drhfb7e7652005-01-24 00:28:42 +0000892 if( SQLITE_OK!=sqlite3_prepare(pDb->db, zSql, -1, &pStmt, &zLeft) ){
drh92febd92004-08-20 18:34:20 +0000893 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
894 rc = TCL_ERROR;
895 break;
danielk197730ccda12004-05-27 12:11:31 +0000896 }
drhfb7e7652005-01-24 00:28:42 +0000897 if( pStmt==0 ){
898 if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
899 /* A compile-time error in the statement
900 */
901 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
902 rc = TCL_ERROR;
903 break;
904 }else{
905 /* The statement was a no-op. Continue to the next statement
906 ** in the SQL string.
907 */
908 zSql = zLeft;
909 continue;
910 }
911 }
912 assert( pPreStmt==0 );
danielk197730ccda12004-05-27 12:11:31 +0000913 }
914
drhfb7e7652005-01-24 00:28:42 +0000915 /* Bind values to parameters that begin with $ or :
916 */
drh92febd92004-08-20 18:34:20 +0000917 nVar = sqlite3_bind_parameter_count(pStmt);
drh1d895032004-08-26 00:56:05 +0000918 nParm = 0;
919 if( nVar>sizeof(aParm)/sizeof(aParm[0]) ){
920 apParm = (Tcl_Obj**)Tcl_Alloc(nVar*sizeof(apParm[0]));
921 }else{
922 apParm = aParm;
923 }
drh92febd92004-08-20 18:34:20 +0000924 for(i=1; i<=nVar; i++){
925 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
drhc8f90792005-01-12 00:08:24 +0000926 if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':') ){
drh92febd92004-08-20 18:34:20 +0000927 Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
928 if( pVar ){
929 int n;
930 u8 *data;
931 char *zType = pVar->typePtr ? pVar->typePtr->name : "";
932 char c = zType[0];
drhdf0bdda2005-06-25 19:31:48 +0000933 if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
934 /* Only load a BLOB type if the Tcl variable is a bytearray and
935 ** has no string representation. */
drh92febd92004-08-20 18:34:20 +0000936 data = Tcl_GetByteArrayFromObj(pVar, &n);
937 sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +0000938 Tcl_IncrRefCount(pVar);
939 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +0000940 }else if( (c=='b' && strcmp(zType,"boolean")==0) ||
941 (c=='i' && strcmp(zType,"int")==0) ){
942 Tcl_GetIntFromObj(interp, pVar, &n);
943 sqlite3_bind_int(pStmt, i, n);
944 }else if( c=='d' && strcmp(zType,"double")==0 ){
945 double r;
946 Tcl_GetDoubleFromObj(interp, pVar, &r);
947 sqlite3_bind_double(pStmt, i, r);
drhdf0bdda2005-06-25 19:31:48 +0000948 }else if( c=='w' && strcmp(zType,"wideInt")==0 ){
949 Tcl_WideInt v;
950 Tcl_GetWideIntFromObj(interp, pVar, &v);
951 sqlite3_bind_int64(pStmt, i, v);
drh92febd92004-08-20 18:34:20 +0000952 }else{
953 data = Tcl_GetStringFromObj(pVar, &n);
954 sqlite3_bind_text(pStmt, i, data, n, SQLITE_STATIC);
drh1d895032004-08-26 00:56:05 +0000955 Tcl_IncrRefCount(pVar);
956 apParm[nParm++] = pVar;
drh92febd92004-08-20 18:34:20 +0000957 }
drhfb7e7652005-01-24 00:28:42 +0000958 }else{
959 sqlite3_bind_null( pStmt, i );
drh92febd92004-08-20 18:34:20 +0000960 }
961 }
962 }
drh92febd92004-08-20 18:34:20 +0000963
964 /* Compute column names */
965 nCol = sqlite3_column_count(pStmt);
966 if( pScript ){
967 apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
968 if( apColName==0 ) break;
969 for(i=0; i<nCol; i++){
970 apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
971 Tcl_IncrRefCount(apColName[i]);
972 }
973 }
974
975 /* If results are being stored in an array variable, then create
976 ** the array(*) entry for that array
977 */
978 if( pArray ){
979 Tcl_Obj *pColList = Tcl_NewObj();
drh3ced14a2005-03-31 18:26:20 +0000980 Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
drh92febd92004-08-20 18:34:20 +0000981 Tcl_IncrRefCount(pColList);
982 for(i=0; i<nCol; i++){
983 Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
984 }
drh3ced14a2005-03-31 18:26:20 +0000985 Tcl_ObjSetVar2(interp, pArray, pStar, pColList,0);
986 Tcl_DecrRefCount(pColList);
987 Tcl_DecrRefCount(pStar);
drh92febd92004-08-20 18:34:20 +0000988 }
989
990 /* Execute the SQL
991 */
drh90b6bb12004-09-13 13:16:31 +0000992 while( rc==TCL_OK && pStmt && SQLITE_ROW==sqlite3_step(pStmt) ){
drh92febd92004-08-20 18:34:20 +0000993 for(i=0; i<nCol; i++){
danielk197730ccda12004-05-27 12:11:31 +0000994 Tcl_Obj *pVal;
995
996 /* Set pVal to contain the i'th column of this row. */
drh92febd92004-08-20 18:34:20 +0000997 switch( sqlite3_column_type(pStmt, i) ){
998 case SQLITE_BLOB: {
999 int bytes = sqlite3_column_bytes(pStmt, i);
1000 pVal = Tcl_NewByteArrayObj(sqlite3_column_blob(pStmt, i), bytes);
1001 break;
1002 }
1003 case SQLITE_INTEGER: {
1004 sqlite_int64 v = sqlite3_column_int64(pStmt, i);
1005 if( v>=-2147483647 && v<=2147483647 ){
1006 pVal = Tcl_NewIntObj(v);
1007 }else{
1008 pVal = Tcl_NewWideIntObj(v);
1009 }
1010 break;
1011 }
1012 case SQLITE_FLOAT: {
1013 double r = sqlite3_column_double(pStmt, i);
1014 pVal = Tcl_NewDoubleObj(r);
1015 break;
1016 }
danielk197755c45f22005-04-03 23:54:43 +00001017 case SQLITE_NULL: {
1018 pVal = dbTextToObj(pDb->zNull);
1019 break;
1020 }
drh92febd92004-08-20 18:34:20 +00001021 default: {
1022 pVal = dbTextToObj(sqlite3_column_text(pStmt, i));
1023 break;
1024 }
danielk197730ccda12004-05-27 12:11:31 +00001025 }
1026
drh92febd92004-08-20 18:34:20 +00001027 if( pScript ){
1028 if( pArray==0 ){
1029 Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001030 }else{
drh92febd92004-08-20 18:34:20 +00001031 Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
danielk197730ccda12004-05-27 12:11:31 +00001032 }
drh1807ce32004-09-07 13:20:35 +00001033 }else if( choice==DB_ONECOLUMN ){
1034 if( pRet==0 ){
1035 pRet = pVal;
1036 Tcl_IncrRefCount(pRet);
1037 }
drh90b6bb12004-09-13 13:16:31 +00001038 rc = TCL_BREAK;
danielk197730ccda12004-05-27 12:11:31 +00001039 }else{
danielk197730ccda12004-05-27 12:11:31 +00001040 Tcl_ListObjAppendElement(interp, pRet, pVal);
1041 }
1042 }
1043
drh92febd92004-08-20 18:34:20 +00001044 if( pScript ){
1045 rc = Tcl_EvalObjEx(interp, pScript, 0);
drh90b6bb12004-09-13 13:16:31 +00001046 if( rc==TCL_CONTINUE ){
1047 rc = TCL_OK;
1048 }
danielk197730ccda12004-05-27 12:11:31 +00001049 }
1050 }
drh90b6bb12004-09-13 13:16:31 +00001051 if( rc==TCL_BREAK ){
1052 rc = TCL_OK;
1053 }
drh92febd92004-08-20 18:34:20 +00001054
1055 /* Free the column name objects */
1056 if( pScript ){
1057 for(i=0; i<nCol; i++){
1058 Tcl_DecrRefCount(apColName[i]);
1059 }
1060 Tcl_Free((char*)apColName);
1061 }
1062
drh1d895032004-08-26 00:56:05 +00001063 /* Free the bound string and blob parameters */
1064 for(i=0; i<nParm; i++){
1065 Tcl_DecrRefCount(apParm[i]);
1066 }
1067 if( apParm!=aParm ){
1068 Tcl_Free((char*)apParm);
1069 }
1070
drhfb7e7652005-01-24 00:28:42 +00001071 /* Reset the statement. If the result code is SQLITE_SCHEMA, then
1072 ** flush the statement cache and try the statement again.
drh92febd92004-08-20 18:34:20 +00001073 */
drhfb7e7652005-01-24 00:28:42 +00001074 rc2 = sqlite3_reset(pStmt);
1075 if( SQLITE_SCHEMA==rc2 ){
1076 /* After a schema change, flush the cache and try to run the
1077 ** statement again
1078 */
1079 flushStmtCache( pDb );
1080 sqlite3_finalize(pStmt);
1081 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001082 continue;
drhfb7e7652005-01-24 00:28:42 +00001083 }else if( SQLITE_OK!=rc2 ){
1084 /* If a run-time error occurs, report the error and stop reading
1085 ** the SQL
1086 */
danielk1977ef2cb632004-05-29 02:37:19 +00001087 Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
drhfb7e7652005-01-24 00:28:42 +00001088 sqlite3_finalize(pStmt);
danielk197730ccda12004-05-27 12:11:31 +00001089 rc = TCL_ERROR;
drhfb7e7652005-01-24 00:28:42 +00001090 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
danielk197730ccda12004-05-27 12:11:31 +00001091 break;
drhfb7e7652005-01-24 00:28:42 +00001092 }else if( pDb->maxStmt<=0 ){
1093 /* If the cache is turned off, deallocated the statement */
1094 if( pPreStmt ) Tcl_Free((char*)pPreStmt);
1095 sqlite3_finalize(pStmt);
1096 }else{
1097 /* Everything worked and the cache is operational.
1098 ** Create a new SqlPreparedStmt structure if we need one.
1099 ** (If we already have one we can just reuse it.)
1100 */
1101 if( pPreStmt==0 ){
1102 len = zLeft - zSql;
1103 pPreStmt = (SqlPreparedStmt*)Tcl_Alloc( sizeof(*pPreStmt) + len );
1104 if( pPreStmt==0 ) return TCL_ERROR;
1105 pPreStmt->pStmt = pStmt;
1106 pPreStmt->nSql = len;
1107 memcpy(pPreStmt->zSql, zSql, len);
1108 pPreStmt->zSql[len] = 0;
1109 }
1110
1111 /* Add the prepared statement to the beginning of the cache list
1112 */
1113 pPreStmt->pNext = pDb->stmtList;
1114 pPreStmt->pPrev = 0;
1115 if( pDb->stmtList ){
1116 pDb->stmtList->pPrev = pPreStmt;
1117 }
1118 pDb->stmtList = pPreStmt;
1119 if( pDb->stmtLast==0 ){
1120 assert( pDb->nStmt==0 );
1121 pDb->stmtLast = pPreStmt;
1122 }else{
1123 assert( pDb->nStmt>0 );
1124 }
1125 pDb->nStmt++;
1126
1127 /* If we have too many statement in cache, remove the surplus from the
1128 ** end of the cache list.
1129 */
1130 while( pDb->nStmt>pDb->maxStmt ){
1131 sqlite3_finalize(pDb->stmtLast->pStmt);
1132 pDb->stmtLast = pDb->stmtLast->pPrev;
1133 Tcl_Free((char*)pDb->stmtLast->pNext);
1134 pDb->stmtLast->pNext = 0;
1135 pDb->nStmt--;
1136 }
danielk197730ccda12004-05-27 12:11:31 +00001137 }
1138
drhfb7e7652005-01-24 00:28:42 +00001139 /* Proceed to the next statement */
danielk197730ccda12004-05-27 12:11:31 +00001140 zSql = zLeft;
1141 }
drh1d895032004-08-26 00:56:05 +00001142 Tcl_DecrRefCount(objv[2]);
danielk197730ccda12004-05-27 12:11:31 +00001143
drh1807ce32004-09-07 13:20:35 +00001144 if( pRet ){
1145 if( rc==TCL_OK ){
1146 Tcl_SetObjResult(interp, pRet);
1147 }
1148 Tcl_DecrRefCount(pRet);
danielk197730ccda12004-05-27 12:11:31 +00001149 }
danielk197730ccda12004-05-27 12:11:31 +00001150 break;
1151 }
drhbec3f402000-08-04 13:49:02 +00001152
1153 /*
drhcabb0812002-09-14 13:47:32 +00001154 ** $db function NAME SCRIPT
1155 **
1156 ** Create a new SQL function called NAME. Whenever that function is
1157 ** called, invoke SCRIPT to evaluate the function.
1158 */
1159 case DB_FUNCTION: {
1160 SqlFunc *pFunc;
1161 char *zName;
1162 char *zScript;
1163 int nScript;
1164 if( objc!=4 ){
1165 Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1166 return TCL_ERROR;
1167 }
1168 zName = Tcl_GetStringFromObj(objv[2], 0);
1169 zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1170 pFunc = (SqlFunc*)Tcl_Alloc( sizeof(*pFunc) + nScript + 1 );
1171 if( pFunc==0 ) return TCL_ERROR;
1172 pFunc->interp = interp;
1173 pFunc->pNext = pDb->pFunc;
1174 pFunc->zScript = (char*)&pFunc[1];
drh0f14e2e2004-06-29 12:39:08 +00001175 pDb->pFunc = pFunc;
drhcabb0812002-09-14 13:47:32 +00001176 strcpy(pFunc->zScript, zScript);
danielk1977c8c11582004-06-29 13:41:21 +00001177 rc = sqlite3_create_function(pDb->db, zName, -1, SQLITE_UTF8,
danielk1977d8123362004-06-12 09:25:12 +00001178 pFunc, tclSqlFunc, 0, 0);
drhfb7e7652005-01-24 00:28:42 +00001179 if( rc!=SQLITE_OK ){
danielk19779636c4e2005-01-25 04:27:54 +00001180 rc = TCL_ERROR;
1181 Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
drhfb7e7652005-01-24 00:28:42 +00001182 }else{
1183 /* Must flush any cached statements */
1184 flushStmtCache( pDb );
1185 }
drhcabb0812002-09-14 13:47:32 +00001186 break;
1187 }
1188
1189 /*
drhaf9ff332002-01-16 21:00:27 +00001190 ** $db last_insert_rowid
1191 **
1192 ** Return an integer which is the ROWID for the most recent insert.
1193 */
1194 case DB_LAST_INSERT_ROWID: {
1195 Tcl_Obj *pResult;
1196 int rowid;
1197 if( objc!=2 ){
1198 Tcl_WrongNumArgs(interp, 2, objv, "");
1199 return TCL_ERROR;
1200 }
danielk19776f8a5032004-05-10 10:34:51 +00001201 rowid = sqlite3_last_insert_rowid(pDb->db);
drhaf9ff332002-01-16 21:00:27 +00001202 pResult = Tcl_GetObjResult(interp);
1203 Tcl_SetIntObj(pResult, rowid);
1204 break;
1205 }
1206
1207 /*
drh1807ce32004-09-07 13:20:35 +00001208 ** The DB_ONECOLUMN method is implemented together with DB_EVAL.
drh5d9d7572003-08-19 14:31:01 +00001209 */
drh1807ce32004-09-07 13:20:35 +00001210
1211 /* $db progress ?N CALLBACK?
1212 **
1213 ** Invoke the given callback every N virtual machine opcodes while executing
1214 ** queries.
1215 */
1216 case DB_PROGRESS: {
1217 if( objc==2 ){
1218 if( pDb->zProgress ){
1219 Tcl_AppendResult(interp, pDb->zProgress, 0);
1220 }
1221 }else if( objc==4 ){
1222 char *zProgress;
1223 int len;
1224 int N;
1225 if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
1226 return TCL_ERROR;
1227 };
1228 if( pDb->zProgress ){
1229 Tcl_Free(pDb->zProgress);
1230 }
1231 zProgress = Tcl_GetStringFromObj(objv[3], &len);
1232 if( zProgress && len>0 ){
1233 pDb->zProgress = Tcl_Alloc( len + 1 );
1234 strcpy(pDb->zProgress, zProgress);
1235 }else{
1236 pDb->zProgress = 0;
1237 }
1238#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1239 if( pDb->zProgress ){
1240 pDb->interp = interp;
1241 sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
1242 }else{
1243 sqlite3_progress_handler(pDb->db, 0, 0, 0);
1244 }
1245#endif
1246 }else{
1247 Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
drh5d9d7572003-08-19 14:31:01 +00001248 return TCL_ERROR;
1249 }
drh5d9d7572003-08-19 14:31:01 +00001250 break;
1251 }
1252
1253 /*
drh22fbcb82004-02-01 01:22:50 +00001254 ** $db rekey KEY
1255 **
1256 ** Change the encryption key on the currently open database.
1257 */
1258 case DB_REKEY: {
1259 int nKey;
1260 void *pKey;
1261 if( objc!=3 ){
1262 Tcl_WrongNumArgs(interp, 2, objv, "KEY");
1263 return TCL_ERROR;
1264 }
1265 pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
drh9eb9e262004-02-11 02:18:05 +00001266#ifdef SQLITE_HAS_CODEC
drh2011d5f2004-07-22 02:40:37 +00001267 rc = sqlite3_rekey(pDb->db, pKey, nKey);
drh22fbcb82004-02-01 01:22:50 +00001268 if( rc ){
danielk1977f20b21c2004-05-31 23:56:42 +00001269 Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
drh22fbcb82004-02-01 01:22:50 +00001270 rc = TCL_ERROR;
1271 }
1272#endif
1273 break;
1274 }
1275
1276 /*
drhbec3f402000-08-04 13:49:02 +00001277 ** $db timeout MILLESECONDS
1278 **
1279 ** Delay for the number of milliseconds specified when a file is locked.
1280 */
drh6d313162000-09-21 13:01:35 +00001281 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +00001282 int ms;
drh6d313162000-09-21 13:01:35 +00001283 if( objc!=3 ){
1284 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +00001285 return TCL_ERROR;
1286 }
drh6d313162000-09-21 13:01:35 +00001287 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
danielk19776f8a5032004-05-10 10:34:51 +00001288 sqlite3_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +00001289 break;
drh75897232000-05-29 14:26:00 +00001290 }
drhb5a20d32003-04-23 12:25:23 +00001291
drh0f14e2e2004-06-29 12:39:08 +00001292 /*
danielk197755c45f22005-04-03 23:54:43 +00001293 ** $db nullvalue ?STRING?
1294 **
1295 ** Change text used when a NULL comes back from the database. If ?STRING?
1296 ** is not present, then the current string used for NULL is returned.
1297 ** If STRING is present, then STRING is returned.
1298 **
1299 */
1300 case DB_NULLVALUE: {
1301 if( objc!=2 && objc!=3 ){
1302 Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
1303 return TCL_ERROR;
1304 }
1305 if( objc==3 ){
1306 int len;
1307 char *zNull = Tcl_GetStringFromObj(objv[2], &len);
1308 if( pDb->zNull ){
1309 Tcl_Free(pDb->zNull);
1310 }
1311 if( zNull && len>0 ){
1312 pDb->zNull = Tcl_Alloc( len + 1 );
1313 strncpy(pDb->zNull, zNull, len);
1314 pDb->zNull[len] = '\0';
1315 }else{
1316 pDb->zNull = 0;
1317 }
1318 }
1319 Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
1320 break;
1321 }
1322
1323 /*
drh0f14e2e2004-06-29 12:39:08 +00001324 ** $db total_changes
1325 **
1326 ** Return the number of rows that were modified, inserted, or deleted
1327 ** since the database handle was created.
1328 */
1329 case DB_TOTAL_CHANGES: {
1330 Tcl_Obj *pResult;
1331 if( objc!=2 ){
1332 Tcl_WrongNumArgs(interp, 2, objv, "");
1333 return TCL_ERROR;
1334 }
1335 pResult = Tcl_GetObjResult(interp);
1336 Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
1337 break;
1338 }
1339
drhb5a20d32003-04-23 12:25:23 +00001340 /* $db trace ?CALLBACK?
1341 **
1342 ** Make arrangements to invoke the CALLBACK routine for each SQL statement
1343 ** that is executed. The text of the SQL is appended to CALLBACK before
1344 ** it is executed.
1345 */
1346 case DB_TRACE: {
1347 if( objc>3 ){
1348 Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
drhb97759e2004-06-29 11:26:59 +00001349 return TCL_ERROR;
drhb5a20d32003-04-23 12:25:23 +00001350 }else if( objc==2 ){
1351 if( pDb->zTrace ){
1352 Tcl_AppendResult(interp, pDb->zTrace, 0);
1353 }
1354 }else{
1355 char *zTrace;
1356 int len;
1357 if( pDb->zTrace ){
1358 Tcl_Free(pDb->zTrace);
1359 }
1360 zTrace = Tcl_GetStringFromObj(objv[2], &len);
1361 if( zTrace && len>0 ){
1362 pDb->zTrace = Tcl_Alloc( len + 1 );
1363 strcpy(pDb->zTrace, zTrace);
1364 }else{
1365 pDb->zTrace = 0;
1366 }
1367 if( pDb->zTrace ){
1368 pDb->interp = interp;
danielk19776f8a5032004-05-10 10:34:51 +00001369 sqlite3_trace(pDb->db, DbTraceHandler, pDb);
drhb5a20d32003-04-23 12:25:23 +00001370 }else{
danielk19776f8a5032004-05-10 10:34:51 +00001371 sqlite3_trace(pDb->db, 0, 0);
drhb5a20d32003-04-23 12:25:23 +00001372 }
1373 }
1374 break;
1375 }
1376
tpoindex1067fe12004-12-17 15:41:11 +00001377 /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
1378 **
1379 ** Copy data into table from filename, optionally using SEPARATOR
1380 ** as column separators. If a column contains a null string, or the
1381 ** value of NULLINDICATOR, a NULL is inserted for the column.
1382 ** conflict-algorithm is one of the sqlite conflict algorithms:
1383 ** rollback, abort, fail, ignore, replace
1384 ** On success, return the number of lines processed, not necessarily same
1385 ** as 'db changes' due to conflict-algorithm selected.
1386 **
1387 ** This code is basically an implementation/enhancement of
1388 ** the sqlite3 shell.c ".import" command.
1389 **
1390 ** This command usage is equivalent to the sqlite2.x COPY statement,
1391 ** which imports file data into a table using the PostgreSQL COPY file format:
1392 ** $db copy $conflit_algo $table_name $filename \t \\N
1393 */
1394 case DB_COPY: {
tpoindex1067fe12004-12-17 15:41:11 +00001395 char *zTable; /* Insert data into this table */
1396 char *zFile; /* The file from which to extract data */
1397 char *zConflict; /* The conflict algorithm to use */
1398 sqlite3_stmt *pStmt; /* A statement */
1399 int rc; /* Result code */
1400 int nCol; /* Number of columns in the table */
1401 int nByte; /* Number of bytes in an SQL string */
1402 int i, j; /* Loop counters */
1403 int nSep; /* Number of bytes in zSep[] */
1404 int nNull; /* Number of bytes in zNull[] */
1405 char *zSql; /* An SQL statement */
1406 char *zLine; /* A single line of input from the file */
1407 char **azCol; /* zLine[] broken up into columns */
1408 char *zCommit; /* How to commit changes */
1409 FILE *in; /* The input file */
1410 int lineno = 0; /* Line number of input file */
1411 char zLineNum[80]; /* Line number print buffer */
1412 Tcl_Obj *pResult; /* interp result */
1413
drh9ee3cdc2004-12-17 20:48:06 +00001414 char *zSep;
1415 char *zNull;
1416 if( objc<5 || objc>7 ){
1417 Tcl_WrongNumArgs(interp, 2, objv,
1418 "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
1419 return TCL_ERROR;
1420 }
1421 if( objc>=6 ){
1422 zSep = Tcl_GetStringFromObj(objv[5], 0);
1423 }else{
1424 zSep = "\t";
1425 }
1426 if( objc>=7 ){
1427 zNull = Tcl_GetStringFromObj(objv[6], 0);
1428 }else{
1429 zNull = "";
1430 }
tpoindex1067fe12004-12-17 15:41:11 +00001431 zConflict = Tcl_GetStringFromObj(objv[2], 0);
1432 zTable = Tcl_GetStringFromObj(objv[3], 0);
1433 zFile = Tcl_GetStringFromObj(objv[4], 0);
1434 nSep = strlen(zSep);
1435 nNull = strlen(zNull);
1436 if( nSep==0 ){
1437 Tcl_AppendResult(interp, "Error: non-null separator required for copy", 0);
1438 return TCL_ERROR;
1439 }
1440 if(sqlite3StrICmp(zConflict, "rollback") != 0 &&
1441 sqlite3StrICmp(zConflict, "abort" ) != 0 &&
1442 sqlite3StrICmp(zConflict, "fail" ) != 0 &&
1443 sqlite3StrICmp(zConflict, "ignore" ) != 0 &&
1444 sqlite3StrICmp(zConflict, "replace" ) != 0 ) {
drh9ee3cdc2004-12-17 20:48:06 +00001445 Tcl_AppendResult(interp, "Error: \"", zConflict,
1446 "\", conflict-algorithm must be one of: rollback, "
1447 "abort, fail, ignore, or replace", 0);
tpoindex1067fe12004-12-17 15:41:11 +00001448 return TCL_ERROR;
1449 }
1450 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1451 if( zSql==0 ){
1452 Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
1453 return TCL_ERROR;
1454 }
1455 nByte = strlen(zSql);
1456 rc = sqlite3_prepare(pDb->db, zSql, 0, &pStmt, 0);
1457 sqlite3_free(zSql);
1458 if( rc ){
1459 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1460 nCol = 0;
1461 }else{
1462 nCol = sqlite3_column_count(pStmt);
1463 }
1464 sqlite3_finalize(pStmt);
1465 if( nCol==0 ) {
1466 return TCL_ERROR;
1467 }
1468 zSql = malloc( nByte + 50 + nCol*2 );
1469 if( zSql==0 ) {
1470 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1471 return TCL_ERROR;
1472 }
drh9ee3cdc2004-12-17 20:48:06 +00001473 sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
1474 zConflict, zTable);
tpoindex1067fe12004-12-17 15:41:11 +00001475 j = strlen(zSql);
1476 for(i=1; i<nCol; i++){
1477 zSql[j++] = ',';
1478 zSql[j++] = '?';
1479 }
1480 zSql[j++] = ')';
1481 zSql[j] = 0;
1482 rc = sqlite3_prepare(pDb->db, zSql, 0, &pStmt, 0);
1483 free(zSql);
1484 if( rc ){
1485 Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
1486 sqlite3_finalize(pStmt);
1487 return TCL_ERROR;
1488 }
1489 in = fopen(zFile, "rb");
1490 if( in==0 ){
1491 Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
1492 sqlite3_finalize(pStmt);
1493 return TCL_ERROR;
1494 }
1495 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1496 if( azCol==0 ) {
1497 Tcl_AppendResult(interp, "Error: can't malloc()", 0);
1498 return TCL_ERROR;
1499 }
1500 sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
1501 zCommit = "COMMIT";
1502 while( (zLine = local_getline(0, in))!=0 ){
1503 char *z;
1504 i = 0;
1505 lineno++;
1506 azCol[0] = zLine;
1507 for(i=0, z=zLine; *z; z++){
1508 if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
1509 *z = 0;
1510 i++;
1511 if( i<nCol ){
1512 azCol[i] = &z[nSep];
1513 z += nSep-1;
1514 }
1515 }
1516 }
1517 if( i+1!=nCol ){
1518 char *zErr;
1519 zErr = malloc(200 + strlen(zFile));
1520 sprintf(zErr,"Error: %s line %d: expected %d columns of data but found %d",
1521 zFile, lineno, nCol, i+1);
1522 Tcl_AppendResult(interp, zErr, 0);
1523 free(zErr);
1524 zCommit = "ROLLBACK";
1525 break;
1526 }
1527 for(i=0; i<nCol; i++){
1528 /* check for null data, if so, bind as null */
1529 if ((nNull>0 && strcmp(azCol[i], zNull)==0) || strlen(azCol[i])==0) {
1530 sqlite3_bind_null(pStmt, i+1);
1531 }else{
1532 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1533 }
1534 }
1535 sqlite3_step(pStmt);
1536 rc = sqlite3_reset(pStmt);
1537 free(zLine);
1538 if( rc!=SQLITE_OK ){
1539 Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
1540 zCommit = "ROLLBACK";
1541 break;
1542 }
1543 }
1544 free(azCol);
1545 fclose(in);
1546 sqlite3_finalize(pStmt);
1547 sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
1548
1549 if( zCommit[0] == 'C' ){
1550 /* success, set result as number of lines processed */
1551 pResult = Tcl_GetObjResult(interp);
1552 Tcl_SetIntObj(pResult, lineno);
1553 rc = TCL_OK;
1554 }else{
1555 /* failure, append lineno where failed */
1556 sprintf(zLineNum,"%d",lineno);
1557 Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
1558 rc = TCL_ERROR;
1559 }
1560 break;
1561 }
1562
danielk19774397de52005-01-12 12:44:03 +00001563 /* $db version
1564 **
1565 ** Return the version string for this database.
1566 */
1567 case DB_VERSION: {
1568 Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
1569 break;
1570 }
1571
tpoindex1067fe12004-12-17 15:41:11 +00001572
drh6d313162000-09-21 13:01:35 +00001573 } /* End of the SWITCH statement */
drh22fbcb82004-02-01 01:22:50 +00001574 return rc;
drh75897232000-05-29 14:26:00 +00001575}
1576
1577/*
drh9bb575f2004-09-06 17:24:11 +00001578** sqlite3 DBNAME FILENAME ?MODE? ?-key KEY?
drh75897232000-05-29 14:26:00 +00001579**
1580** This is the main Tcl command. When the "sqlite" Tcl command is
1581** invoked, this routine runs to process that command.
1582**
1583** The first argument, DBNAME, is an arbitrary name for a new
1584** database connection. This command creates a new command named
1585** DBNAME that is used to control that connection. The database
1586** connection is deleted when the DBNAME command is deleted.
1587**
1588** The second argument is the name of the directory that contains
1589** the sqlite database that is to be accessed.
drhfbc3eab2001-04-06 16:13:42 +00001590**
1591** For testing purposes, we also support the following:
1592**
drh9bb575f2004-09-06 17:24:11 +00001593** sqlite3 -encoding
drhfbc3eab2001-04-06 16:13:42 +00001594**
1595** Return the encoding used by LIKE and GLOB operators. Choices
1596** are UTF-8 and iso8859.
1597**
drh9bb575f2004-09-06 17:24:11 +00001598** sqlite3 -version
drh647cb0e2002-11-04 19:32:25 +00001599**
1600** Return the version number of the SQLite library.
1601**
drh9bb575f2004-09-06 17:24:11 +00001602** sqlite3 -tcl-uses-utf
drhfbc3eab2001-04-06 16:13:42 +00001603**
1604** Return "1" if compiled with a Tcl uses UTF-8. Return "0" if
1605** not. Used by tests to make sure the library was compiled
1606** correctly.
drh75897232000-05-29 14:26:00 +00001607*/
drh22fbcb82004-02-01 01:22:50 +00001608static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +00001609 SqliteDb *p;
drh22fbcb82004-02-01 01:22:50 +00001610 void *pKey = 0;
1611 int nKey = 0;
1612 const char *zArg;
drh75897232000-05-29 14:26:00 +00001613 char *zErrMsg;
drh22fbcb82004-02-01 01:22:50 +00001614 const char *zFile;
drh06b27182002-06-26 20:06:05 +00001615 char zBuf[80];
drh22fbcb82004-02-01 01:22:50 +00001616 if( objc==2 ){
1617 zArg = Tcl_GetStringFromObj(objv[1], 0);
drh22fbcb82004-02-01 01:22:50 +00001618 if( strcmp(zArg,"-version")==0 ){
danielk19776f8a5032004-05-10 10:34:51 +00001619 Tcl_AppendResult(interp,sqlite3_version,0);
drh647cb0e2002-11-04 19:32:25 +00001620 return TCL_OK;
1621 }
drh9eb9e262004-02-11 02:18:05 +00001622 if( strcmp(zArg,"-has-codec")==0 ){
1623#ifdef SQLITE_HAS_CODEC
drh22fbcb82004-02-01 01:22:50 +00001624 Tcl_AppendResult(interp,"1",0);
1625#else
1626 Tcl_AppendResult(interp,"0",0);
1627#endif
1628 return TCL_OK;
1629 }
1630 if( strcmp(zArg,"-tcl-uses-utf")==0 ){
drhfbc3eab2001-04-06 16:13:42 +00001631#ifdef TCL_UTF_MAX
1632 Tcl_AppendResult(interp,"1",0);
1633#else
1634 Tcl_AppendResult(interp,"0",0);
1635#endif
1636 return TCL_OK;
1637 }
1638 }
drh22fbcb82004-02-01 01:22:50 +00001639 if( objc==5 || objc==6 ){
1640 zArg = Tcl_GetStringFromObj(objv[objc-2], 0);
1641 if( strcmp(zArg,"-key")==0 ){
1642 pKey = Tcl_GetByteArrayFromObj(objv[objc-1], &nKey);
1643 objc -= 2;
1644 }
1645 }
1646 if( objc!=3 && objc!=4 ){
1647 Tcl_WrongNumArgs(interp, 1, objv,
drh9eb9e262004-02-11 02:18:05 +00001648#ifdef SQLITE_HAS_CODEC
1649 "HANDLE FILENAME ?-key CODEC-KEY?"
drh22fbcb82004-02-01 01:22:50 +00001650#else
1651 "HANDLE FILENAME ?MODE?"
1652#endif
1653 );
drh75897232000-05-29 14:26:00 +00001654 return TCL_ERROR;
1655 }
drh75897232000-05-29 14:26:00 +00001656 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +00001657 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +00001658 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +00001659 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
1660 return TCL_ERROR;
1661 }
1662 memset(p, 0, sizeof(*p));
drh22fbcb82004-02-01 01:22:50 +00001663 zFile = Tcl_GetStringFromObj(objv[2], 0);
danielk19774f057f92004-06-08 00:02:33 +00001664 sqlite3_open(zFile, &p->db);
danielk197780290862004-05-22 09:21:21 +00001665 if( SQLITE_OK!=sqlite3_errcode(p->db) ){
1666 zErrMsg = strdup(sqlite3_errmsg(p->db));
1667 sqlite3_close(p->db);
1668 p->db = 0;
1669 }
drh2011d5f2004-07-22 02:40:37 +00001670#ifdef SQLITE_HAS_CODEC
1671 sqlite3_key(p->db, pKey, nKey);
drheb8ed702004-02-11 10:37:23 +00001672#endif
drhbec3f402000-08-04 13:49:02 +00001673 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +00001674 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +00001675 Tcl_Free((char*)p);
drh75897232000-05-29 14:26:00 +00001676 free(zErrMsg);
1677 return TCL_ERROR;
1678 }
drhfb7e7652005-01-24 00:28:42 +00001679 p->maxStmt = NUM_PREPARED_STMTS;
drh22fbcb82004-02-01 01:22:50 +00001680 zArg = Tcl_GetStringFromObj(objv[1], 0);
1681 Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
drhc22bd472002-05-10 13:14:07 +00001682
drh06b27182002-06-26 20:06:05 +00001683 /* The return value is the value of the sqlite* pointer
1684 */
1685 sprintf(zBuf, "%p", p->db);
drh5e5377f2002-07-07 17:12:36 +00001686 if( strncmp(zBuf,"0x",2) ){
1687 sprintf(zBuf, "0x%p", p->db);
1688 }
drh06b27182002-06-26 20:06:05 +00001689 Tcl_AppendResult(interp, zBuf, 0);
1690
drhc22bd472002-05-10 13:14:07 +00001691 /* If compiled with SQLITE_TEST turned on, then register the "md5sum"
drh06b27182002-06-26 20:06:05 +00001692 ** SQL function.
drhc22bd472002-05-10 13:14:07 +00001693 */
drh28b4e482002-03-11 02:06:13 +00001694#ifdef SQLITE_TEST
1695 {
drh9bb575f2004-09-06 17:24:11 +00001696 extern void Md5_Register(sqlite3*);
drh3b93bc82005-01-13 23:54:32 +00001697#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00001698 int mallocfail = sqlite3_iMallocFail;
1699 sqlite3_iMallocFail = 0;
danielk19775b59af82004-06-30 12:42:59 +00001700#endif
drhc22bd472002-05-10 13:14:07 +00001701 Md5_Register(p->db);
drh3b93bc82005-01-13 23:54:32 +00001702#ifdef SQLITE_MEMDEBUG
danielk197713073932004-06-30 11:54:06 +00001703 sqlite3_iMallocFail = mallocfail;
danielk19775b59af82004-06-30 12:42:59 +00001704#endif
drh06b27182002-06-26 20:06:05 +00001705 }
drh28b4e482002-03-11 02:06:13 +00001706#endif
danielk19777cedc8d2004-06-10 10:50:08 +00001707 p->interp = interp;
drh75897232000-05-29 14:26:00 +00001708 return TCL_OK;
1709}
1710
1711/*
drh90ca9752001-09-28 17:47:14 +00001712** Provide a dummy Tcl_InitStubs if we are using this as a static
1713** library.
1714*/
1715#ifndef USE_TCL_STUBS
1716# undef Tcl_InitStubs
1717# define Tcl_InitStubs(a,b,c)
1718#endif
1719
1720/*
drh75897232000-05-29 14:26:00 +00001721** Initialize this module.
1722**
1723** This Tcl module contains only a single new Tcl command named "sqlite".
1724** (Hence there is no namespace. There is no point in using a namespace
1725** if the extension only supplies one new name!) The "sqlite" command is
1726** used to open a new SQLite database. See the DbMain() routine above
1727** for additional information.
1728*/
drh38f82712004-06-18 17:10:16 +00001729int Sqlite3_Init(Tcl_Interp *interp){
drh92febd92004-08-20 18:34:20 +00001730 Tcl_InitStubs(interp, "8.4", 0);
drhef4ac8f2004-06-19 00:16:31 +00001731 Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
1732 Tcl_PkgProvide(interp, "sqlite3", "3.0");
drh49766d62005-01-08 18:42:28 +00001733 Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
1734 Tcl_PkgProvide(interp, "sqlite", "3.0");
drh90ca9752001-09-28 17:47:14 +00001735 return TCL_OK;
1736}
drh49766d62005-01-08 18:42:28 +00001737int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
1738int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
1739int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
1740
1741#ifndef SQLITE_3_SUFFIX_ONLY
1742int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
1743int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
1744int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
1745int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
1746#endif
drh75897232000-05-29 14:26:00 +00001747
drh3e27c022004-07-23 00:01:38 +00001748#ifdef TCLSH
1749/*****************************************************************************
1750** The code that follows is used to build standalone TCL interpreters
drh75897232000-05-29 14:26:00 +00001751*/
drh348784e2000-05-29 20:41:49 +00001752
1753/*
drh3e27c022004-07-23 00:01:38 +00001754** If the macro TCLSH is one, then put in code this for the
1755** "main" routine that will initialize Tcl and take input from
1756** standard input.
drh348784e2000-05-29 20:41:49 +00001757*/
drh3e27c022004-07-23 00:01:38 +00001758#if TCLSH==1
drh348784e2000-05-29 20:41:49 +00001759static char zMainloop[] =
1760 "set line {}\n"
1761 "while {![eof stdin]} {\n"
1762 "if {$line!=\"\"} {\n"
1763 "puts -nonewline \"> \"\n"
1764 "} else {\n"
1765 "puts -nonewline \"% \"\n"
1766 "}\n"
1767 "flush stdout\n"
1768 "append line [gets stdin]\n"
1769 "if {[info complete $line]} {\n"
1770 "if {[catch {uplevel #0 $line} result]} {\n"
1771 "puts stderr \"Error: $result\"\n"
1772 "} elseif {$result!=\"\"} {\n"
1773 "puts $result\n"
1774 "}\n"
1775 "set line {}\n"
1776 "} else {\n"
1777 "append line \\n\n"
1778 "}\n"
1779 "}\n"
1780;
drh3e27c022004-07-23 00:01:38 +00001781#endif
1782
1783/*
1784** If the macro TCLSH is two, then get the main loop code out of
1785** the separate file "spaceanal_tcl.h".
1786*/
1787#if TCLSH==2
1788static char zMainloop[] =
1789#include "spaceanal_tcl.h"
1790;
1791#endif
drh348784e2000-05-29 20:41:49 +00001792
1793#define TCLSH_MAIN main /* Needed to fake out mktclapp */
1794int TCLSH_MAIN(int argc, char **argv){
1795 Tcl_Interp *interp;
drh297ecf12001-04-05 15:57:13 +00001796 Tcl_FindExecutable(argv[0]);
drh348784e2000-05-29 20:41:49 +00001797 interp = Tcl_CreateInterp();
drh38f82712004-06-18 17:10:16 +00001798 Sqlite3_Init(interp);
drhd9b02572001-04-15 00:37:09 +00001799#ifdef SQLITE_TEST
drhd1bf3512001-04-07 15:24:33 +00001800 {
1801 extern int Sqlitetest1_Init(Tcl_Interp*);
drh5c4d9702001-08-20 00:33:58 +00001802 extern int Sqlitetest2_Init(Tcl_Interp*);
1803 extern int Sqlitetest3_Init(Tcl_Interp*);
drha6064dc2003-12-19 02:52:05 +00001804 extern int Sqlitetest4_Init(Tcl_Interp*);
danielk1977998b56c2004-05-06 23:37:52 +00001805 extern int Sqlitetest5_Init(Tcl_Interp*);
drhefc251d2001-07-01 22:12:01 +00001806 extern int Md5_Init(Tcl_Interp*);
drh2e66f0b2005-04-28 17:18:48 +00001807 extern int Sqlitetestsse_Init(Tcl_Interp*);
1808
danielk19776490beb2004-05-11 06:17:21 +00001809 Sqlitetest1_Init(interp);
drh5c4d9702001-08-20 00:33:58 +00001810 Sqlitetest2_Init(interp);
drhde647132004-05-07 17:57:49 +00001811 Sqlitetest3_Init(interp);
danielk1977fc57d7b2004-05-26 02:04:57 +00001812 Sqlitetest4_Init(interp);
danielk1977998b56c2004-05-06 23:37:52 +00001813 Sqlitetest5_Init(interp);
drhefc251d2001-07-01 22:12:01 +00001814 Md5_Init(interp);
drh89dec812005-04-28 19:03:37 +00001815#ifdef SQLITE_SSE
drh2e66f0b2005-04-28 17:18:48 +00001816 Sqlitetestsse_Init(interp);
1817#endif
drhd1bf3512001-04-07 15:24:33 +00001818 }
1819#endif
drh3e27c022004-07-23 00:01:38 +00001820 if( argc>=2 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00001821 int i;
1822 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
1823 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
drh61212b62004-12-02 20:17:00 +00001824 for(i=3-TCLSH; i<argc; i++){
drh348784e2000-05-29 20:41:49 +00001825 Tcl_SetVar(interp, "argv", argv[i],
1826 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
1827 }
drh3e27c022004-07-23 00:01:38 +00001828 if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drh0de8c112002-07-06 16:32:14 +00001829 const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
drhc61053b2000-06-04 12:58:36 +00001830 if( zInfo==0 ) zInfo = interp->result;
1831 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +00001832 return 1;
1833 }
drh3e27c022004-07-23 00:01:38 +00001834 }
1835 if( argc<=1 || TCLSH==2 ){
drh348784e2000-05-29 20:41:49 +00001836 Tcl_GlobalEval(interp, zMainloop);
1837 }
1838 return 0;
1839}
1840#endif /* TCLSH */
drh6d313162000-09-21 13:01:35 +00001841
1842#endif /* !defined(NO_TCL) */