File: dbdump.c

package info (click to toggle)
virtuoso-opensource 6.1.4%2Bdfsg1-7
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 245,116 kB
  • sloc: ansic: 639,631; sql: 439,225; xml: 287,085; java: 61,048; sh: 38,723; cpp: 36,889; cs: 25,240; php: 12,562; yacc: 9,036; lex: 7,149; makefile: 6,093; jsp: 4,447; awk: 1,643; perl: 1,017; ruby: 1,003; python: 329
file content (6975 lines) | stat: -rw-r--r-- 226,071 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
/*
 *  $Id: dbdump.c,v 1.5.2.2 2009/05/14 18:32:25 source Exp $
 *
 *  This file is part of the OpenLink Software Virtuoso Open-Source (VOS)
 *  project.
 *
 *  Copyright (C) 1998-2009 OpenLink Software
 *
 *  This project is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU General Public License as published by the
 *  Free Software Foundation; only version 2 of the License, dated June 1991.
 *
 *  This program is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 *
 */

/* #define DBDUMP_VERSION "0.974"  16-MAY-1997 */
/* #define DBDUMP_VERSION "0.975" 06-NOV-1997 */
/* #define DBDUMP_VERSION "0.976" 28-JAN-1998 */
/* #define DBDUMP_VERSION "0.977" 29-JAN-1998 */
/* #define DBDUMP_VERSION "0.978" 17-MAR-1998 */
/* #define DBDUMP_VERSION "0.979" 29-MAR-1998 */
#define DBDUMP_VERSION "0.980"	/* 22-JUN-1998 */

/*
   dbdump - Database Dump using ODBC API calls.

   Programmed in January 1997 - March 1998 by Antti Karttunen

   A generic ODBC tool for dumping out both the schema and
   the contents of the database, in the format appropriate
   for the later feeding to the same or another database
   with the ISQLO utility. That is, the format used is the series
   of SQL-statements CREATE TABLE, CREATE INDEX and INSERT
   terminated by a semicolon.

   Currently tested only with Kubl and Microsoft Access.
   To work with Kubl requires the KUBL ODBC driver version 0.92b
   or later.

   For more info compile and execute without arguments, and
   with the option -h also. (See the end of this module!)

   First version was 0.971

   CHANGES since 8-FEB-1997

   08-FEB-1997 AK   Added issuing of DROP TABLE and DROP INDEX commands
                    when needed.
                    Added select override feature.
                    Corrected the counting of tables in the main loop.
                    (Previously duplicate values were given).

   10-FEB-1997 AK   Added foreach blob output for LONG VARCHAR and
                    LONG VARBINARY columns. Currently allows only
                    one blob per row to be inserted in this way.
                    Version is now 0.972.

   20-FEB-1997 AK   Added checking for object_id index definitions.
                    Detects these only if the version 0.94b or newer
                    of WIODBC.DLL is used. (sqlext.c was respectively
                    changed. Uses own kludgous private index type 9
                    See define SQL_INDEX_OBJECT_ID later in this file.).

                    Made C-style string literal escaping a default.
                    Now you get with a single -e the same effect as
                    previously with double -ee.
                    Use option -n if you want to disable C-style escaping,
                    and use just standard SQL-escaping for single quotes.
                    Changed version number to 0.973

                    Changed after sleeping and reading the documentation
                    the definition of SQL_INDEX_OBJECT_ID to 8.
                    Now the ordinary SQL_INDEX_CLUSTERED, etc. values
                    are plussed to 8, so CLUSTERED and OBJECT_ID can
                    occur at the same time, which is needed when dumping
                    the tables that have real object_id indices.
                    An excerpt from KUBLMAN.DOC clarifies the decision:

   08-MAR-1997 AK   Added a piece of code into main for checking that
                    if the Kubl ODBC driver is greater than or equal
                    0.96, then the lengths of strings returned for bound
                    columns and strings got with SQLGetData are counted
                    without the terminating zero byte.


   Index options can be specified in a CREATE INDEX statement and in
   the PRIMARY KEY clause of a CREATE TABLE.
   The default for a primary key is to cluster it in its own cluster,
   to make it unique and not to make it an object ID.  Specifying
   CLUSTERED will cause the primary key to be clustered by value,
   i.e. to be non-contiguous, mixed with any other keys with values
   in the same range.  Specifying OBJECT_ID together with CLUSTERED
   makes this an object ID key. In this case it should have only one
   key part, the ID, whichever column that is.

   The default for a non-primary key is non-unique, clustered separate
   from other keys and non-object ID.  Specifying CLUSTERED will cluster
   the key by value, dispersing it among other keys with similar key part
   values.  The CLUSTERED OBJECT_ID combination makes this key an object
   ID key.  The UNIQUE option can be given to enforce uniqueness of key
   values.

   The primary key does not have an explicit name in the declaration. It
   is given the same name as the table and thus no other key can be named
   after the table.

   If an UNDER clause appears in CREATE TABLE there may not be a
   PRIMARY KEY since that will be inherited from the table given as
   super table in the UNDER clause.

Further, a note about Object IDs:

   An object ID is a special data type that encodes an identity based
   reference. The object ID is logically composed of the ID, a variable
   length binary string and of a 4 byte class specification that encodes
   the class of the referenced entity.
   Only the ID part of an object ID is meaningful in  comparing ID's.
   An object, i.e. row of any table can be located given its object ID
   by searching  the object ID index cluster which holds all 'object ID'
   keys.
   A key can have the object ID property.  If so, its first key part
   should be of the object ID type and should uniquely identify the
   object.
   Any object that belongs to a table which has an object ID key can be
   retrieved without specification of table by using the ID.

TO BE IMPLEMENTED, how to dump "the first key part that should be of the
object ID type", so that it will retain its object ID nature also when
later loaded through ISQL. (Should we use make_oid function?)
How to detect here that we have a DV_G_REF_CLASS, SQL_C_OID or whatever
object, instead of an ordinary string, as conversion to SQL_C_CHAR will
show it as any ordinary string? (with 4 byte class specification cut off)
(See dv_to_place function is cliuti.c to see how it is handled in that
 case.)

  16-MAY-1997  AK  Version changed to 0.974.
                   Added the definitions of Kubl Extension Option Values
                   SQL_MODE_READ_ONLY_PERMANENTLY, SQL_INDEX_OBJECT_ID
                   and SQL_INDEX_OBJECT_ID_STR into kublext(w).h
                   so removed from here.
                   Corrected also list_data_sources to return
                   correct string when compiled on Unix platforms.

                   Added n+1 SCP and UCP cast-macros make code compilable
                   in C++ as well.

  19-MAY-1997  AK  Some minor bugfixes.
  21-MAY-1997  AK  Now prints precision (in parenthesis) of VARCHAR
                   columns also.

  06-NOV-1997  AK  Version 0.975. Corrected the printing of UNDER
                   keyword in table definitions in case of subtables
                   with no additional columns to supertable.
                   (e.g. CREATE TABLE SUCCUBUS(UNDER INCUBUS); )

                   Replaced all calls to malloc and strdup with
                   our own calls chemalloc and chestrdup, so
                   checking that the memory is not exhausted.
                   With a lots of list linkages where only a
                   slight screw-up could produce circularities
                   or ever-growing list-structures, this is
                   not too prudent.

                   User can now specify multiple,
                   comma-and/or-space-separated tablename patterns
                   in tablename argument.
                   E.g. if the user has given
                          tablequalifier=a
                          tableowner=b
                          tablename=x%,p.q.z%,k.w,l..y
                   then following search patterns are effectively
                   given to SQLTables:
                          a.b.x%
                          p.q.z%
                          a.k.w
                          l..y
                   Of course current Kubl doesn't care a hitch about
                   those prefixes, tablequalifier and tableowner,
                   but some other datasource might care.

                   In case get_real_supertable detects a supertable
                   that has not matched to the patterns given by the
                   user, it is also loaded to all_tables_list.

                   However, tables included in this way do not appear
                   in the output, unless the user explicitly gives
                   T, I, and/or C options, Table definitions, Indices
                   and Contents respectively.

  15-NOV-1997  AK  More new stuff. Specifiers init=, unquoted_columns=
                   etc. Options -p and -+p for plain and prefixed
                   table names.

  28-JAN-1998  AK  Version 0.976.
                   Added -P option (Produce Primary Key by any means)
                   and for that, the new functions
                         get_table_bestrow_columns
                   and   find_first_index_like

                   Modified print_table_definition_banner respectively,
                   as well as added bestrow_columns element to
                   struct tabledeflist.

                   New option -N for "Nicer Output", e.g. with
                   indented table definitions, with one column per line,
                   etc.

                   Added also universal_transfer_flag
                   and for that added new experimental templates
                     transfer_html_page_string1 and
                     transfer_html_page_string2
                   to the end of this source file.
                   Modified output_html_page and output_html_file
                   respectively.

  29-JAN-1998  AK  Version 0.977.
                   Added new_name option, and for
                   substituting its !Q, !O and !N namepart-markers,
                   created function substitute_tablename_expr
                   and str_replace for its needs.

  15 - 17-MAR-1998 AK  Version 0.978.
                   Added DATADEST_TOKEN and TABLELIST_TOKEN
                   into output_html_page and the former also
                   to list_data_sources.

                   Lots of modifications to default template.
                   (E.g. the new optional Data Destination field
                    and its associated username and password fields
                    for the needs of direct table linking).

                   Added direct table linking with functions
                   link_remote_data_source, link_local_and_remote_table
                   do_generic_dest_statement
                   Modified print_table_definition_banner respectively.
                   (print_indexdeflist should be probably modified
                    in the same way).

                   Added last_SQL_state and last_SQL_message fields
                   to struct tabledeflist.

                   Added summary function check_for_failed_tables
                   (which looks for those two fields, possibly set in
                    print_table_definition_banner)

                   Option -a, surround column and index names with
                   doublequotes, implemented.

                   Added Javascript function
                   add_selected_items_to_the_text_elem
                   for the needs of TABLELIST_TOKEN

                   Also set_options_according_to_action
                   which is called on submit, as well as
                   when the SELECT/LIST OPCODE changes.

                   To be done: update the function
                    get_real_supertables to take heed of
                   the new Kubl Table Qualifier and Owner parts
                   (not anymore constant DB and DBA as before)
                   There's also a minor bug in SQLPrimaryKeys
                   in this respect.

                   There are many unnecessary commits
                   after read-operations from the Data Source.
                   They may get removed in the next release.


  29-MAR-1998 AK   Version 0.979.
                   Added the first version of function
                     compose_whole_tablename
                   and for its needs the elements
                     tl_qual_only, tl_own_only and tl_name_only
                   to struct tabledeflist.
                   Note how these new elements will make
                   the call to function divide_tablename_aux
                   unnecessary in many cases.

  22-JUN-1998 YR   Version 0.980
                   Did a quick fix to change behaviour of available
		   tables selection box which caused multiple
		   entries in the selected tables textarea.
		   Removed submit from datasource select.
		   Added some horizontal rules to improve grouping,
		   applied some other quick cosmetics,
		   moved the upper submit button to a more sensible(?)
		   place.
*/



#ifdef UNIX
#define DBDUMP_CGI_LOCATION "dbdump.cgi"	/* Assuming Apache HTTP server. */
#define TRANSFER_PROGRAM_CGI_LOCATION "isqlo.cgi"
#else /* Assuming it is for Microsoft IIS under Windows NT */
#define DBDUMP_CGI_LOCATION "/scripts/dbdump.exe"
#define TRANSFER_PROGRAM_CGI_LOCATION "isqlo.exe"
#endif

/* The above works with Microsoft IIS in Windows NT, when the executable
   dbdump.exe is copied to the directory \InetPub\scripts
   In Unix it should probably be something different.
   If running under Apache Web-server, build the executable with
   the name dbdump.cgi and then reference it with that name from the URL.
   Now assumes that isqlo.cgi or isqlo.exe is copied to the same
   directory as where this is invoked from in cgi-bin usage.
 */

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

#include <Dk.h>
#include <libutil.h>
#include "odbcinc.h"
#include "virtext.h"
#include "timeacct.h"


#define strncasecmp strnicmp
#define strcasecmp  stricmp

/* T should be a string constant, like "poisson"
   If the string S begins with it, then pointer to the next character
   is returned. Otherwise NULL is returned.
   Note how the order of testing is significant. You should first
   check for "foubar" before "fou".
 */
#define string_begins_with(S,T)\
 ( (!strncasecmp(SCP(S),SCP(T),(sizeof((T))-1) )) ? ((S)+(sizeof((T))-1))\
                                                  : NULL)

#ifndef SQL_NO_TOTAL
#define SQL_NO_TOTAL (-4)
#endif

#ifdef UNIX_UDBC
/* At least version 1.0 of libudbc doesn't seem to contain _UDBC_GetFunctions
   Let's define our own dummy macro that returns TRUE for all: */
#define SQLGetFunctions(HDBC_X, API_NUM_X, PTR_TO_FLAG)\
 (( *(PTR_TO_FLAG) = TRUE ), SQL_SUCCESS)
#endif


#define debug_fprintf if(dbdump_debug_level) fprintf
#define DEFAULT_DATASOURCE_IN_UNIX "localhost:1111"
#define DEFAULT_HTML_TEMPLATE_FILE "dbdump.htm"
#define DEFAULT_TRANSFER_TEMPLATE1 "kubltr1.htm"	/* Not actually anywhere */
#define DEFAULT_TRANSFER_TEMPLATE2 "kubltr2.htm"	/* used just as selectors */

#define DATASOURCE_TOKEN "INPUT_DATASOURCE"
#define DATADEST_TOKEN   "INPUT_DATADEST"
#define TABLELIST_TOKEN  "INPUT_TABLES"
#define DEFAULT_CONVERSIONS_TOKEN "DEFAULT_CONVERSIONS"
#define VERSION_TOKEN    "VERSION"


#define NO  !
#define NOT !
#define empty_stringp(X) (!*(X))

#define UCP(X) ((unsigned char *) ((X)))
#define SCP(X) ((char *) ((X)))
#define SWD(X) ((SWORD) (X))

#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif

HDBC hdbc = SQL_NULL_HDBC;
HENV henv = SQL_NULL_HENV;
HSTMT stmt = SQL_NULL_HSTMT;

HDBC datadest_hdbc = SQL_NULL_HDBC;
HSTMT datadest_link_stmt = SQL_NULL_HSTMT;	/* For DB..vd_remote_table(?,?,?) */
HSTMT datadest_gen_stmt = SQL_NULL_HSTMT;	/* For other dest statements, issued with SQLExecDirect */

/* For error messages and like. Will be overwritten with argv[0] in
   the beginning of main. This initial value here serves for seeing
   the version of the program even with strings utility of Unix. */
char *progname = ("Kubl dbdump version " DBDUMP_VERSION);

/* The default values can be overridden in parse_url_query_string. */
char *username = "dba";
char *password = "dba";
char *dest_username = "dba";
char *dest_password = "dba";
char *datasource = NULL;	/* Was: "localhost:1111"; */
char *datadest = NULL;
char *tablequalifier = NULL, *tableowner = NULL;
char *tablename = NULL, *tabletype = NULL;
char *new_name = NULL;

int dbdump_debug_level = 0;
int kubl_mode = 0;		/* Currently affects only how TIMESTAMPS are handled. */
int never_escape_tablenames_in_select = 0;
/* The Access Driver returns varchar columns with the same length as
   what strlen would return for that string (provided that it doesn't
   contain any null bytes between), but the Kubl driver (at least until
   we change it, in case that it is a bug or misfeature) returns them
   with the length strlen(s)+1.
   Now, 8-MAR-1997 wiodbc.dll (version 0.96b) has been changed to
   conform with ODBC, i.e. it returns the length of strings without
   counting the trailing zero-byte.
 */
int varchar_cols_returned_with_length_plus = 0;
unsigned long int getdata_extensions;
int bind_blobs_flag = 0;	/* By default, don't do it. */

int flag_get_list_of_tables = 0;

int web_mode = 0;		/* Is this program used via Web? */
/* When print_blobs_flag is non-zero the blobs are printed out in full. */
int print_blobs_flag = 1;
/* These are swapped automatically in the beginning if we use an
   Old Kubl driver, version less than 0.92: */
int times_conform_to_odbc_flag = 1, times_to_strings_flag = 0;
int verbose_flag = 1;

char *default_insert_mode = "INTO";
char *web_content_type = "text/plain";
#define SELECT_DEFAULT "SELECT * FROM %s"
char *select_statement_template = SELECT_DEFAULT;
char *init_statement = NULL;
char *foreach_end_token = "END";
char *foreach_blob_token = "BLOB";

char *unquoted_columns = NULL;

int only_table_definitions_flag = 0;
int only_index_definitions_flag = 0;
int only_contents_flag = 0;
int auto_only_table_definitions_flag = 0;
int auto_only_index_definitions_flag = 0;
int auto_only_contents_flag = 0;
int dont_issue_drop_commands_flag = 0;

#define DEFAULT_MAXLINELEN "160"
#define DEFAULT_MAXHEXLEN  "64"

/* If set to zero by user, then these have no effect.
   First initialized to default values in the beginning of main
   then later might be overridden in parse_url_query_string: */
long maxlinelength_for_foreach = 0;	/* DEFAULT_MAXLINELEN; */
long maxhexlength_for_foreach = 0;	/* DEFAULT_MAXHEXLEN;  */

int nicer_output_flag = 0;

int use_foreach_for_blobs_flag = 1;
int use_backslash_escapes_in_strings_flag = 1;	/* Now on by default. */
/* Normally singlequotes are escaped as \47, unless this is specified
   as 1, in which case they are escaped by doubling the singlequote: */
int use_singlequote_escape = 0;

unsigned char prefix_with_flag = 0, surround_with_flag = 0;
/* Normally we use SQLColumns, unless this is on. */
int use_sql_describe_flag = 0;
int primary_key_by_all_means_flag = 0;
int kubl_default_conversions_flag = 0;

/* Transfer Schema and/or data to another DBMS, but let the User edit it
   before that, in HTML-form. */
int universal_transfer_flag = 0;
int vd_procedures_flag = 0;
int all_or_nothing_flag = 0;	/* If non-zero, then all linkages must succeed. */

int use_table_prefixes_flag = 1;
int use_table_prefixes_flag_given = 0;

int list_data_sources_flag = 0;
int dump_html_template_file_flag = 0;
int output_html_file (char *filename);

#define IF_ERR_GO(stmt, tag, foo) \
  if (SQL_ERROR == foo)  { \
    print_error (SQL_NULL_HENV, SQL_NULL_HDBC, stmt);  \
    goto tag; \
 }


#define MAX_COLS    313
#define DEFAULT_MAXCOLUMN_WIDTH   3500
#define CHARCOL_LEN 80+1
#define MAXCOLNAME  CHARCOL_LEN

int maxcolumn_width = DEFAULT_MAXCOLUMN_WIDTH;

#define TMP1_LEN ((MAX_COLS*(CHARCOL_LEN+1))+11)	/* Enough? 25677 bytes */
char tmp1[TMP1_LEN + 1];	/* A global string buffer used by many functions */



#define MAX_CONVERSIONS 25


/*
   If kubl_default_conversions_flag is specified (option -K),
   conv_types_table is set to the beginning of this table,
   otherwise it points by default to the end of these
   definitions.
   Because get_converted_type loops the table from the end to the
   beginning, user's mappings (which will be copied after these
   default ones) will override any mappings given here.
   E.g. user can give CONVSRC1=TINYINT & CONVDST1=TINYINT
   to apply otherwise the conversions given here, BUT still keeping
   TINYINT as TINYINT (for whatever perverted reason).
 */

char *kubl_default_conv_types[(2 * (MAX_CONVERSIONS + 1)) + 16] = {
/*         SRC TYPE  ->   KUBL TYPE */
				/*  0 */ "DUMMY", "RUMMY",
				/* Pair 0-1, not used. */
/*  2 */ "TIME", "DATE",
/*  4 */ "BIT", "SMALLINT",
					/*  6 */ "BIT VARYING", "INTEGER",
					/* Really? */
/*  8 */ "BINARY", "CHAR",
/* 10 */ "VARBINARY", "VARCHAR",
/* 12 */ "BIGINT", "CHAR",
					/* 14 */ "TINYINT", "SMALLINT",
					/* SEE THE NOTE BELOW ABOUT conv_types_table ! */
				/* 16 */ NULL, NULL
				/* The rest should be NULL's */
};

#define N_KUBL_DEFAULT_CONVERSIONS 7	/* This should be half of the index of the last non-NULL in above table */

/* Was like this:
char *conv_types_table[2*(MAX_CONVERSIONS+1)] = { NULL };
 */
/* Instead, is now defined like below, pointing either to the beginning
   or to the last used place (index 14) of the above table, depending
   from the flag kubl_default_conversions_flag */
char **conv_types_table = &kubl_default_conv_types[2 * N_KUBL_DEFAULT_CONVERSIONS];


int n_conv_types = 0;		/* This indexes the "table" conv_types_table above, is always even. Indices 0 & 1 are not used. */




typedef struct _out
{
  char *o_buffer;		/* Buffer for SQLBindCol */
  SQLLEN o_col_len;		/* The length of the column on current row */
} stmt_out_t;


SWORD n_out_cols;
stmt_out_t out_cols[MAX_COLS + 1];


struct tabledeflist
{
  struct tabledeflist *next;
  char *name;
  char *tl_qual_only;		/* These three new slots added 29.March 1998 */
  char *tl_own_only;		/* For storing the three parts of tablename */
  char *tl_name_only;		/* returned by SQLTables */
  char *columns;		/* A list of columns: colname1,colname2,etc in string */
  char *all_columns;		/* Similar as above, but including cols of supers */
  char *bestrow_columns;	/* Columns got with SQLSpecialColumns if -P used */
  char *primary_key_name;	/* The name of the primary key. */
  char *primary_key_def;	/* A list of colnames: colname1,colname3,etc. */
  char *primary_key_type;	/* Possible index type like CLUSTERED, etc. */
  char *super_table;		/* Name of the super table if applicable. (KUBL) */
  char *insert_mode;		/* One of the: "INTO", "SOFT" or "REPLACING" */

  char *last_SQL_state;		/* Used only with direct linkage. */
  char *last_SQL_message;	/* The last SQL_error_state and SQL_error_message from the datadest, if statement failed. */

/* Included as supertable of subtable specified, but not itself specified
   by the user? */
  int automatically_included;
  /* In principle the following should contain the count of blob columns
     in this table. Instead it nowadays contains zero or the SQL-type
     of the first blob column encountered: */
  int contains_blobs;
  struct coldeflist *col_defs;
  struct indexdeflist *index_defs;
  struct tabledeflist *super_tl;
  struct subtablelist *sub_tables;
};

struct indexdeflist
{
  struct indexdeflist *next;
  char *index_name;		/* This is also duplicated in index_def. */
/* index_def will contain "CREATE INDEX name ON table (col1,col2,...,coln"
   without the final ending parenthesis. */
  char *index_def;
};

struct coldeflist
{
  struct coldeflist *next;
  char *col_name;
  int col_type;
  SQLULEN col_precision;
  int col_scale;
  int col_nullable;
  int col_unquoted;
/* Currently the following is 1 if this column is the first blob
   (LONG VARCHAR or LONG VARBINARY) column of this table.
   Otherwise, if it's not blob, or it's not the first blob,
   it will be zero: */
  int col_is_nth_blob;
};

struct subtablelist
{
  struct subtablelist *next;
  struct tabledeflist *sub_table;
};

struct tabledeflist *all_tables_list;	/* Initialized in main. */


/* ==================================================================== */
/* Checked malloc and strdup, called chemalloc and chestrdup, in case   */
/* that our virtual memory is exhausted...                              */
/* From isqlodbc.c  --  Should really be in a common module.            */
/* ==================================================================== */


char *
my_strncat (char *string1, const char *string2, size_t count)
{
  size_t str1len = strlen (string1);
  return (strncat (string1, string2, (count - str1len)));
}


char *
chemalloc (size_t size, char *where)	/* where can be NULL or empty */
{
  FILE *error_stream;
  int i = 0;
  char *result;

  if (NO (result = (char *) malloc (size)))
    {
      char num[11];
      sprintf (num, "%ld", (long) size);
    print_again:
      if (0 == i)
	{
	  error_stream = stderr;
	}
      else if (1 == i)
	{
	  error_stream = stdout;
	}
      else
	{
	  exit (1);
	}

      putc ('\n', error_stream);
      fputs (progname, error_stream);
      if (where && *where)	/* Not null, not empty. */
	{
	  fputs (" (", error_stream);
	  fputs (where, error_stream);
	  fputs (")", error_stream);
	}
      fputs (": chemalloc failed when tried to allocate ", stderr);
      fflush (error_stream);
      fputs (num, error_stream);
      fputs (" bytes\n", stderr);
      fflush (error_stream);
      i++;
      goto print_again;
    }
  else
    {
      return (result);
    }
}


char *
chestrdup (char *str, char *where)	/* where can be NULL or empty */
{
  FILE *error_stream;
  int i = 0;
  char *res;

  if (NOT (res = strdup (str)))
    {
    print_again:
      if (0 == i)
	{
	  error_stream = stderr;
	}
      else if (1 == i)
	{
	  error_stream = stdout;
	}
      else
	{
	  exit (1);
	}
/* Don't use fprintf if memory is on the red! */
      putc ('\n', error_stream);
      fputs (progname, error_stream);
      if (where && *where)	/* Not null, not empty. */
	{
	  fputs (" (", error_stream);
	  fputs (where, error_stream);
	  fputs (")", error_stream);
	}
      fputs (": chestrdup failed when tried to make a copy of: ", stderr);
      fflush (error_stream);
      fputs (str, error_stream);
      putc ('\n', error_stream);
      fflush (error_stream);
      i++;
      goto print_again;
    }
  else
    {
      return (res);
    }
}


/* Few macros for strncasestr, which is soon used by str_replace */

/* This returns true for range '\100' - '\177'
   (from '@' via 'A' and 'Z' to 'a' and 'z' and DEL)
   and for range '\300' - '\377' (from ISO8859.1 Agrave to ydieresis)
   In this latter range are most of the accented vowels and some consonants
   of the ISO8859.1, and for the most the upper-lower-relation holds.
 */

#define is_a_letter(C)        ((C) & 0100)	/* Bit-6 (64.) on */
/* This returns only true for 8-bit letters in range \300 - \377: */
#define is_a_iso_letter(C)    (((C) & 0300) == 0300)	/* Bit-7 and Bit-6 on */
#define is_a_lc_letter(C) (((C) & 0140) == 0140)	/* Both bits on */
#define is_a_uc_letter(C) (((C) & 0140) == 0100)	/* Bit-6 on, bit-5 off */
#define iso_to_lower(C) ((unsigned char)(((unsigned char)(C)) | 040))
/* Set bit-5 (32.) on to get a lowercase variant of the letter. */

/* Note that because these macros consider also the characters like
   @, [, \, ], and ^ to be 'letters', they will match against characters
   `, {, |, }, and ~ respectively, which is just all right, because
   in some older implementations of European character sets those
   characters mark the uppercase and lowercase variants of certain
   diacritic letters. (Well, I don't know whether it is always all right
   in applications like this..., well, but currently we just replace
   !Q, !O or !N, (or !q.!o.!n) nothing more).
 */



/* Returns pointer to that point of string1, where the first instance
   of string2 is found. Case doesn't matter. Checks max. maxbytes
   characters from the beginning of string1.
   Probably not the most optimal algorithm, but good enough for me.
   (Cleaned from nc_strstr function of string.c module.)
   If string1 is null terminated string (SQL_NTS) then maxbytes should
   be its length got with strlen(string1).
   Before the loop begins the length of string2 minus one is subtracted
   from it, so that string1 will not be unnecessarily scanned past the
   point where string2 cannot anymore occur as its tail.
 */

#define strncasestr dbdump_strncasestr

unsigned char *
strncasestr (unsigned char *string1, unsigned char *string2, size_t maxbytes)
{
  unsigned char first, d, e;
  unsigned char *s1, *s2;
  size_t str2len = strlen ((char *) string2);


  if (!str2len)
    {
      return (string1);
    }				/* If string2 is an empty string "" */

  first = iso_to_lower (*string2);

  for (maxbytes -= (str2len - 1); (maxbytes > 0) && (d = *string1); maxbytes--)
    {
      if (is_a_uc_letter (d))
	{
	  d = iso_to_lower (d);
	}

      if (d == first)
	{
/* e have to be fetched and checked before d in and-clause, otherwise
   we won't find substrings from the end of string1: */
	  for (s1 = string1, s2 = string2; ((e = *++s2) && (d = *++s1));)
	    {
	      if (is_a_uc_letter (d))
		{
		  d = iso_to_lower (d);
		}
	      if (is_a_uc_letter (e))
		{
		  e = iso_to_lower (e);
		}
	      if (d != e)
		{
		  break;
		}		/* Found first differing character. */
	    }
/* If we exited the above loop with value of e as zero, then we have
   found that the whole string2 is contained in string1: */
	  if (!e)
	    {
	      return (string1);
	    }
/* But if string1 was finished (although s2 still wasn't) then we return
   false, as the 'tail of string1' is now shorter than string2, so it's
   not anymore possible that string2 would fit into it:
   (Actually this case is not anymore possible because of new maxbytes
    counting done in the outer loop.)
 */
	  if (!d)
	    {
	      return (0);
	    }
/* Otherwise, it didn't match this time, let's try to find the next potential
   point of string1 where it would match: */
	}
      string1++;
    }

  return (0);			/* Return false as we didn't find it. */
}



/*
   str_replace(string_exp1, from_exp, to_exp, max_n_replacements)

   Replace every from_exp from string_exp1 with to_exp.
   If the optional fourth argument is non-zero, then replace
   at maximum that many occurrences.

   Modified from bif_replace in sqlbif.c
   (by AK 29. Nov 1997 & 29. Jan 1998)
   In contrast to that, this one does case-insensitive comparison.
   Also, if to_str is NULL, then the effect is same as it would be "",
   i.e. an empty string, so that each occurrence of from_str is just
   simply deleted.
 */
unsigned char *
str_replace (unsigned char *src_str, unsigned char *from_str, unsigned char *to_str, int only_n)
{
  char *me = "str_replace";
  int only_n_flag = (only_n);
  size_t src_len, from_len, to_len, difference, occurrences = 0;
  size_t res_len, non_changed_len, n_changes;
  unsigned char *ptr, *prevptr, *res_ptr;
  unsigned char *res;

  if ((NULL == src_str) || (NULL == from_str))
    {
      return (NULL);
    }

  if (NULL == to_str)
    {
      to_str = UCP ("");
    }

  src_len = strlen (SCP (src_str));
  from_len = strlen (SCP (from_str));
  to_len = strlen (SCP (to_str));
  difference = (to_len - from_len);	/* How many bytes longer? */

/* Don't know actually what we should do when from is an empty string.
   Now just return the string_exp1 back as it is. */
  if (0 == from_len)
    {
      return (UCP (chestrdup (SCP (src_str), me)));
    }
/* if(only_n_flag && (0 == only_n)) { return(box_copy(src_str)); } */

  if (0 != difference)		/* The resulting string would be longer or shorter. */
    {
      /* So we have to count the number of occurrences of from_str in src_src */
      occurrences = 0;
      ptr = src_str;
      while ((!only_n_flag || (occurrences < only_n)) && (ptr = strncasestr (ptr, from_str, (src_len - (ptr - src_str)))))
	{
	  occurrences++;
	  ptr++;
	}
      difference *= occurrences;	/* Now the difference in final length. */
      if (0 == occurrences)
	{
	  return (UCP (chestrdup (SCP (src_str), me)));
	}			/* Nothing to replace. */
    }

/* If from_str and to_str are identical strings? Not really necessary.
  if(((0 == difference) && (0 == strcmp(from_str,to_str))))
   {
     return(box_copy(src_str));
   }
*/

  res_len = (src_len + difference);	/* Difference can be -, 0, + */

/*
  printf("%s: Allocating res of len %d for src_len %d, with from_len %d,"
         " to_len %d, occurrences %d, difference %d, only_n=%d,%d\n",
          me,res_len,src_len,from_len,to_len,occurrences,difference,
          only_n_flag,only_n); fflush(stdout);
 */

  /* +1 for the final zero. */
  res = UCP (chemalloc ((res_len + 1), me));
  res_ptr = res;
  prevptr = src_str;
  n_changes = 0;
  while ((!only_n_flag || (n_changes < only_n)) && (ptr = strncasestr (prevptr, from_str, (src_len - (prevptr - src_str)))))
    {
      if (0 != (non_changed_len = (ptr - prevptr)))	/* Something stays same? */
	{
	  memcpy (res_ptr, prevptr, non_changed_len);
	  res_ptr += non_changed_len;
	}
      if (0 != to_len)		/* When to_len is zero, we actually delete items. */
	{
	  memcpy (res_ptr, to_str, to_len);
	  res_ptr += to_len;
	}
      prevptr = ptr + from_len;
      ptr++;
      n_changes++;
    }
  /* Copy the last remaining piece if necessary. */
  non_changed_len = (src_len - (prevptr - src_str));	/* (src_str+src_len)-prevptr */
  if (0 != non_changed_len)
    {
      memcpy (res_ptr, prevptr, non_changed_len);
      res_ptr += non_changed_len;
    }
  *res_ptr = '\0';		/* res [res_len] = 0; */
  return res;
}


