summaryrefslogtreecommitdiff
path: root/storage/connect/ha_connect.cc
blob: 08a61a75048792fa99cbb75ff1fdc3edbc946947 (plain)
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
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
/* Copyright (C) MariaDB Corporation Ab

  This program 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; version 2 of the License.

  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 Street, Fifth Floor, Boston, MA 02111-1301 USA */

/**
  @file ha_connect.cc

  @brief
  The ha_connect engine is a stubbed storage engine that enables to create tables
  based on external data. Principally they are based on plain files of many
  different types, but also on collections of such files, collection of tables,
  local or remote MySQL/MariaDB tables retrieved via MySQL API,
  ODBC/JDBC tables retrieving data from other DBMS having an ODBC/JDBC server,
	and even virtual tables.

  @details
  ha_connect will let you create/open/delete tables, the created table can be
  done specifying an already existing file, the drop table command will just
  suppress the table definition but not the eventual data file.
  Indexes are not supported for all table types but data can be inserted,
  updated or deleted.

  You can enable the CONNECT storage engine in your build by doing the
  following during your build process:<br> ./configure
  --with-connect-storage-engine

  You can install the CONNECT handler as all other storage handlers.

  Once this is done, MySQL will let you create tables with:<br>
  CREATE TABLE <table name> (...) ENGINE=CONNECT;

  The example storage engine does not use table locks. It
  implements an example "SHARE" that is inserted into a hash by table
  name. This is not used yet.

  Please read the object definition in ha_connect.h before reading the rest
  of this file.

  @note
  This MariaDB CONNECT handler is currently an adaptation of the XDB handler
  that was written for MySQL version 4.1.2-alpha. Its overall design should
  be enhanced in the future to meet MariaDB requirements.

  @note
  It was written also from the Brian's ha_example handler and contains parts
  of it that are there, such as table and system  variables.

  @note
  When you create an CONNECT table, the MySQL Server creates a table .frm
  (format) file in the database directory, using the table name as the file
  name as is customary with MySQL.
  For file based tables, if a file name is not specified, this is an inward
  table. An empty file is made in the current data directory that you can
  populate later like for other engine tables. This file modified on ALTER
  and is deleted when dropping the table.
  If a file name is specified, this in an outward table. The specified file
  will be used as representing the table data and will not be modified or
  deleted on command such as ALTER or DROP.
  To get an idea of what occurs, here is an example select that would do
  a scan of an entire table:

  @code
  ha-connect::open
  ha_connect::store_lock
  ha_connect::external_lock
  ha_connect::info
  ha_connect::rnd_init
  ha_connect::extra
  ENUM HA_EXTRA_CACHE        Cache record in HA_rrnd()
  ha_connect::rnd_next
  ha_connect::rnd_next
  ha_connect::rnd_next
  ha_connect::rnd_next
  ha_connect::rnd_next
  ha_connect::rnd_next
  ha_connect::rnd_next
  ha_connect::rnd_next
  ha_connect::rnd_next
  ha_connect::extra
  ENUM HA_EXTRA_NO_CACHE     End caching of records (def)
  ha_connect::external_lock
  ha_connect::extra
  ENUM HA_EXTRA_RESET        Reset database to after open
  @endcode

  Here you see that the connect storage engine has 9 rows called before
  rnd_next signals that it has reached the end of its data. Calls to
  ha_connect::extra() are hints as to what will be occuring to the request.

  Author  Olivier Bertrand
*/

#ifdef USE_PRAGMA_IMPLEMENTATION
#pragma implementation        // gcc: Class implementation
#endif

#define MYSQL_SERVER 1
#define DONT_DEFINE_VOID
#include "sql_class.h"
#include "create_options.h"
#include "mysql_com.h"
#include "field.h"
#include "sql_parse.h"
#include "sql_base.h"
#include <sys/stat.h>
#include "sql_partition.h"
#undef  OFFSET

#define NOPARSE
#define NJDBC
#if defined(UNIX)
#include "osutil.h"
#endif   // UNIX
#include "global.h"
#include "plgdbsem.h"
#include "xtable.h"
#include "tabext.h"
#if defined(ODBC_SUPPORT)
#include "odbccat.h"
#endif   // ODBC_SUPPORT
#if defined(JAVA_SUPPORT)
#include "tabjdbc.h"
#include "jdbconn.h"
#endif   // JAVA_SUPPORT
#if defined(CMGO_SUPPORT)
#include "cmgoconn.h"
#endif   // CMGO_SUPPORT
#include "tabmysql.h"
#include "filamdbf.h"
#include "tabxcl.h"
#include "tabfmt.h"
//#include "reldef.h"
#include "tabcol.h"
#include "xindex.h"
#if defined(__WIN__)
#include <io.h>
#include "tabwmi.h"
#endif   // __WIN__
#include "connect.h"
#include "user_connect.h"
#include "ha_connect.h"
#include "myutil.h"
#include "preparse.h"
#include "inihandl.h"
#if defined(LIBXML2_SUPPORT)
#include "libdoc.h"
#endif   // LIBXML2_SUPPORT
#include "taboccur.h"
#include "tabpivot.h"
#include "tabfix.h"

#define my_strupr(p)    my_caseup_str(default_charset_info, (p));
#define my_strlwr(p)    my_casedn_str(default_charset_info, (p));
#define my_stricmp(a,b) my_strcasecmp(default_charset_info, (a), (b))


/***********************************************************************/
/*  Initialize the ha_connect static members.                          */
/***********************************************************************/
#define SZCONV     8192
#define SZWORK 67108864             // Default work area size 64M
#define SZWMIN  4194304             // Minimum work area size  4M
#define JSONMAX      10             // JSON Default max grp size

extern "C" {
       char version[]= "Version 1.06.0005 October 14, 2017";
#if defined(__WIN__)
       char compver[]= "Version 1.06.0005 " __DATE__ " "  __TIME__;
       char slash= '\\';
#else   // !__WIN__
       char slash= '/';
#endif  // !__WIN__
} // extern "C"

#if MYSQL_VERSION_ID > 100200
#define stored_in_db stored_in_db()
#endif   // MYSQL_VERSION_ID

#if defined(XMAP)
       my_bool xmap= false;
#endif   // XMAP

ulong  ha_connect::num= 0;

#if defined(XMSG)
extern "C" {
       char *msg_path;
} // extern "C"
#endif   // XMSG

#if defined(JAVA_SUPPORT)
	     char *JvmPath;
			 char *ClassPath;
#endif   // JAVA_SUPPORT

pthread_mutex_t parmut;
pthread_mutex_t usrmut;
pthread_mutex_t tblmut;

/***********************************************************************/
/*  Utility functions.                                                 */
/***********************************************************************/
PQRYRES OEMColumns(PGLOBAL g, PTOS topt, char *tab, char *db, bool info);
PQRYRES VirColumns(PGLOBAL g, bool info);
PQRYRES JSONColumns(PGLOBAL g, PCSZ db, PCSZ dsn, PTOS topt, bool info);
PQRYRES XMLColumns(PGLOBAL g, char *db, char *tab, PTOS topt, bool info);
#if defined(JAVA_SUPPORT)
PQRYRES MGOColumns(PGLOBAL g, PCSZ db, PCSZ url, PTOS topt, bool info);
#endif   // JAVA_SUPPORT
int     TranslateJDBCType(int stp, char *tn, int prec, int& len, char& v);
void    PushWarning(PGLOBAL g, THD *thd, int level);
bool    CheckSelf(PGLOBAL g, TABLE_SHARE *s, PCSZ host, PCSZ db,
	                                           PCSZ tab, PCSZ src, int port);
bool    ZipLoadFile(PGLOBAL, PCSZ, PCSZ, PCSZ, bool, bool);
bool    ExactInfo(void);
#if defined(CMGO_SUPPORT)
//void    mongo_init(bool);
#endif   // CMGO_SUPPORT
USETEMP UseTemp(void);
int     GetConvSize(void);
TYPCONV GetTypeConv(void);
char   *GetJsonNull(void);
uint    GetJsonGrpSize(void);
char   *GetJavaWrapper(void);
uint    GetWorkSize(void);
void    SetWorkSize(uint);
extern "C" const char *msglang(void);

static char *strz(PGLOBAL g, LEX_STRING &ls);

static void PopUser(PCONNECT xp);
static PCONNECT GetUser(THD *thd, PCONNECT xp);
static PGLOBAL  GetPlug(THD *thd, PCONNECT& lxp);

static handler *connect_create_handler(handlerton *hton,
                                       TABLE_SHARE *table,
                                       MEM_ROOT *mem_root);

static int connect_assisted_discovery(handlerton *hton, THD* thd,
                                      TABLE_SHARE *table_s,
                                      HA_CREATE_INFO *info);

/****************************************************************************/
/*  Return str as a zero terminated string.                                 */
/****************************************************************************/
static char *strz(PGLOBAL g, LEX_STRING &ls)
{
  char *str= (char*)PlugSubAlloc(g, NULL, ls.length + 1);

  memcpy(str, ls.str, ls.length);
  str[ls.length]= 0;
  return str;
} // end of strz

/***********************************************************************/
/*  CONNECT session variables definitions.                             */
/***********************************************************************/
// Tracing: 0 no, 1 yes, >1 more tracing
static MYSQL_THDVAR_INT(xtrace,
       PLUGIN_VAR_RQCMDARG, "Console trace value.",
       NULL, NULL, 0, 0, INT_MAX, 1);

// Getting exact info values
static MYSQL_THDVAR_BOOL(exact_info, PLUGIN_VAR_RQCMDARG,
       "Getting exact info values",
       NULL, NULL, 0);

/**
  Temporary file usage:
    no:    Not using temporary file
    auto:  Using temporary file when needed
    yes:   Allways using temporary file
    force: Force using temporary file (no MAP)
    test:  Reserved
*/
const char *usetemp_names[]=
{
  "NO", "AUTO", "YES", "FORCE", "TEST", NullS
};

TYPELIB usetemp_typelib=
{
  array_elements(usetemp_names) - 1, "usetemp_typelib",
  usetemp_names, NULL
};

static MYSQL_THDVAR_ENUM(
  use_tempfile,                    // name
  PLUGIN_VAR_RQCMDARG,             // opt
  "Temporary file use.",           // comment
  NULL,                            // check
  NULL,                            // update function
  1,                               // def (AUTO)
  &usetemp_typelib);               // typelib

// Size used for g->Sarea_Size
static MYSQL_THDVAR_UINT(work_size,
       PLUGIN_VAR_RQCMDARG, 
       "Size of the CONNECT work area.",
       NULL, NULL, SZWORK, SZWMIN, UINT_MAX, 1);

// Size used when converting TEXT columns to VARCHAR
static MYSQL_THDVAR_INT(conv_size,
       PLUGIN_VAR_RQCMDARG,             // opt
       "Size used when converting TEXT columns.",
       NULL, NULL, SZCONV, 0, 65500, 1);

/**
  Type conversion:
    no:   Unsupported types -> TYPE_ERROR
    yes:  TEXT -> VARCHAR
    skip: skip unsupported type columns in Discovery
*/
const char *xconv_names[]=
{
  "NO", "YES", "SKIP", NullS
};

TYPELIB xconv_typelib=
{
  array_elements(xconv_names) - 1, "xconv_typelib",
  xconv_names, NULL
};

static MYSQL_THDVAR_ENUM(
  type_conv,                       // name
  PLUGIN_VAR_RQCMDARG,             // opt
  "Unsupported types conversion.", // comment
  NULL,                            // check
  NULL,                            // update function
  0,                               // def (no)
  &xconv_typelib);                 // typelib

// Null representation for JSON values
static MYSQL_THDVAR_STR(json_null,
	PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_MEMALLOC,
	"Representation of Json null values",
	//     check_json_null, update_json_null,
	NULL, NULL, "<null>");

// Estimate max number of rows for JSON aggregate functions
static MYSQL_THDVAR_UINT(json_grp_size,
       PLUGIN_VAR_RQCMDARG,             // opt
       "max number of rows for JSON aggregate functions.",
       NULL, NULL, JSONMAX, 1, INT_MAX, 1);

#if defined(JAVA_SUPPORT)
// Default java wrapper to use with JDBC tables
static MYSQL_THDVAR_STR(java_wrapper,
	PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_MEMALLOC,
	"Java wrapper class name",
	//     check_java_wrapper, update_java_wrapper,
	NULL, NULL, "wrappers/JdbcInterface");
#endif   // JAVA_SUPPORT

#if 0 // This is apparently not acceptable for a plugin
// Enabling MONGO table type
static MYSQL_THDVAR_BOOL(enable_mongo, PLUGIN_VAR_RQCMDARG,
	"Enabling the MongoDB access",
	NULL, NULL, MONGO_ENABLED);
#endif   // 0

#if defined(XMSG) || defined(NEWMSG)
const char *language_names[]=
{
  "default", "english", "french", NullS
};

TYPELIB language_typelib=
{
  array_elements(language_names) - 1, "language_typelib",
  language_names, NULL
};

static MYSQL_THDVAR_ENUM(
  msg_lang,                        // name
  PLUGIN_VAR_RQCMDARG,             // opt
  "Message language",              // comment
  NULL,                            // check
  NULL,                            // update
  1,                               // def (ENGLISH)      
  &language_typelib);              // typelib
#endif   // XMSG || NEWMSG

/***********************************************************************/
/*  The CONNECT handlerton object.                                     */
/***********************************************************************/
handlerton *connect_hton= NULL;

/***********************************************************************/
/*  Function to export session variable values to other source files.  */
/***********************************************************************/
extern "C" int GetTraceValue(void) 
  {return connect_hton ? THDVAR(current_thd, xtrace) : 0;}
bool ExactInfo(void) {return THDVAR(current_thd, exact_info);}
USETEMP UseTemp(void) {return (USETEMP)THDVAR(current_thd, use_tempfile);}
int GetConvSize(void) {return THDVAR(current_thd, conv_size);}
TYPCONV GetTypeConv(void) {return (TYPCONV)THDVAR(current_thd, type_conv);}
char *GetJsonNull(void)
	{return connect_hton ? THDVAR(current_thd, json_null) : NULL;}
uint GetJsonGrpSize(void)
  {return connect_hton ? THDVAR(current_thd, json_grp_size) : 10;}
uint GetWorkSize(void) {return THDVAR(current_thd, work_size);}
void SetWorkSize(uint) 
{
  // Changing the session variable value seems to be impossible here
  // and should be done in a check function 
  push_warning(current_thd, Sql_condition::WARN_LEVEL_WARN, 0, 
    "Work size too big, try setting a smaller value");
} // end of SetWorkSize
#if defined(XMSG) || defined(NEWMSG)
extern "C" const char *msglang(void)
{
  return language_names[THDVAR(current_thd, msg_lang)];
} // end of msglang
#else   // !XMSG && !NEWMSG

#if defined(JAVA_SUPPORT)
char *GetJavaWrapper(void)
{return connect_hton ? THDVAR(current_thd, java_wrapper) : (char*)"wrappers/JdbcInterface";}
#endif   // JAVA_SUPPORT

#if defined(JAVA_SUPPORT)
//bool MongoEnabled(void) { return THDVAR(current_thd, enable_mongo); }
#endif   // JAVA_SUPPORT

extern "C" const char *msglang(void)
{
#if defined(FRENCH)
  return "french";
#else  // DEFAULT
  return "english";
#endif // DEFAULT
} // end of msglang
#endif  // !XMSG && !NEWMSG

#if 0
/***********************************************************************/
/*  Global variables update functions.                                 */
/***********************************************************************/
static void update_connect_zconv(MYSQL_THD thd,
                                  struct st_mysql_sys_var *var,
                                  void *var_ptr, const void *save)
{
  zconv= *(int *)var_ptr= *(int *)save;
} // end of update_connect_zconv

static void update_connect_xconv(MYSQL_THD thd,
                                 struct st_mysql_sys_var *var,
                                 void *var_ptr, const void *save)
{
  xconv= (int)(*(ulong *)var_ptr= *(ulong *)save);
} // end of update_connect_xconv

#if defined(XMAP)
static void update_connect_xmap(MYSQL_THD thd,
                                struct st_mysql_sys_var *var,
                                void *var_ptr, const void *save)
{
  xmap= (my_bool)(*(my_bool *)var_ptr= *(my_bool *)save);
} // end of update_connect_xmap
#endif   // XMAP
#endif // 0

#if 0 // (was XMSG) Unuseful because not called for default value
static void update_msg_path(MYSQL_THD thd,
                            struct st_mysql_sys_var *var,
                            void *var_ptr, const void *save)
{
  char *value= *(char**)save;
  char *old= *(char**)var_ptr;

  if (value)
    *(char**)var_ptr= my_strdup(value, MYF(0));
  else
    *(char**)var_ptr= 0;

  my_free(old);
} // end of update_msg_path

static int check_msg_path (MYSQL_THD thd, struct st_mysql_sys_var *var,
	                         void *save, struct st_mysql_value *value)
{
	const char *path;
	char	buff[512];
	int		len= sizeof(buff);

	path= value->val_str(value, buff, &len);

	if (path && *path != '*') {
		/* Save a pointer to the name in the
		'file_format_name_map' constant array. */
		*(char**)save= my_strdup(path, MYF(0));
		return(0);
	} else {
		push_warning_printf(thd,
		  Sql_condition::WARN_LEVEL_WARN,
		  ER_WRONG_ARGUMENTS,
		  "CONNECT: invalid message path");
	} // endif path

	*(char**)save= NULL;
	return(1);
} // end of check_msg_path
#endif   // 0

/**
  CREATE TABLE option list (table options)

  These can be specified in the CREATE TABLE:
  CREATE TABLE ( ... ) {...here...}
*/
ha_create_table_option connect_table_option_list[]=
{
  HA_TOPTION_STRING("TABLE_TYPE", type),
  HA_TOPTION_STRING("FILE_NAME", filename),
  HA_TOPTION_STRING("XFILE_NAME", optname),
//HA_TOPTION_STRING("CONNECT_STRING", connect),
  HA_TOPTION_STRING("TABNAME", tabname),
  HA_TOPTION_STRING("TABLE_LIST", tablist),
  HA_TOPTION_STRING("DBNAME", dbname),
  HA_TOPTION_STRING("SEP_CHAR", separator),
  HA_TOPTION_STRING("QCHAR", qchar),
  HA_TOPTION_STRING("MODULE", module),
  HA_TOPTION_STRING("SUBTYPE", subtype),
  HA_TOPTION_STRING("CATFUNC", catfunc),
  HA_TOPTION_STRING("SRCDEF", srcdef),
  HA_TOPTION_STRING("COLIST", colist),
	HA_TOPTION_STRING("FILTER", filter),
	HA_TOPTION_STRING("OPTION_LIST", oplist),
  HA_TOPTION_STRING("DATA_CHARSET", data_charset),
  HA_TOPTION_NUMBER("LRECL", lrecl, 0, 0, INT_MAX32, 1),
  HA_TOPTION_NUMBER("BLOCK_SIZE", elements, 0, 0, INT_MAX32, 1),
//HA_TOPTION_NUMBER("ESTIMATE", estimate, 0, 0, INT_MAX32, 1),
  HA_TOPTION_NUMBER("MULTIPLE", multiple, 0, 0, 3, 1),
  HA_TOPTION_NUMBER("HEADER", header, 0, 0, 3, 1),
  HA_TOPTION_NUMBER("QUOTED", quoted, (ulonglong) -1, 0, 3, 1),
  HA_TOPTION_NUMBER("ENDING", ending, (ulonglong) -1, 0, INT_MAX32, 1),
  HA_TOPTION_NUMBER("COMPRESS", compressed, 0, 0, 2, 1),
  HA_TOPTION_BOOL("MAPPED", mapped, 0),
  HA_TOPTION_BOOL("HUGE", huge, 0),
  HA_TOPTION_BOOL("SPLIT", split, 0),
  HA_TOPTION_BOOL("READONLY", readonly, 0),
  HA_TOPTION_BOOL("SEPINDEX", sepindex, 0),
	HA_TOPTION_BOOL("ZIPPED", zipped, 0),
	HA_TOPTION_END
};


/**
  CREATE TABLE option list (field options)

  These can be specified in the CREATE TABLE per field:
  CREATE TABLE ( field ... {...here...}, ... )
*/
ha_create_table_option connect_field_option_list[]=
{
  HA_FOPTION_NUMBER("FLAG", offset, (ulonglong) -1, 0, INT_MAX32, 1),
  HA_FOPTION_NUMBER("MAX_DIST", freq, 0, 0, INT_MAX32, 1), // BLK_INDX
  HA_FOPTION_NUMBER("FIELD_LENGTH", fldlen, 0, 0, INT_MAX32, 1),
  HA_FOPTION_STRING("DATE_FORMAT", dateformat),
  HA_FOPTION_STRING("FIELD_FORMAT", fieldformat),
  HA_FOPTION_STRING("SPECIAL", special),
  HA_FOPTION_ENUM("DISTRIB", opt, "scattered,clustered,sorted", 0),
  HA_FOPTION_END
};

/*
  CREATE TABLE option list (index options)

  These can be specified in the CREATE TABLE per index:
  CREATE TABLE ( field ..., .., INDEX .... *here*, ... )
*/
ha_create_table_option connect_index_option_list[]=
{
  HA_IOPTION_BOOL("DYNAM", dynamic, 0),
  HA_IOPTION_BOOL("MAPPED", mapped, 0),
  HA_IOPTION_END
};

/***********************************************************************/
/*  Push G->Message as a MySQL warning.                                */
/***********************************************************************/
bool PushWarning(PGLOBAL g, PTDB tdbp, int level)
{
  PHC    phc;
  THD   *thd;
  MYCAT *cat= (MYCAT*)tdbp->GetDef()->GetCat();

  if (!cat || !(phc= cat->GetHandler()) || !phc->GetTable() ||
      !(thd= (phc->GetTable())->in_use))
    return true;

  PushWarning(g, thd, level);
  return false;
} // end of PushWarning

void PushWarning(PGLOBAL g, THD *thd, int level)
  {
  if (thd) {
    Sql_condition::enum_warning_level wlvl;

    wlvl= (Sql_condition::enum_warning_level)level;
    push_warning(thd, wlvl, 0, g->Message);
  } else
    htrc("%s\n", g->Message);

  } // end of PushWarning

#ifdef HAVE_PSI_INTERFACE
static PSI_mutex_key con_key_mutex_CONNECT_SHARE_mutex;

static PSI_mutex_info all_connect_mutexes[]=
{
  { &con_key_mutex_CONNECT_SHARE_mutex, "CONNECT_SHARE::mutex", 0}
};

static void init_connect_psi_keys()
{
  const char* category= "connect";
  int count;

  if (PSI_server == NULL)
    return;

  count= array_elements(all_connect_mutexes);
  PSI_server->register_mutex(category, all_connect_mutexes, count);
}
#else
static void init_connect_psi_keys() {}
#endif


DllExport LPCSTR PlugSetPath(LPSTR to, LPCSTR name, LPCSTR dir)
{
  const char *res= PlugSetPath(to, mysql_data_home, name, dir);
  return res;
}


/**
  @brief
  If frm_error() is called then we will use this to determine
  the file extensions that exist for the storage engine. This is also
  used by the default rename_table and delete_table method in
  handler.cc.

  For engines that have two file name extentions (separate meta/index file
  and data file), the order of elements is relevant. First element of engine
  file name extentions array should be meta/index file extention. Second
  element - data file extention. This order is assumed by
  prepare_for_repair() when REPAIR TABLE ... USE_FRM is issued.

  @see
  rename_table method in handler.cc and
  delete_table method in handler.cc
*/
static const char *ha_connect_exts[]= {
  ".dos", ".fix", ".csv", ".bin", ".fmt", ".dbf", ".xml", ".json", ".ini",
  ".vec", ".dnx", ".fnx", ".bnx", ".vnx", ".dbx", ".dop", ".fop", ".bop",
  ".vop", NULL};

/**
  @brief
  Plugin initialization
*/
static int connect_init_func(void *p)
{
  DBUG_ENTER("connect_init_func");

// added from Sergei mail  
#if 0 // (defined(LINUX))
  Dl_info dl_info;
  if (dladdr(&connect_hton, &dl_info))
  {
    if (dlopen(dl_info.dli_fname, RTLD_NOLOAD | RTLD_NOW | RTLD_GLOBAL) == 0)
    {
      sql_print_information("CONNECT: dlopen() failed, OEM table type is not supported");
      sql_print_information("CONNECT: %s", dlerror());
    }
  }
  else
  {
    sql_print_information("CONNECT: dladdr() failed, OEM table type is not supported");
    sql_print_information("CONNECT: %s", dlerror());
  }
#endif   // 0 (LINUX)

#if defined(__WIN__)
  sql_print_information("CONNECT: %s", compver);
#else   // !__WIN__
  sql_print_information("CONNECT: %s", version);
#endif  // !__WIN__
	pthread_mutex_init(&parmut, NULL);
	pthread_mutex_init(&usrmut, NULL);
	pthread_mutex_init(&tblmut, NULL);

#if defined(LIBXML2_SUPPORT)
  XmlInitParserLib();
#endif   // LIBXML2_SUPPORT

#if 0  //defined(CMGO_SUPPORT)
	mongo_init(true);
#endif   // CMGO_SUPPORT

  init_connect_psi_keys();

  connect_hton= (handlerton *)p;
  connect_hton->state= SHOW_OPTION_YES;
  connect_hton->create= connect_create_handler;
  connect_hton->flags= HTON_TEMPORARY_NOT_SUPPORTED;
  connect_hton->table_options= connect_table_option_list;
  connect_hton->field_options= connect_field_option_list;
  connect_hton->index_options= connect_index_option_list;
  connect_hton->tablefile_extensions= ha_connect_exts;
  connect_hton->discover_table_structure= connect_assisted_discovery;

  if (trace)
    sql_print_information("connect_init: hton=%p", p);

  DTVAL::SetTimeShift();      // Initialize time zone shift once for all
  BINCOL::SetEndian();        // Initialize host endian setting
#if defined(JAVA_SUPPORT)
	JAVAConn::SetJVM();
#endif   // JAVA_SUPPORT
  DBUG_RETURN(0);
} // end of connect_init_func


/**
  @brief
  Plugin clean up
*/
static int connect_done_func(void *)
{
  int error= 0;
  PCONNECT pc, pn;
  DBUG_ENTER("connect_done_func");

#ifdef LIBXML2_SUPPORT
  XmlCleanupParserLib();
#endif // LIBXML2_SUPPORT

#if defined(CMGO_SUPPORT)
	CMgoConn::mongo_init(false);
#endif   // CMGO_SUPPORT

#ifdef JAVA_SUPPORT
	JAVAConn::ResetJVM();
#endif // JAVA_SUPPORT

#if	!defined(__WIN__)
	PROFILE_End();
#endif  // !__WIN__

	pthread_mutex_lock(&usrmut);
	for (pc= user_connect::to_users; pc; pc= pn) {
    if (pc->g)
      PlugCleanup(pc->g, true);

    pn= pc->next;
    delete pc;
    } // endfor pc

	pthread_mutex_unlock(&usrmut);

	pthread_mutex_destroy(&usrmut);
	pthread_mutex_destroy(&parmut);
	pthread_mutex_destroy(&tblmut);
	connect_hton= NULL;
  DBUG_RETURN(error);
} // end of connect_done_func


/**
  @brief
  Example of simple lock controls. The "share" it creates is a
  structure we will pass to each CONNECT handler. Do you have to have
  one of these? Well, you have pieces that are used for locking, and
  they are needed to function.
*/

CONNECT_SHARE *ha_connect::get_share()
{
  CONNECT_SHARE *tmp_share;

  lock_shared_ha_data();

  if (!(tmp_share= static_cast<CONNECT_SHARE*>(get_ha_share_ptr()))) {
    tmp_share= new CONNECT_SHARE;
    if (!tmp_share)
      goto err;
    mysql_mutex_init(con_key_mutex_CONNECT_SHARE_mutex,
                     &tmp_share->mutex, MY_MUTEX_INIT_FAST);
    set_ha_share_ptr(static_cast<Handler_share*>(tmp_share));
    } // endif tmp_share

 err:
  unlock_shared_ha_data();
  return tmp_share;
} // end of get_share


static handler* connect_create_handler(handlerton *hton,
                                   TABLE_SHARE *table,
                                   MEM_ROOT *mem_root)
{
  handler *h= new (mem_root) ha_connect(hton, table);

  if (trace)
    htrc("New CONNECT %p, table: %.*s\n", h,
          table ? table->table_name.length : 6,
          table ? table->table_name.str : "<null>");

  return h;
} // end of connect_create_handler

