File: dbdimp.ec

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

/*TABSTOP=4*/

#ifndef lint
static const char rcs[] = "@(#)$Id: dbdimp.ec,v 100.36.1.1 2003/03/01 01:29:36 jleffler Exp $";
#endif

#include <stdio.h>
#include <string.h>

#define MAIN_PROGRAM	/* Embed version information for JLSS headers */
#include "Informix.h"
#include "decsci.h"
#include "esqlutil.h"

/* Beware omitting the semi-colon! */
$include "esqlinfo.h";

#define L_CURLY	'{'
#define R_CURLY	'}'

/**
 ** JL 2000-01-20: ESQL/C versions 9.2x and later use 32 characters for
 ** usernames.  Earlier versions use 8 characters.  This is safe for the
 ** immediately foreseeable future, but it would be better if B69092 were
 ** fixed so this was not necessary and the #define from esqlc.h could be
 ** used instead of this $define -- DRY (Don't Repeat Yourself)!
 */
$define SQL_USERLEN1     33;

DBISTATE_DECLARE;

static const Sqlca zero_sqlca = { 0 };
static const Link zero_link = { 0, 0, 0 };

/*
** Debugging macros.  NB: functions dbd_ix_debug() and dbd_ix_debug_l()
** are used in other source files and must therefore be actual functions.
** We may fix this one day.
*/
#define dbd_ix_debug(n, fmt, arg) \
	(fflush(stdout), (DBIS->debug >= (n)) ? (void)warn(fmt, arg) : (void)0)
#define dbd_ix_debug_l(n, fmt, arg) \
	(fflush(stdout), (DBIS->debug >= (n)) ? (void)warn(fmt, arg) : (void)0)
/* dbd_ix_debug_2() is used with a variety of argument types... */
#define dbd_ix_debug_2(n, fmt, arg1, arg2) \
	(fflush(stdout), (DBIS->debug >= (n)) ? (void)warn(fmt, arg1, arg2) : (void)0)

/*
** SQLSTATE is only supported in version 6.00 and later.
** The DBI 0.81 spec says that the value S1000 should be returned
** when the implementation does not support SQLSTATE.
*/
#if ESQLC_VERSION < 600
static const char SQLSTATE[] = "S1000";
#endif /* ESQLC_VERSION */

/* One day, these will go!  Maybe... */
static void del_statement(imp_sth_t *imp_sth);
static int  dbd_ix_begin(imp_dbh_t *dbh);

/*
** Discussion of imp_sth->st_state (JL 2002-02-12).
** The State enumeration can take the values: Unused, Prepared,
** Allocated, Described, Declared, Opened, NoMoreData.
** -- Unused state means that there is no prepared statement, nor (by
**    definition) a declared cursor, nor any allocated descriptors.
** -- Prepared state means that there is a prepared statement but no
**    declared cursor nor any allocated descriptors. -JL-VERIFY
** -- Allocated state means that there is a prepared statement and a
**    descriptor for the input parameters (nm_idesc), but no declared
**    cursor nor any output descriptor (nm_odesc). -JL-VERIFY
** -- Described state means that there is a prepared statement and
**    descriptors for both input and output parameters. -JL-VERIFY
** -- Declared state means that there is both a prepared statement and a
**    declared cursor (which is currently closed) and descriptors for
**    both input and output parameters.
** -- Opened state means that the cursor is also open.
** -- NoMoreData state means that the cursor is closed, but that any
**    further fetches on the statement should always indicate NoMoreData
**    (SQLNOTFOUND).  This is a consequence of the DBI requirement that
**    the $sth->finish function should only be necessary for an early
**    exit from a fetch loop.  If you use $sth->finish on a NoMoreData
**    cursor, the state is changed to Declared.  If you use $sth->finish
**    on an open cursor, the cursor is closed and the state is changed
**    to Declared.  If you attempt $sth->finish on a cursor in any other
**    state, you will get an error.
*/

/* ================================================================= */
/* ==================== Driver Level Operations ==================== */
/* ================================================================= */

/* Official name for DBD::Informix module */
const char     *
dbd_ix_module(void)
{
	return(DBD_IX_MODULE);
}

/* Print message with string argument if debug level set high enough */
void
(dbd_ix_debug)(int n, char *fmt, const char *arg)
{
	fflush(stdout);
	if (DBIS->debug >= n)
		warn(fmt, arg);
}

/* Print message with long argument if debug level set high enough */
void
(dbd_ix_debug_l)(int n, char *fmt, long arg)
{
	fflush(stdout);
	if (DBIS->debug >= n)
		warn(fmt, arg);
}

#ifdef DBD_IX_DEBUG_ENVIRONMENT
static void
dbd_ix_printenv(const char *s1, const char *s2)
{
	extern char **environ;
	char **envp = environ;
	char *env;

	fprintf(stderr, "ENV: %s %s - environ = 0x%08X\n", s1, s2, environ);
	while ((env = *envp++) != 0)
		fprintf(stderr, "0x%08X: %s\n", env, env);
}
#endif /* DBD_IX_DEBUG_ENVIRONMENT */

/* Print message on entry to function */
void
dbd_ix_enter(const char *function)
{
	dbd_ix_debug_2(1, "\t-->> %s::%s()\n", dbd_ix_module(), function);
}

/* Print message on exit from function */
void
dbd_ix_exit(const char *function)
{
	dbd_ix_debug_2(1, "\t<<-- %s::%s()\n", dbd_ix_module(), function);
}

/* Do DBI-mandated standard initialization */
void
dbd_ix_init(dbistate_t *dbistate)
{
	DBISTATE_INIT;
}

/* Formally initialize the DBD::Informix driver structure */
int
dbd_ix_dr_driver(SV *drh)
{
	D_imp_drh(drh);

	imp_drh->n_connections = 0;			/* No active connections */
	imp_drh->current_connection = 0;	/* No name */
	imp_drh->multipleconnections = (ESQLC_VERSION >= 600) ? True : False;
	dbd_ix_link_newhead(&imp_drh->head);	/* Linked list of connections */

	return 1;
}

/* Relay function for use by dbd_ix_link_delchain() */
/* Destroys a statement when a database connection is destroyed */
static void
dbd_st_destroyer(void *data)
{
	static const char function[] = "::dbd_st_destroyer";
	dbd_ix_enter(function);
	del_statement((imp_sth_t *)data);
	dbd_ix_exit(function);
}

/* Delete all the statements (and other data) associated with a connection */
static void
del_connection(imp_dbh_t *imp_dbh)
{
	static const char function[] = "::del_connection";
	dbd_ix_enter(function);
	dbd_ix_link_delchain(&imp_dbh->head, dbd_st_destroyer);
	dbd_ix_exit(function);
}

/* Relay (interface) function for use by dbd_ix_link_delchain() */
/* Destroys a database connection when a driver is destroyed */
static void
dbd_db_destroyer(void *data)
{
	static const char function[] = "::dbd_db_destroyer";
	dbd_ix_enter(function);
	del_connection((imp_dbh_t *)data);
	dbd_ix_exit(function);
}

/* Disconnect all connections (cleanly) */
int
dbd_ix_dr_discon_all(SV *drh, imp_drh_t *imp_drh)
{
	static const char function[] = "dbd_ix_dr_discon_all";
	dTHR;

	dbd_ix_enter(function);
	dbd_ix_link_delchain(&imp_drh->head, dbd_db_destroyer);
	dbd_ix_exit(function);
	return(1);
}

/* Format a Informix error message (both SQL and ISAM parts) */
static void
dbd_ix_fmterror(ErrNum rc, char *msgbuf, size_t msgsiz)
{
	char errbuf[256];
	char fmtbuf[256];
	char sql_buf[256];
	char isambuf[256];
	size_t sql_len;
	size_t isamlen;

	/* Format SQL (primary) error */
	if (rgetmsg(rc, errbuf, sizeof(errbuf)) != 0)
		strcpy(errbuf, "<<Failed to locate SQL error message>>");
	sprintf(fmtbuf, errbuf, sqlca.sqlerrm);
	sprintf(sql_buf, "SQL: %ld: %s", rc, fmtbuf);

	/* Format ISAM (secondary) error */
	if (sqlca.sqlerrd[1] != 0)
	{
		if (rgetmsg(sqlca.sqlerrd[1], errbuf, sizeof(errbuf)) != 0)
			strcpy(errbuf, "<<Failed to locate ISAM error message>>");
		sprintf(fmtbuf, errbuf, sqlca.sqlerrm);
		sprintf(isambuf, "ISAM: %ld: %s", sqlca.sqlerrd[1], fmtbuf);
	}
	else
		isambuf[0] = '\0';

	/* Concatenate SQL and ISAM messages */
	/* Note that the messages have trailing newlines */
	sql_len = strlen(sql_buf);
	isamlen = strlen(isambuf);
	if (sql_len + isamlen > msgsiz)
	{
		if (sql_len >= msgsiz)
		{
			isambuf[0] = '\0';
			sql_len = msgsiz - 1;
			sql_buf[sql_len] = '\0';
		}
		else
			isambuf[msgsiz-1-sql_len] = '\0';
	}

	strcpy(msgbuf, sql_buf);
	strcpy(msgbuf + sql_len, isambuf);
	/* Chop the trailing newline so Perl appends line number info. */
	/* Problem reported by Andrew Pimlott <pimlott@abel.math.harvard.edu> */
	msgbuf[sql_len+isamlen-1] = '\0';
}

/* Format a Informix error message - driver handle */
static void
dbd_ix_dr_seterror(imp_drh_t *imp_drh, ErrNum rc)
{
	char msgbuf[512];

	if (rc < 0)
	{
		dbd_ix_fmterror(rc, msgbuf, sizeof(msgbuf));
		/* Record error number, error message, and error state */
		sv_setiv(DBIc_ERR(imp_drh), (IV)rc);
		sv_setpv(DBIc_ERRSTR(imp_drh), msgbuf);
		sv_setpv(DBIc_STATE(imp_drh), SQLSTATE);
		dbd_ix_debug(1, "***ERROR***\n%s\n", msgbuf);
	}
}

/* Format a Informix error message - database handle */
static void
dbd_ix_db_seterror(imp_dbh_t *imp_dbh, ErrNum rc)
{
	char msgbuf[512];

	if (rc < 0)
	{
		dbd_ix_fmterror(rc, msgbuf, sizeof(msgbuf));
		/* Record error number, error message, and error state */
		sv_setiv(DBIc_ERR(imp_dbh), (IV)rc);
		sv_setpv(DBIc_ERRSTR(imp_dbh), msgbuf);
		sv_setpv(DBIc_STATE(imp_dbh), SQLSTATE);
		dbd_ix_debug(1, "***ERROR***\n%s\n", msgbuf);
	}
}

/* Save the current sqlca record */
static void
dbd_ix_savesqlca(imp_dbh_t *imp_dbh)
{
	imp_dbh->ix_sqlca = sqlca;
}

/* Record (and report) and SQL error, saving SQLCA information */
static void
dbd_ix_sqlcode(imp_dbh_t *imp_dbh)
{
	/* If there is an error, record it */
	if (sqlca.sqlcode < 0)
	{
		dbd_ix_savesqlca(imp_dbh);
		dbd_ix_db_seterror(imp_dbh, sqlca.sqlcode);
	}
}

/* ================================================================= */
/* =================== Database Level Operations =================== */
/* ================================================================= */

/* Initialize a connection structure, allocating names */
static void
new_connection(imp_dbh_t *imp_dbh)
{
	static long     connection_num = 0;
	sprintf(imp_dbh->nm_connection, "x_%09ld", connection_num);
	imp_dbh->is_onlinedb  = False;
	imp_dbh->is_loggeddb  = False;
	imp_dbh->is_modeansi  = False;
	imp_dbh->is_txactive  = False;
	imp_dbh->is_connected = False;
	imp_dbh->no_replication = False; /* Bryan Castillo: work is replicated by default */
	imp_dbh->has_procs = False;
	imp_dbh->has_blobs = False;
	imp_dbh->srvr_vrsn = 0;
	imp_dbh->database = (SV *)0;
	imp_dbh->blob_bind = BLOB_DEFAULT;
	imp_dbh->ix_sqlca = zero_sqlca;
	imp_dbh->chain = zero_link;
	imp_dbh->head = zero_link;
	connection_num++;
}