/* =============================================================== */

UCHAR *substitute_tablename_expr (UCHAR * tablename_expr, UCHAR * whole_tablename_org);

char *
escapify (char *resbuf, char *name)
{
  char *retptr = resbuf;

  if (!prefix_with_flag && !surround_with_flag)
    {
      return (name);
    }

  if (prefix_with_flag)		/* For -b option */
    {
      *retptr++ = prefix_with_flag;
    }

  if (surround_with_flag)	/* For -a option */
    {
      *retptr++ = surround_with_flag;
    }

  strcpy (retptr, name);

  if (surround_with_flag)
    {
      retptr += strlen (retptr);
      *retptr++ = surround_with_flag;
      *retptr = '\0';
    }

  return (resbuf);
}

/* Note how -a option (surround_with_flag being doublequote)
   doesn't have any effect here.
   Instead, user has to specify new_name explicitly as "!Q"."!O"."!N"
   in Unix shell this can be given as new_name='"!Q"."!O"."!N"' and
   in Windows as new_name="""!Q"""."""!O"""."""!N"""
   (i.e. by tripling each doublequote).
 */
char *
escapify_and_form_dest_name (char *resbuf, int resbuf_maxsize, char *whole_table_name)
{
  char *resptr = resbuf;

  if (!prefix_with_flag && !new_name)
    {
      return (whole_table_name);
    }

  if (resbuf_maxsize >= 0)
    {
      *resbuf = '\0';
    }
  if (prefix_with_flag)
    {
      if (resbuf_maxsize >= 1)
	{
	  *resptr++ = '\\';
	}
    }
  if (new_name)
    {
      whole_table_name = SCP (substitute_tablename_expr (UCP (new_name), UCP (whole_table_name)));
    }

  strncpy (resptr, whole_table_name, (resbuf_maxsize - (resptr - resbuf)));
  *(resptr + (resbuf_maxsize - (resptr - resbuf))) = '\0';
  if (new_name)
    {
      free (whole_table_name);
    }				/* malloced by subst... */
  return (resbuf);
}



char *
get_converted_type (char *type)
{
  int i;

  /* Loop from the end to the beginning, so that it is possible
     for later conversion definitions to override the previous ones.
     (indices 0 and 1 of conv_types_table are not used. */
  for (i = (2 * n_conv_types); i; i -= 2)
    {
      /* If the destination is NULL, then ignore this conversion: */
      if (conv_types_table[i] && conv_types_table[i + 1] && !strcasecmp (conv_types_table[i], type))
	{
	  return (conv_types_table[i + 1]);
	}
    }

  return (type);		/* If not found from the table return back as it is. */
}


int
length_of_tablelist (struct tabledeflist *tl)
{
  int len = 0;

  while (tl)
    {
      len++;
      tl = tl->next;
    }

  return (len);
}


struct tabledeflist *
find_tabledef (char *table_name, struct tabledeflist *tl)
{
  while (tl)
    {
      if (0 == strcmp (table_name, tl->name))
	{
	  return (tl);
	}
      tl = tl->next;
    }

  return (NULL);
}

struct tabledeflist *
get_ancestor (struct tabledeflist *tl)
{
  if (tl->super_tl)
    {
      return (get_ancestor (tl->super_tl));
    }
  else
    {
      return (tl);
    }
}


int
index_is_found_from_indexdeflist (char *index_name, struct indexdeflist *il)
{
  while (il)
    {
      if (0 == strcmp (index_name, il->index_name))
	{
	  return (1);
	}
      il = il->next;
    }

  return (0);
}


struct indexdeflist *
find_first_index_like (struct indexdeflist *il, char *like_what)
{
  while (il)
    {
      if (!strncmp (il->index_def, like_what, strlen (like_what)))
	{
	  return (il);
	}
      il = il->next;
    }

  return (il);			/* That is, a NULL */
}

/* Returns 1 if table node tl has a super table definition, and index
   index_name has been defined in it, either as a primary key
   or some other kind of index.
   Calls recursively itself, in case that the table has not just
   a super table, but that in turn has another super table definition,
   and so on.
   Otherwise returns zero.
   Of course all the primary keys and all the indices of all the tables
   must have been read in already, so that means that we cannot use
   this function before we are ready to print out the index definitions.
   (Because SQLTables returns tables in alphabetical, not in historical
   order, subtables can be fetched before their parents.)
 */
int
index_has_been_defined_for_supertable (char *index_name, struct tabledeflist *tl)
{
  struct tabledeflist *suptl;

  if (tl->super_table == NULL)
    {
      return (0);
    }
  else
    {
      suptl = tl->super_tl;
      /* Was: find_tabledef(tl->super_table,all_tables_list); */
      if (suptl == NULL)
	{
/* E.g. this might happen if the user dumps selectively some tables
   with a wildcard expression, and some parent table(s) are left out.
   (NOT ANYMORE BECAUSE OF THE NEW CODE IN get_real_supertables)
 */
	  fprintf (stdout,
	      "-- Warning from index_has_been_defined_for_supertable(%s,%s):\n"
	      "-- Can't find the super table '%s' from the table definitions.\n", index_name, tl->name, tl->super_table);
	  return (0);
	}
      /* Either it is the primary key name of ancestor table? */
      if (suptl->primary_key_name && !strcmp (index_name, suptl->primary_key_name))
	{
	  return (1);
	}
      /* Or it is one of its indices? */
      if (index_is_found_from_indexdeflist (index_name, suptl->index_defs))
	{
	  return (1);
	}
      else			/* Otherwise, check same from the grandparent: */
	{
	  return (index_has_been_defined_for_supertable (index_name, suptl));
	}
    }
}

/* Concatenate subtable subtl at the end of sub_tables list of tl.
   A little bit slower than inserting them to the front, but this
   way we keep the original ascending alphabetical order in which
   SQLTables returns the table names.
 */
int
add_to_subtables (struct tabledeflist *subtl, struct tabledeflist *tl)
{
  struct subtablelist *sl, *newnode;
  int count = 1;
  char where[CHARCOL_LEN + 80];

  sprintf (where, "add_to_subtables(\"%s\",\"%s\")", (subtl->name ? subtl->name : "NULL"), (tl->name ? tl->name : "NULL"));

  /* First create a new node with a name subname. */
  newnode = ((struct subtablelist *) chemalloc (sizeof (struct subtablelist), where));
  newnode->next = NULL;
  newnode->sub_table = subtl;

  /* And then figure out where to put it. */
  if (NULL == (sl = tl->sub_tables))	/* First one? */
    {
      tl->sub_tables = newnode;
    }
  else
    {
      /* Find the last node of the sub_tables list: */
      for (; count++, sl->next; sl = sl->next);
      sl->next = newnode;	/* And concatenate the new node after that. */
    }
  return (count);
}

/* Make links between super tables.and their subtables. */
int
reorder_subtables (struct tabledeflist *tl)
{
  struct tabledeflist *supertl;

  while (tl)
    {
      if (tl->super_table)	/* It has a super table so it is a subtable */
	{
	  supertl = find_tabledef (tl->super_table, all_tables_list);
	  if (supertl == NULL)
	    {
/* E.g. this might happen if the user dumps selectively some tables
   with a wildcard expression, and some parent table(s) are left out.
   (NOT ANYMORE BECAUSE OF THE NEW CODE IN get_real_supertables)
 */
	      fprintf (stdout,
		  "-- Warning from reorder_subtables(%s):\n"
		  "-- Can't find the super table '%s' from the table definitions.\n", tl->name, tl->super_table);
	    }
	  else
	    {
	      tl->super_tl = supertl;	/* Link the table to its supertable */
	      add_to_subtables (tl, supertl);	/* And vice versa */
	    }
	}
      tl = tl->next;
    }

  return (1);
}


size_t
construct_where_clause_aux (char *resbuf, char *father, char *child, char *primcols, char *termstr,	/* A right parenthesis */
    size_t maxlength)
{
  size_t tmplen;
  char *ptr, *oldptr, *endptr;
  char tmpbuf[5 * CHARCOL_LEN + 2];
  char temp1[CHARCOL_LEN + 10], temp2[CHARCOL_LEN + 10];

  endptr = resbuf;
  oldptr = primcols;
  while (oldptr)		/* Loop over the comma-separated column names of pk */
    {
      ptr = strchr (oldptr, ',');	/* The next comma. */
      if (ptr)
	{
	  *ptr = '\0';
	}			/* Overwrite temporarily with zero. */
      sprintf (tmpbuf, "%s.%s = %s.%s%s",
	  escapify (temp1, child), oldptr, escapify (temp2, father), oldptr, (ptr ? " and " : termstr));
      if (ptr)
	{
	  *ptr = ',';
	  oldptr = ptr + 1;
	}			/* Restore the comma. */
      else
	{
	  oldptr = NULL;
	}			/* Will stop at the next time on loop top */
      tmplen = strlen (tmpbuf);
      if (tmplen > maxlength)
	{
	  return (0);
	}
      else
	{
	  maxlength -= tmplen;
	  strcpy (endptr, tmpbuf);
	  endptr += tmplen;
	}
    }

  return (endptr - resbuf);	/* Return the length of all stuff collected */
}


size_t
construct_where_clause_for_a_subtable (char *resbuf,
    struct tabledeflist *father, struct tabledeflist *child, char *primcols, size_t maxlength)
{
  size_t tmplen;
  char *endptr = resbuf;
  char tmpbuf[15 * CHARCOL_LEN + 2];
  char temp[CHARCOL_LEN + 10];

  sprintf (tmpbuf, " NOT EXISTS (select %s from %s where ", primcols, escapify (temp, child->name));
  tmplen = strlen (tmpbuf);
  if (tmplen > maxlength)
    {
      return (0);
    }
  else
    {
      maxlength -= tmplen;
      strcpy (endptr, tmpbuf);
      endptr += tmplen;
    }

  tmplen = construct_where_clause_aux (endptr, father->name, child->name, primcols, ")", maxlength);
  if (0 == tmplen)
    {
      return (0);
    }
  maxlength -= tmplen;
  endptr += tmplen;

  return (endptr - resbuf);	/* Return the length of all stuff collected */
}

#define WHERE_WHERE " WHERE"
#define WHERE_AND   " AND"

size_t
make_where_clause_for_table_with_children (char *text, struct tabledeflist *tl, size_t maxlength)
{
  struct subtablelist *sl;
  char *endptr;
  size_t tmplen;
  char *primcols = get_ancestor (tl)->primary_key_def;

  endptr = (text + strlen (text));
  tmplen = (sizeof (WHERE_WHERE) - 1);
  if (maxlength < tmplen)
    {
      return (0);
    }
  strcpy (endptr, WHERE_WHERE);
  maxlength -= tmplen;
  endptr += tmplen;

  sl = tl->sub_tables;
  while (sl)
    {
      tmplen = construct_where_clause_for_a_subtable (endptr, tl, sl->sub_table, primcols, maxlength);
      if (0 == tmplen)
	{
	  return (0);
	}
      maxlength -= tmplen;
      endptr += tmplen;
      if ((sl = sl->next) != NULL)
	{
	  tmplen = (sizeof (WHERE_AND) - 1);
	  if (maxlength < tmplen)
	    {
	      return (0);
	    }
	  strcpy (endptr, WHERE_AND);
	  maxlength -= tmplen;
	  endptr += tmplen;
	}
    }

  return (endptr - text);
}


char SQL_error_state[15] = { 'O', 'K', '\0' };
char SQL_error_message[1000] = { 'O', 'K', '\0' };

void
print_error (HENV e1, HDBC e2, HSTMT e3)
{
  short len;
  SQLError (e1, e2, e3, (UCHAR *) SQL_error_state, NULL,
      (UCHAR *) & SQL_error_message, sizeof (SQL_error_message), (SWORD *) & len);
  printf ("\n-- *** Error %s: %s\n", SQL_error_state, SQL_error_message);
  if (0 == strcmp (SQL_error_state, "08S01"))
    exit (2);
}

/* SQL data type codes.
   These were taken from ../sqlcli.h and ../sqlcli2.h header files.
   Added by AK 3-JAN-1997.
 */
char *
get_sql_type_title (int type)
{
  switch (type)
    {
#ifdef SQL_CHAR
    case SQL_CHAR:
      {
	return ("CHAR");
      }				/*  1 */
#endif
#ifdef SQL_NUMERIC
    case SQL_NUMERIC:
      {
	return ("NUMERIC");
      }				/*  2 */
#endif
#ifdef SQL_DECIMAL
    case SQL_DECIMAL:
      {
	return ("DECIMAL");
      }				/*  3 */
#endif
#ifdef SQL_INTEGER
    case SQL_INTEGER:
      {
	return ("INTEGER");
      }				/*  4 */
#endif
#ifdef SQL_SMALLINT
    case SQL_SMALLINT:
      {
	return ("SMALLINT");
      }				/*  5 */
#endif
#ifdef SQL_FLOAT
    case SQL_FLOAT:
      {
	return ("FLOAT");
      }				/*  6 */
#endif
#ifdef SQL_REAL
    case SQL_REAL:
      {
	return ("REAL");
      }				/*  7 */
#endif
#ifdef SQL_DOUBLE
    case SQL_DOUBLE:
      {
	return ("DOUBLE PRECISION");
      }				/*  8 */
#endif
#ifdef SQL_DATETIME
    case SQL_DATETIME:
      {
	return ("DATE");
      }				/*  9 */
#endif
#if defined  (SQL_DATE) && NOT defined (SQL_DATETIME)
    case SQL_DATE:
      {
	return ("DATE");
      }				/* 9 in sqlext.h */
#endif
#ifdef SQL_TIME
    case SQL_TIME:
      {
	return ("TIME");
      }				/* 10 in sqlext.h */
#endif
#if defined (SQL_INTERVAL) && ((NOT defined (SQL_TIME)) || (SQL_INTERVAL != SQL_TIME))
    case SQL_INTERVAL:
      {
	return ("TIME");
      }				/* 10 */
#endif
#ifdef SQL_TIMESTAMP
    case SQL_TIMESTAMP:
      {
	return ("TIMESTAMP");
      }				/* 11 */
#endif
#ifdef SQL_VARCHAR
    case SQL_VARCHAR:
      {
	return ("VARCHAR");
      }				/* 12 */
#endif
#ifdef SQL_BIT
    case SQL_BIT:
      {
	return ("BIT");
      }				/* 14 */
#endif
#ifdef SQL_BIT_VARYING
    case SQL_BIT_VARYING:
      {
	return ("BIT VARYING");
      }				/* 15 */
#endif
#ifdef SQL_LONGVARCHAR
    case SQL_LONGVARCHAR:
      {
	return ("LONG VARCHAR");
      }				/* (-1) */
#endif
#ifdef SQL_BINARY
    case SQL_BINARY:
      {
	return ("BINARY");
      }				/* (-2) in sqlext.h */
#endif
#ifdef SQL_VARBINARY
    case SQL_VARBINARY:
      {
	return ("VARBINARY");
      }				/* (-3) in sqlext.h */
#endif
#ifdef SQL_LONGVARBINARY
    case SQL_LONGVARBINARY:
      {
	return ("LONG VARBINARY");
      }				/* (-4) */
#endif
#ifdef SQL_BIGINT
    case SQL_BIGINT:
      {
	return ("BIGINT");
      }				/* (-5) in sqlext.h */
#endif
#ifdef SQL_TINYINT
    case SQL_TINYINT:
      {
	return ("TINYINT");
      }				/* (-6) in sqlext.h */
#endif

    default:
      {
	char tmp[33];
	sprintf (tmp, "UNK_TYPE:%d", type);
	return (chestrdup (tmp, "get_sql_type_title"));
      }
    }				/* switch */
}

/* Makes a new, safe copy of the stuff it returns as a result,
   if it is necessary. */
char *
get_sql_col_type_def (int type, SQLULEN precision, int scale, int nullable)
{
  char result[181], more[181];
  char *type_string;
  if (kubl_default_conversions_flag && (SQL_DECIMAL == type || SQL_NUMERIC == type))
    {
      if (scale == 0)
	type = SQL_INTEGER;
      else
	type = SQL_DOUBLE;
    }
  type_string = get_converted_type (get_sql_type_title (type));
  more[0] = '\0';

  if ((type == SQL_CHAR) || (type == SQL_VARCHAR))
    {
      sprintf (more, "(%ld)", precision);
    }
  if (nullable == SQL_NO_NULLS)
    {
      strcat (more, " NOT NULL");
    }

  if (*more)			/* Something to add? */
    {
      strcpy (result, type_string);
      strcat (result, more);
      return (chestrdup (result, "get_sql_col_type_def"));
    }
  else
    {
      return (type_string);
    }
}

/* ================================================================== */

/*

divide_tablename
Taken from isqlodbc.c, should be really in a common module.
See also the notes regarding the next function new_whole_tablename

This should divide tablename (in case that tablequalifier and tableowner
are NULL, i.e. not defined explicitly elsewhere) in the following manner:

tablequalifier = NULL, tableowner = NULL, tablename = qual.own.name
 -> tablequalifier = qual, tableowner = own, tablename = name

tablename = qual..name
 -> tablequalifier = qual, tableowner = NULL, tablename = name

tablename = ..  or tablename = .
 -> tablequalifier = NULL, tableowner = NULL, tablename = NULL

tablename = fool.baal.
-> tablequalifier = fool, tableowner = baal, tablename = NULL

tablename = fool.baal
-> tablequalifier = NULL, tableowner = fool, tablename = baal

tablename = qual..  -> tablequalifier = qual (others NULL)

tablename = .own.  (or own.) -> tableowner = own (others NULL)

tablename = ..name (or .name) -> tablename = name (others NULL)

Returns the new tablename.

If the short integer pointers cbTableName, cbTableQualifier and
cbTableOwner are not NULL, then store the length of corresponding
parts there, and leave the original tablename buffer intact.
If they are NULL, then overwrite the delimiting dots with null bytes.
 */

UCHAR *
divide_tablename_aux (UCHAR * tablename, SWORD * cbTableName,
    UCHAR ** p_tablequalifier, SWORD * cbTableQualifier, UCHAR ** p_tableowner, SWORD * cbTableOwner)
{
  unsigned char *ptr, *ptr2;
  unsigned short int piece1len = 0;

  if (tablename && (ptr = UCP (strchr (SCP (tablename), '.'))))
    {
      if (ptr > (tablename))	/* Period not in the beginning of tablename? */
	{
	  *p_tablequalifier = tablename;
	}
      piece1len = SWD (ptr - tablename);
      if (cbTableQualifier)
	{
	  *cbTableQualifier = piece1len;
	}
      else
	{
	  *ptr = '\0';
	}

      if ((ptr2 = (UCHAR *) strchr ((char *) (ptr + 1), '.')) != NULL)
	{
	  if (ptr2 > (ptr + 1))	/* Second period not right after first one? */
	    {
	      *p_tableowner = ptr + 1;
	    }

	  /* If pattern is like Q..N then p_tableowner is not set
	     (should be NULL presumably when called), but
	     *cbTableOwner is still set to 0 if it's not NULL */

	  if (cbTableOwner)
	    {
	      *cbTableOwner = SWD (ptr2 - (ptr + 1));
	    }
	  else
	    {
	      *ptr2 = '\0';
	    }

	  if (*(ptr2 + 1))
	    {
	      tablename = (ptr2 + 1);
	    }			/* Something following? */
	  else
	    {
	      tablename = NULL;
	    }			/* If nothing after second period. */
	}
      else			/* If only one period found. */
	{
	  *p_tableowner = *p_tablequalifier;
	  *p_tablequalifier = NULL;
	  if (cbTableOwner)
	    {
	      *cbTableOwner = piece1len;
	    }
	  if (cbTableQualifier)
	    {
	      *cbTableQualifier = 0;
	    }
	  /* Check that it's not dangling in the end: */
	  if (*(ptr + 1))
	    {
	      tablename = ptr + 1;
	    }
	  else
	    {
	      tablename = NULL;
	    }
	}
    }
  else				/* No periods found. Set the Qual and Owner count pointers to zero */
    {
      if (cbTableQualifier)
	{
	  *cbTableQualifier = 0;
	}
      if (cbTableOwner)
	{
	  *cbTableOwner = 0;
	}
    }

  if (cbTableName)
    {
      *cbTableName = SWD (tablename ? strlen (SCP (tablename)) : 0);
    }
  return (tablename);
}

/* Note that this corrupts the given tablename by inserting null bytes
   '\0's to the place of dots.
 */
UCHAR *
divide_tablename (UCHAR * tablename, UCHAR ** p_tablequalifier, UCHAR ** p_tableowner)
{
/* Has any effect only if tablequalifier and tableowner are not given
   elsewhere, i.e. they are still NULL. (Stupid rule for compatibility) */
  if (tablename && NO * p_tablequalifier && NO * p_tableowner)
    {
      return (divide_tablename_aux (tablename, NULL, p_tablequalifier, NULL, p_tableowner, NULL));
    }
  else
    {
      return (tablename);
    }
}


#ifdef MOST_CLEARLY_THIS_WOULD_NOT_WORK_IN_MANY_CASES

UCHAR *
repair_tablename (UCHAR * tablequalifier, UCHAR * tableowner, UCHAR * tablename)
{
  if (tablequalifier)
    {
      tablequalifier[strlen (SCP (tablequalifier))] = '.';
    }
  if (tableowner)
    {
      tableowner[strlen (SCP (tableowner))] = '.';
    }
  return (tablename);
}

#endif



#define TN_SQL_QUOTE \
  my_strncat(dest_buf, (char *) quote_char, (dest_size-2))




char *
compose_whole_tablename (struct tabledeflist *tl, char *dest_buf, int dest_size)
{
  static int SQLGetInfo_called = 0;
  static SQLULEN owner_usage, qualifier_usage;
  static UWORD qualifier_location;
  static char *owner_term, *qualifier_term, *qualifier_name_separator;
  static char sp_owner_term[257], sp_qualifier_term[257], sp_qualifier_name_separator[257];
  static SWORD cb_owner_term, cb_qualifier_term, cb_qualifier_name_separator;
  static SWORD cb_owner_usage, cb_qualifier_usage, cb_qualifier_location, cb_quote_char;
  static UCHAR quote_char[2];
  char *me = "compose_whole_tablename";

  if (0 == SQLGetInfo_called)
    {
      HDBC *ptr_to_hdbc = &hdbc;	/* Global to datasource, should be in some struct */
      SQLGetInfo_called = 1;

      /* Clear the string buffers first: */
      sp_owner_term[0] = sp_qualifier_term[0] = sp_qualifier_name_separator[0] = '\0';

      /* These are strictly for debugging: */
      strcpy (sp_owner_term, "omistaja");
      strcpy (sp_qualifier_term, "lunastaja");
      strcpy (sp_qualifier_name_separator, "separaattori");

      SQLGetInfo (*ptr_to_hdbc, SQL_IDENTIFIER_QUOTE_CHAR, quote_char, sizeof (quote_char), &cb_quote_char);
      if (' ' == quote_char[0])
	quote_char[0] = 0;
      SQLGetInfo (*ptr_to_hdbc, SQL_OWNER_TERM, sp_owner_term, (sizeof (sp_owner_term) - 1), ((SWORD *) & cb_owner_term));
      if (SQL_NULL_DATA == cb_owner_term)
	{
	  owner_term = NULL;
	}
      else
	{
	  owner_term = sp_owner_term;
	}

      SQLGetInfo (*ptr_to_hdbc, SQL_QUALIFIER_TERM, sp_qualifier_term,
	  (sizeof (sp_qualifier_term) - 1), ((SWORD *) & cb_qualifier_term));
      if (SQL_NULL_DATA == cb_qualifier_term)
	{
	  qualifier_term = NULL;
	}
      else
	{
	  qualifier_term = sp_qualifier_term;
	}

      SQLGetInfo (*ptr_to_hdbc, SQL_QUALIFIER_NAME_SEPARATOR, sp_qualifier_name_separator,
	  (sizeof (sp_qualifier_name_separator) - 1), ((SWORD *) & cb_qualifier_name_separator));
      if (SQL_NULL_DATA == cb_qualifier_name_separator)
	{
	  qualifier_name_separator = NULL;
	}
      else
	{
	  qualifier_name_separator = sp_qualifier_name_separator;
	}

      owner_usage = qualifier_usage = 0;
      qualifier_location = 0;

      SQLGetInfo (*ptr_to_hdbc, SQL_OWNER_USAGE, &owner_usage, ((SWORD) 4), ((SWORD *) & cb_owner_usage));

      SQLGetInfo (*ptr_to_hdbc, SQL_QUALIFIER_USAGE, &qualifier_usage, ((SWORD) 4), ((SWORD *) & cb_qualifier_usage));

      SQLGetInfo (*ptr_to_hdbc, SQL_QUALIFIER_LOCATION, &qualifier_location, ((SWORD) 2), ((SWORD *) & cb_qualifier_location));


      if (verbose_flag || dbdump_debug_level)
	{
	  fprintf (stdout,
	      "-- %s: owner_term=\"%s\", qualifier_term=\"%s\", qualifier_name_separator=\"%s\"\n"
	      "-- owner_usage=%08lx, qualifier_usage=%08lx, qualifier_location=%u (%s)\n"
	      "-- tl->tl_qual_only=\"%s\", tl->tl_own_only=\"%s\", tl->tl_name_only=\"%s\"\n",
	      me,
	      ((NULL == owner_term) ? "NULL" : owner_term),
	      ((NULL == qualifier_term) ? "NULL" : qualifier_term),
	      ((NULL == qualifier_name_separator) ? "NULL" : qualifier_name_separator),
	      owner_usage, qualifier_usage,
	      qualifier_location,
	      ((SQL_QL_START == qualifier_location) ? "SQL_QL_START"
		  : ((SQL_QL_END == qualifier_location) ? "SQL_QL_END"
		      : "UNKNOWN")),
	      ((NULL == tl->tl_qual_only) ? "NULL" : tl->tl_qual_only),
	      ((NULL == tl->tl_own_only) ? "NULL" : tl->tl_own_only), ((NULL == tl->tl_name_only) ? "NULL" : tl->tl_name_only));
	  fflush (stdout);
	}

    }


/* Anyways, no we should be able to compose the whole tablename
   as the remote end (the original datasource) understands it,
   using the information collected above, as well as the
   elements

     tl_qual_only, tl_own_only and tl_name_only

   in the tabledeflist node.

   Note that any of these, as well as any of SQLGetInfo values
   might be NULLs or empty strings as well.
 */

  dest_buf[0] = '\0';
  dest_buf[dest_size - 1] = '\0';

  if (tl->tl_qual_only && (0 != qualifier_usage) && (SQL_QL_END != qualifier_location))
    {
      TN_SQL_QUOTE;
      my_strncat (dest_buf, tl->tl_qual_only, (dest_size - 2));
      TN_SQL_QUOTE;
      if (NULL != qualifier_name_separator)
	{
	  my_strncat (dest_buf, qualifier_name_separator, (dest_size - 2));
	}
    }

  if (tl->tl_own_only && (0 != owner_usage))
    {
      TN_SQL_QUOTE;
      my_strncat (dest_buf, tl->tl_own_only, (dest_size - 2));
      TN_SQL_QUOTE;
      my_strncat (dest_buf, ".", (dest_size - 2));
    }

  if (tl->tl_name_only)
    {
      TN_SQL_QUOTE;
      my_strncat (dest_buf, tl->tl_name_only, (dest_size - 2));
      TN_SQL_QUOTE;
    }

  if (tl->tl_qual_only && (0 != qualifier_usage) && (SQL_QL_END == qualifier_location))
    {
      if (NULL != qualifier_name_separator)
	{
	  my_strncat (dest_buf, qualifier_name_separator, (dest_size - 2));
	}
      TN_SQL_QUOTE;
      my_strncat (dest_buf, tl->tl_qual_only, (dest_size - 2));
      TN_SQL_QUOTE;
    }

  return (dest_buf);
}


/*
   new_whole_tablename: An "inverse" function of divide_tablename
   This constructs a new whole tablename
   (into a new buffer allocated here for it)
   from the three parts given, i.e. tablequalifier.tableowner.tablename

   If tablequalifier and tableowner are NULL,
   then returns just a copy of tablename. (no dots).
   If only tablequalifier is NULL,
    returns a combination tableowner.tablename
   If only tableowner is NULL,
    returns a combination tablequalifier..tablename
   tablename itself should never be NULL.

   Later we could use SQLGetInfo options SQL_QUALIFIER_LOCATION
   and  SQL_QUALIFIER_NAME_SEPARATOR, so if they are for example
   detected to be SQL_QL_END and "@" instead of SQL_QL_START and ".",
   then we know to construct Oracle-style tablenames like
   "ADMIN.EMP@EMPDATA" instead of Kubl-like "EMPDATA.ADMIN.EMP".
   Similarly, divide_tablename should take heed of that.
   (Where are the column names appended/inserted in the full Oracle
    notation?)

   Maybe we should also check SQL_QUALIFIER_USAGE and SQL_OWNER_USAGE
   and if they are zeroes (but who trusts ODBC drivers?)
   the set use_tables_prefixes_flag to zero in the beginning.
   (But even nowadays the user can use his -p option anytime he wants.)

   YES, SEE THE FUNCTION compose_whole_tablename ABOVE!
 */
UCHAR *
new_whole_tablename (UCHAR * tablequalifier, UCHAR * tableowner, UCHAR * tablename, char *where)
{
  UCHAR *wholetablename;
  size_t whole_len, qual_len, own_len, tab_len;

  if (NULL == tablequalifier)
    {
      if (NULL == tableowner)
	{
	  return (UCP (chestrdup (SCP (tablename), where)));
	}
      else
	{
	  qual_len = 0;
	}
    }
  else
    {
      qual_len = strlen (SCP (tablequalifier)) + 1;	/* Plus one for dot */
      if (NULL == tableowner)	/* tableowner missing from between */
	{
	  tableowner = UCP ("");
	}
    }

  own_len = strlen (SCP (tableowner)) + 1;	/* Plus one for the dot. */
  tab_len = strlen (SCP (tablename));
  whole_len = qual_len + own_len + tab_len;

  wholetablename = UCP (chemalloc ((whole_len + 1), where));

  wholetablename[0] = '\0';

  if (NULL != tablequalifier)
    {
      strcat (SCP (wholetablename), SCP (tablequalifier));
      strcat (SCP (wholetablename), ".");
    }

  if (NULL != tableowner)
    {
      strcat (SCP (wholetablename), SCP (tableowner));
      strcat (SCP (wholetablename), ".");
    }

  strcat (SCP (wholetablename), SCP (tablename));

  return (wholetablename);
}


/*
   A new function by AK 29-JAN-1998.
   Returns a newly strdupped string, which is got by substituting
   from tablename_expr the "variables" !Q, !O and/or !N
   (can be in lowercase also) with the corresponding three parts
   of whole_tablename_org. (Of course, anyone of these
   could be missing, or appear more than once.).
   Makes strdupped copies, of the original whole_tablename_org
   (first argument), so that it is not corrupted in the division,
   as well as with some intermediate results. All these are free'd
   later, except the final result, which is on the responsibility
   of the caller to free.
 */



char *
dsn_to_owner_name (char *dsn)
{
  int inx;
  dsn = strdup (dsn);
  for (inx = 0; inx < 32; inx++)
    {
      char c = dsn[inx];
      if (!c)
	return dsn;
      if (c >= 'a' && c <= 'z')
	c -= 32;
      else if (c >= '0' && c <= '9');
      else if (c >= 'A' && c <= 'Z');
      else
	c = '_';
      dsn[inx] = c;
    }
  dsn[inx] = 0;			/* cut after 32 characters */
  return dsn;
}


