File: pgtclCmds.c

package info (click to toggle)
pgtcl 1%3A1.9%2Bgit20120911-4
  • links: PTS
  • area: main
  • in suites: stretch
  • size: 2,244 kB
  • ctags: 315
  • sloc: ansic: 4,475; tcl: 634; sh: 149; makefile: 36; sql: 11
file content (4628 lines) | stat: -rw-r--r-- 116,895 bytes parent folder | download | duplicates (2)
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
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
/*-------------------------------------------------------------------------
 *
 * pgtclCmds.c
 *	  C functions which implement pg_* tcl commands
 *
 * Portions Copyright (c) 1996-2004, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
 *	  $Id$
 *
 *-------------------------------------------------------------------------
 */

#include <ctype.h>
#include <string.h>
#include <libpq-fe.h>

#include "pgtclCmds.h"
#include "pgtclId.h"
#include "libpq/libpq-fs.h"		/* large-object interface */

#ifndef CONST84
#     define CONST84
#endif

/*
 * Local function forward declarations
 */
static int execute_put_values(Tcl_Interp *interp, CONST84 char *array_varname,
				   PGresult *result, char *nullString, int tupno);


#ifdef TCL_ARRAYS

#define ISOCTAL(c)		(((c) >= '0') && ((c) <= '7'))
#define DIGIT(c)		((c) - '0')


/*
 * translate_escape()
 *
 * This function performs in-place translation of a single C-style
 * escape sequence pointed by p. Curly braces { } and double-quote
 * are left escaped if they appear inside an array.
 * The value returned is the pointer to the last character (the one
 * just before the rest of the buffer).
 */

static inline char *
translate_escape(char *p, int isArray)
{
	char		c,
			   *q,
			   *s;

#ifdef TCL_ARRAYS_DEBUG_ESCAPE
	printf("   escape = '%s'\n", p);
#endif
	/* Address of the first character after the escape sequence */
	s = p + 2;
	switch (c = *(p + 1))
	{
		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
			c = DIGIT(c);
			if (ISOCTAL(*s))
				c = (c << 3) + DIGIT(*s++);
			if (ISOCTAL(*s))
				c = (c << 3) + DIGIT(*s++);
			*p = c;
			break;
		case 'b':
			*p = '\b';
			break;
		case 'f':
			*p = '\f';
			break;
		case 'n':
			*p = '\n';
			break;
		case 'r':
			*p = '\r';
			break;
		case 't':
			*p = '\t';
			break;
		case 'v':
			*p = '\v';
			break;
		case '\\':
		case '{':
		case '}':
		case '"':

			/*
			 * Backslahes, curly braces and double-quotes are left escaped
			 * if they appear inside an array. They will be unescaped by
			 * Tcl in Tcl_AppendElement. The buffer position is advanced
			 * by 1 so that the this character is not processed again by
			 * the caller.
			 */
			if (isArray)
				return p + 1;
			else
				*p = c;
			break;
		case '\0':

			/*
			 * This means a backslash at the end of the string. It should
			 * never happen but in that case replace the \ with a \0 but
			 * don't shift the rest of the buffer so that the caller can
			 * see the end of the string and terminate.
			 */
			*p = c;
			return p;
			break;
		default:

			/*
			 * Default case, store the escaped character over the
			 * backslash and shift the buffer over itself.
			 */
			*p = c;
	}
	/* Shift the rest of the buffer over itself after the current char */
	q = p + 1;
	for (; *s;)
		*q++ = *s++;
	*q = '\0';
#ifdef TCL_ARRAYS_DEBUG_ESCAPE
	printf("   after  = '%s'\n", p);
#endif
	return p;
}

/*
 * tcl_value()
 *
 * This function does in-line conversion of a value returned by libpq
 * into a tcl string or into a tcl list if the value looks like the
 * representation of a postgres array.
 */

static char *
tcl_value(char *value)
{
	int			literal,
				last;
	char	   *p;

	if (!value)
		return NULL;


#ifdef TCL_ARRAYS_DEBUG
	printf("pq_value  = '%s'\n", value);
#endif
	last = strlen(value) - 1;
	if ((last >= 1) && (value[0] == '{') && (value[last] == '}'))
	{
		/* Looks like an array, replace ',' with spaces */
		/* Remove the outer pair of { }, the last first! */
		value[last] = '\0';
		value++;
		literal = 0;
		for (p = value; *p; p++)
		{
			if (!literal)
			{
				/* We are at the list level, look for ',' and '"' */
				switch (*p)
				{
					case '"':	/* beginning of literal */
						literal = 1;
						break;
					case ',':	/* replace the ',' with space */
						*p = ' ';
						break;
				}
			}
			else
			{
				/* We are inside a C string */
				switch (*p)
				{
					case '"':	/* end of literal */
						literal = 0;
						break;
					case '\\':

						/*
						 * escape sequence, translate it
						 */
						p = translate_escape(p, 1);
						break;
				}
			}
			if (!*p)
				break;
		}
	}
	else
	{
		/* Looks like a normal scalar value */
		for (p = value; *p; p++)
		{
			if (*p == '\\')
			{
				/*
				 * escape sequence, translate it
				 */
				p = translate_escape(p, 0);
			}
			if (!*p)
				break;
		}
	}
#ifdef TCL_ARRAYS_DEBUG
	printf("tcl_value = '%s'\n\n", value);
#endif
	return value;
}
#else    /* TCL_ARRAYS */
#define tcl_value(x) x
#endif   /* TCL_ARRAYS */

/*
 * PGgetvalue()
 *
 * This function gets a field result string for a specified PGresult, tuple 
 * number and field number.  If the string is empty and the connection has
 * a non-empty null string value defined, the field is checked to see if
 * the returned field is actually null and, if so, the null string value
 * associated with the connection is returned.
 *
 * If array-into-list processing has been defined, it is also performed,
 * which is probably a bad idea, since it can be tricked by legitimate
 * data, but that's tcl_value's fault, if TCL_ARRAYS is defined.
 */

static char *
PGgetvalue ( PGresult *result, char *nullString, int tupno, int fieldNumber )
{
    char *string;

    string = PQgetvalue (result, tupno, fieldNumber);

	/* if the returned string is empty, see if we have a non-empty null
	 * string value set for this connection and, if so, see if the
	 * value returned is null.  If it is, return the null string.
	 */
	if (*string == '\0') {
		if ((nullString != NULL) && (*nullString != '\0')) {
			if (PQgetisnull (result, tupno, fieldNumber)) {
				return nullString;
			}
		}
		/* string is empty but is either not null or null string is empty,
		 * return the empty string
		 */
		return string;
	}

	/* string is not empty */
	return tcl_value (string);
}

/**********************************
 * pg_conndefaults

 syntax:
 pg_conndefaults

 the return result is a list describing the possible options and their
 current default values for a call to pg_connect with the new -conninfo
 syntax. Each entry in the list is a sublist of the format:

	 {optname label dispchar dispsize value}

 **********************************/

int
Pg_conndefaults(ClientData cData, Tcl_Interp *interp, int objc,
				Tcl_Obj *CONST objv[])
{
	PQconninfoOption *options = PQconndefaults();
	PQconninfoOption *option;

	if (objc != 1)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "");
		return TCL_ERROR;
	}

	if (options)
	{
		Tcl_Obj    *resultList = Tcl_NewListObj(0, NULL);

		Tcl_SetListObj(resultList, 0, NULL);

		for (option = options; option->keyword != NULL; option++)
		{
			char	   *val = option->val ? option->val : "";

			/* start a sublist */
			Tcl_Obj    *subList = Tcl_NewListObj(0, NULL);

			if (Tcl_ListObjAppendElement(interp, subList,
					 Tcl_NewStringObj(option->keyword, -1)) == TCL_ERROR)
				return TCL_ERROR;

			if (Tcl_ListObjAppendElement(interp, subList,
					   Tcl_NewStringObj(option->label, -1)) == TCL_ERROR)
				return TCL_ERROR;

			if (Tcl_ListObjAppendElement(interp, subList,
					Tcl_NewStringObj(option->dispchar, -1)) == TCL_ERROR)
				return TCL_ERROR;

			if (Tcl_ListObjAppendElement(interp, subList,
						   Tcl_NewIntObj(option->dispsize)) == TCL_ERROR)
				return TCL_ERROR;

			if (Tcl_ListObjAppendElement(interp, subList,
								 Tcl_NewStringObj(val, -1)) == TCL_ERROR)
				return TCL_ERROR;

			if (Tcl_ListObjAppendElement(interp, resultList,
										 subList) == TCL_ERROR)
				return TCL_ERROR;
		}
        Tcl_SetObjResult(interp, resultList);
		PQconninfoFree(options);
	}
	return TCL_OK;
}


/*
 *----------------------------------------------------------------------
 *
 * Pg_connect --
 *
 *    make a connection to a backend.
 *    
 * Syntax:
 *    pg_connect dbName [-host hostName] [-port portNumber] [-tty pqtty]]
 *    pg_connect -conninfo "dbname=myydb host=myhost ..."
 *    pg_connect -connlist [list dbname mydb host myhost ...]
 *    pg_connect -connhandle myhandle
 *
 * Results:
 *    the return result is either an error message or a handle for 
 *    a database connection.  Handles start with the prefix "pgsql"
 *
 *----------------------------------------------------------------------
 */

int
Pg_connect(ClientData cData, Tcl_Interp *interp, int objc,
		   Tcl_Obj *CONST objv[])
{
    PGconn	    *conn;
    char	    *connhandle = NULL;
    int             optIndex, i, skip = 0;
    Tcl_DString     ds, utfds;
    Tcl_Obj         *tresult;
    int             async = 0;
        

    static CONST84 char *options[] = {
    	"-host", "-port", "-tty", "-options", "-user", 
        "-password", "-conninfo", "-connlist", "-connhandle",
        "-async", (char *)NULL
    };

    enum options
    {
    	OPT_HOST, OPT_PORT, OPT_TTY, OPT_OPTIONS, OPT_USER, 
        OPT_PASSWORD, OPT_CONNINFO, OPT_CONNLIST, OPT_CONNHANDLE,
        OPT_ASYNC
    };

    Tcl_DStringInit(&ds);

    if (objc == 1)
    {
        Tcl_DStringAppend(&ds, "pg_connect: database name missing\n", -1);
        Tcl_DStringAppend(&ds, "pg_connect databaseName [-host hostName] [-port portNumber] [-tty pgtty]\n", -1);
        Tcl_DStringAppend(&ds, "pg_connect -conninfo conninfoString\n", -1);
        Tcl_DStringAppend(&ds, "pg_connect -connlist [connlist]", -1);
        Tcl_DStringResult(interp, &ds);

        return TCL_ERROR;
    }



    i = objc%2 ? 1 : 2;

    while (i + 1 < objc)
    {
        char	   *nextArg = Tcl_GetStringFromObj(objv[i + 1], NULL);

        if (Tcl_GetIndexFromObj(interp, objv[i], options,
		   "option", TCL_EXACT, &optIndex) != TCL_OK)
		    return TCL_ERROR;

        switch ((enum options) optIndex)
        {
            case OPT_HOST:
            {
                Tcl_DStringAppend(&ds, " host=", -1);
                i += 2;
                break;
            }

            case OPT_PORT:
            {
                Tcl_DStringAppend(&ds, " port=", -1);
                i += 2;
                break;
            }

            case OPT_TTY:
            {
                Tcl_DStringAppend(&ds, " tty=", -1);
                i += 2;
                break;
            }

            case OPT_OPTIONS:
            {
                Tcl_DStringAppend(&ds, " options=", -1);
                i += 2;
                break;
            }
            case OPT_USER:
            {
                Tcl_DStringAppend(&ds, " user=", -1);
                i += 2;
                break;
            }
            case OPT_PASSWORD:
            {
                Tcl_DStringAppend(&ds, " password=", -1);
                i += 2;
                break;
            }
            case OPT_CONNINFO:
            {
                    i += 2;
                    break;
            }
            case OPT_CONNLIST:
            {
                Tcl_Obj    **elemPtrs;
                int        count, lelem;

                Tcl_ListObjGetElements(interp, objv[i + 1], &count, &elemPtrs);

                if (count % 2 != 0)
                {
	            Tcl_WrongNumArgs(interp,1,objv,"-connlist {opt val ...}");
                    Tcl_DStringFree(&ds);

		    return TCL_ERROR;
                }

                for (lelem = 0; lelem < count; lelem=lelem+2) {

                    Tcl_DStringAppend(&ds, " ", -1);
                    Tcl_DStringAppend(&ds, 
                        Tcl_GetStringFromObj(elemPtrs[lelem], NULL), -1);
                    Tcl_DStringAppend(&ds, "=", -1);
                    Tcl_DStringAppend(&ds, 
                        Tcl_GetStringFromObj(elemPtrs[lelem+1], NULL), -1);
                }
                i += 2;
                skip = 1;
                break;
            }
            case OPT_CONNHANDLE:
            {
                connhandle = nextArg;
                i += 2;
                skip = 1;
                break;
            }
            case OPT_ASYNC:
            {
                /*
                 *  Hummm, since we make the arg a string
                 *  at the very beginning, we have to deal
                 *  with that, in regards to finding the
                 *  boolean value for the -async flag
                 */
                 if (strcmp(nextArg, "1") == 0)
                 {
                     async = 1;
                 }
                i += 2;
                skip = 1;
            }
        } /** end switch **/

        if (!skip)
        {
            Tcl_DStringAppend(&ds, nextArg, -1);
        }
        skip = 0;

    } /* end while */

    /*
     *    if even numbered args, then assume connect dbname ?option val? ...
     *    and put dbname into conn string
     */
    if (objc % 2 == 0)
    {
	    if ((i % 2 != 0) || i != objc)
	    {
	        Tcl_WrongNumArgs(interp, 1, objv, 
                    "databaseName ?-host hostName? ?-port portNumber? ?-tty pgtty? ?-options pgoptions?");
                Tcl_DStringFree(&ds);

	        return TCL_ERROR;
	    }

        Tcl_DStringAppend(&ds, " dbname=", -1);
        Tcl_DStringAppend(&ds, Tcl_GetStringFromObj(objv[1], NULL), -1);
    }

    Tcl_ExternalToUtfDString(NULL, Tcl_DStringValue(&ds), -1, &utfds);
    Tcl_DStringFree(&ds);

    if (async)
    {
        conn = PQconnectStart(Tcl_DStringValue(&utfds));
      
    } 
    else 
    {

        conn = PQconnectdb(Tcl_DStringValue(&utfds));
    }

    if (conn == NULL)
    {
        Tcl_SetResult(interp, "Could not allocate connection", TCL_STATIC);
        return TCL_ERROR;
    }

 
    Tcl_DStringFree(&utfds);

    if (PQstatus(conn) != CONNECTION_BAD)
    {
        if (PgSetConnectionId(interp, conn, connhandle))
        {
            return TCL_OK;
        }

    }
   

        tresult = Tcl_NewStringObj("Connection to database failed\n", -1);
        if (PQstatus(conn) != CONNECTION_OK)
	{
	    Tcl_AppendStringsToObj(tresult, PQerrorMessage(conn), NULL);
        }
	else
	{
            Tcl_AppendStringsToObj(tresult, "handle already exists", NULL);
	}

	Tcl_SetObjResult(interp, tresult);
        PQfinish(conn);

        return TCL_ERROR;
   
}


/**********************************
 * pg_disconnect
 close a backend connection

 syntax:
 pg_disconnect connection

 The argument passed in must be a connection pointer.

 **********************************/

int
Pg_disconnect(ClientData cData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    Pg_ConnectionId *connid;
    Tcl_Channel conn_chan;
    CONST84 char	   *connString;
    Tcl_Obj         *tresult;

    if (objc != 2)
    {
	Tcl_WrongNumArgs(interp, 1, objv, "connection");
	return TCL_ERROR;
    }

    connString = Tcl_GetStringFromObj(objv[1], NULL);
    conn_chan = Tcl_GetChannel(interp, connString, 0);
    if (conn_chan == NULL)
    {
        tresult = Tcl_NewStringObj(connString, -1);
        Tcl_AppendStringsToObj(tresult, " is not a valid connection", NULL);
        Tcl_SetObjResult(interp, tresult);

	return TCL_ERROR;
    }

    /* Check that it is a PG connection and not something else */
    connid = (Pg_ConnectionId *) Tcl_GetChannelInstanceData(conn_chan);

    if (connid->conn == NULL)
	return TCL_ERROR;

    /*
     *    We use to call Tcl_UnregisterChannel here, but since
     *    we have a command deletion callback now, that gets
     *    taken care of there (PgDelCmdHandle), by deleting the command
     *    here.
     */
    if (connid->cmd_token != NULL)
    {
        Tcl_DeleteCommandFromToken(interp, connid->cmd_token);
    }

    return TCL_OK;
}