/* Get the server version number 930 => 9.30 */
static int dbd_ix_serverversion(void)
{
	EXEC SQL BEGIN DECLARE SECTION;
	string verstr[SQL_USERLEN1];
	EXEC SQL END DECLARE SECTION;
	int vernum = 0;
	Sqlca local = sqlca;

	/* Note DBINFO('version','major') and DBINFO('version','minor') could be used */
	EXEC SQL DECLARE c_serverversion CURSOR FOR
		SELECT Owner FROM "informix".Systables WHERE TabName = ' VERSION';
	if (sqlca.sqlcode == 0)
	{
		EXEC SQL OPEN c_serverversion;
		if (sqlca.sqlcode == 0)
		{
			EXEC SQL FETCH c_serverversion INTO $verstr;
			if (sqlca.sqlcode == 0)
			{
				/* Convert 7.30UC1 to 730, allowing for version 10.30, etc */
				char *dot = strchr(verstr, '.');
				if (dot != 0)
					memmove(dot, dot+1, strlen(verstr) - (dot - verstr) + 1);
				vernum = strtol(verstr, (char **)0, 10);
			}
			EXEC SQL CLOSE c_serverversion;
		}
		EXEC SQL FREE c_serverversion;
		/* In case we are in a MODE ANSI database */
		EXEC SQL ROLLBACK WORK;
	}
	sqlca = local;
	return vernum;
}

static void
dbd_ix_setdbtype(imp_dbh_t *imp_dbh)
{
	imp_dbh->is_onlinedb = DBD_IX_BOOLEAN(sqlca.sqlwarn.sqlwarn3 == 'W');
	imp_dbh->is_modeansi = DBD_IX_BOOLEAN(sqlca.sqlwarn.sqlwarn2 == 'W');
	imp_dbh->is_loggeddb = DBD_IX_BOOLEAN(sqlca.sqlwarn.sqlwarn1 == 'W');
	/* SE 5.00 and later has stored procedures */
	/* In general, OnLine 5.00 and later has stored procedures */
	imp_dbh->has_procs = True;
	/* SE does not have blobs. */
	/* In general, OnLine 4.00 and later has blobs */
	imp_dbh->has_blobs = imp_dbh->is_onlinedb;

	imp_dbh->srvr_vrsn = dbd_ix_serverversion();
	if (imp_dbh->srvr_vrsn >= 800 && imp_dbh->srvr_vrsn < 830)
	{
		/* XPS 8.0x, 8.1x and 8.2x do not support stored procedures or blobs */
		imp_dbh->has_procs = False;
		imp_dbh->has_blobs = False;
	}
}

/* Preset AutoCommit value */
static void
dbd_ix_db_check_for_autocommit(imp_dbh_t *imp_dbh, SV *dbattr)
{
	static const char function[] = "dbd_ix_db_check_for_autocommit";
	static const char ac[] = "AutoCommit";
	U32 ac_len = sizeof(ac) - 1;
	I32 is_store = 0;

	dbd_ix_enter(function);
	if (SvROK(dbattr) && SvTYPE(SvRV(dbattr)) == SVt_PVHV)
	{
		/* const_cast<char *>(ac) */
		SV **svpp;
		svpp = hv_fetch((HV *)SvRV(dbattr), (char *)ac, ac_len, is_store);
		if (svpp != NULL)
		{
			dbd_ix_debug_l(1, "AutoCommit set to %ld\n", SvTRUE(*svpp));
			DBIc_set(imp_dbh, DBIcf_AutoCommit, SvTRUE(*svpp));
		}
	}
	else
	{
		dbd_ix_debug_2(1, "SvROK = %ld, SvTYPE = %ld\n", SvROK(dbattr),
			SvTYPE(SvRV(dbattr)));
	}
	dbd_ix_exit(function);
}

int
dbd_ix_db_connect(SV *dbh, imp_dbh_t *imp_dbh, char *name, char *user, char *pass, SV *attr)
{
	static const char function[] = "dbd_ix_db_connect";
	dTHR;
	D_imp_drh_from_dbh;
	Boolean conn_ok;

	dbd_ix_enter(function);
	new_connection(imp_dbh);
	if (name != 0 && *name == '\0')
		name = 0;
	if (name != 0 && strcmp(name, DEFAULT_DATABASE) == 0)
		name = 0;

#ifdef DBD_IX_DEBUG_ENVIRONMENT
	dbd_ix_printenv("pre-connect", function);
#endif /* DBD_IX_DEBUG_ENVIRONMENT */

#if ESQLC_VERSION >= 600
	if (user != 0 && *user == '\0')
		user = 0;
	if (pass != 0 && *pass == '\0')
		pass = 0;
	/* 6.00 and later versions of Informix-ESQL/C support CONNECT */
	conn_ok = dbd_ix_connect(imp_dbh->nm_connection, name, user, pass);
#else
	/* Pre-6.00 versions of Informix-ESQL/C do not support CONNECT */
	/* Use DATABASE statement */
	conn_ok = dbd_ix_opendatabase(name);
#endif	/* ESQLC_VERSION >= 600 */

#ifdef DBD_IX_DEBUG_ENVIRONMENT
	dbd_ix_printenv("post-connect", function);
#endif /* DBD_IX_DEBUG_ENVIRONMENT */

	if (sqlca.sqlcode < 0)
	{
		/* Failure of some sort */
		/*
		** JL 2002-12-13: error must be reported to imp_drh, not imp_dbh
		** (because imp_dbh is destroyed when the connect fails).
		*/
		dbd_ix_dr_seterror(imp_drh, sqlca.sqlcode);
		dbd_ix_debug(1, "Exit %s (**ERROR-1**)\n", function);
		dbd_ix_exit(function);
		return 0;
	}

	/* Examine sqlca to see what sort of database we are hooked up to */
	dbd_ix_savesqlca(imp_dbh);
	if (name != 0)
		imp_dbh->database = newSVpv(name, 0);
	dbd_ix_setdbtype(imp_dbh);
	imp_dbh->is_connected = conn_ok;

	/* Record extra active connection and name of current connection */
	imp_drh->n_connections++;
	imp_drh->current_connection = imp_dbh->nm_connection;

	dbd_ix_link_add(&imp_drh->head, &imp_dbh->chain);
	imp_dbh->chain.data = (void *)imp_dbh;
	dbd_ix_link_newhead(&imp_dbh->head);

	/**
	** Unlogged databases are in AutoCommit mode at all times and cannot be
	** switched out of AutoCommit mode.  Ideally, an attempt to connect to
	** one with AutoCommit Off would cause a failure with error -256
	** 'Transaction not available'.  However, since the default attribute
	** is only set after the connection itself is complete, it is not
	** possible.  You can only give the warning.  To comply with the DBI
	** 0.85 standard, all databases, including MODE ANSI databases, run
	** with AutoCommit On by default.  However, this can be overridden by
	** the user as required.
	*/
	dbd_ix_db_check_for_autocommit(imp_dbh, attr);
	if (name != 0 && imp_dbh->is_loggeddb == False && DBI_AutoCommit(imp_dbh) == False)
	{
		/* Simulate connection failure */
		/* JL 2002-12-13: error must be reported to imp_drh (see above) */
		dbd_ix_db_disconnect(dbh, imp_dbh);
		sqlca.sqlcode = -256;
		dbd_ix_dr_seterror(imp_drh, sqlca.sqlcode);
		dbd_ix_debug(1, "Exit %s (**ERROR-2**)\n", function);
		dbd_ix_exit(function);
		return 0;
	}

	DBIc_IMPSET_on(imp_dbh);	/* imp_dbh set up now                   */
	DBIc_ACTIVE_on(imp_dbh);	/* call disconnect before freeing       */

	/* Start a transaction if the database is Logged */
	/* but not MODE ANSI and if AutoCommit is Off */
	if (imp_dbh->is_loggeddb == True && imp_dbh->is_modeansi == False)
	{
		if (DBI_AutoCommit(imp_dbh) == False)
		{
			if (dbd_ix_begin(imp_dbh) == 0)
			{
				dbd_ix_db_disconnect(dbh, imp_dbh);
				dbd_ix_debug(1, "Exit %s (**ERROR-3**)\n", function);
				dbd_ix_exit(function);
				return 0;
			}
		}
	}

	dbd_ix_exit(function);
	return 1;
}

/*
** Until IDS 9.20, a database name could consist of up to 18
** characters, plus the name of the server (for which no explicit
** limit was defined), plus the at sign and the NUL at the end.
** With the release of IDS 9.20, the server and database names can
** be as long as 128 characters each, hence the limits below.
*/
#undef MAXDBS
#undef MAXDBSSIZE
#undef FASIZE
#define MAXDBS 100		/* Up to 100 databases */
#define MAXDBSSIZE	(128+128+2)
#define FASIZE (MAXDBS * MAXDBSSIZE)

/* Return list of databases visible (because of $INFORMIXSERVER and $DBPATH) */
/* NB: It may be possible to access other databases by adding explicit server names */
AV *dbd_ix_dr_data_sources(SV *drh, imp_drh_t *imp_drh, SV *attr)
{
	static const char function[] = "dbd_ix_dr_data_sources";
	int sqlcode;
	int ndbs;
	int i;
	char *dbsname[MAXDBS + 1];
	char dbsarea[FASIZE];
	AV *av = Nullav;		/* Need to return a reference to an array of (mortal) strings */

	dbd_ix_enter(function);
	sqlcode = sqgetdbs(&ndbs, dbsname, MAXDBS, dbsarea, FASIZE);
	if (sqlcode != 0)
	{
		dbd_ix_dr_seterror(imp_drh, sqlcode);
	}
	else
	{
		av = newAV();
		av_extend(av, (I32)ndbs);
		sv_2mortal((SV *)av);
		for (i = 0; i < ndbs; ++i)
		{
			av_store(av, i, newSVpvf("dbi:Informix:%s", dbsname[i]));
		}
	}
	dbd_ix_exit(function);
	return(av);
}

#undef MAXDBS
#undef MAXDBSSIZE
#undef FASIZE

/* Ensure that the correct connection is current */
static int
dbd_db_setconnection(imp_dbh_t *imp_dbh)
{
	int rc = 1;
	D_imp_drh_from_dbh;

	/* If this connection isn't connected, return with failure */
	/* Primarily a concern when destroying connections */
	if (imp_dbh->is_connected == False) {
		/* -349: Database not selected yet. */
		sqlca.sqlcode = -349;
		sqlca.sqlerrd[1] = 0;
		return(0);
	}

	if (imp_drh->current_connection != imp_dbh->nm_connection)
	{
		dbd_ix_setconnection(imp_dbh->nm_connection);
		imp_drh->current_connection = imp_dbh->nm_connection;
		if (sqlca.sqlcode < 0)
			rc = 0;
	}
	return(rc);
}

/* Internal implementation of BEGIN WORK */
/* Assumes correct connection is already set */
static int
dbd_ix_begin(imp_dbh_t *dbh)
{
	int rc = 1;

	/* Bryan Castillo: allow work to be done w/o replication */
$ifdef BEGIN_WORK_WITHOUT_REPLICATION;
	if (dbh->no_replication)
		EXEC SQL BEGIN WORK WITHOUT REPLICATION;
	else
$endif; -- BEGIN_WORK_WITHOUT_REPLICATION
		EXEC SQL BEGIN WORK;

	dbd_ix_sqlcode(dbh);
	if (sqlca.sqlcode < 0)
		rc = 0;
	else
	{
		dbd_ix_debug_2(3, "%s: BEGIN WORK%s\n", dbd_ix_module(),
			(dbh->no_replication ? " WITHOUT REPLICATION" : ""));
		dbh->is_txactive = True;
	}
	return rc;
}

/* Internal implementation of COMMIT WORK */
/* Assumes correct connection is already set */
static int
dbd_ix_commit(imp_dbh_t *dbh)
{
	int rc = 1;

	EXEC SQL COMMIT WORK;
	dbd_ix_sqlcode(dbh);
	if (sqlca.sqlcode < 0)
		rc = 0;
	else
	{
		dbd_ix_debug(3, "%s: COMMIT WORK\n", dbd_ix_module());
		dbh->is_txactive = False;
	}
	return rc;
}

/* Internal implementation of ROLLBACK WORK */
/* Assumes correct connection is already set */
static int
dbd_ix_rollback(imp_dbh_t *dbh)
{
	int rc = 1;

	EXEC SQL ROLLBACK WORK;
	dbd_ix_sqlcode(dbh);
	if (sqlca.sqlcode < 0)
		rc = 0;
	else
	{
		dbd_ix_debug(3, "%s: ROLLBACK WORK\n", dbd_ix_module());
		dbh->is_txactive = False;
	}
	return rc;
}

/* External interface for BEGIN WORK */
int
dbd_ix_db_begin(imp_dbh_t *imp_dbh)
{
	int             rc = 1;

	if (imp_dbh->is_loggeddb != 0)
	{
		if (dbd_db_setconnection(imp_dbh) == 0)
		{
			dbd_ix_savesqlca(imp_dbh);
			return(0);
		}
		rc = dbd_ix_begin(imp_dbh);
	}
	return rc;
}