UCHAR *
substitute_tablename_expr (UCHAR * tablename_expr, UCHAR * whole_tablename_org)
{
  char *dsn2;
  char *where = "form_local_tablename";
  UCHAR *rem_tablequal = NULL, *rem_tableown = NULL;
  UCHAR *rem_tablenam = NULL;
  UCHAR *whole_tablename = UCP (chestrdup (SCP (whole_tablename_org), where));
  UCHAR *res1 = NULL, *res2 = NULL, *res3 = NULL, *res4 = NULL;

  rem_tablenam = divide_tablename (whole_tablename, &rem_tablequal, &rem_tableown);

  res1 = str_replace (tablename_expr, UCP ("!Q"), rem_tablequal, 0);
  res2 = str_replace (res1, UCP ("!O"), rem_tableown, 0);
  res3 = str_replace (res2, UCP ("!N"), rem_tablenam, 0);
  dsn2 = dsn_to_owner_name (datasource);
  res4 = str_replace (res3, UCP ("!D"), UCP (dsn2), 0);

  if (whole_tablename)
    {
      free (whole_tablename);
    }
  if (res1)
    {
      free (res1);
    }
  if (res2)
    {
      free (res2);
    }
  if (res3)
    {
      free (res3);
    }

  return (res4);
}


/* First tries to find the combination table_name.column_name
   from tablecol_names (which should be loosely or tightly comma-separated)
   E.g. if we use tablequal and tableowner prefixing, then
   table_name.column_name might result a string like "QUOI.OWN.TABLA.COL",
   and if that were not found, then next "OWN.TABLA.COL" would be
   searched for, then "TABLA.COL" and finally only "COL".
   That means that user can specify "wildcard" column names like
   "VECTOR" in unquoted_columns, that will be left unquoted in
   whichever table they are ever encountered.
 */
char *
belongs_to (char *table_name, char *column_name, char *tablecol_names)
{
  char table_et_column_name_space[(4 * MAXCOLNAME) + 22];
  char *table_et_column_name = table_et_column_name_space;
  char *ptr, *ptr2;

  if ((NULL == tablecol_names) || empty_stringp (tablecol_names))
    {
      return (NULL);
    }
  sprintf (table_et_column_name, "%s.%s", table_name, column_name);

try_again:
  if ((ptr = strstr (tablecol_names, table_et_column_name)) && ((ptr == tablecol_names)	/* In the beginning? Or the prev char: */
	  || ((isspace (*(ptr - 1)) || (',' == *(ptr - 1)) || (';' == *(ptr - 1))))) && (ptr2 = ptr + strlen (table_et_column_name))	/* to following */
      && (!*ptr2 || isspace (*ptr2) || (',' == *ptr2) || (';' == *ptr2) || ('=' == *ptr2)))	/* For future additions. */
    {
      return (ptr2);
    }
  else if ((table_et_column_name = strchr (table_et_column_name, '.')) != NULL)
    {
      table_et_column_name++;	/* Skip the first part and the dot. */
      goto try_again;
    }
  else
    {
      return (NULL);
    }				/* No luck this time. */
}



/* ================================================================== */
/*         FUNCTIONS FOR READING INFORMATION ABOUT THE SCHEMA         */
/*         USING AVAILABLE ODBC CALLS SQLTables, SQLStatistics, etc.  */
/* ================================================================== */

struct tabledeflist *
new_tabledeflist_node (struct tabledeflist *next,
    char *name,
    char *tl_qual_only,
    char *tl_own_only,
    char *tl_name_only,
    char *columns,
    char *all_columns,
    char *primary_key_name,
    char *primary_key_def,
    char *primary_key_type,
    char *super_table,
    char *insert_mode,
    int automatically_included,
    int contains_blobs,
    struct coldeflist *col_defs, struct indexdeflist *index_defs, struct tabledeflist *super_tl, struct subtablelist *sub_tables)
{
  struct tabledeflist *tl;

  char where[CHARCOL_LEN + 80];

  sprintf (where, "new_tabledeflist_node(\"%s\")", (name ? name : "NULL"));

  tl = (struct tabledeflist *) chemalloc (sizeof (struct tabledeflist), where);

  tl->next = next;
  tl->name = name;
  tl->tl_qual_only = tl_qual_only;
  tl->tl_own_only = tl_own_only;
  tl->tl_name_only = tl_name_only;
  tl->columns = columns;
  tl->all_columns = all_columns;
  tl->primary_key_name = primary_key_name;
  tl->primary_key_def = primary_key_def;
  tl->primary_key_type = primary_key_type;
  tl->super_table = super_table;
  tl->insert_mode = insert_mode;
  tl->automatically_included = automatically_included;
  tl->contains_blobs = contains_blobs;
  tl->col_defs = col_defs;
  tl->index_defs = index_defs;
  tl->super_tl = super_tl;
  tl->sub_tables = sub_tables;

  tl->bestrow_columns = NULL;	/* An ugly exception! (not in args) */
  tl->last_SQL_state = NULL;	/* As well as these. */
  tl->last_SQL_message = NULL;

  return (tl);
}

/* Windows NT and Linux do not have strtok_r, the re-entrant
   variant of strtok, so we just bluntly define strtok_r as strtok
   (wholly ignoring the third argument).
   Ordinary strtok uses its own static buffer, so we should be
   sure that none of the API-functions like SQLTables etc calls uses it
   (not even if inside mutex).
   There are calls to strtok(_r) in few places in the driver-module
   cliuti.c, but they occur only in timestamp and date-conversion,
   which should not be needed by SQLTables.
   Of course, someday we should code a secure re-entrant strtok_r
   of our own for Linux and Windows NT builds.
 */
#if defined  (WIN32) || defined (LINUX)
#ifndef strtok_r
#define strtok_r(X,Y,Z) strtok((X),(Y))
#endif
#endif


struct tabledeflist *
get_all_tables (char *global_tablequalifier, char *global_tableowner, char *tablepatterns, char *tabletype, int *pcount)
{
  UCHAR szTableQualifier[CHARCOL_LEN + 2], szTableOwner[CHARCOL_LEN + 2],
      szTableName[CHARCOL_LEN + 2], szTableType[CHARCOL_LEN + 2];
  char *where = "get_all_tables";
  SQLLEN cbTableQualifier, cbTableOwner, cbTableName, cbTableType;
  SWORD scbTableQualifier = SQL_NTS, scbTableOwner = SQL_NTS, scbTableName = SQL_NTS;
  UCHAR *wholetablename;	/* Concatenated from the three above elements. */
  int rc;
  int n_tables = 0;
  struct tabledeflist *orgtl = NULL, *tl = NULL, *new_node;
  char *tokseps = " ,\t\r\n", *toksave = NULL, *tabletok;
  UCHAR *tablequalifier, *tableowner, *tablename;
  /* Three above items are extracted from tabletok, which in turn
     is separated from tablepatterns.
   */


  if (NULL == tablepatterns)	/* Not specified, list all of this tabletype */
    {
      tabletok = tablepatterns;
      goto creep_into_loop;
    }
  /* Loop over comma and/or whitespace separated tablepatterns */
  for (tabletok = strtok_r (tablepatterns, tokseps, &toksave);	/* The 1st token. */
      (tabletok != NULL); tabletok = strtok_r (NULL, tokseps, &toksave)	/* The next token. */
      )
    {
    creep_into_loop:
      if (verbose_flag || dbdump_debug_level)
	{
	  fprintf (stdout,
	      "-- %s: tablepattern=\"%s\",%ld\n",
	      where, (SCP (tabletok) ? SCP (tabletok) : "NULL"), ((NULL != tabletok) ? strlen (SCP (tabletok)) : 0L));
	}
      tablequalifier = NULL;	/* divide_tablename doesn't do its job */
      tableowner = NULL;	/* unless these two are NULL when called. */
/* Was:
     tablename = divide_tablename(UCP(tabletok),&tablequalifier,&tableowner);
 */
      tablename = divide_tablename_aux (UCP (tabletok), &scbTableName,
	  &tablequalifier, &scbTableQualifier, &tableowner, &scbTableOwner);
      tableowner = ((tableowner || tablequalifier) ? tableowner : UCP (global_tableowner));
      tablequalifier = (tablequalifier ? tablequalifier : UCP (global_tablequalifier));

      if (dbdump_debug_level)
	{
	  fprintf (stdout,
	      "-- tablequalifier=%s,%d  tableowner=%s,%d  tablename=%s,%d  tabletype=%s\n",
	      (SCP (tablequalifier) ? SCP (tablequalifier) : "NULL"),
	      scbTableQualifier,
	      (SCP (tableowner) ? SCP (tableowner) : "NULL"),
	      scbTableOwner,
	      (SCP (tablename) ? SCP (tablename) : "NULL"), scbTableName, (SCP (tabletype) ? SCP (tabletype) : "NULL"));
	}

      strcpy (SCP (szTableName), SCP ("BEFORE_FIRST_TABLE"));

      rc = SQLTables (stmt, UCP (tablequalifier), scbTableQualifier,
	  UCP (tableowner), scbTableOwner, UCP (tablename), scbTableName, UCP (tabletype), SWD (tabletype ? SQL_NTS : 0));
      if (rc == SQL_SUCCESS)
	{
/*      if(use_table_prefixes_flag) We bind the ALWAYS! */
	  {
	    SQLBindCol (stmt, 1,	/* The first column is TableQualifier. */
		SQL_C_CHAR, szTableQualifier, CHARCOL_LEN, &cbTableQualifier);

	    SQLBindCol (stmt, 2,	/* The second column is TableOwner. */
		SQL_C_CHAR, szTableOwner, CHARCOL_LEN, &cbTableOwner);
	  }

	  SQLBindCol (stmt, 3,	/* The third column is TableName. */
	      SQL_C_CHAR, szTableName, CHARCOL_LEN, &cbTableName);

	  SQLBindCol (stmt, 4,	/* The fourth column is TableType. */
	      SQL_C_CHAR, szTableType, CHARCOL_LEN, &cbTableType);

	  while (TRUE)
	    {
	      rc = SQLFetch (stmt);
	      if (rc == SQL_NO_DATA_FOUND)
		{
		  break;
		}
	      IF_ERR_GO (stmt, error, rc);


/* We get NULL tablename's when pattern is either %.. or .%.
   or tabletype is % and others are NULL. This is the enumeration
   special usage for qualifiers, owners and types respectively.
 */
	      if (dbdump_debug_level || (SQL_NULL_DATA == cbTableName))
		{
		  if (dbdump_debug_level || verbose_flag)
		    {
		      fprintf (stdout,
			  "-- %s: %sTableQualifier=\"%s\",%ld TableOwner=\"%s\",%ld "
			  "TableName=\"%s\",%ld TableType=\"%s\",%ld  patterntoken=\"%s\"\n",
			  where,
			  ((SQL_NULL_DATA == cbTableName) ? "Skipping, because: " : ""),
			  (szTableQualifier[0] ? SCP (szTableQualifier) : "NULL"),
			  cbTableQualifier,
			  (szTableOwner[0] ? SCP (szTableOwner) : "NULL"),
			  cbTableOwner,
			  (szTableName[0] ? SCP (szTableName) : "NULL"),
			  cbTableName,
			  (szTableType[0] ? SCP (szTableType) : "NULL"),
			  cbTableType, (SCP (tabletok) ? SCP (tabletok) : "NULL"));
		    }
		  if ((SQL_NULL_DATA == cbTableName))
		    {
		      continue;
		    }
		}

	      if (use_table_prefixes_flag)
		{
		  wholetablename
		      = new_whole_tablename (((SQL_NULL_DATA == cbTableQualifier)
			  ? NULL : szTableQualifier), ((SQL_NULL_DATA == cbTableOwner) ? NULL : szTableOwner), szTableName, where);
		}
	      else
		{		/* If no table-prefixes are used, then make just a copy. */
		  wholetablename = UCP (chestrdup (SCP (szTableName), where));
		}

	      debug_fprintf (stdout, "-- %s: wholetablename=%s\n", where, wholetablename);

	      if (find_tabledef (SCP (wholetablename), orgtl))
		{
		  /* do not load twice the same tables, in case user's
		     search patterns overlap. So we have to free that
		     constructed/copied wholetablename, because it will
		     not be used anywhere
		     (as there already is in orgtl list similarly named one)
		   */
		  free (wholetablename);
		}
	      else
		{
		  new_node = new_tabledeflist_node (NULL,	/* struct tabledeflist *next, */
		      SCP (wholetablename),	/* char *name, */
		      ((SQL_NULL_DATA == cbTableQualifier) ? NULL : SCP (chestrdup (SCP (szTableQualifier), where))), ((SQL_NULL_DATA == cbTableOwner) ? NULL : SCP (chestrdup (SCP (szTableOwner), where))), ((SQL_NULL_DATA == cbTableName) ? NULL : SCP (chestrdup (SCP (szTableName), where))), "",	/* char *columns, */
		      NULL,	/* char *all_columns, */
		      NULL,	/* char *primary_key_name, */
		      "",	/* char *primary_key_def, */
		      "",	/* char *primary_key_type, */
		      NULL,	/* char *super_table, */
		      default_insert_mode,	/* char *insert_mode, */
		      0,	/* int  automatically_included, */
		      0,	/* int  contains_blobs, */
		      NULL,	/* struct coldeflist *col_defs, */
		      NULL,	/* struct indexdeflist *index_defs, */
		      NULL,	/* struct tabledeflist *super_tl, */
		      NULL);	/* struct subtablelist *sub_tables */

		  if (orgtl == NULL)	/* First element! */
		    {
		      tl = orgtl = new_node;	/* orgtl to new_node, and tl to same */
		    }
		  else
		    {		/* Update the next link of the previous node, and set tl
				   then point to this new node (from right to left) */
		      tl = tl->next = new_node;
		    }

		  if (pcount)
		    {
		      ++*pcount;
		    }
		  n_tables++;
		}
	    }			/* while(TRUE) */
	}

    error:;

      SQLFreeStmt (stmt, SQL_UNBIND);
      SQLFreeStmt (stmt, SQL_CLOSE);

      if (SQL_SUCCESS != SQLTransact (henv, hdbc, SQL_COMMIT))
	{
	  print_error (SQL_NULL_HENV, hdbc, SQL_NULL_HSTMT);
	  exit (1);
	}
      if (NULL == tabletok)
	{
	  break;
	}			/* In case tablepatterns was NULL */
    }				/* loop for a while, while tokens last from tablepatterns string. */

  debug_fprintf (stdout, "-- get_all_tables: n_tables=%d\n", n_tables);
  return (orgtl);
}


/* Note from ODBC API Help file:

   SQLColumns returns the results as a standard result set, ordered
   by TABLE_QUALIFIER, TABLE_OWNER, and TABLE_NAME. The following
   table lists the columns in the result set. Additional columns
   beyond column 12 (REMARKS) can be defined by the driver.

 */


int
get_table_columns (struct tabledeflist *tl, int n_cols_with_describe_col)
		      /* If the second arg. is non-zero, then we use
		         SQLDescribeCol instead of SQLColumns */
{
  UCHAR *tablequalifier, *tableowner, *tablename;
  SWORD scbTableQualifier = SQL_NTS, scbTableOwner = SQL_NTS, scbTableName = SQL_NTS;
  SWORD s_cbColumnName;		/* To avoid warnings, we must use 2 different */
  SQLLEN l_cbColumnName;	/* variants for SQLBindCol and SQLDescribeCol */
  SWORD Type, Scale, Nullable;
  SQLULEN Precision;
  SQLLEN cbType, cbPrecision, cbScale, cbNullable;
  int rc;
  UWORD inx = 0;
  struct coldeflist *cl = NULL;
  UCHAR Column_Name[CHARCOL_LEN + 2];
  char temp[CHARCOL_LEN + 2];
  char where[CHARCOL_LEN + 80];

  sprintf (where, "get_table_columns(\"%s\",%d)", (tl->name ? tl->name : "NULL"), n_cols_with_describe_col);

  debug_fprintf (stdout, "-- %s\n", where);

  if (0 == n_cols_with_describe_col)	/* Use SQLColumns */
    {
      tablequalifier = NULL;	/* divide_tablename doesn't do its job */
      tableowner = NULL;	/* unless these two are NULL when called. */
/* Was:
       tablename = divide_tablename(UCP(tl->name),&tablequalifier,&tableowner);
 */
      tablename = divide_tablename_aux (UCP (tl->name), &scbTableName,
	  &tablequalifier, &scbTableQualifier, &tableowner, &scbTableOwner);

      rc = SQLColumns (stmt, tablequalifier, scbTableQualifier, tableowner, scbTableOwner, tablename, scbTableName, NULL, 0);	/* All columns. */

      if (rc == SQL_SUCCESS)
	{
	  SQLBindCol (stmt, 4, SQL_C_CHAR, Column_Name, CHARCOL_LEN, &l_cbColumnName);
	  SQLBindCol (stmt, 5,	/* DATA TYPE is SMALLINT NOT NULL */
	      SQL_C_SSHORT, &Type, 0, &cbType);
	  SQLBindCol (stmt, 7, SQL_C_SLONG, &Precision, 0, &cbPrecision);	/* INTEGER */
	  SQLBindCol (stmt, 9, SQL_C_SSHORT, &Scale, 0, &cbScale);	/* SMALLINT */
	  SQLBindCol (stmt, 11,	/* SMALLINT NOT NULL */
	      SQL_C_SSHORT, &Nullable, 0, &cbNullable);
	}
      else
	{
	  IF_ERR_GO (stmt, error, rc);
	}
    }

  /* No other function (e.g. any of the ones we call in this loop)
     should use tmp1 meanwhile, because we use it for constructing
     the columns string. */
  for (tmp1[0] = '\0', inx = 1; TRUE; inx++)
    {
      if (n_cols_with_describe_col)
	{
	  if (inx > n_cols_with_describe_col)
	    {
	      break;
	    }
	  rc = SQLDescribeCol (stmt, inx,
	      Column_Name, ((SWORD) CHARCOL_LEN), &s_cbColumnName, &Type, &Precision, &Scale, &Nullable);
	}
      else			/* Using SQLColumns with variables bound above. */
	{
	  rc = SQLFetch (stmt);
	  if (rc == SQL_NO_DATA_FOUND)
	    {
	      break;
	    }
	  if (cbScale == SQL_NULL_DATA)
	    {
	      Scale = 0;
	    }
	  if (cbPrecision == SQL_NULL_DATA)
	    {
	      Precision = 0;
	    }
	  if (cbNullable == SQL_NULL_DATA)
	    {
	      Nullable = SQL_NULLABLE_UNKNOWN;
	    }
	}
      IF_ERR_GO (stmt, error, rc);

      if ((n_cols_with_describe_col && (s_cbColumnName == SQL_NULL_DATA))
	  || (NOT n_cols_with_describe_col && (l_cbColumnName == SQL_NULL_DATA)))
	{			/* Shouldn't occur! */
	  fprintf (stdout, "-- Table %s has a column with NULL name (%d)!\n", tl->name, inx);
	  strcpy (SCP (Column_Name), "NULL");
	}

      if (tl->col_defs == NULL)	/* First column definition? */
	{			/* Start constructing the column definition list. */
	  cl = tl->col_defs = (struct coldeflist *) chemalloc (sizeof (struct coldeflist), where);
	}
      else
	{			/* Update the next link of the prev node. */
	  cl->next = (struct coldeflist *) chemalloc (sizeof (struct coldeflist), where);
	  cl = cl->next;
	}

      cl->col_name = chestrdup (SCP (Column_Name), where);
      cl->col_type = Type;
      cl->col_unquoted = !!belongs_to (SCP (tl->name ? tl->name : "NULL"), SCP (Column_Name), SCP (unquoted_columns));

      cl->col_is_nth_blob = 0;
#ifdef SQL_LONGVARCHAR
      if ((SQL_LONGVARCHAR == cl->col_type)
#ifdef SQL_LONGVARBINARY
	  || (SQL_LONGVARBINARY == cl->col_type)
#endif
	  )
	{
/* If tl->contains_blobs contained a count of blob columns in the table
   we would just increment it with:
          tl->contains_blobs++;
   But because now it contains the type of the first blob column
   (SQL_LONGVARCHAR or SQL_LONGVARBINARY), we use the following
   contraption:
*/
	  if (tl->contains_blobs)
	    {			/* There is already at least one blob column in this table? */
	      if (use_foreach_for_blobs_flag && verbose_flag)
		{
		  printf ("-- Table %s has more than one blob column.\n"
		      "-- The column %s of type %s might not get properly inserted.\n",
		      tl->name, cl->col_name, get_sql_type_title (cl->col_type));
		}
	      cl->col_is_nth_blob = 2;
	    }
	  else
	    {
	      tl->contains_blobs = cl->col_type;
	      cl->col_is_nth_blob = 1;
	    }
	}
#endif

      cl->col_precision = Precision;
      cl->col_scale = Scale;
      cl->col_nullable = Nullable;
      cl->next = NULL;
      /* The next two are for building the value of tl->columns */
      if (*tmp1)
	{
	  strcat (tmp1, ",");
	}
      strcat (tmp1, escapify (temp, SCP (Column_Name)));
    }				/* for loop */

  /* If we have come here after select * from table, then we have got */
  if (n_cols_with_describe_col)	/* all the columns, including those of */
    {
      tl->all_columns = chestrdup (tmp1, where);
    }				/* the possible supertables */
  tl->columns = chestrdup (tmp1, where);

  /* If we have used SQLDescribeCol, return here, don't free anything. */
  if (n_cols_with_describe_col)
    {
      return (n_cols_with_describe_col);
    }
error:;

  SQLFreeStmt (stmt, SQL_UNBIND);
  SQLFreeStmt (stmt, SQL_CLOSE);

  if (SQL_SUCCESS != SQLTransact (henv, hdbc, SQL_COMMIT))
    {
      print_error (SQL_NULL_HENV, hdbc, SQL_NULL_HSTMT);
      exit (1);
    }

  return (inx);
}


/* Taken from the KUBLREF.DOC:
   (Alternatives between (* and *) have been commented out from Kubl
   SQL Parser.)

base_table_def:
        CREATE TABLE table_name '(' base_table_element_commalist ')'
    ;

base_table_element_commalist:
        base_table_element
    |    base_table_element_commalist ',' base_table_element
    ;

base_table_element:
        column_def
    |    table_constraint_def
    ;

column_def:
        column data_type column_def_opt_list
    ;

column_def_opt_list:
        (* empty *)
    |    column_def_opt_list column_def_opt
    ;

column_def_opt:
        NOT NULL
(*    |    NOT NULL UNIQUE
    |    NOT NULL PRIMARY KEY opt_index_option_list
    |    DEFAULT literal
    |    DEFAULT NULL
    |    DEFAULT USER
    |    CHECK '(' search_condition ')'
    |    REFERENCES table
    |    REFERENCES table '(' column_commalist ')'
*)
    ;

table_constraint_def:
        UNDER table_name
    |    PRIMARY KEY '(' column_commalist ')' opt_index_option_list
(*    |    UNIQUE '(' column_commalist ')'
    |    FOREIGN KEY '(' column_commalist ')'
            REFERENCES table
    |    FOREIGN KEY '(' column_commalist ')'
            REFERENCES table '(' column_commalist ')'
    |    CHECK '(' search_condition ')'
*)
    ;

column_commalist:
        column
    |    column_commalist ',' column
    ;

index_option:
        CLUSTERED
    |    UNIQUE

    |    OBJECT_ID
    ;

index_option_list:
        index_option
    |    index_option_list index_option
    ;

opt_index_option_list:

    |    index_option_list
    ;

create_index_def:
        CREATE opt_index_option_list INDEX index
                        ON table_name '(' column_commalist ')'
    ;

E.g. only
        create table test(num integer, txt varchar, primary key(num))
works. But not the following:
        create table test(num integer not null primary key, txt varchar)
(From Tismer's mail).

The following examples work:

create table turilas(aapo integer, b varchar, primary key(aapo) unique);

create table purilas(aapo integer, b varchar, primary key(aapo) clustered);

create index huuli on purilas(b,aapo);

create unique index viili on purilas(b,aapo);

The following examples don't work:

SQL> create table test2(a integer, b varchar, primary key(a) not null);
*** Error 37000: 1: syntax error at not

SQL> create table test2(a integer not null, b varchar);
*** Error ....: A table must either have an UNDER or PRIMARY KEY
specification.
SQL> create table test2(a integer not null primary key, b varchar);
*** Error 37000: 1: syntax error at primary

SQL> create table cerdito(pekoni integer, juusto varchar, under cerdo,
                          primary key(pekoni,kalapussi));

*** Error ....: A table can't have both UNDER and PRIMARY KEY.

*/


/*
   scope_specified can be either:
        SQL_SCOPE_CURROW                        0 (default)
        SQL_SCOPE_TRANSACTION                   1
        SQL_SCOPE_SESSION                       2

   nullability can be either
        SQL_NO_NULLS                            0
        SQL_NULLABLE                            1

 */
int
get_table_bestrow_columns (struct tabledeflist *tl, UWORD scope_specified, UWORD nullability)
{
  UCHAR *tablequalifier, *tableowner, *tablename;
  SWORD scbTableQualifier = SQL_NTS, scbTableOwner = SQL_NTS, scbTableName = SQL_NTS;
  SWORD SCOPE, PSEUDO_COLUMN;
  SQLLEN cbSCOPE, cbPSEUDO_COLUMN;
  int rc, count = 0;
  UCHAR Column_Name[CHARCOL_LEN + 2];
  SQLLEN cbColumnName;
  char temp[CHARCOL_LEN + 10], where[CHARCOL_LEN + 80];

  sprintf (where, "get_table_bestrow_columns(\"%s\",%d,%d)", (tl->name ? tl->name : "NULL"), scope_specified, nullability);

  debug_fprintf (stdout, "-- %s\n", where);

  tablequalifier = NULL;	/* divide_tablename doesn't do its job */
  tableowner = NULL;		/* unless these two are NULL when called. */
  tablename = divide_tablename_aux (UCP (tl->name), &scbTableName,
      &tablequalifier, &scbTableQualifier, &tableowner, &scbTableOwner);

  rc = SQLSpecialColumns (stmt,
      ((UWORD) (SQL_BEST_ROWID)),
      UCP (tablequalifier), scbTableQualifier,
      UCP (tableowner), scbTableOwner,
      UCP (tablename), scbTableName, ((UWORD) (scope_specified ? scope_specified : SQL_SCOPE_CURROW)), ((UWORD) nullability));

  if (rc == SQL_SUCCESS)
    {
      SQLBindCol (stmt, 1, SQL_C_SSHORT, &SCOPE, 0, &cbSCOPE);
      SQLBindCol (stmt, 2, SQL_C_CHAR, Column_Name, CHARCOL_LEN, &cbColumnName);
      SQLBindCol (stmt, 8, SQL_C_SSHORT, &PSEUDO_COLUMN, 0, &cbPSEUDO_COLUMN);
/* Here IS_PSEUDO_COLUMN should contain one of the following values:
   (similarly SCOPE should contain one of those values listed in
    the comment before this function).
#define SQL_PC_UNKNOWN                  0
#define SQL_PC_NOT_PSEUDO               1
#define SQL_PC_PSEUDO                   2
 */

      tmp1[0] = '\0';		/* Build a string of column names to global buffer
				   tmp1, I hope that nobody else uses it meanwhile */
      while (TRUE)
	{
	  rc = SQLFetch (stmt);
	  if (rc == SQL_NO_DATA_FOUND)
	    {
	      break;
	    }
	  IF_ERR_GO (stmt, error, rc);

	  count++;
	  {			/* column of it, that has to be concatenated to a string. */

	    if (*tmp1)
	      {
		strcat (tmp1, ",");
	      }
	    strcat (tmp1, escapify (temp, SCP (Column_Name)));
	  }

	}			/* while(TRUE) */

      if (tmp1[0])		/* Got something? */
	{
	  tl->bestrow_columns = chestrdup (tmp1, where);
	}
      else
	{
	  tl->bestrow_columns = NULL;
	}

      debug_fprintf (stdout,
	  "-- get_table_bestrow_columns(\"%s\",%d,%d) -> %s\n",
	  (tl->name ? tl->name : "NULL"), scope_specified, nullability, (tl->bestrow_columns ? tl->bestrow_columns : "NULL"));
    }				/* if(rc == SQL_SUCCESS) */



error:;

  SQLFreeStmt (stmt, SQL_UNBIND);
  SQLFreeStmt (stmt, SQL_CLOSE);

  if (SQL_SUCCESS != SQLTransact (henv, hdbc, SQL_COMMIT))
    {
      print_error (SQL_NULL_HENV, hdbc, SQL_NULL_HSTMT);
      exit (1);
    }

  return (count);
}


/* This doesn't work properly if it is possible to create more than
   one primary key (which is oxymoron), i.e. the index name changes,
   and Seq_In_Index starts running from 1 again.
   Or if columns are not coming in the correct sequence.
   See module wi/sqlext.c for Kubl implementation of SQLPrimaryKeys
 */

int
get_table_primarykey (struct tabledeflist *tl)
{
  UCHAR *tablequalifier, *tableowner, *tablename;
  SWORD scbTableQualifier = SQL_NTS, scbTableOwner = SQL_NTS, scbTableName = SQL_NTS;
  SQLLEN cbTabQual, cbTabOwn, cbTabName;
  SQLLEN cbSuperTabQual, cbSuperTabOwn, cbSuperTabName;
  SQLLEN cbColumnName;
  SQLLEN cbIndexName;
  SWORD Seq_In_Index;
  SQLLEN cbSeq_In_Index;
  int rc, count = 0;
/* These are for Bind: */
  UCHAR Column_Name[CHARCOL_LEN + 2];
  UCHAR Index_Name[CHARCOL_LEN + 2];
  UCHAR TabQual[CHARCOL_LEN + 2], TabOwn[CHARCOL_LEN + 2];
  UCHAR TabName[CHARCOL_LEN + 2];
  UCHAR SuperTabQual[CHARCOL_LEN + 2], SuperTabOwn[CHARCOL_LEN + 2];
  UCHAR SuperTabName[CHARCOL_LEN + 2];
  char temp[CHARCOL_LEN + 2];
  char where[CHARCOL_LEN + 80];

  sprintf (where, "get_table_primarykey(\"%s\")", (tl->name ? tl->name : "NULL"));

  debug_fprintf (stdout, "-- %s\n", where);

  tablequalifier = NULL;	/* divide_tablename doesn't do its job */
  tableowner = NULL;		/* unless these two are NULL when called. */
/* Was:
    tablename = divide_tablename(UCP(tl->name),&tablequalifier,&tableowner);
 */
  tablename = divide_tablename_aux (UCP (tl->name), &scbTableName,
      &tablequalifier, &scbTableQualifier, &tableowner, &scbTableOwner);

  rc = SQLPrimaryKeys (stmt, tablequalifier, scbTableQualifier, tableowner, scbTableOwner, tablename, scbTableName);

  if (rc == SQL_SUCCESS)
    {
      SQLBindCol (stmt, 1, SQL_C_CHAR, TabQual, CHARCOL_LEN, &cbTabQual);
      SQLBindCol (stmt, 2, SQL_C_CHAR, TabOwn, CHARCOL_LEN, &cbTabOwn);
      SQLBindCol (stmt, 3, SQL_C_CHAR, TabName, CHARCOL_LEN, &cbTabName);
      SQLBindCol (stmt, 4, SQL_C_CHAR, Column_Name, CHARCOL_LEN, &cbColumnName);
      SQLBindCol (stmt, 5, SQL_C_SSHORT, &Seq_In_Index, 0, &cbSeq_In_Index);
      SQLBindCol (stmt, 6, SQL_C_CHAR, Index_Name, CHARCOL_LEN, &cbIndexName);

      if (kubl_mode)		/* The 7th column is a Non-Standard Kubl Extension */
	{
	  SQLBindCol (stmt, 7, SQL_C_CHAR, SuperTabQual, CHARCOL_LEN, &cbSuperTabQual);
	  SQLBindCol (stmt, 8, SQL_C_CHAR, SuperTabOwn, CHARCOL_LEN, &cbSuperTabOwn);
	  SQLBindCol (stmt, 9, SQL_C_CHAR, SuperTabName, CHARCOL_LEN, &cbSuperTabName);
	}

      tmp1[0] = '\0';		/* Build a string of column names to global buffer
				   tmp1, I hope that nobody else uses it meanwhile */
      while (TRUE)
	{
	  rc = SQLFetch (stmt);
	  if (rc == SQL_NO_DATA_FOUND)
	    {
	      break;
	    }
	  IF_ERR_GO (stmt, error, rc);

	  count++;
	  /* If the non-standard Kubl extension is used, and the seventh
	     eight, and ninth columns contain a table name which is
	     different from the first, second and third columns
	     (i.e. tl->name, the table name we are looking for at this
	     time), then this table has been defined as UNDER that
	     table, and has no primary key of its own. */
	  if (kubl_mode && (cbSuperTabName != SQL_NULL_DATA) && (strcmp (SCP (TabName), SCP (SuperTabName)) ||	/* Some of these */
		  strcmp (SCP (TabOwn), SCP (SuperTabOwn)) ||	/* three parts is */
		  strcmp (SCP (TabQual), SCP (SuperTabQual))))	/* different? */
	    {
	      if (tl->super_table == NULL)	/* Insert only once. */
		{
		  if (use_table_prefixes_flag)
		    {
		      tl->super_table = SCP (new_whole_tablename (SuperTabQual, SuperTabOwn, SuperTabName, where));
		    }
		  else
		    {
		      tl->super_table = chestrdup (SCP (SuperTabName), where);
		    }
		}
	    }
	  else			/* It is a table with primary key, and here we have one */
	    {			/* column of it, that has to be concatenated to a string. */

	      if (*tmp1)
		{
		  strcat (tmp1, ",");
		}
	      strcat (tmp1, escapify (temp, SCP (Column_Name)));

	      if ((cbIndexName != SQL_NULL_DATA) && (tl->primary_key_name == NULL))	/* Do this only once. */
		{
		  tl->primary_key_name = chestrdup (SCP (Index_Name), where);
		}
	    }

	}			/* while(TRUE) */

      tl->primary_key_def = chestrdup (tmp1, where);
    }				/* if(rc == SQL_SUCCESS) */



error:;

  SQLFreeStmt (stmt, SQL_UNBIND);
  SQLFreeStmt (stmt, SQL_CLOSE);

  if (SQL_SUCCESS != SQLTransact (henv, hdbc, SQL_COMMIT))
    {
      print_error (SQL_NULL_HENV, hdbc, SQL_NULL_HSTMT);
      exit (1);
    }

  return (count);
}