/**********************************
 * pg_exec
 send a query string to the backend connection

 syntax:
 pg_exec connection query [var1] [var2]...

 the return result is either an error message or a handle for a query
 result.  Handles start with the prefix "pgsql"
 **********************************/

int
Pg_exec(ClientData cData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
	Pg_ConnectionId *connid;
	PGconn	   *conn;
	PGresult   *result;
	CONST84 char	   *connString;
	const char *execString;
	const char **paramValues = NULL;

	/* THIS CODE IS REPLICATED IN Pg_sendquery AND SHOULD BE FACTORED */
#ifdef HAVE_PQEXECPARAMS
	int         nParams;

	if (objc < 3)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "connection queryString ?parm...?");
		return TCL_ERROR;
	}

	/* extra params will substitute for $1, $2, etc, in the statement */
	/* objc must be 3 or greater at this point */
	nParams = objc - 3;

	/* If there are any extra params, allocate paramValues and fill it
	 * with the string representations of all of the extra parameters
	 * substituted on the command line.  Otherwise nParams will be 0,
	 * and PQexecParams will work just like PQexec (no $-substitutions).
	 */
	if (nParams > 0) {
	    int param;

	    paramValues = (const char **)ckalloc (nParams * sizeof (char *));

	    for (param = 0; param < nParams; param++) {
		paramValues[param] = Tcl_GetStringFromObj(objv[3+param], NULL);
		if (strcmp(paramValues[param], "NULL") == 0)
                {
                    paramValues[param] = '\0';
                }
	    }
	}
#else /* HAVE_PQEXECPARAMS */
	if (objc != 3)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "connection queryString");
		return TCL_ERROR;
	}
#endif /* HAVE_PQEXECPARAMS */

	/* figure out the connect string and get the connection ID */

	connString = Tcl_GetStringFromObj(objv[1], NULL);
	conn = PgGetConnectionId(interp, connString, &connid);
	if (conn == NULL)
		return TCL_ERROR;

	if (connid->res_copyStatus != RES_COPY_NONE)
	{
		Tcl_SetResult(interp, "Attempt to query while COPY in progress", TCL_STATIC);
		return TCL_ERROR;
	}

        if (connid->callbackPtr || connid->callbackInterp)
        {
               Tcl_SetResult(interp, "Attempt to query while waiting for callback", TCL_STATIC);
               return TCL_ERROR;
         }

	execString = Tcl_GetStringFromObj(objv[2], NULL);

	/* we could call PQexecParams when nParams is 0, but PQexecParams
	 * will not accept more than one SQL statement per call, while
	 * PQexec will.  by checking and using PQexec when no parameters
	 * are included, we maintain compatibility for code that doesn't
	 * use params and might have had multiple statements in a single 
	 * request */
#ifdef HAVE_PQEXECPARAMS
	if (nParams == 0) {
#endif
	    result = PQexec(conn, execString);
#ifdef HAVE_PQEXECPARAMS
	} else {
	    result = PQexecParams(conn, execString, nParams, NULL, paramValues, NULL, NULL, 0);
	    ckfree ((void *)paramValues);
	}
#endif

	connid->sql_count++;

	/* REPLICATED IN pg_exec_prepared -- NEEDS TO BE FACTORED */
	/* Transfer any notify events from libpq to Tcl event queue. */
	PgNotifyTransferEvents(connid);

	if (result)
	{
		int	rId = PgSetResultId(interp, connString, result);

         

		ExecStatusType rStat = PQresultStatus(result);

		if (rStat == PGRES_COPY_IN || rStat == PGRES_COPY_OUT)
		{
			connid->res_copyStatus = RES_COPY_INPROGRESS;
			connid->res_copy = rId;
		}
		return TCL_OK;
	}
	else
	{
		/* error occurred during the query */
		Tcl_SetObjResult(interp, Tcl_NewStringObj(PQerrorMessage(conn), -1));
		return TCL_ERROR;
	}
}

/**********************************
 * pg_exec_prepared
 send a request to executed a prepared statement with given parameters  
 to the backend connection

 syntax:
 pg_exec_prepared connection statement_name [var1] [var2]...

 the return result is either an error message or a handle for a query
 result.  Handles start with the prefix "pgp"
 **********************************/

int
Pg_exec_prepared(ClientData cData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
	Pg_ConnectionId *connid;
	PGconn	   *conn;
	PGresult   *result;
	CONST84 char	   *connString;
	const char *statementNameString;
	const char **paramValues = NULL;

	int         nParams;

    /* THIS CODE IS REPLICATED IN Pg_sendquery_prepared AND NEEDS TO BE FACTORED */
#ifndef HAVE_PQEXECPREPARED
    Tcl_SetObjResult(interp, 
        Tcl_NewStringObj(
        "function unavailable with this version of the postgres libpq library\n", -1));

	return TCL_ERROR;
#else
	if (objc < 3)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "connection statementName [parm...]");
		return TCL_ERROR;
	}

	/* figure out the connect string and get the connection ID */

	connString = Tcl_GetStringFromObj(objv[1], NULL);
	conn = PgGetConnectionId(interp, connString, &connid);
	if (conn == NULL)
		return TCL_ERROR;

	if (connid->res_copyStatus != RES_COPY_NONE)
	{
		Tcl_SetResult(interp, "Attempt to query while COPY in progress", TCL_STATIC);
		return TCL_ERROR;
	}

        if (connid->callbackPtr || connid->callbackInterp)
        {
               Tcl_SetResult(interp, "Attempt to query while waiting for callback", TCL_STATIC);
               return TCL_ERROR;
         }


	/* extra params will substitute for $1, $2, etc, in the statement */
	/* objc must be 3 or greater at this point */
	nParams = objc - 3;

	/* If there are any extra params, allocate paramValues and fill it
	 * with the string representations of all of the extra parameters
	 * substituted on the command line.  Otherwise nParams will be 0,
	 * and we don't need to allocate space, paramValues will be NULL.
	 * However, prepared statements that don't take any parameters aren't
	 * generally real useful.
	 */
	if (nParams > 0) {
	    int param;

	    paramValues = (const char **)ckalloc (nParams * sizeof (char *));

	    for (param = 0; param < nParams; param++) {
		paramValues[param] = Tcl_GetStringFromObj (objv[3+param], NULL);
		if (strcmp(paramValues[param], "NULL") == 0)
                {
                    paramValues[param] = '\0';
                }
	    }
	}

	statementNameString = Tcl_GetStringFromObj(objv[2], NULL);

	result = PQexecPrepared(conn, statementNameString, nParams, paramValues, NULL, NULL, 0);

	if (paramValues != (const char **)NULL) {
	    ckfree ((void *)paramValues);
	}

	connid->sql_count++;

	/* REPLICATED IN pg_exec -- NEEDS TO BE FACTORED */
	/* Transfer any notify events from libpq to Tcl event queue. */
	PgNotifyTransferEvents(connid);

	if (result)
	{
		int	rId = PgSetResultId(interp, connString, result);

		ExecStatusType rStat = PQresultStatus(result);

		if (rStat == PGRES_COPY_IN || rStat == PGRES_COPY_OUT)
		{
			connid->res_copyStatus = RES_COPY_INPROGRESS;
			connid->res_copy = rId;
		}
		return TCL_OK;
	}
	else
	{
		/* error occurred during the query */
		Tcl_SetObjResult(interp, Tcl_NewStringObj(PQerrorMessage(conn), -1));
		return TCL_ERROR;
	}
#endif /* HAVE_PQEXECPREPARED */
}


/**********************************
 * pg_result
 get information about the results of a query

 syntax:

	pg_result result ?option?

 the options are:

	-status the status of the result

	-error	the error message, if the status indicates error; otherwise
		an empty string

	-conn	the connection that produced the result

	-oid	if command was an INSERT, the OID of the inserted tuple

	-numTuples	the number of tuples in the query

	-cmdTuples	Same as -numTuples, but for DELETE and UPDATE

	-numAttrs	returns the number of attributes returned by the query

	-assign arrayName
		assign the results to an array, using subscripts of the form
			(tupno,attributeName)

	-assignbyidx arrayName ?appendstr?
		assign the results to an array using the first field's value
		as a key.
		All but the first field of each tuple are stored, using
		subscripts of the form (field0value,attributeNameappendstr)

	-getTuple tupleNumber
		returns the values of the tuple in a list

	-tupleArray tupleNumber arrayName
		stores the values of the tuple in array arrayName, indexed
		by the attributes returned.  If a value is null, sets an
		empty string or the default string into the array, if
		a default string has been defined.

	-tupleArrayWithoutNulls tupleNumber arrayName
		...stores the values of the tuple in array arrayName, indexed
		by the attributes returned.  If a value is null, unsets the
		field from the array.

	-attributes
		returns a list of the name/type pairs of the tuple attributes

	-lAttributes
		returns a list of the {name type len} entries of the tuple
		attributes

        -list
                returns one list of all of the data

        -llist  returns a list of lists, where each embedded list represents 
                a tuple in the result

	-clear	clear the result buffer. Do not reuse after this

	-null_value_string	Set the value returned for fields that are null
		                (defaults to connection setting, default "")

 **********************************/
int
Pg_result(ClientData cData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
	PGresult   *result;
	int			i;
	int			tupno;
	Tcl_Obj    *arrVarObj;
	Tcl_Obj    *appendstrObj;
	char	   *queryResultString;
	int			optIndex;
	int			errorOptIndex;

	Tcl_Obj* listObj;
	Tcl_Obj* subListObj;
	Tcl_Obj* fieldObj = NULL;
    Tcl_Obj    *fieldNameObj;
	Tcl_Obj* tresult;
    /* Tcl_CmdInfo    infoPtr; */


    Pg_resultid        *resultid;


	static CONST84 char *options[] = {
		"-status", "-error", "-conn", "-oid",
		"-numTuples", "-cmdTuples", "-numAttrs", "-assign", "-assignbyidx",
		"-getTuple", "-tupleArray", "-tupleArrayWithoutNulls", "-attributes", "-lAttributes",
		"-clear", "-list", "-llist", "-dict", "-null_value_string", (char *)NULL
	};

	enum options
	{
		OPT_STATUS, OPT_ERROR, OPT_CONN, OPT_OID,
		OPT_NUMTUPLES, OPT_CMDTUPLES, OPT_NUMATTRS, OPT_ASSIGN, OPT_ASSIGNBYIDX,
		OPT_GETTUPLE, OPT_TUPLEARRAY, OPT_TUPLEARRAY_WITHOUT_NULLS, OPT_ATTRIBUTES, OPT_LATTRIBUTES,
		OPT_CLEAR, OPT_LIST, OPT_LLIST, OPT_DICT, OPT_NULL_VALUE_STRING
	};

	static CONST84 char *errorOptions[] = {
		"severity", "sqlstate", "primary", "detail",
		"hint", "position", "internal_position", "internal_query",
		"context", "file", "line", "function", (char *)NULL
	};

	static CONST char pgDiagCodes[] = {
		PG_DIAG_SEVERITY,
		PG_DIAG_SQLSTATE, 
		PG_DIAG_MESSAGE_PRIMARY,
		PG_DIAG_MESSAGE_DETAIL, 
		PG_DIAG_MESSAGE_HINT, 
		PG_DIAG_STATEMENT_POSITION, 
		PG_DIAG_INTERNAL_POSITION,
		PG_DIAG_INTERNAL_QUERY,
		PG_DIAG_CONTEXT,
		PG_DIAG_SOURCE_FILE, 
		PG_DIAG_SOURCE_LINE, 
		PG_DIAG_SOURCE_FUNCTION
	};

	if (objc < 3 || objc > 5)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "");
		goto Pg_result_errReturn;		/* append help info */
	}

	/* figure out the query result handle and look it up */
	queryResultString = Tcl_GetStringFromObj(objv[1], NULL);
	result = PgGetResultId(interp, queryResultString, &resultid);
	if (result == (PGresult *)NULL)
	{
        tresult = Tcl_NewStringObj(queryResultString, -1);
        Tcl_AppendStringsToObj(tresult, " is not a valid query result", NULL);
        Tcl_SetObjResult(interp, tresult);

		return TCL_ERROR;
	}

	/* process command options */
	if (Tcl_GetIndexFromObj(interp, objv[2], options, "option", TCL_EXACT,
							&optIndex) != TCL_OK)
		return TCL_ERROR;

#ifndef HAVE_TCL_NEWDICTOBJ
    if ((enum options) optIndex == OPT_DICT)
    {
        Tcl_SetObjResult(interp, Tcl_NewStringObj(
          "You need a Tcl version (8.5+) that supports dicts in order to use the -dict option", -1));
	    return TCL_ERROR;
    }

