~drizzle-trunk/drizzle/development

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
/*
  Copyright (C) 2010 Stewart Smith

  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; either version 2
  of the License, or (at your option) any later version.

  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  02110-1301, USA.
*/

/* innobase_get_int_col_max_value() comes from ha_innodb.cc which is under
   the following license and Copyright */

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

Copyright (C) 2000, 2009, MySQL AB & Innobase Oy. All Rights Reserved.
Copyright (C) 2008, 2009 Google Inc.

Portions of this file contain modifications contributed and copyrighted by
Google, Inc. Those modifications are gratefully acknowledged and are described
briefly in the InnoDB documentation. The contributions by Google are
incorporated with their permission, and subject to the conditions contained in
the file COPYING.Google.

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
St, Fifth Floor, Boston, MA 02110-1301 USA

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

Copyright (C) 1995, 2009, Innobase Oy. All Rights Reserved.
Copyright (C) 2009, Percona Inc.

Portions of this file contain modifications contributed and copyrighted
by Percona Inc.. Those modifications are
gratefully acknowledged and are described briefly in the InnoDB
documentation. The contributions by Percona Inc. are incorporated with
their permission, and subject to the conditions contained in the file
COPYING.Percona.

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 St, Fifth Floor, Boston, MA 02110-1301 USA

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


#include <config.h>
#include <drizzled/table.h>
#include <drizzled/error.h>
#include <drizzled/internal/my_pthread.h>
#include <drizzled/plugin/transactional_storage_engine.h>
#include <drizzled/plugin/error_message.h>

#include <fcntl.h>
#include <stdarg.h>

#include <string>
#include <boost/algorithm/string.hpp>
#include <boost/unordered_set.hpp>
#include <boost/foreach.hpp>
#include <map>
#include <fstream>
#include <drizzled/message/table.pb.h>
#include <drizzled/internal/m_string.h>

#include <drizzled/global_charset_info.h>

#include "haildb_datadict_dump_func.h"
#include "config_table_function.h"
#include "status_table_function.h"

#include <haildb.h>

#include "haildb_engine.h"

#include <drizzled/field.h>
#include <drizzled/field/blob.h>
#include <drizzled/field/enum.h>
#include <drizzled/session.h>
#include <drizzled/module/option_map.h>
#include <drizzled/charset.h>
#include <drizzled/current_session.h>

#include <drizzled/key.h>

#include <iostream>

namespace po= boost::program_options;
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace google;
using namespace drizzled;

int read_row_from_haildb(Session *session, unsigned char* buf, ib_crsr_t cursor, ib_tpl_t tuple, Table* table, bool has_hidden_primary_key, uint64_t *hidden_pkey, drizzled::memory::Root **blobroot= NULL);
static void fill_ib_search_tpl_from_drizzle_key(ib_tpl_t search_tuple,
                                                const drizzled::KeyInfo *key_info,
                                                const unsigned char *key_ptr,
                                                uint32_t key_len);
static void store_key_value_from_haildb(KeyInfo *key_info, unsigned char* ref, int ref_len, const unsigned char *record);

#define HAILDB_EXT ".EID"

const char HAILDB_TABLE_DEFINITIONS_TABLE[]= "data_dictionary/haildb_table_definitions";
const string statement_savepoint_name("STATEMENT");

static boost::unordered_set<std::string> haildb_system_table_names;


static const char *HailDBCursor_exts[] = {
  NULL
};

class HailDBEngine : public drizzled::plugin::TransactionalStorageEngine
{
public:
  HailDBEngine(const string &name_arg)
   : drizzled::plugin::TransactionalStorageEngine(name_arg,
                                                  HTON_NULL_IN_KEY |
                                                  HTON_CAN_INDEX_BLOBS |
                                                  HTON_AUTO_PART_KEY |
                                                  HTON_PARTIAL_COLUMN_READ |
                                                  HTON_HAS_DOES_TRANSACTIONS)
  {
    table_definition_ext= HAILDB_EXT;
  }

  ~HailDBEngine();

  virtual Cursor *create(Table &table)
  {
    return new HailDBCursor(*this, table);
  }

  const char **bas_ext() const {
    return HailDBCursor_exts;
  }

  bool validateCreateTableOption(const std::string &key,
                                 const std::string &state);

  int doCreateTable(Session&,
                    Table& table_arg,
                    const drizzled::identifier::Table &identifier,
                    drizzled::message::Table& proto);

  int doDropTable(Session&, const identifier::Table &identifier);

  int doRenameTable(drizzled::Session&,
                    const drizzled::identifier::Table&,
                    const drizzled::identifier::Table&);

  int doGetTableDefinition(Session& session,
                           const identifier::Table &identifier,
                           drizzled::message::Table &table_proto);

  bool doDoesTableExist(Session&, const identifier::Table &identifier);

private:
  void getTableNamesInSchemaFromHailDB(const drizzled::identifier::Schema &schema,
                                       drizzled::plugin::TableNameList *set_of_names,
                                       drizzled::identifier::Table::vector *identifiers);

public:
  void doGetTableIdentifiers(drizzled::CachedDirectory &,
                             const drizzled::identifier::Schema &schema,
                             drizzled::identifier::Table::vector &identifiers);

  /* The following defines can be increased if necessary */
  uint32_t max_supported_keys()          const { return 1000; }
  uint32_t max_supported_key_length()    const { return 3500; }
  uint32_t max_supported_key_part_length() const { return 767; }

  uint32_t index_flags(enum  ha_key_alg) const
  {
    return (HA_READ_NEXT |
            HA_READ_PREV |
            HA_READ_RANGE |
            HA_READ_ORDER |
            HA_KEYREAD_ONLY);
  }
  virtual int doStartTransaction(Session *session,
                                 start_transaction_option_t options);
  virtual void doStartStatement(Session *session);
  virtual void doEndStatement(Session *session);

  virtual int doSetSavepoint(Session* session,
                                 drizzled::NamedSavepoint &savepoint);
  virtual int doRollbackToSavepoint(Session* session,
                                     drizzled::NamedSavepoint &savepoint);
  virtual int doReleaseSavepoint(Session* session,
                                     drizzled::NamedSavepoint &savepoint);
  virtual int doCommit(Session* session, bool all);
  virtual int doRollback(Session* session, bool all);

  typedef std::map<std::string, HailDBTableShare*> HailDBMap;
  HailDBMap haildb_open_tables;
  HailDBTableShare *findOpenTable(const std::string table_name);
  void addOpenTable(const std::string &table_name, HailDBTableShare *);
  void deleteOpenTable(const std::string &table_name);

  uint64_t getInitialAutoIncrementValue(HailDBCursor *cursor);
  uint64_t getHiddenPrimaryKeyInitialAutoIncrementValue(HailDBCursor *cursor);

};

static drizzled::plugin::StorageEngine *haildb_engine= NULL;


static ib_trx_t* get_trx(Session* session)
{
  return (ib_trx_t*) session->getEngineData(haildb_engine);
}

/* This is a superset of the map from innobase plugin.
   Unlike innobase plugin we don't act on errors here, we just
   map error codes. */
static int ib_err_t_to_drizzle_error(Session* session, ib_err_t err)
{
  switch (err)
  {
  case DB_SUCCESS:
    return 0;

  case DB_ERROR:
  default:
    return -1;

  case DB_INTERRUPTED:
    return ER_QUERY_INTERRUPTED; // FIXME: is this correct?

  case DB_OUT_OF_MEMORY:
    return HA_ERR_OUT_OF_MEM;

  case DB_DUPLICATE_KEY:
    return HA_ERR_FOUND_DUPP_KEY;

  case DB_FOREIGN_DUPLICATE_KEY:
    return HA_ERR_FOREIGN_DUPLICATE_KEY;

  case DB_MISSING_HISTORY:
    return HA_ERR_TABLE_DEF_CHANGED;

  case DB_RECORD_NOT_FOUND:
    return HA_ERR_NO_ACTIVE_RECORD;

  case DB_DEADLOCK:
    /* HailDB will roll back a transaction itself due to DB_DEADLOCK.
       This means we have to tell Drizzle about it */
    session->markTransactionForRollback(true);
    return HA_ERR_LOCK_DEADLOCK;

  case DB_LOCK_WAIT_TIMEOUT:
    session->markTransactionForRollback(false);
    return HA_ERR_LOCK_WAIT_TIMEOUT;

  case DB_NO_REFERENCED_ROW:
    return HA_ERR_NO_REFERENCED_ROW;

  case DB_ROW_IS_REFERENCED:
    return HA_ERR_ROW_IS_REFERENCED;

  case DB_CANNOT_ADD_CONSTRAINT:
    return HA_ERR_CANNOT_ADD_FOREIGN;

  case DB_CANNOT_DROP_CONSTRAINT:
    return HA_ERR_ROW_IS_REFERENCED; /* misleading. should have new err code */

  case DB_COL_APPEARS_TWICE_IN_INDEX:
  case DB_CORRUPTION:
    return HA_ERR_CRASHED;

  case DB_MUST_GET_MORE_FILE_SPACE:
  case DB_OUT_OF_FILE_SPACE:
    return HA_ERR_RECORD_FILE_FULL;

  case DB_TABLE_IS_BEING_USED:
    return HA_ERR_WRONG_COMMAND;

  case DB_TABLE_NOT_FOUND:
    return HA_ERR_NO_SUCH_TABLE;

  case DB_TOO_BIG_RECORD:
    return HA_ERR_TO_BIG_ROW;

  case DB_NO_SAVEPOINT:
    return HA_ERR_NO_SAVEPOINT;

  case DB_LOCK_TABLE_FULL:
    return HA_ERR_LOCK_TABLE_FULL;

  case DB_PRIMARY_KEY_IS_NULL:
    return ER_PRIMARY_CANT_HAVE_NULL;

  case DB_TOO_MANY_CONCURRENT_TRXS:
    return HA_ERR_RECORD_FILE_FULL; /* need better error code */

  case DB_END_OF_INDEX:
    return HA_ERR_END_OF_FILE;

  case DB_UNSUPPORTED:
    return HA_ERR_UNSUPPORTED;
  }
}

static ib_trx_level_t tx_isolation_to_ib_trx_level(enum_tx_isolation level)
{
  switch(level)
  {
  case ISO_REPEATABLE_READ:
    return IB_TRX_REPEATABLE_READ;
  case ISO_READ_COMMITTED:
    return IB_TRX_READ_COMMITTED;
  case ISO_SERIALIZABLE:
    return IB_TRX_SERIALIZABLE;
  case ISO_READ_UNCOMMITTED:
    return IB_TRX_READ_UNCOMMITTED;
  }

  assert(0);
  return IB_TRX_REPEATABLE_READ;
}

int HailDBEngine::doStartTransaction(Session *session,
                                             start_transaction_option_t options)
{
  ib_trx_t *transaction;
  ib_trx_level_t isolation_level;

  (void)options;

  transaction= get_trx(session);
  isolation_level= tx_isolation_to_ib_trx_level(session->getTxIsolation());
  *transaction= ib_trx_begin(isolation_level);

  return *transaction == NULL;
}

void HailDBEngine::doStartStatement(Session *session)
{
  if(*get_trx(session) == NULL)
    doStartTransaction(session, START_TRANS_NO_OPTIONS);

  ib_savepoint_take(*get_trx(session), statement_savepoint_name.c_str(),
                    statement_savepoint_name.length());
}

void HailDBEngine::doEndStatement(Session *)
{
}

int HailDBEngine::doSetSavepoint(Session* session,
                                         drizzled::NamedSavepoint &savepoint)
{
  ib_trx_t *transaction= get_trx(session);
  ib_savepoint_take(*transaction, savepoint.getName().c_str(),
                    savepoint.getName().length());
  return 0;
}

int HailDBEngine::doRollbackToSavepoint(Session* session,
                                                drizzled::NamedSavepoint &savepoint)
{
  ib_trx_t *transaction= get_trx(session);
  ib_err_t err;

  err= ib_savepoint_rollback(*transaction, savepoint.getName().c_str(),
                             savepoint.getName().length());

  return ib_err_t_to_drizzle_error(session, err);
}

int HailDBEngine::doReleaseSavepoint(Session* session,
                                             drizzled::NamedSavepoint &savepoint)
{
  ib_trx_t *transaction= get_trx(session);
  ib_err_t err;

  err= ib_savepoint_release(*transaction, savepoint.getName().c_str(),
                            savepoint.getName().length());
  if (err != DB_SUCCESS)
    return ib_err_t_to_drizzle_error(session, err);

  return 0;
}

int HailDBEngine::doCommit(Session* session, bool all)
{
  ib_err_t err;
  ib_trx_t *transaction= get_trx(session);

  if (all)
  {
    err= ib_trx_commit(*transaction);

    if (err != DB_SUCCESS)
      return ib_err_t_to_drizzle_error(session, err);

    *transaction= NULL;
  }

  return 0;
}

int HailDBEngine::doRollback(Session* session, bool all)
{
  ib_err_t err;
  ib_trx_t *transaction= get_trx(session);

  if (all)
  {
    if (ib_trx_state(*transaction) == IB_TRX_NOT_STARTED)
      err= ib_trx_release(*transaction);
    else
      err= ib_trx_rollback(*transaction);

    if (err != DB_SUCCESS)
      return ib_err_t_to_drizzle_error(session, err);

    *transaction= NULL;
  }
  else
  {
    if (ib_trx_state(*transaction) == IB_TRX_NOT_STARTED)
      return 0;

    err= ib_savepoint_rollback(*transaction, statement_savepoint_name.c_str(),
                               statement_savepoint_name.length());
    if (err != DB_SUCCESS)
      return ib_err_t_to_drizzle_error(session, err);
  }

  return 0;
}

HailDBTableShare *HailDBEngine::findOpenTable(const string table_name)
{
  HailDBMap::iterator find_iter=
    haildb_open_tables.find(table_name);

  if (find_iter != haildb_open_tables.end())
    return (*find_iter).second;
  else
    return NULL;
}

void HailDBEngine::addOpenTable(const string &table_name, HailDBTableShare *share)
{
  haildb_open_tables[table_name]= share;
}

void HailDBEngine::deleteOpenTable(const string &table_name)
{
  haildb_open_tables.erase(table_name);
}

static pthread_mutex_t haildb_mutex= PTHREAD_MUTEX_INITIALIZER;

uint64_t HailDBCursor::getHiddenPrimaryKeyInitialAutoIncrementValue()
{
  uint64_t nr;
  ib_err_t err;
  ib_trx_t transaction= *get_trx(getTable()->in_use);
  ib_cursor_attach_trx(cursor, transaction);
  tuple= ib_clust_read_tuple_create(cursor);
  err= ib_cursor_last(cursor);
  assert(err == DB_SUCCESS || err == DB_END_OF_INDEX); // Probably a FIXME
  err= ib_cursor_read_row(cursor, tuple);
  if (err == DB_RECORD_NOT_FOUND)
    nr= 1;
  else
  {
    assert (err == DB_SUCCESS);
    err= ib_tuple_read_u64(tuple, getTable()->getShare()->sizeFields(), &nr);
    nr++;
  }
  ib_tuple_delete(tuple);
  tuple= NULL;
  err= ib_cursor_reset(cursor);
  assert(err == DB_SUCCESS);
  return nr;
}