/* This function reads the real super table names of those
   table names for which get_table_primarykey (e.g. SQLPrimaryKeys)
   indicated to have a supertable. (thus being subtables of
   another table themselves).

   This is needed because Kubl's current SQLPrimaryKeys implementation
   returns incorrect information if table's immediate parent
   is not also its root ancestor. Or correct information if we
   define that it *should* return the name of the ancestor table,
   not one of the immediate parent.

   We have to use our own HSTMT statement handle grs_stmt here,
   because we might call SQLPrimaryKeys at the same time for some of
   new table names, in case the supertable names thus found here
   didn't match to the original tablename specification given by
   the user. So each new table thus encountered needs to be stealthily
   added here to the all_tables_list (actually inserted just to the
   next element of the currently handled one, so that it will be
   handled in the next iteration of loop), and after that
   get_table_primarykey called for also them, so that we see whether
   they got in turn further supertables.

   Returns as the result the number of new supertables added to
   all_tables_list.
 */

/* This is certainly a temporary kludge, until Kubl really implements
   tablequalifier (database) and tableowner parts.
 */
#define KUBL_CONSTANT_TABLE_PREFIXES "db.dba."

/* Yes, this is buggy with current Kubl, needs to be rewritten! */

int
get_real_supertables (struct tabledeflist *tl)
{
  UCHAR *tablequalifier, *tableowner, *tablename;
  SWORD scbTableQualifier = SQL_NTS, scbTableOwner = SQL_NTS, scbTableName = SQL_NTS;
  SQLLEN cbSuperTabName, cbTableName = SQL_NTS;
  UCHAR *SuperTabNamePtr;	/* Usually points to the start of SuperTabName */
  int rc, count = 0;
  struct tabledeflist *supertl;
  char *where = "get_real_supertables";
  HSTMT grs_stmt;
  UCHAR TableName[CHARCOL_LEN + 2];
  UCHAR SuperTabName[CHARCOL_LEN + sizeof (KUBL_CONSTANT_TABLE_PREFIXES) + 2];

  SQLAllocStmt (hdbc, &grs_stmt);


  strcpy (SCP (TableName), "KIRSIKKA");	/* A test. */

  SuperTabNamePtr = SuperTabName;
  if (use_table_prefixes_flag)
    {
      strcpy (SCP (SuperTabName), KUBL_CONSTANT_TABLE_PREFIXES);
      SuperTabNamePtr += strlen (SCP (KUBL_CONSTANT_TABLE_PREFIXES));
    }

/* We should use name_part here, get those three parts! */
  rc = SQLPrepare (grs_stmt,
      UCP ("select v2.KEY_TABLE from SYS_KEYS v1, SYS_KEY_SUBKEY, SYS_KEYS v2 "
	  "where v1.KEY_TABLE = ? and v1.KEY_IS_MAIN = 1 and SUB = v1.KEY_ID "
	  "and v2.KEY_ID = SUPER and v1.KEY_TABLE <> v2.KEY_TABLE"), SQL_NTS);
  IF_ERR_GO (grs_stmt, error, rc);

  rc = SQLSetParam (grs_stmt, 1, SQL_C_CHAR, SQL_CHAR, 0, 0, TableName, &cbTableName);
  IF_ERR_GO (grs_stmt, error, rc);

  rc = SQLBindCol (grs_stmt, 1, SQL_C_CHAR, SuperTabNamePtr, CHARCOL_LEN, &cbSuperTabName);
  IF_ERR_GO (grs_stmt, error, rc);

  for (; tl; tl = tl->next, SQLFreeStmt (grs_stmt, SQL_CLOSE))
    {
      if (NULL == tl->super_table)
	{
	  debug_fprintf (stdout, "-- get_real_supertables(%s) skipping...\n", tl->name);
	  continue;
	}
/* Was: strcpy(SCP(TableName),SCP(tl->name)); */
      tablequalifier = NULL;	/* divide_tablename doesn't do its job */
      tableowner = NULL;	/* unless these two are NULL when called. */
/* Was:
       tablename = divide_tablename(UCP(tl->name),&tablequalifier,&tableowner);
 */
      tablename = divide_tablename_aux (UCP (tl->name), &scbTableName,
	  &tablequalifier, &scbTableQualifier, &tableowner, &scbTableOwner);
      strcpy (SCP (TableName), SCP (tablename));

      rc = SQLExecute (grs_stmt);
      IF_ERR_GO (grs_stmt, error, rc);

      if (rc == SQL_SUCCESS)
	{

	  rc = SQLFetch (grs_stmt);
	  if (rc == SQL_NO_DATA_FOUND)
	    {
	      goto not_found;
	    }
	  IF_ERR_GO (grs_stmt, error, rc);

/* Was here: count++; */

	  if (verbose_flag)
	    {
	      fprintf (stdout, "-- get_real_supertable(%s) %s -> %s\n", tl->name, tl->super_table, SuperTabName);
	    }
	  if (0 != strcmp (SCP (SuperTabName), SCP (tl->super_table)))
	    {			/* If changed, then free the old one and alloc new one. */
	      if (tl->super_table)
		{
		  free (tl->super_table);
		}
	      tl->super_table = chestrdup (SCP (SuperTabName), where);
	    }
	}			/* if(rc == SQL_SUCCESS) */
      else
	{
	not_found:
	  fprintf (stdout,
	      "-- get_real_supertables(%s) Strange: No supertable name was found from\n"
	      "-- tables SYS_KEYS and SYS_KEY_SUBKEY, so keeping the old one = %s\n",
	      /* TableName */ tl->name, tl->super_table);
/*        goto error; */
	}

/* This is only circularity check we do at the moment.
   In case someone screws Kubl or the driver's SQLPrimaryKey's
   code really bad.
 */
      if (0 == strcmp (SCP (tl->name), SCP (tl->super_table)))
	{
	  fprintf (stdout,
	      "-- get_real_subtables(%s): Fatal screw-up: subtable and supertable have\n"
	      "-- got the same name: '%s'. Clearing subtable's super_table link to\n"
	      "-- avoid further circularity catastrophes.\n", tl->name, tl->super_table);
	  fflush (stdout);
	  free (tl->super_table);
	  tl->super_table = NULL;
	}
      if (tl->super_table)	/* Certainly this subtable has a super table. */
	{
	  supertl = find_tabledef (tl->super_table, all_tables_list);
	  if (supertl == NULL)
	    {
/* E.g. this might happen if the user dumps selectively some tables
   with a wildcard expression or single name, and (some) parent table(s)
   are not explicitly specified also. */
	      if (verbose_flag)
		{
		  fprintf (stdout,
		      "-- get_real_subtables(%s): Could not find the super table '%s' from\n"
		      "-- the existing table definitions; adding it to the table list\n"
		      "-- and reading its primary key information. Use options -TIC\n"
		      "-- to get its Table definition, Indices and Contents respectively\n"
		      "-- to the output, or include its name explicitly in tablename argument.\n", tl->name, tl->super_table);
		}
	      supertl = new_tabledeflist_node (tl->next,	/* struct tabledeflist *next, */
		  chestrdup (SCP (tl->super_table), where),	/* char *name, */
		  "SuperQual", "SuperOwn", "SuperName",	/* To be replaced! */
/* Should be something like this:
                       ((SQL_NULL_DATA == cbTableQualifier) ? NULL
                         : UCP(chestrdup(SCP(szTableQualifier),where))),
                       ((SQL_NULL_DATA == cbTableOwner) ? NULL
                         : UCP(chestrdup(SCP(szTableOwner),where))),
                       ((SQL_NULL_DATA == cbTableName) ? NULL
                         : UCP(chestrdup(SCP(szTableName),where))),
 */
		  "",		/* char *columns, */
		  NULL,		/* char *all_columns, */
		  NULL,		/* char *primary_key_name, */
		  "",		/* char *primary_key_def, */
		  "",		/* char *primary_key_type, */
		  NULL,		/* char *super_table, */
		  default_insert_mode,	/* char *insert_mode, */
		  1,		/* int  automatically_included, */
		  0,		/* int  contains_blobs, */
		  NULL,		/* struct coldeflist *col_defs, */
		  NULL,		/* struct indexdeflist *index_defs, */
		  NULL,		/* struct tabledeflist *super_tl, */
		  NULL);	/* struct subtablelist *sub_tables */
	      /* Read the primary key information (and with Kubl also
	         the potential, tentative supertable name) of supertl,
	         and then immediately next time in this loop we check supertl's
	         supertable if it has one of its own
	         (whose name get_table_primarykey will in that case set
	         to super_table slot of supertl)
	       */
	      get_table_primarykey (supertl);
	      tl->next = supertl;
	      count++;
	    }
	}
    }				/* for loop */


error:;
  SQLFreeStmt (grs_stmt, SQL_UNBIND);
  SQLFreeStmt (grs_stmt, SQL_RESET_PARAMS);
  SQLFreeStmt (grs_stmt, SQL_CLOSE);	/* Maybe called unnecessarily, maybe not. */
  SQLFreeStmt (grs_stmt, SQL_DROP);

  if (SQL_SUCCESS != SQLTransact (henv, hdbc, SQL_COMMIT))
    {
      print_error (SQL_NULL_HENV, hdbc, SQL_NULL_HSTMT);
      exit (1);
    }

  return (count);
}


/* The following should match with SQL_INDEX_OBJECT_ID_STR defined in
   sqlext.c ! (Now both defined in kublext.h and kublextw.h)
   And of course it should be different from all standard SQL INDEX TYPE
   definitions defined in sqlext.h (Actually, all those values might
   be added to this one, or bit-ored if you think it that way.)
 */
/* #define SQL_INDEX_OBJECT_ID 8 Now defined in kublext(w).h */


int
get_table_indices (struct tabledeflist *tl)
{
  UCHAR *tablequalifier, *tableowner, *tablename;
  SWORD scbTableQualifier = SQL_NTS, scbTableOwner = SQL_NTS, scbTableName = SQL_NTS;
  SQLLEN cbIndexName, cbColumnName;
  SWORD Non_Unique = 555, Seq_In_Index = 666, Type = 777;
  SQLLEN cbNon_Unique, cbSeq_In_Index, cbType;
  int rc;
  int count = 0;
  int this_one_is_primary_key = 0;
  int previous_one_was_primary_key = this_one_is_primary_key;
  struct indexdeflist *il = NULL;
  char *turnipsi_pointteri = NULL;	/* Crazy, isn't it? Lets me sleep. */
  UCHAR Index_Name[CHARCOL_LEN + 2], Column_Name[CHARCOL_LEN + 2];
  char indextype[CHARCOL_LEN + 2];
  char Previous_Index_Name[CHARCOL_LEN + 2], temp[CHARCOL_LEN + 2];
  char where[CHARCOL_LEN + 80];

  sprintf (where, "get_table_indices(\"%s\")", (tl->name ? tl->name : "NULL"));
  debug_fprintf (stdout, "-- %s\n", where);

  tablequalifier = NULL;	/* divide_tablename doesn't do its job */
  tableowner = NULL;		/* unless these two are NULL when called. */
/* Was:
    tablename = divide_tablename(UCP(tl->name),&tablequalifier,&tableowner);
 */
  tablename = divide_tablename_aux (UCP (tl->name), &scbTableName,
      &tablequalifier, &scbTableQualifier, &tableowner, &scbTableOwner);
  rc = SQLStatistics (stmt, tablequalifier, scbTableQualifier,
      tableowner, scbTableOwner, tablename, scbTableName, SQL_INDEX_ALL, SQL_ENSURE);

/* Note from ODBC API Help file:

   SQLStatistics returns information about a single table as
   a standard result set, ordered by NON_UNIQUE, TYPE, INDEX_QUALIFIER,
   INDEX_NAME, and SEQ_IN_INDEX. The result set combines statistics
   information for the table with information about each index.

   If the row in the result set corresponds to a table, the driver sets
   TYPE to SQL_TABLE_STAT and sets NON_UNIQUE, INDEX_QUALIFIER, INDEX_NAME,
   SEQ_IN_INDEX, COLUMN_NAME, and COLLATION  to NULL. If CARDINALITY or
   PAGES are not available from the data source, the driver sets them to
   NULL.

 */

  if (rc == SQL_SUCCESS)
    {
      SQLBindCol (stmt, 4,	/* NON_UNIQUE is SMALLINT: NULL, 0 or 1 */
	  SQL_C_SSHORT, &Non_Unique, 0, &cbNon_Unique);
      SQLBindCol (stmt, 6, SQL_C_CHAR, Index_Name, CHARCOL_LEN, &cbIndexName);
      SQLBindCol (stmt, 7,	/* TYPE is SMALLINT NOT NULL */
	  SQL_C_SSHORT, &Type, 0, &cbType);
      SQLBindCol (stmt, 8,	/* SEQ_IN_INDEX is SMALLINT: NULL, 1, 2, etc. */
	  SQL_C_SSHORT, &Seq_In_Index, 0, &cbSeq_In_Index);
      SQLBindCol (stmt, 9, SQL_C_CHAR, Column_Name, CHARCOL_LEN, &cbColumnName);



/* Note that this code doesn't work correctly in the hypothetical cases,
   where the index has more than one type specified, e.g. something
   like CLUSTERED HASHED. However, now CLUSTERED OBJECT_ID, etc. work.
 */

      for (count = 0, strcpy (Previous_Index_Name, ""), tmp1[0] = '\0';
/* cond */ TRUE;
/* update */ count++, strcpy (SCP (Previous_Index_Name), SCP (Index_Name)),
/* part: */ previous_one_was_primary_key = this_one_is_primary_key)
	{
	  rc = SQLFetch (stmt);
	  if (rc == SQL_NO_DATA_FOUND)
	    {
	      break;
	    }
	  IF_ERR_GO (stmt, error, rc);
	  *indextype = '\0';	/* Clear the string. */
	backwards:
	  switch (Type)
	    {			/* Skip rows for table itself, because other cols are NULLs */
	    case SQL_TABLE_STAT:	/* 0 */
	      {
		continue;
	      }
	    case SQL_INDEX_CLUSTERED:	/* 1 */
	      {
		my_strncat (indextype, " CLUSTERED", CHARCOL_LEN);
		break;
	      }
	    case SQL_INDEX_HASHED:	/* 2 */
	      {
		my_strncat (indextype, " HASHED", CHARCOL_LEN);
		break;
	      }
	    case SQL_INDEX_OTHER:	/* 3 Normal, nothing special */
	      {			/* indextype = ""; */
		break;
	      }			/* Do nothing. */
	    default:
	      {
		if (Type & SQL_INDEX_OBJECT_ID)	/* 8 Kubl extension ? */
		  {
		    my_strncat (indextype, " OBJECT_ID", CHARCOL_LEN);
		    Type &= ~SQL_INDEX_OBJECT_ID;	/* Clear object_id bit */
		    if (Type)
		      goto backwards;	/* And go add rest. */
		  }		/* Type should be never returned as 8. If it is then
				   we might a catch the bug when we get the following warning
				   type concatenated after the keyword OBJECT_ID itself: */
		sprintf (indextype + strlen (indextype), " UNK-INDEX-TYPE(%d)", Type);
	      }
	    }

	  if (strcmp (SCP (Index_Name), SCP (Previous_Index_Name)))
	    {			/* indname changed? */
	      /* Save what has been collected to tmp1 to the right place: */
	      if (previous_one_was_primary_key)
		{
		  tl->primary_key_def = chestrdup (tmp1, where);
		}
	      else if (*tmp1)
		{
		  if (il)
		    {
		      il->index_def = chestrdup (tmp1, where);
		    }
		  else		/* This is the first index, and no index list has been
				   allocated yet, so save it to temp pointer variable
				   so that it can be later stored into the appropriate
				   place, after that place has been allocated. */
		    {
		      turnipsi_pointteri = chestrdup (tmp1, where);
		    }
		}
	      tmp1[0] = '\0';
	    }

	  /* This is for Access. I clear this later.
	   */
	  if (( /* NOT kubl_mode && */ !strcmp (SCP (Index_Name), "PrimaryKey")))
	    {
	      this_one_is_primary_key = 1;

	      if (*tmp1)
		{
		  strcat (tmp1, ",");
		}
	      strcat (tmp1, escapify (temp, SCP (Column_Name)));

	      if ((tl->primary_key_type == NULL) || empty_stringp (tl->primary_key_type))
		{
		  tl->primary_key_type = chestrdup (indextype, where);
		}
	    }

/* In Kubl mode just note the type of the primary key of the table
   encountered here, whose name has been saved to tl->primary_key_name
   when encountered previously with get_table_primarykey.
   This is for strange cases like
    create table ab(a integer, b varchar, primary key(a) clustered);
   We probably don't need to care about things like: primary key(a) unique
   because primary keys are unique anyway.
   Note that the primary key's name is not necessarily same as
   tl->table_name if the table has been later renamed with ALTER TABLE
   tab RENAME command, or if it is a subtable of another table.

   Changed 28-JAN-1998: Now effective also with other DBMS'ses
   than Kubl. However, only with Kubl we note the type of primary
   key index. E.g. with MS SQL Server, Primary Keys are always
   defined as:

   CREATE UNIQUE CLUSTERED INDEX PK__answer__1E8492F7
   ON kublbm.dbo.answer(a_user,a_qn_id,a_nth,a_q_name);

   So we don't print this redundant index anymore with MS SQL
   (as it is already defined in PRIMARY KEY(...) inside table-definition).
   However, we don't define it as PRIMARY KEY(...) CLUSTERED,
   because, as I understand, CLUSTERED has different meaning in
   Kubl and MS SQL.
 */
	  else if ( /* kubl_mode && */ tl->primary_key_name
	      && !strcmp (SCP (Index_Name), SCP (tl->primary_key_name)))
	    {
	      if (kubl_mode && ((tl->primary_key_type == NULL) || empty_stringp (tl->primary_key_type)))
		{
		  tl->primary_key_type = chestrdup (indextype, where);
		}
	    }
	  else			/* It's an index created with CREATE INDEX. */
	    {
	      this_one_is_primary_key = 0;
	      if (strcmp (SCP (Index_Name), SCP (Previous_Index_Name)))
		{		/* indname changed? */
		  if (tl->index_defs == NULL)	/* First index definition? */
		    {
		      il = tl->index_defs = (struct indexdeflist *) chemalloc (sizeof (struct indexdeflist), where);
		      if (turnipsi_pointteri)	/* Something for us? */
			{
			  il->index_def = turnipsi_pointteri;
			}
		    }
		  else
		    {
		      /* Update the next link of the prev node. */
		      il->next = (struct indexdeflist *) chemalloc (sizeof (struct indexdeflist), where);
		      il = il->next;
		    }

		  /* First column for this index? */
		  sprintf (tmp1, "CREATE%s%s INDEX %s ON ",
		      (((cbNon_Unique != SQL_NULL_DATA) && NOT Non_Unique)
			  ? " UNIQUE" : ""), indextype, escapify (temp, SCP (Index_Name)));
		  strcat (tmp1, escapify_and_form_dest_name (temp, (sizeof (temp) - 1), SCP (tl->name)));
		  strcat (tmp1, "(");
		  strcat (tmp1, escapify (temp, SCP (Column_Name)));

		  il->index_name = chestrdup (SCP (Index_Name), where);
		}
	      else		/* The second or further column for this index. */
		{		/* Just add the col name to the end of index definition: */
		  if (*tmp1)
		    {
		      strcat (tmp1, ",");
		    }
		  strcat (tmp1, escapify (temp, SCP (Column_Name)));
		}
	      il->next = NULL;

	    }			/* else it was an index created with CREATE INDEX. */

	}			/* for loop */

/* We still have to save what we have collected to tmp1 on
   the last round of the loop, to the appropriate place */
      if (previous_one_was_primary_key)
	{
	  tl->primary_key_def = chestrdup (tmp1, where);
	}
      else if (il && *tmp1)
	{
	  il->index_def = chestrdup (tmp1, where);
	}

    }				/* if(rc == SQL_SUCCESS) */

error:;

  SQLFreeStmt (stmt, SQL_UNBIND);
  SQLFreeStmt (stmt, SQL_CLOSE);

  if (SQL_SUCCESS != SQLTransact (henv, hdbc, SQL_COMMIT))
    {
      print_error (SQL_NULL_HENV, hdbc, SQL_NULL_HSTMT);
      exit (1);
    }

  return (count);
}

/* ================================================================== */
/*         FUNCTIONS FOR PRINTING OUT THE STUFF COLLECTED ABOVE       */
/* ================================================================== */

void
print_datetime_col (char *timebinstr, SQLLEN collen, int type)
{
  char temp[121];

  if (times_conform_to_odbc_flag)
    {
      if (times_to_strings_flag)
	sprintf (temp, "%*s", (int) collen, timebinstr);
      else if (type == SQL_DATE)
	{
	  /* Defined in /odbcsdk/include/sqlext.h */
	  TIMESTAMP_STRUCT *ts = ((TIMESTAMP_STRUCT *) timebinstr);
	  sprintf (temp, "%04d.%02d.%02d", ts->year, ts->month, ts->day);
	}
      else if (type == SQL_TIMESTAMP)
	{
	  /* Defined in /odbcsdk/include/sqlext.h */
	  TIMESTAMP_STRUCT *ts = ((TIMESTAMP_STRUCT *) timebinstr);
	  sprintf (temp, "%04d.%02d.%02d %02d:%02d.%02d %06ld",
	      ts->year, ts->month, ts->day, ts->hour, ts->minute, ts->second, (long) ts->fraction);
	}
      else if (type == SQL_TIME)
	{
	  /* Defined in /odbcsdk/include/sqlext.h */
	  TIMESTAMP_STRUCT *ts = ((TIMESTAMP_STRUCT *) timebinstr);

	  sprintf (temp, "%02d:%02d.%02d", ts->hour, ts->minute, ts->second);
	}
      else			/* Shouldn't happen! */
	{
	  sprintf (temp, "SHOULD NOT HAPPEN: print_date_col called(collen=%ld,type=%d)", (long int) collen, type);
	}
    }
  else				/* Native KUBL mode. */
    {
      struct tm *tm;
      struct timeval tv;
      time_t now;

      memcpy (&tv, timebinstr, sizeof (struct timeval));
      TV_TO_STRING (&tv);

      tm = localtime (&now);
      tv.tv_sec = (long) now;
      if (tm)
	{
	  sprintf (temp, "%04d.%02d.%02d %02d:%02d.%02d %06ld",
	      tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec);
	}
      else			/* localtime returned NULL pointer. */
	{
	  sprintf (temp, "INV-TIME(%ld):%08lx:%08lx", (long) collen, tv.tv_sec, tv.tv_usec);
	}
    }

  switch (type)
    {
    case SQL_DATE:
    case SQL_TIMESTAMP:
      printf ("stringdate('%s')", temp);
      break;
    case SQL_TIME:
      printf ("stringtime('%s')", temp);
      break;
    default:
      printf ("%s", temp);
    }
  fflush (stdout);
}



#define print_string_col(s,len,eflag)\
  print_string_col_aux((s),(len),(eflag), 0, 0, NULL, NULL)

/*
   Prints the string s out, and for every single quote present
   prints two single quotes out, which is the standard SQL way of
   escaping a single quote.

   If flag use_backslash_escapes is present, then escape all
   non-printable characters by prefixing them with a backslash.

   This doesn't print the surrounding single quotes.

   The last four arguments are used solely when printing foreach
   stuff for blobs. There are additional quirks for them.

   Returns as a result the new value of chars_since_newline

   The corresponding unescaping function is unescape_string in isql.c
 */
long
print_string_col_aux (UCHAR * s, size_t length, int use_backslash_escapes,
    int is_foreach_blob, long chars_since_newline, char *end_token, char *blob_token)
{
  for (; length--; s++)
    {
      if ('\n' == *s)
	{
	  chars_since_newline = 0;
	}
      else
	{
	  chars_since_newline++;
	}

      if ((SQL_LONGVARCHAR == is_foreach_blob) && maxlinelength_for_foreach && (chars_since_newline >= maxlinelength_for_foreach))
	{
/* If over the allowed line length, then cut the string with \c cut
   escape sequence, and print a newline after that. (\c forces
   ISQL in turn to ignore the following newline, when it reads
   the stuff in with read_blob_from_input and unescape_string).
 */
	  printf ("\\c\n");
	  chars_since_newline = 0;
	}

#ifdef SQL_LONGVARBINARY
/* With binary blobs (got with type SQL_C_CHAR as hexadecimal dump,
   two hex-digits for each byte), we print a newline after every
   64 characters. This blob will be then read in with ISQL with
   FOREACH HEXADECIMAL BLOB INSERT INTO ... statement.
 */
      if ((SQL_LONGVARBINARY == is_foreach_blob) && (empty_stringp (s) ||	/* Either finished? Or... */
	      (maxhexlength_for_foreach &&	/* time to print a newline? */
		  (chars_since_newline >= maxhexlength_for_foreach))))
	{
	  if (empty_stringp (s))
	    {
	      break;
	    }
	  printf ("\n");
	  chars_since_newline = 0;
/* If hexadecimal digits finished, then break from the loop and return */
	}
#endif

/* If the line happens to begin with the end or blob token, then escape
   its first letter: */
      if ((1 == chars_since_newline) &&
	  ((end_token && !strncmp (SCP (s), end_token, strlen (SCP (end_token))))
	      || (blob_token && !strncmp (SCP (s), blob_token, strlen (SCP (blob_token))))))
	{
	  printf ("\\%o", *s);
	  continue;		/* Skip printing of *s in the end of the loop. */
	}
      if (use_backslash_escapes && ((*s != '\'') || NOT use_singlequote_escape))
	{
	  /* Escape everything that is not pure ascii, */
	  /* as well the backslash itself and the singlequote */
	  /* However, with blobs leave newlines as they are. */
	  if (((*s < 32) && (NOT (is_foreach_blob) || (*s != '\n'))) || (*s > 126) || (*s == '\\') || (*s == '\''))
	    {
/* If user gave more than one -e option, then escape also all
   visible ISO-8859/1 letters between 161-255: */
	      if ((use_backslash_escapes > 1) || (*s < 161))
		{
		  printf ("\\%o", *s);
		  continue;	/* Skip printing of *s in the end of the loop */
		}
	    }			/* if it wasn't escapable character, then we fall through. */
	}
      else			/* In SQL standard, we prefix each quote with another one. */
	{			/* And everything else, Vaya con Dios! */
	  if (*s == '\'')
	    {
	      putchar ('\'');
	    }
	}

      putchar (*s);
    }


  fflush (stdout);
  return (chars_since_newline);
}


#define BLOB_BUFFER_SIZE 4096

/* This should be different from all SQL return codes: */
#define PRINT_BLOB_COL__CALL_ME_AGAIN_RC 12345

/*
   print_blob_col either

   1) Prints out the whole blob column as a string literal, with
      appropriate escaping, depending of the global flag
      use_backslash_escapes_in_strings_flag

   2) or if the use_foreach_for_blobs global flag is on and
      the blob column is the ONLY or FIRST blob column on the row
      (if not, then prints it out just like in case 1)
      then checks whether really_do_it argument is

      A) zero (called first time), in which case just prints out
         the parameter marker ? in the middle of insert ... values(...),
         and returns the "private return code" value CALL_ME_AGAIN
         defined above.

      B) or really_do_it is non-zero (called second time for this column,
         after the whole insert statement has been printed), in which
         case outputs the blob data immediately after FOREACH BLOB INSERT
         statement with appropriate escape characters, regardless of the
         value of the global flag  use_backslash_escapes_in_strings_flag

         See function read_blob_from_input in isql.c how the stuff
         produced by this mode is later read in.

         If really_do_it is greater than 1, then the blob to be output
         is the last blob column, and so the delimiting token should
         be END instead of BLOB.

   Returns return code from the last SQLGetData done, or the kludgous
   value defined above.

 */
int
print_blob_col (UWORD n_col, struct coldeflist *cl, int really_do_it)
{
  UCHAR last_character = '\0';
  UCHAR blob_buffer[BLOB_BUFFER_SIZE + 3];
  size_t got_n_bytes;
  size_t total = 0;
  long chars_since_newline = -1;
  int rc;
  int type = cl->col_type;
  int use_foreach_now = (use_foreach_for_blobs_flag && (0 != cl->col_is_nth_blob));
  char *token_to_use = ((really_do_it > 1) ? foreach_end_token : foreach_blob_token);

  if (NOT really_do_it && use_foreach_now)
    {
      putchar ('?');		/* This time we output just a parameter marker. */
      /* And ask the caller to call us again when the whole INSERT
         statement (all other column literal values) has been printed. */
      return (PRINT_BLOB_COL__CALL_ME_AGAIN_RC);
    }

  if (NOT use_foreach_now)
    {
      putchar ('\'');
    }				/* The beginning single quote. */

  for (;;)
    {
      SQLLEN n_recv;
      rc = SQLGetData (stmt, n_col, SQL_C_CHAR, blob_buffer, ((SQLLEN) BLOB_BUFFER_SIZE), &n_recv);

/* Here we got either SQL_NO_DATA or an error. */
      if (((rc != SQL_SUCCESS) && (rc != SQL_SUCCESS_WITH_INFO)) || (n_recv == SQL_NULL_DATA))
	{			/* This ^ means really a blob of length 0, not real NULL ??? */
	  /* With foreach, just print the END token immediately after the
	     FOREACH BLOB INSERT statement, and ISQL will understand that
	     it is an empty blob: */
/* Tell calling function that everything is still all right, no panic: */
	  if (SQL_NO_DATA_FOUND == rc)
	    {
	      rc = SQL_SUCCESS;
	    }
	  if (use_foreach_now)
	    {
	      printf ("%s\n", token_to_use);
	    }
	  /* Otherwise, it is printed out as a string literal '': */
	  else
	    {
	      fputs ("'", stdout);
	    }			/* The ending quote. */
	  fflush (stdout);
	  return (rc);
	}

/* If we get SQL_NO_TOTAL, then we have to use strlen. This doesn't
    work with true binary data with null bytes in the last part. */
      got_n_bytes = ((rc == SQL_SUCCESS) ? ((n_recv != SQL_NO_TOTAL) ? n_recv : strlen (SCP (blob_buffer))) : BLOB_BUFFER_SIZE - 1);	/* Not the last part. */
/* When inputting binary blobs as hexadecimal dump, this will get the
   real length hexdigit string to be printed: */
#ifdef SQL_LONGVARBINARY
      if (SQL_LONGVARBINARY == type)
	{
	  got_n_bytes = strlen (SCP (blob_buffer));
	}
#endif

      total += got_n_bytes;
      blob_buffer[got_n_bytes] = '\0';	/* Make sure it is terminated. */
      if (got_n_bytes)
	{
	  last_character = blob_buffer[got_n_bytes - 1];
	}

/* Was: fwrite(blob_buffer,got_n_bytes,sizeof(char),stdout); */
/* With string literal blobs, always use the value of
   use_backslash_escapes_in_string_flag
   With foreach blobs use its value if it is not zero (in that case use 1)
 */
      chars_since_newline = print_string_col_aux (UCP (blob_buffer), got_n_bytes, ((use_backslash_escapes_in_strings_flag || NOT (use_foreach_now)) ? use_backslash_escapes_in_strings_flag : 1), (use_foreach_now ? type : 0),	/* is foreach blob? */
	  chars_since_newline, (use_foreach_now ? foreach_end_token : NULL), (use_foreach_now ? foreach_blob_token : NULL));

      if (rc == SQL_SUCCESS)	/* No more data after this one. */
	{
	  if (use_foreach_now)
	    {			/* If there were any stuff, and the last char was not a newline,
				   then print out the magic escape sequence \c (followed
				   by a newline) to cut the last line of blob at that point.
				   See unescape_string in ISQL.c for more information.
				   However, don't print that with binary blobs.
				 */
	      if (total && ('\n' != last_character)
#ifdef SQL_LONGVARBINARY
		  && (SQL_LONGVARBINARY != type)
#endif
		  )
		{
		  printf ("\\c\n");
		}
#ifdef SQL_LONGVARBINARY
/* Print the last newline after hexadecimal dump, if it is necessary: */
	      if ((SQL_LONGVARBINARY == type) && (chars_since_newline > 0))
		{
		  printf ("\n");
		}
#endif
	      printf ("%s\n", token_to_use);
	    }
	  else			/* Has been output as a string literal. */
	    {
	      putchar ('\'');
	    }			/* The ending single quote. */

	  return (rc);
	}
    }				/* for loop */

  return (rc);			/* Never reached */

}