#endif


	switch ((enum options) optIndex)
	{
		case OPT_STATUS:
			{
				char	   *resultStatus;

				if (objc != 3)
				{
					Tcl_WrongNumArgs(interp, 3, objv, "");
					return TCL_ERROR;
				}

				resultStatus = PQresStatus(PQresultStatus(result));
				Tcl_SetObjResult(interp, Tcl_NewStringObj(resultStatus, -1));
				return TCL_OK;
			}

		case OPT_ERROR:
			{
				if (objc < 3 || objc > 4)
				{
					Tcl_WrongNumArgs(interp, 3, objv, "[subcode]");
					return TCL_ERROR;
				}

				/* if there's no subfield (objc == 3), just get the result
				 * error message */
				if (objc == 3) {
					Tcl_SetObjResult(interp,
						 Tcl_NewStringObj(PQresultErrorMessage(result), -1));
					return TCL_OK;
				}

				if (Tcl_GetIndexFromObj(interp, objv[3], errorOptions, 
				    "error suboption", TCL_EXACT, &errorOptIndex) != TCL_OK) {
					return TCL_ERROR;
				}

				Tcl_SetObjResult(interp, Tcl_NewStringObj(
                    PQresultErrorField(result,pgDiagCodes[errorOptIndex]),-1));

				return TCL_OK;
			}

		case OPT_CONN:
			{
				if (objc != 3)
				{
					Tcl_WrongNumArgs(interp, 3, objv, "");
					return TCL_ERROR;
				}

				return PgGetConnByResultId(interp, queryResultString);
			}

		case OPT_OID:
			{
				if (objc != 3)
				{
					Tcl_WrongNumArgs(interp, 3, objv, "");
					return TCL_ERROR;
				}

				Tcl_SetObjResult(interp, Tcl_NewLongObj(PQoidValue(result)));
				return TCL_OK;
			}

		case OPT_CLEAR:
			{
				if (objc != 3)
				{
					Tcl_WrongNumArgs(interp, 3, objv, "");
					return TCL_ERROR;
				}

                /* This will take care of the cleanup */
                Tcl_DeleteCommandFromToken(interp, resultid->cmd_token);
				return TCL_OK;
			}

		case OPT_NUMTUPLES:
			{
				if (objc != 3)
				{
					Tcl_WrongNumArgs(interp, 3, objv, "");
					return TCL_ERROR;
				}

				Tcl_SetObjResult(interp, Tcl_NewIntObj(PQntuples(result)));
				return TCL_OK;
			}
		case OPT_CMDTUPLES:
			{
				if (objc != 3)
				{
					Tcl_WrongNumArgs(interp, 3, objv, "");
					return TCL_ERROR;
				}

				Tcl_SetObjResult(interp, Tcl_NewStringObj(
                  PQcmdTuples(result), -1));
				return TCL_OK;
			}

		case OPT_NUMATTRS:
			{
				if (objc != 3)
				{
					Tcl_WrongNumArgs(interp, 3, objv, "");
					return TCL_ERROR;
				}

				Tcl_SetObjResult(interp, Tcl_NewIntObj(PQnfields(result)));
				return TCL_OK;
			}

		case OPT_ASSIGN:
			{
				if (objc != 4)
				{
					Tcl_WrongNumArgs(interp, 3, objv, "arrayName");
					return TCL_ERROR;
				}

				arrVarObj = objv[3];

				/*
				 * this assignment assigns the table of result tuples into
				 * a giant array with the name given in the argument. The
				 * indices of the array are of the form (tupno,attrName).
				 */
				for (tupno = 0; tupno < PQntuples(result); tupno++)
				{
					for (i = 0; i < PQnfields(result); i++)
					{
						Tcl_Obj    *fieldNameObj;

						/*
						 * construct the array element name consisting
						 * of the tuple number, a comma, and the field
						 * name.
						 * this is a little kludgey -- we set the obj
						 * to an int but the append following will force a
						 * string conversion.
						 */
						fieldNameObj = Tcl_NewObj ();
						Tcl_SetIntObj(fieldNameObj, tupno);
						Tcl_AppendToObj(fieldNameObj, ",", 1);
						Tcl_AppendToObj(fieldNameObj, PQfname(result, i), -1);


						if (Tcl_ObjSetVar2(interp, arrVarObj, fieldNameObj,
										   Tcl_NewStringObj(
											 PGgetvalue(result, resultid->nullValueString, tupno, i),
											 -1), TCL_LEAVE_ERR_MSG) == NULL) {
							Tcl_DecrRefCount (fieldNameObj);
							return TCL_ERROR;
						}
					}
				}
				return TCL_OK;
			}

		case OPT_ASSIGNBYIDX:
			{

				if ((objc != 4) && (objc != 5))
				{
					Tcl_WrongNumArgs(interp, 3, objv, "arrayName ?append_string?");
					return TCL_ERROR;
				}

				arrVarObj = objv[3];

				if (objc == 5)
					appendstrObj = objv[4];
				else
					appendstrObj = NULL;

				/*
				 * this assignment assigns the table of result tuples into
				 * a giant array with the name given in the argument.  The
				 * indices of the array are of the form
				 * (field0Value,attrNameappendstr). Here, we still assume
				 * PQfname won't exceed 200 characters, but we dare not
				 * make the same assumption about the data in field 0 nor
				 * the append string.
				 */
				for (tupno = 0; tupno < PQntuples(result); tupno++)
				{
					CONST84 char *field0 = PGgetvalue(result, resultid->nullValueString, tupno, 0);

					for (i = 1; i < PQnfields(result); i++)
					{
						Tcl_Obj    *fieldNameObj;


						fieldNameObj = Tcl_NewObj ();
						Tcl_SetStringObj(fieldNameObj, field0, -1);
						Tcl_AppendToObj(fieldNameObj, ",", 1);
						Tcl_AppendToObj(fieldNameObj, PQfname(result, i), -1);

						if (appendstrObj != NULL)
							Tcl_AppendObjToObj(fieldNameObj, appendstrObj);

						if (Tcl_ObjSetVar2(interp, arrVarObj, fieldNameObj,
										   Tcl_NewStringObj( PGgetvalue(result, resultid->nullValueString, tupno, i), -1), TCL_LEAVE_ERR_MSG) == NULL)
						{
                            
							Tcl_DecrRefCount(fieldNameObj);
							return TCL_ERROR;
						}
					}
				}
				return TCL_OK;
			}

		case OPT_GETTUPLE:
			{
				Tcl_Obj    *resultObj;

				if (objc != 4)
				{
					Tcl_WrongNumArgs(interp, 3, objv, "tuple_number");
					return TCL_ERROR;
				}

				if (Tcl_GetIntFromObj(interp, objv[3], &tupno) == TCL_ERROR)
					return TCL_ERROR;

				if (tupno < 0 || tupno >= PQntuples(result))
				{
                    tresult = Tcl_NewStringObj("argument to getTuple cannot exceed ", -1);
                    Tcl_AppendStringsToObj(tresult, "number of tuples - 1", NULL);
                    Tcl_SetObjResult(interp, tresult);
/*
                    Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
                        "argument to getTuple cannot exceed ",
                        "number of tuples - 1", NULL);
*/
					return TCL_ERROR;
				}

				/* set the result object to be an empty list */
                resultObj = Tcl_NewListObj(0, NULL);

				/* build up a return list, Tcl-object-style */
				for (i = 0; i < PQnfields(result); i++)
				{
					char	   *value;

					value = PGgetvalue(result, resultid->nullValueString, tupno, i);
					if (Tcl_ListObjAppendElement(interp, resultObj,
							   Tcl_NewStringObj(value, -1)) == TCL_ERROR)
						return TCL_ERROR;
				}
                Tcl_SetObjResult(interp, resultObj);
				return TCL_OK;
			}

		case OPT_TUPLEARRAY:
		case OPT_TUPLEARRAY_WITHOUT_NULLS:
			{
				char	   *arrayName;

				if (objc != 5)
				{
					Tcl_WrongNumArgs(interp, 3, objv, "tuple_number array_name");
					return TCL_ERROR;
				}

				if (Tcl_GetIntFromObj(interp, objv[3], &tupno) == TCL_ERROR)
					return TCL_ERROR;

				if (tupno < 0 || tupno >= PQntuples(result))
				{
                    tresult = Tcl_NewStringObj("argument to tupleArray cannot exceed number of tuples - 1", -1);
                    Tcl_SetObjResult(interp, tresult);
					return TCL_ERROR;
				}

				arrayName = Tcl_GetStringFromObj(objv[4], NULL);

				if (optIndex == OPT_TUPLEARRAY)
				{
					/* it's the -array variant, if the field is null,
					 * set it in the array as the empty string or
					 * as the set null value string if one is set
					 */
					for (i = 0; i < PQnfields(result); i++)
					{
						if (Tcl_SetVar2(interp, arrayName, PQfname(result, i),
							 PGgetvalue(result, resultid->nullValueString, 
								 tupno, i), TCL_LEAVE_ERR_MSG) == NULL)
						return TCL_ERROR;
					}
				} else
				{
					/* it's the array_without_nulls variant,
					 * unset the field name from the array
					 * if it's null, else set it.
					 */
					for (i = 0; i < PQnfields(result); i++)
					{
						char *string;

						string = PQgetvalue (result, tupno, i);
						if (*string == '\0') {
							if (PQgetisnull (result, tupno, i)) {
							   Tcl_UnsetVar2 (interp, arrayName, PQfname(result, i), 0);
							   continue;
							}
						}

						if (Tcl_SetVar2(interp, arrayName, PQfname(result, i),
									 string,
										TCL_LEAVE_ERR_MSG) == NULL)
							return TCL_ERROR;
					}
				}
				return TCL_OK;
			}

		case OPT_ATTRIBUTES:
			{
				Tcl_Obj    *resultObj = Tcl_NewListObj(0, NULL);

				if (objc != 3)
				{
					Tcl_WrongNumArgs(interp, 3, objv, "");
					return TCL_ERROR;
				}

				for (i = 0; i < PQnfields(result); i++)
				{
					Tcl_ListObjAppendElement(interp, resultObj,
							   Tcl_NewStringObj(PQfname(result, i), -1));
				}
                Tcl_SetObjResult(interp, resultObj);
				return TCL_OK;
			}

		case OPT_LATTRIBUTES:
			{
				Tcl_Obj    *resultObj = Tcl_NewListObj(0, NULL);

				if (objc != 3)
				{
					Tcl_WrongNumArgs(interp, 3, objv, "");
					return TCL_ERROR;
				}

				for (i = 0; i < PQnfields(result); i++)
				{

					/* start a sublist */
					Tcl_Obj    *subList = Tcl_NewListObj(0, NULL);

					if (Tcl_ListObjAppendElement(interp, subList,
												 Tcl_NewStringObj(PQfname(result, i), -1)) == TCL_ERROR)
						return TCL_ERROR;

					if (Tcl_ListObjAppendElement(interp, subList,
												 Tcl_NewLongObj((long)PQftype(result, i))) == TCL_ERROR)
						return TCL_ERROR;

					if (Tcl_ListObjAppendElement(interp, subList,
												 Tcl_NewLongObj((long)PQfsize(result, i))) == TCL_ERROR)
						return TCL_ERROR;

					/* end the sublist, append to the result list */

					if (Tcl_ListObjAppendElement(interp, resultObj, subList)
						== TCL_ERROR)
						return TCL_ERROR;
				}
                Tcl_SetObjResult(interp, resultObj);
				return TCL_OK;
			}

		case OPT_LIST: 
		{
 	
			listObj = Tcl_NewListObj(0, (Tcl_Obj **) NULL);

			/*
			**	Loop through the tuple, and append each 
			**	attribute to the list
			**
			**	This option appends all of the attributes
			**	for each tuple to the same list
			*/
			for (tupno = 0; tupno < PQntuples(result); tupno++)
			{

				/*
				**	Loop over the attributes for the tuple, 
				**	and append them to the list
				*/
				for (i = 0; i < PQnfields(result); i++)
				{
				    fieldObj = Tcl_NewObj();

				    Tcl_SetStringObj(fieldObj, PGgetvalue(result, resultid->nullValueString, tupno, i), -1);
				    if (Tcl_ListObjAppendElement(interp, listObj, fieldObj) != TCL_OK)
					{
						Tcl_DecrRefCount(listObj);
						Tcl_DecrRefCount(fieldObj);
						return TCL_ERROR;
					}
	
				}
			}
	
			Tcl_SetObjResult(interp, listObj);
			
			return TCL_OK;

		}
		case OPT_LLIST: 
		{
			listObj = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
	
			/*
			**	This is the top level list. This
			**	contains the other lists
			**
			**	This option contructs a list of
			**	attributes for each tuple, and
			**	appends that to the main list.
			**	This is a list of lists
			*/
			for (tupno = 0; tupno < PQntuples(result); tupno++)
			{
				subListObj = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
	
				/*
				**	This is the inner list. This contains
				**	the actual row values
				*/
				for (i = 0; i < PQnfields(result); i++)
				{
	
					fieldObj = Tcl_NewObj();

					Tcl_SetStringObj(fieldObj, PGgetvalue(result, resultid->nullValueString, tupno, i), -1);
	
					if (Tcl_ListObjAppendElement(interp, subListObj, fieldObj) != TCL_OK)
					{
						Tcl_DecrRefCount(listObj);
						Tcl_DecrRefCount(fieldObj);
						return TCL_ERROR;
					}
	
				}
				if (Tcl_ListObjAppendElement(interp, listObj, subListObj) != TCL_OK)
				{
					Tcl_DecrRefCount(listObj);
					Tcl_DecrRefCount(fieldObj);
					return TCL_ERROR;
				}
			}
	
			Tcl_SetObjResult(interp, listObj);
		
			return TCL_OK;
		}

		case OPT_DICT: 
                {

#ifdef HAVE_TCL_NEWDICTOBJ
			listObj = Tcl_NewDictObj();
	
			/*
			**	This is the top level list. This
			**	contains the other lists
			**
			**	This option contructs a list of
			**	attributes for each tuple, and
			**	appends that to the main list.
			**	This is a list of lists
			*/
			for (tupno = 0; tupno < PQntuples(result); tupno++)
			{
				subListObj = Tcl_NewDictObj();
	
				/*
				**	This is the inner list. This contains
				**	the actual row values
				*/
				for (i = 0; i < PQnfields(result); i++)
				{
	
					fieldObj = Tcl_NewObj();
					fieldNameObj = Tcl_NewObj();

					Tcl_SetStringObj(fieldNameObj, PQfname(result, i), -1);
					Tcl_SetStringObj(fieldObj, PGgetvalue(result, resultid->nullValueString, tupno, i), -1);
	
					if (Tcl_DictObjPut(interp, subListObj, fieldNameObj, fieldObj) != TCL_OK)
					{
						Tcl_DecrRefCount(listObj);
						Tcl_DecrRefCount(fieldObj);
						return TCL_ERROR;
					}
	
				}
				if (Tcl_DictObjPut(interp, listObj, Tcl_NewIntObj(tupno), subListObj) != TCL_OK)
				{
					Tcl_DecrRefCount(listObj);
					Tcl_DecrRefCount(fieldObj);
					return TCL_ERROR;
				}
			}
	
			Tcl_SetObjResult(interp, listObj);
			return TCL_OK;

#endif /* HAVE_TCL_NEWDICTOBJ */
                }

		case OPT_NULL_VALUE_STRING:
			{
				char       *nullValueString;
				int         length;

				if ((objc < 3) || (objc > 4))
				{
					Tcl_WrongNumArgs(interp, 3, objv, "?nullValueString?");
					return TCL_ERROR;
				}

				if (objc == 3)
				{
					if (resultid->nullValueString == NULL || 
                           *resultid->nullValueString == '\0') {

                        Tcl_SetObjResult(interp, Tcl_NewStringObj("", 0));
					} else {
                        Tcl_SetObjResult(interp, 
                          Tcl_NewStringObj(resultid->nullValueString, -1));
					}
					return TCL_OK;
				}

				/* objc == 4, they're setting it */
				if (resultid->nullValueString != NULL) {
					if (resultid->connid->nullValueString != resultid->nullValueString)
					ckfree (resultid->nullValueString);
				}

				nullValueString = Tcl_GetStringFromObj (objv[3], &length);
				resultid->nullValueString = ckalloc (length + 1);
				strcpy (resultid->nullValueString, nullValueString);

				Tcl_SetObjResult(interp, objv[3]);
				return TCL_OK;
			}

		default:
			{
                Tcl_SetObjResult(interp, Tcl_NewStringObj("Invalid option\n", -1));
				goto Pg_result_errReturn;		/* append help info */
			}
	}

Pg_result_errReturn:

	tresult = Tcl_NewStringObj("pg_result result ?option? where option is\n", -1);
	Tcl_AppendStringsToObj(tresult, "\t-status\n",
					 "\t-error\n",
					 "\t-conn\n",
					 "\t-oid\n",
					 "\t-numTuples\n",
					 "\t-cmdTuples\n",
					 "\t-numAttrs\n"
					 "\t-assign arrayVarName\n",
					 "\t-assignbyidx arrayVarName ?appendstr?\n",
					 "\t-getTuple tupleNumber\n",
					 "\t-tupleArray tupleNumber arrayVarName\n",
					 "\t-attributes\n"
					 "\t-lAttributes\n"
					 "\t-list\n",
					 "\t-llist\n",
					 "\t-clear\n",
					 "\t-dict\n",
					 (char *)NULL);
        Tcl_SetObjResult(interp, tresult);
	return TCL_ERROR;
}


/**********************************
 * pg_execute
 send a query string to the backend connection and process the result

 syntax:
 pg_execute ?-array name? ?-oid varname? connection query ?loop_body?

 the return result is the number of tuples processed. If the query
 returns tuples (i.e. a SELECT statement), the result is placed into
 variables
 **********************************/

