File: msqltcl.c

package info (click to toggle)
scotty 2.1.9-1
  • links: PTS
  • area: main
  • in suites: hamm
  • size: 9,984 kB
  • ctags: 4,313
  • sloc: ansic: 35,946; sh: 12,591; tcl: 8,122; yacc: 2,442; makefile: 898; lex: 370
file content (1490 lines) | stat: -rw-r--r-- 37,311 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
/*
 * $Id: msqltcl.c,v 1.50 1995/06/06 14:25:25 hs Rel $
 *
 * MSQL interface to Tcl
 *
 * Hakan Soderstrom, hs@soderstrom.se
 *
 */

#include <tnmInt.h>
#include <tnmPort.h>

#ifdef HAVE_MSQL

/*
 * Copyright (c) 1994, 1995 Hakan Soderstrom and Tom Poindexter
 * 
 * Permission to use, copy, modify, distribute, and sell this software
 * and its documentation for any purpose is hereby granted without fee,
 * provided that the above copyright notice and this permission notice
 * appear in all copies of the software and related documentation.
 * 
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
 *
 * IN NO EVENT SHALL HAKAN SODERSTROM OR SODERSTROM PROGRAMVARUVERKSTAD
 * AB BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL
 * DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
 * OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY
 * OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <tcl.h>
#include <msql.h>

#include <errno.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>


#define MSQL_HANDLES      15	/* Default number of handles available. */
#define MSQL_BUFF_SIZE	1024	/* Conversion buffer size for various needs. */
#define MSQL_SMALL_SIZE  TCL_RESULT_SIZE /* Smaller buffer size. */
#define MSQL_NAME_LEN     80    /* Max. host, database name length. */

typedef struct MsqlTclHandle {
  int connection ;         /* Connection handle, if connected; -1 otherwise. */
  char host[MSQL_NAME_LEN] ;      /* Host name, if connected. */
  char database[MSQL_NAME_LEN] ;  /* Db name, if selected; NULL otherwise. */
  m_result* result ;              /* Stored result, if any; NULL otherwise. */
  int res_count ;                 /* Count of unfetched rows in result. */
  int col_count ;                 /* Column count in result, if any. */
} MsqlTclHandle;

static MsqlTclHandle   MsqlHandle[MSQL_HANDLES];  

static char *MsqlHandlePrefix = "msql";
/* Prefix string used to identify handles.
 * The following must be strlen(MsqlHandlePrefix).
 */
#define MSQL_HPREFIX_LEN 4

/* Array for status info, and its elements. */
static char *MsqlStatusArr = "msqlstatus";
#define MSQL_STATUS_CODE "code"
#define MSQL_STATUS_CMD  "command"
#define MSQL_STATUS_MSG  "message"
#define MSQL_STATUS_NULLV  "nullvalue"

/* C variable corresponding to msqlstatus(nullvalue) */
static char* MsqlNullvalue = NULL ;
#define MSQL_NULLV_INIT ""

/* Options to the 'info', 'result', 'col' combo commands. */
     
static char* MsqlDbOpt[] =
{
  "dbname", "dbname?", "tables", "host", "host?", "databases"
};
#define MSQL_INFNAME_OPT 0
#define MSQL_INFNAMEQ_OPT 1
#define MSQL_INFTABLES_OPT 2
#define MSQL_INFHOST_OPT 3
#define MSQL_INFHOSTQ_OPT 4
#define MSQL_INFLIST_OPT 5

#define MSQL_INF_OPT_MAX 5

static char* MsqlResultOpt[] =
{
  "rows", "rows?", "cols", "cols?", "current", "current?"
};
#define MSQL_RESROWS_OPT 0
#define MSQL_RESROWSQ_OPT 1
#define MSQL_RESCOLS_OPT 2
#define MSQL_RESCOLSQ_OPT 3
#define MSQL_RESCUR_OPT 4
#define MSQL_RESCURQ_OPT 5

#define MSQL_RES_OPT_MAX 5

/* Column info definitions. */

static char* MsqlColkey[] =
{
  "table", "name", "type", "length", "prim_key", "non_null"
};

#define MSQL_COL_TABLE_K 0
#define MSQL_COL_NAME_K 1
#define MSQL_COL_TYPE_K 2
#define MSQL_COL_LENGTH_K 3
#define MSQL_COL_PRIMKEY_K 4
#define MSQL_COL_NONNULL_K 5

#define MSQL_COL_K_MAX 5

/* Macro for checking handle syntax; arguments:
 * 'h' must point to the handle.
 * 'H' must be an int variable.
 * RETURNS the handle index; or -1 on syntax conflict.
 * SIDE EFFECT: 'H' will contain the handle index on success.
 * 'h' will point to the first digit on success.
 * ASSUMES constant MSQL_HANDLES >= 10.
 */
#define HSYNTAX(h,H) \
(((strncmp(h,MsqlHandlePrefix,MSQL_HPREFIX_LEN) == 0) && \
(h+=MSQL_HPREFIX_LEN) && isdigit(h[0]))? \
 (((H=h[0]-'0')+1 && h[1]=='\0')?H: \
  ((isdigit(h[1]) && h[2]=='\0' && (H=10*H+h[1]-'0')<MSQL_HANDLES)?H:-1)) \
:-1)


/* Prototypes for all functions. */