#define MAXBLOBS_IN_ROW 101	/* Uhhuh. */
/* Returns either SQL_SUCCESS or the last return code returned by
   print_blob_col (which calls SQLGetData in the loop.) */
int
print_table_row (struct tabledeflist *tl)
{
  char temp[CHARCOL_LEN + 3];
  UWORD inx;
  struct coldeflist *cl;
/* Was:
  struct coldeflist *blob_column_to_be_printed_out_later = NULL;
  UWORD blob_colindex_to_be_printed_out_later = 0; */
  struct coldeflist *blob_columns_to_be_printed_out_later[MAXBLOBS_IN_ROW + 1];
  UWORD blob_colindexes_to_be_printed_out_later[MAXBLOBS_IN_ROW + 1];
  int n_blobs = 0;
  int rc = SQL_SUCCESS;

  if (use_foreach_for_blobs_flag && tl->contains_blobs)
    {
      printf ("FOREACH %sBLOB ",
#ifdef SQL_LONGVARBINARY
	  ((SQL_LONGVARBINARY == tl->contains_blobs) ? "HEXADECIMAL " : "")
#else
	  ""
#endif
	  );
    }

  printf ("INSERT %s %s(%s)",
      tl->insert_mode,
      escapify_and_form_dest_name (temp, (sizeof (temp) - 1), SCP (tl->name)), (tl->all_columns ? tl->all_columns : tl->columns));

  if (nicer_output_flag)
    {
      fputs ("\n ", stdout);	/* VALUES on its own line, indented */
    }
  else
    {
      putc (' ', stdout);
    }
  fputs ("VALUES(", stdout);

/* We should print a warning here if the length tl->col_defs and n_out_cols
   don't match. */
  for (inx = 0, cl = tl->col_defs; (inx < n_out_cols) && cl; inx++)
    {
      int tp = cl->col_type;
      if (out_cols[inx].o_col_len == SQL_NULL_DATA)
	{
	  fputs ("NULL", stdout);
	  fflush (stdout);
	}
      else
	{
	  switch (tp)
	    {
	    case SQL_NUMERIC:
	    case SQL_DECIMAL:
	    case SQL_DOUBLE:
	    case SQL_FLOAT:
	    case SQL_REAL:
	    case SQL_INTEGER:
	    case SQL_TINYINT:
	    case SQL_SMALLINT:
	    case SQL_BIGINT:
	    case SQL_BIT:
	      {			/* All the numeric types, don't use any single quotes! */
		fputs (out_cols[inx].o_buffer, stdout);
		fflush (stdout);
		break;
	      }
	    case SQL_DATE:
	    case SQL_TIME:
	    case SQL_TIMESTAMP:
	      {
		print_datetime_col (out_cols[inx].o_buffer, out_cols[inx].o_col_len, tp);
		break;
	      }
	    case SQL_LONGVARCHAR:
	    case SQL_LONGVARBINARY:
/* LONGVARBINARY works only if driver converts it into e.g. hexadecimal
   text that doesn't contain any null or other deviant bytes. */
	      {
		if (print_blobs_flag)
		  {		/* Note 0-based indexing here. print_blob_col needs one+ */
		    rc = print_blob_col (((UWORD) (inx + 1)), cl, 0);
		    if (rc == PRINT_BLOB_COL__CALL_ME_AGAIN_RC)
		      {
/*
                   blob_colindex_to_be_printed_out_later = (UWORD)(inx+1);
                   blob_column_to_be_printed_out_later = cl;
 */
			blob_colindexes_to_be_printed_out_later[n_blobs] = (UWORD) (inx + 1);
			blob_columns_to_be_printed_out_later[n_blobs] = cl;
			n_blobs++;
		      }
		    else if (SQL_SUCCESS != rc)
		      {
			return (rc);
		      }
		  }
		else
		  {
		    if (out_cols[inx].o_col_len == SQL_NO_TOTAL)
		      {
			strcpy (temp, "BLOB SQL_NO_TOTAL");
		      }
		    else
		      {
			sprintf (temp, "BLOB %ld b", out_cols[inx].o_col_len);
		      }
		    print_string_col (UCP (temp), strlen (temp), use_backslash_escapes_in_strings_flag);
		  }
		break;
	      }
	    default:
	      {			/* It's SQL_CHAR, SQL_VARCHAR, SQL_BINARY, SQL_VARBINARY
				   or something which needs to be surrounded with quotes. */
		SQLLEN real_len = out_cols[inx].o_col_len;

#ifdef SQL_VARCHAR
/* With SQL_VARCHARs the column length returned by the driver/API function
contains also a terminating zero byte. Let's correct it if it's not zero.
At least this was the case with old erroneous Kubl drivers.
However, with Access, the length doesn't include the terminating zero. */
		if ((SQL_VARCHAR == tp) && real_len && varchar_cols_returned_with_length_plus)	/* With old Kubl */
		  {
		    real_len -= varchar_cols_returned_with_length_plus;
		  }
#endif

		if (!cl->col_unquoted)
		  {
		    putchar ('\'');
		  }
		print_string_col (UCP (out_cols[inx].o_buffer), real_len, use_backslash_escapes_in_strings_flag);
		if (!cl->col_unquoted)
		  {
		    putchar ('\'');
		  }
		break;
	      }
	    }			/* switch */
	}			/* else it was not NULL */
      cl = cl->next;
      if (cl)
	{
	  putc (',', stdout);
	}			/* Not the last one? */
/*   if(inx < (n_out_cols-1)) { putchar(','); }  WAS THIS */
    }				/* for */
  printf (");\n");
  fflush (stdout);

/* This old mechanism allowed only one foreach blob per row:
  if(blob_column_to_be_printed_out_later)
   {
     rc = print_blob_col(blob_colindex_to_be_printed_out_later,
                         blob_column_to_be_printed_out_later,
                         1);
     fflush(stdout);
   }
 */
  if (n_blobs)
    {
      int i;
      for (i = 0; i < n_blobs; i++)
	{
	  rc = print_blob_col (blob_colindexes_to_be_printed_out_later[i], blob_columns_to_be_printed_out_later[i], 1 + (i == (n_blobs - 1)));	/* 2 on last blob. */
	  fflush (stdout);
	  if ((SQL_SUCCESS != rc))
	    {
	      return (rc);
	    }			/* Brutal! */
	}
    }


  return (rc);
}


/* Borrowed from isqlodbc.c REALLY, THESE SHOULD BE FLESHED OUT TO THE
   COMMON SUBMODULE, AS WELL AS N+1 OTHER COMMON OR ALMOST-COMMON
   SUBROUTINES USED BY BOTH DBDUMP.C and ISQLODBC.C
 */
#define not_escaped(C)\
 ( ((((unsigned char)(C))) != '\\') && ((((unsigned char)(C))) != '\'')\
   && (( ((((unsigned char)(C))) > 31) && ((((unsigned char)(C))) < 127) )\
      || ((((unsigned char)(C))) > 160) ) )

/* Was like this, but it is too conservative:
( ((((unsigned char)(C))) < 127) && (isalnum((C)) || ('_' == (C))) )
 */

/* The next two functions, escape_string and count_escaped_length
   should use exactly the same criteria for determining what
   to escape and how.
 */
unsigned char *
escape_string (unsigned char *dest, unsigned char *src)
{
  unsigned char *org_dest = dest;

  for (; *src; src++)
    {
      if ('\\' == *src)
	{
	  *dest++ = '\\';
	  *dest++ = '\\';
	}
      else if (not_escaped (*src))
	{
	  *dest++ = *src;
	}
      else			/* Needs backslash plus 3 octal digits. */
	{
	  sprintf (SCP (dest), "\\%03o", *((unsigned char *) src));
	  dest += 4;
	}
    }

  *dest = '\0';
  return (org_dest);
}



int
do_generic_dest_statement (HSTMT * ptr_to_gen_stmt, HDBC hdbc,	/* Datadest (Kubl) connection */
    HENV henv, char *statement_text)
{
				/*RETCODE */ int rc;
				/* Return Code for SQL operations, signed short */

  rc = SQLExecDirect (*ptr_to_gen_stmt, UCP (statement_text), SQL_NTS);

  IF_ERR_GO (*ptr_to_gen_stmt, error, rc);
error:
  return (rc);
}


/* Of course we should run the arguments through the function
   like escape_string in isqlodbc.c before printing them out
   with printf, in the case the output is really used for later
   feeding with isql(o).
   However, as long as there are no quotes nor newlines nor backslashes
   in datasource names, usernames, password and table names,
   it's all right. But with Access full-length tablenames we have
   backslashes! E.g. we might have "C:\CFUSION\DATABASE\cfexamples30"
   as the table qualifier (= database).

   When the stuff goes directly to the destination database
   with SQLExecute, then it doesn't matter so much, as the
   arguments are passed as string parameters, and may contain
   anything there ever might be.
 */

int
link_generic_operation (HSTMT * ptr_to_link_stmt, HDBC hdbc,	/* Datadest (Kubl) connection */
    HENV henv, char *datasource, char *second_arg, char *third_arg, char *output_template,	/* With 7 %s 's */
    char *statement_template)	/* With 3 ?'s */
{
  static char *last_output_template = NULL;
				/* RETCODE */ int rc;
				/* Return Code for SQL operations, signed short */
  SQLLEN cb_datasource = SQL_NTS, cb_second_arg = SQL_NTS, cb_third_arg = SQL_NTS;
  char tmp1buf[2501], tmp2buf[2501];	/* Enough is enough. */

  tmp1buf[0] = tmp2buf[0] = '\0';

  printf (output_template,
      datasource,
      (second_arg ? "'" : ""),
      (second_arg ? SCP (escape_string (UCP (tmp1buf), UCP (second_arg))) : "NULL"),
      (second_arg ? "'" : ""),
      (third_arg ? "'" : ""), (third_arg ? SCP (escape_string (UCP (tmp2buf), UCP (third_arg))) : "NULL"), (third_arg ? "'" : ""));


/* No connection to data destination allocated, so we exit here,
   after just printing the statement. */
  if (SQL_NULL_HDBC == hdbc)
    {
      return (SQL_SUCCESS);
    }

  if (output_template != last_output_template)	/* Statement changed? (or first time here) */
    {
      last_output_template = output_template;	/* Mark the new one. */

      if (SQL_NULL_HSTMT == *ptr_to_link_stmt)	/* First time here? */
	{
	  SQLAllocStmt (hdbc, ptr_to_link_stmt);	/* Allocate a stmt handle. */
	}

      /* Anyways, prepare the new statement: */
      rc = SQLPrepare (*ptr_to_link_stmt, UCP (statement_template), SQL_NTS);
      IF_ERR_GO (*ptr_to_link_stmt, error, rc);
    }

/* Bind the parameters every time, as they can point to different
   places at different times (although datasource is probably constant)
 */
  if (NULL == datasource)
    {
      cb_datasource = SQL_NULL_DATA;
    }
  rc = SQLBindParameter (*ptr_to_link_stmt,
      ((UWORD) 1), ((SWORD) SQL_PARAM_INPUT),
      ((SWORD) SQL_C_CHAR), ((SWORD) SQL_CHAR),
      ((SQLULEN) 0), ((SWORD) 0), ((PTR) datasource), ((SQLLEN) 0), ((SQLLEN *) & cb_datasource));
  IF_ERR_GO (*ptr_to_link_stmt, error, rc);

  if (NULL == second_arg)
    {
      cb_second_arg = SQL_NULL_DATA;
    }
  rc = SQLBindParameter (*ptr_to_link_stmt,
      ((UWORD) 2), ((SWORD) SQL_PARAM_INPUT),
      ((SWORD) SQL_C_CHAR), ((SWORD) SQL_CHAR),
      ((SQLULEN) 0), ((SWORD) 0), ((PTR) second_arg), ((SQLLEN) 0), ((SQLLEN *) & cb_second_arg));
  IF_ERR_GO (*ptr_to_link_stmt, error, rc);

  if (NULL == third_arg)
    {
      cb_third_arg = SQL_NULL_DATA;
    }
  rc = SQLBindParameter (*ptr_to_link_stmt,
      ((UWORD) 3), ((SWORD) SQL_PARAM_INPUT),
      ((SWORD) SQL_C_CHAR), ((SWORD) SQL_CHAR),
      ((SQLULEN) 0), ((SWORD) 0), ((PTR) third_arg), ((SQLLEN) 0), ((SQLLEN *) & cb_third_arg));
  IF_ERR_GO (*ptr_to_link_stmt, error, rc);

/* Okay, first time or not, now the parameters should have been bound. */

  rc = SQLExecute (*ptr_to_link_stmt);
  IF_ERR_GO (*ptr_to_link_stmt, error, rc);

error:;			/* Or not, here we come. */

  SQLFreeStmt (*ptr_to_link_stmt, SQL_RESET_PARAMS);
  return (rc);
}


int
link_remote_data_source (HSTMT * ptr_to_link_stmt, HDBC hdbc,	/* Datadest (Kubl) connection */
    HENV henv, char *datasource, char *username, char *password)
{
  return (link_generic_operation (ptr_to_link_stmt, hdbc, henv,
	  datasource, username, password,
	  "DB..vd_remote_data_source('%s','',%s%s%s,%s%s%s);\n", "DB..vd_remote_data_source(?,'',?,?)"));
}


int
link_local_and_remote_table (HSTMT * ptr_to_link_stmt, HDBC hdbc,	/* Datadest (Kubl) connection */
    HENV henv, char *datasource, char *local_name, char *remote_name)
{
  return (link_generic_operation (ptr_to_link_stmt, hdbc, henv,
	  datasource, local_name, remote_name,
	  "DB..vd_remote_table('%s',replace(%s%s%s,'\"',''),%s%s%s);\n", "DB..vd_remote_table(?,replace(?,'\"',''),?)"));
}

/*
   replace(?,'\"','') (that nukes the doublequotes)
    is unnecessary on the third argument (the original remote name)
    so we don't use it there.

   replace(NULL,'\"','') produces NULL

 */


char statement_text[65000];
/* For strncpy */
#define STMT_SPACE_REST ((sizeof(statement_text)-(indentation_length+100))-(statement_ptr-statement_text))

/* Note: the overflow checking of statement_text buffer is not yet
         really ready.
 */
int
print_table_definition_banner (struct tabledeflist *tl)
{
  int i, rc, indentation_length = 0;
  struct coldeflist *cl;
  char *statement_ptr;
  char *table_destname, tmp_for_destname[(MAXCOLNAME * 3) + 10];
  char tmp[(MAXCOLNAME * 3) + 10];
  char where[CHARCOL_LEN + 80];

  sprintf (where, "print_table_definition_banner(\"%s\")", (tl->name ? tl->name : "NULL"));

  table_destname = escapify_and_form_dest_name (tmp_for_destname, (sizeof (tmp_for_destname) - 1), SCP (tl->name));

  if (vd_procedures_flag)
    {
      rc = link_local_and_remote_table (&datadest_link_stmt, datadest_hdbc, henv, datasource, (table_destname + ('\\' == *table_destname)), NULL);	/* Unlink the old one. */

/* No success, e.g. there exists a local table with the same name */
      if (SQL_SUCCESS != rc)
	{
	  goto error;
	}
/*   IF_ERR_GO (datadest_link_stmt, error, rc); */
    }

  if (0 == dont_issue_drop_commands_flag)
    {
      sprintf (statement_text, "DROP TABLE %s", table_destname);
      printf ("%s;\n", statement_text);
      if (datadest_hdbc)
	{
	  rc = do_generic_dest_statement (&datadest_gen_stmt, datadest_hdbc, henv, statement_text);
	}
      /* Drop may fail, but we don't care. */
    }

  statement_ptr = statement_text;
  sprintf (statement_ptr, "CREATE TABLE %s(", table_destname);
  indentation_length = (int) strlen (statement_text);
  statement_ptr += indentation_length;


  /* Print column definitions.
     In case the option -P is specified and the table has no supertable,
     no primary key definition and no bestrow columns,
     we have to collect all non-blob columns to global tmp1 buffer
     and use that as a primary key.
     (Nobody else should meanwhile use tmp1 !!!)
   */
  for (tmp1[0] = '\0', cl = tl->col_defs; cl;)
    {
      if (primary_key_by_all_means_flag
	  && NO (tl->super_table)
	  && NO (tl->primary_key_def && *(tl->primary_key_def))
	  && NO (tl->bestrow_columns) && (cl->col_type != SQL_LONGVARCHAR) && (cl->col_type != SQL_LONGVARBINARY))
	{
	  if (*tmp1)
	    {
	      strcat (tmp1, ",");
	    }
	  strcat (tmp1, escapify (tmp, SCP (cl->col_name)));
	}

      /* First the column name: */
      strncpy (statement_ptr, escapify (tmp, cl->col_name), STMT_SPACE_REST);
      statement_ptr += strlen (statement_ptr);
      *statement_ptr++ = ' ';

/* Then the datatype possibly with precision and NOT NULL definition. */
      strncpy (statement_ptr,
	  get_sql_col_type_def (cl->col_type, cl->col_precision, cl->col_scale, cl->col_nullable), STMT_SPACE_REST);
      statement_ptr += strlen (statement_ptr);
      cl = cl->next;
/* Print a comma, in case this is not the last column, or even if it
   is but there still follows the UNDER supertable
   or a primary key definition for this table. */
      if (cl || tl->super_table || (tl->primary_key_def && *(tl->primary_key_def)) || primary_key_by_all_means_flag)
	{
	  *statement_ptr++ = ',';
	  if (nicer_output_flag)	/* (... && !cl) -> only PK indented. */
	    {
	      *statement_ptr++ = '\n';
	      for (i = 0; i < indentation_length; i++)
		{
		  *statement_ptr++ = ' ';
		}
	    }
	}
    }

  if (tl->super_table)
    {
      strncpy (statement_ptr, "UNDER ", STMT_SPACE_REST);
      statement_ptr += strlen (statement_ptr);
      strncpy (statement_ptr, escapify_and_form_dest_name (tmp, (sizeof (tmp) - 1), SCP (tl->super_table)), STMT_SPACE_REST);
      statement_ptr += strlen (statement_ptr);
    }

/* There shouldn't exist any tables with both super table and primary key,
   but in case there are, it is easier to catch the bugs when we leave
   the following clause as if, instead of else if
 */
  if (tl->primary_key_def && *(tl->primary_key_def))
    {
      strncpy (statement_ptr, "PRIMARY KEY(", STMT_SPACE_REST);
      statement_ptr += strlen (statement_ptr);
      strncpy (statement_ptr, tl->primary_key_def, STMT_SPACE_REST);
      statement_ptr += strlen (statement_ptr);
      *statement_ptr++ = ')';
      strncpy (statement_ptr, tl->primary_key_type, STMT_SPACE_REST);
      statement_ptr += strlen (statement_ptr);
    }
  else if (primary_key_by_all_means_flag && NO (tl->super_table))
    {
      char *pk_cols = NULL;
      struct indexdeflist *first_unique_index = find_first_index_like (tl->index_defs, "CREATE UNIQUE ");
      if (first_unique_index && (NULL != (pk_cols = strchr (first_unique_index->index_def, '('))))
	{
	  pk_cols++;		/* Past the opening parenthesis */
	}
      else if (tl->bestrow_columns)
	{
	  pk_cols = tl->bestrow_columns;
	}
      else
	{
	  pk_cols = tmp1;
	}			/* Collected above, all non-blob columns */

      strncpy (statement_ptr, "PRIMARY KEY(", STMT_SPACE_REST);
      statement_ptr += strlen (statement_ptr);
      strncpy (statement_ptr, pk_cols, STMT_SPACE_REST);
      statement_ptr += strlen (statement_ptr);
      *statement_ptr++ = ')';
    }

  *statement_ptr++ = ')';	/* The last parenthesis. */
  *statement_ptr++ = '\0';	/* And the statement text is terminated. */

  fputs (statement_text, stdout);
  fputs (";\n", stdout);

  if (datadest_hdbc)
    {
      rc = do_generic_dest_statement (&datadest_gen_stmt, datadest_hdbc, henv, statement_text);
      if (SQL_SUCCESS != rc)
	{
	  goto error;
	}			/* Create table failed? */
    }

  if (vd_procedures_flag)
    {
      char *remote_name = compose_whole_tablename (tl, tmp, (sizeof (tmp) - 3));

      rc = link_local_and_remote_table (&datadest_link_stmt,
	  datadest_hdbc, henv, datasource, (table_destname + ('\\' == *table_destname)), remote_name);
      if (SQL_SUCCESS != rc)
	{
	  goto error;
	}			/* Linking failed? */
    }

  if (nicer_output_flag)
    {
      putc ('\n', stdout);
    }
  fflush (stdout);
  return (1);
error:
/* Save the error state and message to this table's node,
   so that we can later produce a summary of errors
   (with function check_for_failed_tables):
 */
  tl->last_SQL_state = chestrdup (SQL_error_state, where);
  tl->last_SQL_message = chestrdup (SQL_error_message, where);

  fflush (stdout);
  return (0);

}

/* Returns the number of columns if succeeded, otherwise returns zero. */
/* The second argument, for_contents_flag is non-zero when this
   is called for really dumping the contents of the table out
   (probably second time, if this has been also called for getting
   the columns of the table, with for_contents_flag zero).
 */
int
do_select_for_table (struct tabledeflist *tl, int for_contents_flag)
{
  int rc;
  char tmp[CHARCOL_LEN + 5];

/* Now use the spacious global buffer tmp1 for holding the select
   statement string, as it can grow very long when dumping super-tables
   with many subtables.

   Of course here we should use
    compose_whole_tablename(tl,tmp,(sizeof(tmp)-2))
   to get valid tablename-expressions for all kinds of exotic databases.
 */
  sprintf (tmp1, select_statement_template, (never_escape_tablenames_in_select ? tl->name : escapify (tmp, tl->name)));

/* The third arg was: (use_sql_describe_flag ? "*" : tl->columns), */

  if (for_contents_flag)
    {
      if (tl->sub_tables)
	{
	  size_t length_before = strlen (tmp1);
	  size_t enough_space = make_where_clause_for_table_with_children (tmp1, tl,
	      sizeof (tmp1) - 10);
	  if (NOT enough_space)
	    {
	      struct subtablelist *sl;
	      fprintf (stdout, "-- do_select_for_table: Not enough space (only %ld bytes) to hold:\n-- ", (long) sizeof (tmp1));
	      puts (tmp1);	/* This adds the newline ? Hope so. */
	      fprintf (stdout, "-- Dumping the subtables with the REPLACING option instead.\n");
	      tmp1[length_before] = '\0';	/* Restore original version. */
	      for (sl = tl->sub_tables; sl; sl = sl->next)
		{
		  sl->sub_table->insert_mode = "REPLACING";
		}
	    }
	}
    }

  if (for_contents_flag && verbose_flag)	/* Show the select statement. */
    {
      fprintf (stdout, "-- %s\n", tmp1);
      fflush (stdout);
    }

  rc = SQLExecDirect (stmt, UCP (tmp1), SQL_NTS);

  IF_ERR_GO (stmt, error, rc);
  if (rc == SQL_NO_DATA_FOUND)	/* This shouldn't cause an error, but just */
    {
      goto error;
    }				/* frees the handles and returns zero. */

  rc = SQLNumResultCols (stmt, &n_out_cols);
  IF_ERR_GO (stmt, error, rc);

  if (n_out_cols == 0)
    {
      fprintf (stdout, "-- Table %s has %d columns which is very strange indeed!\n", tl->name, n_out_cols);
      return (0);
    }
  else if (n_out_cols > MAX_COLS)
    {
      fprintf (stdout, "-- Table %s has %d columns > max. %d, truncated!\n", tl->name, n_out_cols, MAX_COLS);
      n_out_cols = MAX_COLS;
    }

  return (n_out_cols);

error:;

/* No! Don't free anything here, because we might get
Error S1010: [Microsoft][ODBC Driver Manager] Function Sequence Error.
   Instead, it is the responsibility of the calling function
   (either get_and_print_table_defition, or print_table_contents)
   to do that when it receives zero as a return value.

  SQLFreeStmt (stmt, SQL_UNBIND);
  SQLFreeStmt (stmt, SQL_CLOSE);

  if(SQL_SUCCESS != SQLTransact (henv, hdbc, SQL_COMMIT))
   {
     print_error (SQL_NULL_HENV, hdbc, SQL_NULL_HSTMT);
   }
 */

  return (0);
}


int
get_and_print_table_defition (struct tabledeflist *tl, int print_it_also)
{
  int n_cols;

  debug_fprintf (stdout, "-- get_and_print_table_defition(%s,%d)\n", tl->name, print_it_also);
  if (use_sql_describe_flag)
    {
      n_cols = do_select_for_table (tl, 0);
      if (0 == n_cols)
	goto error;
      get_table_columns (tl, n_cols);	/* Get them with SQLDescribeCol */
    }
  else
    {
      n_cols = get_table_columns (tl, 0);
    }				/* Get them with SQLColumns */

  if (print_it_also)
    {
      print_table_definition_banner (tl);
    }

  return (n_cols);

error:;

  SQLFreeStmt (stmt, SQL_UNBIND);
  SQLFreeStmt (stmt, SQL_CLOSE);

  if (SQL_SUCCESS != SQLTransact (henv, hdbc, SQL_COMMIT))
    {
      print_error (SQL_NULL_HENV, hdbc, SQL_NULL_HSTMT);
    }

  return (0);
}


/* This should be called immediately after
     get_and_print_table_defition and print_indexdeflist
 */
int
print_table_contents (struct tabledeflist *tl)
{
  SWORD btype;
  UWORD inx;
  int n_rows = 0, n_cols = 0, rc;
  struct coldeflist *cl;

  char where[CHARCOL_LEN + 80];

  sprintf (where, "print_table_contents(\"%s\")", (tl->name ? tl->name : "NULL"));

  debug_fprintf (stdout, "-- %s\n", where);

  if (0 == use_sql_describe_flag)	/* We still have to do select. */
    {
      n_cols = do_select_for_table (tl, 1);
      if (0 == n_cols)
	goto error;		/* Not really an error, just skip printing. */
/* If this is a subtable of another table (tl->super_table is not null)
   then we have to reread the column information, this time including
   all the columns, also the columns of all ancestor tables, which are
   get with SQLDescribeCol (in get_table_columns) after the select *
   statement done above.
   Well, actually we have to do it always, because select * might
   return columns in different order as SQLColumns (at least that is
   the case with Access).
 */
/*   if(tl->super_table)   Always do it anyway */
      {
	tl->contains_blobs = 0;	/* Clear the blob counter/flag. */
	tl->col_defs = NULL;	/* Clear the old column definition list. */
	get_table_columns (tl, n_cols);	/* As we are reading them again. */
      }
    }

  /* First bind the column contents buffers. */
  /* We should print a warning here if the length tl->col_defs and
     n_out_cols don't match. */

  for (inx = 1, cl = tl->col_defs; (inx <= n_out_cols) && cl; inx++, cl = cl->next)
    {
      stmt_out_t *out = &out_cols[inx - 1];

      if (NO out->o_buffer)
	{
	  out->o_buffer = (char *) chemalloc (maxcolumn_width + 2, where);
	}

      if (NO times_to_strings_flag && ((cl->col_type == SQL_TIMESTAMP) || (cl->col_type == SQL_DATE) || (cl->col_type == SQL_TIME)))
	{
	  btype = SQL_C_TIMESTAMP;
	}
      else
	{
	  btype = SQL_C_CHAR;
	}

      if (bind_blobs_flag || ((SQL_LONGVARCHAR != cl->col_type) && (SQL_LONGVARBINARY != cl->col_type)))
	{
	  rc = SQLBindCol (stmt, inx, btype, out->o_buffer, ((SQLLEN) maxcolumn_width), &out->o_col_len);
	  IF_ERR_GO (stmt, error, rc);
	}
    }				/* for loop over column list tl->col_defs. */

  for (;;)
    {
      rc = SQLFetch (stmt);
      if (rc == SQL_NO_DATA_FOUND)
	break;
      IF_ERR_GO (stmt, error, rc);
      n_rows++;
      rc = print_table_row (tl);
      IF_ERR_GO (stmt, error, rc);
    }

error:;

  SQLFreeStmt (stmt, SQL_UNBIND);
  SQLFreeStmt (stmt, SQL_CLOSE);

  if (SQL_SUCCESS != SQLTransact (henv, hdbc, SQL_COMMIT))
    {
      print_error (SQL_NULL_HENV, hdbc, SQL_NULL_HSTMT);
    }

  return (n_rows);
}


int
print_indexdeflist (struct tabledeflist *tl)
{
  struct indexdeflist *il;
  int count = 0;
  char tmp[MAXCOLNAME + 5];

  for (il = tl->index_defs; il; il = il->next)
    {
/* Check if the index name appears in one of the ancestor tables
   of this table (either as primary key name or some other index),
   and if it is so, then skip printing of this index, thus avoiding
   duplicate indices: */
      if (index_has_been_defined_for_supertable (il->index_name, tl))
	{
	  continue;
	}
/* If the user dumps out only index definitions without table definitions,
   then we have to prefix each index definition (in case that -r
   option has not been given) with corresponding DROP INDEX statement.
   But if the table definitions are printed also, then each
   DROP TABLE will drop all of its indices too.
 */
      if (NO only_table_definitions_flag && NO dont_issue_drop_commands_flag)
	{
	  printf ("DROP INDEX %s;\n", escapify (tmp, il->index_name));
	}

/* Here we print the ending parenthesis, semicolon and newline also: */
      printf ("%s);\n", il->index_def);
      count++;
    }
  fflush (stdout);

  return (count);
}

/* Pointer to Function returning int, having one tabledeflist and one int
   as its arguments. */
typedef int (*PFI_TABLEDEFLIST) (struct tabledeflist *, int);

int
output_one_table (struct tabledeflist *this_table, int sublevel)
{
  int rows = 0, indices = 0, cols = 0;
  struct subtablelist *sl;
  int save_only_table_definitions_flag = 0;
  int save_only_index_definitions_flag = 0;
  int save_only_contents_flag = 0;

  /* Implicitly included supertable of some subtable? */
  if (this_table->automatically_included)
    {
      save_only_table_definitions_flag = only_table_definitions_flag;
      save_only_index_definitions_flag = only_index_definitions_flag;
      save_only_contents_flag = only_contents_flag;

      only_table_definitions_flag = auto_only_table_definitions_flag;
      only_index_definitions_flag = auto_only_index_definitions_flag;
      only_contents_flag = auto_only_contents_flag;
    }

  cols = get_and_print_table_defition (this_table,
/* Print it only if this flag is on: */ only_table_definitions_flag);

  if (only_index_definitions_flag)
    {
      indices = print_indexdeflist (this_table);
    }
  debug_fprintf (stdout, "-- Table %s %d columns, %d indices output, level %d.\n", this_table->name, cols, indices, sublevel);
  if (only_contents_flag && cols)
    {
      rows = print_table_contents (this_table);
      if (verbose_flag)
	{
	  fprintf (stdout, "-- Table %s %d rows output.\n", this_table->name, rows);
	}
    }

  if (this_table->automatically_included)	/* Restore the normal settings. */
    {
      only_table_definitions_flag = save_only_table_definitions_flag;
      only_index_definitions_flag = save_only_index_definitions_flag;
      only_contents_flag = save_only_contents_flag;
    }

  /* Print its possible subtables. */
  for (sl = this_table->sub_tables; sl; sl = sl->next)
    {
      output_one_table (sl->sub_table, (sublevel + 1));
    }


  return (1);
}