/* External interface for COMMIT WORK */
int
dbd_ix_db_commit(SV *dbh, imp_dbh_t *imp_dbh)
{
	static const char function[] = "dbd_ix_db_commit";
	int             rc = 1;

	if (imp_dbh->is_loggeddb != 0)
	{
		if (dbd_db_setconnection(imp_dbh) == 0)
		{
			dbd_ix_savesqlca(imp_dbh);
			return(0);
		}
		if ((rc = dbd_ix_commit(imp_dbh)) != 0)
		{
			if (imp_dbh->is_modeansi == False &&
				DBI_AutoCommit(imp_dbh) == False)
			{
				dbd_ix_debug(1, "%s - AUTOCOMMIT Off => BEGIN WORK\n", function);
				rc = dbd_ix_begin(imp_dbh);
			}
		}
	}
	return rc;
}

/* External interface for ROLLBACK WORK */
int
dbd_ix_db_rollback(SV *dbh, imp_dbh_t *imp_dbh)
{
	static const char function[] = "dbd_ix_db_rollback";
	int             rc = 1;

	if (imp_dbh->is_loggeddb != 0)
	{
		if (dbd_db_setconnection(imp_dbh) == 0)
		{
			dbd_ix_savesqlca(imp_dbh);
			return(0);
		}
		if ((rc = dbd_ix_rollback(imp_dbh)) != 0)
		{
			if (imp_dbh->is_modeansi == False &&
				DBI_AutoCommit(imp_dbh) == False)
			{
				dbd_ix_debug(1, "%s - AUTOCOMMIT Off => BEGIN WORK\n", function);
				rc = dbd_ix_begin(imp_dbh);
			}
		}
	}
	return rc;
}

/* Do nothing -- for use by cleanup code */
static void
noop(void *data)
{
}

/* Close a connection, destroying any dependent statements */
int
dbd_ix_db_disconnect(SV *dbh, imp_dbh_t *imp_dbh)
{
	static const char function[] = "dbd_ix_db_disconnect";
	dTHR;
	D_imp_drh_from_dbh;
	int junk;

	dbd_ix_enter(function);

	if (dbd_db_setconnection(imp_dbh) == 0)
	{
		dbd_ix_savesqlca(imp_dbh);
		dbd_ix_debug(1, "%s -- set connection failed", function);
		dbd_ix_exit(function);
		return(0);
	}

	dbd_ix_debug(1, "%s -- delete statements\n", function);
	dbd_ix_link_delchain(&imp_dbh->head, dbd_st_destroyer);
	dbd_ix_debug(1, "%s -- statements deleted\n", function);

	/* Rollback transaction before disconnecting */
	if (imp_dbh->is_loggeddb == True && imp_dbh->is_txactive == True)
		junk = dbd_ix_rollback(imp_dbh);

#if ESQLC_VERSION >= 600
	dbd_ix_disconnect(imp_dbh->nm_connection);
#else
	if (imp_dbh->is_connected == True)
	{
		char *dbname = (imp_dbh->database) ? SvPV(imp_dbh->database, na) : "";
		dbd_ix_closedatabase(dbname);
	}
#endif	/* ESQLC_VERSION >= 600 */
	SvREFCNT_dec(imp_dbh->database);

	dbd_ix_sqlcode(imp_dbh);
	imp_dbh->is_connected = False;

	/* We assume that disconnect will always work       */
	/* since most errors imply already disconnected.    */
	DBIc_ACTIVE_off(imp_dbh);

	/* Record loss of connection in driver block */
	imp_drh->n_connections--;
	imp_drh->current_connection = 0;
	assert(imp_drh->n_connections >= 0);
	dbd_ix_link_delete(&imp_dbh->chain, noop);

	/* We don't free imp_dbh since a reference still exists	 */
	/* The DESTROY method is the only one to 'free' memory.	 */
	dbd_ix_exit(function);
	return 1;
}

void
dbd_ix_db_destroy(SV *dbh, imp_dbh_t *imp_dbh)
{
	static const char function[] = "dbd_ix_db_destroy";
	dbd_ix_enter(function);
	if (DBIc_is(imp_dbh, DBIcf_ACTIVE))
		dbd_ix_db_disconnect(dbh, imp_dbh);
	DBIc_off(imp_dbh, DBIcf_IMPSET);
	dbd_ix_exit(function);
}

/* ================================================================== */
/* =================== Statement Level Operations =================== */
/* ================================================================== */

/* Initialize a statement structure, allocating names */
static void
new_statement(imp_dbh_t *imp_dbh, imp_sth_t *imp_sth)
{
	static long     cursor_num = 0;

	sprintf(imp_sth->nm_stmnt, "p_%09ld", cursor_num);
	sprintf(imp_sth->nm_cursor, "c_%09ld", cursor_num);
	sprintf(imp_sth->nm_obind, "d_%09ld", cursor_num);
	sprintf(imp_sth->nm_ibind, "b_%09ld", cursor_num);
	imp_sth->dbh = imp_dbh;
	imp_sth->st_state = Unused;
	imp_sth->st_type = 0;
	imp_sth->st_text = 0;
	imp_sth->n_iblobs = 0;
	imp_sth->n_oblobs = 0;
	imp_sth->n_icols = 0;
	imp_sth->n_rows = 0;
	imp_sth->n_ocols = 0;
	imp_sth->is_holdcursor = False;
	imp_sth->is_scrollcursor = False;
	dbd_ix_link_add(&imp_dbh->head, &imp_sth->chain);
	imp_sth->chain.data = (void *)imp_sth;
	cursor_num++;
	/* Cleanup required for statement chain in imp_dbh */
	DBIc_on(imp_sth, DBIcf_IMPSET);
}

#ifdef USE_DBD_IX_STMT_STATE_NAME
static const char *dbd_ix_stmt_state_name(State state)
{
	const char *s;
	switch (state)
	{
	case Unused:
		s = "Unused";
		break;
	case Prepared:
		s = "Prepared";
		break;
	case Allocated:
		s = "Allocated";
		break;
	case Described:
		s = "Described";
		break;
	case Declared:
		s = "Declared";
		break;
	case Opened:
		s = "Opened";
		break;
	case NoMoreData:
		s = "NoMoreData";
		break;
	default:
		s = "*invalid state*";
		break;
	}
	return(s);
}
#endif /* USE_DBD_IX_STMT_STATE_NAME */

/* Close cursor */
static int
dbd_ix_close(imp_sth_t *imp_sth)
{
	static const char function[] = "dbd_ix_close";
	EXEC SQL BEGIN DECLARE SECTION;
	char           *nm_cursor = imp_sth->nm_cursor;
	EXEC SQL END DECLARE SECTION;

	dbd_ix_enter(function);

	assert(imp_sth->st_state == Opened);
	if (imp_sth->st_state == Opened)
	{
		EXEC SQL CLOSE :nm_cursor;
		dbd_ix_sqlcode(imp_sth->dbh);
		imp_sth->st_state = Declared;
		if (sqlca.sqlcode < 0)
		{
			dbd_ix_exit(function);
			return 0;
		}
	}
	dbd_ix_exit(function);
	return 1;
}

/* Release a complete SQL DESCRIPTOR, including any blobs */
static void dbd_ix_st_deallocate(char *p_name, int nblobs, int ncols)
{
	EXEC SQL BEGIN DECLARE SECTION;
	char *name = p_name;
	EXEC SQL END DECLARE SECTION;

	/* ESQL/C does not (always) deallocate blob space automatically */
	/* Verified unfixed for ESQL/C 6.00.UE1 on Solaris 2.4 */
	/* Verified unfixed for ESQL/C 7.21.UC1 on Solaris 2.4 with Purify */
	/* Verified unfixed for ESQL/C 7.23.UC1 on Solaris 2.4 */
	/* Verified *fixed* in 7.24.UC1 on Solaris 2.5.1 (bad frees reported) */
	/* Verified as a bad fix on Windows 95/NT by Harald Ums (no version) */
#if ESQLC_VERSION < 724
#define DBD_IX_RELEASE_BLOBS
#endif
#ifdef WIN32
#undef DBD_IX_RELEASE_BLOBS
#endif /* WIN32 */

#ifdef DBD_IX_RELEASE_BLOBS
	if (nblobs > 0)
	{
		EXEC SQL BEGIN DECLARE SECTION;
		int             colno;
		int             coltype;
		loc_t           blob;
		EXEC SQL END DECLARE SECTION;

		for (colno = 1; colno <= ncols; colno++)
		{
			EXEC SQL GET DESCRIPTOR :name VALUE :colno :coltype = TYPE;
			if (sqlca.sqlcode != 0)
				break;
			if (coltype == SQLBYTES || coltype == SQLTEXT)
			{
				EXEC SQL GET DESCRIPTOR :name VALUE :colno :blob = DATA;
				if (sqlca.sqlcode != 0)
					break;
				if (blob.loc_loctype == LOCMEMORY && blob.loc_buffer != 0)
					free(blob.loc_buffer);
			}
		}
	}
#endif /* DBD_IX_RELEASE_BLOBS */

	if (ncols > 0)
	{
		dbd_ix_debug(3, "dbd_ix_st_deallocate() DEALLOCATE DESCRIPTOR %s\n", name);
		EXEC SQL DEALLOCATE DESCRIPTOR :name;
		if (sqlca.sqlcode != 0)
			dbd_ix_debug_l(0, "dbd_ix_st_deallocate() - DEALLOCATE DESCRIPTOR failed %ld\n", sqlca.sqlcode);
	}
}

/* Release all database and allocated resources for statement */
static void
del_statement(imp_sth_t *imp_sth)
{
	EXEC SQL BEGIN DECLARE SECTION;
	char           *name;
	EXEC SQL END DECLARE SECTION;

	dbd_ix_debug_l(3, "-->> del_statement() 0x%08X\n", (long)imp_sth);

	if (dbd_db_setconnection(imp_sth->dbh) == 0)
	{
		dbd_ix_savesqlca(imp_sth->dbh);
		return;
	}

	switch (imp_sth->st_state)
	{
	case NoMoreData:
		dbd_ix_debug(5, "-->> del_statement() state %s\n", "NoMoreData");
		/* FALLTHROUGH */

	case Opened:
		dbd_ix_debug(5, "-->> del_statement() state %s\n", "Opened");
		name = imp_sth->nm_cursor;
		EXEC SQL CLOSE :name;
		dbd_ix_debug(3, "del_statement() CLOSE cursor %s\n", name);
		/* FALLTHROUGH */

	case Declared:
		dbd_ix_debug(5, "-->> del_statement() state %s\n", "Declared");
		name = imp_sth->nm_cursor;
		EXEC SQL FREE :name;
		dbd_ix_debug(3, "del_statement() FREE cursor %s\n", name);
		/* FALLTHROUGH */

	case Described:
		dbd_ix_debug(5, "-->> del_statement() state %s\n", "Described");
		/* FALLTHROUGH */

	case Allocated:
		dbd_ix_debug(5, "-->> del_statement() state %s\n", "Allocated");
		dbd_ix_st_deallocate(imp_sth->nm_obind, imp_sth->n_oblobs, imp_sth->n_ocols);
		/* FALLTHROUGH */

	case Prepared:
		dbd_ix_debug(5, "-->> del_statement() state %s\n", "Prepared");
		dbd_ix_st_deallocate(imp_sth->nm_ibind, imp_sth->n_iblobs, imp_sth->n_icols);
		name = imp_sth->nm_stmnt;
		EXEC SQL FREE :name;
		dbd_ix_debug(3, "del_statement() FREE statement %s\n", name);
		/* FALLTHROUGH */

	case Unused:
		dbd_ix_debug(5, "-->> del_statement() state %s\n", "Unused");
		break;
	}
	if (imp_sth->st_text != 0)
		SvREFCNT_dec(imp_sth->st_text);
	imp_sth->st_state = Unused;
	dbd_ix_link_delete(&imp_sth->chain, noop);
	DBIc_off(imp_sth, DBIcf_IMPSET);
	dbd_ix_debug_l(3, "<<-- del_statement() 0x%08X\n", (long)imp_sth);
}

