blob: 0399b3f198b717b964e55ef6ea384795f436a18d [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
2** Copyright (c) 1999, 2000 D. Richard Hipp
3**
4** This program is free software; you can redistribute it and/or
5** modify it under the terms of the GNU General Public
6** License as published by the Free Software Foundation; either
7** version 2 of the License, or (at your option) any later version.
8**
9** This program is distributed in the hope that it will be useful,
10** but WITHOUT ANY WARRANTY; without even the implied warranty of
11** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12** General Public License for more details.
13**
14** You should have received a copy of the GNU General Public
15** License along with this library; if not, write to the
16** Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17** Boston, MA 02111-1307, USA.
18**
19** Author contact information:
20** drh@hwaci.com
21** http://www.hwaci.com/drh/
22**
23*************************************************************************
24** A TCL Interface to SQLite
25**
drh9b0d0a82000-09-30 22:46:05 +000026** $Id: tclsqlite.c,v 1.10 2000/09/30 22:46:07 drh Exp $
drh75897232000-05-29 14:26:00 +000027*/
drh6d313162000-09-21 13:01:35 +000028#ifndef NO_TCL /* Omit this whole file if TCL is unavailable */
29
drh75897232000-05-29 14:26:00 +000030#include "sqlite.h"
31#include <tcl.h>
32#include <stdlib.h>
33#include <string.h>
34
35/*
drhbec3f402000-08-04 13:49:02 +000036** There is one instance of this structure for each SQLite database
37** that has been opened by the SQLite TCL interface.
38*/
39typedef struct SqliteDb SqliteDb;
40struct SqliteDb {
41 sqlite *db; /* The "real" database structure */
42 Tcl_Interp *interp; /* The interpreter used for this database */
drh6d313162000-09-21 13:01:35 +000043 char *zBusy; /* The busy callback routine */
drhbec3f402000-08-04 13:49:02 +000044};
45
46/*
drh75897232000-05-29 14:26:00 +000047** An instance of this structure passes information thru the sqlite
48** logic from the original TCL command into the callback routine.
49*/
50typedef struct CallbackData CallbackData;
51struct CallbackData {
52 Tcl_Interp *interp; /* The TCL interpreter */
53 char *zArray; /* The array into which data is written */
drh6d313162000-09-21 13:01:35 +000054 Tcl_Obj *pCode; /* The code to execute for each row */
drh75897232000-05-29 14:26:00 +000055 int once; /* Set only for the first invocation of callback */
56};
57
58/*
59** Called for each row of the result.
60*/
61static int DbEvalCallback(
62 void *clientData, /* An instance of CallbackData */
63 int nCol, /* Number of columns in the result */
64 char ** azCol, /* Data for each column */
65 char ** azN /* Name for each column */
66){
67 CallbackData *cbData = (CallbackData*)clientData;
68 int i, rc;
69 if( cbData->zArray[0] ){
70 if( cbData->once ){
drh9b0d0a82000-09-30 22:46:05 +000071 Tcl_SetVar2(cbData->interp, cbData->zArray, "*", "", 0);
drh75897232000-05-29 14:26:00 +000072 for(i=0; i<nCol; i++){
73 Tcl_SetVar2(cbData->interp, cbData->zArray, "*", azN[i],
74 TCL_LIST_ELEMENT|TCL_APPEND_VALUE);
75 }
76 }
77 for(i=0; i<nCol; i++){
drhc61053b2000-06-04 12:58:36 +000078 char *z = azCol[i];
79 if( z==0 ) z = "";
80 Tcl_SetVar2(cbData->interp, cbData->zArray, azN[i], z, 0);
drh75897232000-05-29 14:26:00 +000081 }
82 }else{
83 for(i=0; i<nCol; i++){
drhc61053b2000-06-04 12:58:36 +000084 char *z = azCol[i];
85 if( z==0 ) z = "";
86 Tcl_SetVar(cbData->interp, azN[i], z, 0);
drh75897232000-05-29 14:26:00 +000087 }
88 }
89 cbData->once = 0;
drh6d313162000-09-21 13:01:35 +000090 rc = Tcl_EvalObj(cbData->interp, cbData->pCode);
drh9b0d0a82000-09-30 22:46:05 +000091 return rc!=TCL_OK && rc!=TCL_CONTINUE;
drh75897232000-05-29 14:26:00 +000092}
93
94/*
drh6d313162000-09-21 13:01:35 +000095** This is an alternative callback for database queries. Instead
96** of invoking a TCL script to handle the result, this callback just
97** appends each column of the result to a list. After the query
98** is complete, the list is returned.
99*/
100static int DbEvalCallback2(
101 void *clientData, /* An instance of CallbackData */
102 int nCol, /* Number of columns in the result */
103 char ** azCol, /* Data for each column */
104 char ** azN /* Name for each column */
105){
106 Tcl_Obj *pList = (Tcl_Obj*)clientData;
107 int i;
108 for(i=0; i<nCol; i++){
109 Tcl_Obj *pElem;
110 if( azCol[i] && *azCol[i] ){
111 pElem = Tcl_NewStringObj(azCol[i], -1);
112 }else{
113 pElem = Tcl_NewObj();
114 }
115 Tcl_ListObjAppendElement(0, pList, pElem);
116 }
117 return 0;
118}
119
120/*
drh75897232000-05-29 14:26:00 +0000121** Called when the command is deleted.
122*/
123static void DbDeleteCmd(void *db){
drhbec3f402000-08-04 13:49:02 +0000124 SqliteDb *pDb = (SqliteDb*)db;
125 sqlite_close(pDb->db);
126 if( pDb->zBusy ){
127 Tcl_Free(pDb->zBusy);
128 }
129 Tcl_Free((char*)pDb);
130}
131
132/*
133** This routine is called when a database file is locked while trying
134** to execute SQL.
135*/
136static int DbBusyHandler(void *cd, const char *zTable, int nTries){
137 SqliteDb *pDb = (SqliteDb*)cd;
138 int rc;
139 char zVal[30];
140 char *zCmd;
141 char *zResult;
142 Tcl_DString cmd;
143
144 Tcl_DStringInit(&cmd);
145 Tcl_DStringAppend(&cmd, pDb->zBusy, -1);
146 Tcl_DStringAppendElement(&cmd, zTable);
147 sprintf(zVal, " %d", nTries);
148 Tcl_DStringAppend(&cmd, zVal, -1);
149 zCmd = Tcl_DStringValue(&cmd);
150 rc = Tcl_Eval(pDb->interp, zCmd);
151 Tcl_DStringFree(&cmd);
152 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
153 return 0;
154 }
155 return 1;
drh75897232000-05-29 14:26:00 +0000156}
157
158/*
159** The "sqlite" command below creates a new Tcl command for each
160** connection it opens to an SQLite database. This routine is invoked
161** whenever one of those connection-specific commands is executed
162** in Tcl. For example, if you run Tcl code like this:
163**
164** sqlite db1 "my_database"
165** db1 close
166**
167** The first command opens a connection to the "my_database" database
168** and calls that connection "db1". The second command causes this
169** subroutine to be invoked.
170*/
drh6d313162000-09-21 13:01:35 +0000171static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +0000172 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +0000173 int choice;
174 static char *DB_optStrs[] = {
175 "busy", "close", "complete", "eval", "timeout"
176 };
177 enum DB_opts {
178 DB_BUSY, DB_CLOSE, DB_COMPLETE, DB_EVAL, DB_TIMEOUT
179 };
180
181 if( objc<2 ){
182 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +0000183 return TCL_ERROR;
184 }
drh6d313162000-09-21 13:01:35 +0000185 if( Tcl_GetIndexFromObj(interp, objv[1], DB_optStrs, "option", 0, &choice) ){
186 return TCL_ERROR;
187 }
188
189 switch( (enum DB_opts)choice ){
drh75897232000-05-29 14:26:00 +0000190
drhbec3f402000-08-04 13:49:02 +0000191 /* $db busy ?CALLBACK?
192 **
193 ** Invoke the given callback if an SQL statement attempts to open
194 ** a locked database file.
195 */
drh6d313162000-09-21 13:01:35 +0000196 case DB_BUSY: {
197 if( objc>3 ){
198 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +0000199 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +0000200 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +0000201 if( pDb->zBusy ){
202 Tcl_AppendResult(interp, pDb->zBusy, 0);
203 }
204 }else{
drh6d313162000-09-21 13:01:35 +0000205 char *zBusy;
206 int len;
drhbec3f402000-08-04 13:49:02 +0000207 if( pDb->zBusy ){
208 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +0000209 }
drh6d313162000-09-21 13:01:35 +0000210 zBusy = Tcl_GetStringFromObj(objv[2], &len);
211 if( zBusy && len>0 ){
212 pDb->zBusy = Tcl_Alloc( len + 1 );
213 strcpy(pDb->zBusy, zBusy);
214 }else{
215 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +0000216 }
217 if( pDb->zBusy ){
218 pDb->interp = interp;
219 sqlite_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +0000220 }else{
221 sqlite_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +0000222 }
223 }
drh6d313162000-09-21 13:01:35 +0000224 break;
225 }
drhbec3f402000-08-04 13:49:02 +0000226
drh75897232000-05-29 14:26:00 +0000227 /* $db close
228 **
229 ** Shutdown the database
230 */
drh6d313162000-09-21 13:01:35 +0000231 case DB_CLOSE: {
232 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
233 break;
234 }
drh75897232000-05-29 14:26:00 +0000235
236 /* $db complete SQL
237 **
238 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
239 ** additional lines of input are needed. This is similar to the
240 ** built-in "info complete" command of Tcl.
241 */
drh6d313162000-09-21 13:01:35 +0000242 case DB_COMPLETE: {
243 Tcl_Obj *pResult;
244 int isComplete;
245 if( objc!=3 ){
246 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +0000247 return TCL_ERROR;
248 }
drh6d313162000-09-21 13:01:35 +0000249 isComplete = sqlite_complete( Tcl_GetStringFromObj(objv[2], 0) );
250 pResult = Tcl_GetObjResult(interp);
251 Tcl_SetBooleanObj(pResult, isComplete);
252 break;
253 }
drh75897232000-05-29 14:26:00 +0000254
255 /*
256 ** $db eval $sql ?array { ...code... }?
257 **
258 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +0000259 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +0000260 ** If "array" and "code" are omitted, then no callback is every invoked.
261 ** If "array" is an empty string, then the values are placed in variables
262 ** that have the same name as the fields extracted by the query.
263 */
drh6d313162000-09-21 13:01:35 +0000264 case DB_EVAL: {
drh75897232000-05-29 14:26:00 +0000265 CallbackData cbData;
266 char *zErrMsg;
drh6d313162000-09-21 13:01:35 +0000267 char *zSql;
drh75897232000-05-29 14:26:00 +0000268 int rc;
269
drh6d313162000-09-21 13:01:35 +0000270 if( objc!=5 && objc!=3 ){
271 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME CODE?");
drh75897232000-05-29 14:26:00 +0000272 return TCL_ERROR;
273 }
drhbec3f402000-08-04 13:49:02 +0000274 pDb->interp = interp;
drh6d313162000-09-21 13:01:35 +0000275 zSql = Tcl_GetStringFromObj(objv[2], 0);
276 Tcl_IncrRefCount(objv[2]);
277 if( objc==5 ){
drh75897232000-05-29 14:26:00 +0000278 cbData.interp = interp;
drhdcc581c2000-05-30 13:44:19 +0000279 cbData.once = 1;
drh6d313162000-09-21 13:01:35 +0000280 cbData.zArray = Tcl_GetStringFromObj(objv[3], 0);
281 cbData.pCode = objv[4];
drh75897232000-05-29 14:26:00 +0000282 zErrMsg = 0;
drh6d313162000-09-21 13:01:35 +0000283 Tcl_IncrRefCount(objv[3]);
284 Tcl_IncrRefCount(objv[4]);
285 rc = sqlite_exec(pDb->db, zSql, DbEvalCallback, &cbData, &zErrMsg);
286 Tcl_DecrRefCount(objv[4]);
287 Tcl_DecrRefCount(objv[3]);
drh75897232000-05-29 14:26:00 +0000288 }else{
drh6d313162000-09-21 13:01:35 +0000289 Tcl_Obj *pList = Tcl_NewObj();
290 rc = sqlite_exec(pDb->db, zSql, DbEvalCallback2, pList, &zErrMsg);
291 Tcl_SetObjResult(interp, pList);
drh75897232000-05-29 14:26:00 +0000292 }
293 if( zErrMsg ){
294 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
295 free(zErrMsg);
296 }
drh6d313162000-09-21 13:01:35 +0000297 Tcl_DecrRefCount(objv[2]);
drh75897232000-05-29 14:26:00 +0000298 return rc;
drh6d313162000-09-21 13:01:35 +0000299 }
drhbec3f402000-08-04 13:49:02 +0000300
301 /*
302 ** $db timeout MILLESECONDS
303 **
304 ** Delay for the number of milliseconds specified when a file is locked.
305 */
drh6d313162000-09-21 13:01:35 +0000306 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +0000307 int ms;
drh6d313162000-09-21 13:01:35 +0000308 if( objc!=3 ){
309 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +0000310 return TCL_ERROR;
311 }
drh6d313162000-09-21 13:01:35 +0000312 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
drhbec3f402000-08-04 13:49:02 +0000313 sqlite_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +0000314 break;
drh75897232000-05-29 14:26:00 +0000315 }
drh6d313162000-09-21 13:01:35 +0000316 } /* End of the SWITCH statement */
drh75897232000-05-29 14:26:00 +0000317 return TCL_OK;
318}
319
320/*
321** sqlite DBNAME FILENAME ?MODE?
322**
323** This is the main Tcl command. When the "sqlite" Tcl command is
324** invoked, this routine runs to process that command.
325**
326** The first argument, DBNAME, is an arbitrary name for a new
327** database connection. This command creates a new command named
328** DBNAME that is used to control that connection. The database
329** connection is deleted when the DBNAME command is deleted.
330**
331** The second argument is the name of the directory that contains
332** the sqlite database that is to be accessed.
333*/
334static int DbMain(void *cd, Tcl_Interp *interp, int argc, char **argv){
335 int mode;
drhbec3f402000-08-04 13:49:02 +0000336 SqliteDb *p;
drh75897232000-05-29 14:26:00 +0000337 char *zErrMsg;
338 if( argc!=3 && argc!=4 ){
339 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
340 " HANDLE FILENAME ?MODE?\"", 0);
341 return TCL_ERROR;
342 }
343 if( argc==3 ){
drh58b95762000-06-02 01:17:37 +0000344 mode = 0666;
drh75897232000-05-29 14:26:00 +0000345 }else if( Tcl_GetInt(interp, argv[3], &mode)!=TCL_OK ){
346 return TCL_ERROR;
347 }
348 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +0000349 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +0000350 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +0000351 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
352 return TCL_ERROR;
353 }
354 memset(p, 0, sizeof(*p));
355 p->db = sqlite_open(argv[2], mode, &zErrMsg);
356 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +0000357 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +0000358 Tcl_Free((char*)p);
drh75897232000-05-29 14:26:00 +0000359 free(zErrMsg);
360 return TCL_ERROR;
361 }
drh6d313162000-09-21 13:01:35 +0000362 Tcl_CreateObjCommand(interp, argv[1], DbObjCmd, (char*)p, DbDeleteCmd);
drh75897232000-05-29 14:26:00 +0000363 return TCL_OK;
364}
365
366/*
367** Initialize this module.
368**
369** This Tcl module contains only a single new Tcl command named "sqlite".
370** (Hence there is no namespace. There is no point in using a namespace
371** if the extension only supplies one new name!) The "sqlite" command is
372** used to open a new SQLite database. See the DbMain() routine above
373** for additional information.
374*/
375int Sqlite_Init(Tcl_Interp *interp){
376 Tcl_CreateCommand(interp, "sqlite", DbMain, 0, 0);
drh167a4b12000-08-17 09:49:59 +0000377 Tcl_PkgProvide(interp, "sqlite", "1.0");
drh75897232000-05-29 14:26:00 +0000378 return TCL_OK;
379}
380int Sqlite_SafeInit(Tcl_Interp *interp){
381 return TCL_OK;
382}
383
384/*
385** If compiled using mktclapp, this routine runs to initialize
386** everything.
387*/
388int Et_AppInit(Tcl_Interp *interp){
389 return Sqlite_Init(interp);
390}
drh348784e2000-05-29 20:41:49 +0000391
392/*
393** If the macro TCLSH is defined and is one, then put in code for the
394** "main" routine that will initialize Tcl.
395*/
396#if defined(TCLSH) && TCLSH==1
397static char zMainloop[] =
398 "set line {}\n"
399 "while {![eof stdin]} {\n"
400 "if {$line!=\"\"} {\n"
401 "puts -nonewline \"> \"\n"
402 "} else {\n"
403 "puts -nonewline \"% \"\n"
404 "}\n"
405 "flush stdout\n"
406 "append line [gets stdin]\n"
407 "if {[info complete $line]} {\n"
408 "if {[catch {uplevel #0 $line} result]} {\n"
409 "puts stderr \"Error: $result\"\n"
410 "} elseif {$result!=\"\"} {\n"
411 "puts $result\n"
412 "}\n"
413 "set line {}\n"
414 "} else {\n"
415 "append line \\n\n"
416 "}\n"
417 "}\n"
418;
419
420#define TCLSH_MAIN main /* Needed to fake out mktclapp */
421int TCLSH_MAIN(int argc, char **argv){
422 Tcl_Interp *interp;
423 interp = Tcl_CreateInterp();
424 Sqlite_Init(interp);
425 if( argc>=2 ){
426 int i;
427 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
428 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
429 for(i=2; i<argc; i++){
430 Tcl_SetVar(interp, "argv", argv[i],
431 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
432 }
433 if( Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drhc61053b2000-06-04 12:58:36 +0000434 char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
435 if( zInfo==0 ) zInfo = interp->result;
436 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +0000437 return 1;
438 }
439 }else{
440 Tcl_GlobalEval(interp, zMainloop);
441 }
442 return 0;
443}
444#endif /* TCLSH */
drh6d313162000-09-21 13:01:35 +0000445
446#endif /* !defined(NO_TCL) */