/****************************************************************************/
/*  ha_connect constructor.                                                 */
/****************************************************************************/
ha_connect::ha_connect(handlerton *hton, TABLE_SHARE *table_arg)
       :handler(hton, table_arg)
{
  hnum= ++num;
  xp= (table) ? GetUser(ha_thd(), NULL) : NULL;
  if (xp)
    xp->SetHandler(this);
#if defined(__WIN__)
  datapath= ".\\";
#else   // !__WIN__
  datapath= "./";
#endif  // !__WIN__
  tdbp= NULL;
  sdvalin1= sdvalin2= sdvalin3= sdvalin4= NULL;
  sdvalout= NULL;
  xmod= MODE_ANY;
  istable= false;
  memset(partname, 0, sizeof(partname));
  bzero((char*) &xinfo, sizeof(XINFO));
  valid_info= false;
  valid_query_id= 0;
  creat_query_id= (table && table->in_use) ? table->in_use->query_id : 0;
  stop= false;
  alter= false;
  mrr= false;
  nox= true;
  abort= false;
  indexing= -1;
  locked= 0;
  part_id= NULL;
  data_file_name= NULL;
  index_file_name= NULL;
  enable_activate_all_index= 0;
  int_table_flags= (HA_NO_TRANSACTIONS | HA_NO_PREFIX_CHAR_KEYS);
  ref_length= sizeof(int);
  share= NULL;
  tshp= NULL;
} // end of ha_connect constructor


/****************************************************************************/
/*  ha_connect destructor.                                                  */
/****************************************************************************/
ha_connect::~ha_connect(void)
{
  if (trace)
    htrc("Delete CONNECT %p, table: %.*s, xp=%p count=%d\n", this,
                         table ? table->s->table_name.length : 6,
                         table ? table->s->table_name.str : "<null>",
                         xp, xp ? xp->count : 0);

	PopUser(xp);
} // end of ha_connect destructor


/****************************************************************************/
/*  Check whether this user can be removed.                                 */
/****************************************************************************/
static void PopUser(PCONNECT xp)
{
	if (xp) {
		pthread_mutex_lock(&usrmut);
		xp->count--;

		if (!xp->count) {
			PCONNECT p;

			for (p= user_connect::to_users; p; p= p->next)
			  if (p == xp)
				  break;

		  if (p) {
			  if (p->next)
				  p->next->previous= p->previous;

			  if (p->previous)
				  p->previous->next= p->next;
			  else
				  user_connect::to_users= p->next;

		  } // endif p

			PlugCleanup(xp->g, true);
			delete xp;
		} // endif count

		pthread_mutex_unlock(&usrmut);
	} // endif xp

} // end of PopUser


/****************************************************************************/
/*  Get a pointer to the user of this handler.                              */
/****************************************************************************/
static PCONNECT GetUser(THD *thd, PCONNECT xp)
{
	if (!thd)
    return NULL;

	if (xp) {
		if (thd == xp->thdp)
			return xp;

		PopUser(xp);		// Avoid memory leak
	} // endif xp

	pthread_mutex_lock(&usrmut);

	for (xp= user_connect::to_users; xp; xp= xp->next)
    if (thd == xp->thdp)
      break;

	if (xp)
		xp->count++;

	pthread_mutex_unlock(&usrmut);

	if (!xp) {
		xp = new user_connect(thd);

		if (xp->user_init()) {
			delete xp;
			xp = NULL;
		} // endif user_init

	}	// endif xp

  //} else
  //  xp->count++;

  return xp;
} // end of GetUser

/****************************************************************************/
/*  Get the global pointer of the user of this handler.                     */
/****************************************************************************/
static PGLOBAL GetPlug(THD *thd, PCONNECT& lxp)
{
  lxp= GetUser(thd, lxp);
  return (lxp) ? lxp->g : NULL;
} // end of GetPlug

/****************************************************************************/
/*  Get the implied table type.                                             */
/****************************************************************************/
TABTYPE ha_connect::GetRealType(PTOS pos)
{
  TABTYPE type;
  
  if (pos || (pos= GetTableOptionStruct())) {
    type= GetTypeID(pos->type);

    if (type == TAB_UNDEF)
      type= pos->srcdef ? TAB_MYSQL : pos->tabname ? TAB_PRX : TAB_DOS;

  } else
    type= TAB_UNDEF;

  return type;
} // end of GetRealType

/** @brief
  The name of the index type that will be used for display.
  Don't implement this method unless you really have indexes.
 */
const char *ha_connect::index_type(uint inx) 
{ 
  switch (GetIndexType(GetRealType())) {
    case 1:
      if (table_share)
        return (GetIndexOption(&table_share->key_info[inx], "Dynamic"))
             ? "KINDEX" : "XINDEX";
      else
        return "XINDEX";

    case 2: return "REMOTE";
    case 3: return "VIRTUAL";
    } // endswitch

  return "Unknown";
} // end of index_type

/** @brief
  This is a bitmap of flags that indicates how the storage engine
  implements indexes. The current index flags are documented in
  handler.h. If you do not implement indexes, just return zero here.

    @details
  part is the key part to check. First key part is 0.
  If all_parts is set, MySQL wants to know the flags for the combined
  index, up to and including 'part'.
*/
//ong ha_connect::index_flags(uint inx, uint part, bool all_parts) const
ulong ha_connect::index_flags(uint, uint, bool) const
{
  ulong       flags= HA_READ_NEXT | HA_READ_RANGE |
                     HA_KEYREAD_ONLY | HA_KEY_SCAN_NOT_ROR;
  ha_connect *hp= (ha_connect*)this;
  PTOS        pos= hp->GetTableOptionStruct();

  if (pos) {
    TABTYPE type= hp->GetRealType(pos);

    switch (GetIndexType(type)) {
      case 1: flags|= (HA_READ_ORDER | HA_READ_PREV); break;
      case 2: flags|= HA_READ_AFTER_KEY;              break;
      } // endswitch

    } // endif pos

  return flags;
} // end of index_flags

/** @brief
  This is a list of flags that indicate what functionality the storage
  engine implements. The current table flags are documented in handler.h
*/
ulonglong ha_connect::table_flags() const
{
  ulonglong   flags= HA_CAN_VIRTUAL_COLUMNS | HA_REC_NOT_IN_SEQ |
                     HA_NO_AUTO_INCREMENT | HA_NO_PREFIX_CHAR_KEYS |
                     HA_BINLOG_ROW_CAPABLE | HA_BINLOG_STMT_CAPABLE |
                     HA_PARTIAL_COLUMN_READ | HA_FILE_BASED |
//                   HA_NULL_IN_KEY |    not implemented yet
//                   HA_FAST_KEY_READ |  causes error when sorting (???)
                     HA_NO_TRANSACTIONS | HA_DUPLICATE_KEY_NOT_IN_ORDER |
                     HA_NO_BLOBS | HA_MUST_USE_TABLE_CONDITION_PUSHDOWN;
  ha_connect *hp= (ha_connect*)this;
  PTOS        pos= hp->GetTableOptionStruct();

  if (pos) {
    TABTYPE type= hp->GetRealType(pos);

    if (IsFileType(type))
      flags|= HA_FILE_BASED;

    if (IsExactType(type))
      flags|= (HA_HAS_RECORDS | HA_STATS_RECORDS_IS_EXACT);

    // No data change on ALTER for outward tables
    if (!IsFileType(type) || hp->FileExists(pos->filename, true))
      flags|= HA_NO_COPY_ON_ALTER;

    } // endif pos

  return flags;
} // end of table_flags

/****************************************************************************/
/*  Return the value of an option specified in an option list.              */
/****************************************************************************/
PCSZ GetListOption(PGLOBAL g, PCSZ opname, PCSZ oplist, PCSZ def)
{
  if (!oplist)
    return (char*)def;

  char  key[16], val[256];
  char *pv, *pn, *pk= (char*)oplist;
	PCSZ  opval= def;
  int   n;

	while (*pk == ' ')
		pk++;

  for (; pk; pk= pn) {
    pn= strchr(pk, ',');
    pv= strchr(pk, '=');

    if (pv && (!pn || pv < pn)) {
			n = MY_MIN(static_cast<size_t>(pv - pk), sizeof(key) - 1);
			memcpy(key, pk, n);

			while (n && key[n - 1] == ' ')
				n--;

      key[n]= 0;

      while(*(++pv) == ' ') ;

			n= MY_MIN((pn ? pn - pv : strlen(pv)), sizeof(val) - 1);
      memcpy(val, pv, n);

			while (n && val[n - 1] == ' ')
				n--;

			val[n]= 0;
    } else {
			n= MY_MIN((pn ? pn - pk : strlen(pk)), sizeof(key) - 1);
      memcpy(key, pk, n);

			while (n && key[n - 1] == ' ')
				n--;

			key[n]= 0;
      val[0]= 0;
    } // endif pv

    if (!stricmp(opname, key)) {
      opval= PlugDup(g, val);
      break;
    } else if (!pn)
      break;

		while (*(++pn) == ' ') ;
    } // endfor pk

  return opval;
} // end of GetListOption

/****************************************************************************/
/*  Return the value of a string option or NULL if not specified.           */
/****************************************************************************/
PCSZ GetStringTableOption(PGLOBAL g, PTOS options, PCSZ opname, PCSZ sdef)
{
	PCSZ opval= NULL;

  if (!options)
    return sdef;
  else if (!stricmp(opname, "Type"))
    opval= options->type;
  else if (!stricmp(opname, "Filename"))
    opval= options->filename;
  else if (!stricmp(opname, "Optname"))
    opval= options->optname;
  else if (!stricmp(opname, "Tabname"))
    opval= options->tabname;
  else if (!stricmp(opname, "Tablist"))
    opval= options->tablist;
  else if (!stricmp(opname, "Database") ||
           !stricmp(opname, "DBname"))
    opval= options->dbname;
  else if (!stricmp(opname, "Separator"))
    opval= options->separator;
  else if (!stricmp(opname, "Qchar"))
    opval= options->qchar;
  else if (!stricmp(opname, "Module"))
    opval= options->module;
  else if (!stricmp(opname, "Subtype"))
    opval= options->subtype;
  else if (!stricmp(opname, "Catfunc"))
    opval= options->catfunc;
  else if (!stricmp(opname, "Srcdef"))
    opval= options->srcdef;
  else if (!stricmp(opname, "Colist"))
    opval= options->colist;
	else if (!stricmp(opname, "Filter"))
		opval = options->filter;
	else if (!stricmp(opname, "Data_charset"))
    opval= options->data_charset;

  if (!opval && options->oplist)
    opval= GetListOption(g, opname, options->oplist);

  return opval ? (char*)opval : sdef;
} // end of GetStringTableOption

/****************************************************************************/
/*  Return the value of a Boolean option or bdef if not specified.          */
/****************************************************************************/
bool GetBooleanTableOption(PGLOBAL g, PTOS options, PCSZ opname, bool bdef)
{
  bool opval= bdef;
	PCSZ pv;

  if (!options)
    return bdef;
  else if (!stricmp(opname, "Mapped"))
    opval= options->mapped;
  else if (!stricmp(opname, "Huge"))
    opval= options->huge;
  else if (!stricmp(opname, "Split"))
    opval= options->split;
  else if (!stricmp(opname, "Readonly"))
    opval= options->readonly;
  else if (!stricmp(opname, "SepIndex"))
    opval= options->sepindex;
  else if (!stricmp(opname, "Header"))
    opval= (options->header != 0);   // Is Boolean for some table types
	else if (!stricmp(opname, "Zipped"))
		opval = options->zipped;
	else if (options->oplist)
    if ((pv= GetListOption(g, opname, options->oplist)))
      opval= (!*pv || *pv == 'y' || *pv == 'Y' || atoi(pv) != 0);

  return opval;
} // end of GetBooleanTableOption

/****************************************************************************/
/*  Return the value of an integer option or NO_IVAL if not specified.      */
/****************************************************************************/
int GetIntegerTableOption(PGLOBAL g, PTOS options, PCSZ opname, int idef)
{
  ulonglong opval= (ulonglong) NO_IVAL;

  if (!options)
    return idef;
  else if (!stricmp(opname, "Lrecl"))
    opval= options->lrecl;
  else if (!stricmp(opname, "Elements"))
    opval= options->elements;
  else if (!stricmp(opname, "Multiple"))
    opval= options->multiple;
  else if (!stricmp(opname, "Header"))
    opval= options->header;
  else if (!stricmp(opname, "Quoted"))
    opval= options->quoted;
  else if (!stricmp(opname, "Ending"))
    opval= options->ending;
  else if (!stricmp(opname, "Compressed"))
    opval= (options->compressed);

  if ((ulonglong) opval == (ulonglong)NO_IVAL) {
		PCSZ pv;

    if ((pv= GetListOption(g, opname, options->oplist)))
      opval= CharToNumber((char*)pv, strlen(pv), ULONGLONG_MAX, true);
    else
      return idef;

    } // endif opval

  return (int)opval;
} // end of GetIntegerTableOption

/****************************************************************************/
/*  Return the table option structure.                                      */
/****************************************************************************/
PTOS ha_connect::GetTableOptionStruct(TABLE_SHARE *s)
{
  TABLE_SHARE *tsp= (tshp) ? tshp : (s) ? s : table_share;

	return (tsp && (!tsp->db_plugin || 
		              !stricmp(plugin_name(tsp->db_plugin)->str, "connect") ||
									!stricmp(plugin_name(tsp->db_plugin)->str, "partition")))
									? tsp->option_struct : NULL;
} // end of GetTableOptionStruct

/****************************************************************************/
/*  Return the string eventually formatted with partition name.             */
/****************************************************************************/
char *ha_connect::GetRealString(PCSZ s)
{
  char *sv;

  if (IsPartitioned() && s && *partname) {
    sv= (char*)PlugSubAlloc(xp->g, NULL, 0);
    sprintf(sv, s, partname);
    PlugSubAlloc(xp->g, NULL, strlen(sv) + 1);
  } else
    sv= (char*)s;

  return sv;
} // end of GetRealString

/****************************************************************************/
/*  Return the value of a string option or sdef if not specified.           */
/****************************************************************************/
PCSZ ha_connect::GetStringOption(PCSZ opname, PCSZ sdef)
{
	PCSZ opval= NULL;
  PTOS options= GetTableOptionStruct();

  if (!stricmp(opname, "Connect")) {
    LEX_STRING cnc= (tshp) ? tshp->connect_string 
                           : table->s->connect_string;

    if (cnc.length)
      opval= strz(xp->g, cnc);
		else
			opval= GetListOption(xp->g, opname, options->oplist);

	} else if (!stricmp(opname, "Query_String")) {
//  This escapes everything and returns a wrong query 
//	opval = thd_query_string(table->in_use)->str;
		opval = (PCSZ)PlugSubAlloc(xp->g, NULL, 
			thd_query_string(table->in_use)->length + 1);
		strcpy((char*)opval, thd_query_string(table->in_use)->str);
//	sprintf((char*)opval, "%s", thd_query_string(table->in_use)->str);
	} else if (!stricmp(opname, "Partname"))
    opval= partname;
  else if (!stricmp(opname, "Table_charset")) {
    const CHARSET_INFO *chif= (tshp) ? tshp->table_charset 
                                     : table->s->table_charset;

    if (chif)
      opval= (char*)chif->csname;

  } else
    opval= GetStringTableOption(xp->g, options, opname, NULL);

  if (opval && (!stricmp(opname, "connect") 
             || !stricmp(opname, "tabname") 
             || !stricmp(opname, "filename")
						 || !stricmp(opname, "optname")
						 || !stricmp(opname, "entry")))
						 opval = GetRealString(opval);

  if (!opval) {
    if (sdef && !strcmp(sdef, "*")) {
      // Return the handler default value
      if (!stricmp(opname, "Dbname") || !stricmp(opname, "Database"))
        opval= (char*)GetDBName(NULL);    // Current database
      else if (!stricmp(opname, "Type"))  // Default type
        opval= (!options) ? NULL :
               (options->srcdef)  ? (char*)"MYSQL" :
               (options->tabname) ? (char*)"PROXY" : (char*)"DOS";
      else if (!stricmp(opname, "User"))  // Connected user
        opval= (char *) "root";
      else if (!stricmp(opname, "Host"))  // Connected user host
        opval= (char *) "localhost";
      else
        opval= sdef;                      // Caller default

    } else
      opval= sdef;                        // Caller default

    } // endif !opval

  return opval;
} // end of GetStringOption

/****************************************************************************/
/*  Return the value of a Boolean option or bdef if not specified.          */
/****************************************************************************/
bool ha_connect::GetBooleanOption(PCSZ opname, bool bdef)
{
  bool  opval;
  PTOS  options= GetTableOptionStruct();

  if (!stricmp(opname, "View"))
    opval= (tshp) ? tshp->is_view : table_share->is_view;
  else
    opval= GetBooleanTableOption(xp->g, options, opname, bdef);

  return opval;
} // end of GetBooleanOption

/****************************************************************************/
/*  Set the value of the opname option (does not work for oplist options)   */
/*  Currently used only to set the Sepindex value.                          */
/****************************************************************************/
bool ha_connect::SetBooleanOption(PCSZ opname, bool b)
{
  PTOS options= GetTableOptionStruct();

  if (!options)
    return true;

  if (!stricmp(opname, "SepIndex"))
    options->sepindex= b;
  else
    return true;

  return false;
} // end of SetBooleanOption

/****************************************************************************/
/*  Return the value of an integer option or NO_IVAL if not specified.      */
/****************************************************************************/
int ha_connect::GetIntegerOption(PCSZ opname)
{
  int          opval;
  PTOS         options= GetTableOptionStruct();
  TABLE_SHARE *tsp= (tshp) ? tshp : table_share;

  if (!stricmp(opname, "Avglen"))
    opval= (int)tsp->avg_row_length;
  else if (!stricmp(opname, "Estimate"))
    opval= (int)tsp->max_rows;
  else
    opval= GetIntegerTableOption(xp->g, options, opname, NO_IVAL);

  return opval;
} // end of GetIntegerOption

/****************************************************************************/
/*  Set the value of the opname option (does not work for oplist options)   */
/*  Currently used only to set the Lrecl value.                             */
/****************************************************************************/
bool ha_connect::SetIntegerOption(PCSZ opname, int n)
{
  PTOS options= GetTableOptionStruct();

  if (!options)
    return true;

  if (!stricmp(opname, "Lrecl"))
    options->lrecl= n;
  else if (!stricmp(opname, "Elements"))
    options->elements= n;
//else if (!stricmp(opname, "Estimate"))
//  options->estimate= n;
  else if (!stricmp(opname, "Multiple"))
    options->multiple= n;
  else if (!stricmp(opname, "Header"))
    options->header= n;
  else if (!stricmp(opname, "Quoted"))
    options->quoted= n;
  else if (!stricmp(opname, "Ending"))
    options->ending= n;
  else if (!stricmp(opname, "Compressed"))
    options->compressed= n;
  else
    return true;
//else if (options->oplist)
//  SetListOption(opname, options->oplist, n);

  return false;
} // end of SetIntegerOption

/****************************************************************************/
/*  Return a field option structure.                                        */
/****************************************************************************/
PFOS ha_connect::GetFieldOptionStruct(Field *fdp)
{
  return fdp->option_struct;
} // end of GetFildOptionStruct

/****************************************************************************/
/*  Returns the column description structure used to make the column.       */
/****************************************************************************/
void *ha_connect::GetColumnOption(PGLOBAL g, void *field, PCOLINFO pcf)
{
  const char *cp;
  char   *chset, v = 0;
  ha_field_option_struct *fop;
  Field*  fp;
  Field* *fldp;

  // Double test to be on the safe side
  if (!table)
    return NULL;

  // Find the column to describe
  if (field) {
    fldp= (Field**)field;
    fldp++;
  } else
    fldp= (tshp) ? tshp->field : table->field;

  if (!fldp || !(fp= *fldp))
    return NULL;

  // Get the CONNECT field options structure
  fop= GetFieldOptionStruct(fp);
  pcf->Flags= 0;

  // Now get column information
  pcf->Name= (char*)fp->field_name;

  if (fop && fop->special) {
    pcf->Fieldfmt= (char*)fop->special;
    pcf->Flags= U_SPECIAL;
    return fldp;
    } // endif special

  pcf->Scale= 0;
  pcf->Opt= (fop) ? (int)fop->opt : 0;

  if ((pcf->Length= fp->field_length) < 0)
    pcf->Length= 256;            // BLOB?

  pcf->Precision= pcf->Length;

  if (fop) {
    pcf->Offset= (int)fop->offset;
    pcf->Freq= (int)fop->freq;
    pcf->Datefmt= (char*)fop->dateformat;
    pcf->Fieldfmt= (char*)fop->fieldformat;
  } else {
    pcf->Offset= -1;
    pcf->Freq= 0;
    pcf->Datefmt= NULL;
    pcf->Fieldfmt= NULL;
  } // endif fop

  chset = (char *)fp->charset()->name;

  switch (fp->type()) {
    case MYSQL_TYPE_BLOB:
    case MYSQL_TYPE_VARCHAR:
    case MYSQL_TYPE_VAR_STRING:
      pcf->Flags |= U_VAR;
			// fall through
    default:
      pcf->Type= MYSQLtoPLG(fp->type(), &v);
      break;
    } // endswitch SQL type

  switch (pcf->Type) {
    case TYPE_STRING:
		case TYPE_BIN:
			// Do something for case
      cp= chset;

      // Find if collation name ends by _ci
      if (!strcmp(cp + strlen(cp) - 3, "_ci")) {
        pcf->Scale= 1;     // Case insensitive
        pcf->Opt= 0;       // Prevent index opt until it is safe
        } // endif ci

      break;
    case TYPE_DOUBLE:
      pcf->Scale= MY_MAX(MY_MIN(fp->decimals(), ((unsigned)pcf->Length - 2)), 0);
      break;
    case TYPE_DECIM:
      pcf->Precision= ((Field_new_decimal*)fp)->precision;
      pcf->Length= pcf->Precision;
      pcf->Scale= fp->decimals();
      break;
    case TYPE_DATE:
      // Field_length is only used for DATE columns
      if (fop && fop->fldlen)
        pcf->Length= (int)fop->fldlen;
      else {
        int len;

        if (pcf->Datefmt) {
          // Find the (max) length produced by the date format
          char    buf[256];
          PGLOBAL g= GetPlug(table->in_use, xp);
          PDTP    pdtp= MakeDateFormat(g, pcf->Datefmt, false, true, 0);
          struct tm datm;
          bzero(&datm, sizeof(datm));
          datm.tm_mday= 12;
          datm.tm_mon= 11;
          datm.tm_year= 112;
          mktime(&datm); // set other fields get proper day name
          len= strftime(buf, 256, pdtp->OutFmt, &datm);
        } else
          len= 0;

        // 11 is for signed numeric representation of the date
        pcf->Length= (len) ? len : 11;
        } // endelse

      // For Value setting
      pcf->Precision= MY_MAX(pcf->Precision, pcf->Length);
      break;
    default:
      break;
    } // endswitch type

  if (fp->flags & UNSIGNED_FLAG)
    pcf->Flags |= U_UNSIGNED;

  if (fp->flags & ZEROFILL_FLAG)
    pcf->Flags |= U_ZEROFILL;

  // This is used to skip null bit
  if (fp->real_maybe_null())
    pcf->Flags |= U_NULLS;

  // Mark virtual columns as such
  if (fp->vcol_info && !fp->stored_in_db)
    pcf->Flags |= U_VIRTUAL;

  pcf->Key= 0;   // Not used when called from MySQL

  // Get the comment if any
  if (fp->comment.str && fp->comment.length)
    pcf->Remark= strz(g, fp->comment);
  else
    pcf->Remark= NULL;

  return fldp;
} // end of GetColumnOption

/****************************************************************************/
/*  Return an index option structure.                                       */
/****************************************************************************/
PXOS ha_connect::GetIndexOptionStruct(KEY *kp)
{
  return kp->option_struct;
} // end of GetIndexOptionStruct

/****************************************************************************/
/*  Return a Boolean index option or false if not specified.                */
/****************************************************************************/
bool ha_connect::GetIndexOption(KEY *kp, PCSZ opname)
{
  bool opval= false;
  PXOS options= GetIndexOptionStruct(kp);

  if (options) {
    if (!stricmp(opname, "Dynamic"))
      opval= options->dynamic;
    else if (!stricmp(opname, "Mapped"))
      opval= options->mapped;

  } else if (kp->comment.str && kp->comment.length) {
		PCSZ pv, oplist= strz(xp->g, kp->comment);

    if ((pv= GetListOption(xp->g, opname, oplist)))
      opval= (!*pv || *pv == 'y' || *pv == 'Y' || atoi(pv) != 0);

  } // endif comment

  return opval;
} // end of GetIndexOption

/****************************************************************************/
/*  Returns the index description structure used to make the index.         */
/****************************************************************************/
bool ha_connect::IsUnique(uint n)
{
  TABLE_SHARE *s= (table) ? table->s : NULL;
  KEY          kp= s->key_info[n];

  return (kp.flags & 1) != 0;
} // end of IsUnique

/****************************************************************************/
/*  Returns the index description structure used to make the index.         */
/****************************************************************************/
PIXDEF ha_connect::GetIndexInfo(TABLE_SHARE *s)
{
  char    *name, *pn;
  bool     unique;
  PIXDEF   xdp, pxd=NULL, toidx= NULL;
  PKPDEF   kpp, pkp;
  KEY      kp;
  PGLOBAL& g= xp->g;

  if (!s)
    s= table->s;

  for (int n= 0; (unsigned)n < s->keynames.count; n++) {
    if (trace)
      htrc("Getting created index %d info\n", n + 1);

    // Find the index to describe
    kp= s->key_info[n];

    // Now get index information
    pn= (char*)s->keynames.type_names[n];
    name= PlugDup(g, pn);
    unique= (kp.flags & 1) != 0;
    pkp= NULL;

    // Allocate the index description block
    xdp= new(g) INDEXDEF(name, unique, n);

    // Get the the key parts info
    for (int k= 0; (unsigned)k < kp.user_defined_key_parts; k++) {
      pn= (char*)kp.key_part[k].field->field_name;
      name= PlugDup(g, pn);

      // Allocate the key part description block
      kpp= new(g) KPARTDEF(name, k + 1);
      kpp->SetKlen(kp.key_part[k].length);

#if 0             // NIY
    // Index on auto increment column can be an XXROW index
    if (kp.key_part[k].field->flags & AUTO_INCREMENT_FLAG &&
        kp.uder_defined_key_parts == 1) {
      char   *type= GetStringOption("Type", "DOS");
      TABTYPE typ= GetTypeID(type);

      xdp->SetAuto(IsTypeFixed(typ));
      } // endif AUTO_INCREMENT
#endif // 0

      if (pkp)
        pkp->SetNext(kpp);
      else
        xdp->SetToKeyParts(kpp);

      pkp= kpp;
      } // endfor k

    xdp->SetNParts(kp.user_defined_key_parts);
    xdp->Dynamic= GetIndexOption(&kp, "Dynamic");
    xdp->Mapped= GetIndexOption(&kp, "Mapped");

    if (pxd)
      pxd->SetNext(xdp);
    else
      toidx= xdp;

    pxd= xdp;
    } // endfor n

  return toidx;
} // end of GetIndexInfo

/****************************************************************************/
/*  Returns the index description structure used to make the index.         */
/****************************************************************************/
bool ha_connect::CheckVirtualIndex(TABLE_SHARE *s)
{

  char    *rid;
  KEY      kp;
  Field   *fp;
  PGLOBAL& g= xp->g;

  if (!s)
    s= table->s;

  for (int n= 0; (unsigned)n < s->keynames.count; n++) {
    kp= s->key_info[n];

    // Now get index information

    // Get the the key parts info
    for (int k= 0; (unsigned)k < kp.user_defined_key_parts; k++) {
      fp= kp.key_part[k].field;
      rid= (fp->option_struct) ? fp->option_struct->special : NULL;

      if (!rid || (stricmp(rid, "ROWID") && stricmp(rid, "ROWNUM"))) {
        strcpy(g->Message, "Invalid virtual index");
        return true;
        } // endif rowid

      } // endfor k

    } // endfor n

  return false;
} // end of CheckVirtualIndex

bool ha_connect::IsPartitioned(void)
{
#ifdef WITH_PARTITION_STORAGE_ENGINE
  if (tshp)
    return tshp->partition_info_str_len > 0;
  else if (table && table->part_info)
    return true;
  else
#endif
    return false;

} // end of IsPartitioned

PCSZ ha_connect::GetDBName(PCSZ name)
{
  return (name) ? name : table->s->db.str;
} // end of GetDBName

const char *ha_connect::GetTableName(void)
{
  return tshp ? tshp->table_name.str : table_share->table_name.str;
} // end of GetTableName

char *ha_connect::GetPartName(void)
{
  return (IsPartitioned()) ? partname : (char*)GetTableName();
} // end of GetTableName

#if 0
/****************************************************************************/
/*  Returns the column real or special name length of a field.              */
/****************************************************************************/
int ha_connect::GetColNameLen(Field *fp)
{
  int n;
  PFOS fop= GetFieldOptionStruct(fp);

  // Now get the column name length
  if (fop && fop->special)
    n= strlen(fop->special) + 1;
  else
    n= strlen(fp->field_name);

  return n;
} // end of GetColNameLen

/****************************************************************************/
/*  Returns the column real or special name of a field.                     */
/****************************************************************************/
char *ha_connect::GetColName(Field *fp)
{
  PFOS fop= GetFieldOptionStruct(fp);

  return (fop && fop->special) ? fop->special : (char*)fp->field_name;
} // end of GetColName