uint64_t HailDBCursor::getInitialAutoIncrementValue()
{
  uint64_t nr;
  int error;

  (void) extra(HA_EXTRA_KEYREAD);
  getTable()->mark_columns_used_by_index_no_reset(getTable()->getShare()->next_number_index);
  doStartIndexScan(getTable()->getShare()->next_number_index, 1);
  if (getTable()->getShare()->next_number_keypart == 0)
  {						// Autoincrement at key-start
    error=index_last(getTable()->getUpdateRecord());
  }
  else
  {
    unsigned char key[MAX_KEY_LENGTH];
    key_copy(key, getTable()->getInsertRecord(),
             getTable()->key_info + getTable()->getShare()->next_number_index,
             getTable()->getShare()->next_number_key_offset);
    error= index_read_map(getTable()->getUpdateRecord(), key,
                          make_prev_keypart_map(getTable()->getShare()->next_number_keypart),
                          HA_READ_PREFIX_LAST);
  }

  if (error)
    nr=1;
  else
    nr= ((uint64_t) getTable()->found_next_number_field->
         val_int_offset(getTable()->getShare()->rec_buff_length)+1);
  doEndIndexScan();
  (void) extra(HA_EXTRA_NO_KEYREAD);

  if (getTable()->getShare()->getTableMessage()->options().auto_increment_value() > nr)
    nr= getTable()->getShare()->getTableMessage()->options().auto_increment_value();

  return nr;
}

HailDBTableShare::HailDBTableShare(const char* name, bool hidden_primary_key)
  : use_count(0), has_hidden_primary_key(hidden_primary_key)
{
  table_name.assign(name);
}

uint64_t HailDBEngine::getInitialAutoIncrementValue(HailDBCursor *cursor)
{
  doStartTransaction(current_session, START_TRANS_NO_OPTIONS);
  uint64_t initial_auto_increment_value= cursor->getInitialAutoIncrementValue();
  doCommit(current_session, true);

  return initial_auto_increment_value;
}

uint64_t HailDBEngine::getHiddenPrimaryKeyInitialAutoIncrementValue(HailDBCursor *cursor)
{
  doStartTransaction(current_session, START_TRANS_NO_OPTIONS);
  uint64_t initial_auto_increment_value= cursor->getHiddenPrimaryKeyInitialAutoIncrementValue();
  doCommit(current_session, true);

  return initial_auto_increment_value;
}

HailDBTableShare *HailDBCursor::get_share(const char *table_name, bool has_hidden_primary_key, int *rc)
{
  pthread_mutex_lock(&haildb_mutex);

  HailDBEngine *a_engine= static_cast<HailDBEngine *>(getEngine());
  share= a_engine->findOpenTable(table_name);

  if (!share)
  {
    share= new HailDBTableShare(table_name, has_hidden_primary_key);

    if (share == NULL)
    {
      pthread_mutex_unlock(&haildb_mutex);
      *rc= HA_ERR_OUT_OF_MEM;
      return(NULL);
    }

    if (getTable()->found_next_number_field)
    {
      share->auto_increment_value.fetch_and_store(
                                  a_engine->getInitialAutoIncrementValue(this));

    }

    if (has_hidden_primary_key)
    {
      uint64_t hidden_pkey= 0;
      hidden_pkey= a_engine->getHiddenPrimaryKeyInitialAutoIncrementValue(this);
      share->hidden_pkey_auto_increment_value.fetch_and_store(hidden_pkey);
    }

    a_engine->addOpenTable(share->table_name, share);
    thr_lock_init(&share->lock);
  }
  share->use_count++;

  pthread_mutex_unlock(&haildb_mutex);

  return(share);
}

int HailDBCursor::free_share()
{
  pthread_mutex_lock(&haildb_mutex);
  if (!--share->use_count)
  {
    HailDBEngine *a_engine= static_cast<HailDBEngine *>(getEngine());
    a_engine->deleteOpenTable(share->table_name);
    delete share;
  }
  pthread_mutex_unlock(&haildb_mutex);

  return 0;
}


THR_LOCK_DATA **HailDBCursor::store_lock(Session *session,
                                                 THR_LOCK_DATA **to,
                                                 thr_lock_type lock_type)
{
  /* Currently, we can get a transaction start by ::store_lock
     instead of beginTransaction, startStatement.

     See https://bugs.launchpad.net/drizzle/+bug/535528

     all stemming from the transactional engine interface needing
     a severe amount of immodium.
   */

  if(*get_trx(session) == NULL)
  {
    static_cast<HailDBEngine*>(getEngine())->
                    doStartTransaction(session, START_TRANS_NO_OPTIONS);
  }

  if (lock_type != TL_UNLOCK)
  {
    ib_savepoint_take(*get_trx(session), statement_savepoint_name.c_str(),
                      statement_savepoint_name.length());
  }

  /* the below is adapted from ha_innodb.cc */

  const uint32_t sql_command = session->getSqlCommand();

  if (sql_command == SQLCOM_DROP_TABLE) {

    /* MySQL calls this function in DROP Table though this table
    handle may belong to another session that is running a query.
    Let us in that case skip any changes to the prebuilt struct. */ 

  } else if (lock_type == TL_READ_WITH_SHARED_LOCKS
       || lock_type == TL_READ_NO_INSERT
       || (lock_type != TL_IGNORE
           && sql_command != SQLCOM_SELECT)) {

    /* The OR cases above are in this order:
    1) MySQL is doing LOCK TABLES ... READ LOCAL, or we
    are processing a stored procedure or function, or
    2) (we do not know when TL_READ_HIGH_PRIORITY is used), or
    3) this is a SELECT ... IN SHARE MODE, or
    4) we are doing a complex SQL statement like
    INSERT INTO ... SELECT ... and the logical logging (MySQL
    binlog) requires the use of a locking read, or
    MySQL is doing LOCK TABLES ... READ.
    5) we let InnoDB do locking reads for all SQL statements that
    are not simple SELECTs; note that select_lock_type in this
    case may get strengthened in ::external_lock() to LOCK_X.
    Note that we MUST use a locking read in all data modifying
    SQL statements, because otherwise the execution would not be
    serializable, and also the results from the update could be
    unexpected if an obsolete consistent read view would be
    used. */

    enum_tx_isolation isolation_level= session->getTxIsolation();

    if (isolation_level != ISO_SERIALIZABLE
        && (lock_type == TL_READ || lock_type == TL_READ_NO_INSERT)
        && (sql_command == SQLCOM_INSERT_SELECT
      || sql_command == SQLCOM_UPDATE
      || sql_command == SQLCOM_CREATE_TABLE)) {

      /* If we either have innobase_locks_unsafe_for_binlog
      option set or this session is using READ COMMITTED
      isolation level and isolation level of the transaction
      is not set to serializable and MySQL is doing
      INSERT INTO...SELECT or UPDATE ... = (SELECT ...) or
      CREATE  ... SELECT... without FOR UPDATE or
      IN SHARE MODE in select, then we use consistent
      read for select. */

      ib_lock_mode= IB_LOCK_NONE;
    } else if (sql_command == SQLCOM_CHECKSUM) {
      /* Use consistent read for checksum table */

      ib_lock_mode= IB_LOCK_NONE;
    } else {
      ib_lock_mode= IB_LOCK_S;
    }

  } else if (lock_type != TL_IGNORE) {

    /* We set possible LOCK_X value in external_lock, not yet
    here even if this would be SELECT ... FOR UPDATE */
    ib_lock_mode= IB_LOCK_NONE;
  }

  if (lock_type != TL_IGNORE && lock.type == TL_UNLOCK) {

    /* If we are not doing a LOCK TABLE, DISCARD/IMPORT
    TABLESPACE or TRUNCATE TABLE then allow multiple
    writers. Note that ALTER TABLE uses a TL_WRITE_ALLOW_READ
    < TL_WRITE_CONCURRENT_INSERT.
    */

    if ((lock_type >= TL_WRITE_CONCURRENT_INSERT
         && lock_type <= TL_WRITE)
        && ! session->doing_tablespace_operation()
        && sql_command != SQLCOM_TRUNCATE
        && sql_command != SQLCOM_CREATE_TABLE) {

      lock_type = TL_WRITE_ALLOW_WRITE;
    }

    /* In queries of type INSERT INTO t1 SELECT ... FROM t2 ...
    MySQL would use the lock TL_READ_NO_INSERT on t2, and that
    would conflict with TL_WRITE_ALLOW_WRITE, blocking all inserts
    to t2. Convert the lock to a normal read lock to allow
    concurrent inserts to t2.
    */

    if (lock_type == TL_READ_NO_INSERT) {

      lock_type = TL_READ;
    }

    lock.type = lock_type;
  }

  *to++= &lock;

  return to;
}

void HailDBCursor::get_auto_increment(uint64_t, //offset,
                                              uint64_t, //increment,
                                              uint64_t, //nb_dis,
                                              uint64_t *first_value,
                                              uint64_t *nb_reserved_values)
{
fetch:
  *first_value= share->auto_increment_value.fetch_and_increment();
  if (*first_value == 0)
  {
    /* if it's zero, then we skip it... why? because of ass.
       set auto-inc to -1 and the sequence is:
       -1, 1.
       Zero is still "magic".
    */
    share->auto_increment_value.compare_and_swap(1, 0);
    goto fetch;
  }
  *nb_reserved_values= 1;
}

static const char* table_path_to_haildb_name(const char* name)
{
  size_t l= strlen(name);
  static string datadict_path("data_dictionary/");
  static string sys_prefix("data_dictionary/haildb_");
  static string sys_table_prefix("HAILDB_");

  if (strncmp(name, sys_prefix.c_str(), sys_prefix.length()) == 0)
  {
    string find_name(name+datadict_path.length());
    std::transform(find_name.begin(), find_name.end(), find_name.begin(), ::toupper);
    boost::unordered_set<string>::iterator iter= haildb_system_table_names.find(find_name);
    if (iter != haildb_system_table_names.end())
      return iter->c_str()+sys_table_prefix.length();
  }

  int slashes= 2;
  while(slashes>0 && l > 0)
  {
    l--;
    if (name[l] == '/')
      slashes--;
  }
  if (slashes==0)
    l++;

  return &name[l];
}

static void TableIdentifier_to_haildb_name(const identifier::Table &identifier, std::string *str)
{
  str->assign(table_path_to_haildb_name(identifier.getPath().c_str()));
}

HailDBCursor::HailDBCursor(drizzled::plugin::StorageEngine &engine_arg,
                           Table &table_arg)
  :Cursor(engine_arg, table_arg),
   ib_lock_mode(IB_LOCK_NONE),
   write_can_replace(false),
   blobroot(NULL)
{ }

static unsigned int get_first_unique_index(drizzled::Table &table)
{
  for (uint32_t k= 0; k < table.getShare()->keys; k++)
  {
    if (table.key_info[k].flags & HA_NOSAME)
    {
      return k;
    }
  }

  return 0;
}

int HailDBCursor::open(const char *name, int, uint32_t)
{
  const char* haildb_table_name= table_path_to_haildb_name(name);
  ib_err_t err= ib_table_get_id(haildb_table_name, &table_id);
  bool has_hidden_primary_key= false;
  ib_id_t idx_id;

  if (err != DB_SUCCESS)
    return ib_err_t_to_drizzle_error(getTable()->getSession(), err);

  err= ib_cursor_open_table_using_id(table_id, NULL, &cursor);
  cursor_is_sec_index= false;

  if (err != DB_SUCCESS)
    return ib_err_t_to_drizzle_error(getTable()->getSession(), err);

  err= ib_index_get_id(haildb_table_name, "HIDDEN_PRIMARY", &idx_id);

  if (err == DB_SUCCESS)
    has_hidden_primary_key= true;

  int rc;
  share= get_share(name, has_hidden_primary_key, &rc);
  lock.init(&share->lock);


  if (getTable()->getShare()->getPrimaryKey() != MAX_KEY)
    ref_length= getTable()->key_info[getTable()->getShare()->getPrimaryKey()].key_length;
  else if (share->has_hidden_primary_key)
    ref_length= sizeof(uint64_t);
  else
  {
    unsigned int keynr= get_first_unique_index(*getTable());
    ref_length= getTable()->key_info[keynr].key_length;
  }

  in_table_scan= false;

  return(0);
}

int HailDBCursor::close(void)
{
  ib_err_t err= ib_cursor_close(cursor);
  if (err != DB_SUCCESS)
    return ib_err_t_to_drizzle_error(getTable()->getSession(), err);

  free_share();

  delete blobroot;
  blobroot= NULL;

  return 0;
}

int HailDBCursor::external_lock(Session* session, int lock_type)
{
  ib_cursor_stmt_begin(cursor);

  (void)session;

  if (lock_type == F_WRLCK)
  {
    /* SELECT ... FOR UPDATE or UPDATE TABLE */
    ib_lock_mode= IB_LOCK_X;
  }
  else
    ib_lock_mode= IB_LOCK_NONE;

  return 0;
}

static int create_table_add_field(ib_tbl_sch_t schema,
                                  const message::Table::Field &field,
                                  ib_err_t *err)
{
  ib_col_attr_t column_attr= IB_COL_NONE;

  if (field.has_constraints() && field.constraints().is_notnull())
    column_attr= IB_COL_NOT_NULL;

  switch (field.type())
  {
  case message::Table::Field::VARCHAR:
    *err= ib_table_schema_add_col(schema, field.name().c_str(), IB_VARCHAR,
                                  column_attr, 0,
                                  field.string_options().length());
    break;
  case message::Table::Field::INTEGER:
    *err= ib_table_schema_add_col(schema, field.name().c_str(), IB_INT,
                                  column_attr, 0, 4);
    break;
  case message::Table::Field::BIGINT:
    *err= ib_table_schema_add_col(schema, field.name().c_str(), IB_INT,
                                  column_attr, 0, 8);
    break;
  case message::Table::Field::DOUBLE:
  case message::Table::Field::DATETIME:
    *err= ib_table_schema_add_col(schema, field.name().c_str(), IB_DOUBLE,
                                  column_attr, 0, sizeof(double));
    break;
  case message::Table::Field::ENUM:
    *err= ib_table_schema_add_col(schema, field.name().c_str(), IB_INT,
                                  column_attr, 0, 4);
    break;
  case message::Table::Field::DATE:
    *err= ib_table_schema_add_col(schema, field.name().c_str(), IB_INT,
                                  column_attr, 0, 4);
    break;
  case message::Table::Field::EPOCH:
    *err= ib_table_schema_add_col(schema, field.name().c_str(), IB_INT,
                                  column_attr, 0, 8);
    break;
  case message::Table::Field::BLOB:
    *err= ib_table_schema_add_col(schema, field.name().c_str(), IB_BLOB,
                                  column_attr, 0, 0);
    break;
  case message::Table::Field::DECIMAL:
    *err= ib_table_schema_add_col(schema, field.name().c_str(), IB_DECIMAL,
                                  column_attr, 0, 0);
    break;
  default:
    my_error(ER_CHECK_NOT_IMPLEMENTED, MYF(0), "Column Type");
    return(HA_ERR_UNSUPPORTED);
  }

  return 0;
}