int
Pg_execute(ClientData cData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
	Pg_ConnectionId *connid;
	PGconn	   *conn;
	PGresult   *result;
	int			i;
	int			tupno;
	int			ntup;
	int			loop_rc;
	CONST84 char	   *array_varname = NULL;
	char	   *arg;
	char	   *connString;
	char	   *queryString;

	Tcl_Obj    *oid_varnameObj = NULL;
	Tcl_Obj    *evalObj;
	Tcl_Obj    *resultObj;

	char	   *usage = "?-array arrayname? ?-oid varname? "
	"connection queryString ?loop_body?";

	/*
	 * First we parse the options
	 */
	i = 1;
	while (i < objc)
	{
		arg = Tcl_GetStringFromObj(objv[i], NULL);
		if (arg[0] != '-')
                {
		    break;
                }

		if (strcmp(arg, "-array") == 0)
		{
			/*
			 * The rows should appear in an array vs. to single variables
			 */
			i++;
			if (i == objc)
			{
				Tcl_WrongNumArgs(interp, 1, objv, usage);
				return TCL_ERROR;
			}

			array_varname = Tcl_GetStringFromObj(objv[i++], NULL);
			continue;
		}

		arg = Tcl_GetStringFromObj(objv[i], NULL);

		if (strcmp(arg, "-oid") == 0)
		{
			/*
			 * We should place PQoidValue() somewhere
			 */
			i++;
			if (i == objc)
			{
				Tcl_WrongNumArgs(interp, 1, objv, usage);
				return TCL_ERROR;
			}
			oid_varnameObj = objv[i++];
			continue;
		}

		Tcl_WrongNumArgs(interp, 1, objv, usage);
		return TCL_ERROR;
	}

	/*
	 * Check that after option parsing at least 'connection' and 'query'
	 * are left
	 */
	if (objc - i < 2)
	{
		Tcl_WrongNumArgs(interp, 1, objv, usage);
		return TCL_ERROR;
	}

	/*
	 * Get the connection and make sure no COPY command is pending
	 */
	connString = Tcl_GetStringFromObj(objv[i++], NULL);
	conn = PgGetConnectionId(interp, connString, &connid);
	if (conn == NULL)
		return TCL_ERROR;

	if (connid->res_copyStatus != RES_COPY_NONE)
	{
            Tcl_SetObjResult(interp, 
              Tcl_NewStringObj("Attempt to query while COPY in progress", -1));

		return TCL_ERROR;
	}

        if (connid->callbackPtr || connid->callbackInterp)
        {
               Tcl_SetResult(interp, "Attempt to query while waiting for callback", TCL_STATIC);
               return TCL_ERROR;
         }


	/*
	 * Execute the query
	 */
	queryString = Tcl_GetStringFromObj(objv[i++], NULL);
	result = PQexec(conn, queryString);
	connid->sql_count++;

	/*
	 * Transfer any notify events from libpq to Tcl event queue.
	 */
	PgNotifyTransferEvents(connid);

	/*
	 * Check for errors
	 */
	if (result == NULL)
	{
            Tcl_SetObjResult(interp, Tcl_NewStringObj(PQerrorMessage(conn), -1));

		return TCL_ERROR;
	}

	/*
	 * Set the oid variable to the returned oid of an INSERT statement if
	 * requested (or 0 if it wasn't an INSERT)
	 */
	if (oid_varnameObj != NULL)
	{
		if (Tcl_ObjSetVar2(interp, oid_varnameObj, NULL,
						   Tcl_NewLongObj((long)PQoidValue(result)), TCL_LEAVE_ERR_MSG) == NULL)
		{
			PQclear(result);
			return TCL_ERROR;
		}
	}

	/*
	 * Decide how to go on based on the result status
	 */
	switch (PQresultStatus(result))
	{
		case PGRES_TUPLES_OK:
			/* fall through if we have tuples */
			break;

		case PGRES_EMPTY_QUERY:
		case PGRES_COMMAND_OK:
		case PGRES_COPY_IN:
		case PGRES_COPY_OUT:
		/* tell the number of affected tuples for non-SELECT queries */
                    Tcl_SetObjResult(interp,
                        Tcl_NewStringObj(PQcmdTuples(result), -1));
                    PQclear(result);
                    return TCL_OK;

		default:
			/* anything else must be an error */
			/* set the result object to be an empty list */
			resultObj = Tcl_NewListObj(0, NULL);
			if (Tcl_ListObjAppendElement(interp, resultObj,
			   Tcl_NewStringObj(PQresStatus(PQresultStatus(result)), -1))
				== TCL_ERROR)
				return TCL_ERROR;

			if (Tcl_ListObjAppendElement(interp, resultObj,
					  Tcl_NewStringObj(PQresultErrorMessage(result), -1))
				== TCL_ERROR)
				return TCL_ERROR;

            Tcl_SetObjResult(interp, resultObj);
			PQclear(result);
			return TCL_ERROR;
	}

	/*
	 * We reach here only for queries that returned tuples
	 */
	if (i == objc)
	{
		/*
		 * We don't have a loop body. If we have at least one result row,
		 * we set all the variables to the first one and return.
		 */
		if (PQntuples(result) > 0)
		{
			if (execute_put_values(interp, array_varname, result, connid->nullValueString, 0) != TCL_OK)
			{
				PQclear(result);
				return TCL_ERROR;
			}
		}

		Tcl_SetObjResult(interp, Tcl_NewIntObj(PQntuples(result)));
		PQclear(result);
		return TCL_OK;
	}

	/*
	 * We have a loop body. For each row in the result set, put the values
	 * into the Tcl variables and execute the body.
	 */
	ntup = PQntuples(result);
	evalObj = objv[i];
	for (tupno = 0; tupno < ntup; tupno++)
	{
		if (execute_put_values(interp, array_varname, result, connid->nullValueString, tupno) != TCL_OK)
		{
			PQclear(result);
			return TCL_ERROR;
		}

		loop_rc = Tcl_EvalObjEx(interp, evalObj, 0);

		/* The returncode of the loop body controls the loop execution */
		if (loop_rc == TCL_OK || loop_rc == TCL_CONTINUE)
		{
			/* OK or CONTINUE means start next loop invocation */
			continue;
		}

		if (loop_rc == TCL_RETURN)
		{
			/* RETURN means hand up the given interpreter result */
			PQclear(result);
			return TCL_RETURN;
		}

		if (loop_rc == TCL_BREAK)
		{
			/* BREAK means leave the loop */
			break;
		}

		PQclear(result);
		return TCL_ERROR;
	}

	/*
	 * At the end of the loop we put the number of rows we got into the
	 * interpreter result and clear the result set.
	 */
	Tcl_SetObjResult(interp, Tcl_NewIntObj(ntup));
	PQclear(result);
	return TCL_OK;
}


/**********************************
 * execute_put_values

 Put the values of one tuple into Tcl variables named like the
 column names, or into an array indexed by the column names.
 **********************************/
static int
execute_put_values(Tcl_Interp *interp, CONST84 char *array_varname,
				   PGresult *result, char *nullValueString, int tupno)
{
	int			i;
	int			n;
	char	   *fname;
	char	   *value;

	/*
	 * For each column get the column name and value and put it into a Tcl
	 * variable (either scalar or array item)
	 */
	n = PQnfields(result);
	for (i = 0; i < n; i++)
	{
		fname = PQfname(result, i);
		value = PGgetvalue(result, nullValueString, tupno, i);

		if (array_varname != NULL)
		{
			if (Tcl_SetVar2(interp, array_varname, fname, value,
							TCL_LEAVE_ERR_MSG) == NULL)
				return TCL_ERROR;
		}
		else
		{
			if (Tcl_SetVar(interp, fname, value, TCL_LEAVE_ERR_MSG) == NULL)
				return TCL_ERROR;
		}
	}
	return TCL_OK;
}

/**********************************
 * pg_lo_open
	 open a large object

 syntax:
 pg_lo_open conn objOid mode

 where mode can be either 'r', 'w', or 'rw'
**********************/

int
Pg_lo_open(ClientData cData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
	PGconn	   *conn;
	int			lobjId;
	int			mode;
	int			fd;
	char	   *connString;
	char	   *modeString;
	int			modeStringLen;

	if (objc != 4)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "connection lobjOid mode");
		return TCL_ERROR;
	}

	connString = Tcl_GetStringFromObj(objv[1], NULL);
	conn = PgGetConnectionId(interp, connString,  NULL);
	if (conn == NULL)
		return TCL_ERROR;

	if (Tcl_GetIntFromObj(interp, objv[2], &lobjId) == TCL_ERROR)
		return TCL_ERROR;

	modeString = Tcl_GetStringFromObj(objv[3], &modeStringLen);
	if ((modeStringLen < 1) || (modeStringLen > 2))
	{

        Tcl_SetObjResult(interp, 
            Tcl_NewStringObj("mode argument must be 'r', 'w', or 'rw'", -1));

		return TCL_ERROR;
	}

	switch (modeString[0])
	{
		case 'r':
		case 'R':
			mode = INV_READ;
			break;
		case 'w':
		case 'W':
			mode = INV_WRITE;
			break;
		default:
            Tcl_SetObjResult(interp, 
             Tcl_NewStringObj("mode argument must be 'r', 'w', or 'rw'", -1));
			return TCL_ERROR;
	}

	switch (modeString[1])
	{
		case '\0':
			break;
		case 'r':
		case 'R':
			mode |= INV_READ;
			break;
		case 'w':
		case 'W':
			mode |= INV_WRITE;
			break;
		default:
            Tcl_SetObjResult(interp, 
             Tcl_NewStringObj("mode argument must be 'r', 'w', or 'rw'", -1));
			return TCL_ERROR;
	}

	fd = lo_open(conn, lobjId, mode);
	Tcl_SetObjResult(interp, Tcl_NewIntObj(fd));
	return TCL_OK;
}

/**********************************
 * pg_lo_close
	 close a large object

 syntax:
 pg_lo_close conn fd

**********************/
int
Pg_lo_close(ClientData cData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
	PGconn	   *conn;
	int			fd;
	char	   *connString;

	if (objc != 3)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "connection fd");
		return TCL_ERROR;
	}

	connString = Tcl_GetStringFromObj(objv[1], NULL);
	conn = PgGetConnectionId(interp, connString, NULL);
	if (conn == NULL)
		return TCL_ERROR;

	if (Tcl_GetIntFromObj(interp, objv[2], &fd) != TCL_OK)
		return TCL_ERROR;

	Tcl_SetObjResult(interp, Tcl_NewIntObj(lo_close(conn, fd)));
	return TCL_OK;
}

/**********************************
 * pg_lo_read
	 reads at most len bytes from a large object into a variable named
 bufVar

 syntax:
 pg_lo_read conn fd bufVar len

 bufVar is the name of a variable in which to store the contents of the read

**********************/
int
Pg_lo_read(ClientData cData, Tcl_Interp *interp, int objc,
		   Tcl_Obj *CONST objv[])
{
	PGconn	   *conn;
	int			fd;
	int			nbytes = 0;
	char	   *buf;
	Tcl_Obj    *bufVar;
	Tcl_Obj    *bufObj;
	int			len;
	int			rc = TCL_OK;

	if (objc != 5)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "conn fd bufVar len");
		return TCL_ERROR;
	}

	conn = PgGetConnectionId(interp, Tcl_GetStringFromObj(objv[1], NULL),
							 NULL);
	if (conn == NULL)
		return TCL_ERROR;

	if (Tcl_GetIntFromObj(interp, objv[2], &fd) != TCL_OK)
		return TCL_ERROR;

	bufVar = objv[3];

	if (Tcl_GetIntFromObj(interp, objv[4], &len) != TCL_OK)
		return TCL_ERROR;

	if (len <= 0)
	{
		Tcl_SetObjResult(interp, Tcl_NewIntObj(nbytes));
		return TCL_OK;
	}

	buf = ckalloc(len + 1);

	nbytes = lo_read(conn, fd, buf, len);
        if (nbytes >= 0)
        {
            #if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION >= 1 || TCL_MAJOR_VERSION > 8
	        bufObj = Tcl_NewByteArrayObj((unsigned char*)buf, nbytes);
            #else
	        bufObj = Tcl_NewStringObj(buf, nbytes);
            #endif

	    if (Tcl_ObjSetVar2(interp, bufVar, NULL, bufObj,
					   TCL_LEAVE_ERR_MSG | TCL_PARSE_PART1) == NULL)
		rc = TCL_ERROR;
        }
   
        if (rc == TCL_OK)
		Tcl_SetObjResult(interp, Tcl_NewIntObj(nbytes));

	ckfree((char*)buf);
	return rc;
}

/***********************************
Pg_lo_write
   write at most len bytes to a large object

 syntax:
 pg_lo_write conn fd buf len

***********************************/
int
Pg_lo_write(ClientData cData, Tcl_Interp *interp, int objc,
			Tcl_Obj *CONST objv[])
{
	PGconn	   *conn;
	char	   *buf;
	int			fd;
	int			nbytes = 0;
	int			len;

	if (objc != 5)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "conn fd buf len");
		return TCL_ERROR;
	}

	conn = PgGetConnectionId(interp, Tcl_GetStringFromObj(objv[1], NULL),
							 NULL);
	if (conn == NULL)
		return TCL_ERROR;

	if (Tcl_GetIntFromObj(interp, objv[2], &fd) != TCL_OK)
		return TCL_ERROR;

	buf = (char*)Tcl_GetByteArrayFromObj(objv[3], &nbytes);

	if (Tcl_GetIntFromObj(interp, objv[4], &len) != TCL_OK)
		return TCL_ERROR;

	if (len > nbytes)
		len = nbytes;

	if (len <= 0)
	{
		Tcl_SetObjResult(interp, Tcl_NewIntObj(0));
		return TCL_OK;
	}

	nbytes = lo_write(conn, fd, (char*)buf, len);
	Tcl_SetObjResult(interp, Tcl_NewIntObj(nbytes));
	return TCL_OK;
}

/***********************************
Pg_lo_lseek
	seek to a certain position in a large object

syntax
  pg_lo_lseek conn fd offset whence

whence can be either
"SEEK_CUR", "SEEK_END", or "SEEK_SET"
***********************************/
int
Pg_lo_lseek(ClientData cData, Tcl_Interp *interp, int objc,
			Tcl_Obj *CONST objv[])
{
	PGconn	   *conn;
	int			fd;
	char	   *whenceStr;
	int			offset;
	int			whence;
	char	   *connString;
        Tcl_Obj    *tresult;

	if (objc != 5)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "conn fd offset whence");
		return TCL_ERROR;
	}

	connString = Tcl_GetStringFromObj(objv[1], NULL);
	conn = PgGetConnectionId(interp, connString, NULL);
	if (conn == NULL)
		return TCL_ERROR;

	if (Tcl_GetIntFromObj(interp, objv[2], &fd) != TCL_OK)
		return TCL_ERROR;

	if (Tcl_GetIntFromObj(interp, objv[3], &offset) == TCL_ERROR)
		return TCL_ERROR;

	whenceStr = Tcl_GetStringFromObj(objv[4], NULL);

	if (strcmp(whenceStr, "SEEK_SET") == 0)
		whence = SEEK_SET;
	else if (strcmp(whenceStr, "SEEK_CUR") == 0)
		whence = SEEK_CUR;
	else if (strcmp(whenceStr, "SEEK_END") == 0)
		whence = SEEK_END;
	else
	{
            tresult = Tcl_NewStringObj("'whence' must be SEEK_SET, SEEK_CUR or SEEK_END", -1);
            Tcl_SetObjResult(interp, tresult);

            return TCL_ERROR;
	}

	Tcl_SetObjResult(interp, Tcl_NewIntObj(lo_lseek(conn, fd, offset, whence)));
	return TCL_OK;
}


/***********************************
Pg_lo_creat
   create a new large object with mode

 syntax:
   pg_lo_creat conn mode

mode can be any OR'ing together of INV_READ, INV_WRITE,
for now, we don't support any additional storage managers.

***********************************/
int
Pg_lo_creat(ClientData cData, Tcl_Interp *interp, int objc,
			Tcl_Obj *CONST objv[])
{
	PGconn	   *conn;
	char	   *modeStr;
	char	   *modeWord;
	int			mode;
	char	   *connString;
        Tcl_Obj    *tresult;

	if (objc != 3)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "conn mode");
		return TCL_ERROR;
	}

	connString = Tcl_GetStringFromObj(objv[1], NULL);
	conn = PgGetConnectionId(interp, connString, NULL);
	if (conn == NULL)
		return TCL_ERROR;

	modeStr = Tcl_GetStringFromObj(objv[2], NULL);

	modeWord = strtok(modeStr, "|");
	if (strcmp(modeWord, "INV_READ") == 0)
		mode = INV_READ;
	else if (strcmp(modeWord, "INV_WRITE") == 0)
		mode = INV_WRITE;
	else
	{
            tresult = Tcl_NewStringObj("mode must be some OR'd combination of INV_READ, and INV_WRITE", -1);
            Tcl_SetObjResult(interp, tresult);

	    return TCL_ERROR;
	}

	while ((modeWord = strtok(NULL, "|")) != NULL)
	{
		if (strcmp(modeWord, "INV_READ") == 0)
			mode |= INV_READ;
		else if (strcmp(modeWord, "INV_WRITE") == 0)
			mode |= INV_WRITE;
		else
		{
                    tresult = Tcl_NewStringObj("mode must be some OR'd combination of INV_READ, and INV_WRITE", -1);
                    Tcl_SetObjResult(interp, tresult);

			return TCL_ERROR;
		}
	}

	Tcl_SetObjResult(interp, Tcl_NewIntObj(lo_creat(conn, mode)));
	return TCL_OK;
}