/* Create the input descriptor for the specified number of items */
static int
dbd_ix_setbindnum(imp_sth_t *imp_sth, int items)
{
	static const char function[] = "dbd_ix_setbindnum";
	EXEC SQL BEGIN DECLARE SECTION;
	int  bind_size = items;
	char           *nm_ibind = imp_sth->nm_ibind;
	EXEC SQL END DECLARE SECTION;

	dbd_ix_enter(function);

	if (dbd_db_setconnection(imp_sth->dbh) == 0)
	{
		dbd_ix_exit(function);
		return 0;
	}

	if (items > imp_sth->n_icols)
	{
		if (imp_sth->n_icols > 0)
		{
			dbd_ix_debug(3, "dbd_ix_setbindnum() DEALLOCATE descriptor %s\n", nm_ibind);
			EXEC SQL DEALLOCATE DESCRIPTOR :nm_ibind;
			dbd_ix_sqlcode(imp_sth->dbh);
			imp_sth->n_icols = 0;
			if (sqlca.sqlcode < 0)
			{
				dbd_ix_exit(function);
				return 0;
			}
		}
		dbd_ix_debug(3, "dbd_ix_setbindnum() ALLOCATE descriptor %s\n", nm_ibind);
		EXEC SQL ALLOCATE DESCRIPTOR :nm_ibind WITH MAX :bind_size;
		dbd_ix_sqlcode(imp_sth->dbh);
		if (sqlca.sqlcode < 0)
		{
			dbd_ix_exit(function);
			return 0;
		}
		imp_sth->n_icols = items;
	}
	dbd_ix_exit(function);
	return 1;
}

/* Bind the value to input descriptor entry */
static int
dbd_ix_bindsv(imp_sth_t *imp_sth, int idx, int p_type, SV *val)
{
	static const char function[] = "dbd_ix_bindsv";
	int rc = 1;
	STRLEN len;
	EXEC SQL BEGIN DECLARE SECTION;
	char           *nm_ibind = imp_sth->nm_ibind;
	char *string;
	long  intvar;
	double          numeric;
	int     length;
	int index = idx;
	loc_t blob;
	int type = p_type;
	EXEC SQL END DECLARE SECTION;
#if ESQLC_VERSION == 500 || ESQLC_VERSION == 501
	/**
	** The hostvar struct uses 'short' for the size, so we can't get
	** maximum size character columns.  This isn't a major problem.
	** Note that the independent DECLARE SECTIONs are necessary.
	*/
	EXEC SQL BEGIN DECLARE SECTION;
	char longchar[32767];
	char shortchar[256];
	EXEC SQL END DECLARE SECTION;
#endif /* ESQLC_VERSION in {500, 501} */

	dbd_ix_enter(function);

	if ((rc = dbd_db_setconnection(imp_sth->dbh)) == 0)
	{
		dbd_ix_savesqlca(imp_sth->dbh);
		dbd_ix_exit(function);
		return(rc);
	}

	dbd_ix_debug_l(2, "---- dbd_ix_bindsv() fld-indx = %ld\n", (long)index);
	dbd_ix_debug_l(2, "---- dbd_ix_bindsv() inp-type = %ld\n", (long)type);
	if (type == SQLVCHAR)
	{
		/**
		** SQLVCHAR is the default type.  See if there's any information
		** available in the descriptor because of a described INSERT.
		*/
		EXEC SQL GET DESCRIPTOR :nm_ibind VALUE :index :type = TYPE;
		/* If there is no info, work on the basis of the type in the SV */
	}


	/**
	** JL 2000-09-28:
	** Don't sweat the types too hard (yet).  At the moment, if the
	** specified type of the parameter is TEXT or BYTE, then we give it
	** special attention.  Otherwise, we look at the Perl variable and
	** see whether the value is null, an integer, a decimal or a string,
	** and encode the SQL descriptor accordingly.  That means we largely
	** ignore the specified type, too.
	** What happens if you insert integer 12 into a DATETIME HOUR TO HOUR?
	** When collection types etc are supported, we may need some more
	** code in here.
	*/
	if (type == SQLBYTES || type == SQLTEXT)
	{
		/* Trust that the user knows what they are up to! */
		blob_locate(&blob, BLOB_IN_MEMORY);
		if (!SvOK(val))
		{
			dbd_ix_debug(2, "%s -- null blob\n", function);
			blob.loc_indicator = -1;
			blob.loc_buffer = 0;
			blob.loc_bufsize = 0;
			blob.loc_size = 0;
		}
		else
		{
			dbd_ix_debug(2, "%s -- blob\n", function);
			blob.loc_buffer = SvPV(val, len);
			blob.loc_bufsize = len + 1;
			blob.loc_size = len;
		}
		EXEC SQL SET DESCRIPTOR :nm_ibind VALUE :index TYPE = :type, DATA = :blob;
	}
	else if (!SvOK(val))
	{
		/* It's a null! */
		dbd_ix_debug(2, "%s -- null\n", function);
		type = SQLCHAR;
#if ESQLC_VERSION >= 600
		EXEC SQL SET DESCRIPTOR :nm_ibind VALUE :index
						TYPE = :type, LENGTH = 0, INDICATOR = -1;
#else
		/**
		** JL 1997-05-20:
		** There appears to be a bug in ESQL/C 5.0x (for x in 0..6) such
		** that the SET DESCRIPTOR code core dumps when asked to process a
		** NULL.  We use a cheat, pure and simple, to get around this bug.
		** We use the internal representation for a SMALLINT NULL (-32768)
		** as the value to be inserted.  It shouldn't work (arguably
		** another bug), but since it does, we'll exploit it.  Ugh!
		*/
		{
#define SMINTNULL -32768	/* Internal representation of SMALLINT NULL */
		EXEC SQL BEGIN DECLARE SECTION;
			short           ival = SMINTNULL;
		EXEC SQL END DECLARE SECTION;
		type = SQLSMINT;
		EXEC SQL SET DESCRIPTOR :nm_ibind VALUE :index
						TYPE = :type, DATA = :ival;
		}
#endif
	}
	else if (SvIOKp(val))
	{
		dbd_ix_debug(2, "%s -- integer\n", function);
		type = SQLINT;
		intvar = SvIV(val);
		EXEC SQL SET DESCRIPTOR :nm_ibind VALUE :index
						TYPE = :type, DATA = :intvar;
	}
	else if (SvNOKp(val))
	{
		dbd_ix_debug(2, "%s -- numeric\n", function);
		type = SQLFLOAT;
		numeric = SvNV(val);
		EXEC SQL SET DESCRIPTOR :nm_ibind VALUE :index
						TYPE = :type, DATA = :numeric;
	}
	else
	{
		dbd_ix_debug(2, "%s -- string\n", function);
		type = SQLCHAR;
		string = SvPV(val, len);
		length = len + 1;
#if ESQLC_VERSION == 500 || ESQLC_VERSION == 501
		if (length < sizeof(shortchar))
		{
			strncpy(shortchar, string, length);
			shortchar[length] = '\0';
			EXEC SQL SET DESCRIPTOR :nm_ibind VALUE :index
							TYPE = :type, LENGTH = :length,
							DATA = :shortchar;
		}
		else
		{
			if (length >= sizeof(longchar))
				length = sizeof(longchar) - 1;
			strncpy(longchar, string, length);
			longchar[length] = '\0';
			EXEC SQL SET DESCRIPTOR :nm_ibind VALUE :index
							TYPE = :type, LENGTH = :length,
							DATA = :longchar;
		}
#else
		if (length == 1)
		{
			/**
			** Even if you insert "" as a literal into a VARCHAR(), you get
			** a blank returned.  If you manage to insert a zero length
			** string via a variable into a VARCHAR, then you get a NULL
			** output string.  This is arguably a bug, but oh well!
			*/
			string = " ";
			length = 2;
		}
		EXEC SQL SET DESCRIPTOR :nm_ibind VALUE :index
						TYPE = :type, LENGTH = :length,
						DATA = :string;
#endif /* ESQLC_VERSION in {500, 501} */
	}
	dbd_ix_sqlcode(imp_sth->dbh);
	if (sqlca.sqlcode < 0)
	{
		rc = 0;
	}
	dbd_ix_exit(function);
	return(rc);
}

static int
count_blobs(char *descname, int ncols)
{
	EXEC SQL BEGIN DECLARE SECTION;
	char           *nm_obind = descname;
	int	colno;
	int coltype;
	EXEC SQL END DECLARE SECTION;
	int nblobs = 0;

	for (colno = 1; colno <= ncols; colno++)
	{
		EXEC SQL GET DESCRIPTOR :nm_obind VALUE :colno :coltype = TYPE;

		/* dbd_ix_sqlcode(imp_sth->dbh); */
		if (coltype == SQLBYTES || coltype == SQLTEXT)
		{
			nblobs++;
		}
	}
	return(nblobs);
}

/* Process blobs (if any) */
static void
dbd_ix_blobs(imp_sth_t *imp_sth)
{
	static const char function[] = "dbd_ix_blobs";
	EXEC SQL BEGIN DECLARE SECTION;
	char           *nm_obind = imp_sth->nm_obind;
	loc_t		   blob;
	int 			colno;
	int coltype;
	EXEC SQL END DECLARE SECTION;
	int             n_ocols = imp_sth->n_ocols;

	dbd_ix_enter(function);
	imp_sth->n_oblobs = count_blobs(nm_obind, n_ocols);
	if (imp_sth->n_oblobs == 0)
	{
		dbd_ix_exit(function);
		return;
	}

	/* warn("dbd_ix_blobs: %d blobs\n", imp_sth->n_oblobs); */

	/* Set blob location */
	if (blob_locate(&blob, imp_sth->blob_bind) != 0)
	{
		croak("memory allocation error 3 in dbd_ix_blobs\n");
	}

	for (colno = 1; colno <= n_ocols; colno++)
	{
		EXEC SQL GET DESCRIPTOR :nm_obind VALUE :colno :coltype = TYPE;
		dbd_ix_sqlcode(imp_sth->dbh);
		if (coltype == SQLBYTES || coltype == SQLTEXT)
		{
			/* Tell ESQL/C how to handle this blob */
			EXEC SQL SET DESCRIPTOR :nm_obind VALUE :colno DATA = :blob;
			dbd_ix_sqlcode(imp_sth->dbh);
		}
	}
	dbd_ix_exit(function);
}

/* set the cast types for udts. returns number of udt columns */
static int
dbd_ix_udts(imp_sth_t *imp_sth)
{
	static const char function[] = "dbd_ix_udts";
	int nudts = 0;
	EXEC SQL BEGIN DECLARE SECTION;
	char *nm_obind = imp_sth->nm_obind;
	int coltype;
	int colno;
	EXEC SQL END DECLARE SECTION;

	dbd_ix_enter(function);
#if ESQLC_VERSION > 900
	for (colno = 1; colno <= imp_sth->n_ocols; colno++)
	{
		EXEC SQL GET DESCRIPTOR :nm_obind VALUE :colno :coltype = TYPE;
		dbd_ix_sqlcode(imp_sth->dbh);
		if (ISCOMPLEXTYPE(coltype) || ISUDTTYPE(coltype)
			|| ISDISTINCTTYPE(coltype))
		{
			/**
			** MYK 2000-01-19 (ESQL/C 9.30).
			** For the reasons unknown SQLCHAR is the only one that
			** works.  Also, the manuals say LENGTH=0 sets to the actual
			** value length.  In fact it just causes FETCH to fail.
			*/
			coltype = SQLCHAR;
			EXEC SQL SET DESCRIPTOR :nm_obind VALUE :colno TYPE = :coltype,
				LENGTH = 256;
			dbd_ix_sqlcode(imp_sth->dbh);
			nudts++;
		}
	}
#endif /* ESQLC_VERSION > 900 */
	dbd_ix_exit(function);
	return nudts;
}

/* Declare cursor for SELECT, EXECUTE PROCEDURE, or INSERT */
static int
dbd_ix_declare(imp_sth_t *imp_sth)
{
	static const char function[] = "dbd_ix_declare";
	EXEC SQL BEGIN DECLARE SECTION;
	char           *nm_stmnt = imp_sth->nm_stmnt;
	char           *nm_cursor = imp_sth->nm_cursor;
	EXEC SQL END DECLARE SECTION;

	dbd_ix_enter(function);
#ifdef SQ_EXECPROC
	assert(imp_sth->st_type == SQ_SELECT || imp_sth->st_type == SQ_INSERT ||
		   imp_sth->st_type == SQ_EXECPROC);
#else
	assert(imp_sth->st_type == SQ_SELECT || imp_sth->st_type == SQ_INSERT);
#endif /* SQ_EXECPROC */
	assert(imp_sth->st_state == Described);
	dbd_ix_blobs(imp_sth);
	dbd_ix_udts( imp_sth );

	/* BR 1999-08-30: Hold Cursor -- Not necessarily correct... */
	if (imp_sth->dbh->is_modeansi == True &&
		DBI_AutoCommit(imp_sth->dbh) == True)
	{
		/* XPS 8.11 does not support hold cursors (Robert Wyrick <rob@wyrick.org>) */
		/* Note that the ESQL/C does support hold cursors. */
		/* The issue is whether the server does. */
		/* Assume 8.00 through 8.29 does not do so either.  8.30 may support them. */
		if (imp_sth->dbh->srvr_vrsn >= 800 && imp_sth->dbh->srvr_vrsn < 830)
			imp_sth->is_holdcursor = False;
		else
			imp_sth->is_holdcursor = True;
	}

#define print_tf(a) (a == True ? "True" : "False")
	dbd_ix_debug(3, "is_holdcursor   = %s", print_tf(imp_sth->is_holdcursor));
	dbd_ix_debug(3, "is_scrollcursor = %s", print_tf(imp_sth->is_scrollcursor));
	dbd_ix_debug(3, "is_insertcursor = %s", print_tf(imp_sth->is_insertcursor));
#undef print_tf

	if (imp_sth->is_scrollcursor == True)
	{
		if (imp_sth->is_holdcursor == True)
		{
			EXEC SQL DECLARE :nm_cursor SCROLL CURSOR WITH HOLD FOR :nm_stmnt;
		}
		else
		{
			EXEC SQL DECLARE :nm_cursor SCROLL CURSOR FOR :nm_stmnt;
		}
	}
	else
	{
		if (imp_sth->is_insertcursor && imp_sth->dbh->is_loggeddb &&
			DBI_AutoCommit(imp_sth->dbh) == True)
		{
			warn("insert cursor ineffective with AutoCommit enabled");
		}
		if (imp_sth->is_holdcursor == True)
		{
			EXEC SQL DECLARE :nm_cursor CURSOR WITH HOLD FOR :nm_stmnt;
		}
		else
		{
			EXEC SQL DECLARE :nm_cursor CURSOR FOR :nm_stmnt;
		}
	}
	dbd_ix_sqlcode(imp_sth->dbh);
	if (sqlca.sqlcode < 0)
	{
		dbd_ix_exit(function);
		return 0;
	}
	imp_sth->st_state = Declared;
	dbd_ix_exit(function);
	return 1;
}