static ib_err_t store_table_message(ib_trx_t transaction, const char* table_name, drizzled::message::Table& table_message)
{
  ib_crsr_t cursor;
  ib_tpl_t message_tuple;
  ib_err_t err;
  string serialized_message;

  err= ib_cursor_open_table(HAILDB_TABLE_DEFINITIONS_TABLE, transaction, &cursor);
  if (err != DB_SUCCESS)
    return err;

  message_tuple= ib_clust_read_tuple_create(cursor);

  err= ib_col_set_value(message_tuple, 0, table_name, strlen(table_name));
  if (err != DB_SUCCESS)
    goto cleanup;

  try {
    table_message.SerializeToString(&serialized_message);
  }
  catch (...)
  {
    goto cleanup;
  }

  err= ib_col_set_value(message_tuple, 1, serialized_message.c_str(),
                        serialized_message.length());
  if (err != DB_SUCCESS)
    goto cleanup;

  err= ib_cursor_insert_row(cursor, message_tuple);

cleanup:
  ib_tuple_delete(message_tuple);

  ib_err_t cleanup_err= ib_cursor_close(cursor);
  if (err == DB_SUCCESS)
    err= cleanup_err;

  return err;
}

bool HailDBEngine::validateCreateTableOption(const std::string &key,
                                                     const std::string &state)
{
  if (boost::iequals(key, "ROW_FORMAT"))
  {
    if (boost::iequals(state, "COMPRESSED"))
      return true;

    if (boost::iequals(state, "COMPACT"))
      return true;

    if (boost::iequals(state, "DYNAMIC"))
      return true;

    if (boost::iequals(state, "REDUNDANT"))
      return true;
  }

  return false;
}

static ib_tbl_fmt_t parse_ib_table_format(const std::string &value)
{
  if (boost::iequals(value, "REDUNDANT"))
    return IB_TBL_REDUNDANT;
  else if (boost::iequals(value, "COMPACT"))
    return IB_TBL_COMPACT;
  else if (boost::iequals(value, "DYNAMIC"))
    return IB_TBL_DYNAMIC;
  else if (boost::iequals(value, "COMPRESSED"))
    return IB_TBL_COMPRESSED;

  assert(false); /* You need to add possible table formats here */
  return IB_TBL_COMPACT;
}

int HailDBEngine::doCreateTable(Session &session,
                                        Table& table_obj,
                                        const drizzled::identifier::Table &identifier,
                                        drizzled::message::Table& table_message)
{
  ib_tbl_sch_t haildb_table_schema= NULL;
//  ib_idx_sch_t haildb_pkey= NULL;
  ib_trx_t haildb_schema_transaction;
  ib_id_t haildb_table_id;
  ib_err_t haildb_err= DB_SUCCESS;
  string haildb_table_name;
  bool has_explicit_pkey= false;

  (void)table_obj;

  if (table_message.type() == message::Table::TEMPORARY)
  {
    ib_bool_t create_db_err= ib_database_create(GLOBAL_TEMPORARY_EXT);
    if (create_db_err != IB_TRUE)
      return -1;
  }

  TableIdentifier_to_haildb_name(identifier, &haildb_table_name);

  ib_tbl_fmt_t haildb_table_format= IB_TBL_COMPACT;

  const size_t num_engine_options= table_message.engine().options_size();
  for (size_t x= 0; x < num_engine_options; x++)
  {
    const message::Engine::Option &engine_option= table_message.engine().options(x);
    if (boost::iequals(engine_option.name(), "ROW_FORMAT"))
    {
      haildb_table_format= parse_ib_table_format(engine_option.state());
    }
  }

  haildb_err= ib_table_schema_create(haildb_table_name.c_str(),
                                     &haildb_table_schema,
                                     haildb_table_format, 0);

  if (haildb_err != DB_SUCCESS)
  {
    push_warning_printf(&session, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
                        ER_CANT_CREATE_TABLE,
                        _("Cannot create table %s. HailDB Error %d (%s)\n"),
                        haildb_table_name.c_str(), haildb_err, ib_strerror(haildb_err));
    return ib_err_t_to_drizzle_error(&session, haildb_err);
  }

  for (int colnr= 0; colnr < table_message.field_size() ; colnr++)
  {
    const message::Table::Field field = table_message.field(colnr);

    int field_err= create_table_add_field(haildb_table_schema, field,
                                          &haildb_err);

    if (haildb_err != DB_SUCCESS || field_err != 0)
      ib_table_schema_delete(haildb_table_schema); /* cleanup */

    if (haildb_err != DB_SUCCESS)
    {
      push_warning_printf(&session, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
                          ER_CANT_CREATE_TABLE,
                          _("Cannot create field %s on table %s."
                            " HailDB Error %d (%s)\n"),
                          field.name().c_str(), haildb_table_name.c_str(),
                          haildb_err, ib_strerror(haildb_err));
      return ib_err_t_to_drizzle_error(&session, haildb_err);
    }
    if (field_err != 0)
      return field_err;
  }

  bool has_primary= false;
  for (int indexnr= 0; indexnr < table_message.indexes_size() ; indexnr++)
  {
    message::Table::Index *index = table_message.mutable_indexes(indexnr);

    ib_idx_sch_t haildb_index;

    haildb_err= ib_table_schema_add_index(haildb_table_schema, index->name().c_str(),
                                   &haildb_index);
    if (haildb_err != DB_SUCCESS)
      goto schema_error;

    if (index->is_primary())
    {
      has_primary= true;
      haildb_err= ib_index_schema_set_clustered(haildb_index);
      has_explicit_pkey= true;
      if (haildb_err != DB_SUCCESS)
        goto schema_error;
    }

    if (index->is_unique())
    {
      haildb_err= ib_index_schema_set_unique(haildb_index);
      if (haildb_err != DB_SUCCESS)
        goto schema_error;
    }

    if (index->type() == message::Table::Index::UNKNOWN_INDEX)
      index->set_type(message::Table::Index::BTREE);

    for (int partnr= 0; partnr < index->index_part_size(); partnr++)
    {
      const message::Table::Index::IndexPart part= index->index_part(partnr);
      const message::Table::Field::FieldType part_type= table_message.field(part.fieldnr()).type();
      uint64_t compare_length= 0;

      if (part_type == message::Table::Field::BLOB
          || part_type == message::Table::Field::VARCHAR)
        compare_length= part.compare_length();

      haildb_err= ib_index_schema_add_col(haildb_index,
                            table_message.field(part.fieldnr()).name().c_str(),
                                          compare_length);
      if (haildb_err != DB_SUCCESS)
        goto schema_error;
    }

    if (! has_primary && index->is_unique())
    {
      haildb_err= ib_index_schema_set_clustered(haildb_index);
      has_explicit_pkey= true;
      if (haildb_err != DB_SUCCESS)
        goto schema_error;
    }

  }

  if (! has_explicit_pkey)
  {
    ib_idx_sch_t haildb_index;

    haildb_err= ib_table_schema_add_col(haildb_table_schema, "hidden_primary_key_col",
                                        IB_INT, IB_COL_NOT_NULL, 0, 8);

    haildb_err= ib_table_schema_add_index(haildb_table_schema, "HIDDEN_PRIMARY",
                                          &haildb_index);
    if (haildb_err != DB_SUCCESS)
      goto schema_error;

    haildb_err= ib_index_schema_set_clustered(haildb_index);
    if (haildb_err != DB_SUCCESS)
      goto schema_error;

    haildb_err= ib_index_schema_add_col(haildb_index, "hidden_primary_key_col", 0);
    if (haildb_err != DB_SUCCESS)
      goto schema_error;
  }

  haildb_schema_transaction= ib_trx_begin(IB_TRX_REPEATABLE_READ);
  haildb_err= ib_schema_lock_exclusive(haildb_schema_transaction);
  if (haildb_err != DB_SUCCESS)
  {
    ib_err_t rollback_err= ib_trx_rollback(haildb_schema_transaction);
    ib_table_schema_delete(haildb_table_schema);

    push_warning_printf(&session, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
                        ER_CANT_CREATE_TABLE,
                        _("Cannot Lock HailDB Data Dictionary. HailDB Error %d (%s)\n"),
                        haildb_err, ib_strerror(haildb_err));

    assert (rollback_err == DB_SUCCESS);

    return HA_ERR_GENERIC;
  }

  haildb_err= ib_table_create(haildb_schema_transaction, haildb_table_schema,
                              &haildb_table_id);

  if (haildb_err != DB_SUCCESS)
  {
    ib_err_t rollback_err= ib_trx_rollback(haildb_schema_transaction);
    ib_table_schema_delete(haildb_table_schema);

    if (haildb_err == DB_TABLE_IS_BEING_USED)
      return EEXIST;

    push_warning_printf(&session, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
                        ER_CANT_CREATE_TABLE,
                        _("Cannot create table %s. HailDB Error %d (%s)\n"),
                        haildb_table_name.c_str(),
                        haildb_err, ib_strerror(haildb_err));

    assert (rollback_err == DB_SUCCESS);
    return HA_ERR_GENERIC;
  }

  if (table_message.type() == message::Table::TEMPORARY)
  {
    session.getMessageCache().storeTableMessage(identifier, table_message);
    haildb_err= DB_SUCCESS;
  }
  else
    haildb_err= store_table_message(haildb_schema_transaction,
                                    haildb_table_name.c_str(),
                                    table_message);

  if (haildb_err == DB_SUCCESS)
    haildb_err= ib_trx_commit(haildb_schema_transaction);
  else
    haildb_err= ib_trx_rollback(haildb_schema_transaction);

schema_error:
  ib_table_schema_delete(haildb_table_schema);

  if (haildb_err != DB_SUCCESS)
  {
    push_warning_printf(&session, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
                        ER_CANT_CREATE_TABLE,
                        _("Cannot create table %s. HailDB Error %d (%s)\n"),
                        haildb_table_name.c_str(),
                        haildb_err, ib_strerror(haildb_err));
    return ib_err_t_to_drizzle_error(&session, haildb_err);
  }

  return 0;
}

static int delete_table_message_from_haildb(ib_trx_t transaction, const char* table_name)
{
  ib_crsr_t cursor;
  ib_tpl_t search_tuple;
  int res;
  ib_err_t err;

  err= ib_cursor_open_table(HAILDB_TABLE_DEFINITIONS_TABLE, transaction, &cursor);
  if (err != DB_SUCCESS)
    return err;

  search_tuple= ib_clust_search_tuple_create(cursor);

  err= ib_col_set_value(search_tuple, 0, table_name, strlen(table_name));
  if (err != DB_SUCCESS)
    goto rollback;

//  ib_cursor_set_match_mode(cursor, IB_EXACT_MATCH);

  err= ib_cursor_moveto(cursor, search_tuple, IB_CUR_GE, &res);
  if (err == DB_RECORD_NOT_FOUND || res != 0)
    goto rollback;

  err= ib_cursor_delete_row(cursor);
  assert (err == DB_SUCCESS);

rollback:
  ib_err_t rollback_err= ib_cursor_close(cursor);
  if (err == DB_SUCCESS)
    err= rollback_err;

  ib_tuple_delete(search_tuple);

  return err;
}

int HailDBEngine::doDropTable(Session &session,
                                      const identifier::Table &identifier)
{
  ib_trx_t haildb_schema_transaction;
  ib_err_t haildb_err;
  string haildb_table_name;

  TableIdentifier_to_haildb_name(identifier, &haildb_table_name);

  haildb_schema_transaction= ib_trx_begin(IB_TRX_REPEATABLE_READ);
  haildb_err= ib_schema_lock_exclusive(haildb_schema_transaction);
  if (haildb_err != DB_SUCCESS)
  {
    ib_err_t rollback_err= ib_trx_rollback(haildb_schema_transaction);

    push_warning_printf(&session, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
                        ER_CANT_DELETE_FILE,
                        _("Cannot Lock HailDB Data Dictionary. HailDB Error %d (%s)\n"),
                        haildb_err, ib_strerror(haildb_err));

    assert (rollback_err == DB_SUCCESS);

    return HA_ERR_GENERIC;
  }

  if (identifier.getType() == message::Table::TEMPORARY)
  {
      session.getMessageCache().removeTableMessage(identifier);
      delete_table_message_from_haildb(haildb_schema_transaction,
                                       haildb_table_name.c_str());
  }
  else
  {
    if (delete_table_message_from_haildb(haildb_schema_transaction, haildb_table_name.c_str()) != DB_SUCCESS)
    {
      ib_schema_unlock(haildb_schema_transaction);
      ib_err_t rollback_err= ib_trx_rollback(haildb_schema_transaction);
      assert(rollback_err == DB_SUCCESS);
      return HA_ERR_GENERIC;
    }
  }

  haildb_err= ib_table_drop(haildb_schema_transaction, haildb_table_name.c_str());

  if (haildb_err == DB_TABLE_NOT_FOUND)
  {
    haildb_err= ib_trx_rollback(haildb_schema_transaction);
    assert(haildb_err == DB_SUCCESS);
    return ENOENT;
  }
  else if (haildb_err != DB_SUCCESS)
  {
    ib_err_t rollback_err= ib_trx_rollback(haildb_schema_transaction);

    push_warning_printf(&session, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
                        ER_CANT_DELETE_FILE,
                        _("Cannot DROP table %s. HailDB Error %d (%s)\n"),
                        haildb_table_name.c_str(),
                        haildb_err, ib_strerror(haildb_err));

    assert(rollback_err == DB_SUCCESS);

    return HA_ERR_GENERIC;
  }

  haildb_err= ib_trx_commit(haildb_schema_transaction);
  if (haildb_err != DB_SUCCESS)
  {
    ib_err_t rollback_err= ib_trx_rollback(haildb_schema_transaction);

    push_warning_printf(&session, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
                        ER_CANT_DELETE_FILE,
                        _("Cannot DROP table %s. HailDB Error %d (%s)\n"),
                        haildb_table_name.c_str(),
                        haildb_err, ib_strerror(haildb_err));

    assert(rollback_err == DB_SUCCESS);
    return HA_ERR_GENERIC;
  }

  return 0;
}