int
output_tables_with (struct tabledeflist *tl, PFI_TABLEDEFLIST out_fun)
{
  for (; tl; tl = tl->next)
    {
      if (tl->super_table)
	{
	  continue;
	}			/* Skip subtables on top level */
      (out_fun) (tl, 0);
    }

  return (1);
}


int
output_tables (struct tabledeflist *tl)
{
  return (output_tables_with (tl, output_one_table));
}


/* Outputs subtables with indentation, according to sublevel. */
int
output_one_table_as_option (struct tabledeflist *this_table, int sublevel)
{
  int i;
  struct subtablelist *sl;
  char *one_space = "&nbsp;&nbsp;&nbsp;";	/* Actually three, looks better */
  char few_spaces[381];

  for (i = 0; (i < sublevel) && (i < (sizeof (few_spaces) - 1)); i++)
    {
      strcpy (&few_spaces[i], one_space);
      i += (int) (strlen (one_space));
    }
  few_spaces[i] = '\0';

  printf ("<OPTION VALUE=\"%s\">%s%s\n", this_table->name, few_spaces, this_table->name);

  /* And then print its possible subtables. */
  for (sl = this_table->sub_tables; sl; sl = sl->next)
    {
      output_one_table_as_option (sl->sub_table, (sublevel + 1));
    }

  return (1);
}


int
output_tables_as_select_list (struct tabledeflist *tl, int list_size)
{
  int rc;

  printf
      ("<SELECT NAME=\"S_TABLES\" MULTIPLE onchange=\"add_selected_items_to_the_text_elem(this,this.form.tablename)\" SIZE=%d>\n",
      list_size);

  rc = (output_tables_with (tl, output_one_table_as_option));

  printf ("</SELECT>\n");
  fflush (stdout);

  return (1);
}

int
output_tablelist_token (int list_size)
{
  if (flag_get_list_of_tables)
    {
      return (output_tables_as_select_list (all_tables_list, list_size));
    }
  else
    {
      printf ("<INPUT TYPE=SUBMIT NAME=\"RTL\" VALUE=\"Show List\" "
	  " onclick=\"select_option_with_value(this.form.OPCODE,'RTL'); check_radiobutton_with_value(this.form.OPTION_qv,'q')\">\n");
      fflush (stdout);
      return (1);
    }
}


/* ================================================================== */
/*  TWO FUNCTIONS FOR PARSING URL QUERY STRINGS & COMMAND LINE ARGS   */
/* ================================================================== */



/* The following two functions were taken from AK's conjugate software,
   module conjtest.cpp.

 */
UCHAR *
parse_url_value (UCHAR * url_piece)
{
  UCHAR *s, *t;
  UCHAR save_char;
  unsigned int tmp;

  s = t = url_piece;

  while (*s)
    {
      switch (*s)
	{
	case '+':
	  {
	    *t++ = ' ';
	    s++;
	    break;
	  }			/* Plus signs to spaces */
	case '%':
	  {			/* Double %% can be used for escaping a percent sign itself */
	    if (*(s + 1) == '%')
	      {
		*t++ = '%';
		s += 2;
	      }
	    else if (NOT isalnum (*(s + 1)))	/* Not followed by hex digits? */
	      {
		*t++ = *s++;
	      }
	    else if (strlen ((char *) s) >= 3)
	      {
		save_char = *(s + 3);
		*(s + 3) = '\0';
		/* Convert two hex digits to int */
		sscanf (((const char *) s + 1), "%x", &tmp);
		*(s + 3) = save_char;
		*t++ = ((UCHAR) tmp);
		s += 3;
	      }
	    else		/* Copy the trailing percent signs literally. */
	      {
		*t++ = *s++;
	      }
	    break;
	  }
	default:
	  {
	    *t++ = *s++;
	    break;
	  }
	}
    }

  *t = '\0';
  return (url_piece);
}

/* Finds the next delimiter character in the query string. It is currently
   either an ampersand or a slash. If neither of them found returns NULL */
char *
next_delimiter (char *str)
{
  char *dp1, *dp2;

  dp1 = strchr (str, '&');	/* Stupid... */
  dp2 = strchr (str, '/');
  if (dp1 && (NO dp2 || (dp1 <= dp2)))
    {
      return (dp1);
    }
  if (dp2)
    {
      return (dp2);
    }
  return (NULL);
}

/* Appends contents of ptr2 (a URL-encoded string) after the old value
   of item, comma-separated.
   Uses tmp1 as a temporary buffer.
 */
char *
append_to_specval (char *item, char *ptr2, char *where)
{
  if (*ptr2)
    {
      if (item)			/* There are more than one type specifiers, */
	{			/* and this is not the first one. */
	  sprintf (tmp1, "%s,%s", SCP (item), SCP (parse_url_value (UCP (ptr2))));
	  free (item);		/* The old version. */
	  item = chestrdup (SCP (tmp1), where);
	}
      else			/* First item. */
	{
	  item = chestrdup (SCP (parse_url_value ((UCHAR *) (ptr2))), where);
	}
    }
  return (item);
}


/* Returns an error message if something fails, otherwise returns NULL */
char *
parse_url_query_string (char *query_string)	/* input */
{
  char *ptr1, *ptr2, *ptr3;
  char *parse_url_error_message = NULL;
  unsigned int count = 0;
  int convdst;			/* A flag, either 0 or 1. */

  char where[3005];

  strcpy (where, "parse_url_query_string(\"");
  my_strncat (where, (query_string ? query_string : "NULL"), sizeof (where) - 5);
  my_strncat (where, "\")", sizeof (where) - 5);
  where[sizeof (where) - 5] = '\0';

  ptr1 = query_string;
  while (ptr1)
    {
      if (NOT (ptr2 = (strchr (((char *) ptr1), '='))))
	{
	  break;
	}
      if ((ptr3 = (next_delimiter (((char *) ptr2)))))
	{
	  *ptr3++ = '\0';
	}			/* Overwrite the ampersand, and skip past. */
      *ptr2++ = '\0';		/* Overwrite the equal sign, and skip past. */
/* ptr1 points to the beginning of the variable name.
   ptr2 points two characters past the end of the variable name, i.e. one
    past the equal sign (=) which has been overwritten by zero '\0',
    that is to the beginning of the variable value, corresponding to
    variable name where ptr1 points to.
   ptr3 points two characters past the end of variable value, i.e. one
    past the ampersand (&) which has been overwritten by zero, that is
    to the beginning of the next variable name. Or if we have found the
    last name=value pair, then it contains the NULL.
 */
      if (!strcasecmp (((char *) ptr1), "tablequalifier"))
	{			/* Also if ptr2 is an empty string. */
	  if (*ptr2)
	    tablequalifier = SCP (parse_url_value ((UCHAR *) (ptr2)));
	}
      else if (!strcasecmp (((char *) ptr1), "tableowner"))
	{
	  if (*ptr2)
	    tableowner = SCP (parse_url_value ((UCHAR *) (ptr2)));
	}
      else if (!strcasecmp (((char *) ptr1), "tablename"))
	{
	  if (*ptr2)
	    tablename = SCP (append_to_specval (tablename, ptr2, where));
/* Was:   if(*ptr2) tablename = SCP(parse_url_value((UCHAR *)(ptr2))); */
	}
      else if (!strcasecmp (((char *) ptr1), "tabletype"))
	{
	  if (*ptr2)
	    tabletype = SCP (append_to_specval (tabletype, ptr2, where));
	}
      else if (!strcasecmp (((char *) ptr1), "new_name"))
	{
	  if (*ptr2)
	    new_name = SCP (parse_url_value ((UCHAR *) (ptr2)));
	}
      else if (!strcasecmp (((char *) ptr1), "unquoted_columns"))
	{
	  if (*ptr2)
	    unquoted_columns = SCP (append_to_specval (unquoted_columns, ptr2, where));
	}
      else if (!strcasecmp (((char *) ptr1), "username") || !strcasecmp (((char *) ptr1), "s_conuser"))
	{
	  if (*ptr2)
	    username = SCP (parse_url_value ((UCHAR *) (ptr2)));
	}
      else if (!strcasecmp (((char *) ptr1), "empty_username"))
	{
	  if (*ptr2)
	    {
	      username = "";
	    }
	}
      else if (!strcasecmp (((char *) ptr1), "password") || !strcasecmp (((char *) ptr1), "s_conpass"))
	{
	  if (*ptr2)
	    password = SCP (parse_url_value ((UCHAR *) (ptr2)));
	}
      else if (!strcasecmp (((char *) ptr1), "empty_password"))
	{
	  if (*ptr2)
	    {
	      password = "";
	    }
	}
      else if (!strcasecmp (((char *) ptr1), "datasource") || !strcasecmp (((char *) ptr1), "s_datasource"))
	{
	  if (*ptr2)
	    datasource = SCP (parse_url_value ((UCHAR *) (ptr2)));
	}
      else if (!strcasecmp (((char *) ptr1), "datadest") || !strcasecmp (((char *) ptr1), "s_datadest"))
	{
	  if (*ptr2)
	    datadest = SCP (parse_url_value ((UCHAR *) (ptr2)));
	}
      else if (!strcasecmp (((char *) ptr1), "s_dstuser"))
	{
	  if (*ptr2)
	    dest_username = SCP (parse_url_value ((UCHAR *) (ptr2)));
	}
      else if (!strcasecmp (((char *) ptr1), "s_empty_dstuser"))
	{
	  if (*ptr2)
	    {
	      dest_username = "";
	    }
	}
      else if (!strcasecmp (((char *) ptr1), "s_dstpass"))
	{
	  if (*ptr2)
	    dest_password = SCP (parse_url_value ((UCHAR *) (ptr2)));
	}
      else if (!strcasecmp (((char *) ptr1), "s_empty_dstpass"))
	{
	  if (*ptr2)
	    {
	      dest_password = "";
	    }
	}
      else if (!strcasecmp (((char *) ptr1), "insert_mode"))
	{
	  if (*ptr2)
	    default_insert_mode = SCP (parse_url_value ((UCHAR *) (ptr2)));
	}
      else if (!strcasecmp (((char *) ptr1), "content_type"))
	{
	  if (*ptr2)
	    web_content_type = SCP (parse_url_value ((UCHAR *) (ptr2)));
	}
      else if (((convdst = 0), !strncasecmp (((char *) ptr1), "convsrc", 7))
	  || ((convdst = 1), !strncasecmp (((char *) ptr1), "convdst", 7)))
	{
	  int n = atoi (ptr1 + 7);
	  if ((n < 1) || (n > MAX_CONVERSIONS))
	    {
	      sprintf (tmp1,
		  "%s-- Conversion option %s is invalid. N must be between 1 and %d!\n",
		  (parse_url_error_message ? parse_url_error_message : ""), ptr1, MAX_CONVERSIONS);
	      if (parse_url_error_message)
		{
		  free (parse_url_error_message);
		}
	      parse_url_error_message = chestrdup (tmp1, where);
	    }
	  else if (*ptr2)
	    {
	      conv_types_table[(2 * n) + convdst] = SCP (parse_url_value (UCP (ptr2)));
	      if (n > n_conv_types)
		{
		  n_conv_types = n;
		}		/* Keeps the max n encountered. */
	    }
	}
      else if (!strcasecmp (((char *) ptr1), "init"))
	{
	  if (*ptr2)
	    init_statement = SCP (parse_url_value ((UCHAR *) (ptr2)));
	}
      else if (!strcasecmp (((char *) ptr1), "RTL"))
	{
	  if (*ptr2)
	    {
	      flag_get_list_of_tables = 1;
	    }
	}
      else if (!strcasecmp (((char *) ptr1), "RTL2"))
	{
	  if (*ptr2)
	    {
	      flag_get_list_of_tables = 1;
	    }
	}
      else if (!strcasecmp (((char *) ptr1), "OPCODE"))
	{
	  if (!strcasecmp (((char *) ptr2), "RTL"))
	    {
	      flag_get_list_of_tables = 1;
	    }
	}
      else if (!strcasecmp (((char *) ptr1), "select"))
	{			/* User wants to override the default select statement. */
	  /* The template may contain one %s place marker for table name */
	  if (*ptr2)
	    select_statement_template = SCP (parse_url_value ((UCHAR *) (ptr2)));
	}
      else if (!strcasecmp (((char *) ptr1), "endtoken"))
	{			/* User wants to override the default end token "END" */
	  if (*ptr2)
	    foreach_end_token = SCP (parse_url_value ((UCHAR *) (ptr2)));
	}
      else if (!strcasecmp (((char *) ptr1), "foreach_maxhexlen"))
	{
	  if (*ptr2)
	    maxhexlength_for_foreach = atol (SCP (parse_url_value ((UCHAR *) (ptr2))));
	}
      else if (!strcasecmp (((char *) ptr1), "foreach_maxlinelen"))
	{
	  if (*ptr2)
	    maxlinelength_for_foreach = atol (SCP (parse_url_value ((UCHAR *) (ptr2))));
	}
      else if (!strcasecmp (((char *) ptr1), "maxcolumn_width"))
	{
	  if (*ptr2)
	    maxcolumn_width = atol (SCP (parse_url_value ((UCHAR *) (ptr2))));
	}
/* If there were nothing before an equal sign, then it's probably
   converted from a dash -, i.e. it's an option given from the
   command line. */
      else if (!*ptr1 || !strncasecmp (((char *) ptr1), "option", 6))
	{
	  int oppo = 0;
	  UCHAR *s = parse_url_value ((UCHAR *) (ptr2));
	  if ('+' == *s)
	    {
	      oppo = 1;
	      s++;
	    }
	  for (; *s; s++)
	    {
	      switch (*s)	/* Stupid idea: tolower(*s) */
		{
		case 'D':
		  {
		    dbdump_debug_level++;
		    break;
		  }
		case 'B':
		  {
		    bind_blobs_flag = (1 ^ oppo);
		    break;
		  }
		case 'A':
		  {
		    all_or_nothing_flag++;
		    break;
		  }
		case 'a':
		  {
		    never_escape_tablenames_in_select = (surround_with_flag == 0);
		    surround_with_flag = '"';
		    break;
		  }
		case 'b':
		  {
/* Was like this:
                   backslashify_always_flag++;
                   never_escape_tablenames_in_select
                     = (backslashify_always_flag < 2);
 */
		    never_escape_tablenames_in_select = (prefix_with_flag == 0);
		    prefix_with_flag = '\\';
		    break;
		  }
		case 'd':
		  {
		    use_sql_describe_flag = 1;
		    break;
		  }
		case 'K':
		  {
		    kubl_default_conversions_flag = 1;
		    break;
		  }
		case 'P':
		  {
		    primary_key_by_all_means_flag++;
		    break;
		  }
		case 'U':
		  {
		    universal_transfer_flag++;
		    break;
		  }
		case 'V':
		  {
		    vd_procedures_flag++;
		    break;
		  }
		case 'N':
		  {
		    nicer_output_flag++;
		    break;
		  }
		case 'p':
		  {
		    use_table_prefixes_flag = (0 ^ oppo);
		    use_table_prefixes_flag_given = 1;
		    break;
		  }
		case 't':
		  {
		    only_table_definitions_flag = 1;
		    break;
		  }
		case 'i':
		  {
		    only_index_definitions_flag = 1;
		    break;
		  }
		case 'c':
		  {
		    only_contents_flag = 1;
		    break;
		  }
		case 'T':
		  {
		    auto_only_table_definitions_flag = 1;
		    break;
		  }
		case 'I':
		  {
		    auto_only_index_definitions_flag = 1;
		    break;
		  }
		case 'C':
		  {
		    auto_only_contents_flag = 1;
		    break;
		  }
		case 'q':
		  {
		    verbose_flag = 0;
		    break;
		  }		/* Q as Quiet */
		case 'v':
		  {
		    verbose_flag = 1;
		    break;
		  }		/* V as Verbose */
		case 'l':
		  {
		    list_data_sources_flag = 1;
		    break;
		  }
		case 'h':
		  {
		    dump_html_template_file_flag++;
		    break;
		  }
/* I.e. we can use -ne to force both use_singlequote_escape and
                                     use_backslash_escapes_in_strings on
   so that doubling singlequotes has priority over backslashifying.
   See function print_string_col_aux. */
		case 'e':
		  {
		    use_backslash_escapes_in_strings_flag++;
		    break;
		  }
		case 'n':
		  {
		    use_backslash_escapes_in_strings_flag = 0;
		    use_singlequote_escape = 1;
		    break;
		  }
		case 'r':
		  {
		    dont_issue_drop_commands_flag = 1;
		    break;
		  }
/* -s: Keep all blobs as string literals, don't use foreach contraption: */
		case 's':
		  {
		    use_foreach_for_blobs_flag = 0;
		    break;
		  }
		default:
		  {
		    break;
		  }
		}
	    }
	}

      ptr1 = ptr3;
      count++;
    }

  return (parse_url_error_message);
}

/* ================================================================== */
/*                       MAIN & related                               */
/* ================================================================== */




int
driver_has_necessary_sql_functions ()
{
  UWORD TablesExists = TRUE, ColumnsExists = TRUE, FunctionExists = TRUE;

  fflush (stdout);
  SQLGetFunctions (hdbc, SQL_API_SQLTABLES, &TablesExists);
  if (0 == TablesExists)
    {
      fprintf (stderr, "-- Sorry, this driver doesn't implement SQLTables. Goodbye!\n");
      exit (1);
    }
  SQLGetFunctions (hdbc, SQL_API_SQLCOLUMNS, &ColumnsExists);
  if (0 == ColumnsExists)
    {
      fprintf (stderr, "-- Hmmm, this driver doesn't implement SQLColumns. Trying to use SQLDescribeCol instead.\n");
      use_sql_describe_flag = 1;
    }
  SQLGetFunctions (hdbc, SQL_API_SQLDESCRIBECOL, &FunctionExists);
  if (0 == FunctionExists)
    {
      fprintf (stderr, "-- Haa! this driver doesn't implement SQLDescribeCol either. Goodbye!\n");
      exit (1);
    }
  SQLGetFunctions (hdbc, SQL_API_SQLSTATISTICS, &FunctionExists);
  if (0 == FunctionExists)
    {
      fprintf (stderr, "-- Sorry, this driver doesn't implement SQLStatistics. Can't get index information.\n");
      only_index_definitions_flag = 0;
    }

  fflush (stderr);
  return (1);
}


#if defined(UNIX) && !defined(UNIX_ODBC)	/* && !defined(UDBC) */
#define USE_TEXTFIELD_DATASOURCE
#endif


#ifdef USE_TEXTFIELD_DATASOURCE

/* Neither ODBC nor UDBC, no way to know available data sources in
   this machine. (Probably running in Unix). */
int
list_data_sources (int for_html, char *templatename, char *tagname)
{
  char *selected_datasource = NULL;

  if (!strcmp (templatename, DEFAULT_HTML_TEMPLATE_FILE))	/* Using main template? */
    {
      selected_datasource = datasource;
    }

  if (!strcmp (tagname, DATADEST_TOKEN))
    {
      selected_datasource = "";
    }

  if (for_html)
    {
      printf ("<INPUT NAME=%s TYPE=TEXT VALUE=\"%s\">\n",
	  (!strcmp (tagname, DATADEST_TOKEN) ? "S_DATADEST"
	      : "S_DATASOURCE"), (selected_datasource ? selected_datasource : DEFAULT_DATASOURCE_IN_UNIX));
    }
  else
    {
      printf ("Don't know how to list available data sources in Unix. Try %s or wherever"
	  " your KUBL server is listening.\n", DEFAULT_DATASOURCE_IN_UNIX);
    }

  return 0;
}

#else

#define DRIVDESCMAX 256
#ifndef SQL_MAX_DSN_LENGTH
#define SQL_MAX_DSN_LENGTH 512
#endif

int
list_data_sources (int for_html, char *templatename, char *tagname)
{
  char DSN[SQL_MAX_DSN_LENGTH + 1], DriverDescription[DRIVDESCMAX + 1];
  SWORD pcbDSN, pcbDescription;
  int rc, count;
  char *selected_datasource = NULL;

  strcpy (DSN, "VIRGEN");
  strcpy (DriverDescription, "CERDO");

  if (for_html)
    {
      printf ("<SELECT NAME=");
      if (!strcmp (tagname, DATADEST_TOKEN))
	{
	  printf ("S_DATADEST>");
	  printf ("<OPTION VALUE=\"\">Data Destination for Direct Table Linkage:</OPTION>\n");
	}
      else
	{
	  printf ("S_DATASOURCE");
	  if (!strcmp (templatename, DEFAULT_HTML_TEMPLATE_FILE))	/* Using main template? */
	    {
/* Do not try to get list of tables when in DBDUMP->ISQLO transfer
   template, nether we will use the old datasource as the new destination
   by default:
 */
	      printf (
/*  " onchange=\"this.form.RTL2.value='YES'; this.form.submit();\""); */
/*    " onchange=\"select_option_with_value(this.form.OPCODE,'RTL');\n check_radiobutton_with_value(this.form.OPTION_qv,'q');\n this.form.submit();\""); */
		  " onchange=\"select_option_with_value(this.form.OPCODE,'RTL');\n check_radiobutton_with_value(this.form.OPTION_qv,'q');\"");
	      selected_datasource = datasource;
	    }
	  printf (">\n");
	}
    }


  for (count = 0; 1; count++)
    {
      rc = SQLDataSources (henv,
	  ((UWORD) (count ? SQL_FETCH_NEXT : SQL_FETCH_FIRST)),
	  UCP (DSN), ((SWORD) SQL_MAX_DSN_LENGTH), &pcbDSN, UCP (DriverDescription), ((SWORD) DRIVDESCMAX), &pcbDescription);
      if (rc == SQL_NO_DATA_FOUND)
	{
	  break;
	}
      IF_ERR_GO (stmt, error, rc);

      if (for_html)
	{
	  printf ("<OPTION%s VALUE=\"%s\">%s,   %s</OPTION>\n",
	      ((selected_datasource && !strcmp (DSN, selected_datasource)) ? " SELECTED" : ""), DSN, DSN, DriverDescription);
	}
      else
	{
	  printf ("%-25s %s\n", DSN, DriverDescription);
	}
    }
  if (for_html)
    {
      printf ("</SELECT>\n");
    }
  return (count);
error:
  if (for_html)
    {
      printf ("</SELECT>\n");
    }

  fprintf (stderr, "print_data_sources: SQLDataSources returned status %d, count=%d\n", rc, count);
  fflush (stderr);

  return (0);
}

#endif


void
l_usage (char *progname)
{
  fprintf (stderr, "DBDUMP - DataBase Dump, Version %s\n", DBDUMP_VERSION);
  fprintf (stderr, "Usage: %s datasource [username [password]] spec=val spec=val ... -options\n", progname);
  fprintf (stderr, "The specifiers are:\n"
/* Has to fit into one page! */
      "username       Username to open the database connection with.\n"
      "password       Password to open the database connection with.\n"
      "tablequalifier Default Table Qualifier  by default NULL, i.e. all.\n"
      "tableowner     Default Table Owner      by default NULL, i.e. all.\n"
      "tablename      Table Name Pattern (use %%'s and ?'s as wildcards).\n"
      "               by default this is NULL, i.e. dbdump lists all tables.\n"
      "tablename=a.b.c is equal to tablequalifier=a tableowner=b tablename=c\n"
      "(You can specify more than one pattern or explicit name with tablename, just\n"
      " separate them with commas. E.g. tablename=table1,mytable%%,table3)\n"
      "tabletype      Table Types      by default NULL, all types.\n"
      "               Use tabletype=TABLE to get only user tables.\n"
      "insert_mode    For inserts. By default INTO, could be also REPLACING or SOFT.\n"
      "init=statement SQL statement executed in the start. E.g. \"init=use datab2\"\n"
      "unquoted_columns=tablename1.colname1,tablename1.colname2,tablename2.col1\n"
      "               Use this option to specify which columns in which tables\n"
      "               shall not be quoted, even if they were nominally VARCHAR\n"
      "               columns. Use this for columns containing vector data.\n"
      "convsrcN (where N is between 1 and %d) Source type to convert into a type\n", MAX_CONVERSIONS);

  fprintf (stderr,
      "given with the corresponding convdstN   E.g. use convsrc1=BIT convdst1=INTEGER\n"
      "to convert all columns with the type BIT to columns of type INTEGER.\n"
      "-K             Use Kubl default conversions (in addition to any of your own).\n");

  fprintf (stderr, "More?>");
  getchar ();			/* This is for pause. */
  fprintf (stderr,
      "Options are:\n"
      "-t Only table definitions   -i Only index definitions   -c Only contents\n"
      "There are also corresponding option letters in Uppercase:\n"
      "-T Only table definitions   -I Only index definitions   -C Only contents\n"
      " to control how automatically included supertables are output. By default\n"
      " the tables which are parent tables of some matched subtables, but which\n"
      " themselves are not explicitly specified in/matched to the tablename argument\n"
      " are not shown in dump. Use -TIC to show all information about them also.\n"
      "-q Be brief, no informative output.   -v Be verbose, loquacious.\n"
      "-n Don't escape string literals in C-style. -e Escape diacritic letters too.\n"
      "-ne Escape singlequotes by doubling them, all others in C-style.\n"
      "-N Generate somewhat more human-readable output, more than 1 line/statement.\n"
      "-r Don't issue any DROP TABLE or DROP INDEX commands.\n" "-s Never use FOREACH construct to output blobs.\n");
/* These are obsoleted by new_name specifier:
"-p Use plain tablenames without prefixes, default with Kubl and Access.\n"
"-+p Use prefixed tablenames (e.g. db.dba.tabname1), default with MS SQL.\n"
 */

  fprintf (stderr, "More?>");
  getchar ();			/* This is for pause. */

  fprintf (stderr,
      "More options:\n"
      "-a Surround all column and index names with a doublequote (\")\n"
      "-b Prefix all names (of tables, indices and columns) with a backslash (\\)\n"
      "Use -bb to also escape tablenames when used in select statement.\n"
      "\n"
      "new_name=!Q.!O.!N  Specify a new destination name for the table(s) to be\n"
      "   dumped. Markers !Q, !O and !N refer respectively to Qualifier, Owner and\n"
      "   Name parts of the original name. Use only !N to get non-prefixed names.\n"
      "   In Windows use an expression like new_name=\"\"\"!Q\"\"\".\"\"\"!O\"\"\".\"\"\"!N\"\"\"\n"
      "   and in Unix shell one like new_name='\"!Q\".\"!O\".\"!N\"' to get each part\n"
      "   surrounded with doublequotes. Use this if you use -a option.\n"
      "\n"
      "-P Produce Primary Key by any means if not explicitly present in the source\n"
      "   schema. I.e. either the first Unique Index defined, columns returned\n"
      "   by SQLSpecialColumns with SQL_BEST_ROWID option, or if all else fails,\n"
      "   all non-blob columns of the table together.\n" "-V Produce DB..vd_remote_data_source and DB..vd_remote_table calls.\n");

  fprintf (stderr, "More?>");
  getchar ();			/* This is for pause. */

  fprintf (stderr, "Use    %s -l   to list available datasources.\n", progname);
  fprintf (stderr,
      "E.g. use\n"
      "%s KUBL dba dba -bbq \"tablename=?ala,t%%%%\" tabletype=TABLE convsrc1=BIT convdst1=INTEGER convsrc2=TIMESTAMP convdst2=DATE\n",
      progname);
  fprintf (stderr,
      "  to dump from the datasource KUBL (with username dba and password dba)\n"
      "  all user defined tables with four letter names ending with  'ala'\n"
      "  as well as all tables with names of any length, beginning with letter 't'\n"
      "  (you could also give them separately as \"tablename=?ala\" \"tablename=t*\")\n"
      "  and convert all encountered BIT types to INTEGERs and all TIMESTAMPs to\n"
      "  DATEs in the column definitions,\n"
      "  and use the options -bb and -q (escape names and be brief)\n"
      "  If in Unix, use localhost:1111 as a datasource address instead of Kubl\n"
      "  if you have Kubl server listening at port 1111 in the same machine.\n");

  fprintf (stderr,
      "\nIn the specifier values you can use + for space, %%2B for +, %%26 for &\n"
      "%%%% or %%25 for a percent sign itself, %%3D for =, %%2F for / and %%2D for -\n\n");


  fprintf (stderr,
      "You can copy this executable to your Web server's script directory, and try\n"
      "it with your Web browser, using URL like http://localhost/scripts/dbdump.exe\n"
      "(or something like .../cgi-bin/dbdump or dbdump.cgi with Unix Web servers)\n");
  fprintf (stderr, "Use    %s -h > %s   to dump out the internal HTML template to the\n", progname, DEFAULT_HTML_TEMPLATE_FILE);
  fprintf (stderr, "       default template file, after which you can edit it to suit your taste.\n");
  fprintf (stderr, "Use    %s -hh  to see how the internal template looks after expansion.\n", progname);
  fprintf (stderr, "Please see http://www.kubl.com/ for more information about our products.\n");
  fflush (stderr);
}

int
version_less_than (char *s, int major, int minor)
{
  int tmp;
  while (*s && NOT isdigit (*s))
    {
      s++;
    }				/* Skip non-digits. */
  if (empty_stringp (s))
    {
      return (0);
    }				/* Premature end? */
  tmp = atoi (s);
  if (tmp > major)
    {
      return (0);
    }
  else if (tmp < major)
    {
      return (1);
    }
  /* They are equivalent, we have to check the minor part also. */
  while (*s && (*s != '.'))
    {
      s++;
    }				/* Search a period. */
  if (empty_stringp (s) || empty_stringp (++s))
    {
      return (0);
    }				/* Not found or followed by nothing */
  tmp = atoi (s);
  return (tmp < minor);
}

char dbms[100];
char drv[100];
long ignore;

int
connect_to_datasource_or_dest (HDBC * ptr_to_hdbc, HENV henv, char *datasource, char *username, char *password)
{
  int rc;

  SQLAllocConnect (henv, ptr_to_hdbc);

  /* We could get messages like:
     Error 01000: Changed database context to 'master'
     from MS SQL Server. Don't output any messages for those!
   */
  if ((SQL_SUCCESS != (rc = SQLConnect (*ptr_to_hdbc,
		  (UCHAR *) datasource, SQL_NTS,
		  (UCHAR *) username, SQL_NTS, (UCHAR *) password, SQL_NTS))) && (SQL_SUCCESS_WITH_INFO != rc))
    {
      print_error (SQL_NULL_HENV, *ptr_to_hdbc, SQL_NULL_HSTMT);
      printf ("-- could not connect to \"%s\".\n", datasource);
      if (rc == SQL_ERROR)
	exit (3);
    }

  SQLSetConnectOption (*ptr_to_hdbc, SQL_AUTOCOMMIT, 0);

  SQLGetInfo (*ptr_to_hdbc, SQL_DBMS_NAME, dbms, sizeof (dbms), ((SWORD *) & ignore));
  SQLGetInfo (*ptr_to_hdbc, SQL_DRIVER_VER, drv, sizeof (drv), ((SWORD *) & ignore));
  SQLGetInfo (*ptr_to_hdbc, SQL_GETDATA_EXTENSIONS, &getdata_extensions, ((SWORD) 4), ((SWORD *) & ignore));

  return (rc);
}

/*
   In this function we check if any direct linking of tables
   failed in print_table_definition_banner
 */
int
check_for_failed_tables (struct tabledeflist *tl)
{
  int number_of_failed = 0;

  for (; tl; tl = tl->next)
    {
      if (tl->last_SQL_state)
	{
	  if (0 == number_of_failed)
	    {
	      fprintf (stdout, "-- The linking of the following tables failed for the following reasons:\n");
	    }
	  fprintf (stdout, "-- \"%s\" -> %s: %s\n", tl->name, tl->last_SQL_state, tl->last_SQL_message);
	  number_of_failed++;
	}
    }

  fflush (stdout);
  return (number_of_failed);
}