/****************************************************************************/
/*  Adds the column real or special name of a field to a string.            */
/****************************************************************************/
void ha_connect::AddColName(char *cp, Field *fp)
{
  PFOS fop= GetFieldOptionStruct(fp);

  // Now add the column name
  if (fop && fop->special)
    // The prefix * mark the column as "special"
    strcat(strcpy(cp, "*"), strupr(fop->special));
  else
    strcpy(cp, (char*)fp->field_name);

} // end of AddColName
#endif // 0

/***********************************************************************/
/*  This function sets the current database path.                      */
/***********************************************************************/
bool ha_connect::SetDataPath(PGLOBAL g, PCSZ path) 
{
  return (!(datapath= SetPath(g, path)));
} // end of SetDataPath

/****************************************************************************/
/*  Get the table description block of a CONNECT table.                     */
/****************************************************************************/
PTDB ha_connect::GetTDB(PGLOBAL g)
{
  const char *table_name;
  PTDB        tp;

  // Double test to be on the safe side
  if (!g || !table)
    return NULL;

  table_name= GetTableName();

  if (!xp->CheckQuery(valid_query_id) && tdbp
                      && !stricmp(tdbp->GetName(), table_name)
                      && (tdbp->GetMode() == xmod
                       || (tdbp->GetMode() == MODE_READ && xmod == MODE_READX)
                       || tdbp->GetAmType() == TYPE_AM_XML)) {
    tp= tdbp;
    tp->SetMode(xmod);
  } else if ((tp= CntGetTDB(g, table_name, xmod, this))) {
    valid_query_id= xp->last_query_id;
//  tp->SetMode(xmod);
  } else
    htrc("GetTDB: %s\n", g->Message);

  return tp;
} // end of GetTDB

/****************************************************************************/
/*  Open a CONNECT table, restricting column list if cols is true.          */
/****************************************************************************/
int ha_connect::OpenTable(PGLOBAL g, bool del)
{
  bool  rc= false;
  char *c1= NULL, *c2=NULL;

  // Double test to be on the safe side
  if (!g || !table) {
    htrc("OpenTable logical error; g=%p table=%p\n", g, table);
    return HA_ERR_INITIALIZATION;
    } // endif g

  if (!(tdbp= GetTDB(g)))
    return RC_FX;
  else if (tdbp->IsReadOnly())
    switch (xmod) {
      case MODE_WRITE:
      case MODE_INSERT:
      case MODE_UPDATE:
      case MODE_DELETE:
        strcpy(g->Message, MSG(READ_ONLY));
        return HA_ERR_TABLE_READONLY;
      default:
        break;
      } // endswitch xmode

  if (xmod != MODE_INSERT || tdbp->GetAmType() == TYPE_AM_MYSQL
                          || tdbp->GetAmType() == TYPE_AM_ODBC
													|| tdbp->GetAmType() == TYPE_AM_JDBC) {
		// Get the list of used fields (columns)
    char        *p;
    unsigned int k1, k2, n1, n2;
    Field*      *field;
    Field*       fp;
    MY_BITMAP   *map= (xmod == MODE_INSERT) ? table->write_set : table->read_set;
    MY_BITMAP   *ump= (xmod == MODE_UPDATE) ? table->write_set : NULL;

    k1= k2= 0;
    n1= n2= 1;         // 1 is space for final null character

    for (field= table->field; fp= *field; field++) {
      if (bitmap_is_set(map, fp->field_index)) {
        n1+= (strlen(fp->field_name) + 1);
        k1++;
        } // endif

      if (ump && bitmap_is_set(ump, fp->field_index)) {
        n2+= (strlen(fp->field_name) + 1);
        k2++;
        } // endif

      } // endfor field

    if (k1) {
      p= c1= (char*)PlugSubAlloc(g, NULL, n1);

      for (field= table->field; fp= *field; field++)
        if (bitmap_is_set(map, fp->field_index)) {
          strcpy(p, (char*)fp->field_name);
          p+= (strlen(p) + 1);
          } // endif used field

      *p= '\0';          // mark end of list
      } // endif k1

    if (k2) {
      p= c2= (char*)PlugSubAlloc(g, NULL, n2);

      for (field= table->field; fp= *field; field++)
        if (bitmap_is_set(ump, fp->field_index)) {
          strcpy(p, (char*)fp->field_name);

          if (part_id && bitmap_is_set(part_id, fp->field_index)) {
            // Trying to update a column used for partitioning
            // This cannot be currently done because it may require
            // a row to be moved in another partition.
            sprintf(g->Message, 
              "Cannot update column %s because it is used for partitioning",
              p);
            return HA_ERR_INTERNAL_ERROR;
            } // endif part_id

          p+= (strlen(p) + 1);
          } // endif used field

      *p= '\0';          // mark end of list
      } // endif k2

    } // endif xmod

  // Open the table
  if (!(rc= CntOpenTable(g, tdbp, xmod, c1, c2, del, this))) {
    istable= true;
//  strmake(tname, table_name, sizeof(tname)-1);

    // We may be in a create index query
    if (xmod == MODE_ANY && *tdbp->GetName() != '#') {
      // The current indexes
      PIXDEF oldpix= GetIndexInfo();
      } // endif xmod

  } else
    htrc("OpenTable: %s\n", g->Message);

  if (rc) {
    tdbp= NULL;
    valid_info= false;
    } // endif rc

  return (rc) ? HA_ERR_INITIALIZATION : 0;
} // end of OpenTable


/****************************************************************************/
/*  CheckColumnList: check that all bitmap columns do exist.                */
/****************************************************************************/
bool ha_connect::CheckColumnList(PGLOBAL g)
{
  // Check the list of used fields (columns)
  bool       brc= false;
  PCOL       colp;
  Field*    *field;
  Field*     fp;
  MY_BITMAP *map= table->read_set;

	try {
    for (field= table->field; fp= *field; field++)
      if (bitmap_is_set(map, fp->field_index)) {
        if (!(colp= tdbp->ColDB(g, (PSZ)fp->field_name, 0))) {
          sprintf(g->Message, "Column %s not found in %s", 
                  fp->field_name, tdbp->GetName());
					throw 1;
				} // endif colp

        if ((brc= colp->InitValue(g)))
					throw 2;

        colp->AddColUse(U_P);           // For PLG tables
        } // endif

	} catch (int n) {
		if (trace)
			htrc("Exception %d: %s\n", n, g->Message);
		brc = true;
	} catch (const char *msg) {
		strcpy(g->Message, msg);
		brc = true;
	} // end catch

  return brc;
} // end of CheckColumnList


/****************************************************************************/
/*  IsOpened: returns true if the table is already opened.                  */
/****************************************************************************/
bool ha_connect::IsOpened(void)
{
  return (!xp->CheckQuery(valid_query_id) && tdbp
                                          && tdbp->GetUse() == USE_OPEN);
} // end of IsOpened


/****************************************************************************/
/*  Close a CONNECT table.                                                  */
/****************************************************************************/
int ha_connect::CloseTable(PGLOBAL g)
{
  int rc= CntCloseTable(g, tdbp, nox, abort);
  tdbp= NULL;
  sdvalin1= sdvalin2= sdvalin3= sdvalin4= NULL;
  sdvalout=NULL;
  valid_info= false;
  indexing= -1;
  nox= true;
  abort= false;
  return rc;
} // end of CloseTable


/***********************************************************************/
/*  Make a pseudo record from current row values. Specific to MySQL.   */
/***********************************************************************/
int ha_connect::MakeRecord(char *buf)
{
	PCSZ           fmt;
  char          *p, val[32];
  int            rc= 0;
  Field*        *field;
  Field         *fp;
  my_bitmap_map *org_bitmap;
  CHARSET_INFO  *charset= tdbp->data_charset();
//MY_BITMAP      readmap;
  MY_BITMAP     *map;
  PVAL           value;
  PCOL           colp= NULL;
  DBUG_ENTER("ha_connect::MakeRecord");

  if (trace > 1)
    htrc("Maps: read=%08X write=%08X vcol=%08X defr=%08X defw=%08X\n",
            *table->read_set->bitmap, *table->write_set->bitmap,
            (table->vcol_set) ? *table->vcol_set->bitmap : 0,
            *table->def_read_set.bitmap, *table->def_write_set.bitmap);

  // Avoid asserts in field::store() for columns that are not updated
  org_bitmap= dbug_tmp_use_all_columns(table, table->write_set);

  // This is for variable_length rows
  memset(buf, 0, table->s->null_bytes);

  // When sorting read_set selects all columns, so we use def_read_set
  map= (MY_BITMAP *)&table->def_read_set;

  // Make the pseudo record from field values
  for (field= table->field; *field && !rc; field++) {
    fp= *field;

    if (fp->vcol_info && !fp->stored_in_db)
      continue;            // This is a virtual column

    if (bitmap_is_set(map, fp->field_index) || alter) {
      // This is a used field, fill the buffer with value
      for (colp= tdbp->GetColumns(); colp; colp= colp->GetNext())
        if ((!mrr || colp->GetKcol()) &&
            !stricmp(colp->GetName(), (char*)fp->field_name))
          break;

      if (!colp) {
        if (mrr)
          continue;

        htrc("Column %s not found\n", fp->field_name);
        dbug_tmp_restore_column_map(table->write_set, org_bitmap);
        DBUG_RETURN(HA_ERR_WRONG_IN_RECORD);
        } // endif colp

      value= colp->GetValue();
      p= NULL;

      // All this was better optimized
      if (!value->IsNull()) {
        switch (value->GetType()) {
          case TYPE_DATE:
            if (!sdvalout)
              sdvalout= AllocateValue(xp->g, TYPE_STRING, 20);

            switch (fp->type()) {
              case MYSQL_TYPE_DATE:
                fmt= "%Y-%m-%d";
                break;
              case MYSQL_TYPE_TIME:
                fmt= "%H:%M:%S";
                break;
              case MYSQL_TYPE_YEAR:
                fmt= "%Y";
                break;
              default:
                fmt= "%Y-%m-%d %H:%M:%S";
                break;
              } // endswitch type

            // Get date in the format required by MySQL fields
            value->FormatValue(sdvalout, fmt);
            p= sdvalout->GetCharValue();
            rc= fp->store(p, strlen(p), charset, CHECK_FIELD_WARN);
            break;
          case TYPE_STRING:
          case TYPE_DECIM:
            p= value->GetCharString(val);
            charset= tdbp->data_charset();
            rc= fp->store(p, strlen(p), charset, CHECK_FIELD_WARN);
            break;
					case TYPE_BIN:
						p = value->GetCharValue();
						charset = &my_charset_bin;
						rc = fp->store(p, strlen(p), charset, CHECK_FIELD_WARN);
						break;
          case TYPE_DOUBLE:
            rc= fp->store(value->GetFloatValue());
            break;
          default:
            rc= fp->store(value->GetBigintValue(), value->IsUnsigned());
            break;
          } // endswitch Type

        // Store functions returns 1 on overflow and -1 on fatal error
        if (rc > 0) {
          char buf[256];
          THD *thd= ha_thd();

          sprintf(buf, "Out of range value %.140s for column '%s' at row %ld",
            value->GetCharString(val),
            fp->field_name, 
            thd->get_stmt_da()->current_row_for_warning());

          push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 0, buf);
          DBUG_PRINT("MakeRecord", ("%s", buf));
          rc= 0;
        } else if (rc < 0)
          rc= HA_ERR_WRONG_IN_RECORD;

        fp->set_notnull();
      } else
        fp->set_null();

      } // endif bitmap

    } // endfor field

  // This is sometimes required for partition tables because the buf
  // can be different from the table->record[0] buffer
  if (buf != (char*)table->record[0])
    memcpy(buf, table->record[0], table->s->stored_rec_length);

  // This is copied from ha_tina and is necessary to avoid asserts
  dbug_tmp_restore_column_map(table->write_set, org_bitmap);
  DBUG_RETURN(rc);
} // end of MakeRecord


/***********************************************************************/
/*  Set row values from a MySQL pseudo record. Specific to MySQL.      */
/***********************************************************************/
int ha_connect::ScanRecord(PGLOBAL g, const uchar *)
{
  char    attr_buffer[1024];
  char    data_buffer[1024];
  PCSZ    fmt;
  int     rc= 0;
  PCOL    colp;
  PVAL    value, sdvalin;
  Field  *fp;
//PTDBASE tp= (PTDBASE)tdbp;
  String  attribute(attr_buffer, sizeof(attr_buffer),
                    table->s->table_charset);
  my_bitmap_map *bmap= dbug_tmp_use_all_columns(table, table->read_set);
  const CHARSET_INFO *charset= tdbp->data_charset();
  String  data_charset_value(data_buffer, sizeof(data_buffer),  charset);

  // Scan the pseudo record for field values and set column values
  for (Field **field=table->field ; *field ; field++) {
    fp= *field;

    if ((fp->vcol_info && !fp->stored_in_db) ||
         fp->option_struct->special)
      continue;            // Is a virtual column possible here ???

    if ((xmod == MODE_INSERT && tdbp->GetAmType() != TYPE_AM_MYSQL
                             && tdbp->GetAmType() != TYPE_AM_ODBC
														 && tdbp->GetAmType() != TYPE_AM_JDBC) ||
														 bitmap_is_set(table->write_set, fp->field_index)) {
      for (colp= tdbp->GetSetCols(); colp; colp= colp->GetNext())
        if (!stricmp(colp->GetName(), fp->field_name))
          break;

      if (!colp) {
        htrc("Column %s not found\n", fp->field_name);
        rc= HA_ERR_WRONG_IN_RECORD;
        goto err;
      } else
        value= colp->GetValue();

      // This is a used field, fill the value from the row buffer
      // All this could be better optimized
      if (fp->is_null()) {
        if (colp->IsNullable())
          value->SetNull(true);

        value->Reset();
      } else switch (value->GetType()) {
        case TYPE_DOUBLE:
          value->SetValue(fp->val_real());
          break;
        case TYPE_DATE:
          // Get date in the format produced by MySQL fields
          switch (fp->type()) {
            case MYSQL_TYPE_DATE:
              if (!sdvalin2) {
                sdvalin2= (DTVAL*)AllocateValue(xp->g, TYPE_DATE, 19);
                fmt= "YYYY-MM-DD";
                ((DTVAL*)sdvalin2)->SetFormat(g, fmt, strlen(fmt));
                } // endif sdvalin1

              sdvalin= sdvalin2;
              break;
            case MYSQL_TYPE_TIME:
              if (!sdvalin3) {
                sdvalin3= (DTVAL*)AllocateValue(xp->g, TYPE_DATE, 19);
                fmt= "hh:mm:ss";
                ((DTVAL*)sdvalin3)->SetFormat(g, fmt, strlen(fmt));
                } // endif sdvalin1

              sdvalin= sdvalin3;
              break;
            case MYSQL_TYPE_YEAR:
              if (!sdvalin4) {
                sdvalin4= (DTVAL*)AllocateValue(xp->g, TYPE_DATE, 19);
                fmt= "YYYY";
                ((DTVAL*)sdvalin4)->SetFormat(g, fmt, strlen(fmt));
                } // endif sdvalin1

              sdvalin= sdvalin4;
              break;
            default:
              if (!sdvalin1) {
                sdvalin1= (DTVAL*)AllocateValue(xp->g, TYPE_DATE, 19);
                fmt= "YYYY-MM-DD hh:mm:ss";
                ((DTVAL*)sdvalin1)->SetFormat(g, fmt, strlen(fmt));
                } // endif sdvalin1

              sdvalin= sdvalin1;
            } // endswitch type

          sdvalin->SetNullable(colp->IsNullable());
          fp->val_str(&attribute);
          sdvalin->SetValue_psz(attribute.c_ptr_safe());
          value->SetValue_pval(sdvalin);
          break;
        default:
          fp->val_str(&attribute);

          if (charset != &my_charset_bin) {
            // Convert from SQL field charset to DATA_CHARSET
            uint cnv_errors;

            data_charset_value.copy(attribute.ptr(), attribute.length(),
                                    attribute.charset(), charset, &cnv_errors);
            value->SetValue_psz(data_charset_value.c_ptr_safe());
          } else
            value->SetValue_psz(attribute.c_ptr_safe());

          break;
        } // endswitch Type

#ifdef NEWCHANGE
    } else if (xmod == MODE_UPDATE) {
      PCOL cp;

      for (cp= tdbp->GetColumns(); cp; cp= cp->GetNext())
        if (!stricmp(colp->GetName(), cp->GetName()))
          break;

      if (!cp) {
        rc= HA_ERR_WRONG_IN_RECORD;
        goto err;
        } // endif cp

      value->SetValue_pval(cp->GetValue());
    } else // mode Insert
      value->Reset();
#else
    } // endif bitmap_is_set
#endif

    } // endfor field

 err:
  dbug_tmp_restore_column_map(table->read_set, bmap);
  return rc;
} // end of ScanRecord


/***********************************************************************/
/*  Check change in index column. Specific to MySQL.                   */
/*  Should be elaborated to check for real changes.                    */
/***********************************************************************/
int ha_connect::CheckRecord(PGLOBAL g, const uchar *, const uchar *newbuf)
{
	return ScanRecord(g, newbuf);
} // end of dummy CheckRecord


/***********************************************************************/
/*  Return true if this field is used in current indexing.             */
/***********************************************************************/
bool ha_connect::IsIndexed(Field *fp)
{
	if (active_index < MAX_KEY) {
		KEY_PART_INFO *kpart;
		KEY           *kfp= &table->key_info[active_index];
		uint           rem= kfp->user_defined_key_parts;

		for (kpart= kfp->key_part; rem; rem--, kpart++)
			if (kpart->field == fp)
				return true;

	} // endif active_index

	return false;
} // end of IsIndexed


/***********************************************************************/
/*  Return the where clause for remote indexed read.                   */
/***********************************************************************/
bool ha_connect::MakeKeyWhere(PGLOBAL g, PSTRG qry, OPVAL vop, char q,
	                            const key_range *kr)
{
	const uchar     *ptr;
//uint             i, rem, len, klen, stlen;
	uint             i, rem, len, stlen;
	bool             nq, both, oom;
	OPVAL            op;
	Field           *fp;
	const key_range *ranges[2];
	my_bitmap_map   *old_map;
	KEY             *kfp;
  KEY_PART_INFO   *kpart;

  if (active_index == MAX_KEY)
    return false;

	ranges[0]= kr;
	ranges[1]= (end_range && !eq_range) ? &save_end_range : NULL;

	if (!ranges[0] && !ranges[1]) {
		strcpy(g->Message, "MakeKeyWhere: No key");
	  return true;
	}	else
		both= ranges[0] && ranges[1];

	kfp= &table->key_info[active_index];
	old_map= dbug_tmp_use_all_columns(table, table->write_set);

	for (i = 0; i <= 1; i++) {
		if (ranges[i] == NULL)
			continue;

		if (both && i > 0)
			qry->Append(") AND (");
		else
			qry->Append(" WHERE (");

//	klen= len= ranges[i]->length;
		len= ranges[i]->length;
		rem= kfp->user_defined_key_parts;
		ptr= ranges[i]->key;

		for (kpart= kfp->key_part; rem; rem--, kpart++) {
			fp= kpart->field;
			stlen= kpart->store_length;
			nq= fp->str_needs_quotes();

			if (kpart != kfp->key_part)
				qry->Append(" AND ");

			if (q) {
				qry->Append(q);
				qry->Append((PSZ)fp->field_name);
				qry->Append(q);
			}	else
				qry->Append((PSZ)fp->field_name);

			switch (ranges[i]->flag) {
			case HA_READ_KEY_EXACT:
//			op= (stlen >= len || !nq || fp->result_type() != STRING_RESULT)
//				? OP_EQ : OP_LIKE;
				op= OP_EQ;
				break;
			case HA_READ_AFTER_KEY:	  
				op= (stlen >= len || i > 0) ? (i > 0 ? OP_LE : OP_GT) : OP_GE;
				break;
			case HA_READ_KEY_OR_NEXT:
				op= OP_GE;
				break;
			case HA_READ_BEFORE_KEY:	
				op= (stlen >= len) ? OP_LT : OP_LE;
				break;
			case HA_READ_KEY_OR_PREV:
				op= OP_LE;
				break;
			default:
				sprintf(g->Message, "cannot handle flag %d", ranges[i]->flag);
				goto err;
			}	// endswitch flag

			qry->Append((PSZ)GetValStr(op, false));

			if (nq)
				qry->Append('\'');

			if (kpart->key_part_flag & HA_VAR_LENGTH_PART) {
				String varchar;
				uint   var_length= uint2korr(ptr);

				varchar.set_quick((char*)ptr + HA_KEY_BLOB_LENGTH,
					var_length, &my_charset_bin);
				qry->Append(varchar.ptr(), varchar.length(), nq);
			}	else {
				char   strbuff[MAX_FIELD_WIDTH];
				String str(strbuff, sizeof(strbuff), kpart->field->charset()), *res;

				res= fp->val_str(&str, ptr);
				qry->Append(res->ptr(), res->length(), nq);
			} // endif flag

			if (nq)
				qry->Append('\'');

			if (stlen >= len)
				break;

			len-= stlen;

			/* For nullable columns, null-byte is already skipped before, that is
			ptr was incremented by 1. Since store_length still counts null-byte,
			we need to subtract 1 from store_length. */
			ptr+= stlen - MY_TEST(kpart->null_bit);
		} // endfor kpart

		} // endfor i

	qry->Append(')');

  if ((oom= qry->IsTruncated()))
    strcpy(g->Message, "Out of memory");

	dbug_tmp_restore_column_map(table->write_set, old_map);
	return oom;

err:
	dbug_tmp_restore_column_map(table->write_set, old_map);
	return true;
} // end of MakeKeyWhere


/***********************************************************************/
/*  Return the string representing an operator.                        */
/***********************************************************************/
const char *ha_connect::GetValStr(OPVAL vop, bool neg)
{
  const char *val;

  switch (vop) {
    case OP_EQ:
      val= " = ";
      break;
    case OP_NE:
      val= " <> ";
      break;
    case OP_GT:
      val= " > ";
      break;
    case OP_GE:
      val= " >= ";
      break;
    case OP_LT:
      val= " < ";
      break;
    case OP_LE:
      val= " <= ";
      break;
    case OP_IN:
      val= (neg) ? " NOT IN (" : " IN (";
      break;
    case OP_NULL:
      val= (neg) ? " IS NOT NULL" : " IS NULL";
      break;
    case OP_LIKE:
      val= (neg) ? " NOT LIKE " : " LIKE ";
      break;
    case OP_XX:
      val= (neg) ? " NOT BETWEEN " : " BETWEEN ";
      break;
    case OP_EXIST:
      val= (neg) ? " NOT EXISTS " : " EXISTS ";
      break;
    case OP_AND:
      val= " AND ";
      break;
    case OP_OR:
      val= " OR ";
      break;
    case OP_NOT:
      val= " NOT ";
      break;
    case OP_CNC:
      val= " || ";
      break;
    case OP_ADD:
      val= " + ";
      break;
    case OP_SUB:
      val= " - ";
      break;
    case OP_MULT:
      val= " * ";
      break;
    case OP_DIV:
      val= " / ";
      break;
    default:
      val= " ? ";
      break;
    } /* endswitch */

  return val;
} // end of GetValStr

#if 0
/***********************************************************************/
/*  Check the WHERE condition and return a CONNECT filter.             */
/***********************************************************************/
PFIL ha_connect::CheckFilter(PGLOBAL g)
{
  return CondFilter(g, (Item *)pushed_cond);
} // end of CheckFilter
#endif // 0

/***********************************************************************/
/*  Check the WHERE condition and return a CONNECT filter.             */
/***********************************************************************/
PFIL ha_connect::CondFilter(PGLOBAL g, Item *cond)
{
  unsigned int i;
  bool  ismul= false;
  OPVAL vop= OP_XX;
  PFIL  filp= NULL;

  if (!cond)
    return NULL;

  if (trace)
    htrc("Cond type=%d\n", cond->type());

  if (cond->type() == COND::COND_ITEM) {
    PFIL       fp;
    Item_cond *cond_item= (Item_cond *)cond;

    if (trace)
      htrc("Cond: Ftype=%d name=%s\n", cond_item->functype(),
                                       cond_item->func_name());

    switch (cond_item->functype()) {
      case Item_func::COND_AND_FUNC: vop= OP_AND; break;
      case Item_func::COND_OR_FUNC:  vop= OP_OR;  break;
      default: return NULL;
      } // endswitch functype

    List<Item>* arglist= cond_item->argument_list();
    List_iterator<Item> li(*arglist);
    Item *subitem;

    for (i= 0; i < arglist->elements; i++)
      if ((subitem= li++)) {
        if (!(fp= CondFilter(g, subitem))) {
          if (vop == OP_OR)
            return NULL;
        } else
          filp= (filp) ? MakeFilter(g, filp, vop, fp) : fp;

      } else
        return NULL;

  } else if (cond->type() == COND::FUNC_ITEM) {
    unsigned int i;
    bool       iscol, neg= FALSE;
    PCOL       colp[2]= {NULL,NULL};
    PPARM      pfirst= NULL, pprec= NULL;
    POPER      pop;
    Item_func *condf= (Item_func *)cond;
    Item*     *args= condf->arguments();

    if (trace)
      htrc("Func type=%d argnum=%d\n", condf->functype(),
                                       condf->argument_count());

    switch (condf->functype()) {
      case Item_func::EQUAL_FUNC:
      case Item_func::EQ_FUNC: vop= OP_EQ;  break;
      case Item_func::NE_FUNC: vop= OP_NE;  break;
      case Item_func::LT_FUNC: vop= OP_LT;  break;
      case Item_func::LE_FUNC: vop= OP_LE;  break;
      case Item_func::GE_FUNC: vop= OP_GE;  break;
      case Item_func::GT_FUNC: vop= OP_GT;  break;
      case Item_func::IN_FUNC: vop= OP_IN;	/* fall through */
      case Item_func::BETWEEN:
        ismul= true;
        neg= ((Item_func_opt_neg *)condf)->negated;
        break;
      default: return NULL;
      } // endswitch functype

    pop= (POPER)PlugSubAlloc(g, NULL, sizeof(OPER));
    pop->Name= NULL;
    pop->Val=vop;
    pop->Mod= 0;

    if (condf->argument_count() < 2)
      return NULL;

    for (i= 0; i < condf->argument_count(); i++) {
      if (trace)
        htrc("Argtype(%d)=%d\n", i, args[i]->type());

      if (i >= 2 && !ismul) {
        if (trace)
          htrc("Unexpected arg for vop=%d\n", vop);

        continue;
        } // endif i

      if ((iscol= args[i]->type() == COND::FIELD_ITEM)) {
        Item_field *pField= (Item_field *)args[i];

        // IN and BETWEEN clauses should be col VOP list
        if (i && ismul)
          return NULL;

        if (pField->field->table != table ||
            !(colp[i]= tdbp->ColDB(g, (PSZ)pField->field->field_name, 0)))
          return NULL;  // Column does not belong to this table

				// These types are not yet implemented (buggy)
				switch (pField->field->type()) {
				case MYSQL_TYPE_TIMESTAMP:
				case MYSQL_TYPE_DATE:
				case MYSQL_TYPE_TIME:
				case MYSQL_TYPE_DATETIME:
				case MYSQL_TYPE_YEAR:
				case MYSQL_TYPE_NEWDATE:
					return NULL;
				default:
					break;
				} // endswitch type

        if (trace) {
          htrc("Field index=%d\n", pField->field->field_index);
          htrc("Field name=%s\n", pField->field->field_name);
          } // endif trace

      } else {
        char    buff[256];
        String *res, tmp(buff, sizeof(buff), &my_charset_bin);
        Item_basic_constant *pval= (Item_basic_constant *)args[i];
        PPARM pp= (PPARM)PlugSubAlloc(g, NULL, sizeof(PARM));

        // IN and BETWEEN clauses should be col VOP list
        if (!i && (ismul))
          return NULL;

				switch (args[i]->real_type()) {
          case COND::STRING_ITEM:
						res= pval->val_str(&tmp);
						pp->Value= PlugSubAllocStr(g, NULL, res->ptr(), res->length());
            pp->Type= (pp->Value) ? TYPE_STRING : TYPE_ERROR;
            break;
          case COND::INT_ITEM:
            pp->Type= TYPE_INT;
            pp->Value= PlugSubAlloc(g, NULL, sizeof(int));
            *((int*)pp->Value)= (int)pval->val_int();
            break;
          case COND::DATE_ITEM:
            pp->Type= TYPE_DATE;
            pp->Value= PlugSubAlloc(g, NULL, sizeof(int));
            *((int*)pp->Value)= (int)pval->val_int_from_date();
            break;
          case COND::REAL_ITEM:
            pp->Type= TYPE_DOUBLE;
            pp->Value= PlugSubAlloc(g, NULL, sizeof(double));
            *((double*)pp->Value)= pval->val_real();
            break;
          case COND::DECIMAL_ITEM:
            pp->Type= TYPE_DOUBLE;
            pp->Value= PlugSubAlloc(g, NULL, sizeof(double));
            *((double*)pp->Value)= pval->val_real_from_decimal();
            break;
          case COND::CACHE_ITEM:    // Possible ???
          case COND::NULL_ITEM:     // TODO: handle this
          default:
            return NULL;
          } // endswitch type

				if (trace)
          htrc("Value type=%hd\n", pp->Type);

        // Append the value to the argument list
        if (pprec)
          pprec->Next= pp;
        else
          pfirst= pp;

        pp->Domain= i;
        pp->Next= NULL;
        pprec= pp;
      } // endif type

      } // endfor i

    filp= MakeFilter(g, colp, pop, pfirst, neg);
  } else {
    if (trace)
      htrc("Unsupported condition\n");

    return NULL;
  } // endif's type

  return filp;
} // end of CondFilter