extern Tcl_CmdProc  Msqltcl_Connect;
extern Tcl_CmdProc  Msqltcl_Use;
extern Tcl_CmdProc  Msqltcl_Sel;
extern Tcl_CmdProc  Msqltcl_Next;
extern Tcl_CmdProc  Msqltcl_Seek;
extern Tcl_CmdProc  Msqltcl_Map;
extern Tcl_CmdProc  Msqltcl_Exec;
extern Tcl_CmdProc  Msqltcl_Close;
extern Tcl_CmdProc  Msqltcl_Info;
extern Tcl_CmdProc  Msqltcl_Result;
extern Tcl_CmdProc  Msqltcl_Col;
extern Tcl_CmdProc  Msqltcl_State;

  
/* CONFLICT HANDLING
 *
 * Every command begins by calling 'msql_prologue'.
 * This function resets msqlstatus(code) to zero; the other array elements
 * retain their previous values.
 * The function also saves argc/argv in global variables.
 * After this the command processing proper begins.
 *
 * If there is a conflict, the message is taken from one of the following
 * sources,
 * -- this code (msql_prim_confl),
 * -- the database server (msql_server_confl),
 * -- a POSIX (system call) diagnostic.
 * A complete message is put together from the above plus the name of the
 * command where the conflict was detected.
 * The complete message is returned as the Tcl result and is also stored in
 * msqlstatus(message).
 * msqlstatus(code) is set to "-1", except for POSIX conflicts where 'errno'
 * is used.
 * In addition, the whole command where the conflict was detected is put
 * together from the saved argc/argv and is copied into msqlstatus(command).
 */

static Tcl_Interp* saved_interp;
static int saved_argc;
static char** saved_argv;


/*
 *----------------------------------------------------------------------
 * msql_reassemble
 * Reassembles the current command from the saved argv; copies it into
 * msqlstatus(command).
 */

static void
msql_reassemble ()
{
  unsigned int flags = TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT;
  int idx ;

  for (idx = 0; idx < saved_argc; ++idx)
    {
      Tcl_SetVar2 (saved_interp, MsqlStatusArr, MSQL_STATUS_CMD,
		   saved_argv[idx], flags) ;
      flags |= TCL_APPEND_VALUE ;
    }
}


/*
 *----------------------------------------------------------------------
 * msql_posix_confl
 * Conflict handling after a failed system call.
 */

static int
msql_posix_confl (syscall)
     char* syscall;
{
  char buf[MSQL_SMALL_SIZE];
  char* strerror () ;
  char* msg = strerror (errno) ;

  sprintf(buf, "%d", errno) ;
  Tcl_SetVar2 (saved_interp, MsqlStatusArr, MSQL_STATUS_CODE, buf,
	       TCL_GLOBAL_ONLY);
  Tcl_SetResult (saved_interp, "", TCL_STATIC) ;
  Tcl_AppendResult (saved_interp, saved_argv[0], "/POSIX: (", syscall,
		    ") ", (msg == NULL) ? "" : msg, (char*)NULL);
  Tcl_SetVar2 (saved_interp, MsqlStatusArr, MSQL_STATUS_MSG,
	       saved_interp->result, TCL_GLOBAL_ONLY);
  msql_reassemble () ;
  return TCL_ERROR ;
}


/*
 *----------------------------------------------------------------------
 * msql_prim_confl
 * Conflict handling after a primitive conflict.
 *
 */

static int
msql_prim_confl (msg)
     char* msg ;
{
  Tcl_SetVar2 (saved_interp, MsqlStatusArr, MSQL_STATUS_CODE, "-1",
	       TCL_GLOBAL_ONLY);
  Tcl_SetResult (saved_interp, "", TCL_STATIC) ;
  Tcl_AppendResult (saved_interp, saved_argv[0], ": ", msg, (char*)NULL) ;
  Tcl_SetVar2 (saved_interp, MsqlStatusArr, MSQL_STATUS_MSG,
	       saved_interp->result, TCL_GLOBAL_ONLY);
  msql_reassemble () ;
  return TCL_ERROR ;
}


/*
 *----------------------------------------------------------------------
 * msql_server_confl
 * Conflict handling after an mSQL conflict.
 *
 */

static int
msql_server_confl ()
{
  Tcl_SetVar2 (saved_interp, MsqlStatusArr, MSQL_STATUS_CODE, "-1",
	       TCL_GLOBAL_ONLY);
  Tcl_SetResult (saved_interp, "", TCL_STATIC) ;
  Tcl_AppendResult (saved_interp, saved_argv[0], "/db server: ",
		    (msqlErrMsg == NULL) ? "" : msqlErrMsg, (char*)NULL) ;
  Tcl_SetVar2 (saved_interp, MsqlStatusArr, MSQL_STATUS_MSG,
	       saved_interp->result, TCL_GLOBAL_ONLY);
  msql_reassemble () ;
  return TCL_ERROR ;
}


/*----------------------------------------------------------------------
 * get_handle_plain
 * Check handle syntax (and nothing else).
 * RETURN: MsqlHandle index number or -1 on error.
 */
static int
get_handle_plain (handle) 
     char *handle;
{
  int hi ;
  char* hp = handle ;
  
  if (HSYNTAX(hp,hi) < 0)
    {
      msql_prim_confl ("weird handle") ; /*  */
      return -1 ;
    }
  else
    return hi ;
}


/*----------------------------------------------------------------------
 * get_handle_conn
 * Check handle syntax, verify that the handle is connected.
 * RETURN: MsqlHandle index number or -1 on error.
 */
static int
get_handle_conn (handle) 
     char *handle;
{
  int hi ;
  char* hp = handle ;

  if (HSYNTAX(hp,hi) < 0)
    {
      msql_prim_confl ("weird handle") ;
      return -1 ;
    }

  if (MsqlHandle[hi].connection < 0)
    {
      msql_prim_confl ("handle not connected") ;
      return -1 ;
    }
  else
    return hi ;
}


/*----------------------------------------------------------------------
 * get_handle_db
 * Check handle syntax, verify that the handle is connected and that
 * there is a current database.
 * RETURN: MsqlHandle index number or -1 on error.
 */