/***********************************
Pg_lo_tell
	returns the current seek location of the large object

 syntax:
   pg_lo_tell conn fd

***********************************/
int
Pg_lo_tell(ClientData cData, Tcl_Interp *interp, int objc,
		   Tcl_Obj *CONST objv[])
{
	PGconn	   *conn;
	int			fd;
	char	   *connString;

	if (objc != 3)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "conn fd");
		return TCL_ERROR;
	}

	connString = Tcl_GetStringFromObj(objv[1], NULL);
	conn = PgGetConnectionId(interp, connString, NULL);
	if (conn == NULL)
		return TCL_ERROR;

	if (Tcl_GetIntFromObj(interp, objv[2], &fd) != TCL_OK)
		return TCL_ERROR;

	Tcl_SetObjResult(interp, Tcl_NewIntObj(lo_tell(conn, fd)));
	return TCL_OK;
}

/***********************************
Pg_lo_truncate
	truncates a large object to the given length.  If length is greater
	than the current large object length, the large object is extended
	with null bytes.

 syntax:
   pg_lo_truncate conn fd len

***********************************/
int
Pg_lo_truncate(ClientData cData, Tcl_Interp *interp, int objc,
		   Tcl_Obj *CONST objv[])
{
#ifdef HAVE_LO_TRUNCATE
	PGconn	   *conn;
	int			fd;
	int			len = 0;
	char	   *connString;
#endif

	if ((objc < 3) || (objc > 4))
	{
		Tcl_WrongNumArgs(interp, 1, objv, "conn fd ?len?");
		return TCL_ERROR;
	}

#ifndef HAVE_LO_TRUNCATE
        Tcl_SetObjResult(interp, Tcl_NewStringObj(
          "The version of libpq that Pgtcl was compiled against does not have lo_truncate", -1));
	    return TCL_ERROR;
#else
	connString = Tcl_GetStringFromObj(objv[1], NULL);
	conn = PgGetConnectionId(interp, connString, NULL);
	if (conn == NULL)
		return TCL_ERROR;

	if (Tcl_GetIntFromObj(interp, objv[2], &fd) != TCL_OK)
		return TCL_ERROR;

	if (objc == 4) {
		if (Tcl_GetIntFromObj(interp, objv[3], &len) != TCL_OK)
			return TCL_ERROR;
	}
	Tcl_SetObjResult(interp, Tcl_NewIntObj(lo_truncate(conn, fd, len)));

#endif /* HAVE_LO_TRUNCATE */
	return TCL_OK;
}

/***********************************
Pg_lo_unlink
	unlink a file based on lobject id

 syntax:
   pg_lo_unlink conn lobjId


***********************************/
int
Pg_lo_unlink(ClientData cData, Tcl_Interp *interp, int objc,
			 Tcl_Obj *CONST objv[])
{
	PGconn	   *conn;
	int			lobjId;
	int			retval;
	char	   *connString;
        Tcl_Obj    *tresult;

	if (objc != 3)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "conn fd");
		return TCL_ERROR;
	}

	connString = Tcl_GetStringFromObj(objv[1], NULL);
	conn = PgGetConnectionId(interp, connString, NULL);
	if (conn == NULL)
		return TCL_ERROR;

	if (Tcl_GetIntFromObj(interp, objv[2], &lobjId) == TCL_ERROR)
		return TCL_ERROR;

	retval = lo_unlink(conn, lobjId);
	if (retval == -1)
	{
            tresult = Tcl_NewStringObj("unlink of '", -1);
            Tcl_AppendStringsToObj(tresult, lobjId, NULL);
            Tcl_AppendStringsToObj(tresult, "' failed", NULL);
            Tcl_SetObjResult(interp, tresult);

            return TCL_ERROR;
	}

	Tcl_SetObjResult(interp, Tcl_NewIntObj(retval));
	return TCL_OK;
}

/***********************************
Pg_lo_import
	import a Unix file into an (inversion) large objct
 returns the oid of that object upon success
 returns InvalidOid upon failure

 syntax:
   pg_lo_import conn filename

***********************************/

int
Pg_lo_import(ClientData cData, Tcl_Interp *interp, int objc,
			 Tcl_Obj *CONST objv[])
{
	PGconn	   *conn;
	const char	   *filename;
	Oid			lobjId;
	char	   *connString;
        Tcl_Obj    *tresult;

	if (objc != 3)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "conn filename");
		return TCL_ERROR;
	}

	connString = Tcl_GetStringFromObj(objv[1], NULL);
	conn = PgGetConnectionId(interp, connString, NULL);
	if (conn == NULL)
		return TCL_ERROR;

	filename = Tcl_GetStringFromObj(objv[2], NULL);

	lobjId = lo_import(conn, filename);
	if (lobjId == InvalidOid)
	{
            tresult = Tcl_NewStringObj("import of '", -1);
            Tcl_AppendStringsToObj(tresult, filename, NULL);
            Tcl_AppendStringsToObj(tresult, "' failed", NULL);
            Tcl_SetObjResult(interp, tresult);

            return TCL_ERROR;
	}

	Tcl_SetObjResult(interp, Tcl_NewLongObj((long)lobjId));
	return TCL_OK;
}

/***********************************
Pg_lo_export
	export an Inversion large object to a Unix file

 syntax:
   pg_lo_export conn lobjId filename

***********************************/

int
Pg_lo_export(ClientData cData, Tcl_Interp *interp, int objc,
			 Tcl_Obj *CONST objv[])
{
	PGconn	   *conn;
	const char	   *filename;
	Oid			lobjId;
	int			retval;
	char	   *connString;
        Tcl_Obj    *tresult;

	if (objc != 4)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "conn lobjId filename");
		return TCL_ERROR;
	}

	connString = Tcl_GetStringFromObj(objv[1], NULL);
	conn = PgGetConnectionId(interp, connString, NULL);
	if (conn == NULL)
		return TCL_ERROR;

	if (Tcl_GetIntFromObj(interp, objv[2], (int *)&lobjId) == TCL_ERROR)
		return TCL_ERROR;

	filename = Tcl_GetStringFromObj(objv[3], NULL);

	retval = lo_export(conn, lobjId, filename);
	if (retval == -1)
	{
            tresult = Tcl_NewStringObj("export failed", -1);
            Tcl_SetObjResult(interp, tresult);

            return TCL_ERROR;
	}
	return TCL_OK;
}

/**********************************
 * pg_select
 send a select query string to the backend connection

 syntax:
 pg_select ?-nodotfields? ?-withoutnulls? connection query var proc

 The query must be a select statement

 The var is used in the proc as an array

 The proc is run once for each row found

 .headers, .numcols and .tupno are not set if -nodotfields is specified

 null variables are set as empty strings unless -withoutnulls is specified,
 in which case null variables are made to simply be absent from the
 array

 Originally I was also going to update changes but that has turned out
 to be not so simple.  Instead, the caller should get the OID of any
 table they want to update and update it themself in the loop.	I may
 try to write a simplified table lookup and update function to make
 that task a little easier.

 The return is either TCL_OK, TCL_ERROR or TCL_RETURN and interp->result
 may contain more information.
 **********************************/

int
Pg_select(ClientData cData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
	Pg_ConnectionId *connid;
	PGconn	   *conn;
	PGresult   *result;
	int			r,
				retval = TCL_ERROR;
	int			tupno,
				column,
				ncols;
	int         withoutNulls = 0;
	int         noDotFields = 0;
	int         index = 1;
	char       *optString;
	char	   *connString;
	char	   *queryString;
	char	   *varNameString;
	Tcl_Obj    *varNameObj;
	Tcl_Obj    *procStringObj;
	Tcl_Obj    *columnListObj;
	Tcl_Obj   **columnNameObjs = NULL;

	if (objc < 5 || objc > 7)
	{
	    wrongargs:
		Tcl_WrongNumArgs(interp, 1, objv, "?-nodotfields? ?-withoutnulls? connection queryString var proc");
		return TCL_ERROR;
	}

	while (objc - index >= 5) {
	    optString = Tcl_GetString (objv[index]);
	    if (*optString == '-' && strcmp (optString, "-withoutnulls") == 0) {
	        withoutNulls = 1;
		index++;
	    } else if (*optString == '-' && strcmp (optString, "-nodotfields") == 0) {
	        noDotFields = 1;
		index++;
	    } else {
	        goto wrongargs;
	    }
	}

	connString = Tcl_GetStringFromObj(objv[index++], NULL);
	queryString = Tcl_GetStringFromObj(objv[index++], NULL);

	varNameObj = objv[index++];
	varNameString = Tcl_GetStringFromObj(varNameObj, NULL);

	procStringObj = objv[index++];

	conn = PgGetConnectionId(interp, connString, &connid);
	if (conn == NULL)
		return TCL_ERROR;

	connid->sql_count++;
	if ((result = PQexec(conn, queryString)) == 0)
	{
		/* error occurred sending the query */
		Tcl_SetResult(interp, PQerrorMessage(conn), TCL_VOLATILE);
		return TCL_ERROR;
	}

	/* Transfer any notify events from libpq to Tcl event queue. */
	PgNotifyTransferEvents(connid);

	if (PQresultStatus(result) != PGRES_TUPLES_OK)
	{
		/* query failed, or it wasn't SELECT */
		Tcl_SetResult(interp, (char *)PQresultErrorMessage(result),
					  TCL_VOLATILE);
		PQclear(result);
		return TCL_ERROR;
	}

	ncols = PQnfields(result);
	columnNameObjs = (Tcl_Obj **)ckalloc(sizeof(Tcl_Obj *) * ncols);

	for (column = 0; column < ncols; column++) {
		char *colName = PQfname(result, column);
		if (colName == NULL) {
			// PQfname failed, shouldn't happen, but we've seen it
			char		msg[60];

			sprintf(msg, "PQfname() returned NULL for column %d, ncols %d",
						column, ncols);
			Tcl_SetResult(interp, msg, TCL_VOLATILE);
			PQclear(result);
			return TCL_ERROR;
		} else {
			columnNameObjs[column] = Tcl_NewStringObj(colName, -1);
		}
	}

	columnListObj = Tcl_NewListObj(ncols, columnNameObjs);

	if (!noDotFields && Tcl_SetVar2Ex(interp, varNameString, ".headers", 
	                  columnListObj, TCL_LEAVE_ERR_MSG) == NULL) goto done;

	if (!noDotFields && Tcl_SetVar2Ex(interp, varNameString, ".numcols", 
	                  Tcl_NewIntObj(ncols), TCL_LEAVE_ERR_MSG) == NULL) goto done;

	retval = TCL_OK;

	for (tupno = 0; tupno < PQntuples(result); tupno++)
	{
		if (!noDotFields && Tcl_SetVar2Ex(interp, varNameString, ".tupno", 
		    Tcl_NewIntObj(tupno), TCL_LEAVE_ERR_MSG) == NULL)
		{
		    retval = TCL_ERROR;
			goto done;
		}

		for (column = 0; column < ncols; column++)
		{
			Tcl_Obj    *valueObj = NULL;
			char *string;

			string = PQgetvalue (result, tupno, column);
			if (*string == '\0') {
			    if (PQgetisnull (result, tupno, column)) {
				if (withoutNulls) {
				    Tcl_UnsetVar2 (interp, varNameString, PQfname(result, column), 0);
				    continue;
				}

				if ((connid->nullValueString != NULL) && (*connid->nullValueString != '\0')) {
				    valueObj = Tcl_NewStringObj(connid->nullValueString, -1);
				}
			    }
			}

			if (valueObj == NULL) {
			    valueObj = Tcl_NewStringObj(string, -1);
			}

			if (Tcl_ObjSetVar2(interp, varNameObj, columnNameObjs[column],
						   valueObj, TCL_LEAVE_ERR_MSG) == NULL)
			{
			    retval = TCL_ERROR;
			    goto done;
			}
		}

		r = Tcl_EvalObjEx(interp, procStringObj, 0);
		if ((r != TCL_OK) && (r != TCL_CONTINUE))
		{
			if (r == TCL_BREAK)
				break;			/* exit loop, but return TCL_OK */

			if (r == TCL_ERROR)
			{
				char		msg[60];

				sprintf(msg, "\n    (\"pg_select\" body line %d)",
						Tcl_GetErrorLine(interp));
				Tcl_AddErrorInfo(interp, msg);
			}

			retval = r;
			break;
		}
	}

	done:
	if (columnNameObjs != NULL)
	{
		ckfree((void *)columnNameObjs);
	}
	Tcl_UnsetVar(interp, varNameString, 0);
	PQclear(result);
	return retval;
}

/*
 * Test whether any callbacks are registered on this connection for
 * the given relation name.  NB: supplied name must be case-folded already.
 */

static int
Pg_have_listener(Pg_ConnectionId * connid, const char *relname)
{
	Pg_TclNotifies *notifies;
	Tcl_HashEntry *entry;

	for (notifies = connid->notify_list;
		 notifies != NULL;
		 notifies = notifies->next)
	{
		Tcl_Interp *interp = notifies->interp;

		if (interp == NULL)
			continue;			/* ignore deleted interpreter */

		entry = Tcl_FindHashEntry(&notifies->notify_hash, (char *)relname);
		if (entry == NULL)
			continue;			/* no pg_listen in this interpreter */

		return 1;			/* OK, there is a listener */
	}

	return 0;				/* Found no listener */
}

/***********************************
Pg_listen
	create or remove a callback request for notifies on a given name

 syntax:
   pg_listen conn notifyname ?callbackcommand?

   With a fourth arg, creates or changes the callback command for
   notifies on the given name; without, cancels the callback request.

   Callbacks can occur whenever Tcl is executing its event loop.
   This is the normal idle loop in Tk; in plain tclsh applications,
   vwait or update can be used to enter the Tcl event loop.
***********************************/
int
Pg_listen(ClientData cData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
	const char	   *origrelname;
	char	   *caserelname;
	char	   *callback = NULL;
	Pg_TclNotifies *notifies;
	Tcl_HashEntry *entry;
	Pg_ConnectionId *connid;
	PGconn	   *conn;
	PGresult   *result;
	int			new;
	char	   *connString;
	int			callbackStrlen = 0;
	int         origrelnameStrlen;
        Tcl_Obj     *tresult;

	if (objc < 3 || objc > 4)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "connection relname ?callback?");
		return TCL_ERROR;
	}

	/*
	 * Get the command arguments. Note that the relation name will be
	 * copied by Tcl_CreateHashEntry while the callback string must be
	 * allocated by us.
	 */
	connString = Tcl_GetStringFromObj(objv[1], NULL);
	conn = PgGetConnectionId(interp, connString, &connid);
	if (conn == NULL)
		return TCL_ERROR;

        if (connid->callbackPtr || connid->callbackInterp)
        {
               Tcl_SetResult(interp, "Attempt to query while waiting for callback", TCL_STATIC);
               return TCL_ERROR;
         }

	/*
	 * LISTEN/NOTIFY do not preserve case unless the relation name is
	 * quoted.	We have to do the same thing to ensure that we will find
	 * the desired pg_listen item.
	 */
	origrelname = Tcl_GetStringFromObj(objv[2], &origrelnameStrlen);
	caserelname = (char *)ckalloc((unsigned)(origrelnameStrlen + 1));
	if (*origrelname == '"')
	{
		/* Copy a quoted string without downcasing */
		strcpy(caserelname, origrelname + 1);
		caserelname[origrelnameStrlen - 2] = '\0';
	}
	else
	{
		/* Downcase it */
		const char   *rels = origrelname;
		char	   *reld = caserelname;

		while (*rels)
			*reld++ = tolower((unsigned char)*rels++);
		*reld = '\0';
	}

	if (objc > 3)
	{
		char	   *callbackStr;

		callbackStr = Tcl_GetStringFromObj(objv[3], &callbackStrlen);
		callback = ckalloc(callbackStrlen + 1);
		strcpy(callback, callbackStr);
	}

	/* Find or make a Pg_TclNotifies struct for this interp and connection */

	for (notifies = connid->notify_list; notifies; notifies = notifies->next)
	{
		if (notifies->interp == interp)
			break;
	}

	if (notifies == NULL)
	{
		notifies = (Pg_TclNotifies *) ckalloc(sizeof(Pg_TclNotifies));
		notifies->interp = interp;
		Tcl_InitHashTable(&notifies->notify_hash, TCL_STRING_KEYS);
		notifies->conn_loss_cmd = NULL;
		notifies->next = connid->notify_list;
		connid->notify_list = notifies;
		Tcl_CallWhenDeleted(interp, PgNotifyInterpDelete,
							(ClientData)notifies);
	}

	if (callback)
	{
		/*
		 * Create or update a callback for a relation
		 */
		int			alreadyHadListener = Pg_have_listener(connid, caserelname);

		entry = Tcl_CreateHashEntry(&notifies->notify_hash, caserelname, &new);
		/* If update, free the old callback string */
		if (!new)
			ckfree((char *)Tcl_GetHashValue(entry));

		/* Store the new callback string */
		Tcl_SetHashValue(entry, callback);

		/* Start the notify event source if it isn't already running */
		PgStartNotifyEventSource(connid);

		/*
		 * Send a LISTEN command if this is the first listener.
		 */
		if (!alreadyHadListener)
		{
			char	   *cmd = (char *)ckalloc((unsigned)(origrelnameStrlen + 8));

			sprintf(cmd, "LISTEN %s", origrelname);
			result = PQexec(conn, cmd);
			ckfree(cmd);
			/* Transfer any notify events from libpq to Tcl event queue. */
			PgNotifyTransferEvents(connid);
			if (PQresultStatus(result) != PGRES_COMMAND_OK)
			{
				/* Error occurred during the execution of command */
				PQclear(result);
				Tcl_DeleteHashEntry(entry);
				ckfree(callback);
				ckfree(caserelname);
				Tcl_SetResult(interp, PQerrorMessage(conn), TCL_VOLATILE);
				return TCL_ERROR;
			}
			PQclear(result);
		}
	}
	else
	{
		/*
		 * Remove a callback for a relation
		 */
		entry = Tcl_FindHashEntry(&notifies->notify_hash, caserelname);
		if (entry == NULL)
		{
                    tresult = Tcl_NewStringObj("not listening on ", -1);
                    Tcl_AppendStringsToObj(tresult, origrelname, NULL);
                    Tcl_SetObjResult(interp, tresult);

			ckfree(caserelname);
			return TCL_ERROR;
		}
		ckfree((char *)Tcl_GetHashValue(entry));
		Tcl_DeleteHashEntry(entry);

		/*
		 * Send an UNLISTEN command if that was the last listener. Note:
		 * we don't attempt to turn off the notify mechanism if no LISTENs
		 * remain active; not worth the trouble.
		 */
		if (!Pg_have_listener(connid, caserelname))
		{
			char	   *cmd = (char *)
			ckalloc((unsigned)(origrelnameStrlen + 10));

			sprintf(cmd, "UNLISTEN %s", origrelname);
			result = PQexec(conn, cmd);
			ckfree(cmd);
			/* Transfer any notify events from libpq to Tcl event queue. */
			PgNotifyTransferEvents(connid);
			if (PQresultStatus(result) != PGRES_COMMAND_OK)
			{
				/* Error occurred during the execution of command */
				PQclear(result);
				ckfree(caserelname);
				Tcl_SetResult(interp, PQerrorMessage(conn), TCL_VOLATILE);
				return TCL_ERROR;
			}
			PQclear(result);
		}
	}

	ckfree(caserelname);
	return TCL_OK;
}