/***********************************************************************/
/*  Check the WHERE condition and return a MYSQL/ODBC/JDBC/WQL filter. */
/***********************************************************************/
PCFIL ha_connect::CheckCond(PGLOBAL g, PCFIL filp, const Item *cond)
{
	AMT   tty = filp->Type;
  char *body= filp->Body;
	char *havg= filp->Having;
	unsigned int i;
  bool  ismul= false, x= (tty == TYPE_AM_MYX || tty == TYPE_AM_XDBC);
  bool  nonul= ((tty == TYPE_AM_ODBC || tty == TYPE_AM_JDBC) && 
		 (tdbp->GetMode() == MODE_INSERT || tdbp->GetMode() == MODE_DELETE));
  OPVAL vop= OP_XX;

  if (!cond)
    return NULL;

  if (trace)
    htrc("Cond type=%d\n", cond->type());

  if (cond->type() == COND::COND_ITEM) {
    char      *pb0, *pb1, *pb2, *ph0, *ph1, *ph2;
		bool       bb = false, bh = false;
    Item_cond *cond_item= (Item_cond *)cond;

    if (x)
      return NULL;
		else
			pb0= pb1= pb2= ph0= ph1= ph2= NULL;

    if (trace)
      htrc("Cond: Ftype=%d name=%s\n", cond_item->functype(),
                                       cond_item->func_name());

    switch (cond_item->functype()) {
      case Item_func::COND_AND_FUNC: vop= OP_AND; break;
      case Item_func::COND_OR_FUNC:  vop= OP_OR;  break;
      default: return NULL;
      } // endswitch functype

    List<Item>* arglist= cond_item->argument_list();
    List_iterator<Item> li(*arglist);
    const Item *subitem;

    pb0= pb1= body + strlen(body);
    strcpy(pb0, "(");
    pb2= pb1 + 1;

		if (havg) {
			ph0= ph1= havg + strlen(havg);
			strcpy(ph0, "(");
			ph2= ph1 + 1;
		} // endif havg

    for (i= 0; i < arglist->elements; i++)
      if ((subitem= li++)) {
        if (!CheckCond(g, filp, subitem)) {
          if (vop == OP_OR || nonul)
            return NULL;
					else {
						*pb2= 0;
						if (havg) *ph2= 0;
					}	// endelse

        } else {
					if (filp->Bd) {
						pb1= pb2 + strlen(pb2);
						strcpy(pb1, GetValStr(vop, false));
						pb2= pb1 + strlen(pb1);
					} // endif Bd

					if (filp->Hv) {
						ph1= ph2 + strlen(ph2);
						strcpy(ph1, GetValStr(vop, false));
						ph2= ph1 + strlen(ph1);
					} // endif Hv

        } // endif CheckCond

				bb |= filp->Bd;
				bh |= filp->Hv;
				filp->Bd = filp->Hv = false;
      } else
        return NULL;

    if (bb)	{
      strcpy(pb1, ")");
			filp->Bd = bb;
		} else
			*pb0= 0;

		if (havg) {
			if (bb && bh && vop == OP_OR) {
				// Cannot or'ed a where clause with a having clause
				bb= bh= 0;
				*pb0 = 0;
				*ph0 = 0;
			} else if (bh)	{
				strcpy(ph1, ")");
				filp->Hv= bh;
			} else
				*ph0 = 0;

		} // endif havg

		if (!bb && !bh)
			return NULL;

  } else if (cond->type() == COND::FUNC_ITEM) {
    unsigned int i;
    bool       iscol, ishav= false, neg= false;
    Item_func *condf= (Item_func *)cond;
    Item*     *args= condf->arguments();

		filp->Bd = filp->Hv = false;

    if (trace)
      htrc("Func type=%d argnum=%d\n", condf->functype(),
                                       condf->argument_count());

    switch (condf->functype()) {
      case Item_func::EQUAL_FUNC:
			case Item_func::EQ_FUNC:     vop= OP_EQ;   break;
			case Item_func::NE_FUNC:     vop= OP_NE;   break;
			case Item_func::LT_FUNC:     vop= OP_LT;   break;
			case Item_func::LE_FUNC:     vop= OP_LE;   break;
			case Item_func::GE_FUNC:     vop= OP_GE;   break;
			case Item_func::GT_FUNC:     vop= OP_GT;   break;
			case Item_func::LIKE_FUNC:
				vop= OP_LIKE; 
				neg = ((Item_func_opt_neg *)condf)->negated;
				break;
			case Item_func::ISNOTNULL_FUNC:
				neg = true;	
				// fall through
			case Item_func::ISNULL_FUNC: vop= OP_NULL; break;
			case Item_func::IN_FUNC:     vop= OP_IN; /* fall through */
      case Item_func::BETWEEN:
        ismul= true;
        neg= ((Item_func_opt_neg *)condf)->negated;
        break;
      default: return NULL;
      } // endswitch functype

    if (condf->argument_count() < 2)
      return NULL;
    else if (ismul && tty == TYPE_AM_WMI)
      return NULL;        // Not supported by WQL

    if (x && (neg || !(vop == OP_EQ || vop == OP_IN || vop == OP_NULL)))
      return NULL;

    for (i= 0; i < condf->argument_count(); i++) {
      if (trace)
        htrc("Argtype(%d)=%d\n", i, args[i]->type());

      if (i >= 2 && !ismul) {
        if (trace)
          htrc("Unexpected arg for vop=%d\n", vop);

        continue;
        } // endif i

      if ((iscol= args[i]->type() == COND::FIELD_ITEM)) {
        const char *fnm;
        ha_field_option_struct *fop;
        Item_field *pField= (Item_field *)args[i];

				// IN and BETWEEN clauses should be col VOP list
				if (i && (x || ismul))
          return NULL;	// IN and BETWEEN clauses should be col VOP list
				else if (pField->field->table != table)
					return NULL;  // Field does not belong to this table
				else if (tty != TYPE_AM_WMI && IsIndexed(pField->field))
					return NULL;  // Will be handled by ReadKey
        else
          fop= GetFieldOptionStruct(pField->field);

        if (fop && fop->special) {
          if (tty == TYPE_AM_TBL && !stricmp(fop->special, "TABID"))
            fnm= "TABID";
          else if (tty == TYPE_AM_PLG)
            fnm= fop->special;
          else
            return NULL;

				} else if (tty == TYPE_AM_TBL) {
					return NULL;
				} else {
					bool h;

					fnm = filp->Chk(pField->field->field_name, &h);

					if (h && i && !ishav)
						return NULL;			// Having should be	col VOP arg
					else
						ishav = h;

				}	// endif's

        if (trace) {
          htrc("Field index=%d\n", pField->field->field_index);
          htrc("Field name=%s\n", pField->field->field_name);
          htrc("Field type=%d\n", pField->field->type());
          htrc("Field_type=%d\n", args[i]->field_type());
          } // endif trace

        strcat((ishav ? havg : body), fnm);
      } else if (args[i]->type() == COND::FUNC_ITEM) {
        if (tty == TYPE_AM_MYSQL) {
          if (!CheckCond(g, filp, args[i]))
            return NULL;

        } else
          return NULL;

      } else {
        char    buff[256];
        String *res, tmp(buff, sizeof(buff), &my_charset_bin);
        Item_basic_constant *pval= (Item_basic_constant *)args[i];
        Item::Type type= args[i]->real_type();

        switch (type) {
          case COND::STRING_ITEM:
          case COND::INT_ITEM:
          case COND::REAL_ITEM:
          case COND::NULL_ITEM:
          case COND::DECIMAL_ITEM:
          case COND::DATE_ITEM:
          case COND::CACHE_ITEM:
            break;
          default:
            return NULL;
          } // endswitch type

        if ((res= pval->val_str(&tmp)) == NULL)
          return NULL;                      // To be clarified

        if (trace)
          htrc("Value=%.*s\n", res->length(), res->ptr());

        // IN and BETWEEN clauses should be col VOP list
        if (!i && (x || ismul))
          return NULL;

        if (!x) {
					const char *p;
					char *s = (ishav) ? havg : body;
					uint	j, k, n;

          // Append the value to the filter
          switch (args[i]->field_type()) {
            case MYSQL_TYPE_TIMESTAMP:
            case MYSQL_TYPE_DATETIME:
              if (tty == TYPE_AM_ODBC) {
                strcat(s, "{ts '");
                strncat(s, res->ptr(), res->length());

                if (res->length() < 19)
                  strcat(s, "1970-01-01 00:00:00" + res->length());

                strcat(s, "'}");
                break;
                } // endif ODBC

							// fall through
            case MYSQL_TYPE_DATE:
              if (tty == TYPE_AM_ODBC) {
                strcat(s, "{d '");
                strcat(strncat(s, res->ptr(), res->length()), "'}");
                break;
                } // endif ODBC

            case MYSQL_TYPE_TIME:
              if (tty == TYPE_AM_ODBC) {
                strcat(s, "{t '");
                strcat(strncat(s, res->ptr(), res->length()), "'}");
                break;
                } // endif ODBC

            case MYSQL_TYPE_VARCHAR:
              if (tty == TYPE_AM_ODBC && i) {
                switch (args[0]->field_type()) {
                  case MYSQL_TYPE_TIMESTAMP:
                  case MYSQL_TYPE_DATETIME:
                    strcat(s, "{ts '");
                    strncat(s, res->ptr(), res->length());

                    if (res->length() < 19)
                      strcat(s, "1970-01-01 00:00:00" + res->length());

                    strcat(s, "'}");
                    break;
                  case MYSQL_TYPE_DATE:
                    strcat(s, "{d '");
                    strncat(s, res->ptr(), res->length());
                    strcat(s, "'}");
                    break;
                  case MYSQL_TYPE_TIME:
                    strcat(s, "{t '");
                    strncat(s, res->ptr(), res->length());
                    strcat(s, "'}");
                    break;
                  default:
										j = strlen(s);
										s[j++] = '\'';
										p = res->ptr();
										n = res->length();

										for (k = 0; k < n; k++) {
											if (p[k] == '\'')
												s[j++] = '\'';

											s[j++] = p[k];
										} // endfor k

										s[j++] = '\'';
										s[j] = 0;
								} // endswitch field type

              } else {
								j = strlen(s);
								s[j++] = '\'';
								p = res->ptr();
								n = res->length();

								for (k = 0; k < n; k++) {
									if (p[k] == '\'')
										s[j++] = '\'';

									s[j++] = p[k];
								} // endfor k

								s[j++] = '\'';
								s[j] = 0;
							} // endif tty

              break;
            default:
              strncat(s, res->ptr(), res->length());
            } // endswitch field type

        } else {
          if (args[i]->field_type() == MYSQL_TYPE_VARCHAR) {
            // Add the command to the list
            PCMD *ncp, cmdp= new(g) CMD(g, (char*)res->c_ptr());

            for (ncp= &filp->Cmds; *ncp; ncp= &(*ncp)->Next) ;

            *ncp= cmdp;
          } else
            return NULL;

        } // endif x

      } // endif's Type

      if (!x) {
				char *s = (ishav) ? havg : body;

				if (!i)
          strcat(s, GetValStr(vop, neg));
        else if (vop == OP_XX && i == 1)
          strcat(s, " AND ");
        else if (vop == OP_IN)
          strcat(s, (i == condf->argument_count() - 1) ? ")" : ",");

        } // endif x

      } // endfor i

			if (x)
				filp->Op = vop;
			else if (ishav)
				filp->Hv = true;
			else
				filp->Bd = true;

  } else {
    if (trace)
      htrc("Unsupported condition\n");

    return NULL;
  } // endif's type

  return filp;
} // end of CheckCond


 /**
   Push condition down to the table handler.

   @param  cond   Condition to be pushed. The condition tree must not be
                  modified by the caller.

   @return
     The 'remainder' condition that caller must use to filter out records.
     NULL means the handler will not return rows that do not match the
     passed condition.

   @note
     CONNECT handles the filtering only for table types that construct
     an SQL or WQL query, but still leaves it to MySQL because only some
     parts of the filter may be relevant.
     The first suballocate finds the position where the string will be
     constructed in the sarea. The second one does make the suballocation
     with the proper length.
 */
const COND *ha_connect::cond_push(const COND *cond)
{
  DBUG_ENTER("ha_connect::cond_push");

  if (tdbp) {
    PGLOBAL& g= xp->g;
    AMT      tty= tdbp->GetAmType();
    bool     x= (tty == TYPE_AM_MYX || tty == TYPE_AM_XDBC);
    bool     b= (tty == TYPE_AM_WMI || tty == TYPE_AM_ODBC  ||
                 tty == TYPE_AM_TBL || tty == TYPE_AM_MYSQL ||
								 tty == TYPE_AM_PLG || tty == TYPE_AM_JDBC  || x);

		// This should never happen but is done to avoid crashing
		try {
			if (b) {
				PCFIL filp;
				int   rc;

				if ((filp = tdbp->GetCondFil()) && tdbp->GetCond() == cond &&
					filp->Idx == active_index && filp->Type == tty)
					goto fin;

				filp = new(g) CONDFIL(active_index, tty);
				rc = filp->Init(g, this);

				if (rc == RC_INFO) {
					filp->Having = (char*)PlugSubAlloc(g, NULL, 256);
					*filp->Having = 0;
				} else if (rc == RC_FX)
					goto fin;

				filp->Body = (char*)PlugSubAlloc(g, NULL, (x) ? 128 : 0);
				*filp->Body = 0;

				if (CheckCond(g, filp, cond)) {
					if (filp->Having && strlen(filp->Having) > 255)
						goto fin;								// Memory collapse

					if (trace)
						htrc("cond_push: %s\n", filp->Body);

					tdbp->SetCond(cond);

					if (!x)
						PlugSubAlloc(g, NULL, strlen(filp->Body) + 1);
					else
						cond = NULL;             // Does this work?

					tdbp->SetCondFil(filp);
				} else if (x && cond)
					tdbp->SetCondFil(filp);   // Wrong filter

			} else if (tdbp->CanBeFiltered()) {
				if (!tdbp->GetCond() || tdbp->GetCond() != cond) {
					tdbp->SetFilter(CondFilter(g, (Item *)cond));

					if (tdbp->GetFilter())
					  tdbp->SetCond(cond);

			  } // endif cond

			}	// endif tty

		} catch (int n) {
			if (trace)
				htrc("Exception %d: %s\n", n, g->Message);
		} catch (const char *msg) {
			strcpy(g->Message, msg);
		} // end catch

	fin:;
  } // endif tdbp

  // Let MySQL do the filtering
  DBUG_RETURN(cond);
} // end of cond_push

/**
  Number of rows in table. It will only be called if
  (table_flags() & (HA_HAS_RECORDS | HA_STATS_RECORDS_IS_EXACT)) != 0
*/
ha_rows ha_connect::records()
{
  if (!valid_info)
    info(HA_STATUS_VARIABLE);

  if (tdbp)
    return stats.records;
  else
    return HA_POS_ERROR;

} // end of records


/**
  Return an error message specific to this handler.

  @param error  error code previously returned by handler
  @param buf    pointer to String where to add error message

  @return
    Returns true if this is a temporary error
*/
bool ha_connect::get_error_message(int error, String* buf)
{
  DBUG_ENTER("ha_connect::get_error_message");

  if (xp && xp->g) {
    PGLOBAL g= xp->g;
    char    msg[3072];         // MAX_STR * 3
    uint    dummy_errors;
    uint32  len= copy_and_convert(msg, strlen(g->Message) * 3,
                               system_charset_info,
                               g->Message, strlen(g->Message),
                               &my_charset_latin1,
                               &dummy_errors);

    if (trace)
      htrc("GEM(%d): len=%u %s\n", error, len, g->Message);

    msg[len]= '\0';
    buf->copy(msg, (uint)strlen(msg), system_charset_info);
  } else
    buf->copy("Cannot retrieve msg", 19, system_charset_info);

  DBUG_RETURN(false);
} // end of get_error_message

/**
  Convert a filename partition name to system
*/
static char *decode(PGLOBAL g, const char *pn)
  {
  char  *buf= (char*)PlugSubAlloc(g, NULL, strlen(pn) + 1);
  uint   dummy_errors;
  uint32 len= copy_and_convert(buf, strlen(pn) + 1,
                               system_charset_info,
                               pn, strlen(pn),
                               &my_charset_filename,
                               &dummy_errors);
  buf[len]= '\0';
  return buf;
  } // end of decode

/**
  @brief
  Used for opening tables. The name will be the name of the file.

  @details
  A table is opened when it needs to be opened; e.g. when a request comes in
  for a SELECT on the table (tables are not open and closed for each request,
  they are cached).

  Called from handler.cc by handler::ha_open(). The server opens all tables by
  calling ha_open() which then calls the handler specific open().

  @note
  For CONNECT no open can be done here because field information is not yet
  updated. >>>>> TO BE CHECKED <<<<<
  (Thread information could be get by using 'ha_thd')

  @see
  handler::ha_open() in handler.cc
*/
int ha_connect::open(const char *name, int mode, uint test_if_locked)
{
  int rc= 0;
  DBUG_ENTER("ha_connect::open");

  if (trace)
     htrc("open: name=%s mode=%d test=%u\n", name, mode, test_if_locked);

  if (!(share= get_share()))
    DBUG_RETURN(1);

  thr_lock_data_init(&share->lock,&lock,NULL);

  // Try to get the user if possible
  xp= GetUser(ha_thd(), xp);
  PGLOBAL g= (xp) ? xp->g : NULL;

  // Try to set the database environment
  if (g) {
    rc= (CntCheckDB(g, this, name)) ? (-2) : 0;

    if (g->Mrr) {
      // This should only happen for the mrr secondary handler
      mrr= true;
      g->Mrr= false;
    } else
      mrr= false;

#if defined(WITH_PARTITION_STORAGE_ENGINE)
    if (table->part_info) {
      if (GetStringOption("Filename") || GetStringOption("Tabname")
                                      || GetStringOption("Connect")) {
        strncpy(partname, decode(g, strrchr(name, '#') + 1), sizeof(partname) - 1);
//      strcpy(partname, table->part_info->curr_part_elem->partition_name);
//      part_id= &table->part_info->full_part_field_set;
      } else       // Inward table
        strncpy(partname, strrchr(name, slash) + 1, sizeof(partname) - 1);

      part_id= &table->part_info->full_part_field_set; // Temporary
      } // endif part_info
#endif   // WITH_PARTITION_STORAGE_ENGINE
  } else
    rc= HA_ERR_INTERNAL_ERROR;

  DBUG_RETURN(rc);
} // end of open

/**
  @brief
  Make the indexes for this table
*/
int ha_connect::optimize(THD* thd, HA_CHECK_OPT*)
{
  int      rc= 0;
  PGLOBAL& g= xp->g;
  PDBUSER  dup= PlgGetUser(g);

	try {
		// Ignore error on the opt file
		dup->Check &= ~CHK_OPT;
		tdbp = GetTDB(g);
		dup->Check |= CHK_OPT;

		if (tdbp && !tdbp->IsRemote()) {
			bool dop = IsTypeIndexable(GetRealType(NULL));
			bool dox = (tdbp->GetDef()->Indexable() == 1);

			if ((rc = ((PTDBASE)tdbp)->ResetTableOpt(g, dop, dox))) {
				if (rc == RC_INFO) {
					push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 0, g->Message);
					rc = 0;
				} else
					rc = HA_ERR_INTERNAL_ERROR;

			} // endif rc

		} else if (!tdbp)
			rc = HA_ERR_INTERNAL_ERROR;

	} catch (int n) {
		if (trace)
			htrc("Exception %d: %s\n", n, g->Message);
		rc = HA_ERR_INTERNAL_ERROR;
	} catch (const char *msg) {
		strcpy(g->Message, msg);
		rc = HA_ERR_INTERNAL_ERROR;
	} // end catch

  return rc;
} // end of optimize

/**
  @brief
  Closes a table.

  @details
  Called from sql_base.cc, sql_select.cc, and table.cc. In sql_select.cc it is
  only used to close up temporary tables or during the process where a
  temporary table is converted over to being a myisam table.

  For sql_base.cc look at close_data_tables().

  @see
  sql_base.cc, sql_select.cc and table.cc
*/
int ha_connect::close(void)
{
  int rc= 0;
  DBUG_ENTER("ha_connect::close");

  // If this is called by a later query, the table may have
  // been already closed and the tdbp is not valid anymore.
  if (tdbp && xp->last_query_id == valid_query_id)
    rc= CloseTable(xp->g);

  DBUG_RETURN(rc);
} // end of close


/**
  @brief
  write_row() inserts a row. No extra() hint is given currently if a bulk load
  is happening. buf() is a byte array of data. You can use the field
  information to extract the data from the native byte array type.

    @details
  Example of this would be:
    @code
  for (Field **field=table->field ; *field ; field++)
  {
    ...
  }
    @endcode

  See ha_tina.cc for an example of extracting all of the data as strings.
  ha_berekly.cc has an example of how to store it intact by "packing" it
  for ha_berkeley's own native storage type.

  See the note for update_row() on auto_increments and timestamps. This
  case also applies to write_row().

  Called from item_sum.cc, item_sum.cc, sql_acl.cc, sql_insert.cc,
  sql_insert.cc, sql_select.cc, sql_table.cc, sql_udf.cc, and sql_update.cc.

    @see
  item_sum.cc, item_sum.cc, sql_acl.cc, sql_insert.cc,
  sql_insert.cc, sql_select.cc, sql_table.cc, sql_udf.cc and sql_update.cc
*/
int ha_connect::write_row(uchar *buf)
{
  int      rc= 0;
  PGLOBAL& g= xp->g;
  DBUG_ENTER("ha_connect::write_row");

  // This is not tested yet
  if (xmod == MODE_ALTER) {
    if (IsPartitioned() && GetStringOption("Filename", NULL))
      // Why does this happen now that check_if_supported_inplace_alter is called?
      DBUG_RETURN(0);     // Alter table on an outward partition table

    xmod= MODE_INSERT;
  } else if (xmod == MODE_ANY)
    DBUG_RETURN(0);       // Probably never met

  // Open the table if it was not opened yet (locked)
  if (!IsOpened() || xmod != tdbp->GetMode()) {
    if (IsOpened())
      CloseTable(g);

    if ((rc= OpenTable(g)))
      DBUG_RETURN(rc);

    } // endif isopened

#if 0                // AUTO_INCREMENT NIY
  if (table->next_number_field && buf == table->record[0]) {
    int error;

    if ((error= update_auto_increment()))
      return error;

    } // endif nex_number_field
#endif // 0

  // Set column values from the passed pseudo record
  if ((rc= ScanRecord(g, buf)))
    DBUG_RETURN(rc);

  // Return result code from write operation
  if (CntWriteRow(g, tdbp)) {
    DBUG_PRINT("write_row", ("%s", g->Message));
    htrc("write_row: %s\n", g->Message);
    rc= HA_ERR_INTERNAL_ERROR;
  } else                // Table is modified
    nox= false;         // Indexes to be remade

  DBUG_RETURN(rc);
} // end of write_row


/**
  @brief
  Yes, update_row() does what you expect, it updates a row. old_data will have
  the previous row record in it, while new_data will have the newest data in it.
  Keep in mind that the server can do updates based on ordering if an ORDER BY
  clause was used. Consecutive ordering is not guaranteed.

    @details
  Currently new_data will not have an updated auto_increament record, or
  and updated timestamp field. You can do these for example by doing:
    @code
  if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_UPDATE)
    table->timestamp_field->set_time();
  if (table->next_number_field && record == table->record[0])
    update_auto_increment();
    @endcode

  Called from sql_select.cc, sql_acl.cc, sql_update.cc, and sql_insert.cc.

    @see
  sql_select.cc, sql_acl.cc, sql_update.cc and sql_insert.cc
*/
int ha_connect::update_row(const uchar *old_data, uchar *new_data)
{
  int      rc= 0;
  PGLOBAL& g= xp->g;
  DBUG_ENTER("ha_connect::update_row");

  if (trace > 1)
    htrc("update_row: old=%s new=%s\n", old_data, new_data);

  // Check values for possible change in indexed column
  if ((rc= CheckRecord(g, old_data, new_data)))
    DBUG_RETURN(rc);

  if (CntUpdateRow(g, tdbp)) {
    DBUG_PRINT("update_row", ("%s", g->Message));
    htrc("update_row CONNECT: %s\n", g->Message);
    rc= HA_ERR_INTERNAL_ERROR;
  } else
    nox= false;               // Table is modified

  DBUG_RETURN(rc);
} // end of update_row


/**
  @brief
  This will delete a row. buf will contain a copy of the row to be deleted.
  The server will call this right after the current row has been called (from
  either a previous rnd_nexT() or index call).

  @details
  If you keep a pointer to the last row or can access a primary key it will
  make doing the deletion quite a bit easier. Keep in mind that the server does
  not guarantee consecutive deletions. ORDER BY clauses can be used.

  Called in sql_acl.cc and sql_udf.cc to manage internal table
  information.  Called in sql_delete.cc, sql_insert.cc, and
  sql_select.cc. In sql_select it is used for removing duplicates
  while in insert it is used for REPLACE calls.

  @see
  sql_acl.cc, sql_udf.cc, sql_delete.cc, sql_insert.cc and sql_select.cc
*/
int ha_connect::delete_row(const uchar *)
{
  int rc= 0;
  DBUG_ENTER("ha_connect::delete_row");

  if (CntDeleteRow(xp->g, tdbp, false)) {
    rc= HA_ERR_INTERNAL_ERROR;
    htrc("delete_row CONNECT: %s\n", xp->g->Message);
  } else
    nox= false;             // To remake indexes

  DBUG_RETURN(rc);
} // end of delete_row


/****************************************************************************/
/*  We seem to come here at the begining of an index use.                   */
/****************************************************************************/
int ha_connect::index_init(uint idx, bool sorted)
{
  int rc;
  PGLOBAL& g= xp->g;
  DBUG_ENTER("index_init");

  if (trace)
    htrc("index_init: this=%p idx=%u sorted=%d\n", this, idx, sorted);

  if (GetIndexType(GetRealType()) == 2) {
    if (xmod == MODE_READ)
      // This is a remote index
      xmod= MODE_READX;

    if (!(rc= rnd_init(0))) {
//    if (xmod == MODE_READX) {
        active_index= idx;
        indexing= IsUnique(idx) ? 1 : 2;
//    } else {
//      active_index= MAX_KEY;
//      indexing= 0;
//    } // endif xmod

      } //endif rc

    DBUG_RETURN(rc);
    } // endif index type

  if ((rc= rnd_init(0)))
    DBUG_RETURN(rc);

  if (locked == 2) {
    // Indexes are not updated in lock write mode
    active_index= MAX_KEY;
    indexing= 0;
    DBUG_RETURN(0);
    } // endif locked

  indexing= CntIndexInit(g, tdbp, (signed)idx, sorted);

  if (indexing <= 0) {
    DBUG_PRINT("index_init", ("%s", g->Message));
    htrc("index_init CONNECT: %s\n", g->Message);
    active_index= MAX_KEY;
    rc= HA_ERR_INTERNAL_ERROR;
  } else if (tdbp->GetKindex()) {
    if (((PTDBDOX)tdbp)->To_Kindex->GetNum_K()) {
      if (tdbp->GetFtype() != RECFM_NAF)
        ((PTDBDOX)tdbp)->GetTxfp()->ResetBuffer(g);

      active_index= idx;
//  } else {        // Void table
//    active_index= MAX_KEY;
//    indexing= 0;
    } // endif Num

    rc= 0;
  } // endif indexing

  if (trace)
    htrc("index_init: rc=%d indexing=%d active_index=%d\n",
            rc, indexing, active_index);

  DBUG_RETURN(rc);
} // end of index_init

/****************************************************************************/
/*  We seem to come here at the end of an index use.                        */
/****************************************************************************/
int ha_connect::index_end()
{
  DBUG_ENTER("index_end");
  active_index= MAX_KEY;
  ds_mrr.dsmrr_close();
  DBUG_RETURN(rnd_end());
} // end of index_end


/****************************************************************************/
/*  This is internally called by all indexed reading functions.             */
/****************************************************************************/
int ha_connect::ReadIndexed(uchar *buf, OPVAL op, const key_range *kr) 
{
  int rc;

//statistic_increment(ha_read_key_count, &LOCK_status);

  switch (CntIndexRead(xp->g, tdbp, op, kr, mrr)) {
    case RC_OK:
      xp->fnd++;
      rc= MakeRecord((char*)buf);
      break;
    case RC_EF:         // End of file
      rc= HA_ERR_END_OF_FILE;
      break;
    case RC_NF:         // Not found
      xp->nfd++;
      rc= (op == OP_SAME) ? HA_ERR_END_OF_FILE : HA_ERR_KEY_NOT_FOUND;
      break;
    default:          // Read error
      DBUG_PRINT("ReadIndexed", ("%s", xp->g->Message));
      htrc("ReadIndexed: %s\n", xp->g->Message);
      rc= HA_ERR_INTERNAL_ERROR;
      break;
    } // endswitch RC

  if (trace > 1)
    htrc("ReadIndexed: op=%d rc=%d\n", op, rc);

  table->status= (rc == RC_OK) ? 0 : STATUS_NOT_FOUND;
  return rc;
} // end of ReadIndexed