static int
get_handle_db (handle) 
     char *handle;
{
  int hi ;
  char* hp = handle ;

  if (HSYNTAX(hp,hi) < 0)
    {
      msql_prim_confl ("weird handle") ;
      return -1 ;
    }

  if (MsqlHandle[hi].connection < 0)
    {
      msql_prim_confl ("handle not connected") ;
      return -1 ;
    }

  if (MsqlHandle[hi].database[0] == '\0')
    {
      msql_prim_confl ("no current database") ;
      return -1 ;
    }
  else
    return hi ;
}


/*----------------------------------------------------------------------
 * get_handle_res
 * Check handle syntax, verify that the handle is connected and that
 * there is a current database and that there is a pending result.
 * RETURN: MsqlHandle index number or -1 on error.
 */

static int
get_handle_res (handle) 
     char *handle;
{
  int hi ;
  char* hp = handle ;

  if (HSYNTAX(hp,hi) < 0)
    {
      msql_prim_confl ("weird handle") ;
      return -1 ;
    }

  if (MsqlHandle[hi].connection < 0)
    {
      msql_prim_confl ("handle not connected") ;
      return -1 ;
    }

  if (MsqlHandle[hi].database[0] == '\0')
    {
      msql_prim_confl ("no current database") ;
      return -1 ;
    }

  if (MsqlHandle[hi].result == NULL)
    {
      msql_prim_confl ("no result pending") ; /*  */
      return -1 ;
    }
  else
    return hi ;
}


/* 
 *----------------------------------------------------------------------
 * handle_init
 * Initialize the handle array.
 */
static void 
handle_init () 
{
  int i ;

  for (i = 0; i < MSQL_HANDLES; i++) {
    MsqlHandle[i].connection = -1 ;
    MsqlHandle[i].host[0] = '\0' ;
    MsqlHandle[i].database[0] = '\0' ;
    MsqlHandle[i].result = NULL ;
    MsqlHandle[i].res_count = 0 ;
    MsqlHandle[i].col_count = 0 ;
  }
}


/*
 *----------------------------------------------------------------------
 * clear_msg
 *
 * Clears all error and message elements in the global array variable.
 *
 */

static void
clear_msg(interp)
    Tcl_Interp *interp;
{
    Tcl_SetVar2(interp, MsqlStatusArr, MSQL_STATUS_CODE, "0", TCL_GLOBAL_ONLY);
    Tcl_SetVar2(interp, MsqlStatusArr, MSQL_STATUS_CMD, "", TCL_GLOBAL_ONLY);
    Tcl_SetVar2(interp, MsqlStatusArr, MSQL_STATUS_MSG, "", TCL_GLOBAL_ONLY);
}


/*
 *----------------------------------------------------------------------
 * msql_prologue
 *
 * Does most of standard command prologue; required for all commands
 * having conflict handling.
 * 'req_args' must be the required number of arguments for the command,
 * including the command word.
 * 'usage_msg' must be a usage message, leaving out the command name.
 * Checks the handle assumed to be present in argv[1] if 'check' is not NULL.
 * RETURNS: Handle index or -1 on failure.
 * Returns zero if 'check' is NULL.
 * SIDE EFFECT: Sets the Tcl result on failure.
 */

static int
msql_prologue (interp, argc, argv, req_args, check, usage_msg)
     Tcl_Interp *interp;
     int         argc;
     char      **argv;
     int         req_args;
     char       *usage_msg;
     int (*check) () ; /* Pointer to function for checking the handle. */
{
  char buf[MSQL_BUFF_SIZE];
  int hand = 0;
  int need;

  /* Reset msqlstatus(code). */
  Tcl_SetVar2 (interp, MsqlStatusArr, MSQL_STATUS_CODE, "0",
	       TCL_GLOBAL_ONLY);

  /* Save command environment. */
  saved_interp = interp;
  saved_argc = argc ;
  saved_argv = argv ;

  /* Check number of minimum args. */
  if ((need = req_args - argc) > 0) 
    {
      sprintf (buf, "%d more %s needed: %s %s", need, (need>1)?"args":"arg",
	       argv[0], usage_msg);
      (void)msql_prim_confl (buf) ;
      return -1 ;
    }

  /* Check the handle.
   * The function is assumed to set the status array on conflict.
   */
  if (check != NULL && (hand = check (argv[1])) < 0)
    return -1 ;

  return (hand);
}


/*
 *----------------------------------------------------------------------
 * msql_colinfo
 *
 * Given an m_field struct and a string keyword appends a piece of
 * column info (one item) to the Tcl result.
 * ASSUMES 'fld' is non-null.
 * RETURNS 0 on success, 1 otherwise.
 * SIDE EFFECT: Sets the result and status on failure.
 */