/**********************************
 * pg_sendquery
 send a query string to the backend connection

 syntax:
 pg_sendquery connection query

 the return result is either an error message or nothing, indicating the
 command was dispatched.
 **********************************/
int
Pg_sendquery(ClientData cData, Tcl_Interp *interp, int objc,
			 Tcl_Obj *CONST objv[])
{
	Pg_ConnectionId *connid;
	PGconn	   *conn;
	char	   *connString;
	char	   *execString;
	int			status;

	/* THIS CODE IS REPLICATED IN Pg_exec AND SHOULD BE FACTORED */
#ifdef HAVE_PQSENDQUERYPARAMS
	int         nParams;
	const char **paramValues = NULL;

	if (objc < 3)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "connection queryString [parm...]");
		return TCL_ERROR;
	}

	/* extra params will substitute for $1, $2, etc, in the statement */
	/* objc must be 3 or greater at this point */
	nParams = objc - 3;

	/* If there are any extra params, allocate paramValues and fill it
	 * with the string representations of all of the extra parameters
	 * substituted on the command line.  Otherwise nParams will be 0,
	 * and PQexecParams will work just like PQexec (no $-substitutions).
	 */
	if (nParams > 0) {
	    int param;

	    paramValues = (const char **)ckalloc (nParams * sizeof (char *));

	    for (param = 0; param < nParams; param++) {
		paramValues[param] = Tcl_GetStringFromObj (objv[3+param], NULL);
		if (strcmp(paramValues[param], "NULL") == 0)
                {
                    paramValues[param] = '\0';
                }
	    }
	}
#else /* HAVE_PQSENDQUERYPARAMS */
	if (objc != 3)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "connection queryString");
		return TCL_ERROR;
	}
#endif /* HAVE_PQSENDQUERYPARAMS */

	connString = Tcl_GetStringFromObj(objv[1], NULL);

	conn = PgGetConnectionId(interp, connString, &connid);
	if (conn == NULL)
		return TCL_ERROR;

	if (connid->res_copyStatus != RES_COPY_NONE)
	{
		Tcl_SetResult(interp, "Attempt to query while COPY in progress", TCL_STATIC);
		return TCL_ERROR;
	}

	execString = Tcl_GetStringFromObj(objv[2], NULL);

#ifdef HAVE_PQSENDQUERYPARAMS
	if (nParams == 0) {
#endif
		status = PQsendQuery(conn, execString);
#ifdef HAVE_PQSENDQUERYPARAMS
	} else {
	    status = PQsendQueryParams(conn, execString, nParams, NULL, paramValues, NULL, NULL, 1);
	    ckfree ((void *)paramValues);
	}
#endif
	connid->sql_count++;

	/* Transfer any notify events from libpq to Tcl event queue. */
	PgNotifyTransferEvents(connid);

	if (status)
		return TCL_OK;
	else
	{
		/* error occurred during the query */
		Tcl_SetObjResult(interp, Tcl_NewStringObj(PQerrorMessage(conn), -1));
		return TCL_ERROR;
	}
}

/**********************************
 * pg_sendquery_prepared
 send a request to executed a prepared statement with given parameters  
 to the backend connection, asynchronously

 syntax:
 pg_sendquery_prepared connection statement_name [var1] [var2]...

 the return result is either an error message or a handle for a query
 result.  Handles start with the prefix "pgp"
 **********************************/

int
Pg_sendquery_prepared(ClientData cData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
	Pg_ConnectionId *connid;
	PGconn	   *conn;
	char	   *connString;
	char	   *statementNameString;
	const char **paramValues = NULL;

	int         nParams;
	int         status;

    /* THIS CODE IS REPLICATED IN Pg_exec_prepared AND NEEDS TO BE FACTORED */
#ifndef HAVE_PQSENDQUERYPREPARED
        Tcl_SetObjResult(interp, Tcl_NewStringObj("function unavailable with this version of the postgres libpq library", -1));
	return TCL_ERROR;
#else /* HAVE_PQSENDQUERYPREPARED */
	if (objc < 3)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "connection statementName [parm...]");
		return TCL_ERROR;
	}

	/* extra params will substitute for $1, $2, etc, in the statement */
	/* objc must be 3 or greater at this point */
	nParams = objc - 3;

	/* figure out the connect string and get the connection ID */

	connString = Tcl_GetStringFromObj(objv[1], NULL);
	conn = PgGetConnectionId(interp, connString, &connid);
	if (conn == NULL)
		return TCL_ERROR;

	if (connid->res_copyStatus != RES_COPY_NONE)
	{
		Tcl_SetResult(interp, "Attempt to query while COPY in progress", TCL_STATIC);
		return TCL_ERROR;
	}

	/* If there are any extra params, allocate paramValues and fill it
	 * with the string representations of all of the extra parameters
	 * substituted on the command line.  Otherwise nParams will be 0,
	 * and we don't need to allocate space, paramValues will be NULL.
	 * However, prepared statements that don't take any parameters aren't
	 * generally real useful.
	 */
	if (nParams > 0) {
	    int param;

	    paramValues = (const char **)ckalloc (nParams * sizeof (char *));

	    for (param = 0; param < nParams; param++) {
		paramValues[param] = Tcl_GetStringFromObj (objv[3+param], NULL);
		if (strcmp(paramValues[param], "NULL") == 0)
                {
                    paramValues[param] = '\0';
                }
	    }
	}

	statementNameString = Tcl_GetStringFromObj(objv[2], NULL);

	status = PQsendQueryPrepared(conn, statementNameString, nParams, paramValues, NULL, NULL, 1);
	connid->sql_count++;

	if (paramValues != (const char **)NULL) {
	    ckfree ((void *)paramValues);
	}

	/* Transfer any notify events from libpq to Tcl event queue. */
	PgNotifyTransferEvents(connid);

	if (status)
		return TCL_OK;
	else
	{
		/* error occurred during the query */
		Tcl_SetObjResult(interp, Tcl_NewStringObj(PQerrorMessage(conn), -1));
		return TCL_ERROR;
	}
#endif /* HAVE_PQSENDQUERYPREPARED */
}

/**********************************
 * pg_set_single_row_mode
 if called at the correct time and referencing new enough libpq (9.2+)
 this activates single-row return mode for the current query and returns 1,
 else returns 0.

 syntax:
 pg_set_single_row_mode connection

 the return result is either 1 or 0.
 **********************************/

int
Pg_set_single_row_mode(ClientData cData, Tcl_Interp *interp, int objc,
			Tcl_Obj *CONST objv[])
{
	Pg_ConnectionId *connid;
	PGconn	   *conn;
	char	   *connString;
#ifdef HAVE_PQSETSINGLEROWMODE
	int         setRowModeResult;
#endif

	if (objc != 2)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "connection");
		return TCL_ERROR;
	}

	connString = Tcl_GetStringFromObj(objv[1], NULL);

	conn = PgGetConnectionId(interp, connString, &connid);
	if (conn == NULL)
		return TCL_ERROR;

#ifndef HAVE_PQSETSINGLEROWMODE
                Tcl_SetObjResult(interp, 
                    Tcl_NewStringObj(
                        "function unavailable with this version of the postgres libpq library\n", -1));

	        return TCL_ERROR;
#else
	setRowModeResult = PQsetSingleRowMode (conn);
	Tcl_SetObjResult (interp, Tcl_NewIntObj (setRowModeResult));
	return TCL_OK;
#endif
}


/**********************************
 * pg_getresult
 wait for the next result from a prior pg_sendquery

 syntax:
 pg_getresult connection

 the return result is either an error message, nothing, or a handle for a query
 result.  Handles start with the prefix "pgp"
 **********************************/

int
Pg_getresult(ClientData cData, Tcl_Interp *interp, int objc,
			 Tcl_Obj *CONST objv[])
{
	Pg_ConnectionId *connid;
	PGconn	   *conn;
	PGresult   *result;
	char	   *connString;

	if (objc != 2)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "connection");
		return TCL_ERROR;
	}

	connString = Tcl_GetStringFromObj(objv[1], NULL);

	conn = PgGetConnectionId(interp, connString, &connid);
	if (conn == NULL)
		return TCL_ERROR;

        if (connid->callbackPtr || connid->callbackInterp)
        {
           /* Cancel any callback script: the user lost patience */

           Tcl_DecrRefCount(connid->callbackPtr);
           Tcl_Release((ClientData) connid->callbackInterp);

           connid->callbackPtr=NULL;
           connid->callbackInterp=NULL;
        }


	result = PQgetResult(conn);

	/* Transfer any notify events from libpq to Tcl event queue. */
	PgNotifyTransferEvents(connid);

	/* if there's a non-null result, give the caller the handle */
	if (result)
	{
		int			rId = PgSetResultId(interp, connString, result);

		ExecStatusType rStat = PQresultStatus(result);

		if (rStat == PGRES_COPY_IN || rStat == PGRES_COPY_OUT)
		{
			connid->res_copyStatus = RES_COPY_INPROGRESS;
			connid->res_copy = rId;
		}
	}
	return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * Pg_getdata --
 *
 *    returns the data from the connection, from either a async
 *    connection, or a async query
 *
 * Syntax:
 *    pg_getdata $conn -result|-connection
 *
 * Results:
 *    the return result is a handle for the data that has
 *    arrived on that connection channel
 *
 *----------------------------------------------------------------------
 */

int
Pg_getdata(ClientData cData, Tcl_Interp *interp, int objc,
			 Tcl_Obj *CONST objv[])
{
    Pg_ConnectionId *connid;
    PGconn	    *conn;
    char	    *connString;
    int             optIndex;

    static CONST84 char *options[] = {
    	"-result", "-connection", NULL
    };

    enum options
    {
    	OPT_RESULT, OPT_CONNECTION
    };
    
    if (objc != 3)
    {
    	Tcl_WrongNumArgs(interp, 1, objv, "connection -result|-connection");
        return TCL_ERROR;
    }

    if (Tcl_GetIndexFromObj(interp, objv[2], options, "option", TCL_EXACT, &optIndex) != TCL_OK)
    {
		return TCL_ERROR;
    }

    connString = Tcl_GetStringFromObj(objv[1], NULL);

    conn = PgGetConnectionId(interp, connString, &connid);
    if (conn == NULL)
    	return TCL_ERROR;

    if (optIndex == OPT_RESULT)
    {
        PGresult        *result;
        result = PQgetResult(conn);

        /* if there's a non-null result, give the caller the handle */
        if (result)
        {
            int    rId = PgSetResultId(interp, connString, result);
    
            ExecStatusType rStat = PQresultStatus(result);
    
            if (rStat == PGRES_COPY_IN || rStat == PGRES_COPY_OUT)
            {
                connid->res_copyStatus = RES_COPY_INPROGRESS;
                connid->res_copy = rId;
            }
        }
    }
    else if (optIndex == OPT_CONNECTION)
    {
        PostgresPollingStatusType pollstatus;
        Tcl_Obj         *res = NULL;

        pollstatus = PQconnectPoll(conn);

        switch (pollstatus)
        {
            case PGRES_POLLING_FAILED:
            {
                res = Tcl_NewStringObj("PGRES_POLLING_FAILED", -1);
                break;
            }
            case PGRES_POLLING_READING:
            {
                res = Tcl_NewStringObj("PGRES_POLLING_READING", -1);
                break;
            }
            case PGRES_POLLING_WRITING:
            {
                res = Tcl_NewStringObj("PGRES_POLLING_WRITING", -1);
                break;
            }
            case PGRES_POLLING_OK:
            {
                res = Tcl_NewStringObj("PGRES_POLLING_OK", -1);
                break;
            }
            case PGRES_POLLING_ACTIVE:
            {
                res = Tcl_NewStringObj("PGRES_POLLING_ACTIVE", -1);
            }
        }

	Tcl_SetObjResult(interp, res);
    }
    else
    {
    	Tcl_WrongNumArgs(interp, 1, objv, "connection -result|-connection");
        return TCL_ERROR;
    }
        /* Transfer any notify events from libpq to Tcl event queue. */
        PgNotifyTransferEvents(connid);
    return TCL_OK;
}

/**********************************
 * pg_isbusy
 see if a query is busy, i.e. pg_getresult would block.

 syntax:
 pg_isbusy connection

 return is 1 if it's busy and pg_getresult would block, 0 otherwise
 **********************************/

int
Pg_isbusy(ClientData cData, Tcl_Interp *interp, int objc,
		  Tcl_Obj *CONST objv[])
{
	Pg_ConnectionId *connid;
	PGconn	   *conn;
	char	   *connString;

	if (objc != 2)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "connection");
		return TCL_ERROR;
	}

	connString = Tcl_GetStringFromObj(objv[1], NULL);

	conn = PgGetConnectionId(interp, connString, &connid);
	if (conn == NULL)
		return TCL_ERROR;

	PQconsumeInput(conn);

	Tcl_SetObjResult(interp, Tcl_NewIntObj(PQisBusy(conn)));
	return TCL_OK;
}

/**********************************
 * pg_blocking
 see or set whether or not a connection is set to blocking or nonblocking

 syntax:
 pg_blocking connection
 pg_blocking connection 1
 pg_blocking connection 0

 return is 1 if it's blocking or 0 if not (if called with two arguments),
 sets blocking if called with 3.
 **********************************/