#ifdef NOT_USED
/**
  @brief
  Positions an index cursor to the index specified in the handle. Fetches the
  row if available. If the key value is null, begin at the first key of the
  index.
*/
int ha_connect::index_read_map(uchar *buf, const uchar *key,
                               key_part_map keypart_map __attribute__((unused)),
                               enum ha_rkey_function find_flag
                               __attribute__((unused)))
{
  DBUG_ENTER("ha_connect::index_read");
  DBUG_RETURN(HA_ERR_WRONG_COMMAND);
}
#endif // NOT_USED


/****************************************************************************/
/*  This is called by handler::index_read_map.                              */
/****************************************************************************/
int ha_connect::index_read(uchar * buf, const uchar * key, uint key_len,
                           enum ha_rkey_function find_flag)
{
  int rc;
  OPVAL op= OP_XX;
  DBUG_ENTER("ha_connect::index_read");

  switch(find_flag) {
    case HA_READ_KEY_EXACT:   op= OP_EQ; break;
    case HA_READ_AFTER_KEY:   op= OP_GT; break;
    case HA_READ_KEY_OR_NEXT: op= OP_GE; break;
    default: DBUG_RETURN(-1);      break;
    } // endswitch find_flag

  if (trace > 1)
    htrc("%p index_read: op=%d\n", this, op);

  if (indexing > 0) {
		start_key.key= key;
		start_key.length= key_len;
		start_key.flag= find_flag;
		start_key.keypart_map= 0;

    rc= ReadIndexed(buf, op, &start_key);

    if (rc == HA_ERR_INTERNAL_ERROR) {
      nox= true;                  // To block making indexes
      abort= true;                // Don't rename temp file
      } // endif rc

  } else
    rc= HA_ERR_INTERNAL_ERROR;  // HA_ERR_KEY_NOT_FOUND ?

  DBUG_RETURN(rc);
} // end of index_read


/**
  @brief
  Used to read forward through the index.
*/
int ha_connect::index_next(uchar *buf)
{
  int rc;
  DBUG_ENTER("ha_connect::index_next");
  //statistic_increment(ha_read_next_count, &LOCK_status);

  if (indexing > 0)
    rc= ReadIndexed(buf, OP_NEXT);
  else if (!indexing)
    rc= rnd_next(buf);
  else
    rc= HA_ERR_INTERNAL_ERROR;

  DBUG_RETURN(rc);
} // end of index_next


/**
  @brief
  Used to read backwards through the index.
*/
int ha_connect::index_prev(uchar *buf)
{
  DBUG_ENTER("ha_connect::index_prev");
  int rc;

  if (indexing > 0) {
    rc= ReadIndexed(buf, OP_PREV);
  } else
    rc= HA_ERR_WRONG_COMMAND;

  DBUG_RETURN(rc);
} // end of index_prev


/**
  @brief
  index_first() asks for the first key in the index.

    @details
  Called from opt_range.cc, opt_sum.cc, sql_handler.cc, and sql_select.cc.

    @see
  opt_range.cc, opt_sum.cc, sql_handler.cc and sql_select.cc
*/
int ha_connect::index_first(uchar *buf)
{
  int rc;
  DBUG_ENTER("ha_connect::index_first");

  if (indexing > 0)
    rc= ReadIndexed(buf, OP_FIRST);
  else if (indexing < 0)
    rc= HA_ERR_INTERNAL_ERROR;
  else if (CntRewindTable(xp->g, tdbp)) {
    table->status= STATUS_NOT_FOUND;
    rc= HA_ERR_INTERNAL_ERROR;
  } else
    rc= rnd_next(buf);

  DBUG_RETURN(rc);
} // end of index_first


/**
  @brief
  index_last() asks for the last key in the index.

    @details
  Called from opt_range.cc, opt_sum.cc, sql_handler.cc, and sql_select.cc.

    @see
  opt_range.cc, opt_sum.cc, sql_handler.cc and sql_select.cc
*/
int ha_connect::index_last(uchar *buf)
{
  DBUG_ENTER("ha_connect::index_last");
  int rc;

  if (indexing <= 0) {
    rc= HA_ERR_INTERNAL_ERROR;
  } else
    rc= ReadIndexed(buf, OP_LAST);

  DBUG_RETURN(rc);
}


/****************************************************************************/
/*  This is called to get more rows having the same index value.            */
/****************************************************************************/
//t ha_connect::index_next_same(uchar *buf, const uchar *key, uint keylen)
int ha_connect::index_next_same(uchar *buf, const uchar *, uint)
{
  int rc;
  DBUG_ENTER("ha_connect::index_next_same");
//statistic_increment(ha_read_next_count, &LOCK_status);

  if (!indexing)
    rc= rnd_next(buf);
  else if (indexing > 0)
    rc= ReadIndexed(buf, OP_SAME);
  else
    rc= HA_ERR_INTERNAL_ERROR;

  DBUG_RETURN(rc);
} // end of index_next_same


/**
  @brief
  rnd_init() is called when the system wants the storage engine to do a table
  scan. See the example in the introduction at the top of this file to see when
  rnd_init() is called.

    @details
  Called from filesort.cc, records.cc, sql_handler.cc, sql_select.cc, sql_table.cc,
  and sql_update.cc.

    @note
  We always call open and extern_lock/start_stmt before comming here.

    @see
  filesort.cc, records.cc, sql_handler.cc, sql_select.cc, sql_table.cc and sql_update.cc
*/
int ha_connect::rnd_init(bool scan)
{
  PGLOBAL g= ((table && table->in_use) ? GetPlug(table->in_use, xp) :
              (xp) ? xp->g : NULL);
  DBUG_ENTER("ha_connect::rnd_init");

  // This is not tested yet
  if (xmod == MODE_ALTER) {
    xmod= MODE_READ;
    alter= 1;
    } // endif xmod

  if (trace)
    htrc("rnd_init: this=%p scan=%d xmod=%d alter=%d\n",
            this, scan, xmod, alter);

  if (!g || !table || xmod == MODE_INSERT)
    DBUG_RETURN(HA_ERR_INITIALIZATION);

  // Do not close the table if it was opened yet (locked?)
  if (IsOpened()) {
    if (IsPartitioned() && xmod != MODE_INSERT)
      if (CheckColumnList(g)) // map can have been changed
        DBUG_RETURN(HA_ERR_INTERNAL_ERROR);

    if (tdbp->OpenDB(g))      // Rewind table
      DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
    else
      DBUG_RETURN(0);

  } else if (xp->CheckQuery(valid_query_id))
    tdbp= NULL;       // Not valid anymore

  // When updating, to avoid skipped update, force the table
  // handler to retrieve write-only fields to be able to compare
  // records and detect data change.
  if (xmod == MODE_UPDATE)
    bitmap_union(table->read_set, table->write_set);

  if (OpenTable(g, xmod == MODE_DELETE))
    DBUG_RETURN(HA_ERR_INITIALIZATION);

  xp->nrd= xp->fnd= xp->nfd= 0;
  xp->tb1= my_interval_timer();
  DBUG_RETURN(0);
} // end of rnd_init

/**
  @brief
  Not described.

  @note
  The previous version said:
  Stop scanning of table. Note that this may be called several times during
  execution of a sub select.
  =====> This has been moved to external lock to avoid closing subselect tables.
*/
int ha_connect::rnd_end()
{
  int rc= 0;
  DBUG_ENTER("ha_connect::rnd_end");

  // If this is called by a later query, the table may have
  // been already closed and the tdbp is not valid anymore.
//  if (tdbp && xp->last_query_id == valid_query_id)
//    rc= CloseTable(xp->g);

  ds_mrr.dsmrr_close();
  DBUG_RETURN(rc);
} // end of rnd_end


/**
  @brief
  This is called for each row of the table scan. When you run out of records
  you should return HA_ERR_END_OF_FILE. Fill buff up with the row information.
  The Field structure for the table is the key to getting data into buf
  in a manner that will allow the server to understand it.

    @details
  Called from filesort.cc, records.cc, sql_handler.cc, sql_select.cc, sql_table.cc,
  and sql_update.cc.

    @see
  filesort.cc, records.cc, sql_handler.cc, sql_select.cc, sql_table.cc and sql_update.cc
*/
int ha_connect::rnd_next(uchar *buf)
{
  int rc;
  DBUG_ENTER("ha_connect::rnd_next");
//statistic_increment(ha_read_rnd_next_count, &LOCK_status);

  if (tdbp->GetMode() == MODE_ANY) {
    // We will stop on next read
    if (!stop) {
      stop= true;
      DBUG_RETURN(RC_OK);
    } else
      DBUG_RETURN(HA_ERR_END_OF_FILE);

    } // endif Mode

  switch (CntReadNext(xp->g, tdbp)) {
    case RC_OK:
      rc= MakeRecord((char*)buf);
      break;
    case RC_EF:         // End of file
      rc= HA_ERR_END_OF_FILE;
      break;
    case RC_NF:         // Not found
      rc= HA_ERR_RECORD_DELETED;
      break;
    default:            // Read error
      htrc("rnd_next CONNECT: %s\n", xp->g->Message);
      rc= (records()) ? HA_ERR_INTERNAL_ERROR : HA_ERR_END_OF_FILE;
      break;
    } // endswitch RC

  if (trace > 1 && (rc || !(xp->nrd++ % 16384))) {
    ulonglong tb2= my_interval_timer();
    double elapsed= (double) (tb2 - xp->tb1) / 1000000000ULL;
    DBUG_PRINT("rnd_next", ("rc=%d nrd=%u fnd=%u nfd=%u sec=%.3lf\n",
                             rc, (uint)xp->nrd, (uint)xp->fnd,
                             (uint)xp->nfd, elapsed));
    htrc("rnd_next: rc=%d nrd=%u fnd=%u nfd=%u sec=%.3lf\n",
                             rc, (uint)xp->nrd, (uint)xp->fnd,
                             (uint)xp->nfd, elapsed);
    xp->tb1= tb2;
    xp->fnd= xp->nfd= 0;
    } // endif nrd

  table->status= (!rc) ? 0 : STATUS_NOT_FOUND;
  DBUG_RETURN(rc);
} // end of rnd_next


/**
  @brief
  position() is called after each call to rnd_next() if the data needs
  to be ordered. You can do something like the following to store
  the position:
    @code
  my_store_ptr(ref, ref_length, current_position);
    @endcode

    @details
  The server uses ref to store data. ref_length in the above case is
  the size needed to store current_position. ref is just a byte array
  that the server will maintain. If you are using offsets to mark rows, then
  current_position should be the offset. If it is a primary key like in
  BDB, then it needs to be a primary key.

  Called from filesort.cc, sql_select.cc, sql_delete.cc, and sql_update.cc.

    @see
  filesort.cc, sql_select.cc, sql_delete.cc and sql_update.cc
*/
void ha_connect::position(const uchar *)
{
  DBUG_ENTER("ha_connect::position");
  my_store_ptr(ref, ref_length, (my_off_t)tdbp->GetRecpos());

  if (trace > 1)
    htrc("position: pos=%d\n", tdbp->GetRecpos());

  DBUG_VOID_RETURN;
} // end of position


/**
  @brief
  This is like rnd_next, but you are given a position to use
  to determine the row. The position will be of the type that you stored in
  ref. You can use my_get_ptr(pos,ref_length) to retrieve whatever key
  or position you saved when position() was called.

    @details
  Called from filesort.cc, records.cc, sql_insert.cc, sql_select.cc, and sql_update.cc.

    @note
  Is this really useful? It was never called even when sorting.

    @see
  filesort.cc, records.cc, sql_insert.cc, sql_select.cc and sql_update.cc
*/
int ha_connect::rnd_pos(uchar *buf, uchar *pos)
{
  int     rc;
//PTDBASE tp= (PTDBASE)tdbp;
  DBUG_ENTER("ha_connect::rnd_pos");

  if (!tdbp->SetRecpos(xp->g, (int)my_get_ptr(pos, ref_length))) {
    if (trace)
      htrc("rnd_pos: %d\n", tdbp->GetRecpos());

    tdbp->SetFilter(NULL);
    rc= rnd_next(buf);
	} else {
		PGLOBAL g = GetPlug((table) ? table->in_use : NULL, xp);
		strcpy(g->Message, "Not supported by this table type");
		my_message(ER_ILLEGAL_HA, g->Message, MYF(0));
		rc= HA_ERR_INTERNAL_ERROR;
	}	// endif SetRecpos

  DBUG_RETURN(rc);
} // end of rnd_pos


/**
  @brief
  ::info() is used to return information to the optimizer. See my_base.h for
  the complete description.

    @details
  Currently this table handler doesn't implement most of the fields really needed.
  SHOW also makes use of this data.

  You will probably want to have the following in your code:
    @code
  if (records < 2)
    records= 2;
    @endcode
  The reason is that the server will optimize for cases of only a single
  record. If, in a table scan, you don't know the number of records, it
  will probably be better to set records to two so you can return as many
  records as you need. Along with records, a few more variables you may wish
  to set are:
    records
    deleted
    data_file_length
    index_file_length
    delete_length
    check_time
  Take a look at the public variables in handler.h for more information.

  Called in filesort.cc, ha_heap.cc, item_sum.cc, opt_sum.cc, sql_delete.cc,
  sql_delete.cc, sql_derived.cc, sql_select.cc, sql_select.cc, sql_select.cc,
  sql_select.cc, sql_select.cc, sql_show.cc, sql_show.cc, sql_show.cc, sql_show.cc,
  sql_table.cc, sql_union.cc, and sql_update.cc.

    @see
  filesort.cc, ha_heap.cc, item_sum.cc, opt_sum.cc, sql_delete.cc, sql_delete.cc,
  sql_derived.cc, sql_select.cc, sql_select.cc, sql_select.cc, sql_select.cc,
  sql_select.cc, sql_show.cc, sql_show.cc, sql_show.cc, sql_show.cc, sql_table.cc,
  sql_union.cc and sql_update.cc
*/
int ha_connect::info(uint flag)
{
  bool    pure= false;
  PGLOBAL g= GetPlug((table) ? table->in_use : NULL, xp);

  DBUG_ENTER("ha_connect::info");

	if (!g) {
		my_message(ER_UNKNOWN_ERROR, "Cannot get g pointer", MYF(0));
		DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
	}	// endif g

	if (trace)
    htrc("%p In info: flag=%u valid_info=%d\n", this, flag, valid_info);

  // tdbp must be available to get updated info
  if (xp->CheckQuery(valid_query_id) || !tdbp) {
    PDBUSER dup= PlgGetUser(g);
    PCATLG  cat= (dup) ? dup->Catalog : NULL;

    if (xmod == MODE_ANY || xmod == MODE_ALTER) {
      // Pure info, not a query
      pure= true;
      xp->CheckCleanup(xmod == MODE_ANY && valid_query_id == 0);
      } // endif xmod

    // This is necessary for getting file length
		if (table) {
			if (SetDataPath(g, table->s->db.str)) {
				my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
				DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
			}	// endif SetDataPath

		} else
      DBUG_RETURN(HA_ERR_INTERNAL_ERROR);       // Should never happen

		if (!(tdbp = GetTDB(g))) {
			my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
			DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
		} // endif tdbp

    valid_info = false;
    } // endif tdbp

  if (!valid_info) {
    valid_info= CntInfo(g, tdbp, &xinfo);

    if (((signed)xinfo.records) < 0)
      DBUG_RETURN(HA_ERR_INITIALIZATION);  // Error in Cardinality

    } // endif valid_info

  if (flag & HA_STATUS_VARIABLE) {
    stats.records= xinfo.records;
    stats.deleted= 0;
    stats.data_file_length= xinfo.data_file_length;
    stats.index_file_length= 0;
    stats.delete_length= 0;
    stats.check_time= 0;
    stats.mean_rec_length= xinfo.mean_rec_length;
    } // endif HA_STATUS_VARIABLE

  if (flag & HA_STATUS_CONST) {
    // This is imported from the previous handler and must be reconsidered
    stats.max_data_file_length= 4294967295LL;
    stats.max_index_file_length= 4398046510080LL;
    stats.create_time= 0;
    data_file_name= xinfo.data_file_name;
    index_file_name= NULL;
//  sortkey= (uint) - 1;           // Table is not sorted
    ref_length= sizeof(int);      // Pointer size to row
    table->s->db_options_in_use= 03;
    stats.block_size= 1024;
    table->s->keys_in_use.set_prefix(table->s->keys);
    table->s->keys_for_keyread= table->s->keys_in_use;
//  table->s->keys_for_keyread.subtract(table->s->read_only_keys);
    table->s->db_record_offset= 0;
    } // endif HA_STATUS_CONST

  if (flag & HA_STATUS_ERRKEY) {
    errkey= 0;
    } // endif HA_STATUS_ERRKEY

  if (flag & HA_STATUS_TIME)
    stats.update_time= 0;

  if (flag & HA_STATUS_AUTO)
    stats.auto_increment_value= 1;

  if (tdbp && pure)
    CloseTable(g);        // Not used anymore

  DBUG_RETURN(0);
} // end of info


/**
  @brief
  extra() is called whenever the server wishes to send a hint to
  the storage engine. The myisam engine implements the most hints.
  ha_innodb.cc has the most exhaustive list of these hints.

  @note
  This is not yet implemented for CONNECT.

  @see
  ha_innodb.cc
*/
int ha_connect::extra(enum ha_extra_function /*operation*/)
{
  DBUG_ENTER("ha_connect::extra");
  DBUG_RETURN(0);
} // end of extra


/**
  @brief
  Used to delete all rows in a table, including cases of truncate and cases where
  the optimizer realizes that all rows will be removed as a result of an SQL statement.

    @details
  Called from item_sum.cc by Item_func_group_concat::clear(),
  Item_sum_count_distinct::clear(), and Item_func_group_concat::clear().
  Called from sql_delete.cc by mysql_delete().
  Called from sql_select.cc by JOIN::reinit().
  Called from sql_union.cc by st_select_lex_unit::exec().

    @see
  Item_func_group_concat::clear(), Item_sum_count_distinct::clear() and
  Item_func_group_concat::clear() in item_sum.cc;
  mysql_delete() in sql_delete.cc;
  JOIN::reinit() in sql_select.cc and
  st_select_lex_unit::exec() in sql_union.cc.
*/
int ha_connect::delete_all_rows()
{
  int     rc= 0;
  PGLOBAL g= xp->g;
  DBUG_ENTER("ha_connect::delete_all_rows");

  if (tdbp && tdbp->GetUse() == USE_OPEN &&
      tdbp->GetAmType() != TYPE_AM_XML &&
      tdbp->GetFtype() != RECFM_NAF)
    // Close and reopen the table so it will be deleted
    rc= CloseTable(g);

  if (!(rc= OpenTable(g))) {
    if (CntDeleteRow(g, tdbp, true)) {
      htrc("%s\n", g->Message);
      rc= HA_ERR_INTERNAL_ERROR;
    } else
      nox= false;

    } // endif rc

  DBUG_RETURN(rc);
} // end of delete_all_rows


bool ha_connect::check_privileges(THD *thd, PTOS options, char *dbn, bool quick)
{
  const char *db= (dbn && *dbn) ? dbn : NULL;
  TABTYPE     type=GetRealType(options);

  switch (type) {
    case TAB_UNDEF:
//  case TAB_CATLG:
    case TAB_PLG:
    case TAB_JCT:
    case TAB_DMY:
    case TAB_NIY:
      my_printf_error(ER_UNKNOWN_ERROR,
                      "Unsupported table type %s", MYF(0), options->type);
      return true;

    case TAB_DOS:
    case TAB_FIX:
    case TAB_BIN:
    case TAB_CSV:
    case TAB_FMT:
    case TAB_DBF:
    case TAB_XML:
    case TAB_INI:
    case TAB_VEC:
    case TAB_JSON:
			if (options->filename && *options->filename) {
				if (!quick) {
					char path[FN_REFLEN], dbpath[FN_REFLEN];

 					strcpy(dbpath, mysql_real_data_home);

					if (db)
#if defined(__WIN__)
						strcat(strcat(dbpath, db), "\\");
#else   // !__WIN__
						strcat(strcat(dbpath, db), "/");
#endif  // !__WIN__

					(void)fn_format(path, options->filename, dbpath, "",
						MY_RELATIVE_PATH | MY_UNPACK_FILENAME);

					if (!is_secure_file_path(path)) {
						my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--secure-file-priv");
						return true;
					} // endif path
				}
			} else
        return false;

      // check FILE_ACL
      // fall through
    case TAB_ODBC:
		case TAB_JDBC:
		case TAB_MYSQL:
		case TAB_MONGO:
		case TAB_DIR:
    case TAB_MAC:
    case TAB_WMI:
		case TAB_ZIP:
		case TAB_OEM:
#ifdef NO_EMBEDDED_ACCESS_CHECKS
      return false;
#endif
      /*
        If table or table->mdl_ticket is NULL - it's a DLL, e.g. CREATE TABLE.
        if the table has an MDL_EXCLUSIVE lock - it's a DDL too, e.g. the
        insert step of CREATE ... SELECT.

        Otherwise it's a DML, the table was normally opened, locked,
        privilege were already checked, and table->grant.privilege is set.
        With SQL SECURITY DEFINER, table->grant.privilege has definer's privileges.

        Unless we're in prelocking mode, in this case table->grant.privilege
        is only checked in start_stmt(), not in external_lock().
      */
      if (!table || !table->mdl_ticket || table->mdl_ticket->get_type() == MDL_EXCLUSIVE)
        return check_access(thd, FILE_ACL, db, NULL, NULL, 0, 0);
      if ((!quick && thd->lex->requires_prelocking()) || table->grant.privilege & FILE_ACL)
        return false;
      status_var_increment(thd->status_var.access_denied_errors);
      my_error(access_denied_error_code(thd->password), MYF(0),
               thd->security_ctx->priv_user, thd->security_ctx->priv_host,
               (thd->password ?  ER(ER_YES) : ER(ER_NO)));
      return true;

    // This is temporary until a solution is found
    case TAB_TBL:
    case TAB_XCL:
    case TAB_PRX:
    case TAB_OCCUR:
    case TAB_PIVOT:
    case TAB_VIR:
      return false;
    } // endswitch type

  my_printf_error(ER_UNKNOWN_ERROR, "check_privileges failed", MYF(0));
  return true;
} // end of check_privileges

// Check that two indexes are equivalent
bool ha_connect::IsSameIndex(PIXDEF xp1, PIXDEF xp2)
{
  bool   b= true;
  PKPDEF kp1, kp2;

  if (stricmp(xp1->Name, xp2->Name))
    b= false;
  else if (xp1->Nparts  != xp2->Nparts  ||
           xp1->MaxSame != xp2->MaxSame ||
           xp1->Unique  != xp2->Unique)
    b= false;
  else for (kp1= xp1->ToKeyParts, kp2= xp2->ToKeyParts;
            b && (kp1 || kp2);
            kp1= kp1->Next, kp2= kp2->Next)
    if (!kp1 || !kp2)
      b= false;
    else if (stricmp(kp1->Name, kp2->Name))
      b= false;
    else if (kp1->Klen != kp2->Klen)
      b= false;

  return b;
} // end of IsSameIndex