static int
msql_colinfo (interp, fld, keyw)
     Tcl_Interp  *interp;
     m_field* fld ;
     char* keyw ;
{
  char buf[MSQL_SMALL_SIZE];
  char keybuf[MSQL_SMALL_SIZE];
  int idx ;
  char* res ;
  int retcode ;
  
  for (idx = 0;
       idx <= MSQL_COL_K_MAX && strcmp (MsqlColkey[idx], keyw) != 0;
       idx++) ;

  switch (idx)
    {
    case MSQL_COL_TABLE_K:
      res = fld->table ;
      break ;
    case MSQL_COL_NAME_K:
      res = fld->name ;
      break ;
    case MSQL_COL_TYPE_K:
      switch (fld->type)
	{
	case INT_TYPE:
	  res = "int" ;
	  break ;
	case CHAR_TYPE:
	  res = "char" ;
	  break ;
	case REAL_TYPE:
	  res = "real" ;
	  break ;
	default:
	  sprintf (buf, "column '%s' has weird datatype", fld->name) ;
	  res = NULL ;
	}
      break ;
    case MSQL_COL_LENGTH_K:
      sprintf (buf, "%d", fld->length) ;
      res = buf ;
      break ;
    case MSQL_COL_PRIMKEY_K:
      sprintf (buf, "%c", (IS_PRI_KEY(fld->flags))?'1':'0') ;
      res = buf ;
      break ;
    case MSQL_COL_NONNULL_K:
      sprintf (buf, "%c", (IS_NOT_NULL(fld->flags))?'1':'0') ;
      res = buf ;
      break ;
    default:
      if (strlen (keyw) >= MSQL_NAME_LEN)
	{
	  strncpy (keybuf, keyw, MSQL_NAME_LEN) ;
	  strcat (keybuf, "...") ;
	}
      else
	strcpy (keybuf, keyw) ;

      sprintf (buf, "unknown option: %s", keybuf) ;
      res = NULL ;
    }

  if (res == NULL)
    {
      (void)msql_prim_confl (buf) ;
      retcode = 1 ;
    }
  else
    {
      Tcl_AppendElement (interp, res) ;
      retcode = 0 ;
    }

  return retcode ;
}


/*
 *----------------------------------------------------------------------
 * Msqltcl_Kill
 * Close all connections.
 *
 */

void
Msqltcl_Kill (clientData)
    ClientData clientData;
{
  int i ;

  for (i = 0; i < MSQL_HANDLES; i++)
    {
      if (MsqlHandle[i].connection >=0)
	msqlClose (MsqlHandle[i].connection) ;
    }
  
  handle_init () ;
}


/*
 *----------------------------------------------------------------------
 * Msqltcl_Init
 * Perform all initialization for the MSQL to Tcl interface.
 * Adds additional commands to interp, creates message array, initializes
 * all handles.
 *
 * A call to Msqltcl_Init should exist in Tcl_CreateInterp or
 * Tcl_CreateExtendedInterp.
 */

int
Msqltcl_Init (interp)
    Tcl_Interp *interp;
{
  char nbuf[MSQL_SMALL_SIZE];
  int code;

  code = Tcl_PkgProvide(interp, "Msql", "1.50");
  if (code != TCL_OK) {
    return code;
  }

  /*
   * Initialize mSQL proc structures 
   */
  handle_init () ;

  /*
   * Initialize the new Tcl commands.
   * Deleting any command will close all connections.
   */
  Tcl_CreateCommand (interp, "msqlconnect", Msqltcl_Connect, (ClientData)NULL,
		     Msqltcl_Kill);
  Tcl_CreateCommand (interp, "msqluse",     Msqltcl_Use,     (ClientData)NULL,
		     Msqltcl_Kill);
  Tcl_CreateCommand (interp, "msqlsel",     Msqltcl_Sel,     (ClientData)NULL,
		     Msqltcl_Kill);
  Tcl_CreateCommand (interp, "msqlnext",    Msqltcl_Next,    (ClientData)NULL,
		     Msqltcl_Kill);
  Tcl_CreateCommand (interp, "msqlseek",    Msqltcl_Seek,    (ClientData)NULL,
                     Msqltcl_Kill);
  Tcl_CreateCommand (interp, "msqlmap",     Msqltcl_Map,     (ClientData)NULL,
		     Msqltcl_Kill);
  Tcl_CreateCommand (interp, "msqlexec",    Msqltcl_Exec,    (ClientData)NULL,
		     Msqltcl_Kill);
  Tcl_CreateCommand (interp, "msqlclose",   Msqltcl_Close,   (ClientData)NULL,
		     Msqltcl_Kill);
  Tcl_CreateCommand (interp, "msqlinfo",    Msqltcl_Info,    (ClientData)NULL,
		     Msqltcl_Kill);
  Tcl_CreateCommand (interp, "msqlresult",  Msqltcl_Result,  (ClientData)NULL,
		     Msqltcl_Kill);
  Tcl_CreateCommand (interp, "msqlcol",     Msqltcl_Col,     (ClientData)NULL,
		     Msqltcl_Kill);
  Tcl_CreateCommand (interp, "msqlstate",   Msqltcl_State,   (ClientData)NULL,
		     Msqltcl_Kill);

  /* Initialize msqlstatus global array. */
  clear_msg(interp);

  /* Link the null value element to the corresponding C variable. */
  if ((MsqlNullvalue = (char*) ckalloc (12)) == NULL)
    {
      fprintf (stderr, "*** msqltcl: out of memory\n") ;
      return TCL_ERROR ;
    }
  (void)strcpy (MsqlNullvalue, MSQL_NULLV_INIT);
  (void)sprintf (nbuf, "%s(%s)", MsqlStatusArr, MSQL_STATUS_NULLV) ;
  Tcl_LinkVar (interp, nbuf, (char*)&MsqlNullvalue, TCL_LINK_STRING) ;

  /* A little sanity check.
   * If this message appears you must change the source code and recompile.
   */
  if (strlen (MsqlHandlePrefix) == MSQL_HPREFIX_LEN)
    return TCL_OK;
  else
    {
      fprintf (stderr, "*** msqltcl (msqltcl.c): handle prefix inconsistency!\n") ;
      return TCL_ERROR ;
    }
}


/*
 *----------------------------------------------------------------------
 *
 * Msqltcl_Connect
 * Implements the msqlconnect command:
 * usage: msqlconnect ?server-host?
 *	                
 * Results:
 *      handle - a character string of newly open handle
 *      TCL_OK - connect successful
 *      TCL_ERROR - connect not successful - error message returned
 */