int
Pg_blocking(ClientData cData, Tcl_Interp *interp, int objc,
			Tcl_Obj *CONST objv[])
{
	Pg_ConnectionId *connid;
	PGconn	   *conn;
	char	   *connString;
	int			boolean;

	if ((objc < 2) || (objc > 3))
	{
		Tcl_WrongNumArgs(interp, 1, objv, "connection ?bool?");
		return TCL_ERROR;
	}

	connString = Tcl_GetStringFromObj(objv[1], NULL);

	conn = PgGetConnectionId(interp, connString, &connid);
	if (conn == NULL)
		return TCL_ERROR;

	if (objc == 2)
	{
		Tcl_SetObjResult(interp, Tcl_NewBooleanObj(!PQisnonblocking(conn)));
		return TCL_OK;
	}

	/* objc == 3, they're setting it */
	if (Tcl_GetBooleanFromObj(interp, objv[2], &boolean) == TCL_ERROR)
		return TCL_ERROR;

	PQsetnonblocking(conn, !boolean);
	return TCL_OK;
}

/**********************************
 * pg_null_value_string
 see or set the null value string

 syntax:
 pg_null_value_string connection
 pg_null_value_string connection nullString

 return is the current null value string if called with two arguments or
 the new null value string if called with 3.
 **********************************/

int
Pg_null_value_string(ClientData cData, Tcl_Interp *interp, int objc,
			         Tcl_Obj *CONST objv[])
{
	Pg_ConnectionId *connid;
	PGconn	   *conn;
	char	   *connString;
	char       *nullValueString;
	int			length;

	if ((objc < 2) || (objc > 3))
	{
		Tcl_WrongNumArgs(interp, 1, objv, "connection ?string?");
		return TCL_ERROR;
	}

	connString = Tcl_GetStringFromObj(objv[1], NULL);

	conn = PgGetConnectionId(interp, connString, &connid);
	if (conn == NULL)
		return TCL_ERROR;

	if (objc == 2)
	{
		if (connid->nullValueString == NULL || *connid->nullValueString == '\0') {
			Tcl_SetObjResult(interp, Tcl_NewStringObj("", 0));
		} else {
			Tcl_SetObjResult(interp, 
                          Tcl_NewStringObj(connid->nullValueString, -1));
		}
		return TCL_OK;
	}

	/* objc == 3, they're setting it */
	if (connid->nullValueString != NULL) {
		ckfree (connid->nullValueString);
	}

	nullValueString = Tcl_GetStringFromObj (objv[2], &length);
	connid->nullValueString = ckalloc (length + 1);
	strcpy (connid->nullValueString, nullValueString);

	Tcl_SetObjResult(interp, objv[2]);
	return TCL_OK;
}

/**********************************
 * pg_cancelrequest
 request that postgresql abandon processing of the current command

 syntax:
 pg_cancelrequest connection

 returns nothing if the command successfully dispatched or if nothing was
 going on, otherwise an error
 **********************************/

int
Pg_cancelrequest(ClientData cData, Tcl_Interp *interp, int objc,
				 Tcl_Obj *CONST objv[])
{
	Pg_ConnectionId *connid;
	PGconn	   *conn;
	char	   *connString;

	if (objc != 2)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "connection");
		return TCL_ERROR;
	}

	connString = Tcl_GetStringFromObj(objv[1], NULL);

	conn = PgGetConnectionId(interp, connString, &connid);
	if (conn == NULL)
		return TCL_ERROR;

       /*
        * Clear any async result callback, if present.
        */

        if (connid->callbackPtr)    {
           Tcl_DecrRefCount(connid->callbackPtr);
           connid->callbackPtr = NULL;
        }

        if (connid->callbackInterp) {
           Tcl_Release((ClientData) connid->callbackInterp);
           connid->callbackInterp = NULL;
        }


	if (PQrequestCancel(conn) == 0)
	{
		Tcl_SetObjResult(interp,
			 Tcl_NewStringObj(PQerrorMessage(conn), -1));
		return TCL_ERROR;
	}
	return TCL_OK;
}