MODE ha_connect::CheckMode(PGLOBAL g, THD *thd, 
	                         MODE newmode, bool *chk, bool *cras)
{
#if defined(DEVELOPMENT)
	if (true) {
#else
  if (trace) {
#endif
    LEX_STRING *query_string= thd_query_string(thd);
    htrc("%p check_mode: cmdtype=%d\n", this, thd_sql_command(thd));
    htrc("Cmd=%.*s\n", (int) query_string->length, query_string->str);
    } // endif trace

  // Next code is temporarily replaced until sql_command is set
  stop= false;

  if (newmode == MODE_WRITE) {
    switch (thd_sql_command(thd)) {
      case SQLCOM_LOCK_TABLES:
        locked= 2; // fall through
      case SQLCOM_CREATE_TABLE:
      case SQLCOM_INSERT:
      case SQLCOM_LOAD:
      case SQLCOM_INSERT_SELECT:
        newmode= MODE_INSERT;
        break;
//    case SQLCOM_REPLACE:
//    case SQLCOM_REPLACE_SELECT:
//      newmode= MODE_UPDATE;               // To be checked
//      break;
      case SQLCOM_DELETE:
      case SQLCOM_DELETE_MULTI:
      case SQLCOM_TRUNCATE:
        newmode= MODE_DELETE;
        break;
      case SQLCOM_UPDATE:
      case SQLCOM_UPDATE_MULTI:
        newmode= MODE_UPDATE;
        break;
      case SQLCOM_SELECT:
      case SQLCOM_OPTIMIZE:
        newmode= MODE_READ;
        break;
      case SQLCOM_FLUSH:
        locked= 0;
      case SQLCOM_DROP_TABLE:
      case SQLCOM_RENAME_TABLE:
        newmode= MODE_ANY;
        break;
      case SQLCOM_CREATE_VIEW:
      case SQLCOM_DROP_VIEW:
        newmode= MODE_ANY;
        break;
      case SQLCOM_ALTER_TABLE:
        newmode= MODE_ALTER;
        break;
      case SQLCOM_DROP_INDEX:
      case SQLCOM_CREATE_INDEX:
//      if (!IsPartitioned()) {
          newmode= MODE_ANY;
          break;
//        } // endif partitioned

      default:
        htrc("Unsupported sql_command=%d\n", thd_sql_command(thd));
        strcpy(g->Message, "CONNECT Unsupported command");
        my_message(ER_NOT_ALLOWED_COMMAND, g->Message, MYF(0));
        newmode= MODE_ERROR;
        break;
      } // endswitch newmode

  } else if (newmode == MODE_READ) {
    switch (thd_sql_command(thd)) {
      case SQLCOM_CREATE_TABLE:
        *chk= true;
        *cras= true;
      case SQLCOM_INSERT:
      case SQLCOM_LOAD:
      case SQLCOM_INSERT_SELECT:
//    case SQLCOM_REPLACE:
//    case SQLCOM_REPLACE_SELECT:
      case SQLCOM_DELETE:
      case SQLCOM_DELETE_MULTI:
      case SQLCOM_TRUNCATE:
      case SQLCOM_UPDATE:
      case SQLCOM_UPDATE_MULTI:
      case SQLCOM_SELECT:
      case SQLCOM_OPTIMIZE:
      case SQLCOM_SET_OPTION:
        break;
      case SQLCOM_LOCK_TABLES:
        locked= 1;
        break;
      case SQLCOM_DROP_TABLE:
      case SQLCOM_RENAME_TABLE:
        newmode= MODE_ANY;
        break;
      case SQLCOM_CREATE_VIEW:
      case SQLCOM_DROP_VIEW:
        newmode= MODE_ANY;
        break;
      case SQLCOM_ALTER_TABLE:
        *chk= true;
        newmode= MODE_ALTER;
        break;
      case SQLCOM_DROP_INDEX:
      case SQLCOM_CREATE_INDEX:
//      if (!IsPartitioned()) {
          *chk= true;
          newmode= MODE_ANY;
          break;
//        } // endif partitioned

			case SQLCOM_CHECK: // TODO implement it
			case SQLCOM_END:	 // Met in procedures: IF(EXISTS(SELECT...
				newmode= MODE_READ;
        break;
      default:
        htrc("Unsupported sql_command=%d\n", thd_sql_command(thd));
        strcpy(g->Message, "CONNECT Unsupported command");
        my_message(ER_NOT_ALLOWED_COMMAND, g->Message, MYF(0));
        newmode= MODE_ERROR;
        break;
      } // endswitch newmode

  } // endif's newmode

  if (trace)
    htrc("New mode=%d\n", newmode);

  return newmode;
} // end of check_mode

int ha_connect::start_stmt(THD *thd, thr_lock_type lock_type)
{
  int     rc= 0;
  bool    chk=false, cras= false;
  MODE    newmode;
  PGLOBAL g= GetPlug(thd, xp);
  DBUG_ENTER("ha_connect::start_stmt");

  if (check_privileges(thd, GetTableOptionStruct(), table->s->db.str, true))
    DBUG_RETURN(HA_ERR_INTERNAL_ERROR);

  // Action will depend on lock_type
  switch (lock_type) {
    case TL_WRITE_ALLOW_WRITE:
    case TL_WRITE_CONCURRENT_INSERT:
    case TL_WRITE_DELAYED:
    case TL_WRITE_DEFAULT:
    case TL_WRITE_LOW_PRIORITY:
    case TL_WRITE:
    case TL_WRITE_ONLY:
      newmode= MODE_WRITE;
      break;
    case TL_READ:
    case TL_READ_WITH_SHARED_LOCKS:
    case TL_READ_HIGH_PRIORITY:
    case TL_READ_NO_INSERT:
    case TL_READ_DEFAULT:
      newmode= MODE_READ;
      break;
    case TL_UNLOCK:
    default:
      newmode= MODE_ANY;
      break;
    } // endswitch mode

  xmod= CheckMode(g, thd, newmode, &chk, &cras);
  DBUG_RETURN((xmod == MODE_ERROR) ? HA_ERR_INTERNAL_ERROR : 0);
} // end of start_stmt

/**
  @brief
  This create a lock on the table. If you are implementing a storage engine
  that can handle transacations look at ha_berkely.cc to see how you will
  want to go about doing this. Otherwise you should consider calling flock()
  here. Hint: Read the section "locking functions for mysql" in lock.cc to understand
  this.

    @details
  Called from lock.cc by lock_external() and unlock_external(). Also called
  from sql_table.cc by copy_data_between_tables().

    @note
  Following what we did in the MySQL XDB handler, we use this call to actually
  physically open the table. This could be reconsider when finalizing this handler
  design, which means we have a better understanding of what MariaDB does.

    @see
  lock.cc by lock_external() and unlock_external() in lock.cc;
  the section "locking functions for mysql" in lock.cc;
  copy_data_between_tables() in sql_table.cc.
*/
int ha_connect::external_lock(THD *thd, int lock_type)
{
  int     rc= 0;
  bool    xcheck=false, cras= false;
  MODE    newmode;
  PTOS    options= GetTableOptionStruct();
  PGLOBAL g= GetPlug(thd, xp);
  DBUG_ENTER("ha_connect::external_lock");

  DBUG_ASSERT(thd == current_thd);

  if (trace)
    htrc("external_lock: this=%p thd=%p xp=%p g=%p lock_type=%d\n",
            this, thd, xp, g, lock_type);

  if (!g)
    DBUG_RETURN(HA_ERR_INTERNAL_ERROR);

  // Action will depend on lock_type
  switch (lock_type) {
    case F_WRLCK:
      newmode= MODE_WRITE;
      break;
    case F_RDLCK:
      newmode= MODE_READ;
      break;
    case F_UNLCK:
    default:
      newmode= MODE_ANY;
      break;
    } // endswitch mode

  if (newmode == MODE_ANY) {
    int sqlcom= thd_sql_command(thd);

    // This is unlocking, do it by closing the table
    if (xp->CheckQueryID() && sqlcom != SQLCOM_UNLOCK_TABLES
                           && sqlcom != SQLCOM_LOCK_TABLES
                           && sqlcom != SQLCOM_FLUSH
                           && sqlcom != SQLCOM_BEGIN
                           && sqlcom != SQLCOM_DROP_TABLE) {
      sprintf(g->Message, "external_lock: unexpected command %d", sqlcom);
      push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 0, g->Message);
      DBUG_RETURN(0);
    } else if (g->Xchk) {
      if (!tdbp) {
				if (!(tdbp = GetTDB(g))) {
//        DBUG_RETURN(HA_ERR_INTERNAL_ERROR);  causes assert error
					push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 0, g->Message);
					DBUG_RETURN(0);
				} else if (!tdbp->GetDef()->Indexable()) {
          sprintf(g->Message, "external_lock: Table %s is not indexable", tdbp->GetName());
//        DBUG_RETURN(HA_ERR_INTERNAL_ERROR);  causes assert error
          push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 0, g->Message);
          DBUG_RETURN(0);
        } else if (tdbp->GetDef()->Indexable() == 1) {
          bool    oldsep= ((PCHK)g->Xchk)->oldsep;
          bool    newsep= ((PCHK)g->Xchk)->newsep;
          PTDBDOS tdp= (PTDBDOS)tdbp;
      
          PDOSDEF ddp= (PDOSDEF)tdp->GetDef();
          PIXDEF  xp, xp1, xp2, drp=NULL, adp= NULL;
          PIXDEF  oldpix= ((PCHK)g->Xchk)->oldpix;
          PIXDEF  newpix= ((PCHK)g->Xchk)->newpix;
          PIXDEF *xlst, *xprc; 
      
          ddp->SetIndx(oldpix);
      
          if (oldsep != newsep) {
            // All indexes have to be remade
            ddp->DeleteIndexFile(g, NULL);
            oldpix= NULL;
            ddp->SetIndx(NULL);
            SetBooleanOption("Sepindex", newsep);
          } else if (newsep) {
            // Make the list of dropped indexes
            xlst= &drp; xprc= &oldpix;
      
            for (xp2= oldpix; xp2; xp2= xp) {
              for (xp1= newpix; xp1; xp1= xp1->Next)
                if (IsSameIndex(xp1, xp2))
                  break;        // Index not to drop
      
              xp= xp2->GetNext();
      
              if (!xp1) {
                *xlst= xp2;
                *xprc= xp;
                *(xlst= &xp2->Next)= NULL;
              } else
                xprc= &xp2->Next;
      
              } // endfor xp2
      
            if (drp) {
              // Here we erase the index files
              ddp->DeleteIndexFile(g, drp);
              } // endif xp1
      
          } else if (oldpix) {
            // TODO: optimize the case of just adding new indexes
            if (!newpix)
              ddp->DeleteIndexFile(g, NULL);
      
            oldpix= NULL;     // To remake all indexes
            ddp->SetIndx(NULL);
          } // endif sepindex
      
          // Make the list of new created indexes
          xlst= &adp; xprc= &newpix;
      
          for (xp1= newpix; xp1; xp1= xp) {
            for (xp2= oldpix; xp2; xp2= xp2->Next)
              if (IsSameIndex(xp1, xp2))
                break;        // Index already made
      
            xp= xp1->Next;
      
            if (!xp2) {
              *xlst= xp1;
              *xprc= xp;
              *(xlst= &xp1->Next)= NULL;
            } else
              xprc= &xp1->Next;
      
            } // endfor xp1
      
          if (adp)
            // Here we do make the new indexes
            if (tdp->MakeIndex(g, adp, true) == RC_FX) {
              // Make it a warning to avoid crash
              push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 
                                0, g->Message);
              rc= 0;
							//my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
							//rc= HA_ERR_INTERNAL_ERROR;
						} // endif MakeIndex
      
        } else if (tdbp->GetDef()->Indexable() == 3) {
          if (CheckVirtualIndex(NULL)) {
            // Make it a warning to avoid crash
            push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 
                              0, g->Message);
            rc= 0;
            } // endif Check

        } // endif indexable

        } // endif Tdbp

      } // endelse Xchk

    if (CloseTable(g)) {
      // This is an error while builing index
      // Make it a warning to avoid crash
      push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 0, g->Message);
      rc= 0;
			//my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
			//rc = HA_ERR_INTERNAL_ERROR;
		} // endif Close

    locked= 0;
//	m_lock_type= lock_type;
    xmod= MODE_ANY;              // For info commands
    DBUG_RETURN(rc);
    } // endif MODE_ANY
  else
  if (check_privileges(thd, options, table->s->db.str)) {
    strcpy(g->Message, "This operation requires the FILE privilege");
    htrc("%s\n", g->Message);
    DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
    } // endif check_privileges


  DBUG_ASSERT(table && table->s);

  // Table mode depends on the query type
  newmode= CheckMode(g, thd, newmode, &xcheck, &cras);

  if (newmode == MODE_ERROR)
    DBUG_RETURN(HA_ERR_INTERNAL_ERROR);

  // If this is the start of a new query, cleanup the previous one
  if (xp->CheckCleanup()) {
    tdbp= NULL;
    valid_info= false;
    } // endif CheckCleanup

#if 0
  if (xcheck) {
    // This must occur after CheckCleanup
    if (!g->Xchk) {
      g->Xchk= new(g) XCHK;
      ((PCHK)g->Xchk)->oldsep= GetBooleanOption("Sepindex", false);
      ((PCHK)g->Xchk)->oldpix= GetIndexInfo();
      } // endif Xchk

  } else
    g->Xchk= NULL;
#endif // 0

  if (cras)
    g->Createas= 1;       // To tell created table to ignore FLAG

  if (trace) {
#if 0
    htrc("xcheck=%d cras=%d\n", xcheck, cras);

    if (xcheck)
      htrc("oldsep=%d oldpix=%p\n",
              ((PCHK)g->Xchk)->oldsep, ((PCHK)g->Xchk)->oldpix);
#endif // 0
    htrc("Calling CntCheckDB db=%s cras=%d\n", GetDBName(NULL), cras);
    } // endif trace

  // Set or reset the good database environment
  if (CntCheckDB(g, this, GetDBName(NULL))) {
    htrc("%p external_lock: %s\n", this, g->Message);
    rc= HA_ERR_INTERNAL_ERROR;
  // This can NOT be called without open called first, but
  // the table can have been closed since then
  } else if (!tdbp || xp->CheckQuery(valid_query_id) || xmod != newmode) {
    if (tdbp) {
      // If this is called by a later query, the table may have
      // been already closed and the tdbp is not valid anymore.
      if (xp->last_query_id == valid_query_id)
        rc= CloseTable(g);
      else
        tdbp= NULL;

      } // endif tdbp

    xmod= newmode;

    // Delay open until used fields are known
  } // endif tdbp

  if (trace)
    htrc("external_lock: rc=%d\n", rc);

  DBUG_RETURN(rc);
} // end of external_lock


/**
  @brief
  The idea with handler::store_lock() is: The statement decides which locks
  should be needed for the table. For updates/deletes/inserts we get WRITE
  locks, for SELECT... we get read locks.

    @details
  Before adding the lock into the table lock handler (see thr_lock.c),
  mysqld calls store lock with the requested locks. Store lock can now
  modify a write lock to a read lock (or some other lock), ignore the
  lock (if we don't want to use MySQL table locks at all), or add locks
  for many tables (like we do when we are using a MERGE handler).

  Berkeley DB, for example, changes all WRITE locks to TL_WRITE_ALLOW_WRITE
  (which signals that we are doing WRITES, but are still allowing other
  readers and writers).

  When releasing locks, store_lock() is also called. In this case one
  usually doesn't have to do anything.

  In some exceptional cases MySQL may send a request for a TL_IGNORE;
  This means that we are requesting the same lock as last time and this
  should also be ignored. (This may happen when someone does a flush
  table when we have opened a part of the tables, in which case mysqld
  closes and reopens the tables and tries to get the same locks at last
  time). In the future we will probably try to remove this.

  Called from lock.cc by get_lock_data().

    @note
  In this method one should NEVER rely on table->in_use, it may, in fact,
  refer to a different thread! (this happens if get_lock_data() is called
  from mysql_lock_abort_for_thread() function)

    @see
  get_lock_data() in lock.cc
*/
THR_LOCK_DATA **ha_connect::store_lock(THD *,
                                       THR_LOCK_DATA **to,
                                       enum thr_lock_type lock_type)
{
  if (lock_type != TL_IGNORE && lock.type == TL_UNLOCK)
    lock.type=lock_type;
  *to++ = &lock;
  return to;
}


/**
  Searches for a pointer to the last occurrence of  the
  character c in the string src.
  Returns true on failure, false on success.
*/
static bool
strnrchr(LEX_CSTRING *ls, const char *src, size_t length, int c)
{
  const char *srcend, *s;
  for (s= srcend= src + length; s > src; s--)
  {
    if (s[-1] == c)
    {
      ls->str= s;
      ls->length= srcend - s;
      return false;
    }
  }
  return true;
}


/**
  Split filename into database and table name.
*/
static bool
filename_to_dbname_and_tablename(const char *filename,
                                 char *database, size_t database_size,
                                 char *table, size_t table_size)
{
  LEX_CSTRING d, t;
  size_t length= strlen(filename);

  /* Find filename - the rightmost directory part */
  if (strnrchr(&t, filename, length, slash) || t.length + 1 > table_size)
    return true;
  memcpy(table, t.str, t.length);
  table[t.length]= '\0';
  if (!(length-= t.length))
    return true;

  length--; /* Skip slash */

  /* Find database name - the second rightmost directory part */
  if (strnrchr(&d, filename, length, slash) || d.length + 1 > database_size)
    return true;
  memcpy(database, d.str, d.length);
  database[d.length]= '\0';
  return false;
} // end of filename_to_dbname_and_tablename

/**
  @brief
  Used to delete or rename a table. By the time delete_table() has been
  called all opened references to this table will have been closed
  (and your globally shared references released) ===> too bad!!!
  The variable name will just be the name of the table.
  You will need to remove or rename any files you have created at
  this point.

    @details
  If you do not implement this, the default delete_table() is called from
  handler.cc and it will delete all files with the file extensions returned
  by bas_ext().

  Called from handler.cc by delete_table and ha_create_table(). Only used
  during create if the table_flag HA_DROP_BEFORE_CREATE was specified for
  the storage engine.

    @see
  delete_table and ha_create_table() in handler.cc
*/
int ha_connect::delete_or_rename_table(const char *name, const char *to)
{
  DBUG_ENTER("ha_connect::delete_or_rename_table");
  char db[128], tabname[128];
  int  rc= 0;
  bool ok= false;
  THD *thd= current_thd;
  int  sqlcom= thd_sql_command(thd);

  if (trace) {
    if (to)
      htrc("rename_table: this=%p thd=%p sqlcom=%d from=%s to=%s\n",
              this, thd, sqlcom, name, to);
    else
      htrc("delete_table: this=%p thd=%p sqlcom=%d name=%s\n",
              this, thd, sqlcom, name);

    } // endif trace

  if (to && (filename_to_dbname_and_tablename(to, db, sizeof(db),
                                             tabname, sizeof(tabname))
      || (*tabname == '#' && sqlcom == SQLCOM_CREATE_INDEX)))
    DBUG_RETURN(0);

  if (filename_to_dbname_and_tablename(name, db, sizeof(db),
                                       tabname, sizeof(tabname))
      || (*tabname == '#' && sqlcom == SQLCOM_CREATE_INDEX))
    DBUG_RETURN(0);

  // If a temporary file exists, all the tests below were passed
  // successfully when making it, so they are not needed anymore
  // in particular because they sometimes cause DBUG_ASSERT crash.
  // Also, for partitioned tables, no test can be done because when
  // this function is called, the .par file is already deleted and
  // this causes the open_table_def function to fail.
  // Not having any other clues (table and table_share are NULL)
  // the only mean we have to test for partitioning is this:
  if (*tabname != '#' && !strstr(tabname, "#P#")) {
    // We have to retrieve the information about this table options.
    ha_table_option_struct *pos;
    char         key[MAX_DBKEY_LENGTH];
    uint         key_length;
    TABLE_SHARE *share;

//  if ((p= strstr(tabname, "#P#")))   won't work, see above
//    *p= 0;             // Get the main the table name

    key_length= tdc_create_key(key, db, tabname);

    // share contains the option struct that we need
    if (!(share= alloc_table_share(db, tabname, key, key_length)))
      DBUG_RETURN(rc);

    // Get the share info from the .frm file
    Dummy_error_handler error_handler;
    thd->push_internal_handler(&error_handler);
    bool got_error= open_table_def(thd, share);
    thd->pop_internal_handler();
    if (!got_error) {
      // Now we can work
      if ((pos= share->option_struct)) {
        if (check_privileges(thd, pos, db))
          rc= HA_ERR_INTERNAL_ERROR;         // ???
        else
          if (IsFileType(GetRealType(pos)) && !pos->filename)
            ok= true;

        } // endif pos

      } // endif open_table_def

    free_table_share(share);
  } else              // Temporary file
    ok= true;

  if (ok) {
    // Let the base handler do the job
    if (to)
      rc= handler::rename_table(name, to);
    else if ((rc= handler::delete_table(name)) == ENOENT)
      rc= 0;        // No files is not an error for CONNECT

    } // endif ok

  DBUG_RETURN(rc);
} // end of delete_or_rename_table

int ha_connect::delete_table(const char *name)
{
  return delete_or_rename_table(name, NULL);
} // end of delete_table

int ha_connect::rename_table(const char *from, const char *to)
{
  return delete_or_rename_table(from, to);
} // end of rename_table

/**
  @brief
  Given a starting key and an ending key, estimate the number of rows that
  will exist between the two keys.

  @details
  end_key may be empty, in which case determine if start_key matches any rows.

  Called from opt_range.cc by check_quick_keys().

  @see
  check_quick_keys() in opt_range.cc
*/
ha_rows ha_connect::records_in_range(uint inx, key_range *min_key,
                                               key_range *max_key)
{
  ha_rows rows;
  DBUG_ENTER("ha_connect::records_in_range");

  if (indexing < 0 || inx != active_index)
    if (index_init(inx, false))
      DBUG_RETURN(HA_POS_ERROR);

  if (trace)
    htrc("records_in_range: inx=%d indexing=%d\n", inx, indexing);

  if (indexing > 0) {
    int          nval;
    uint         len[2];
    const uchar *key[2];
    bool         incl[2];
    key_part_map kmap[2];

    key[0]= (min_key) ? min_key->key : NULL;
    key[1]= (max_key) ? max_key->key : NULL;
    len[0]= (min_key) ? min_key->length : 0;
    len[1]= (max_key) ? max_key->length : 0;
    incl[0]= (min_key) ? (min_key->flag == HA_READ_KEY_EXACT) : false;
    incl[1]= (max_key) ? (max_key->flag == HA_READ_AFTER_KEY) : false;
    kmap[0]= (min_key) ? min_key->keypart_map : 0;
    kmap[1]= (max_key) ? max_key->keypart_map : 0;

    if ((nval= CntIndexRange(xp->g, tdbp, key, len, incl, kmap)) < 0)
      rows= HA_POS_ERROR;
    else
      rows= (ha_rows)nval;

  } else if (indexing == 0)
    rows= 100000000;        // Don't use missing index
  else
    rows= HA_POS_ERROR;

  if (trace)
    htrc("records_in_range: rows=%llu\n", rows);

  DBUG_RETURN(rows);
} // end of records_in_range

// Used to check whether a MYSQL table is created on itself
bool CheckSelf(PGLOBAL g, TABLE_SHARE *s, PCSZ host,
	             PCSZ db, PCSZ tab, PCSZ src, int port)
{
  if (src)
    return false;
  else if (host && stricmp(host, "localhost") && strcmp(host, "127.0.0.1"))
    return false;
  else if (db && stricmp(db, s->db.str))
    return false;
  else if (tab && stricmp(tab, s->table_name.str))
    return false;
  else if (port && port != (signed)GetDefaultPort())
    return false;

  strcpy(g->Message, "This MySQL table is defined on itself");
  return true;
} // end of CheckSelf

/**
  Convert an ISO-8859-1 column name to UTF-8
*/
static char *encode(PGLOBAL g, const char *cnm)
  {
  char  *buf= (char*)PlugSubAlloc(g, NULL, strlen(cnm) * 3);
  uint   dummy_errors;
  uint32 len= copy_and_convert(buf, strlen(cnm) * 3,
                               &my_charset_utf8_general_ci,
                               cnm, strlen(cnm),
                               &my_charset_latin1,
                               &dummy_errors);
  buf[len]= '\0';
  return buf;
  } // end of encode

/**
  Store field definition for create.

  @return
    Return 0 if ok
*/
static bool add_field(String *sql, const char *field_name, int typ, int len,
                      int dec, char *key, uint tm, const char *rem, char *dft,
                      char *xtra, char *fmt, int flag, bool dbf, char v)
{
  char var = (len > 255) ? 'V' : v;
  bool q, error= false;
  const char *type= PLGtoMYSQLtype(typ, dbf, var);

  error|= sql->append('`');
  error|= sql->append(field_name);
  error|= sql->append("` ");
  error|= sql->append(type);

	if (typ == TYPE_STRING || 
		 (len && typ != TYPE_DATE && (typ != TYPE_DOUBLE || dec >= 0))) {
    error|= sql->append('(');
    error|= sql->append_ulonglong(len);

		if (typ == TYPE_DOUBLE) {
      error|= sql->append(',');
      // dec must be < len and < 31
      error|= sql->append_ulonglong(MY_MIN(dec, (MY_MIN(len, 31) - 1)));
    } else if (dec > 0 && !strcmp(type, "DECIMAL")) {
      error|= sql->append(',');
      // dec must be < len
      error|= sql->append_ulonglong(MY_MIN(dec, len - 1));
    } // endif dec

    error|= sql->append(')');
    } // endif len

  if (v == 'U')
    error|= sql->append(" UNSIGNED");
  else if (v == 'Z')
    error|= sql->append(" ZEROFILL");

  if (key && *key) {
    error|= sql->append(" ");
    error|= sql->append(key);
    } // endif key

  if (tm)
    error|= sql->append(STRING_WITH_LEN(" NOT NULL"), system_charset_info);

  if (dft && *dft) {
    error|= sql->append(" DEFAULT ");

    if (typ == TYPE_DATE)
      q = (strspn(dft, "0123456789 -:/") == strlen(dft));
    else
      q = !IsTypeNum(typ);

    if (q) {
      error|= sql->append("'");
      error|= sql->append_for_single_quote(dft, strlen(dft));
      error|= sql->append("'");
    } else
      error|= sql->append(dft);

    } // endif dft

  if (xtra && *xtra) {
    error|= sql->append(" ");
    error|= sql->append(xtra);
    } // endif rem

  if (rem && *rem) {
    error|= sql->append(" COMMENT '");
    error|= sql->append_for_single_quote(rem, strlen(rem));
    error|= sql->append("'");
    } // endif rem

  if (fmt && *fmt) {
    error|= sql->append(" FIELD_FORMAT='");
    error|= sql->append_for_single_quote(fmt, strlen(fmt));
    error|= sql->append("'");
    } // endif flag

  if (flag) {
    error|= sql->append(" FLAG=");
    error|= sql->append_ulonglong(flag);
    } // endif flag

  error|= sql->append(',');
  return error;
} // end of add_field

/**
  Initialise the table share with the new columns.

  @return
    Return 0 if ok
*/
static int init_table_share(THD* thd,
                            TABLE_SHARE *table_s,
                            HA_CREATE_INFO *create_info,
                            String *sql)
{
  bool oom= false;
  PTOS topt= table_s->option_struct;

  sql->length(sql->length()-1); // remove the trailing comma
  sql->append(')');

  for (ha_create_table_option *opt= connect_table_option_list;
       opt->name; opt++) {
    ulonglong   vull;
    const char *vstr;

    switch (opt->type) {
      case HA_OPTION_TYPE_ULL:
        vull= *(ulonglong*)(((char*)topt) + opt->offset);

        if (vull != opt->def_value) {
          oom|= sql->append(' ');
          oom|= sql->append(opt->name);
          oom|= sql->append('=');
          oom|= sql->append_ulonglong(vull);
          } // endif vull

        break;
      case HA_OPTION_TYPE_STRING:
        vstr= *(char**)(((char*)topt) + opt->offset);

        if (vstr) {
          oom|= sql->append(' ');
          oom|= sql->append(opt->name);
          oom|= sql->append("='");
          oom|= sql->append_for_single_quote(vstr, strlen(vstr));
          oom|= sql->append('\'');
          } // endif vstr

        break;
      case HA_OPTION_TYPE_BOOL:
        vull= *(bool*)(((char*)topt) + opt->offset);

        if (vull != opt->def_value) {
          oom|= sql->append(' ');
          oom|= sql->append(opt->name);
          oom|= sql->append('=');
          oom|= sql->append(vull ? "YES" : "NO");
          } // endif vull

        break;
      default: // no enums here, good :)
        break;
      } // endswitch type

    if (oom)
      return HA_ERR_OUT_OF_MEM;

    } // endfor opt

  if (create_info->connect_string.length) {
    oom|= sql->append(' ');
    oom|= sql->append("CONNECTION='");
    oom|= sql->append_for_single_quote(create_info->connect_string.str,
                                       create_info->connect_string.length);
    oom|= sql->append('\'');

    if (oom)
      return HA_ERR_OUT_OF_MEM;

    } // endif string

  if (create_info->default_table_charset) {
    oom|= sql->append(' ');
    oom|= sql->append("CHARSET=");
    oom|= sql->append(create_info->default_table_charset->csname);

    if (oom)
      return HA_ERR_OUT_OF_MEM;

    } // endif charset

  if (trace)
    htrc("s_init: %.*s\n", sql->length(), sql->ptr());

  return table_s->init_from_sql_statement_string(thd, true,
                                                 sql->ptr(), sql->length());
} // end of init_table_share