int
Msqltcl_Connect (clientData, interp, argc, argv)
     ClientData   clientData;
     Tcl_Interp  *interp;
     int          argc;
     char       **argv;
{
  int        hand = -1;
  int        i;
  char       buf[MSQL_BUFF_SIZE];
  int connect ;

  /* Pro-forma check (should never fail). */
  if (msql_prologue (interp, argc, argv, 1, NULL, "?hostname?") < 0)
    return TCL_ERROR;

  /* Find an unused handle. */
  for (i = 0; i < MSQL_HANDLES; i++) {
    if (MsqlHandle[i].connection <= 0) {
      hand = i;
      break;
    }
  }

  if (hand == -1)
    return msql_prim_confl ("no mSQL handles available");

  if (argc > 1 && strlen (argv[1]) > 0)
    {
      connect = msqlConnect (argv[1]) ;
      strncpy (MsqlHandle[hand].host, argv[1], MSQL_NAME_LEN) ;
      MsqlHandle[hand].host[MSQL_NAME_LEN - 1] = '\0' ;
    }
  else
    {
      if (gethostname (buf, MSQL_NAME_LEN) == 0)
	{
	  connect = msqlConnect ((char*)NULL) ;
	  strcpy (MsqlHandle[hand].host, buf) ;
	}
      else
	return msql_posix_confl ("gethostname") ;
    }

  if (connect < 0)
    {
      MsqlHandle[hand].connection = -1 ; /* Just to be sure. */
      return msql_server_confl ();
    }
  else
    MsqlHandle[hand].connection = connect ;

  /* Construct handle and return. */
  sprintf(buf, "%s%d", MsqlHandlePrefix, hand);
  Tcl_SetResult(interp, buf, TCL_VOLATILE);

  return TCL_OK;
}


/*
 *----------------------------------------------------------------------
 *
 * Msqltcl_Use
 *    Implements the msqluse command:
 *    usage: msqluse handle dbname
 *	                
 *    results:
 *	Sets current database to dbname.
 */

int
Msqltcl_Use (clientData, interp, argc, argv)
     ClientData   clientData;
     Tcl_Interp  *interp;
     int          argc;
     char       **argv;
{
  int hand;
  
  if ((hand = msql_prologue(interp, argc, argv, 3, get_handle_conn,
			    "handle dbname")) < 0)
    return TCL_ERROR;

  if (strlen (argv[2]) >= MSQL_NAME_LEN)
    return msql_prim_confl ("database name too long") ;
  if (msqlSelectDB (MsqlHandle[hand].connection, argv[2]) < 0)
    return msql_server_confl () ;

  strcpy (MsqlHandle[hand].database, argv[2]) ;
  return TCL_OK;
}



/*
 *----------------------------------------------------------------------
 *
 * Msqltcl_Sel
 *    Implements the msqlsel command:
 *    usage: msqlsel handle sel-query
 *	                
 *    results:
 *
 *    SIDE EFFECT: Flushes any pending result, even in case of conflict.
 *    Stores new results.
 */

int
Msqltcl_Sel (clientData, interp, argc, argv)
     ClientData   clientData;
     Tcl_Interp  *interp;
     int          argc;
     char       **argv;
{
  int     hand;
  
  if ((hand = msql_prologue(interp, argc, argv, 3, get_handle_db,
			    "handle sel-query")) < 0)
    return TCL_ERROR;

  /* Flush any previous result. */
  if (MsqlHandle[hand].result != NULL)
    {
      msqlFreeResult (MsqlHandle[hand].result) ;
      MsqlHandle[hand].result = NULL ;
    }

  if (msqlQuery (MsqlHandle[hand].connection, argv[2]) < 0)
    return msql_server_confl () ;

  if ((MsqlHandle[hand].result = msqlStoreResult ()) == NULL)
    {
      (void)strcpy (interp->result, "-1") ;
    }
  else
    {
      MsqlHandle[hand].res_count = msqlNumRows (MsqlHandle[hand].result) ;
      MsqlHandle[hand].col_count = msqlNumFields (MsqlHandle[hand].result) ;
      (void)sprintf (interp->result, "%d", MsqlHandle[hand].res_count) ;
    }

  return TCL_OK;
}


/*
 *----------------------------------------------------------------------
 *
 * Msqltcl_Exec
 * Implements the msqlexec command:
 * usage: msqlexec handle sql-statement
 *	                
 * Results:
 *
 * SIDE EFFECT: Flushes any pending result, even in case of conflict.
 */

int
Msqltcl_Exec (clientData, interp, argc, argv)
     ClientData   clientData;
     Tcl_Interp  *interp;
     int          argc;
     char       **argv;
{
  int     hand;
  
  if ((hand = msql_prologue(interp, argc, argv, 3, get_handle_db,
			    "handle sql-statement")) < 0)
    return TCL_ERROR;

  /* Flush any previous result. */
  if (MsqlHandle[hand].result != NULL)
    {
      msqlFreeResult (MsqlHandle[hand].result) ;
      MsqlHandle[hand].result = NULL ;
    }

  if (msqlQuery (MsqlHandle[hand].connection, argv[2]) < 0)
    return msql_server_confl () ;

  return TCL_OK ;
}


/*
 *----------------------------------------------------------------------
 *
 * Msqltcl_Next
 *    Implements the msqlnext command:
 *    usage: msqlnext handle
 *	                
 *    results:
 *	next row from pending results as tcl list, or null list.
 */