/*
** dbd_ix_preparse() -- based on dbd_preparse() in DBD::ODBC 0.15
**
** Count the placeholders (?) parameters in the statement.
**
** The main-stream version also edits the string (in situ because the
** output will never be longer than the input) and recognizes both :9 (9 =
** digit string) positional parameters and :a (a = alphanumeric identifier)
** named parameters and converts them to ?.  However, this Informix version
** does not handle these non-standard extensions because the :a notation
** causes problems with Informix's FROM dbase:table notation, and the :9
** notation causes problems with DATETIME and INTERVAL literals!
**
** The code handles single-quoted literals and double-quoted delimited
** identifiers and ANSI SQL "--.*\n" comments and Informix "{.*}" comments.
** Note that it does nothing with "#.*\n" Perl/Shell comments.  Also note
** that it does not handle ODBC-style extensions.  The shorthand notation
** for these is identical to an Informix {} comment; longhand notation
** looks like "--*(details*)--" without the quotes.
*/

static int
dbd_ix_preparse(char *statement)
{
	char            end_quote = '\0';
	char           *src;
	char           *dst;
	int             idx = 0;
	int             style = 0;
	int             laststyle = 0;
	char            ch;

	dbd_ix_debug(4, "-->>dbd_ix_preparse(): <<%s>>\n", statement);
	src = statement;
	dst = statement;
	while ((ch = *src++) != '\0')
	{
		if (ch == end_quote)
			end_quote = '\0';
		else if (end_quote != '\0')
		{
			*dst++ = ch;
			continue;
		}
		else if (ch == '\'' || ch == '\"')
			end_quote = ch;
		else if (ch == L_CURLY)
			end_quote = R_CURLY;
		else if (ch == '-' && *src == '-')
		{
			end_quote = '\n';
		}
		if (ch == '?')
		{
			/* X/Open standard	 */
			*dst++ = '?';
			idx++;
			style = 3;
		}
		else
		{
			/* Perhaps ':=' PL/SQL construct or dbase:table in Informix */
			/* Or it could be :2 or :22 as part of a DATETIME/INTERVAL */
			*dst++ = ch;
			continue;
		}
		if (laststyle && style != laststyle)
			croak("Can't mix placeholder styles (%d/%d)", style, laststyle);
		laststyle = style;
	}
	if (end_quote != '\0')
	{
		switch (end_quote)
		{
		case '\'':
			warn("Incomplete single-quoted string\n");
			break;
		case '\"':
			warn("Incomplete double-quoted string (delimited identifier)\n");
			break;
		case R_CURLY:
			warn("Incomplete bracketed {...} comment\n");
			break;
		case '\n':
			warn("Incomplete double-dash comment\n");
			break;
		default:
			assert(0);
			break;
		}
	}
	*dst = '\0';
	dbd_ix_debug(4, "<<--dbd_ix_preparse(): %d placeholders\n", idx);
	return(idx);
}

static Boolean
dbd_ix_st_attrib(SV *attribs, const char *attr)
{
	Boolean rc = False;

	/* Modularized version of Bill Rothanburg <brothanb@fll-ro.dhl.com> code */
	/* To determine the setting of Hold and Scroll Cursor Attributes */
	if (attribs != NULL)
	{
		SV				**svpp;
		U32				len;

		len = strlen(attr);
		svpp = hv_fetch((HV *) SvRV(attribs), (char *)attr, len, 0);
		if (svpp != NULL)
		{
			rc = DBD_IX_BOOLEAN(SvTRUE(*svpp));
			dbd_ix_debug_2(1, "%s set to %ld\n", attr, (long)rc);
		}
	}
	return(rc);
}

/*
** Count the number of described items in the given statement.
**
** JL 2000-02-08: This is a ridiculous way to have to do things, but it
** works with ESQL/C 9.30.UC1, and there doesn't seem to be a way to
** find out how big a descriptor to allocate without trying and failing!
**
** Note that there is a chance that the free(u) will cause the Sqlda
** structure to be double-released in some early 5.0x versions of
** ESQL/C.  However, precise information about which versions are
** afflicted is not available, so we press ahead...
**
** NB: if we ever switch from SQL DESCRIPTORs to Sqlda structures, then
** this kludge becomes unnecessary, of course.  The only reason for
** retaining SQL DESCRIPTORs at the moment is the NULLABLE attribute --
** the Sqlda structure does not give this information.
*/
static int
count_descriptors(char *stmt)
{
	Sqlda	*u;
	int		 n = 256;
	EXEC SQL BEGIN DECLARE SECTION;
	char *nm_stmt = stmt;
	EXEC SQL END DECLARE SECTION;

	EXEC SQL DESCRIBE :nm_stmt INTO u;
	if (sqlca.sqlcode >= 0)
	{
		n = u->sqld;
#if defined(PERL_OBJECT) && (ESQLC_VERSION >= 720 || (ESQLC_VERSION >= 501 && ESQLC_VERSION < 600))
		/**
		** JL 2000-02-29:
		** Using SqlFreeMem() is the recommended fix for PTS Bug B83831
		** on Win32 platforms.  See the notes in the file Notes/nt for
		** more details about this.  SqlFreeMem() is not necessarily
		** documented, but it should be.  Apparently, SqlFreeMem() was
		** available in 5.01.WC1, so it should be available in all 5.x
		** versions.  It was reinstated in 7.20.TD1; the conditions
		** above document this.  It was only ever available on Win32
		** (Windows NT) and never on Unix.  The PERL_OBJECT define is
		** associated with ActiveState's Active Perl on NT and only
		** optionally with a manual build of Perl on NT.  If there is a
		** better platform indicator, we can change that part of the
		** condition.  Note that even if the DBD::Informix code only
		** uses Sqlda structures, the NT platform will probably use
		** SqlFreeMem().  You may run into crashes if SqlFreeMem() is
		** not available for your version of ESQL/C on NT.
		*/
		SqlFreeMem(u, SQLDA_FREE);
#else
		free(u);
#endif
	}
	dbd_ix_debug_l(1, "number of described fields %ld\n", (long)n);
	return(n);
}

int
dbd_ix_st_prepare(SV *sth, imp_sth_t *imp_sth, char *stmt, SV *attribs)
{
	static const char function[] = "dbd_ix_st_prepare";
	D_imp_dbh_from_sth;
	int  rc = 1;
	static const char ix_hc[] = "ix_CursorWithHold";
	static const char ix_sc[] = "ix_ScrollCursor";
	static const char ix_ic[] = "ix_InsertCursor";
	EXEC SQL BEGIN DECLARE SECTION;
	char           *statement = stmt;
	int             desc_count;
	char           *nm_stmnt;
	char           *nm_obind;
	char           *nm_cursor;
	EXEC SQL END DECLARE SECTION;

	dbd_ix_enter(function);

	if (stmt == 0 || *stmt == '\0')
	{
		/* No valid statement text */
		/* -402: Address of a host variable is NULL. */
		dbd_ix_db_seterror(imp_dbh, -402);
		dbd_ix_savesqlca(imp_dbh);
		dbd_ix_exit(function);
		return(0);
	}

	if ((rc = dbd_db_setconnection(imp_dbh)) == 0)
	{
		dbd_ix_savesqlca(imp_dbh);
		dbd_ix_exit(function);
		return(rc);
	}

	new_statement(imp_dbh, imp_sth);
	nm_stmnt = imp_sth->nm_stmnt;
	nm_obind = imp_sth->nm_obind;
	nm_cursor = imp_sth->nm_cursor;
	imp_sth->st_text = newSVpv(stmt, 0);

	/* Bill R. Code to allow the setting of Hold and Scroll Cursor Attribs */
	if (attribs == NULL)
		dbd_ix_debug(4, "%s - no attribs set", function);
	else
	{
		imp_sth->is_holdcursor = dbd_ix_st_attrib(attribs, ix_hc);
		imp_sth->is_scrollcursor = dbd_ix_st_attrib(attribs, ix_sc);
		imp_sth->is_insertcursor = dbd_ix_st_attrib(attribs, ix_ic);
	}

	dbd_ix_debug(4, "dbd_ix_st_prepare -- <<%s>>\n", statement);
	EXEC SQL PREPARE :nm_stmnt FROM :statement;
	dbd_ix_savesqlca(imp_dbh);
	dbd_ix_sqlcode(imp_dbh);
	if (sqlca.sqlcode < 0)
	{
		del_statement(imp_sth);
		dbd_ix_exit(function);
		return 0;
	}
	imp_sth->st_state = Prepared;

	/* Record the number of input parameters in the statement */
	DBIc_NUM_PARAMS(imp_sth) = dbd_ix_preparse(statement);

	/* Allocate space for that many parameters */
	if (dbd_ix_setbindnum(imp_sth, DBIc_NUM_PARAMS(imp_sth)) == 0)
	{
		del_statement(imp_sth);
		dbd_ix_exit(function);
		return 0;
	}

	desc_count = count_descriptors(nm_stmnt);
	/* SQL DESCRIPTORS must have WITH MAX of at least one (error -470) */
	if (desc_count == 0)
		desc_count = 1;
	dbd_ix_debug(3, "dbd_ix_st_prepare() ALLOCATE descriptor %s\n", nm_obind);
	EXEC SQL ALLOCATE DESCRIPTOR :nm_obind WITH MAX :desc_count;
	dbd_ix_sqlcode(imp_dbh);
	if (sqlca.sqlcode < 0)
	{
		del_statement(imp_sth);
		dbd_ix_exit(function);
		return 0;
	}
	imp_sth->st_state = Allocated;

	EXEC SQL DESCRIBE :nm_stmnt USING SQL DESCRIPTOR :nm_obind;
	dbd_ix_sqlcode(imp_dbh);
	if (sqlca.sqlcode < 0)
	{
		del_statement(imp_sth);
		dbd_ix_exit(function);
		return 0;
	}
	imp_sth->st_state = Described;
	imp_sth->st_type = sqlca.sqlcode;
	if (imp_sth->st_type == 0)
		imp_sth->st_type = SQ_SELECT;

	EXEC SQL GET DESCRIPTOR :nm_obind :desc_count = COUNT;
	dbd_ix_sqlcode(imp_dbh);
	if (sqlca.sqlcode < 0)
	{
		del_statement(imp_sth);
		dbd_ix_exit(function);
		return 0;
	}

	/* Record the number of fields in the cursor for DBI and DBD::Informix  */
	DBIc_NUM_FIELDS(imp_sth) = imp_sth->n_ocols = desc_count;

	/* Cannot create an INSERT cursor except on an insert statement */
	if (imp_sth->is_insertcursor == True && imp_sth->st_type != SQ_INSERT)
	{
		/* -481: Invalid statement name or statement was not prepared */
		/* Generated by 9.21.UC1 in response to declare cursor on update stmt */
		sqlca.sqlcode = -481;
		dbd_ix_sqlcode(imp_dbh);
		del_statement(imp_sth);
		dbd_ix_exit(function);
		return(0);
	}

	/**
	** Only non-cursory statements need an output descriptor.
	** Only cursory statements need a cursor declared for them.
	** INSERT may yield an input descriptor (which will appear to be the
	** output descriptor, such being the wonders of Informix).
	** UPDATE and DELETE (and, indeed, INSERT, SELECT and EXECUTE
	** PROCEDURE) statements would benefit from having a description of
	** the input parameters, but this is not available.  SQL-92 defines
	** DESCRIBE INPUT and DESCRIBE OUTPUT, but (as of 2000-08-01)
	** Informix does not implement DESCRIBE INPUT.
	*/
	if (imp_sth->st_type == SQ_SELECT)
		rc = dbd_ix_declare(imp_sth);
#ifdef SQ_EXECPROC	/* Defined for servers 5.00 and later, except perhaps 8.[012]x XPS */
	else if (imp_sth->st_type == SQ_EXECPROC && desc_count > 0)
		rc = dbd_ix_declare(imp_sth);
#endif	/* SQ_EXECPROC */
	else if (imp_sth->st_type == SQ_INSERT && desc_count > 0)
	{
		int nudts = dbd_ix_udts(imp_sth);

		dbd_ix_blobs(imp_sth);
		if (imp_sth->n_oblobs > 0 || nudts > 0)
		{
			/**
			** Switch the nm_obind and nm_ibind names so that when
			** dbd_ix_bindsv() is at work, it has an already populated SQL
			** descriptor to work with, that already has the blobs set up
			** correctly.
			*/
			Name tmpname;
			dbd_ix_debug(3, "dbd_ix_st_prepare() switch descriptor names: old ibind %s\n", imp_sth->nm_ibind);
			dbd_ix_debug(3, "dbd_ix_st_prepare() switch descriptor names: old obind %s\n", imp_sth->nm_obind);
			strcpy(tmpname, imp_sth->nm_ibind);
			strcpy(imp_sth->nm_ibind, imp_sth->nm_obind);
			strcpy(imp_sth->nm_obind, tmpname);
			dbd_ix_debug(3, "dbd_ix_st_prepare() switch descriptor names: new ibind %s\n", imp_sth->nm_ibind);
			dbd_ix_debug(3, "dbd_ix_st_prepare() switch descriptor names: new obind %s\n", imp_sth->nm_obind);
			imp_sth->n_icols = desc_count;
		}
		rc = 1;
		if (imp_sth->is_insertcursor == True)
			rc = dbd_ix_declare(imp_sth);
	}
	else
	{
		/**
		** JL 2000-08-09:
		** The IDS 7.30 and later servers nearly support describe for
		** UPDATE.  However, it requires a special server configuration.
		** Worse, the information returned by DESCRIBE is not usable.
		** Bug B111987: DESCRIBE ON UPDATE STATEMENT GIVES INADEQUATE
		** (AND UNUSABLE) INFORMATION.  The short description starts:
		** [Summary: the ability to DESCRIBE the input parameters of an
		** UPDATE might as well not exist -- it cannot be used in real
		** life ESQL/C programs.]
		**
		** The only reliable thing to do with the description of the
		** input parameters to an UPDATE statement is to ignore it.
		*/
		dbd_ix_debug(3, "dbd_ix_st_prepare() DEALLOCATE DESCRIPTOR %s\n", nm_obind);
		EXEC SQL DEALLOCATE DESCRIPTOR :nm_obind;
		imp_sth->st_state = Prepared;
		rc = 1;
	}

	dbd_ix_debug_2(2, "%s'imp_sth->n_ocols: %d\n", function, imp_sth->n_ocols);

	dbd_ix_exit(function);
	return rc;
}