static ib_err_t rename_table_message(ib_trx_t transaction, const identifier::Table &from_identifier, const identifier::Table &to_identifier)
{
  ib_crsr_t cursor;
  ib_tpl_t search_tuple;
  ib_tpl_t read_tuple;
  ib_tpl_t update_tuple;
  int res;
  ib_err_t err;
  ib_err_t rollback_err;
  const char *message;
  ib_ulint_t message_len;
  drizzled::message::Table table_message;
  string from_haildb_table_name;
  string to_haildb_table_name;
  const char *from;
  const char *to;
  string serialized_message;
  ib_col_meta_t col_meta;

  TableIdentifier_to_haildb_name(from_identifier, &from_haildb_table_name);
  TableIdentifier_to_haildb_name(to_identifier, &to_haildb_table_name);

  from= from_haildb_table_name.c_str();
  to= to_haildb_table_name.c_str();

  err= ib_cursor_open_table(HAILDB_TABLE_DEFINITIONS_TABLE, transaction, &cursor);
  if (err != DB_SUCCESS)
  {
    rollback_err= ib_trx_rollback(transaction);
    assert(rollback_err == DB_SUCCESS);
    return err;
  }

  search_tuple= ib_clust_search_tuple_create(cursor);
  read_tuple= ib_clust_read_tuple_create(cursor);

  err= ib_col_set_value(search_tuple, 0, from, strlen(from));
  if (err != DB_SUCCESS)
    goto rollback;

//  ib_cursor_set_match_mode(cursor, IB_EXACT_MATCH);

  err= ib_cursor_moveto(cursor, search_tuple, IB_CUR_GE, &res);
  if (err == DB_RECORD_NOT_FOUND || res != 0)
    goto rollback;

  err= ib_cursor_read_row(cursor, read_tuple);
  if (err == DB_RECORD_NOT_FOUND || res != 0)
    goto rollback;

  message= (const char*)ib_col_get_value(read_tuple, 1);
  message_len= ib_col_get_meta(read_tuple, 1, &col_meta);

  if (table_message.ParseFromArray(message, message_len) == false)
    goto rollback;

  table_message.set_name(to_identifier.getTableName());
  table_message.set_schema(to_identifier.getSchemaName());

  update_tuple= ib_clust_read_tuple_create(cursor);

  err= ib_tuple_copy(update_tuple, read_tuple);
  assert(err == DB_SUCCESS);

  err= ib_col_set_value(update_tuple, 0, to, strlen(to));

  try {
    table_message.SerializeToString(&serialized_message);
  }
  catch (...)
  {
    goto rollback;
  }

  err= ib_col_set_value(update_tuple, 1, serialized_message.c_str(),
                        serialized_message.length());

  err= ib_cursor_update_row(cursor, read_tuple, update_tuple);


  ib_tuple_delete(update_tuple);
  ib_tuple_delete(read_tuple);
  ib_tuple_delete(search_tuple);

  err= ib_cursor_close(cursor);

rollback:
  return err;
}

int HailDBEngine::doRenameTable(drizzled::Session &session,
                                        const drizzled::identifier::Table &from,
                                        const drizzled::identifier::Table &to)
{
  ib_trx_t haildb_schema_transaction;
  ib_err_t err;
  string from_haildb_table_name;
  string to_haildb_table_name;

  if (to.getType() == message::Table::TEMPORARY
      && from.getType() == message::Table::TEMPORARY)
  {
    session.getMessageCache().renameTableMessage(from, to);
    return 0;
  }

  TableIdentifier_to_haildb_name(from, &from_haildb_table_name);
  TableIdentifier_to_haildb_name(to, &to_haildb_table_name);

  haildb_schema_transaction= ib_trx_begin(IB_TRX_REPEATABLE_READ);
  err= ib_schema_lock_exclusive(haildb_schema_transaction);
  if (err != DB_SUCCESS)
  {
    push_warning_printf(&session, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
                        ER_CANT_DELETE_FILE,
                        _("Cannot Lock HailDB Data Dictionary. HailDB Error %d (%s)\n"),
                        err, ib_strerror(err));

    goto rollback;
  }

  err= ib_table_rename(haildb_schema_transaction,
                       from_haildb_table_name.c_str(),
                       to_haildb_table_name.c_str());
  if (err != DB_SUCCESS)
    goto rollback;

  err= rename_table_message(haildb_schema_transaction, from, to);

  if (err != DB_SUCCESS)
    goto rollback;

  err= ib_trx_commit(haildb_schema_transaction);
  if (err != DB_SUCCESS)
    goto rollback;

  return 0;
rollback:
  ib_err_t rollback_err= ib_schema_unlock(haildb_schema_transaction);
  assert(rollback_err == DB_SUCCESS);
  rollback_err= ib_trx_rollback(haildb_schema_transaction);
  assert(rollback_err == DB_SUCCESS);
  return ib_err_t_to_drizzle_error(&session, err);
}

void HailDBEngine::getTableNamesInSchemaFromHailDB(
                                 const drizzled::identifier::Schema &schema,
                                 drizzled::plugin::TableNameList *set_of_names,
                                 drizzled::identifier::Table::vector *identifiers)
{
  ib_trx_t   transaction;
  ib_crsr_t  cursor;
  /*
    Why not use getPath()?
  */
  string search_string(schema.getSchemaName());

  boost::algorithm::to_lower(search_string);

  search_string.append("/");

  transaction = ib_trx_begin(IB_TRX_REPEATABLE_READ);
  ib_err_t haildb_err= ib_schema_lock_exclusive(transaction);
  assert(haildb_err == DB_SUCCESS); /* FIXME: doGetTableNames needs to be able to return error */

  if (search_string.compare("data_dictionary/") == 0)
  {
    if (set_of_names)
    {
      BOOST_FOREACH(std::string table_name, haildb_system_table_names)
      {
        set_of_names->insert(table_name);
      }
    }
    if (identifiers)
    {
      BOOST_FOREACH(std::string table_name, haildb_system_table_names)
      {
        identifiers->push_back(identifier::Table(schema.getSchemaName(),
                                               table_name));
      }
    }
  }

  haildb_err= ib_cursor_open_table("SYS_TABLES", transaction, &cursor);
  assert(haildb_err == DB_SUCCESS); /* FIXME */

  ib_tpl_t read_tuple;
  ib_tpl_t search_tuple;

  read_tuple= ib_clust_read_tuple_create(cursor);
  search_tuple= ib_clust_search_tuple_create(cursor);

  haildb_err= ib_col_set_value(search_tuple, 0, search_string.c_str(),
                               search_string.length());
  assert (haildb_err == DB_SUCCESS); // FIXME

  int res;
  haildb_err = ib_cursor_moveto(cursor, search_tuple, IB_CUR_GE, &res);
  // fixme: check error above

  while (haildb_err == DB_SUCCESS)
  {
    haildb_err= ib_cursor_read_row(cursor, read_tuple);

    const char *table_name;
    int table_name_len;
    ib_col_meta_t column_metadata;

    table_name= (const char*)ib_col_get_value(read_tuple, 0);
    table_name_len=  ib_col_get_meta(read_tuple, 0, &column_metadata);

    if (search_string.compare(0, search_string.length(),
                              table_name, search_string.length()) == 0)
    {
      const char *just_table_name= strchr(table_name, '/');
      assert(just_table_name);
      just_table_name++; /* skip over '/' */
      if (set_of_names)
        set_of_names->insert(just_table_name);
      if (identifiers)
        identifiers->push_back(identifier::Table(schema.getSchemaName(), just_table_name));
    }


    haildb_err= ib_cursor_next(cursor);
    read_tuple= ib_tuple_clear(read_tuple);
  }

  ib_tuple_delete(read_tuple);
  ib_tuple_delete(search_tuple);

  haildb_err= ib_cursor_close(cursor);
  assert(haildb_err == DB_SUCCESS); // FIXME

  haildb_err= ib_trx_commit(transaction);
  assert(haildb_err == DB_SUCCESS); // FIXME
}

void HailDBEngine::doGetTableIdentifiers(drizzled::CachedDirectory &,
                                                 const drizzled::identifier::Schema &schema,
                                                 drizzled::identifier::Table::vector &identifiers)
{
  getTableNamesInSchemaFromHailDB(schema, NULL, &identifiers);
}

static int read_table_message_from_haildb(const char* table_name, drizzled::message::Table *table_message)
{
  ib_trx_t transaction;
  ib_tpl_t search_tuple;
  ib_tpl_t read_tuple;
  ib_crsr_t cursor;
  const char *message;
  ib_ulint_t message_len;
  ib_col_meta_t col_meta;
  int res;
  ib_err_t err;
  ib_err_t rollback_err;

  transaction= ib_trx_begin(IB_TRX_REPEATABLE_READ);
  err= ib_schema_lock_exclusive(transaction);
  if (err != DB_SUCCESS)
  {
    rollback_err= ib_trx_rollback(transaction);
    assert(rollback_err == DB_SUCCESS);
    return err;
  }

  err= ib_cursor_open_table(HAILDB_TABLE_DEFINITIONS_TABLE, transaction, &cursor);
  if (err != DB_SUCCESS)
  {
    rollback_err= ib_trx_rollback(transaction);
    assert(rollback_err == DB_SUCCESS);
    return err;
  }

  search_tuple= ib_clust_search_tuple_create(cursor);
  read_tuple= ib_clust_read_tuple_create(cursor);

  err= ib_col_set_value(search_tuple, 0, table_name, strlen(table_name));
  if (err != DB_SUCCESS)
    goto rollback;

//  ib_cursor_set_match_mode(cursor, IB_EXACT_MATCH);

  err= ib_cursor_moveto(cursor, search_tuple, IB_CUR_GE, &res);
  if (err == DB_RECORD_NOT_FOUND || res != 0)
    goto rollback;

  err= ib_cursor_read_row(cursor, read_tuple);
  if (err == DB_RECORD_NOT_FOUND || res != 0)
    goto rollback;

  message= (const char*)ib_col_get_value(read_tuple, 1);
  message_len= ib_col_get_meta(read_tuple, 1, &col_meta);

  if (table_message->ParseFromArray(message, message_len) == false)
    goto rollback;

  ib_tuple_delete(search_tuple);
  ib_tuple_delete(read_tuple);
  err= ib_cursor_close(cursor);
  if (err != DB_SUCCESS)
    goto rollback_close_err;
  err= ib_trx_commit(transaction);
  if (err != DB_SUCCESS)
    goto rollback_close_err;

  return 0;

rollback:
  ib_tuple_delete(search_tuple);
  ib_tuple_delete(read_tuple);
  rollback_err= ib_cursor_close(cursor);
  assert(rollback_err == DB_SUCCESS);
rollback_close_err:
  ib_schema_unlock(transaction);
  rollback_err= ib_trx_rollback(transaction);
  assert(rollback_err == DB_SUCCESS);

  if (strcmp(table_name, HAILDB_TABLE_DEFINITIONS_TABLE) == 0)
  {
    message::Engine *engine= table_message->mutable_engine();
    engine->set_name("InnoDB");
    table_message->set_name("haildb_table_definitions");
    table_message->set_schema("data_dictionary");
    table_message->set_type(message::Table::STANDARD);
    table_message->set_creation_timestamp(0);
    table_message->set_update_timestamp(0);

    message::Table::TableOptions *options= table_message->mutable_options();
    options->set_collation_id(my_charset_bin.number);
    options->set_collation(my_charset_bin.name);

    message::Table::Field *field= table_message->add_field();
    field->set_name("table_name");
    field->set_type(message::Table::Field::VARCHAR);
    message::Table::Field::StringFieldOptions *stropt= field->mutable_string_options();
    stropt->set_length(IB_MAX_TABLE_NAME_LEN);
    stropt->set_collation_id(my_charset_bin.number);
    stropt->set_collation(my_charset_bin.name);

    field= table_message->add_field();
    field->set_name("message");
    field->set_type(message::Table::Field::BLOB);
    stropt= field->mutable_string_options();
    stropt->set_collation_id(my_charset_bin.number);
    stropt->set_collation(my_charset_bin.name);

    message::Table::Index *index= table_message->add_indexes();
    index->set_name("PRIMARY");
    index->set_is_primary(true);
    index->set_is_unique(true);
    index->set_type(message::Table::Index::BTREE);
    index->set_key_length(IB_MAX_TABLE_NAME_LEN);
    message::Table::Index::IndexPart *part= index->add_index_part();
    part->set_fieldnr(0);
    part->set_compare_length(IB_MAX_TABLE_NAME_LEN);

    return 0;
  }

  return -1;
}

int HailDBEngine::doGetTableDefinition(Session &session,
                                               const identifier::Table &identifier,
                                               drizzled::message::Table &table)
{
  ib_crsr_t haildb_cursor= NULL;
  string haildb_table_name;

  /* Check temporary tables!? */
  if (session.getMessageCache().getTableMessage(identifier, table))
    return EEXIST;

  TableIdentifier_to_haildb_name(identifier, &haildb_table_name);

  if (ib_cursor_open_table(haildb_table_name.c_str(), NULL, &haildb_cursor) != DB_SUCCESS)
    return ENOENT;

  ib_err_t err= ib_cursor_close(haildb_cursor);

  assert (err == DB_SUCCESS);

  if (read_table_message_from_haildb(haildb_table_name.c_str(), &table) != 0)
  {
    if (get_haildb_system_table_message(haildb_table_name.c_str(), &table) == 0)
      return EEXIST;
  }

  return EEXIST;
}

bool HailDBEngine::doDoesTableExist(Session &,
                                    const identifier::Table& identifier)
{
  ib_crsr_t haildb_cursor;
  string haildb_table_name;

  TableIdentifier_to_haildb_name(identifier, &haildb_table_name);

  boost::unordered_set<string>::iterator iter= haildb_system_table_names.find(identifier.getTableName());
  if (iter != haildb_system_table_names.end())
    return true;

  if (ib_cursor_open_table(haildb_table_name.c_str(), NULL, &haildb_cursor) != DB_SUCCESS)
    return false;

  ib_err_t err= ib_cursor_close(haildb_cursor);
  assert(err == DB_SUCCESS);

  return true;
}

const char *HailDBCursor::index_type(uint32_t)
{
  return("BTREE");
}