int
Msqltcl_Next (clientData, interp, argc, argv)
     ClientData   clientData;
     Tcl_Interp  *interp;
     int          argc;
     char       **argv;
{
  int hand;
  int idx ;
  m_row row ;
  char* val ;
  
  if ((hand = msql_prologue(interp, argc, argv, 2, get_handle_res,
			    "handle")) < 0)
    return TCL_ERROR;

  
  if (MsqlHandle[hand].res_count == 0)
    return TCL_OK ;
  else if ((row = msqlFetchRow (MsqlHandle[hand].result)) == NULL)
    {
      MsqlHandle[hand].res_count = 0 ;
      return msql_prim_confl ("result counter out of sync") ;
    }
  else
    MsqlHandle[hand].res_count-- ;
  
  for (idx = 0 ; idx < MsqlHandle[hand].col_count ; idx++)
    {
      if ((val = *row++) == NULL)
	val = MsqlNullvalue ;
      Tcl_AppendElement (interp, val) ;
    }
  
  return TCL_OK;
}


/*
 *----------------------------------------------------------------------
 *
 * Msqltcl_Seek
 *    Implements the msqlseek command:
 *    usage: msqlseek handle rownumber
 *	                
 *    results:
 *	number of remaining rows
 */

int
Msqltcl_Seek (clientData, interp, argc, argv)
    ClientData   clientData;
    Tcl_Interp  *interp;
    int          argc;
    char       **argv;
{
    int hand;
    int res;
    int row;
    int total;
   
    if ((hand = msql_prologue(interp, argc, argv, 3, get_handle_res,
                              " handle row-index")) < 0)
      return TCL_ERROR;

    if ((res = Tcl_GetInt (interp, argv[2], &row)) != TCL_OK)
      return res;
    
    total = msqlNumRows (MsqlHandle[hand].result);
    
    if (total + row < 0)
      {
	msqlDataSeek (MsqlHandle[hand].result, 0);
	MsqlHandle[hand].res_count = total;
      }
    else if (row < 0)
      {
	msqlDataSeek (MsqlHandle[hand].result, total + row);
	MsqlHandle[hand].res_count = -row;
      }
    else if (row >= total)
      {
	msqlDataSeek (MsqlHandle[hand].result, row);
	MsqlHandle[hand].res_count = 0;
      }
    else
      {
	msqlDataSeek (MsqlHandle[hand].result, row);
	MsqlHandle[hand].res_count = total - row;
      }

    (void)sprintf (interp->result, "%d", MsqlHandle[hand].res_count) ;
    return TCL_OK;
}


/*
 *----------------------------------------------------------------------
 *
 * Msqltcl_Map
 * Implements the msqlmap command:
 * usage: msqlmap handle binding-list script
 *	                
 * Results:
 * SIDE EFFECT: For each row the column values are bound to the variables
 * in the binding list and the script is evaluated.
 * The variables are created in the current context.
 * NOTE: msqlmap works very much like a 'foreach' construct.
 * The 'continue' and 'break' commands may be used with their usual effect.
 */

int
Msqltcl_Map (clientData, interp, argc, argv)
     ClientData   clientData;
     Tcl_Interp  *interp;
     int          argc;
     char       **argv;
{
  int code ;
  int count ;
  int hand ;
  int idx ;
  int listArgc ;
  char** listArgv ;
  m_row row ;
  char* val ;
  
  if ((hand = msql_prologue(interp, argc, argv, 4, get_handle_res,
			    "handle binding-list script")) < 0)
    return TCL_ERROR;

  if (Tcl_SplitList (interp, argv[2], &listArgc, &listArgv) != TCL_OK)
    return TCL_ERROR ;
  
  if (listArgc > MsqlHandle[hand].col_count)
    {
      ckfree ((char*)listArgv) ;
      return msql_prim_confl ("too many variables in binding list") ;
    }
  else
    count = (listArgc < MsqlHandle[hand].col_count)?listArgc
      :MsqlHandle[hand].col_count ;
  
  while (MsqlHandle[hand].res_count > 0)
    {
      /* Get next row, decrement row counter. */
      if ((row = msqlFetchRow (MsqlHandle[hand].result)) == NULL)
	{
	  MsqlHandle[hand].res_count = 0 ;
	  ckfree ((char*)listArgv) ;
	  return msql_prim_confl ("result counter out of sync") ;
	}
      else
	MsqlHandle[hand].res_count-- ;
      
      /* Bind variables to column values. */
      for (idx = 0; idx < count; idx++)
	{
	  if (listArgv[idx][0] != '-')
	    {
	      if ((val = *row++) == NULL)
		val = MsqlNullvalue ;
	      if (Tcl_SetVar (interp, listArgv[idx], val, TCL_LEAVE_ERR_MSG)
		  == NULL)
		{
		  ckfree ((char*)listArgv) ;
		  return TCL_ERROR ;
		}
	    }
	  else
	    row++ ;
	}

      /* Evaluate the script. */
      if ((code = Tcl_Eval (interp, argv[3])) != TCL_OK)
	switch (code) 
	  {
	  case TCL_CONTINUE:
	    continue ;
	    break ;
	  case TCL_BREAK:
	    ckfree ((char*)listArgv) ;
	    return TCL_OK ;
	    break ;
	  default:
	    ckfree ((char*)listArgv) ;
	    return code ;
	  }
    }
  ckfree ((char*)listArgv) ;
  return TCL_OK ;
}


/*
 *----------------------------------------------------------------------
 *
 * Msqltcl_Info
 * Implements the msqlinfo command:
 * usage: msqlinfo handle option
 *
 */