/* CLOSE cursor */
int
dbd_ix_st_finish(SV *sth, imp_sth_t *imp_sth, int gd_flag)
{
	static const char function[] = "dbd_ix_st_finish";
	dTHR;
	int rc;

	dbd_ix_enter(function);

	if ((rc = dbd_db_setconnection(imp_sth->dbh)) == 0)
	{
		dbd_ix_savesqlca(imp_sth->dbh);
	}
	else
	{
		if (imp_sth->st_state == Opened)
			rc = dbd_ix_close(imp_sth);
		else if (imp_sth->st_state == NoMoreData)
			imp_sth->st_state = Declared;
		else
			rc = 0;
		DBIc_ACTIVE_off(imp_sth);
	}

	dbd_ix_exit(function);
	return rc;
}

/* Free up resources used by the cursor or statement */
void
dbd_ix_st_destroy(SV *sth, imp_sth_t *imp_sth)
{
	static const char function[] = "dbd_ix_st_destroy";
	dbd_ix_enter(function);
	del_statement(imp_sth);
	dbd_ix_exit(function);
}

/* Convert DECIMAL to convenient string */
/* Patches problems with Informix conversion routines in pre-7.10 versions */
/* Don't forget that decimals are stored in a base-100 notation */
#if ESQLC_VERSION < 710
static char *
decgen(dec_t *val, int collen)
{
	char *str;
	int dp = PRECDEC(collen);	/* Decimal places */
	int sf = PRECTOT(collen);	/* Significant digits */

	if (dp == 0xFF)
	{
		/* Floating point decimal */
		str = decsci(val, sf, 0);
	}
	else
	{
		str = decfix(val, dp, 0);
	}
	while (*str == ' ')
		str++;
	/* Chop trailing blanks */
	str[byleng(str, strlen(str))] = '\0';
	return str;
}

#else

static char *
decgen(dec_t *val, int collen)
{
	static char buffer[170];
	char *str;
	int dp = PRECDEC(collen);	/* Decimal places */
	int sf = PRECTOT(collen);	/* Significant digits */

	if (dp == 0xFF)
		dp = -1;
	dectoasc(val, buffer, sizeof(buffer), dp);
	str = buffer;
	while (*str == ' ')
		str++;
	/* Chop trailing blanks */
	str[byleng(str, strlen(str))] = '\0';
	return str;
}

#endif /* ESQLC_VERSION < 710 */