/***********************************
Pg_on_connection_loss
	create or remove a callback request for unexpected connection loss

 syntax:
   pg_on_connection_loss conn ?callbackcommand?

   With a third arg, creates or changes the callback command for
   connection loss; without, cancels the callback request.

   Callbacks can occur whenever Tcl is executing its event loop.
   This is the normal idle loop in Tk; in plain tclsh applications,
   vwait or update can be used to enter the Tcl event loop.
***********************************/
int
Pg_on_connection_loss(ClientData cData, Tcl_Interp *interp, int objc,
				 Tcl_Obj *CONST objv[])
{
	char	   *callback = NULL;
	Pg_TclNotifies *notifies;
	Pg_ConnectionId *connid;
	PGconn	   *conn;
	char	   *connString;

	if (objc < 2 || objc > 3)
	{
		Tcl_WrongNumArgs(interp, 1, objv, "connection ?callback?");
		return TCL_ERROR;
	}

	/*
	 * Get the command arguments.
	 */
	connString = Tcl_GetStringFromObj(objv[1], NULL);
	conn = PgGetConnectionId(interp, connString, &connid);
	if (conn == NULL)
		return TCL_ERROR;

	if (objc > 2)
	{
		int         callbackStrLen;
		char	   *callbackStr;

		/* there is probably a better way to do this, like incrementing
		 * the reference count (?) */
		callbackStr = Tcl_GetStringFromObj(objv[2], &callbackStrLen);
		callback = (char *) ckalloc((unsigned) (callbackStrLen + 1));
		strcpy(callback, callbackStr);
	}

	/* Find or make a Pg_TclNotifies struct for this interp and connection */

	for (notifies = connid->notify_list; notifies; notifies = notifies->next)
	{
		if (notifies->interp == interp)
			break;
	}
	if (notifies == NULL)
	{
		notifies = (Pg_TclNotifies *) ckalloc(sizeof(Pg_TclNotifies));
		notifies->interp = interp;
		Tcl_InitHashTable(&notifies->notify_hash, TCL_STRING_KEYS);
		notifies->conn_loss_cmd = NULL;
		notifies->next = connid->notify_list;
		connid->notify_list = notifies;
		Tcl_CallWhenDeleted(interp, PgNotifyInterpDelete,
							(ClientData) notifies);
	}

	/* Store new callback setting */

	if (notifies->conn_loss_cmd)
		ckfree((void *) notifies->conn_loss_cmd);
	notifies->conn_loss_cmd = callback;

	if (callback)
	{
		/*
		 * Start the notify event source if it isn't already running. The
		 * notify source will cause Tcl to watch read-ready on the
		 * connection socket, so that we find out quickly if the
		 * connection drops.
		 */
		PgStartNotifyEventSource(connid);
	}

	return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * Pg_quote --
 *
 *    returns the quoted version of the passed in string
 *
 * Syntax:
 *    pg_quote ?connection? string
 *
 * Results:
 *
 *    If the connection handle is specified, we examine the string to
 *    see if it matches the null value string defined in the connection
 *    ID.  If it is, we return the string "NULL", unquoted.
 *
 *    If the passed in string doesn't match the null value string or if
 *    pg_quote was invoked with only one argument, the string is escaped
 *    using P
 *
 *    the return result is either an error message or the passed
 *    in string after going through PQescapeString
 *
 *----------------------------------------------------------------------
 */
int
Pg_quote (ClientData cData, Tcl_Interp *interp, int objc,
		  Tcl_Obj *CONST objv[])
{
	char	   *fromString = NULL;
	char	   *toString;
	int         fromStringLen;
	int         stringSize;
	Pg_ConnectionId *connid;
	PGconn	   *conn = NULL;
	char	   *connString;
	int         error = 0;
	static Tcl_Obj *nullStringObj = NULL;

	/* allocate the null string object if we don't have it and increment
	 * its reference count so it'll never be freed.  We can use it over
	 * and over and it'll keep using the same string object
	 */
	if (nullStringObj == NULL) 
	{
		nullStringObj = Tcl_NewStringObj ("NULL", -1);
		Tcl_IncrRefCount (nullStringObj);
	}

	if ((objc < 2) || (objc > 3)) 
	{
		Tcl_WrongNumArgs(interp, 1, objv, "?connection? string");
		return TCL_ERROR;
	}

	if (objc == 2)
	{
	    /*
	     * Get the "from" string.
	     */
	    fromString = Tcl_GetStringFromObj(objv[1], &fromStringLen);
	} else
	{
	    connString = Tcl_GetStringFromObj(objv[1], NULL);
	    conn = PgGetConnectionId(interp, connString, &connid);
	    if (conn == NULL)
		    return TCL_ERROR;

	    /*
	     * Get the "from" string.
	     */
	    fromString = Tcl_GetStringFromObj(objv[2], &fromStringLen);

	    /*
	     * If the from string is empty, see if the null value string is also
	     * empty and if so, return the string NULL rather than something
	     * quoted
	     */
	    if (fromStringLen == 0) 
		{
		    if (connid->nullValueString == NULL 
			  || *connid->nullValueString == '\0') 
			{
			    Tcl_SetObjResult (interp, nullStringObj);
			    return TCL_OK;
		    }
	    } else {
		    /*
		     * The from string wasn't null, see if the connection's null value
		     * string also isn't null and if so, if they match and if so,
		     * return the string NULL
		     */
		    if (connid->nullValueString != NULL)
			{
			    if (strcmp (fromString, connid->nullValueString) == 0)
				{
				    Tcl_SetObjResult (interp, nullStringObj);
				    return TCL_OK;
			    }
		    }
	    }
	}

	/* 
	 * It wasn't the null string or we were called with two args,
	 * allocate the "to" string, the max size is documented in the
	 * postgres docs as 2 * fromStringLen + 1 and we add two more
	 * for the leading and trailing single quotes
	 */
	toString = (char *) ckalloc((2 * fromStringLen) + 3);

	/*
	 * call the library routine to escape the string, use
	 * Tcl_SetResult to set the command result to be that string,
	 * with TCL_DYNAMIC, we tell Tcl to free the memory when it's
	 * done with it 
	 */
	 *toString = '\'';

	 if (objc == 3) 
	 {
		stringSize = PQescapeStringConn (conn, toString+1, fromString, 
										 fromStringLen, &error);
		if (error) 
		{
			/* error returned from PQescapeStringConn, send it on up */
			ckfree (toString);
			Tcl_SetObjResult (interp, Tcl_NewStringObj ( PQerrorMessage (conn),
							  -1));
			return TCL_ERROR;
		}
	} else {
		stringSize = PQescapeString (toString+1, fromString, fromStringLen);
	}

	toString[stringSize+1] = '\'';
	toString[stringSize+2] = '\0';
	Tcl_SetResult(interp, toString, TCL_DYNAMIC);
	return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * Pg_escapeBytea --
 *
 *    returns the escaped version of the passed in binary
 *    string
 *
 * Syntax:
 *    pg_escapeBytea binaryString
 *
 * Results:
 *    the return result is either an error message or the passed
 *    in binary string after going through PQescapeBytea
 *
 * NOTE: PQunescapeBytea is *not* the direct inverse
 *     of PQescapeBytea. The result from PQescapeBytea needs
 *     to go through extra parsing, where as PQunescapeBytea
 *     is at the end of the parsing stage.
 *----------------------------------------------------------------------
 */
int
Pg_escapeBytea(ClientData cData, Tcl_Interp *interp, int objc,
                                 Tcl_Obj *CONST objv[])
{
        unsigned char    	*from;
        unsigned char           *to;
        int                      fromLen;
        size_t                   toLen;
	PGconn	                *conn = NULL;
	char                    *connString;

        if ((objc < 2) || (objc > 3))
        {
                Tcl_WrongNumArgs(interp, 1, objv, "?connection? binaryString");
                return TCL_ERROR;
        }

	if (objc == 2)
	{
	    /*
	     * Get the "from" string.
	     */
	    from = Tcl_GetByteArrayFromObj(objv[1], &fromLen);

	    to = PQescapeBytea(from, fromLen, &toLen);
	} else
	{
	    connString = Tcl_GetStringFromObj(objv[1], NULL);
	    conn = PgGetConnectionId(interp, connString, NULL);
	    if (conn == NULL)
		return TCL_ERROR;

	    /*
	     * Get the "from" string.
	     */
	    from = Tcl_GetByteArrayFromObj(objv[2], &fromLen);

	    to = PQescapeByteaConn(conn, from, fromLen, &toLen);
	}

        if (! to)
        {
            Tcl_SetObjResult(interp, Tcl_NewStringObj("Failed to quote binary string", -1));
            return TCL_ERROR;
        }

        Tcl_SetObjResult(interp, Tcl_NewStringObj((char *)to, -1));

        #ifdef PQfreemem
            PQfreemem(to);
        #else
            PQfreeNotify(to);
        #endif

        return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * Pg_unescapeBytea --
 *
 *    returns the unescaped version of the passed in escaped binary
 *    string
 *
 * Syntax:
 *    pg_unescapeBytea escapedBinaryString
 *
 * Results:
 *    the return result is either an error message or the passed
 *    in string, that has gone through PQunescapeBytea
 *
 * NOTE: PQunescapeBytea is *not* the direct inverse
 *     of PQescapeBytea. The result from PQescapeBytea needs
 *     to go through extra parsing, where as PQunescapeBytea
 *     is at the end of the parsing stage.
 *----------------------------------------------------------------------
 */
int
Pg_unescapeBytea(ClientData cData, Tcl_Interp *interp, int objc,
                                 Tcl_Obj *CONST objv[])
{
    const unsigned char  *from;
    unsigned char        *to;
    int         fromLen;
    size_t      toLen;

    if (objc != 2)
    {
        Tcl_WrongNumArgs(interp, 1, objv, "binaryString");
        return TCL_ERROR;
    }

    from = (const unsigned char *)Tcl_GetStringFromObj(objv[1], &fromLen);
    to   = PQunescapeBytea(from, &toLen);
    if (! to)
    {
        Tcl_SetObjResult(interp, Tcl_NewStringObj("Failed to unquote binary string", -1));
        return TCL_ERROR;
    }

    Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(to, toLen));

    #ifdef PQfreemem
        PQfreemem(to);
    #else
        PQfreeNotify(to);
    #endif

    return TCL_OK;
}


/*
 *----------------------------------------------------------------------
 *
 * Pg_dbinfo --
 *
 *    returns either the connection handles or the result handles
 *
 * Syntax:
 *    pg_dbinfo connections
 *    pg_dbinfo results connHandle 
 *    pg_dbinfo version connHandle 
 *    pg_dbinfo protocol connHandle 
 *    pg_dbinfo param connHandle paramName
 *    pg_dbinfo backendpid connHandle
 *    pg_dbinfo socket connHandle
 *    pg_dbinfo sql_count connHandle
 *
 *    pg_dbinfo dbname connHandle
 *    pg_dbinfo user connHandle
 *    pg_dbinfo pass connHandle
 *    pg_dbinfo host connHandle
 *    pg_dbinfo port connHandle
 *    pg_dbinfo options connHandle
 *    pg_dbinfo status connHandle
 *    pg_dbinfo transaction_status connHandle
 *    pg_dbinfo error_message connHandle
 *    pg_dbinfo needs_password connHandle
 *    pg_dbinfo used_password connHandle
 *    pg_dbinfo used_ssl connHandle
 *
 * Results:
 *    the return result is either an error message or a list of
 *    the connection/result handles.
 *
 *----------------------------------------------------------------------
 */
int
Pg_dbinfo(ClientData cData, Tcl_Interp *interp, int objc,
				 Tcl_Obj *CONST objv[])
{
    Pg_ConnectionId *connid = NULL;
    char	    *connString = NULL;
    char	    buf[32];
    Tcl_Obj         *listObj;
    Tcl_Obj         *tresult;
    Tcl_Obj         **elemPtrs;
    int             i, count, optIndex;
    Tcl_Channel     conn_chan;
    const char      *paramname;

    static CONST84 char *cmdargs = "connections|results|version|protocol|param|backendpid|socket|sql_count|dbname|user|password|host|port|options|status|transaction_status|error_message|needs_password|used_password|used_ssl";

    static CONST84 char *options[] = {
    	"connections", "results", "version", "protocol", 
        "param", "backendpid", "socket", "sql_count", 
	"dbname", "user", "password", "host", "port",
	"options", "status", "transaction_status",
	"error_message", "needs_password", "used_password",
	"used_ssl",
	NULL
    };

    enum options
    {
    	OPT_CONNECTIONS, OPT_RESULTS, OPT_VERSION, OPT_PROTOCOL,
        OPT_PARAM, OPT_BACKENDPID, OPT_SOCKET, OPT_SQL_COUNT,
	OPT_DBNAME, OPT_USER, OPT_PASSWORD, OPT_HOST, OPT_PORT,
	OPT_OPTIONS, OPT_STATUS, OPT_TRANSACTION_STATUS,
	OPT_ERROR_MESSAGE, OPT_NEEDS_PASSWORD, OPT_USED_PASSWORD,
	OPT_USED_SSL
    };
    
    if (objc <= 1)
    {
	Tcl_WrongNumArgs(interp,1,objv,cmdargs);
        return TCL_ERROR;
    }

    if (Tcl_GetIndexFromObj(interp, objv[1], options, "option", TCL_EXACT, &optIndex) != TCL_OK) {
		return TCL_ERROR;
    }

    /* 
     * this is common for most cmdargs, so do it upfront
     */
    if (optIndex != OPT_CONNECTIONS)
    {
        if (objc != 3) {
			Tcl_WrongNumArgs(interp, 2, objv, "connHandle");
			return TCL_ERROR;
		}

	connString = Tcl_GetStringFromObj(objv[2], NULL);
	conn_chan = Tcl_GetChannel(interp, connString, 0);
	if (conn_chan == NULL)
	{
	    tresult = Tcl_NewStringObj(connString, -1);
	    Tcl_AppendStringsToObj(tresult, " is not a valid connection", NULL);
	    Tcl_SetObjResult(interp, tresult);

	    return TCL_ERROR;
	}

	/* Check that it is a PG connection and not something else */
	connid = (Pg_ConnectionId *) Tcl_GetChannelInstanceData(conn_chan);

	if (connid->conn == NULL) {
	    return TCL_ERROR;
	}
    }

    switch ((enum options) optIndex)
    {
        case OPT_CONNECTIONS:
        {

            listObj = Tcl_NewListObj(0, (Tcl_Obj **) NULL);

            /*
             * This is not a very robust method to use.
             * Will have to re-think this
             */
            Tcl_GetChannelNames(interp);

            Tcl_ListObjGetElements(interp, Tcl_GetObjResult(interp), 
                &count, &elemPtrs);

            for (i = 0; i < count; i++) {

                char *name = Tcl_GetStringFromObj(elemPtrs[i], NULL);

                conn_chan = Tcl_GetChannel(interp, name, 0);
                if (conn_chan != NULL && 
                    Tcl_GetChannelType(conn_chan) == &Pg_ConnType)
                {

                    if (Tcl_ListObjAppendElement(interp, listObj, elemPtrs[i]) != TCL_OK)
                    {
                        Tcl_DecrRefCount(listObj);
                        return TCL_ERROR;
                    }
                }


            }
             break;
        }
        case OPT_RESULTS:
        {

        listObj = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
    
        for (i = 0; i <= connid->res_last; i++)
        {
     
            if (connid->results[i] == 0)
            {
                continue;
            }
    
            sprintf(buf, "%s.%d", connString, i);
            if (Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(buf, -1)) != TCL_OK)
            {
                Tcl_DecrRefCount(listObj);
                return TCL_ERROR;
            }
        }
            break;
        }
        case OPT_VERSION:
        {
#ifdef HAVE_PQSERVERVERSION

            Tcl_SetObjResult(interp, Tcl_NewIntObj(
                             PQserverVersion(connid->conn)));
    
            return TCL_OK;

#else /* HAVE_PQSERVERVERSION */
        Tcl_SetObjResult(interp, Tcl_NewStringObj(
          "You need a PG version > 7.4 that supports server version", -1));
	    return TCL_ERROR;
#endif /* HAVE_PQSERVERVERSION */
        }
        case OPT_PROTOCOL:
        {
            Tcl_SetObjResult(interp, Tcl_NewIntObj(
                            PQprotocolVersion(connid->conn)));
            return TCL_OK;
        }
        case OPT_PARAM:
        {
            paramname = Tcl_GetStringFromObj(objv[3], NULL);
            Tcl_SetObjResult(interp, Tcl_NewStringObj(
                             PQparameterStatus(connid->conn, paramname), -1));
            return TCL_OK;
        }
        case OPT_BACKENDPID:
        {
            Tcl_SetObjResult(interp, Tcl_NewIntObj(
                             PQbackendPID(connid->conn)));
            return TCL_OK;
        }
        case OPT_SOCKET:
        {
            Tcl_SetObjResult(interp, Tcl_NewIntObj(
                             PQsocket(connid->conn)));
            return TCL_OK;
        }
        case OPT_SQL_COUNT:
        {
            Tcl_SetObjResult(interp, Tcl_NewIntObj(
                             connid->sql_count));
            return TCL_OK;
        }

	case OPT_DBNAME:
	{
            Tcl_SetObjResult(interp, Tcl_NewStringObj(
                             PQdb(connid->conn), -1));
            return TCL_OK;
	}

	case OPT_USER:
	{
            Tcl_SetObjResult(interp, Tcl_NewStringObj(
                             PQuser(connid->conn), -1));
            return TCL_OK;
	}

	case OPT_PASSWORD:
	{
            Tcl_SetObjResult(interp, Tcl_NewStringObj(
                             PQpass(connid->conn), -1));
            return TCL_OK;
	}

	case OPT_HOST:
	{
            Tcl_SetObjResult(interp, Tcl_NewStringObj(
                             PQhost(connid->conn), -1));
            return TCL_OK;
	}

	case OPT_PORT:
	{
            Tcl_SetObjResult(interp, Tcl_NewStringObj(
                             PQport(connid->conn), -1));
            return TCL_OK;
	}

	case OPT_OPTIONS: {
            Tcl_SetObjResult(interp, Tcl_NewStringObj(
                             PQoptions(connid->conn), -1));
            return TCL_OK;
	}

	case OPT_STATUS: {
	    switch (PQstatus(connid->conn)) {
	        case CONNECTION_OK:
		{
		    Tcl_SetObjResult(interp, 
		        Tcl_NewStringObj("connection_ok", -1));
		    return TCL_OK;
		}

		case CONNECTION_BAD: {
		    Tcl_SetObjResult(interp, 
		        Tcl_NewStringObj("connection_bad", -1));
		    return TCL_OK;
		}

		default: {
		    Tcl_SetObjResult(interp, 
		        Tcl_NewStringObj("unrecognized_status", -1));
		    return TCL_OK;
		}
	    }
	}

	case OPT_TRANSACTION_STATUS: {
	    switch (PQtransactionStatus(connid->conn)) {
	        case PQTRANS_IDLE: {
		    Tcl_SetObjResult(interp, 
		        Tcl_NewStringObj("idle", -1));
		    return TCL_OK;
		}

	        case PQTRANS_ACTIVE: {
		    Tcl_SetObjResult(interp, 
		        Tcl_NewStringObj("command_in_progress", -1));
		    return TCL_OK;
		}

		case PQTRANS_INTRANS: {
		    Tcl_SetObjResult(interp, 
		        Tcl_NewStringObj("idle_in_valid_block", -1));
		    return TCL_OK;
		}

		case PQTRANS_INERROR: {
		    Tcl_SetObjResult(interp, 
		        Tcl_NewStringObj("idle_in_failed_block", -1));
		    return TCL_OK;
		}

		case PQTRANS_UNKNOWN: {
		    Tcl_SetObjResult(interp, 
		        Tcl_NewStringObj("connection_bad", -1));
		    return TCL_OK;
		}

		default: {
		    Tcl_SetObjResult(interp, 
		        Tcl_NewStringObj("unrecognized_status", -1));
		    return TCL_OK;
		}
	    }
	}

	case OPT_ERROR_MESSAGE: {
            Tcl_SetObjResult(interp, Tcl_NewStringObj(
                             PQerrorMessage(connid->conn), -1));
            return TCL_OK;
	}

	case OPT_NEEDS_PASSWORD: {
            Tcl_SetObjResult(interp, Tcl_NewBooleanObj(
                             PQconnectionNeedsPassword(connid->conn)));
            return TCL_OK;
	}

	case OPT_USED_PASSWORD: {
            Tcl_SetObjResult(interp, Tcl_NewBooleanObj(
                             PQconnectionUsedPassword(connid->conn)));
            return TCL_OK;
	}

	case OPT_USED_SSL: {
            Tcl_SetObjResult(interp, Tcl_NewBooleanObj(
                             (PQgetssl(connid->conn) != NULL)));
            return TCL_OK;
	}

        default:
        {
	    Tcl_WrongNumArgs(interp,1,objv,cmdargs);
            return TCL_ERROR;
        }

    }
    Tcl_SetObjResult(interp, listObj);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * Pg_sql --
 *
 *    returns result handle
 *
 * Syntax:
 *    pg_sql connhandle sqlStmt \
 *        ?-params {list}? \
 *        ?-binparams {list}? \
 *        ?-binresults? \
 *        ?-callback script? \
 *        ?-async yes|no? \
 *        ?-prepared yes|no?
 *
 * Results:
 *    the return result is either an error message or a list of
 *    the connection/result handles.
 *
 *----------------------------------------------------------------------
 */
int
Pg_sql(ClientData cData, Tcl_Interp *interp, int objc,
				 Tcl_Obj *CONST objv[])
{

    PGconn          *conn;
    PGresult        *result = NULL;
    CONST84 char    *connString;
    const char      *execString;
    const char     **paramValues = NULL;
    int             *binValues = NULL;
    const int       *paramLengths = NULL;
    Pg_ConnectionId *connid;
    Tcl_Obj         **elemPtrs;
    Tcl_Obj         **elembinPtrs;
    int             i=3;
    int             count=0, countbin=0, optIndex;
    int             params=0,binparams=0,binresults=0,callback=0,async=0,prepared=0;
    unsigned char   flags = 0;
    int             status = 0;

    static CONST84 char *cmdargs = "";

    static CONST84 char *options[] = {
    	"-params", "-binparams", "-binresults", "-callback", 
        "-async", "-prepared", NULL
    };

    enum options
    {
    	OPT_PARAMS, OPT_BINPARAMS, OPT_BINRESULTS, OPT_CALLBACK,
        OPT_ASYNC, OPT_PREPARED
    };
    
    if (objc < 3)
    {
	Tcl_WrongNumArgs(interp,1,objv,cmdargs);
        return TCL_ERROR;
    }

    /*
     *  We just loop through now to set some
     *  flags, since some of the options are
     *  dependent on others
     */
    while (i < objc)
    {

        if (Tcl_GetIndexFromObj(interp, objv[i], options,
		   "option", TCL_EXACT, &optIndex) != TCL_OK)
		    return TCL_ERROR;

        switch ((enum options) optIndex)
        {
            case OPT_PARAMS:
            {

#ifndef HAVE_PQEXECPARAMS
                Tcl_SetObjResult(interp, 
                    Tcl_NewStringObj(
                        "function unavailable with this version of the postgres libpq library\n", -1));

	        return TCL_ERROR;
#endif

                flags = flags | 0x01;
                params = i+1;
                i=i+2;
                Tcl_ListObjGetElements(interp, objv[params], &count, &elemPtrs);
                if (count == 0) {
                    params = 0;
                }

                break;
            }
            case OPT_BINPARAMS:
            {
                flags = flags | 0x02;
                binparams = i+1;
                i=i+2;
                break;
            }
            case OPT_BINRESULTS:
            {
                flags = flags | 0x04;
                Tcl_GetBooleanFromObj(interp, objv[i+1], &binresults);
                /*
                binresults = i+1;
                */
                i=i+2;
                break;
            }
            case OPT_CALLBACK:
            {
                /* assume async if -callback too */
                flags = flags | 0x10;
                flags = flags | 0x08;
                callback = i+1;
                async = 1;
                i=i+2;
                break;
            }
            case OPT_ASYNC:
            {
                flags = flags | 0x10;
                Tcl_GetBooleanFromObj(interp, objv[i+1], &async);
                /*
                async = i+1;
                */
                i=i+2;
                break;
            }
            case OPT_PREPARED:
            {
#ifndef HAVE_PQEXECPREPARED
                Tcl_SetObjResult(interp, 
                    Tcl_NewStringObj(
                        "function unavailable with this version of the postgres libpq library\n", -1));

	        return TCL_ERROR;
#endif
                flags = flags | 0x20;
                /*
                prepared = i+1;
                */
                Tcl_GetBooleanFromObj(interp, objv[i+1], &prepared);
                i=i+2;
            }
        } /* end switch */


        /*
         * Check error case where -binparams or
         * -binresults are given but -params is not
         if ((flags == 0x06) || (flags == 0x04) || (flags == 0x02)) {
            Tcl_SetResult(interp, "Need to specify -params", TCL_STATIC);
            return TCL_ERROR;
         }
*/

    } /* end while */

    /*
     * Check error case where -binparams or
     * -binresults are given but -params is not
     */
     if (!params && (binparams != 0 || binresults != 0)) {
        Tcl_SetResult(interp, "Need to specify -params option", TCL_STATIC);
        return TCL_ERROR;
     }

    /*
     *  Handle param options
     */
     if (params) {
         Tcl_ListObjGetElements(interp, objv[binparams], &countbin, &elembinPtrs);

         if (countbin != 0 && countbin != count) {
            Tcl_SetResult(interp, "-params and -binparams need the same number of elements", TCL_STATIC); 
            return TCL_ERROR;
         }

	 int param;

	 paramValues = (const char **)ckalloc (count * sizeof (char *));
	 binValues = (int *)ckalloc (countbin * sizeof (char *));

	 for (param = 0; param < count; param++) {
	     paramValues[param] = Tcl_GetStringFromObj (elemPtrs[param], NULL);
	     if (strcmp(paramValues[param], "NULL") == 0)
             {
                 paramValues[param] = '\0';
             }
	 }

	 for (param = 0; param < countbin; param++) {
	     Tcl_GetBooleanFromObj (interp, elembinPtrs[param], &binValues[param]);
	 }
     }

    connString = Tcl_GetStringFromObj(objv[1], NULL);
    conn = PgGetConnectionId(interp, connString, &connid);
    if (conn == NULL) 
            return TCL_ERROR;

    if (connid->res_copyStatus != RES_COPY_NONE)
    {
        Tcl_SetResult(interp, "Attempt to query while COPY in progress", TCL_STATIC); 
        return TCL_ERROR;
    }

    execString = Tcl_GetStringFromObj(objv[2], NULL);

    /*
     * Handle the callback first, before executing statments
     */
    if (callback) {
        if (connid->callbackPtr || connid->callbackInterp)
        {
            Tcl_SetResult(interp, "Attempt to wait for result while already waiting", TCL_STATIC);
            return TCL_ERROR;
       }

       /* Start the notify event source if it isn't already running */
       PgStartNotifyEventSource(connid);

       connid->callbackPtr= objv[callback];
       connid->callbackInterp= interp;

       Tcl_IncrRefCount(objv[callback]);
       Tcl_Preserve((ClientData) interp);

       /* 
        *  invoke function based on type 
        *  of query 
        */
        if (prepared) {
	    status = PQsendQueryPrepared(conn, execString, count, paramValues, paramLengths, binValues, binresults);
        } else if (params) {
            status = PQsendQueryParams(conn, execString, count, NULL, paramValues, paramLengths, binValues, binresults);

        } else {
    
	    status = PQsendQuery(conn, execString);
/*
            ckfree ((void *)paramValues);
*/
        }
    } else {

        if (prepared) {
	    result = PQexecPrepared(conn, execString, count, paramValues, paramLengths, binValues, binresults);
        } else if (params) {
            result = PQexecParams(conn, execString, count, NULL, paramValues, paramLengths, binValues, binresults);
        } else {
            result = PQexec(conn, execString);
            ckfree ((void *)paramValues);
        }
    } /* end if callback */

    PgNotifyTransferEvents(connid);

    if (result || status)
    {
	if (result)
	    {
		int              rId = PgSetResultId(interp, connString, result);
		ExecStatusType rStat = PQresultStatus(result);

		if (rStat == PGRES_COPY_IN || rStat == PGRES_COPY_OUT)
		    {
			connid->res_copyStatus = RES_COPY_INPROGRESS;
			connid->res_copy = rId;
		    }
	    }
	return TCL_OK;
    }
    else
    {
	/* error occurred during the query */
	Tcl_SetObjResult(interp, Tcl_NewStringObj(PQerrorMessage(conn), -1));
	return TCL_ERROR;
    }

    
    return TCL_OK;
}

/*
error severity
error sqlstate
error message
error message primary
error message detail
error message hint
error position
error context
error source file
error source line
error source function
*/