int
Msqltcl_Info (clientData, interp, argc, argv)
     ClientData   clientData;
     Tcl_Interp  *interp;
     int          argc;
     char       **argv;
{
  char buf[MSQL_BUFF_SIZE];
  int count ;
  int hand ;
  int idx ;
  m_result* list ;
  m_row row ;
  char* val ;
  
  /* We can't fully check the handle at this stage. */
  if ((hand = msql_prologue(interp, argc, argv, 3, get_handle_plain,
			    "handle option")) < 0)
    return TCL_ERROR;

  for (idx = 0;
       idx <= MSQL_INF_OPT_MAX && strcmp (argv[2], MsqlDbOpt[idx]) != 0;
       idx++) ;

  /* First check the handle. Checking depends on the option. */
  switch (idx)
    {
    case MSQL_INFNAME_OPT:
    case MSQL_INFTABLES_OPT:
      hand = get_handle_db (argv[1]) ;
      break ;
    case MSQL_INFNAMEQ_OPT:
      if ((hand = get_handle_conn (argv[1])) >= 0)
	{
	  if (MsqlHandle[hand].database[0] == '\0')
	    return TCL_OK ; /* Return empty string if no current db. */
	}
      break ;
    case MSQL_INFHOST_OPT:
    case MSQL_INFLIST_OPT:
      hand = get_handle_conn (argv[1]) ;
      break ;
    case MSQL_INFHOSTQ_OPT:
      if (MsqlHandle[hand].connection < 0)
	return TCL_OK ; /* Return empty string if not connected. */
      break ;
    default: /* unknown option */
      sprintf (buf, "'%s' unknown option", argv[2]);
      return msql_prim_confl (buf) ;
    }

  if (hand < 0)
      return TCL_ERROR ;

  /* Handle OK, return the requested info. */
  switch (idx)
    {
    case MSQL_INFNAME_OPT:
    case MSQL_INFNAMEQ_OPT:
      strcpy (interp->result, MsqlHandle[hand].database) ;
      break ;
    case MSQL_INFTABLES_OPT:
      if ((list = msqlListTables (MsqlHandle[hand].connection)) == NULL)
	return msql_prim_confl ("could not access table names; server may have gone away") ;

      for (count = msqlNumRows (list); count > 0; count--)
	{
	  val = *(row = msqlFetchRow (list)) ;
	  Tcl_AppendElement (interp, (val == NULL)?"":val) ;
	}
      msqlFreeResult (list) ;
      break ;
    case MSQL_INFHOST_OPT:
    case MSQL_INFHOSTQ_OPT:
      strcpy (interp->result, MsqlHandle[hand].host) ;
      break ;
    case MSQL_INFLIST_OPT:
      if ((list = msqlListDBs (MsqlHandle[hand].connection)) == NULL)
	return msql_prim_confl ("could not access database names; server may have gone away") ;

      for (count = msqlNumRows (list); count > 0; count--)
	{
	  val = *(row = msqlFetchRow (list)) ;
	  Tcl_AppendElement (interp, (val == NULL)?"":val) ;
	}
      msqlFreeResult (list) ;
      break ;
    default: /* should never happen */
      return msql_prim_confl ("weirdness in Msqltcl_Info") ;
    }
  return TCL_OK ;
}


/*
 *----------------------------------------------------------------------
 *
 * Msqltcl_Result
 * Implements the msqlresult command:
 * usage: msqlresult handle option
 *
 */

int
Msqltcl_Result (clientData, interp, argc, argv)
     ClientData   clientData;
     Tcl_Interp  *interp;
     int          argc;
     char       **argv;
{
  char buf[MSQL_BUFF_SIZE];
  int hand ;
  int idx ;


  /* We can't fully check the handle at this stage. */
  if ((hand = msql_prologue(interp, argc, argv, 3, get_handle_plain,
			    " handle option")) < 0)
    return TCL_ERROR;

  for (idx = 0;
       idx <= MSQL_RES_OPT_MAX && strcmp (argv[2], MsqlResultOpt[idx]) != 0;
       idx++) ;

  /* First check the handle. Checking depends on the option. */
  switch (idx)
    {
    case MSQL_RESROWS_OPT:
    case MSQL_RESCOLS_OPT:
    case MSQL_RESCUR_OPT:
      hand = get_handle_res (argv[1]) ;
      break ;
    case MSQL_RESROWSQ_OPT:
    case MSQL_RESCOLSQ_OPT:
    case MSQL_RESCURQ_OPT:
      if ((hand = get_handle_db (argv[1])) >= 0)
	{
	  if (MsqlHandle[hand].result == NULL)
	    return TCL_OK ; /* Return empty string if no pending result. */
	}
      break ;
    default: /* unknown option */
      sprintf (buf, "'%s' unknown option", argv[2]);
      return msql_prim_confl (buf) ;
    }

  if (hand < 0)
    return TCL_ERROR ;

  /* Handle OK; return requested info. */
  switch (idx)
    {
    case MSQL_RESROWS_OPT:
    case MSQL_RESROWSQ_OPT:
      sprintf (interp->result, "%d", MsqlHandle[hand].res_count) ;
      break ;
    case MSQL_RESCOLS_OPT:
    case MSQL_RESCOLSQ_OPT:
      sprintf (interp->result, "%d", MsqlHandle[hand].col_count) ;
      break ;
    case MSQL_RESCUR_OPT:
    case MSQL_RESCURQ_OPT:
      sprintf (interp->result, "%d", msqlNumRows (MsqlHandle[hand].result)
	       - MsqlHandle[hand].res_count) ;
/*     default: */
    }
  return TCL_OK ;
}


/*
 *----------------------------------------------------------------------
 *
 * Msqltcl_Col
 *    Implements the msqlcol command:
 *    usage: msqlcol handle table-name option ?option ...?
 *           msqlcol handle -current option ?option ...?
 * '-current' can only be used if there is a pending result.
 *	                
 *    results:
 *	List of lists containing column attributes.
 *      If a single attribute is requested the result is a simple list.
 *
 * SIDE EFFECT: '-current' disturbs the field position of the result.
 */