/*
** Fetch a single row of data.
**
** Note the use of 'varchar' variables.  Given the sample code:
**
** #include <stdio.h>
** int main(int argc, char **argv)
** {
**     EXEC SQL BEGIN DECLARE SECTION;
**     char    cc[30];
**     varchar vc[30];
**     EXEC SQL END DECLARE SECTION;
**     EXEC SQL WHENEVER ERROR STOP;
**     EXEC SQL DATABASE Apt;
**     EXEC SQL CREATE TEMP TABLE Test(Col01 CHAR(20), Col02 VARCHAR(20));
**     EXEC SQL INSERT INTO Test VALUES("ABCDEFGHIJ     ", "ABCDEFGHIJ     ");
**     EXEC SQL SELECT Col01, Col01 INTO :cc, :vc FROM Test;
**     printf("Col01: cc = <<%s>>\n", cc);
**     printf("Col01: vc = <<%s>>\n", vc);
**     EXEC SQL SELECT Col02, Col02 INTO :cc, :vc FROM TestTable;
**     printf("Col02: cc = <<%s>>\n", cc);
**     printf("Col02: vc = <<%s>>\n", vc);
**     return(0);
** }
**
** The output looks like:
**		Col01: cc = <<ABCDEFGHIJ                   >>
**		Col01: vc = <<ABCDEFGHIJ          >>
**		Col02: cc = <<ABCDEFGHIJ                   >>
**		Col02: vc = <<ABCDEFGHIJ     >>
** Note that the data returned into 'cc' is blank padded to the length of
** the host variable, not the length of the database column, whereas 'vc'
** is blank-padded to the length of the database column for a CHAR column,
** and to the length of the inserted data in a VARCHAR column.
*/
AV *
dbd_ix_st_fetch(SV *sth, imp_sth_t *imp_sth)
{
	static const char function[] = "dbd_ix_st_fetch";
	AV	*av;
	EXEC SQL BEGIN DECLARE SECTION;
	char           *nm_cursor = imp_sth->nm_cursor;
	char           *nm_obind = imp_sth->nm_obind;
	varchar         coldata[256];
	long			coltype;
	long			collength;
	long			colind;
	char            colname[SQL_COLNAMELEN];
	int				index;
	char           *result;
	long            length;
	loc_t			blob;
	dec_t			decval;
$ifdef IUS_DATA_TYPES;
	long            extypeid;
#ifdef SQLLVARCHAR
	lvarchar       *lvar = 0;
#endif
$endif; -- IUS_DATA_TYPES
	EXEC SQL END DECLARE SECTION;
#if ESQLC_VERSION == 500 || ESQLC_VERSION == 501
	EXEC SQL BEGIN DECLARE SECTION;
	/**
	** The hostvar struct uses 'short' for the size, so we can't get
	** maximum size character columns.  This isn't a major problem.
	** Note that the independent DECLARE SECTIONs are necessary.
	*/
	varchar         longchar[32767];
	EXEC SQL END DECLARE SECTION;
#endif /* ESQLC_VERSION in {500, 501} */

	dbd_ix_enter(function);

	if (dbd_db_setconnection(imp_sth->dbh) == 0)
	{
		dbd_ix_savesqlca(imp_sth->dbh);
		dbd_ix_exit(function);
		return Nullav;
	}

	if (imp_sth->st_state == NoMoreData)
	{
		/* Simulate SQLNOTFOUND on a closed cursor */
		dbd_ix_debug(1, "%s: Simulate SQLNOTFOUND\n", function);
		sqlca.sqlcode = SQLNOTFOUND;
		dbd_ix_savesqlca(imp_sth->dbh);
		dbd_ix_sqlcode(imp_sth->dbh);
		dbd_ix_exit(function);
		return Nullav;
	}

	dbd_ix_blobs(imp_sth); /* Fix -451 errors; Rich Jones <rich@annexia.org> */

	EXEC SQL FETCH :nm_cursor USING SQL DESCRIPTOR :nm_obind;
	dbd_ix_savesqlca(imp_sth->dbh);
	dbd_ix_sqlcode(imp_sth->dbh);
	if (sqlca.sqlcode != 0)
	{
		if (sqlca.sqlcode != SQLNOTFOUND)
		{
			dbd_ix_debug(1, "Exit %s -- fetch failed\n", function);
		}
		else
		{
			/* Implicitly CLOSE cursor when no more data available */
			dbd_ix_close(imp_sth);
			imp_sth->st_state = NoMoreData;
			dbd_ix_debug(1, "Exit %s -- SQLNOTFOUND\n", function);
		}
		dbd_ix_exit(function);
		return Nullav;
	}

	imp_sth->n_rows++;

	av = DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth);

	for (index = 1; index <= imp_sth->n_ocols; index++)
	{
		SV             *sv = AvARRAY(av)[index - 1];
		EXEC SQL GET DESCRIPTOR :nm_obind VALUE :index
				:coltype = TYPE, :collength = LENGTH,
				:colind = INDICATOR, :colname = NAME;
		dbd_ix_sqlcode(imp_sth->dbh);

		if (colind != 0)
		{
			/* Data is null */
			result = coldata;
			length = 0;
			result[length] = '\0';
			(void)SvOK_off(sv);
			/* warn("NULL Data: %d <<%s>>\n", length, result); */
		}
		else
		{
			switch (coltype)
			{
			case SQLINT:
			case SQLSERIAL:
			case SQLSMINT:
			case SQLDATE:
			case SQLDTIME:
			case SQLINTERVAL:
#ifdef SQLBOOL
			case SQLBOOL:
#endif	/* SQLBOOL */
#ifdef SQLSERIAL8
			case SQLSERIAL8:
#endif /* SQLSERIAL8 */
#ifdef SQLINT8
			case SQLINT8:
#endif /* SQLINT8 */
				/* These types will always fit into a 256 character string */
				EXEC SQL GET DESCRIPTOR :nm_obind VALUE :index
						:coldata = DATA;
				result = coldata;
				length = byleng(result, strlen(result));
				result[length] = '\0';
				/* warn("Normal Data: %d <<%s>>\n", length, result); */
				break;

			case SQLFLOAT:
			case SQLSMFLOAT:
			case SQLDECIMAL:
			case SQLMONEY:
				/*
				** Default formatting (in some versions of ESQL/C)
				** assumes 2 decimal places -- wrong!
				*/
				EXEC SQL GET DESCRIPTOR: nm_obind VALUE:index
						:decval = DATA;
				strcpy(coldata, decgen(&decval, collength));
				result = coldata;
				length = strlen(result);
				/* warn("Decimal Data: %d <<%s>>\n", length, result); */
				break;

$ifdef IUS_DATA_TYPES;
#ifdef SQLUDTFIXED
			case SQLUDTFIXED:
				{
					EXEC SQL BEGIN DECLARE SECTION;
					fixed binary ifx_lo_t bclob;
					EXEC SQL END DECLARE SECTION;
					char            cb = 'C';
					int             error = 0;

					EXEC SQL GET DESCRIPTOR :nm_obind VALUE :index
										:extypeid = EXTYPEID;

					result = NULL;

					switch (extypeid)
					{
					case XID_BLOB:
						cb = 'B';
						/* FALLTHROUGH */
					case XID_CLOB:
						{
							int             LO_fd;
							ifx_lo_stat_t  *LO_stat;
							ifx_int8_t      size;

							EXEC SQL GET DESCRIPTOR :nm_obind VALUE :index
												:bclob = DATA;
							LO_fd = ifx_lo_open(&bclob, LO_RDONLY, &error);
							if (LO_fd == -1)
							{
								croak("Error opening %cLOB: %d", cb, error);
							}
							if (ifx_lo_stat(LO_fd, &LO_stat) < 0)
							{
								croak("Error getting %cLOB stat", cb);
							}
							if (ifx_lo_stat_size(LO_stat, &size) != 0)
							{
								croak("Error getting %cLOB size", cb);
							}
							if (ifx_int8tolong(&size, &length) != 0)
							{
								croak("Error converting %cbLOB size to length", cb);
							}
							if (ifx_lo_close(LO_fd) != 0)
							{
								croak("Error closing %cLOB", cb);
							}
							if (ifx_lo_to_buffer(&bclob, length, &result, &error) < 0)
							{
								croak("Error copying from %cLOB", cb);
							}
							break;
						}
					default:
						warn("IUS extended type (%d) is not yet supported", extypeid);
						break;
					}
					break;
				}
#endif

#ifdef SQLLVARCHAR
			case SQLLVARCHAR:
				if (ifx_var_flag(&lvar, 1) < 0)
				{
					warn("Cannot set automatic memory for lvarchar");
					break;
				}
				EXEC SQL GET DESCRIPTOR :nm_obind VALUE :index
									:lvar = DATA;
				result = (char *)ifx_var_getdata(&lvar);
				if ((length = ifx_var_getlen(&lvar)) < 0)
				{
					warn("Length of lvarchar < 0");
				}
				if (result == 0)
				{
					/* Franky Wong <fwong@seattletimes.com> */
					result = "";
					length = 0;
				}
				/**
				** FW 2002-05-12: Franky Wong <fwong@seattletimes.com>.
				** JL 2002-12-06: Problem resurfaced because of faulty fix
				** and reported by Mike Langen <mike.langen@tamedia.ch>.
				** New test t/t93lvarchar.t should prevent reoccurrences.
				** Empirical evidence on Solaris 2.6 with CSDK 2.10.UC1
				** (ESQL/C 9.16.UC1) shows that the LVARCHAR variable is
				** supplied with 2 NULs '\0' at the end, and both are
				** counted in the length.  This is also found on Solaris
				** 2.7 with CSDK 2.80.UC1 (ESQL/C 9.52.UC1).  The test
				** below corrects for this.  I don't know whether this is
				** really the way it should be according to the specs; the
				** manuals do not cover such fine details.  Also, Solaris
				** is bad (good?) at having NULs in convenient places; the
				** fix may not work properly on other platforms.
				*/
				if (length >= 2 && result[length-1] == '\0' && result[length-2] == '\0')
					length -= 2;
				break;
#endif	/* SQLLVARCHAR */

$endif; -- IUS_DATATYPES

			case SQLVCHAR:
#ifdef SQLNVCHAR
			case SQLNVCHAR:
#endif /* SQLNVCHAR */
				/* These types will always fit into a 256 character string */
				/* NB: VARCHAR strings always retain trailing blanks */
				EXEC SQL GET DESCRIPTOR :nm_obind VALUE :index
						:coldata = DATA;
				result = coldata;
				length = strlen(result);
				/* warn("VARCHAR Data: %d <<%s>>\n", length, result); */
				break;

			case SQLCHAR:
#ifdef SQLNCHAR
			case SQLNCHAR:
#endif /* SQLNCHAR */
				/**
				** NB: CHAR strings have trailing blanks (which are added
				** automatically by the database) removed by byleng() etc.
				*/
#if ESQLC_VERSION == 500 || ESQLC_VERSION == 501
				/**
				** There's a bug in 5.00 and 5.01 which means that GET
				** DESCRIPTOR does not work with 'char *' as the receiving
				** column.  This is fixed in 5.02.  This code works around
				** that bug by using character arrays instead of 'char *'
				** to receive the data.  This works because sizeof(array)
				** is not the same as sizeof(&array[0]), even though in
				** every other context, array decays to &array[0].
				*/
				if (collength < 256)
				{
					EXEC SQL GET DESCRIPTOR :nm_obind VALUE :index
							:coldata = DATA;
					result = coldata;
				}
				else
				{
					EXEC SQL GET DESCRIPTOR :nm_obind VALUE :index
										:coldata = DATA;
					result = longchar;
				}
#else
				if (collength < 256)
					result = coldata;
				else
				{
					/* Placate bloody-minded MSVC and C++ compilers */
					result = (char *)malloc(collength + 1);
					if (result == 0)
						die("%s::st::dbd_ix_st_fetch: malloc failed\n", dbd_ix_module());
				}
				EXEC SQL GET DESCRIPTOR :nm_obind VALUE :index
						:result = DATA;
#endif /* ESQLC_VERSION in {500, 501} */
				/* Conditionally chop trailing blanks */
				length = strlen(result);
				if (DBIc_is(imp_sth, DBIcf_ChopBlanks))
					length = byleng(result, length);
				result[length] = '\0';
				/* warn("Character Data: %d <<%s>>\n", length, result); */
				break;

			case SQLTEXT:
			case SQLBYTES:
				/* warn("fetch: processing blob\n"); */
				blob_locate(&blob, BLOB_IN_MEMORY);
				EXEC SQL GET DESCRIPTOR :nm_obind VALUE :index
						:blob = DATA;
				result = blob.loc_buffer;
				length = blob.loc_size;
				/* Warning - this data is not null-terminated! */
				/* warn("Blob Data: %d <<%*.*s>>\n", length, length, length,
				   result); */
				/* Data has been passed to Perl; mark it as such! */
				blob.loc_buffer = 0;
				blob_release(&blob, 0);	/* 0 => do not delete files */
				break;

			default:
				warn("%s - Unknown type code: %ld\n"
					  "(This type is probably IUS-specific and is not supported yet.)\n"
					  "coltype = %ld, collength = %ld, colind = %ld, colname = %s\n"
						"-- value treated as NULL!\n",
					  function, coltype, coltype, collength, colind, colname);
				length = 0;
				result = coldata;
				result[length] = '\0';
				break;
			}

			if (sqlca.sqlcode < 0)
			{
				dbd_ix_sqlcode(imp_sth->dbh);
				*result = '\0';
			}

			sv_setpvn(sv, result, length);
			if (result != coldata)
			{
#if ESQLC_VERSION == 500 || ESQLC_VERSION == 501
				if (result != longchar)
#endif /* ESQLC_VERSION in {500, 501} */
					switch (coltype)
					{
$ifdef IUS_DATA_TYPES;
#ifdef SQLLVARCHAR
					case SQLLVARCHAR:
						if (ifx_var_dealloc(&lvar) < 0)
						{
							warn("Having problems freeing lvarchar");
						}
						break;
#endif	/* defined... */
$endif; -- IUS_DATATYPES
					case SQLBYTES:
					case SQLTEXT:
						break;
					default:
					free(result);
						break;
					}
			}
		}
	}
	dbd_ix_exit(function);
	return(av);
}

/* Open a cursor */
static int
dbd_ix_open(imp_sth_t *imp_sth)
{
	static const char function[] = "dbd_ix_open";
	EXEC SQL BEGIN DECLARE SECTION;
	char           *nm_cursor = imp_sth->nm_cursor;
	char           *nm_ibind = imp_sth->nm_ibind;
	EXEC SQL END DECLARE SECTION;

	dbd_ix_enter(function);
	assert(imp_sth->st_state == Declared || imp_sth->st_state == Opened ||
			imp_sth->st_state == NoMoreData);
	/* Close currently open cursors - MODE ANSI databases give error otherwise */
	if (imp_sth->st_state == Opened)
	{
		dbd_ix_close(imp_sth);
		if (sqlca.sqlcode < 0)
		{
			dbd_ix_exit(function);
			return 0;
		}
	}
	assert(imp_sth->st_state == Declared || imp_sth->st_state == NoMoreData);

	if ((imp_sth->st_type != SQ_INSERT) && (imp_sth->n_icols > 0) )
		EXEC SQL OPEN :nm_cursor USING SQL DESCRIPTOR :nm_ibind;
	else
		EXEC SQL OPEN :nm_cursor;
	dbd_ix_sqlcode(imp_sth->dbh);
	dbd_ix_savesqlca(imp_sth->dbh);
	if (sqlca.sqlcode < 0)
	{
		dbd_ix_exit(function);
		return 0;
	}
	imp_sth->st_state = Opened;
	if (imp_sth->dbh->is_modeansi == True)
		imp_sth->dbh->is_txactive = True;
	imp_sth->n_rows = 0;
	dbd_ix_exit(function);
	return 1;
}

/* Parse statement for name of database -- what a pain! */
static void
dbd_ix_setdbname(const char *kw1, const char *kw2, imp_sth_t *sth)
{
	static const char function[] = "dbd_ix_setdbname";
	/**
	** Scan through statement string, skipping comments ('{}' and '--\n'
	** style), seeking (case-insensitively) the text of kw1 as the first
	** word in the statement, and kw2 (if not null) as the second word in
	** the statement.  The required database name is the third word in the
	** statement.  Pain!  Oh the pain!  Why can't I have the database name
	** returned to me by Informix?  About the only mercy is that we know
	** that there is a major problem if the keywords are not found.
	** OK: we created sqltoken() to handle this!
	*/
	/* Where's the statement text? */
	char *tok = SvPV(sth->st_text, na);
	char *end = tok;

	dbd_ix_enter(function);
	tok = sqltoken(end, &end);
	/* Should be same as kw1 -- give or take case */
	if (DBIc_DBISTATE(sth)->debug >= 6)
		warn("%s: %s = <<%*.*s>>\n", function, kw1, end - tok, end - tok, tok);
	/* What's the Perl case-insensitive string comparison routine called? */
	if (kw2 != 0)
	{
		tok = sqltoken(end, &end);
		if (DBIc_DBISTATE(sth)->debug >= 6)
			warn("%s: %s = <<%*.*s>>\n", function, kw2, end - tok, end - tok, tok);
		/* Should be same as kw2 -- give or take case */
	}
	tok = sqltoken(end, &end);
	if (DBIc_DBISTATE(sth)->debug >= 6)
		warn("%s: dbn = <<%*.*s>>\n", function, end - tok, end - tok, tok);
	/* Should be the database name! */
	/* Must handle this correctly! */
	if (sth->dbh->database != 0)
		SvREFCNT_dec(sth->dbh->database);
	sth->dbh->database = newSVpv(tok, end - tok);
	if (DBIc_DBISTATE(sth)->debug >= 4)
		warn("new database name <<%s>>\n", SvPV(sth->dbh->database, na));
	dbd_ix_exit(function);
}