static ib_err_t write_row_to_haildb_tuple(const unsigned char* buf,
                                          Field **fields, ib_tpl_t tuple)
{
  int colnr= 0;
  ib_err_t err= DB_ERROR;
  ptrdiff_t row_offset= buf - (*fields)->getTable()->getInsertRecord();

  for (Field **field= fields; *field; field++, colnr++)
  {
    (**field).move_field_offset(row_offset);

    if (! (**field).isWriteSet() && (**field).is_null())
    {
      (**field).move_field_offset(-row_offset);
      continue;
    }

    if ((**field).is_null())
    {
      err= ib_col_set_value(tuple, colnr, NULL, IB_SQL_NULL);
      assert(err == DB_SUCCESS);
      (**field).move_field_offset(-row_offset);
      continue;
    }

    if ((**field).type() == DRIZZLE_TYPE_VARCHAR)
    {
      /* To get around the length bytes (1 or 2) at (**field).ptr
         we can use Field_varstring::val_str to a String
         to get a pointer to the real string without copying it.
      */
      String str;
      (**field).setReadSet();
      (**field).val_str_internal(&str);
      err= ib_col_set_value(tuple, colnr, str.ptr(), str.length());
    }
    else if ((**field).type() == DRIZZLE_TYPE_ENUM)
    {
      err= ib_tuple_write_u32(tuple, colnr, *((ib_u32_t*)(*field)->ptr));
    }
    else if ((**field).type() == DRIZZLE_TYPE_DATE)
    {
      (**field).setReadSet();
      err= ib_tuple_write_u32(tuple, colnr, (*field)->val_int());
    }
    else if ((**field).type() == DRIZZLE_TYPE_BLOB)
    {
      Field_blob *blob= reinterpret_cast<Field_blob*>(*field);
      unsigned char* blob_ptr;
      uint32_t blob_length= blob->get_length();
      blob->get_ptr(&blob_ptr);
      err= ib_col_set_value(tuple, colnr, blob_ptr, blob_length);
    }
    else
    {
      err= ib_col_set_value(tuple, colnr, (*field)->ptr, (*field)->data_length());
    }

    assert (err == DB_SUCCESS);

    (**field).move_field_offset(-row_offset);
  }

  return err;
}

static uint64_t innobase_get_int_col_max_value(const Field* field)
{
  uint64_t	max_value = 0;

  switch(field->key_type()) {
    /* TINY */
  case HA_KEYTYPE_BINARY:
    max_value = 0xFFULL;
    break;
    /* LONG */
  case HA_KEYTYPE_ULONG_INT:
    max_value = 0xFFFFFFFFULL;
    break;
  case HA_KEYTYPE_LONG_INT:
    max_value = 0x7FFFFFFFULL;
    break;
    /* BIG */
  case HA_KEYTYPE_ULONGLONG:
    max_value = 0xFFFFFFFFFFFFFFFFULL;
    break;
  case HA_KEYTYPE_LONGLONG:
    max_value = 0x7FFFFFFFFFFFFFFFULL;
    break;
  case HA_KEYTYPE_DOUBLE:
    /* We use the maximum as per IEEE754-2008 standard, 2^53 */
    max_value = 0x20000000000000ULL;
    break;
  default:
    assert(false);
  }

  return(max_value);
}

int HailDBCursor::doInsertRecord(unsigned char *record)
{
  ib_err_t err;
  int ret= 0;

  ib_trx_t transaction= *get_trx(getTable()->in_use);

  tuple= ib_clust_read_tuple_create(cursor);

  if (cursor_is_sec_index)
  {
    err= ib_cursor_close(cursor);
    assert(err == DB_SUCCESS);

    err= ib_cursor_open_table_using_id(table_id, transaction, &cursor);

    if (err != DB_SUCCESS)
      return ib_err_t_to_drizzle_error(getTable()->getSession(), err);

    cursor_is_sec_index= false;
  }
  else
  {
    ib_cursor_attach_trx(cursor, transaction);
  }

  err= ib_cursor_first(cursor);
  if (current_session->getLex()->sql_command == SQLCOM_CREATE_TABLE
      && err == DB_MISSING_HISTORY)
  {
    /* See https://bugs.launchpad.net/drizzle/+bug/556978
     *
     * In CREATE SELECT, transaction is started in ::store_lock
     * at the start of the statement, before the table is created.
     * This means the table doesn't exist in our snapshot,
     * and we get a DB_MISSING_HISTORY error on ib_cursor_first().
     * The way to get around this is to here, restart the transaction
     * and continue.
     *
     * yuck.
     */

    HailDBEngine *storage_engine= static_cast<HailDBEngine*>(getEngine());
    err= ib_cursor_reset(cursor);
    storage_engine->doCommit(current_session, true);
    storage_engine->doStartTransaction(current_session, START_TRANS_NO_OPTIONS);
    transaction= *get_trx(getTable()->in_use);
    assert(err == DB_SUCCESS);
    ib_cursor_attach_trx(cursor, transaction);
    err= ib_cursor_first(cursor);
  }

  assert(err == DB_SUCCESS || err == DB_END_OF_INDEX);


  if (getTable()->next_number_field)
  {
    update_auto_increment();

    uint64_t temp_auto= getTable()->next_number_field->val_int();

    if (temp_auto <= innobase_get_int_col_max_value(getTable()->next_number_field))
    {
      while (true)
      {
        uint64_t fetched_auto= share->auto_increment_value;

        if (temp_auto >= fetched_auto)
        {
          uint64_t store_value= temp_auto+1;
          if (store_value == 0)
            store_value++;

          if (share->auto_increment_value.compare_and_swap(store_value, fetched_auto) == fetched_auto)
            break;
        }
        else
          break;
      }
    }

  }

  write_row_to_haildb_tuple(record, getTable()->getFields(), tuple);

  if (share->has_hidden_primary_key)
  {
    err= ib_tuple_write_u64(tuple, getTable()->getShare()->sizeFields(),
                            share->hidden_pkey_auto_increment_value.fetch_and_increment());
  }

  err= ib_cursor_insert_row(cursor, tuple);

  if (err == DB_DUPLICATE_KEY)
  {
    if (write_can_replace)
    {
      store_key_value_from_haildb(getTable()->key_info + getTable()->getShare()->getPrimaryKey(),
                                  ref, ref_length, record);

      ib_tpl_t search_tuple= ib_clust_search_tuple_create(cursor);

      fill_ib_search_tpl_from_drizzle_key(search_tuple,
                                          getTable()->key_info + 0,
                                          ref, ref_length);

      int res;
      err= ib_cursor_moveto(cursor, search_tuple, IB_CUR_GE, &res);
      assert(err == DB_SUCCESS);
      ib_tuple_delete(search_tuple);

      tuple= ib_tuple_clear(tuple);
      err= ib_cursor_delete_row(cursor);

      err= ib_cursor_first(cursor);
      assert(err == DB_SUCCESS || err == DB_END_OF_INDEX);

      write_row_to_haildb_tuple(record, getTable()->getFields(), tuple);

      err= ib_cursor_insert_row(cursor, tuple);
      assert(err==DB_SUCCESS); // probably be nice and process errors
    }
    else
      ret= HA_ERR_FOUND_DUPP_KEY;
  }
  else if (err != DB_SUCCESS)
    ret= ib_err_t_to_drizzle_error(getTable()->getSession(), err);

  tuple= ib_tuple_clear(tuple);
  ib_tuple_delete(tuple);
  tuple= NULL;
  err= ib_cursor_reset(cursor);

  return ret;
}

int HailDBCursor::doUpdateRecord(const unsigned char *old_data,
                                 unsigned char *new_data)
{
  ib_tpl_t update_tuple;
  ib_err_t err;
  bool created_tuple= false;

  update_tuple= ib_clust_read_tuple_create(cursor);

  if (tuple == NULL)
  {
    ib_trx_t transaction= *get_trx(getTable()->in_use);

    if (cursor_is_sec_index)
    {
      err= ib_cursor_close(cursor);
      assert(err == DB_SUCCESS);

      err= ib_cursor_open_table_using_id(table_id, transaction, &cursor);

      if (err != DB_SUCCESS)
        return ib_err_t_to_drizzle_error(getTable()->getSession(), err);
      cursor_is_sec_index= false;
    }
    else
    {
      ib_cursor_attach_trx(cursor, transaction);
    }

    store_key_value_from_haildb(getTable()->key_info + getTable()->getShare()->getPrimaryKey(),
                                  ref, ref_length, old_data);

    ib_tpl_t search_tuple= ib_clust_search_tuple_create(cursor);

    fill_ib_search_tpl_from_drizzle_key(search_tuple,
                                        getTable()->key_info + 0,
                                        ref, ref_length);

    err= ib_cursor_set_lock_mode(cursor, IB_LOCK_X);
    assert(err == DB_SUCCESS);

    int res;
    err= ib_cursor_moveto(cursor, search_tuple, IB_CUR_GE, &res);
    assert(err == DB_SUCCESS);

    tuple= ib_clust_read_tuple_create(cursor);

    err= ib_cursor_read_row(cursor, tuple);
    assert(err == DB_SUCCESS);// FIXME

    created_tuple= true;
  }

  err= ib_tuple_copy(update_tuple, tuple);
  assert(err == DB_SUCCESS);

  write_row_to_haildb_tuple(new_data, getTable()->getFields(), update_tuple);

  err= ib_cursor_update_row(cursor, tuple, update_tuple);

  ib_tuple_delete(update_tuple);

  if (created_tuple)
  {
    ib_err_t ib_err= ib_cursor_reset(cursor); //fixme check error
    assert(ib_err == DB_SUCCESS);
    tuple= ib_tuple_clear(tuple);
    ib_tuple_delete(tuple);
    tuple= NULL;
  }

  advance_cursor= true;

  return ib_err_t_to_drizzle_error(getTable()->getSession(), err);
}

int HailDBCursor::doDeleteRecord(const unsigned char *)
{
  ib_err_t err;

  assert(ib_cursor_is_positioned(cursor) == IB_TRUE);
  err= ib_cursor_delete_row(cursor);

  advance_cursor= true;

  return ib_err_t_to_drizzle_error(getTable()->getSession(), err);
}

int HailDBCursor::delete_all_rows(void)
{
  /* I *think* ib_truncate is non-transactional....
     so only support TRUNCATE and not DELETE FROM t;
     (this is what ha_innodb does)
  */
  if (getTable()->in_use->getSqlCommand() != SQLCOM_TRUNCATE)
    return HA_ERR_WRONG_COMMAND;

  ib_id_t id;
  ib_err_t err;

  ib_trx_t transaction= ib_trx_begin(IB_TRX_REPEATABLE_READ);

  if (cursor_is_sec_index)
  {
    err= ib_cursor_close(cursor);
    assert(err == DB_SUCCESS);

    err= ib_cursor_open_table_using_id(table_id, transaction, &cursor);

    if (err != DB_SUCCESS)
      return ib_err_t_to_drizzle_error(getTable()->getSession(), err);
    cursor_is_sec_index= false;
  }
  else
  {
    ib_cursor_attach_trx(cursor, transaction);
  }

  err= ib_schema_lock_exclusive(transaction);
  if (err != DB_SUCCESS)
  {
    ib_err_t rollback_err= ib_trx_rollback(transaction);

    push_warning_printf(getTable()->in_use, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
                        ER_CANT_DELETE_FILE,
                        _("Cannot Lock HailDB Data Dictionary. HailDB Error %d (%s)\n"),
                        err, ib_strerror(err));

    assert (rollback_err == DB_SUCCESS);

    return HA_ERR_GENERIC;
  }

  share->auto_increment_value.fetch_and_store(1);

  err= ib_cursor_truncate(&cursor, &id);
  if (err != DB_SUCCESS)
    goto err;

  ib_schema_unlock(transaction);
  /* ib_cursor_truncate commits on success */

  err= ib_cursor_open_table_using_id(id, NULL, &cursor);
  if (err != DB_SUCCESS)
    goto err;

  return 0;

err:
  ib_schema_unlock(transaction);
  ib_err_t rollback_err= ib_trx_rollback(transaction);
  assert(rollback_err == DB_SUCCESS);
  return ib_err_t_to_drizzle_error(getTable()->getSession(), err);
}

int HailDBCursor::doStartTableScan(bool)
{
  ib_err_t err= DB_SUCCESS;
  ib_trx_t transaction;

  if (in_table_scan)
    doEndTableScan();
  in_table_scan= true;

  transaction= *get_trx(getTable()->in_use);

  assert(transaction != NULL);

  if (cursor_is_sec_index)
  {
    err= ib_cursor_close(cursor);
    assert(err == DB_SUCCESS);

    err= ib_cursor_open_table_using_id(table_id, transaction, &cursor);
    cursor_is_sec_index= false;
  }
  else
  {
    ib_cursor_attach_trx(cursor, transaction);
  }

  if (err != DB_SUCCESS)
    return ib_err_t_to_drizzle_error(getTable()->getSession(), err);

  err= ib_cursor_set_lock_mode(cursor, ib_lock_mode);
  assert(err == DB_SUCCESS); // FIXME

  tuple= ib_clust_read_tuple_create(cursor);

  err= ib_cursor_first(cursor);
  if (err != DB_SUCCESS && err != DB_END_OF_INDEX)
  {
    int reset_err= ib_cursor_reset(cursor);
    assert(reset_err == DB_SUCCESS);
    return ib_err_t_to_drizzle_error(getTable()->getSession(), err);
  }

  advance_cursor= false;

  return(0);
}

int read_row_from_haildb(Session *session, unsigned char* buf, ib_crsr_t cursor, ib_tpl_t tuple, Table* table, bool has_hidden_primary_key, uint64_t *hidden_pkey, drizzled::memory::Root **blobroot)
{
  ib_err_t err;
  ptrdiff_t row_offset= buf - table->getInsertRecord();

  err= ib_cursor_read_row(cursor, tuple);

  if (err == DB_RECORD_NOT_FOUND)
    return HA_ERR_END_OF_FILE;
  if (err != DB_SUCCESS)
    return ib_err_t_to_drizzle_error(session, err);

  int colnr= 0;

  /* We need the primary key for ::position() to work */
  if (table->getShare()->getPrimaryKey() != MAX_KEY)
    table->mark_columns_used_by_index_no_reset(table->getShare()->getPrimaryKey());

  for (Field **field= table->getFields() ; *field ; field++, colnr++)
  {
    if (! (**field).isReadSet())
      (**field).setReadSet(); /* Fucking broken API screws us royally. */

    (**field).move_field_offset(row_offset);

    (**field).setWriteSet();

    uint32_t length= ib_col_get_len(tuple, colnr);
    if (length == IB_SQL_NULL)
    {
      (**field).set_null();
      (**field).move_field_offset(-row_offset);
      continue;
    }
    else
      (**field).set_notnull();

    if ((**field).type() == DRIZZLE_TYPE_VARCHAR)
    {
      (*field)->store((const char*)ib_col_get_value(tuple, colnr),
                      length,
                      &my_charset_bin);
    }
    else if ((**field).type() == DRIZZLE_TYPE_DATE)
    {
      uint32_t date_read;
      err= ib_tuple_read_u32(tuple, colnr, &date_read);
      (*field)->store(date_read);
    }
    else if ((**field).type() == DRIZZLE_TYPE_BLOB)
    {
      if (blobroot == NULL)
        (reinterpret_cast<Field_blob*>(*field))->set_ptr(length,
                                      (unsigned char*)ib_col_get_value(tuple,
                                                                       colnr));
      else
      {
        if (*blobroot == NULL)
        {
          *blobroot= new drizzled::memory::Root();
          (**blobroot).init_alloc_root();
        }

        unsigned char *blob_ptr= (unsigned char*)(**blobroot).alloc_root(length);
        memcpy(blob_ptr, ib_col_get_value(tuple, colnr), length);
        (reinterpret_cast<Field_blob*>(*field))->set_ptr(length, blob_ptr);
      }
    }
    else
    {
      ib_col_copy_value(tuple, colnr, (*field)->ptr, (*field)->data_length());
    }

    (**field).move_field_offset(-row_offset);

    if (err != DB_SUCCESS)
      return ib_err_t_to_drizzle_error(session, err);
  }

  if (has_hidden_primary_key)
  {
    err= ib_tuple_read_u64(tuple, colnr, hidden_pkey);
  }

  return ib_err_t_to_drizzle_error(session, err);
}