int
main (int argc, char **argv)
{
  char *query_string;
  char *query_string_error = NULL;

#if 0
#ifdef MALLOC_DEBUG
  dbg_malloc_enable ();
#endif
#endif

  progname = argv[0];

  maxlinelength_for_foreach = atol (DEFAULT_MAXLINELEN);
  maxhexlength_for_foreach = atol (DEFAULT_MAXHEXLEN);

  SQLAllocEnv (&henv);		/* This might be needed quite soon. */

  if ((query_string = getenv ("QUERY_STRING")) || getenv ("HTTP_HOST") || getenv ("SERVER_PROTOCOL"))	/* Used as a CGI-script? */
    {				/* There is a query string in the environment variable QUERY_STRING */
      /* which means that this is used with the Web browser. */
      web_mode = 1;
      if (query_string)
	{
	  /* The following might override web_content_type */
	  query_string_error = parse_url_query_string (query_string);
	}

      if (flag_get_list_of_tables || (!datasource || universal_transfer_flag))
	{
	  printf ("Content-Type: %s\r\n\r\n", "text/html");
	  fflush (stdout);
	  if (!flag_get_list_of_tables)
	    {
	      output_html_file (universal_transfer_flag ? DEFAULT_TRANSFER_TEMPLATE1 : DEFAULT_HTML_TEMPLATE_FILE);
	      if (!universal_transfer_flag)
		{
		  exit (0);
		}
	    }
	}
      else			/* Ordinary usage. */
	{
	  printf ("Content-Type: %s\r\n\r\n", web_content_type);
	  fflush (stdout);
	}
    }
  else
    {
      int i, nth_non_option;
      for (i = 1, nth_non_option = 0; i < argc; i++)
	{
/* If the argument begins with a dash (-) then overwrite it with an
   equal sign (=) so that it will be interpreted as an option in
   parse_url_query_string. */
	  if (((*(argv[i]) == '-') && (*(argv[i]) = '=')) || strchr (argv[i], '='))	/* There's an equal sign? */
	    {
	      query_string = argv[i];
	      query_string_error = parse_url_query_string (query_string);
	      if (query_string_error)
		{
		  goto arg_error;
		}
	    }
	  else
	    {
	      switch (++nth_non_option)
		{
		case 1:
		  {
		    datasource = argv[i];
		    break;
		  }
		case 2:
		  {
		    username = argv[i];
		    break;
		  }
		case 3:
		  {
		    password = argv[i];
		    break;
		  }
		}
	    }
	}			/* for loop over arguments */
    }				/* else, not used with the Web browser */

  if (list_data_sources_flag)
    {
      list_data_sources (web_mode, "", "");
      exit (0);
    }

  if (dump_html_template_file_flag)
    {
      output_html_file (DEFAULT_HTML_TEMPLATE_FILE);
      exit (0);
    }

  if (query_string_error)
    {
    arg_error:
      fputs (query_string_error, (web_mode ? stdout : stderr));
      exit (1);
    }

  if ((NO datasource) && (0 == web_mode))
    {
      l_usage (*argv);
      exit (0);
    }

/* Note that parse_url_query_string inserts into string pointer arguments
   various substrings of query_string, returned by getenv or taken from
   the command line arg. If I remember right, getenv returns a pointer
   to static string buffer, so if you call getenv second time, its
   result will overwrite the old query_string, and probably also the
   resulting strings you got here.
 */

  if (NO only_table_definitions_flag && NO only_index_definitions_flag && NO only_contents_flag)
    {				/* If ALL these flags has been left OFF, then turn them ALL ON */
      only_table_definitions_flag = only_index_definitions_flag = only_contents_flag = 1;
    }

/* Not done here anymore, instead in get_all_tables for each separate token
  tablename = divide_tablename(tablename,&tablequalifier,&tableowner);
 */

  if (flag_get_list_of_tables)
    {
      tablequalifier = tableowner = tablename = NULL;	/* Everything? */
      verbose_flag = 0;		/* Force it to shut up, in case our JavaScript code fails. */
    }

  if (verbose_flag && datasource)
    {
      fprintf (stdout, "-- %s: dumping datasource \"%s\", username=%s\n", *argv, datasource, username);
      fprintf (stdout,
	  "-- tablequalifier=%s  tableowner=%s  tablename=%s  tabletype=%s\n",
	  (tablequalifier ? tablequalifier : "NULL"),
	  (tableowner ? tableowner : "NULL"), (tablename ? "is given, one or more" /* tablename */ : "NULL"),
	  (tabletype ? tabletype : "NULL"));
    }

  if (kubl_default_conversions_flag)
    {
      conv_types_table = &kubl_default_conv_types[0];	/* "Rewind" to the beginning. */
      n_conv_types += N_KUBL_DEFAULT_CONVERSIONS;	/* We got this many for free! */
    }

  if (verbose_flag && n_conv_types)
    {
      int i;

      fprintf (stdout, "-- Converting %d types\n", n_conv_types);
      for (i = 2; i <= (2 * n_conv_types); i += 2)
	{
	  fprintf (stdout, "-- From %s to %s\n",
	      (conv_types_table[i] ? conv_types_table[i] : "NULL"), (conv_types_table[i + 1] ? conv_types_table[i + 1] : "NULL"));
	}
    }

  fflush (stdout);

  connect_to_datasource_or_dest (&hdbc, henv, datasource, username, password);

  if (verbose_flag)
    {
      fprintf (stdout, "-- Connected to datasource \"%s\", Driver v. %s.\n", dbms, drv);
    }

  if (strstr (dbms, "UBL") || strstr (dbms, "ubl"))
    {
      kubl_mode = 1;
      if (version_less_than (drv, 0, 92))
	{
	  fprintf (stderr, "-- Sorry, you need KUBL ODBC driver version 0.92 or later to run this tool.\n");
	  fprintf (stderr, "-- It is available from http://www.kubl.com\n");
	  exit (1);
	  times_conform_to_odbc_flag = 0;
	  times_to_strings_flag = 1;
	}
      if (version_less_than (drv, 0, 96))
	{
	  varchar_cols_returned_with_length_plus = 1;
	}
      never_escape_tablenames_in_select = 0;	/* Yes, escape them. */
      if (0 == use_table_prefixes_flag_given)
	{			/* Not explicitly specified by the user? Then turn it on because */
	  use_table_prefixes_flag = 1;	/* Prefixes are useful with new Kubl */
	}
    }
  else				/* Some other DBMS, e.g. Access. */
    {
      kubl_mode = 0;
/*   times_conform_to_odbc_flag=1;   Already initialized to these values.
     times_to_strings_flag=0; */
    }
  if (strstr (dbms, "ccess") || strstr (dbms, "CCESS"))
    {
      never_escape_tablenames_in_select = 1;
      if (0 == use_table_prefixes_flag_given)
	{			/* Not explicitly specified by the user? */
	  use_table_prefixes_flag = 0;	/* Prefixes are harmful for Access */
	}
    }
  /* For Microsoft SQL Server */
  else if (strstr (dbms, "SQL Server") || strstr (dbms, "SQL SERVER"))
    {
      never_escape_tablenames_in_select = 1;
      if (0 == use_table_prefixes_flag_given)
	{			/* Not explicitly specified by the user? */
	  use_table_prefixes_flag = 1;	/* Prefixes are useful with MS SQL Server */
	}
    }

/* #endif */

  SQLAllocStmt (hdbc, &stmt);

  if (init_statement)		/* User gave one initialization statement? */
    {				/* e.g. "USE somedatabasename" with MS SQL server */
      IF_ERR_GO (stmt, error, SQLExecDirect (stmt, UCP (init_statement), SQL_NTS));
    error:
      SQLFreeStmt (stmt, SQL_CLOSE);
      if (SQL_SUCCESS != SQLTransact (henv, hdbc, SQL_COMMIT))
	{
	  print_error (SQL_NULL_HENV, hdbc, SQL_NULL_HSTMT);
	  exit (1);
	}
    }


  driver_has_necessary_sql_functions ();	/* Will exit by itself if not. */

  if (datadest)
    {
      connect_to_datasource_or_dest (&datadest_hdbc, henv, datadest, dest_username, dest_password);

      if (verbose_flag)
	{
	  fprintf (stdout, "-- Connected to data destination \"%s\", Driver v. %s.\n", dbms, drv);
	}

      SQLAllocStmt (datadest_hdbc, &datadest_gen_stmt);
    }


  {
    int count = 0;
    int no_sql_primary_keys = 0;
    struct tabledeflist *tl;
    UWORD FunctionExists = TRUE;	/* Unless otherwise proved. */

    tl = all_tables_list = get_all_tables (tablequalifier, tableowner, tablename, tabletype, &count);

    SQLGetFunctions (hdbc, SQL_API_SQLPRIMARYKEYS, &FunctionExists);
    if (FunctionExists)
      {
	while (tl)
	  {
/*        debug_fprintf(stdout,
           "-- Reading primary key information of the table %s\n",tl->name);
 */
	    get_table_primarykey (tl);
	    tl = tl->next;
	  }
	if (kubl_mode)
	  {
	    count += get_real_supertables (all_tables_list);
	  }
      }
    else
      {
	no_sql_primary_keys = 1;
	if (verbose_flag)
	  {
	    fprintf (stdout, "-- SQLPrimaryKeys not implemented. Trying to find primary keys with SQLStatistics.\n");
	  }
	SQLGetFunctions (hdbc, SQL_API_SQLSTATISTICS, &FunctionExists);
	if (NO FunctionExists)
	  {
	    fprintf (stderr, "-- Sorry, SQLStatistics not implemented. Exiting.\n");
	    exit (1);
	  }
      }

    if (flag_get_list_of_tables)
      {
	reorder_subtables (all_tables_list);
	output_html_file (DEFAULT_HTML_TEMPLATE_FILE);
	SQLDisconnect (hdbc);
	exit (0);
      }

    if (primary_key_by_all_means_flag)
      {
	SQLGetFunctions (hdbc, SQL_API_SQLSPECIALCOLUMNS, &FunctionExists);
	if (NO FunctionExists)
	  {
	    fprintf (stderr,
		"-- Sorry, SQLSpecialColumns not implemented. It could be hard to determine\n"
		"-- which columns to use as a Primary Key if nothing else is found.\n");
	  }
	else
	  {
	    tl = all_tables_list;
	    while (tl)
	      {
/* If user gave just one -P option, then use SQL_SCOPE_CURROW (0).
   With -PP use SQL_SCOPE_TRANSACTION (1) and
   with -PPP use SQL_SCOPE_SESSION (2)
 */
		get_table_bestrow_columns (tl, ((UWORD) ((primary_key_by_all_means_flag & 3) - 1)), ((UWORD) SQL_NULLABLE));	/* Or SQL_NO_NULLS */
		tl = tl->next;
	      }
	  }
      }

/* Now always get index-information in, regardless whether it will be
   printed or not. (For example, we might need it for PRIMARY KEYs
   anyway).
    if(no_sql_primary_keys || only_index_definitions_flag)
 */
    {
      for (tl = all_tables_list; tl; tl = tl->next)
	{
/*        debug_fprintf(stdout,
           "-- Reading index information of the table %s\n",tl->name); */
	  get_table_indices (tl);	/* Uses SQLStatistics */
	}
    }

    if (verbose_flag)
      {
	fprintf (stdout, "-- Definitions of %d tables were read in.\n", count);
	fflush (stdout);
      }

    /* This will put all the subtables (their tl nodes) to the
       sub_tables lists of their respective super tables, but still
       keep the sub_table nodes themselves intact in all_tables_list.
     */
    reorder_subtables (all_tables_list);
    if (vd_procedures_flag)
      {
	int rc = link_remote_data_source (&datadest_link_stmt,
	    datadest_hdbc,
	    henv,
	    datasource, username, password);

	if (datadest_hdbc)	/* Better to be ON! in this case. */
	  {
	    auto_only_table_definitions_flag = 1;
	  }

	/* No success, so we failed in start. */
	if (SQL_SUCCESS != rc)
	  {
	    fprintf (stderr,
		"-- Linking remote data source to data destination failed.\n"
		"-- Are you sure your data destination is Kubl Universe DBMS?\n");
	    exit (1);
	  }
      }

    output_tables (all_tables_list);
    if (verbose_flag)
      {
	printf ("EXIT;\n");
      }				/* -- The End is Near -- */
    printf ("\n");

    if (datadest_hdbc)		/* We still need to commit the destination data source? */
      {
	UWORD commit_or_rollback = SQL_COMMIT;	/* Could be SQL_ROLLBACK as well */

	int n_failed = check_for_failed_tables (all_tables_list);

	if (n_failed)
	  {
	    if (all_or_nothing_flag)
	      {
		fprintf (stdout, "-- %d linkages failed, discarding all the linkages done at this time.\n", n_failed);
		commit_or_rollback = SQL_ROLLBACK;
		fflush (stdout);
	      }
	  }

	if (SQL_SUCCESS != SQLTransact (henv, datadest_hdbc, commit_or_rollback))
	  {
	    print_error (SQL_NULL_HENV, datadest_hdbc, SQL_NULL_HSTMT);
	    SQLDisconnect (datadest_hdbc);	/* And have some manners */
	  }

	else if (n_failed)
	  {
	    if ((SQL_COMMIT == commit_or_rollback))
	      {
		fprintf (stdout,
		    "-- %d linkages failed, but %d linkages still succeeded and committed.\n", n_failed, (count - n_failed));
		fflush (stdout);
	      }
	  }
      }

    if (universal_transfer_flag)
      {
	output_html_file (DEFAULT_TRANSFER_TEMPLATE2);
      }
  }


  SQLDisconnect (hdbc);

  exit (0);
}

/* ================================================================== */
/*            FUNCTIONS FOR OUTPUTTING HTML PAGE                      */
/* ================================================================== */

typedef char *(*PFSTR) (char *);
/* Pointer to function returning a char pointer, taking one string as
   its argument. */

FILE *html_infp = NULL;

char *
line_from_html_file (char *templatename)
{
  return (fgets (tmp1, TMP1_LEN, html_infp));
}

/* Return the whole string in one piece. After that return NULL.
   Really Ad Hoc just for quick, quick work.
 */
char *
line_from_html_string (char *templatename)
{
  static char counts_visited = 0;
  static char *last_templatename = "";
  extern char *html_page_string;	/* In the end of this module. */
  extern char *transfer_html_page_string1, *transfer_html_page_string2;

  if ((0 == counts_visited) || (templatename != last_templatename))
    {				/* First time here with this templatename? */
      counts_visited++;
      last_templatename = templatename;

      if (!strcmp (templatename, DEFAULT_TRANSFER_TEMPLATE1))
	{
	  return (transfer_html_page_string1);
	}

      if (!strcmp (templatename, DEFAULT_TRANSFER_TEMPLATE2))
	{
	  return (transfer_html_page_string2);
	}

      if (!strcmp (templatename, DEFAULT_HTML_TEMPLATE_FILE))
	{
	  return (html_page_string);
	}
    }

  return (NULL);
}


/* This contains the crudest kind of a template interpreter. It just checks
   whether the string $INPUT_DATASOURCE is found in the midst of lines.
 */
int
output_html_page (PFSTR sourcefun, char *templatename)
{
  char *line, *ptr, *next;


  while ((line = ((sourcefun) (templatename))) != NULL)	/* Still got something. */
    {
    again:
/* Option -hh prints out with the tokens expanded, but the option -h
   prints the template out in the raw format: */
      if ((dump_html_template_file_flag != 1) && (ptr = strchr (line, '$')))
	{
	  fwrite (line, sizeof (char), (ptr - line), stdout);
	  if ((next = string_begins_with ((ptr + 1), VERSION_TOKEN)) != NULL)
	    {
	      fputs (DBDUMP_VERSION, stdout);
	      line = next;
	    }
	  else if ((next = string_begins_with ((ptr + 1), DATASOURCE_TOKEN)) != NULL)
	    {
	      list_data_sources (1, templatename, DATASOURCE_TOKEN);
	      line = next;
	    }
	  else if ((next = string_begins_with ((ptr + 1), DATADEST_TOKEN)) != NULL)
	    {
	      list_data_sources (1, templatename, DATADEST_TOKEN);
	      line = next;
	    }
	  else if ((next = string_begins_with ((ptr + 1), TABLELIST_TOKEN))
	      || (next = string_begins_with ((ptr + 1), "N_TABLES_OR_MAX")))
	    {
	      int max_value = atoi (next);
	      int n_tables = length_of_tablelist (all_tables_list);

	      if (0 == n_tables)
		{
		  n_tables = 1;
		}
	      if ((0 != max_value) && (max_value < n_tables))
		{
		  n_tables = max_value;
		}

	      if (string_begins_with ((ptr + 1), TABLELIST_TOKEN))
		{
		  output_tablelist_token (n_tables);
		}
	      else
		{
		  printf ("%d", n_tables);
		}

	      while (*next && isdigit (*next))
		{
		  next++;
		}		/* Skip the digits */
	      line = next;
	    }
	  else if ((next = string_begins_with ((ptr + 1), DEFAULT_CONVERSIONS_TOKEN)) != NULL)
	    {
	      int i;
	      for (i = 2; i <= (N_KUBL_DEFAULT_CONVERSIONS * 2); i += 2)
		{
		  printf ("<LI><B>%s</B> <CODE>-&GT;</CODE> <B>%s</B>\n",
		      kubl_default_conv_types[i], kubl_default_conv_types[i + 1]);
		}
	      line = next;
	    }

	  if (*line)		/* And go back to the beginning to print the rest. */
	    {
	      goto again;
	    }			/* (if there's anything left.) */
	}
      else			/* A normal line. */
	{
	  fputs (line, stdout);
	}
    }				/* while */
  return (1);
}

int
output_html_file (char *templatename)
{
/* When using option -h, then take it always from the memory. */
  if (dump_html_template_file_flag || NO (html_infp = fopen (templatename, "r")))
    {
/* Don't whine anymore for this. Use a string given below instead!
       fprintf(stderr,"Cannot open file %s for reading!\n",filename);
       return(0);
 */
      output_html_page (line_from_html_string, templatename);
    }
  else
    {
      output_html_page (line_from_html_file, templatename);
    }
  return (1);
}

/*
  You can dump this out in the unexpanded form with a command DBDUMP -h
  and in the expanded form with a command: DBDUMP -hh
  If there is a filename dbdump.htm in the same directory where the
  dbdump.exe is executed as a CGI-script, then that file is used
  instead of this string.

  Yes, the layout really sucks now.

  Note how the double-choosing of tablenames
  by transferring them from S_TABLES multichoice select/option list
  to tablename multiline textfield with the JavaScript function
  add_selected_items_to_the_text_elem
  (See the C-function output_tables_as_select_list)
  is NOT really necessary.
  We COULD discard with the single/multiline textfield,
  and rename the multichoice select-list to tablename
  (instead of S_TABLES).
  Even then, the user could choose various tables separated from each
  other in the list (by pressing CTRL while dragging the mouse
  over further tablenames).
  However, by having the multiline textfield next to the select-list,
  the user can also enter any wildcard patterns like *.*.*, etc,
  or directly any tablename he knows must exist in the datasource.
 */

char *html_page_string
    =
    "<HTML><HEAD><TITLE>DBDUMP - DataBase Dump, version " DBDUMP_VERSION "</TITLE>\n"
    "<META NAME=DESCRIPTION CONTENT=\"DBDUMP default template for table linking and dumping.\">\n"
    "<SCRIPT LANGUAGE=\"JavaScript\">\n"
    "<!-- Hide the script from old browsers\n"
    "function check_radiobutton_with_value(items,with_value)\n"
    "{\n"
    "   var j, maxval = items.length;\n"
    "   for(j = 0; j < maxval; j++)\n"
    "    {\n"
    "      if(items[j].value == with_value) { items[j].checked = 1; }\n"
    "      else { items[j].checked = 0; }\n"
    "    }\n"
    "   return(j);\n"
    "}\n"
    "\n"
    "function select_option_with_value(items,with_value)\n"
    "{\n"
    "   var j, maxval = items.length;\n"
    "   for(j = 0; j < maxval; j++)\n"
    "    {\n"
    "      if(items[j].value == with_value) { items[j].selected = 1; }\n"
    "      else { items[j].selected = 0; }\n"
    "    }\n"
    "   return(j);\n"
    "}\n"
    "\n"
    "function set_options_according_to_action(form_obj)\n"
    "{\n"
    "    var selected_action = form_obj.OPCODE.options[form_obj.OPCODE.selectedIndex].value;\n"
    "\n" "    form_obj.OPTION_U.checked = 0; // Don't use ISQL-form unless otherwise indicated.\n"
/* "    form_obj.RTL2.value = '';\n" */
    "\n"
    "    if((\"LTD\" == selected_action) // Link tables directly\n"
    "     || (\"LTDAON\" == selected_action) // --- '' --- all or none\n"
    "     || (\"LTI\" == selected_action)) // Link tables via ISQL-form\n"
    "     {\n"
    "       form_obj.OPTION_V.checked = 1; // Produce Linking Calls\n"
    "       form_obj.OPTION_K.checked = 1; // Use Kubl default conversions\n"
    "       form_obj.OPTION_P.checked = 1; // Get Primary Keys by any means\n"
    "       form_obj.OPTION_small_a.checked = 1; // Quote column (and index) names\n"
    "\n"
    "       if(\"LTI\" == selected_action) // via ISQL-form?\n"
    "        {\n"
    "          form_obj.OPTION_U.checked = 1; // Use ISQL-form.\n"
    "        }\n"
    "       else // LTD or LTDAON\n"
    "        {\n"
    "          if(\"LTDAON\" == selected_action)\n"
    "           { form_obj.OPTION_A.checked = 1; } // All or None flag on.\n"
    "          else\n" "           { form_obj.OPTION_A.checked = 0; } // All or None flag off.\n"
#ifdef USE_TEXTFIELD_DATASOURCE
    "          if(0 == form_obj.S_DATADEST.value.length)\n"
#else
    "          if(0 == form_obj.S_DATADEST.selectedIndex)\n"
#endif
    "           {\n"
    "             alert(\"You must set Data Destination to proper Kubl Virtual Database!\");\n"
    "             return(false);\n"
    "           }\n"
    "        }\n"
    "     }\n"
    "    else // Not a \"Link tables\" operation, so it's probably a dump\n"
    "     {\n"
    "       form_obj.OPTION_V.checked = 0; // Do not produce Linking Calls\n"
    "     }\n"
    "\n"
    "    if(\"DUS\" == selected_action) // Dump schema/contents to Screen\n"
    "     {\n"
    "       form_obj.CONTENT_TYPE.checked = 0; // No special content type.\n"
    "     }\n"
    "    else if(\"DUF\" == selected_action) // Dump schema/contents to File\n"
    "     {\n"
    "       form_obj.CONTENT_TYPE.checked = 1; // Special content type.\n"
    "     }\n"
    "    else if(\"DUI\" == selected_action) // Dump schema/contents via ISQL-form\n"
    "     {\n"
    "       form_obj.CONTENT_TYPE.checked = 0; // No special content type.\n"
    "       form_obj.OPTION_U.checked = 1; // Use ISQL-form.\n"
    "     }\n"
    "    else if(\"RTL\" == selected_action) // Reload table list, quietly\n"
    "     {\n" "       check_radiobutton_with_value(form_obj.OPTION_qv,'q');\n" "     }\n" "\n"
/*
"// We cannot produce any comment lines beginning with a double-dash\n"
"// because ISQL cannot yet handle (skip) them when they come from\n"
"// HTML-form. So let's turn verbose-mode off (quiet-mode on)\n"
"// when via ISQL-form is used:\n"
 */
    "    if(form_obj.OPTION_U.checked)\n"
    "     {\n"
    "       check_radiobutton_with_value(form_obj.OPTION_qv,'q');\n"
    "     }\n"
    "\n"
    "    return(true);\n"
    "}\n"
    "\n"
    "\n"
    "function add_selected_items_to_the_text_elem(select_items,text_elem)\n"
    "{\n"
    "   var j, maxval = select_items.length;\n"
    "   text_elem.value=\"\";"
    "   for(j = 0; j < maxval; j++)\n"
    "    {\n"
    "      if(select_items[j].selected)\n"
    "       {\n"
    "         if(text_elem.value.length != 0)\n"
    "          { text_elem.value += '\\r\\n'; }\n"
    "         text_elem.value += select_items[j].value;\n"
    "       }\n" "    }\n" "}\n" "\n" "// -- Stop Hiding Here -->\n" "</SCRIPT>\n" "</HEAD>\n" "<BODY>\n"
/* "<FORM ACTION=\"" DBDUMP_CGI_LOCATION "\" NAME=\"DBDUMP_OPTIONS\" METHOD=GET" */
    "<FORM NAME=\"DBDUMP_OPTIONS\" METHOD=GET" " onsubmit=\"return(set_options_according_to_action(this))\">\n"
/* "<INPUT TYPE=HIDDEN NAME=RTL2 VALUE=\"\">\n" */
    "<TABLE>\n"
    "<TR>\n"
    "<TD VALIGN=CENTER><B>Data Source</B></TD>\n"
    "<TD VALIGN=TOP COLSPAN=2>$" DATASOURCE_TOKEN "</TD>\n"
    "</TR>\n"
    "<TR>\n"
    "<TD VALIGN=CENTER><B>Username&nbsp;&amp;&nbsp;Password</B></TD>\n"
    "<TD VALIGN=TOP><INPUT TYPE=TEXT NAME=username SIZE=10><INPUT TYPE=CHECKBOX NAME=EMPTY_USERNAME VALUE=\"ON\">(empty)</TD>\n"
    "<TD VALIGN=TOP><INPUT TYPE=PASSWORD NAME=password SIZE=10><INPUT TYPE=CHECKBOX NAME=EMPTY_PASSWORD VALUE=\"ON\">(empty)</TD>\n"
    "</TR>\n"
    "<TR><TD COLSPAN=3><HR></TD></TR>\n"
    "<TR>\n"
    "<TD VALIGN=CENTER><B>Data&nbsp;Destination</B><BR><I>(Use only with direct linkage)</I></TD>\n"
    "<TD VALIGN=TOP COLSPAN=2>$" DATADEST_TOKEN "</TD>\n"
    "</TR>\n"
    "<TR>\n"
    "<TD VALIGN=CENTER><B>Username&nbsp;&amp;&nbsp;Password for Destination</B></TD>\n"
    "<TD VALIGN=TOP><INPUT TYPE=TEXT NAME=s_dstuser SIZE=10><INPUT TYPE=CHECKBOX NAME=S_EMPTY_DSTUSER VALUE=\"ON\">(empty)</TD>\n"
    "<TD VALIGN=TOP><INPUT TYPE=PASSWORD NAME=s_dstpass SIZE=10><INPUT TYPE=CHECKBOX NAME=S_EMPTY_DSTPASS VALUE=\"ON\">(empty)</TD>\n"
    "</TR>\n"
    "<TR><TD COLSPAN=3><HR></TD></TR>\n"
    "<TR>\n"
    "<TD></TD><TD VALIGN=TOP><B>Available Tables</B></TD>\n"
    "<TD VALIGN=TOP NOWRAP><B>Tables to Link/Dump</B> <I>(Leave empty: All)</I></TD>\n"
    "</TR>\n"
    "<TR><TD></TD>\n"
    "<TD COLSPAN=1 VALIGN=TOP>$" TABLELIST_TOKEN "10</TD>\n"
    "<TD VALIGN=TOP><TEXTAREA NAME=tablename ROWS=$N_TABLES_OR_MAX10 COLS=24></TEXTAREA></TD>\n" "</TR>\n"
/*
"<TR>\n"
"<TD VALIGN=TOP></TD>\n"
"<TD VALIGN=TOP><INPUT TYPE=SUBMIT VALUE=DUMP></TD>\n"
"<TD VALIGN=TOP><INPUT TYPE=RESET VALUE=CLEAR></TD>\n"
"</TR>\n"
 */
    "<TR>\n"
    "<TD VALIGN=CENTER><B>Action</B></TD>\n"
    "</TD>\n"
    "\n"
    "<TD VALIGN=TOP COLSPAN=1>\n"
    "<SELECT NAME=OPCODE onchange=\"set_options_according_to_action(this.form)\">\n"
    "<OPTION VALUE=\"LTD\">Link tables directly\n"
    "<OPTION VALUE=\"LTDAON\">Link tables directly, all or none\n"
    "<OPTION VALUE=\"LTI\">Link tables via ISQL-form\n"
    "<OPTION VALUE=\"DUS\">Dump schema/contents to Screen\n"
    "<OPTION VALUE=\"DUF\">Dump schema/contents to File\n"
    "<OPTION VALUE=\"DUI\">Dump schema/contents via ISQL-form\n"
    "<OPTION VALUE=\"RTL\">Reload table list\n"
    "</SELECT>\n"
    "</TD>\n"
    "<TD VALIGN=TOP><INPUT TYPE=SUBMIT VALUE=\"Do it\" WIDTH=120></TD>\n" "</TR>\n" "\n" "<TR><TD COLSPAN=3><HR></TD></TR>\n"
/*

"<TR>\n"
"<TD VALIGN=TOP><B>Table Name(s)</B></TD>\n"
"<TD COLSPAN=2>\n"
"<!-- INPUT TYPE=TEXT NAME=tablequalifier -->\n"
"<!-- INPUT TYPE=TEXT NAME=tableowner -->\n"
"<INPUT TYPE=TEXT SIZE=45 NAME=tablename>\n"
"<INPUT TYPE=SUBMIT VALUE=DUMP>\n"
"</TD>\n"
"</TR>\n"
 */
    "<TR>\n"
    "<TD VALIGN=TOP><B>Options</B></TD>\n"
    "<TD COLSPAN=2>\n"
    "<TABLE>\n"
    "<TR><TD COLSPAN=1 VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=OPTION_V VALUE=V CHECKED>"
    " <B>Produce Table Linkage Calls</B>\n"
    "</TD><TD COLSPAN=1 VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=OPTION_A VALUE=A> <B>Link none if any linkage fails</B>\n"
    "</TD></TR>\n"
    "<!-- The next two work like radiobuttons, turning each other off -->\n"
    "<TR>\n"
    "<TD VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=OPTION_U VALUE=U "
    "onclick=\"if(this.checked) { this.form.CONTENT_TYPE.checked=0; }\">\n"
    "<B>Transfer Schema/Data to another DBMS (via HTML-form)</B>\n"
    "</TD><TD VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=CONTENT_TYPE VALUE=\"x-DBDUMP-output-to-text-file\" "
    "onclick=\"if(this.checked) { this.form.OPTION_U.checked=0; }\">\n" "<B>Dump to file instead of screen</B>\n" "</TD></TR>\n"
/* With U be also absolutely quiet (option q), because isql(odbc)
   cannot currently handle comments beginning with double-dash (--)
   coming in S_EXEC argument (in Url). This is done with JavaScript
   event handler onClick, which will toggle the radiobutton OPTION_qv
   (later in this form) to quiet-state, from the default verbose-state.
   Also, use N option (nicer_output_flag), so that PRIMARY KEYs are
   shown on the next line, appropriately indented.
 */
    "<TR>\n"
    "<TD VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=OPTION_P VALUE=P CHECKED> <B>Produce Primary Key by any means</B>\n"
    "</TD><TD VALIGN=TOP></TD></TR>\n"
    "<TR>\n"
    "<TD VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=OPTIONS VALUE=t CHECKED> <B>Table definitions only</B>\n"
    "</TD><TD VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=OPTIONS VALUE=i > <B>Index definitions only</B>\n"
    "</TD></TR><TR><TD VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=OPTIONS VALUE=c> <B>Contents only</B>\n"
    "</TD><TD VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=OPTIONS VALUE=d> <B>The -d option (obscure)</B>\n"
    "</TD></TR>\n"
    "<TR>\n"
    "<TD VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=OPTIONS VALUE=T CHECKED> <B>Only supertable table definitions</B>\n"
    "</TD><TD VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=OPTIONS VALUE=I CHECKED> <B>Only supertable index definitions</B>\n"
    "</TD></TR><TR><TD VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=OPTIONS VALUE=C> <B>Only supertable contents</B>\n"
    "</TD><TD VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=OPTIONS VALUE=TIC> <B>All supertable information (-TIC)</B>\n"
    "</TD></TR>\n"
    "<TR><TD COLSPAN=2 VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=OPTION_small_a CHECKED VALUE=a> <B>Surround all column and index names with doublequotes</B>\n"
    "</TD></TR>\n"