static int
dbd_ix_exec(imp_sth_t *imp_sth)
{
	static const char function[] = "dbd_ix_exec";
	EXEC SQL BEGIN DECLARE SECTION;
	char           *nm_cursor = imp_sth->nm_cursor;
	char           *nm_stmnt = imp_sth->nm_stmnt;
	char           *nm_ibind = imp_sth->nm_ibind;
	EXEC SQL END DECLARE SECTION;
	imp_dbh_t *dbh = imp_sth->dbh;
	int rc = 1;
	Boolean exec_stmt = True;

	dbd_ix_enter(function);

	if (imp_sth->st_type == SQ_BEGWORK)
	{
		/* BEGIN WORK in a logged non-ANSI database with AutoCommit Off */
		/* will fail because we're already in a transaction. */
		/* Pretend it succeeded. */
		if (dbh->is_loggeddb == True && dbh->is_modeansi == False)
		{
			if (DBI_AutoCommit(dbh) == False)
			{
				dbd_ix_debug(1, "%s - AUTOCOMMIT Off => Pretend to BEGIN WORK succesfully\n", function);
				exec_stmt = False;
				sqlca.sqlcode = 0;
			}
		}
	}

	if (exec_stmt == True)
	{
		if (imp_sth->n_icols <= 0)
		{
			dbd_ix_debug(2, "---- EXECUTE %s - no parameters\n", nm_stmnt);
			EXEC SQL EXECUTE :nm_stmnt;
		}
		else if (imp_sth->st_type == SQ_INSERT && imp_sth->is_insertcursor == True)
		{
			dbd_ix_debug_2(2, "---- PUT %s USING %s\n", nm_cursor, nm_ibind);
			EXEC SQL PUT :nm_cursor USING SQL DESCRIPTOR :nm_ibind;
		}
		else
		{
			dbd_ix_debug_2(2, "---- EXECUTE %s USING %s\n", nm_stmnt, nm_ibind);
			EXEC SQL EXECUTE :nm_stmnt USING SQL DESCRIPTOR :nm_ibind;
		}
	}

	dbd_ix_sqlcode(dbh);
	dbd_ix_savesqlca(dbh);
	if (sqlca.sqlcode < 0)
	{
		dbd_ix_exit(function);
		return 0;
	}

	/**
	** Here we need to analyse what was done...
	** BEGIN WORK, COMMIT WORK, ROLLBACK WORK are important.
	** So are DATABASE, CLOSE DATABASE, CREATE DATABASE.
	** For SE, we could use START DATABASE or ROLLFORWARD DATABASE.
	** Note that although it is unlikely to happen with Perl, the DATABASE
	** operations other than CLOSE DATABASE can have a '?' place of the
	** database name, so the same statement could be executed several times
	** with different names, and the name is then available in nm_ibind.
	** On the other hand, if it is not in nm_ibind, it has to be extracted
	** from the statement string itself.
	*/
	imp_sth->n_rows = sqlca.sqlerrd[2];
	switch (imp_sth->st_type)
	{
	case SQ_BEGWORK:
		dbd_ix_debug(3, "%s: BEGIN WORK\n", dbd_ix_module());
		dbh->is_txactive = True;
		assert(dbh->is_loggeddb == True);
		/* Even BEGIN WORK has to be committed if AutoCommit is On */
		if (DBI_AutoCommit(dbh) == True)
		{
			dbd_ix_debug(1, "%s - AUTOCOMMIT On => COMMIT WORK\n", function);
			rc = dbd_ix_commit(dbh);
		}
		break;
	case SQ_COMMIT:
		dbd_ix_debug(3, "%s: COMMIT WORK\n", dbd_ix_module());
		dbh->is_txactive = False;
		assert(dbh->is_loggeddb == True);
		/* In a logged database with AutoCommit Off, do BEGIN WORK */
		if (dbh->is_modeansi == False && DBI_AutoCommit(dbh) == False)
		{
			dbd_ix_debug(1, "%s - AUTOCOMMIT Off => BEGIN WORK\n", function);
			rc = dbd_ix_begin(dbh);
		}
		break;
	case SQ_ROLLBACK:
		dbd_ix_debug(3, "%s: ROLLBACK WORK\n", dbd_ix_module());
		dbh->is_txactive = False;
		assert(dbh->is_loggeddb == True);
		/* In a logged database with AutoCommit Off, do BEGIN WORK */
		if (dbh->is_modeansi == False && DBI_AutoCommit(dbh) == False)
		{
			dbd_ix_debug(1, "%s - AUTOCOMMIT Off => BEGIN WORK\n", function);
			rc = dbd_ix_begin(dbh);
		}
		break;
	case SQ_DATABASE:
		dbh->is_txactive = False;
		dbd_ix_setdbtype(dbh);
		dbd_ix_setdbname("DATABASE", 0, imp_sth);
		break;
	case SQ_CREADB:
		dbh->is_txactive = False;
		dbd_ix_setdbtype(dbh);
		dbd_ix_setdbname("CREATE", "DATABASE", imp_sth);
		break;
	case SQ_STARTDB:
		dbh->is_txactive = False;
		dbd_ix_setdbtype(dbh);
		dbd_ix_setdbname("START", "DATABASE", imp_sth);
		break;
	case SQ_RFORWARD:
		dbh->is_txactive = False;
		dbd_ix_setdbtype(dbh);
		dbd_ix_setdbname("ROLLFORWARD", "DATABASE", imp_sth);
		break;
	case SQ_CLSDB:
		/**
		** CLOSE DATABASE -- no transactions, no autocommit, etc.
		** With 6.00 upwards, the connection to the server still exists
		** With 5.00, if the database was remote, then the connection
		** is broken by close database; otherwise, it remains.  Assume
		** it still exists until further notice...
		*/
		dbh->is_txactive = False;
		dbh->is_modeansi = False;
		dbh->is_onlinedb = False;
		dbh->is_loggeddb = False;
		DBIc_set(dbh, DBIcf_AutoCommit, False);
		SvREFCNT_dec(dbh->database);
		dbh->database = 0;
		break;
	default:
		if (dbh->is_modeansi)
			dbh->is_txactive = True;
		/* COMMIT WORK for MODE ANSI databases when AutoCommit is On */
		if (dbh->is_modeansi == True && DBI_AutoCommit(dbh) == True)
		{
			dbd_ix_debug(1, "%s - AUTOCOMMIT On => COMMIT WORK\n", function);
			rc = dbd_ix_commit(dbh);
		}
		break;
	}

	DBIc_on(imp_sth, DBIcf_IMPSET);	/* Qu'est que c'est? */
	dbd_ix_exit(function);
	return rc;
}

/*
** Execute the statement.
** - OPEN the cursor for a SELECT or cursory EXECUTE PROCEDURE.
** - EXECUTE the statement for anything else.
** Remember that dbd_st_execute() must return:
**      -2 or smaller   => error
**      -1              => unknown number of rows affected
**       0 or greater   => known number of rows affected
** DBD::Informix will not return -1, though there's at least half an
** argument for returning -1 after dbd_ix_open() is called.
*/
int
dbd_ix_st_execute(SV *sth, imp_sth_t *imp_sth)
{
	static const char function[] = "dbd_ix_st_execute";
	dTHR;
	int rv;
	int rc;

	dbd_ix_enter(function);

	if ((rc = dbd_db_setconnection(imp_sth->dbh)) == 0)
	{
		assert(sqlca.sqlcode < 0);
		dbd_ix_sqlcode(imp_sth->dbh);
		dbd_ix_exit(function);
		return(sqlca.sqlcode);
	}

	if (imp_sth->st_type == SQ_SELECT)
		rc = dbd_ix_open(imp_sth);
#ifdef SQ_EXECPROC
	else if (imp_sth->st_type == SQ_EXECPROC && imp_sth->n_ocols > 0)
		rc = dbd_ix_open(imp_sth);
#endif /* SQ_EXECPROC */
	else
	{
		rc = 1;
		/* only open cursor if it is not currently open, otherwise it flushes */
		if ((imp_sth->st_type == SQ_INSERT) &&
			(imp_sth->is_insertcursor == True) &&
			(imp_sth->st_state != Opened))
			rc = dbd_ix_open(imp_sth);
		if (rc)
		    rc = dbd_ix_exec(imp_sth);
	}

	/* Map returned values from dbd_ix_exec and dbd_ix_open */
	if (rc == 0)
	{
		/* Statement failed -- return the error code */
		assert(sqlca.sqlcode < 0);
		dbd_ix_sqlcode(imp_sth->dbh);
		rv = sqlca.sqlcode;
	}
	else
	{
		/**
		** Statement succeeded.  Don't forget about MODE ANSI database and
		** an UPDATE which does not alter any rows returning SQLNOTFOUND.
		** MODE ANSI problem found by Chuck.Collins@zool.Airtouch.com
		*/
		rv = sqlca.sqlerrd[2];
		assert((sqlca.sqlcode == 0 || sqlca.sqlcode == SQLNOTFOUND) && rv >= 0);
	}

	dbd_ix_exit(function);
	return(rv);
}

int
dbd_ix_st_rows(SV *sth, imp_sth_t *imp_sth)
{
	return(imp_sth->n_rows);
}

/*
** Map the DBI standard type numbers (SQL_NUMERIC, etc) to Informix types.
** Cribbed from DBD::Oracle v1.13, file dbdimp.c, function ora_sql_type().
*/
static int
ix_sql_type(int sql_type)
{
	int ix_type;

	/* XXX should detect DBI reserved standard type range here */

	switch (sql_type)
	{
	case SQL_NUMERIC:
	case SQL_DECIMAL:
	case SQL_INTEGER:
	case SQL_BIGINT:
	case SQL_TINYINT:
	case SQL_SMALLINT:
	case SQL_FLOAT:
	case SQL_REAL:
	case SQL_DOUBLE:
	case SQL_VARCHAR:
	case SQL_CHAR:
	case SQL_DATE:
	case SQL_TIME:
	case SQL_TIMESTAMP:
		ix_type = SQLCHAR;       /* Informix CHAR */
		break;

	case SQL_BINARY:
	case SQL_VARBINARY:
	case SQL_LONGVARBINARY:
		ix_type = SQLBYTES;      /* Informix BYTE blob */
		break;

	case SQL_LONGVARCHAR:
		ix_type = SQLTEXT;       /* Informix TEXT blob */
		break;

	default:
		ix_type = SQLCHAR;
		break;
	}
	return(ix_type);
}

/*
** Validate Informix type number.
** List cribbed from constant() in Informix.xs and should match that list
*/
static int
valid_ix_type(int val_type)
{
	int rc = 1;
	switch (val_type)
	{
	case SQLSMINT:
	case SQLINT:
	case SQLSERIAL:
	case SQLINT8:
	case SQLSERIAL8:
	case SQLDECIMAL:
	case SQLMONEY:
	case SQLFLOAT:
	case SQLSMFLOAT:
	case SQLCHAR:
	case SQLVCHAR:
	case SQLNCHAR:
	case SQLNVCHAR:
	case SQLLVARCHAR:
	case SQLBOOL:
	case SQLDATE:
	case SQLDTIME:
	case SQLINTERVAL:
	case SQLBYTES:
	case SQLTEXT:
	case SQLSET:
	case SQLMULTISET:
	case SQLLIST:
	case SQLROW:
	case SQLCOLLECTION:
	case SQLUDTVAR:
	case SQLUDTFIXED:
	/*
	** In the Informix system catalog, CLOB and BLOB types are simply
	** specific cases of a fixed UDT.  They seem to have extended ids
	** 10, 11.  However, they are also base types (opaque), and there
	** is storage information for them in the create table statement
	** (a PUT clause after the column list).  We need to handle them
	** specially, so define unique values for them in dbdimp.h.
	*/
	case DBD_IX_SQLCLOB:
	case DBD_IX_SQLBLOB:
		rc = 1;
		break;

	default:
		rc = 0;
		break;
	}
	return(rc);
}

/*
** Convert ix_type attribute, or sql_type value, to Informix type number
**
** if (attribs includes { ix_type => xxx }, then extract val_type = xxx.
** else if (sql_type != 0) val_type = ix_type_matching_sql_type(sql_type);
** else val_type = SQLVCHAR;
**
** Cribbed from DBD::Oracle v1.13, file dbdimp.c, function dbd_bind_ph().
*/
static int
dbd_ix_st_bind_type(IV sql_type, SV *attribs)
{
	static const char function[] = "::st::dbd_ix_st_bind_type";
	int val_type = SQLVCHAR;
	dbd_ix_enter(function);

	dbd_ix_debug_l(4, "---- dbd_ix_st_bind_type(): sql_type = %ld\n", sql_type);

	if (attribs)
	{
		SV **svp = hv_fetch((HV*)SvRV(attribs), "ix_type", sizeof("ix_type")-1, 0);
		if (svp != NULL)
		{
			val_type = SvIV(*svp);
			dbd_ix_debug_l(4, "---- dbd_ix_st_bind_type(): val_type = $attribs{ix_type} = %ld\n", val_type);
			if (!valid_ix_type(val_type))
				croak("Can't bind ix_type %d not supported", val_type);
			if (sql_type)
				croak("Can't specify both TYPE (%d) and ix_type (%d)",
						sql_type, val_type);
		}
	}
	if (sql_type)
	{
		val_type = ix_sql_type(sql_type);
		dbd_ix_debug_l(4, "---- dbd_ix_st_bind_type(): mapped SQL type to val_type = %ld\n", val_type);
	}
	dbd_ix_exit(function);
	return(val_type);
}


/* Called extensively by execute method when it is given parameters! */
int
dbd_ix_st_bind_ph(SV *sth, imp_sth_t *imp_sth, SV *param, SV *value,
	IV sql_type, SV *attribs, int is_inout, IV maxlen)
{
	static const char function[] = "::st::dbd_ix_st_bind_ph";
	int rc;
	int val_type;

	dbd_ix_enter(function);
	if (is_inout)
		croak("%s() - inout parameters not implemented\n", function);
	val_type = dbd_ix_st_bind_type(sql_type, attribs);
	rc = dbd_ix_bindsv(imp_sth, SvIV(param), val_type, value);
	dbd_ix_exit(function);
	return(rc);
}

int
dbd_ix_st_blob_read(SV *sth, imp_sth_t *imp_sth, int field, long offset,
					long len, SV *destrv, long destoffset)
{
	croak("%s::st::dbd_ix_st_blob_read() - not implemented\n", dbd_ix_module());
	return -1;
}

/* -------------- End of $RCSfile: dbdimp.ec,v $ -------------- */