int HailDBCursor::rnd_next(unsigned char *buf)
{
  ib_err_t err;
  int ret;

  if (advance_cursor)
  {
    err= ib_cursor_next(cursor);
    if (err != DB_SUCCESS)
      return ib_err_t_to_drizzle_error(getTable()->getSession(), err);
  }

  tuple= ib_tuple_clear(tuple);
  ret= read_row_from_haildb(getTable()->getSession(), buf, cursor, tuple,
                            getTable(),
                            share->has_hidden_primary_key,
                            &hidden_autoinc_pkey_position);

  advance_cursor= true;
  return ret;
}

int HailDBCursor::doEndTableScan()
{
  ib_err_t err;

  ib_tuple_delete(tuple);
  tuple= NULL;
  err= ib_cursor_reset(cursor);
  assert(err == DB_SUCCESS);
  in_table_scan= false;
  return ib_err_t_to_drizzle_error(getTable()->getSession(), err);
}

int HailDBCursor::rnd_pos(unsigned char *buf, unsigned char *pos)
{
  ib_err_t err;
  int res;
  int ret= 0;
  ib_tpl_t search_tuple= ib_clust_search_tuple_create(cursor);

  if (share->has_hidden_primary_key)
  {
    err= ib_col_set_value(search_tuple, 0,
                          ((uint64_t*)(pos)), sizeof(uint64_t));
    if (err != DB_SUCCESS)
      return ib_err_t_to_drizzle_error(getTable()->getSession(), err);
  }
  else
  {
    unsigned int keynr;
    if (getTable()->getShare()->getPrimaryKey() != MAX_KEY)
      keynr= getTable()->getShare()->getPrimaryKey();
    else
      keynr= get_first_unique_index(*getTable());

    fill_ib_search_tpl_from_drizzle_key(search_tuple,
                                        getTable()->key_info + keynr,
                                        pos, ref_length);
  }

  err= ib_cursor_moveto(cursor, search_tuple, IB_CUR_GE, &res);
  if (err != DB_SUCCESS)
    return ib_err_t_to_drizzle_error(getTable()->getSession(), err);

  assert(res==0);
  if (res != 0)
    ret= -1;

  ib_tuple_delete(search_tuple);

  tuple= ib_tuple_clear(tuple);

  if (ret == 0)
    ret= read_row_from_haildb(getTable()->getSession(), buf, cursor, tuple,
                              getTable(),
                              share->has_hidden_primary_key,
                              &hidden_autoinc_pkey_position);

  advance_cursor= true;

  return(ret);
}

static void store_key_value_from_haildb(KeyInfo *key_info, unsigned char* ref, int ref_len, const unsigned char *record)
{
  KeyPartInfo* key_part= key_info->key_part;
  KeyPartInfo* end= key_info->key_part + key_info->key_parts;
  unsigned char* ref_start= ref;

  memset(ref, 0, ref_len);

  for (; key_part != end; key_part++)
  {
    char is_null= 0;

    if(key_part->null_bit)
    {
      *ref= is_null= record[key_part->null_offset] & key_part->null_bit;
      ref++;
    }

    Field *field= key_part->field;

    if (field->type() == DRIZZLE_TYPE_VARCHAR)
    {
      if (is_null)
      {
        ref+= key_part->length + 2; /* 2 bytes for length */
        continue;
      }

      String str;
      field->val_str_internal(&str);

      *ref++= (char)(str.length() & 0x000000ff);
      *ref++= (char)((str.length()>>8) & 0x000000ff);

      memcpy(ref, str.ptr(), str.length());
      ref+= key_part->length;
    }
    // FIXME: blobs.
    else
    {
      if (is_null)
      {
        ref+= key_part->length;
        continue;
      }

      memcpy(ref, record+key_part->offset, key_part->length);
      ref+= key_part->length;
    }

  }

  assert(ref == ref_start + ref_len);
}

void HailDBCursor::position(const unsigned char *record)
{
  if (share->has_hidden_primary_key)
    *((uint64_t*) ref)= hidden_autoinc_pkey_position;
  else
  {
    unsigned int keynr;
    if (getTable()->getShare()->getPrimaryKey() != MAX_KEY)
      keynr= getTable()->getShare()->getPrimaryKey();
    else
      keynr= get_first_unique_index(*getTable());

    store_key_value_from_haildb(getTable()->key_info + keynr,
                                ref, ref_length, record);
  }

  return;
}

double HailDBCursor::scan_time()
{
  ib_table_stats_t table_stats;
  ib_err_t err;

  err= ib_get_table_statistics(cursor, &table_stats, sizeof(table_stats));

  /* Approximate I/O seeks for full table scan */
  return (double) (table_stats.stat_clustered_index_size / 16384);
}

int HailDBCursor::info(uint32_t flag)
{
  ib_table_stats_t table_stats;
  ib_err_t err;

  if (flag & HA_STATUS_VARIABLE)
  {
    err= ib_get_table_statistics(cursor, &table_stats, sizeof(table_stats));

    stats.records= table_stats.stat_n_rows;

    if (table_stats.stat_n_rows < 2)
      stats.records= 2;

    stats.deleted= 0;
    stats.data_file_length= table_stats.stat_clustered_index_size;
    stats.index_file_length= table_stats.stat_sum_of_other_index_sizes;

    stats.mean_rec_length= stats.data_file_length / stats.records;
  }

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

  if (flag & HA_STATUS_ERRKEY) {
    const char *err_table_name;
    const char *err_index_name;

    ib_trx_t transaction= *get_trx(getTable()->in_use);

    err= ib_get_duplicate_key(transaction, &err_table_name, &err_index_name);

    errkey= UINT32_MAX;

    for (unsigned int i = 0; i < getTable()->getShare()->keys; i++)
    {
      if (strcmp(err_index_name, getTable()->key_info[i].name) == 0)
      {
        errkey= i;
        break;
      }
    }

  }

  if (flag & HA_STATUS_CONST)
  {
    for (unsigned int i = 0; i < getTable()->getShare()->sizeKeys(); i++)
    {
      const char* index_name= getTable()->key_info[i].name;
      uint64_t ncols;
      int64_t *n_diff;
      ha_rows rec_per_key;

      err= ib_get_index_stat_n_diff_key_vals(cursor, index_name,
                                             &ncols, &n_diff);

      if (err != DB_SUCCESS)
        return ib_err_t_to_drizzle_error(getTable()->getSession(), err);

      for (unsigned int j=0; j < getTable()->key_info[i].key_parts; j++)
      {
        if (n_diff[j+1] == 0)
          rec_per_key= stats.records;
        else
          rec_per_key= stats.records / n_diff[j+1];

        /* We import this heuristic from ha_innodb, which says
           that MySQL favours table scans too much over index searches,
           so we pretend our index selectivity is 2 times better. */

        rec_per_key= rec_per_key / 2;

        if (rec_per_key == 0)
          rec_per_key= 1;

        getTable()->key_info[i].rec_per_key[j]=
          rec_per_key >= ~(ulong) 0 ? ~(ulong) 0 :
          (ulong) rec_per_key;
      }

      free(n_diff);
    }
  }

  return(0);
}

int HailDBCursor::doStartIndexScan(uint32_t keynr, bool)
{
  ib_err_t err;
  ib_trx_t transaction= *get_trx(getTable()->in_use);

  active_index= keynr;

  if (active_index == 0 && ! share->has_hidden_primary_key)
  {
    if (cursor_is_sec_index)
    {
      err= ib_cursor_close(cursor);
      assert(err == DB_SUCCESS);

      err= ib_cursor_open_table_using_id(table_id, transaction, &cursor);

      if (err != DB_SUCCESS)
        return ib_err_t_to_drizzle_error(getTable()->getSession(), err);

    }
    else
    {
      ib_cursor_attach_trx(cursor, transaction);
    }

    cursor_is_sec_index= false;
    tuple= ib_clust_read_tuple_create(cursor);
  }
  else
  {
    ib_id_t index_id;
    err= ib_index_get_id(table_path_to_haildb_name(getShare()->getPath()),
                         getShare()->getKeyInfo(keynr).name,
                         &index_id);
    if (err != DB_SUCCESS)
      return ib_err_t_to_drizzle_error(getTable()->getSession(), err);

    err= ib_cursor_close(cursor);
    assert(err == DB_SUCCESS);

    err= ib_cursor_open_index_using_id(index_id, transaction, &cursor);

    if (err != DB_SUCCESS)
      return ib_err_t_to_drizzle_error(getTable()->getSession(), err);

    cursor_is_sec_index= true;

    tuple= ib_clust_read_tuple_create(cursor);
    ib_cursor_set_cluster_access(cursor);
  }

  err= ib_cursor_set_lock_mode(cursor, ib_lock_mode);
  assert(err == DB_SUCCESS);

  advance_cursor= false;
  return 0;
}

static ib_srch_mode_t ha_rkey_function_to_ib_srch_mode(drizzled::ha_rkey_function find_flag)
{
  switch (find_flag)
  {
  case HA_READ_KEY_EXACT:
    return IB_CUR_GE;
  case HA_READ_KEY_OR_NEXT:
    return IB_CUR_GE;
  case HA_READ_KEY_OR_PREV:
    return IB_CUR_LE;
  case HA_READ_AFTER_KEY:
    return IB_CUR_G;
  case HA_READ_BEFORE_KEY:
    return IB_CUR_L;
  case HA_READ_PREFIX:
    return IB_CUR_GE;
  case HA_READ_PREFIX_LAST:
    return IB_CUR_LE;
  case HA_READ_PREFIX_LAST_OR_PREV:
    return IB_CUR_LE;
  case HA_READ_MBR_CONTAIN:
  case HA_READ_MBR_INTERSECT:
  case HA_READ_MBR_WITHIN:
  case HA_READ_MBR_DISJOINT:
  case HA_READ_MBR_EQUAL:
    assert(false); /* these just exist in the enum, not used. */
  }

  assert(false);
  /* Must return or compiler complains about reaching end of function */
  return (ib_srch_mode_t)0;
}

static void fill_ib_search_tpl_from_drizzle_key(ib_tpl_t search_tuple,
                                                const drizzled::KeyInfo *key_info,
                                                const unsigned char *key_ptr,
                                                uint32_t key_len)
{
  KeyPartInfo *key_part= key_info->key_part;
  KeyPartInfo *end= key_part + key_info->key_parts;
  const unsigned char *buff= key_ptr;
  ib_err_t err;

  int fieldnr= 0;

  for(; key_part != end && buff < key_ptr + key_len; key_part++)
  {
    Field *field= key_part->field;
    bool is_null= false;

    if (key_part->null_bit)
    {
      is_null= *buff;
      if (is_null)
      {
        err= ib_col_set_value(search_tuple, fieldnr, NULL, IB_SQL_NULL);
        assert(err == DB_SUCCESS);
      }
      buff++;
    }

    if (field->type() == DRIZZLE_TYPE_VARCHAR)
    {
      if (is_null)
      {
        buff+= key_part->length + 2; /* 2 bytes length */
        continue;
      }

      int length= *buff + (*(buff + 1) << 8);
      buff+=2;
      err= ib_col_set_value(search_tuple, fieldnr, buff, length);
      assert(err == DB_SUCCESS);

      buff+= key_part->length;
    }
    else if (field->type() == DRIZZLE_TYPE_DATE)
    {
      uint32_t date_int= static_cast<uint32_t>(field->val_int());
      err= ib_col_set_value(search_tuple, fieldnr, &date_int, 4);
      buff+= key_part->length;
    }
    // FIXME: BLOBs
    else
    {
      if (is_null)
      {
        buff+= key_part->length;
        continue;
      }

      err= ib_col_set_value(search_tuple, fieldnr,
                            buff, key_part->length);
      assert(err == DB_SUCCESS);

      buff+= key_part->length;
    }

    fieldnr++;
  }

  assert(buff == key_ptr + key_len);
}

int HailDBCursor::haildb_index_read(unsigned char *buf,
                                            const unsigned char *key_ptr,
                                            uint32_t key_len,
                                            drizzled::ha_rkey_function find_flag,
                                            bool allocate_blobs)
{
  ib_tpl_t search_tuple;
  int res;
  ib_err_t err;
  int ret;
  ib_srch_mode_t search_mode;

  search_mode= ha_rkey_function_to_ib_srch_mode(find_flag);

  if (active_index == 0 && ! share->has_hidden_primary_key)
    search_tuple= ib_clust_search_tuple_create(cursor);
  else
    search_tuple= ib_sec_search_tuple_create(cursor);

  fill_ib_search_tpl_from_drizzle_key(search_tuple,
                                      getTable()->key_info + active_index,
                                      key_ptr, key_len);

  err= ib_cursor_moveto(cursor, search_tuple, search_mode, &res);
  ib_tuple_delete(search_tuple);

  if ((err == DB_RECORD_NOT_FOUND || err == DB_END_OF_INDEX))
  {
    getTable()->status= STATUS_NOT_FOUND;
    return HA_ERR_KEY_NOT_FOUND;
  }

  if (err != DB_SUCCESS)
  {
    return ib_err_t_to_drizzle_error(getTable()->getSession(), err);
  }

  tuple= ib_tuple_clear(tuple);
  ret= read_row_from_haildb(getTable()->getSession(), buf, cursor, tuple,
                            getTable(),
                            share->has_hidden_primary_key,
                            &hidden_autoinc_pkey_position,
                            (allocate_blobs)? &blobroot : NULL);
  if (ret == 0)
    getTable()->status= 0;
  else
    getTable()->status= STATUS_NOT_FOUND;

  advance_cursor= true;

  return ret;
}

int HailDBCursor::index_read(unsigned char *buf,
                                     const unsigned char *key_ptr,
                                     uint32_t key_len,
                                     drizzled::ha_rkey_function find_flag)
{
  return haildb_index_read(buf, key_ptr, key_len, find_flag, false);
}