/* These two are semi obsolete: */
    "<TR><TD VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=OPTIONS VALUE=b> <B>Prefix all names with backslash</B>\n"
    "</TD><TD VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=OPTIONS VALUE=bb> <B>Like above, but also in select statement</B>\n"
    "</TD></TR>\n"
    "<TR><TD VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=OPTIONS VALUE=r> <B>No drops<B>\n"
    "</TD><TD VALIGN=TOP>\n" "<INPUT TYPE=CHECKBOX NAME=OPTIONS VALUE=s> <B>Never use foreach<B>\n" "</TD></TR>\n"
/*
"<TR><TD COLSPAN=2>\n"
"<INPUT TYPE=CHECKBOX NAME=OPTIONS VALUE=p> "
"<B>Use plain tablenames only, no prefixes</B>\n"
"</TD></TR>\n"
 */
/* Neither of these are initially checked (except in Lynx) which
   allows for this program to set the appropriate default mode right
   after the connection, for instance for:
   Access (where prefixing produces incorrect behaviour) and
   Old Kubl (where prefixing is unnecessary), and
   New Kubl and MS SQL Server (where prefixing is usually very useful).
 */
/* Largely obsoleted by new_name option with its !Q.!O.!N markers.
   This just confuses users, commented out.
"<TR><TD VALIGN=TOP>\n"
"<INPUT TYPE=RADIO NAME=OPTIONp VALUE=\"p\"> <B>Plain tablenames,<BR>\n"
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;no prefixes</B>\n"
"</TD><TD VALIGN=TOP>\n"
"<INPUT TYPE=RADIO NAME=OPTIONp VALUE=\"+p\"> <B>Prefixed tablenames<BR>\n"
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</B>(e.g. <CODE>db.dba.tabnam</CODE>)\n"
"</TD></TR>\n"
 */
    "<TR><TD VALIGN=TOP>\n" "<INPUT TYPE=RADIO NAME=OPTION_qv VALUE=\"q\" > <B>Brief</B>\n" "</TD><TD VALIGN=TOP>\n" "<INPUT TYPE=RADIO NAME=OPTION_qv CHECKED VALUE=\"v\"> <B>Verbose</B>\n" "</TD></TR>\n" "<TR><TD VALIGN=TOP>\n" "<INPUT TYPE=RADIO CHECKED NAME=OPTION2 VALUE=\"\"> "	/* Was ne */
    "<B>Escape strange chars</B>\n" "</TD><TD VALIGN=TOP>\n" "<INPUT TYPE=RADIO NAME=OPTION2 VALUE=e> "	/* Was nee */
    "<B>Escape also ISO-8859/1</B>\n" "</TD></TR>\n" "<TR><TD COLSPAN=2>\n" "<INPUT TYPE=RADIO NAME=OPTION2 VALUE=n> "	/* Is n */
    "<B>Escape only single quotes by doubling them</B>\n"
    "</TD></TR>\n"
    "<TR><TD VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=OPTION_N VALUE=N CHECKED>"
    " <B>Indented table-definitions</B>\n"
    "</TD><TD VALIGN=TOP>\n"
    "<INPUT TYPE=CHECKBOX NAME=OPTIONS VALUE=D> <B>Debug trace<B>\n"
    "</TD></TR>\n"
    "</TABLE>\n"
    "</TD>\n"
    "</TR>\n"
    "<TR><TD VALIGN=TOP><B>Convert types</B></TD>"
    "<TD VALIGN=TOP COLSPAN=2><INPUT TYPE=CHECKBOX NAME=OPTION_K VALUE=K> <B>Kubl Default Conversions</B> <I>(Use this when destination is Kubl)</I></TD></TR>\n"
    "<TR><TD VALIGN=TOP><B>as well as</B></TD><TD VALIGN=TOP><B>from</B></TD><TD VALIGN=TOP><B>to</B></TD></TR>\n"
    "<TR><TD VALIGN=TOP></TD>\n"
    "<TD VALIGN=TOP><SELECT NAME=CONVSRC1>\n"
    "<OPTION VALUE=\"\">-\n"
    "<OPTION>CHAR\n"
    "<OPTION>NUMERIC\n"
    "<OPTION>DECIMAL\n"
    "<OPTION>INTEGER\n"
    "<OPTION>SMALLINT\n"
    "<OPTION>FLOAT\n"
    "<OPTION>REAL\n"
    "<OPTION>DOUBLE PRECISION\n"
    "<OPTION>DATE\n"
    "<OPTION>TIME\n"
    "<OPTION>TIMESTAMP\n"
    "<OPTION>VARCHAR\n"
    "<OPTION>BIT\n"
    "<OPTION>BIT VARYING\n"
    "<OPTION>LONG VARCHAR\n"
    "<OPTION>BINARY\n"
    "<OPTION>VARBINARY\n"
    "<OPTION>LONG VARBINARY\n"
    "<OPTION>BIGINT\n"
    "<OPTION>TINYINT\n"
    "</SELECT>\n"
    "</TD>\n"
    "<TD VALIGN=TOP><SELECT NAME=CONVDST1>\n"
    "<OPTION VALUE=\"\">-\n"
    "<OPTION>CHAR\n"
    "<OPTION>NUMERIC\n"
    "<OPTION>DECIMAL\n"
    "<OPTION>INTEGER\n"
    "<OPTION>SMALLINT\n"
    "<OPTION>FLOAT\n"
    "<OPTION>REAL\n"
    "<OPTION>DOUBLE PRECISION\n"
    "<OPTION>DATE\n"
    "<OPTION>TIME\n"
    "<OPTION>TIMESTAMP\n"
    "<OPTION>VARCHAR\n"
    "<OPTION>BIT\n"
    "<OPTION>BIT VARYING\n"
    "<OPTION>LONG VARCHAR\n"
    "<OPTION>BINARY\n"
    "<OPTION>VARBINARY\n"
    "<OPTION>LONG VARBINARY\n"
    "<OPTION>BIGINT\n"
    "<OPTION>TINYINT\n"
    "</SELECT>\n"
    "</TD>\n"
    "</TR>\n"
    "<TR><TD VALIGN=TOP></TD>\n"
    "<TD VALIGN=TOP><SELECT NAME=CONVSRC2>\n"
    "<OPTION VALUE=\"\">-\n"
    "<OPTION>CHAR\n"
    "<OPTION>NUMERIC\n"
    "<OPTION>DECIMAL\n"
    "<OPTION>INTEGER\n"
    "<OPTION>SMALLINT\n"
    "<OPTION>FLOAT\n"
    "<OPTION>REAL\n"
    "<OPTION>DOUBLE PRECISION\n"
    "<OPTION>DATE\n"
    "<OPTION>TIME\n"
    "<OPTION>TIMESTAMP\n"
    "<OPTION>VARCHAR\n"
    "<OPTION>BIT\n"
    "<OPTION>BIT VARYING\n"
    "<OPTION>LONG VARCHAR\n"
    "<OPTION>BINARY\n"
    "<OPTION>VARBINARY\n"
    "<OPTION>LONG VARBINARY\n"
    "<OPTION>BIGINT\n"
    "<OPTION>TINYINT\n"
    "</SELECT>\n"
    "</TD>\n"
    "<TD VALIGN=TOP><SELECT NAME=CONVDST2>\n"
    "<OPTION VALUE=\"\">-\n"
    "<OPTION>CHAR\n"
    "<OPTION>NUMERIC\n"
    "<OPTION>DECIMAL\n"
    "<OPTION>INTEGER\n"
    "<OPTION>SMALLINT\n"
    "<OPTION>FLOAT\n"
    "<OPTION>REAL\n"
    "<OPTION>DOUBLE PRECISION\n"
    "<OPTION>DATE\n"
    "<OPTION>TIME\n"
    "<OPTION>TIMESTAMP\n"
    "<OPTION>VARCHAR\n"
    "<OPTION>BIT\n"
    "<OPTION>BIT VARYING\n"
    "<OPTION>LONG VARCHAR\n"
    "<OPTION>BINARY\n"
    "<OPTION>VARBINARY\n"
    "<OPTION>LONG VARBINARY\n"
    "<OPTION>BIGINT\n"
    "<OPTION>TINYINT\n"
    "</SELECT>\n"
    "</TD>\n"
    "</TR>\n"
    "<!-- We could have more of these conversion pop-ups, but at least\n"
    "     my Netscape starts behaving very erratically when there are four\n"
    "     pairs of them. -->\n"
    "<TR><TD VALIGN=TOP><B>New Name for Table(s)</B></TD>\n"
    "<TD COLSPAN=2>\n"
    "<INPUT TYPE=TEXT SIZE=45 NAME=\"new_name\" VALUE=\"&quot;!D&quot;.&quot;!N&quot;\">\n"
    "</TD>\n"
    "</TR>\n"
    "<TR><TD VALIGN=TOP><B>Initial Statement</B></TD>\n"
    "<TD COLSPAN=2>\n"
    "<INPUT TYPE=TEXT SIZE=45 NAME=init>\n"
    "</TD>\n"
    "</TR>\n"
    "<TR><TD VALIGN=TOP><B>Select Override</B></TD>\n"
    "<TD COLSPAN=2>\n"
    "<INPUT TYPE=TEXT SIZE=45 NAME=select>\n"
    "</TD>\n"
    "</TR>\n"
    "<TR><TD VALIGN=TOP><B>Unquoted Columns</B></TD>\n"
    "<TD COLSPAN=2>\n"
    "<INPUT TYPE=TEXT SIZE=45 NAME=unquoted_columns>\n"
    "</TD>\n"
    "</TR>\n"
    "<TR>\n"
    "<TD VALIGN=TOP><B>Table Type(s)</B></TD>\n"
    "<TD VALIGN=TOP COLSPAN=2>\n"
    "<TABLE>\n"
    "<TR>\n"
    "<TD><INPUT TYPE=CHECKBOX NAME=TABLETYPE VALUE=\"TABLE\" CHECKED>\n"
    "<B>table</B></TD>\n"
    "<TD><INPUT TYPE=CHECKBOX NAME=TABLETYPE VALUE=\"SYSTEM TABLE\">\n"
    "<B>system table</B></TD>\n"
    "<TD><INPUT TYPE=CHECKBOX NAME=TABLETYPE VALUE=\"GLOBAL TEMPORARY\">\n"
    "<B>global temporary</B></TD>\n"
    "</TR><TR>\n"
    "<TD><INPUT TYPE=CHECKBOX NAME=TABLETYPE VALUE=\"VIEW\">\n"
    "<B>view</B></TD>\n"
    "<TD><INPUT TYPE=CHECKBOX NAME=TABLETYPE VALUE=\"SYNONYM\">\n"
    "<B>synonym</B></TD>\n"
    "<TD><INPUT TYPE=CHECKBOX NAME=TABLETYPE VALUE=\"LOCAL TEMPORARY\"> \n"
    "<B>local temporary</B></TD>\n"
    "</TR><TR>\n"
    "<TD><INPUT TYPE=CHECKBOX NAME=TABLETYPE VALUE=\"ALIAS\"> \n" "<B>alias</B></TD>\n" "</TR>\n" "</TABLE>\n" "</TD></TR>\n"
/* Quite unnecessary, at least currently.
"<TR><TD><B>Other tabletype(s)</B></TD>\n"
"<TD><INPUT TYPE=TEXT NAME=TABLETYPE></TD>\n"
"<TD>(enter in uppercase, separate with commas)</TD>\n"
"</TR>\n"
 */
    "<TR>\n"
    "<TD VALIGN=TOP><B>Insert Mode</B></TD>\n"
    "<TD COLSPAN=2><SELECT NAME=INSERT_MODE>\n"
    "<OPTION SELECTED>INTO\n" "<OPTION>SOFT\n" "<OPTION>REPLACING\n" "</SELECT>\n" "</TD>\n" "</TR>\n"
/* Quite unnecessary, at least currently.
"<TR>\n"
"<TD VALIGN=TOP><B>End Token</B></TD>\n"
"<TD COLSPAN=2><INPUT TYPE=TEXT NAME=ENDTOKEN VALUE=END>\n"
"</TD>\n"
"</TR>\n"
 */
    "<TR>\n"
    "<TD VALIGN=TOP><B>MaxLine/HexLen</B></TD>\n"
    "<TD VALIGN=TOP><INPUT TYPE=TEXT NAME=FOREACH_MAXLINELEN VALUE=" DEFAULT_MAXLINELEN
    "></TD>\n"
    "<TD VALIGN=TOP><INPUT TYPE=TEXT NAME=FOREACH_MAXHEXLEN VALUE=" DEFAULT_MAXHEXLEN
    "></TD>\n"
    "</TR>\n"
    "<TR>\n"
    "<TD VALIGN=TOP></TD>\n"
    "<TD VALIGN=TOP><INPUT TYPE=SUBMIT VALUE=DUMP></TD>\n"
    "<TD VALIGN=TOP><INPUT TYPE=RESET VALUE=CLEAR></TD>\n"
    "</TR>\n"
    "</TABLE>\n"
    "</FORM>\n"
    "<HR>\n"
    "<H3>Notes</H3>\n"
    "<UL>\n"
    "<P><LI>\n"
    "DBDUMP has been tested to work with <B>Kubl</B> as well as \n"
    "with <CODE>Microsoft Access, Driver version 3.40.2829.</CODE>\n"
/* "Now it more or less also works with " */
    "and\n"
    "<CODE>Microsoft SQL Server, Driver v. 02.65.0240.</CODE>\n"
    "(Although the BLOB-columns are still problematic).\n"
    "<P><LI>\n"
    "To work with Kubl it needs KUBL ODBC driver, version 0.92\n"
    "or newer, or needs to be linked with the corresponding static library\n"
    "<CODE>libwic.a</CODE> or <CODE>wic.lib</CODE>\n"
    "<P><LI>\n"
    "Only the datasources that have been defined as System DSN's are shown\n"
    "in the <B>Data Source</B> pop-up list given on the top of this form.\n"
    "This is the case when DBDUMP is used with the Microsoft Internet\n"
    "Information Server in Windows NT. When used in Unix you should enter\n"
    "into the textfield the host name and the port where Kubl is listening.\n"
    "The default is <CODE>localhost:1111</CODE>\n"
    "<P><LI>\n"
    "If you leave the <B>Tables to Link/Dump</B> field as empty, then all tables\n"
    "of the given <B>Table Type(s)</B> are listed (by default, all user defined\n"
    "tables). You can give in this field either an exact table name or\n"
    "a wildcard expression like <CODE>t%</CODE> to dump all tables beginning\n"
    "with the letter 't'. If you give a string\n"
    "like <CODE>Qual.Own.Name</CODE> then tablequalifier is set to\n"
    "<CODE>Qual</CODE>, tableowner to <CODE>Own</CODE> and tablename to\n"
    "<CODE>Name</CODE>. You can give multiple such tablename patterns separated\n"
    "with commas.\n"
    "<P><LI>\n"
    "Specify the format you want tablenames appear in <B>New Name for Table(s)</B>\n"
    "field. You can use markers <B><!-- CODE -->!Q<!-- /CODE --></B>, <B><!-- CODE -->!O<!-- /CODE --></B>\n"
    "and <B><!-- CODE -->!N<!-- /CODE --></B> to refer respectively to\n"
    "Qualifier, Owner and Name parts of the original name. The default is\n"
    "<B><!-- CODE -->&quot;!Q&quot;.&quot;!O&quot;.&quot;!N&quot;<!-- /CODE --></B> which will\n"
    "just copy each original tablename\n"
    "as it was, with all of its prefixes, each one surrounded by doublequotes.\n"
    "Use <B>!Q.!O.!N</B> to avoid this surrounding.\n"
    "Use single <B><!-- CODE -->!N<!-- /CODE --></B>\n"
    "to get rid off all but just the name part itself.\n"
    "Use <B><!-- CODE -->!O.!N@!Q<!-- /CODE --></B> to get Oracle-styled table names like\n"
    "ADMIN.EMP@EMPDATA\n"
    "<BR>Somewhat more contrived example:\n"
    "Use <B><!-- CODE -->Fou..Bar!N_!N2<!-- /CODE --></B> to move all dumped tables under\n"
    "qualifier (database) <B><!-- CODE -->Fou<!-- /CODE --></B> in the eventual destination database,\n"
    "and to leave owner unspecified, and to prefix each tablename with prefix\n"
    "<B><!-- CODE -->Bar<!-- /CODE --></B>, and duplicate the original name part itself,\n"
    "so that it will appear twice in the new name, separated by underscore,\n"
    "and followed by the digit&nbsp;2.\n"
    "<BR>E.g. <B><!-- CODE -->something.anything.bar<!-- /CODE --></B> would be converted to\n"
    "<B><!-- CODE -->Fou..Barbar_bar2<!-- /CODE --></B>\n"
    "<P><LI>\n"
    "You can give your own select statement to <B>Select Override</B> field.\n"
    "The default is  <CODE>" SELECT_DEFAULT "</CODE>  that is, dump all\n"
    "rows with all columns. Use <B><!-- CODE -->%s<!-- /CODE --></B> as a marker\n"
    "for the name of each table for which the DBDUMP is applied to, unless you\n"
    "give an explicit table name, in which case you should type that same\n"
    "table name to <B>Table Name</B> field also.\n"
    "<P><LI>\n"
    "In <B>Initial Statement</B> field you can specify one SQL-statement\n"
    "that is executed right after the connection, before any other operations.\n"
/* More crap:
"For example, if you are using <CODE>Microsoft SQL Server</CODE> and\n"
"want to discard all tablequalifier (i.e. database) and tableowner\n"
"information from the output, then check <B>Plain&nbsp;tablenames</B> button\n"
"and enter to this field a statement like <CODE>use&nbsp;pubs</CODE>, where\n"
"<CODE>pubs</CODE> is the name of database where DBDUMP's attention is\n"
"switched to (instead of default <CODE>master</CODE> database).\n"
"<BR>Otherwise, you can give <B>Table&nbsp;Name(s)</B> pattern explicitly as\n"
"<CODE>pubs..</CODE> or <CODE>pubs..%</CODE> to output all tables from <CODE>pubs</CODE> database,\n"
"listed with their full tablequalifier and tableowner prefixes.\n"
"<BR>However, in the latter case you cannot check <B>Plain&nbsp;tablenames</B> button\n"
"(unless you also give <CODE>use&nbsp;pubs</CODE> as init statement), because\n"
"then the <CODE>select</CODE>'s would be done from <CODE>master</CODE> database,\n"
"(which is the default when tablename is given without any prefixes),\n"
"instead of <CODE>pubs</CODE>.\n"
"<BR>With MS SQL Server you could also give in this field a statement\n"
"like <CODE>set&nbsp;rowcount&nbsp;7</CODE> (or even two statements at the same time:\n"
"<CODE>set&nbsp;rowcount&nbsp;7;&nbsp;use&nbsp;pubs</CODE>)\n"
"to effect that no more than 7 rows are listed from no more than 7 tables.\n"
 */
    "<P><LI>\n"
    "In <B>Unquoted Columns</B> field you can enter one or more comma-separated\n"
    "<CODE>tablename.columnname</CODE> pairs whose contents in output will not be enclosed\n"
    "with single quotes <CODE>(' ')</CODE> even if the corresponding nominal column\n"
    "types were VARCHARs. For example, you have to specify here all columns that\n"
    "contain vector data (lvectors, dvectors or fvectors) if you later want\n"
    "correctly import the produced output back to Kubl via Kubl Isql, i.e.\n"
    "so that vectors are kept as vectors, not corrupted to corresponding\n" "strings of their ascii representations.\n"
/* "(which is not very globewise!)\n" Cut the Crap!
"<BR>You may also use this feature for things like converting zip-codes\n"
"from strings to integers, if you are sure that they are always strictly\n"
"numeric in the source data\n"
"(In that case you would have to manually edit the\n"
"respective column type to INTEGER).\n"
 */
/* Obsolete options, notes commented out!
"<BR>Note that if you have <B>Prefixed tablenames</B> on, then you may\n"
"also specify here the tablequalifier and tableowner prefixes,\n"
"e.g. <CODE>db.dba.tabname1.colname1,db.dba.tabname2.colnamex</CODE>,\n"
"although it is not necessary. On the other hand, you don't need to\n"
"specify anything else than just bare column names\n"
"in which case all columns so named, regardless of in which table,\n"
"are thus unquoted.\n"
 */
    "<P><LI>\n"
    "Use <B>escape all names</B> option to prefix all table, index and\n"
    "column names with a backslash (\\), thus avoiding name conflicts with\n"
    "reserved SQL words like DATE and PASSWORD.\n"
    "<P><LI>Check one of the options <B>escape strange chars</B>,\n"
    "<B>escape only single quotes by doubling them</B>, etc to effect how\n"
    "string literals are escaped. Use former for C-like escaping, with a backslash\n"
    "followed upto three octal digits, and the latter for standard SQL-escaping\n"
    "with every single quote replaced by two. Note that the latter doesn't\n"
    "permit any newlines or other special characters in string literals.\n"
    "<P><LI>\n"
    "Use <B>dump to file instead of screen</B> option to send the data\n"
    "with the unknown content type instead of text/plain, thus forcing\n"
    "your browser to ask for a filename where to save the output, instead\n"
    "of showing it on the screen. Use this option if you have megabytes\n" "to dump and don't want to thrash your browser.\n"
/* This is not true anymore, as we now always read index information
   regardless whether it is output or not:
"<P><LI>\n"
"If you have checked the <B>table definitions only</B>, but not\n"
"the <B>index definitions only</B> option you might miss the type\n"
"of the primary key in those rare cases where the primary key is\n"
"defined with an additional index type, for example if originally defined\n"
"as <CODE>primary key(i1) clustered</CODE>, then the keyword\n"
"<CODE>clustered</CODE> is simply omitted from the dump output.\n"
 */
    "<P><LI>\n"
    "Use the <B>-d option</B> to force DBDUMP to use <CODE>select *</CODE>\n"
    "and <CODE>SQLDescribeCol</CODE> to get the columns of the table, instead\n"
    "of using the default <CODE>SQLColumns</CODE>. This might result a \n"
    "different ordering of columns. Don't use this one with Kubl if the\n"
    "database contains subtable (UNDER) definitions.\n"
    "<P><LI>\n"
    "Unless you check the <B>Never use foreach</B> option, DBDUMP will\n"
    "output every row with a column of type <B>LONG VARCHAR</B> or\n"
    "<B>LONG VARBINARY</B> using the parameterized <B>FOREACH BLOB</B> construct,\n"
    "which Kubl Isql will later recognize and parse accordingly.\n"
/* This is changed now?
"Currently, only the first blob column of each row is output in that way,\n"
"all others are output as quote-enclosed string literals.\n"
 */
    "In <B>MaxLine/HexLen</B> fields you can override the default maximum values\n"
    "used when the lines of foreach blobs are printed. If you give them as zero then\n"
    "blob lines got from the driver are never cut.\n"
    "<P><LI>\n"
    "To use DBDUMP in the command shell take the URL query string\n"
    "generated by this form (at the right side of the question mark)\n"
    "and give it as a command line argument, enclosed in doublequotes,\n"
    "or replace all ampersands (&AMP;) with " /* Stupid usage: slashes (/) or */ "spaces.\n"
/*
"<P><LI>\n"
"Use type conversions like <B>BIT -&GT; INTEGER</B> and \n"
"<B>LONG VARBINARY -&GT; LONG VARCHAR</B> if you want to transfer\n"
"data from other DBMS's to Kubl.\n"
 */
    "<P><LI>\n"
    "Use the conversion <B>TIMESTAMP</B> =&GT; <B>DATE</B> if you want to keep\n" "the original dates intact in Kubl.\n" "<P><LI>\n"
/* Very cumbersome hacker-stuff:
"To define more type conversions than those two that can be defined\n"
"with the pop-up menus you can manually add similar arguments\n"
"&AMP;CONVSRC3=type&AMP;CONVDST3=type&AMP;etc. after the end of the\n"
"URL generated by this form.\n"
 */
    "Check <B>Kubl Default Conversions</B> when your Data Destination is Kubl.\n"
    "It will effect the following type conversions to all columns of\n"
    "all tables fetched, in addition to any conversions of your own:\n" "<UL>\n" "$" DEFAULT_CONVERSIONS_TOKEN "\n" "</UL>\n"
/* Doesn't apply anymore, except to blobs that are not the first blob
   column in the row, and when the C-like backslash escaping is not
   used (or receiving DBMS doesn't understand it, or the string literal's
   length grows too big.)

"<P><LI>\n"
"<B>A Known Pitfall:</B>\n"
"Character data, if it contains newlines, whether in VARCHARs or\n"
"LONG VARCHARs (blobs), is printed out without any escape sequences,\n"
"and when the produced dump file is later read in with ISQLO, it will\n"
"blatantly fail.\n"
 */
/* Add this crap to release notes/documentation when that is finally
    written:
"<P><LI>\n"
"<B>Note:</B>\n"
"DBDUMP version 0.973 can now detect OBJECT_ID indices returned by\n"
"the Kubl ODBC driver (WIODBC.DLL version 0.94b or later).\n"
"If you have old databases created with Kubl server previous to version\n"
"0.95b G12d2 where KEY_IS_UNIQUE and KEY_IS_OBJECT_ID\n"
"columns were swapped in SYS_KEYS table, you might get funny\n"
"results, with all the unique indices dumped as they were OBJECT_ID indices.\n"
"You can use your editor to swap the index definitions manually from the\n"
"produced dump file.\n"
 */
    "<P><LI>\n"
    "<B>Warning:</B>\n"
    "If you have any datasources among your System DSN's, which themselves\n"
    "haven't been protected by the username/password checks\n"
    "then you might want to limit the access to this CGI-script with the\n"
    "password, by explicitly configuring your Web server.\n";



/***********************************************************************/
/*                                                                     */
/*   Template for the Transfer Page follows, in two parts.             */
/*   Here we use METHOD=POST and ENCTYPE="multipart/form-data"         */
/*   because that allows the largest amount of data to be passed from  */
/*   this form. Currently this is 65500 bytes per one field            */
/*   (also the TEXTAREA S_EXEC field, which is filled here, and        */
/*    which might now easily overflow)                                 */
/*   but in future isqlodbc.c should modified so that when S_EXEC      */
/*   is encountered in RFC1521/RFC1867 stream, it is not collected     */
/*   to a normal Url-argument, but instead, command reading is started */
/*   from that point of stdin, like the user were interactively        */
/*   feeding those same commands, meaning that indefinitely long       */
/*   series of statements can be transferred.                          */
/*                                                                     */
/*   No, now we don't use even that, just an ordinary Urlencoded POST  */
/*   No, we try it! No, we don't! Now... maybe some day we can decide! */
/***********************************************************************/


char *transfer_html_page_string1 =
    "<HTML><HEAD><TITLE>Kubl DBDUMP (version " DBDUMP_VERSION ") -&gt; ISQLO</TITLE>\n"
    "</HEAD>\n" "<BODY>\n" "<FORM ACTION=\"" TRANSFER_PROGRAM_CGI_LOCATION "\" METHOD=POST ENCTYPE=\"multipart/form-data\">\n"
/* "<FORM ACTION=\"" TRANSFER_PROGRAM_CGI_LOCATION "\" METHOD=POST>\n" */
    "<TABLE>\n"
    "<TR>\n"
    "<TD VALIGN=TOP NOWRAP><B>Data Destination</B></TD>\n"
    "<TD COLSPAN=2>$" DATASOURCE_TOKEN "</TD>\n"
    "</TR>\n"
    "<TR>\n"
    "<TD VALIGN=TOP><B>Username&nbsp;&amp;&nbsp;Password</B></TD>\n"
    "<TD><INPUT TYPE=TEXT NAME=S_CONUSER SIZE=10><INPUT TYPE=CHECKBOX NAME=S_EMPTY_USERNAME VALUE=\"ON\">(empty)</TD>\n"
    "<TD><INPUT TYPE=PASSWORD NAME=S_CONPASS SIZE=10><INPUT TYPE=CHECKBOX NAME=S_EMPTY_PASSWORD VALUE=\"ON\">(empty)</TD>\n"
    "</TR>\n"
    "<TR><TD VALIGN=TOP><B>Statements</B></TD>\n"
    "<TD COLSPAN=2>One or more, separated with semicolons (;) <INPUT TYPE=SUBMIT VALUE=\"DO IT!\"></TD></TR>\n"
    "<TR><TD VALIGN=TOP COLSPAN=3><TEXTAREA NAME=\"S_EXEC\" ROWS=17 COLS=60>\n";

/* The output from previous dbdump (presumably the schema, plus
   maybe also contents), is output here, between these two templates.
   Of course it should be also HTMLEscaped, but as long as
   we transfer just schemas, we don't care.
   Only in actual contents might occur few angle brackets <, >, etc.
 */

char *transfer_html_page_string2 =
    "</TEXTAREA></TD></TR>\n"
    "<TR>\n"
    "<TD VALIGN=TOP><B>Options</B></TD>\n"
    "<TD COLSPAN=2>\n"
    "<TABLE>\n"
    "<TR>\n"
    "<TD><INPUT NAME=\"S_MAXROWS\" TYPE=TEXT SIZE=8 VALUE=\"1000\">\n"
    "<!-- B -->Max Rows<!-- /B --></TD>\n"
    "<TD><INPUT NAME=\"S_TIMEOUT\" TYPE=TEXT SIZE=8 VALUE=\"1000\">\n"
    "<!-- B -->Timeout in Seconds<!-- /B --></TD>\n"
    "</TR>\n"
    "<TR>\n"
    "<TD><INPUT TYPE=CHECKBOX NAME=\"S_READMODE\" VALUE=\"SNAPSHOT\">\n"
    "<!-- B -->Snapshot Readmode<!-- /B --></TD>\n"
    "<TD>\n"
    "<INPUT TYPE=CHECKBOX NAME=\"S_AUTOCOMMIT\" VALUE=\"ON\"> <!-- B -->Autocommitted Execution<!-- /B -->\n"
    "</TD>\n"
    "</TR>\n"
    "<TR>\n"
    "<TD>\n"
    "<INPUT TYPE=CHECKBOX NAME=\"S_BLOBS\" VALUE=\"ON\"> <!-- B -->Show Blobs<!-- /B -->\n"
    "</TD>\n"
    "<TD>\n"
    "<INPUT TYPE=CHECKBOX NAME=\"S_BANNER\" VALUE=\"OFF\"> <!-- B -->No Banner<!-- /B -->\n"
    "</TD>\n"
    "</TR>\n"
    "<TR>\n"
    "<TD>\n"
    "<INPUT TYPE=RADIO NAME=\"S_VERBOSE\" VALUE=\"OFF\"> <!-- B -->Brief<!-- /B -->\n"
    "</TD>\n"
    "<TD>\n"
    "<INPUT TYPE=RADIO CHECKED NAME=\"S_VERBOSE\" VALUE=\"ON\"> <!-- B -->Verbose Output<!-- /B -->\n"
    "</TD>\n"
    "</TR>\n"
    "<TR>\n"
    "<TD>\n"
    "<INPUT CHECKED TYPE=RADIO NAME=\"S_CONTENT_TYPE\" VALUE=\"text/plain\">\n"
    "<!-- B -->Output in raw text format to screen<!-- /B -->\n"
    "</TD>\n"
    "<TD>\n"
    "<INPUT TYPE=RADIO NAME=\"S_CONTENT_TYPE\" VALUE=\"x-isql/plain\">\n"
    "<!-- B -->Output in raw text format to file<!-- /B -->\n"
    "</TD>\n"
    "</TR>\n"
    "<TR>\n"
    "<TD COLSPAN=2>\n"
    "<INPUT TYPE=RADIO NAME=\"S_CONTENT_TYPE\" VALUE=\"text/html\">\n"
    "<!-- B -->Output in HTML format to screen<!-- /B -->\n"
    "</TD>\n"
    "</TR>\n"
    "<TR>\n"
    "<TD><INPUT CHECKED TYPE=CHECKBOX NAME=\"S_OO_SB\" VALUE=\"&LT;TABLE&#32;BORDER&GT;\">\n"
    "<!-- B -->Use Table Borders<!-- /B --></TD>\n"
    "<TD><INPUT TYPE=CHECKBOX NAME=\"S_OO_ESC\" VALUE=\"OFF\">\n"
    "<!-- B -->No HTML-Escaping<!-- /B --></TD>\n"
    "</TR>\n"
    "<TR>\n"
    "<TD><INPUT TYPE=SUBMIT VALUE=\"Do it\"></TD>\n"
    "<TD><INPUT TYPE=RESET VALUE=\"Reset\"></TD>\n"
    "</TR>\n" "</TABLE>\n" "</TD>\n" "</TR>\n" "</TABLE>\n" "</FORM>\n" "</BODY></HTML>\n";