int
Msqltcl_Col (clientData, interp, argc, argv)
     ClientData   clientData;
     Tcl_Interp  *interp;
     int          argc;
     char       **argv;
{
  char buf[MSQL_BUFF_SIZE];
  int coln ;
  int conflict ;
  int current_db ;
  int hand;
  int idx ;
  int listArgc ;
  char** listArgv ;
  m_field* fld ;
  m_result* result ;
  char* sep ;
  int simple ;
  
  /* This check is enough only without '-current'. */
  if ((hand = msql_prologue(interp, argc, argv, 4, get_handle_db,
			    "handle table-name option ?option ...?")) < 0)
    return TCL_ERROR;

  /* Fetch column info.
   * Two ways: explicit database and table names, or current.
   */
  current_db = strcmp (argv[2], "-current") == 0 ;
  
  if (current_db)
    {
      if ((hand = get_handle_res (argv[1])) < 0)
	return TCL_ERROR ;
      else
	result = MsqlHandle[hand].result ;
    }
  else
    {
      if ((result = msqlListFields (MsqlHandle[hand].connection, argv[2])) == NULL)
	{
	  sprintf (buf, "no column info for table '%s'; %s", argv[2],
		   "server may have gone away") ;
	  return msql_prim_confl (buf) ;
	}
    }

  /* Must examine the first specifier at this point. */
  if (Tcl_SplitList (interp, argv[3], &listArgc, &listArgv) != TCL_OK)
    return TCL_ERROR ;

  conflict = 0 ;
  simple = (argc == 4) && (listArgc == 1) ;

  if (simple)
    {
      msqlFieldSeek (result, 0) ;
      while ((fld = msqlFetchField (result)) != NULL)
	if (msql_colinfo (interp, fld, argv[3]))
	  {
	    conflict = 1 ;
	    break ;
	  }
    }
  else if (listArgc > 1)
    {
      msqlFieldSeek (result, 0) ;
      for (sep = "{"; (fld = msqlFetchField (result)) != NULL; sep = " {")
	{
	  Tcl_AppendResult (interp, sep, (char*)NULL) ;
	  for (coln = 0; coln < listArgc; coln++)
	    if (msql_colinfo (interp, fld, listArgv[coln]))
	      {
		conflict = 1 ;
		break ;
	      }
	  if (conflict)
	    break ;
	  Tcl_AppendResult (interp, "}", (char*)NULL) ;
	}
      ckfree ((char*)listArgv) ;
    }
  else
    {
      ckfree ((char*)listArgv) ; /* listArgc == 1, no splitting */
      for (idx = 3, sep = "{"; idx < argc; idx++, sep = " {")
	{
	  Tcl_AppendResult (interp, sep, (char*)NULL) ;
	  msqlFieldSeek (result, 0) ;
	  while ((fld = msqlFetchField (result)) != NULL)
	    if (msql_colinfo (interp, fld, argv[idx]))
	      {
		conflict = 1 ;
		break ;
	      }
	  if (conflict)
	    break ;
	  Tcl_AppendResult (interp, "}", (char*)NULL) ;
	}
    }
  
  if (!current_db)
    msqlFreeResult (result) ;
  return (conflict)?TCL_ERROR:TCL_OK ;
}


/*
 *----------------------------------------------------------------------
 *
 * Msqltcl_State
 *    Implements the msqlstate command:
 *    usage: msqlstate ?-numeric? handle 
 *	                
 */

int
Msqltcl_State (clientData, interp, argc, argv)
     ClientData   clientData;
     Tcl_Interp  *interp;
     int          argc;
     char       **argv;
{
  int hi;
  char* hp ;
  int numeric ;
  char* res ;
  
  if (msql_prologue(interp, argc, argv, 2, NULL, "?-numeric? handle") < 0)
    return TCL_ERROR;

  if ((numeric = (strcmp (argv[1], "-numeric") == 0)) && argc < 3)
    return msql_prim_confl ("handle required") ;
  
  hp = (numeric)?argv[2]:argv[1] ;

  if (HSYNTAX(hp,hi) < 0)
    res = (numeric)?"0":"NOT_A_HANDLE" ;
  else if (MsqlHandle[hi].connection < 0)
    res = (numeric)?"1":"UNCONNECTED" ;
  else if (MsqlHandle[hi].database[0] == '\0')
    res = (numeric)?"2":"CONNECTED" ;
  else if (MsqlHandle[hi].result == NULL)
    res = (numeric)?"3":"IN_USE" ;
  else
    res = (numeric)?"4":"RESULT_PENDING" ;

  (void)strcpy (interp->result, res) ;
  return TCL_OK ;
}


/*
 *----------------------------------------------------------------------
 *
 * Msqltcl_Close --
 *    Implements the msqlclose command:
 *    usage: msqlclose ?handle?
 *	                
 *    results:
 *	null string
 */

int
Msqltcl_Close (clientData, interp, argc, argv)
     ClientData   clientData;
     Tcl_Interp  *interp;
     int          argc;
     char       **argv;
{
  int     hand;
  
  /* If handle omitted, close all connections. */
  if (argc == 1)
    {
      Msqltcl_Kill ((ClientData)NULL) ;
      return TCL_OK ;
    }
  
  if ((hand = msql_prologue(interp, argc, argv, 2, get_handle_conn,
			    "handle")) < 0)
    return TCL_ERROR;

  msqlClose (MsqlHandle[hand].connection) ;

  MsqlHandle[hand].connection = -1 ;
  MsqlHandle[hand].host[0] = '\0' ;
  MsqlHandle[hand].database[0] = '\0' ;

  if (MsqlHandle[hand].result != NULL)
    msqlFreeResult (MsqlHandle[hand].result) ;
    
  MsqlHandle[hand].result = NULL ;
  MsqlHandle[hand].res_count = 0 ;

  return TCL_OK;
}

#endif HAVE_MSQL