/**
  @brief
  connect_assisted_discovery() is called when creating a table with no columns.

  @details
  When assisted discovery is used the .frm file have not already been
  created. You can overwrite some definitions at this point but the
  main purpose of it is to define the columns for some table types.

  @note
  this function is no more called in case of CREATE .. SELECT
*/
static int connect_assisted_discovery(handlerton *, THD* thd,
                                      TABLE_SHARE *table_s,
                                      HA_CREATE_INFO *create_info)
{
  char     v=0;
	PCSZ     fncn= "?";
	PCSZ     user, fn, db, host, pwd, sep, tbl, src;
	PCSZ     col, ocl, rnk, pic, fcl, skc, zfn;
  char    *tab, *dsn, *shm, *dpath; 
#if defined(__WIN__)
	PCSZ     nsp= NULL, cls= NULL;
#endif   // __WIN__
//int      hdr, mxe;
	int      port = 0, mxr = 0, rc = 0, mul = 0, lrecl = 0;
	PCSZ     tabtyp = NULL;
#if defined(ODBC_SUPPORT)
  POPARM   sop= NULL;
	PCSZ     ucnc= NULL;
	bool     cnc= false;
  int      cto= -1, qto= -1;
#endif   // ODBC_SUPPORT
#if defined(JAVA_SUPPORT)
	PJPARM   sjp= NULL;
	PCSZ     driver= NULL;
	char    *url= NULL;
#endif   // JAVA_SUPPORT
  uint     tm, fnc= FNC_NO, supfnc= (FNC_NO | FNC_COL);
  bool     bif, ok= false, dbf= false;
  TABTYPE  ttp= TAB_UNDEF;
  PQRYRES  qrp= NULL;
  PCOLRES  crp;
  PCONNECT xp= NULL;
  PGLOBAL  g= GetPlug(thd, xp);

  if (!g)
    return HA_ERR_INTERNAL_ERROR;

  PDBUSER  dup= PlgGetUser(g);
  PCATLG   cat= (dup) ? dup->Catalog : NULL;
  PTOS     topt= table_s->option_struct;
  char     buf[1024];
  String   sql(buf, sizeof(buf), system_charset_info);

  sql.copy(STRING_WITH_LEN("CREATE TABLE whatever ("), system_charset_info);
  user= host= pwd= tbl= src= col= ocl= pic= fcl= skc= rnk= zfn= dsn= NULL;

  // Get the useful create options
  ttp= GetTypeID(topt->type);
  fn=  topt->filename;
  tab= (char*)topt->tabname;
  src= topt->srcdef;
  db=  topt->dbname;
  fncn= topt->catfunc;
  fnc= GetFuncID(fncn);
  sep= topt->separator;
	mul = (int)topt->multiple;
	tbl= topt->tablist;
  col= topt->colist;

  if (topt->oplist) {
    host= GetListOption(g, "host", topt->oplist, "localhost");
    user= GetListOption(g, "user", topt->oplist, 
          ((ttp == TAB_ODBC || ttp == TAB_JDBC) ? NULL : "root"));
    // Default value db can come from the DBNAME=xxx option.
    db= GetListOption(g, "database", topt->oplist, db);
    col= GetListOption(g, "colist", topt->oplist, col);
    ocl= GetListOption(g, "occurcol", topt->oplist, NULL);
    pic= GetListOption(g, "pivotcol", topt->oplist, NULL);
    fcl= GetListOption(g, "fnccol", topt->oplist, NULL);
    skc= GetListOption(g, "skipcol", topt->oplist, NULL);
    rnk= GetListOption(g, "rankcol", topt->oplist, NULL);
    pwd= GetListOption(g, "password", topt->oplist);
#if defined(__WIN__)
    nsp= GetListOption(g, "namespace", topt->oplist);
    cls= GetListOption(g, "class", topt->oplist);
#endif   // __WIN__
    port= atoi(GetListOption(g, "port", topt->oplist, "0"));
#if defined(ODBC_SUPPORT)
		tabtyp = GetListOption(g, "Tabtype", topt->oplist, NULL);
		mxr= atoi(GetListOption(g,"maxres", topt->oplist, "0"));
    cto= atoi(GetListOption(g,"ConnectTimeout", topt->oplist, "-1"));
    qto= atoi(GetListOption(g,"QueryTimeout", topt->oplist, "-1"));
    
    if ((ucnc= GetListOption(g, "UseDSN", topt->oplist)))
      cnc= (!*ucnc || *ucnc == 'y' || *ucnc == 'Y' || atoi(ucnc) != 0);
#endif
#if defined(JAVA_SUPPORT)
		driver= GetListOption(g, "Driver", topt->oplist, NULL);
#endif   // JAVA_SUPPORT
#if defined(PROMPT_OK)
    cop= atoi(GetListOption(g, "checkdsn", topt->oplist, "0"));
#endif   // PROMPT_OK
#if defined(ZIP_SUPPORT)
		zfn = GetListOption(g, "Zipfile", topt->oplist, NULL);
#endif   // ZIP_SUPPORT
	} else {
    host= "localhost";
    user= ((ttp == TAB_ODBC || ttp == TAB_JDBC) ? NULL : "root");
  } // endif option_list

  if (!(shm= (char*)db))
    db= table_s->db.str;                   // Default value

	try {
		// Check table type
		if (ttp == TAB_UNDEF) {
			topt->type = (src) ? "MYSQL" : (tab) ? "PROXY" : "DOS";
			ttp = GetTypeID(topt->type);
			sprintf(g->Message, "No table_type. Was set to %s", topt->type);
			push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 0, g->Message);
		} else if (ttp == TAB_NIY) {
			sprintf(g->Message, "Unsupported table type %s", topt->type);
			rc = HA_ERR_INTERNAL_ERROR;
			goto err;
		} // endif ttp

		if (!tab) {
			if (ttp == TAB_TBL) {
				// Make tab the first table of the list
				char *p;

				if (!tbl) {
					strcpy(g->Message, "Missing table list");
					rc = HA_ERR_INTERNAL_ERROR;
					goto err;
				} // endif tbl

				tab = PlugDup(g, tbl);

				if ((p = strchr(tab, ',')))
					*p = 0;

				if ((p = strchr(tab, '.'))) {
					*p = 0;
					db = tab;
					tab = p + 1;
				} // endif p

			} else if (ttp != TAB_ODBC || !(fnc & (FNC_TABLE | FNC_COL)))
				tab = table_s->table_name.str;           // Default value

		} // endif tab

		switch (ttp) {
#if defined(ODBC_SUPPORT)
			case TAB_ODBC:
				dsn = strz(g, create_info->connect_string);

				if (fnc & (FNC_DSN | FNC_DRIVER)) {
					ok = true;
#if defined(PROMPT_OK)
				} else if (!stricmp(thd->main_security_ctx.host, "localhost")
					&& cop == 1) {
					if ((dsn = ODBCCheckConnection(g, dsn, cop)) != NULL) {
						thd->make_lex_string(&create_info->connect_string, dsn, strlen(dsn));
						ok = true;
					} // endif dsn
#endif   // PROMPT_OK

				} else if (!dsn) {
					sprintf(g->Message, "Missing %s connection string", topt->type);
				} else {
					// Store ODBC additional parameters
					sop = (POPARM)PlugSubAlloc(g, NULL, sizeof(ODBCPARM));
					sop->User = (char*)user;
					sop->Pwd = (char*)pwd;
					sop->Cto = cto;
					sop->Qto = qto;
					sop->UseCnc = cnc;
					ok = true;
				} // endif's

				supfnc |= (FNC_TABLE | FNC_DSN | FNC_DRIVER);
				break;
#endif   // ODBC_SUPPORT
#if defined(JAVA_SUPPORT)
			case TAB_JDBC:
				if (fnc & FNC_DRIVER) {
					ok = true;
				} else if (!(url = strz(g, create_info->connect_string))) {
					strcpy(g->Message, "Missing URL");
				} else {
					// Store JDBC additional parameters
					int      rc;
					PJDBCDEF jdef = new(g) JDBCDEF();

					jdef->SetName(create_info->alias);
					sjp = (PJPARM)PlugSubAlloc(g, NULL, sizeof(JDBCPARM));
					sjp->Driver = driver;
					//		sjp->Properties = prop;
					sjp->Fsize = 0;
					sjp->Scrollable = false;

					if ((rc = jdef->ParseURL(g, url, false)) == RC_OK) {
						sjp->Url = url;
						sjp->User = (char*)user;
						sjp->Pwd = (char*)pwd;
						ok = true;
					} else if (rc == RC_NF) {
						if (jdef->GetTabname())
							tab = (char*)jdef->GetTabname();

						ok = jdef->SetParms(sjp);
					} // endif rc

				} // endif's

				supfnc |= (FNC_DRIVER | FNC_TABLE);
				break;
#endif   // JAVA_SUPPORT
			case TAB_DBF:
				dbf = true;
				// Passthru
			case TAB_CSV:
				if (!fn && fnc != FNC_NO)
					sprintf(g->Message, "Missing %s file name", topt->type);
				else if (sep && strlen(sep) > 1)
					sprintf(g->Message, "Invalid separator %s", sep);
				else
					ok = true;

				break;
			case TAB_MYSQL:
				ok = true;

				if (create_info->connect_string.str &&
					create_info->connect_string.length) {
					PMYDEF  mydef = new(g) MYSQLDEF();

					dsn = strz(g, create_info->connect_string);
					mydef->SetName(create_info->alias);

					if (!mydef->ParseURL(g, dsn, false)) {
						if (mydef->GetHostname())
							host = mydef->GetHostname();

						if (mydef->GetUsername())
							user = mydef->GetUsername();

						if (mydef->GetPassword())
							pwd = mydef->GetPassword();

						if (mydef->GetTabschema())
							db = mydef->GetTabschema();

						if (mydef->GetTabname())
							tab = (char*)mydef->GetTabname();

						if (mydef->GetPortnumber())
							port = mydef->GetPortnumber();

					} else
						ok = false;

				} else if (!user)
					user = "root";

				if (ok && CheckSelf(g, table_s, host, db, tab, src, port))
					ok = false;

				break;
#if defined(__WIN__)
			case TAB_WMI:
				ok = true;
				break;
#endif   // __WIN__
			case TAB_PIVOT:
				supfnc = FNC_NO;
			case TAB_PRX:
			case TAB_TBL:
			case TAB_XCL:
			case TAB_OCCUR:
				if (!src && !stricmp(tab, create_info->alias) &&
					(!db || !stricmp(db, table_s->db.str)))
					sprintf(g->Message, "A %s table cannot refer to itself", topt->type);
				else
					ok = true;

				break;
			case TAB_OEM:
				if (topt->module && topt->subtype)
					ok = true;
				else
					strcpy(g->Message, "Missing OEM module or subtype");

				break;
#if defined(LIBXML2_SUPPORT) || defined(DOMDOC_SUPPORT)
			case TAB_XML:
#endif   // LIBXML2_SUPPORT  ||         DOMDOC_SUPPORT
			case TAB_JSON:
				dsn = strz(g, create_info->connect_string);

				if (!fn && !zfn && !mul && !dsn)
					sprintf(g->Message, "Missing %s file name", topt->type);
				else
					ok = true;

				break;
#if defined(JAVA_SUPPORT)
			case TAB_MONGO:
				if (!topt->tabname)
					topt->tabname = tab;

				ok = true;
				break;
#endif   // JAVA_SUPPORT
			case TAB_VIR:
				ok = true;
				break;
			default:
				sprintf(g->Message, "Cannot get column info for table type %s", topt->type);
				break;
		} // endif ttp

	// Check for supported catalog function
		if (ok && !(supfnc & fnc)) {
			sprintf(g->Message, "Unsupported catalog function %s for table type %s",
				fncn, topt->type);
			ok = false;
		} // endif supfnc

		if (src && fnc != FNC_NO) {
			strcpy(g->Message, "Cannot make catalog table from srcdef");
			ok = false;
		} // endif src

		if (ok) {
			const char *cnm, *rem;
			char *dft, *xtra, *key, *fmt;
			int   i, len, prec, dec, typ, flg;

			if (!(dpath = SetPath(g, table_s->db.str))) {
				rc = HA_ERR_INTERNAL_ERROR;
				goto err;
			}	// endif dpath

			if (src && ttp != TAB_PIVOT && ttp != TAB_ODBC && ttp != TAB_JDBC) {
				qrp = SrcColumns(g, host, db, user, pwd, src, port);

				if (qrp && ttp == TAB_OCCUR)
					if (OcrSrcCols(g, qrp, col, ocl, rnk)) {
						rc = HA_ERR_INTERNAL_ERROR;
						goto err;
					} // endif OcrSrcCols

			} else switch (ttp) {
				case TAB_DBF:
					qrp = DBFColumns(g, dpath, fn, fnc == FNC_COL);
					break;
#if defined(ODBC_SUPPORT)
				case TAB_ODBC:
					switch (fnc) {
						case FNC_NO:
						case FNC_COL:
							if (src) {
								qrp = ODBCSrcCols(g, dsn, (char*)src, sop);
								src = NULL;     // for next tests
							} else
								qrp = ODBCColumns(g, dsn, shm, tab, NULL,
									mxr, fnc == FNC_COL, sop);

							break;
						case FNC_TABLE:
							qrp = ODBCTables(g, dsn, shm, tab, NULL, mxr, true, sop);
							break;
						case FNC_DSN:
							qrp = ODBCDataSources(g, mxr, true);
							break;
						case FNC_DRIVER:
							qrp = ODBCDrivers(g, mxr, true);
							break;
						default:
							sprintf(g->Message, "invalid catfunc %s", fncn);
							break;
					} // endswitch info

					break;
#endif   // ODBC_SUPPORT
#if defined(JAVA_SUPPORT)
				case TAB_JDBC:
					switch (fnc) {
						case FNC_NO:
						case FNC_COL:
							if (src) {
								qrp = JDBCSrcCols(g, (char*)src, sjp);
								src = NULL;     // for next tests
							} else
								qrp = JDBCColumns(g, shm, tab, NULL, mxr, fnc == FNC_COL, sjp);

							break;
						case FNC_TABLE:
							qrp = JDBCTables(g, shm, tab, tabtyp, mxr, true, sjp);
							break;
#if 0
						case FNC_DSN:
							qrp = JDBCDataSources(g, mxr, true);
							break;
#endif // 0
						case FNC_DRIVER:
							qrp = JDBCDrivers(g, mxr, true);
							break;
						default:
							sprintf(g->Message, "invalid catfunc %s", fncn);
							break;
					} // endswitch info

					break;
#endif   // JAVA_SUPPORT
				case TAB_MYSQL:
					qrp = MyColumns(g, thd, host, db, user, pwd, tab,
						NULL, port, fnc == FNC_COL);
					break;
				case TAB_CSV:
					qrp = CSVColumns(g, dpath, topt, fnc == FNC_COL);
					break;
#if defined(__WIN__)
				case TAB_WMI:
					qrp = WMIColumns(g, nsp, cls, fnc == FNC_COL);
					break;
#endif   // __WIN__
				case TAB_PRX:
				case TAB_TBL:
				case TAB_XCL:
				case TAB_OCCUR:
					bif = fnc == FNC_COL;
					qrp = TabColumns(g, thd, db, tab, bif);

					if (!qrp && bif && fnc != FNC_COL)         // tab is a view
						qrp = MyColumns(g, thd, host, db, user, pwd, tab, NULL, port, false);

					if (qrp && ttp == TAB_OCCUR && fnc != FNC_COL)
						if (OcrColumns(g, qrp, col, ocl, rnk)) {
							rc = HA_ERR_INTERNAL_ERROR;
							goto err;
						} // endif OcrColumns

					break;
				case TAB_PIVOT:
					qrp = PivotColumns(g, tab, src, pic, fcl, skc, host, db, user, pwd, port);
					break;
				case TAB_VIR:
					qrp = VirColumns(g, fnc == FNC_COL);
					break;
				case TAB_JSON:
					qrp = JSONColumns(g, db, dsn, topt, fnc == FNC_COL);
					break;
#if defined(MONGO_SUPPORT)
				case TAB_MONGO:
					url = strz(g, create_info->connect_string);
					qrp = MGOColumns(g, db, url, topt, fnc == FNC_COL);
					break;
#endif   // MONGO_SUPPORT
#if defined(LIBXML2_SUPPORT) || defined(DOMDOC_SUPPORT)
				case TAB_XML:
					qrp = XMLColumns(g, (char*)db, tab, topt, fnc == FNC_COL);
					break;
#endif   // LIBXML2_SUPPORT  ||         DOMDOC_SUPPORT
				case TAB_OEM:
					qrp = OEMColumns(g, topt, tab, (char*)db, fnc == FNC_COL);
					break;
				default:
					strcpy(g->Message, "System error during assisted discovery");
					break;
			} // endswitch ttp

			if (!qrp) {
				rc = HA_ERR_INTERNAL_ERROR;
				goto err;
			} // endif !qrp

			if (fnc != FNC_NO || src || ttp == TAB_PIVOT) {
				// Catalog like table
				for (crp = qrp->Colresp; !rc && crp; crp = crp->Next) {
					cnm = (ttp == TAB_PIVOT) ? crp->Name : encode(g, crp->Name);
					typ = crp->Type;
					len = crp->Length;
					dec = crp->Prec;
					flg = crp->Flag;
					v = (crp->Kdata->IsUnsigned()) ? 'U' : crp->Var;
					tm = (crp->Kdata->IsNullable()) ? 0 : NOT_NULL_FLAG;

					if (!len && typ == TYPE_STRING)
						len = 256;      // STRBLK's have 0 length

					// Now add the field
					if (add_field(&sql, cnm, typ, len, dec, NULL, tm,
						NULL, NULL, NULL, NULL, flg, dbf, v))
						rc = HA_ERR_OUT_OF_MEM;
				} // endfor crp

			} else {
				char *schem = NULL;
				char *tn = NULL;

				// Not a catalog table
				if (!qrp->Nblin) {
					if (tab)
						sprintf(g->Message, "Cannot get columns from %s", tab);
					else
						strcpy(g->Message, "Fail to retrieve columns");

					rc = HA_ERR_INTERNAL_ERROR;
					goto err;
				} // endif !nblin

				for (i = 0; !rc && i < qrp->Nblin; i++) {
					typ = len = prec = dec = 0;
					tm = NOT_NULL_FLAG;
					cnm = (char*)"noname";
					dft = xtra = key = fmt = tn = NULL;
					v = ' ';
					rem = NULL;

					for (crp = qrp->Colresp; crp; crp = crp->Next)
						switch (crp->Fld) {
							case FLD_NAME:
								if (ttp == TAB_PRX ||
									(ttp == TAB_CSV && topt->data_charset &&
									(!stricmp(topt->data_charset, "UTF8") ||
										!stricmp(topt->data_charset, "UTF-8"))))
									cnm = crp->Kdata->GetCharValue(i);
								else
									cnm = encode(g, crp->Kdata->GetCharValue(i));

								break;
							case FLD_TYPE:
								typ = crp->Kdata->GetIntValue(i);
								v = (crp->Nulls) ? crp->Nulls[i] : 0;
								break;
							case FLD_TYPENAME:
								tn = crp->Kdata->GetCharValue(i);
								break;
							case FLD_PREC:
								// PREC must be always before LENGTH
								len = prec = crp->Kdata->GetIntValue(i);
								break;
							case FLD_LENGTH:
								len = crp->Kdata->GetIntValue(i);
								break;
							case FLD_SCALE:
								dec = (!crp->Kdata->IsNull(i)) ? crp->Kdata->GetIntValue(i) : -1;
								break;
							case FLD_NULL:
								if (crp->Kdata->GetIntValue(i))
									tm = 0;               // Nullable

								break;
							case FLD_FORMAT:
								fmt = (crp->Kdata) ? crp->Kdata->GetCharValue(i) : NULL;
								break;
							case FLD_REM:
								rem = crp->Kdata->GetCharValue(i);
								break;
								//          case FLD_CHARSET:
															// No good because remote table is already translated
								//            if (*(csn= crp->Kdata->GetCharValue(i)))
								//              cs= get_charset_by_name(csn, 0);

								//            break;
							case FLD_DEFAULT:
								dft = crp->Kdata->GetCharValue(i);
								break;
							case FLD_EXTRA:
								xtra = crp->Kdata->GetCharValue(i);

								// Auto_increment is not supported yet
								if (!stricmp(xtra, "AUTO_INCREMENT"))
									xtra = NULL;

								break;
							case FLD_KEY:
								if (ttp == TAB_VIR)
									key = crp->Kdata->GetCharValue(i);

								break;
							case FLD_SCHEM:
#if defined(ODBC_SUPPORT) || defined(JAVA_SUPPORT)
								if ((ttp == TAB_ODBC || ttp == TAB_JDBC) && crp->Kdata) {
									if (schem && stricmp(schem, crp->Kdata->GetCharValue(i))) {
										sprintf(g->Message,
											"Several %s tables found, specify DBNAME", tab);
										rc = HA_ERR_INTERNAL_ERROR;
										goto err;
									} else if (!schem)
										schem = crp->Kdata->GetCharValue(i);

								} // endif ttp
#endif   // ODBC_SUPPORT	||				 JAVA_SUPPORT
							default:
								break;                 // Ignore
						} // endswitch Fld

#if defined(ODBC_SUPPORT)
					if (ttp == TAB_ODBC) {
						int  plgtyp;
						bool w = false;            // Wide character type

						// typ must be PLG type, not SQL type
						if (!(plgtyp = TranslateSQLType(typ, dec, prec, v, w))) {
							if (GetTypeConv() == TPC_SKIP) {
								// Skip this column
								sprintf(g->Message, "Column %s skipped (unsupported type %d)",
									cnm, typ);
								push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 0, g->Message);
								continue;
							} else {
								sprintf(g->Message, "Unsupported SQL type %d", typ);
								rc = HA_ERR_INTERNAL_ERROR;
								goto err;
							} // endif type_conv

						} else
							typ = plgtyp;

						switch (typ) {
							case TYPE_STRING:
								if (w) {
									sprintf(g->Message, "Column %s is wide characters", cnm);
									push_warning(thd, Sql_condition::WARN_LEVEL_NOTE, 0, g->Message);
								} // endif w

								break;
							case TYPE_DOUBLE:
								// Some data sources do not count dec in length (prec)
								prec += (dec + 2);        // To be safe
								break;
							case TYPE_DECIM:
								prec = len;
								break;
							default:
								dec = 0;
						} // endswitch typ

					} else
#endif   // ODBC_SUPPORT
#if defined(JAVA_SUPPORT)
						if (ttp == TAB_JDBC) {
							int  plgtyp;

							// typ must be PLG type, not SQL type
							if (!(plgtyp = TranslateJDBCType(typ, tn, dec, prec, v))) {
								if (GetTypeConv() == TPC_SKIP) {
									// Skip this column
									sprintf(g->Message, "Column %s skipped (unsupported type %d)",
										cnm, typ);
									push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 0, g->Message);
									continue;
								} else {
									sprintf(g->Message, "Unsupported SQL type %d", typ);
									rc = HA_ERR_INTERNAL_ERROR;
									goto err;
								} // endif type_conv

							} else
								typ = plgtyp;

							switch (typ) {
								case TYPE_DOUBLE:
								case TYPE_DECIM:
									// Some data sources do not count dec in length (prec)
									prec += (dec + 2);        // To be safe
									break;
								default:
									dec = 0;
							} // endswitch typ

						} else
#endif   // ODBC_SUPPORT
							// Make the arguments as required by add_fields
							if (typ == TYPE_DOUBLE)
								prec = len;

						if (typ == TYPE_DATE)
							prec = 0;

						// Now add the field
						if (add_field(&sql, cnm, typ, prec, dec, key, tm, rem, dft, xtra,
							fmt, 0, dbf, v))
							rc = HA_ERR_OUT_OF_MEM;
				} // endfor i

			} // endif fnc

			if (!rc)
				rc = init_table_share(thd, table_s, create_info, &sql);

			//g->jump_level--;
			//PopUser(xp);
			//return rc;
		} else {
			rc = HA_ERR_UNSUPPORTED;
		} // endif ok

	} catch (int n) {
		if (trace)
			htrc("Exception %d: %s\n", n, g->Message);
		rc = HA_ERR_INTERNAL_ERROR;
	} catch (const char *msg) {
		strcpy(g->Message, msg);
		rc = HA_ERR_INTERNAL_ERROR;
	} // end catch

 err:
  if (rc)
    my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));

	PopUser(xp);
	return rc;
} // end of connect_assisted_discovery

/**
  Get the database name from a qualified table name.
*/
char *ha_connect::GetDBfromName(const char *name)
{
  char *db, dbname[128], tbname[128];

  if (filename_to_dbname_and_tablename(name, dbname, sizeof(dbname),
                                             tbname, sizeof(tbname)))
    *dbname= 0;

  if (*dbname) {
    assert(xp && xp->g);
    db= (char*)PlugSubAlloc(xp->g, NULL, strlen(dbname + 1));
    strcpy(db, dbname);
  } else
    db= NULL;

  return db;
} // end of GetDBfromName


/**
  @brief
  create() is called to create a database. The variable name will have the name
  of the table.

  @details
  When create() is called you do not need to worry about
  opening the table. Also, the .frm file will have already been
  created so adjusting create_info is not necessary. You can overwrite
  the .frm file at this point if you wish to change the table
  definition, but there are no methods currently provided for doing
  so.

  Called from handle.cc by ha_create_table().

  @note
  Currently we do some checking on the create definitions and stop
  creating if an error is found. We wish we could change the table
  definition such as providing a default table type. However, as said
  above, there are no method to do so.

  @see
  ha_create_table() in handle.cc
*/

int ha_connect::create(const char *name, TABLE *table_arg,
                       HA_CREATE_INFO *create_info)
{
  int     rc= RC_OK;
  bool    dbf, inward;
  Field* *field;
  Field  *fp;
  TABTYPE type;
  TABLE  *st= table;                       // Probably unuseful
  THD    *thd= ha_thd();
	LEX_STRING cnc = table_arg->s->connect_string;
#ifdef WITH_PARTITION_STORAGE_ENGINE
  partition_info *part_info= table_arg->part_info;
#else
#define part_info 0
#endif   // WITH_PARTITION_STORAGE_ENGINE
  xp= GetUser(thd, xp);
  PGLOBAL g= xp->g;

  DBUG_ENTER("ha_connect::create");
  /*
    This assignment fixes test failures if some
    "ALTER TABLE t1 ADD KEY(a)" query exits on ER_ACCESS_DENIED_ERROR
    (e.g. on missing FILE_ACL). All following "CREATE TABLE" failed with
    "ERROR 1105: CONNECT index modification should be in-place"
    TODO: check with Olivier.
  */
  g->Xchk= NULL;
  int  sqlcom= thd_sql_command(table_arg->in_use);
  PTOS options= GetTableOptionStruct(table_arg->s);

  table= table_arg;         // Used by called functions

  if (trace)
    htrc("create: this=%p thd=%p xp=%p g=%p sqlcom=%d name=%s\n",
           this, thd, xp, g, sqlcom, GetTableName());

  // CONNECT engine specific table options:
  DBUG_ASSERT(options);
  type= GetTypeID(options->type);

  // Check table type
  if (type == TAB_UNDEF) {
    options->type= (options->srcdef)  ? "MYSQL" :
                   (options->tabname) ? "PROXY" : "DOS";
    type= GetTypeID(options->type);
    sprintf(g->Message, "No table_type. Will be set to %s", options->type);

    if (sqlcom == SQLCOM_CREATE_TABLE)
      push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 0, g->Message);

  } else if (type == TAB_NIY) {
    sprintf(g->Message, "Unsupported table type %s", options->type);
    my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
    DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
  } // endif ttp

  if (check_privileges(thd, options, GetDBfromName(name)))
    DBUG_RETURN(HA_ERR_INTERNAL_ERROR);

  inward= IsFileType(type) && !options->filename &&
		     (type != TAB_JSON || !cnc.length);

  if (options->data_charset) {
    const CHARSET_INFO *data_charset;

    if (!(data_charset= get_charset_by_csname(options->data_charset,
                                              MY_CS_PRIMARY, MYF(0)))) {
      my_error(ER_UNKNOWN_CHARACTER_SET, MYF(0), options->data_charset);
      DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
      } // endif charset

    if (type == TAB_XML && data_charset != &my_charset_utf8_general_ci) {
      my_printf_error(ER_UNKNOWN_ERROR,
                      "DATA_CHARSET='%s' is not supported for TABLE_TYPE=XML",
                        MYF(0), options->data_charset);
      DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
      } // endif utf8

    } // endif charset

  if (!g) {
    rc= HA_ERR_INTERNAL_ERROR;
    DBUG_RETURN(rc);
  } else
    dbf= (GetTypeID(options->type) == TAB_DBF && !options->catfunc);

  // Can be null in ALTER TABLE
  if (create_info->alias)
    // Check whether a table is defined on itself
    switch (type) {
      case TAB_PRX:
      case TAB_XCL:
      case TAB_PIVOT:
      case TAB_OCCUR:
        if (options->srcdef) {
          strcpy(g->Message, "Cannot check looping reference");
          push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 0, g->Message);
        } else if (options->tabname) {
          if (!stricmp(options->tabname, create_info->alias) &&
             (!options->dbname || 
              !stricmp(options->dbname, table_arg->s->db.str))) {
            sprintf(g->Message, "A %s table cannot refer to itself",
                                options->type);
            my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
            DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
            } // endif tab

        } else {
          strcpy(g->Message, "Missing object table name or definition");
          my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
          DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
        } // endif tabname

				// fall through
      case TAB_MYSQL:
        if (!part_info)
       {const char *src= options->srcdef;
				PCSZ host, db, tab= options->tabname;
        int  port;

        host= GetListOption(g, "host", options->oplist, NULL);
        db= GetStringOption("database", NULL);
        port= atoi(GetListOption(g, "port", options->oplist, "0"));

        if (create_info->connect_string.str &&
            create_info->connect_string.length) {
          char   *dsn= strz(g, create_info->connect_string);
          PMYDEF  mydef= new(g) MYSQLDEF();

          mydef->SetName(create_info->alias);

          if (!mydef->ParseURL(g, dsn, false)) {
            if (mydef->GetHostname())
              host= mydef->GetHostname();

						if (mydef->GetTabschema())
							db = mydef->GetTabschema();

            if (mydef->GetTabname())
              tab= mydef->GetTabname();

            if (mydef->GetPortnumber())
              port= mydef->GetPortnumber();

          } else {
            my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
            DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
          } // endif ParseURL

          } // endif connect_string

        if (CheckSelf(g, table_arg->s, host, db, tab, src, port)) {
          my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
          DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
          } // endif CheckSelf

       } break;
      default: /* do nothing */;
        break;
     } // endswitch ttp

  if (type == TAB_XML) {
    bool dom;                  // True: MS-DOM, False libxml2
		PCSZ xsup= GetListOption(g, "Xmlsup", options->oplist, "*");

    // Note that if no support is specified, the default is MS-DOM
    // on Windows and libxml2 otherwise
    switch (toupper(*xsup)) {
      case '*':
#if defined(__WIN__)
        dom= true;
#else   // !__WIN__
        dom= false;
#endif  // !__WIN__
        break;
      case 'M':
      case 'D':
        dom= true;
        break;
      default:
        dom= false;
        break;
      } // endswitch xsup

#if !defined(DOMDOC_SUPPORT)
    if (dom) {
      strcpy(g->Message, "MS-DOM not supported by this version");
      xsup= NULL;
      } // endif DomDoc
#endif   // !DOMDOC_SUPPORT

#if !defined(LIBXML2_SUPPORT)
    if (!dom) {
      strcpy(g->Message, "libxml2 not supported by this version");
      xsup= NULL;
      } // endif Libxml2
#endif   // !LIBXML2_SUPPORT

    if (!xsup) {
      my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
      rc= HA_ERR_INTERNAL_ERROR;
      DBUG_RETURN(rc);
      } // endif xsup

    } // endif type

  if (type == TAB_JSON) {
    int pretty= atoi(GetListOption(g, "Pretty", options->oplist, "2"));

    if (!options->lrecl && pretty != 2) {
      sprintf(g->Message, "LRECL must be specified for pretty=%d", pretty);
      my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
      rc= HA_ERR_INTERNAL_ERROR;
      DBUG_RETURN(rc);
      } // endif lrecl

    } // endif type	JSON

	if (type == TAB_CSV) {
		const char *sep = options->separator;

		if (sep && strlen(sep) > 1) {
			sprintf(g->Message, "Invalid separator %s", sep);
			my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
			rc= HA_ERR_INTERNAL_ERROR;
			DBUG_RETURN(rc);
		} // endif sep

	} // endif type	CSV

  // Check column types
  for (field= table_arg->field; *field; field++) {
    fp= *field;

    if (fp->vcol_info && !fp->stored_in_db)
      continue;            // This is a virtual column

    if (fp->flags & AUTO_INCREMENT_FLAG) {
      strcpy(g->Message, "Auto_increment is not supported yet");
      my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
      rc= HA_ERR_INTERNAL_ERROR;
      DBUG_RETURN(rc);
      } // endif flags

    if (fp->flags & (BLOB_FLAG | ENUM_FLAG | SET_FLAG)) {
      sprintf(g->Message, "Unsupported type for column %s",
                          fp->field_name);
      my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
      rc= HA_ERR_INTERNAL_ERROR;
      DBUG_RETURN(rc);
      } // endif flags

    if (type == TAB_VIR)
      if (!fp->option_struct || !fp->option_struct->special) {
        strcpy(g->Message, "Virtual tables accept only special or virtual columns");
        my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
        rc= HA_ERR_INTERNAL_ERROR;
        DBUG_RETURN(rc);
        } // endif special
      
    switch (fp->type()) {
      case MYSQL_TYPE_SHORT:
      case MYSQL_TYPE_LONG:
      case MYSQL_TYPE_FLOAT:
      case MYSQL_TYPE_DOUBLE:
      case MYSQL_TYPE_TIMESTAMP:
      case MYSQL_TYPE_DATE:
      case MYSQL_TYPE_TIME:
      case MYSQL_TYPE_DATETIME:
      case MYSQL_TYPE_YEAR:
      case MYSQL_TYPE_NEWDATE:
      case MYSQL_TYPE_LONGLONG:
      case MYSQL_TYPE_TINY:
      case MYSQL_TYPE_DECIMAL:
      case MYSQL_TYPE_NEWDECIMAL:
      case MYSQL_TYPE_INT24:
        break;                     // Ok
      case MYSQL_TYPE_VARCHAR:
      case MYSQL_TYPE_VAR_STRING:
      case MYSQL_TYPE_STRING:
#if 0
        if (!fp->field_length) {
          sprintf(g->Message, "Unsupported 0 length for column %s",
                              fp->field_name);
          rc= HA_ERR_INTERNAL_ERROR;
          my_printf_error(ER_UNKNOWN_ERROR,
                          "Unsupported 0 length for column %s",
                          MYF(0), fp->field_name);
          DBUG_RETURN(rc);
          } // endif fp
#endif // 0
        break;                     // To be checked
      case MYSQL_TYPE_BIT:
      case MYSQL_TYPE_NULL:
      case MYSQL_TYPE_ENUM:
      case MYSQL_TYPE_SET:
      case MYSQL_TYPE_TINY_BLOB:
      case MYSQL_TYPE_MEDIUM_BLOB:
      case MYSQL_TYPE_LONG_BLOB:
      case MYSQL_TYPE_BLOB:
      case MYSQL_TYPE_GEOMETRY:
      default:
//      fprintf(stderr, "Unsupported type column %s\n", fp->field_name);
        sprintf(g->Message, "Unsupported type for column %s",
                            fp->field_name);
        rc= HA_ERR_INTERNAL_ERROR;
        my_printf_error(ER_UNKNOWN_ERROR, "Unsupported type for column %s",
                        MYF(0), fp->field_name);
        DBUG_RETURN(rc);
        break;
      } // endswitch type

    if ((fp)->real_maybe_null() && !IsTypeNullable(type)) {
      my_printf_error(ER_UNKNOWN_ERROR,
                      "Table type %s does not support nullable columns",
                      MYF(0), options->type);
      DBUG_RETURN(HA_ERR_UNSUPPORTED);
      } // endif !nullable

    if (dbf) {
      bool b= false;

      if ((b= strlen(fp->field_name) > 10))
        sprintf(g->Message, "DBF: Column name '%s' is too long (max=10)",
                            fp->field_name);
      else if ((b= fp->field_length > 255))
        sprintf(g->Message, "DBF: Column length too big for '%s' (max=255)",
                            fp->field_name);

      if (b) {
        my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
        rc= HA_ERR_INTERNAL_ERROR;
        DBUG_RETURN(rc);
        } // endif b

      } // endif dbf

    } // endfor field

  if ((sqlcom == SQLCOM_CREATE_TABLE || *GetTableName() == '#') && inward) {
    // The file name is not specified, create a default file in
    // the database directory named table_name.table_type.
    // (temporarily not done for XML because a void file causes
    // the XML parsers to report an error on the first Insert)
    char buf[_MAX_PATH], fn[_MAX_PATH], dbpath[_MAX_PATH], lwt[12];
    int  h;

    // Check for incompatible options
    if (options->sepindex) {
      my_message(ER_UNKNOWN_ERROR,
            "SEPINDEX is incompatible with unspecified file name", MYF(0));
      DBUG_RETURN(HA_ERR_UNSUPPORTED);
		} else if (GetTypeID(options->type) == TAB_VEC) {
			if (!table->s->max_rows || options->split) {
				my_printf_error(ER_UNKNOWN_ERROR,
					"%s tables whose file name is unspecified cannot be split",
					MYF(0), options->type);
				DBUG_RETURN(HA_ERR_UNSUPPORTED);
			} else if (options->header == 2) {
				my_printf_error(ER_UNKNOWN_ERROR,
					"header=2 is not allowed for %s tables whose file name is unspecified",
					MYF(0), options->type);
				DBUG_RETURN(HA_ERR_UNSUPPORTED);
			} // endif's

		} else if (options->zipped) {
			my_message(ER_UNKNOWN_ERROR,
				"ZIPPED is incompatible with unspecified file name", MYF(0));
			DBUG_RETURN(HA_ERR_UNSUPPORTED);
		}	// endif's options

    // Fold type to lower case
    for (int i= 0; i < 12; i++)
      if (!options->type[i]) {
        lwt[i]= 0;
        break;
      } else
        lwt[i]= tolower(options->type[i]);

    if (part_info) {
      char *p;

      strcpy(dbpath, name);
      p= strrchr(dbpath, slash);
      strncpy(partname, ++p, sizeof(partname) - 1);
      strcat(strcat(strcpy(buf, p), "."), lwt);
      *p= 0;
    } else {
      strcat(strcat(strcpy(buf, GetTableName()), "."), lwt);
      sprintf(g->Message, "No file name. Table will use %s", buf);
  
      if (sqlcom == SQLCOM_CREATE_TABLE)
        push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 0, g->Message);
  
      strcat(strcat(strcpy(dbpath, "./"), table->s->db.str), "/");
    } // endif part_info

    PlugSetPath(fn, buf, dbpath);

    if ((h= ::open(fn, O_CREAT | O_EXCL, 0666)) == -1) {
      if (errno == EEXIST)
        sprintf(g->Message, "Default file %s already exists", fn);
      else
        sprintf(g->Message, "Error %d creating file %s", errno, fn);

      push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 0, g->Message);
    } else
      ::close(h);
    
    if ((type == TAB_FMT || options->readonly) && sqlcom == SQLCOM_CREATE_TABLE)
      push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 0,
        "Congratulation, you just created a read-only void table!");

    } // endif sqlcom

  if (trace)
    htrc("xchk=%p createas=%d\n", g->Xchk, g->Createas);

	if (options->zipped) {
		// Check whether the zip entry must be made from a file
		PCSZ fn = GetListOption(g, "Load", options->oplist, NULL);

		if (fn) {
			char zbuf[_MAX_PATH], buf[_MAX_PATH], dbpath[_MAX_PATH];
			PCSZ entry = GetListOption(g, "Entry", options->oplist, NULL);
			PCSZ a = GetListOption(g, "Append", options->oplist, "NO");
			bool append = *a == '1' || *a == 'Y' || *a == 'y' || !stricmp(a, "ON");
			PCSZ m = GetListOption(g, "Mulentries", options->oplist, "NO");
			bool mul = *m == '1' || *m == 'Y' || *m == 'y' || !stricmp(m, "ON");

			if (!entry && !mul) {
				my_message(ER_UNKNOWN_ERROR, "Missing entry name", MYF(0));
				DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
			}	// endif entry

			strcat(strcat(strcpy(dbpath, "./"), table->s->db.str), "/");
			PlugSetPath(zbuf, options->filename, dbpath);
			PlugSetPath(buf, fn, dbpath);

			if (ZipLoadFile(g, zbuf, buf, entry, append, mul)) {
				my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
				DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
			}	// endif LoadFile

		}	// endif fn

	}	// endif zipped

  // To check whether indexes have to be made or remade
  if (!g->Xchk) {
    PIXDEF xdp;

    // We should be in CREATE TABLE, ALTER_TABLE or CREATE INDEX
    if (!(sqlcom == SQLCOM_CREATE_TABLE || sqlcom == SQLCOM_ALTER_TABLE ||
          sqlcom == SQLCOM_CREATE_INDEX || sqlcom == SQLCOM_DROP_INDEX))  
//         (sqlcom == SQLCOM_CREATE_INDEX && part_info) ||  
//         (sqlcom == SQLCOM_DROP_INDEX && part_info)))  
      push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 0,
        "Unexpected command in create, please contact CONNECT team");

    if (part_info && !inward)
      strncpy(partname, decode(g, strrchr(name, '#') + 1), sizeof(partname) - 1);
