blob: 25f4086507c3edf8f688cc1b7652b31df9292786 [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**
drh7c68d602000-10-11 19:28:51 +000026** $Id: tclsqlite.c,v 1.11 2000/10/11 19:28:52 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;
drhbec3f402000-08-04 13:49:02 +0000141 Tcl_DString cmd;
142
143 Tcl_DStringInit(&cmd);
144 Tcl_DStringAppend(&cmd, pDb->zBusy, -1);
145 Tcl_DStringAppendElement(&cmd, zTable);
146 sprintf(zVal, " %d", nTries);
147 Tcl_DStringAppend(&cmd, zVal, -1);
148 zCmd = Tcl_DStringValue(&cmd);
149 rc = Tcl_Eval(pDb->interp, zCmd);
150 Tcl_DStringFree(&cmd);
151 if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
152 return 0;
153 }
154 return 1;
drh75897232000-05-29 14:26:00 +0000155}
156
157/*
158** The "sqlite" command below creates a new Tcl command for each
159** connection it opens to an SQLite database. This routine is invoked
160** whenever one of those connection-specific commands is executed
161** in Tcl. For example, if you run Tcl code like this:
162**
163** sqlite db1 "my_database"
164** db1 close
165**
166** The first command opens a connection to the "my_database" database
167** and calls that connection "db1". The second command causes this
168** subroutine to be invoked.
169*/
drh6d313162000-09-21 13:01:35 +0000170static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
drhbec3f402000-08-04 13:49:02 +0000171 SqliteDb *pDb = (SqliteDb*)cd;
drh6d313162000-09-21 13:01:35 +0000172 int choice;
173 static char *DB_optStrs[] = {
174 "busy", "close", "complete", "eval", "timeout"
175 };
176 enum DB_opts {
177 DB_BUSY, DB_CLOSE, DB_COMPLETE, DB_EVAL, DB_TIMEOUT
178 };
179
180 if( objc<2 ){
181 Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
drh75897232000-05-29 14:26:00 +0000182 return TCL_ERROR;
183 }
drh6d313162000-09-21 13:01:35 +0000184 if( Tcl_GetIndexFromObj(interp, objv[1], DB_optStrs, "option", 0, &choice) ){
185 return TCL_ERROR;
186 }
187
188 switch( (enum DB_opts)choice ){
drh75897232000-05-29 14:26:00 +0000189
drhbec3f402000-08-04 13:49:02 +0000190 /* $db busy ?CALLBACK?
191 **
192 ** Invoke the given callback if an SQL statement attempts to open
193 ** a locked database file.
194 */
drh6d313162000-09-21 13:01:35 +0000195 case DB_BUSY: {
196 if( objc>3 ){
197 Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
drhbec3f402000-08-04 13:49:02 +0000198 return TCL_ERROR;
drh6d313162000-09-21 13:01:35 +0000199 }else if( objc==2 ){
drhbec3f402000-08-04 13:49:02 +0000200 if( pDb->zBusy ){
201 Tcl_AppendResult(interp, pDb->zBusy, 0);
202 }
203 }else{
drh6d313162000-09-21 13:01:35 +0000204 char *zBusy;
205 int len;
drhbec3f402000-08-04 13:49:02 +0000206 if( pDb->zBusy ){
207 Tcl_Free(pDb->zBusy);
drhbec3f402000-08-04 13:49:02 +0000208 }
drh6d313162000-09-21 13:01:35 +0000209 zBusy = Tcl_GetStringFromObj(objv[2], &len);
210 if( zBusy && len>0 ){
211 pDb->zBusy = Tcl_Alloc( len + 1 );
212 strcpy(pDb->zBusy, zBusy);
213 }else{
214 pDb->zBusy = 0;
drhbec3f402000-08-04 13:49:02 +0000215 }
216 if( pDb->zBusy ){
217 pDb->interp = interp;
218 sqlite_busy_handler(pDb->db, DbBusyHandler, pDb);
drh6d313162000-09-21 13:01:35 +0000219 }else{
220 sqlite_busy_handler(pDb->db, 0, 0);
drhbec3f402000-08-04 13:49:02 +0000221 }
222 }
drh6d313162000-09-21 13:01:35 +0000223 break;
224 }
drhbec3f402000-08-04 13:49:02 +0000225
drh75897232000-05-29 14:26:00 +0000226 /* $db close
227 **
228 ** Shutdown the database
229 */
drh6d313162000-09-21 13:01:35 +0000230 case DB_CLOSE: {
231 Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
232 break;
233 }
drh75897232000-05-29 14:26:00 +0000234
235 /* $db complete SQL
236 **
237 ** Return TRUE if SQL is a complete SQL statement. Return FALSE if
238 ** additional lines of input are needed. This is similar to the
239 ** built-in "info complete" command of Tcl.
240 */
drh6d313162000-09-21 13:01:35 +0000241 case DB_COMPLETE: {
242 Tcl_Obj *pResult;
243 int isComplete;
244 if( objc!=3 ){
245 Tcl_WrongNumArgs(interp, 2, objv, "SQL");
drh75897232000-05-29 14:26:00 +0000246 return TCL_ERROR;
247 }
drh6d313162000-09-21 13:01:35 +0000248 isComplete = sqlite_complete( Tcl_GetStringFromObj(objv[2], 0) );
249 pResult = Tcl_GetObjResult(interp);
250 Tcl_SetBooleanObj(pResult, isComplete);
251 break;
252 }
drh75897232000-05-29 14:26:00 +0000253
254 /*
255 ** $db eval $sql ?array { ...code... }?
256 **
257 ** The SQL statement in $sql is evaluated. For each row, the values are
drhbec3f402000-08-04 13:49:02 +0000258 ** placed in elements of the array named "array" and ...code... is executed.
drh75897232000-05-29 14:26:00 +0000259 ** If "array" and "code" are omitted, then no callback is every invoked.
260 ** If "array" is an empty string, then the values are placed in variables
261 ** that have the same name as the fields extracted by the query.
262 */
drh6d313162000-09-21 13:01:35 +0000263 case DB_EVAL: {
drh75897232000-05-29 14:26:00 +0000264 CallbackData cbData;
265 char *zErrMsg;
drh6d313162000-09-21 13:01:35 +0000266 char *zSql;
drh75897232000-05-29 14:26:00 +0000267 int rc;
268
drh6d313162000-09-21 13:01:35 +0000269 if( objc!=5 && objc!=3 ){
270 Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME CODE?");
drh75897232000-05-29 14:26:00 +0000271 return TCL_ERROR;
272 }
drhbec3f402000-08-04 13:49:02 +0000273 pDb->interp = interp;
drh6d313162000-09-21 13:01:35 +0000274 zSql = Tcl_GetStringFromObj(objv[2], 0);
275 Tcl_IncrRefCount(objv[2]);
276 if( objc==5 ){
drh75897232000-05-29 14:26:00 +0000277 cbData.interp = interp;
drhdcc581c2000-05-30 13:44:19 +0000278 cbData.once = 1;
drh6d313162000-09-21 13:01:35 +0000279 cbData.zArray = Tcl_GetStringFromObj(objv[3], 0);
280 cbData.pCode = objv[4];
drh75897232000-05-29 14:26:00 +0000281 zErrMsg = 0;
drh6d313162000-09-21 13:01:35 +0000282 Tcl_IncrRefCount(objv[3]);
283 Tcl_IncrRefCount(objv[4]);
284 rc = sqlite_exec(pDb->db, zSql, DbEvalCallback, &cbData, &zErrMsg);
285 Tcl_DecrRefCount(objv[4]);
286 Tcl_DecrRefCount(objv[3]);
drh75897232000-05-29 14:26:00 +0000287 }else{
drh6d313162000-09-21 13:01:35 +0000288 Tcl_Obj *pList = Tcl_NewObj();
289 rc = sqlite_exec(pDb->db, zSql, DbEvalCallback2, pList, &zErrMsg);
290 Tcl_SetObjResult(interp, pList);
drh75897232000-05-29 14:26:00 +0000291 }
292 if( zErrMsg ){
293 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
294 free(zErrMsg);
295 }
drh6d313162000-09-21 13:01:35 +0000296 Tcl_DecrRefCount(objv[2]);
drh75897232000-05-29 14:26:00 +0000297 return rc;
drh6d313162000-09-21 13:01:35 +0000298 }
drhbec3f402000-08-04 13:49:02 +0000299
300 /*
301 ** $db timeout MILLESECONDS
302 **
303 ** Delay for the number of milliseconds specified when a file is locked.
304 */
drh6d313162000-09-21 13:01:35 +0000305 case DB_TIMEOUT: {
drhbec3f402000-08-04 13:49:02 +0000306 int ms;
drh6d313162000-09-21 13:01:35 +0000307 if( objc!=3 ){
308 Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
drhbec3f402000-08-04 13:49:02 +0000309 return TCL_ERROR;
310 }
drh6d313162000-09-21 13:01:35 +0000311 if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
drhbec3f402000-08-04 13:49:02 +0000312 sqlite_busy_timeout(pDb->db, ms);
drh6d313162000-09-21 13:01:35 +0000313 break;
drh75897232000-05-29 14:26:00 +0000314 }
drh6d313162000-09-21 13:01:35 +0000315 } /* End of the SWITCH statement */
drh75897232000-05-29 14:26:00 +0000316 return TCL_OK;
317}
318
319/*
320** sqlite DBNAME FILENAME ?MODE?
321**
322** This is the main Tcl command. When the "sqlite" Tcl command is
323** invoked, this routine runs to process that command.
324**
325** The first argument, DBNAME, is an arbitrary name for a new
326** database connection. This command creates a new command named
327** DBNAME that is used to control that connection. The database
328** connection is deleted when the DBNAME command is deleted.
329**
330** The second argument is the name of the directory that contains
331** the sqlite database that is to be accessed.
332*/
333static int DbMain(void *cd, Tcl_Interp *interp, int argc, char **argv){
334 int mode;
drhbec3f402000-08-04 13:49:02 +0000335 SqliteDb *p;
drh75897232000-05-29 14:26:00 +0000336 char *zErrMsg;
337 if( argc!=3 && argc!=4 ){
338 Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
339 " HANDLE FILENAME ?MODE?\"", 0);
340 return TCL_ERROR;
341 }
342 if( argc==3 ){
drh58b95762000-06-02 01:17:37 +0000343 mode = 0666;
drh75897232000-05-29 14:26:00 +0000344 }else if( Tcl_GetInt(interp, argv[3], &mode)!=TCL_OK ){
345 return TCL_ERROR;
346 }
347 zErrMsg = 0;
drh4cdc9e82000-08-04 14:56:24 +0000348 p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
drh75897232000-05-29 14:26:00 +0000349 if( p==0 ){
drhbec3f402000-08-04 13:49:02 +0000350 Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
351 return TCL_ERROR;
352 }
353 memset(p, 0, sizeof(*p));
354 p->db = sqlite_open(argv[2], mode, &zErrMsg);
355 if( p->db==0 ){
drh75897232000-05-29 14:26:00 +0000356 Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
drhbec3f402000-08-04 13:49:02 +0000357 Tcl_Free((char*)p);
drh75897232000-05-29 14:26:00 +0000358 free(zErrMsg);
359 return TCL_ERROR;
360 }
drh6d313162000-09-21 13:01:35 +0000361 Tcl_CreateObjCommand(interp, argv[1], DbObjCmd, (char*)p, DbDeleteCmd);
drh75897232000-05-29 14:26:00 +0000362 return TCL_OK;
363}
364
365/*
366** Initialize this module.
367**
368** This Tcl module contains only a single new Tcl command named "sqlite".
369** (Hence there is no namespace. There is no point in using a namespace
370** if the extension only supplies one new name!) The "sqlite" command is
371** used to open a new SQLite database. See the DbMain() routine above
372** for additional information.
373*/
374int Sqlite_Init(Tcl_Interp *interp){
375 Tcl_CreateCommand(interp, "sqlite", DbMain, 0, 0);
drh167a4b12000-08-17 09:49:59 +0000376 Tcl_PkgProvide(interp, "sqlite", "1.0");
drh75897232000-05-29 14:26:00 +0000377 return TCL_OK;
378}
379int Sqlite_SafeInit(Tcl_Interp *interp){
380 return TCL_OK;
381}
382
383/*
384** If compiled using mktclapp, this routine runs to initialize
385** everything.
386*/
387int Et_AppInit(Tcl_Interp *interp){
388 return Sqlite_Init(interp);
389}
drh348784e2000-05-29 20:41:49 +0000390
391/*
392** If the macro TCLSH is defined and is one, then put in code for the
393** "main" routine that will initialize Tcl.
394*/
395#if defined(TCLSH) && TCLSH==1
396static char zMainloop[] =
397 "set line {}\n"
398 "while {![eof stdin]} {\n"
399 "if {$line!=\"\"} {\n"
400 "puts -nonewline \"> \"\n"
401 "} else {\n"
402 "puts -nonewline \"% \"\n"
403 "}\n"
404 "flush stdout\n"
405 "append line [gets stdin]\n"
406 "if {[info complete $line]} {\n"
407 "if {[catch {uplevel #0 $line} result]} {\n"
408 "puts stderr \"Error: $result\"\n"
409 "} elseif {$result!=\"\"} {\n"
410 "puts $result\n"
411 "}\n"
412 "set line {}\n"
413 "} else {\n"
414 "append line \\n\n"
415 "}\n"
416 "}\n"
417;
418
419#define TCLSH_MAIN main /* Needed to fake out mktclapp */
420int TCLSH_MAIN(int argc, char **argv){
421 Tcl_Interp *interp;
422 interp = Tcl_CreateInterp();
423 Sqlite_Init(interp);
424 if( argc>=2 ){
425 int i;
426 Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
427 Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
428 for(i=2; i<argc; i++){
429 Tcl_SetVar(interp, "argv", argv[i],
430 TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
431 }
432 if( Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
drhc61053b2000-06-04 12:58:36 +0000433 char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
434 if( zInfo==0 ) zInfo = interp->result;
435 fprintf(stderr,"%s: %s\n", *argv, zInfo);
drh348784e2000-05-29 20:41:49 +0000436 return 1;
437 }
438 }else{
439 Tcl_GlobalEval(interp, zMainloop);
440 }
441 return 0;
442}
443#endif /* TCLSH */
drh6d313162000-09-21 13:01:35 +0000444
445#endif /* !defined(NO_TCL) */