/* This is straight from cursor.cc, but it's private there :( */
uint32_t HailDBCursor::calculate_key_len(uint32_t key_position,
                                                 key_part_map keypart_map_arg)
{
  /* works only with key prefixes */
  assert(((keypart_map_arg + 1) & keypart_map_arg) == 0);

  KeyPartInfo *key_part_found= getTable()->getShare()->getKeyInfo(key_position).key_part;
  KeyPartInfo *end_key_part_found= key_part_found + getTable()->getShare()->getKeyInfo(key_position).key_parts;
  uint32_t length= 0;

  while (key_part_found < end_key_part_found && keypart_map_arg)
  {
    length+= key_part_found->store_length;
    keypart_map_arg >>= 1;
    key_part_found++;
  }
  return length;
}


int HailDBCursor::haildb_index_read_map(unsigned char * buf,
                                                const unsigned char *key,
                                                key_part_map keypart_map,
                                                enum ha_rkey_function find_flag,
                                                bool allocate_blobs)
{
  uint32_t key_len= calculate_key_len(active_index, keypart_map);
  return  haildb_index_read(buf, key, key_len, find_flag, allocate_blobs);
}

int HailDBCursor::index_read_idx_map(unsigned char * buf,
                                             uint32_t index,
                                             const unsigned char * key,
                                             key_part_map keypart_map,
                                             enum ha_rkey_function find_flag)
{
  int error, error1;
  error= doStartIndexScan(index, 0);
  if (!error)
  {
    error= haildb_index_read_map(buf, key, keypart_map, find_flag, true);
    error1= doEndIndexScan();
  }
  return error ?  error : error1;
}

int HailDBCursor::reset()
{
  if (blobroot)
    blobroot->free_root(MYF(0));

  return 0;
}

int HailDBCursor::analyze(Session*)
{
  ib_err_t err;

  err= ib_update_table_statistics(cursor);

  return ib_err_t_to_drizzle_error(getTable()->getSession(), err);
}

int HailDBCursor::index_next(unsigned char *buf)
{
  int ret= HA_ERR_END_OF_FILE;

  if (advance_cursor)
  {
    ib_err_t err= ib_cursor_next(cursor);
    if (err == DB_END_OF_INDEX)
      return HA_ERR_END_OF_FILE;
  }

  tuple= ib_tuple_clear(tuple);
  ret= read_row_from_haildb(getTable()->getSession(), buf, cursor, tuple,
                            getTable(),
                            share->has_hidden_primary_key,
                            &hidden_autoinc_pkey_position);

  advance_cursor= true;
  return ret;
}

int HailDBCursor::doEndIndexScan()
{
  active_index= MAX_KEY;

  return doEndTableScan();
}

int HailDBCursor::index_prev(unsigned char *buf)
{
  int ret= HA_ERR_END_OF_FILE;
  ib_err_t err;

  if (advance_cursor)
  {
    err= ib_cursor_prev(cursor);
    if (err != DB_SUCCESS)
    {
      if (err == DB_END_OF_INDEX)
        return HA_ERR_END_OF_FILE;
      else
        return ib_err_t_to_drizzle_error(getTable()->getSession(), err);
    }
  }

  tuple= ib_tuple_clear(tuple);
  ret= read_row_from_haildb(getTable()->getSession(), buf, cursor, tuple,
                            getTable(),
                            share->has_hidden_primary_key,
                            &hidden_autoinc_pkey_position);

  advance_cursor= true;

  return ret;
}


int HailDBCursor::index_first(unsigned char *buf)
{
  int ret= HA_ERR_END_OF_FILE;
  ib_err_t err;

  err= ib_cursor_first(cursor);
  if (err != DB_SUCCESS)
    return ib_err_t_to_drizzle_error(getTable()->getSession(), err);

  tuple= ib_tuple_clear(tuple);
  ret= read_row_from_haildb(getTable()->getSession(), buf, cursor, tuple,
                            getTable(),
                            share->has_hidden_primary_key,
                            &hidden_autoinc_pkey_position);

  advance_cursor= true;

  return ret;
}


int HailDBCursor::index_last(unsigned char *buf)
{
  int ret= HA_ERR_END_OF_FILE;
  ib_err_t err;

  err= ib_cursor_last(cursor);
  if (err != DB_SUCCESS)
    return ib_err_t_to_drizzle_error(getTable()->getSession(), err);

  tuple= ib_tuple_clear(tuple);
  ret= read_row_from_haildb(getTable()->getSession(), buf, cursor, tuple,
                            getTable(),
                            share->has_hidden_primary_key,
                            &hidden_autoinc_pkey_position);
  advance_cursor= true;

  return ret;
}

int HailDBCursor::extra(enum ha_extra_function operation)
{
  switch (operation)
  {
  case HA_EXTRA_FLUSH:
    if (blobroot)
      blobroot->free_root(MYF(0));
    break;
  case HA_EXTRA_WRITE_CAN_REPLACE:
    write_can_replace= true;
    break;
  case HA_EXTRA_WRITE_CANNOT_REPLACE:
    write_can_replace= false;
    break;
  default:
    break;
  }

  return 0;
}

static int create_table_message_table()
{
  ib_tbl_sch_t schema;
  ib_idx_sch_t index_schema;
  ib_trx_t transaction;
  ib_id_t table_id;
  ib_err_t err, rollback_err;
  ib_bool_t create_db_err;

  create_db_err= ib_database_create("data_dictionary");
  if (create_db_err != IB_TRUE)
    return -1;

  err= ib_table_schema_create(HAILDB_TABLE_DEFINITIONS_TABLE, &schema,
                              IB_TBL_COMPACT, 0);
  if (err != DB_SUCCESS)
    return err;

  err= ib_table_schema_add_col(schema, "table_name", IB_VARCHAR, IB_COL_NONE, 0,
                               IB_MAX_TABLE_NAME_LEN);
  if (err != DB_SUCCESS)
    goto free_err;

  err= ib_table_schema_add_col(schema, "message", IB_BLOB, IB_COL_NONE, 0, 0);
  if (err != DB_SUCCESS)
    goto free_err;

  err= ib_table_schema_add_index(schema, "PRIMARY_KEY", &index_schema);
  if (err != DB_SUCCESS)
    goto free_err;

  err= ib_index_schema_add_col(index_schema, "table_name", 0);
  if (err != DB_SUCCESS)
    goto free_err;
  err= ib_index_schema_set_clustered(index_schema);
  if (err != DB_SUCCESS)
    goto free_err;

  transaction= ib_trx_begin(IB_TRX_REPEATABLE_READ);
  err= ib_schema_lock_exclusive(transaction);
  if (err != DB_SUCCESS)
    goto rollback;

  err= ib_table_create(transaction, schema, &table_id);
  if (err != DB_SUCCESS)
    goto rollback;

  err= ib_trx_commit(transaction);
  if (err != DB_SUCCESS)
    goto rollback;

  ib_table_schema_delete(schema);

  return 0;
rollback:
  ib_schema_unlock(transaction);
  rollback_err= ib_trx_rollback(transaction);
  assert(rollback_err == DB_SUCCESS);
free_err:
  ib_table_schema_delete(schema);
  return err;
}

static bool innobase_use_doublewrite= true;
static bool srv_file_per_table= false;
static bool innobase_adaptive_hash_index;
static bool srv_adaptive_flushing;
static bool innobase_print_verbose_log;
static bool innobase_rollback_on_timeout;
static bool innobase_create_status_file;
static bool srv_use_sys_malloc;
static string innobase_file_format_name;
typedef constrained_check<unsigned int, 1000, 1> autoextend_constraint;
static autoextend_constraint srv_auto_extend_increment;
typedef constrained_check<size_t, SIZE_MAX, 5242880, 1048576> buffer_pool_constraint;
static buffer_pool_constraint innobase_buffer_pool_size;
typedef constrained_check<size_t, SIZE_MAX, 512, 1024> additional_mem_pool_constraint;
static additional_mem_pool_constraint innobase_additional_mem_pool_size;
static bool  innobase_use_checksums= true;
typedef constrained_check<unsigned int, UINT_MAX, 100> io_capacity_constraint;
typedef constrained_check<uint32_t, 2, 0> trinary_constraint;
static trinary_constraint innobase_fast_shutdown;
static trinary_constraint srv_flush_log_at_trx_commit;
typedef constrained_check<uint32_t, 6, 0> force_recovery_constraint;
static force_recovery_constraint innobase_force_recovery;
typedef constrained_check<int64_t, INT64_MAX, 1024*1024, 1024*1024> log_file_constraint;
static log_file_constraint haildb_log_file_size;

static io_capacity_constraint srv_io_capacity;
typedef constrained_check<unsigned int, 100, 2> log_files_in_group_constraint;
static log_files_in_group_constraint haildb_log_files_in_group;
typedef constrained_check<unsigned int, 1024*1024*1024, 1> lock_wait_constraint;
static lock_wait_constraint innobase_lock_wait_timeout;
typedef constrained_check<long, LONG_MAX, 256*1024, 1024> log_buffer_size_constraint;
static log_buffer_size_constraint innobase_log_buffer_size;
typedef constrained_check<unsigned int, 97, 5> lru_old_blocks_constraint;
static lru_old_blocks_constraint innobase_lru_old_blocks_pct;
typedef constrained_check<unsigned int, 99, 0> max_dirty_pages_constraint;
static max_dirty_pages_constraint haildb_max_dirty_pages_pct;
static uint64_constraint haildb_max_purge_lag;
static uint64_constraint haildb_sync_spin_loops;
typedef constrained_check<uint32_t, UINT32_MAX, 10> open_files_constraint;
static open_files_constraint haildb_open_files;
typedef constrained_check<unsigned int, 64, 1> io_threads_constraint;
static io_threads_constraint haildb_read_io_threads;
static io_threads_constraint haildb_write_io_threads;


static uint32_t innobase_lru_block_access_recency;



static int haildb_file_format_name_validate(Session*, set_var *var)
{

  const char *format= var->value->str_value.ptr();
  if (format == NULL)
    return 1;

  ib_err_t err= ib_cfg_set_text("file_format", format);

  if (err == DB_SUCCESS)
  {
    innobase_file_format_name= format;
    return 0;
  }
  else
    return 1;
}

static void haildb_lru_old_blocks_pct_update(Session*, sql_var_t)
{
  int ret= ib_cfg_set_int("lru_old_blocks_pct", static_cast<uint32_t>(innobase_lru_old_blocks_pct));
  (void)ret;
}

static void haildb_lru_block_access_recency_update(Session*, sql_var_t)
{
  int ret= ib_cfg_set_int("lru_block_access_recency", static_cast<uint32_t>(innobase_lru_block_access_recency));
  (void)ret;
}

static void haildb_status_file_update(Session*, sql_var_t)
{
  ib_err_t err;

  if (innobase_create_status_file)
    err= ib_cfg_set_bool_on("status_file");
  else
    err= ib_cfg_set_bool_off("status_file");
  (void)err;
}

extern "C" int haildb_errmsg_callback(ib_msg_stream_t, const char *fmt, ...);
namespace drizzled
{
extern bool volatile shutdown_in_progress;
}

extern "C" int haildb_errmsg_callback(ib_msg_stream_t, const char *fmt, ...)
{
  bool r= false;
  va_list args;
  va_start(args, fmt);
  if (not shutdown_in_progress)
  {
    r= plugin::ErrorMessage::vprintf(error::WARN, fmt, args);
  }
  else
  {
    vfprintf(stderr, fmt, args);
  }
  va_end(args);

  return (! r==true);
}