//    strcpy(partname, part_info->curr_part_elem->partition_name);

    if (g->Alchecked == 0 &&
        (!IsFileType(type) || FileExists(options->filename, false))) {
      if (part_info) {
        sprintf(g->Message, "Data repartition in %s is unchecked", partname); 
        push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 0, g->Message);
      } else if (sqlcom == SQLCOM_ALTER_TABLE) {
        // This is an ALTER to CONNECT from another engine.
        // It cannot be accepted because the table data would be modified
        // except when the target file does not exist.
        strcpy(g->Message, "Operation denied. Table data would be modified.");
        my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
        DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
      } // endif part_info

      } // endif outward

    // Get the index definitions
    if ((xdp= GetIndexInfo()) || sqlcom == SQLCOM_DROP_INDEX) {
      if (options->multiple) {
        strcpy(g->Message, "Multiple tables are not indexable");
        my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
        rc= HA_ERR_UNSUPPORTED;
      } else if (options->compressed) {
        strcpy(g->Message, "Compressed tables are not indexable");
        my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
        rc= HA_ERR_UNSUPPORTED;
      } else if (GetIndexType(type) == 1) {
        PDBUSER dup= PlgGetUser(g);
        PCATLG  cat= (dup) ? dup->Catalog : NULL;

				if (SetDataPath(g, table_arg->s->db.str)) {
					my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
					rc = HA_ERR_INTERNAL_ERROR;
				} else if (cat) {
          if (part_info)
            strncpy(partname, 
                    decode(g, strrchr(name, (inward ? slash : '#')) + 1),
										sizeof(partname) - 1);

          if ((rc= optimize(table->in_use, NULL))) {
            htrc("Create rc=%d %s\n", rc, g->Message);
            my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
            rc= HA_ERR_INTERNAL_ERROR;
          } else
            CloseTable(g);

          } // endif cat
    
      } else if (GetIndexType(type) == 3) {
        if (CheckVirtualIndex(table_arg->s)) {
          my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
          rc= HA_ERR_UNSUPPORTED;
          } // endif Check

      } else if (!GetIndexType(type)) {
        sprintf(g->Message, "Table type %s is not indexable", options->type);
        my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
        rc= HA_ERR_UNSUPPORTED;
      } // endif index type

      } // endif xdp

  } else {
    // This should not happen anymore with indexing new way
    my_message(ER_UNKNOWN_ERROR,
               "CONNECT index modification should be in-place", MYF(0));
    DBUG_RETURN(HA_ERR_UNSUPPORTED);
  } // endif Xchk

  table= st;
  DBUG_RETURN(rc);
} // end of create

/**
  Used to check whether a file based outward table can be populated by
  an ALTER TABLE command. The conditions are:
  - file does not exist or is void
  - user has file privilege
*/
bool ha_connect::FileExists(const char *fn, bool bf)
{
  if (!fn || !*fn)
    return false;
  else if (IsPartitioned() && bf)
    return true;

  if (table) {
    const char *s;
		char  tfn[_MAX_PATH], filename[_MAX_PATH], path[_MAX_PATH];
		bool  b= false;
    int   n;
    struct stat info;

#if defined(__WIN__)
    s= "\\";
#else   // !__WIN__
    s= "/";
#endif  // !__WIN__
    if (IsPartitioned()) {
      sprintf(tfn, fn, GetPartName());

      // This is to avoid an initialization error raised by the
      // test on check_table_flags made in ha_partition::open
      // that can fail if some partition files are empty.
      b= true;
    } else
      strcpy(tfn, fn);

    strcat(strcat(strcat(strcpy(path, "."), s), table->s->db.str), s);
    PlugSetPath(filename, tfn, path);
    n= stat(filename, &info);

    if (n < 0) {
      if (errno != ENOENT) {
        char buf[_MAX_PATH + 20];

        sprintf(buf, "Error %d for file %s", errno, filename);
        push_warning(table->in_use, Sql_condition::WARN_LEVEL_WARN, 0, buf);
        return true;
      } else
        return false;

    } else
      return (info.st_size || b) ? true : false;

    } // endif table

  return true;
} // end of FileExists

// Called by SameString and NoFieldOptionChange
bool ha_connect::CheckString(PCSZ str1, PCSZ str2)
{
  bool  b1= (!str1 || !*str1), b2= (!str2 || !*str2);

  if (b1 && b2)
    return true;
  else if ((b1 && !b2) || (!b1 && b2) || stricmp(str1, str2))
    return false;

  return true;
} // end of CheckString

/**
  check whether a string option have changed
  */
bool ha_connect::SameString(TABLE *tab, PCSZ opn)
{
  PCSZ str1, str2;

  tshp= tab->s;                 // The altered table
  str1= GetStringOption(opn);
  tshp= NULL;
  str2= GetStringOption(opn);
  return CheckString(str1, str2);
} // end of SameString

/**
  check whether a Boolean option have changed
  */
bool ha_connect::SameBool(TABLE *tab, PCSZ opn)
{
  bool b1, b2;

  tshp= tab->s;                 // The altered table
  b1= GetBooleanOption(opn, false);
  tshp= NULL;
  b2= GetBooleanOption(opn, false);
  return (b1 == b2);
} // end of SameBool

/**
  check whether an integer option have changed
  */
bool ha_connect::SameInt(TABLE *tab, PCSZ opn)
{
  int i1, i2;

  tshp= tab->s;                 // The altered table
  i1= GetIntegerOption(opn);
  tshp= NULL;
  i2= GetIntegerOption(opn);

  if (!stricmp(opn, "lrecl"))
    return (i1 == i2 || !i1 || !i2);
  else if (!stricmp(opn, "ending"))
    return (i1 == i2 || i1 <= 0 || i2 <= 0);
  else
    return (i1 == i2);

} // end of SameInt

/**
  check whether a field option have changed
  */
bool ha_connect::NoFieldOptionChange(TABLE *tab)
{
  bool rc= true;
  ha_field_option_struct *fop1, *fop2;
  Field* *fld1= table->s->field;
  Field* *fld2= tab->s->field;

  for (; rc && *fld1 && *fld2; fld1++, fld2++) {
    fop1= (*fld1)->option_struct;
    fop2= (*fld2)->option_struct;

    rc= (fop1->offset == fop2->offset &&
         fop1->fldlen == fop2->fldlen &&
         CheckString(fop1->dateformat, fop2->dateformat) &&
         CheckString(fop1->fieldformat, fop2->fieldformat) &&
         CheckString(fop1->special, fop2->special));
    } // endfor fld

  return rc;
} // end of NoFieldOptionChange

 /**
    Check if a storage engine supports a particular alter table in-place

    @param    altered_table     TABLE object for new version of table.
    @param    ha_alter_info     Structure describing changes to be done
                                by ALTER TABLE and holding data used
                                during in-place alter.

    @retval   HA_ALTER_ERROR                  Unexpected error.
    @retval   HA_ALTER_INPLACE_NOT_SUPPORTED  Not supported, must use copy.
    @retval   HA_ALTER_INPLACE_EXCLUSIVE_LOCK Supported, but requires X lock.
    @retval   HA_ALTER_INPLACE_SHARED_LOCK_AFTER_PREPARE
                                              Supported, but requires SNW lock
                                              during main phase. Prepare phase
                                              requires X lock.
    @retval   HA_ALTER_INPLACE_SHARED_LOCK    Supported, but requires SNW lock.
    @retval   HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE
                                              Supported, concurrent reads/writes
                                              allowed. However, prepare phase
                                              requires X lock.
    @retval   HA_ALTER_INPLACE_NO_LOCK        Supported, concurrent
                                              reads/writes allowed.

    @note The default implementation uses the old in-place ALTER API
    to determine if the storage engine supports in-place ALTER or not.

    @note Called without holding thr_lock.c lock.
 */
enum_alter_inplace_result
ha_connect::check_if_supported_inplace_alter(TABLE *altered_table,
                                Alter_inplace_info *ha_alter_info)
{
  DBUG_ENTER("check_if_supported_alter");

  bool            idx= false, outward= false;
  THD            *thd= ha_thd();
  int             sqlcom= thd_sql_command(thd);
  TABTYPE         newtyp, type= TAB_UNDEF;
  HA_CREATE_INFO *create_info= ha_alter_info->create_info;
  PTOS            newopt, oldopt;
  xp= GetUser(thd, xp);
  PGLOBAL         g= xp->g;

  if (!g || !table) {
    my_message(ER_UNKNOWN_ERROR, "Cannot check ALTER operations", MYF(0));
    DBUG_RETURN(HA_ALTER_ERROR);
    } // endif Xchk

  newopt= altered_table->s->option_struct;
  oldopt= table->s->option_struct;

  // If this is the start of a new query, cleanup the previous one
  if (xp->CheckCleanup()) {
    tdbp= NULL;
    valid_info= false;
    } // endif CheckCleanup

  g->Alchecked= 1;       // Tested in create
  g->Xchk= NULL;
  type= GetRealType(oldopt);
  newtyp= GetRealType(newopt);

  // No copy algorithm for outward tables
  outward= (!IsFileType(type) || (oldopt->filename && *oldopt->filename));

  // Index operations
  Alter_inplace_info::HA_ALTER_FLAGS index_operations=
    Alter_inplace_info::ADD_INDEX |
    Alter_inplace_info::DROP_INDEX |
    Alter_inplace_info::ADD_UNIQUE_INDEX |
    Alter_inplace_info::DROP_UNIQUE_INDEX |
    Alter_inplace_info::ADD_PK_INDEX |
    Alter_inplace_info::DROP_PK_INDEX;

  Alter_inplace_info::HA_ALTER_FLAGS inplace_offline_operations=
    Alter_inplace_info::ALTER_COLUMN_EQUAL_PACK_LENGTH |
    Alter_inplace_info::ALTER_COLUMN_NAME |
    Alter_inplace_info::ALTER_COLUMN_DEFAULT |
    Alter_inplace_info::CHANGE_CREATE_OPTION |
    Alter_inplace_info::ALTER_RENAME |
    Alter_inplace_info::ALTER_PARTITIONED | index_operations;

  if (ha_alter_info->handler_flags & index_operations ||
      !SameString(altered_table, "optname") ||
      !SameBool(altered_table, "sepindex")) {
    if (newopt->multiple) {
      strcpy(g->Message, "Multiple tables are not indexable");
      my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
      DBUG_RETURN(HA_ALTER_ERROR);
    } else if (newopt->compressed) {
      strcpy(g->Message, "Compressed tables are not indexable");
      my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
      DBUG_RETURN(HA_ALTER_ERROR);
    } else if (GetIndexType(type) == 1) {
      g->Xchk= new(g) XCHK;
      PCHK xcp= (PCHK)g->Xchk;
  
      xcp->oldpix= GetIndexInfo(table->s);
      xcp->newpix= GetIndexInfo(altered_table->s);
      xcp->oldsep= GetBooleanOption("sepindex", false);
      xcp->oldsep= xcp->SetName(g, GetStringOption("optname"));
      tshp= altered_table->s;
      xcp->newsep= GetBooleanOption("sepindex", false);
      xcp->newsep= xcp->SetName(g, GetStringOption("optname"));
      tshp= NULL;
  
      if (trace && g->Xchk)
        htrc(
          "oldsep=%d newsep=%d oldopn=%s newopn=%s oldpix=%p newpix=%p\n",
                xcp->oldsep, xcp->newsep, 
                SVP(xcp->oldopn), SVP(xcp->newopn), 
                xcp->oldpix, xcp->newpix);
  
      if (sqlcom == SQLCOM_ALTER_TABLE)
        idx= true;
      else
        DBUG_RETURN(HA_ALTER_INPLACE_EXCLUSIVE_LOCK);

    } else if (GetIndexType(type) == 3) {
      if (CheckVirtualIndex(altered_table->s)) {
        my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
        DBUG_RETURN(HA_ALTER_ERROR);
        } // endif Check

    } else if (!GetIndexType(type)) {
      sprintf(g->Message, "Table type %s is not indexable", oldopt->type);
      my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
      DBUG_RETURN(HA_ALTER_ERROR);
    } // endif index type

    } // endif index operation

  if (!SameString(altered_table, "filename")) {
    if (!outward) {
      // Conversion to outward table is only allowed for file based
      // tables whose file does not exist.
      tshp= altered_table->s;
			PCSZ fn= GetStringOption("filename");
      tshp= NULL;

      if (FileExists(fn, false)) {
        strcpy(g->Message, "Operation denied. Table data would be lost.");
        my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
        DBUG_RETURN(HA_ALTER_ERROR);
      } else
        goto fin;

    } else
      goto fin;

    } // endif filename

  /* Is there at least one operation that requires copy algorithm? */
  if (ha_alter_info->handler_flags & ~inplace_offline_operations)
    goto fin;

  /*
    ALTER TABLE tbl_name CONVERT TO CHARACTER SET .. and
    ALTER TABLE table_name DEFAULT CHARSET = .. most likely
    change column charsets and so not supported in-place through
    old API.

    Changing of PACK_KEYS, MAX_ROWS and ROW_FORMAT options were
    not supported as in-place operations in old API either.
  */
  if (create_info->used_fields & (HA_CREATE_USED_CHARSET |
                                  HA_CREATE_USED_DEFAULT_CHARSET |
                                  HA_CREATE_USED_PACK_KEYS |
                                  HA_CREATE_USED_MAX_ROWS) ||
      (table->s->row_type != create_info->row_type))
    goto fin;

#if 0
  uint table_changes= (ha_alter_info->handler_flags &
                       Alter_inplace_info::ALTER_COLUMN_EQUAL_PACK_LENGTH) ?
    IS_EQUAL_PACK_LENGTH : IS_EQUAL_YES;

  if (table->file->check_if_incompatible_data(create_info, table_changes)
      == COMPATIBLE_DATA_YES)
    DBUG_RETURN(HA_ALTER_INPLACE_EXCLUSIVE_LOCK);
#endif // 0

  // This was in check_if_incompatible_data
  if (NoFieldOptionChange(altered_table) &&
      type == newtyp &&
      SameInt(altered_table, "lrecl") &&
      SameInt(altered_table, "elements") &&
      SameInt(altered_table, "header") &&
      SameInt(altered_table, "quoted") &&
      SameInt(altered_table, "ending") &&
      SameInt(altered_table, "compressed"))
    DBUG_RETURN(HA_ALTER_INPLACE_EXCLUSIVE_LOCK);

fin:
  if (idx) {
    // Indexing is only supported inplace
    my_message(ER_ALTER_OPERATION_NOT_SUPPORTED,
      "Alter operations not supported together by CONNECT", MYF(0));
    DBUG_RETURN(HA_ALTER_ERROR);
  } else if (outward) {
    if (IsFileType(type))
      push_warning(thd, Sql_condition::WARN_LEVEL_WARN, 0,
        "This is an outward table, table data were not modified.");

    DBUG_RETURN(HA_ALTER_INPLACE_EXCLUSIVE_LOCK);
  } else
    DBUG_RETURN(HA_ALTER_INPLACE_NOT_SUPPORTED);

} // end of check_if_supported_inplace_alter


/**
  check_if_incompatible_data() called if ALTER TABLE can't detect otherwise
  if new and old definition are compatible

  @details If there are no other explicit signs like changed number of
  fields this function will be called by compare_tables()
  (sql/sql_tables.cc) to decide should we rewrite whole table or only .frm
  file.

  @note: This function is no more called by check_if_supported_inplace_alter
*/

bool ha_connect::check_if_incompatible_data(HA_CREATE_INFO *, uint)
{
  DBUG_ENTER("ha_connect::check_if_incompatible_data");
  // TO DO: really implement and check it.
  push_warning(ha_thd(), Sql_condition::WARN_LEVEL_WARN, 0,
      "Unexpected call to check_if_incompatible_data.");
  DBUG_RETURN(COMPATIBLE_DATA_NO);
} // end of check_if_incompatible_data

/****************************************************************************
 * CONNECT MRR implementation: use DS-MRR
   This is just copied from myisam
 ***************************************************************************/

int ha_connect::multi_range_read_init(RANGE_SEQ_IF *seq, void *seq_init_param,
                                     uint n_ranges, uint mode,
                                     HANDLER_BUFFER *buf)
{
  return ds_mrr.dsmrr_init(this, seq, seq_init_param, n_ranges, mode, buf);
} // end of multi_range_read_init

int ha_connect::multi_range_read_next(range_id_t *range_info)
{
  return ds_mrr.dsmrr_next(range_info);
} // end of multi_range_read_next

ha_rows ha_connect::multi_range_read_info_const(uint keyno, RANGE_SEQ_IF *seq,
                                               void *seq_init_param,
                                               uint n_ranges, uint *bufsz,
                                               uint *flags, Cost_estimate *cost)
{
  /*
    This call is here because there is no location where this->table would
    already be known.
    TODO: consider moving it into some per-query initialization call.
  */
  ds_mrr.init(this, table);

  // MMR is implemented for "local" file based tables only
  if (!IsFileType(GetRealType(GetTableOptionStruct())))
    *flags|= HA_MRR_USE_DEFAULT_IMPL;

  ha_rows rows= ds_mrr.dsmrr_info_const(keyno, seq, seq_init_param, n_ranges,
                                        bufsz, flags, cost);
  xp->g->Mrr= !(*flags & HA_MRR_USE_DEFAULT_IMPL);
  return rows;
} // end of multi_range_read_info_const

ha_rows ha_connect::multi_range_read_info(uint keyno, uint n_ranges, uint keys,
                                         uint key_parts, uint *bufsz,
                                         uint *flags, Cost_estimate *cost)
{
  ds_mrr.init(this, table);

  // MMR is implemented for "local" file based tables only
  if (!IsFileType(GetRealType(GetTableOptionStruct())))
    *flags|= HA_MRR_USE_DEFAULT_IMPL;

  ha_rows rows= ds_mrr.dsmrr_info(keyno, n_ranges, keys, key_parts, bufsz,
                                  flags, cost);
  xp->g->Mrr= !(*flags & HA_MRR_USE_DEFAULT_IMPL);
  return rows;
} // end of multi_range_read_info


int ha_connect::multi_range_read_explain_info(uint mrr_mode, char *str,
                                             size_t size)
{
  return ds_mrr.dsmrr_explain_info(mrr_mode, str, size);
} // end of multi_range_read_explain_info

/* CONNECT MRR implementation ends */

#if 0
// Does this make sens for CONNECT?
Item *ha_connect::idx_cond_push(uint keyno_arg, Item* idx_cond_arg)
{
  pushed_idx_cond_keyno= keyno_arg;
  pushed_idx_cond= idx_cond_arg;
  in_range_check_pushed_down= TRUE;
  if (active_index == pushed_idx_cond_keyno)
    mi_set_index_cond_func(file, handler_index_cond_check, this);
  return NULL;
}
#endif // 0


struct st_mysql_storage_engine connect_storage_engine=
{ MYSQL_HANDLERTON_INTERFACE_VERSION };

/***********************************************************************/
/*  CONNECT global variables definitions.                              */
/***********************************************************************/
#if defined(XMAP)
// Using file mapping for indexes if true
static MYSQL_SYSVAR_BOOL(indx_map, xmap, PLUGIN_VAR_RQCMDARG,
       "Using file mapping for indexes", NULL, NULL, 0);
#endif   // XMAP

#if defined(XMSG)
static MYSQL_SYSVAR_STR(errmsg_dir_path, msg_path,
//     PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_MEMALLOC,
       PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
       "Path to the directory where are the message files",
//     check_msg_path, update_msg_path,
       NULL, NULL,
       "../../../../storage/connect/");     // for testing
#endif   // XMSG

#if defined(JAVA_SUPPORT)
static MYSQL_SYSVAR_STR(jvm_path, JvmPath,
	PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_MEMALLOC,
	"Path to the directory where is the JVM lib",
	//     check_jvm_path, update_jvm_path,
	NULL, NULL,	NULL);

static MYSQL_SYSVAR_STR(class_path, ClassPath,
	PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_MEMALLOC,
	"Java class path",
	//     check_class_path, update_class_path,
	NULL, NULL, NULL);
#endif   // JAVA_SUPPORT


static struct st_mysql_sys_var* connect_system_variables[]= {
  MYSQL_SYSVAR(xtrace),
  MYSQL_SYSVAR(conv_size),
  MYSQL_SYSVAR(type_conv),
#if defined(XMAP)
  MYSQL_SYSVAR(indx_map),
#endif   // XMAP
  MYSQL_SYSVAR(work_size),
  MYSQL_SYSVAR(use_tempfile),
  MYSQL_SYSVAR(exact_info),
#if defined(XMSG) || defined(NEWMSG)
  MYSQL_SYSVAR(msg_lang),
#endif   // XMSG || NEWMSG
#if defined(XMSG)
  MYSQL_SYSVAR(errmsg_dir_path),
#endif   // XMSG
	MYSQL_SYSVAR(json_null),
  MYSQL_SYSVAR(json_grp_size),
#if defined(JAVA_SUPPORT)
	MYSQL_SYSVAR(jvm_path),
	MYSQL_SYSVAR(class_path),
	MYSQL_SYSVAR(java_wrapper),
#endif   // JAVA_SUPPORT
#if defined(JAVA_SUPPORT)
//MYSQL_SYSVAR(enable_mongo),
#endif   // JAVA_SUPPORT
NULL
};

maria_declare_plugin(connect)
{
  MYSQL_STORAGE_ENGINE_PLUGIN,
  &connect_storage_engine,
  "CONNECT",
  "Olivier Bertrand",
  "Management of External Data (SQL/NOSQL/MED), including many file formats",
  PLUGIN_LICENSE_GPL,
  connect_init_func,                            /* Plugin Init */
  connect_done_func,                            /* Plugin Deinit */
  0x0106,                                       /* version number (1.05) */
  NULL,                                         /* status variables */
  connect_system_variables,                     /* system variables */
  "1.06.0005",                                  /* string version */
	MariaDB_PLUGIN_MATURITY_STABLE                /* maturity */
}
maria_declare_plugin_end;