static int haildb_init(drizzled::module::Context &context)
{
  haildb_system_table_names.insert(std::string("HAILDB_SYS_TABLES"));
  haildb_system_table_names.insert(std::string("HAILDB_SYS_COLUMNS"));
  haildb_system_table_names.insert(std::string("HAILDB_SYS_INDEXES"));
  haildb_system_table_names.insert(std::string("HAILDB_SYS_FIELDS"));
  haildb_system_table_names.insert(std::string("HAILDB_SYS_FOREIGN"));
  haildb_system_table_names.insert(std::string("HAILDB_SYS_FOREIGN_COLS"));

  const module::option_map &vm= context.getOptions();

  /* Inverted Booleans */

  innobase_adaptive_hash_index= (vm.count("disable-adaptive-hash-index")) ? false : true;
  srv_adaptive_flushing= (vm.count("disable-adaptive-flushing")) ? false : true;
  innobase_use_checksums= (vm.count("disable-checksums")) ? false : true;
  innobase_use_doublewrite= (vm.count("disable-doublewrite")) ? false : true;
  innobase_print_verbose_log= (vm.count("disable-print-verbose-log")) ? false : true;
  srv_use_sys_malloc= (vm.count("use-internal-malloc")) ? false : true;


  ib_err_t err;

  err= ib_init();
  if (err != DB_SUCCESS)
    goto haildb_error;

  ib_logger_set(haildb_errmsg_callback, NULL);

  if (not vm["data-home-dir"].as<string>().empty())
  {
    err= ib_cfg_set_text("data_home_dir", vm["data-home-dir"].as<string>().c_str());
    if (err != DB_SUCCESS)
      goto haildb_error;
  }

  if (vm.count("log-group-home-dir"))
  {
    err= ib_cfg_set_text("log_group_home_dir", vm["log-group-home-dir"].as<string>().c_str());
    if (err != DB_SUCCESS)
      goto haildb_error;
  }

  if (innobase_print_verbose_log)
    err= ib_cfg_set_bool_on("print_verbose_log");
  else
    err= ib_cfg_set_bool_off("print_verbose_log");

  if (err != DB_SUCCESS)
    goto haildb_error;

  if (innobase_rollback_on_timeout)
    err= ib_cfg_set_bool_on("rollback_on_timeout");
  else
    err= ib_cfg_set_bool_off("rollback_on_timeout");

  if (err != DB_SUCCESS)
    goto haildb_error;

  if (innobase_use_doublewrite)
    err= ib_cfg_set_bool_on("doublewrite");
  else
    err= ib_cfg_set_bool_off("doublewrite");

  if (err != DB_SUCCESS)
    goto haildb_error;

  if (innobase_adaptive_hash_index)
    err= ib_cfg_set_bool_on("adaptive_hash_index");
  else
    err= ib_cfg_set_bool_off("adaptive_hash_index");

  if (err != DB_SUCCESS)
    goto haildb_error;

  if (srv_adaptive_flushing)
    err= ib_cfg_set_bool_on("adaptive_flushing");
  else
    err= ib_cfg_set_bool_off("adaptive_flushing");

  if (err != DB_SUCCESS)
    goto haildb_error;

  err= ib_cfg_set_int("additional_mem_pool_size", innobase_additional_mem_pool_size.get());
  if (err != DB_SUCCESS)
    goto haildb_error;

  err= ib_cfg_set_int("autoextend_increment", srv_auto_extend_increment.get());
  if (err != DB_SUCCESS)
    goto haildb_error;

  err= ib_cfg_set_int("buffer_pool_size", innobase_buffer_pool_size.get());
  if (err != DB_SUCCESS)
    goto haildb_error;

  err= ib_cfg_set_int("io_capacity", srv_io_capacity.get());
  if (err != DB_SUCCESS)
    goto haildb_error;

  if (srv_file_per_table)
    err= ib_cfg_set_bool_on("file_per_table");
  else
    err= ib_cfg_set_bool_off("file_per_table");

  if (err != DB_SUCCESS)
    goto haildb_error;

  err= ib_cfg_set_int("flush_log_at_trx_commit",
                      srv_flush_log_at_trx_commit.get());
  if (err != DB_SUCCESS)
    goto haildb_error;

  if (vm.count("flush-method") != 0)
  {
    err= ib_cfg_set_text("flush_method", 
                         vm["flush-method"].as<string>().c_str());
    if (err != DB_SUCCESS)
      goto haildb_error;
  }

  err= ib_cfg_set_int("force_recovery",
                      innobase_force_recovery.get());
  if (err != DB_SUCCESS)
    goto haildb_error;

  err= ib_cfg_set_text("data_file_path", vm["data-file-path"].as<string>().c_str());
  if (err != DB_SUCCESS)
    goto haildb_error;

  err= ib_cfg_set_int("log_file_size", haildb_log_file_size.get());
  if (err != DB_SUCCESS)
    goto haildb_error;

  err= ib_cfg_set_int("log_buffer_size", innobase_log_buffer_size.get());
  if (err != DB_SUCCESS)
    goto haildb_error;

  err= ib_cfg_set_int("log_files_in_group", haildb_log_files_in_group.get());
  if (err != DB_SUCCESS)
    goto haildb_error;

  err= ib_cfg_set_int("checksums", innobase_use_checksums);
  if (err != DB_SUCCESS)
    goto haildb_error;

  err= ib_cfg_set_int("lock_wait_timeout", innobase_lock_wait_timeout.get());
  if (err != DB_SUCCESS)
    goto haildb_error;

  err= ib_cfg_set_int("max_dirty_pages_pct", haildb_max_dirty_pages_pct.get());
  if (err != DB_SUCCESS)
    goto haildb_error;

  err= ib_cfg_set_int("max_purge_lag", haildb_max_purge_lag.get());
  if (err != DB_SUCCESS)
    goto haildb_error;

  err= ib_cfg_set_int("open_files", haildb_open_files.get());
  if (err != DB_SUCCESS)
    goto haildb_error;

  err= ib_cfg_set_int("read_io_threads", haildb_read_io_threads.get());
  if (err != DB_SUCCESS)
    goto haildb_error;

  err= ib_cfg_set_int("write_io_threads", haildb_write_io_threads.get());
  if (err != DB_SUCCESS)
    goto haildb_error;

  err= ib_cfg_set_int("sync_spin_loops", haildb_sync_spin_loops.get());
  if (err != DB_SUCCESS)
    goto haildb_error;

  if (srv_use_sys_malloc)
    err= ib_cfg_set_bool_on("use_sys_malloc");
  else
    err= ib_cfg_set_bool_off("use_sys_malloc");

  if (err != DB_SUCCESS)
    goto haildb_error;

  err= ib_startup(innobase_file_format_name.c_str());
  if (err != DB_SUCCESS)
    goto haildb_error;

  create_table_message_table();

  haildb_engine= new HailDBEngine("InnoDB");
  context.add(haildb_engine);
  context.registerVariable(new sys_var_bool_ptr_readonly("adaptive_hash_index",
                                                         &innobase_adaptive_hash_index));
  context.registerVariable(new sys_var_bool_ptr_readonly("adaptive_flushing",
                                                         &srv_adaptive_flushing));
  context.registerVariable(new sys_var_constrained_value_readonly<size_t>("additional_mem_pool_size",innobase_additional_mem_pool_size));
  context.registerVariable(new sys_var_constrained_value_readonly<unsigned int>("autoextend_increment", srv_auto_extend_increment));
  context.registerVariable(new sys_var_constrained_value_readonly<size_t>("buffer_pool_size", innobase_buffer_pool_size));
  context.registerVariable(new sys_var_bool_ptr_readonly("checksums",
                                                         &innobase_use_checksums));
  context.registerVariable(new sys_var_bool_ptr_readonly("doublewrite",
                                                         &innobase_use_doublewrite));
  context.registerVariable(new sys_var_const_string_val("data_file_path",
                                                vm["data-file-path"].as<string>()));
  context.registerVariable(new sys_var_const_string_val("data_home_dir",
                                                vm["data-home-dir"].as<string>()));
  context.registerVariable(new sys_var_constrained_value_readonly<unsigned int>("io_capacity", srv_io_capacity));
  context.registerVariable(new sys_var_constrained_value_readonly<uint32_t>("fast_shutdown", innobase_fast_shutdown));
  context.registerVariable(new sys_var_bool_ptr_readonly("file_per_table",
                                                         &srv_file_per_table));
  context.registerVariable(new sys_var_bool_ptr_readonly("rollback_on_timeout",
                                                         &innobase_rollback_on_timeout));
  context.registerVariable(new sys_var_bool_ptr_readonly("print_verbose_log",
                                                         &innobase_print_verbose_log));
  context.registerVariable(new sys_var_bool_ptr("status_file",
                                                &innobase_create_status_file,
                                                haildb_status_file_update));
  context.registerVariable(new sys_var_bool_ptr_readonly("use_sys_malloc",
                                                         &srv_use_sys_malloc));
  context.registerVariable(new sys_var_std_string("file_format",
                                                  innobase_file_format_name,
                                                  haildb_file_format_name_validate));
  context.registerVariable(new sys_var_constrained_value_readonly<uint32_t>("flush_log_at_trx_commit", srv_flush_log_at_trx_commit));
  context.registerVariable(new sys_var_const_string_val("flush_method",
                                                vm.count("flush-method") ?  vm["flush-method"].as<string>() : ""));
  context.registerVariable(new sys_var_constrained_value_readonly<uint32_t>("force_recovery", innobase_force_recovery));
  context.registerVariable(new sys_var_const_string_val("log_group_home_dir",
                                                vm.count("log-group-home-dir") ?  vm["log-group-home-dir"].as<string>() : ""));
  context.registerVariable(new sys_var_constrained_value<int64_t>("log_file_size", haildb_log_file_size));
  context.registerVariable(new sys_var_constrained_value_readonly<unsigned int>("log_files_in_group", haildb_log_files_in_group));
  context.registerVariable(new sys_var_constrained_value_readonly<unsigned int>("lock_wait_timeout", innobase_lock_wait_timeout));
  context.registerVariable(new sys_var_constrained_value_readonly<long>("log_buffer_size", innobase_log_buffer_size));
  context.registerVariable(new sys_var_constrained_value<unsigned int>("lru_old_blocks_pct", innobase_lru_old_blocks_pct, haildb_lru_old_blocks_pct_update));
  context.registerVariable(new sys_var_uint32_t_ptr("lru_block_access_recency",
                                                    &innobase_lru_block_access_recency,
                                                    haildb_lru_block_access_recency_update));
  context.registerVariable(new sys_var_constrained_value_readonly<unsigned int>("max_dirty_pages_pct", haildb_max_dirty_pages_pct));
  context.registerVariable(new sys_var_constrained_value_readonly<uint64_t>("max_purge_lag", haildb_max_purge_lag));
  context.registerVariable(new sys_var_constrained_value_readonly<uint64_t>("sync_spin_loops", haildb_sync_spin_loops));
  context.registerVariable(new sys_var_constrained_value_readonly<uint32_t>("open_files", haildb_open_files));
  context.registerVariable(new sys_var_constrained_value_readonly<unsigned int>("read_io_threads", haildb_read_io_threads));
  context.registerVariable(new sys_var_constrained_value_readonly<unsigned int>("write_io_threads", haildb_write_io_threads));

  haildb_datadict_dump_func_initialize(context);
  config_table_function_initialize(context);
  status_table_function_initialize(context);

  return 0;
haildb_error:
  fprintf(stderr, _("Error starting HailDB %d (%s)\n"),
          err, ib_strerror(err));
  return -1;
}


HailDBEngine::~HailDBEngine()
{
  ib_err_t err;
  ib_shutdown_t shutdown_flag= IB_SHUTDOWN_NORMAL;

  if (innobase_fast_shutdown.get() == 1)
    shutdown_flag= IB_SHUTDOWN_NO_IBUFMERGE_PURGE;
  else if (innobase_fast_shutdown.get() == 2)
    shutdown_flag= IB_SHUTDOWN_NO_BUFPOOL_FLUSH;

  err= ib_shutdown(shutdown_flag);

  if (err != DB_SUCCESS)
  {
    fprintf(stderr,"Error %d shutting down HailDB!\n", err);
  }

}


static void init_options(drizzled::module::option_context &context)
{
  context("disable-adaptive-hash-index",
          N_("Disable HailDB adaptive hash index (enabled by default)."));
  context("disable-adaptive-flushing",
          N_("Do not attempt to flush dirty pages to avoid IO bursts at checkpoints."));
  context("additional-mem-pool-size",
          po::value<additional_mem_pool_constraint>(&innobase_additional_mem_pool_size)->default_value(8*1024*1024L),
          N_("Size of a memory pool HailDB uses to store data dictionary information and other internal data structures."));
  context("autoextend-increment",
          po::value<autoextend_constraint>(&srv_auto_extend_increment)->default_value(8),
          N_("Data file autoextend increment in megabytes"));
  context("buffer-pool-size",
          po::value<buffer_pool_constraint>(&innobase_buffer_pool_size)->default_value(128*1024*1024L),
          N_("The size of the memory buffer HailDB uses to cache data and indexes of its tables."));
  context("data-home-dir",
          po::value<string>()->default_value(""),
          N_("The common part for HailDB table spaces."));
  context("disable-checksums",
          N_("Disable HailDB checksums validation (enabled by default)."));
  context("disable-doublewrite",
          N_("Disable HailDB doublewrite buffer (enabled by default)."));
  context("io-capacity",
          po::value<io_capacity_constraint>(&srv_io_capacity)->default_value(200),
          N_("Number of IOPs the server can do. Tunes the background IO rate"));
  context("fast-shutdown",
          po::value<trinary_constraint>(&innobase_fast_shutdown)->default_value(1),
          N_("Speeds up the shutdown process of the HailDB storage engine. Possible values are 0, 1 (faster) or 2 (fastest - crash-like)."));
  context("file-per-table",
          po::value<bool>(&srv_file_per_table)->default_value(false)->zero_tokens(),
          N_("Stores each HailDB table to an .ibd file in the database dir."));
  context("file-format",
          po::value<string>(&innobase_file_format_name)->default_value("Barracuda"),
          N_("File format to use for new tables in .ibd files."));
  context("flush-log-at-trx-commit",
          po::value<trinary_constraint>(&srv_flush_log_at_trx_commit)->default_value(1),
          N_("Set to 0 (write and flush once per second),1 (write and flush at each commit) or 2 (write at commit, flush once per second)."));
  context("flush-method",
          po::value<string>(),
          N_("With which method to flush data."));
  context("force-recovery",
          po::value<force_recovery_constraint>(&innobase_force_recovery)->default_value(0),
          N_("Helps to save your data in case the disk image of the database becomes corrupt."));
  context("data-file-path",
          po::value<string>()->default_value("ibdata1:10M:autoextend"),
          N_("Path to individual files and their sizes."));
  context("log-group-home-dir",
          po::value<string>(),
          N_("Path to HailDB log files."));
  context("log-file-size",
          po::value<log_file_constraint>(&haildb_log_file_size)->default_value(20*1024*1024L),
          N_("Size of each log file in a log group."));
  context("haildb-log-files-in-group",
          po::value<log_files_in_group_constraint>(&haildb_log_files_in_group)->default_value(2),
          N_("Number of log files in the log group. HailDB writes to the files in a circular fashion. Value 3 is recommended here."));
  context("lock-wait-timeout",
          po::value<lock_wait_constraint>(&innobase_lock_wait_timeout)->default_value(5),
          N_("Timeout in seconds an HailDB transaction may wait for a lock before being rolled back. Values above 100000000 disable the timeout."));
  context("log-buffer-size",
        po::value<log_buffer_size_constraint>(&innobase_log_buffer_size)->default_value(8*1024*1024L),
        N_("The size of the buffer which HailDB uses to write log to the log files on disk."));
  context("lru-old-blocks-pct",
          po::value<lru_old_blocks_constraint>(&innobase_lru_old_blocks_pct)->default_value(37),
          N_("Sets the point in the LRU list from where all pages are classified as old (Advanced users)"));
  context("lru-block-access-recency",
          po::value<uint32_t>(&innobase_lru_block_access_recency)->default_value(0),
          N_("Milliseconds between accesses to a block at which it is made young. 0=disabled (Advanced users)"));
  context("max-dirty-pages-pct",
          po::value<max_dirty_pages_constraint>(&haildb_max_dirty_pages_pct)->default_value(75),
          N_("Percentage of dirty pages allowed in bufferpool."));
  context("max-purge-lag",
          po::value<uint64_constraint>(&haildb_max_purge_lag)->default_value(0),
          N_("Desired maximum length of the purge queue (0 = no limit)"));
  context("rollback-on-timeout",
          po::value<bool>(&innobase_rollback_on_timeout)->default_value(false)->zero_tokens(),
          N_("Roll back the complete transaction on lock wait timeout, for 4.x compatibility (disabled by default)"));
  context("open-files",
          po::value<open_files_constraint>(&haildb_open_files)->default_value(300),
          N_("How many files at the maximum HailDB keeps open at the same time."));
  context("read-io-threads",
          po::value<io_threads_constraint>(&haildb_read_io_threads)->default_value(4),
          N_("Number of background read I/O threads in HailDB."));
  context("write-io-threads",
          po::value<io_threads_constraint>(&haildb_write_io_threads)->default_value(4),
          N_("Number of background write I/O threads in HailDB."));
  context("disable-print-verbose-log",
          N_("Disable if you want to reduce the number of messages written to the log (default: enabled)."));
  context("status-file",
          po::value<bool>(&innobase_create_status_file)->default_value(false)->zero_tokens(),
          N_("Enable SHOW HAILDB STATUS output in the log"));
  context("sync-spin-loops",
          po::value<uint64_constraint>(&haildb_sync_spin_loops)->default_value(30L),
          N_("Count of spin-loop rounds in HailDB mutexes (30 by default)"));
  context("use-internal-malloc",
          N_("Use HailDB's internal memory allocator instead of the OS memory allocator"));
}

DRIZZLE_DECLARE_PLUGIN
{
  DRIZZLE_VERSION_ID,
  "INNODB",
  "1.0",
  "Stewart Smith",
  "Transactional Storage Engine using the HailDB Library",
  PLUGIN_LICENSE_GPL,
  haildb_init,     /* Plugin Init */
  NULL, /* depends */
  init_options                /* config options   */
}
DRIZZLE_DECLARE_PLUGIN_END;